diff --git a/.github/ISSUE_TEMPLATE/-------.md b/.github/ISSUE_TEMPLATE/-------.md new file mode 100644 index 00000000..9a217d76 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/-------.md @@ -0,0 +1,21 @@ +--- +name: 发现一个新问题 +about: 提交一个新issue +title: "[feature]提交一个新issue" +labels: issue +assignees: yanglr + +--- + +**描述问题** +简要描述你发现了本仓库的问题,比如: 代码没法运行, 拼写错误等 + +**如何重现** +重现该现象的步骤: +1. 移步到网址 '...' +2. 单击'....' +3. 下拉到 '....' +4. 出现(具体问题) + +**期待的结果** +具体说说你希望达到什么样的预期结果~ diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a019f494 --- /dev/null +++ b/.gitignore @@ -0,0 +1,252 @@ +.sass-cache +.jekyll-cache +.jekyll-metadata +*.sw[po] +.DS_Store +Gemfile.lock +.vs/ +_site/ + +# Java/idea J +out/ +.class +*.sqlite + +*.suo +*.user +*.userosscache +*.sln.docstates +*.exe + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + Run code snippet \ No newline at end of file diff --git a/91algo/README.md b/91algo/README.md new file mode 100644 index 00000000..cd90d3c7 --- /dev/null +++ b/91algo/README.md @@ -0,0 +1,284 @@ +# 91 算法(第5期) + +[91 算法第5期网站](https://leetcode-solution.cn/91)。 + +91 算法是一个为期 91 天的大家一起打卡的活动, 大家可以一起做和学习带有讲解和按照专题的算法题。 + +## 主要编程语言 +老师使用的语言主要是 Python/JavaScript... + +本人暂定使用 C++ 来完成。 + +## LeetCode 题解 + +| 基础篇 | 进阶篇 | 专题篇 | +| --------------------------- | ------------------------- | --------------------------------------- | +| [数组/栈/队列](#数组栈队列) | [高频面试题](#高频面试题) | [二分法](#二分法) | +| [链表](#链表) | [前缀树](#前缀树) | [滑动窗口](#滑动窗口) | +| [树](#树) | [并查集](#并查集) | [位运算](#位运算) | +| [哈希表](#哈希表) | [跳表](#跳表) | [搜索(BFS/DFS/回溯)](#搜索bfs-dfs-回溯) | +| [双指针](#双指针) | [剪枝](#剪枝) | [背包问题](#背包问题) | +| - | [字符串匹配](#字符串匹配) | [动态规划](#动态规划) | +| - | [堆](#堆) | [分治](#分治) | +| - | - | [贪心](#贪心) | + +## 每日一题 汇总 + +- [x] [【day1】989.数组形式的整数加法](./daily/posts/day1.md) +- [x] [【day2】821.字符的最短距离](./daily/posts/day2.md) +- [x] [【day3】1381.设计一个支持增量操作的栈 09-12](./daily/posts/day3.md) +- [x] [【day4】394.字符串解码 09-13](./daily/posts/day4.md) +- [x] [【day5】232.用栈实现队列 09-14](./daily/posts/day5.md) +- [x] [【day6】768.最多能完成排序的块 II 09-15](./daily/posts/day6.md) +- [x] [【day7】61.旋转链表](./daily/posts/day7.md) +- [x] [【day8】24.两两交换链表中的节点](./daily/posts/day8.md) +- [x] [【day9】109.有序链表转换二叉搜索树 09-18](./daily/posts/day9.md) +- [x] [【day10】160.相交链表 09-19](./daily/posts/day10.md) +- [x] [【day11】142.环形链表 II 09-20](./daily/posts/day11.md) +- [x] [【day12】146.LRU 缓存机制 09-21](./daily/posts/day12.md) +- [x] [【day13】104.二叉树的最大深度 09-22](./daily/posts/day13.md) +- [x] [【day14】100.相同的树 09-23](./daily/posts/day14.md) +- [x] [【day15】129.求根到叶子节点数字之和](./daily/posts/day15.md) +- [x] [【day16】513.找树左下角的值 09-25](./daily/posts/day16.md) +- [x] [【day17】297.二叉树的序列化与反序列化 09-26](./daily/posts/day17.md) +- [x] [【day18】987.二叉树的垂序遍历 09-27](./daily/posts/day18.md) +- [x] [【day19】1.两数之和 09-28](./daily/posts/day19.md) +- [x] [【day20】347.前 K 个高频元素](./daily/posts/day20.md) +- [x] [【day21】447.回旋镖的数量 09-30](./daily/posts/day21.md) +- [x] [【day22】3.无重复字符的最长子串 10-01](./daily/posts/day22.md) +- [x] [【day23】30.串联所有单词的子串10-02](./daily/posts/day23.md) +- [x] [【day24】1590.使数组和能被P整除 10-03](./daily/posts/day24.md) +- [x] [【day25】876.链表的中间结点 10-04](./daily/posts/day25.md) +- [x] [【day26】26.删除有序数组中的重复项 10-05](./daily/posts/day26.md) +- [x] [【day27】35.搜索插入位置 10-06](./daily/posts/day27.md) +- [x] [【day28】239.滑动窗口最大值 10-07](./daily/posts/day28.md) +- [x] [【day29】997.找到小镇的法官 10-08](./daily/posts/day29.md) +- [x] [【day30】886.可能的二分法 10-09](./daily/posts/day30.md) +- [x] [【day31】1203.项目管理 10-10](./daily/posts/day31.md) +- [x] [【day32】657.机器人能否返回原点 10-11](./daily/posts/day32.md) + + +## 基础篇 + +### 数组,栈,队列 + +#### 每日一题 + +- [x] [【day1】989.数组形式的整数加法](./daily/posts/day1.md) +- [x] [【day2】821.字符的最短距离](./daily/posts/day2.md) +- [x] [【day3】1381.设计一个支持增量操作的栈 09-12](./daily/posts/day3.md) +- [x] [【day4】394.字符串解码 09-13](./daily/posts/day4.md) +- [x] [【day5】232.用栈实现队列 09-14](./daily/posts/day5.md) +- [x] [【day6】768.最多能完成排序的块 II 09-15](./daily/posts/day6.md) + + +#### 数组拓展题目 + +- [x] [75.颜色分类](./daily/posts/basic/array-stack-queue/ext-sort-colors.md) + + +#### 栈拓展题目 + +- [ ] [946. 验证栈序列](https://leetcode-cn.com/problems/validate-stack-sequences/) + +#### 队列拓展题目 + +- [ ] [155.最小栈](https://leetcode-cn.com/problems/min-stack/) + + +#### 相关专题 + +- [ ] [前缀和](https://lucifer.ren/blog/2020/09/27/atMostK/) + +### 链表 + +#### 每日一题 + +- [x] [【day7】24.两两交换链表中的节点](./daily/posts/basic/linked-list/07.swap-nodes-in-pairs.md) + + +#### 链表拓展题目 + +- [x] [2.两数相加](./daily/posts/problems/2.add-two-numbers.md) + +### 树 + +#### 每日一题 + +- [x] [【day-13】104.二叉树的最大深度](./daily/posts/basic/binary-tree/13.maximum-depth-of-binary-tree.md) + +#### 树拓展题目 + +- [x] [105.从前序与中序遍历序列构造二叉树](./daily/posts/basic/binary-tree/ + +### 哈希表 + +#### 每日一题 + +- [x] [【day-19】1.两数之和](./daily/posts/basic/hashmap/19.two-sum.md) + + +#### 哈希表拓展题目 + +- [x] [645.错误的集合](./daily/posts/basic/hashmap/ext-set-mismatch.md) + + +### 双指针 + +#### 每日一题 + +- [x] [【day-25】35.搜索插入位置](./daily/posts/basic/two-pointers/25.search-insert-position.md) + + +#### 双指针拓展题目 + +- [x] [875.爱吃香蕉的珂珂](./daily/posts/basic/two-pointers/ext-koko-eating-bananas.md) + +## 进阶篇 + +### 高频面试题 + +**二叉树遍历系列** + +- [x] [【day-34】二叉树遍历系列](./daily/posts/medium/hot/34.traversal-of-binary-tree.md) + +**反转链表系列** + +- [x] [【day-35】206.反转链表](./daily/posts/medium/hot/35.reverse-linked-list.md) + +**位运算系列** + +- [ ] [【day-36】78.子集](./daily/posts/medium/hot/36.subsets.md) + +**动态规划系列** + +- [x] [【day-37】62.不同路径](./daily/posts/medium/hot/37.unique-paths.md) + + +**有效括号系列** + +- [x] [【day-38】20.有效括号](./daily/posts/medium/hot/38.valid-parentheses.md) + + +**设计系列** + +- [ ] [【day-39】剑指 Offer09.用两个栈实现队列](./daily/posts/) + + +**前缀和系列** + +- [x] [【day-40】网易面试题](./daily/posts/medium/hot/40.netease.md) + + +### 前缀树 + +- [x] [【day-41】208.实现 Trie](./daily/posts/medium/trie/41.implement-trie-prefix-tree.md) + +### 并查集 + +#### 每日一题 + +- [x] [【day-44】547.朋友圈](./daily/posts/medium/union-find/44.friend-circles.md) + + +#### 拓展 + +- [x] [1202.交换字符串中的元素](./daily/posts/medium/union-find/ext-smallest-string-with-swaps.md) + +### 跳表 + +- [ ] [【day-47】1206.设计跳表](./daily/posts/) + +### 剪枝 + +#### 每日一题 + +- [x] [【day-48】814.二叉树剪枝](./daily/posts/medium/prune/48.binary-tree-pruning.md) + + +### 字符串匹配 + +#### 每日一题 + +- [ ] [【day-52】28.实现 strStr()](./daily/posts/medium/rk-kpm/52.implement-strstr.md) + +#### 拓展题目 + +- [ ] [1371.每个元音包含偶数次的最长子字符串](./daily/posts/medium/day-52.md) + + +### 堆 + +#### 每日一题 + +- [x] [【day-54】215.数组中的第 K 个最大元素](./daily/posts/medium/heap/54.kth-largest-element-in-an-array.md) + + +## 专题篇 + +### 二分法 + +#### 每日一题 + +- [x] [【day-61】69.x 的平方根](./daily/posts/topics/binary-search/61.sqrtx.md) + + +#### 拓展题目 + +- [x] [33.搜索旋转排序数组](./daily/posts/topics/binary-search/ext-search-in-rotated-sorted-array.md) + +### 滑动窗口 + +#### 每日一题 + +- [x] [【day-67】1456.定长子串中元音的最大数目](./daily/posts/topics/sliding-window/67.maximum-number-of-vowels-in-a-substring-of-given-length.md) + +#### 拓展题目 + +- [x] [581.最短无序连续子数组](./daily/posts/topics/sliding-window/ext-shortest-unsorted-continuous-subarray.md) + +### 位运算 + +- [ ] [【day-72】268.缺失数字](./daily/posts/topics/day-72.md) + + +### 搜索(BFS, DFS, 回溯) + +- [x] [【day-74】1254.统计封闭岛屿的数目](./daily/posts/topics/day-74.md) + + +- [x] [5210.球会落何处](./daily/posts/topics/searching/ext-where-will-the-ball-fall.md) + +### 背包问题 + +- [x] [【day-80】322.零钱兑换](./daily/posts/topics/day-80.md) + + +### 动态规划 + +- [ ] [【day-84】爬楼梯变种](./daily/posts/topics/day-84.md) + + +### 分治 + +- [x] [【day-88】96.不同的二叉搜索树](./daily/posts/topics/day-88.md) + + +### 贪心 + +#### 每日一题 + +- [ ] [【day-90】765.情侣牵手](./daily/posts/topics/day-90.md) + +#### 贪心拓展题目 + +- [x] [135.分发糖果](./daily/posts/topics/greedy/ext-candy.md) + + +## 其他 + +- [x] [77.组合](./daily/posts/extensions/77.combination.md) + + +> [在线电子书](https://geekplayers.com/leetcode) + diff --git a/91algo/code-templates/README.md b/91algo/code-templates/README.md new file mode 100644 index 00000000..af24e140 --- /dev/null +++ b/91algo/code-templates/README.md @@ -0,0 +1,3 @@ +# 本人原创的代码模板(Code templates) + +根据课程给的伪代码, 主要使用C++语言来完成。 diff --git a/91algo/cpp/.vscode/c_cpp_properties.json b/91algo/cpp/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..7576cd08 --- /dev/null +++ b/91algo/cpp/.vscode/c_cpp_properties.json @@ -0,0 +1,21 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.19041.0", + "compilerPath": "C:/Program Files/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/g++.exe", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "gcc-x86" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/91algo/cpp/.vscode/launch.json b/91algo/cpp/.vscode/launch.json new file mode 100644 index 00000000..2af67dc7 --- /dev/null +++ b/91algo/cpp/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + "version": "0.2.0", + "configurations": [ + { + "name": "g++.exe - Build and debug active file", + "type": "cppdbg", + "request": "launch", + "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { // Display content in STL containers pretty + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ], + // VS Code debug的日志信息,能清楚gdb加载和运行的各种过程 + "logging": { + "moduleLoad": false, + "trace": true, + "engineLogging": true, + "exceptions": true + }, + "preLaunchTask": "C/C++: g++.exe build active file" + } + ] +} \ No newline at end of file diff --git a/91algo/cpp/.vscode/settings.json b/91algo/cpp/.vscode/settings.json new file mode 100644 index 00000000..9a91c8a3 --- /dev/null +++ b/91algo/cpp/.vscode/settings.json @@ -0,0 +1,77 @@ +{ + "files.associations": { + "*.vue": "vue", + "deque": "cpp", + "string": "cpp", + "vector": "cpp", + "algorithm": "cpp", + "unordered_set": "cpp", + "queue": "cpp", + "iterator": "cpp", + "iostream": "cpp", + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "charconv": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "codecvt": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "csetjmp": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cuchar": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "forward_list": "cpp", + "list": "cpp", + "unordered_map": "cpp", + "exception": "cpp", + "functional": "cpp", + "map": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "ratio": "cpp", + "regex": "cpp", + "set": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "fstream": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "mutex": "cpp", + "new": "cpp", + "ostream": "cpp", + "scoped_allocator": "cpp", + "shared_mutex": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "thread": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "valarray": "cpp" + } +} \ No newline at end of file diff --git a/91algo/cpp/.vscode/tasks.json b/91algo/cpp/.vscode/tasks.json new file mode 100644 index 00000000..1ad2a5fb --- /dev/null +++ b/91algo/cpp/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + //"type": "shell", + "label": "C/C++: g++.exe build active file", + "command": "g++", + "args": [ + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} \ No newline at end of file diff --git a/91algo/cpp/README.md b/91algo/cpp/README.md new file mode 100644 index 00000000..f137b2cb --- /dev/null +++ b/91algo/cpp/README.md @@ -0,0 +1,3 @@ +# 课程代码 + +本人暂定使用 C++ 来完成, 包括`day1~day91这91天的每日一题`, 以及`相关扩展题`。 diff --git a/91algo/cpp/leetcode989-add-to-array-form-of-integer_add_logic.cpp b/91algo/cpp/leetcode989-add-to-array-form-of-integer_add_logic.cpp new file mode 100644 index 00000000..8faccd1c --- /dev/null +++ b/91algo/cpp/leetcode989-add-to-array-form-of-integer_add_logic.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector addToArrayForm(vector& A, int k) { + if (k == 0) return A; + vector res; + int n = A.size(); + // 对位相加 + int carry = 0; + int sum = 0; + int i = n - 1; + while (k > 0 || i >= 0) + { + sum = carry + (k % 10); + if (i >= 0) // 保证访问A[i]前不越界 + sum += A[i]; + + carry = (sum <= 9) ? 0 : 1; + res.push_back(sum % 10); + k = k / 10; + + i--; + } + if (carry == 1) res.push_back(1); + reverse(res.begin(), res.end()); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector A = {2, 7, 4}; + int K = 81; + + auto res = sol.addToArrayForm(A, K); + for (auto &num : res) + cout << num << endl; + + return 0; +} diff --git a/91algo/daily/.vscode/c_cpp_properties.json b/91algo/daily/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..7576cd08 --- /dev/null +++ b/91algo/daily/.vscode/c_cpp_properties.json @@ -0,0 +1,21 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.19041.0", + "compilerPath": "C:/Program Files/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/g++.exe", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "gcc-x86" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/91algo/daily/.vscode/launch.json b/91algo/daily/.vscode/launch.json new file mode 100644 index 00000000..2af67dc7 --- /dev/null +++ b/91algo/daily/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + "version": "0.2.0", + "configurations": [ + { + "name": "g++.exe - Build and debug active file", + "type": "cppdbg", + "request": "launch", + "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { // Display content in STL containers pretty + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ], + // VS Code debug的日志信息,能清楚gdb加载和运行的各种过程 + "logging": { + "moduleLoad": false, + "trace": true, + "engineLogging": true, + "exceptions": true + }, + "preLaunchTask": "C/C++: g++.exe build active file" + } + ] +} \ No newline at end of file diff --git a/91algo/daily/.vscode/settings.json b/91algo/daily/.vscode/settings.json new file mode 100644 index 00000000..9a91c8a3 --- /dev/null +++ b/91algo/daily/.vscode/settings.json @@ -0,0 +1,77 @@ +{ + "files.associations": { + "*.vue": "vue", + "deque": "cpp", + "string": "cpp", + "vector": "cpp", + "algorithm": "cpp", + "unordered_set": "cpp", + "queue": "cpp", + "iterator": "cpp", + "iostream": "cpp", + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "charconv": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "codecvt": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "csetjmp": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cuchar": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "forward_list": "cpp", + "list": "cpp", + "unordered_map": "cpp", + "exception": "cpp", + "functional": "cpp", + "map": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "ratio": "cpp", + "regex": "cpp", + "set": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "fstream": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "mutex": "cpp", + "new": "cpp", + "ostream": "cpp", + "scoped_allocator": "cpp", + "shared_mutex": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "thread": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "valarray": "cpp" + } +} \ No newline at end of file diff --git a/91algo/daily/.vscode/tasks.json b/91algo/daily/.vscode/tasks.json new file mode 100644 index 00000000..1ad2a5fb --- /dev/null +++ b/91algo/daily/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + //"type": "shell", + "label": "C/C++: g++.exe build active file", + "command": "g++", + "args": [ + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} \ No newline at end of file diff --git a/91algo/daily/day1[2021-09-10] leetcode989-add-to-array-form-of-integer.cpp b/91algo/daily/day1[2021-09-10] leetcode989-add-to-array-form-of-integer.cpp new file mode 100644 index 00000000..8faccd1c --- /dev/null +++ b/91algo/daily/day1[2021-09-10] leetcode989-add-to-array-form-of-integer.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector addToArrayForm(vector& A, int k) { + if (k == 0) return A; + vector res; + int n = A.size(); + // 对位相加 + int carry = 0; + int sum = 0; + int i = n - 1; + while (k > 0 || i >= 0) + { + sum = carry + (k % 10); + if (i >= 0) // 保证访问A[i]前不越界 + sum += A[i]; + + carry = (sum <= 9) ? 0 : 1; + res.push_back(sum % 10); + k = k / 10; + + i--; + } + if (carry == 1) res.push_back(1); + reverse(res.begin(), res.end()); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector A = {2, 7, 4}; + int K = 81; + + auto res = sol.addToArrayForm(A, K); + for (auto &num : res) + cout << num << endl; + + return 0; +} diff --git a/91algo/daily/day24[2021-10-03] binarySearch924-delete-sublist-to-make-sum-divisible-by-k_presum.cpp b/91algo/daily/day24[2021-10-03] binarySearch924-delete-sublist-to-make-sum-divisible-by-k_presum.cpp new file mode 100644 index 00000000..33b0c732 --- /dev/null +++ b/91algo/daily/day24[2021-10-03] binarySearch924-delete-sublist-to-make-sum-divisible-by-k_presum.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +int floorMod(const int& a, const int& b) +{ + return (a % b + b) % b; +} +int solve(vector& nums, int k) { + int allSum = 0; + for (int& num : nums) + allSum += num; + + allSum = floorMod(allSum, k); + unordered_map dict; // dict: 某个前缀和%k得到的余数->pos + dict[0] = -1; + + int preSum = 0; + int minLen = nums.size(); + for (int i = 0; i < nums.size(); i++) { + preSum += nums[i]; + int mod = floorMod(preSum, k); + dict[mod] = i; + + if (dict.count(floorMod(preSum - allSum, k))) + minLen = min(minLen, i - dict[floorMod(preSum - allSum, k)]); + } + return minLen == nums.size() ? -1 : minLen; +} + +// Test +int main() +{ + vector A = {1, 8, 6, 4, 5}; + int k = 7; + auto res = solve(A, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/91algo/daily/day2[2021-09-11] leetcode821-shortest-distance-to-a-character_naive_solution.cpp b/91algo/daily/day2[2021-09-11] leetcode821-shortest-distance-to-a-character_naive_solution.cpp new file mode 100644 index 00000000..982b2af0 --- /dev/null +++ b/91algo/daily/day2[2021-09-11] leetcode821-shortest-distance-to-a-character_naive_solution.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector shortestToChar(string s, char c) { + // 题意: 计算 abs[i] = indexGap(i, nearest_c), 1 <= s.length <= 10^4 + // 输出 abs[i]的数组 + vector indexes; // indexes of char c + for (int i = 0; i < s.size(); i++) + { + if (s[i] == c) indexes.push_back(i); + } + vector res; + for (int i = 0; i < s.size(); i++) + { + vector gaps; // gap for char s[i] to char c + for (auto index : indexes) + gaps.push_back(abs(index - i)); + auto it = min_element(gaps.begin(), gaps.end()); + res.push_back(*it); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "loveleetcode"; + char c = 'e'; + auto res = sol.shortestToChar(s, c); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/91algo/daily/day2[2021-09-11] leetcode821-shortest-distance-to-a-character_two_pointers1.cpp b/91algo/daily/day2[2021-09-11] leetcode821-shortest-distance-to-a-character_two_pointers1.cpp new file mode 100644 index 00000000..82694102 --- /dev/null +++ b/91algo/daily/day2[2021-09-11] leetcode821-shortest-distance-to-a-character_two_pointers1.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector shortestToChar(string s, char c) { + vector gaps(s.size()); + vector chars(s.begin(), s.end()); + + for (int i = 0; i < chars.size(); i++) + { + // 如果当前字符就是要搜索的字符c, 距离为 0 + if (chars[i] == c) gaps[i] = 0; + else /* 否则分别向左、向右找最近的字符c */ + { + int leftDistance = INT_MAX, rightDistance = INT_MAX; + for (int left = i; left >= 0; left--) + { + if (chars[left] == c) // 向左找, 找到第一个 + { + leftDistance = i - left; + break; + } + } + for (int right = i; right < chars.size(); right++) // 向右找, 找到第一个 + { + if (chars[right] == c) + { + rightDistance = right - i; + break; + } + } + gaps[i] = min(leftDistance, rightDistance); + } + } + + return gaps; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "loveleetcode"; + char c = 'e'; + auto res = sol.shortestToChar(s, c); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/91algo/daily/day3[2021-09-12] leetcode1381-design-a-stack-with-increment-operation_stack.cpp b/91algo/daily/day3[2021-09-12] leetcode1381-design-a-stack-with-increment-operation_stack.cpp new file mode 100644 index 00000000..2689ad26 --- /dev/null +++ b/91algo/daily/day3[2021-09-12] leetcode1381-design-a-stack-with-increment-operation_stack.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; + +class CustomStack { +public: + vector stack; + int size; + + CustomStack(int maxSize) { + stack.resize(maxSize); + size = 0; + } + + void push(int x) { + if (size < stack.size()) + { + stack[size] = x; + size++; + } + } + /* 弹出栈顶元素,并返回栈顶的值,或栈为空时返回 -1 */ + int pop() { + int res = -1; + if (size > 0) + { + size--; + res = stack[size]; + } + + return res; + } + /* 栈底的 k 个元素的值都增加 val 。如果栈中元素总数小于 k ,则栈中的所有元素都增加 val */ + void increment(int k, int val) { + for (int i = 0; i < min(k, size); i++) + stack[i] += val; + } +}; + +// Test +int main() +{ + int maxSize = 5; + CustomStack *customStack = new CustomStack(3); // Stack 初始化为 [], 长度为3 + customStack->push(1); // 栈变为 [1] + customStack->push(2); // 栈变为 [1, 2] + customStack->push(8); // 栈变为 [1, 2, 8] + int val1 = customStack->pop(); // 返回栈顶值8, 栈变为 [1, 2] + cout << val1 << endl; + + customStack->increment(2, 100); // 栈变为 [101, 102] + + return 0; +} \ No newline at end of file diff --git a/91algo/daily/day4[2021-09-13] leetcode394-decode-string_two_stacks.cpp b/91algo/daily/day4[2021-09-13] leetcode394-decode-string_two_stacks.cpp new file mode 100644 index 00000000..f666d9f4 --- /dev/null +++ b/91algo/daily/day4[2021-09-13] leetcode394-decode-string_two_stacks.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string decodeString(string s) { + deque numStack; + deque strStack; + string resStr; + + int n = s.size(); + for (int i = 0; i < n; i++) + { + char ch = s[i]; + if (isdigit(ch)) + { + int digit = ch - '0'; + while (i < n - 1 && isdigit(s[i + 1])) + { + digit = digit * 10 + s[i + 1] - '0'; + i++; + } + numStack.push_front(digit); + } + else if (ch == '[') + { + strStack.push_front(resStr); + resStr.clear(); + } + else if (ch == ']') + { + string tmp = strStack.front(); + strStack.pop_front(); + int repeatCount = numStack.front(); + numStack.pop_front(); + for (int j = 0; j < repeatCount; j++) + tmp.append(resStr); + + resStr = tmp; + } + else resStr.push_back(ch); // 直接取出来放进结果字符串中 + } + return resStr; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "2[abc]3[cd]ef"; + auto res = sol.decodeString(s); + // 期望的结果: "abcabccdcdcdef" + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/91algo/daily/day5[2021-09-14] leetcode232-implement-queue-using-stacks_two_stacks.cpp b/91algo/daily/day5[2021-09-14] leetcode232-implement-queue-using-stacks_two_stacks.cpp new file mode 100644 index 00000000..f76e4aaf --- /dev/null +++ b/91algo/daily/day5[2021-09-14] leetcode232-implement-queue-using-stacks_two_stacks.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +using namespace std; + +class MyQueue { + stack s1, s2; + int front; + +public: + /** Initialize your data structure here. */ + MyQueue() {} + + /** Push element x to the back of queue. */ + void push(int x) { + if (s1.empty()) + front = x; + + s1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + if (s2.empty()) + { + while (!s1.empty()) + { /* 把s1中的元素全部移到s2中 */ + s2.push(s1.top()); + s1.pop(); + } + } + int res = s2.top(); + s2.pop(); + + return res; + } + + /** Get the front element. */ + int peek() { + if (!s2.empty()) + return s2.top(); + + return front; + } + + /** Returns whether the queue is empty. */ + bool empty() { + return s1.empty() && s2.empty(); + } +}; + +// Test +int main() +{ + MyQueue* q = new MyQueue(); + q->push(1); + q->push(2); + int val = q->peek(); + cout << val << endl; + int val2 = q->pop(); // return 1, queue is [2] + cout << val2 << endl; + bool isEmpty = q->empty(); + cout << (isEmpty ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/91algo/daily/posts/README.md b/91algo/daily/posts/README.md new file mode 100644 index 00000000..66fbc0ec --- /dev/null +++ b/91algo/daily/posts/README.md @@ -0,0 +1,278 @@ +# 相关文章 + +`91算法活动(第5期)`相关的打卡文章会发表在博客 [玩转力扣 | 极客学长](https://www.geekzl.com/leetcode), 或直接以markdown格式上传到这. + +
+ +## LeetCode 题解 + +| 基础篇 | 进阶篇 | 专题篇 | +| --------------------------- | ------------------------- | --------------------------------------- | +| [数组/栈/队列](#数组栈队列) | [高频面试题](#高频面试题) | [二分法](#二分法) | +| [链表](#链表) | [前缀树](#前缀树) | [滑动窗口](#滑动窗口) | +| [树](#树) | [并查集](#并查集) | [位运算](#位运算) | +| [哈希表](#哈希表) | [跳表](#跳表) | [搜索(BFS/DFS/回溯)](#搜索bfs-dfs-回溯) | +| [双指针](#双指针) | [剪枝](#剪枝) | [背包问题](#背包问题) | +| - | [字符串匹配](#字符串匹配) | [动态规划](#动态规划) | +| - | [堆](#堆) | [分治](#分治) | +| - | - | [贪心](#贪心) | + +## 每日一题 汇总 + +- [x] [【day1】989.数组形式的整数加法](./day1.md) +- [x] [【day2】821.字符的最短距离](./day2.md) +- [x] [【day3】1381.设计一个支持增量操作的栈 09-12](./day3.md) +- [x] [【day4】394.字符串解码 09-13](./day4.md) +- [x] [【day5】232.用栈实现队列 09-14](./day5.md) +- [x] [【day6】768.最多能完成排序的块 II 09-15](./day6.md) +- [x] [【day7】61.旋转链表](./day7.md) +- [x] [【day8】24.两两交换链表中的节点](./day8.md) +- [x] [【day9】109.有序链表转换二叉搜索树 09-18](./day9.md) +- [x] [【day10】160.相交链表 09-19](./day10.md) +- [x] [【day11】142.环形链表 II 09-20](./day11.md) +- [x] [【day12】146.LRU 缓存机制 09-21](./day12.md) +- [x] [【day13】104.二叉树的最大深度 09-22](./day13.md) +- [x] [【day14】100.相同的树 09-23](./day14.md) +- [x] [【day15】129.求根到叶子节点数字之和](./day15.md) +- [x] [【day16】513.找树左下角的值 09-25](./day16.md) +- [x] [【day17】297.二叉树的序列化与反序列化 09-26](./day17.md) +- [x] [【day18】987.二叉树的垂序遍历 09-27](./day18.md) +- [x] [【day19】1.两数之和 09-28](./day19.md) +- [x] [【day20】347.前 K 个高频元素](./day20.md) +- [x] [【day21】447.回旋镖的数量 09-30](./day21.md) +- [x] [【day22】3.无重复字符的最长子串 10-01](./day22.md) +- [x] [【day23】30.串联所有单词的子串10-02](./day23.md) +- [x] [【day24】1590.使数组和能被P整除 10-03](./day24.md) +- [x] [【day25】876.链表的中间结点 10-04](./day25.md) +- [x] [【day26】26.删除有序数组中的重复项 10-05](./day26.md) +- [x] [【day27】35.搜索插入位置 10-06](./day27.md) +- [x] [【day28】239.滑动窗口最大值 10-07](./day28.md) +- [x] [【day29】997.找到小镇的法官 10-08](./day29.md) +- [x] [【day30】886.可能的二分法 10-09](./day30.md) +- [x] [【day31】1203.项目管理 10-10](./day31.md) +- [x] [【day32】657.机器人能否返回原点 10-11](./day32.md) + + +## 基础篇 + +### 数组,栈,队列 + +#### 每日一题 + +- [x] [【day1】989.数组形式的整数加法](./day1.md) +- [x] [【day2】821.字符的最短距离](./day2.md) +- [x] [【day3】1381.设计一个支持增量操作的栈 09-12](./day3.md) +- [x] [【day4】394.字符串解码 09-13](./day4.md) +- [x] [【day5】232.用栈实现队列 09-14](./day5.md) +- [x] [【day6】768.最多能完成排序的块 II 09-15](./day6.md) + + +#### 数组拓展题目 + +- [x] [75.颜色分类](./basic/array-stack-queue/ext-sort-colors.md) + + +#### 栈拓展题目 + +- [ ] [946. 验证栈序列](https://leetcode-cn.com/problems/validate-stack-sequences/) + +#### 队列拓展题目 + +- [ ] [155.最小栈](https://leetcode-cn.com/problems/min-stack/) + + +#### 相关专题 + +- [ ] [前缀和](https://lucifer.ren/blog/2020/09/27/atMostK/) + +### 链表 + +#### 每日一题 + +- [x] [【day7】24.两两交换链表中的节点](./basic/linked-list/07.swap-nodes-in-pairs.md) + + +#### 链表拓展题目 + +- [x] [2.两数相加](./problems/2.add-two-numbers.md) + +### 树 + +#### 每日一题 + +- [x] [【day-13】104.二叉树的最大深度](./basic/binary-tree/13.maximum-depth-of-binary-tree.md) + +#### 树拓展题目 + +- [x] [105.从前序与中序遍历序列构造二叉树](./basic/binary-tree/ + +### 哈希表 + +#### 每日一题 + +- [x] [【day-19】1.两数之和](./basic/hashmap/19.two-sum.md) + + +#### 哈希表拓展题目 + +- [x] [645.错误的集合](./basic/hashmap/ext-set-mismatch.md) + + +### 双指针 + +#### 每日一题 + +- [x] [【day-25】35.搜索插入位置](./basic/two-pointers/25.search-insert-position.md) + + +#### 双指针拓展题目 + +- [x] [875.爱吃香蕉的珂珂](./basic/two-pointers/ext-koko-eating-bananas.md) + +## 进阶篇 + +### 高频面试题 + +**二叉树遍历系列** + +- [x] [【day-34】二叉树遍历系列](./medium/hot/34.traversal-of-binary-tree.md) + +**反转链表系列** + +- [x] [【day-35】206.反转链表](./medium/hot/35.reverse-linked-list.md) + +**位运算系列** + +- [ ] [【day-36】78.子集](./medium/hot/36.subsets.md) + +**动态规划系列** + +- [x] [【day-37】62.不同路径](./medium/hot/37.unique-paths.md) + + +**有效括号系列** + +- [x] [【day-38】20.有效括号](./medium/hot/38.valid-parentheses.md) + + +**设计系列** + +- [ ] [【day-39】剑指 Offer09.用两个栈实现队列](./) + + +**前缀和系列** + +- [x] [【day-40】网易面试题](./medium/hot/40.netease.md) + + +### 前缀树 + +- [x] [【day-41】208.实现 Trie](./medium/trie/41.implement-trie-prefix-tree.md) + +### 并查集 + +#### 每日一题 + +- [x] [【day-44】547.朋友圈](./medium/union-find/44.friend-circles.md) + + +#### 拓展 + +- [x] [1202.交换字符串中的元素](./medium/union-find/ext-smallest-string-with-swaps.md) + +### 跳表 + +- [ ] [【day-47】1206.设计跳表](./) + +### 剪枝 + +#### 每日一题 + +- [x] [【day-48】814.二叉树剪枝](./medium/prune/48.binary-tree-pruning.md) + + +### 字符串匹配 + +#### 每日一题 + +- [ ] [【day-52】28.实现 strStr()](./medium/rk-kpm/52.implement-strstr.md) + +#### 拓展题目 + +- [ ] [1371.每个元音包含偶数次的最长子字符串](./medium/day-52.md) + + +### 堆 + +#### 每日一题 + +- [x] [【day-54】215.数组中的第 K 个最大元素](./medium/heap/54.kth-largest-element-in-an-array.md) + + +## 专题篇 + +### 二分法 + +#### 每日一题 + +- [x] [【day-61】69.x 的平方根](./topics/binary-search/61.sqrtx.md) + + +#### 拓展题目 + +- [x] [33.搜索旋转排序数组](./topics/binary-search/ext-search-in-rotated-sorted-array.md) + +### 滑动窗口 + +#### 每日一题 + +- [x] [【day-67】1456.定长子串中元音的最大数目](./topics/sliding-window/67.maximum-number-of-vowels-in-a-substring-of-given-length.md) + +#### 拓展题目 + +- [x] [581.最短无序连续子数组](./topics/sliding-window/ext-shortest-unsorted-continuous-subarray.md) + +### 位运算 + +- [ ] [【day-72】268.缺失数字](./topics/day-72.md) + + +### 搜索(BFS, DFS, 回溯) + +- [x] [【day-74】1254.统计封闭岛屿的数目](./topics/day-74.md) + + +- [x] [5210.球会落何处](./topics/searching/ext-where-will-the-ball-fall.md) + +### 背包问题 + +- [x] [【day-80】322.零钱兑换](./topics/day-80.md) + + +### 动态规划 + +- [ ] [【day-84】爬楼梯变种](./topics/day-84.md) + + +### 分治 + +- [x] [【day-88】96.不同的二叉搜索树](./topics/day-88.md) + + +### 贪心 + +#### 每日一题 + +- [ ] [【day-90】765.情侣牵手](./topics/day-90.md) + +#### 贪心拓展题目 + +- [x] [135.分发糖果](./topics/greedy/ext-candy.md) + + +## 其他 + +- [x] [77.组合](./extensions/77.combination.md) + + +> [在线电子书](https://geekplayers.com/leetcode) diff --git a/91algo/daily/posts/day1.md b/91algo/daily/posts/day1.md new file mode 100644 index 00000000..f4ba23cd --- /dev/null +++ b/91algo/daily/posts/day1.md @@ -0,0 +1,105 @@ +# day1 - leetcode989. 数组形式的整数加法[2021-09-10] + +## 题目地址(989. 数组形式的整数加法) + +[989. 数组形式的整数加法](https://leetcode-cn.com/problems/add-to-array-form-of-integer/) + +https://leetcode-cn.com/problems/add-to-array-form-of-integer/ + +## 入选理由 + +1. 简单题目,适合大家上手。 +2. 之前力扣官方的每日一题,质量比较高 + +## 题目描述 + +对于非负整数 `X` 而言,`*X*` 的*数组形式*是每位数字按从左到右的顺序形成的数组。例如,如果 `X = 1231`,那么其数组形式为 `[1,2,3,1]`。 + +给定非负整数 `X` 的数组形式 `A`,返回整数 `X+K` 的数组形式。 + +**示例 1:** + +输入:A = [1,2,0,0], K = 34 输出:[1,2,3,4] 解释:1200 + 34 = 1234 + +**示例 2:** + +输入:A = [2,7,4], K = 181 输出:[4,5,5] 解释:274 + 181 = 455 + +**示例 3:** + +输入:A = [2,1,5], K = 806 输出:[1,0,2,1] 解释:215 + 806 = 1021 + +**示例 4:** + +输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1 输出:[1,0,0,0,0,0,0,0,0,0,0] 解释:9999999999 + 1 = 10000000000 + +**提示:** + +1. `1 <= A.length <= 10000` +2. `0 <= A[i] <= 9` +3. `0 <= K <= 10000` +4. 如果 `A.length > 1`,那么 `A[0] != 0` + +## 难度 + +- 简单 + +## 标签 + +[数组](https://leetcode-cn.com/tag/array/), [数学](https://leetcode-cn.com/tag/math/) + +## 前置知识 + +- 数组的遍历 + +## 思路 + +### 双指针 + 进位加法逻辑 + +双指针, 让两个数的末位对齐, 两个指针 i, j均从各自字符串的末尾开始走。 + +定义一个数组来存放结果, 一个int值carry来记录每位的进位值, 初始值设为0。 +算当前位置的数时, sum = a[i] + b[j] + carry, 每趟都要记得更新carry的值。 + +循环结束时, 由于低位的数字字符先加到了结果字符串中, 最后还需要 reverse 一次, 让位置恢复正常。 + +## 代码 + +### 实现语言: C++ + +```cpp +class Solution { +public: + vector addToArrayForm(vector& A, int k) { + if (k == 0) return A; + vector res; + int n = A.size(); + // 对位相加 + int carry = 0; + int sum = 0; + int i = n - 1; + while (k > 0 || i >= 0) + { + sum = carry + (k % 10); + if (i >= 0) // 保证访问A[i]前不越界 + sum += A[i]; + + carry = (sum <= 9) ? 0 : 1; + res.push_back(sum % 10); + k = k / 10; + + i--; + } + if (carry == 1) res.push_back(1); + reverse(res.begin(), res.end()); + return res; + } +}; +``` + +代码已上传到: [leetcode-ac/91algo - github.com](https://github.com/yanglr/leetcode-ac/tree/master/91algo) + +## 复杂度分析 + +- 时间复杂度:O(max(n, k)),其中 n 为数组长度, k为数K的长度。 +- 空间复杂度:O(n), 主要是结果数组用的空间 diff --git a/91algo/daily/posts/day10.md b/91algo/daily/posts/day10.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day11.md b/91algo/daily/posts/day11.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day12.md b/91algo/daily/posts/day12.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day13.md b/91algo/daily/posts/day13.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day14.md b/91algo/daily/posts/day14.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day15.md b/91algo/daily/posts/day15.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day16.md b/91algo/daily/posts/day16.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day17.md b/91algo/daily/posts/day17.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day18.md b/91algo/daily/posts/day18.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day19.md b/91algo/daily/posts/day19.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day2.md b/91algo/daily/posts/day2.md new file mode 100644 index 00000000..fd6ca29a --- /dev/null +++ b/91algo/daily/posts/day2.md @@ -0,0 +1,110 @@ +# day2 - 821. 字符的最短距离[2021-09-11] + +## 题目地址(821. 字符的最短距离) + +https://leetcode-cn.com/problems/shortest-distance-to-a-character + + + +## 思路 + +**题意**: 计算 `abs[i] = indexGap(i, 最近的字符c)`, 1 <= s.length <= 10^4 +输出 `abs[i]`的数组 + +### 解法: 双指针 中心扩展 + +使用一个结果数组 gaps[] + +将string s转为字符数组,然后从前往后遍历。 +循环变量记作i, 对于每一趟: +如果当前字符就是要搜索的字符c, 距离记为 0,否则分别向左、向右找最近的字符c。 +向左找, 找到第一个字符c, 将指针i与之的index之差记作leftDistance。 +向右找, 找到第一个字符c, 将指针i与之的index之差记作rightDistance。 +取两者的较小值。 + +依次填充 gaps[i] 的值即可。 + + + +## 代码 + +### 实现语言: C++ + +```cpp +class Solution { +public: + vector shortestToChar(string s, char c) { + vector gaps(s.size()); + vector chars(s.begin(), s.end()); + + for (int i = 0; i < chars.size(); i++) + { + // 如果当前字符就是要搜索的字符c, 距离为 0 + if (chars[i] == c) gaps[i] = 0; + else /* 否则分别向左、向右找最近的字符c */ + { + int leftDistance = INT_MAX, rightDistance = INT_MAX; + for (int left = i; left >= 0; left--) + { + if (chars[left] == c) // 向左找, 找到第一个 + { + leftDistance = i - left; + break; + } + } + for (int right = i; right < chars.size(); right++) // 向右找, 找到第一个 + { + if (chars[right] == c) + { + rightDistance = right - i; + break; + } + } + gaps[i] = min(leftDistance, rightDistance); + } + } + + return gaps; + } +}; +``` + +代码已同步上传到: [leetcode-ac/91algo - github.com](https://github.com/yanglr/leetcode-ac/tree/master/91algo) + + + +#### 复杂度分析 + +- 时间复杂度:O(n^2),其中 n 为字符串长度。 +- 空间复杂度:O(n) + + + +### 暴力解法: + +可以过,但比较慢。 + +```cpp +class Solution { +public: + vector shortestToChar(string s, char c) { + // 题意: 计算 abs[i] = indexGap(i, nearest_c), 1 <= s.length <= 10^4 + // 输出 abs[i]的数组 + vector indexes; // indexes of char c + for (int i = 0; i < s.size(); i++) + { + if (s[i] == c) indexes.push_back(i); + } + vector res; + for (int i = 0; i < s.size(); i++) + { + vector gaps; // gap for char s[i] to char c + for (auto index : indexes) + gaps.push_back(abs(index - i)); + auto it = min_element(gaps.begin(), gaps.end()); + res.push_back(*it); + } + return res; + } +}; +``` diff --git a/91algo/daily/posts/day20.md b/91algo/daily/posts/day20.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day21.md b/91algo/daily/posts/day21.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day22.md b/91algo/daily/posts/day22.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day23.md b/91algo/daily/posts/day23.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day24.md b/91algo/daily/posts/day24.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day25.md b/91algo/daily/posts/day25.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day26.md b/91algo/daily/posts/day26.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day27.md b/91algo/daily/posts/day27.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day28.md b/91algo/daily/posts/day28.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day29.md b/91algo/daily/posts/day29.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day3.md b/91algo/daily/posts/day3.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day30.md b/91algo/daily/posts/day30.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day31.md b/91algo/daily/posts/day31.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day32.md b/91algo/daily/posts/day32.md new file mode 100644 index 00000000..de56d8a2 --- /dev/null +++ b/91algo/daily/posts/day32.md @@ -0,0 +1,59 @@ +# day32 - leetcode657. 机器人能否返回原点[2021-10-11] + +## 题目地址(657. 机器人能否返回原点) + + + + +## 思路 + +### 模拟法 + + + +定义一个初始坐标(x, y), 每次从moves数组读入一个字符, 根据具体反向进行一次x或y的增减。 +看循环结束时, 是否能使 x == 0 且 y ==0 。 + + + +## 代码 + + +### 实现语言: C++ + + + +```cpp +class Solution { +public: + bool judgeCircle(string moves) { + int x = 0; + int y = 0; + for (const auto& move : moves) + { + switch (move) + { + case 'U': + y--; + break; + case 'D': + y++; + break; + case 'R': + x++; + break; + case 'L': + x--; + break; + } + } + return x == 0 && y == 0; + } +}; +``` + + +## 复杂度分析 + +- 时间复杂度:O(n) +- 空间复杂度:O(1) diff --git a/91algo/daily/posts/day4.md b/91algo/daily/posts/day4.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day5.md b/91algo/daily/posts/day5.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day6.md b/91algo/daily/posts/day6.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day7.md b/91algo/daily/posts/day7.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day8.md b/91algo/daily/posts/day8.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/daily/posts/day9.md b/91algo/daily/posts/day9.md new file mode 100644 index 00000000..e69de29b diff --git a/91algo/notes/README.md b/91algo/notes/README.md new file mode 100644 index 00000000..ce1e5d72 --- /dev/null +++ b/91algo/notes/README.md @@ -0,0 +1,3 @@ +# 课程笔记 + +这里会记录重要笔记. diff --git a/91algo/templates/README.md b/91algo/templates/README.md new file mode 100644 index 00000000..af24e140 --- /dev/null +++ b/91algo/templates/README.md @@ -0,0 +1,3 @@ +# 本人原创的代码模板(Code templates) + +根据课程给的伪代码, 主要使用C++语言来完成。 diff --git a/AimedAtOffer2014edition/AimedAtOffer11-Pow(x, n).cpp b/AimedAtOffer2014edition/AimedAtOffer11-Pow(x, n).cpp deleted file mode 100644 index 892e9625..00000000 --- a/AimedAtOffer2014edition/AimedAtOffer11-Pow(x, n).cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -using namespace std; -class Solution { -public: - double Power(double base, int exponent) { - if(exponent < 0) - { - exponent = -exponent; - base = 1.0/base; - } - double res = 1.0; - for(; exponent > 0; exponent >>= 1) - { - if((exponent & 0x1) == 1) res *= base; - base *= base; - } - return res; - } -}; - -// ����Ϊ���� -int main() -{ - Solution sol; - double num1=sol.Power(20, 2); - double num2=sol.Power(13, -2); - double num3=sol.Power(-10, 3); - int num4=sol.Power(0, 0); - printf("%f\n",num1); - printf("%f\n",num2); - printf("%f\n",num3); - printf("%d\n",num4); - return 0; -} \ No newline at end of file diff --git a/AimedAtOffer2014edition/AimedAtOffer15-kthFromTail.cpp b/AimedAtOffer2014edition/AimedAtOffer15-kthFromTail.cpp deleted file mode 100644 index f2462370..00000000 --- a/AimedAtOffer2014edition/AimedAtOffer15-kthFromTail.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include - -using namespace std; -struct ListNode { - int val; - struct ListNode *next; - ListNode(int x) : - val(x), next(NULL) { - } -}; - -class Solution{ -public: -ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) - { - if(pListHead==NULL || k==0) return NULL; - - ListNode *pAhead,*pBehind; - pAhead=pListHead; - pBehind=NULL; - for(unsigned int idx=0; idxnext==NULL) return NULL; - else pAhead=pAhead->next; - } - pBehind=pListHead; - while(pAhead->next != NULL) - { - pAhead=pAhead->next; - pBehind=pBehind->next; - } - return pBehind; - } -}; - -// ����Ϊ���Բ��� - -int main() -{ - ListNode *p_head,*kthNode; - Solution sol; - - p_head=new ListNode(5); - p_head->next=new ListNode(2); - p_head->next->next=new ListNode(3); - p_head->next->next->next=new ListNode(8); - // p_head=NULL; - - kthNode=sol.FindKthToTail(p_head,2); - - if(kthNode!=NULL) cout<<"The value of kth Node is: "<val< -#include -#include -using namespace std; - -class Solution { -public: - bool IsPopOrder(vector pushV,vector popV) { - if(pushV.size() == 0 || popV.size() == 0) - return false; // �������һ�����г���Ϊ0���򲻺����⣬����false - stack s; - - int k=0; - for(int i=0;i invec(in,in+5); - vector vec1(a,a+5); - vector vec2(b,b+5); - - //vector invec(0); - //vector vec1(0); - //vector vec2(0); - - cout<<"Is the sequence possible pop order ?: "< -#include -#include -using namespace std; - -class Solution{ -public: -void replaceSpace(char *str, int length) // ��������ָ��:lengthΪ�ַ�����str�������� -{ - if(str==NULL || length<=0) return; - - int newlen=0; - int spaceCount = 0; - int idx; - for(idx = 0; str[idx] != '\0'; idx++) - { - if (str[idx] == ' ') - { - spaceCount++; - } - } - newlen = idx + 2*spaceCount; - if(newlen > length) return; - str[newlen]='\0'; //���кܹؼ� - int frontCur = idx - 1, backCur = newlen-1; - for(; frontCur >= 0 && backCur > frontCur; frontCur--) - { - if (str[frontCur] == ' ') - { - str[backCur--] = '0'; - str[backCur--] = '2'; - str[backCur--] = '%'; - } - else str[backCur--] = str[frontCur]; - } -} -}; - -// ����Ϊ���Բ��� - -int main() -{ - Solution sol; - char str[]="Hello World, haha"; - sol.replaceSpace(str, 20); - // printf("%s\n",str); - cout< -#include -#include -using namespace std; -struct TreeNode{ - int val; - struct TreeNode *left; - struct TreeNode *right; - TreeNode(int x) : - val(x), left(NULL), right(NULL) { - } -}; -class Solution { -public: - TreeNode* KthNode(TreeNode* pRoot, unsigned int k) - { - TreeNode *p=pRoot; - TreeNode *resNode; - if(p==NULL || k==0) return NULL; - stack st; - unsigned int count=0; - - while(!st.empty() || p != NULL) - { - if(p != NULL) - { - st.push(p); - p=p->left; - } - if(p == NULL) - { - p=st.top(); // obtain the current node - count++; - if(count==k) resNode=p; - st.pop(); - p=p->right; - } - } - return resNode; - } -}; - -// testing - -// 6 -// / \ -// 3 8 -// / \ / \ -// 2 5 7 9 - -int main() -{ - Solution sol; - TreeNode* root = new TreeNode(6); - root->left = new TreeNode(3); - root->left->left = new TreeNode(2); - root->left->right = new TreeNode(5); - root->right = new TreeNode(8); - root->right->left = new TreeNode(7); - root->right->right = new TreeNode(9); - TreeNode* p=sol.KthNode(root, 3); - printf("The value of Kth Node is: %d\n", p->val); - return 0; -} diff --git a/AimedAtOffer2014edition/AimedAtOffer7-QueueByTwoStacks.cpp b/AimedAtOffer2014edition/AimedAtOffer7-QueueByTwoStacks.cpp deleted file mode 100644 index 26a33b6c..00000000 --- a/AimedAtOffer2014edition/AimedAtOffer7-QueueByTwoStacks.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include -using namespace std; - -class Solution -{ -private: - stack stack1; - stack stack2; -public: - void push(int node) - { - stack1.push(node); - } - - int pop() - { - int tempVal; - if(stack2.empty()){ - while(!stack1.empty()){ - tempVal=stack1.top(); - stack2.push(tempVal); - stack1.pop(); - } - } - tempVal=stack2.top(); - stack2.pop(); - return tempVal; - } -}; - -// ����Ϊ���Բ��֣������������ -int main() -{ - Solution sol; - - srand((unsigned)time(NULL)); - rand(); - double feed=((double) rand()/(RAND_MAX)) + 1; // ��������������� - - for(int idx=1;idx<=5;idx++) - { - sol.push(3.24*idx*feed); - } - cout< -using namespace std; - -struct ListNode { - int val; - struct ListNode *next; - ListNode(int x) : - val(x), next(NULL) { - } -}; - -class Solution { -public: - ListNode* sortList(ListNode* head) { - ListNode *pFast, *pSlow; - pFast=head; - pSlow=head; - if(head==NULL || head->next==NULL) return head; - else { - while(pFast->next!=NULL && pFast->next->next!=NULL) - { - pFast=pFast->next->next; - pSlow=pSlow->next; - } - pFast=pSlow; - pSlow=pSlow->next; - pFast->next=NULL; - - pFast=sortList(head); - pSlow=sortList(pSlow); - return merge(pFast,pSlow); - } -} - - ListNode* merge(ListNode* head1, ListNode *head2) - { - ListNode *res, *p; - if(head1==NULL) return head2; - if(head2==NULL) return head1; - if(head1->val < head2->val) - { - res=head1; - head1=head1->next; - } - else { - res=head2; - head2=head2->next; - } - p=res; - while(head1!=NULL && head2!=NULL) - { - if(head1->val < head2->val) - { - p->next=head1; - head1=head1->next; - } - else { - p->next=head2; - head2=head2->next; - } - p=p->next; - } - - if(head1!=NULL) p->next=head1; - else if(head2!=NULL) p->next=head2; - return res; - } -}; - -// ����Ϊ���Բ��� - -int main() -{ - ListNode *pOut; - ListNode *head=new ListNode(5); - head->next=new ListNode(8); - head->next->next=new ListNode(7); - head->next->next->next=new ListNode(12); - head->next->next->next->next=new ListNode(4); - Solution sol; - - pOut=sol.sortList(head); - - while(pOut!=NULL) - { - cout<val<<" "; - pOut=pOut->next; - } - cout< -using namespace std; - -struct ListNode { - int val; - ListNode *next; - ListNode(int x) : val(x), next(NULL) {} -}; - -class Solution { -public: - ListNode* reverseList(ListNode* head) { - ListNode *p; - ListNode *newhead=NULL; - p=head; - - if(head==NULL || head->next==NULL) return head; - - while(p!=NULL) - { - ListNode *temp=p; - p=p->next; - - temp->next=newhead; - newhead=temp; - } - return newhead; - } -}; - -int main() -{ - ListNode *p_head, *newhead, *track; - Solution sol; - - p_head=new ListNode(5); - p_head->next=new ListNode(2); - p_head->next->next=new ListNode(3); - p_head->next->next->next=new ListNode(8); - // p_head=NULL; - - newhead=sol.reverseList(p_head); - track=newhead; - - while(track != NULL) - { - cout<<"The value of related Node is: "<val<next; - } - return 0; -} \ No newline at end of file diff --git a/AimedAtOffer2014edition/baiduFront-ex1.cpp b/AimedAtOffer2014edition/baiduFront-ex1.cpp deleted file mode 100644 index 901a9637..00000000 --- a/AimedAtOffer2014edition/baiduFront-ex1.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -using namespace std; -typedef long long int64; // int64(LL): 64λ������, ��long long�ı�� - -int64 m,n,k; -int64 cal(int64 x) // �����xС�����ĸ��� -{ - int64 sum=0; - for(int i=1;i<=n;i++) - { - sum += min(m,x/i); - } - return sum; -} - -int64 binarySearch(int64 leftVal, int64 rightVal, int64 kth) -{ - int64 midVal; - - while(leftVal <= rightVal) - { - midVal=(leftVal+rightVal)/2; - if(cal(midVal) < kth) leftVal=midVal+1; // Ҫ�ҵ����ں��棬�������޼������� - else rightVal=midVal-1; // Ҫ�ҵ�����ǰ�棬�������޼�����С - } - return leftVal; -} - -int main() -{ - while(cin>>m>>n>>k && m>=1 && n>=1 && k>=1 && k<=m*n) - { - cout< -#include -#include -using namespace std; - -int maxProfit(vector& prices) { - int len=prices.size(); - if(len==0||len==1) - return 0; - int min=prices[0]; - int sum=0; - for(int i=1;imin) - { - int temp=prices[i]-min; - if(temp>sum) - sum=temp; - } - } - return sum; -} - -int main() -{ - int n; - vector vec; - while(scanf("%d", &n)) - { - vec.push_back(n); - char ch = getchar(); - if(ch == '\n') break; - } - - // for(int i: vec) - // cout< -#include -using namespace std; -class Solution { -public: - vector grayCode(int n) { - int size = 1< grayCodes(size,0); - int gDecNum=0; - for(int i = 0; i < size; i++){ - gDecNum = i ^ (i>>1); // ��ѧ��ʽdigG[i]=i ^ i/2��gDecNum��һ���������Ӧ�Ķ����������洢ʱ���int(ʮ����) - grayCodes[i] = gDecNum; - } - return grayCodes; - } -}; - -// ����Ϊ���Բ��� -int main() -{ - int n,j; - vector arr,display; - cin>>n; - - Solution sol; - display=sol.grayCode(n); - for(j=0;j -#include -#include -#include -using namespace std; - -typedef struct node{ - int index; - int value; - node(){}; - node(int i, int v) : index(i), value(v){} -}Node; - -bool compare(const Node& a, const Node& b){ - return a.value < b.value; -} - -class Solution { -public: - vector twoSum(vector &nums, int target) { - - int len = nums.size(); - assert(len >= 2); - - vector ret(2, 0); // ��ʼ����ret����2��ֵΪ0��Ԫ�� - - vector nums2(len); - for(int i = 0; i < len; i++){ - nums2[i] = Node(i+1, nums[i]); - } - - sort(nums2.begin(), nums2.end(), compare); // ���ÿ��ţ�T(n)=O(n*log(n)) - - int l = 0; - int r = len - 1; - while(l < r){ - int sum = nums2[l].value + nums2[r].value; - if(sum == target){ - ret[0] = min(nums2[l].index, nums2[r].index)-1; // ע�⣬������Ҫ��ȥ1 - ret[1] = max(nums2[l].index, nums2[r].index)-1; - break; - } else if(sum < target){ - l++; - } else { - r--; - } - } - return ret; // ������ָ����ɨ - } -}; - -// �����Dz��Դ��� - -int main() -{ - Solution sol; - vector arr; - - arr.push_back(3); - arr.push_back(2); - arr.push_back(4); - - vector ret = sol.twoSum(arr, 6); - cout< -#include - -using namespace std; - -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(NULL), right(NULL) {} - }; - -class Solution { -public: - TreeNode* invertTree(TreeNode* root) { - if(root==NULL) return NULL; - TreeNode* p; - p=root->left; - root->left=root->right; - root->right=p; - - invertTree(root->left); - invertTree(root->right); - return root; - } -}; - -// ����Ϊ��֤ -int main() { - TreeNode *root = new TreeNode(-1); - TreeNode *temp; - root->left = new TreeNode(2); - root->right = new TreeNode(3); - root->right->right = new TreeNode(0); - - Solution sol; - - cout << root->left->val << endl; - temp=sol.invertTree(root); - cout << temp->left->val << endl; - cout << temp->left->left->val << endl; - - return 0; -} \ No newline at end of file diff --git a/AimedAtOffer2014edition/leetcode338.cpp b/AimedAtOffer2014edition/leetcode338.cpp deleted file mode 100644 index eefdf32e..00000000 --- a/AimedAtOffer2014edition/leetcode338.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -using namespace std; - -class Solution { -public: - vector countBits(int num) { - vector res; - res.push_back(0); - if(num <= 0 ) return res; - for(int i=1; i <= num; i++) - { - int temp = i; - int count = 0; - while(temp != 0) - { - temp = temp&(temp-1); - count++; - } - res.push_back(count); - } - return res; - } -}; - -int main() -{ - Solution sol; - vector res; - int n; - cin>>n; - res=sol.countBits(n); - - for(auto i:res) - cout< -#include -using namespace std; - -class Solution { -public: - int myAtoi(string str) - { - if(str=="") return 0; // str.length()==0 �ȼ��� str==""������������дΪif(str=="" || str.length()==0) - long long final, res=0; - int len=str.length(); - int sign=1; - int sign_count=0; - for(int i=0; i='0') - { - res = res*10+ch-'0'; - if(res> INT_MAX && sign==1) return INT_MAX; - if(res< INT_MIN && sign==-1) return INT_MIN; - if(i+1= INT_MIN && res <= INT_MAX) final=res*sign; - else if(sign==1) final = INT_MAX; - else if(sign==-1) final = INT_MIN; // ���Խ�������߽磬������Ӧ��ֵ - return final; // -2147483648[(signed int)0x80000000] ~ 2147483647(0x7FFFFFFF) - } -}; - -// ����Ϊ���� -int main() -{ - string str0; // str0.size() == 0; // ����İ�䣺��д�ɲ�д���ַ���Ĭ�ϳ�ʼ��Ϊ�մ� - string str1="1ab3"; // Ӧ����1 - string str2="18446744073709551617"; - string str3="- +899999 "; - string str4=" 010"; // Ӧ����10 - string str5=" +0 123"; - string str6="13 456"; // 123 - string str7=" - 321"; - - Solution sol; - cout< -#include -using namespace std; - -class Solution{ -public: -void quickSort(int arr[], int forward, int backward) -{ - int part_pos; // ��¼ÿ�ε��ÿ��� quickSort()����Ԫe��λ�� - if(forward>=backward) return; - - // int split(int[], int, int); // �������C�����У��˴���Ҫ����һ�£����������class���棬���ܽ������� - part_pos=split(arr, forward, backward); - - cout<<"The postion of the partition elemen is: "<part_val) backward--; - if(forward>=backward) break; - arr[forward++]=arr[backward]; - - while(forward=backward) break; - arr[backward--]=arr[forward]; - } - arr[backward]=part_val; - return backward; -} -}; - -int main() -{ - Solution sol; - int arr[]={12,3,6,18,7,15,10,56,4}; - sol.quickSort(arr,0,8); - printf("The final result is:\n"); - for(int idx=0;idx<9;idx++) - { - printf("%d ",arr[idx]); - } - printf("\n"); - return 0; -} \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..4d482ad0 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +leetcode-ac_contact. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..9eb93dfb --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,4 @@ +# How to contribute +如果想第一时间收到最新更新, 还请点个star/fork 或 watch, 如果有不错的解法也欢迎提PR~ + +如果在本项目中发现问题, 欢迎给我提issue喔, 看到后会立刻回复的~ diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..8e199408 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Bravo Yeung极客学长 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git "a/LeetCode\344\270\255\346\226\207title(\346\214\201\347\273\255\346\233\264\346\226\260).md" "b/LeetCode\344\270\255\346\226\207title(\346\214\201\347\273\255\346\233\264\346\226\260).md" deleted file mode 100644 index f7a98db1..00000000 --- "a/LeetCode\344\270\255\346\226\207title(\346\214\201\347\273\255\346\233\264\346\226\260).md" +++ /dev/null @@ -1,119 +0,0 @@ -| leetcode 编号 | 英文title(中文title) | 要求 | 备注 | -| --------------------------------------- | ---------------------------------------- | ------ | ------------ | -| LeetCode 1 | Two Sum(2数之和为目标数) | | | -| LeetCode 2 | Add Two Numbers(两数相加) | | | -| LeetCode 3 | Longest Substring Without Repeating Characters(最长无重复字串) | 必会 | | -| LeetCode 4 | Median of Two Sorted Arrays(两个已排序数组的中位数) | 必会 | | -| LeetCode 5 | Longest Palindromic Substring(最大回文子字符串) | 必会 | | -| LeetCode 6 | ZigZag Conversion(Z型转换) | | | -| LeetCode 7 | Reverse Integer(翻转整数) | | | -| LeetCode 8 | String to Integer (atoi)(转换到整型) | 必会 | 剑指offer有 | -| LeetCode 9 | Palindrome Number (回文数) | | | -| LeetCode 10 | Regular Expression Matching (正则表达式匹配) | 必会 | | -| LeetCode 11 | Container With Most Water(最大水容器) | | | -| LeetCode 12 | Integer to Roman(整型数到罗马数) | | | -| LeetCode 13 | Roman to Integer(罗马数到整型数) | | | -| LeetCode 14 | Longest Common Prefix(最长公共前缀) | | | -| LeetCode 15 | 3 Sum(3个数的和) | | | -| LeetCode 16 | 3 Sum Closest(最接近的3个数的和) | | | -| LeetCode 17 | Letter Combinations of a Phone Number(电话号码的字母组合) | | | -| LeetCode 18 | 4Sum(4个数的和) | | | -| LeetCode 19 | Remove Nth Node From End of List(从列表尾部删除第N个结点)(*) | 必会 | | -| LeetCode 20 | Valid Parentheses(有效的括号) | | | -| LeetCode 21 | Merge Two Sorted Lists(合并两个已排序的数组) | 必会 | 已AC | -| LeetCode 22 | Generate Parentheses(生成括号) | | | -| LeetCode 23 | Merge k Sorted Lists(合并K个已排序链表) | | | -| LeetCode 24 | Swap Nodes in Pairs(交换序列中的结点) | | | -| LeetCode 25 | Reverse Nodes in k-Group(在K组链表中反转结点) | | | -| LeetCode 26 | Remove Duplicates from Sorted Array(从已排序数组中移除重复元素) | | | -| LeetCode 27 | Remove Element(移除元素) | | | -| LeetCode 28 | Implement strStr()(实现strStr()函数) | | | -| LeetCode 29 | Divide Two Integers(两个整数相除)(*) | | | -| LeetCode 30 | Substring with Concatenation of All Words(与所有文字串联子串)(*) | | | -| LeetCode 31 | Next Permutation(下一个排列) | | | -| LeetCode 32 | Longest Valid Parentheses(最长有效括号)(*) | | | -| LeetCode 33 | Search in Rotated Sorted Array(旋转数组求查找某个值是否存在) | | | -| LeetCode 34 | Search for a Range(搜索范围) | | | -| LeetCode 35 | Search Insert Position(搜索并插入) | | | -| LeetCode 36 | Valid Sudoku(有效数独)(*) | | | -| LeetCode 37 | Sudoku Solver(求解数独)(*) | | | -| LeetCode 38 | Count and Say(计数与报数) | | | -| LeetCode 50 | Pow(x, n)(Math、Binary Search)(*) | | | -| Leetcode 53 | Maximum Subarray(连续子数组的最大和) | 必会 | | -| LeetCode 58 | Length of Last Word(最后单词的长度) | | | -| LeetCode 66 | Plus One(加一)(vector) | | | -| LeetCode 67 | Add Binary(二进制相加)(*) | | | -| LeetCode 69 | Sqrt(x)(Math、Binary Search)(*) | | | -| LeetCode 70 | Climbing Stairs(爬楼梯)(动态规划)(*) | | | -| LeetCode 74 | Search a 2D Matrix(搜索2D矩阵) | | | -| LeetCode 75 | Sort Colors(颜色排序) | | | -| LeetCode 83 | Remove Duplicates from Sorted List(从已排序链表中移除重复元素)(*) | 必会 | | -| LeetCode 84 | Largest Rectangle in Histogram(直方图上的最大矩形)(*) | hard,栈 | | -| LeetCode 88 | Merge Sorted Array(合并排序数组)(*) | | | -| LeetCode 94 | Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代) | | | -| LeetCode 100 | Same Tree(相同树判断)(二叉树、递归、栈和队列、深搜和宽搜) | | | -| LeetCode 101 | Symmetric Tree(对称树)(*) | | | -| LeetCode 102 | Binary Tree Level Order Traversal(二叉树的层级顺序遍历)(*) | | | -| LeetCode 104 | Maximum Depth of Binary Tree(二叉树的最大深度) | | | -| LeetCode 105 | Construct Binary Tree from Preorder and Inorder Traversal(根据中序和前序遍历结果重建二叉树) | 必会 | | -| LeetCode 106 | Construct Binary Tree from Inorder and Postorder Traversal(根据中序和后序遍历结果重建二叉树) | 必会 | 剑指offer有 | -| LeetCode 107 | Binary Tree Level Order Traversal II(二叉树的层级顺序遍历2,BFS)(*) | 必会 | | -| LeetCode 110 | Balanced Binary Tree(平衡二叉树)(*) | | | -| LeetCode 111 | Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*) | | | -| LeetCode 112 | Path Sum(路径和)(BT、DP)(*) | | | -| LeetCode 113 | Path Sum II(二叉树中和为某个值的路径) | 必会 | | -| LeetCode 118 | Pascal's Triangle(帕斯卡三角形)(vector) | | | -| LeetCode 119 | Pascal's Triangle II(帕斯卡三角形II)(vector、数学公式)(*) | | | -| LeetCode 121 | Best Time to Buy and Sell Stock(股票买入卖出的最佳时间) | | | -| LeetCode 122 | Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II) | | | -| LeetCode 125 | Valid Palindrome(有效回文)(*) | | | -| LeetCode 136 | Single Number(只出现一次的数字) | 必会 | | -| LeetCode 137 | Single Number II(只出现一次的数字 II)(*) | 必会 | | -| LeetCode 138 | Copy List with Random Pointer(复杂链表的复制) | 必会 | 剑指offer有 | -| LeetCode 142 | Linked List Cycle II(判断链表是否有环) | 必会 | | -| LeetCode 144 | Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代) | | | -| LeetCode 145 | Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代) | | | -| LeetCode 151 | Reverse Words in a String(翻转字符串中的单词) | 必会 | | -| LeetCode 153 | Find Minimum in Rotated Sorted Array(旋转数组求最小值) | 必会 | | -| LeetCode 155 | Min Stack(实现一个栈,要求常数级时间内找出栈中的最小值) | 必会 | | -| LeetCode 160 | Intersection of Two Linked Lists(两个单链表的交点)(*) | 必会 | 剑指offer有 | -| LeetCode 165 | Compare Version Numbers(比较版本号)(string)(*) | | | -| LeetCode 168 | Excel Sheet Column Title(Excel的列向表标题) | | | -| LeetCode 169 | Majority Element(主要元素)(vector、map) | | | -| LeetCode 171 | Excel Sheet Column Number(Excel的列向表数字) | | | -| LeetCode 172 | Factorial Trailing Zeroes(阶乘后的零)(*) | | | -| LeetCode 189 | Rotate Array(旋转数组) | | | -| LeetCode 191 | Number of 1 Bits(给定的数的二进制表示中,有多少个 1) | | | -| LeetCode 198 | House Robber(强盗盗窃最大值)(动态规划)(*) | | | -| LeetCode 202 | Happy Number(开心数)(vector、unordered_set) | | | -| LeetCode 203 | Remove Linked List Elements(移除链表元素)(*) | | | -| LeetCode 204 | Count Primes(质数计数)(*) | | | -| LeetCode 205 | Isomorphic Strings(同构的字符串)(string、vector、map)(*) | | | -| LeetCode 206 | Reverse Linked List(反转链表)(四步将递归改写成迭代)(*) | 必会 | | -| LeetCode 215 | Kth Largest Element in an Array(第k大的数) | 必会 | | -| LeetCode 217 | Contains Duplicate(包含重复数字)(Vector、hash) | | | -| LeetCode 219 | Contains Duplicate II(包含重复数字2)(*) | | | -| LeetCode 223 | Rectangle Area(矩形面积) | | | -| LeetCode 225 | Implement Stack using Queues(用两个队列来实现栈)(*) | 必会 | | -| LeetCode 226 | Invert Binary Tree(翻转二叉树,求树的镜像) | 必会 | 剑指offer有 | -| LeetCode 228 | Summary Ranges(值域)(*) | | | -| LeetCode 231 | Power of Two(2的幂) | | | -| LeetCode 232 | Implement Queue using Stacks(用两个栈来实现队列)(*) | 必会 | 剑指offer有,已AC | -| LeetCode 234 | Palindrome Linked List(回文链表)(*) | | | -| LeetCode 235 | Lowest Common Ancestor of a Binary Search Tree(二叉搜索树的最小公共祖先) | | 剑指offer有 | -| LeetCode 237 | Delete Node in a Linked List(在链表中删除节点) | 必会 | | -| LeetCode 238 | Product of Array Except Self(除自身外数组其余数的乘积) | | | -| LeetCode 242 | Valid Anagram(有效字谜)(*) | | | -| LeetCode 258 | Add Digits(数字相加,数字根) | | | -| LeetCode 260 | Single Number III(只出现一次的数字 III)(*) | 必会 | | -| LeetCode 263 | Ugly Number(丑数) | | | -| LeetCode 268 | Missing Number(丢失的数字) | | | -| LeetCode 278 | First Bad Version(第一个坏版本)(二分法)(*) | | | -| LeetCode 283 | Move Zeroes(移动所有的零元素) | | | -| LeetCode 290 | Word Pattern(单词模式)(istringstream、vector、map)(*) | | | -| LeetCode 292 | Nim Game(Nim游戏) | | | -| LeetCode 303 | Range Sum Query - Immutable(范围总和查询-永久不变)(*) | | | -| LeetCode 319 | Bulb Switcher(灯泡切换)(从规律中发现算法……) | | | -| LeetCode 326 | Power of Three(3的幂)(递归、Log函数) | | | -| LeetCode 328 | Odd Even Linked List(奇偶链表)(*) | | | - diff --git "a/PHP\345\270\270\347\224\250\345\207\275\346\225\260\346\200\273\347\273\223(160\345\244\232\344\270\252).md" "b/PHP\345\270\270\347\224\250\345\207\275\346\225\260\346\200\273\347\273\223(160\345\244\232\344\270\252).md" deleted file mode 100644 index b62a0ba1..00000000 --- "a/PHP\345\270\270\347\224\250\345\207\275\346\225\260\346\200\273\347\273\223(160\345\244\232\344\270\252).md" +++ /dev/null @@ -1,1236 +0,0 @@ -# PHP常用函数总结 - -## 数学函数 -1.abs(): 求绝对值 -```php -$abs = abs(-4.2); //4.2 数字绝对值数字 -``` -2.ceil(): 进一法取整 -```php -echo ceil(9.999); // 10 浮点数进一取整 -``` -3.floor(): 舍去法取整 -```php - echo floor(9.999); // 9 浮点数直接舍去小数部分 -``` -4.fmod(): 浮点数取余 -```php - $x = 5.7; - $y = 1.3; // 两个浮点数,x>y 浮点余数 - $r = fmod($x, $y); - // $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7 -``` -5.pow(): 返回数的n次方 -```php - echo pow(-1, 20); // 1 基础数|n次方乘方值 -``` -6.round(): 浮点数四舍五入 -```php - echo round(1.95583, 2); // 1.96, 一个数值|保留小数点后多少位,默认为0 舍入后的结果 -``` -7.sqrt(): 求平方根 -```php - echo sqrt(9); //3 被开方的数平方根 -``` -8.max(): 求最大值 -```php - echo max(1, 3, 5, 6, 7); // 7 -``` -多个数字或数组 -返回其中的最大值 -```php - echo max(array(2, 4, 5)); // 5 -``` -9.min(): 求最小值 - -*输入*: 多个数字或数组 - -*输出*: 返回其中的最小值 - -10.mt_rand(): 更好的随机数 - -*输入*: 最小|最大, -*输出*: 随机数随机返回范围内的值 -```php - echo mt_rand(0,9);//n -``` -11.rand(): 随机数 -*输入*: 最小|最大, -*输出*: 随机数随机返回范围内的值 - -12.pi(): 获取圆周率值 - -### **去空格或或其他字符:** - -13.trim(): 删除字符串两端的空格或其他预定义字符 -```php - $str = "\r\nHello World!\r\n"; - echo trim($str); -``` -输入: 目标字符串 -返回值: 清除后的字符串 - -14.rtrim(): 删除字符串右边的空格或其他预定义字符 -```php - $str = "Hello World!\n\n"; - echo rtrim($str); -``` -15.chop(): rtrim()的别名 - -16.ltrim(): 删除字符串左边的空格或其他预定义字符 -```php - $str = "\r\nHello World!"; - echo ltrim($str); -``` -17.dirname(): 返回路径中的目录部分 -```php - echo dirname("c:/testweb/home.php"); //c:/testweb -``` -输入: 一个包含路径的字符串 -返回值: 返回文件路径的目录部分 - -### **字符串生成与转化:**   -18.str_pad(): 把字符串填充为指定的长度 -```php - $str = "Hello World"; - echo str_pad($str,20,"."); -``` -*输入*: -要填充的字符串|新字符串的长度|供填充使用的字符串, 默认是空白 - -*输出*: -完成后的字符串 - -19.str_repeat(): 重复使用指定字符串 -```php - echo str_repeat(".",13); // 要重复的字符串|字符串将被重复的次数13个点 -``` -20.str_split(): 把字符串分割到数组中 -```php -print_r(str_split("Hello")); -``` -*输入*: 要分割的字符串|每个数组元素的长度,默认1 - -*输出*: 拆分后的字符串数组 - -21.strrev(): 反转字符串 -```php - echo strrev("Hello World!"); // !dlroW olleH -``` -输出: 目标字符串颠倒顺序后的字符串 -
- -22.wordwrap(): 按照指定长度对字符串进行折行处理 -```php - $str = "An example on a long word is: - Supercalifragulistic"; - echo wordwrap($str,15); -``` -输入: 目标字符串|最大宽数 - -输出: 折行后的新字符串 - -23.str_shuffle(): 随机地打乱字符串中所有字符 -```php - echo str_shuffle("Hello World"); -``` -输入: 目标字符串顺序 -输出: 打乱后的字符串 - -24.parse_str(): 将字符串解析成变量 -```php - parse_str("id=23&name=John%20Adams", $myArray); - print_r($myArray); -``` -*输入*: 要解析的字符串|存储变量的数组名称 - -*输出*: -返回Array( -[id] => 23 -[name] => John Adams) - -25.number_format(): 通过千位分组来格式化数字 -*输入:* -要格式化的数字|规定多少个小数|规定用作小数点的字符 -串|规定用作千位分隔符的字符串 - -*输出:* -1,000,000 -1,000,000.00 -1.000.000,00 - - -### **大小写转换:** - -26.strtolower(): 字符串转为小写 -```php - echo strtolower("Hello WORLD!"); -``` -目标字符串 -小写字符串 - -27.strtoupper(): 字符串转为大写 -```php - echo strtoupper("Hello WORLD!"); -``` -输出: 大写字符串 - -28.ucfirst(): 字符串首字母大写 -```php - echo ucfirst("hello world"); // Hello world -``` -29.ucwords(): 字符串每个单词首字符转为大写 -```php - echo ucwords("hello world"); // Hello World -``` -### **html标签关联:** - -30.htmlentities(): 把字符转为HTML实体 -```php - $str = "John & 'Adams'"; -echo htmlentities($str, ENT_COMPAT); // John & 'Adams' -``` -31.htmlspecialchars(): 预定义字符转html编码 - -32.nl2br(): \n转义为`
`标签 -```php - echo nl2br("One line.\nAnother line."); -``` -输出: 处理后的字符串 - -33.strip_tags(): 剥去 HTML、XML 以及 PHP 的标签 -```php - echo strip_tags("Hello world!");   -``` -34.addcslashes():在指定的字符前添加反斜线转义字符串中字符 -```php - $str = "Hello, my name is John Adams."; - echo $str; - echo addcslashes($str,'m'); -``` -*输入:* -目标字符串|指定的特定字符或字符范围 - -35.stripcslashes(): 删除由addcslashes()添加的反斜线 -```php - echo stripcslashes("Hello, \my na\me is Kai Ji\m."); - // 目标字符串 Hello, my name is Kai Jim. -``` -36.addslashes(): 指定预定义字符前添加反斜线 -```php - $str = "Who's John Adams?"; -echo addslashes($str); -``` -输出: 把目标串中的' " \和null进行转义处理 - -37.stripslashes(): 删除由addslashes()添加的转义字符 -```php - echo stripslashes("Who\'s John Adams?"); // 清除转义符号Who's John Adams? -``` -38.quotemeta(): 在字符串中某些预定义的字符前添加反斜线 -```php - $str = "Hello world. (can you hear me?)"; -echo quotemeta($str); - // Hello world\. \(can you hear me\?\) -``` -39.chr(): 从指定的 ASCII 值返回字符 -```php - echo chr(052); // ASCII 值返回对应的字符 -``` -40.ord(): 返回字符串第一个字符的ASCII值 -```php - echo ord("hello"); 字符串第一个字符的 ASCII 值 -``` -### **字符串比较:** - -41.strcasecmp(): 不区分大小写比较两字符串 -```php - echo strcasecmp("Hello world!","HELLO WORLD!"); -``` -*输入:* -两个目标字符串 -*输出:* -大1|等0|小 -1 - -42.strcmp(): 区分大小写比较两字符串 - -43.strncmp(): 比较字符串前n个字符,区分大小写 - -调用: `int strncmp ( string $str1 , string $str2 , int $len)` -  -44.strncasecmp(): 比较字符串前n个字符,不区分大小写 - -调用: `int strncasecmp ( string $str1 , string $str2 , int $len )` - -45.strnatcmp(): 自然顺序法比较字符串长度,区分大小写 - -调用: `int strnatcmp ( string $str1 , string $str2 )` - -*输入:* -目标字符串  - -46.strnatcasecmp(): 自然顺序法比较字符串长度, 不区分大小写 - -调用: `int strnatcasecmp ( string $str1 , string $str2 )` - -字符串切割与拼接: - -47.chunk_split():将字符串分成小块 - -调用: `str chunk_split(str $body[,int $len[,str $end]]) ` - -*输入:* -`$body`目标字串, `$len`长度, `$str`插入结束符 -*输出:* -分割后的字符串 - -48.strtok(): 切开字符串 - -调用: `str strtok(str $str,str $token)` - -目标字符串`$str`,以`$token`为标志切割返回切割后的字符串 - -49.explode(): 使用一个字符串为标志分割另一个字符串 - -调用: `array explode(str $sep,str $str[,int $limit])` - -*输入:* `$sep`为分割符,`$str`目标字符串,`$limit`返回数组最多包含元素数 -*输出:* 字符串被分割后形成的数组 - -50.implode(): 同join,将数组值用预订字符连接成字符串 - -调用: `string implode ( string $glue , array $pieces )` - -`$glue`默认, 用''则直接相连 - -51.substr(): 截取字符串 - -调用: `string substr ( string $string , int $start [, int $length ] )` - -**字符串查找替换:** - -52.str_replace(): 字符串替换操作,区分大小写 - -调用`mix str_replace(mix $search,mix $replace, mix $subject[,int &$num])` - -*输入*: -`$search`查找的字符串,`$replace`替换的字符串,`$subject`被查找字串, `&$num` -*输出*: 返回替换后的结果 - -53.str_ireplace() 字符串替换操作,不区分大小写 - -调用: `mix str_ireplace ( mix $search , mix $replace , mix $subject [, int &$count ] )` - -*输入*: -`$search`查找的字符串,`$replace`替换的字符串,`$subject`被查找字串,`&$num` -*输出*: 返回替换后的结果 - -54.substr_count(): 统计一个字符串,在另一个字符串中出现次数 - -调用: `int substr_count ( string $haystack , string $needle[, int $offset = 0 [, int $length ]] )` - -55.substr_replace(): 替换字符串中某串为另一个字符串 - -调用: `mixed substr_replace ( mixed $string, string $replacement,int $start [, int $length ] ) ` - -56.similar_text(): 返回两字符串相同字符的数量 - -调用: `int similar_text(str $str1,str $str2)` -*输入*: -两个比较的字符串 - -*输出*: -整形,相同字符数量 - -57.strrchr(): 返回一个字符串在另一个字符串中最后一次出现位置开始到末尾的字符串 - -调用: `string strrchr ( string $haystack , mixed $needle )` - -58.strstr(): 返回一个字符串在另一个字符串中开始位置到结束的字符串 - -调用: `string strstr ( string $str, string $needle , bool $before_needle )` -   -59.strchr(): strstr()的别名,返回一个字符串在另一个字符串中首次出现的位置开始到末尾的字符串 - -调用: ` string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )` -   -60.stristr(): 返回一个字符串在另一个字符串中开始位置到结束的字符串,不区分大小写 - -调用:` string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )` - -61.strtr(): 转换字符串中的某些字符 - -调用: `string strtr ( string $str , string $from , string $to )` - -62.strpos(): 寻找字符串中某字符最先出现的位置 - -调用: `int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )` - -63.stripos(): 寻找字符串中某字符最先出现的位置,不区分大小写 -调用: `int stripos ( string $haystack , string $needle [, int $offset ] )` - -64.strrpos(): 寻找某字符串中某字符最后出现的位置 - -调用: ` int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )` - -65.strripos(): 寻找某字符串中某字符最后出现的位置,不区分大小写 - -调用: ` int strripos ( string $haystack , string $needle [, int $offset ] )` - -66.strspn(): 返回字符串中首次符合mask的子字符串长度 -调用: ` int strspn ( string $str1 , string $str2 [, int $start [, int $length ]] )` - -67.strcspn(): 返回字符串中不符合mask的字符串的长度 - -调用: `int strcspn ( string $str1 , string $str2 [, int $start [, int $length ]] )` - -*输入*: -`$str1`被查询,`$str2`查询字符串,`$start`开始查询的字符,`$length`是查询长度 -*输出*: -返回从开始到第几个字符 - -### **字符串统计:** - -68.str_word_count(): 统计字符串含有的单词数 - -调用: `mix str_word_count(str $str,[])` - -输入: 目标字符串 -输出: 统计处的数量 - -69.strlen(): 统计字符串长度int strlen(str $str) - -输入: 目标字符串 -输出:整型长度 - -70.count_chars(): 统计字符串中所有字母出现次数(0..255) -调用: ` mixed count_chars ( string $string [, int $mode ] )` - - -### **字符串编码:** - -71.md5(): 字符串md5编码 - - $str = "Hello"; -echo md5($str); - -## 数组函数 - -数组创建: - -72.array(): 生成一个数组 -```php - $a=array("Dog","Cat","Horse"); - print_r($a); -``` -数组值或,键=>值一个数组型变量 - -73.array_combine(): 生成一个数组,用一个数组的值 -作为键名,另一个数组值作为值 -```php - $a1=array("a","b","c","d"); - $a2=array("Cat","Dog","Horse","Cow"); - print_r(array_combine($a1,$a2)); -``` -`$a1`为提供键,`$a2`提供值合成后的数组 -74.range(): 创建并返回一个包含指定范围的元素的数组。 -```php - $number = range(0,50,10); - print_r ($number); -``` -输入: 0是最小值,50是最大值,10是步长 -输出: 合成后的数组 - -75.compact(): 创建一个由参数所带变量组成的数组 -```php - $firstname = "Peter"; - $lastname = "Griffin"; - $age = "38"; - $result = compact("firstname", "lastname", - "age"); - print_r($result); -``` -### 变量或数组 -返回由变量名为键,变量值为值的数组,变量也可以为多维数组.会递归处理 -76.array_fill(): 用给定的填充(值生成)数组 -```php - $a=array_fill(2,3,"Dog"); - print_r($a); -``` -2是键,3是填充的数量,'Dog'为填充内容返回完成的数组 - -### **数组合并和拆分:**     -77.array_chunk(): 把一个数组分割为新的数组块 -```php - $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); -print_r(array_chunk($a,2)); -``` -一个数组分割后的多维数组,规定每个新数组包含2个元素 - -78.array_merge(): 把两个或多个数组合并为一个数组。 -```php - $a1=array("a"=>"Horse","b"=>"Dog"); - $a2=array("c"=>"Cow","b"=>"Cat"); - print_r(array_merge($a1,$a2)); -``` -输入: 两个数组 -输出: 返回完成后的数组 - -79.array_slice(): 在数组中根据条件取出一段值,并返回。 -```php - $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); -print_r(array_slice($a,1,2)); -``` -输入: 一个数组 -输出: 1为从'Cat'开始,2为返回两个元素 - -### 数组比较: - -80.array_diff(): 返回两个数组的差集数组 -```php - $a1=array(0=>"Cat",1=>"Dog",2=>"Horse"); -$a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); - print_r(array_diff($a1,$a2)); //返回'Cat' -``` -输入: 两个或多个数组 -输出: `$a1`与`$a2`的不同之处 - -81.array_intersect(): 返回两个或多个数组的交集数组 -输出: -返回'Dog'和'Horse',$a1与$a2的相同之处 - -### 数组查找替换:      -82.array_search(): 在数组中查找一个值,返回一个键,没有返回返回假 -```php - $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); - echo array_search("Dog",$a); -``` -输入: 一个数组 -输出: 成功返回键名,失败返回false - -83.array_splice(): 把数组中一部分删除用其他值替代 -```php - $a1=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); - $a2=array(0=>"Tiger",1=>"Lion"); - array_splice($a1,0,2,$a2); - print_r($a1); -``` -输入: 一个或多个数组 -输出: `$a1`被移除的部分由`$a2`补全 - -84.array_sum(): 返回数组中所有值的总和 -```php - $a=array(0=>"5",1=>"15",2=>"25"); - echo array_sum($a); -``` -输入: 一个数组 -输出: 返回和 - -85.in_array(): 在数组中搜索给定的值,区分大小写 -```php - $people = array("Peter", "Joe", "Glenn", "Cleveland"); - if (in_array("Glenn",$people) { - echo "Match found"; - } - else{ - echo "Match not found"; - } -``` -输入: 需要搜索的值|数组 -输出: true/false - -86.array_key_exists(): 判断某个数组中是否存在指定的 key - -输入: 需要搜索的键名|数组 - -### 数组指针操作: - -87.key(): 返回数组内部指针当前指向元素的键名 -    -88.current(): 返回数组中的当前元素(单元). -    -89.next(): 把指向当前元素的指针移动到下一个元素的位置,并返回当前元素的值 -    -90.prev(): 把指向当前元素的指针移动到上一个元素的位置,并返回当前元素的值 -    -91.end(): 将数组内部指针指向最后一个元素,并返回该元素的值(如果成功) -    -92.reset(): 把数组的内部指针指向第一个元素,并返回这个元素的值 -    -93.list(): 用数组中的元素为一组变量赋值 -```php - $my_array=array("Dog","Cat","Horse"); - list($a, $b, $c) = $my_array; -``` -输入: `$a`, `$b`, `$c`为需要赋值的变量 -输出: 变量分别匹配数组中的值 - -94.array_shift(): 删除数组中的第一个元素,并返回被删除元素的值 -```php - $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); - echo array_shift($a); - print_r ($a); -``` -95.array_unshift(): 在数组开头插入一个或多个元素 - -```php - $a=array("a"=>"Cat","b"=>"Dog"); - array_unshift($a,"Horse"); - print_r($a); -``` - -96.array_push(): 向数组最后压入一个或多个元素 -```php -$a=array("Dog","Cat"); -array_push($a,"Horse","Bird"); -print_r($a); -``` - -输入: 目标数组|需要压入的值 -返回值: 返回新的数组 - -97.array_pop(): 取得(删除)数组中的最后一个元素 -```php - $a=array("Dog","Cat","Horse"); - array_pop($a); - print_r($a); -``` -输入: `$a`为目标数组 -输出: 返回数组剩余元素 - -### **数组键值操作:**      -98.shuffle(): 将数组打乱,保留键名 -```php - $my_array = array("a" => "Dog", "b" => "Cat"); - shuffle($my_array); - print_r($my_array); -``` -输入: 一个或多个数组 -输出: 顺序打乱后的数组 - -99.count(): 计算数组中的单元数目或对象中的属性个数 -```php - $people = array("Peter", "Joe", "Glenn", - "Cleveland"); - $result = count($people); - echo $result; -``` -输入: 数组 -输出: 输出元素个数 - -100.array_flip(): 返回一个键值反转后的数组 -```php - $a=array(0=>"Dog",1=>"Cat",2=>"Horse"); -print_r(array_flip($a)); -``` -输出: 返回完成后的数组 -101.array_keys(): 返回数组所有的键,组成一个数组 -```php - $a=array("a"=>"Horse","b"=>"Cat","c"=>"Dog"); - print_r(array_keys($a)); -``` -输出: 返回由键名组成的数组 - -102.array_values(): 返回数组中所有值,组成一个数组 - -输出: 返回由键值组成的数组 - -103.array_reverse(): 返回一个元素顺序相反的数组 -元素顺序相反的一个数组,键名和键值依然匹配 - -104.array_count_values(): 统计数组中所有的值出现的次数 -```php - $a=array("Cat","Dog","Horse","Dog"); - print_r(array_count_values($a)); -``` -输出: 返回数组原键值为新键名,次数为新键值 - -105.array_rand(): 从数组中随机抽取一个或多个元素,注意是键名!!! -```php - $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); - print_r(array_rand($a,1)); -``` -`$a`为目标数组, 1为抽取第几个元素的键名返回第1个元素的键名b - -106.each(): 返回数组中当前的键/值对并将数组指针向前移动一步 -调用`array each ( array &$array )` - -在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()。 - -返回值: -数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为0,1,key和 value。单元 0 和 key 包含有数组单元的键名,1 和 value 包含有数据。 -如果内部指针越过了数组的末端,则 each() 返回 FALSE。 - -107.array_unique(): 删除重复值,返回剩余数组 -```php - $a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat"); - print_r(array_unique($a)); -``` -输入: 数组 -输入: 返回无重复值数组,键名不变 - -### **数组排序:**    -108.sort(): 按升序对给定数组的值排序,不保留键名 -```php - $my_array = array("a" => "Dog", "b" => "Cat", - "c" => "Horse"); - sort($my_array); - print_r($my_array); -``` -输出: true/false -  -109.rsort(): 对数组逆向排序,不保留键名   -110.asort(): 对数组排序,保持索引关系    -111.arsort(): 对数组逆向排序,保持索引关  -112.ksort(): 系按键名对数组排序  -113.krsort(): 将数组按照键逆向排序 -114.natsort(): 用自然顺序算法对数组中的元素排序     -115.natcasesort(): 自然排序,不区分大小写    -   - -## 文件系统函数 - -116.fopen(): 打开文件或者 URL -```php - $handle = fopen("ftp://user:password@example.com/somefile.txt", "w"); -``` - -调用: `resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] )` - -返回值: 如果打开失败,本函数返回 FALSE - -117.fclose(): 关闭一个已打开的文件指针 -```php - $handle = fopen('somefile.txt', 'r'); - fclose($handle); - bool fclose(resource handle) -``` -输出: 如果成功则返回 TRUE,失败则返回 FALSE - -### **文件属性** - -118.file_exists(): 检查文件或目录是否存在 -```php - $filename = '/path/to/foo.txt'; - if (file_exists($filename)) { - echo "exists"; - } else { - echo "does not exist"; - } -``` -调用: `bool file_exists ( string filename )` -输入: 指定的文件或目录 -输出: 存在则返回 TRUE,否则返回 FALSE - -119.filesize(): 取得文件大小 -```php - $filename = 'somefile.txt'; -echo $filename . ': ' . filesize($filename) .'bytes'; -``` -调用: `int filesize ( string $filename )` - -输出: 返回文件大小的字节数,如果出错返回 FALSE 并生成一条 E_WARNING 级的错误 - -120.is_readable(): 判断给定文件是否可读 -```php - $filename = 'test.txt'; - if (is_readable($filename)) { - echo '可读'; - } else { - echo '不可读'; - } -``` -调用: `bool is_readable ( string $filename )` -输出: 如果由 filename指定的文件或目录存在并且可读则返回 TRUE - -121.is_writable(): 判断给定文件是否可写 -```php - $filename = 'test.txt'; - if (is_writable($filename)) { - echo '可写'; - } else { - echo '不可写'; - } -``` -调用: bool is_writable ( string $filename ) -filename 参数 可以是一个允许进行是否可写检查的目录名 - -输出: -如果文件存在并且可写则返回 TRUE。 - -122.is_executable(): 判断给定文件是否可执行 -```php - $file = 'setup.exe'; - if (is_executable($file)) { - echo '可执行'; - } else { - echo '不可执行'; - } -``` -调用: `bool is_executable ( string $filename )` -输出: 如果文件存在且可执行则返回 TRUE - -123.filectime(): 获取文件的创建时间 -```php - $filename = 'somefile.txt'; -echo filectime($filename); -``` -调用: `int filectime ( string $filename )` -输出: 时间以 Unix 时间戳的方式返回,如果出错则返回FALSE - -124.filemtime(): 获取文件的修改时间 -```php - $filename = 'somefile.txt'; -echo filemtime($filename); - int filemtime ( string $filename ) -``` -输出: 返回文件上次被修改的时间,出错时返回 FALSE。时间以 Unix时间戳的方式返回 - -125.fileatime(): 获取文件的上次访问时间 -```php - $filename = 'somefile.txt'; -echo fileatime($filename); -``` -调用: `int fileatime (string $filename)` - -输出: 返回文件上次被访问的时间, 如果出错则返回FALSE. 时间以Unix时间戳的方式返回. - -126.stat(): 获取文件大部分属性值 -```php - $filename = 'somefile.txt'; -var_dump(fileatime($filename)); -``` -调用: array stat (string $filename -输出: 返回由 filename 指定的文件的统计信息 - -### **文件操作** - -127.fwrite(): 写入文件 -```php - $filename = 'test.txt'; - $somecontent = "添加这些文字到文件\n"; - $handle = fopen($filename, 'a'); - fwrite($handle, $somecontent); - fclose($handle); -``` -调用: `int fwrite ( resource handle, string string [, int length] )` - -输出: -把 string 的内容写入 文件指针 handle 处。如果指定了 length,当写入了length个字节或者写完了string以后,写入就会停止, 视乎先碰到哪种情况 - -128.fputs(): 同上  -   -129.fread(): 读取文件 -```php - $filename = "/usr/local/something.txt"; -$handle = fopen($filename, "r"); -$contents = fread($handle, filesize($filename)); - fclose($handle); -``` -调用: `string fread ( int handle, int length )` -从文件指针handle,读取最多 length 个字节 - -130.feof(): 检测文件指针是否到了文件结束的位置 -```php - $file = @fopen("no_such_file", "r"); - while (!feof($file)) { - } - fclose($file); -``` -调用: bool feof ( resource handle ) -输出: 如果文件指针到了 EOF 或者出错时则返回TRUE,否则返回一个错误(包括 socket 超时),其它情况则返回 FALSE - -131.fgets(): 从文件指针中读取一行 -```php - $handle = @fopen("/tmp/inputfile.txt", "r"); - if ($handle) { - while (!feof($handle)) { - $buffer = fgets($handle, 4096); - echo $buffer; - } - fclose($handle); - } -``` -调用: `string fgets ( int handle [, int length] )` -输出: 从handle指向的文件中读取一行并返回长度最多为length-1字节的字符串.碰到换行符(包括在返回值中)、EOF 或者已经读取了length -1字节后停止(看先碰到那一种情况). 如果没有指定 length,则默认为1K, 或者说 1024 字节. - -132.fgetc(): 从文件指针中读取字符 -```php - $fp = fopen('somefile.txt', 'r'); - if (!$fp) { - echo 'Could not open file somefile.txt'; - } - while (false !== ($char = fgetc($fp))) { - echo "$char\n"; - } -``` -输入: `string fgetc ( resource $handle )` -输出: 返回一个包含有一个字符的字符串,该字符从 handle指向的文件中得到. 碰到 EOF 则返回 FALSE. - -133.file(): 把整个文件读入一个数组中 -```php - $lines = file('http://www.example.com/'); -``` -// 在数组中循环,显示 HTML 的源文件并加上行号。 -```php - foreach ($lines as $line_num => $line) { - echo "Line #{$line_num} : " . - htmlspecialchars($line) . "
\n"; - } -``` -// 另一个例子将 web 页面读入字符串。参见 `file_get_contents()`。 -```php - $html = implode('', file('http://www.example.com/')); -``` -调用: `array file ( string $filename [, int $use_include_path [, resource $context ]] )` - -输出: 数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败 file() 返回 FALSE - -134.readfile(): 输出一个文件  -调用: `int readfile ( string $filename [, bool $use_include_path [, resource $context ]] )` - -输出: 读入一个文件并写入到输出缓冲。返回从文件中读入的字节数。如果出错返回 FALSE - -135.file_get_contents(): 将整个文件读入一个字符串 -```php - echo file_get_contents('http://www.baidu.com/'); -``` -调用: -`string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )` -  -136.file_put_contents():将一个字符串写入文件 -```php - file_put_contents('1.txt','aa'); -``` -调用: `int file_put_contents ( string $filename , string $data [, int $flags [, resource $context ]] )` - -输出: 该函数将返回写入到文件内数据的字节数 - -137.ftell(): 返回文件指针读/写的位置 -```php - $fp=fopen('tx.txt','r'); - fseek($fp,10); - echo ftell($fp); - fread($fp,4); - echo ftell($fp); -``` -调用: `int ftell ( resource $handle )` -输出: 返回由 handle 指定的文件指针的位置,也就是文件流中的偏移量 - -138.fseek(): 在文件指针中定位 -```php - $fp=fopen('tx.txt','r'); - fseek($fp,10); - echo ftell($fp); - fread($fp,4); - echo ftell($fp); -``` -调用: `int fseek ( resource $handle , int $offset [, int $whence ] )` -输出: 成功则返回 0;否则返回 -1 - -139.rewind(): 倒回文件指针的位置 -```php - $fp=fopen('tx.txt','r'); - fseek($fp,3); - echo ftell($fp); - fread($fp,4); - rewind($fp); - echo ftell($fp); -``` -调用: `bool rewind ( resource $handle )` -返回值: 如果成功则返回 TRUE,失败则返回 FALSE - -140.flock(): 轻便的执行文件锁定 -```php - $fp=fopen('tx.txt','r'); - flock($fp, LOCK_SH);//共享锁 - //flock($fp, LOCK_EX);//独立锁,写文件时用它打开 - //flock($fp, LOCK_NB);//附加锁 - flock($fp, LOCK_UN);//释放锁 - fclose($fp); -``` -调用: `bool flock ( int $handle , int $operation [, int &$wouldblock ] )` -输出: 如果成功则返回 TRUE,失败则返回 FALSE - -### **目录** -141.basename(): 返回路径中的文件名部分 -```php - path = "/home/httpd/html/index.php"; - $file = basename($path); - $file = basename($path,".php"); -``` -调用: `string basename ( string $path [, string $suffix ])` -输出: 给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结 -束的,那这一部分也会被去掉 - -142.dirname(): 返回路径中的目录部分 -```php - $path = "/etc/passwd"; - $file = dirname($path); -``` -调用: `string dirname ( string $path )` -输出: 给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名 - -143.pathinfo(): 返回文件路径的信息 -```php - echo '
';
-    print_r(pathinfo("/www/htdocs/index.html"));
-    echo '
'; -``` -调用: `mixed pathinfo ( string $path [, int $options ] )` -返回一个关联数组包含有 path 的信息 - -144.opendir(): 打开目录句柄 -```php -$fp=opendir('E:/xampp/htdocs/php/study/19'); -echo readdir($fp); -closedir($fp); -``` -调用: `resource opendir ( string $path [, resource $context ] )` -返回值: 如果成功则返回目录句柄的 resource,失败则返回FALSE - -145.readdir(): 从目录句柄中读取条目 -```php -$fp=opendir('E:/xampp/htdocs/php/study/19'); -echo readdir($fp); -closedir($fp); -``` -调用: `string readdir ( resource $dir_handle )` -返回值: 返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回 - -146.closedir(): 关闭目录句柄 -```php - $fp=opendir('E:/xampp/htdocs/php/study/19'); - echo readdir($fp); - closedir($fp); -``` -调用: `void closedir ( resource $dir_handle )` -关闭由 dir_handle 指定的目录流。流必须之前被opendir() 所打开 -147.rewinddir() : 倒回目录句柄 -```php - $fp=opendir('E:/xampp/htdocs/php/study/19'); - echo readdir($fp).'
'; - echo readdir($fp).'
'; - echo readdir($fp).'
'; - rewinddir($fp); - echo readdir($fp).'
'; - closedir($fp); -``` -调用: `void rewinddir ( resource $dir_handle )` -输出: 将 dir_handle 指定的目录流重置到目录的开头 -148.mkdir(): 新建目录 -```php - mkdir('123'); -``` -调用: `bool mkdir ( string $pathname [, int $mode [, bool $recursive [, resource $context ]]] )` -输出: 尝试新建一个由 pathname 指定的目录 - -149.rmdir(): 删除目录 -```php - rmdir('123'); -``` -调用: `bool rmdir ( string $dirname )` -输出: 尝试删除 dirname 所指定的目录。目录必须是空的,而且要有相应的权限。如果成功则返回TRUE,失败则返回 FALSE - -150.unlink(): 删除文件 -```php - unlink('123/1.txt'); - rmdir('123'); -``` -调用: `bool unlink ( string $filename )` -输出: 删除 filename 。和 Unix C 的 unlink() 函数相似。如果成功则返回 TRUE,失败则返回 FALSE - -151.copy(): 拷贝文件 -```php - copy('index.php','index.php.bak'); -``` -调用: `bool copy ( string $source , string $dest )` -输出: 将文件从 source 拷贝到 dest. 如果成功则返回TRUE,失败则返回 FALSE - -152.rename(): 重命名一个文件或目录 -```php - rename('tx.txt','txt.txt'); -``` -调用: `bool rename ( string $oldname , string $newname [, resource $context ] )` -输出: 如果成功则返回 TRUE,失败则返回 FALSE - -### **文件的上传与下载** - -153.is_uploaded_file():判断文件是否是通过 HTTP POST上传的 -```php - if(is_uploaded_file($_FILES['bus']['tmp_name'])){ - if( move_uploaded_file($_FILES['bus']['tmp_name'], - $NewPath) ){ - echo '上传成功
'; - }else{ - exit('失败'); - } - }else{ - exit('不是上传文件'); - } -``` -调用: `bool is_uploaded_file ( string $filename )`   - -154.move_uploaded_file(): 将上传的文件移动到新位置 -```php - if(is_uploaded_file($_FILES['bus']['tmp_name'])){ - if( move_uploaded_file($_FILES['bus']['tmp_name'], - $NewPath) ){ - echo '上传成功
'; - }else{ - exit('失败'); - } - }else{ - exit('不是上传文件'); - } -``` -调用: `bool move_uploaded_file ( string $filename , string` - -## 时间函数 - -155.time(): 返回当前的 Unix 时间戳time(); -调用: `int time ( void )` -输出: 返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数 - -156.mktime(): 取得一个日期的 Unix 时间戳 -```php - mktime(0, 0, 0, 4, 25, 2012); -``` -调用: `int mktime ([ int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year [, int $is_dst ]]]]]]] )` -  -156.date(): 格式化一个本地时间/日期 -```php -date('Y年m月d日 H:i:s'); -``` -调用: `string date ( string $format [, int $timestamp ] )` - -输出: 2016年09月10日 20:45:54 - -157.checkdate(): 验证一个格里高里日期 -调用: `bool checkdate ( int $month , int $day , int $year)` -输出: 如果给出的日期有效则返回 TRUE,否则返回 FALSE -```php - if(checkdate(6,31,2012)){ - echo '成立'; - }else{ - echo '不成立'; - } -``` -158.date_default_timezone_set(): 设定用于一个脚本中所有日期时间函数的默认时区 -```php - date_default_timezone_set('PRC'); -``` -调用: `bool date_default_timezone_set ( string $timezone_identifier)` - -返回值: 如果 timezone_identifier 参数无效则返回 FALSE,否则返回 TRUE。 - -159.getdate(): 取得日期/时间信息 -调用: `array getdate ([ int $timestamp ] )` - -输出: 返回一个根据timestamp得出的包含有日期信息的关联数组。如果没有给出时间戳则认为是当前本地时间 -```php - $t=getdate(); - var_dump($t); -``` - -160.strtotime(): 将任何英文文本的日期时间描述解析为 Unix 时间戳 -```php - echo strtotime("now"); - int strtotime ( string $time [, int $now ] )   - echo strtotime("10 September 2000"); - echo strtotime("+1 day"); - echo strtotime("+1 week"); - echo strtotime("+1 week 2 days 4 hours 2 seconds"); - echo strtotime("next Thursday"); - echo strtotime("last Monday"); -``` -161.microtime(): 返回当前 Unix 时间戳和微秒数 -调用: `mixed microtime ([ bool $get_as_float ] )` -```php - $start=microtime(true); - sleep(3); - $stop=microtime(true); - echo $stop-$start; -``` -其他常用: - -162.intval(): 获取变量的整数值 -调用: `int intval ( mixed $var [, int $base = 10 ] )` -通过使用指定的进制 base 转换(默认是十进制),返回变量 var 的 integer 数值。 intval() 不能用于 object,否则会产生 E_NOTICE 错误并返回 1。 - -var: 要转换成 integer 的数量值 - -base: 转化所使用的进制 - -返回值: 成功时返回 var 的 integer 值,失败时返回 0。 空的 array 返回 0,非空的 array 返回 1。 - -163. PDO类的相关函数 -prepare() -execute() -fetch() - -```php -Database CODINGGROUND Connected

"; -}catch(PDOException $e){ - echo "

" . $e->getMessage() . "

"; -} -$sql = 'SELECT * FROM users'; -$stmt = $conn->prepare($sql); -$stmt->execute(); - -echo ""; -while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ - echo ""; - foreach($row as $value) - { - echo sprintf("", $value); - } - echo ""; -} -echo "
%s
"; -?> -``` - -## 正则表达式-元字符 - -**元字符及其匹配范围** - -`\d` 匹配任意一个十进制数字,等价于: `[0-9]` -`\D` 匹配除十进制数字以外的任意数字,等价于: `[^0-9]` -`\s`:匹配空白字符,等价于: `[\n\f\r\t\v]` -`\S`: 匹配除空白字符以外的任意一个字符, 等价于`[^\n\f\r\t\v]` - -`\w` 匹配任意一个数字、字母和下划线,等价于: `[0-9a-zA-Z_]` -`\W` 匹配除字母、数字和下划线以外的任意字符, 等价于: `[^0-9a-zA-Z_]` -`[]` 1)用来表示范围。2)匹配任意一个中括号中定义的原子 -  -`[^]`: 中括号里面的^(抑扬符):表示匹配任意一个除中括号里面定义的原子 - -#### **限定次数** - -`*` 匹配0次、1次或多次其前的原子, 等价于: `{0,}` -`+` 匹配1次或多次其前的原子, 等价于: `{1,}` -`?` 匹配0次或1次其前的原子, 等价于: `{0,1}` -`{n}` 表示其前的原子正好出现n次, 等价于: `{n,}` -表示其前的原子至少出现n次,最多不限制 -  -`{m,n}` 表示其前的原子最少出现m次,最多出现n次 -  -#### **其它** -`.` 匹配除换行符(\n)以外的任意字符【windows下还匹配`\f\r`】  -`|` 两个或多个分支选择【优先级最低】 -`^` 匹配输入字符的开始位置  -`$` 匹配输入字符的结束位置  -`\b` 匹配词边界  -`\B` 匹配非词边界  -`()` 1)模式单元,把多个小原子组成一个大原子。2)可以改变优先级 \ No newline at end of file diff --git a/README.md b/README.md index 3a886958..1e81d48c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,145 @@ -# 算法刷题与练习 -LeetCodeOJ - Solutions +# 玩转力扣 | LeetCode原创题解 + + 仓库[**leetcode-ac**](https://github.com/yanglr/leetcode-ac)提供LeetCode中文题大全、LeetCode**清晰易懂的代码**(含多种语言: C++/Java/C#/Python/Go) 及详细题解, 并将**持续不断更新**, 助你早日斩获大厂Offer! + +如果想第一时间收到最新更新, 还请点个star/fork 或 watch, 如果有不错的解法也欢迎提PR~ + +如果在本项目中发现问题, 欢迎给我提issue喔, 看到后会立刻回复的~ + +
+ + +## 📢我们的slogan + +本仓库[**leetcode-ac**](https://github.com/yanglr/leetcode-ac)的口号是: AC一时爽, 一直AC一直爽。 + +欢迎关注本项目的同名公众号 **「玩转力扣」**,极客学长带你 **轻松刷 LeetCode**! + + + +
+ +**ps**: 所有题解的代码将第一时间在本仓库更新, 而所有题解将第一时间在公众号 **「玩转力扣」** 更新! + +
+ +## 🍖仓库食用指南 + +**1、先给本仓库点个 star,满足一下我的虚荣心**,题解质量绝对值你一个 star。我还在继续创作,给我一点继续写文的动力,感谢。 + + +**2、建议关注我的公众号「大白技术控」,坚持高质量的文章输出。** + + +**3、建议收藏我的在线网站,每篇文章开头都有对应的力扣题目链接,可以边看文章边刷题**: + +在线阅读 地址: + + +**4、欢迎关注 [我的知乎](https://www.zhihu.com/people/legege007)**。 + +
+ +## 🔧 代码快速查找 + +为方便大家迅速找到代码, 本仓库提供了如下功能: + +在此页面找到"Go to File", 然后输入"leetcode+题目编号"(leetcode后面跟上编号, 中间这个"+"不需要, 中间也不要输入空格), 比如: `leetcode65`, 效果如下: + +![代码快速查找-玩转力扣](https://github.com/yanglr/leetcode-ac/blob/master/assets/images/leetcode-code-quick-find.gif?raw=true "代码快速查找-玩转力扣-极客学长") + +## 🚀 题解进度表 + +题解进度表包含题解传送门、AC状态、代码传送门等信息。 + +详情请看: [题解进度表](https://github.com/yanglr/leetcode-ac/blob/master/leetcode-ac-tracking.md) + + +
+ +## 已完成的题解列表 + +[轻松刷Leetcode系列 - 如何使用 VS code 的 Leetcode 插件刷题](https://zhuanlan.zhihu.com/p/85142574) + +[轻松刷LeetCode系列 - Leetcode9.回文数 Python版](https://geekplayers.com/python-leetcode9-palindrome-number.html) + +[轻松刷LeetCode系列 - Leetcode13.罗马数字转整数 Python版](https://geekplayers.com/python-leetcode13-roman-to-integer.html) + +[轻松刷Leetcode系列 - LeetCode38.外观数列(报数) C#版](https://zhuanlan.zhihu.com/p/86412518) + +[轻松刷LeetCode系列 - Leetcode58.最后一个单词的长度 Python版](https://geekplayers.com/python-leetcode58-length-of-last-word.html) + +[轻松刷LeetCode系列 - LeetCode67.二进制数求和 Python版](https://geekplayers.com/python-leetcode67-add-binary.html) + +[轻松刷LeetCode系列 - Leetcode89.格雷码 Python版](https://geekplayers.com/python-leetcode89-gary-code.html) + +[轻松刷LeetCode系列 - LeetCode136.只出现一次的数 Python版](https://geekplayers.com/python-leetcode136-single-number.html) + +[轻松刷Leetcode系列 - Leetcode191.位1的个数 Python版](https://zhuanlan.zhihu.com/p/82539155) + +[轻松刷LeetCode系列 - LeetCode202.快乐数 Python版](https://geekplayers.com/python-leetcode202-happy-number.html) + +[轻松刷LeetCode系列 - LeetCode204.统计质数 Python版](https://geekplayers.com/python-leetcode204-count-primes.html) + +[轻松刷LeetCode系列 - LeetCode345.反转字符串中的元音字母 Python版](https://geekplayers.com/leetcode345-reverse-vowels-of-a-string.html) + +[轻松刷Leetcode系列 - LeetCode593.有效的正方形 C#版](https://zhuanlan.zhihu.com/p/89105960) + +[轻松刷Leetcode系列 - LeetCode633.平方数之和 C#版](https://zhuanlan.zhihu.com/p/87986301) + +[轻松刷LeetCode系列 - LeetCode645.错误的集合 Python版](https://geekplayers.com/python-leetcode645-set-mismatch.html) + +[轻松刷Leetcode系列 - leetcode728.自除数 C#版](https://zhuanlan.zhihu.com/p/86695886) + +[轻松刷LeetCode系列 - LeetCode976.三角形的最大周长 Python版](https://geekplayers.com/leetcode976-largest-perimeter-triangle.html) + +[轻松刷LeetCode系列 - LeetCode977.有序数组的平方 Python版](https://geekplayers.com/python-leetcode977-squares-of-a-sorted-array.html) + + + +
+ +## 各语言代码所在位置 + +### C++代码: +[cpp-leetcode](https://github.com/yanglr/leetcode-ac/tree/master/cpp-leetcode) + + +### C#代码: +[csharp-leetcode](https://github.com/yanglr/leetcode-ac/tree/master/csharp-leetcode) + + +### Python代码: +[python3-leetcode](https://github.com/yanglr/leetcode-ac/tree/master/python3-leetcode) + + + +### Java代码: + +intelliJ idea 版: +[java-leetcode Idea](https://github.com/yanglr/leetcode-ac/tree/master/java-leetcode_intelliJ_idea) + +VS code 版: +[java-leetcode vscode](https://github.com/yanglr/leetcode-ac/tree/master/java-leetcode_vscode) + + +### Golang代码: +[go-leetcode](https://github.com/yanglr/leetcode-ac/tree/master/go-leetcode) + +
+ +## LeetCode中文题大全 + +[leetcode中文题1-400](https://github.com/yanglr/leetcode-ac/tree/master/中文题1-2000/leetcode1-400) + +[leetcode中文题401-2000](https://github.com/yanglr/leetcode-ac/tree/master/中文题1-2000/leetcode401-2000) + +
+ +## 关于作者 + +知乎 [极客学长Bravo](https://www.zhihu.com/people/legege007), 4.5万读者。 + +B站 [极客学长呀](https://space.bilibili.com/1443957), 后续会用视频的形式来带大家刷LeetCode题,欢迎点个关注,敬请期待~ + +本人的个人独立网站: [极客中心](https://www.geekzl.com) diff --git a/SUMMARY.md b/SUMMARY.md new file mode 100644 index 00000000..abf83b61 --- /dev/null +++ b/SUMMARY.md @@ -0,0 +1,8 @@ +# Table of contents + +* [玩转力扣 | 题解主页](README.md) +* [leetcode1 两数之和【简单难度】](posts/leetcode1.md) +* [leetcode4 寻找两个正序数组的中位数【困难难度】](posts/leetcode4.md) +* [leetcode11 盛最多水的容器【中等难度】](posts/leetcode11.md) +* [leetcode36 有效的数独【中等难度】](posts/leetcode36.md) +* [leetcode38 外观数列(报数)【中等难度】](posts/leetcode38.md) diff --git a/Welcome_to_use_CSDN-markdown_Editor.md b/Welcome_to_use_CSDN-markdown_Editor.md deleted file mode 100644 index 4c1c57e4..00000000 --- a/Welcome_to_use_CSDN-markdown_Editor.md +++ /dev/null @@ -1,173 +0,0 @@ -# CSDN-markdown编辑器 使用示例 - -本Markdown编辑器使用[StackEdit][6]修改而来,用它写博客,将会带来全新的体验哦: - -- **Markdown和扩展Markdown简洁的语法** -- **代码块高亮** -- **图片链接和图片上传** -- ***LaTex*数学公式** -- **UML序列图和流程图** -- **离线写博客** -- **导入导出Markdown文件** -- **丰富的快捷键** - -------------------- - -## 快捷键 - - - 加粗 `Ctrl + B` - - 斜体 `Ctrl + I` - - 引用 `Ctrl + Q` - - 插入链接 `Ctrl + L` - - 插入代码 `Ctrl + K` - - 插入图片 `Ctrl + G` - - 提升标题 `Ctrl + H` - - 有序列表 `Ctrl + O` - - 无序列表 `Ctrl + U` - - 横线 `Ctrl + R` - - 撤销 `Ctrl + Z` - - 重做 `Ctrl + Y` - -## Markdown及扩展 - -> Markdown 是一种轻量级标记语言,它允许人们使用易读易写的纯文本格式编写文档,然后转换成格式丰富的HTML页面。 —— [ 维基百科 ] - -使用简单的符号标识不同的标题,将某些文字标记为**粗体**或者*斜体*,创建一个[链接](http://www.csdn.net)等,详细语法参考帮助?。 - -本编辑器支持 **Markdown Extra** ,  扩展了很多好用的功能。具体请参考[Github][2]. - -### 表格 - -**Markdown Extra** 表格语法: - -项目 | 价格 --------- | --- -Computer | $1600 -Phone | $12 -Pipe | $1 - -可以使用冒号来定义对齐方式: - -| 项目 | 价格 | 数量 | -| :-------- | --------:| :--: | -| Computer | 1600 元 | 5 | -| Phone | 12 元 | 12 | -| Pipe | 1 元 | 234 | - -### 定义列表 - -**Markdown Extra** 定义列表语法: -项目1 - -项目2 - -: 定义 A - -: 定义 B - -项目3 - -: 定义 C - -: 定义 D - - > 定义D内容 - -### 代码块 -代码块语法遵循标准markdown代码,例如: -``` python -@requires_authorization -def somefunc(param1='', param2=0): - '''A docstring''' - if param1 > param2: # interesting - print 'Greater' - return (param2 - param1 + 1) or None -class SomeClass: - pass ->>> message = '''interpreter -... prompt''' -``` - -## 自定义字体颜色(github中看不到颜色): -Hello - -## 删除线 -~~Hello~~ - -###脚注 -生成一个脚注[^footnote]. -[^footnote]: 这里是 **脚注** 的 *内容*. - -### 目录 -用 `[TOC]`来生成目录: - -[TOC] - -### 数学公式 -使用MathJax渲染*LaTex* 数学公式,详见[math.stackexchange.com][1]. - - - 行内公式,数学公式为:$\Gamma(n) = (n-1)!\quad\forall n\in\mathbb N$。 - - 块级公式: - - $ x = \dfrac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$ - -更多LaTex语法请参考 [这儿][3]. - -### UML 图: - -可以渲染序列图: - -```sequence -张三->李四: 嘿,小四儿, 写博客了没? -Note right of 李四: 李四愣了一下,说: -李四-->张三: 忙得吐血,哪有时间写。 -``` - -或者流程图: - -```flow -st=>start: 开始 -e=>end: 结束 -op=>operation: 我的操作 -cond=>condition: 确认? - -st->op->cond -cond(yes)->e -cond(no)->op -``` - -- 关于 **序列图** 语法,参考 [这儿][4], -- 关于 **流程图** 语法,参考 [这儿][5]. - -## 离线写博客 - -即使用户在没有网络的情况下,也可以通过本编辑器离线写博客(直接在曾经使用过的浏览器中输入[write.blog.csdn.net/mdeditor](http://write.blog.csdn.net/mdeditor) 即可。**Markdown编辑器**使用浏览器离线存储将内容保存在本地。 - -用户写博客的过程中,内容实时保存在浏览器缓存中,在用户关闭浏览器或者其它异常情况下,内容不会丢失。用户再次打开浏览器时,会显示上次用户正在编辑的没有发表的内容。 - -博客发表后,本地缓存将被删除。  - -用户可以选择 把正在写的博客保存到服务器草稿箱,即使换浏览器或者清除缓存,内容也不会丢失。 - -> **注意:**虽然浏览器存储大部分时候都比较可靠,但为了您的数据安全,在联网后,**请务必及时发表或者保存到服务器草稿箱**。 - -## 浏览器兼容 - - 1. 目前,本编辑器对Chrome浏览器支持最为完整。建议大家使用较新版本的Chrome。 - 2. IE9以下不支持 - 3. IE9, 10, 11中存在以下问题 - 1. 不支持离线功能 - 2. IE9不支持文件导入导出 - 3. IE10不支持拖拽文件导入 - ---------- - -[1]: http://math.stackexchange.com/ -[2]: https://github.com/jmcmanus/pagedown-extra "Pagedown Extra" -[3]: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference -[4]: http://bramp.github.io/js-sequence-diagrams/ -[5]: http://adrai.github.io/flowchart.js/ -[6]: https://github.com/benweet/stackedit - -## 在csdn Markdown模式下的显示效果: - diff --git a/Welcome_to_use_CSDN-markdown_Editor_new.md b/Welcome_to_use_CSDN-markdown_Editor_new.md deleted file mode 100644 index de9c356f..00000000 --- a/Welcome_to_use_CSDN-markdown_Editor_new.md +++ /dev/null @@ -1,268 +0,0 @@ -## CSDN新版Markdown编辑器(Alpha 2.0版) 使用示例 - -**具体更新:** -CSDN新版Markdown编辑器(Alpha 2.0版)使用须知-CSDN论坛 -https://bbs.csdn.net/topics/392449440 - -@[TOC](这里写自定义目录标题) - -# 欢迎使用Markdown编辑器 - -你好! 这是你第一次使用 **Markdown编辑器** 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。 - -## 新的改变 - -我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客: - - 1. **全新的界面设计** ,将会带来全新的写作体验; - 2. 在创作中心设置你喜爱的代码高亮样式,Markdown **将代码片显示选择的高亮样式** 进行展示; - 3. 增加了 **图片拖拽** 功能,你可以将本地的图片直接拖拽到编辑区域直接展示; - 4. 全新的 **KaTeX数学公式** 语法; - 5. 增加了支持**甘特图的mermaid语法[^1]** 功能; - 6. 增加了 **多屏幕编辑** Markdown文章功能; - 7. 增加了 **焦点写作模式、预览模式、简洁写作模式、左右区域同步滚轮设置** 等功能,功能按钮位于编辑区域与预览区域中间; - 8. 增加了 **检查列表** 功能。 -[^1]: [mermaid语法说明](https://mermaidjs.github.io/) - -## 功能快捷键 - -撤销:Ctrl/Command + Z - -重做:Ctrl/Command + Y - -加粗:Ctrl/Command + Shift + B - -斜体:Ctrl/Command + Shift + I - -标题:Ctrl/Command + Shift + H - -删除线:Ctrl/Command + Shift + S - -无序列表:Ctrl/Command + Shift + U - -有序列表:Ctrl/Command + Shift + O - -检查列表:Ctrl/Command + Shift + C - -插入代码:Ctrl/Command + Shift + K - -插入链接:Ctrl/Command + Shift + L - -插入图片:Ctrl/Command + Shift + G - - -## 合理的创建标题,有助于目录的生成 - -直接输入1次#,并按下space后,将生成1级标题。 -输入2次#,并按下space后,将生成2级标题。 -以此类推,我们支持6级标题。有助于使用`TOC`语法后生成一个完美的目录。 - - - -## 如何改变文本的样式 - -*强调文本* _强调文本_ - -**加粗文本** __加粗文本__ - -==标记文本== - -~~删除文本~~ - -> 引用文本 - -H~2~O is是液体。 - -2^10^ 运算结果是 1024. - - - -## 插入链接与图片 - -链接: [link](https://mp.csdn.net). - -图片: ![Alt](https://avatar.csdn.net/7/7/B/1_ralf_hx163com.jpg) - -带尺寸的图片: ![Alt](https://avatar.csdn.net/7/7/B/1_ralf_hx163com.jpg =30x30) - -当然,我们为了让用户更加便捷,我们增加了图片拖拽功能。 - - -## 如何插入一段漂亮的代码片 - -去[博客设置](https://mp.csdn.net/configure)页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 `代码片`. -```javascript -// An highlighted block -var foo = 'bar'; -``` - - -## 生成一个适合你的列表 - -- 项目 - - 项目 - - 项目 - -1. 项目1 -2. 项目2 -3. 项目3 - -- [ ] 计划任务 -- [x] 完成任务 - - -## 创建一个表格 -一个简单的表格是这么创建的: -| 项目 | Value | -| ---- | ----- | -| 电脑 | $1600 | -| 手机 | $12 | -| 导管 | $1 | - -### 设定内容居中、居左、居右 -使用`:---------:`居中 - -使用`:----------`居左 - -使用`----------:`居右 - -| 第一列 | 第二列 | 第三列 | -| :------------: | -------------: | :------------- | -| 第一列文本居中 | 第二列文本居右 | 第三列文本居左 | - - - -### SmartyPants - -SmartyPants将ASCII标点字符转换为“智能”印刷标点HTML实体。例如: - - - -| TYPE |ASCII |HTML -|----------------|-------------------------------|-----------------------------| -|Single backticks|`'Isn't this fun?'` |'Isn't this fun?' | -|Quotes |`"Isn't this fun?"` |"Isn't this fun?" | -|Dashes |`-- is en-dash, --- is em-dash`|-- is en-dash, --- is em-dash| - - - -## 创建一个自定义列表 - -Markdown -: Text-to-HTML conversion tool - -Authors -: John -: Luke - - -## 如何创建一个注脚 - -一个具有注脚的文本。[^2] - -[^2]: 注脚的解释 - - - -## 注释也是必不可少的 - -Markdown将文本转换为 HTML。 - -*[HTML]: 超文本标记语言 - - -## KaTeX数学公式 - -您可以使用渲染LaTeX数学表达式 [KaTeX](https://khan.github.io/KaTeX/): - -Gamma公式展示 $\Gamma(n) = (n-1)!\quad\forall -n\in\mathbb N$ 是通过欧拉积分 - -$$ -\Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. -$$ - -> 你可以找到更多关于的信息 **LaTeX** 数学表达式[here][1]. - - - -## 新的甘特图功能,丰富你的文章 - -```mermaid -gantt - dateFormat YYYY-MM-DD - title Adding GANTT diagram functionality to mermaid - section 现有任务 - 已完成 :done, des1, 2014-01-06,2014-01-08 - 进行中 :active, des2, 2014-01-09, 3d - 计划一 : des3, after des2, 5d - 计划二 : des4, after des3, 5d -``` -- 关于 **甘特图** 语法,参考 [这儿][2], - - - -## UML 图表 - -可以使用UML图表进行渲染。 [Mermaid](https://mermaidjs.github.io/). 例如下面产生的一个序列图:: - -```mermaid -sequenceDiagram -张三 ->> 李四: 你好!李四, 最近怎么样? -李四-->>王五: 你最近怎么样,王五? -李四--x 张三: 我很好,谢谢! -李四-x 王五: 我很好,谢谢! -Note right of 王五: 李四想了很长时间, 文字太长了
不适合放在一行. - -李四-->>张三: 打量着王五... -张三->>王五: 很好... 王五, 你怎么样? -``` - -这将产生一个流程图。: - -```mermaid -graph LR -A[长方形] -- 链接 --> B((圆)) -A --> C(圆角长方形) -B --> D{菱形} -C --> D -``` - -- 关于 **Mermaid** 语法,参考 [这儿][3], - - - -## FLowchart流程图 - -我们依旧会支持flowchart的流程图: -```mermaid -flowchat -st=>start: 开始 -e=>end: 结束 -op=>operation: 我的操作 -cond=>condition: 确认? - -st->op->cond -cond(yes)->e -cond(no)->op -``` - -- 关于 **Flowchart流程图** 语法,参考 [这儿][4]. - - -## 导出与导入 - -### 导出 -如果你想尝试使用此编辑器, 你可以在此篇文章任意编辑。当你完成了一篇文章的写作, 在上方工具栏找到 **文章导出** ,生成一个.md文件或者.html文件进行本地保存。 - -### 导入 -如果你想加载一篇你写过的.md文件或者.html文件,在上方工具栏可以选择导入功能进行对应扩展名的文件导入, -继续你的创作。 - -[1]: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference -[2]: https://mermaidjs.github.io/ -[3]: https://mermaidjs.github.io/ -[4]: http://adrai.github.io/flowchart.js/ - -## 在csdn Markdown模式下的显示效果: - diff --git a/Youdao_Note_Markdown_Template.md b/Youdao_Note_Markdown_Template.md deleted file mode 100644 index 5b810fac..00000000 --- a/Youdao_Note_Markdown_Template.md +++ /dev/null @@ -1,355 +0,0 @@ -### 有道云笔记 markdown模板 - -[toc] - - - -抽空把[【简明版】有道云笔记Markdown指南](http://note.youdao.com/iyoudao/?p=2411)的图片版欢迎成了Markdown~ - - - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/758x240-2.jpg) - -什么是Markdown?Markdown是一种轻量级的「标记语言」,通常为程序员群体所用,目前它已是全球最大的技术分享网站 GitHub 和技术问答网站 StackOverFlow 的御用书写格式。 - -**有道云笔记内置Markdown编辑器和使用指南,非技术类笔记用户,千万不要被「标记」、「语言」吓到,Markdown的语法十分简单,常用的标记符号不超过十个,用于日常写作记录绰绰有余,不到半小时就能完全掌握。** - -就是这十个不到的标记符号,却能让人**优雅地沉浸式记录,专注内容而不是纠结排版**,达到「心中无尘,码字入神」的境界。 - -# 一、利用Markdown可以做什么? - -1. 代码高亮 - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/1-1%E4%BB%A3%E7%A0%81%E9%AB%98%E4%BA%AE.png) - -### 代码高亮 - -```python - -@requires_authorization - -def somefunc(param1='', param2=0): - -'''A docstring''' - -if param1 > param2: # interesting - -print 'Greater' - -return (param2-param1+1) or None - -Class SomeClass: - -pass - ->>> message = '''interpreter - -... prompt''' - -``` - -2. 制作待办事项To-do List - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/1-2%E5%BE%85%E5%8A%9E%E4%BA%8B%E9%A1%B9.png) - -### To-do List - -- [x] 已完成项目1 - -- [x] 已完成事项1 - -- [x] 已完成事项2 - -- [ ] 待办事项1 - -- [ ] 待办事项2 - -3. 高效绘制 流程图、序列图、甘特图、表格 - -### 流程图: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/%E6%B5%81%E7%A8%8B%E5%9B%BE.png) - -``` - -graph TD - -A[christmas] -->B(Go shopping) - -B --> C{LEt me think} - -C -->|One| D[Laptop] - -C -->|Two| E[iPhone] - -C -->|Three|F[Car] - -``` - -### 序列图: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/%E5%BA%8F%E5%88%97%E5%9B%BE.png) - -``` - -sequenceDiagram - -loop every day - -Alice->>John: Hello John, how are you? - -John-->> Alice: Great! - -end - -``` - -### 甘特图: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/%E7%94%98%E7%89%B9%E5%9B%BE.png) - -``` - -gantt - -dateFormat YYYY-MM-DD - -title 产品计划表 - -section 初期阶段 - -明确需求: 2016-03-01, 10d - -section 中期阶段 - -跟进开发: 2016-03-11, 15d - -section 后期阶段 - -走查测试: 2016-03-20, 9d - -``` - -**==tips==: 以上流程图均为半角标点** - -### 表格: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/1-3%E8%A1%A8%E6%A0%BC.png) - -### 表格 - -|Item | Value | Qty | - -|:------    |---------:    |:--:  | - -|Computer  |  1600 USD    |  5  | - -|Phone      |  12 USD      |  12  | - -|Pipe      |  12 USD      |  234  | - -4. 书写数学公式 - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/%E6%95%B0%E5%AD%A6%E5%85%AC%E5%BC%8F.png) - -## Mathematical formula `$y = x^2$` - -Inline math: `$\dfrac{\tfrac{1}{2}[1-(\tfrac{1}{2})^n]}{1 - \tfrac{1}{2}} = s_n$` - -Math block: - -```math - -\oint_C x^3\, dx+4y^2\,dy - -2 = \left(\frac{\left(3-x\right)\times 2}{3-x}\right) - -\sum_{m=1}^\infty\sum_{n=1}^\infty\frac{m^2n}{3^m\left(m3^n+n3^m\right)} - -\phi_n(\kappa) = \frac{1}{4\pi^2\kappa^2}\int_0^\infty\frac{\sin(\kappa R)}{\kappa R}\frac{\partial}{\partial R}\left[R^2\frac{\partial D_n(R)}{\partial R}\right]dR - -``` - -# 二、有道云笔记Markdown简明版使用指南 - -**0. 标题** - -标题是每篇文章必备而且最常用的格式。 - -在Markdown中,如果想将一段文字定义为标题,只需要在这段文字前面加上 #,再在 # 后加一个空格即可。还可增加二、三、四、五、六级标题,总共六级,只需要增加 # ,增加一个 # ,标题字号相应降低一级。如图: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-0-%E6%A0%87%E9%A2%98.png) - -# 一级标题 - -## 二级标题 - -### 三级标题 - -#### 四级标题 - -**1. 列表** - -列表格式也很常用,它可以让你的文稿变得井井有条。在 Markdown 中,你只需要在文字前面加上 - 就可以了;如果你希望是有序列表,在文字前面加上 1. 2. 3. 即可 - -#### 无序列表 - -- 列表1 - -- 列表1.1 - -- 列表1.2 - -- 列表2 - -- 列表3 - -- - -#### 有序列表 - -1. 列表1 - -1. 列表1.1 - -2. 列表1.2 - -2. 列表2 - -3. 列表3 - -**2. 引用** - -如果你需要在文稿中引用一段别处的句子,那么就要用到「引用」格式。 - -在引用文字前加上 > 并与文字保留一个字符的空格,即可。 - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-2%E5%BC%95%E7%94%A8.png) - -######引用 - -> 记录, 成为更好的自己。————有道云笔记 - -**3. 粗体和斜体** - -Markdown 的粗体和斜体也非常简单: - -用两个 * 包含一段文本就是粗体的语法; - -用一个 * 包含一段文本就是斜体的语法。 - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-3-%E7%B2%97%E4%BD%93%E6%96%9C%E4%BD%93.png) - -*这是斜体* - -**这是粗体** - -#### 注意: 符号与文本之间无需空格 - -**4. 链接和图片** - -``` - -链接:在 Markdown 中,插入链接只需要使用 [显示文本](链接地址) 即可。 - -图片:在 Markdown 中,插入图片只需要使用 ![显示文本](图片链接地址)即可。 - -``` - -注:插入图片的语法和链接的语法很像,只是前面多了一个 ! - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-4%E9%93%BE%E6%8E%A5%E4%B8%8E%E5%9B%BE%E7%89%87.png) - -#### 插入链接 - -[有道云笔记官网](http://note.youdao.com/) - -#### 插入图片 - -![有道云笔记](http://note.youdao.com/favicon.ico) - -**5. 分割线** - -分割线的语法只需要另起一行,连续输入三个星号 *** 即可分割两段文字内容。 - -如图: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-5-%E5%88%86%E5%89%B2%E7%BA%BF.png) - -#### 分割线 - -这是第一段内容 - -*** - -这是第二段内容 - -**6. 表格** - -当你需要在Markdown文稿中键入表格,代码如下: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-6%E8%A1%A8%E6%A0%BC.png) - -示例参考: - -### 表格 - -|Item | Value | Qty | - -|:------    |---------:    |:--:  | - -|Computer  |  1600 USD    |  5  | - -|Phone      |  12 USD      |  12  | - -|Pipe      |  12 USD      |  234  | - -**如上7大格式是写作文稿时最常使用的。** - -怎么样,看了相关Markdown语法是不是觉得挺简单? - -当然,Markdown新手在使用不熟练的情况下,可能会忘记相关语法,也没关系,笔记的工具栏内置了Markdown语法,方便学习与熟悉。 - -如,「表格」语法相对复杂,你可能忘记了,这时候,你只需要点击编辑框上方工具栏,点选「表格」的图标,左边编辑区便会出现「表格」相应代码: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-6%E8%A1%A8%E6%A0%BC-3.jpg) - -然后,你只需要将代码替换成相应文本即可,如图: - -![](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/1-3%E8%A1%A8%E6%A0%BC1.png) - -熟悉语法之后,还是建议大家少使用辅助工具栏,尽量自己键入代码,感受纯文本之美。 - -当然,有道云笔记的Markdown还能支持制作待办事项,书写流程图、序列图、甘特图,书写数学公式等,是不是够极客,够有逼格? - -看看笔记菌用Markdown甘特图写的项目计划时间表: - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/2-6-8.png) - -## Tips for 有道云笔记中的 Markdown - -**① 实时同步预览,所看即所得** - -我们将笔记编辑界面一分为二,左边为编辑区,右边为预览区,两区滚动条同步。在编辑区的操作能够实时反映在预览区,方便及时调整和查看最终版面效果。 - -**② 工具栏内置Markdown语法,方便新手学习** - -编辑页面顶端的工具栏有对应代码,如果你是一个不熟悉Markdown语法的新手,可以先尝试用工具栏辅助操作。也可以在网上搜索「Markdown语法指南」进行学习。 - -当然,如果你觉得工具栏太打扰,点击下方分界条即可隐藏工具栏,切换到极简编辑环境。 - -**③ 实时云端保存** - -Markdown模式继承了有道云笔记的优良传统,你每一次击键的内容都会实时保存在云端,无需担心浏览器崩溃、设备没电、突然断网等情况。对于写作者来说,更是再也不用担心因为各种原因痛失文稿的情况了。 - -**④ 界面大小可点击分界条调整。** - -点击“1”处,工具栏收起; - -点击“2”处,右侧预览区收起。 - -![image](http://note.youdao.com/iyoudao/wp-content/uploads/2016/09/91.jpg) - - -## 在有道云笔记 - Markdown模式下的显示效果: - diff --git a/ZOJ-PHP/zoj1088.php b/ZOJ-PHP/zoj1088.php deleted file mode 100644 index 79d03e9b..00000000 --- a/ZOJ-PHP/zoj1088.php +++ /dev/null @@ -1,23 +0,0 @@ - +#include +#include +#include + +#define x first // 简化代码 +#define y second + +using namespace std; +typedef pair PII; +const int N = 1010, M = N * N; + +int n, m; +char g[N][N]; +bool st[N][N]; // st: 代表state +PII q[M]; + +void bfs(int startX, int startY) +{ + int hh = 0, tt = -1; // 模拟一个队列, hh: 队头, tt: 队尾, q中装的是pair + q[++tt] = {startX, startY}; + st[startX][startY] = true; + + while (hh <= tt) + { + PII t = q[hh++]; + + for (int i = t.x - 1; i <= t.x + 1; ++i) // 遍历8个方向, 即遍历3*3的矩阵, skip掉最中间那个 + { + for (int j = t.y - 1; j <= t.y + 1; ++j) + { + if (i == t.x && j == t.y) // 不处理3x3个格子中最中间那个 + continue; + if (i < 0 || i >= n || j < 0 || j >= m) // 越界的不处理 + continue; + if (g[i][j] == '.' || st[i][j]) // 当前位置是空地或当前位置之前已访问过, 不处理 + continue; + + q[++tt] = {i, j}; + st[i][j] = true; + } + } + } +} + +int main() +{ + freopen("in1097.txt", "r", stdin); /* 重定向到从文件输入, 提交到 OJ 前本句需删除. */ + scanf("%d%d", &n, &m); + for (int i = 0; i < n; ++i) + scanf("%s", g[i]); + + int cnt = 0; + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < m; ++j) + { + if (g[i][j] == 'W' && !st[i][j]) + { + bfs(i, j); + cnt++; + } + } + } + + printf("%d\n", cnt); + return 0; +} \ No newline at end of file diff --git a/algo-basic/acwing167-sticks.cpp b/algo-basic/acwing167-sticks.cpp new file mode 100644 index 00000000..242cb3c6 --- /dev/null +++ b/algo-basic/acwing167-sticks.cpp @@ -0,0 +1,108 @@ +#include +// #include +#include +using namespace std; + +const int N = 70; +int n; // 所有木棒的个数 +int sum, length; /* sum: 所有木棒的长度总和, length: 当前枚举的木棍的长度 */ + +int sticks[N]; // 存所有的木棒 +bool st[N]; // 存每根木棒当前有没有被用过 + +/** + * u: 当前拼到了第几根(1, 2…)木棍, 木棒内部的编号No. + cur: 当前这根木棍已经拼了多长 + start: 当前从原木棒数组的哪个index开始枚举 +*/ +bool dfs(int u, int cur, int start) +{ + if (u * length == sum) // 找到了一组解 + { + return true; + } + if (cur == length) /* 搜索下一个新的木棍 */ + return dfs(u + 1, 0, 0); + for (int i = start; i < n; i++) // 循环需要从start开始 + { + if (st[i]) continue; // 当前木棍用掉了 + int l = sticks[i]; + if (cur + l <= length) + { + st[i] = true; + if (dfs(u, cur + l, i + 1)) + { + return true; + } + st[i] = false; // 清空访问状态 + // 剪枝3 如果是第一根木棍放入失败, 则一定失败 + if (!cur) + { + return false; + } + //剪枝4 如果是最后一根木棒放入失败, 则一定失败 + if (cur + l == length) + { + return false; + } + // 剪枝2 如果失败了, 则跳过长度相等的木棒 + int j = i; + while (j < n && sticks[j] == l) + { + j++; + } + i = j - 1; + } + } + return false; +} + +/** + 输入样例: + + 9 + 5 2 1 5 2 1 5 2 1 + 4 + 1 2 3 4 + 0 +*/ +// Test +int main() +{ + while (cin >> n, n) + { + sum = 0, length = 0; + fill(st, st + N, false); // 把所有长度>50的木棍的访问状态清空一下 + for (int i = 0; i < n; i++) + { + cin >> sticks[i]; + if (sticks[i] > 50) + { + continue; + } + sum += sticks[i]; + length = max(length, sticks[i]); + } + + // 剪枝: 优化搜索顺序 + sort(sticks, sticks + n, greater()); + for (int i = 0; i < n; i++) + { + if (sticks[i] > 50) + { + st[i] = true; + } + } + + while (true) + { + if (sum % length == 0 && dfs(0, 0, 0)) + { + cout << length << endl; + break; + } + length++; + } + } + return 0; +} \ No newline at end of file diff --git a/algo-basic/acwing785-quick-sort_do_while.cpp b/algo-basic/acwing785-quick-sort_do_while.cpp new file mode 100644 index 00000000..73dfc767 --- /dev/null +++ b/algo-basic/acwing785-quick-sort_do_while.cpp @@ -0,0 +1,45 @@ +/** acwing地址: https://www.acwing.com/problem/content/description/787/ + * 作者: 极客学长 + * 日期: 2021-08-13 11:07:23 +*/ +#include +using namespace std; + +const int N = 1e6 + 10; // 1e6表示 10^6 +int n; +int A[N]; + +void quickSort(int A[], int l, int r) +{ + if (l >= r) return; + int x = A[(l+r)/2]; // 分界点取中间点比较保险, 因为有时会遇到最坏的情形(极度散乱, 熵最大时)~ + int i = l - 1, j = r + 1; /* 每次交换完之后, 向中间一定1位 */ + // 双指针 + while (i < j) + { + do i++; while (A[i] < x); + do j--; while (A[j] > x); + if (i < j) swap(A[i], A[j]); + } + // 递归处理左侧 + quickSort(A, l, j); + // 递归处理右侧 + quickSort(A, j+1, r); +} + +int main() +{ + // scanf("%d", &n); + // for (int i = 0; i < n; i++) + // scanf("%d", &A[i]); + n = 5; + int T[] = {10, 7, 6, 2, 4}; + copy(T, T + n, A); // n = len(T) = 5 + + quickSort(A, 0, n - 1); // 用具体的 l 和 r 值调用 quickSort(A, l, r); + + for (int i = 0; i < n; i++) + printf("%d ", A[i]); + + return 0; +} \ No newline at end of file diff --git a/algo-basic/acwing785-quick-sort_while_hardcode_input.cpp b/algo-basic/acwing785-quick-sort_while_hardcode_input.cpp new file mode 100644 index 00000000..153c646c --- /dev/null +++ b/algo-basic/acwing785-quick-sort_while_hardcode_input.cpp @@ -0,0 +1,48 @@ +/** acwing地址: https://www.acwing.com/problem/content/description/787/ + * 作者: 极客学长 + * 日期: 2021-08-13 11:27:23 +*/ +#include +#include +using namespace std; + +const int N = 1e6 + 10; // 1e6表示 10^6 +int n; +int A[N]; + +void quickSort(int A[], int l, int r) +{ + if (l >= r) return; + int x = A[(l+r)/2]; // 分界点取中间点比较保险, 因为有时会遇到最坏的情形(极度散乱, 熵最大时)~ + int i = l - 1, j = r + 1; /* 每次交换完之后, 向中间一定1位 */ + // 双指针 + while (i < j) + { + i++; + while (A[i] < x) i++; + j--; + while (A[j] > x) j--; + if (i < j) swap(A[i], A[j]); + } + // 递归处理左侧 + quickSort(A, l, j); + // 递归处理右侧 + quickSort(A, j+1, r); +} + +int main() +{ + // scanf("%d", &n); + // for (int i = 0; i < n; i++) + // scanf("%d", &A[i]); + n = 5; + int T[] = {3, 2, 2, 5, 3}; /* 使用临时数组保存input中的数组, 之前为A设置了最大长度, 但具体使用时不一定需要用这么多空间, 于是这里使用std::copy给实际情况赋值 */ + copy(T, T + n, A); // std::copy, 而 n = len(T) = 5 + + quickSort(A, 0, n - 1); // 用具体的 l 和 r 值调用 quickSort(A, l, r); + + for (int i = 0; i < n; i++) + printf("%d ", A[i]); + + return 0; +} \ No newline at end of file diff --git a/algo-basic/acwing785-quick-sort_while_readFile.cpp b/algo-basic/acwing785-quick-sort_while_readFile.cpp new file mode 100644 index 00000000..3dc186ec --- /dev/null +++ b/algo-basic/acwing785-quick-sort_while_readFile.cpp @@ -0,0 +1,54 @@ +/** acwing地址: https://www.acwing.com/problem/content/description/787/ + * 作者: 极客学长 + * 时间: 2021-08-13 11:16:23 +*/ +#include +#include +using namespace std; + +const int N = 1e6 + 10; // 1e6表示 10^6, 使用 #define 的宏定义也行 +int n; +int A[N]; + +void quickSort(int A[], int l, int r) +{ + if (l >= r) return; + int x = A[(l+r)/2]; // 分界点取中间点比较保险, 因为有时会遇到最坏的情形(极度散乱, 熵最大时)~ + int i = l - 1, j = r + 1; /* 每次交换完之后, 向中间一定1位 */ + // 双指针 + while (i < j) + { + // 不管三七二十一, 先移动1步再比较 + while (A[++i] < x); + while (A[--j] > x); + // 上面两行等价于: + // i++; + // while (A[i] < x) i++; + // j--; + // while (A[j] > x) j--; + + // Debug + // printf("%d ", i); 结束时i 最小为0(在迭代中没继续移动) + // printf("%d\n", j); + if (i < j) swap(A[i], A[j]); // 此轮处理完时j 成了新的分界点 + } + // 递归处理左侧 + quickSort(A, l, j); + // 递归处理右侧 + quickSort(A, j + 1, r); +} + +int main() +{ + freopen("in785.txt", "r", stdin); /* 重定向到从文件输入, 提交到 OJ 前本句需删除. 输入文件中隔开符号应该为空格, 不能有逗号或其他任意字符. */ + scanf("%d", &n); + for (int i = 0; i < n; i++) + scanf("%d", &A[i]); + + quickSort(A, 0, n - 1); // 用具体的 l 和 r 值调用 quickSort(A, l, r); + + for (int i = 0; i < n; i++) + printf("%d ", A[i]); + + return 0; +} \ No newline at end of file diff --git a/algo-basic/acwing787-merge-sort.cpp b/algo-basic/acwing787-merge-sort.cpp new file mode 100644 index 00000000..9b99e451 --- /dev/null +++ b/algo-basic/acwing787-merge-sort.cpp @@ -0,0 +1,42 @@ +#include +#include +using namespace std; + +const int N = 100010; +int n; +int A[N], tmp[N]; + +void mergeSort(int A[], int l, int r) +{ + if (l >= r) return; + + int mid = (l+r)/2; + mergeSort(A, l, mid); + mergeSort(A, mid+1, r); + int i = l, j = mid+1, k=0; + while (i <= mid && j <= r) + { + if (A[i] <= A[j]) tmp[k++] = A[i++]; + else tmp[k++] = A[j++]; + } + // 上面这次循环结束时, 如果左半边没处理完需要进行如下操作 + while (i <= mid) tmp[k++] = A[i++]; + while (j <= r) tmp[k++] = A[j++]; + for (int i=l, j=0; i <= r; i++, j++) A[i] = tmp[j]; +} + +int main() +{ + // scanf("%d", &n); + // for (int i = 0; i < n; i++) + // scanf("%d", &A[i]); + n = 5; + int T[] = {3, 2, 2, 5, 3}; + copy(T, T + n, A); + + mergeSort(A, 0, n-1); + + for (int i = 0; i> 1; + if (check(mid)) + r = mid; + // check()判断mid是否满足性质 + else l = mid + 1; + } + return l; +} + +// 区间[1, r]被划分成[1, mid - 1]和[mid, r]时使用: +int bsearch_2(int l, int r) +{ + while (l < r) + { + int mid = l + r + 1 >> 1; + if (check(mid)) + l = mid; + else r = mid - 1; + } + return l; +} diff --git a/algo-basic/in1097.txt b/algo-basic/in1097.txt new file mode 100644 index 00000000..98123be1 --- /dev/null +++ b/algo-basic/in1097.txt @@ -0,0 +1,11 @@ +10 12 +W........WW. +.WWW.....WWW +....WW...WW. +.........WW. +.........W.. +..W......W.. +.W.W.....WW. +W.W.W.....W. +.W.W......W. +..W.......W. \ No newline at end of file diff --git a/algo-basic/in167.txt b/algo-basic/in167.txt new file mode 100644 index 00000000..e69de29b diff --git a/algo-basic/in785.txt b/algo-basic/in785.txt new file mode 100644 index 00000000..1f721abd --- /dev/null +++ b/algo-basic/in785.txt @@ -0,0 +1,2 @@ +5 +3 2 2 5 3 \ No newline at end of file diff --git a/assets/0000-0099/0001.Two Sum/README_EN.md b/assets/0000-0099/0001.Two Sum/README_EN.md new file mode 100644 index 00000000..79c05009 --- /dev/null +++ b/assets/0000-0099/0001.Two Sum/README_EN.md @@ -0,0 +1,144 @@ +# [1. Two Sum](https://leetcode.com/problems/two-sum) + + + +## Description + +

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

+ +

You may assume that each input would have exactly one solution, and you may not use the same element twice.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,7,11,15], target = 9
+Output: [0,1]
+Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
+
+ +

Example 2:

+ +
+Input: nums = [3,2,4], target = 6
+Output: [1,2]
+
+ +

Example 3:

+ +
+Input: nums = [3,3], target = 6
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 103
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
  • Only one valid answer exists.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + helper = {} + for i, v in enumerate(nums): + num = target - v + if num in helper: + return [helper[num], i] + helper[v] = i +``` + +### **Java** + +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + Map map = new HashMap<>(); + for (int i = 0, n = nums.length; i < n; ++i) { + int num = target - nums[i]; + if (map.containsKey(num)) { + return new int[]{map.get(num), i}; + } + map.put(nums[i], i); + } + return null; + } +} +``` + +### **JavaScript** + +```js +var twoSum = function (nums, target) { + const map = new Map(); + for (let i = 0; i < nums.length; i++) { + if (map.has(target - nums[i])) { + return [map.get(target - nums[i]), i]; + } + map.set(nums[i], i); + } + return []; +}; +``` + +### **Swift** + +```swift +class Solution { + func twoSum(_ nums: [Int], _ target: Int) -> [Int] { + var map = [Int: Int]() + var i = 0 + for num in nums { + map[num] = i + i = i + 1 + } + i = 0 + for num in nums { + if let otherIndex = map[target - num], otherIndex != i { + return [i, otherIndex] + } + i = i + 1 + } + return [] + } +} +``` + +### **Nim** + +```nim +import std/enumerate + +proc twoSum(nums: seq[int], target: int): seq[int] = + var + bal: int + tdx: int + for idx, val in enumerate(nums): + bal = target - val + if bal in nums: + tdx = nums.find(bal) + if idx != tdx: + return @[idx, tdx] + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0002.Add Two Numbers/README_EN.md b/assets/0000-0099/0002.Add Two Numbers/README_EN.md new file mode 100644 index 00000000..5201d5a9 --- /dev/null +++ b/assets/0000-0099/0002.Add Two Numbers/README_EN.md @@ -0,0 +1,337 @@ +# [2. Add Two Numbers](https://leetcode.com/problems/add-two-numbers) + + + +## Description + +

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

+ +

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

+ +

 

+

Example 1:

+ +
+Input: l1 = [2,4,3], l2 = [5,6,4]
+Output: [7,0,8]
+Explanation: 342 + 465 = 807.
+
+ +

Example 2:

+ +
+Input: l1 = [0], l2 = [0]
+Output: [0]
+
+ +

Example 3:

+ +
+Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
+Output: [8,9,9,9,0,0,0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each linked list is in the range [1, 100].
  • +
  • 0 <= Node.val <= 9
  • +
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + carry, cur = 0, dummy + while l1 or l2 or carry: + s = (0 if not l1 else l1.val) + (0 if not l2 else l2.val) + carry + carry, val = divmod(s, 10) + cur.next = ListNode(val) + cur = cur.next + l1 = None if not l1 else l1.next + l2 = None if not l2 else l2.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + int carry = 0; + ListNode* cur = dummy; + while (l1 || l2 || carry) { + int s = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; + carry = s / 10; + cur->next = new ListNode(s % 10); + cur = cur->next; + l1 = l1 ? l1->next : nullptr; + l2 = l2 ? l2->next : nullptr; + } + return dummy->next; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + const dummy = new ListNode(); + let carry = 0; + let cur = dummy; + while (l1 || l2 || carry) { + const s = (l1?.val || 0) + (l2?.val || 0) + carry; + carry = Math.floor(s / 10); + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1?.next; + l2 = l2?.next; + } + return dummy.next; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + carry := 0 + cur := dummy + for l1 != nil || l2 != nil || carry != 0 { + s := carry + if l1 != nil { + s += l1.Val + } + if l2 != nil { + s += l2.Val + } + carry = s / 10 + cur.Next = &ListNode{s % 10, nil} + cur = cur.Next + if l1 != nil { + l1 = l1.Next + } + if l2 != nil { + l2 = l2.Next + } + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + dummy = ListNode.new() + carry = 0 + cur = dummy + while !l1.nil? || !l2.nil? || carry > 0 + s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry + carry = s / 10 + cur.next = ListNode.new(s % 10) + cur = cur.next + l1 = l1.nil? ? l1 : l1.next + l2 = l2.nil? ? l2 : l2.next + end + dummy.next +end +``` + +### **Swift** + +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { + var dummy = ListNode.init() + var carry = 0 + var l1 = l1 + var l2 = l2 + var cur = dummy + while l1 != nil || l2 != nil || carry != 0 { + let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry + carry = s / 10 + cur.next = ListNode.init(s % 10) + cur = cur.next! + l1 = l1?.next + l2 = l2?.next + } + return dummy.next + } +} +``` + +### **Nim** + +```nim +#[ + # Driver code in the solution file + # Definition for singly-linked list. + type + Node[int] = ref object + value: int + next: Node[int] + + SinglyLinkedList[T] = object + head, tail: Node[T] +]# + +# More efficient code churning ... +proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = + var + aggregate: SinglyLinkedList + psum: seq[char] + temp_la, temp_lb: seq[int] + + while not l1.head.isNil: + temp_la.add(l1.head.value) + l1.head = l1.head.next + + while not l2.head.isNil: + temp_lb.add(l2.head.value) + l2.head = l2.head.next + + psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) + for i in psum: aggregate.append(($i).parseInt()) + + result = aggregate +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0002.Add Two Numbers/images/addtwonumber1.jpg b/assets/0000-0099/0002.Add Two Numbers/images/addtwonumber1.jpg new file mode 100644 index 00000000..68dc055a Binary files /dev/null and b/assets/0000-0099/0002.Add Two Numbers/images/addtwonumber1.jpg differ diff --git a/assets/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md b/assets/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md new file mode 100644 index 00000000..7186fd15 --- /dev/null +++ b/assets/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md @@ -0,0 +1,141 @@ +# [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters) + + + +## Description + +

Given a string s, find the length of the longest substring without repeating characters.

+ +

 

+

Example 1:

+ +
+Input: s = "abcabcbb"
+Output: 3
+Explanation: The answer is "abc", with the length of 3.
+
+ +

Example 2:

+ +
+Input: s = "bbbbb"
+Output: 1
+Explanation: The answer is "b", with the length of 1.
+
+ +

Example 3:

+ +
+Input: s = "pwwkew"
+Output: 3
+Explanation: The answer is "wke", with the length of 3.
+Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
+
+ +

Example 4:

+ +
+Input: s = ""
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 5 * 104
  • +
  • s consists of English letters, digits, symbols and spaces.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + res, chars = 0, dict() + i = j = 0 + while j < len(s): + if s[j] in chars: + i = max(i, chars[s[j]] + 1) + res = max(res, j - i + 1) + chars[s[j]] = j + j += 1 + return res +``` + +### **Java** + +```java +class Solution { + public int lengthOfLongestSubstring(String s) { + int res = 0; + Map chars = new HashMap<>(); + for (int i = 0, j = 0; j < s.length(); ++j) { + char c = s.charAt(j); + if (chars.containsKey(c)) { + i = Math.max(i, chars.get(c) + 1); + } + chars.put(c, j); + res = Math.max(res, j - i + 1); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function lengthOfLongestSubstring(s: string): number { + // 滑动窗口+哈希表 + let left = -1; + let maxLen = 0; + let hashTable = new Map(); + for (let right = 0; right < s.length; right++) { + let cur = s.charAt(right); + if (hashTable.has(cur)) { + left = Math.max(left, hashTable.get(cur)); + } + hashTable.set(cur, right); + maxLen = Math.max(maxLen, right - left); + } + return maxLen; + }; +``` + +### **Swift** + +```swift +class Solution { + func lengthOfLongestSubstring(_ s: String) -> Int { + var map = [Character: Int]() + var currentStartingIndex = 0 + var i = 0 + var maxLength = 0 + for char in s { + if map[char] != nil { + if map[char]! >= currentStartingIndex { + maxLength = max(maxLength, i - currentStartingIndex) + currentStartingIndex = map[char]! + 1 + } + } + map[char] = i + i += 1 + } + return max(maxLength, i - currentStartingIndex) + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md b/assets/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md new file mode 100644 index 00000000..4415143a --- /dev/null +++ b/assets/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md @@ -0,0 +1,84 @@ +# [4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays) + + + +## Description + +

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [1,3], nums2 = [2]
+Output: 2.00000
+Explanation: merged array = [1,2,3] and median is 2.
+
+ +

Example 2:

+ +
+Input: nums1 = [1,2], nums2 = [3,4]
+Output: 2.50000
+Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
+
+ +

Example 3:

+ +
+Input: nums1 = [0,0], nums2 = [0,0]
+Output: 0.00000
+
+ +

Example 4:

+ +
+Input: nums1 = [], nums2 = [1]
+Output: 1.00000
+
+ +

Example 5:

+ +
+Input: nums1 = [2], nums2 = []
+Output: 2.00000
+
+ +

 

+

Constraints:

+ +
    +
  • nums1.length == m
  • +
  • nums2.length == n
  • +
  • 0 <= m <= 1000
  • +
  • 0 <= n <= 1000
  • +
  • 1 <= m + n <= 2000
  • +
  • -106 <= nums1[i], nums2[i] <= 106
  • +
+ +

 

+Follow up: The overall run time complexity should be O(log (m+n)). + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0005.Longest Palindromic Substring/README_EN.md b/assets/0000-0099/0005.Longest Palindromic Substring/README_EN.md new file mode 100644 index 00000000..d8f4f694 --- /dev/null +++ b/assets/0000-0099/0005.Longest Palindromic Substring/README_EN.md @@ -0,0 +1,104 @@ +# [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring) + + + +## Description + +

Given a string s, return the longest palindromic substring in s.

+ + + +

 

+ +

Example 1:

+ + + +
+
+Input: s = "babad"
+
+Output: "bab"
+
+Note: "aba" is also a valid answer.
+
+
+ + + +

Example 2:

+ + + +
+
+Input: s = "cbbd"
+
+Output: "bb"
+
+
+ + + +

Example 3:

+ + + +
+
+Input: s = "a"
+
+Output: "a"
+
+
+ + + +

Example 4:

+ + + +
+
+Input: s = "ac"
+
+Output: "a"
+
+
+ + + +

 

+ +

Constraints:

+ + + +
    +
  • 1 <= s.length <= 1000
  • +
  • s consist of only digits and English letters (lower-case and/or upper-case),
  • +
+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0006.ZigZag Conversion/README_EN.md b/assets/0000-0099/0006.ZigZag Conversion/README_EN.md new file mode 100644 index 00000000..c0c613f9 --- /dev/null +++ b/assets/0000-0099/0006.ZigZag Conversion/README_EN.md @@ -0,0 +1,82 @@ +# [6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion) + + + +## Description + +

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

+ +
+P   A   H   N
+A P L S I I G
+Y   I   R
+
+ +

And then read line by line: "PAHNAPLSIIGYIR"

+ +

Write the code that will take a string and make this conversion given a number of rows:

+ +
+string convert(string s, int numRows);
+
+ +

 

+

Example 1:

+ +
+Input: s = "PAYPALISHIRING", numRows = 3
+Output: "PAHNAPLSIIGYIR"
+
+ +

Example 2:

+ +
+Input: s = "PAYPALISHIRING", numRows = 4
+Output: "PINALSIGYAHRPI"
+Explanation:
+P     I    N
+A   L S  I G
+Y A   H R
+P     I
+
+ +

Example 3:

+ +
+Input: s = "A", numRows = 1
+Output: "A"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • +
  • 1 <= numRows <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0007.Reverse Integer/README_EN.md b/assets/0000-0099/0007.Reverse Integer/README_EN.md new file mode 100644 index 00000000..aa3d9dff --- /dev/null +++ b/assets/0000-0099/0007.Reverse Integer/README_EN.md @@ -0,0 +1,100 @@ +# [7. Reverse Integer](https://leetcode.com/problems/reverse-integer) + + + +## Description + +

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

+ +

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

+ +

 

+

Example 1:

+
Input: x = 123
+Output: 321
+

Example 2:

+
Input: x = -123
+Output: -321
+

Example 3:

+
Input: x = 120
+Output: 21
+

Example 4:

+
Input: x = 0
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • -231 <= x <= 231 - 1
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def reverse(self, x: int) -> int: + y = int(str(abs(x))[::-1]) + res = -y if x < 0 else y + return 0 if res < -2**31 or res > 2**31 -1 else res +``` + +### **Java** + +```java +class Solution { + public int reverse(int x) { + long res = 0; + while (x != 0) { + res = res * 10 + (x % 10); + x /= 10; + } + return res < Integer.MIN_VALUE || res > Integer.MAX_VALUE ? 0 : (int) res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int reverse(int x) { + long long ans = 0; + while (x) { + ans = ans * 10 + x % 10; + x /= 10; + } + return ans < INT_MIN || ans > INT_MAX ? 0 : ans; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @return {number} + */ +var reverse = function (x) { + let res = 0; + while (x) { + res = res * 10 + (x % 10); + x = ~~(x / 10); + } + return res < Math.pow(-2, 31) || res > Math.pow(2, 31) - 1 ? 0 : res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0008.String to Integer (atoi)/README_EN.md b/assets/0000-0099/0008.String to Integer (atoi)/README_EN.md new file mode 100644 index 00000000..e72df39a --- /dev/null +++ b/assets/0000-0099/0008.String to Integer (atoi)/README_EN.md @@ -0,0 +1,189 @@ +# [8. String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi) + + + +## Description + +

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

+ +

The algorithm for myAtoi(string s) is as follows:

+ +
    +
  1. Read in and ignore any leading whitespace.
  2. +
  3. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  4. +
  5. Read in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored.
  6. +
  7. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  8. +
  9. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
  10. +
  11. Return the integer as the final result.
  12. +
+ +

Note:

+ +
    +
  • Only the space character ' ' is considered a whitespace character.
  • +
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
  • +
+ +

 

+

Example 1:

+ +
+Input: s = "42"
+Output: 42
+Explanation: The underlined characters are what is read in, the caret is the current reader position.
+Step 1: "42" (no characters read because there is no leading whitespace)
+         ^
+Step 2: "42" (no characters read because there is neither a '-' nor '+')
+         ^
+Step 3: "42" ("42" is read in)
+           ^
+The parsed integer is 42.
+Since 42 is in the range [-231, 231 - 1], the final result is 42.
+
+ +

Example 2:

+ +
+Input: s = "   -42"
+Output: -42
+Explanation:
+Step 1: "   -42" (leading whitespace is read and ignored)
+            ^
+Step 2: "   -42" ('-' is read, so the result should be negative)
+             ^
+Step 3: "   -42" ("42" is read in)
+               ^
+The parsed integer is -42.
+Since -42 is in the range [-231, 231 - 1], the final result is -42.
+
+ +

Example 3:

+ +
+Input: s = "4193 with words"
+Output: 4193
+Explanation:
+Step 1: "4193 with words" (no characters read because there is no leading whitespace)
+         ^
+Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
+         ^
+Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
+             ^
+The parsed integer is 4193.
+Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
+
+ +

Example 4:

+ +
+Input: s = "words and 987"
+Output: 0
+Explanation:
+Step 1: "words and 987" (no characters read because there is no leading whitespace)
+         ^
+Step 2: "words and 987" (no characters read because there is neither a '-' nor '+')
+         ^
+Step 3: "words and 987" (reading stops immediately because there is a non-digit 'w')
+         ^
+The parsed integer is 0 because no digits were read.
+Since 0 is in the range [-231, 231 - 1], the final result is 0.
+
+ +

Example 5:

+ +
+Input: s = "-91283472332"
+Output: -2147483648
+Explanation:
+Step 1: "-91283472332" (no characters read because there is no leading whitespace)
+         ^
+Step 2: "-91283472332" ('-' is read, so the result should be negative)
+          ^
+Step 3: "-91283472332" ("91283472332" is read in)
+                     ^
+The parsed integer is -91283472332.
+Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648. 
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 200
  • +
  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def myAtoi(self, s: str) -> int: + if not s: + return 0 + n = len(s) + if n == 0: + return 0 + i = 0 + while s[i] == ' ': + i += 1 + # only contains blank space + if i == n: + return 0 + sign = -1 if s[i] == '-' else 1 + if s[i] in ['-', '+']: + i += 1 + res, flag = 0, (2 ** 31 - 1) // 10 + while i < n: + # not a number, exit the loop + if not s[i].isdigit(): + break + c = int(s[i]) + # if overflows + if res > flag or (res == flag and c > 7): + return 2 ** 31 - 1 if sign > 0 else -2 ** 31 + res = res * 10 + c + i += 1 + return sign * res +``` + +### **Java** + +```java +class Solution { + public int myAtoi(String s) { + if (s == null) return 0; + int n = s.length(); + if (n == 0) return 0; + int i = 0; + while (s.charAt(i) == ' ') { + // only contains blank space + if (++i == n) return 0; + } + int sign = 1; + if (s.charAt(i) == '-') sign = -1; + if (s.charAt(i) == '-' || s.charAt(i) == '+') ++i; + int res = 0, flag = Integer.MAX_VALUE / 10; + for (; i < n; ++i) { + // not a number, exit the loop + if (s.charAt(i) < '0' || s.charAt(i) > '9') break; + // if overflows + if (res > flag || (res == flag && s.charAt(i) > '7')) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; + res = res * 10 + (s.charAt(i) - '0'); + } + return sign * res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0009.Palindrome Number/README_EN.md b/assets/0000-0099/0009.Palindrome Number/README_EN.md new file mode 100644 index 00000000..54ba1e4b --- /dev/null +++ b/assets/0000-0099/0009.Palindrome Number/README_EN.md @@ -0,0 +1,92 @@ +# [9. Palindrome Number](https://leetcode.com/problems/palindrome-number) + + + +## Description + +

Given an integer x, return true if x is palindrome integer.

+ +

An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.

+ +

 

+

Example 1:

+ +
+Input: x = 121
+Output: true
+
+ +

Example 2:

+ +
+Input: x = -121
+Output: false
+Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
+
+ +

Example 3:

+ +
+Input: x = 10
+Output: false
+Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
+
+ +

Example 4:

+ +
+Input: x = -101
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= x <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without converting the integer to a string? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + y, t = 0, x + while t: + y = y * 10 + t % 10 + t //= 10 + return x == y +``` + +### **Java** + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0) return false; + int y = 0, t = x; + while (t != 0) { + y = y * 10 + t % 10; + t /= 10; + } + return x == y; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0010.Regular Expression Matching/README_EN.md b/assets/0000-0099/0010.Regular Expression Matching/README_EN.md new file mode 100644 index 00000000..c90db168 --- /dev/null +++ b/assets/0000-0099/0010.Regular Expression Matching/README_EN.md @@ -0,0 +1,90 @@ +# [10. Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching) + + + +## Description + +

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where: 

+ +
    +
  • '.' Matches any single character.​​​​
  • +
  • '*' Matches zero or more of the preceding element.
  • +
+ +

The matching should cover the entire input string (not partial).

+ +

 

+

Example 1:

+ +
+Input: s = "aa", p = "a"
+Output: false
+Explanation: "a" does not match the entire string "aa".
+
+ +

Example 2:

+ +
+Input: s = "aa", p = "a*"
+Output: true
+Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
+
+ +

Example 3:

+ +
+Input: s = "ab", p = ".*"
+Output: true
+Explanation: ".*" means "zero or more (*) of any character (.)".
+
+ +

Example 4:

+ +
+Input: s = "aab", p = "c*a*b"
+Output: true
+Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
+
+ +

Example 5:

+ +
+Input: s = "mississippi", p = "mis*is*p*."
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 20
  • +
  • 0 <= p.length <= 30
  • +
  • s contains only lowercase English letters.
  • +
  • p contains only lowercase English letters, '.', and '*'.
  • +
  • It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0011.Container With Most Water/README_EN.md b/assets/0000-0099/0011.Container With Most Water/README_EN.md new file mode 100644 index 00000000..c564b6b5 --- /dev/null +++ b/assets/0000-0099/0011.Container With Most Water/README_EN.md @@ -0,0 +1,169 @@ +# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water) + + + +## Description + +

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

+ +

Notice that you may not slant the container.

+ +

 

+

Example 1:

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

Example 2:

+ +
+Input: height = [1,1]
+Output: 1
+
+ +

Example 3:

+ +
+Input: height = [4,3,2,1,4]
+Output: 16
+
+ +

Example 4:

+ +
+Input: height = [1,2,1]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • n == height.length
  • +
  • 2 <= n <= 105
  • +
  • 0 <= height[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxArea(self, height: List[int]) -> int: + i, j = 0, len(height) - 1 + res = 0 + while i < j: + t = (j - i) * min(height[i], height[j]) + res = max(res, t) + if height[i] < height[j]: + i += 1 + else: + j -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public int maxArea(int[] height) { + int i = 0, j = height.length - 1; + int res = 0; + while (i < j) { + int t = (j - i) * Math.min(height[i], height[j]); + res = Math.max(res, t); + if (height[i] < height[j]) ++i; + else --j; + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxArea(vector& height) { + int i = 0, j = height.size() - 1; + int res = 0; + while (i < j) { + int t = (j - i) * min(height[i], height[j]); + res = max(res, t); + if (height[i] < height[j]) ++i; + else --j; + } + return res; + } +}; +``` + +### **Go** + +```go +func maxArea(height []int) int { + i, j := 0, len(height) - 1 + res := 0 + for i != j { + t := (j - i) * min(height[i], height[j]) + res = max(res, t) + if height[i] < height[j] { + i++ + } else { + j-- + } + } + return res +} + +func min(a, b int) int { + if a > b { + return b + } + return a +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function (height) { + let i = 0, + j = height.length - 1; + let res = 0; + while (i < j) { + const t = (j - i) * Math.min(height[i], height[j]); + res = Math.max(res, t); + if (height[i] < height[j]) ++i; + else --j; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0011.Container With Most Water/images/question_11.jpg b/assets/0000-0099/0011.Container With Most Water/images/question_11.jpg new file mode 100644 index 00000000..2ba17cbb Binary files /dev/null and b/assets/0000-0099/0011.Container With Most Water/images/question_11.jpg differ diff --git a/assets/0000-0099/0012.Integer to Roman/README_EN.md b/assets/0000-0099/0012.Integer to Roman/README_EN.md new file mode 100644 index 00000000..88558c04 --- /dev/null +++ b/assets/0000-0099/0012.Integer to Roman/README_EN.md @@ -0,0 +1,140 @@ +# [12. Integer to Roman](https://leetcode.com/problems/integer-to-roman) + + + +## Description + +

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

+ +
+Symbol       Value
+I             1
+V             5
+X             10
+L             50
+C             100
+D             500
+M             1000
+ +

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

+ +

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

+ +
    +
  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • +
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • +
  • C can be placed before D (500) and M (1000) to make 400 and 900.
  • +
+ +

Given an integer, convert it to a roman numeral.

+ +

 

+

Example 1:

+ +
+Input: num = 3
+Output: "III"
+
+ +

Example 2:

+ +
+Input: num = 4
+Output: "IV"
+
+ +

Example 3:

+ +
+Input: num = 9
+Output: "IX"
+
+ +

Example 4:

+ +
+Input: num = 58
+Output: "LVIII"
+Explanation: L = 50, V = 5, III = 3.
+
+ +

Example 5:

+ +
+Input: num = 1994
+Output: "MCMXCIV"
+Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num <= 3999
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def intToRoman(self, num: int) -> str: + nums = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] + res = [] + for k, v in nums: + while num >= k: + num -= k + res.append(v) + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String intToRoman(int num) { + int[] nums = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + String[] romans = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < nums.length; ++i) { + while (num >= nums[i]) { + num -= nums[i]; + sb.append(romans[i]); + } + } + return sb.toString(); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string intToRoman(int num) { + vector nums{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + vector romans{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + string ans; + for (int i = 0; i < nums.size(); ++i) { + while (num >= nums[i]) { + num -= nums[i]; + ans.append(romans[i]); + } + } + return ans; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0013.Roman to Integer/README_EN.md b/assets/0000-0099/0013.Roman to Integer/README_EN.md new file mode 100644 index 00000000..e7773871 --- /dev/null +++ b/assets/0000-0099/0013.Roman to Integer/README_EN.md @@ -0,0 +1,241 @@ +# [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer) + + + +## Description + +

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

+ + + +
+
+Symbol       Value
+
+I             1
+
+V             5
+
+X             10
+
+L             50
+
+C             100
+
+D             500
+
+M             1000
+ + + +

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

+ + + +

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

+ + + +
    +
  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • +
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • +
  • C can be placed before D (500) and M (1000) to make 400 and 900.
  • +
+ + + +

Given a roman numeral, convert it to an integer.

+ + + +

 

+ +

Example 1:

+ + + +
+
+Input: s = "III"
+
+Output: 3
+
+
+ + + +

Example 2:

+ + + +
+
+Input: s = "IV"
+
+Output: 4
+
+
+ + + +

Example 3:

+ + + +
+
+Input: s = "IX"
+
+Output: 9
+
+
+ + + +

Example 4:

+ + + +
+
+Input: s = "LVIII"
+
+Output: 58
+
+Explanation: L = 50, V= 5, III = 3.
+
+
+ + + +

Example 5:

+ + + +
+
+Input: s = "MCMXCIV"
+
+Output: 1994
+
+Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
+
+
+ + + +

 

+ +

Constraints:

+ + + +
    +
  • 1 <= s.length <= 15
  • +
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • +
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def romanToInt(self, s: str) -> int: + nums = { + 'M': 1000, + 'CM': 900, + 'D': 500, + 'CD': 400, + 'C': 100, + 'XC': 90, + 'L': 50, + 'XL': 40, + 'X': 10, + 'IX': 9, + 'V': 5, + 'IV': 4, + 'I': 1 + } + i = res = 0 + while i < len(s): + if i + 1 < len(s) and s[i:i + 2] in nums: + res += nums[s[i: i + 2]] + i += 2 + else: + res += nums[s[i: i + 1]] + i += 1 + return res +``` + +### **Java** + +```java +class Solution { + public int romanToInt(String s) { + Map nums = new HashMap<>(); + nums.put("M", 1000); + nums.put("CM", 900); + nums.put("D", 500); + nums.put("CD", 400); + nums.put("C", 100); + nums.put("XC", 90); + nums.put("L", 50); + nums.put("XL", 40); + nums.put("X", 10); + nums.put("IX", 9); + nums.put("V", 5); + nums.put("IV", 4); + nums.put("I", 1); + int res = 0; + for (int i = 0; i < s.length();) { + if (i + 1 < s.length() && nums.get(s.substring(i, i + 2)) != null) { + res += nums.get(s.substring(i, i + 2)); + i += 2; + } else { + res += nums.get(s.substring(i, i + 1)); + i += 1; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { + public: + int romanToInt(string s) { + unordered_map nums{ + {'I', 1}, + {'V', 5}, + {'X', 10}, + {'L', 50}, + {'C', 100}, + {'D', 500}, + {'M', 1000}, + }; + int ans = 0; + for (int i = 0; i < s.size() - 1; ++i) { + if (nums[s[i]] < nums[s[i + 1]]) + ans -= nums[s[i]]; + else + ans += nums[s[i]]; + } + return ans + nums[s.back()]; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0014.Longest Common Prefix/README_EN.md b/assets/0000-0099/0014.Longest Common Prefix/README_EN.md new file mode 100644 index 00000000..295a0d28 --- /dev/null +++ b/assets/0000-0099/0014.Longest Common Prefix/README_EN.md @@ -0,0 +1,101 @@ +# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix) + + + +## Description + +

Write a function to find the longest common prefix string amongst an array of strings.

+ +

If there is no common prefix, return an empty string "".

+ +

 

+

Example 1:

+ +
+Input: strs = ["flower","flow","flight"]
+Output: "fl"
+
+ +

Example 2:

+ +
+Input: strs = ["dog","racecar","car"]
+Output: ""
+Explanation: There is no common prefix among the input strings.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= strs.length <= 200
  • +
  • 0 <= strs[i].length <= 200
  • +
  • strs[i] consists of only lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + n = len(strs) + if n == 0: + return '' + for i in range(len(strs[0])): + for j in range(1, n): + if len(strs[j]) <= i or strs[j][i] != strs[0][i]: + return strs[0][:i] + return strs[0] +``` + +### **Java** + +```java +class Solution { + public String longestCommonPrefix(String[] strs) { + int n; + if ((n = strs.length) == 0) return ""; + for (int i = 0; i < strs[0].length(); ++i) { + for (int j = 1; j < n; ++j) { + if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) { + return strs[0].substring(0, i); + } + } + } + return strs[0]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string longestCommonPrefix(vector& strs) { + int n; + if ((n = strs.size()) == 0) return ""; + for (int i = 0; i < strs[0].size(); ++i) { + for (int j = 1; j < n; ++j) { + if (strs[j].size() <= i || strs[j][i] != strs[0][i]) { + return strs[0].substr(0, i); + } + } + } + return strs[0]; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0015.3Sum/README_EN.md b/assets/0000-0099/0015.3Sum/README_EN.md new file mode 100644 index 00000000..c075f610 --- /dev/null +++ b/assets/0000-0099/0015.3Sum/README_EN.md @@ -0,0 +1,151 @@ +# [15. 3Sum](https://leetcode.com/problems/3sum) + + + +## Description + +

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

+ +

Notice that the solution set must not contain duplicate triplets.

+ +

 

+

Example 1:

+
Input: nums = [-1,0,1,2,-1,-4]
+Output: [[-1,-1,2],[-1,0,1]]
+

Example 2:

+
Input: nums = []
+Output: []
+

Example 3:

+
Input: nums = [0]
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 3000
  • +
  • -105 <= nums[i] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + if nums is None or len(nums) < 3: + return [] + nums.sort() + n = len(nums) + res = [] + for i in range(n - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + p, q = i + 1, n - 1 + while p < q: + if p > i + 1 and nums[p] == nums[p - 1]: + p += 1 + continue + if q < n - 1 and nums[q] == nums[q + 1]: + q -= 1 + continue + if nums[i] + nums[p] + nums[q] < 0: + p += 1 + elif nums[i] + nums[p] + nums[q] > 0: + q -= 1 + else: + res.append([nums[i], nums[p], nums[q]]) + p += 1 + q -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public List> threeSum(int[] nums) { + int n; + if (nums == null || (n = nums.length) < 3) { + return Collections.emptyList(); + } + Arrays.sort(nums); + List> res = new ArrayList<>(); + for (int i = 0; i < n - 2; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + int p = i + 1, q = n - 1; + while (p < q) { + if (p > i + 1 && nums[p] == nums[p - 1]) { + ++p; + continue; + } + if (q < n - 1 && nums[q] == nums[q + 1]) { + --q; + continue; + } + if (nums[p] + nums[q] + nums[i] < 0) { + ++p; + } else if (nums[p] + nums[q] + nums[i] > 0) { + --q; + } else { + res.add(Arrays.asList(nums[p], nums[q], nums[i])); + ++p; + --q; + } + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function (nums) { + let len = nums.length; + if (len < 3) return []; + let res = []; + nums.sort((a, b) => a - b); + for (let i = 0; i < len - 2; i++) { + if (nums[i] > 0) break; + if (i > 0 && nums[i] === nums[i - 1]) continue; + let left = i + 1, right = len - 1; + while (left < right) { + if (nums[i] + nums[left] + nums[right] === 0) { + res.push([nums[i], nums[left], nums[right]]); + while (nums[left] === nums[left + 1]) left++; + left++; + while (nums[right] === nums[right - 1]) right--; + right--; + continue; + } else if (nums[i] + nums[left] + nums[right] > 0) { + right--; + continue; + } else { + left++; + continue; + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0016.3Sum Closest/README_EN.md b/assets/0000-0099/0016.3Sum Closest/README_EN.md new file mode 100644 index 00000000..89107bbc --- /dev/null +++ b/assets/0000-0099/0016.3Sum Closest/README_EN.md @@ -0,0 +1,160 @@ +# [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest) + + + +## Description + +

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

+ +

 

+

Example 1:

+ +
+Input: nums = [-1,2,1,-4], target = 1
+Output: 2
+Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= nums.length <= 10^3
  • +
  • -10^3 <= nums[i] <= 10^3
  • +
  • -10^4 <= target <= 10^4
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def threeSumClosest(self, nums: List[int], target: int) -> int: + def twoSumClosest(nums, start, end, target): + res = 0 + diff = 10000 + while start < end: + val = nums[start] + nums[end] + if val == target: + return val + if abs(val - target) < diff: + res = val + diff = abs(val - target) + if val < target: + start += 1 + else: + end -= 1 + return res + + nums.sort() + res, n = 0, len(nums) + diff = 10000 + for i in range(n - 2): + t = twoSumClosest(nums, i + 1, n - 1, target - nums[i]) + if abs(nums[i] + t - target) < diff: + res = nums[i] + t + diff = abs(nums[i] + t - target) + return res +``` + +### **Java** + +```java +class Solution { + public int threeSumClosest(int[] nums, int target) { + Arrays.sort(nums); + int res = 0; + int n = nums.length; + int diff = Integer.MAX_VALUE; + for (int i = 0; i < n - 2; ++i) { + int t = twoSumClosest(nums, i + 1, n - 1, target - nums[i]); + if (Math.abs(nums[i] + t - target) < diff) { + res = nums[i] + t; + diff = Math.abs(nums[i] + t - target); + } + } + return res; + } + + private int twoSumClosest(int[] nums, int start, int end, int target) { + int res = 0; + int diff = Integer.MAX_VALUE; + while (start < end) { + int val = nums[start] + nums[end]; + if (val == target) { + return val; + } + if (Math.abs(val - target) < diff) { + res = val; + diff = Math.abs(val - target); + } + if (val < target) { + ++start; + } else { + --end; + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function (nums, target) { + let len = nums.length; + nums.sort((a, b) => a - b); + let diff = Infinity; + let res; + for (let i = 0; i < len - 2; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + let left = i + 1, right = len - 1; + let cur = nums[i] + nums[i + 1] + nums[i + 2]; + if (cur > target) { + let newDiff = Math.abs((cur - target)) + if (newDiff < diff) { + diff = newDiff; + res = cur; + } + break; + } + while (left < right) { + cur = nums[i] + nums[left] + nums[right]; + if (cur === target) return target; + let newDiff = Math.abs((cur - target)) + if (newDiff < diff) { + diff = newDiff; + res = cur; + } + if (cur < target) { + while (nums[left] === nums[left + 1]) left++; + left++; + continue; + } else { + while (nums[right] === nums[right - 1]) right--; + right--; + continue; + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md b/assets/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md new file mode 100644 index 00000000..e5a9a0d4 --- /dev/null +++ b/assets/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md @@ -0,0 +1,111 @@ +# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number) + + + +## Description + +

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

+ +

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

+ +

+ +

 

+

Example 1:

+ +
+Input: digits = "23"
+Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
+
+ +

Example 2:

+ +
+Input: digits = ""
+Output: []
+
+ +

Example 3:

+ +
+Input: digits = "2"
+Output: ["a","b","c"]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= digits.length <= 4
  • +
  • digits[i] is a digit in the range ['2', '9'].
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + n = len(digits) + if n == 0: + return [] + chars = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] + strs = [chars[int(d) - 2] for d in digits] + res = [] + for s in strs: + if not res: + res = list(s) + else: + cache = [] + for item in res: + for letter in s: + cache.append(item + letter) + res = cache + return res +``` + +### **Java** + +```java +class Solution { + public List letterCombinations(String digits) { + int n; + if ((n = digits.length()) == 0) return Collections.emptyList(); + List chars = Arrays.asList("abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"); + + List strs = new ArrayList<>(); + for (char c : digits.toCharArray()) { + strs.add(chars.get(c - '0' - 2)); + } + List res = new ArrayList<>(); + for (String str : strs) { + if (res.size() == 0) { + for (char c : str.toCharArray()) { + res.add(String.valueOf(c)); + } + } else { + List cache = new ArrayList<>(); + for (String item : res) { + for (char c : str.toCharArray()) { + cache.add(item + String.valueOf(c)); + } + } + res = cache; + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0017.Letter Combinations of a Phone Number/images/17_telephone_keypad.png b/assets/0000-0099/0017.Letter Combinations of a Phone Number/images/17_telephone_keypad.png new file mode 100644 index 00000000..ef7a0bff Binary files /dev/null and b/assets/0000-0099/0017.Letter Combinations of a Phone Number/images/17_telephone_keypad.png differ diff --git a/assets/0000-0099/0018.4Sum/README_EN.md b/assets/0000-0099/0018.4Sum/README_EN.md new file mode 100644 index 00000000..2f42f819 --- /dev/null +++ b/assets/0000-0099/0018.4Sum/README_EN.md @@ -0,0 +1,175 @@ +# [18. 4Sum](https://leetcode.com/problems/4sum) + + + +## Description + +

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

+ +
    +
  • 0 <= a, b, c, d < n
  • +
  • a, b, c, and d are distinct.
  • +
  • nums[a] + nums[b] + nums[c] + nums[d] == target
  • +
+ +

You may return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,0,-1,0,-2,2], target = 0
+Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
+
+ +

Example 2:

+ +
+Input: nums = [2,2,2,2,2], target = 8
+Output: [[2,2,2,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -109 <= nums[i] <= 109
  • +
  • -109 <= target <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + res = [] + if nums is None or len(nums) < 4: + return res + n = len(nums) + nums.sort() + for i in range(n - 3): + if i > 0 and nums[i] == nums[i - 1]: + continue + for j in range(i + 1, n - 2): + if j > i + 1 and nums[j] == nums[j - 1]: + continue + p, q = j + 1, n - 1 + while p < q: + if p > j + 1 and nums[p] == nums[p - 1]: + p += 1 + continue + if q < n - 1 and nums[q] == nums[q + 1]: + q -= 1 + continue + t = nums[i] + nums[j] + nums[p] + nums[q] + if t == target: + res.append([nums[i], nums[j], nums[p], nums[q]]) + p += 1 + q -= 1 + elif t < target: + p += 1 + else: + q -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public List> fourSum(int[] nums, int target) { + int n; + if (nums == null || (n = (nums.length)) < 4) { + return Collections.emptyList(); + } + Arrays.sort(nums); + List> res = new ArrayList<>(); + for (int i = 0; i < n - 3; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < n - 2; ++j) { + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + int p = j + 1, q = n - 1; + while (p < q) { + if (p > j + 1 && nums[p] == nums[p - 1]) { + ++p; + continue; + } + if (q < n - 1 && nums[q] == nums[q + 1]) { + --q; + continue; + } + int t = nums[i] + nums[j] + nums[p] + nums[q]; + if (t == target) { + res.add(Arrays.asList(nums[i], nums[j], nums[p], nums[q])); + ++p; + --q; + } else if (t < target) { + ++p; + } else { + --q; + } + } + } + } + return res; + } +} +``` +### **JavaScript** +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function (nums, target) { + let len = nums.length; + let res = []; + if (len < 4) return []; + nums.sort((a, b) => a - b); + for (i = 0; i < len - 3; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + if (nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 3] < target) continue; + if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break; + for (j = i + 1; j < len - 2; j++) { + if (j > i + 1 && nums[j] === nums[j - 1]) continue; + let left = j + 1, right = len - 1; + while (left < right) { + if (nums[i] + nums[j] + nums[left] + nums[right] === target) { + res.push([nums[i], nums[j], nums[left], nums[right]]); + while (nums[left] === nums[left + 1]) left++; + left++; + while (nums[right] === nums[right - 1]) right--; + right--; + continue; + } else if (nums[i] + nums[j] + nums[left] + nums[right] > target) { + right--; + continue; + } else { + left++; + continue; + } + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0019.Remove Nth Node From End of List/README_EN.md b/assets/0000-0099/0019.Remove Nth Node From End of List/README_EN.md new file mode 100644 index 00000000..a2d91958 --- /dev/null +++ b/assets/0000-0099/0019.Remove Nth Node From End of List/README_EN.md @@ -0,0 +1,223 @@ +# [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list) + + + +## Description + +

Given the head of a linked list, remove the nth node from the end of the list and return its head.

+ +

Follow up: Could you do this in one pass?

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5], n = 2
+Output: [1,2,3,5]
+
+ +

Example 2:

+ +
+Input: head = [1], n = 1
+Output: []
+
+ +

Example 3:

+ +
+Input: head = [1,2], n = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is sz.
  • +
  • 1 <= sz <= 30
  • +
  • 0 <= Node.val <= 100
  • +
  • 1 <= n <= sz
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + dummy = ListNode(next=head) + fast = slow = dummy + for _ in range(n): + fast = fast.next + while fast.next: + slow, fast = slow.next, fast.next + slow.next = slow.next.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(0, head); + ListNode fast = dummy, slow = dummy; + while (n-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + slow.next = slow.next.next; + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode* dummy = new ListNode(0, head); + ListNode* fast = dummy; + ListNode* slow = dummy; + while (n--) { + fast = fast->next; + } + while (fast->next) { + slow = slow->next; + fast = fast->next; + } + slow->next = slow->next->next; + return dummy->next; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNthFromEnd(head *ListNode, n int) *ListNode { + dummy := &ListNode{0, head} + fast := dummy + slow := dummy + for n > 0 { + fast = fast.Next + n -= 1 + } + for fast.Next != nil { + slow = slow.Next + fast = fast.Next + } + slow.Next = slow.Next.Next + return dummy.Next +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function(head, n) { + const dummy = new ListNode(0, head); + let fast = dummy, slow = dummy; + while (n--) { + fast = fast.next; + } + while (fast.next) { + slow = slow.next; + fast = fast.next; + } + slow.next = slow.next.next; + return dummy.next; +}; +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @param {Integer} n +# @return {ListNode} +def remove_nth_from_end(head, n) + dummy = ListNode.new(0, head) + fast = slow = dummy + while n > 0 + fast = fast.next + n -= 1 + end + while fast.next + slow = slow.next + fast = fast.next + end + slow.next = slow.next.next + return dummy.next +end +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0019.Remove Nth Node From End of List/images/remove_ex1.jpg b/assets/0000-0099/0019.Remove Nth Node From End of List/images/remove_ex1.jpg new file mode 100644 index 00000000..e3532a17 Binary files /dev/null and b/assets/0000-0099/0019.Remove Nth Node From End of List/images/remove_ex1.jpg differ diff --git a/assets/0000-0099/0020.Valid Parentheses/README_EN.md b/assets/0000-0099/0020.Valid Parentheses/README_EN.md new file mode 100644 index 00000000..3bea40a9 --- /dev/null +++ b/assets/0000-0099/0020.Valid Parentheses/README_EN.md @@ -0,0 +1,128 @@ +# [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses) + + + +## Description + +

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

+ +

An input string is valid if:

+ +
    +
  1. Open brackets must be closed by the same type of brackets.
  2. +
  3. Open brackets must be closed in the correct order.
  4. +
+ +

 

+

Example 1:

+ +
+Input: s = "()"
+Output: true
+
+ +

Example 2:

+ +
+Input: s = "()[]{}"
+Output: true
+
+ +

Example 3:

+ +
+Input: s = "(]"
+Output: false
+
+ +

Example 4:

+ +
+Input: s = "([)]"
+Output: false
+
+ +

Example 5:

+ +
+Input: s = "{[]}"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of parentheses only '()[]{}'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isValid(self, s: str) -> bool: + q = [] + parentheses = {'()', '[]', '{}'} + for ch in s: + if ch in '([{': + q.append(ch) + elif not q or q.pop() + ch not in parentheses: + return False + return not q +``` + +### **Java** + +```java +class Solution { + public boolean isValid(String s) { + char[] chars = s.toCharArray(); + Deque q = new ArrayDeque<>(); + for (char ch : chars) { + boolean left = ch == '(' || ch == '[' || ch == '{'; + if (left) q.push(ch); + else if (q.isEmpty() || !match(q.pop(), ch)) return false; + } + return q.isEmpty(); + } + + private boolean match(char l, char r) { + return (l == '(' && r == ')') || (l == '{' && r == '}') || (l == '[' && r == ']'); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isValid(string s) { + stack q; + for (int i = 0, n = s.length(); i < n; ++i) { + if (s[i] == '{' || s[i] == '[' || s[i] == '(') q.push(s[i]); + else if (q.empty() || !match(q.top(), s[i])) return false; + else q.pop(); + } + return q.empty(); + } +private: + bool match(char l, char r) { + return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0021.Merge Two Sorted Lists/README_EN.md b/assets/0000-0099/0021.Merge Two Sorted Lists/README_EN.md new file mode 100644 index 00000000..1403c1b1 --- /dev/null +++ b/assets/0000-0099/0021.Merge Two Sorted Lists/README_EN.md @@ -0,0 +1,273 @@ +# [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists) + + + +## Description + +

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

+ +

 

+

Example 1:

+ +
+Input: l1 = [1,2,4], l2 = [1,3,4]
+Output: [1,1,2,3,4,4]
+
+ +

Example 2:

+ +
+Input: l1 = [], l2 = []
+Output: []
+
+ +

Example 3:

+ +
+Input: l1 = [], l2 = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both lists is in the range [0, 50].
  • +
  • -100 <= Node.val <= 100
  • +
  • Both l1 and l2 are sorted in non-decreasing order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + cur = dummy + while l1 and l2: + if l1.val <= l2.val: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + cur.next = l1 or l2 + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + ListNode* cur = dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + cur->next = l1; + l1 = l1->next; + } else { + cur->next = l2; + l2 = l2->next; + } + cur = cur->next; + } + cur->next = l1 ? l1 : l2; + return dummy->next; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + cur := dummy + for l1 != nil && l2 != nil { + if l1.Val <= l2.Val { + cur.Next = l1 + l1 = l1.Next + } else { + cur.Next = l2 + l2 = l2.Next + } + cur = cur.Next + } + if l1 != nil { + cur.Next = l1 + } else if l2 != nil { + cur.Next = l2 + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def merge_two_lists(l1, l2) + dummy = ListNode.new() + cur = dummy + while l1 && l2 + if l1.val <= l2.val + cur.next = l1 + l1 = l1.next + else + cur.next = l2 + l2 = l2.next + end + cur = cur.next + end + cur.next = l1 || l2 + dummy.next +end +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0021.Merge Two Sorted Lists/images/merge_ex1.jpg b/assets/0000-0099/0021.Merge Two Sorted Lists/images/merge_ex1.jpg new file mode 100644 index 00000000..c2769aa9 Binary files /dev/null and b/assets/0000-0099/0021.Merge Two Sorted Lists/images/merge_ex1.jpg differ diff --git a/assets/0000-0099/0022.Generate Parentheses/README_EN.md b/assets/0000-0099/0022.Generate Parentheses/README_EN.md new file mode 100644 index 00000000..156f1c2e --- /dev/null +++ b/assets/0000-0099/0022.Generate Parentheses/README_EN.md @@ -0,0 +1,148 @@ +# [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses) + + + +## Description + +

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

+ +

 

+

Example 1:

+
Input: n = 3
+Output: ["((()))","(()())","(())()","()(())","()()()"]
+

Example 2:

+
Input: n = 1
+Output: ["()"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + def dfs(ans, l, r, n): + if len(ans) == (n << 1): + self.res.append(ans) + return + if l < n: + dfs(ans + '(', l + 1, r, n) + if r < l: + dfs(ans + ')', l, r + 1, n) + + self.res = [] + dfs('', 0, 0, n) + return self.res +``` + +### **Java** + +```java +class Solution { + public List generateParenthesis(int n) { + List res = new ArrayList<>(); + dfs(res, "", 0, 0, n); + return res; + } + + private void dfs(List res, String ans, int l, int r, int n) { + if (ans.length() == (n << 1)) { + res.add(ans); + return; + } + if (l < n) { + dfs(res, ans + "(", l + 1, r, n); + } + if (r < l) { + dfs(res, ans + ")", l, r + 1, n); + } + } +} +``` + +### **TypeScript** + +```ts +function generateParenthesis(n: number): string[] { + let ans = []; + dfs(n, 0, 0, '', ans); + return ans; +}; + +function dfs(n: number, left: number, right: number, str: string, ans: string[]) { + if (str.length == 2 * n) { + ans.push(str); + return; + } + if (left < n) { + dfs(n, left + 1, right, str + '(', ans); + } + if (right < left) { + dfs(n, left, right + 1, str + ')', ans); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector generateParenthesis(int n) { + vector res; + dfs(res, "", 0, 0, n); + return res; + } + +private: + void dfs(vector& res, string ans, int l, int r, int n) { + if (ans.size() == (n << 1)) { + res.push_back(ans); + return; + } + if (l < n) dfs(res, ans + "(", l + 1, r, n); + if (r < l) dfs(res, ans + ")", l, r + 1, n); + } +}; +``` + +### **Go** + +```go +func generateParenthesis(n int) []string { + res := new([]string) + dfs(res, "", 0, 0, n) + return *res +} + +func dfs(res *[]string, ans string, l, r, n int) { + if len(ans) == (n << 1) { + *res = append(*res, ans) + return + } + if l < n { + dfs(res, ans+"(", l+1, r, n) + } + if r < l { + dfs(res, ans+")", l, r+1, n) + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0023.Merge k Sorted Lists/README_EN.md b/assets/0000-0099/0023.Merge k Sorted Lists/README_EN.md new file mode 100644 index 00000000..8faf0ff9 --- /dev/null +++ b/assets/0000-0099/0023.Merge k Sorted Lists/README_EN.md @@ -0,0 +1,358 @@ +# [23. Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists) + + + +## Description + +

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

+ +

Merge all the linked-lists into one sorted linked-list and return it.

+ +

 

+

Example 1:

+ +
+Input: lists = [[1,4,5],[1,3,4],[2,6]]
+Output: [1,1,2,3,4,4,5,6]
+Explanation: The linked-lists are:
+[
+  1->4->5,
+  1->3->4,
+  2->6
+]
+merging them into one sorted list:
+1->1->2->3->4->4->5->6
+
+ +

Example 2:

+ +
+Input: lists = []
+Output: []
+
+ +

Example 3:

+ +
+Input: lists = [[]]
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • k == lists.length
  • +
  • 0 <= k <= 10^4
  • +
  • 0 <= lists[i].length <= 500
  • +
  • -10^4 <= lists[i][j] <= 10^4
  • +
  • lists[i] is sorted in ascending order.
  • +
  • The sum of lists[i].length won't exceed 10^4.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeKLists(self, lists: List[ListNode]) -> ListNode: + if not lists: + return None + n = len(lists) + for i in range(1, n): + lists[i] = self.mergeTwoLists(lists[i - 1], lists[i]) + return lists[n - 1] + + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + cur = dummy + while l1 and l2: + if l1.val <= l2.val: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + cur.next = l1 or l2 + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + int n; + if (lists == null || (n = lists.length) == 0) { + return null; + } + for (int i = 1; i < n; ++i) { + lists[i] = mergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; + } + + private ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + int n = lists.size(); + if (n == 0) { + return nullptr; + } + for (int i = 1; i < n; ++i) { + lists[i] = mergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; + } + +private: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + ListNode* cur = dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + cur->next = l1; + l1 = l1->next; + } else { + cur->next = l2; + l2 = l2->next; + } + cur = cur->next; + } + cur->next = l1 ? l1 : l2; + return dummy->next; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeKLists(lists []*ListNode) *ListNode { + n := len(lists) + if n == 0 { + return nil + } + for i := 1; i < n; i++ { + lists[i] = mergeTwoLists(lists[i-1], lists[i]) + } + return lists[n-1] +} + + func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + cur := dummy + for l1 != nil && l2 != nil { + if l1.Val <= l2.Val { + cur.Next = l1 + l1 = l1.Next + } else { + cur.Next = l2 + l2 = l2.Next + } + cur = cur.Next + } + if l1 != nil { + cur.Next = l1 + } else if l2 != nil { + cur.Next = l2 + } + return dummy.Next +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode[]} lists + * @return {ListNode} + */ +var mergeKLists = function(lists) { + const n = lists.length; + if (n == 0) { + return null; + } + for (let i = 1; i < n; ++i) { + lists[i] = mergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; +}; + +function mergeTwoLists(l1, l2) { + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode[]} lists +# @return {ListNode} +def merge_k_lists(lists) + n = lists.length + i = 1 + while i < n + lists[i] = merge_two_lists(lists[i - 1], lists[i]) + i += 1 + end + lists[n - 1] +end + +def merge_two_lists(l1, l2) + dummy = ListNode.new() + cur = dummy + while l1 && l2 + if l1.val <= l2.val + cur.next = l1 + l1 = l1.next + else + cur.next = l2 + l2 = l2.next + end + cur = cur.next + end + cur.next = l1 || l2 + dummy.next +end +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeKLists(ListNode[] lists) { + int n = lists.Length; + if (n == 0) { + return null; + } + for (int i = 1; i < n; ++i) { + lists[i] = MergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; + } + + private ListNode MergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0024.Swap Nodes in Pairs/README_EN.md b/assets/0000-0099/0024.Swap Nodes in Pairs/README_EN.md new file mode 100644 index 00000000..2ee14918 --- /dev/null +++ b/assets/0000-0099/0024.Swap Nodes in Pairs/README_EN.md @@ -0,0 +1,218 @@ +# [24. Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs) + + + +## Description + +

Given a linked list, swap every two adjacent nodes and return its head.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4]
+Output: [2,1,4,3]
+
+ +

Example 2:

+ +
+Input: head = []
+Output: []
+
+ +

Example 3:

+ +
+Input: head = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 100].
  • +
  • 0 <= Node.val <= 100
  • +
+ +

 

+Follow up: Can you solve the problem without modifying the values in the list's nodes? (i.e., Only nodes themselves may be changed.) + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + dummy = ListNode(next=head) + pre, cur = dummy, head + while cur and cur.next: + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre, cur = cur, cur.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy, cur = head; + while (cur != null && cur.next != null) { + ListNode t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; + } + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + const dummy = new ListNode(0, head); + let pre = dummy; + let cur = head; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; + } + return dummy.next; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode *dummy = new ListNode(0, head); + ListNode *pre = dummy, *cur = head; + while (cur != nullptr && cur->next != nullptr) { + ListNode *t = cur->next; + cur->next = t->next; + t->next = cur; + pre->next = t; + pre = cur; + cur = cur->next; + } + return dummy->next; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func swapPairs(head *ListNode) *ListNode { + dummy := &ListNode{0, head} + pre, cur := dummy, head + for cur != nil && cur.Next != nil { + t := cur.Next + cur.Next = t.Next + t.Next = cur + pre.Next = t + pre = cur + cur = cur.Next + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @return {ListNode} +def swap_pairs(head) + dummy = ListNode.new(0, head) + pre = dummy + cur = head + while !cur.nil? && !cur.next.nil? + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre = cur + cur = cur.next + end + dummy.next +end +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0024.Swap Nodes in Pairs/images/swap_ex1.jpg b/assets/0000-0099/0024.Swap Nodes in Pairs/images/swap_ex1.jpg new file mode 100644 index 00000000..6120aad8 Binary files /dev/null and b/assets/0000-0099/0024.Swap Nodes in Pairs/images/swap_ex1.jpg differ diff --git a/assets/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md b/assets/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md new file mode 100644 index 00000000..441b8b3a --- /dev/null +++ b/assets/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md @@ -0,0 +1,305 @@ +# [25. Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group) + + + +## Description + +

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

+ +

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

+ +

Follow up:

+ +
    +
  • Could you solve the problem in O(1) extra memory space?
  • +
  • You may not alter the values in the list's nodes, only nodes itself may be changed.
  • +
+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5], k = 2
+Output: [2,1,4,3,5]
+
+ +

Example 2:

+ +
+Input: head = [1,2,3,4,5], k = 3
+Output: [3,2,1,4,5]
+
+ +

Example 3:

+ +
+Input: head = [1,2,3,4,5], k = 1
+Output: [1,2,3,4,5]
+
+ +

Example 4:

+ +
+Input: head = [1], k = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range sz.
  • +
  • 1 <= sz <= 5000
  • +
  • 0 <= Node.val <= 1000
  • +
  • 1 <= k <= sz
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseKGroup(self, head: ListNode, k: int) -> ListNode: + def reverseList(head): + pre, p = None, head + while p: + q = p.next + p.next = pre + pre = p + p = q + return pre + + dummy = ListNode(next=head) + pre = cur = dummy + while cur.next: + for _ in range(k): + cur = cur.next + if cur is None: + return dummy.next + t = cur.next + cur.next = None + start = pre.next + pre.next = reverseList(start) + start.next = t + pre = start + cur = pre + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy, cur = dummy; + while (cur.next != null) { + for (int i = 0; i < k && cur != null; ++i) { + cur = cur.next; + } + if (cur == null) { + return dummy.next; + } + ListNode t = cur.next; + cur.next = null; + ListNode start = pre.next; + pre.next = reverseList(start); + start.next = t; + pre = start; + cur = pre; + } + return dummy.next; + } + + private ListNode reverseList(ListNode head) { + ListNode pre = null, p = head; + while (p != null) { + ListNode q = p.next; + p.next = pre; + pre = p; + p = q; + } + return pre; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseKGroup(head: ListNode | null, k: number): ListNode | null { + let dummy = new ListNode(0, head); + let pre = dummy; + // pre->head-> ... ->tail-> next + while (head != null) { + let tail = pre; + for (let i=0; i next -> ... -> tail -> pre + while (pre != tail) { + let t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + return [tail, head] +} +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + dummy := &ListNode{0, head} + pre := dummy + cur := dummy + for cur.Next != nil { + for i := 0; i < k && cur != nil; i++ { + cur = cur.Next + } + if cur == nil { + return dummy.Next + } + t := cur.Next + cur.Next = nil + start := pre.Next + pre.Next = reverseList(start) + start.Next = t + pre = start + cur = pre + } + return dummy.Next +} + +func reverseList(head *ListNode) *ListNode { + if head == nil ||head.Next == nil { + return head + } + dummyHead := &ListNode{} + cur := head + for cur != nil { + tmp := cur.Next + cur.Next = dummyHead.Next + dummyHead.Next = cur + cur = tmp + } + return dummyHead.Next +} +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseKGroup(ListNode head, int k) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy, cur = dummy; + while (cur.next != null) + { + for (int i = 0; i < k && cur != null; ++i) + { + cur = cur.next; + } + if (cur == null) + { + return dummy.next; + } + ListNode t = cur.next; + cur.next = null; + ListNode start = pre.next; + pre.next = ReverseList(start); + start.next = t; + pre = start; + cur = pre; + } + return dummy.next; + } + + private ListNode ReverseList(ListNode head) { + ListNode pre = null, p = head; + while (p != null) + { + ListNode q = p.next; + p.next = pre; + pre = p; + p = q; + } + return pre; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0025.Reverse Nodes in k-Group/images/reverse_ex1.jpg b/assets/0000-0099/0025.Reverse Nodes in k-Group/images/reverse_ex1.jpg new file mode 100644 index 00000000..18896bdc Binary files /dev/null and b/assets/0000-0099/0025.Reverse Nodes in k-Group/images/reverse_ex1.jpg differ diff --git a/assets/0000-0099/0025.Reverse Nodes in k-Group/images/reverse_ex2.jpg b/assets/0000-0099/0025.Reverse Nodes in k-Group/images/reverse_ex2.jpg new file mode 100644 index 00000000..6f3ef0e7 Binary files /dev/null and b/assets/0000-0099/0025.Reverse Nodes in k-Group/images/reverse_ex2.jpg differ diff --git a/assets/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md b/assets/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md new file mode 100644 index 00000000..a4bafd55 --- /dev/null +++ b/assets/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md @@ -0,0 +1,169 @@ +# [26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array) + + + +## Description + +

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

+ +

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

+ +

Clarification:

+ +

Confused why the returned value is an integer but your answer is an array?

+ +

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

+ +

Internally you can think of this:

+ +
+// nums is passed in by reference. (i.e., without making a copy)
+int len = removeDuplicates(nums);
+
+// any modification to nums in your function would be known by the caller.
+// using the length returned by your function, it prints the first len elements.
+for (int i = 0; i < len; i++) {
+    print(nums[i]);
+}
+ +

 

+

Example 1:

+ +
+Input: nums = [1,1,2]
+Output: 2, nums = [1,2]
+Explanation: Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.
+
+ +

Example 2:

+ +
+Input: nums = [0,0,1,1,1,2,2,3,3,4]
+Output: 5, nums = [0,1,2,3,4]
+Explanation: Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 3 * 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + cnt, n = 0, len(nums) + for i in range(1, n): + if nums[i] == nums[i - 1]: + cnt += 1 + else: + nums[i - cnt] = nums[i] + return n - cnt +``` + +### **Java** + +```java +class Solution { + public int removeDuplicates(int[] nums) { + int cnt = 0, n = nums.length; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function (nums) { + let cnt = 0; + const n = nums.length; + for (let i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; +}; +``` + +### **Go** + +```go +func removeDuplicates(nums []int) int { + cnt := 0 + n := len(nums) + for i := 1; i < n; i++ { + if nums[i] == nums[i - 1] { + cnt++ + } else { + nums[i - cnt] = nums[i] + } + } + return n - cnt +} +``` + +### **C++** + +```cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + int cnt = 0, n = nums.size(); + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +}; +``` + +### **C#** + +```cs +public class Solution { + public int RemoveDuplicates(int[] nums) { + int cnt = 0; + int n = nums.Length; + for (int i = 1; i < n; ++i) + { + if (nums[i] == nums[i - 1]) + { + ++cnt; + } + else + { + nums[i - cnt] = nums[i]; + } + } + return n - cnt; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0027.Remove Element/README_EN.md b/assets/0000-0099/0027.Remove Element/README_EN.md new file mode 100644 index 00000000..0f916364 --- /dev/null +++ b/assets/0000-0099/0027.Remove Element/README_EN.md @@ -0,0 +1,149 @@ +# [27. Remove Element](https://leetcode.com/problems/remove-element) + + + +## Description + +

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

+ +

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

+ +

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

+ +

Clarification:

+ +

Confused why the returned value is an integer but your answer is an array?

+ +

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

+ +

Internally you can think of this:

+ +
+// nums is passed in by reference. (i.e., without making a copy)
+int len = removeElement(nums, val);
+
+// any modification to nums in your function would be known by the caller.
+// using the length returned by your function, it prints the first len elements.
+for (int i = 0; i < len; i++) {
+    print(nums[i]);
+}
+ +

 

+

Example 1:

+ +
+Input: nums = [3,2,2,3], val = 3
+Output: 2, nums = [2,2]
+Explanation: Your function should return length = 2, with the first two elements of nums being 2.
+It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.
+
+ +

Example 2:

+ +
+Input: nums = [0,1,2,2,3,0,4,2], val = 2
+Output: 5, nums = [0,1,4,0,3]
+Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 50
  • +
  • 0 <= val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + cnt, n = 0, len(nums) + for i in range(n): + if nums[i] == val: + cnt += 1 + else: + nums[i - cnt] = nums[i] + return n - cnt +``` + +### **Java** + +```java +class Solution { + public int removeElement(int[] nums, int val) { + int cnt = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + if (nums[i] == val) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int removeElement(vector& nums, int val) { + int cnt = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + if (nums[i] == val) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function (nums, val) { + let cnt = 0; + const n = nums.length; + for (let i = 0; i < n; ++i) { + if (nums[i] == val) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; +}; +``` + +### **Go** + +```go +func removeElement(nums []int, val int) int { + cnt, n := 0, len(nums) + for i := 0; i < n; i++ { + if (nums[i] == val) { + cnt++ + } else { + nums[i - cnt] = nums[i] + } + } + return n - cnt +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0028.Implement strStr()/README_EN.md b/assets/0000-0099/0028.Implement strStr()/README_EN.md new file mode 100644 index 00000000..f2921f48 --- /dev/null +++ b/assets/0000-0099/0028.Implement strStr()/README_EN.md @@ -0,0 +1,59 @@ +# [28. Implement strStr()](https://leetcode.com/problems/implement-strstr) + + + +## Description + +

Implement strStr().

+ +

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

+ +

Clarification:

+ +

What should we return when needle is an empty string? This is a great question to ask during an interview.

+ +

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

+ +

 

+

Example 1:

+
Input: haystack = "hello", needle = "ll"
+Output: 2
+

Example 2:

+
Input: haystack = "aaaaa", needle = "bba"
+Output: -1
+

Example 3:

+
Input: haystack = "", needle = ""
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 0 <= haystack.length, needle.length <= 5 * 104
  • +
  • haystack and needle consist of only lower-case English characters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0029.Divide Two Integers/README_EN.md b/assets/0000-0099/0029.Divide Two Integers/README_EN.md new file mode 100644 index 00000000..03ffbca0 --- /dev/null +++ b/assets/0000-0099/0029.Divide Two Integers/README_EN.md @@ -0,0 +1,77 @@ +# [29. Divide Two Integers](https://leetcode.com/problems/divide-two-integers) + + + +## Description + +

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.

+ +

Return the quotient after dividing dividend by divisor.

+ +

The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

+ +

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.

+ +

 

+

Example 1:

+ +
+Input: dividend = 10, divisor = 3
+Output: 3
+Explanation: 10/3 = truncate(3.33333..) = 3.
+
+ +

Example 2:

+ +
+Input: dividend = 7, divisor = -3
+Output: -2
+Explanation: 7/-3 = truncate(-2.33333..) = -2.
+
+ +

Example 3:

+ +
+Input: dividend = 0, divisor = 1
+Output: 0
+
+ +

Example 4:

+ +
+Input: dividend = 1, divisor = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= dividend, divisor <= 231 - 1
  • +
  • divisor != 0
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md b/assets/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md new file mode 100644 index 00000000..036522ea --- /dev/null +++ b/assets/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md @@ -0,0 +1,69 @@ +# [30. Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words) + + + +## Description + +

You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.

+ +

You can return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: s = "barfoothefoobarman", words = ["foo","bar"]
+Output: [0,9]
+Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
+The output order does not matter, returning [9,0] is fine too.
+
+ +

Example 2:

+ +
+Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
+Output: []
+
+ +

Example 3:

+ +
+Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
+Output: [6,9,12]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lower-case English letters.
  • +
  • 1 <= words.length <= 5000
  • +
  • 1 <= words[i].length <= 30
  • +
  • words[i] consists of lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0031.Next Permutation/README_EN.md b/assets/0000-0099/0031.Next Permutation/README_EN.md new file mode 100644 index 00000000..c6d869be --- /dev/null +++ b/assets/0000-0099/0031.Next Permutation/README_EN.md @@ -0,0 +1,58 @@ +# [31. Next Permutation](https://leetcode.com/problems/next-permutation) + + + +## Description + +

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

+ +

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

+ +

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

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: [1,3,2]
+

Example 2:

+
Input: nums = [3,2,1]
+Output: [1,2,3]
+

Example 3:

+
Input: nums = [1,1,5]
+Output: [1,5,1]
+

Example 4:

+
Input: nums = [1]
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0032.Longest Valid Parentheses/README_EN.md b/assets/0000-0099/0032.Longest Valid Parentheses/README_EN.md new file mode 100644 index 00000000..35d330c9 --- /dev/null +++ b/assets/0000-0099/0032.Longest Valid Parentheses/README_EN.md @@ -0,0 +1,64 @@ +# [32. Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses) + + + +## Description + +

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

+ +

 

+

Example 1:

+ +
+Input: s = "(()"
+Output: 2
+Explanation: The longest valid parentheses substring is "()".
+
+ +

Example 2:

+ +
+Input: s = ")()())"
+Output: 4
+Explanation: The longest valid parentheses substring is "()()".
+
+ +

Example 3:

+ +
+Input: s = ""
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 3 * 104
  • +
  • s[i] is '(', or ')'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md b/assets/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md new file mode 100644 index 00000000..d6678007 --- /dev/null +++ b/assets/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md @@ -0,0 +1,146 @@ +# [33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array) + + + +## Description + +

There is an integer array nums sorted in ascending order (with distinct values).

+ +

Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

+ +

Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

+ +

 

+

Example 1:

+
Input: nums = [4,5,6,7,0,1,2], target = 0
+Output: 4
+

Example 2:

+
Input: nums = [4,5,6,7,0,1,2], target = 3
+Output: -1
+

Example 3:

+
Input: nums = [1], target = 0
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -104 <= nums[i] <= 104
  • +
  • All values of nums are unique.
  • +
  • nums is guaranteed to be rotated at some pivot.
  • +
  • -104 <= target <= 104
  • +
+ +

 

+Follow up: Can you achieve this in O(log n) time complexity? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def search(self, nums: List[int], target: int) -> int: + l, r = 0, len(nums) - 1 + while l <= r: + mid = (l + r) >> 1 + if nums[mid] == target: + return mid + if nums[mid] > target: + if nums[mid] >= nums[r] and target < nums[l]: + l = mid + 1 + else: + r = mid - 1 + else: + if nums[mid] <= nums[l] and target > nums[r]: + r = mid - 1 + else: + l = mid + 1 + return -1 +``` + +### **Java** + +```java +class Solution { + public int search(int[] nums, int target) { + int l = 0, r = nums.length - 1; + while (l <= r) { + int mid = (l + r) >>> 1; + if (nums[mid] == target) return mid; + if (nums[mid] > target) { + if (nums[mid] >= nums[r] && target < nums[l]) l = mid + 1; + else r = mid - 1; + } else { + if (nums[mid] <= nums[l] && target > nums[r]) r = mid - 1; + else l = mid + 1; + } + } + return -1; + } +} +``` + +### **C++** + + + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int l = 0, r = nums.size() - 1; + while (l <= r) { + int mid = (l + r) >> 1; + if (nums[mid] == target) return mid; + if (nums[mid] > target) { + if (nums[mid] >= nums[r] && target < nums[l]) l = mid + 1; + else r = mid - 1; + } else { + if (nums[mid] <= nums[l] && target > nums[r]) r = mid - 1; + else l = mid + 1; + } + } + return -1; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + let l = 0, r = nums.length - 1; + if (l > r) return -1; + while (l <= r) { + let mid = l + Math.floor((r - l) / 2); + if (nums[mid] === target) return mid; + else if (nums[mid] <= nums[r] && target <= nums[r] && target >= nums[mid]) + l = mid + 1; + else if (nums[mid] >= nums[l] && target <= nums[mid] && target >= nums[l]) + r = mid - 1; + else if (nums[mid] >= nums[r]) + l = mid + 1; + else if (nums[mid] <= nums[l]) + r = mid - 1; + else return -1; + } + return -1; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md b/assets/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md new file mode 100644 index 00000000..f0eb3400 --- /dev/null +++ b/assets/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md @@ -0,0 +1,219 @@ +# [34. Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array) + + + +## Description + +

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

+ +

If target is not found in the array, return [-1, -1].

+ +

Follow up: Could you write an algorithm with O(log n) runtime complexity?

+ +

 

+

Example 1:

+
Input: nums = [5,7,7,8,8,10], target = 8
+Output: [3,4]
+

Example 2:

+
Input: nums = [5,7,7,8,8,10], target = 6
+Output: [-1,-1]
+

Example 3:

+
Input: nums = [], target = 0
+Output: [-1,-1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • nums is a non-decreasing array.
  • +
  • -109 <= target <= 109
  • +
+ + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + if len(nums) == 0: + return [-1, -1] + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + if nums[left] != target: + return [-1, -1] + l, right = left, len(nums) - 1 + while left < right: + mid = (left + right + 1) >> 1 + if nums[mid] <= target: + left = mid + else: + right = mid - 1 + return [l, left] +``` + +### **Java** + +```java +class Solution { + public int[] searchRange(int[] nums, int target) { + if (nums.length == 0) { + return new int[]{-1, -1}; + } + // find first position + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >>> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (nums[left] != target) { + return new int[]{-1, -1}; + } + int l = left; + + // find last position + right = nums.length - 1; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return new int[]{l, left}; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector searchRange(vector& nums, int target) { + if (nums.size() == 0) { + return vector{-1, -1}; + } + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (nums[left] != target) { + return vector{-1, -1}; + } + int l = left; + right = nums.size() - 1; + while (left < right) { + int mid = left + right + 1 >> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return vector{l, left}; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var searchRange = function(nums, target) { + if (nums.length == 0) { + return [-1, -1]; + } + let left = 0; + let right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (nums[left] != target) { + return [-1, -1]; + } + let l = left; + right = nums.length - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return [l, left]; +}; +``` + +### **Go** + +```go +func searchRange(nums []int, target int) []int { + if len(nums) == 0 { + return []int{-1, -1} + } + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= target { + right = mid + } else { + left = mid + 1 + } + } + if nums[left] != target { + return []int{-1, -1} + } + l := left + right = len(nums) - 1 + for left < right { + mid := (left + right + 1) >> 1 + if nums[mid] <= target { + left = mid + } else { + right = mid - 1 + } + } + return []int{l, left} +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0035.Search Insert Position/README_EN.md b/assets/0000-0099/0035.Search Insert Position/README_EN.md new file mode 100644 index 00000000..28fef636 --- /dev/null +++ b/assets/0000-0099/0035.Search Insert Position/README_EN.md @@ -0,0 +1,141 @@ +# [35. Search Insert Position](https://leetcode.com/problems/search-insert-position) + + + +## Description + +

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

+ +

 

+

Example 1:

+
Input: nums = [1,3,5,6], target = 5
+Output: 2
+

Example 2:

+
Input: nums = [1,3,5,6], target = 2
+Output: 1
+

Example 3:

+
Input: nums = [1,3,5,6], target = 7
+Output: 4
+

Example 4:

+
Input: nums = [1,3,5,6], target = 0
+Output: 0
+

Example 5:

+
Input: nums = [1], target = 0
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums contains distinct values sorted in ascending order.
  • +
  • -104 <= target <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int searchInsert(int[] nums, int target) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >>> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int searchInsert(vector& nums, int target) { + int left = 0, right = nums.size(); + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func searchInsert(nums []int, target int) int { + left, right := 0, len(nums) + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= target { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var searchInsert = function(nums, target) { + let left = 0; + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0036.Valid Sudoku/README_EN.md b/assets/0000-0099/0036.Valid Sudoku/README_EN.md new file mode 100644 index 00000000..8abffd18 --- /dev/null +++ b/assets/0000-0099/0036.Valid Sudoku/README_EN.md @@ -0,0 +1,210 @@ +# [36. Valid Sudoku](https://leetcode.com/problems/valid-sudoku) + + + +## Description + +

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

+ +
    +
  1. Each row must contain the digits 1-9 without repetition.
  2. +
  3. Each column must contain the digits 1-9 without repetition.
  4. +
  5. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
  6. +
+ +

Note:

+ +
    +
  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • +
  • Only the filled cells need to be validated according to the mentioned rules.
  • +
+ +

 

+

Example 1:

+ +
+Input: board = 
+[["5","3",".",".","7",".",".",".","."]
+,["6",".",".","1","9","5",".",".","."]
+,[".","9","8",".",".",".",".","6","."]
+,["8",".",".",".","6",".",".",".","3"]
+,["4",".",".","8",".","3",".",".","1"]
+,["7",".",".",".","2",".",".",".","6"]
+,[".","6",".",".",".",".","2","8","."]
+,[".",".",".","4","1","9",".",".","5"]
+,[".",".",".",".","8",".",".","7","9"]]
+Output: true
+
+ +

Example 2:

+ +
+Input: board = 
+[["8","3",".",".","7",".",".",".","."]
+,["6",".",".","1","9","5",".",".","."]
+,[".","9","8",".",".",".",".","6","."]
+,["8",".",".",".","6",".",".",".","3"]
+,["4",".",".","8",".","3",".",".","1"]
+,["7",".",".",".","2",".",".",".","6"]
+,[".","6",".",".",".",".","2","8","."]
+,[".",".",".","4","1","9",".",".","5"]
+,[".",".",".",".","8",".",".","7","9"]]
+Output: false
+Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
+
+ +

 

+

Constraints:

+ +
    +
  • board.length == 9
  • +
  • board[i].length == 9
  • +
  • board[i][j] is a digit or '.'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + row = [[False] * 9 for _ in range(9)] + col = [[False] * 9 for _ in range(9)] + sub = [[False] * 9 for _ in range(9)] + for i in range(9): + for j in range(9): + c = board[i][j] + if c == '.': + continue + num = int(c) - 1 + k = i // 3 * 3 + j // 3 + if row[i][num] or col[j][num] or sub[k][num]: + return False + row[i][num] = True + col[j][num] = True + sub[k][num] = True + return True +``` + +### **Java** + +```java +class Solution { + public boolean isValidSudoku(char[][] board) { + boolean[][] row = new boolean[9][9]; + boolean[][] col = new boolean[9][9]; + boolean[][] sub = new boolean[9][9]; + for (int i = 0; i < 9; ++i) { + for (int j = 0; j < 9; ++j) { + char c = board[i][j]; + if (c == '.') { + continue; + } + int num = c - '0' - 1; + int k = i / 3 * 3 + j / 3; + if (row[i][num] || col[j][num] || sub[k][num]) { + return false; + } + row[i][num] = true; + col[j][num] = true; + sub[k][num] = true; + } + } + return true; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isValidSudoku(vector>& board) { + vector> row(9, vector(9, false)); + vector> col(9, vector(9, false)); + vector> sub(9, vector(9, false)); + for (int i = 0; i < 9; ++i) { + for (int j = 0; j < 9; ++j) { + char c = board[i][j]; + if (c == '.') continue; + int num = c - '0' - 1; + int k = i / 3 * 3 + j / 3; + if (row[i][num] || col[j][num] || sub[k][num]) { + return false; + } + row[i][num] = true; + col[j][num] = true; + sub[k][num] = true; + } + } + return true; + } +}; +``` + +### **Go** + +```go +func isValidSudoku(board [][]byte) bool { + row, col, sub := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} + for i := 0; i < 9; i++ { + for j := 0; j < 9; j++ { + num := board[i][j] - byte('1') + if num < 0 || num > 9 { + continue + } + k := i/3*3 + j/3 + if row[i][num] || col[j][num] || sub[k][num] { + return false + } + row[i][num] = true + col[j][num] = true + sub[k][num] = true + } + } + return true +} +``` + +### **JavaScript** + +```js +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function(board) { + let row = [...Array(9)].map(() => Array(9).fill(false)); + let col = [...Array(9)].map(() => Array(9).fill(false)); + let sub = [...Array(9)].map(() => Array(9).fill(false)); + for (let i = 0; i < 9; ++i) { + for (let j = 0; j < 9; ++j) { + const num = board[i][j].charCodeAt() - '1'.charCodeAt(); + if (num < 0 || num > 9) { + continue; + } + const k = Math.floor(i / 3) * 3 + Math.floor(j / 3); + if (row[i][num] || col[j][num] || sub[k][num]) { + return false; + } + row[i][num] = true; + col[j][num] = true; + sub[k][num] = true; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0036.Valid Sudoku/images/250px-sudoku-by-l2g-20050714svg.png b/assets/0000-0099/0036.Valid Sudoku/images/250px-sudoku-by-l2g-20050714svg.png new file mode 100644 index 00000000..8cea21e9 Binary files /dev/null and b/assets/0000-0099/0036.Valid Sudoku/images/250px-sudoku-by-l2g-20050714svg.png differ diff --git a/assets/0000-0099/0037.Sudoku Solver/README_EN.md b/assets/0000-0099/0037.Sudoku Solver/README_EN.md new file mode 100644 index 00000000..7e5f1593 --- /dev/null +++ b/assets/0000-0099/0037.Sudoku Solver/README_EN.md @@ -0,0 +1,63 @@ +# [37. Sudoku Solver](https://leetcode.com/problems/sudoku-solver) + + + +## Description + +

Write a program to solve a Sudoku puzzle by filling the empty cells.

+ +

A sudoku solution must satisfy all of the following rules:

+ +
    +
  1. Each of the digits 1-9 must occur exactly once in each row.
  2. +
  3. Each of the digits 1-9 must occur exactly once in each column.
  4. +
  5. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
  6. +
+ +

The '.' character indicates empty cells.

+ +

 

+

Example 1:

+ +
+Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
+Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
+Explanation: The input board is shown above and the only valid solution is shown below:
+
+
+
+ +

 

+

Constraints:

+ +
    +
  • board.length == 9
  • +
  • board[i].length == 9
  • +
  • board[i][j] is a digit or '.'.
  • +
  • It is guaranteed that the input board has only one solution.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0037.Sudoku Solver/images/250px-sudoku-by-l2g-20050714_solutionsvg.png b/assets/0000-0099/0037.Sudoku Solver/images/250px-sudoku-by-l2g-20050714_solutionsvg.png new file mode 100644 index 00000000..f3a2ccd0 Binary files /dev/null and b/assets/0000-0099/0037.Sudoku Solver/images/250px-sudoku-by-l2g-20050714_solutionsvg.png differ diff --git a/assets/0000-0099/0037.Sudoku Solver/images/250px-sudoku-by-l2g-20050714svg.png b/assets/0000-0099/0037.Sudoku Solver/images/250px-sudoku-by-l2g-20050714svg.png new file mode 100644 index 00000000..8cea21e9 Binary files /dev/null and b/assets/0000-0099/0037.Sudoku Solver/images/250px-sudoku-by-l2g-20050714svg.png differ diff --git a/assets/0000-0099/0038.Count and Say/README_EN.md b/assets/0000-0099/0038.Count and Say/README_EN.md new file mode 100644 index 00000000..7d01e2ae --- /dev/null +++ b/assets/0000-0099/0038.Count and Say/README_EN.md @@ -0,0 +1,71 @@ +# [38. Count and Say](https://leetcode.com/problems/count-and-say) + + + +## Description + +

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

+ +
    +
  • countAndSay(1) = "1"
  • +
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.
  • +
+ +

To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

+ +

For example, the saying and conversion for digit string "3322251":

+ +

Given a positive integer n, return the nth term of the count-and-say sequence.

+ +

 

+

Example 1:

+ +
+Input: n = 1
+Output: "1"
+Explanation: This is the base case.
+
+ +

Example 2:

+ +
+Input: n = 4
+Output: "1211"
+Explanation:
+countAndSay(1) = "1"
+countAndSay(2) = say "1" = one 1 = "11"
+countAndSay(3) = say "11" = two 1's = "21"
+countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 30
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0038.Count and Say/images/countandsay.jpg b/assets/0000-0099/0038.Count and Say/images/countandsay.jpg new file mode 100644 index 00000000..84725c5f Binary files /dev/null and b/assets/0000-0099/0038.Count and Say/images/countandsay.jpg differ diff --git a/assets/0000-0099/0039.Combination Sum/README_EN.md b/assets/0000-0099/0039.Combination Sum/README_EN.md new file mode 100644 index 00000000..78352643 --- /dev/null +++ b/assets/0000-0099/0039.Combination Sum/README_EN.md @@ -0,0 +1,86 @@ +# [39. Combination Sum](https://leetcode.com/problems/combination-sum) + + + +## Description + +

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

+ +

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

+ +

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

+ +

 

+

Example 1:

+ +
+Input: candidates = [2,3,6,7], target = 7
+Output: [[2,2,3],[7]]
+Explanation:
+2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
+7 is a candidate, and 7 = 7.
+These are the only two combinations.
+
+ +

Example 2:

+ +
+Input: candidates = [2,3,5], target = 8
+Output: [[2,2,2,2],[2,3,3],[3,5]]
+
+ +

Example 3:

+ +
+Input: candidates = [2], target = 1
+Output: []
+
+ +

Example 4:

+ +
+Input: candidates = [1], target = 1
+Output: [[1]]
+
+ +

Example 5:

+ +
+Input: candidates = [1], target = 2
+Output: [[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= candidates.length <= 30
  • +
  • 1 <= candidates[i] <= 200
  • +
  • All elements of candidates are distinct.
  • +
  • 1 <= target <= 500
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0040.Combination Sum II/README_EN.md b/assets/0000-0099/0040.Combination Sum II/README_EN.md new file mode 100644 index 00000000..4d7dd212 --- /dev/null +++ b/assets/0000-0099/0040.Combination Sum II/README_EN.md @@ -0,0 +1,70 @@ +# [40. Combination Sum II](https://leetcode.com/problems/combination-sum-ii) + + + +## Description + +

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

+ +

Each number in candidates may only be used once in the combination.

+ +

Note: The solution set must not contain duplicate combinations.

+ +

 

+

Example 1:

+ +
+Input: candidates = [10,1,2,7,6,1,5], target = 8
+Output: 
+[
+[1,1,6],
+[1,2,5],
+[1,7],
+[2,6]
+]
+
+ +

Example 2:

+ +
+Input: candidates = [2,5,2,1,2], target = 5
+Output: 
+[
+[1,2,2],
+[5]
+]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= candidates.length <= 100
  • +
  • 1 <= candidates[i] <= 50
  • +
  • 1 <= target <= 30
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0041.First Missing Positive/README_EN.md b/assets/0000-0099/0041.First Missing Positive/README_EN.md new file mode 100644 index 00000000..b5de89d4 --- /dev/null +++ b/assets/0000-0099/0041.First Missing Positive/README_EN.md @@ -0,0 +1,54 @@ +# [41. First Missing Positive](https://leetcode.com/problems/first-missing-positive) + + + +## Description + +

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

+ +

 

+

Example 1:

+
Input: nums = [1,2,0]
+Output: 3
+

Example 2:

+
Input: nums = [3,4,-1,1]
+Output: 2
+

Example 3:

+
Input: nums = [7,8,9,11,12]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 300
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+

Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0042.Trapping Rain Water/README_EN.md b/assets/0000-0099/0042.Trapping Rain Water/README_EN.md new file mode 100644 index 00000000..41d34c39 --- /dev/null +++ b/assets/0000-0099/0042.Trapping Rain Water/README_EN.md @@ -0,0 +1,188 @@ +# [42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water) + + + +## Description + +

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

+ +

 

+

Example 1:

+ +
+Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
+Output: 6
+Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
+
+ +

Example 2:

+ +
+Input: height = [4,2,0,3,2,5]
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • n == height.length
  • +
  • 0 <= n <= 3 * 104
  • +
  • 0 <= height[i] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n < 3: + return 0 + + lmx, rmx = [height[0]] * n, [height[n - 1]] * n + for i in range(1, n): + lmx[i] = max(lmx[i - 1], height[i]) + rmx[n - 1 - i] = max(rmx[n - i], height[n - 1 - i]) + + res = 0 + for i in range(n): + res += min(lmx[i], rmx[i]) - height[i] + return res +``` + +### **Java** + +```java +class Solution { + public int trap(int[] height) { + int n = height.length; + if (n < 3) { + return 0; + } + + int[] lmx = new int[n]; + int[] rmx = new int[n]; + lmx[0] = height[0]; + rmx[n - 1] = height[n - 1]; + for (int i = 1; i < n; ++i) { + lmx[i] = Math.max(lmx[i - 1], height[i]); + rmx[n - 1 - i] = Math.max(rmx[n - i], height[n - i - 1]); + } + + int res = 0; + for (int i = 0; i < n; ++i) { + res += Math.min(lmx[i], rmx[i]) - height[i]; + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function trap(height: number[]): number { + let ans = 0; + let left = 0, right = height.length - 1; + let maxLeft = 0, maxRight = 0; + while (left < right) { + if (height[left] < height[right]) { + // move left + if (height[left] >= maxLeft) { + maxLeft = height[left]; + } else { + ans += (maxLeft - height[left]); + } + ++left; + } else { + // move right + if (height[right] >= maxRight) { + maxRight = height[right]; + } else { + ans += (maxRight - height[right]); + } + --right; + } + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + if (n < 3) { + return 0; + } + + vector lmx(n, height[0]); + vector rmx(n, height[n - 1]); + for (int i = 1; i < n; ++i) { + lmx[i] = max(lmx[i - 1], height[i]); + rmx[n - 1 - i] = max(rmx[n - i], height[n - 1 - i]); + } + + int res = 0; + for (int i = 0; i < n; ++i) { + res += min(lmx[i], rmx[i]) - height[i]; + } + return res; + } +}; +``` + +### **Go** + +```go +func trap(height []int) int { + n := len(height) + if n < 3 { + return 0 + } + + lmx, rmx := make([]int, n), make([]int, n) + lmx[0], rmx[n-1] = height[0], height[n-1] + for i := 1; i < n; i++ { + lmx[i] = max(lmx[i-1], height[i]) + rmx[n-1-i] = max(rmx[n-i], height[n-1-i]) + } + + res := 0 + for i := 0; i < n; i++ { + res += min(lmx[i], rmx[i]) - height[i] + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0042.Trapping Rain Water/images/rainwatertrap.png b/assets/0000-0099/0042.Trapping Rain Water/images/rainwatertrap.png new file mode 100644 index 00000000..521f3a6c Binary files /dev/null and b/assets/0000-0099/0042.Trapping Rain Water/images/rainwatertrap.png differ diff --git a/assets/0000-0099/0043.Multiply Strings/README_EN.md b/assets/0000-0099/0043.Multiply Strings/README_EN.md new file mode 100644 index 00000000..58acc6b8 --- /dev/null +++ b/assets/0000-0099/0043.Multiply Strings/README_EN.md @@ -0,0 +1,51 @@ +# [43. Multiply Strings](https://leetcode.com/problems/multiply-strings) + + + +## Description + +

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

+ +

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

+ +

 

+

Example 1:

+
Input: num1 = "2", num2 = "3"
+Output: "6"
+

Example 2:

+
Input: num1 = "123", num2 = "456"
+Output: "56088"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= num1.length, num2.length <= 200
  • +
  • num1 and num2 consist of digits only.
  • +
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0044.Wildcard Matching/README_EN.md b/assets/0000-0099/0044.Wildcard Matching/README_EN.md new file mode 100644 index 00000000..420dc0bb --- /dev/null +++ b/assets/0000-0099/0044.Wildcard Matching/README_EN.md @@ -0,0 +1,88 @@ +# [44. Wildcard Matching](https://leetcode.com/problems/wildcard-matching) + + + +## Description + +

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

+ +
    +
  • '?' Matches any single character.
  • +
  • '*' Matches any sequence of characters (including the empty sequence).
  • +
+ +

The matching should cover the entire input string (not partial).

+ +

 

+

Example 1:

+ +
+Input: s = "aa", p = "a"
+Output: false
+Explanation: "a" does not match the entire string "aa".
+
+ +

Example 2:

+ +
+Input: s = "aa", p = "*"
+Output: true
+Explanation: '*' matches any sequence.
+
+ +

Example 3:

+ +
+Input: s = "cb", p = "?a"
+Output: false
+Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
+
+ +

Example 4:

+ +
+Input: s = "adceb", p = "*a*b"
+Output: true
+Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
+
+ +

Example 5:

+ +
+Input: s = "acdcb", p = "a*c?b"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length, p.length <= 2000
  • +
  • s contains only lowercase English letters.
  • +
  • p contains only lowercase English letters, '?' or '*'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0045.Jump Game II/README_EN.md b/assets/0000-0099/0045.Jump Game II/README_EN.md new file mode 100644 index 00000000..3ef016ba --- /dev/null +++ b/assets/0000-0099/0045.Jump Game II/README_EN.md @@ -0,0 +1,148 @@ +# [45. Jump Game II](https://leetcode.com/problems/jump-game-ii) + + + +## Description + +

Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

+ +

Each element in the array represents your maximum jump length at that position.

+ +

Your goal is to reach the last index in the minimum number of jumps.

+ +

You can assume that you can always reach the last index.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,3,1,1,4]
+Output: 2
+Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
+Input: nums = [2,3,0,1,4]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def jump(self, nums: List[int]) -> int: + end = mx = steps = 0 + for i, num in enumerate(nums[:-1]): + mx = max(mx, i + num) + if i == end: + end = mx + steps += 1 + return steps +``` + +### **Java** + +```java +class Solution { + public int jump(int[] nums) { + int end = 0; + int mx = 0; + int steps = 0; + for (int i = 0; i < nums.length - 1; ++i) { + mx = Math.max(mx, i + nums[i]); + if (i == end) { + end = mx; + ++steps; + } + } + return steps; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int jump(vector& nums) { + int mx = 0, steps = 0, end = 0; + for (int i = 0; i < nums.size() - 1; ++i) { + mx = max(mx, i + nums[i]); + if (i == end) { + end = mx; + ++steps; + } + } + return steps; + } +}; +``` + +### **Go** + +```go +func jump(nums []int) int { + mx, steps, end := 0, 0, 0 + for i := 0; i < len(nums)-1; i++ { + mx = max(mx, i+nums[i]) + if i == end { + end = mx + steps++ + } + } + return steps +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int Jump(int[] nums) { + int end = 0; + int mx = 0; + int steps = 0; + for (int i = 0; i < nums.Length - 1; ++i) + { + mx = Math.Max(mx, i + nums[i]); + if (i == end) + { + end = mx; + ++steps; + } + } + return steps; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0046.Permutations/README_EN.md b/assets/0000-0099/0046.Permutations/README_EN.md new file mode 100644 index 00000000..c76e26a4 --- /dev/null +++ b/assets/0000-0099/0046.Permutations/README_EN.md @@ -0,0 +1,153 @@ +# [46. Permutations](https://leetcode.com/problems/permutations) + + + +## Description + +

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
+

Example 2:

+
Input: nums = [0,1]
+Output: [[0,1],[1,0]]
+

Example 3:

+
Input: nums = [1]
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 6
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the integers of nums are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + if len(nums) <= 1: + return [nums] + res = [] + for i, num in enumerate(nums): + n = nums[:i] + nums[i + 1:] + for item in self.permute(n): + res.append([num] + item) + return res +``` + +### **Java** + +Backtracking: + +```java +class Solution { + public List> permute(int[] nums) { + List> res = new ArrayList<>(); + List path = new ArrayList<>(); + boolean[] used = new boolean[nums.length]; + dfs(nums, 0, res, path, used); + return res; + } + + private void dfs(int[] nums, int i, List> res, List path, boolean[] used) { + if (i == nums.length) { + res.add(new ArrayList<>(path)); + return; + } + for (int j = 0; j < nums.length; ++j) { + if (!used[j]) { + path.add(nums[j]); + used[j] = true; + dfs(nums, i + 1, res, path, used); + used[j] = false; + path.remove(path.size() - 1); + } + } + } +} +``` + +- Recursion: + +```java +class Solution { + public List> permute(int[] nums) { + List> res = new ArrayList<>(); + permute(res, nums, 0); + return res; + } + + private void permute(List> res, int[] nums, int start) { + if (start == nums.length) { + List t = new ArrayList<>(); + for (int e : nums) { + t.add(e); + } + res.add(t); + return; + } + for (int i = start; i < nums.length; ++i) { + swap(nums, i, start); + permute(res, nums, start + 1); + swap(nums, i, start); + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function(nums) { + let res = []; + let solution = []; + let record = new Array(nums.length).fill(false); + dfs(nums, 0, record, solution, res); + return res; +}; + +function dfs (nums, depth, record, solution, res) { + if (depth == nums.length) { + res.push(solution.slice()); + return; + } + for (let i = 0; i < nums.length; i++) { + if (!record[i]) { + solution.push(nums[i]); + record[i] = true; + dfs(nums, depth + 1, record, solution, res); + solution.pop(); + record[i] = false; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0047.Permutations II/README_EN.md b/assets/0000-0099/0047.Permutations II/README_EN.md new file mode 100644 index 00000000..8ab4e304 --- /dev/null +++ b/assets/0000-0099/0047.Permutations II/README_EN.md @@ -0,0 +1,58 @@ +# [47. Permutations II](https://leetcode.com/problems/permutations-ii) + + + +## Description + +

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,1,2]
+Output:
+[[1,1,2],
+ [1,2,1],
+ [2,1,1]]
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3]
+Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 8
  • +
  • -10 <= nums[i] <= 10
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0048.Rotate Image/README_EN.md b/assets/0000-0099/0048.Rotate Image/README_EN.md new file mode 100644 index 00000000..8e3fcb7d --- /dev/null +++ b/assets/0000-0099/0048.Rotate Image/README_EN.md @@ -0,0 +1,102 @@ +# [48. Rotate Image](https://leetcode.com/problems/rotate-image) + + + +## Description + +

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

+ +

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

+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [[7,4,1],[8,5,2],[9,6,3]]
+
+ +

Example 2:

+ +
+Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
+Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
+
+ +

Example 3:

+ +
+Input: matrix = [[1]]
+Output: [[1]]
+
+ +

Example 4:

+ +
+Input: matrix = [[1,2],[3,4]]
+Output: [[3,1],[4,2]]
+
+ +

 

+

Constraints:

+ +
    +
  • matrix.length == n
  • +
  • matrix[i].length == n
  • +
  • 1 <= n <= 20
  • +
  • -1000 <= matrix[i][j] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + s, n = 0, len(matrix) + while s < (n >> 1): + e = n - s - 1 + for i in range(s, e): + t = matrix[i][e] + matrix[i][e] = matrix[s][i] + matrix[s][i] = matrix[n - i - 1][s] + matrix[n - i - 1][s] = matrix[e][n - i - 1] + matrix[e][n - i - 1] = t + s += 1 +``` + +### **Java** + +```java +class Solution { + public void rotate(int[][] matrix) { + int s = 0, n = matrix.length; + while (s < (n >> 1)) { + int e = n - s - 1; + for (int i = s; i < e; ++i) { + int t = matrix[i][e]; + matrix[i][e] = matrix[s][i]; + matrix[s][i] = matrix[n - i - 1][s]; + matrix[n - i - 1][s] = matrix[e][n - i - 1]; + matrix[e][n - i - 1] = t; + } + ++s; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0048.Rotate Image/images/mat1.jpg b/assets/0000-0099/0048.Rotate Image/images/mat1.jpg new file mode 100644 index 00000000..d91bebf6 Binary files /dev/null and b/assets/0000-0099/0048.Rotate Image/images/mat1.jpg differ diff --git a/assets/0000-0099/0048.Rotate Image/images/mat2.jpg b/assets/0000-0099/0048.Rotate Image/images/mat2.jpg new file mode 100644 index 00000000..0276ac2d Binary files /dev/null and b/assets/0000-0099/0048.Rotate Image/images/mat2.jpg differ diff --git a/assets/0000-0099/0049.Group Anagrams/README_EN.md b/assets/0000-0099/0049.Group Anagrams/README_EN.md new file mode 100644 index 00000000..1454281a --- /dev/null +++ b/assets/0000-0099/0049.Group Anagrams/README_EN.md @@ -0,0 +1,54 @@ +# [49. Group Anagrams](https://leetcode.com/problems/group-anagrams) + + + +## Description + +

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

+ +

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

+ +

 

+

Example 1:

+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
+Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
+

Example 2:

+
Input: strs = [""]
+Output: [[""]]
+

Example 3:

+
Input: strs = ["a"]
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 104
  • +
  • 0 <= strs[i].length <= 100
  • +
  • strs[i] consists of lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0050.Pow(x, n)/README_EN.md b/assets/0000-0099/0050.Pow(x, n)/README_EN.md new file mode 100644 index 00000000..3ee648ef --- /dev/null +++ b/assets/0000-0099/0050.Pow(x, n)/README_EN.md @@ -0,0 +1,103 @@ +# [50. Pow(x, n)](https://leetcode.com/problems/powx-n) + + + +## Description + +

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

+ +

 

+

Example 1:

+ +
+Input: x = 2.00000, n = 10
+Output: 1024.00000
+
+ +

Example 2:

+ +
+Input: x = 2.10000, n = 3
+Output: 9.26100
+
+ +

Example 3:

+ +
+Input: x = 2.00000, n = -2
+Output: 0.25000
+Explanation: 2-2 = 1/22 = 1/4 = 0.25
+
+ +

 

+

Constraints:

+ +
    +
  • -100.0 < x < 100.0
  • +
  • -231 <= n <= 231-1
  • +
  • -104 <= xn <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def myPow(self, x: float, n: int) -> float: + if n == 0: + return 1 + if n < 0: + return 1 / self.myPow(x, -n) + y = self.myPow(x, n >> 1) + return y * y if (n & 1) == 0 else y * y * x +``` + +### **Java** + +```java +class Solution { + public double myPow(double x, int n) { + long N = n; + return N >= 0 ? pow(x, N) : 1.0 / pow(x, -N); + } + + public double pow(double x, long N) { + if (N == 0) { + return 1.0; + } + double y = pow(x, N >> 1); + return (N & 1) == 0 ? y * y : y * y * x; + } +} +``` + +### **TypeScript** + +```ts +function myPow(x: number, n: number): number { + let res = 1; + if (n < 0) { + n = -n; + x = 1 / x; + } + for (let i = n; i != 0; i = Math.floor(i / 2)) { + if ((i & 1) == 1) { + res *= x; + } + x *= x; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0051.N-Queens/README_EN.md b/assets/0000-0099/0051.N-Queens/README_EN.md new file mode 100644 index 00000000..3e1f71ed --- /dev/null +++ b/assets/0000-0099/0051.N-Queens/README_EN.md @@ -0,0 +1,59 @@ +# [51. N-Queens](https://leetcode.com/problems/n-queens) + + + +## Description + +

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

+ +

Given an integer n, return all distinct solutions to the n-queens puzzle.

+ +

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

+ +

 

+

Example 1:

+ +
+Input: n = 4
+Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
+Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: [["Q"]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 9
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0051.N-Queens/images/8-queens.png b/assets/0000-0099/0051.N-Queens/images/8-queens.png new file mode 100644 index 00000000..0ed5de45 Binary files /dev/null and b/assets/0000-0099/0051.N-Queens/images/8-queens.png differ diff --git a/assets/0000-0099/0052.N-Queens II/README_EN.md b/assets/0000-0099/0052.N-Queens II/README_EN.md new file mode 100644 index 00000000..10964e6b --- /dev/null +++ b/assets/0000-0099/0052.N-Queens II/README_EN.md @@ -0,0 +1,57 @@ +# [52. N-Queens II](https://leetcode.com/problems/n-queens-ii) + + + +## Description + +

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

+ +

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

+ +

 

+

Example 1:

+ +
+Input: n = 4
+Output: 2
+Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 9
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0052.N-Queens II/images/8-queens.png b/assets/0000-0099/0052.N-Queens II/images/8-queens.png new file mode 100644 index 00000000..0ed5de45 Binary files /dev/null and b/assets/0000-0099/0052.N-Queens II/images/8-queens.png differ diff --git a/assets/0000-0099/0053.Maximum Subarray/README_EN.md b/assets/0000-0099/0053.Maximum Subarray/README_EN.md new file mode 100644 index 00000000..1e3b58b6 --- /dev/null +++ b/assets/0000-0099/0053.Maximum Subarray/README_EN.md @@ -0,0 +1,149 @@ +# [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray) + + + +## Description + +

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

+ +

 

+

Example 1:

+ +
+Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
+Output: 6
+Explanation: [4,-1,2,1] has the largest sum = 6.
+
+ +

Example 2:

+ +
+Input: nums = [1]
+Output: 1
+
+ +

Example 3:

+ +
+Input: nums = [5,4,-1,7,8]
+Output: 23
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -105 <= nums[i] <= 105
  • +
+ +

 

+Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + res = f = nums[0] + for num in nums[1:]: + f = num + max(f, 0) + res = max(res, f) + return res +``` + +### **Java** + +```java +class Solution { + public int maxSubArray(int[] nums) { + int f = nums[0], res = nums[0]; + for (int i = 1, n = nums.length; i < n; ++i) { + f = nums[i] + Math.max(f, 0); + res = Math.max(res, f); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxSubArray(vector& nums) { + int f = nums[0], res = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + f = nums[i] + max(f, 0); + res = max(res, f); + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function (nums) { + let f = nums[0], + res = nums[0]; + for (let i = 1; i < nums.length; ++i) { + f = nums[i] + Math.max(f, 0); + res = Math.max(res, f); + } + return res; +}; +``` + +### **Go** + +```go +func maxSubArray(nums []int) int { + f, res := nums[0], nums[0] + for i := 1; i < len(nums); i++ { + if f > 0 { + f += nums[i] + } else { + f = nums[i] + } + if f > res { + res = f + } + } + return res +} +``` + +### **C#** + +```cs +public class Solution { + public int MaxSubArray(int[] nums) { + int res = nums[0], f = nums[0]; + for (int i = 1; i < nums.Length; ++i) + { + f = nums[i] + Math.Max(f, 0); + res = Math.Max(res, f); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0054.Spiral Matrix/README_EN.md b/assets/0000-0099/0054.Spiral Matrix/README_EN.md new file mode 100644 index 00000000..7feac3b6 --- /dev/null +++ b/assets/0000-0099/0054.Spiral Matrix/README_EN.md @@ -0,0 +1,143 @@ +# [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix) + + + +## Description + +

Given an m x n matrix, return all elements of the matrix in spiral order.

+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [1,2,3,6,9,8,7,4,5]
+
+ +

Example 2:

+ +
+Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
+Output: [1,2,3,4,8,12,11,10,9,5,6,7]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 10
  • +
  • -100 <= matrix[i][j] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + def add(i1, j1, i2, j2): + if i1 == i2: + return [matrix[i1][j] for j in range(j1, j2 + 1)] + if j1 == j2: + return [matrix[i][j1] for i in range(i1, i2 + 1)] + return [matrix[i1][j] for j in range(j1, j2)] + [matrix[i][j2] for i in range(i1, i2)] + [matrix[i2][j] for j in range(j2, j1, -1)] + [matrix[i][j1] for i in range(i2, i1, -1)] + + m, n = len(matrix), len(matrix[0]) + i1, j1, i2, j2 = 0, 0, m - 1, n - 1 + res = [] + while i1 <= i2 and j1 <= j2: + res += add(i1, j1, i2, j2) + i1, j1, i2, j2 = i1 + 1, j1 + 1, i2 - 1, j2 - 1 + return res +``` + +### **Java** + +```java +class Solution { + private List res; + + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + res = new ArrayList<>(); + int i1 = 0, i2 = m - 1; + int j1 = 0, j2 = n - 1; + while (i1 <= i2 && j1 <= j2) { + add(matrix, i1++, j1++, i2--, j2--); + } + return res; + } + + private void add(int[][] matrix, int i1, int j1, int i2, int j2) { + if (i1 == i2) { + for (int j = j1; j <= j2; ++j) { + res.add(matrix[i1][j]); + } + return; + } + if (j1 == j2) { + for (int i = i1; i <= i2; ++i) { + res.add(matrix[i][j1]); + } + return; + } + for (int j = j1; j < j2; ++j) { + res.add(matrix[i1][j]); + } + for (int i = i1; i < i2; ++i) { + res.add(matrix[i][j2]); + } + for (int j = j2; j > j1; --j) { + res.add(matrix[i2][j]); + } + for (int i = i2; i > i1; --i) { + res.add(matrix[i][j1]); + } + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { + let m = matrix.length; + if (m === 0) return []; + let res = []; + let top = 0, bottom = m - 1, left = 0, right = matrix[0].length - 1; + while (left < right && bottom > top) { + for (let i = left; i < right; i++) res.push(matrix[top][i]); + for (let i = top; i < bottom; i++) res.push(matrix[i][right]); + for (let i = right; i > left; i--) res.push(matrix[bottom][i]); + for (let i = bottom; i > top; i--) res.push(matrix[i][left]); + top++; + bottom--; + left++; + right--; + } + if (left === right) { + for (i = top; i <= bottom; i++) res.push(matrix[i][left]); + } else if (top === bottom) { + for (i = left; i <= right; i++) res.push(matrix[top][i]); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0054.Spiral Matrix/images/spiral.jpg b/assets/0000-0099/0054.Spiral Matrix/images/spiral.jpg new file mode 100644 index 00000000..45693040 Binary files /dev/null and b/assets/0000-0099/0054.Spiral Matrix/images/spiral.jpg differ diff --git a/assets/0000-0099/0054.Spiral Matrix/images/spiral1.jpg b/assets/0000-0099/0054.Spiral Matrix/images/spiral1.jpg new file mode 100644 index 00000000..18f7d237 Binary files /dev/null and b/assets/0000-0099/0054.Spiral Matrix/images/spiral1.jpg differ diff --git a/assets/0000-0099/0055.Jump Game/README_EN.md b/assets/0000-0099/0055.Jump Game/README_EN.md new file mode 100644 index 00000000..85bf3fab --- /dev/null +++ b/assets/0000-0099/0055.Jump Game/README_EN.md @@ -0,0 +1,137 @@ +# [55. Jump Game](https://leetcode.com/problems/jump-game) + + + +## Description + +

Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

+ +

Each element in the array represents your maximum jump length at that position.

+ +

Determine if you are able to reach the last index.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,3,1,1,4]
+Output: true
+Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
+
+ +

Example 2:

+ +
+Input: nums = [3,2,1,0,4]
+Output: false
+Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • 0 <= nums[i] <= 105
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def canJump(self, nums: List[int]) -> bool: + mx = 0 + for i, num in enumerate(nums): + if i > mx: + return False + mx = max(mx, i + num) + return True +``` + +### **Java** + +```java +class Solution { + public boolean canJump(int[] nums) { + int mx = 0; + for (int i = 0; i < nums.length; ++i) { + if (i > mx) { + return false; + } + mx = Math.max(mx, i + nums[i]); + } + return true; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool canJump(vector& nums) { + int mx = 0; + for (int i = 0; i < nums.size(); ++i) { + if (i > mx) { + return false; + } + mx = max(mx, i + nums[i]); + } + return true; + } +}; +``` + +### **Go** + +```go +func canJump(nums []int) bool { + mx := 0 + for i, num := range nums { + if i > mx { + return false + } + mx = max(mx, i+num) + } + return true +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public bool CanJump(int[] nums) { + int mx = 0; + for (int i = 0; i < nums.Length; ++i) + { + if (i > mx) + { + return false; + } + mx = Math.Max(mx, i + nums[i]); + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0056.Merge Intervals/README_EN.md b/assets/0000-0099/0056.Merge Intervals/README_EN.md new file mode 100644 index 00000000..4c6e9f28 --- /dev/null +++ b/assets/0000-0099/0056.Merge Intervals/README_EN.md @@ -0,0 +1,58 @@ +# [56. Merge Intervals](https://leetcode.com/problems/merge-intervals) + + + +## Description + +

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

+ +

 

+

Example 1:

+ +
+Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
+Output: [[1,6],[8,10],[15,18]]
+Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
+
+ +

Example 2:

+ +
+Input: intervals = [[1,4],[4,5]]
+Output: [[1,5]]
+Explanation: Intervals [1,4] and [4,5] are considered overlapping.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= starti <= endi <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0057.Insert Interval/README_EN.md b/assets/0000-0099/0057.Insert Interval/README_EN.md new file mode 100644 index 00000000..93609d1f --- /dev/null +++ b/assets/0000-0099/0057.Insert Interval/README_EN.md @@ -0,0 +1,82 @@ +# [57. Insert Interval](https://leetcode.com/problems/insert-interval) + + + +## Description + +

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

+ +

You may assume that the intervals were initially sorted according to their start times.

+ +

 

+

Example 1:

+ +
+Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
+Output: [[1,5],[6,9]]
+
+ +

Example 2:

+ +
+Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
+Output: [[1,2],[3,10],[12,16]]
+Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
+ +

Example 3:

+ +
+Input: intervals = [], newInterval = [5,7]
+Output: [[5,7]]
+
+ +

Example 4:

+ +
+Input: intervals = [[1,5]], newInterval = [2,3]
+Output: [[1,5]]
+
+ +

Example 5:

+ +
+Input: intervals = [[1,5]], newInterval = [2,7]
+Output: [[1,7]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= intervals[i][0] <= intervals[i][1] <= 105
  • +
  • intervals is sorted by intervals[i][0] in ascending order.
  • +
  • newInterval.length == 2
  • +
  • 0 <= newInterval[0] <= newInterval[1] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0058.Length of Last Word/README_EN.md b/assets/0000-0099/0058.Length of Last Word/README_EN.md new file mode 100644 index 00000000..868648e3 --- /dev/null +++ b/assets/0000-0099/0058.Length of Last Word/README_EN.md @@ -0,0 +1,77 @@ +# [58. Length of Last Word](https://leetcode.com/problems/length-of-last-word) + + + +## Description + +

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

+ +

A word is a maximal substring consisting of non-space characters only.

+ +

 

+

Example 1:

+
Input: s = "Hello World"
+Output: 5
+

Example 2:

+
Input: s = " "
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of only English letters and spaces ' '.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def lengthOfLastWord(self, s: str) -> int: + last_word_length = 0 + meet_word = False + for i in range(len(s) - 1, -1, -1): + ch = ord(s[i]) + if ch >= 65 and ch <= 122: + meet_word = True + last_word_length += 1 + elif meet_word: + break + return last_word_length +``` + +### **Java** + +```java +class Solution { + public int lengthOfLastWord(String s) { + int n = s.length(); + int lastWordLength = 0; + boolean meetWord = false; + for (int i = n - 1; i >= 0; --i) { + char ch = s.charAt(i); + if (ch >= 'A' && ch <= 'z') { + meetWord = true; + ++lastWordLength; + } else if (meetWord) { + break; + } + } + return lastWordLength; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0059.Spiral Matrix II/README_EN.md b/assets/0000-0099/0059.Spiral Matrix II/README_EN.md new file mode 100644 index 00000000..67e85c7c --- /dev/null +++ b/assets/0000-0099/0059.Spiral Matrix II/README_EN.md @@ -0,0 +1,136 @@ +# [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii) + + + +## Description + +

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

+ +

 

+

Example 1:

+ +
+Input: n = 3
+Output: [[1,2,3],[8,9,4],[7,6,5]]
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: [[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 20
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + res = [[0] * n for _ in range(n)] + num = 1 + m1, m2 = 0, n - 1 + while m1 < m2: + for j in range(m1, m2): + res[m1][j] = num + num += 1 + for i in range(m1, m2): + res[i][m2] = num + num += 1 + for j in range(m2, m1, -1): + res[m2][j] = num + num += 1 + for i in range(m2, m1, -1): + res[i][m1] = num + num += 1 + m1 += 1 + m2 -= 1 + if m1 == m2: + res[m1][m1] = num + return res +``` + +### **Java** + +```java +class Solution { + public int[][] generateMatrix(int n) { + int[][] res = new int[n][n]; + int num = 1; + int m1 = 0, m2 = n - 1; + while (m1 < m2) { + for (int j = m1; j < m2; ++j) { + res[m1][j] = num++; + } + for (int i = m1; i < m2; ++i) { + res[i][m2] = num++; + } + for (int j = m2; j > m1; --j) { + res[m2][j] = num++; + } + for (int i = m2; i > m1; --i) { + res[i][m1] = num++; + } + ++m1; + --m2; + } + if (m1 == m2) { + res[m1][m1] = num; + } + + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> generateMatrix(int n) { + vector> res(n, vector(n, 0)); + int num = 1; + int m1 = 0, m2 = n - 1; + while (m1 < m2) { + for (int j = m1; j < m2; ++j) { + res[m1][j] = num++; + } + for (int i = m1; i < m2; ++i) { + res[i][m2] = num++; + } + for (int j = m2; j > m1; --j) { + res[m2][j] = num++; + } + for (int i = m2; i > m1; --i) { + res[i][m1] = num++; + } + ++m1; + --m2; + } + if (m1 == m2) { + res[m1][m1] = num; + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0059.Spiral Matrix II/images/spiraln.jpg b/assets/0000-0099/0059.Spiral Matrix II/images/spiraln.jpg new file mode 100644 index 00000000..4d95f4fb Binary files /dev/null and b/assets/0000-0099/0059.Spiral Matrix II/images/spiraln.jpg differ diff --git a/assets/0000-0099/0060.Permutation Sequence/README_EN.md b/assets/0000-0099/0060.Permutation Sequence/README_EN.md new file mode 100644 index 00000000..f248fdaf --- /dev/null +++ b/assets/0000-0099/0060.Permutation Sequence/README_EN.md @@ -0,0 +1,64 @@ +# [60. Permutation Sequence](https://leetcode.com/problems/permutation-sequence) + + + +## Description + +

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

+ +

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

+ +
    +
  1. "123"
  2. +
  3. "132"
  4. +
  5. "213"
  6. +
  7. "231"
  8. +
  9. "312"
  10. +
  11. "321"
  12. +
+ +

Given n and k, return the kth permutation sequence.

+ +

 

+

Example 1:

+
Input: n = 3, k = 3
+Output: "213"
+

Example 2:

+
Input: n = 4, k = 9
+Output: "2314"
+

Example 3:

+
Input: n = 3, k = 1
+Output: "123"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 9
  • +
  • 1 <= k <= n!
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0061.Rotate List/README_EN.md b/assets/0000-0099/0061.Rotate List/README_EN.md new file mode 100644 index 00000000..8415a6a7 --- /dev/null +++ b/assets/0000-0099/0061.Rotate List/README_EN.md @@ -0,0 +1,253 @@ +# [61. Rotate List](https://leetcode.com/problems/rotate-list) + + + +## Description + +

Given the head of a linked list, rotate the list to the right by k places.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5], k = 2
+Output: [4,5,1,2,3]
+
+ +

Example 2:

+ +
+Input: head = [0,1,2], k = 4
+Output: [2,0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 500].
  • +
  • -100 <= Node.val <= 100
  • +
  • 0 <= k <= 2 * 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def rotateRight(self, head: ListNode, k: int) -> ListNode: + if k == 0 or head is None or head.next is None: + return head + n, cur = 0, head + while cur: + n, cur = n + 1, cur.next + k %= n + if k == 0: + return head + + slow = fast = head + for _ in range(k): + fast = fast.next + while fast.next: + slow, fast = slow.next, fast.next + + start = slow.next + slow.next = None + fast.next = head + return start +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode rotateRight(ListNode head, int k) { + if (k == 0 || head == null || head.next == null) { + return head; + } + int n = 0; + for (ListNode cur = head; cur != null; cur = cur.next) { + ++n; + } + k %= n; + if (k == 0) { + return head; + } + ListNode slow = head, fast = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + + ListNode start = slow.next; + slow.next = null; + fast.next = head; + return start; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function rotateRight(head: ListNode | null, k: number): ListNode | null { + if (k == 0 || head == null || head.next == null) return head; + // mod n + let n = 0; + let p = head; + while (p != null) { + ++n; + p = p.next; + } + k %= n; + if (k == 0) return head; + + let fast = head, slow = head; + for (let i = 0; i < k; ++i) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + let start = slow.next; + slow.next = null; + fast.next = head; + return start; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + if (k == 0 || !head || !head->next) { + return head; + } + int n = 0; + for (ListNode *cur = head; !!cur; cur = cur->next) { + ++n; + } + k %= n; + if (k == 0) { + return head; + } + ListNode *slow = head, *fast = head; + while (k-- > 0) { + fast = fast->next; + } + while (fast->next) { + slow = slow->next; + fast = fast->next; + } + + ListNode *start = slow->next; + slow->next = nullptr; + fast->next = head; + return start; + } +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RotateRight(ListNode head, int k) { + if (k == 0 || head == null || head.next == null) + { + return head; + } + var n = 0; + for (ListNode cur = head; cur != null; cur = cur.next) + { + ++n; + } + k %= n; + if (k == 0) + { + return head; + } + ListNode slow = head, fast = head; + while (k-- > 0) + { + fast = fast.next; + } + while (fast.next != null) + { + slow = slow.next; + fast = fast.next; + } + + ListNode start = slow.next; + slow.next = null; + fast.next = head; + return start; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0061.Rotate List/Soution.ts b/assets/0000-0099/0061.Rotate List/Soution.ts new file mode 100644 index 00000000..91e4ecee --- /dev/null +++ b/assets/0000-0099/0061.Rotate List/Soution.ts @@ -0,0 +1,37 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + + function rotateRight(head: ListNode | null, k: number): ListNode | null { + if (k == 0 || head == null || head.next == null) return head; + // mod n + let n = 0; + let p = head; + while (p != null) { + ++n; + p = p.next; + } + k %= n; + if (k == 0) return head; + + let fast = head, slow = head; + for (let i = 0; i < k; ++i) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + let start = slow.next; + slow.next = null; + fast.next = head; + return start; +}; \ No newline at end of file diff --git a/assets/0000-0099/0061.Rotate List/images/roate2.jpg b/assets/0000-0099/0061.Rotate List/images/roate2.jpg new file mode 100644 index 00000000..1d26d679 Binary files /dev/null and b/assets/0000-0099/0061.Rotate List/images/roate2.jpg differ diff --git a/assets/0000-0099/0061.Rotate List/images/rotate1.jpg b/assets/0000-0099/0061.Rotate List/images/rotate1.jpg new file mode 100644 index 00000000..ed07be7c Binary files /dev/null and b/assets/0000-0099/0061.Rotate List/images/rotate1.jpg differ diff --git a/assets/0000-0099/0062.Unique Paths/README_EN.md b/assets/0000-0099/0062.Unique Paths/README_EN.md new file mode 100644 index 00000000..83f42904 --- /dev/null +++ b/assets/0000-0099/0062.Unique Paths/README_EN.md @@ -0,0 +1,136 @@ +# [62. Unique Paths](https://leetcode.com/problems/unique-paths) + + + +## Description + +

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

+ +

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

+ +

How many possible unique paths are there?

+ +

 

+

Example 1:

+ +
+Input: m = 3, n = 7
+Output: 28
+
+ +

Example 2:

+ +
+Input: m = 3, n = 2
+Output: 3
+Explanation:
+From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
+1. Right -> Down -> Down
+2. Down -> Down -> Right
+3. Down -> Right -> Down
+
+ +

Example 3:

+ +
+Input: m = 7, n = 3
+Output: 28
+
+ +

Example 4:

+ +
+Input: m = 3, n = 3
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 100
  • +
  • It's guaranteed that the answer will be less than or equal to 2 * 109.
  • +
+ +## Solutions + +Dynamic programming. + + + +### **Python3** + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + dp = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + return dp[-1][-1] +``` + +### **Java** + +```java +class Solution { + public int uniquePaths(int m, int n) { + int[][] dp = new int[m][n]; + for (int i = 0; i < m; ++i) { + Arrays.fill(dp[i], 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + return dp[m - 1][n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector> dp(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + return dp[m - 1][n - 1]; + } +}; +``` + +### **Go** + +```go +func uniquePaths(m int, n int) int { + dp := make([][]int, m) + for i := 0; i < m; i++ { + dp[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if i == 0 || j == 0 { + dp[i][j] = 1 + } else { + dp[i][j] = dp[i-1][j] + dp[i][j-1] + } + } + } + return dp[m-1][n-1] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0062.Unique Paths/images/robot_maze.png b/assets/0000-0099/0062.Unique Paths/images/robot_maze.png new file mode 100644 index 00000000..e1aa2836 Binary files /dev/null and b/assets/0000-0099/0062.Unique Paths/images/robot_maze.png differ diff --git a/assets/0000-0099/0063.Unique Paths II/README_EN.md b/assets/0000-0099/0063.Unique Paths II/README_EN.md new file mode 100644 index 00000000..fdf6d968 --- /dev/null +++ b/assets/0000-0099/0063.Unique Paths II/README_EN.md @@ -0,0 +1,156 @@ +# [63. Unique Paths II](https://leetcode.com/problems/unique-paths-ii) + + + +## Description + +

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

+ +

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

+ +

Now consider if some obstacles are added to the grids. How many unique paths would there be?

+ +

An obstacle and space is marked as 1 and 0 respectively in the grid.

+ +

 

+

Example 1:

+ +
+Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
+Output: 2
+Explanation: There is one obstacle in the middle of the 3x3 grid above.
+There are two ways to reach the bottom-right corner:
+1. Right -> Right -> Down -> Down
+2. Down -> Down -> Right -> Right
+
+ +

Example 2:

+ +
+Input: obstacleGrid = [[0,1],[0,0]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == obstacleGrid.length
  • +
  • n == obstacleGrid[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • obstacleGrid[i][j] is 0 or 1.
  • +
+ + +## Solutions + +Dynamic programming. + + + +### **Python3** + +```python +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + m, n = len(obstacleGrid), len(obstacleGrid[0]) + dp = [[0] * n for _ in range(m)] + for i in range(m): + if obstacleGrid[i][0] == 1: + break + dp[i][0] = 1 + for j in range(n): + if obstacleGrid[0][j] == 1: + break + dp[0][j] = 1 + for i in range(1, m): + for j in range(1, n): + if obstacleGrid[i][j] == 0: + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + return dp[-1][-1] +``` + +### **Java** + +```java +class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + int m = obstacleGrid.length, n = obstacleGrid[0].length; + int[][] dp = new int[m][n]; + for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) { + dp[i][0] = 1; + } + for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j) { + dp[0][j] = 1; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (obstacleGrid[i][j] == 0) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m - 1][n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int m = obstacleGrid.size(), n = obstacleGrid[0].size(); + vector> dp(m, vector(n)); + for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) { + dp[i][0] = 1; + } + for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j) { + dp[0][j] = 1; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (obstacleGrid[i][j] == 0) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m - 1][n - 1]; + } +}; +``` + +### **Go** + +```go +func uniquePathsWithObstacles(obstacleGrid [][]int) int { + m, n := len(obstacleGrid), len(obstacleGrid[0]) + dp := make([][]int, m) + for i := 0; i < m; i++ { + dp[i] = make([]int, n) + } + for i := 0; i < m && obstacleGrid[i][0] == 0; i++ { + dp[i][0] = 1 + } + for j := 0; j < n && obstacleGrid[0][j] == 0; j++ { + dp[0][j] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if obstacleGrid[i][j] == 0 { + dp[i][j] = dp[i-1][j] + dp[i][j-1] + } + } + } + return dp[m-1][n-1] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0063.Unique Paths II/images/robot1.jpg b/assets/0000-0099/0063.Unique Paths II/images/robot1.jpg new file mode 100644 index 00000000..5e357f01 Binary files /dev/null and b/assets/0000-0099/0063.Unique Paths II/images/robot1.jpg differ diff --git a/assets/0000-0099/0063.Unique Paths II/images/robot2.jpg b/assets/0000-0099/0063.Unique Paths II/images/robot2.jpg new file mode 100644 index 00000000..a629fbfa Binary files /dev/null and b/assets/0000-0099/0063.Unique Paths II/images/robot2.jpg differ diff --git a/assets/0000-0099/0063.Unique Paths II/images/robot_maze.png b/assets/0000-0099/0063.Unique Paths II/images/robot_maze.png new file mode 100644 index 00000000..e1aa2836 Binary files /dev/null and b/assets/0000-0099/0063.Unique Paths II/images/robot_maze.png differ diff --git a/assets/0000-0099/0064.Minimum Path Sum/README_EN.md b/assets/0000-0099/0064.Minimum Path Sum/README_EN.md new file mode 100644 index 00000000..892778bc --- /dev/null +++ b/assets/0000-0099/0064.Minimum Path Sum/README_EN.md @@ -0,0 +1,146 @@ +# [64. Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum) + + + +## Description + +

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

+ +

Note: You can only move either down or right at any point in time.

+ +

 

+

Example 1:

+ +
+Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
+Output: 7
+Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
+
+ +

Example 2:

+ +
+Input: grid = [[1,2,3],[4,5,6]]
+Output: 12
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 0 <= grid[i][j] <= 100
  • +
+ +## Solutions + +Dynamic programming. + + + +### **Python3** + +```python +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + dp = [[grid[0][0]] * n for _ in range(m)] + for i in range(1, m): + dp[i][0] = dp[i - 1][0] + grid[i][0] + for j in range(1, n): + dp[0][j] = dp[0][j - 1] + grid[0][j] + for i in range(1, m): + for j in range(1, n): + dp[i][j] = min(dp[i -1][j], dp[i][j - 1]) + grid[i][j] + return dp[-1][-1] +``` + +### **Java** + +```java +class Solution { + public int minPathSum(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] dp = new int[m][n]; + dp[0][0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + dp[i][0] = dp[i - 1][0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + dp[0][j] = dp[0][j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + } + } + return dp[m - 1][n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> dp(m, vector(n, grid[0][0])); + for (int i = 1; i < m; ++i) { + dp[i][0] = dp[i - 1][0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + dp[0][j] = dp[0][j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + } + } + return dp[m - 1][n - 1]; + } +}; +``` + +### **Go** + +```go +func minPathSum(grid [][]int) int { + m, n := len(grid), len(grid[0]) + dp := make([][]int, m) + for i := 0; i < m; i++ { + dp[i] = make([]int, n) + } + dp[0][0] = grid[0][0] + for i := 1; i < m; i++ { + dp[i][0] = dp[i-1][0] + grid[i][0] + } + for j := 1; j < n; j++ { + dp[0][j] = dp[0][j-1] + grid[0][j] + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] + } + } + return dp[m-1][n-1] +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0064.Minimum Path Sum/images/minpath.jpg b/assets/0000-0099/0064.Minimum Path Sum/images/minpath.jpg new file mode 100644 index 00000000..bd8f7398 Binary files /dev/null and b/assets/0000-0099/0064.Minimum Path Sum/images/minpath.jpg differ diff --git a/assets/0000-0099/0065.Valid Number/README_EN.md b/assets/0000-0099/0065.Valid Number/README_EN.md new file mode 100644 index 00000000..d793e4f7 --- /dev/null +++ b/assets/0000-0099/0065.Valid Number/README_EN.md @@ -0,0 +1,98 @@ +# [65. Valid Number](https://leetcode.com/problems/valid-number) + + + +## Description + +

A valid number can be split up into these components (in order):

+ +
    +
  1. A decimal number or an integer.
  2. +
  3. (Optional) An 'e' or 'E', followed by an integer.
  4. +
+ +

A decimal number can be split up into these components (in order):

+ +
    +
  1. (Optional) A sign character (either '+' or '-').
  2. +
  3. One of the following formats: +
      +
    1. At least one digit, followed by a dot '.'.
    2. +
    3. At least one digit, followed by a dot '.', followed by at least one digit.
    4. +
    5. A dot '.', followed by at least one digit.
    6. +
    +
  4. +
+ +

An integer can be split up into these components (in order):

+ +
    +
  1. (Optional) A sign character (either '+' or '-').
  2. +
  3. At least one digit.
  4. +
+ +

For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].

+ +

Given a string s, return true if s is a valid number.

+ +

 

+

Example 1:

+ +
+Input: s = "0"
+Output: true
+
+ +

Example 2:

+ +
+Input: s = "e"
+Output: false
+
+ +

Example 3:

+ +
+Input: s = "."
+Output: false
+
+ +

Example 4:

+ +
+Input: s = ".1"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 20
  • +
  • s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0066.Plus One/README_EN.md b/assets/0000-0099/0066.Plus One/README_EN.md new file mode 100644 index 00000000..ada37def --- /dev/null +++ b/assets/0000-0099/0066.Plus One/README_EN.md @@ -0,0 +1,68 @@ +# [66. Plus One](https://leetcode.com/problems/plus-one) + + + +## Description + +

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

+ +

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

+ +

You may assume the integer does not contain any leading zero, except the number 0 itself.

+ +

 

+

Example 1:

+ +
+Input: digits = [1,2,3]
+Output: [1,2,4]
+Explanation: The array represents the integer 123.
+
+ +

Example 2:

+ +
+Input: digits = [4,3,2,1]
+Output: [4,3,2,2]
+Explanation: The array represents the integer 4321.
+
+ +

Example 3:

+ +
+Input: digits = [0]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= digits.length <= 100
  • +
  • 0 <= digits[i] <= 9
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0067.Add Binary/README_EN.md b/assets/0000-0099/0067.Add Binary/README_EN.md new file mode 100644 index 00000000..49f1d1be --- /dev/null +++ b/assets/0000-0099/0067.Add Binary/README_EN.md @@ -0,0 +1,127 @@ +# [67. Add Binary](https://leetcode.com/problems/add-binary) + + + +## Description + +

Given two binary strings a and b, return their sum as a binary string.

+ +

 

+

Example 1:

+
Input: a = "11", b = "1"
+Output: "100"
+

Example 2:

+
Input: a = "1010", b = "1011"
+Output: "10101"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= a.length, b.length <= 104
  • +
  • a and b consist only of '0' or '1' characters.
  • +
  • Each string does not contain leading zeros except for the zero itself.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def addBinary(self, a: str, b: str) -> str: + return bin(int(a, 2) + int(b, 2))[2:] +``` + +### **Java** + +```java +class Solution { + public String addBinary(String a, String b) { + StringBuilder sb = new StringBuilder(); + int i = a.length() - 1, j = b.length() - 1, carry = 0; + while (i >= 0 || j >= 0 || carry != 0) { + int s = carry + (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0); + sb.append(s % 2); + carry = s / 2; + --i; + --j; + } + return sb.reverse().toString(); + } +} +``` + +### **C#** + +```cs +using System; +using System.Collections.Generic; + +public class Solution { + public string AddBinary(string a, string b) { + var list = new List(Math.Max(a.Length, b.Length) + 1); + var i = a.Length - 1; + var j = b.Length - 1; + var carry = 0; + while (i >= 0 || j >= 0) + { + if (i >= 0) + { + carry += a[i] - '0'; + } + if (j >= 0) + { + carry += b[j] - '0'; + } + list.Add((char)((carry % 2) + '0')); + carry /= 2; + --i; + --j; + } + if (carry > 0) list.Add((char) (carry + '0')); + list.Reverse(); + return new string(list.ToArray()); + } +} +``` + +### **Go** + +```go +func addBinary(a string, b string) string { + for len(a) > len(b) { + b = "0" + b + } + for len(a) < len(b) { + a = "0" + a + } + zero := []byte("0")[0] + ret := make([]byte, len(a)) + for right := len(a) - 1; right > 0; right-- { + t := ret[right] + a[right] + b[right] - zero*2 + ret[right] = t%2 + zero + if t >= 2 { + ret[right-1] = 1 + } + } + t := ret[0] + a[0] + b[0] - zero*2 + ret[0] = t%2 + zero + if t >= 2 { + ret = append([]byte("1"), ret...) + } + + return string(ret) +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0068.Text Justification/README_EN.md b/assets/0000-0099/0068.Text Justification/README_EN.md new file mode 100644 index 00000000..d640517a --- /dev/null +++ b/assets/0000-0099/0068.Text Justification/README_EN.md @@ -0,0 +1,96 @@ +# [68. Text Justification](https://leetcode.com/problems/text-justification) + + + +## Description + +

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

+ +

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

+ +

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

+ +

For the last line of text, it should be left justified and no extra space is inserted between words.

+ +

Note:

+ +
    +
  • A word is defined as a character sequence consisting of non-space characters only.
  • +
  • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
  • +
  • The input array words contains at least one word.
  • +
+ +

 

+

Example 1:

+ +
+Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
+Output:
+[
+   "This    is    an",
+   "example  of text",
+   "justification.  "
+]
+ +

Example 2:

+ +
+Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
+Output:
+[
+  "What   must   be",
+  "acknowledgment  ",
+  "shall be        "
+]
+Explanation: Note that the last line is "shall be    " instead of "shall     be", because the last line must be left-justified instead of fully-justified.
+Note that the second line is also left-justified becase it contains only one word.
+ +

Example 3:

+ +
+Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
+Output:
+[
+  "Science  is  what we",
+  "understand      well",
+  "enough to explain to",
+  "a  computer.  Art is",
+  "everything  else  we",
+  "do                  "
+]
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 300
  • +
  • 1 <= words[i].length <= 20
  • +
  • words[i] consists of only English letters and symbols.
  • +
  • 1 <= maxWidth <= 100
  • +
  • words[i].length <= maxWidth
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0069.Sqrt(x)/README_EN.md b/assets/0000-0099/0069.Sqrt(x)/README_EN.md new file mode 100644 index 00000000..e7cb14a0 --- /dev/null +++ b/assets/0000-0099/0069.Sqrt(x)/README_EN.md @@ -0,0 +1,179 @@ +# [69. Sqrt(x)](https://leetcode.com/problems/sqrtx) + + + +## Description + +

Given a non-negative integer x, compute and return the square root of x.

+ +

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

+ +

 

+

Example 1:

+ +
+Input: x = 4
+Output: 2
+
+ +

Example 2:

+ +
+Input: x = 8
+Output: 2
+Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
+ +

 

+

Constraints:

+ +
    +
  • 0 <= x <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def mySqrt(self, x: int) -> int: + if x == 0: + return 0 + left, right = 1, x + while left < right: + mid = (left + right + 1) >> 1 + # mid*mid <= x + if x // mid >= mid: + left = mid + else: + right = mid - 1 + return left +``` + +### **Java** + +```java +class Solution { + public int mySqrt(int x) { + if (x == 0) { + return 0; + } + int left = 1, right = x; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if (x / mid >= mid) { + // mid*mid <= x + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int mySqrt(int x) { + if (x == 0) { + return 0; + } + int left = 1, right = x; + while (left < right) { + int mid = left + ((right - left + 1) >> 1); + if (x / mid >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @return {number} + */ +var mySqrt = function(x) { + if (x == 0) { + return 0; + } + let left = 1; + let right = x; + while (left < right) { + const mid = (left + right + 1) >>> 1; + if (x / mid >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; +``` + +### **Go** + +```go +func mySqrt(x int) int { + if x == 0 { + return 0 + } + left, right := 1, x + for left < right { + mid := left + (right-left+1)>>1 + if x/mid >= mid { + left = mid + } else { + right = mid - 1 + } + } + return left +} +``` + +### **C#** + +```cs +public class Solution { + public int MySqrt(int x) { + if (x == 0) { + return 0; + } + int left = 1, right = x; + while (left < right) + { + int mid = left + right + 1 >> 1; + if (x / mid >= mid) + { + left = mid; + } + else + { + right = mid - 1; + } + } + return left; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0070.Climbing Stairs/README_EN.md b/assets/0000-0099/0070.Climbing Stairs/README_EN.md new file mode 100644 index 00000000..d87b590d --- /dev/null +++ b/assets/0000-0099/0070.Climbing Stairs/README_EN.md @@ -0,0 +1,126 @@ +# [70. Climbing Stairs](https://leetcode.com/problems/climbing-stairs) + + + +## Description + +

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

+ +

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

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 2
+Explanation: There are two ways to climb to the top.
+1. 1 step + 1 step
+2. 2 steps
+
+ +

Example 2:

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

 

+

Constraints:

+ +
    +
  • 1 <= n <= 45
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def climbStairs(self, n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return b +``` + +### **Java** + +```java +class Solution { + public int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { + let a = 0, + b = 1; + for (let i = 0; i < n; ++i) { + const c = a + b; + a = b; + b = c; + } + return b; +}; +``` + +### **Go** + +```go +func climbStairs(n int) int { + a, b := 0, 1 + for i := 0; i < n; i++ { + a, b = b, a + b + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0071.Simplify Path/README_EN.md b/assets/0000-0099/0071.Simplify Path/README_EN.md new file mode 100644 index 00000000..42947d56 --- /dev/null +++ b/assets/0000-0099/0071.Simplify Path/README_EN.md @@ -0,0 +1,86 @@ +# [71. Simplify Path](https://leetcode.com/problems/simplify-path) + + + +## Description + +

Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

+ +

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

+ +

The canonical path should have the following format:

+ +
    +
  • The path starts with a single slash '/'.
  • +
  • Any two directories are separated by a single slash '/'.
  • +
  • The path does not end with a trailing '/'.
  • +
  • The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
  • +
+ +

Return the simplified canonical path.

+ +

 

+

Example 1:

+ +
+Input: path = "/home/"
+Output: "/home"
+Explanation: Note that there is no trailing slash after the last directory name.
+
+ +

Example 2:

+ +
+Input: path = "/../"
+Output: "/"
+Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
+
+ +

Example 3:

+ +
+Input: path = "/home//foo/"
+Output: "/home/foo"
+Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
+
+ +

Example 4:

+ +
+Input: path = "/a/./b/../../c/"
+Output: "/c"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= path.length <= 3000
  • +
  • path consists of English letters, digits, period '.', slash '/' or '_'.
  • +
  • path is a valid absolute Unix path.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0072.Edit Distance/README_EN.md b/assets/0000-0099/0072.Edit Distance/README_EN.md new file mode 100644 index 00000000..f5c103e0 --- /dev/null +++ b/assets/0000-0099/0072.Edit Distance/README_EN.md @@ -0,0 +1,73 @@ +# [72. Edit Distance](https://leetcode.com/problems/edit-distance) + + + +## Description + +

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

+ +

You have the following three operations permitted on a word:

+ +
    +
  • Insert a character
  • +
  • Delete a character
  • +
  • Replace a character
  • +
+ +

 

+

Example 1:

+ +
+Input: word1 = "horse", word2 = "ros"
+Output: 3
+Explanation: 
+horse -> rorse (replace 'h' with 'r')
+rorse -> rose (remove 'r')
+rose -> ros (remove 'e')
+
+ +

Example 2:

+ +
+Input: word1 = "intention", word2 = "execution"
+Output: 5
+Explanation: 
+intention -> inention (remove 't')
+inention -> enention (replace 'i' with 'e')
+enention -> exention (replace 'n' with 'x')
+exention -> exection (replace 'n' with 'c')
+exection -> execution (insert 'u')
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= word1.length, word2.length <= 500
  • +
  • word1 and word2 consist of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0073.Set Matrix Zeroes/README_EN.md b/assets/0000-0099/0073.Set Matrix Zeroes/README_EN.md new file mode 100644 index 00000000..7e855203 --- /dev/null +++ b/assets/0000-0099/0073.Set Matrix Zeroes/README_EN.md @@ -0,0 +1,209 @@ +# [73. Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes) + + + +## Description + +

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

+ +

Follow up:

+ +
    +
  • A straight forward solution using O(mn) space is probably a bad idea.
  • +
  • A simple improvement uses O(m + n) space, but still not the best solution.
  • +
  • Could you devise a constant space solution?
  • +
+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
+Output: [[1,0,1],[0,0,0],[1,0,1]]
+
+ +

Example 2:

+ +
+Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
+Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[0].length
  • +
  • 1 <= m, n <= 200
  • +
  • -231 <= matrix[i][j] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +Solution 1: + +```python +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + m, n = len(matrix), len(matrix[0]) + zero_rows = [False] * m + zero_cols = [False] * n + for i in range(m): + for j in range(n): + if matrix[i][j] == 0: + zero_rows[i] = zero_cols[j] = True + for i in range(m): + for j in range(n): + if zero_rows[i] or zero_cols[j]: + matrix[i][j] = 0 +``` + +Solution 2: + +```python +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + m, n = len(matrix), len(matrix[0]) + first_row_has_zero = any(matrix[0][j] == 0 for j in range(n)) + first_col_has_zero = any(matrix[i][0] == 0 for i in range(m)) + + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] == 0: + matrix[i][0] = matrix[0][j] = 0 + + for i in range(1, m): + for j in range(1, n): + if matrix[i][0] == 0 or matrix[0][j] == 0: + matrix[i][j] = 0 + + if first_row_has_zero: + for j in range(n): + matrix[0][j] = 0 + + if first_col_has_zero: + for i in range(m): + matrix[i][0] = 0 +``` + +### **Java** + +Solution 1: + +```java +class Solution { + public void setZeroes(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + boolean[] zeroRows = new boolean[m]; + boolean[] zeroCols = new boolean[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == 0) { + zeroRows[i] = zeroCols[j] = true; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (zeroRows[i] || zeroCols[j]) { + matrix[i][j] = 0; + } + } + } + } +} +``` + +Solution 2: + +```java +class Solution { + public void setZeroes(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + boolean firstRowHasZero = false; + boolean firstColHasZero = false; + for (int j = 0; j < n; ++j) { + if (matrix[0][j] == 0) { + firstRowHasZero = true; + break; + } + } + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + firstColHasZero = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] == 0) { + matrix[i][0] = matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (firstRowHasZero) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (firstColHasZero) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + vector zeroRows(m), zeroCols(n); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 0) { + zeroRows[i] = zeroCols[j] = true; + } + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (zeroRows[i] || zeroCols[j]) { + matrix[i][j] = 0; + } + } + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0073.Set Matrix Zeroes/images/mat1.jpg b/assets/0000-0099/0073.Set Matrix Zeroes/images/mat1.jpg new file mode 100644 index 00000000..eb252a4b Binary files /dev/null and b/assets/0000-0099/0073.Set Matrix Zeroes/images/mat1.jpg differ diff --git a/assets/0000-0099/0073.Set Matrix Zeroes/images/mat2.jpg b/assets/0000-0099/0073.Set Matrix Zeroes/images/mat2.jpg new file mode 100644 index 00000000..af372d5f Binary files /dev/null and b/assets/0000-0099/0073.Set Matrix Zeroes/images/mat2.jpg differ diff --git a/assets/0000-0099/0074.Search a 2D Matrix/README_EN.md b/assets/0000-0099/0074.Search a 2D Matrix/README_EN.md new file mode 100644 index 00000000..81e9d23f --- /dev/null +++ b/assets/0000-0099/0074.Search a 2D Matrix/README_EN.md @@ -0,0 +1,155 @@ +# [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix) + + + +## Description + +

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

+ +
    +
  • Integers in each row are sorted from left to right.
  • +
  • The first integer of each row is greater than the last integer of the previous row.
  • +
+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
+Output: true
+
+ +

Example 2:

+ +
+Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • -104 <= matrix[i][j], target <= 104
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + left, right = 0, m * n - 1 + while left < right: + mid = (left + right) >> 1 + x, y = divmod(mid, n) + if matrix[x][y] >= target: + right = mid + else: + left = mid + 1 + return matrix[left // n][left % n] == target +``` + +### **Java** + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int left = 0, right = m * n - 1; + while (left < right) { + int mid = (left + right) >> 1; + int x = mid / n, y = mid % n; + if (matrix[x][y] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return matrix[left / n][left % n] == target; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int left = 0, right = m * n - 1; + while (left < right) { + int mid = left + right >> 1; + int x = mid / n, y = mid % n; + if (matrix[x][y] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return matrix[left / n][left % n] == target; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + const m = matrix.length; + const n = matrix[0].length; + let left = 0; + let right = m * n - 1; + while (left < right) { + const mid = (left + right) >> 1; + const x = Math.floor(mid / n); + const y = mid % n; + if (matrix[x][y] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return matrix[Math.floor(left / n)][left % n] == target; +}; +``` + +### **Go** + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + left, right := 0, m*n-1 + for left < right { + mid := (left + right) >> 1 + x, y := mid/n, mid%n + if matrix[x][y] >= target { + right = mid + } else { + left = mid + 1 + } + } + return matrix[left/n][left%n] == target +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0074.Search a 2D Matrix/images/mat.jpg b/assets/0000-0099/0074.Search a 2D Matrix/images/mat.jpg new file mode 100644 index 00000000..40824937 Binary files /dev/null and b/assets/0000-0099/0074.Search a 2D Matrix/images/mat.jpg differ diff --git a/assets/0000-0099/0074.Search a 2D Matrix/images/mat2.jpg b/assets/0000-0099/0074.Search a 2D Matrix/images/mat2.jpg new file mode 100644 index 00000000..9c46e777 Binary files /dev/null and b/assets/0000-0099/0074.Search a 2D Matrix/images/mat2.jpg differ diff --git a/assets/0000-0099/0075.Sort Colors/README_EN.md b/assets/0000-0099/0075.Sort Colors/README_EN.md new file mode 100644 index 00000000..702734b3 --- /dev/null +++ b/assets/0000-0099/0075.Sort Colors/README_EN.md @@ -0,0 +1,141 @@ +# [75. Sort Colors](https://leetcode.com/problems/sort-colors) + + + +## Description + +

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

+ +

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

+ +

 

+

Example 1:

+
Input: nums = [2,0,2,1,1,0]
+Output: [0,0,1,1,2,2]
+

Example 2:

+
Input: nums = [2,0,1]
+Output: [0,1,2]
+

Example 3:

+
Input: nums = [0]
+Output: [0]
+

Example 4:

+
Input: nums = [1]
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 300
  • +
  • nums[i] is 0, 1, or 2.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you solve this problem without using the library's sort function?
  • +
  • Could you come up with a one-pass algorithm using only O(1) constant space?
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + i, j = -1, len(nums) + cur = 0 + while cur < j: + if nums[cur] == 0: + i += 1 + nums[cur], nums[i] = nums[i], nums[cur] + cur += 1 + elif nums[cur] == 1: + cur += 1 + else: + j -= 1 + nums[cur], nums[j] = nums[j], nums[cur] +``` + +### **Java** + +```java +class Solution { + public void sortColors(int[] nums) { + int i = -1, j = nums.length; + int cur = 0; + while (cur < j) { + if (nums[cur] == 0) { + swap(nums, cur++, ++i); + } else if (nums[cur] == 1) { + ++cur; + } else { + swap(nums, cur, --j); + } + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + void sortColors(vector& nums) { + int i = -1, j = nums.size(), cur = 0; + while (cur < j) { + if (nums[cur] == 0) { + swap(nums[++i], nums[cur++]); + } else if (nums[cur] == 1) { + ++cur; + } else { + swap(nums[cur], nums[--j]); + } + } + } +}; +``` + +### **Go** + +```go +func sortColors(nums []int) { + i, j, cur := -1, len(nums), 0 + for cur < j { + if nums[cur] == 0 { + i++ + nums[cur], nums[i] = nums[i], nums[cur] + cur++ + } else if nums[cur] == 1 { + cur++ + } else { + j-- + nums[cur], nums[j] = nums[j], nums[cur] + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0076.Minimum Window Substring/README_EN.md b/assets/0000-0099/0076.Minimum Window Substring/README_EN.md new file mode 100644 index 00000000..3f5194b6 --- /dev/null +++ b/assets/0000-0099/0076.Minimum Window Substring/README_EN.md @@ -0,0 +1,92 @@ +# [76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring) + + + +## Description + +

Given two strings s and t, return the minimum window in s which will contain all the characters in t. If there is no such window in s that covers all characters in t, return the empty string "".

+ +

Note that If there is such a window, it is guaranteed that there will always be only one unique minimum window in s.

+ +

 

+

Example 1:

+
Input: s = "ADOBECODEBANC", t = "ABC"
+Output: "BANC"
+

Example 2:

+
Input: s = "a", t = "a"
+Output: "a"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 105
  • +
  • s and t consist of English letters.
  • +
+ +

 

+Follow up: Could you find an algorithm that runs in O(n) time? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **TypeScript** + +```ts +function minWindow(s: string, t: string): string { + let n1 = s.length, n2 = t.length; + if (n1 < n2) return ''; + let need = new Array(128).fill(0); + let window = new Array(128).fill(0); + for (let i = 0; i < n2; ++i) { + ++need[t.charCodeAt(i)]; + } + + let left = 0, right = 0; + let res = ''; + let count = 0; + let min = n1 + 1; + while (right < n1) { + let cur = s.charCodeAt(right); + ++window[cur]; + if (need[cur] > 0 && need[cur] >= window[cur]) { + ++count; + } + while (count == n2) { + cur = s.charCodeAt(left); + if (need[cur] > 0 && need[cur] >= window[cur]) { + --count; + } + if (right - left + 1 < min) { + min = right - left + 1; + res = s.slice(left, right + 1); + } + --window[cur]; + ++left; + } + ++right; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0077.Combinations/README_EN.md b/assets/0000-0099/0077.Combinations/README_EN.md new file mode 100644 index 00000000..aeaccd4a --- /dev/null +++ b/assets/0000-0099/0077.Combinations/README_EN.md @@ -0,0 +1,65 @@ +# [77. Combinations](https://leetcode.com/problems/combinations) + + + +## Description + +

Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].

+ +

You may return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: n = 4, k = 2
+Output:
+[
+  [2,4],
+  [3,4],
+  [2,3],
+  [1,2],
+  [1,3],
+  [1,4],
+]
+
+ +

Example 2:

+ +
+Input: n = 1, k = 1
+Output: [[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 20
  • +
  • 1 <= k <= n
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0078.Subsets/README_EN.md b/assets/0000-0099/0078.Subsets/README_EN.md new file mode 100644 index 00000000..57b483c7 --- /dev/null +++ b/assets/0000-0099/0078.Subsets/README_EN.md @@ -0,0 +1,86 @@ +# [78. Subsets](https://leetcode.com/problems/subsets) + + + +## Description + +

Given an integer array nums of unique elements, return all possible subsets (the power set).

+ +

The solution set must not contain duplicate subsets. Return the solution in any order.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3]
+Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
+
+ +

Example 2:

+ +
+Input: nums = [0]
+Output: [[],[0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
  • All the numbers of nums are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + def dfs(nums, i, res, path): + res.append(copy.deepcopy(path)) + while i < len(nums): + path.append(nums[i]) + dfs(nums, i + 1, res, path) + path.pop() + i += 1 + res, path = [], [] + dfs(nums, 0, res, path) + return res +``` + +### **Java** + +```java +class Solution { + public List> subsets(int[] nums) { + List path = new ArrayList<>(); + List> res = new ArrayList<>(); + dfs(nums, 0, res, path); + return res; + } + + private void dfs(int[] nums, int i, List> res, List path) { + res.add(new ArrayList<>(path)); + while (i < nums.length) { + path.add(nums[i]); + dfs(nums, i + 1, res, path); + path.remove(path.size() - 1); + ++i; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0079.Word Search/README_EN.md b/assets/0000-0099/0079.Word Search/README_EN.md new file mode 100644 index 00000000..cb4c2e61 --- /dev/null +++ b/assets/0000-0099/0079.Word Search/README_EN.md @@ -0,0 +1,159 @@ +# [79. Word Search](https://leetcode.com/problems/word-search) + + + +## Description + +

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

+ +

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

+ +

 

+

Example 1:

+ +
+Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
+Output: true
+
+ +

Example 2:

+ +
+Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
+Output: true
+
+ +

Example 3:

+ +
+Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n = board[i].length
  • +
  • 1 <= m, n <= 6
  • +
  • 1 <= word.length <= 15
  • +
  • board and word consists of only lowercase and uppercase English letters.
  • +
+ +

 

+

Follow up: Could you use search pruning to make your solution faster with a larger board?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + def dfs(i, j, cur): + if cur == len(word): + return True + if i < 0 or i >= m or j < 0 or j >= n or visited[i][j] or word[cur] != board[i][j]: + return False + visited[i][j] = True + next = cur + 1 + res = dfs(i + 1, j, next) or dfs(i - 1, j, next) or dfs(i, j + 1, next) or dfs(i, j - 1, next) + visited[i][j] = False + return res + m, n = len(board), len(board[0]) + visited = [[False for _ in range(n)] for _ in range(m)] + for i in range(m): + for j in range(n): + res = dfs(i, j, 0) + if res: + return True + return False +``` + +### **Java** + +```java +class Solution { + private boolean[][] visited; + + public boolean exist(char[][] board, String word) { + int m = board.length, n = board[0].length; + visited = new boolean[m][n]; + char[] chars = word.toCharArray(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + boolean res = dfs(board, i, j, chars, 0); + if (res) return true; + } + } + return false; + } + + private boolean dfs(char[][] board, int i, int j, char[] chars, int cur) { + if (cur == chars.length) return true; + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; + if (visited[i][j] || board[i][j] != chars[cur]) return false; + visited[i][j] = true; + int next = cur + 1; + boolean res = dfs(board, i + 1, j, chars, next) + || dfs(board, i - 1, j, chars, next) + || dfs(board, i, j + 1, chars, next) + || dfs(board, i, j - 1, chars, next); + visited[i][j] = false; + return res; + } +} +``` + +### **TypeScript** + +```ts +function exist(board: string[][], word: string): boolean { + let m = board.length, n = board[0].length; + let visited = Array.from({ length: m }, v => new Array(n).fill(false)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (dfs(board, word, i, j, 0, visited)) { + return true; + } + } + } + return false; +}; + +function dfs(board: string[][], word: string, i: number, j: number, depth: number, visited: boolean[][]): boolean { + let m = board.length, n = board[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || visited[i][j]) { + return false; + } + if (board[i][j] != word.charAt(depth)) { + return false; + } + + if (depth == word.length - 1) { + return true; + } + + visited[i][j] = true; + ++depth; + let res = false; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + res = res || dfs(board, word, x, y, depth, visited); + } + visited[i][j] = false; + return res; +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0079.Word Search/images/word-1.jpg b/assets/0000-0099/0079.Word Search/images/word-1.jpg new file mode 100644 index 00000000..42aec09d Binary files /dev/null and b/assets/0000-0099/0079.Word Search/images/word-1.jpg differ diff --git a/assets/0000-0099/0079.Word Search/images/word2.jpg b/assets/0000-0099/0079.Word Search/images/word2.jpg new file mode 100644 index 00000000..2175d7ce Binary files /dev/null and b/assets/0000-0099/0079.Word Search/images/word2.jpg differ diff --git a/assets/0000-0099/0079.Word Search/images/word3.jpg b/assets/0000-0099/0079.Word Search/images/word3.jpg new file mode 100644 index 00000000..d614a938 Binary files /dev/null and b/assets/0000-0099/0079.Word Search/images/word3.jpg differ diff --git a/assets/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md b/assets/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md new file mode 100644 index 00000000..f479b5af --- /dev/null +++ b/assets/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md @@ -0,0 +1,157 @@ +# [80. Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii) + + + +## Description + +

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

+ +

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

+ +

Clarification:

+ +

Confused why the returned value is an integer, but your answer is an array?

+ +

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller.

+ +

Internally you can think of this:

+ +
+// nums is passed in by reference. (i.e., without making a copy)
+int len = removeDuplicates(nums);
+
+// any modification to nums in your function would be known by the caller.
+// using the length returned by your function, it prints the first len elements.
+for (int i = 0; i < len; i++) {
+    print(nums[i]);
+}
+
+ +

 

+

Example 1:

+ +
+Input: nums = [1,1,1,2,2,3]
+Output: 5, nums = [1,1,2,2,3]
+Explanation: Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It doesn't matter what you leave beyond the returned length.
+
+ +

Example 2:

+ +
+Input: nums = [0,0,1,1,1,1,2,3,3]
+Output: 7, nums = [0,0,1,1,2,3,3]
+Explanation: Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond the returned length.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + n = len(nums) + cnt, cur = 0, 1 + for i in range(1, n): + if nums[i] == nums[i - 1]: + cnt += 1 + else: + cnt = 0 + if cnt < 2: + nums[cur] = nums[i] + cur += 1 + return cur +``` + +### **Java** + +```java +class Solution { + public int removeDuplicates(int[] nums) { + int cnt = 0, cur = 1; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else cnt = 0; + if (cnt < 2) nums[cur++] = nums[i]; + } + return cur; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + int n = nums.size(); + int cnt = 0, cur = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else cnt = 0; + if (cnt < 2) nums[cur++] = nums[i]; + } + return cur; + } +}; +``` + +### **C#** + +```cs +public class Solution { + public int RemoveDuplicates(int[] nums) { + int cnt = 0, cur = 1; + for (int i = 1; i < nums.Length; ++i) + { + if (nums[i] == nums[i - 1]) ++cnt; + else cnt = 0; + if (cnt < 2) nums[cur++] = nums[i]; + } + return cur; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function (nums) { + if (nums.length == 0) return 0; + let len = nums.length; + let j = 0; + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] != nums[i - 1] || nums[i] != nums[i + 1]) { + nums[j++] = nums[i]; + } + } + nums[j] = nums[len - 1]; + return j + 1; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md b/assets/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md new file mode 100644 index 00000000..733f5b7b --- /dev/null +++ b/assets/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md @@ -0,0 +1,116 @@ +# [81. Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii) + + + +## Description + +

There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

+ +

Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].

+ +

Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

+ +

 

+

Example 1:

+
Input: nums = [2,5,6,0,0,1,2], target = 0
+Output: true
+

Example 2:

+
Input: nums = [2,5,6,0,0,1,2], target = 3
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is guaranteed to be rotated at some pivot.
  • +
  • -104 <= target <= 104
  • +
+ +

 

+Follow up: This problem is the same as Search in Rotated Sorted Array, where nums may contain duplicates. Would this affect the runtime complexity? How and why? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def search(self, nums: List[int], target: int) -> bool: + l, r = 0, len(nums) - 1 + while l <= r: + mid = (l + r) >> 1 + if nums[mid] == target: + return True + if nums[mid] < nums[r] or nums[mid] < nums[l]: + if target > nums[mid] and target <= nums[r]: + l = mid + 1 + else: + r = mid - 1 + elif nums[mid] > nums[l] or nums[mid] > nums[r]: + if target < nums[mid] and target >= nums[l]: + r = mid - 1 + else: + l = mid + 1 + else: + r -= 1 + return False +``` + +### **Java** + +```java +class Solution { + public boolean search(int[] nums, int target) { + int l = 0, r = nums.length - 1; + while (l <= r) { + int mid = (l + r) >>> 1; + if (nums[mid] == target) return true; + if (nums[mid] < nums[r] || nums[mid] < nums[l]) { + if (target > nums[mid] && target <= nums[r]) l = mid + 1; + else r = mid - 1; + } else if (nums[mid] > nums[l] || nums[mid] > nums[r]) { + if (target < nums[mid] && target >= nums[l]) r = mid - 1; + else l = mid + 1; + } else r--; + } + return false; + } +} +``` + +### **C++** + + + +```cpp +class Solution { +public: + bool search(vector& nums, int target) { + int l = 0, r = nums.size() - 1; + while (l <= r) { + int mid = (l + r) >> 1; + if (nums[mid] == target) return true; + if (nums[mid] < nums[r] || nums[mid] < nums[l]) { + if (target > nums[mid] && target <= nums[r]) l = mid + 1; + else r = mid - 1; + } else if (nums[mid] > nums[l] || nums[mid] > nums[r]) { + if (target < nums[mid] && target >= nums[l]) r = mid - 1; + else l = mid + 1; + } else r--; + } + return false; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md b/assets/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md new file mode 100644 index 00000000..9968e021 --- /dev/null +++ b/assets/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md @@ -0,0 +1,131 @@ +# [82. Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii) + + + +## Description + +

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,3,4,4,5]
+Output: [1,2,5]
+
+ +

Example 2:

+ +
+Input: head = [1,1,1,2,3]
+Output: [2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 300].
  • +
  • -100 <= Node.val <= 100
  • +
  • The list is guaranteed to be sorted in ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + dummy = ListNode(-1, head) + cur = dummy + while cur.next and cur.next.next: + if cur.next.val == cur.next.next.val: + val = cur.next.val + while cur.next and cur.next.val == val: + cur.next = cur.next.next + else: + cur = cur.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(-1, head); + ListNode cur = dummy; + while (cur.next != null && cur.next.next != null) { + if (cur.next.val == cur.next.next.val) { + int val = cur.next.val; + while (cur.next != null && cur.next.val == val) { + cur.next = cur.next.next; + } + } else { + cur = cur.next; + } + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* dummy = new ListNode(-1, head); + ListNode* cur = dummy; + while (cur->next != nullptr && cur->next->next != nullptr) { + if (cur->next->val == cur->next->next->val) { + int val = cur->next->val; + while (cur->next != nullptr && cur->next->val == val) { + cur->next = cur->next->next; + } + } else { + cur = cur->next; + } + } + return dummy->next; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0082.Remove Duplicates from Sorted List II/images/linkedlist1.jpg b/assets/0000-0099/0082.Remove Duplicates from Sorted List II/images/linkedlist1.jpg new file mode 100644 index 00000000..2861b1d6 Binary files /dev/null and b/assets/0000-0099/0082.Remove Duplicates from Sorted List II/images/linkedlist1.jpg differ diff --git a/assets/0000-0099/0082.Remove Duplicates from Sorted List II/images/linkedlist2.jpg b/assets/0000-0099/0082.Remove Duplicates from Sorted List II/images/linkedlist2.jpg new file mode 100644 index 00000000..7f25d174 Binary files /dev/null and b/assets/0000-0099/0082.Remove Duplicates from Sorted List II/images/linkedlist2.jpg differ diff --git a/assets/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md b/assets/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md new file mode 100644 index 00000000..cc10a471 --- /dev/null +++ b/assets/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md @@ -0,0 +1,136 @@ +# [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list) + + + +## Description + +

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

+ +

 

+

Example 1:

+ +
+Input: head = [1,1,2]
+Output: [1,2]
+
+ +

Example 2:

+ +
+Input: head = [1,1,2,3,3]
+Output: [1,2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 300].
  • +
  • -100 <= Node.val <= 100
  • +
  • The list is guaranteed to be sorted in ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + cur = head + while cur and cur.next: + if cur.val == cur.next.val: + cur.next = cur.next.next + else: + cur = cur.next + return head +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode cur = head; + while (cur != null && cur.next != null) { + if (cur.val == cur.next.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return head; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* cur = head; + while (cur != nullptr && cur->next != nullptr) { + if (cur->val == cur->next->val) { + cur->next = cur->next->next; + } else { + cur = cur->next; + } + } + return head; + } +}; +``` + +### **Go** + +```go +func deleteDuplicates(head *ListNode) *ListNode { + current := head + for current != nil && current.Next != nil { + if current.Val == current.Next.Val { + current.Next = current.Next.Next + } else { + current = current.Next + } + } + return head +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0083.Remove Duplicates from Sorted List/images/list1.jpg b/assets/0000-0099/0083.Remove Duplicates from Sorted List/images/list1.jpg new file mode 100644 index 00000000..e05337a4 Binary files /dev/null and b/assets/0000-0099/0083.Remove Duplicates from Sorted List/images/list1.jpg differ diff --git a/assets/0000-0099/0083.Remove Duplicates from Sorted List/images/list2.jpg b/assets/0000-0099/0083.Remove Duplicates from Sorted List/images/list2.jpg new file mode 100644 index 00000000..84b0cc39 Binary files /dev/null and b/assets/0000-0099/0083.Remove Duplicates from Sorted List/images/list2.jpg differ diff --git a/assets/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md b/assets/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md new file mode 100644 index 00000000..211da2ee --- /dev/null +++ b/assets/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md @@ -0,0 +1,57 @@ +# [84. Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram) + + + +## Description + +

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

+ +

 

+

Example 1:

+ +
+Input: heights = [2,1,5,6,2,3]
+Output: 10
+Explanation: The above is a histogram where width of each bar is 1.
+The largest rectangle is shown in the red area, which has an area = 10 units.
+
+ +

Example 2:

+ +
+Input: heights = [2,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= heights.length <= 105
  • +
  • 0 <= heights[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0084.Largest Rectangle in Histogram/images/histogram.png b/assets/0000-0099/0084.Largest Rectangle in Histogram/images/histogram.png new file mode 100644 index 00000000..43600013 Binary files /dev/null and b/assets/0000-0099/0084.Largest Rectangle in Histogram/images/histogram.png differ diff --git a/assets/0000-0099/0084.Largest Rectangle in Histogram/images/histogram_area.png b/assets/0000-0099/0084.Largest Rectangle in Histogram/images/histogram_area.png new file mode 100644 index 00000000..7a1a0ca9 Binary files /dev/null and b/assets/0000-0099/0084.Largest Rectangle in Histogram/images/histogram_area.png differ diff --git a/assets/0000-0099/0085.Maximal Rectangle/README_EN.md b/assets/0000-0099/0085.Maximal Rectangle/README_EN.md new file mode 100644 index 00000000..dcfcaefa --- /dev/null +++ b/assets/0000-0099/0085.Maximal Rectangle/README_EN.md @@ -0,0 +1,79 @@ +# [85. Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle) + + + +## Description + +

Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
+Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 6
+Explanation: The maximal rectangle is shown in the above picture.
+
+ +

Example 2:

+ +
+Input: matrix = []
+Output: 0
+
+ +

Example 3:

+ +
+Input: matrix = [["0"]]
+Output: 0
+
+ +

Example 4:

+ +
+Input: matrix = [["1"]]
+Output: 1
+
+ +

Example 5:

+ +
+Input: matrix = [["0","0"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • rows == matrix.length
  • +
  • cols == matrix[i].length
  • +
  • 0 <= row, cols <= 200
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0085.Maximal Rectangle/images/maximal.jpg b/assets/0000-0099/0085.Maximal Rectangle/images/maximal.jpg new file mode 100644 index 00000000..c7fa5b6c Binary files /dev/null and b/assets/0000-0099/0085.Maximal Rectangle/images/maximal.jpg differ diff --git a/assets/0000-0099/0086.Partition List/README_EN.md b/assets/0000-0099/0086.Partition List/README_EN.md new file mode 100644 index 00000000..d1f02a6d --- /dev/null +++ b/assets/0000-0099/0086.Partition List/README_EN.md @@ -0,0 +1,142 @@ +# [86. Partition List](https://leetcode.com/problems/partition-list) + + + +## Description + +

Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

+ +

You should preserve the original relative order of the nodes in each of the two partitions.

+ +

 

+

Example 1:

+ +
+Input: head = [1,4,3,2,5,2], x = 3
+Output: [1,2,2,4,3,5]
+
+ +

Example 2:

+ +
+Input: head = [2,1], x = 2
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 200].
  • +
  • -100 <= Node.val <= 100
  • +
  • -200 <= x <= 200
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def partition(self, head: ListNode, x: int) -> ListNode: + l1, l2 = ListNode(), ListNode() + cur1, cur2 = l1, l2 + while head: + if head.val < x: + cur1.next = head + cur1 = cur1.next + else: + cur2.next = head + cur2 = cur2.next + head = head.next + cur1.next = l2.next + cur2.next = None + return l1.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode partition(ListNode head, int x) { + ListNode l1 = new ListNode(0); + ListNode l2 = new ListNode(0); + ListNode cur1 = l1, cur2 = l2; + while (head != null) { + if (head.val < x) { + cur1.next = head; + cur1 = cur1.next; + } else { + cur2.next = head; + cur2 = cur2.next; + } + head = head.next; + } + cur1.next = l2.next; + cur2.next = null; + return l1.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + ListNode* l1 = new ListNode(); + ListNode* l2 = new ListNode(); + ListNode* cur1 = l1; + ListNode* cur2 = l2; + while (head != nullptr) { + if (head->val < x) { + cur1->next = head; + cur1 = cur1->next; + } else { + cur2->next = head; + cur2 = cur2->next; + } + head = head->next; + } + cur1->next = l2->next; + cur2->next = nullptr; + return l1->next; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0086.Partition List/images/partition.jpg b/assets/0000-0099/0086.Partition List/images/partition.jpg new file mode 100644 index 00000000..1c6c3014 Binary files /dev/null and b/assets/0000-0099/0086.Partition List/images/partition.jpg differ diff --git a/assets/0000-0099/0087.Scramble String/README_EN.md b/assets/0000-0099/0087.Scramble String/README_EN.md new file mode 100644 index 00000000..b30d4f27 --- /dev/null +++ b/assets/0000-0099/0087.Scramble String/README_EN.md @@ -0,0 +1,129 @@ +# [87. Scramble String](https://leetcode.com/problems/scramble-string) + + + +## Description + +

We can scramble a string s to get a string t using the following algorithm:

+ +
    +
  1. If the length of the string is 1, stop.
  2. +
  3. If the length of the string is > 1, do the following: +
      +
    • Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.
    • +
    • Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.
    • +
    • Apply step 1 recursively on each of the two substrings x and y.
    • +
    +
  4. +
+ +

Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.

+ +

 

+

Example 1:

+ +
+Input: s1 = "great", s2 = "rgeat"
+Output: true
+Explanation: One possible scenario applied on s1 is:
+"great" --> "gr/eat" // divide at random index.
+"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
+"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at ranom index each of them.
+"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
+"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
+"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
+The algorithm stops now and the result string is "rgeat" which is s2.
+As there is one possible scenario that led s1 to be scrambled to s2, we return true.
+
+ +

Example 2:

+ +
+Input: s1 = "abcde", s2 = "caebd"
+Output: false
+
+ +

Example 3:

+ +
+Input: s1 = "a", s2 = "a"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • s1.length == s2.length
  • +
  • 1 <= s1.length <= 30
  • +
  • s1 and s2 consist of lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isScramble(self, s1: str, s2: str) -> bool: + n = len(s1) + dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] + for i in range(n): + for j in range(n): + dp[i][j][1] = s1[i] == s2[j] + for l in range(2, n + 1): + for i1 in range(n - l + 1): + for i2 in range(n - l + 1): + for i in range(1, l): + if dp[i1][i2][i] and dp[i1 + i][i2 + i][l - i]: + dp[i1][i2][l] = True + break + if dp[i1][i2 + l - i][i] and dp[i1 + i][i2][l - i]: + dp[i1][i2][l] = True + break + return dp[0][0][n] +``` + +### **Java** + +```java +class Solution { + public boolean isScramble(String s1, String s2) { + int n = s1.length(); + boolean[][][] dp = new boolean[n][n][n + 1]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + dp[i][j][1] = s1.charAt(i) == s2.charAt(j); + } + } + for (int len = 2; len <= n; ++len) { + for (int i1 = 0; i1 <= n - len; ++i1) { + for (int i2 = 0; i2 <= n - len; ++i2) { + for (int i = 1; i < len; ++i) { + if (dp[i1][i2][i] && dp[i1 + i][i2 + i][len - i]) { + dp[i1][i2][len] = true; + break; + } + if (dp[i1][i2 + len - i][i] && dp[i1 + i][i2][len - i]) { + dp[i1][i2][len] = true; + break; + } + } + } + } + } + return dp[0][0][n]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0087.Scramble String/images/demo.png b/assets/0000-0099/0087.Scramble String/images/demo.png new file mode 100644 index 00000000..4d40b115 Binary files /dev/null and b/assets/0000-0099/0087.Scramble String/images/demo.png differ diff --git a/assets/0000-0099/0088.Merge Sorted Array/README_EN.md b/assets/0000-0099/0088.Merge Sorted Array/README_EN.md new file mode 100644 index 00000000..2fe51a2c --- /dev/null +++ b/assets/0000-0099/0088.Merge Sorted Array/README_EN.md @@ -0,0 +1,119 @@ +# [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array) + + + +## Description + +

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

+ +

The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.

+ +

 

+

Example 1:

+
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
+Output: [1,2,2,3,5,6]
+

Example 2:

+
Input: nums1 = [1], m = 1, nums2 = [], n = 0
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • nums1.length == m + n
  • +
  • nums2.length == n
  • +
  • 0 <= m, n <= 200
  • +
  • 1 <= m + n <= 200
  • +
  • -109 <= nums1[i], nums2[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + i, j, k = m - 1, n - 1, m + n - 1 + while j >= 0: + if i >= 0 and nums1[i] > nums2[j]: + nums1[k] = nums1[i] + i -= 1 + else: + nums1[k] = nums2[j] + j -= 1 + k -= 1 +``` + +### **Java** + +```java +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = m - 1, j = n - 1, k = m + n - 1; + while (j >= 0) { + if (i >= 0 && nums1[i] > nums2[j]) { + nums1[k--] = nums1[i--]; + } else { + nums1[k--] = nums2[j--]; + } + } + } +} +``` + +### **Go** + +```go +func merge(nums1 []int, m int, nums2 []int, n int) { + i, j, k := m - 1, n - 1, m + n - 1 + for j >= 0 { + if i >= 0 && nums1[i] > nums2[j] { + nums1[k] = nums1[i] + i-- + } else { + nums1[k] = nums2[j] + j-- + } + k-- + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number} m + * @param {number[]} nums2 + * @param {number} n + * @return {void} Do not return anything, modify nums1 in-place instead. + */ +var merge = function (nums1, m, nums2, n) { + let i = m - 1, + j = n - 1, + k = m + n - 1; + while (j >= 0) { + if (i >= 0 && nums1[i] > nums2[j]) { + nums1[k--] = nums1[i--]; + } else { + nums1[k--] = nums2[j--]; + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0089.Gray Code/README_EN.md b/assets/0000-0099/0089.Gray Code/README_EN.md new file mode 100644 index 00000000..0ce4b02e --- /dev/null +++ b/assets/0000-0099/0089.Gray Code/README_EN.md @@ -0,0 +1,68 @@ +# [89. Gray Code](https://leetcode.com/problems/gray-code) + + + +## Description + +

The gray code is a binary numeral system where two successive values differ in only one bit.

+ +

Given an integer n representing the total number of bits in the code, return any sequence of gray code.

+ +

A gray code sequence must begin with 0.

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: [0,1,3,2]
+Explanation:
+00 - 0
+01 - 1
+11 - 3
+10 - 2
+[0,2,3,1] is also a valid gray code sequence.
+00 - 0
+10 - 2
+11 - 3
+01 - 1
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 16
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0090.Subsets II/README_EN.md b/assets/0000-0099/0090.Subsets II/README_EN.md new file mode 100644 index 00000000..3adf150d --- /dev/null +++ b/assets/0000-0099/0090.Subsets II/README_EN.md @@ -0,0 +1,83 @@ +# [90. Subsets II](https://leetcode.com/problems/subsets-ii) + + + +## Description + +

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

+ +

The solution set must not contain duplicate subsets. Return the solution in any order.

+ +

 

+

Example 1:

+
Input: nums = [1,2,2]
+Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
+

Example 2:

+
Input: nums = [0]
+Output: [[],[0]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 10
  • +
  • -10 <= nums[i] <= 10
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + def dfs(nums, i, res, path): + res.append(copy.deepcopy(path)) + for j in range(i, len(nums)): + if j != i and nums[j] == nums[j - 1]: + continue + path.append(nums[j]) + dfs(nums, j + 1, res, path) + path.pop() + res, path = [], [] + nums.sort() + dfs(nums, 0, res, path) + return res +``` + +### **Java** + +```java +class Solution { + public List> subsetsWithDup(int[] nums) { + List path = new ArrayList<>(); + List> res = new ArrayList<>(); + Arrays.sort(nums); + dfs(nums, 0, res, path); + return res; + } + + private void dfs(int[] nums, int i, List> res, List path) { + res.add(new ArrayList<>(path)); + for (int j = i; j < nums.length; ++j) { + if (j != i && nums[j] == nums[j - 1]) { + continue; + } + path.add(nums[j]); + dfs(nums, i + 1, res, path); + path.remove(path.size() - 1); + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0091.Decode Ways/README_EN.md b/assets/0000-0099/0091.Decode Ways/README_EN.md new file mode 100644 index 00000000..e3af2127 --- /dev/null +++ b/assets/0000-0099/0091.Decode Ways/README_EN.md @@ -0,0 +1,241 @@ +# [91. Decode Ways](https://leetcode.com/problems/decode-ways) + + + +## Description + +

A message containing letters from A-Z can be encoded into numbers using the following mapping:

+ +
+'A' -> "1"
+'B' -> "2"
+...
+'Z' -> "26"
+
+ +

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

+ +
    +
  • "AAJF" with the grouping (1 1 10 6)
  • +
  • "KJF" with the grouping (11 10 6)
  • +
+ +

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

+ +

Given a string s containing only digits, return the number of ways to decode it.

+ +

The answer is guaranteed to fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
+Input: s = "12"
+Output: 2
+Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
+
+ +

Example 2:

+ +
+Input: s = "226"
+Output: 3
+Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
+
+ +

Example 3:

+ +
+Input: s = "0"
+Output: 0
+Explanation: There is no character that is mapped to a number starting with 0.
+The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0.
+Hence, there are no valid ways to decode this since all digits need to be mapped.
+
+ +

Example 4:

+ +
+Input: s = "06"
+Output: 0
+Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s contains only digits and may contain leading zero(s).
  • +
+ + +## Solutions + +Dynamic programming. + + + +### **Python3** + +Solution1: + +```python +class Solution: + def numDecodings(self, s: str) -> int: + n = len(s) + dp = [0] * (n + 1) + dp[0] = 1 + for i in range(1, n + 1): + if s[i - 1] != '0': + dp[i] += dp[i - 1] + if i > 1 and s[i - 2] != '0' and (int(s[i - 2]) * 10 + int(s[i - 1]) <= 26): + dp[i] += dp[i - 2] + return dp[n] +``` + +Solution2: + +```python +class Solution: + def numDecodings(self, s: str) -> int: + n = len(s) + a, b, c = 0, 1, 0 + for i in range(1, n + 1): + c = 0 + if s[i - 1] != '0': + c += b + if i > 1 and s[i - 2] != '0' and (int(s[i - 2]) * 10 + int(s[i - 1]) <= 26): + c += a + a, b = b, c + return c +``` + +### **Java** + +Solution1: + +```java +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s.charAt(i - 1) != '0') { + dp[i] += dp[i - 1]; + } + if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + s.charAt(i - 1) - '0') <= 26) { + dp[i] += dp[i - 2]; + } + } + return dp[n]; + } +} +``` + +Solution2: + +```java +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int a = 0, b = 1, c = 0; + for (int i = 1; i <= n; ++i) { + c = 0; + if (s.charAt(i - 1) != '0') { + c += b; + } + if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + s.charAt(i - 1) - '0') <= 26) { + c += a; + } + a = b; + b = c; + } + return c; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); + vector dp(n + 1); + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s[i - 1] != '0') { + dp[i] += dp[i - 1]; + } + if (i > 1 && s[i - 2] != '0') { + if ((s[i - 2] - '0') * 10 + s[i - 1] - '0' <= 26) { + dp[i] += dp[i - 2]; + } + } + } + return dp[n]; + } +}; +``` + +### **Go** + +```go +func numDecodings(s string) int { + n := len(s) + dp := make([]int, n+1) + dp[0] = 1 + for i := 1; i <= n; i++ { + if s[i-1] != '0' { + dp[i] += dp[i-1] + } + if i > 1 && s[i-2] != '0' { + if (s[i-2]-'0')*10+(s[i-1]-'0') <= 26 { + dp[i] += dp[i-2] + } + } + } + return dp[n] +} +``` + +### **C#** + +```cs +public class Solution { + public int NumDecodings(string s) { + if (s.Length == 0) return 0; + + var f0 = 1; + var f1 = 1; + var f2 = 1; + for (var i = 0; i < s.Length; ++i) + { + f0 = f1; + f1 = f2; + f2 = 0; + var two = i > 0 ? int.Parse(string.Format("{0}{1}", s[i - 1], s[i])) : 0; + if (two >= 10 && two <= 26) + { + f2 += f0; + } + if (s[i] != '0') + { + f2 += f1; + } + } + return f2; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0092.Reverse Linked List II/README_EN.md b/assets/0000-0099/0092.Reverse Linked List II/README_EN.md new file mode 100644 index 00000000..8d2424ad --- /dev/null +++ b/assets/0000-0099/0092.Reverse Linked List II/README_EN.md @@ -0,0 +1,235 @@ +# [92. Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii) + + + +## Description + +

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5], left = 2, right = 4
+Output: [1,4,3,2,5]
+
+ +

Example 2:

+ +
+Input: head = [5], left = 1, right = 1
+Output: [5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is n.
  • +
  • 1 <= n <= 500
  • +
  • -500 <= Node.val <= 500
  • +
  • 1 <= left <= right <= n
  • +
+ +

 

+Follow up: Could you do it in one pass? + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: + if head is None or head.next is None or left == right: + return head + dummy = ListNode(0, head) + pre = dummy + for _ in range(left - 1): + pre = pre.next + p, q = pre, pre.next + cur = q + for _ in range(right - left + 1): + t = cur.next + cur.next = pre + pre, cur = cur, t + p.next = pre + q.next = cur + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseBetween(ListNode head, int left, int right) { + if (head == null || head.next == null || left == right) { + return head; + } + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + for (int i = 0; i < left - 1; ++i) { + pre = pre.next; + } + ListNode p = pre; + ListNode q = pre.next; + ListNode cur = q; + for (int i = 0; i < right - left + 1; ++i) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} left + * @param {number} right + * @return {ListNode} + */ +var reverseBetween = function(head, left, right) { + if (!head || !head.next || left == right) { + return head; + } + const dummy = new ListNode(0, head); + let pre = dummy; + for (let i = 0; i < left - 1; ++i) { + pre = pre.next; + } + const p = pre; + const q = pre.next; + let cur = q; + for (let i = 0; i < right - left + 1; ++i) { + const t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int left, int right) { + if (head == nullptr || head->next == nullptr || left == right) { + return head; + } + ListNode *dummy = new ListNode(0, head); + ListNode *pre = dummy; + for (int i = 0; i < left - 1; ++i) { + pre = pre->next; + } + ListNode *p = pre, *q = pre->next; + ListNode *cur = q; + for (int i = 0; i < right - left + 1; ++i) { + ListNode *t = cur->next; + cur->next = pre; + pre = cur; + cur = t; + } + p->next = pre; + q->next = cur; + return dummy->next; + } +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseBetween(ListNode head, int left, int right) { + if (head == null || head.next == null || left == right) + { + return head; + } + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + for (int i = 0; i < left - 1; ++i) + { + pre = pre.next; + } + ListNode p = pre; + ListNode q = pre.next; + ListNode cur = q; + for (int i = 0; i < right - left + 1; ++i) + { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0092.Reverse Linked List II/images/rev2ex2.jpg b/assets/0000-0099/0092.Reverse Linked List II/images/rev2ex2.jpg new file mode 100644 index 00000000..445def22 Binary files /dev/null and b/assets/0000-0099/0092.Reverse Linked List II/images/rev2ex2.jpg differ diff --git a/assets/0000-0099/0093.Restore IP Addresses/README_EN.md b/assets/0000-0099/0093.Restore IP Addresses/README_EN.md new file mode 100644 index 00000000..6200fe55 --- /dev/null +++ b/assets/0000-0099/0093.Restore IP Addresses/README_EN.md @@ -0,0 +1,59 @@ +# [93. Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses) + + + +## Description + +

Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s. You can return them in any order.

+ +

A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single dots and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. 

+ +

 

+

Example 1:

+
Input: s = "25525511135"
+Output: ["255.255.11.135","255.255.111.35"]
+

Example 2:

+
Input: s = "0000"
+Output: ["0.0.0.0"]
+

Example 3:

+
Input: s = "1111"
+Output: ["1.1.1.1"]
+

Example 4:

+
Input: s = "010010"
+Output: ["0.10.0.10","0.100.1.0"]
+

Example 5:

+
Input: s = "101023"
+Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 3000
  • +
  • s consists of digits only.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md b/assets/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md new file mode 100644 index 00000000..fc0bf9ba --- /dev/null +++ b/assets/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md @@ -0,0 +1,237 @@ +# [94. Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal) + + + +## Description + +

Given the root of a binary tree, return the inorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,2,3]
+Output: [1,3,2]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
+Input: root = [1,2]
+Output: [2,1]
+
+ +

Example 5:

+ +
+Input: root = [1,null,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+ +

Follow up:

+ +

Recursive solution is trivial, could you do it iteratively?

+ +

 

+ + +## Solutions + + + +### **Python3** + +Recusive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + def inorder(root): + if root: + inorder(root.left) + res.append(root.val) + inorder(root.right) + res = [] + inorder(root) + return res +``` + +Non-recursive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + s = [] + res = [] + while root or s: + if root: + s.append(root) + root = root.left + else: + root = s.pop() + res.append(root.val) + root = root.right + return res +``` + +### **Java** + +Recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private List res; + + public List inorderTraversal(TreeNode root) { + res = new ArrayList<>(); + inorder(root); + return res; + } + + private void inorder(TreeNode root) { + if (root != null) { + inorder(root.left); + res.add(root.val); + inorder(root.right); + } + } +} +``` + +Non-recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List inorderTraversal(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + List res = new ArrayList<>(); + Deque s = new ArrayDeque<>(); + while (root != null || !s.isEmpty()) { + if (root != null) { + s.push(root); + root = root.left; + } else { + root = s.pop(); + res.add(root.val); + root = root.right; + } + } + return res; + } +} +``` +### **JavaScript** + +Recursive: + +```js +var inorderTraversal = function(root) { + let res = []; + function inorder(root){ + if(root){ + inorder(root.left); + res.push(root.val); + inorder(root.right); + } + } + inorder(root); + return res; +}; +``` +Non-recursive: + +```js +var inorderTraversal = function (root) { + let res = [], stk = []; + let cur = root; + while (cur || stk.length !== 0) { + while (cur) { + stk.push(cur); + cur = cur.left; + } + let top = stk.pop(); + res.push(top.val); + cur = top.right; + + } + return res; +}; +``` + + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_1.jpg b/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_1.jpg new file mode 100644 index 00000000..98c26f26 Binary files /dev/null and b/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_1.jpg differ diff --git a/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_4.jpg b/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_4.jpg new file mode 100644 index 00000000..667c51b6 Binary files /dev/null and b/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_4.jpg differ diff --git a/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_5.jpg b/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_5.jpg new file mode 100644 index 00000000..abd71d00 Binary files /dev/null and b/assets/0000-0099/0094.Binary Tree Inorder Traversal/images/inorder_5.jpg differ diff --git a/assets/0000-0099/0095.Unique Binary Search Trees II/README_EN.md b/assets/0000-0099/0095.Unique Binary Search Trees II/README_EN.md new file mode 100644 index 00000000..89837f8c --- /dev/null +++ b/assets/0000-0099/0095.Unique Binary Search Trees II/README_EN.md @@ -0,0 +1,54 @@ +# [95. Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii) + + + +## Description + +

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: n = 3
+Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: [[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0095.Unique Binary Search Trees II/images/uniquebstn3.jpg b/assets/0000-0099/0095.Unique Binary Search Trees II/images/uniquebstn3.jpg new file mode 100644 index 00000000..b3131e71 Binary files /dev/null and b/assets/0000-0099/0095.Unique Binary Search Trees II/images/uniquebstn3.jpg differ diff --git a/assets/0000-0099/0096.Unique Binary Search Trees/README_EN.md b/assets/0000-0099/0096.Unique Binary Search Trees/README_EN.md new file mode 100644 index 00000000..f44ac825 --- /dev/null +++ b/assets/0000-0099/0096.Unique Binary Search Trees/README_EN.md @@ -0,0 +1,105 @@ +# [96. Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees) + + + +## Description + +

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

+ +

 

+

Example 1:

+ +
+Input: n = 3
+Output: 5
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 19
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numTrees(self, n: int) -> int: + dp = [0] * (n + 1) + dp[0] = 1 + for i in range(1, n + 1): + for j in range(i): + dp[i] += dp[j] * dp[i - j - 1] + return dp[-1] +``` + +### **Java** + +```java +class Solution { + public int numTrees(int n) { + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + dp[i] += dp[j] * dp[i - j - 1]; + } + } + return dp[n]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numTrees(int n) { + vector dp(n + 1); + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + dp[i] += dp[j] * dp[i - j - 1]; + } + } + return dp[n]; + } +}; +``` + +### **Go** + +```go +func numTrees(n int) int { + dp := make([]int, n+1) + dp[0] = 1 + for i := 1; i <= n; i++ { + for j := 0; j < i; j++ { + dp[i] += dp[j] * dp[i-j-1] + } + } + return dp[n] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0096.Unique Binary Search Trees/images/uniquebstn3.jpg b/assets/0000-0099/0096.Unique Binary Search Trees/images/uniquebstn3.jpg new file mode 100644 index 00000000..b3131e71 Binary files /dev/null and b/assets/0000-0099/0096.Unique Binary Search Trees/images/uniquebstn3.jpg differ diff --git a/assets/0000-0099/0097.Interleaving String/README_EN.md b/assets/0000-0099/0097.Interleaving String/README_EN.md new file mode 100644 index 00000000..235bec04 --- /dev/null +++ b/assets/0000-0099/0097.Interleaving String/README_EN.md @@ -0,0 +1,77 @@ +# [97. Interleaving String](https://leetcode.com/problems/interleaving-string) + + + +## Description + +

Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

+ +

An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that:

+ +
    +
  • s = s1 + s2 + ... + sn
  • +
  • t = t1 + t2 + ... + tm
  • +
  • |n - m| <= 1
  • +
  • The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...
  • +
+ +

Note: a + b is the concatenation of strings a and b.

+ +

 

+

Example 1:

+ +
+Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
+Output: true
+
+ +

Example 2:

+ +
+Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
+Output: false
+
+ +

Example 3:

+ +
+Input: s1 = "", s2 = "", s3 = ""
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s1.length, s2.length <= 100
  • +
  • 0 <= s3.length <= 200
  • +
  • s1, s2, and s3 consist of lowercase English letters.
  • +
+ +

 

+

Follow up: Could you solve it using only O(s2.length) additional memory space?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0097.Interleaving String/images/interleave.jpg b/assets/0000-0099/0097.Interleaving String/images/interleave.jpg new file mode 100644 index 00000000..641b506e Binary files /dev/null and b/assets/0000-0099/0097.Interleaving String/images/interleave.jpg differ diff --git a/assets/0000-0099/0098.Validate Binary Search Tree/README_EN.md b/assets/0000-0099/0098.Validate Binary Search Tree/README_EN.md new file mode 100644 index 00000000..f27f7b36 --- /dev/null +++ b/assets/0000-0099/0098.Validate Binary Search Tree/README_EN.md @@ -0,0 +1,107 @@ +# [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree) + + + +## Description + +

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

+ +

A valid BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [2,1,3]
+Output: true
+
+ +

Example 2:

+ +
+Input: root = [5,1,4,null,null,3,6]
+Output: false
+Explanation: The root node's value is 5 but its right child's value is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + pre = None + def isValidBST(self, root: TreeNode) -> bool: + if not root: + return True + if not self.isValidBST(root.left): + return False + if self.pre is not None and self.pre >= root.val: + return False + self.pre = root.val + if not self.isValidBST(root.right): + return False + return True +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Integer pre = null; + public boolean isValidBST(TreeNode root) { + if (root == null) return true; + if (!isValidBST(root.left)) return false; + if (pre != null && pre >= root.val) return false; + pre = root.val; + if (!isValidBST(root.right)) return false; + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0098.Validate Binary Search Tree/images/tree1.jpg b/assets/0000-0099/0098.Validate Binary Search Tree/images/tree1.jpg new file mode 100644 index 00000000..905159e8 Binary files /dev/null and b/assets/0000-0099/0098.Validate Binary Search Tree/images/tree1.jpg differ diff --git a/assets/0000-0099/0098.Validate Binary Search Tree/images/tree2.jpg b/assets/0000-0099/0098.Validate Binary Search Tree/images/tree2.jpg new file mode 100644 index 00000000..0bef5ec2 Binary files /dev/null and b/assets/0000-0099/0098.Validate Binary Search Tree/images/tree2.jpg differ diff --git a/assets/0000-0099/0099.Recover Binary Search Tree/README_EN.md b/assets/0000-0099/0099.Recover Binary Search Tree/README_EN.md new file mode 100644 index 00000000..164f0706 --- /dev/null +++ b/assets/0000-0099/0099.Recover Binary Search Tree/README_EN.md @@ -0,0 +1,83 @@ +# [99. Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree) + + + +## Description + +

You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

+ +

Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

+ +

 

+

Example 1:

+ +
+Input: root = [1,3,null,null,2]
+Output: [3,1,null,null,2]
+Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
+
+ +

Example 2:

+ +
+Input: root = [3,1,4,null,null,2]
+Output: [2,1,4,null,null,3]
+Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 1000].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + first = None + second = None + prev = None + def recoverTree(self, root: TreeNode) -> None: + """ + Do not return anything, modify root in-place instead. + """ + def dfs(root): + if root: + dfs(root.left) + if self.prev and root.val < self.prev.val: + if not self.first: + self.first = self.prev + self.second = root + self.prev = root + dfs(root.right) + dfs(root) + self.first.val, self.second.val = self.second.val, self.first.val +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0000-0099/0099.Recover Binary Search Tree/images/recover1.jpg b/assets/0000-0099/0099.Recover Binary Search Tree/images/recover1.jpg new file mode 100644 index 00000000..6e488f13 Binary files /dev/null and b/assets/0000-0099/0099.Recover Binary Search Tree/images/recover1.jpg differ diff --git a/assets/0000-0099/0099.Recover Binary Search Tree/images/recover2.jpg b/assets/0000-0099/0099.Recover Binary Search Tree/images/recover2.jpg new file mode 100644 index 00000000..31e56d1e Binary files /dev/null and b/assets/0000-0099/0099.Recover Binary Search Tree/images/recover2.jpg differ diff --git a/assets/0100-0199/0100.Same Tree/README_EN.md b/assets/0100-0199/0100.Same Tree/README_EN.md new file mode 100644 index 00000000..ab75803c --- /dev/null +++ b/assets/0100-0199/0100.Same Tree/README_EN.md @@ -0,0 +1,168 @@ +# [100. Same Tree](https://leetcode.com/problems/same-tree) + + + +## Description + +

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

+ +

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

+ +

 

+

Example 1:

+ +
+Input: p = [1,2,3], q = [1,2,3]
+Output: true
+
+ +

Example 2:

+ +
+Input: p = [1,2], q = [1,null,2]
+Output: false
+
+ +

Example 3:

+ +
+Input: p = [1,2,1], q = [1,1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both trees is in the range [0, 100].
  • +
  • -104 <= Node.val <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: + if p == q: + return True + if p is None or q is None or p.val != q.val: + return False + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == q) return true; + if (p == null || q == null || p.val != q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == q) return true; + if (!p || !q || p->val != q->val) return false; + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == q { + return true + } + if p == nil || q == nil || p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function (p, q) { + if (!p && !q) return true; + if (p && q) { + return (p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) + } + return false; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0100.Same Tree/images/ex1.jpg b/assets/0100-0199/0100.Same Tree/images/ex1.jpg new file mode 100644 index 00000000..7454c319 Binary files /dev/null and b/assets/0100-0199/0100.Same Tree/images/ex1.jpg differ diff --git a/assets/0100-0199/0100.Same Tree/images/ex2.jpg b/assets/0100-0199/0100.Same Tree/images/ex2.jpg new file mode 100644 index 00000000..dbeba312 Binary files /dev/null and b/assets/0100-0199/0100.Same Tree/images/ex2.jpg differ diff --git a/assets/0100-0199/0100.Same Tree/images/ex3.jpg b/assets/0100-0199/0100.Same Tree/images/ex3.jpg new file mode 100644 index 00000000..cb8f68c3 Binary files /dev/null and b/assets/0100-0199/0100.Same Tree/images/ex3.jpg differ diff --git a/assets/0100-0199/0101.Symmetric Tree/README_EN.md b/assets/0100-0199/0101.Symmetric Tree/README_EN.md new file mode 100644 index 00000000..bfa1ef43 --- /dev/null +++ b/assets/0100-0199/0101.Symmetric Tree/README_EN.md @@ -0,0 +1,114 @@ +# [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree) + + + +## Description + +

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,2,3,4,4,3]
+Output: true
+
+ +

Example 2:

+ +
+Input: root = [1,2,2,null,3,null,3]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Could you solve it both recursively and iteratively? + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if root is None: + return True + return self.is_symmetric(root.left, root.right) + + def is_symmetric(self, left: TreeNode, right: TreeNode) -> bool: + if left is None and right is None: + return True + if left is None or right is None or left.val != right.val: + return False + return self.is_symmetric(left.left, right.right) and self.is_symmetric(left.right, right.left) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null) return true; + return isSymmetric(root.left, root.right); + } + + private boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null && right == null) return true; + if (left == null || right == null || left.val != right.val) return false; + return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (!root) return true; + return isSymmetric(root->left, root->right); + } + +private: + bool isSymmetric(TreeNode* left, TreeNode* right) { + if (!left && !right) return true; + if (!left && right || left && !right || left->val != right->val) return false; + return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left); + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0101.Symmetric Tree/TreeNode.d.ts b/assets/0100-0199/0101.Symmetric Tree/TreeNode.d.ts new file mode 100644 index 00000000..37695956 --- /dev/null +++ b/assets/0100-0199/0101.Symmetric Tree/TreeNode.d.ts @@ -0,0 +1,6 @@ +declare class TreeNode { + val: number; + left: TreeNode | null; + right: TreeNode | null; + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null); +} \ No newline at end of file diff --git a/assets/0100-0199/0101.Symmetric Tree/images/symtree1.jpg b/assets/0100-0199/0101.Symmetric Tree/images/symtree1.jpg new file mode 100644 index 00000000..3a11d03d Binary files /dev/null and b/assets/0100-0199/0101.Symmetric Tree/images/symtree1.jpg differ diff --git a/assets/0100-0199/0101.Symmetric Tree/images/symtree2.jpg b/assets/0100-0199/0101.Symmetric Tree/images/symtree2.jpg new file mode 100644 index 00000000..f45fa485 Binary files /dev/null and b/assets/0100-0199/0101.Symmetric Tree/images/symtree2.jpg differ diff --git a/assets/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md b/assets/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md new file mode 100644 index 00000000..c4b25178 --- /dev/null +++ b/assets/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md @@ -0,0 +1,187 @@ +# [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal) + + + +## Description + +

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[9,20],[15,7]]
+
+ +

Example 2:

+ +
+Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def levelOrder(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + res = [] + q = [] + q.append(root) + while q: + size = len(q) + t = [] + for _ in range(size): + node = q.pop(0) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + t.append(node.val) + res.append(t) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + if (root == null) return Collections.emptyList(); + Deque q = new ArrayDeque<>(); + q.offer(root); + List> res = new ArrayList<>(); + while (!q.isEmpty()) { + int size = q.size(); + List t = new ArrayList<>(); + while (size-- > 0) { + TreeNode node = q.poll(); + t.add(node.val); + if (node.left != null) q.offer(node.left); + if (node.right != null) q.offer(node.right); + } + res.add(t); + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + if (!root) return {}; + vector> res; + queue q{{root}}; + while (!q.empty()) { + vector oneLevel; + for (int i = q.size(); i > 0; --i) { + TreeNode* t = q.front(); + q.pop(); + oneLevel.push_back(t->val); + if (t->left) q.push(t->left); + if (t->right) q.push(t->right); + } + res.push_back(oneLevel); + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function (root) { + let result = []; + if (!root) return result; + + let queue = []; + queue.push(root); + while (queue.length) { + let size = queue.length; + let levelItems = []; + while (size--) { + let node = queue.shift(); + levelItems.push(node.val); + if (node.left) { + queue.push(node.left); + } + if (node.right) { + queue.push(node.right); + } + } + result.push(levelItems); + } + return result; +}; + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0102.Binary Tree Level Order Traversal/images/tree1.jpg b/assets/0100-0199/0102.Binary Tree Level Order Traversal/images/tree1.jpg new file mode 100644 index 00000000..5c4570da Binary files /dev/null and b/assets/0100-0199/0102.Binary Tree Level Order Traversal/images/tree1.jpg differ diff --git a/assets/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md b/assets/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md new file mode 100644 index 00000000..651e773e --- /dev/null +++ b/assets/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md @@ -0,0 +1,179 @@ +# [103. Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal) + + + +## Description + +

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: [[3],[20,9],[15,7]]
+
+ +

Example 2:

+ +
+Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + res = [] + q = collections.deque([root]) + left = False + while q: + size = len(q) + t = [] + for _ in range(size): + node = q.popleft() + t.append(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if left: + t.reverse() + res.append(t) + left = not left + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Deque q = new ArrayDeque<>(); + q.offer(root); + List> res = new ArrayList<>(); + boolean left = false; + while (!q.isEmpty()) { + int size = q.size(); + List t = new ArrayList<>(); + while (size-- > 0) { + TreeNode node = q.pollFirst(); + t.add(node.val); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + if (left) { + Collections.reverse(t); + } + res.add(t); + left = !left; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var zigzagLevelOrder = function (root) { + if (!root) { + return []; + } + let res = [], q = []; + q.push(root); + let leftToRight = true; + while (q.length) { + let levelSize = q.length, levelOutput = []; + for (let i = 0; i < levelSize; i++) { + let cur = q.shift(); + if (cur.left) { + q.push(cur.left); + } + if (cur.right) { + q.push(cur.right); + } + if (leftToRight) { + levelOutput.push(cur.val); + } else { + levelOutput.unshift(cur.val); + } + } + res.push(levelOutput); + leftToRight = !leftToRight; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/images/tree1.jpg b/assets/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/images/tree1.jpg new file mode 100644 index 00000000..5c4570da Binary files /dev/null and b/assets/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/images/tree1.jpg differ diff --git a/assets/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md b/assets/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md new file mode 100644 index 00000000..5119227d --- /dev/null +++ b/assets/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md @@ -0,0 +1,154 @@ +# [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) + + + +## Description + +

Given the root of a binary tree, return its maximum depth.

+ + + +

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

+ + + +

 

+ +

Example 1:

+ + + +
+
+Input: root = [3,9,20,null,null,15,7]
+
+Output: 3
+
+
+ + + +

Example 2:

+ + + +
+
+Input: root = [1,null,2]
+
+Output: 2
+
+
+ + + +

Example 3:

+ + + +
+
+Input: root = []
+
+Output: 0
+
+
+ + + +

Example 4:

+ + + +
+
+Input: root = [0]
+
+Output: 1
+
+
+ + + +

 

+ +

Constraints:

+ + + +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + l = self.maxDepth(root.left) + r = self.maxDepth(root.right) + return 1 + max(l, r) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + int l = maxDepth(root.left); + int r = maxDepth(root.right); + return 1 + Math.max(l, r); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxDepth(TreeNode* root) { + if (!root) return 0; + int l = maxDepth(root->left); + int r = maxDepth(root->right); + return max(l, r) + 1; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0104.Maximum Depth of Binary Tree/images/tmp-tree.jpg b/assets/0100-0199/0104.Maximum Depth of Binary Tree/images/tmp-tree.jpg new file mode 100644 index 00000000..5f387b76 Binary files /dev/null and b/assets/0100-0199/0104.Maximum Depth of Binary Tree/images/tmp-tree.jpg differ diff --git a/assets/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md b/assets/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md new file mode 100644 index 00000000..4e8d3eb7 --- /dev/null +++ b/assets/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md @@ -0,0 +1,111 @@ +# [105. Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal) + + + +## Description + +

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
+Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
+Input: preorder = [-1], inorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 3000
  • +
  • inorder.length == preorder.length
  • +
  • -3000 <= preorder[i], inorder[i] <= 3000
  • +
  • preorder and inorder consist of unique values.
  • +
  • Each value of inorder also appears in preorder.
  • +
  • preorder is guaranteed to be the preorder traversal of the tree.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + indexes = {} + def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: + def build(preorder, inorder, p1, p2, i1, i2) -> TreeNode: + if p1 > p2 or i1 > i2: + return None + root_val = preorder[p1] + pos = self.indexes[root_val] + root = TreeNode(root_val) + root.left = None if pos == i1 else build(preorder, inorder, p1 + 1, p1 - i1 + pos, i1, pos - 1) + root.right = None if pos == i2 else build(preorder, inorder, p1 - i1 + pos + 1, p2, pos + 1, i2) + return root + n = len(inorder) + for i in range(n): + self.indexes[inorder[i]] = i + return build(preorder, inorder, 0, n - 1, 0, n - 1) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private Map indexes = new HashMap<>(); + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = inorder.length; + for (int i = 0; i < n; ++i) { + indexes.put(inorder[i], i); + } + return build(preorder, inorder, 0, n - 1, 0, n - 1); + } + + private TreeNode build(int[] preorder, int[] inorder, int p1, int p2, int i1, int i2) { + if (p1 > p2 || i1 > i2) return null; + int rootVal = preorder[p1]; + int pos = indexes.get(rootVal); + TreeNode node = new TreeNode(rootVal); + node.left = pos == i1 ? null : build(preorder, inorder, p1 + 1, pos - i1 + p1, i1, pos - 1); + node.right = pos == i2 ? null : build(preorder, inorder, pos - i1 + p1 + 1, p2, pos + 1, i2); + return node; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/images/tree.jpg b/assets/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/images/tree.jpg new file mode 100644 index 00000000..d77a04e7 Binary files /dev/null and b/assets/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/images/tree.jpg differ diff --git a/assets/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md b/assets/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md new file mode 100644 index 00000000..9f0ae86d --- /dev/null +++ b/assets/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md @@ -0,0 +1,134 @@ +# [106. Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal) + + + +## Description + +

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

+ +

 

+

Example 1:

+ +
+Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
+Output: [3,9,20,null,null,15,7]
+
+ +

Example 2:

+ +
+Input: inorder = [-1], postorder = [-1]
+Output: [-1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= inorder.length <= 3000
  • +
  • postorder.length == inorder.length
  • +
  • -3000 <= inorder[i], postorder[i] <= 3000
  • +
  • inorder and postorder consist of unique values.
  • +
  • Each value of postorder also appears in inorder.
  • +
  • inorder is guaranteed to be the inorder traversal of the tree.
  • +
  • postorder is guaranteed to be the postorder traversal of the tree.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + indexes = {} + def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: + def build(inorder, postorder, i1, i2, p1, p2): + if i1 > i2 or p1 > p2: + return None + root_val = postorder[p2] + pos = self.indexes[root_val] + root = TreeNode(root_val) + root.left = None if pos == i1 else build(inorder, postorder, i1, pos - 1, p1, p1 - i1 + pos - 1) + root.right = None if pos == i2 else build(inorder, postorder, pos + 1, i2, p1 - i1 + pos, p2 - 1) + return root + n = len(inorder) + for i in range(n): + self.indexes[inorder[i]] = i + return build(inorder, postorder, 0, n - 1, 0, n - 1) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private Map indexes = new HashMap<>(); + + public TreeNode buildTree(int[] inorder, int[] postorder) { + int n = inorder.length; + for (int i = 0; i < n; ++i) { + indexes.put(inorder[i], i); + } + return build(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1); + } + + private TreeNode build(int[] inorder, int[] postorder, int i1, int i2, int p1, int p2) { + if (i1 > i2 || p1 > p2) return null; + int rootVal = postorder[p2]; + int pos = indexes.get(rootVal); + TreeNode root = new TreeNode(rootVal); + root.left = pos == i1 ? null : build(inorder, postorder, i1, pos - 1, p1, p1 - i1 + pos - 1); + root.right = pos == i2 ? null : build(inorder, postorder, pos + 1, i2, p1 - i1 + pos, p2 - 1); + return root; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + TreeNode *buildTree(vector &inorder, vector &postorder) { + return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); + } + TreeNode *buildTree(vector &inorder, int iLeft, int iRight, vector &postorder, int pLeft, int pRight) { + if (iLeft > iRight || pLeft > pRight) return NULL; + TreeNode *cur = new TreeNode(postorder[pRight]); + int i = 0; + for (i = iLeft; i < inorder.size(); ++i) { + if (inorder[i] == cur->val) + break; + } + cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1); + cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1); + return cur; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/images/tree.jpg b/assets/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/images/tree.jpg new file mode 100644 index 00000000..d77a04e7 Binary files /dev/null and b/assets/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/images/tree.jpg differ diff --git a/assets/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md b/assets/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md new file mode 100644 index 00000000..2393197e --- /dev/null +++ b/assets/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md @@ -0,0 +1,158 @@ +# [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii) + + + +## Description + +

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: [[15,7],[9,20],[3]]
+
+ +

Example 2:

+ +
+Input: root = [1]
+Output: [[1]]
+
+ +

Example 3:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + q = [root] + res = [] + while q: + size = len(q) + t = [] + for _ in range(size): + node = q.pop(0) + t.append(node.val) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + res.append(t) + return res[::-1] +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + if (root == null) return Collections.emptyList(); + Deque q = new ArrayDeque<>(); + List> res = new ArrayList<>(); + q.offer(root); + while (!q.isEmpty()) { + int size = q.size(); + List t = new ArrayList<>(); + while (size-- > 0) { + TreeNode node = q.poll(); + t.add(node.val); + if (node.left != null) q.offer(node.left); + if (node.right != null) q.offer(node.right); + } + res.add(0, t); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrderBottom = function (root) { + if (!root) { + return []; + } + let q = [], output = [], levelOutput = []; + q.push(root); + q.push(null); + while (q.length) { + let cur = q.shift(); + levelOutput.push(cur.val); + if (cur.left) { + q.push(cur.left); + } + if (cur.right) { + q.push(cur.right); + } + if (!q[0]) { + q.shift(); + output.unshift(levelOutput); + levelOutput = []; + if (q.length) { + q.push(null); + } + } + } + return output; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0107.Binary Tree Level Order Traversal II/images/tree1.jpg b/assets/0100-0199/0107.Binary Tree Level Order Traversal II/images/tree1.jpg new file mode 100644 index 00000000..5c4570da Binary files /dev/null and b/assets/0100-0199/0107.Binary Tree Level Order Traversal II/images/tree1.jpg differ diff --git a/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md new file mode 100644 index 00000000..fbcd46cb --- /dev/null +++ b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md @@ -0,0 +1,170 @@ +# [108. Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree) + + + +## Description + +

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

+ +

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

+ +

 

+

Example 1:

+ +
+Input: nums = [-10,-3,0,5,9]
+Output: [0,-3,9,-10,null,5]
+Explanation: [0,-10,5,null,-3,null,9] is also accepted:
+
+
+ +

Example 2:

+ +
+Input: nums = [1,3]
+Output: [3,1]
+Explanation: [1,3] and [3,1] are both a height-balanced BSTs.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • nums is sorted in a strictly increasing order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def sortedArrayToBST(self, nums: List[int]) -> TreeNode: + def buildBST(nums, start, end): + if start > end: + return None + mid = (start + end) >> 1 + return TreeNode(nums[mid], buildBST(nums, start, mid - 1), buildBST(nums, mid + 1, end)) + + return buildBST(nums, 0, len(nums) - 1) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + return buildBST(nums, 0, nums.length - 1); + } + + private TreeNode buildBST(int[] nums, int start, int end) { + if (start > end) { + return null; + } + int mid = (start + end) >> 1; + TreeNode root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + return buildBST(nums, 0, nums.size() - 1); + } + +private: + TreeNode* buildBST(vector& nums, int start, int end) { + if (start > end) { + return nullptr; + } + int mid = (start + end) / 2; + TreeNode *root = new TreeNode(nums[mid]); + root->left = buildBST(nums, start, mid - 1); + root->right = buildBST(nums, mid + 1, end); + return root; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = function(nums) { + const buildBST = (nums, start, end) => { + if (start > end) { + return null; + } + const mid = (start + end) >> 1; + const root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } + + return buildBST(nums, 0, nums.length - 1); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree.jpg b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree.jpg new file mode 100644 index 00000000..b8a09c5e Binary files /dev/null and b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree.jpg differ diff --git a/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree1.jpg b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree1.jpg new file mode 100644 index 00000000..ea5afcf7 Binary files /dev/null and b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree1.jpg differ diff --git a/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree2.jpg b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree2.jpg new file mode 100644 index 00000000..ba150447 Binary files /dev/null and b/assets/0100-0199/0108.Convert Sorted Array to Binary Search Tree/images/btree2.jpg differ diff --git a/assets/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md b/assets/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md new file mode 100644 index 00000000..5cf3a244 --- /dev/null +++ b/assets/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md @@ -0,0 +1,229 @@ +# [109. Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree) + + + +## Description + +

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

+ +

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

+ +

 

+

Example 1:

+ +
+Input: head = [-10,-3,0,5,9]
+Output: [0,-3,9,-10,null,5]
+Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
+
+ +

Example 2:

+ +
+Input: head = []
+Output: []
+
+ +

Example 3:

+ +
+Input: head = [0]
+Output: [0]
+
+ +

Example 4:

+ +
+Input: head = [1,3]
+Output: [3,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in head is in the range [0, 2 * 104].
  • +
  • -10^5 <= Node.val <= 10^5
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def sortedListToBST(self, head: ListNode) -> TreeNode: + def buildBST(nums, start, end): + if start > end: + return None + mid = (start + end) >> 1 + return TreeNode(nums[mid], buildBST(nums, start, mid - 1), buildBST(nums, mid + 1, end)) + + nums = [] + while head: + nums.append(head.val) + head = head.next + return buildBST(nums, 0, len(nums) - 1) +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + List nums = new ArrayList<>(); + for (; head != null; head = head.next) { + nums.add(head.val); + } + return buildBST(nums, 0, nums.size() - 1); + } + + private TreeNode buildBST(List nums, int start, int end) { + if (start > end) { + return null; + } + int mid = (start + end) >> 1; + TreeNode root = new TreeNode(nums.get(mid)); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* sortedListToBST(ListNode* head) { + vector nums; + for (; head != nullptr; head = head->next) { + nums.push_back(head->val); + } + return buildBST(nums, 0, nums.size() - 1); + } + +private: + TreeNode* buildBST(vector& nums, int start, int end) { + if (start > end) { + return nullptr; + } + int mid = (start + end) / 2; + TreeNode *root = new TreeNode(nums[mid]); + root->left = buildBST(nums, start, mid - 1); + root->right = buildBST(nums, mid + 1, end); + return root; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {ListNode} head + * @return {TreeNode} + */ +var sortedListToBST = function(head) { + const buildBST = (nums, start, end) => { + if (start > end) { + return null; + } + const mid = (start + end) >> 1; + const root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } + + const nums = new Array(); + for (; head != null; head = head.next) { + nums.push(head.val); + } + return buildBST(nums, 0, nums.length - 1); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0109.Convert Sorted List to Binary Search Tree/images/linked.jpg b/assets/0100-0199/0109.Convert Sorted List to Binary Search Tree/images/linked.jpg new file mode 100644 index 00000000..45f937c3 Binary files /dev/null and b/assets/0100-0199/0109.Convert Sorted List to Binary Search Tree/images/linked.jpg differ diff --git a/assets/0100-0199/0110.Balanced Binary Tree/README_EN.md b/assets/0100-0199/0110.Balanced Binary Tree/README_EN.md new file mode 100644 index 00000000..1f674cc9 --- /dev/null +++ b/assets/0100-0199/0110.Balanced Binary Tree/README_EN.md @@ -0,0 +1,179 @@ +# [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree) + + + +## Description + +

Given a binary tree, determine if it is height-balanced.

+ +

For this problem, a height-balanced binary tree is defined as:

+ +
+

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

+
+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: true
+
+ +

Example 2:

+ +
+Input: root = [1,2,2,3,3,null,null,4,4]
+Output: false
+
+ +

Example 3:

+ +
+Input: root = []
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -104 <= Node.val <= 104
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + def height(root): + if not root: + return 0 + return 1 + max(height(root.left), height(root.right)) + if not root: + return True + left_height, right_height = height(root.left), height(root.right) + return abs(left_height - right_height) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isBalanced(TreeNode root) { + if (root == null) { + return true; + } + int leftHeight = height(root.left); + int rightHeight = height(root.right); + return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right); + } + + private int height(TreeNode root) { + if (root == null) { + return 0; + } + int l = height(root.left); + int r = height(root.right); + return 1 + Math.max(l, r); + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ + var isBalanced = function(root) { + if (root == null) return true; + let left = root.left; + let right = root.right; + return isBalanced(left) && isBalanced(right) && Math.abs(depth(left) - depth(right)) <= 1; +}; + +function depth(root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isBalanced(TreeNode* root) { + if (root == nullptr) { + return true; + } + int leftHeight = height(root->left); + int rightHeight = height(root->right); + return abs(leftHeight - rightHeight) <= 1 && isBalanced(root->left) && isBalanced(root->right); + } +private: + int height(TreeNode* root) { + if (root == nullptr) { + return 0; + } + int l = height(root->left); + int r = height(root->right); + return 1 + max(l, r); + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0110.Balanced Binary Tree/images/balance_1.jpg b/assets/0100-0199/0110.Balanced Binary Tree/images/balance_1.jpg new file mode 100644 index 00000000..3cf88903 Binary files /dev/null and b/assets/0100-0199/0110.Balanced Binary Tree/images/balance_1.jpg differ diff --git a/assets/0100-0199/0110.Balanced Binary Tree/images/balance_2.jpg b/assets/0100-0199/0110.Balanced Binary Tree/images/balance_2.jpg new file mode 100644 index 00000000..bdd3fec9 Binary files /dev/null and b/assets/0100-0199/0110.Balanced Binary Tree/images/balance_2.jpg differ diff --git a/assets/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md b/assets/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md new file mode 100644 index 00000000..8aab066c --- /dev/null +++ b/assets/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md @@ -0,0 +1,154 @@ +# [111. Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree) + + + +## Description + +

Given a binary tree, find its minimum depth.

+ +

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

+ +

Note: A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: 2
+
+ +

Example 2:

+ +
+Input: root = [2,null,3,null,4,null,5,null,6]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 105].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + if root.left is None: + return 1 + self.minDepth(root.right) + if root.right is None: + return 1 + self.minDepth(root.left) + return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int minDepth(TreeNode root) { + if (root == null) { + return 0; + } + if (root.left == null) { + return 1 + minDepth(root.right); + } + if (root.right == null) { + return 1 + minDepth(root.left); + } + return 1 + Math.min(minDepth(root.left), minDepth(root.right)); + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function(root) { + if (root == null) return 0; + if (root.left == null) return minDepth(root.right) + 1; + if (root.right == null) return minDepth(root.left) + 1; + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + if (root->left == nullptr) { + return 1 + minDepth(root->right); + } + if (root->right == nullptr) { + return 1 + minDepth(root->left); + } + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0111.Minimum Depth of Binary Tree/images/ex_depth.jpg b/assets/0100-0199/0111.Minimum Depth of Binary Tree/images/ex_depth.jpg new file mode 100644 index 00000000..9ac3029d Binary files /dev/null and b/assets/0100-0199/0111.Minimum Depth of Binary Tree/images/ex_depth.jpg differ diff --git a/assets/0100-0199/0112.Path Sum/README_EN.md b/assets/0100-0199/0112.Path Sum/README_EN.md new file mode 100644 index 00000000..f7d7e49e --- /dev/null +++ b/assets/0100-0199/0112.Path Sum/README_EN.md @@ -0,0 +1,99 @@ +# [112. Path Sum](https://leetcode.com/problems/path-sum) + + + +## Description + +

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
+Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
+Output: true
+
+ +

Example 2:

+ +
+Input: root = [1,2,3], targetSum = 5
+Output: false
+
+ +

Example 3:

+ +
+Input: root = [1,2], targetSum = 0
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def hasPathSum(self, root: TreeNode, sum: int) -> bool: + def dfs(root, sum): + if root is None: + return False + if root.val == sum and root.left is None and root.right is None: + return True + return dfs(root.left, sum - root.val) or dfs(root.right, sum - root.val) + return dfs(root, sum) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean hasPathSum(TreeNode root, int sum) { + return dfs(root, sum); + } + + private boolean dfs(TreeNode root, int sum) { + if (root == null) return false; + if (root.val == sum && root.left == null && root.right == null) return true; + return dfs(root.left, sum - root.val) || dfs(root.right, sum - root.val); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0112.Path Sum/images/pathsum1.jpg b/assets/0100-0199/0112.Path Sum/images/pathsum1.jpg new file mode 100644 index 00000000..cfbe70c2 Binary files /dev/null and b/assets/0100-0199/0112.Path Sum/images/pathsum1.jpg differ diff --git a/assets/0100-0199/0112.Path Sum/images/pathsum2.jpg b/assets/0100-0199/0112.Path Sum/images/pathsum2.jpg new file mode 100644 index 00000000..e69a7b1e Binary files /dev/null and b/assets/0100-0199/0112.Path Sum/images/pathsum2.jpg differ diff --git a/assets/0100-0199/0113.Path Sum II/README_EN.md b/assets/0100-0199/0113.Path Sum II/README_EN.md new file mode 100644 index 00000000..871ba710 --- /dev/null +++ b/assets/0100-0199/0113.Path Sum II/README_EN.md @@ -0,0 +1,119 @@ +# [113. Path Sum II](https://leetcode.com/problems/path-sum-ii) + + + +## Description + +

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum.

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
+Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
+Output: [[5,4,11,2],[5,8,4,5]]
+
+ +

Example 2:

+ +
+Input: root = [1,2,3], targetSum = 5
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1,2], targetSum = 0
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • -1000 <= targetSum <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: + def dfs(root, sum): + if root is None: + return + path.append(root.val) + if root.val == sum and root.left is None and root.right is None: + res.append(path.copy()) + dfs(root.left, sum - root.val) + dfs(root.right, sum - root.val) + path.pop() + if not root: + return [] + res = [] + path = [] + dfs(root, sum) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private List> res; + private List path; + + public List> pathSum(TreeNode root, int sum) { + if (root == null) return Collections.emptyList(); + res = new ArrayList<>(); + path = new ArrayList<>(); + dfs(root, sum); + return res; + } + + private void dfs(TreeNode root, int sum) { + if (root == null) return; + path.add(root.val); + if (root.val == sum && root.left == null && root.right == null) { + res.add(new ArrayList<>(path)); + } + dfs(root.left, sum - root.val); + dfs(root.right, sum - root.val); + path.remove(path.size() - 1); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0113.Path Sum II/images/pathsum2.jpg b/assets/0100-0199/0113.Path Sum II/images/pathsum2.jpg new file mode 100644 index 00000000..e69a7b1e Binary files /dev/null and b/assets/0100-0199/0113.Path Sum II/images/pathsum2.jpg differ diff --git a/assets/0100-0199/0113.Path Sum II/images/pathsumii1.jpg b/assets/0100-0199/0113.Path Sum II/images/pathsumii1.jpg new file mode 100644 index 00000000..a5f1830f Binary files /dev/null and b/assets/0100-0199/0113.Path Sum II/images/pathsumii1.jpg differ diff --git a/assets/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md b/assets/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md new file mode 100644 index 00000000..d5938966 --- /dev/null +++ b/assets/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md @@ -0,0 +1,187 @@ +# [114. Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list) + + + +## Description + +

Given the root of a binary tree, flatten the tree into a "linked list":

+ +
    +
  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • +
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [1,2,5,3,4,null,6]
+Output: [1,null,2,null,3,null,4,null,5,null,6]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+Follow up: Can you flatten the tree in-place (with O(1) extra space)? + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def flatten(self, root: TreeNode) -> None: + """ + Do not return anything, modify root in-place instead. + """ + while root: + if root.left: + pre = root.left + while pre.right: + pre = pre.right + pre.right = root.right + root.right = root.left + root.left = None + root = root.right +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public void flatten(TreeNode root) { + while (root != null) { + if (root.left != null) { + TreeNode pre = root.left; + while (pre.right != null) { + pre = pre.right; + } + pre.right = root.right; + root.right = root.left; + root.left = null; + } + root = root.right; + } + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +/** + Do not return anything, modify root in-place instead. + */ +function flatten(root: TreeNode | null): void { + while (root != null) { + if (root.left != null) { + let pre = root.left; + while (pre.right != null) { + pre = pre.right; + } + pre.right = root.right; + root.right = root.left; + root.left = null; + } + root = root.right; + } +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void flatten(TreeNode* root) { + while (root) { + if (root->left) { + TreeNode *pre = root->left; + while (pre->right) { + pre = pre->right; + } + pre->right = root->right; + root->right = root->left; + root->left = nullptr; + } + root = root->right; + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0114.Flatten Binary Tree to Linked List/images/flaten.jpg b/assets/0100-0199/0114.Flatten Binary Tree to Linked List/images/flaten.jpg new file mode 100644 index 00000000..3ac4f976 Binary files /dev/null and b/assets/0100-0199/0114.Flatten Binary Tree to Linked List/images/flaten.jpg differ diff --git a/assets/0100-0199/0115.Distinct Subsequences/README_EN.md b/assets/0100-0199/0115.Distinct Subsequences/README_EN.md new file mode 100644 index 00000000..d13591b5 --- /dev/null +++ b/assets/0100-0199/0115.Distinct Subsequences/README_EN.md @@ -0,0 +1,70 @@ +# [115. Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences) + + + +## Description + +

Given two strings s and t, return the number of distinct subsequences of s which equals t.

+ +

A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).

+ +

It is guaranteed the answer fits on a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
+Input: s = "rabbbit", t = "rabbit"
+Output: 3
+Explanation:
+As shown below, there are 3 ways you can generate "rabbit" from S.
+rabbbit
+rabbbit
+rabbbit
+
+ +

Example 2:

+ +
+Input: s = "babgbag", t = "bag"
+Output: 5
+Explanation:
+As shown below, there are 5 ways you can generate "bag" from S.
+babgbag
+babgbag
+babgbag
+babgbag
+babgbag
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 1000
  • +
  • s and t consist of English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md b/assets/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md new file mode 100644 index 00000000..085dada7 --- /dev/null +++ b/assets/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md @@ -0,0 +1,206 @@ +# [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node) + + + +## Description + +

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

+ +
+
+struct Node {
+
+  int val;
+
+  Node *left;
+
+  Node *right;
+
+  Node *next;
+
+}
+
+
+ +

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

+ +

Initially, all next pointers are set to NULL.

+ +

 

+ +

Follow up:

+ +
    +
  • You may only use constant extra space.
  • +
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
  • +
+ +

 

+ +

Example 1:

+ +

+ +
+
+Input: root = [1,2,3,4,5,6,7]
+
+Output: [1,#,2,3,#,4,5,6,7,#]
+
+Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
+
+
+ +

 

+ +

Constraints:

+ +
    +
  • The number of nodes in the given tree is less than 4096.
  • +
  • -1000 <= node.val <= 1000
  • +
+ +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + +class Solution: + def connect(self, root: 'Node') -> 'Node': + if root is None or (root.left is None and root.right is None): + return root + q = collections.deque([root]) + while q: + size = len(q) + cur = None + for _ in range(size): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + node.next = cur + cur = node + return root +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root == null || (root.left == null && root.right == null)) { + return root; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + while (!q.isEmpty()) { + Node cur = null; + for (int i = 0, n = q.size(); i < n; ++i) { + Node node = q.pollFirst(); + if (node.right != null) { + q.offer(node.right); + } + if (node.left != null) { + q.offer(node.left); + } + node.next = cur; + cur = node; + } + } + return root; + } +} +``` + +### **C++** + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (!root || (!root->left && !root->right)) { + return root; + } + queue q; + q.push(root); + while (!q.empty()) { + Node* cur = nullptr; + for (int i = 0, n = q.size(); i < n; ++i) { + Node* node = q.front(); + q.pop(); + if (node->right) { + q.push(node->right); + } + if (node->left) { + q.push(node->left); + } + node->next = cur; + cur = node; + } + } + return root; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0116.Populating Next Right Pointers in Each Node/images/116_sample.png b/assets/0100-0199/0116.Populating Next Right Pointers in Each Node/images/116_sample.png new file mode 100644 index 00000000..621c514e Binary files /dev/null and b/assets/0100-0199/0116.Populating Next Right Pointers in Each Node/images/116_sample.png differ diff --git a/assets/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md b/assets/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md new file mode 100644 index 00000000..be2333a6 --- /dev/null +++ b/assets/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md @@ -0,0 +1,201 @@ +# [117. Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii) + + + +## Description + +

Given a binary tree

+ +
+
+struct Node {
+
+  int val;
+
+  Node *left;
+
+  Node *right;
+
+  Node *next;
+
+}
+
+
+ +

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

+ +

Initially, all next pointers are set to NULL.

+ +

 

+ +

Follow up:

+ +
    +
  • You may only use constant extra space.
  • +
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
  • +
+ +

 

+

Example 1:

+ +

+ +
+Input: root = [1,2,3,4,5,null,7]
+Output: [1,#,2,3,#,4,5,7,#]
+Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the given tree is less than 6000.
  • +
  • -100 <= node.val <= 100
  • +
+ +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + +class Solution: + def connect(self, root: 'Node') -> 'Node': + if root is None or (root.left is None and root.right is None): + return root + q = collections.deque([root]) + while q: + size = len(q) + cur = None + for _ in range(size): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + node.next = cur + cur = node + return root + +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root == null || (root.left == null && root.right == null)) { + return root; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + while (!q.isEmpty()) { + Node cur = null; + for (int i = 0, n = q.size(); i < n; ++i) { + Node node = q.pollFirst(); + if (node.right != null) { + q.offer(node.right); + } + if (node.left != null) { + q.offer(node.left); + } + node.next = cur; + cur = node; + } + } + return root; + } +} +``` + +### **C++** + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (!root || (!root->left && !root->right)) { + return root; + } + queue q; + q.push(root); + while (!q.empty()) { + Node* cur = nullptr; + for (int i = 0, n = q.size(); i < n; ++i) { + Node* node = q.front(); + q.pop(); + if (node->right) { + q.push(node->right); + } + if (node->left) { + q.push(node->left); + } + node->next = cur; + cur = node; + } + } + return root; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0117.Populating Next Right Pointers in Each Node II/images/117_sample.png b/assets/0100-0199/0117.Populating Next Right Pointers in Each Node II/images/117_sample.png new file mode 100644 index 00000000..2193a98d Binary files /dev/null and b/assets/0100-0199/0117.Populating Next Right Pointers in Each Node II/images/117_sample.png differ diff --git a/assets/0100-0199/0118.Pascal's Triangle/README_EN.md b/assets/0100-0199/0118.Pascal's Triangle/README_EN.md new file mode 100644 index 00000000..2b9c00d7 --- /dev/null +++ b/assets/0100-0199/0118.Pascal's Triangle/README_EN.md @@ -0,0 +1,131 @@ +# [118. Pascal's Triangle](https://leetcode.com/problems/pascals-triangle) + + + +## Description + +

Given an integer numRows, return the first numRows of Pascal's triangle.

+ +

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

+ +

 

+

Example 1:

+
Input: numRows = 5
+Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
+

Example 2:

+
Input: numRows = 1
+Output: [[1]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= numRows <= 30
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + res = [] + for i in range(numRows): + t = [1 if j == 0 or j == i else 0 for j in range(i + 1)] + for j in range(1, i): + t[j] = res[i - 1][j - 1] + res[i - 1][j] + res.append(t) + return res +``` + +### **Java** + +```java +class Solution { + public List> generate(int numRows) { + List> res = new ArrayList<>(); + for (int i = 0; i < numRows; ++i) { + List t = new ArrayList<>(); + for (int j = 0; j < i + 1; ++j) { + boolean firstOrLast = j == 0 || j == i; + t.add(firstOrLast ? 1 : 0); + } + for (int j = 1; j < i; ++j) { + int val = res.get(i - 1).get(j - 1) + res.get(i - 1).get(j); + t.set(j, val); + } + res.add(t); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> generate(int numRows) { + vector> res; + for (int i = 0; i < numRows; ++i) { + vector t(i + 1); + t[0] = 1; + t[i] = 1; + for (int j = 1; j < i; ++j) { + t[j] = res[i - 1][j - 1] + res[i - 1][j]; + } + res.push_back(t); + } + return res; + } +}; +``` + +### **Go** + +```go +func generate(numRows int) [][]int { + res := make([][]int, numRows) + for i := 0; i < numRows; i++ { + t := make([]int, i+1) + t[0] = 1 + t[i] = 1 + for j := 1; j < i; j++ { + t[j] = res[i-1][j-1] + res[i-1][j] + } + res[i] = t + } + return res +} +``` + +### **JavaScript** + +```js +const generate = function (numRows) { + let arr = []; + for (let i = 0; i < numRows; i++) { + let row = []; + row[0] = 1; + row[i] = 1; + for (let j = 1; j < row.length - 1; j++) { + row[j] = arr[i - 1][j - 1] + arr[i - 1][j]; + } + arr.push(row); + } + return arr; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0118.Pascal's Triangle/images/PascalTriangleAnimated2.gif b/assets/0100-0199/0118.Pascal's Triangle/images/PascalTriangleAnimated2.gif new file mode 100644 index 00000000..c002af43 Binary files /dev/null and b/assets/0100-0199/0118.Pascal's Triangle/images/PascalTriangleAnimated2.gif differ diff --git a/assets/0100-0199/0119.Pascal's Triangle II/README_EN.md b/assets/0100-0199/0119.Pascal's Triangle II/README_EN.md new file mode 100644 index 00000000..e860f837 --- /dev/null +++ b/assets/0100-0199/0119.Pascal's Triangle II/README_EN.md @@ -0,0 +1,120 @@ +# [119. Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii) + + + +## Description + +

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

+ +

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

+ +

 

+

Example 1:

+
Input: rowIndex = 3
+Output: [1,3,3,1]
+

Example 2:

+
Input: rowIndex = 0
+Output: [1]
+

Example 3:

+
Input: rowIndex = 1
+Output: [1,1]
+
+

 

+

Constraints:

+ +
    +
  • 0 <= rowIndex <= 33
  • +
+ +

 

+

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def getRow(self, rowIndex: int) -> List[int]: + row = [1] * (rowIndex + 1) + for i in range(2, rowIndex + 1): + for j in range(i - 1, 0, -1): + row[j] += row[j - 1] + return row +``` + +### **Java** + +```java +class Solution { + public List getRow(int rowIndex) { + List row = new ArrayList<>(); + for (int i = 0; i < rowIndex + 1; ++i) { + row.add(1); + } + for (int i = 2; i < rowIndex + 1; ++i) { + for (int j = i - 1; j > 0; --j) { + row.set(j, row.get(j) + row.get(j - 1)); + } + } + return row; + } +} +``` + +### **TypeScript** + +```ts +function getRow(rowIndex: number): number[] { + let ans = new Array(rowIndex + 1).fill(1); + for (let i = 2; i < rowIndex + 1; ++i) { + for (let j = i -1; j > 0; --j) { + ans[j] += ans[j - 1]; + } + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector getRow(int rowIndex) { + vector row(rowIndex + 1, 1); + for (int i = 2; i < rowIndex + 1; ++i) { + for (int j = i - 1; j > 0; --j) { + row[j] += row[j - 1]; + } + } + return row; + } +}; +``` + +### **Go** + +```go +func getRow(rowIndex int) []int { + row := make([]int, rowIndex+1) + row[0] = 1 + for i := 1; i <= rowIndex; i++ { + for j := i; j > 0; j-- { + row[j] += row[j-1] + } + } + return row +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0119.Pascal's Triangle II/images/PascalTriangleAnimated2.gif b/assets/0100-0199/0119.Pascal's Triangle II/images/PascalTriangleAnimated2.gif new file mode 100644 index 00000000..c002af43 Binary files /dev/null and b/assets/0100-0199/0119.Pascal's Triangle II/images/PascalTriangleAnimated2.gif differ diff --git a/assets/0100-0199/0120.Triangle/README_EN.md b/assets/0100-0199/0120.Triangle/README_EN.md new file mode 100644 index 00000000..22018657 --- /dev/null +++ b/assets/0100-0199/0120.Triangle/README_EN.md @@ -0,0 +1,153 @@ +# [120. Triangle](https://leetcode.com/problems/triangle) + + + +## Description + +

Given a triangle array, return the minimum path sum from top to bottom.

+ +

For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

+ +

 

+

Example 1:

+ +
+Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
+Output: 11
+Explanation: The triangle looks like:
+   2
+  3 4
+ 6 5 7
+4 1 8 3
+The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
+
+ +

Example 2:

+ +
+Input: triangle = [[-10]]
+Output: -10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= triangle.length <= 200
  • +
  • triangle[0].length == 1
  • +
  • triangle[i].length == triangle[i - 1].length + 1
  • +
  • -104 <= triangle[i][j] <= 104
  • +
+ +

 

+Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle? + +## Solutions + +Dynamic programming. + + + +### **Python3** + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + for i in range(1, n): + for j in range(i + 1): + mi = float('inf') + if j > 0: + mi = min(mi, triangle[i - 1][j - 1]) + if j < i: + mi = min(mi, triangle[i - 1][j]) + triangle[i][j] += mi + return min(triangle[n - 1]) +``` + +### **Java** + +```java +class Solution { + public int minimumTotal(List> triangle) { + int n = triangle.size(); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i + 1; ++j) { + int mi = Integer.MAX_VALUE; + if (j > 0) { + mi = Math.min(mi, triangle.get(i - 1).get(j - 1)); + } + if (j < i) { + mi = Math.min(mi, triangle.get(i - 1).get(j)); + } + triangle.get(i).set(j, triangle.get(i).get(j) + mi); + } + } + int res = Integer.MAX_VALUE; + for (int val : triangle.get(n - 1)) { + res = Math.min(res, val); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i + 1; ++j) { + int mi = INT_MAX; + if (j > 0) mi = min(mi, triangle[i - 1][j - 1]); + if (j < i) mi = min(mi, triangle[i - 1][j]); + triangle[i][j] += mi; + } + } + int res = INT_MAX; + for (int& val : triangle[n - 1]) { + res = min(res, val); + } + return res; + } +}; +``` + +### **Go** + +```go +func minimumTotal(triangle [][]int) int { + n := len(triangle) + for i := 1; i < n; i++ { + for j := 0; j < i+1; j++ { + mi := 2000000 + if j > 0 && mi > triangle[i-1][j-1] { + mi = triangle[i-1][j-1] + } + if j < i && mi > triangle[i-1][j] { + mi = triangle[i-1][j] + } + triangle[i][j] += mi + } + } + + res := 2000000 + for j := 0; j < n; j++ { + if res > triangle[n-1][j] { + res = triangle[n-1][j] + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md b/assets/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md new file mode 100644 index 00000000..1328b6da --- /dev/null +++ b/assets/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md @@ -0,0 +1,154 @@ +# [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock) + + + +## Description + +

You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

+ +

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

+ +

 

+

Example 1:

+ +
+Input: prices = [7,1,5,3,6,4]
+Output: 5
+Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
+Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
+
+ +

Example 2:

+ +
+Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transactions are done and the max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + res, mi = 0, prices[0] + for price in prices[1:]: + res = max(res, price - mi) + mi = min(mi, price) + return res +``` + +### **Java** + +```java +class Solution { + public int maxProfit(int[] prices) { + int res = 0, mi = prices[0]; + for (int i = 1; i < prices.length; ++i) { + res = Math.max(res, prices[i] - mi); + mi = Math.min(mi, prices[i]); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int res = 0, mi = prices[0]; + for (int i = 1; i < prices.size(); ++i) { + res = max(res, prices[i] - mi); + mi = min(mi, prices[i]); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int) int { + res, mi := 0, prices[0] + for i := 1; i < len(prices); i++ { + res = max(res, prices[i]-mi) + mi = min(min, prices[i]) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let res = 0; + let mi = prices[0]; + for (let i = 1; i < prices.length; ++i) { + res = Math.max(res, prices[i] - mi); + mi = Math.min(mi, prices[i]); + } + return res; +}; +``` + +### **C#** + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int res = 0, mi = prices[0]; + for (int i = 1; i < prices.Length; ++i) + { + res = Math.Max(res, prices[i] - mi); + mi = Math.Min(mi, prices[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md b/assets/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md new file mode 100644 index 00000000..a9a9d428 --- /dev/null +++ b/assets/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md @@ -0,0 +1,236 @@ +# [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii) + + + +## Description + +

You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
+Input: prices = [7,1,5,3,6,4]
+Output: 7
+Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
+Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
+
+ +

Example 2:

+ +
+Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
+
+ +

Example 3:

+ +
+Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transaction is done, i.e., max profit = 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 3 * 104
  • +
  • 0 <= prices[i] <= 104
  • +
+ + +## Solutions + +Greedy or Dynamic Programming. + + + +### **Python3** + +Greedy: + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + res = 0 + for i in range(1, len(prices)): + t = prices[i] - prices[i - 1] + res += max(t, 0) + return res +``` + +Dynamic Programming: + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f1, f2 = -prices[0], 0 + for price in prices[1:]: + f1 = max(f1, f2 - price) + f2 = max(f2, f1 + price) + return f2 +``` + +### **Java** + +Greedy: + +```java +class Solution { + public int maxProfit(int[] prices) { + int res = 0; + for (int i = 1; i < prices.length; ++i) { + int t = prices[i] - prices[i - 1]; + res += Math.max(t, 0); + } + return res; + } +} +``` + +Dynamic Programming: + +```java +class Solution { + public int maxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, f2 - prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + } + return f2; + } +} +``` + +### **TypeScript** + +```ts +function maxProfit(prices: number[]): number { + let ans = 0; + for (let i = 1; i < prices.length; i++) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; +}; +``` + +### **C++** + +Greedy: + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int res = 0; + for (int i = 1; i < prices.size(); ++i) { + int t = prices[i] - prices[i - 1]; + res += max(t, 0); + } + return res; + } +}; +``` + +Dynamic Programming: + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.size(); ++i) { + f1 = max(f1, f2 - prices[i]); + f2 = max(f2, f1 + prices[i]); + } + return f2; + } +}; +``` + +### **Go** + +Greedy: + +```go +func maxProfit(prices []int) int { + res := 0 + for i := 1; i < len(prices); i++ { + t := prices[i] - prices[i-1] + if t > 0 { + res += t + } + } + return res +} +``` + +Dynamic Programming: + +```go +func maxProfit(prices []int) int { + f1, f2 := -prices[0], 0 + for _, price := range prices[1:] { + f1 = max(f1, f2-price) + f2 = max(f2, f1+price) + } + return f2 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +Greedy: + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int res = 0; + for (int i = 1; i < prices.Length; ++i) + { + int t = prices[i] - prices[i - 1]; + res += Math.Max(t, 0); + } + return res; + } +} +``` + +Dynamic Programming: + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.Length; ++i) + { + f1 = Math.Max(f1, f2 - prices[i]); + f2 = Math.Max(f2, f1 + prices[i]); + } + return f2; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md b/assets/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md new file mode 100644 index 00000000..93c12aa8 --- /dev/null +++ b/assets/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md @@ -0,0 +1,154 @@ +# [123. Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii) + + + +## Description + +

You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete at most two transactions.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
+Input: prices = [3,3,5,0,0,3,1,4]
+Output: 6
+Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
+Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
+ +

Example 2:

+ +
+Input: prices = [1,2,3,4,5]
+Output: 4
+Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
+Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
+
+ +

Example 3:

+ +
+Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transaction is done, i.e. max profit = 0.
+
+ +

Example 4:

+ +
+Input: prices = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 105
  • +
  • 0 <= prices[i] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0 + for price in prices[1:]: + f1 = max(f1, -price) + f2 = max(f2, f1 + price) + f3 = max(f3, f2 - price) + f4 = max(f4, f3 + price) + return f4 +``` + +### **Java** + +```java +class Solution { + public int maxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, -prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + f3 = Math.max(f3, f2 - prices[i]); + f4 = Math.max(f4, f3 + prices[i]); + } + return f4; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; + for (int i = 1; i < prices.size(); ++i) { + f1 = max(f1, -prices[i]); + f2 = max(f2, f1 + prices[i]); + f3 = max(f3, f2 - prices[i]); + f4 = max(f4, f3 + prices[i]); + } + return f4; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int) int { + f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 + for i := 1; i < len(prices); i++ { + f1 = max(f1, -prices[i]) + f2 = max(f2, f1 + prices[i]) + f3 = max(f3, f2 - prices[i]) + f4 = max(f4, f3 + prices[i]) + } + return f4 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; + for (int i = 1; i < prices.Length; ++i) + { + f1 = Math.Max(f1, -prices[i]); + f2 = Math.Max(f2, f1 + prices[i]); + f3 = Math.Max(f3, f2 - prices[i]); + f4 = Math.Max(f4, f3 + prices[i]); + } + return f4; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md b/assets/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md new file mode 100644 index 00000000..538543d0 --- /dev/null +++ b/assets/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md @@ -0,0 +1,61 @@ +# [124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum) + + + +## Description + +

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

+ +

The path sum of a path is the sum of the node's values in the path.

+ +

Given the root of a binary tree, return the maximum path sum of any path.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3]
+Output: 6
+Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
+
+ +

Example 2:

+ +
+Input: root = [-10,9,20,null,null,15,7]
+Output: 42
+Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3 * 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0124.Binary Tree Maximum Path Sum/images/exx1.jpg b/assets/0100-0199/0124.Binary Tree Maximum Path Sum/images/exx1.jpg new file mode 100644 index 00000000..8402ff72 Binary files /dev/null and b/assets/0100-0199/0124.Binary Tree Maximum Path Sum/images/exx1.jpg differ diff --git a/assets/0100-0199/0124.Binary Tree Maximum Path Sum/images/exx2.jpg b/assets/0100-0199/0124.Binary Tree Maximum Path Sum/images/exx2.jpg new file mode 100644 index 00000000..557cd593 Binary files /dev/null and b/assets/0100-0199/0124.Binary Tree Maximum Path Sum/images/exx2.jpg differ diff --git a/assets/0100-0199/0125.Valid Palindrome/README_EN.md b/assets/0100-0199/0125.Valid Palindrome/README_EN.md new file mode 100644 index 00000000..990cda1a --- /dev/null +++ b/assets/0100-0199/0125.Valid Palindrome/README_EN.md @@ -0,0 +1,138 @@ +# [125. Valid Palindrome](https://leetcode.com/problems/valid-palindrome) + + + +## Description + +

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

+ +

 

+

Example 1:

+ +
+Input: s = "A man, a plan, a canal: Panama"
+Output: true
+Explanation: "amanaplanacanalpanama" is a palindrome.
+
+ +

Example 2:

+ +
+Input: s = "race a car"
+Output: false
+Explanation: "raceacar" is not a palindrome.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2 * 105
  • +
  • s consists only of printable ASCII characters.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPalindrome(self, s: str) -> bool: + i, j = 0, len(s) - 1 + while i < j: + if not s[i].isalnum(): + i += 1 + elif not s[j].isalnum(): + j -= 1 + elif s[i].lower() != s[j].lower(): + return False + else: + i += 1 + j -= 1 + return True +``` + +### **Java** + +```java +class Solution { + public boolean isPalindrome(String s) { + int i = 0, j = s.length() - 1; + while (i < j) { + if (!Character.isLetterOrDigit(s.charAt(i))) { + ++i; + } else if (!Character.isLetterOrDigit(s.charAt(j))) { + --j; + } else if (Character.toUpperCase(s.charAt(i)) != Character.toUpperCase(s.charAt(j))) { + return false; + } else { + ++i; + --j; + } + } + return true; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPalindrome(string s) { + int i = 0, j = s.size() - 1; + while (i < j) { + if (!isAlphaNum(s[i])) ++i; + else if (!isAlphaNum(s[j])) --j; + else if ((s[i] + 32 - 'a') % 32 != (s[j] + 32 - 'a') % 32) return false; + else { + ++i; + --j; + } + } + return true; + } + +private: + bool isAlphaNum(char &ch) { + if (ch >= 'a' && ch <= 'z') return true; + if (ch >= 'A' && ch <= 'Z') return true; + if (ch >= '0' && ch <= '9') return true; + return false; + } +}; +``` + +### **TypeScript** + +```ts +function isPalindrome(s: string): boolean { + let left: number = 0, right: number = s.length - 1; + while (left < right) { + let char1: string = s.charAt(left); + let char2: string = s.charAt(right); + if (!(/[a-zA-Z0-9]/).test(char1)) { + ++left; + } else if (!(/[a-zA-Z0-9]/).test(char2)) { + --right; + } else if (char1.toLocaleLowerCase() != char2.toLocaleLowerCase()) { + return false; + } else { + ++left; + --right; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0126.Word Ladder II/README_EN.md b/assets/0100-0199/0126.Word Ladder II/README_EN.md new file mode 100644 index 00000000..d8766985 --- /dev/null +++ b/assets/0100-0199/0126.Word Ladder II/README_EN.md @@ -0,0 +1,72 @@ +# [126. Word Ladder II](https://leetcode.com/problems/word-ladder-ii) + + + +## Description + +

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

+ +
    +
  • Every adjacent pair of words differs by a single letter.
  • +
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • +
  • sk == endWord
  • +
+ +

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

+ +

 

+

Example 1:

+ +
+Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
+Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
+Explanation: There are 2 shortest transformation sequences:
+"hit" -> "hot" -> "dot" -> "dog" -> "cog"
+"hit" -> "hot" -> "lot" -> "log" -> "cog"
+
+ +

Example 2:

+ +
+Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
+Output: []
+Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= beginWord.length <= 7
  • +
  • endWord.length == beginWord.length
  • +
  • 1 <= wordList.length <= 5000
  • +
  • wordList[i].length == beginWord.length
  • +
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • +
  • beginWord != endWord
  • +
  • All the words in wordList are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0127.Word Ladder/README_EN.md b/assets/0100-0199/0127.Word Ladder/README_EN.md new file mode 100644 index 00000000..0ca733b4 --- /dev/null +++ b/assets/0100-0199/0127.Word Ladder/README_EN.md @@ -0,0 +1,70 @@ +# [127. Word Ladder](https://leetcode.com/problems/word-ladder) + + + +## Description + +

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

+ +
    +
  • Every adjacent pair of words differs by a single letter.
  • +
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • +
  • sk == endWord
  • +
+ +

Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

+ +

 

+

Example 1:

+ +
+Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
+Output: 5
+Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.
+
+ +

Example 2:

+ +
+Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
+Output: 0
+Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= beginWord.length <= 10
  • +
  • endWord.length == beginWord.length
  • +
  • 1 <= wordList.length <= 5000
  • +
  • wordList[i].length == beginWord.length
  • +
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • +
  • beginWord != endWord
  • +
  • All the words in wordList are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0128.Longest Consecutive Sequence/README_EN.md b/assets/0100-0199/0128.Longest Consecutive Sequence/README_EN.md new file mode 100644 index 00000000..9da5dc59 --- /dev/null +++ b/assets/0100-0199/0128.Longest Consecutive Sequence/README_EN.md @@ -0,0 +1,58 @@ +# [128. Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence) + + + +## Description + +

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

+ +

 

+

Example 1:

+ +
+Input: nums = [100,4,200,1,3,2]
+Output: 4
+Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
+
+ +

Example 2:

+ +
+Input: nums = [0,3,7,2,5,8,4,6,0,1]
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ +

 

+Follow up: Could you implement the O(n) solution? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md b/assets/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md new file mode 100644 index 00000000..f5f7bfef --- /dev/null +++ b/assets/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md @@ -0,0 +1,75 @@ +# [129. Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers) + + + +## Description + +

You are given the root of a binary tree containing digits from 0 to 9 only.

+ +

Each root-to-leaf path in the tree represents a number.

+ +
    +
  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
  • +
+ +

Return the total sum of all root-to-leaf numbers.

+ +

A leaf node is a node with no children.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3]
+Output: 25
+Explanation:
+The root-to-leaf path 1->2 represents the number 12.
+The root-to-leaf path 1->3 represents the number 13.
+Therefore, sum = 12 + 13 = 25.
+
+ +

Example 2:

+ +
+Input: root = [4,9,0,5,1]
+Output: 1026
+Explanation:
+The root-to-leaf path 4->9->5 represents the number 495.
+The root-to-leaf path 4->9->1 represents the number 491.
+The root-to-leaf path 4->0 represents the number 40.
+Therefore, sum = 495 + 491 + 40 = 1026.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • 0 <= Node.val <= 9
  • +
  • The depth of the tree will not exceed 10.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0129.Sum Root to Leaf Numbers/images/num1tree.jpg b/assets/0100-0199/0129.Sum Root to Leaf Numbers/images/num1tree.jpg new file mode 100644 index 00000000..b806f980 Binary files /dev/null and b/assets/0100-0199/0129.Sum Root to Leaf Numbers/images/num1tree.jpg differ diff --git a/assets/0100-0199/0129.Sum Root to Leaf Numbers/images/num2tree.jpg b/assets/0100-0199/0129.Sum Root to Leaf Numbers/images/num2tree.jpg new file mode 100644 index 00000000..02e1174d Binary files /dev/null and b/assets/0100-0199/0129.Sum Root to Leaf Numbers/images/num2tree.jpg differ diff --git a/assets/0100-0199/0130.Surrounded Regions/README_EN.md b/assets/0100-0199/0130.Surrounded Regions/README_EN.md new file mode 100644 index 00000000..71eb9534 --- /dev/null +++ b/assets/0100-0199/0130.Surrounded Regions/README_EN.md @@ -0,0 +1,116 @@ +# [130. Surrounded Regions](https://leetcode.com/problems/surrounded-regions) + + + +## Description + +

Given an m x n matrix board containing 'X' and 'O', capture all regions surrounded by 'X'.

+ +

A region is captured by flipping all 'O's into 'X's in that surrounded region.

+ +

 

+

Example 1:

+ +
+Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
+Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
+Explanation: Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
+
+ +

Example 2:

+ +
+Input: board = [["X"]]
+Output: [["X"]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • board[i][j] is 'X' or 'O'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **TypeScript** + +```ts +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + let m = board.length, n = board[0].length; + if (m < 3 || n < 3) return; + let visited = Array.from({ length: m }, v => new Array(n).fill(false)); + // 第一行,最后一行, 第一列, 最后一列 + for (let i of [0, m-1]) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'X') { + visited[i][j] = true; + } else { + dfs(board, i, j, visited, true); + } + } + } + for (let i = 0; i < m; ++i) { + for (let j of [0, n - 1]) { + if (board[i][j] == 'X') { + visited[i][j] = true; + } else { + dfs(board, i, j, visited, true); + } + } + } + for (let i = 1; i < m - 1; ++i) { + for (let j = 1; j < n - 1; ++j) { + !visited[i][j] && dfs(board, i, j, visited); + } + } +}; + +function dfs(board: string[][], i: number, j: number, visited: boolean[][], edge = false): void { + let m = board.length, n = board[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || visited[i][j]) { + return; + } + + visited[i][j] = true; + if (board[i][j] == 'X') { + return; + } + if (!edge) { + board[i][j] = 'X'; + } + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + dfs(board, x, y, visited, edge); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0130.Surrounded Regions/images/xogrid.jpg b/assets/0100-0199/0130.Surrounded Regions/images/xogrid.jpg new file mode 100644 index 00000000..7ef7698d Binary files /dev/null and b/assets/0100-0199/0130.Surrounded Regions/images/xogrid.jpg differ diff --git a/assets/0100-0199/0131.Palindrome Partitioning/README_EN.md b/assets/0100-0199/0131.Palindrome Partitioning/README_EN.md new file mode 100644 index 00000000..a8eadb35 --- /dev/null +++ b/assets/0100-0199/0131.Palindrome Partitioning/README_EN.md @@ -0,0 +1,50 @@ +# [131. Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning) + + + +## Description + +

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

+ +

A palindrome string is a string that reads the same backward as forward.

+ +

 

+

Example 1:

+
Input: s = "aab"
+Output: [["a","a","b"],["aa","b"]]
+

Example 2:

+
Input: s = "a"
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 16
  • +
  • s contains only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0132.Palindrome Partitioning II/README_EN.md b/assets/0100-0199/0132.Palindrome Partitioning II/README_EN.md new file mode 100644 index 00000000..f8f44ec6 --- /dev/null +++ b/assets/0100-0199/0132.Palindrome Partitioning II/README_EN.md @@ -0,0 +1,65 @@ +# [132. Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii) + + + +## Description + +

Given a string s, partition s such that every substring of the partition is a palindrome.

+ +

Return the minimum cuts needed for a palindrome partitioning of s.

+ +

 

+

Example 1:

+ +
+Input: s = "aab"
+Output: 1
+Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
+
+ +

Example 2:

+ +
+Input: s = "a"
+Output: 0
+
+ +

Example 3:

+ +
+Input: s = "ab"
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2000
  • +
  • s consists of lower-case English letters only.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0133.Clone Graph/README_EN.md b/assets/0100-0199/0133.Clone Graph/README_EN.md new file mode 100644 index 00000000..ccd9cc8c --- /dev/null +++ b/assets/0100-0199/0133.Clone Graph/README_EN.md @@ -0,0 +1,122 @@ +# [133. Clone Graph](https://leetcode.com/problems/clone-graph) + + + +## Description + +

Given a reference of a node in a connected undirected graph.

+ + + +

Return a deep copy (clone) of the graph.

+ + + +

Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

+ + + +
+
+class Node {
+
+    public int val;
+
+    public List<Node> neighbors;
+
+}
+
+
+ + + +

 

+ + + +

Test case format:

+ + + +

For simplicity sake, each node's value is the same as the node's index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.

+ + + +

Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

+ + + +

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

+ + +

 

+

Example 1:

+ +
+Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
+Output: [[2,4],[1,3],[2,4],[1,3]]
+Explanation: There are 4 nodes in the graph.
+1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
+4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
+
+ +

Example 2:

+ +
+Input: adjList = [[]]
+Output: [[]]
+Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
+
+ +

Example 3:

+ +
+Input: adjList = []
+Output: []
+Explanation: This an empty graph, it does not have any nodes.
+
+ +

Example 4:

+ +
+Input: adjList = [[2],[1]]
+Output: [[2],[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= Node.val <= 100
  • +
  • Node.val is unique for each node.
  • +
  • Number of Nodes will not exceed 100.
  • +
  • There is no repeated edges and no self-loops in the graph.
  • +
  • The Graph is connected and all nodes can be visited starting from the given node.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0133.Clone Graph/images/133_clone_graph_question.png b/assets/0100-0199/0133.Clone Graph/images/133_clone_graph_question.png new file mode 100644 index 00000000..d4627a50 Binary files /dev/null and b/assets/0100-0199/0133.Clone Graph/images/133_clone_graph_question.png differ diff --git a/assets/0100-0199/0133.Clone Graph/images/graph-1.png b/assets/0100-0199/0133.Clone Graph/images/graph-1.png new file mode 100644 index 00000000..d332f377 Binary files /dev/null and b/assets/0100-0199/0133.Clone Graph/images/graph-1.png differ diff --git a/assets/0100-0199/0133.Clone Graph/images/graph.png b/assets/0100-0199/0133.Clone Graph/images/graph.png new file mode 100644 index 00000000..92c9c5db Binary files /dev/null and b/assets/0100-0199/0133.Clone Graph/images/graph.png differ diff --git a/assets/0100-0199/0134.Gas Station/README_EN.md b/assets/0100-0199/0134.Gas Station/README_EN.md new file mode 100644 index 00000000..75993c7c --- /dev/null +++ b/assets/0100-0199/0134.Gas Station/README_EN.md @@ -0,0 +1,76 @@ +# [134. Gas Station](https://leetcode.com/problems/gas-station) + + + +## Description + +

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

+ +

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

+ +

Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

+ +

 

+

Example 1:

+ +
+Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
+Output: 3
+Explanation:
+Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
+Travel to station 4. Your tank = 4 - 1 + 5 = 8
+Travel to station 0. Your tank = 8 - 2 + 1 = 7
+Travel to station 1. Your tank = 7 - 3 + 2 = 6
+Travel to station 2. Your tank = 6 - 4 + 3 = 5
+Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
+Therefore, return 3 as the starting index.
+
+ +

Example 2:

+ +
+Input: gas = [2,3,4], cost = [3,4,3]
+Output: -1
+Explanation:
+You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
+Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
+Travel to station 0. Your tank = 4 - 3 + 2 = 3
+Travel to station 1. Your tank = 3 - 3 + 3 = 3
+You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
+Therefore, you can't travel around the circuit once no matter where you start.
+
+ +

 

+

Constraints:

+ +
    +
  • gas.length == n
  • +
  • cost.length == n
  • +
  • 1 <= n <= 104
  • +
  • 0 <= gas[i], cost[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0135.Candy/README_EN.md b/assets/0100-0199/0135.Candy/README_EN.md new file mode 100644 index 00000000..516ba22c --- /dev/null +++ b/assets/0100-0199/0135.Candy/README_EN.md @@ -0,0 +1,68 @@ +# [135. Candy](https://leetcode.com/problems/candy) + + + +## Description + +

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

+ +

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

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

Return the minimum number of candies you need to have to distribute the candies to the children.

+ +

 

+

Example 1:

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

Example 2:

+ +
+Input: ratings = [1,2,2]
+Output: 4
+Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
+The third child gets 1 candy because it satisfies the above two conditions.
+
+ +

 

+

Constraints:

+ +
    +
  • n == ratings.length
  • +
  • 1 <= n <= 2 * 104
  • +
  • 0 <= ratings[i] <= 2 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0136.Single Number/README_EN.md b/assets/0100-0199/0136.Single Number/README_EN.md new file mode 100644 index 00000000..053039ac --- /dev/null +++ b/assets/0100-0199/0136.Single Number/README_EN.md @@ -0,0 +1,110 @@ +# [136. Single Number](https://leetcode.com/problems/single-number) + + + +## Description + +

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

+ +

Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

+ +

 

+

Example 1:

+
Input: nums = [2,2,1]
+Output: 1
+

Example 2:

+
Input: nums = [4,1,2,1,2]
+Output: 4
+

Example 3:

+
Input: nums = [1]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -3 * 104 <= nums[i] <= 3 * 104
  • +
  • Each element in the array appears twice except for one element which appears only once.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + res = 0 + for num in nums: + res ^= num + return res +``` + +### **Java** + +```java +class Solution { + public int singleNumber(int[] nums) { + int res = 0; + for (int num : nums) { + res ^= num; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function (nums) { + let res = 0; + for (let num of nums) { + res ^= num; + } + return res; +}; +``` + +### **Go** + +```go +func singleNumber(nums []int) int { + res := 0 + for _, v := range nums { + res ^= v + } + return res +} +``` + +### **C++** + +```cpp +class Solution { +public: + int singleNumber(vector& nums) { + int res = 0; + for (auto num : nums) { + res ^= num; + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0137.Single Number II/README_EN.md b/assets/0100-0199/0137.Single Number II/README_EN.md new file mode 100644 index 00000000..40ff8ad1 --- /dev/null +++ b/assets/0100-0199/0137.Single Number II/README_EN.md @@ -0,0 +1,81 @@ +# [137. Single Number II](https://leetcode.com/problems/single-number-ii) + + + +## Description + +

Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.

+ +

 

+

Example 1:

+
Input: nums = [2,2,3,2]
+Output: 3
+

Example 2:

+
Input: nums = [0,1,0,1,0,1,99]
+Output: 99
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • Each element in nums appears exactly three times except for one element which appears once.
  • +
+ +

 

+

Follow up: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + bits = [0] * 32 + for num in nums: + for i in range(32): + bits[i] += (num & 1) + num >>= 1 + res = 0 + for i in range(32): + if bits[i] % 3 != 0: + res |= (1 << i) + return res if bits[31] % 3 == 0 else ~(res ^ 0xffffffff) +``` + +### **Java** + +```java +class Solution { + public int singleNumber(int[] nums) { + int[] bits = new int[32]; + for (int num : nums) { + for (int i = 0; i < 32; ++i) { + bits[i] += (num & 1); + num >>= 1; + } + } + + int res = 0; + for (int i = 0; i < 32; ++i) { + if (bits[i] % 3 == 1) { + res |= (1 << i); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0138.Copy List with Random Pointer/README_EN.md b/assets/0100-0199/0138.Copy List with Random Pointer/README_EN.md new file mode 100644 index 00000000..fe7311f9 --- /dev/null +++ b/assets/0100-0199/0138.Copy List with Random Pointer/README_EN.md @@ -0,0 +1,367 @@ +# [138. Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer) + + + +## Description + +

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

+ +

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

+ +

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

+ +

Return the head of the copied linked list.

+ +

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

+ +
    +
  • val: an integer representing Node.val
  • +
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
  • +
+ +

Your code will only be given the head of the original linked list.

+ +

 

+

Example 1:

+ +
+Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
+Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
+
+ +

Example 2:

+ +
+Input: head = [[1,1],[2,1]]
+Output: [[1,1],[2,1]]
+
+ +

Example 3:

+ +

+ +
+Input: head = [[3,null],[3,0],[3,null]]
+Output: [[3,null],[3,0],[3,null]]
+
+ +

Example 4:

+ +
+Input: head = []
+Output: []
+Explanation: The given linked list is empty (null pointer), so return null.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 1000
  • +
  • -10000 <= Node.val <= 10000
  • +
  • Node.random is null or is pointing to some node in the linked list.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + +class Solution: + def copyRandomList(self, head: 'Node') -> 'Node': + if head is None: + return None + + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + cur.next.random = None if cur.random is None else cur.random.next + cur = cur.next.next + + copy = head.next + cur = head + while cur: + next = cur.next + cur.next = next.next + next.next = None if next.next is None else next.next.next + cur = cur.next + return copy +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + int val; + Node next; + Node random; + + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } +} +*/ + +class Solution { + public Node copyRandomList(Node head) { + if (head == null) { + return null; + } + + Node cur = head; + while (cur != null) { + Node node = new Node(cur.val); + node.next = cur.next; + cur.next = node; + cur = node.next; + } + + cur = head; + while (cur != null) { + cur.next.random = cur.random == null ? null : cur.random.next; + cur = cur.next.next; + } + + Node copy = head.next; + cur = head; + while (cur != null) { + Node next = cur.next; + cur.next = next.next; + next.next = next.next == null ? null : next.next.next; + cur = cur.next; + } + return copy; + } +} +``` + +### **C++** + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + Node* cur = head; + while (cur) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + + cur = head; + while (cur) { + cur->next->random = cur->random ? cur->random->next : nullptr; + cur = cur->next->next; + } + + Node* copy = head->next; + cur = head; + while (cur) { + Node* next = cur->next; + cur->next = next->next; + next->next = next->next ? next->next->next : nullptr; + cur = cur->next; + } + return copy; + } +}; +``` + +### **C#** + +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; + + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ + +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + + Node cur = head; + while (cur != null) { + Node node = new Node(cur.val); + node.next = cur.next; + cur.next = node; + cur = node.next; + } + + cur = head; + while (cur != null) { + cur.next.random = cur.random == null ? null : cur.random.next; + cur = cur.next.next; + } + + Node copy = head.next; + cur = head; + while (cur != null) { + Node next = cur.next; + cur.next = next.next; + next.next = next.next == null ? null : next.next.next; + cur = cur.next; + } + return copy; + } +} +``` + +### **Go** + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + + cur := head + for cur != nil { + node := &Node{ + Val: cur.Val, + Next: cur.Next, + Random: nil, + } + cur.Next = node + cur = node.Next + } + + cur = head + for cur != nil { + if cur.Random == nil { + cur.Next.Random = nil + } else { + cur.Next.Random = cur.Random.Next + } + cur = cur.Next.Next + } + + copy := head.Next + cur = head + for cur != nil { + next := cur.Next + cur.Next = next.Next + if (next.Next == nil) { + next.Next = nil + } else { + next.Next = next.Next.Next + } + cur = cur.Next + } + return copy +} +``` + +### **JavaScript** + +```js +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head) { + if (head == null) { + return null; + } + let cur = head; + while (cur != null) { + let node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + + cur = head; + while (cur != null) { + cur.next.random = cur.random == null ? null : cur.random.next; + cur = cur.next.next; + } + + let copy = head.next; + cur = head; + while (cur != null) { + let next = cur.next; + cur.next = next.next; + next.next = next.next == null ? null : next.next.next; + cur = cur.next; + } + return copy; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0138.Copy List with Random Pointer/images/e1.png b/assets/0100-0199/0138.Copy List with Random Pointer/images/e1.png new file mode 100644 index 00000000..f6bcccf1 Binary files /dev/null and b/assets/0100-0199/0138.Copy List with Random Pointer/images/e1.png differ diff --git a/assets/0100-0199/0138.Copy List with Random Pointer/images/e2.png b/assets/0100-0199/0138.Copy List with Random Pointer/images/e2.png new file mode 100644 index 00000000..940edb63 Binary files /dev/null and b/assets/0100-0199/0138.Copy List with Random Pointer/images/e2.png differ diff --git a/assets/0100-0199/0138.Copy List with Random Pointer/images/e3.png b/assets/0100-0199/0138.Copy List with Random Pointer/images/e3.png new file mode 100644 index 00000000..a6bd087e Binary files /dev/null and b/assets/0100-0199/0138.Copy List with Random Pointer/images/e3.png differ diff --git a/assets/0100-0199/0139.Word Break/README_EN.md b/assets/0100-0199/0139.Word Break/README_EN.md new file mode 100644 index 00000000..ececbb9b --- /dev/null +++ b/assets/0100-0199/0139.Word Break/README_EN.md @@ -0,0 +1,173 @@ +# [139. Word Break](https://leetcode.com/problems/word-break) + + + +## Description + +

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

+ +

Note that the same word in the dictionary may be reused multiple times in the segmentation.

+ +

 

+

Example 1:

+ +
+Input: s = "leetcode", wordDict = ["leet","code"]
+Output: true
+Explanation: Return true because "leetcode" can be segmented as "leet code".
+
+ +

Example 2:

+ +
+Input: s = "applepenapple", wordDict = ["apple","pen"]
+Output: true
+Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
+Note that you are allowed to reuse a dictionary word.
+
+ +

Example 3:

+ +
+Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 300
  • +
  • 1 <= wordDict.length <= 1000
  • +
  • 1 <= wordDict[i].length <= 20
  • +
  • s and wordDict[i] consist of only lowercase English letters.
  • +
  • All the strings of wordDict are unique.
  • +
+ + +## Solutions + +Dynamic Programming. + + + +### **Python3** + +```python +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + words = set(wordDict) + n = len(s) + dp = [False] * (n + 1) + dp[0] = True + for i in range(1, n + 1): + for j in range(i): + if dp[j] and s[j:i] in words: + dp[i] = True + break + return dp[n] +``` + +### **Java** + +```java +class Solution { + public boolean wordBreak(String s, List wordDict) { + Set words = new HashSet<>(wordDict); + int n = s.length(); + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (dp[j] && words.contains(s.substring(j, i))) { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + unordered_set words; + for (auto word : wordDict) { + words.insert(word); + } + int n = s.size(); + vector dp(n + 1, false); + dp[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (dp[j] && words.find(s.substr(j, i - j)) != words.end()) { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +}; +``` + +### **Go** + +```go +func wordBreak(s string, wordDict []string) bool { + words := make(map[string]bool) + for _, word := range wordDict { + words[word] = true + } + n := len(s) + dp := make([]bool, n+1) + dp[0] = true + for i := 1; i <= n; i++ { + for j := 0; j < i; j++ { + if dp[j] && words[s[j:i]] { + dp[i] = true + break + } + } + } + return dp[n] +} +``` + +### **C#** + +```cs +public class Solution { + public bool WordBreak(string s, IList wordDict) { + var words = new HashSet(wordDict); + int n = s.Length; + var dp = new bool[n + 1]; + dp[0] = true; + for (int i = 1; i <= n; ++i) + { + for (int j = 0; j < i; ++j) + { + if (dp[j] && words.Contains(s.Substring(j, i - j))) + { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0140.Word Break II/README_EN.md b/assets/0100-0199/0140.Word Break II/README_EN.md new file mode 100644 index 00000000..c08caf52 --- /dev/null +++ b/assets/0100-0199/0140.Word Break II/README_EN.md @@ -0,0 +1,68 @@ +# [140. Word Break II](https://leetcode.com/problems/word-break-ii) + + + +## Description + +

Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.

+ +

Note that the same word in the dictionary may be reused multiple times in the segmentation.

+ +

 

+

Example 1:

+ +
+Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
+Output: ["cats and dog","cat sand dog"]
+
+ +

Example 2:

+ +
+Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
+Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
+Explanation: Note that you are allowed to reuse a dictionary word.
+
+ +

Example 3:

+ +
+Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 20
  • +
  • 1 <= wordDict.length <= 1000
  • +
  • 1 <= wordDict[i].length <= 10
  • +
  • s and wordDict[i] consist of only lowercase English letters.
  • +
  • All the strings of wordDict are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0141.Linked List Cycle/README_EN.md b/assets/0100-0199/0141.Linked List Cycle/README_EN.md new file mode 100644 index 00000000..f0231163 --- /dev/null +++ b/assets/0100-0199/0141.Linked List Cycle/README_EN.md @@ -0,0 +1,189 @@ +# [141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) + + + +## Description + +

Given head, the head of a linked list, determine if the linked list has a cycle in it.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

+ +

Return true if there is a cycle in the linked list. Otherwise, return false.

+ +

 

+

Example 1:

+ +
+Input: head = [3,2,0,-4], pos = 1
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
+
+ +

Example 2:

+ +
+Input: head = [1,2], pos = 0
+Output: true
+Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
+
+ +

Example 3:

+ +
+Input: head = [1], pos = -1
+Output: false
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + slow = fast = head + while fast and fast.next: + slow, fast = slow.next, fast.next.next + if slow == fast: + return True + return False +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + return true; + } + } + return false; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode* slow = head; + ListNode* fast = head; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + return true; + } + } + return false; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + let slow = head; + let fast = head; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + return true; + } + } + return false; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func hasCycle(head *ListNode) bool { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + if slow == fast { + return true + } + } + return false +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist.png b/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist.png new file mode 100644 index 00000000..20737422 Binary files /dev/null and b/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist.png differ diff --git a/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist_test2.png b/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist_test2.png new file mode 100644 index 00000000..f8158f13 Binary files /dev/null and b/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist_test2.png differ diff --git a/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist_test3.png b/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist_test3.png new file mode 100644 index 00000000..73bf10ed Binary files /dev/null and b/assets/0100-0199/0141.Linked List Cycle/images/circularlinkedlist_test3.png differ diff --git a/assets/0100-0199/0142.Linked List Cycle II/README_EN.md b/assets/0100-0199/0142.Linked List Cycle II/README_EN.md new file mode 100644 index 00000000..f8aeb156 --- /dev/null +++ b/assets/0100-0199/0142.Linked List Cycle II/README_EN.md @@ -0,0 +1,220 @@ +# [142. Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii) + + + +## Description + +

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

+ +

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

+ +

Notice that you should not modify the linked list.

+ +

 

+

Example 1:

+ +
+Input: head = [3,2,0,-4], pos = 1
+Output: tail connects to node index 1
+Explanation: There is a cycle in the linked list, where tail connects to the second node.
+
+ +

Example 2:

+ +
+Input: head = [1,2], pos = 0
+Output: tail connects to node index 0
+Explanation: There is a cycle in the linked list, where tail connects to the first node.
+
+ +

Example 3:

+ +
+Input: head = [1], pos = -1
+Output: no cycle
+Explanation: There is no cycle in the linked list.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the list is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • pos is -1 or a valid index in the linked-list.
  • +
+ +

 

+

Follow up: Can you solve it using O(1) (i.e. constant) memory?

+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def detectCycle(self, head: ListNode) -> ListNode: + slow = fast = head + has_cycle = False + while not has_cycle and fast and fast.next: + slow, fast = slow.next, fast.next.next + has_cycle = slow == fast + if not has_cycle: + return None + p = head + while p != slow: + p, slow = p.next, slow.next + return p +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode slow = head, fast = head; + boolean hasCycle = false; + while (!hasCycle && fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + hasCycle = slow == fast; + } + if (!hasCycle) { + return null; + } + ListNode p = head; + while (p != slow) { + p = p.next; + slow = slow.next; + } + return p; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + ListNode* slow = head; + ListNode* fast = head; + bool hasCycle = false; + while (!hasCycle && fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + hasCycle = slow == fast; + } + if (!hasCycle) { + return nullptr; + } + ListNode* p = head; + while (p != slow) { + p = p->next; + slow = slow->next; + } + return p; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {ListNode} + */ +var detectCycle = function(head) { + let slow = head; + let fast = head; + let hasCycle = false; + while (!hasCycle && fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + hasCycle = slow == fast; + } + if (!hasCycle) { + return null; + } + let p = head; + while (p != slow) { + p = p.next; + slow = slow.next; + } + return p; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func detectCycle(head *ListNode) *ListNode { + slow, fast := head, head + hasCycle := false + for !hasCycle && fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + hasCycle = slow == fast + } + if !hasCycle { + return nil + } + p := head + for p != slow { + p, slow = p.Next, slow.Next + } + return p +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist.png b/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist.png new file mode 100644 index 00000000..02e16eca Binary files /dev/null and b/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist.png differ diff --git a/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist_test2.png b/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist_test2.png new file mode 100644 index 00000000..52b93946 Binary files /dev/null and b/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist_test2.png differ diff --git a/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist_test3.png b/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist_test3.png new file mode 100644 index 00000000..b991c24b Binary files /dev/null and b/assets/0100-0199/0142.Linked List Cycle II/images/circularlinkedlist_test3.png differ diff --git a/assets/0100-0199/0142.Linked List Cycle II/images/linked-list-cycle-ii.png b/assets/0100-0199/0142.Linked List Cycle II/images/linked-list-cycle-ii.png new file mode 100644 index 00000000..7a7ad3ae Binary files /dev/null and b/assets/0100-0199/0142.Linked List Cycle II/images/linked-list-cycle-ii.png differ diff --git a/assets/0100-0199/0143.Reorder List/README_EN.md b/assets/0100-0199/0143.Reorder List/README_EN.md new file mode 100644 index 00000000..9d09fa9a --- /dev/null +++ b/assets/0100-0199/0143.Reorder List/README_EN.md @@ -0,0 +1,280 @@ +# [143. Reorder List](https://leetcode.com/problems/reorder-list) + + + +## Description + +

You are given the head of a singly linked-list. The list can be represented as:

+ +
+L0 → L1 → … → Ln - 1 → Ln
+
+ +

Reorder the list to be on the following form:

+ +
+L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
+
+ +

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4]
+Output: [1,4,2,3]
+
+ +

Example 2:

+ +
+Input: head = [1,2,3,4,5]
+Output: [1,5,2,4,3]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 5 * 104].
  • +
  • 1 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reorderList(self, head: ListNode) -> None: + """ + Do not return anything, modify head in-place instead. + """ + if head is None or head.next is None: + return + + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + + cur = slow.next + slow.next = None + + pre = None + while cur: + t = cur.next + cur.next = pre + pre, cur = cur, t + cur = head + + while pre: + t = pre.next + pre.next = cur.next + cur.next = pre + cur, pre = pre.next, t +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public void reorderList(ListNode head) { + if (head == null || head.next == null) { + return; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + ListNode cur = slow.next; + slow.next = null; + + ListNode pre = null; + while (cur != null) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + while (pre != null) { + ListNode t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } + } +} +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public void ReorderList(ListNode head) { + if (head == null || head.next == null) + { + return; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + + ListNode cur = slow.next; + slow.next = null; + + ListNode pre = null; + while (cur != null) + { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + while (pre != null) + { + ListNode t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } + } +} +``` + +### **Go** + + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + func reorderList(head *ListNode) { + if head == nil || head.Next == nil { + return + } + slow, fast := head, head.Next + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + + cur := slow.Next + slow.Next = nil + + var pre *ListNode + for cur != nil { + t := cur.Next + cur.Next = pre + pre, cur = cur, t + } + cur = head + + for pre != nil { + t := pre.Next + pre.Next = cur.Next + cur.Next = pre + cur, pre = pre.Next, t + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {void} Do not return anything, modify head in-place instead. + */ +var reorderList = function(head) { + if (!head || !head.next) { + return; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + let cur = slow.next; + slow.next = null; + + let pre = null; + while (cur) { + const t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + while (pre) { + const t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0143.Reorder List/images/reorder1linked-list.jpg b/assets/0100-0199/0143.Reorder List/images/reorder1linked-list.jpg new file mode 100644 index 00000000..1b736c55 Binary files /dev/null and b/assets/0100-0199/0143.Reorder List/images/reorder1linked-list.jpg differ diff --git a/assets/0100-0199/0143.Reorder List/images/reorder2-linked-list.jpg b/assets/0100-0199/0143.Reorder List/images/reorder2-linked-list.jpg new file mode 100644 index 00000000..e6ad6674 Binary files /dev/null and b/assets/0100-0199/0143.Reorder List/images/reorder2-linked-list.jpg differ diff --git a/assets/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md b/assets/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md new file mode 100644 index 00000000..f0131d48 --- /dev/null +++ b/assets/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md @@ -0,0 +1,229 @@ +# [144. Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal) + + + +## Description + +

Given the root of a binary tree, return the preorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,2,3]
+Output: [1,2,3]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
+Input: root = [1,2]
+Output: [1,2]
+
+ +

Example 5:

+ +
+Input: root = [1,null,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+ + +## Solutions + + + +### **Python3** + +Recursive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + def preorder(root): + if root: + res.append(root.val) + preorder(root.left) + preorder(root.right) + res = [] + preorder(root) + return res +``` + +Non-recursive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + if root is None: + return [] + res = [] + s = [root] + while s: + node = s.pop() + res.append(node.val) + if node.right: + s.append(node.right) + if node.left: + s.append(node.left) + return res +``` + +### **Java** + +Recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private List res; + + public List preorderTraversal(TreeNode root) { + res = new ArrayList<>(); + preorder(root); + return res; + } + + private void preorder(TreeNode root) { + if (root != null) { + res.add(root.val); + preorder(root.left); + preorder(root.right); + } + } +} +``` + +Non-recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + List res = new ArrayList<>(); + Deque s = new ArrayDeque<>(); + s.push(root); + while (!s.isEmpty()) { + TreeNode node = s.pop(); + res.add(node.val); + if (node.right != null) { + s.push(node.right); + } + if (node.left != null) { + s.push(node.left); + } + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + if (root == nullptr) return res; + stack s; + s.push(root); + while (!s.empty()) { + TreeNode *node = s.top(); + s.pop(); + res.push_back(node->val); + if (node->right) s.push(node->right); + if (node->left) s.push(node->left); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_1.jpg b/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_1.jpg new file mode 100644 index 00000000..98c26f26 Binary files /dev/null and b/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_1.jpg differ diff --git a/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_4.jpg b/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_4.jpg new file mode 100644 index 00000000..667c51b6 Binary files /dev/null and b/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_4.jpg differ diff --git a/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_5.jpg b/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_5.jpg new file mode 100644 index 00000000..abd71d00 Binary files /dev/null and b/assets/0100-0199/0144.Binary Tree Preorder Traversal/images/inorder_5.jpg differ diff --git a/assets/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md b/assets/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md new file mode 100644 index 00000000..115503e7 --- /dev/null +++ b/assets/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md @@ -0,0 +1,202 @@ +# [145. Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal) + + + +## Description + +

Given the root of a binary tree, return the postorder traversal of its nodes' values.

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,2,3]
+Output: [3,2,1]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
+Input: root = [1,2]
+Output: [2,1]
+
+ +

Example 5:

+ +
+Input: root = [1,null,2]
+Output: [2,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +

 

+ +

Follow up:

+ +

Recursive solution is trivial, could you do it iteratively?

+ +

 

+ + +## Solutions + + + +### **Python3** + +Recursive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: TreeNode) -> List[int]: + def postorder(root): + if root: + postorder(root.left) + postorder(root.right) + res.append(root.val) + res = [] + postorder(root) + return res +``` + +Non-recursive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: TreeNode) -> List[int]: + if not root: + return [] + s1 = [root] + s2 = [] + while s1: + node = s1.pop() + s2.append(node.val) + if node.left: + s1.append(node.left) + if node.right: + s1.append(node.right) + return s2[::-1] +``` + +### **Java** + +Recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private List res; + + public List postorderTraversal(TreeNode root) { + res = new ArrayList<>(); + postorder(root); + return res; + } + + private void postorder(TreeNode root) { + if (root != null) { + postorder(root.left); + postorder(root.right); + res.add(root.val); + } + } +} +``` + +Non-recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Deque s1 = new ArrayDeque<>(); + List s2 = new ArrayList<>(); + s1.push(root); + while (!s1.isEmpty()) { + TreeNode node = s1.pop(); + s2.add(node.val); + if (node.left != null) { + s1.push(node.left); + } + if (node.right != null) { + s1.push(node.right); + } + } + Collections.reverse(s2); + return s2; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre1.jpg b/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre1.jpg new file mode 100644 index 00000000..da04d2a7 Binary files /dev/null and b/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre1.jpg differ diff --git a/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre2.jpg b/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre2.jpg new file mode 100644 index 00000000..834747e2 Binary files /dev/null and b/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre2.jpg differ diff --git a/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre3.jpg b/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre3.jpg new file mode 100644 index 00000000..b585a51f Binary files /dev/null and b/assets/0100-0199/0145.Binary Tree Postorder Traversal/images/pre3.jpg differ diff --git a/assets/0100-0199/0146.Lru Cache/README_EN.md b/assets/0100-0199/0146.Lru Cache/README_EN.md new file mode 100644 index 00000000..bff959ae --- /dev/null +++ b/assets/0100-0199/0146.Lru Cache/README_EN.md @@ -0,0 +1,224 @@ +# [146. LRU Cache](https://leetcode.com/problems/lru-cache) + + + +## Description + +

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

+ +

Implement the LRUCache class:

+ +
    +
  • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  • +
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • +
  • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
  • +
+ +

Follow up:
+Could you do get and put in O(1) time complexity?

+ +

 

+

Example 1:

+ +
+Input
+["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
+[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
+Output
+[null, null, null, 1, null, -1, null, -1, 3, 4]
+
+Explanation
+LRUCache lRUCache = new LRUCache(2);
+lRUCache.put(1, 1); // cache is {1=1}
+lRUCache.put(2, 2); // cache is {1=1, 2=2}
+lRUCache.get(1);    // return 1
+lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
+lRUCache.get(2);    // returns -1 (not found)
+lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
+lRUCache.get(1);    // return -1 (not found)
+lRUCache.get(3);    // return 3
+lRUCache.get(4);    // return 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= capacity <= 3000
  • +
  • 0 <= key <= 3000
  • +
  • 0 <= value <= 104
  • +
  • At most 3 * 104 calls will be made to get and put.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Node: + def __init__(self, key=0, value=0): + self.key = key + self.value = value + self.prev = None + self.next = None + +class LRUCache: + + def __init__(self, capacity: int): + self.cache = {} + self.head = Node() + self.tail = Node() + self.capacity = capacity + self.size = 0 + self.head.next = self.tail + self.tail.prev = self.head + + def get(self, key: int) -> int: + if key not in self.cache: + return -1 + node = self.cache[key] + self.move_to_head(node) + return node.value + + def put(self, key: int, value: int) -> None: + if key in self.cache: + node = self.cache[key] + node.value = value + self.move_to_head(node) + else: + node = Node(key, value) + self.cache[key] = node + self.add_to_head(node) + self.size += 1 + if self.size > self.capacity: + node = self.remove_tail() + self.cache.pop(node.key) + self.size -= 1 + + def move_to_head(self, node): + self.remove_node(node) + self.add_to_head(node) + + def remove_node(self, node): + node.prev.next = node.next + node.next.prev = node.prev + + def add_to_head(self, node): + node.next = self.head.next + self.head.next.prev = node + self.head.next = node + node.prev = self.head + + def remove_tail(self): + node = self.tail.prev + self.remove_node(node) + return node + + +# Your LRUCache object will be instantiated and called as such: +# obj = LRUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) +``` + +### **Java** + +```java +class LRUCache { + class Node { + int key; + int value; + Node prev; + Node next; + Node() { + + } + Node(int key, int value) { + this.key = key; + this.value = value; + } + } + + private Map cache; + private Node head; + private Node tail; + private int capacity; + private int size; + + public LRUCache(int capacity) { + cache = new HashMap<>(); + this.capacity = capacity; + head = new Node(); + tail = new Node(); + head.next = tail; + tail.prev = head; + } + + public int get(int key) { + if (!cache.containsKey(key)) { + return -1; + } + Node node = cache.get(key); + moveToHead(node); + return node.value; + } + + public void put(int key, int value) { + if (cache.containsKey(key)) { + Node node = cache.get(key); + node.value = value; + moveToHead(node); + } else { + Node node = new Node(key, value); + cache.put(key, node); + addToHead(node); + ++size; + if (size > capacity) { + node = removeTail(); + cache.remove(node.key); + --size; + } + } + } + + private void moveToHead(Node node) { + removeNode(node); + addToHead(node); + } + + private void removeNode(Node node) { + node.prev.next = node.next; + node.next.prev = node.prev; + } + + private void addToHead(Node node) { + node.next = head.next; + head.next.prev = node; + head.next = node; + node.prev = head; + } + + private Node removeTail() { + Node node = tail.prev; + removeNode(node); + return node; + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0147.Insertion Sort List/README_EN.md b/assets/0100-0199/0147.Insertion Sort List/README_EN.md new file mode 100644 index 00000000..c82bfe2e --- /dev/null +++ b/assets/0100-0199/0147.Insertion Sort List/README_EN.md @@ -0,0 +1,160 @@ +# [147. Insertion Sort List](https://leetcode.com/problems/insertion-sort-list) + + + +## Description + +

Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.

+ +

The steps of the insertion sort algorithm:

+ +
    +
  1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
  2. +
  3. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
  4. +
  5. It repeats until no input elements remain.
  6. +
+ +

The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.

+ +

 

+

Example 1:

+ +
+Input: head = [4,2,1,3]
+Output: [1,2,3,4]
+
+ +

Example 2:

+ +
+Input: head = [-1,5,3,4,0]
+Output: [-1,0,3,4,5]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 5000].
  • +
  • -5000 <= Node.val <= 5000
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def insertionSortList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + dummy = ListNode(head.val, head) + pre, cur = dummy, head + while cur: + if pre.val <= cur.val: + pre, cur = cur, cur.next + continue + p = dummy + while p.next.val <= cur.val: + p = p.next + t = cur.next + cur.next = p.next + p.next = cur + pre.next = t + cur = t + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode insertionSortList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode dummy = new ListNode(head.val, head); + ListNode pre = dummy, cur = head; + while (cur != null) { + if (pre.val <= cur.val) { + pre = cur; + cur = cur.next; + continue; + } + ListNode p = dummy; + while (p.next.val <= cur.val) { + p = p.next; + } + ListNode t = cur.next; + cur.next = p.next; + p.next = cur; + pre.next = t; + cur = t; + } + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ + var insertionSortList = function(head) { + if (head == null || head.next == null) return head; + let dummy = new ListNode(head.val, head); + let prev = dummy, cur = head; + while (cur != null) { + if (prev.val <= cur.val) { + prev = cur; + cur = cur.next; + continue; + } + let p = dummy; + while (p.next.val <= cur.val) { + p = p.next; + } + let t = cur.next; + cur.next = p.next; + p.next = cur; + prev.next = t; + cur = t; + } + return dummy.next; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0147.Insertion Sort List/images/Insertion-sort-example-300px.gif b/assets/0100-0199/0147.Insertion Sort List/images/Insertion-sort-example-300px.gif new file mode 100644 index 00000000..96c1b12d Binary files /dev/null and b/assets/0100-0199/0147.Insertion Sort List/images/Insertion-sort-example-300px.gif differ diff --git a/assets/0100-0199/0147.Insertion Sort List/images/sort1linked-list.jpg b/assets/0100-0199/0147.Insertion Sort List/images/sort1linked-list.jpg new file mode 100644 index 00000000..ed217f88 Binary files /dev/null and b/assets/0100-0199/0147.Insertion Sort List/images/sort1linked-list.jpg differ diff --git a/assets/0100-0199/0147.Insertion Sort List/images/sort2linked-list.jpg b/assets/0100-0199/0147.Insertion Sort List/images/sort2linked-list.jpg new file mode 100644 index 00000000..7ecf17d0 Binary files /dev/null and b/assets/0100-0199/0147.Insertion Sort List/images/sort2linked-list.jpg differ diff --git a/assets/0100-0199/0148.Sort List/README_EN.md b/assets/0100-0199/0148.Sort List/README_EN.md new file mode 100644 index 00000000..e2824697 --- /dev/null +++ b/assets/0100-0199/0148.Sort List/README_EN.md @@ -0,0 +1,271 @@ +# [148. Sort List](https://leetcode.com/problems/sort-list) + + + +## Description + +

Given the head of a linked list, return the list after sorting it in ascending order.

+ +

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

+ +

 

+

Example 1:

+ +
+Input: head = [4,2,1,3]
+Output: [1,2,3,4]
+
+ +

Example 2:

+ +
+Input: head = [-1,5,3,4,0]
+Output: [-1,0,3,4,5]
+
+ +

Example 3:

+ +
+Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 5 * 104].
  • +
  • -105 <= Node.val <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def sortList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + t = slow.next + slow.next = None + l1, l2 = self.sortList(head), self.sortList(t) + dummy = ListNode() + cur = dummy + while l1 and l2: + if l1.val <= l2.val: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + cur.next = l1 or l2 + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode t = slow.next; + slow.next = null; + ListNode l1 = sortList(head); + ListNode l2 = sortList(t); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var sortList = function(head) { + if (!head || !head.next) { + return head; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + let t = slow.next; + slow.next = null; + let l1 = sortList(head); + let l2 = sortList(t); + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode SortList(ListNode head) { + if (head == null || head.next == null) + { + return head; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + ListNode t = slow.next; + slow.next = null; + ListNode l1 = SortList(head); + ListNode l2 = SortList(t); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) + { + if (l1.val <= l2.val) + { + cur.next = l1; + l1 = l1.next; + } + else + { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function sortList(head: ListNode | null): ListNode | null { + if (head == null || head.next == null) return head; + // 快慢指针定位中点 + let slow: ListNode = head, fast: ListNode = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + // 归并排序 + let mid: ListNode = slow.next; + slow.next = null; + let l1: ListNode = sortList(head); + let l2: ListNode = sortList(mid); + let dummy: ListNode = new ListNode(); + let cur: ListNode = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0148.Sort List/images/sort_list_1.jpg b/assets/0100-0199/0148.Sort List/images/sort_list_1.jpg new file mode 100644 index 00000000..f37fecb3 Binary files /dev/null and b/assets/0100-0199/0148.Sort List/images/sort_list_1.jpg differ diff --git a/assets/0100-0199/0148.Sort List/images/sort_list_2.jpg b/assets/0100-0199/0148.Sort List/images/sort_list_2.jpg new file mode 100644 index 00000000..8d3fa345 Binary files /dev/null and b/assets/0100-0199/0148.Sort List/images/sort_list_2.jpg differ diff --git a/assets/0100-0199/0149.Max Points on a Line/README_EN.md b/assets/0100-0199/0149.Max Points on a Line/README_EN.md new file mode 100644 index 00000000..c3de434d --- /dev/null +++ b/assets/0100-0199/0149.Max Points on a Line/README_EN.md @@ -0,0 +1,156 @@ +# [149. Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line) + + + +## Description + +

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

+ +

 

+

Example 1:

+ +
+Input: points = [[1,1],[2,2],[3,3]]
+Output: 3
+
+ +

Example 2:

+ +
+Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= points.length <= 300
  • +
  • points[i].length == 2
  • +
  • -104 <= xi, yi <= 104
  • +
  • All the points are unique.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + def gcd(a, b) -> int: + return a if b == 0 else gcd(b, a % b) + + n = len(points) + if n < 3: + return n + res = 0 + for i in range(n - 1): + counter = collections.Counter() + t_max = duplicate = 0 + for j in range(i + 1, n): + delta_x = points[i][0] - points[j][0] + delta_y = points[i][1] - points[j][1] + if delta_x == 0 and delta_y == 0: + duplicate += 1 + continue + g = gcd(delta_x, delta_y) + d_x = delta_x // g + d_y = delta_y // g + key = f'{d_x}.{d_y}' + counter[key] += 1 + t_max = max(t_max, counter[key]) + res = max(res, t_max + duplicate + 1) + return res +``` + +### **Java** + +```java +class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + if (n < 3) { + return n; + } + int res = 0; + for (int i = 0; i < n - 1; ++i) { + Map kCounter = new HashMap<>(); + int max = 0; + int duplicate = 0; + for (int j = i + 1; j < n; ++j) { + int deltaX = points[i][0] - points[j][0]; + int deltaY = points[i][1] - points[j][1]; + if (deltaX == 0 && deltaY == 0) { + ++duplicate; + continue; + } + int gcd = gcd(deltaX, deltaY); + int dX = deltaX / gcd; + int dY = deltaY / gcd; + String key = dX + "." + dY; + kCounter.put(key, kCounter.getOrDefault(key, 0) + 1); + max = Math.max(max, kCounter.get(key)); + } + res = Math.max(res, max + duplicate + 1); + } + return res; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +### **Go** + +```go +func maxPoints(points [][]int) int { + type pair struct { + first int + second int + } + n := len(points) + if n <= 2 { + return n + } + ans := 0 + for i := 0; i < n-1; i++ { + freq := make(map[pair]int) + for j := i + 1; j < n; j++ { + x1, y1, x2, y2 := points[i][0], points[i][1], points[j][0], points[j][1] + dx, dy := x2-x1, y2-y1 + g := gcd(dx, dy) + p := pair{dx / g, dy / g} + freq[p]++ + ans = max(ans, freq[p]+1) + } + } + return ans +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0149.Max Points on a Line/images/plane1.jpg b/assets/0100-0199/0149.Max Points on a Line/images/plane1.jpg new file mode 100644 index 00000000..3f2f46eb Binary files /dev/null and b/assets/0100-0199/0149.Max Points on a Line/images/plane1.jpg differ diff --git a/assets/0100-0199/0149.Max Points on a Line/images/plane2.jpg b/assets/0100-0199/0149.Max Points on a Line/images/plane2.jpg new file mode 100644 index 00000000..6f3d4a74 Binary files /dev/null and b/assets/0100-0199/0149.Max Points on a Line/images/plane2.jpg differ diff --git a/assets/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md b/assets/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md new file mode 100644 index 00000000..8b7f2174 --- /dev/null +++ b/assets/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md @@ -0,0 +1,125 @@ +# [150. Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation) + + + +## Description + +

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

+ +

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

+ +

Note that division between two integers should truncate toward zero.

+ +

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

+ +

 

+

Example 1:

+ +
+Input: tokens = ["2","1","+","3","*"]
+Output: 9
+Explanation: ((2 + 1) * 3) = 9
+
+ +

Example 2:

+ +
+Input: tokens = ["4","13","5","/","+"]
+Output: 6
+Explanation: (4 + (13 / 5)) = 6
+
+ +

Example 3:

+ +
+Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
+Output: 22
+Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
+= ((10 * (6 / (12 * -11))) + 17) + 5
+= ((10 * (6 / -132)) + 17) + 5
+= ((10 * 0) + 17) + 5
+= (0 + 17) + 5
+= 17 + 5
+= 22
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= tokens.length <= 104
  • +
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
  • +
+ + +## Solutions + + + +### **Python3** + +```python +import operator + +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + opt = { + "+": operator.add, + "-": operator.sub, + "*": operator.mul, + "/": operator.truediv + } + s = [] + for token in tokens: + if token in opt: + s.append(int(opt[token](s.pop(-2), s.pop(-1)))) + else: + s.append(int(token)) + return s[0] +``` + +### **Java** + +```java +class Solution { + public int evalRPN(String[] tokens) { + Deque s = new ArrayDeque<>(); + int left, right; + for (String token : tokens) { + switch(token) { + case "+": + right = s.pop(); + left = s.pop(); + s.push(left + right); + break; + case "-": + right = s.pop(); + left = s.pop(); + s.push(left - right); + break; + case "*": + right = s.pop(); + left = s.pop(); + s.push(left * right); + break; + case "/": + right = s.pop(); + left = s.pop(); + s.push(left / right); + break; + default: + s.push(Integer.valueOf(token)); + } + } + return s.pop(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0151.Reverse Words in a String/README_EN.md b/assets/0100-0199/0151.Reverse Words in a String/README_EN.md new file mode 100644 index 00000000..a206dd72 --- /dev/null +++ b/assets/0100-0199/0151.Reverse Words in a String/README_EN.md @@ -0,0 +1,117 @@ +# [151. Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string) + + + +## Description + +

Given an input string s, reverse the order of the words.

+ +

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

+ +

Return a string of the words in reverse order concatenated by a single space.

+ +

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

+ +

 

+

Example 1:

+ +
+Input: s = "the sky is blue"
+Output: "blue is sky the"
+
+ +

Example 2:

+ +
+Input: s = "  hello world  "
+Output: "world hello"
+Explanation: Your reversed string should not contain leading or trailing spaces.
+
+ +

Example 3:

+ +
+Input: s = "a good   example"
+Output: "example good a"
+Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
+
+ +

Example 4:

+ +
+Input: s = "  Bob    Loves  Alice   "
+Output: "Alice Loves Bob"
+
+ +

Example 5:

+ +
+Input: s = "Alice does not even like bob"
+Output: "bob like even not does Alice"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • +
  • There is at least one word in s.
  • +
+ +

 

+

Follow up: Could you solve it in-place with O(1) extra space?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def reverseWords(self, s: str) -> str: + words = s.strip().split() + return ' '.join(words[::-1]) +``` + +### **Java** + +```java +class Solution { + public String reverseWords(String s) { + List words = Arrays.asList(s.trim().split("\\s+")); + Collections.reverse(words); + return String.join(" ", words); + } +} +``` + +### **C#** + +```cs +public class Solution { + public string ReverseWords(string s) { + return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + } +} +``` + +### **TypeScript** + +```ts +function reverseWords(s: string): string { + let words: string[] = s.trim().split(/\s+/g); + words.reverse(); + return words.join(' '); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0152.Maximum Product Subarray/README_EN.md b/assets/0100-0199/0152.Maximum Product Subarray/README_EN.md new file mode 100644 index 00000000..e263ef0b --- /dev/null +++ b/assets/0100-0199/0152.Maximum Product Subarray/README_EN.md @@ -0,0 +1,163 @@ +# [152. Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray) + + + +## Description + +

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

+ +

It is guaranteed that the answer will fit in a 32-bit integer.

+ +

A subarray is a contiguous subsequence of the array.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,3,-2,4]
+Output: 6
+Explanation: [2,3] has the largest product 6.
+
+ +

Example 2:

+ +
+Input: nums = [-2,0,-1]
+Output: 0
+Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -10 <= nums[i] <= 10
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + maxf = minf = res = nums[0] + for num in nums[1:]: + m, n = maxf, minf + maxf = max(num, m * num, n * num) + minf = min(num, m * num, n * num) + res = max(res, maxf) + return res +``` + +### **Java** + +```java +class Solution { + public int maxProduct(int[] nums) { + int maxf = nums[0], minf = nums[0], res = nums[0]; + for (int i = 1; i < nums.length; ++i) { + int m = maxf, n = minf; + maxf = Math.max(nums[i], Math.max(m * nums[i], n * nums[i])); + minf = Math.min(nums[i], Math.min(m * nums[i], n * nums[i])); + res = Math.max(res, maxf); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function maxProduct(nums: number[]): number { + let n = nums.length; + let preMax = nums[0], preMin = nums[0], ans = nums[0]; + for (let i = 1; i < n; ++i) { + let cur = nums[i]; + let x = preMax, y = preMin; + preMax = Math.max(x * cur, y * cur, cur); + preMin = Math.min(x * cur, y * cur, cur); + ans = Math.max(preMax, ans); + } + return ans; +}; +``` + +### **C#** + +```cs +public class Solution { + public int MaxProduct(int[] nums) { + int maxf = nums[0], minf = nums[0], res = nums[0]; + for (int i = 1; i < nums.Length; ++i) + { + int m = maxf, n = minf; + maxf = Math.Max(nums[i], Math.Max(nums[i] * m, nums[i] * n)); + minf = Math.Min(nums[i], Math.Min(nums[i] * m, nums[i] * n)); + res = Math.Max(res, maxf); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProduct(vector& nums) { + int maxf = nums[0], minf = nums[0], res = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int m = maxf, n = minf; + maxf = max(nums[i], max(nums[i] * m, nums[i] * n)); + minf = min(nums[i], min(nums[i] * m, nums[i] * n)); + res = max(res, maxf); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxProduct(nums []int) int { + maxf, minf, res := nums[0], nums[0], nums[0] + for i := 1; i < len(nums); i++ { + m, n := maxf, minf + maxf = max(nums[i], max(nums[i]*m, nums[i]*n)) + minf = min(nums[i], min(nums[i]*m, nums[i]*n)) + res = max(res, maxf) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md b/assets/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md new file mode 100644 index 00000000..c7abab99 --- /dev/null +++ b/assets/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md @@ -0,0 +1,157 @@ +# [153. Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array) + + + +## Description + +

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

+ +
    +
  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • +
  • [0,1,2,4,5,6,7] if it was rotated 7 times.
  • +
+ +

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

+ +

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,4,5,1,2]
+Output: 1
+Explanation: The original array was [1,2,3,4,5] rotated 3 times.
+
+ +

Example 2:

+ +
+Input: nums = [4,5,6,7,0,1,2]
+Output: 0
+Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
+
+ +

Example 3:

+ +
+Input: nums = [11,13,15,17]
+Output: 11
+Explanation: The original array was [11,13,15,17] and it was rotated 4 times. 
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5000
  • +
  • -5000 <= nums[i] <= 5000
  • +
  • All the integers of nums are unique.
  • +
  • nums is sorted and rotated between 1 and n times.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findMin(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + if nums[l] < nums[r]: + return nums[0] + while l < r: + m = (l + r) >> 1 + if nums[m] > nums[r]: + l = m + 1 + else: + r = m + return nums[l] +``` + +### **Java** + +```java +class Solution { + public int findMin(int[] nums) { + int l = 0, r = nums.length - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + int m = (l + r) >>> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; + } + return nums[l]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findMin(vector& nums) { + int l = 0, r = nums.size() - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + int m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; + } + return nums[l]; + } +}; +``` + +### **Go** + +```go +func findMin(nums []int) int { + l, r := 0, len(nums) - 1 + if nums[l] < nums[r] { + return nums[0] + } + for l < r { + m := (l + r) >> 1 + if nums[m] > nums[r] { + l = m + 1 + } else { + r = m + } + } + return nums[l] +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let l = 0, + r = nums.length - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; + } + return nums[l]; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md b/assets/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md new file mode 100644 index 00000000..df828150 --- /dev/null +++ b/assets/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md @@ -0,0 +1,121 @@ +# [154. Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii) + + + +## Description + +

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:

+ +
    +
  • [4,5,6,7,0,1,4] if it was rotated 4 times.
  • +
  • [0,1,4,4,5,6,7] if it was rotated 7 times.
  • +
+ +

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

+ +

Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.

+ +

 

+

Example 1:

+
Input: nums = [1,3,5]
+Output: 1
+

Example 2:

+
Input: nums = [2,2,2,0,1]
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5000
  • +
  • -5000 <= nums[i] <= 5000
  • +
  • nums is sorted and rotated between 1 and n times.
  • +
+ +

 

+Follow up: This is the same as Find Minimum in Rotated Sorted Array but with duplicates. Would allow duplicates affect the run-time complexity? How and why? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findMin(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + while l < r: + m = (l + r) >> 1 + if nums[m] > nums[r]: + l = m + 1 + elif nums[m] < nums[r]: + r = m + else: + r -= 1 + return nums[l] +``` + +### **Java** + +```java +class Solution { + public int findMin(int[] nums) { + int l = 0, r = nums.length - 1; + while (l < r) { + int m = (l + r) >>> 1; + if (nums[m] > nums[r]) l = m + 1; + else if (nums[m] < nums[r]) r = m; + else --r; + } + return nums[l]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findMin(vector& nums) { + int l = 0, r = nums.size() - 1; + while (l < r) { + int m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else if (nums[m] < nums[r]) r = m; + else --r; + } + return nums[l]; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let l = 0, + r = nums.length - 1; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else if (nums[m] < nums[r]) r = m; + else --r; + } + return nums[l]; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0155.Min Stack/README_EN.md b/assets/0100-0199/0155.Min Stack/README_EN.md new file mode 100644 index 00000000..5542d7da --- /dev/null +++ b/assets/0100-0199/0155.Min Stack/README_EN.md @@ -0,0 +1,233 @@ +# [155. Min Stack](https://leetcode.com/problems/min-stack) + + + +## Description + +

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

+ +

Implement the MinStack class:

+ +
    +
  • MinStack() initializes the stack object.
  • +
  • void push(val) pushes the element val onto the stack.
  • +
  • void pop() removes the element on the top of the stack.
  • +
  • int top() gets the top element of the stack.
  • +
  • int getMin() retrieves the minimum element in the stack.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MinStack","push","push","push","getMin","pop","top","getMin"]
+[[],[-2],[0],[-3],[],[],[],[]]
+
+Output
+[null,null,null,null,-3,null,0,-2]
+
+Explanation
+MinStack minStack = new MinStack();
+minStack.push(-2);
+minStack.push(0);
+minStack.push(-3);
+minStack.getMin(); // return -3
+minStack.pop();
+minStack.top();    // return 0
+minStack.getMin(); // return -2
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= val <= 231 - 1
  • +
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • +
  • At most 3 * 104 calls will be made to push, pop, top, and getMin.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class MinStack: + + def __init__(self): + """ + initialize your data structure here. + """ + self.s = [] + self.mins = [float('inf')] + + def push(self, val: int) -> None: + self.s.append(val) + self.mins.append(min(self.mins[-1], val)) + + def pop(self) -> None: + self.s.pop() + self.mins.pop() + + def top(self) -> int: + return self.s[-1] + + def getMin(self) -> int: + return self.mins[-1] + + +# Your MinStack object will be instantiated and called as such: +# obj = MinStack() +# obj.push(val) +# obj.pop() +# param_3 = obj.top() +# param_4 = obj.getMin() +``` + +### **Java** + +```java +class MinStack { + private Deque s; + private Deque mins; + + /** initialize your data structure here. */ + public MinStack() { + s = new ArrayDeque<>(); + mins = new ArrayDeque<>(); + mins.push(Integer.MAX_VALUE); + } + + public void push(int val) { + s.push(val); + mins.push(Math.min(mins.peek(), val)); + } + + public void pop() { + s.pop(); + mins.pop(); + } + + public int top() { + return s.peek(); + } + + public int getMin() { + return mins.peek(); + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack obj = new MinStack(); + * obj.push(val); + * obj.pop(); + * int param_3 = obj.top(); + * int param_4 = obj.getMin(); + */ +``` + +### **C++** + +```cpp +class MinStack { +private: + stack s; + stack mins; + +public: + /** initialize your data structure here. */ + MinStack() { + mins.push(INT_MAX); + } + + void push(int val) { + s.push(val); + mins.push(min(mins.top(), val)); + } + + void pop() { + s.pop(); + mins.pop(); + } + + int top() { + return s.top(); + } + + int getMin() { + return mins.top(); + } +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(val); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ +``` + +### **JavaScript** + +```js +/** + * initialize your data structure here. + */ +var MinStack = function() { + this.s = []; + this.mins = [Infinity]; +}; + +/** + * @param {number} val + * @return {void} + */ +MinStack.prototype.push = function(val) { + this.s.push(val); + this.mins.push(Math.min(this.mins[this.mins.length - 1], val)); +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function() { + this.s.pop(); + this.mins.pop(); +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function() { + return this.s[this.s.length - 1]; +}; + +/** + * @return {number} + */ +MinStack.prototype.getMin = function() { + return this.mins[this.mins.length - 1]; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0156.Binary Tree Upside Down/README_EN.md b/assets/0100-0199/0156.Binary Tree Upside Down/README_EN.md new file mode 100644 index 00000000..56da20fc --- /dev/null +++ b/assets/0100-0199/0156.Binary Tree Upside Down/README_EN.md @@ -0,0 +1,75 @@ +# [156. Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down) + + + +## Description + +

Given the root of a binary tree, turn the tree upside down and return the new root.

+ +

You can turn a binary tree upside down with the following steps:

+ +
    +
  1. The original left child becomes the new root.
  2. +
  3. The original root becomes the new right child.
  4. +
  5. The original right child becomes the new left child.
  6. +
+ +

+ +

The mentioned steps are done level by level, it is guaranteed that every node in the given tree has either 0 or 2 children.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,4,5]
+Output: [4,5,2,null,null,3,1]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree will be in the range [0, 10].
  • +
  • 1 <= Node.val <= 10
  • +
  • Every node has either 0 or 2 children.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0156.Binary Tree Upside Down/images/main.jpg b/assets/0100-0199/0156.Binary Tree Upside Down/images/main.jpg new file mode 100644 index 00000000..c1c97fb4 Binary files /dev/null and b/assets/0100-0199/0156.Binary Tree Upside Down/images/main.jpg differ diff --git a/assets/0100-0199/0156.Binary Tree Upside Down/images/updown.jpg b/assets/0100-0199/0156.Binary Tree Upside Down/images/updown.jpg new file mode 100644 index 00000000..ed9f7eb6 Binary files /dev/null and b/assets/0100-0199/0156.Binary Tree Upside Down/images/updown.jpg differ diff --git a/assets/0100-0199/0157.Read N Characters Given Read4/README_EN.md b/assets/0100-0199/0157.Read N Characters Given Read4/README_EN.md new file mode 100644 index 00000000..0f2a1ea3 --- /dev/null +++ b/assets/0100-0199/0157.Read N Characters Given Read4/README_EN.md @@ -0,0 +1,127 @@ +# [157. Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4) + + + +## Description + +

Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters.

+ +

Method read4:

+ +

The API read4 reads four consecutive characters from file, then writes those characters into the buffer array buf4.

+ +

The return value is the number of actual characters read.

+ +

Note that read4() has its own file pointer, much like FILE *fp in C.

+ +

Definition of read4:

+ +
+    Parameter:  char[] buf4
+    Returns:    int
+
+buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].
+
+ +

Below is a high-level example of how read4 works:

+ +
+File file("abcde"); // File is "abcde", initially file pointer (fp) points to 'a'
+char[] buf4 = new char[4]; // Create buffer with enough space to store characters
+read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
+read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
+read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file
+
+ +

 

+ +

Method read:

+ +

By using the read4 method, implement the method read that reads n characters from file and store it in the buffer array buf. Consider that you cannot manipulate file directly.

+ +

The return value is the number of actual characters read.

+ +

Definition of read:

+ +
+    Parameters:	char[] buf, int n
+    Returns:	int
+
+buf[] is a destination, not a source. You will need to write the results to buf[].
+
+ +

Note:

+ +
    +
  • Consider that you cannot manipulate the file directly. The file is only accessible for read4 but not for read.
  • +
  • The read function will only be called once for each test case.
  • +
  • You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.
  • +
+ +

 

+

Example 1:

+ +
+Input: file = "abc", n = 4
+Output: 3
+Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
+Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to.
+
+ +

Example 2:

+ +
+Input: file = "abcde", n = 5
+Output: 5
+Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5.
+
+ +

Example 3:

+ +
+Input: file = "abcdABCD1234", n = 12
+Output: 12
+Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12.
+
+ +

Example 4:

+ +
+Input: file = "leetcode", n = 5
+Output: 5
+Explanation: After calling your read method, buf should contain "leetc". We read a total of 5 characters from the file, so return 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= file.length <= 500
  • +
  • file consist of English letters and digits.
  • +
  • 1 <= n <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0157.Read N Characters Given Read4/images/157_example.png b/assets/0100-0199/0157.Read N Characters Given Read4/images/157_example.png new file mode 100644 index 00000000..e30c0c72 Binary files /dev/null and b/assets/0100-0199/0157.Read N Characters Given Read4/images/157_example.png differ diff --git a/assets/0100-0199/0158.Read N Characters Given Read4 II - Call multiple times/README_EN.md b/assets/0100-0199/0158.Read N Characters Given Read4 II - Call multiple times/README_EN.md new file mode 100644 index 00000000..3663061e --- /dev/null +++ b/assets/0100-0199/0158.Read N Characters Given Read4 II - Call multiple times/README_EN.md @@ -0,0 +1,123 @@ +# [158. Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times) + + + +## Description + +

Given a file and assume that you can only read the file using a given method read4, implement a method read to read n characters. Your method read may be called multiple times.

+ +

Method read4:

+ +

The API read4 reads four consecutive characters from file, then writes those characters into the buffer array buf4.

+ +

The return value is the number of actual characters read.

+ +

Note that read4() has its own file pointer, much like FILE *fp in C.

+ +

Definition of read4:

+ +
+    Parameter:  char[] buf4
+    Returns:    int
+
+buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].
+
+ +

Below is a high-level example of how read4 works:

+ +
+File file("abcde"); // File is "abcde", initially file pointer (fp) points to 'a'
+char[] buf4 = new char[4]; // Create buffer with enough space to store characters
+read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
+read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
+read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file
+
+ +

 

+ +

Method read:

+ +

By using the read4 method, implement the method read that reads n characters from file and store it in the buffer array buf. Consider that you cannot manipulate file directly.

+ +

The return value is the number of actual characters read.

+ +

Definition of read:

+ +
+    Parameters:	char[] buf, int n
+    Returns:	int
+
+buf[] is a destination, not a source. You will need to write the results to buf[].
+
+ +

Note:

+ +
    +
  • Consider that you cannot manipulate the file directly. The file is only accessible for read4 but not for read.
  • +
  • The read function may be called multiple times.
  • +
  • Please remember to RESET your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see here for more details.
  • +
  • You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.
  • +
  • It is guaranteed that in a given test case the same buffer buf is called by read.
  • +
+ +

 

+

Example 1:

+ +
+Input: file = "abc", queries = [1,2,1]
+Output: [1,2,0]
+Explanation: The test case represents the following scenario:
+File file("abc");
+Solution sol;
+sol.read(buf, 1); // After calling your read method, buf should contain "a". We read a total of 1 character from the file, so return 1.
+sol.read(buf, 2); // Now buf should contain "bc". We read a total of 2 characters from the file, so return 2.
+sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.
+Assume buf is allocated and guaranteed to have enough space for storing all characters from the file.
+
+ +

Example 2:

+ +
+Input: file = "abc", queries = [4,1]
+Output: [3,0]
+Explanation: The test case represents the following scenario:
+File file("abc");
+Solution sol;
+sol.read(buf, 4); // After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
+sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= file.length <= 500
  • +
  • file consist of English letters and digits.
  • +
  • 1 <= queries.length <= 10
  • +
  • 1 <= queries[i] <= 500
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0158.Read N Characters Given Read4 II - Call multiple times/images/157_example.png b/assets/0100-0199/0158.Read N Characters Given Read4 II - Call multiple times/images/157_example.png new file mode 100644 index 00000000..f6cfe220 Binary files /dev/null and b/assets/0100-0199/0158.Read N Characters Given Read4 II - Call multiple times/images/157_example.png differ diff --git a/assets/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md b/assets/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md new file mode 100644 index 00000000..1b7697c0 --- /dev/null +++ b/assets/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md @@ -0,0 +1,57 @@ +# [159. Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters) + + + +## Description + +

Given a string s, return the length of the longest substring that contains at most two distinct characters.

+ +

 

+

Example 1:

+ +
+Input: s = "eceba"
+Output: 3
+Explanation: The substring is "ece" which its length is 3.
+
+ +

Example 2:

+ +
+Input: s = "ccaabbb"
+Output: 5
+Explanation: The substring is "aabbb" which its length is 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md b/assets/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md new file mode 100644 index 00000000..0a731acb --- /dev/null +++ b/assets/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md @@ -0,0 +1,219 @@ +# [160. Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists) + + + +## Description + +

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

+ +

For example, the following two linked lists begin to intersect at node c1:

+ +

It is guaranteed that there are no cycles anywhere in the entire linked structure.

+ +

Note that the linked lists must retain their original structure after the function returns.

+ +

 

+

Example 1:

+ +
+Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
+Output: Intersected at '8'
+Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
+
+ +

Example 2:

+ +
+Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
+Output: Intersected at '2'
+Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
+From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
+
+ +

Example 3:

+ +
+Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
+Output: No intersection
+Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
+Explanation: The two lists do not intersect, so return null.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes of listA is in the m.
  • +
  • The number of nodes of listB is in the n.
  • +
  • 0 <= m, n <= 3 * 104
  • +
  • 1 <= Node.val <= 105
  • +
  • 0 <= skipA <= m
  • +
  • 0 <= skipB <= n
  • +
  • intersectVal is 0 if listA and listB do not intersect.
  • +
  • intersectVal == listA[skipA + 1] == listB[skipB + 1] if listA and listB intersect.
  • +
+ +

 

+Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory? + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + cur1, cur2 = headA, headB + while cur1 != cur2: + cur1 = headB if cur1 is None else cur1.next + cur2 = headA if cur2 is None else cur2.next + return cur1 +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + ListNode cur1 = headA, cur2 = headB; + while (cur1 != cur2) { + cur1 = cur1 == null ? headB : cur1.next; + cur2 = cur2 == null ? headA : cur2.next; + } + return cur1; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode* cur1 = headA; + ListNode* cur2 = headB; + while (cur1 != cur2) { + cur1 = cur1 ? cur1->next : headB; + cur2 = cur2 ? cur2->next : headA; + } + return cur1; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ + var getIntersectionNode = function(headA, headB) { + let cur1 = headA; + let cur2 = headB; + while (cur1 != cur2) { + cur1 = cur1 ? cur1.next : headB; + cur2 = cur2 ? cur2.next : headA; + } + return cur1; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + func getIntersectionNode(headA, headB *ListNode) *ListNode { + cur1, cur2 := headA, headB + for cur1 != cur2 { + if cur1 == nil { + cur1 = headB + } else { + cur1 = cur1.Next + } + if cur2 == nil { + cur2 = headA + } else { + cur2 = cur2.Next + } + } + return cur1 +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { + let p1: ListNode | null = headA; + let p2: ListNode | null = headB; + while (p1 != p2) { + p1 = p1 == null ? headB : p1.next; + p2 = p2 == null ? headA : p2.next; + } + return p1; +}; +``` +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_1.png b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_1.png new file mode 100644 index 00000000..e4992208 Binary files /dev/null and b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_1.png differ diff --git a/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_2.png b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_2.png new file mode 100644 index 00000000..2cfe7e03 Binary files /dev/null and b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_2.png differ diff --git a/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_3.png b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_3.png new file mode 100644 index 00000000..98b1ebfe Binary files /dev/null and b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_example_3.png differ diff --git a/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_statement.png b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_statement.png new file mode 100644 index 00000000..8baa8c55 Binary files /dev/null and b/assets/0100-0199/0160.Intersection of Two Linked Lists/images/160_statement.png differ diff --git a/assets/0100-0199/0161.One Edit Distance/README_EN.md b/assets/0100-0199/0161.One Edit Distance/README_EN.md new file mode 100644 index 00000000..855b53e9 --- /dev/null +++ b/assets/0100-0199/0161.One Edit Distance/README_EN.md @@ -0,0 +1,80 @@ +# [161. One Edit Distance](https://leetcode.com/problems/one-edit-distance) + + + +## Description + +

Given two strings s and t, return true if they are both one edit distance apart, otherwise return false.

+ +

A string s is said to be one distance apart from a string t if you can:

+ +
    +
  • Insert exactly one character into s to get t.
  • +
  • Delete exactly one character from s to get t.
  • +
  • Replace exactly one character of s with a different character to get t.
  • +
+ +

 

+

Example 1:

+ +
+Input: s = "ab", t = "acb"
+Output: true
+Explanation: We can insert 'c' into s to get t.
+
+ +

Example 2:

+ +
+Input: s = "", t = ""
+Output: false
+Explanation: We cannot get t from s by only one step.
+
+ +

Example 3:

+ +
+Input: s = "a", t = ""
+Output: true
+
+ +

Example 4:

+ +
+Input: s = "", t = "A"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 104
  • +
  • 0 <= t.length <= 104
  • +
  • s and t consist of lower-case letters, upper-case letters and/or digits.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0162.Find Peak Element/README_EN.md b/assets/0100-0199/0162.Find Peak Element/README_EN.md new file mode 100644 index 00000000..c579813f --- /dev/null +++ b/assets/0100-0199/0162.Find Peak Element/README_EN.md @@ -0,0 +1,140 @@ +# [162. Find Peak Element](https://leetcode.com/problems/find-peak-element) + + + +## Description + +

A peak element is an element that is strictly greater than its neighbors.

+ +

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

+ +

You may imagine that nums[-1] = nums[n] = -∞.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,1]
+Output: 2
+Explanation: 3 is a peak element and your function should return the index number 2.
+ +

Example 2:

+ +
+Input: nums = [1,2,1,3,5,6,4]
+Output: 5
+Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • nums[i] != nums[i + 1] for all valid i.
  • +
+ +

 

+Follow up: Could you implement a solution with logarithmic complexity? + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def findPeakElement(self, nums: List[int]) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] > nums[mid + 1]: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int findPeakElement(int[] nums) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] > nums[mid + 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **TypeScript** + +```ts +function findPeakElement(nums: number[]): number { + let left = 0, right = nums.length - 1; + while (left < right) { + let mid: number = (left + right) >> 1; + if (nums[mid] <= nums[mid+1]) { + left = mid +1; + } else { + right = mid; + } + } + return left; +}; +``` + +### **Go** + +```go +func findPeakElement(nums []int) int { + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if nums[mid] > nums[mid+1] { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findPeakElement(vector& nums) { + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] > nums[mid + 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0163.Missing Ranges/README_EN.md b/assets/0100-0199/0163.Missing Ranges/README_EN.md new file mode 100644 index 00000000..a6102075 --- /dev/null +++ b/assets/0100-0199/0163.Missing Ranges/README_EN.md @@ -0,0 +1,97 @@ +# [163. Missing Ranges](https://leetcode.com/problems/missing-ranges) + + + +## Description + +

You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.

+ +

A number x is considered missing if x is in the range [lower, upper] and x is not in nums.

+ +

Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.

+ +

Each range [a,b] in the list should be output as:

+ +
    +
  • "a->b" if a != b
  • +
  • "a" if a == b
  • +
+ +

 

+

Example 1:

+ +
+Input: nums = [0,1,3,50,75], lower = 0, upper = 99
+Output: ["2","4->49","51->74","76->99"]
+Explanation: The ranges are:
+[2,2] --> "2"
+[4,49] --> "4->49"
+[51,74] --> "51->74"
+[76,99] --> "76->99"
+
+ +

Example 2:

+ +
+Input: nums = [], lower = 1, upper = 1
+Output: ["1"]
+Explanation: The only missing range is [1,1], which becomes "1".
+
+ +

Example 3:

+ +
+Input: nums = [], lower = -3, upper = -1
+Output: ["-3->-1"]
+Explanation: The only missing range is [-3,-1], which becomes "-3->-1".
+
+ +

Example 4:

+ +
+Input: nums = [-1], lower = -1, upper = -1
+Output: []
+Explanation: There are no missing ranges since there are no missing numbers.
+
+ +

Example 5:

+ +
+Input: nums = [-1], lower = -2, upper = -1
+Output: ["-2"]
+
+ +

 

+

Constraints:

+ +
    +
  • -109 <= lower <= upper <= 109
  • +
  • 0 <= nums.length <= 100
  • +
  • lower <= nums[i] <= upper
  • +
  • All the values of nums are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0164.Maximum Gap/README_EN.md b/assets/0100-0199/0164.Maximum Gap/README_EN.md new file mode 100644 index 00000000..cb18cc3b --- /dev/null +++ b/assets/0100-0199/0164.Maximum Gap/README_EN.md @@ -0,0 +1,59 @@ +# [164. Maximum Gap](https://leetcode.com/problems/maximum-gap) + + + +## Description + +

Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,6,9,1]
+Output: 3
+Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
+
+ +

Example 2:

+ +
+Input: nums = [10]
+Output: 0
+Explanation: The array contains less than 2 elements, therefore return 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • 0 <= nums[i] <= 109
  • +
+ +

 

+Follow up: Could you solve it in linear time/space? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0165.Compare Version Numbers/README_EN.md b/assets/0100-0199/0165.Compare Version Numbers/README_EN.md new file mode 100644 index 00000000..b6cd3529 --- /dev/null +++ b/assets/0100-0199/0165.Compare Version Numbers/README_EN.md @@ -0,0 +1,96 @@ +# [165. Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers) + + + +## Description + +

Given two version numbers, version1 and version2, compare them.

+ +
    +
+ +

Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

+ +

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

+ +

Return the following:

+ +
    +
  • If version1 < version2, return -1.
  • +
  • If version1 > version2, return 1.
  • +
  • Otherwise, return 0.
  • +
+ +

 

+

Example 1:

+ +
+Input: version1 = "1.01", version2 = "1.001"
+Output: 0
+Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".
+
+ +

Example 2:

+ +
+Input: version1 = "1.0", version2 = "1.0.0"
+Output: 0
+Explanation: version1 does not specify revision 2, which means it is treated as "0".
+
+ +

Example 3:

+ +
+Input: version1 = "0.1", version2 = "1.1"
+Output: -1
+Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.
+
+ +

Example 4:

+ +
+Input: version1 = "1.0.1", version2 = "1"
+Output: 1
+
+ +

Example 5:

+ +
+Input: version1 = "7.5.2.4", version2 = "7.5.3"
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= version1.length, version2.length <= 500
  • +
  • version1 and version2 only contain digits and '.'.
  • +
  • version1 and version2 are valid version numbers.
  • +
  • All the given revisions in version1 and version2 can be stored in a 32-bit integer.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md b/assets/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md new file mode 100644 index 00000000..9b09b638 --- /dev/null +++ b/assets/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md @@ -0,0 +1,63 @@ +# [166. Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal) + + + +## Description + +

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

+ +

If the fractional part is repeating, enclose the repeating part in parentheses.

+ +

If multiple answers are possible, return any of them.

+ +

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

+ +

 

+

Example 1:

+
Input: numerator = 1, denominator = 2
+Output: "0.5"
+

Example 2:

+
Input: numerator = 2, denominator = 1
+Output: "2"
+

Example 3:

+
Input: numerator = 2, denominator = 3
+Output: "0.(6)"
+

Example 4:

+
Input: numerator = 4, denominator = 333
+Output: "0.(012)"
+

Example 5:

+
Input: numerator = 1, denominator = 5
+Output: "0.2"
+
+

 

+

Constraints:

+ +
    +
  • -231 <= numerator, denominator <= 231 - 1
  • +
  • denominator != 0
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0167.Two Sum II - Input array is sorted/README_EN.md b/assets/0100-0199/0167.Two Sum II - Input array is sorted/README_EN.md new file mode 100644 index 00000000..c53ca150 --- /dev/null +++ b/assets/0100-0199/0167.Two Sum II - Input array is sorted/README_EN.md @@ -0,0 +1,117 @@ +# [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted) + + + +## Description + +

Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

+ +

Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.

+ +

You may assume that each input would have exactly one solution and you may not use the same element twice.

+ +

 

+

Example 1:

+ +
+Input: numbers = [2,7,11,15], target = 9
+Output: [1,2]
+Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
+
+ +

Example 2:

+ +
+Input: numbers = [2,3,4], target = 6
+Output: [1,3]
+
+ +

Example 3:

+ +
+Input: numbers = [-1,0], target = -1
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= numbers.length <= 3 * 104
  • +
  • -1000 <= numbers[i] <= 1000
  • +
  • numbers is sorted in increasing order.
  • +
  • -1000 <= target <= 1000
  • +
  • Only one valid answer exists.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + low, high = 0, len(numbers) - 1 + while low <= high: + if numbers[low] + numbers[high] == target: + return [low + 1, high + 1] + if numbers[low] + numbers[high] < target: + low += 1 + else: + high -= 1 + return [-1, -1] +``` + +### **Java** + +```java +class Solution { + public int[] twoSum(int[] numbers, int target) { + int low = 0, high = numbers.length - 1; + while (low <= high) { + if (numbers[low] + numbers[high] == target) { + return new int[]{low + 1, high + 1}; + } + if (numbers[low] + numbers[high] < target) { + ++low; + } else { + --high; + } + } + return new int[]{-1, -1}; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int low = 0, high = numbers.size() - 1; + while (low <= high) { + if (numbers[low] + numbers[high] == target) { + return {low + 1, high + 1}; + } + if (numbers[low] + numbers[high] < target) { + ++low; + } else { + --high; + } + } + return {-1, -1}; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0168.Excel Sheet Column Title/README_EN.md b/assets/0100-0199/0168.Excel Sheet Column Title/README_EN.md new file mode 100644 index 00000000..6b580e91 --- /dev/null +++ b/assets/0100-0199/0168.Excel Sheet Column Title/README_EN.md @@ -0,0 +1,128 @@ +# [168. Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title) + + + +## Description + +

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

+ +

For example:

+ +
+A -> 1
+B -> 2
+C -> 3
+...
+Z -> 26
+AA -> 27
+AB -> 28 
+...
+
+ +

 

+

Example 1:

+ +
+Input: columnNumber = 1
+Output: "A"
+
+ +

Example 2:

+ +
+Input: columnNumber = 28
+Output: "AB"
+
+ +

Example 3:

+ +
+Input: columnNumber = 701
+Output: "ZY"
+
+ +

Example 4:

+ +
+Input: columnNumber = 2147483647
+Output: "FXSHRXW"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= columnNumber <= 231 - 1
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def convertToTitle(self, columnNumber: int) -> str: + res = [] + while columnNumber: + columnNumber -= 1 + res.append(chr(ord('A') + columnNumber % 26)) + columnNumber //= 26 + return ''.join(res[::-1]) +``` + +### **Java** + +```java +class Solution { + public String convertToTitle(int columnNumber) { + StringBuilder res = new StringBuilder(); + while (columnNumber != 0) { + --columnNumber; + res.append((char) ('A' + columnNumber % 26)); + columnNumber /= 26; + } + return res.reverse().toString(); + } +} +``` + +### **TypeScript** + +```ts +function convertToTitle(columnNumber: number): string { + let res: string[] = []; + while (columnNumber > 0) { + --columnNumber; + let num: number = columnNumber % 26; + res.unshift(String.fromCharCode(num + 65)); + columnNumber = Math.floor(columnNumber / 26); + } + return res.join(''); +}; +``` + +### **C#** + +```cs +public class Solution { + public string ConvertToTitle(int columnNumber) { + StringBuilder res = new StringBuilder(); + while (columnNumber != 0) { + --columnNumber; + res.Append((char) ('A' + columnNumber % 26)); + columnNumber /= 26; + } + return new string(res.ToString().Reverse().ToArray()); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0169.Majority Element/README_EN.md b/assets/0100-0199/0169.Majority Element/README_EN.md new file mode 100644 index 00000000..780a8b53 --- /dev/null +++ b/assets/0100-0199/0169.Majority Element/README_EN.md @@ -0,0 +1,140 @@ +# [169. Majority Element](https://leetcode.com/problems/majority-element) + + + +## Description + +

Given an array nums of size n, return the majority element.

+ +

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

+ +

 

+

Example 1:

+
Input: nums = [3,2,3]
+Output: 3
+

Example 2:

+
Input: nums = [2,2,1,1,1,2,2]
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow-up: Could you solve the problem in linear time and in O(1) space? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def majorityElement(self, nums: List[int]) -> int: + cnt = major = 0 + for num in nums: + if cnt == 0: + major = num + cnt = 1 + else: + cnt += (1 if major == num else -1) + return major +``` + +### **Java** + +```java +class Solution { + public int majorityElement(int[] nums) { + int cnt = 0, major = 0; + for (int num : nums) { + if (cnt == 0) { + major = num; + cnt = 1; + } else { + cnt += (major == num ? 1 : -1); + } + } + return major; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var majorityElement = function(nums) { + let cnt = 0; + let major = 0; + for (const num of nums) { + if (cnt == 0) { + major = num; + cnt = 1; + } else { + cnt += (major == num ? 1 : -1); + } + } + return major; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int majorityElement(vector& nums) { + int cnt = 0, major = 0; + for (int num : nums) { + if (cnt == 0) { + major = num; + cnt = 1; + } else { + cnt += (major == num ? 1 : -1); + } + } + return major; + } +}; +``` + +### **C#** + +```cs +public class Solution { + public int MajorityElement(int[] nums) { + int cnt = 0, major = 0; + foreach (int num in nums) + { + if (cnt == 0) + { + major = num; + cnt = 1; + } + else + { + cnt += (major == num ? 1 : -1); + } + } + return major; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0170.Two Sum III - Data structure design/README_EN.md b/assets/0100-0199/0170.Two Sum III - Data structure design/README_EN.md new file mode 100644 index 00000000..d05230c5 --- /dev/null +++ b/assets/0100-0199/0170.Two Sum III - Data structure design/README_EN.md @@ -0,0 +1,133 @@ +# [170. Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design) + + + +## Description + +

Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.

+ +

Implement the TwoSum class:

+ +
    +
  • TwoSum() Initializes the TwoSum object, with an empty array initially.
  • +
  • void add(int number) Adds number to the data structure.
  • +
  • boolean find(int value) Returns true if there exists any pair of numbers whose sum is equal to value, otherwise, it returns false.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["TwoSum", "add", "add", "add", "find", "find"]
+[[], [1], [3], [5], [4], [7]]
+Output
+[null, null, null, null, true, false]
+
+Explanation
+TwoSum twoSum = new TwoSum();
+twoSum.add(1);   // [] --> [1]
+twoSum.add(3);   // [1] --> [1,3]
+twoSum.add(5);   // [1,3] --> [1,3,5]
+twoSum.find(4);  // 1 + 3 = 4, return true
+twoSum.find(7);  // No two integers sum up to 7, return false
+
+ +

 

+

Constraints:

+ +
    +
  • -105 <= number <= 105
  • +
  • -231 <= value <= 231 - 1
  • +
  • At most 5 * 104 calls will be made to add and find.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class TwoSum: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.counter = collections.Counter() + + def add(self, number: int) -> None: + """ + Add the number to an internal data structure.. + """ + self.counter[number] += 1 + + def find(self, value: int) -> bool: + """ + Find if there exists any pair of numbers which sum is equal to the value. + """ + for num in self.counter.keys(): + other = value - num + if other in self.counter: + if other != num: + return True + if other == num and self.counter[num] > 1: + return True + return False + + +# Your TwoSum object will be instantiated and called as such: +# obj = TwoSum() +# obj.add(number) +# param_2 = obj.find(value) +``` + +### **Java** + +```java +class TwoSum { + private Map counter; + + /** Initialize your data structure here. */ + public TwoSum() { + counter = new HashMap<>(); + } + + /** Add the number to an internal data structure.. */ + public void add(int number) { + counter.put(number, counter.getOrDefault(number, 0) + 1); + } + + /** Find if there exists any pair of numbers which sum is equal to the value. */ + public boolean find(int value) { + for (int num : counter.keySet()) { + int other = value - num; + if (counter.containsKey(other)) { + if (num != other) { + return true; + } + if (num == other && counter.get(other) > 1) { + return true; + } + } + } + return false; + } +} + +/** + * Your TwoSum object will be instantiated and called as such: + * TwoSum obj = new TwoSum(); + * obj.add(number); + * boolean param_2 = obj.find(value); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0171.Excel Sheet Column Number/README_EN.md b/assets/0100-0199/0171.Excel Sheet Column Number/README_EN.md new file mode 100644 index 00000000..8fde4f5c --- /dev/null +++ b/assets/0100-0199/0171.Excel Sheet Column Number/README_EN.md @@ -0,0 +1,123 @@ +# [171. Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number) + + + +## Description + +

Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.

+ +

For example:

+ +
+A -> 1
+B -> 2
+C -> 3
+...
+Z -> 26
+AA -> 27
+AB -> 28 
+...
+
+ +

 

+

Example 1:

+ +
+Input: columnTitle = "A"
+Output: 1
+
+ +

Example 2:

+ +
+Input: columnTitle = "AB"
+Output: 28
+
+ +

Example 3:

+ +
+Input: columnTitle = "ZY"
+Output: 701
+
+ +

Example 4:

+ +
+Input: columnTitle = "FXSHRXW"
+Output: 2147483647
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= columnTitle.length <= 7
  • +
  • columnTitle consists only of uppercase English letters.
  • +
  • columnTitle is in the range ["A", "FXSHRXW"].
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def titleToNumber(self, columnTitle: str) -> int: + res = 0 + for c in columnTitle: + res = res * 26 + (ord(c) - ord('A') + 1) + return res +``` + +### **Java** + +```java +class Solution { + public int titleToNumber(String columnTitle) { + int res = 0; + for (char c : columnTitle.toCharArray()) { + res = res * 26 + (c - 'A' + 1); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function titleToNumber(columnTitle: string): number { + let res: number = 0; + for (let char of columnTitle) { + res = res * 26 + char.charCodeAt(0) - 64; + } + return res; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int titleToNumber(string columnTitle) { + int res = 0; + for (char c : columnTitle) { + res = res * 26 + (c - 'A' + 1); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md b/assets/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md new file mode 100644 index 00000000..8d3ee353 --- /dev/null +++ b/assets/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md @@ -0,0 +1,78 @@ +# [172. Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes) + + + +## Description + +

Given an integer n, return the number of trailing zeroes in n!.

+ +

Follow up: Could you write a solution that works in logarithmic time complexity?

+ +

 

+

Example 1:

+ +
+Input: n = 3
+Output: 0
+Explanation: 3! = 6, no trailing zero.
+
+ +

Example 2:

+ +
+Input: n = 5
+Output: 1
+Explanation: 5! = 120, one trailing zero.
+
+ +

Example 3:

+ +
+Input: n = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **TypeScript** + +```ts +function trailingZeroes(n: number): number { + let count = 0; + while (n > 0) { + n = Math.floor(n / 5); + count += n; + } + return count; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0173.Binary Search Tree Iterator/README_EN.md b/assets/0100-0199/0173.Binary Search Tree Iterator/README_EN.md new file mode 100644 index 00000000..4d16fca5 --- /dev/null +++ b/assets/0100-0199/0173.Binary Search Tree Iterator/README_EN.md @@ -0,0 +1,214 @@ +# [173. Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator) + + + +## Description + +

Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):

+ +
    +
  • BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
  • +
  • boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
  • +
  • int next() Moves the pointer to the right, then returns the number at the pointer.
  • +
+ +

Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.

+ +

You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.

+ +

 

+

Example 1:

+ +
+
+Input
+["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
+[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
+Output
+[null, 3, 7, true, 9, true, 15, true, 20, false]
+
+Explanation
+BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
+bSTIterator.next();    // return 3
+bSTIterator.next();    // return 7
+bSTIterator.hasNext(); // return True
+bSTIterator.next();    // return 9
+bSTIterator.hasNext(); // return True
+bSTIterator.next();    // return 15
+bSTIterator.hasNext(); // return True
+bSTIterator.next();    // return 20
+bSTIterator.hasNext(); // return False
+
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 105].
  • +
  • 0 <= Node.val <= 106
  • +
  • At most 105 calls will be made to hasNext, and next.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + + def __init__(self, root: TreeNode): + def inorder(root): + if root is None: + return + inorder(root.left) + self.vals.append(root.val) + inorder(root.right) + + self.cur = 0 + self.vals = [] + inorder(root) + + def next(self) -> int: + res = self.vals[self.cur] + self.cur += 1 + return res + + def hasNext(self) -> bool: + return self.cur < len(self.vals) + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class BSTIterator { + + private List vals; + private int next; + + public BSTIterator(TreeNode root) { + next = 0; + vals = new ArrayList<>(); + inorder(root); + } + + public int next() { + return vals.get(next++); + } + + public boolean hasNext() { + return next < vals.size(); + } + + private void inorder(TreeNode root) { + if (root == null) { + return; + } + inorder(root.left); + vals.add(root.val); + inorder(root.right); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ +``` + +## **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + */ +var BSTIterator = function (root) { + this.stk = []; + this.cur = root; +} + + +/** + * @return {number} + */ +BSTIterator.prototype.next = function () { + while (this.cur) { + this.stk.push(this.cur); + this.cur = this.cur.left; + } + this.cur = this.stk.pop(); + let res = this.cur.val; + this.cur = this.cur.right; + return (res); +}; + +/** + * @return {boolean} + */ +BSTIterator.prototype.hasNext = function () { + if (this.stk.length === 0 && this.cur === null) return false; + return true; +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0173.Binary Search Tree Iterator/images/bst-tree.png b/assets/0100-0199/0173.Binary Search Tree Iterator/images/bst-tree.png new file mode 100644 index 00000000..f06112af Binary files /dev/null and b/assets/0100-0199/0173.Binary Search Tree Iterator/images/bst-tree.png differ diff --git a/assets/0100-0199/0174.Dungeon Game/README_EN.md b/assets/0100-0199/0174.Dungeon Game/README_EN.md new file mode 100644 index 00000000..492b3788 --- /dev/null +++ b/assets/0100-0199/0174.Dungeon Game/README_EN.md @@ -0,0 +1,68 @@ +# [174. Dungeon Game](https://leetcode.com/problems/dungeon-game) + + + +## Description + +

The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.

+ +

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

+ +

Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).

+ +

To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

+ +

Return the knight's minimum initial health so that he can rescue the princess.

+ +

Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

+ +

 

+

Example 1:

+ +
+Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
+Output: 7
+Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
+
+ +

Example 2:

+ +
+Input: dungeon = [[0]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == dungeon.length
  • +
  • n == dungeon[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • -1000 <= dungeon[i][j] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0174.Dungeon Game/images/dungeon-grid-1.jpg b/assets/0100-0199/0174.Dungeon Game/images/dungeon-grid-1.jpg new file mode 100644 index 00000000..03d8f863 Binary files /dev/null and b/assets/0100-0199/0174.Dungeon Game/images/dungeon-grid-1.jpg differ diff --git a/assets/0100-0199/0175.Combine Two Tables/README_EN.md b/assets/0100-0199/0175.Combine Two Tables/README_EN.md new file mode 100644 index 00000000..c575a061 --- /dev/null +++ b/assets/0100-0199/0175.Combine Two Tables/README_EN.md @@ -0,0 +1,91 @@ +# [175. Combine Two Tables](https://leetcode.com/problems/combine-two-tables) + + + +## Description + +

Table: Person

+ + + +
+
++-------------+---------+
+
+| Column Name | Type    |
+
++-------------+---------+
+
+| PersonId    | int     |
+
+| FirstName   | varchar |
+
+| LastName    | varchar |
+
++-------------+---------+
+
+PersonId is the primary key column for this table.
+
+
+ + + +

Table: Address

+ + + +
+
++-------------+---------+
+
+| Column Name | Type    |
+
++-------------+---------+
+
+| AddressId   | int     |
+
+| PersonId    | int     |
+
+| City        | varchar |
+
+| State       | varchar |
+
++-------------+---------+
+
+AddressId is the primary key column for this table.
+
+
+ + + +

 

+ + + +

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

+ + + +
+
+FirstName, LastName, City, State
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT p.FirstName, p.LastName, a.City, a.State +FROM Person p +LEFT JOIN Address a +ON p.PersonId = a.PersonId; +``` + + diff --git a/assets/0100-0199/0176.Second Highest Salary/README_EN.md b/assets/0100-0199/0176.Second Highest Salary/README_EN.md new file mode 100644 index 00000000..acabcc07 --- /dev/null +++ b/assets/0100-0199/0176.Second Highest Salary/README_EN.md @@ -0,0 +1,82 @@ +# [176. Second Highest Salary](https://leetcode.com/problems/second-highest-salary) + + + +## Description + +

Write a SQL query to get the second highest salary from the Employee table.

+ + + +
+
++----+--------+
+
+| Id | Salary |
+
++----+--------+
+
+| 1  | 100    |
+
+| 2  | 200    |
+
+| 3  | 300    |
+
++----+--------+
+
+
+ + + +

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

+ + + +
+
++---------------------+
+
+| SecondHighestSalary |
+
++---------------------+
+
+| 200                 |
+
++---------------------+
+
+
+ + + +## Solutions + + + +### **SQL** + +Solution 1: Use Sub Query and LIMIT. + +```sql +# Write your MySQL query statement below +SELECT +( + SELECT DISTINCT Salary + FROM Employee + ORDER BY Salary DESC + LIMIT 1 OFFSET 1 +) AS SecondHighestSalary; +``` + +Solution 2: Use `MAX()` function. + +```sql +# Write your MySQL query statement below +SELECT MAX(Salary) AS SecondHighestSalary +FROM Employee +WHERE Salary < ( + SELECT MAX(Salary) + FROM Employee +); +``` + + diff --git a/assets/0100-0199/0177.Nth Highest Salary/README_EN.md b/assets/0100-0199/0177.Nth Highest Salary/README_EN.md new file mode 100644 index 00000000..74a813d0 --- /dev/null +++ b/assets/0100-0199/0177.Nth Highest Salary/README_EN.md @@ -0,0 +1,73 @@ +# [177. Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary) + + + +## Description + +

Write a SQL query to get the nth highest salary from the Employee table.

+ + + +
+
++----+--------+
+
+| Id | Salary |
+
++----+--------+
+
+| 1  | 100    |
+
+| 2  | 200    |
+
+| 3  | 300    |
+
++----+--------+
+
+
+ + + +

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

+ + + +
+
++------------------------+
+
+| getNthHighestSalary(2) |
+
++------------------------+
+
+| 200                    |
+
++------------------------+
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql +CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT +BEGIN + SET N = N - 1; + RETURN ( + # Write your MySQL query statement below. + SELECT ( + SELECT DISTINCT Salary + FROM Employee + ORDER BY Salary DESC + LIMIT 1 OFFSET N + ) + ); +END +``` + + diff --git a/assets/0100-0199/0178.Rank Scores/README_EN.md b/assets/0100-0199/0178.Rank Scores/README_EN.md new file mode 100644 index 00000000..f75ea081 --- /dev/null +++ b/assets/0100-0199/0178.Rank Scores/README_EN.md @@ -0,0 +1,78 @@ +# [178. Rank Scores](https://leetcode.com/problems/rank-scores) + + + +## Description + +

Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

+ +
++----+-------+
+| Id | Score |
++----+-------+
+| 1  | 3.50  |
+| 2  | 3.65  |
+| 3  | 4.00  |
+| 4  | 3.85  |
+| 5  | 4.00  |
+| 6  | 3.65  |
++----+-------+
+
+ +

For example, given the above Scores table, your query should generate the following report (order by highest score):

+ +
++-------+---------+
+| score | Rank    |
++-------+---------+
+| 4.00  | 1       |
+| 4.00  | 1       |
+| 3.85  | 2       |
+| 3.65  | 3       |
+| 3.65  | 3       |
+| 3.50  | 4       |
++-------+---------+
+
+ +

Important Note: For MySQL solutions, to escape reserved words used as column names, you can use an apostrophe before and after the keyword. For example `Rank`.

+ + +## Solutions + + + +### **MySQL8** + +Use `DENSE_RANK()` to solve this problem. + +```sql +DENSE_RANK() OVER ( + PARTITION BY [{,...}] + ORDER BY [ASC|DESC], [{,...}] +) +``` + +Solution: + +```sql +# Write your MySQL query statement below +SELECT Score, DENSE_RANK() OVER (ORDER BY Score DESC) 'Rank' +FROM Scores; +``` + +### **MySQL5** + +MySQL only provides [window function](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html) after version 8. In previous versions, variables can be used to achieve similar functions: + +```sql +SELECT Score, + CONVERT(rk, SIGNED) `Rank` +FROM (SELECT Score, + IF(@latest = Score, @rank, @rank := @rank + 1) rk, + @latest := Score + FROM Scores, + (SELECT @rank := 0, @latest := NULL) tmp + ORDER BY Score DESC) s; +``` + + diff --git a/assets/0100-0199/0179.Largest Number/README_EN.md b/assets/0100-0199/0179.Largest Number/README_EN.md new file mode 100644 index 00000000..512be305 --- /dev/null +++ b/assets/0100-0199/0179.Largest Number/README_EN.md @@ -0,0 +1,91 @@ +# [179. Largest Number](https://leetcode.com/problems/largest-number) + + + +## Description + +

Given a list of non-negative integers nums, arrange them such that they form the largest number.

+ +

Note: The result may be very large, so you need to return a string instead of an integer.

+ +

 

+

Example 1:

+ +
+Input: nums = [10,2]
+Output: "210"
+
+ +

Example 2:

+ +
+Input: nums = [3,30,34,5,9]
+Output: "9534330"
+
+ +

Example 3:

+ +
+Input: nums = [1]
+Output: "1"
+
+ +

Example 4:

+ +
+Input: nums = [10]
+Output: "10"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +from functools import cmp_to_key + +class Solution: + def largestNumber(self, nums: List[int]) -> str: + num_list = list(map(str, nums)) + num_list.sort(key=cmp_to_key(lambda x, y: int(y + x) - int(x + y))) + return '0' if num_list[0] == '0' else ''.join(num_list) +``` + +### **Java** + +```java +class Solution { + public String largestNumber(int[] nums) { + List numList = new ArrayList<>(); + for (int num : nums) { + numList.add(String.valueOf(num)); + } + numList.sort((a, b) -> (b + a).compareTo(a + b)); + if ("0".equals(numList.get(0))) return "0"; + StringBuilder sb = new StringBuilder(); + for (String s : numList) { + sb.append(s); + } + return sb.toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0180.Consecutive Numbers/README_EN.md b/assets/0100-0199/0180.Consecutive Numbers/README_EN.md new file mode 100644 index 00000000..74bed11a --- /dev/null +++ b/assets/0100-0199/0180.Consecutive Numbers/README_EN.md @@ -0,0 +1,65 @@ +# [180. Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers) + + + +## Description + +

Table: Logs

+ +
++-------------+---------+
+| Column Name | Type    |
++-------------+---------+
+| id          | int     |
+| num         | varchar |
++-------------+---------+
+id is the primary key for this table.
+
+ +

 

+ +

Write an SQL query to find all numbers that appear at least three times consecutively.

+ +

Return the result table in any order.

+ +

The query result format is in the following example:

+ +

 

+ +
+Logs table:
++----+-----+
+| Id | Num |
++----+-----+
+| 1  | 1   |
+| 2  | 1   |
+| 3  | 1   |
+| 4  | 2   |
+| 5  | 1   |
+| 6  | 2   |
+| 7  | 2   |
++----+-----+
+
+Result table:
++-----------------+
+| ConsecutiveNums |
++-----------------+
+| 1               |
++-----------------+
+1 is the only number that appears consecutively for at least three times.
+
+ + +## Solutions + + + +### **SQL** + +``` +select distinct(Num) as ConsecutiveNums from Logs Curr where + Num = (select Num from Logs where id = Curr.id - 1) and + Num = (select Num from Logs where id = Curr.id - 2) +``` + + diff --git a/assets/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md b/assets/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md new file mode 100644 index 00000000..ad7adbd2 --- /dev/null +++ b/assets/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md @@ -0,0 +1,64 @@ +# [181. Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers) + + + +## Description + +

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

+ + + +
+
++----+-------+--------+-----------+
+
+| Id | Name  | Salary | ManagerId |
+
++----+-------+--------+-----------+
+
+| 1  | Joe   | 70000  | 3         |
+
+| 2  | Henry | 80000  | 4         |
+
+| 3  | Sam   | 60000  | NULL      |
+
+| 4  | Max   | 90000  | NULL      |
+
++----+-------+--------+-----------+
+
+
+ + + +

Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

+ + + +
+
++----------+
+
+| Employee |
+
++----------+
+
+| Joe      |
+
++----------+
+
+
+ + + +## Solutions + + + +### **SQL** + +``` +select Name as Employee from Employee Curr where + Salary > (select Salary from Employee where Id = Curr.ManagerId) +``` + + diff --git a/assets/0100-0199/0182.Duplicate Emails/README_EN.md b/assets/0100-0199/0182.Duplicate Emails/README_EN.md new file mode 100644 index 00000000..80732f2b --- /dev/null +++ b/assets/0100-0199/0182.Duplicate Emails/README_EN.md @@ -0,0 +1,65 @@ +# [182. Duplicate Emails](https://leetcode.com/problems/duplicate-emails) + + + +## Description + +

Write a SQL query to find all duplicate emails in a table named Person.

+ + + +
+
++----+---------+
+
+| Id | Email   |
+
++----+---------+
+
+| 1  | a@b.com |
+
+| 2  | c@d.com |
+
+| 3  | a@b.com |
+
++----+---------+
+
+
+ + + +

For example, your query should return the following for the above table:

+ + + +
+
++---------+
+
+| Email   |
+
++---------+
+
+| a@b.com |
+
++---------+
+
+
+ + + +

Note: All emails are in lowercase.

+ + + +## Solutions + + + +### **SQL** + +``` +select Email from Person group by Email having count(Email) > 1 +``` + + diff --git a/assets/0100-0199/0183.Customers Who Never Order/README_EN.md b/assets/0100-0199/0183.Customers Who Never Order/README_EN.md new file mode 100644 index 00000000..775f3831 --- /dev/null +++ b/assets/0100-0199/0183.Customers Who Never Order/README_EN.md @@ -0,0 +1,92 @@ +# [183. Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order) + + + +## Description + +

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

+ + + +

Table: Customers.

+ + + +
+
++----+-------+
+
+| Id | Name  |
+
++----+-------+
+
+| 1  | Joe   |
+
+| 2  | Henry |
+
+| 3  | Sam   |
+
+| 4  | Max   |
+
++----+-------+
+
+
+ + + +

Table: Orders.

+ + + +
+
++----+------------+
+
+| Id | CustomerId |
+
++----+------------+
+
+| 1  | 3          |
+
+| 2  | 1          |
+
++----+------------+
+
+
+ + + +

Using the above tables as example, return the following:

+ + + +
+
++-----------+
+
+| Customers |
+
++-----------+
+
+| Henry     |
+
+| Max       |
+
++-----------+
+
+
+ + + +## Solutions + + + +### **SQL** + +``` +select Name as Customers from Customers + where id not in (select CustomerId from Orders) +``` + + diff --git a/assets/0100-0199/0184.Department Highest Salary/README_EN.md b/assets/0100-0199/0184.Department Highest Salary/README_EN.md new file mode 100644 index 00000000..1b3be6ad --- /dev/null +++ b/assets/0100-0199/0184.Department Highest Salary/README_EN.md @@ -0,0 +1,111 @@ +# [184. Department Highest Salary](https://leetcode.com/problems/department-highest-salary) + + + +## Description + +

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

+ + + +
+
++----+-------+--------+--------------+
+
+| Id | Name  | Salary | DepartmentId |
+
++----+-------+--------+--------------+
+
+| 1  | Joe   | 70000  | 1            |
+
+| 2  | Jim   | 90000  | 1            |
+
+| 3  | Henry | 80000  | 2            |
+
+| 4  | Sam   | 60000  | 2            |
+
+| 5  | Max   | 90000  | 1            |
+
++----+-------+--------+--------------+
+
+
+ + + +

The Department table holds all departments of the company.

+ + + +
+
++----+----------+
+
+| Id | Name     |
+
++----+----------+
+
+| 1  | IT       |
+
+| 2  | Sales    |
+
++----+----------+
+
+
+ + + +

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter).

+ + + +
+
++------------+----------+--------+
+
+| Department | Employee | Salary |
+
++------------+----------+--------+
+
+| IT         | Max      | 90000  |
+
+| IT         | Jim      | 90000  |
+
+| Sales      | Henry    | 80000  |
+
++------------+----------+--------+
+
+
+ + + +

Explanation:

+ + + +

Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.

+ + + +## Solutions + + + +### **SQL** + +``` +SELECT + Department.NAME AS Department, + Employee.NAME AS Employee, + Salary +FROM + Employee, + Department +WHERE + Employee.DepartmentId = Department.Id + AND ( Employee.DepartmentId, Salary ) + IN (SELECT DepartmentId, max( Salary ) + FROM Employee + GROUP BY DepartmentId ) +``` + + diff --git a/assets/0100-0199/0185.Department Top Three Salaries/README_EN.md b/assets/0100-0199/0185.Department Top Three Salaries/README_EN.md new file mode 100644 index 00000000..23b1f222 --- /dev/null +++ b/assets/0100-0199/0185.Department Top Three Salaries/README_EN.md @@ -0,0 +1,125 @@ +# [185. Department Top Three Salaries](https://leetcode.com/problems/department-top-three-salaries) + + + +## Description + +

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.

+ + + +
+
++----+-------+--------+--------------+
+
+| Id | Name  | Salary | DepartmentId |
+
++----+-------+--------+--------------+
+
+| 1  | Joe   | 85000  | 1            |
+
+| 2  | Henry | 80000  | 2            |
+
+| 3  | Sam   | 60000  | 2            |
+
+| 4  | Max   | 90000  | 1            |
+
+| 5  | Janet | 69000  | 1            |
+
+| 6  | Randy | 85000  | 1            |
+
+| 7  | Will  | 70000  | 1            |
+
++----+-------+--------+--------------+
+
+
+ + + +

The Department table holds all departments of the company.

+ + + +
+
++----+----------+
+
+| Id | Name     |
+
++----+----------+
+
+| 1  | IT       |
+
+| 2  | Sales    |
+
++----+----------+
+
+
+ + + +

Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).

+ + + +
+
++------------+----------+--------+
+
+| Department | Employee | Salary |
+
++------------+----------+--------+
+
+| IT         | Max      | 90000  |
+
+| IT         | Randy    | 85000  |
+
+| IT         | Joe      | 85000  |
+
+| IT         | Will     | 70000  |
+
+| Sales      | Henry    | 80000  |
+
+| Sales      | Sam      | 60000  |
+
++------------+----------+--------+
+
+
+ + + +

Explanation:

+ + + +

In IT department, Max earns the highest salary, both Randy and Joe earn the second highest salary, and Will earns the third highest salary. There are only two employees in the Sales department, Henry earns the highest salary while Sam earns the second highest salary.

+ + + +## Solutions + + + +### **SQL** + +``` +SELECT + Department.NAME AS Department, + Employee.NAME AS Employee, + Salary +FROM + Employee, + Department +WHERE + Employee.DepartmentId = Department.Id + AND (SELECT + COUNT(DISTINCT e2.Salary) + FROM + Employee e2 + WHERE + e2.Salary > Employee.Salary + AND Employee.DepartmentId = e2.DepartmentId + ) < 3 +``` + + diff --git a/assets/0100-0199/0186.Reverse Words in a String II/README_EN.md b/assets/0100-0199/0186.Reverse Words in a String II/README_EN.md new file mode 100644 index 00000000..42012606 --- /dev/null +++ b/assets/0100-0199/0186.Reverse Words in a String II/README_EN.md @@ -0,0 +1,55 @@ +# [186. Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii) + + + +## Description + +

Given a character array s, reverse the order of the words.

+ +

A word is defined as a sequence of non-space characters. The words in s will be separated by a single space.

+ +

 

+

Example 1:

+
Input: s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
+Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
+

Example 2:

+
Input: s = ["a"]
+Output: ["a"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is an English letter (uppercase or lowercase), digit, or space ' '.
  • +
  • There is at least one word in s.
  • +
  • s does not contain leading or trailing spaces.
  • +
  • All the words in s are guaranteed to be separated by a single space.
  • +
+ +

 

+Follow up: Could you do it in-place without allocating extra space? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0187.Repeated DNA Sequences/README_EN.md b/assets/0100-0199/0187.Repeated DNA Sequences/README_EN.md new file mode 100644 index 00000000..4909b257 --- /dev/null +++ b/assets/0100-0199/0187.Repeated DNA Sequences/README_EN.md @@ -0,0 +1,102 @@ +# [187. Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences) + + + +## Description + +

The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.

+ +
    +
  • For example, "ACGAATTCCG" is a DNA sequence.
  • +
+ +

When studying DNA, it is useful to identify repeated sequences within the DNA.

+ +

Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.

+ +

 

+

Example 1:

+
Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
+Output: ["AAAAACCCCC","CCCCCAAAAA"]
+

Example 2:

+
Input: s = "AAAAAAAAAAAAA"
+Output: ["AAAAAAAAAA"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either 'A', 'C', 'G', or 'T'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findRepeatedDnaSequences(self, s: str) -> List[str]: + n = 10 + subs = set() + res = set() + for i in range(len(s) - n + 1): + sub = s[i:i + n] + if sub in subs: + res.add(sub) + subs.add(sub) + return list(res) +``` + +### **Java** + +```java +class Solution { + public List findRepeatedDnaSequences(String s) { + int len = 10; + Set subs = new HashSet<>(); + Set res = new HashSet<>(); + for (int i = 0; i < s.length() - len + 1; ++i) { + String sub = s.substring(i, i + len); + if (subs.contains(sub)) { + res.add(sub); + } + subs.add(sub); + } + return new ArrayList<>(res); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {string[]} + */ +var findRepeatedDnaSequences = function(s) { + let n = 10; + let subs = new Set(); + let res = new Set(); + for (let i = 0; i < s.length - n + 1; i++) { + let sub = s.slice(i, i + n); + if (subs.has(sub)) { + res.add(sub); + } + subs.add(sub); + } + return [...res]; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md b/assets/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md new file mode 100644 index 00000000..f5306db0 --- /dev/null +++ b/assets/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md @@ -0,0 +1,62 @@ +# [188. Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv) + + + +## Description + +

You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.

+ +

Find the maximum profit you can achieve. You may complete at most k transactions.

+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
+Input: k = 2, prices = [2,4,1]
+Output: 2
+Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
+
+ +

Example 2:

+ +
+Input: k = 2, prices = [3,2,6,5,0,3]
+Output: 7
+Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= k <= 100
  • +
  • 0 <= prices.length <= 1000
  • +
  • 0 <= prices[i] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0189.Rotate Array/README_EN.md b/assets/0100-0199/0189.Rotate Array/README_EN.md new file mode 100644 index 00000000..fecac75c --- /dev/null +++ b/assets/0100-0199/0189.Rotate Array/README_EN.md @@ -0,0 +1,121 @@ +# [189. Rotate Array](https://leetcode.com/problems/rotate-array) + + + +## Description + +

Given an array, rotate the array to the right by k steps, where k is non-negative.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,4,5,6,7], k = 3
+Output: [5,6,7,1,2,3,4]
+Explanation:
+rotate 1 steps to the right: [7,1,2,3,4,5,6]
+rotate 2 steps to the right: [6,7,1,2,3,4,5]
+rotate 3 steps to the right: [5,6,7,1,2,3,4]
+
+ +

Example 2:

+ +
+Input: nums = [-1,-100,3,99], k = 2
+Output: [3,99,-1,-100]
+Explanation: 
+rotate 1 steps to the right: [99,-1,-100,3]
+rotate 2 steps to the right: [3,99,-1,-100]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • 0 <= k <= 105
  • +
+ +

 

+

Follow up:

+ +
    +
  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • +
  • Could you do it in-place with O(1) extra space?
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + n = len(nums) + k %= n + if n < 2 or k == 0: + return + nums[:] = nums[::-1] + nums[:k] = nums[:k][::-1] + nums[k:] = nums[k:][::-1] +``` + +### **Java** + +```java +class Solution { + public void rotate(int[] nums, int k) { + if (nums == null) { + return; + } + int n = nums.length; + k %= n; + if (n < 2 || k == 0) { + return; + } + + rotate(nums, 0, n - 1); + rotate(nums, 0, k - 1); + rotate(nums, k, n - 1); + } + + private void rotate(int[] nums, int i, int j) { + while (i < j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + ++i; + --j; + } + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {void} Do not return anything, modify nums in-place instead. + */ +var rotate = function (nums, k) { + k %= nums.length; + nums.splice(0, 0, ...nums.splice(-k, k)) +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0190.Reverse Bits/README_EN.md b/assets/0100-0199/0190.Reverse Bits/README_EN.md new file mode 100644 index 00000000..3cf59c6a --- /dev/null +++ b/assets/0100-0199/0190.Reverse Bits/README_EN.md @@ -0,0 +1,116 @@ +# [190. Reverse Bits](https://leetcode.com/problems/reverse-bits) + + + +## Description + +

Reverse bits of a given 32 bits unsigned integer.

+ +

Note:

+ +
    +
  • Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • +
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
  • +
+ +

Follow up:

+ +

If this function is called many times, how would you optimize it?

+ +

 

+

Example 1:

+ +
+Input: n = 00000010100101000001111010011100
+Output:    964176192 (00111001011110000010100101000000)
+Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
+
+ +

Example 2:

+ +
+Input: n = 11111111111111111111111111111101
+Output:   3221225471 (10111111111111111111111111111111)
+Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
+
+ +

 

+

Constraints:

+ +
    +
  • The input must be a binary string of length 32
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def reverseBits(self, n: int) -> int: + res = 0 + for i in range(32): + res |= ((n & 1) << (31 - i)) + n >>= 1 + return res +``` + +### **Java** + +```java +public class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + int res = 0; + for (int i = 0; i < 32 && n != 0; ++i) { + res |= ((n & 1) << (31 - i)); + n >>>= 1; + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t res = 0; + for (int i = 0; i < 32; ++i) { + res |= ((n & 1) << (31 - i)); + n >>= 1; + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n) { + let res = 0; + for (let i = 0; i < 32 && n > 0; ++i) { + res |= (n & 1) << (31 - i); + n >>>= 1; + } + return res >>> 0; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0191.Number of 1 Bits/README_EN.md b/assets/0100-0199/0191.Number of 1 Bits/README_EN.md new file mode 100644 index 00000000..0047896f --- /dev/null +++ b/assets/0100-0199/0191.Number of 1 Bits/README_EN.md @@ -0,0 +1,106 @@ +# [191. Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits) + + + +## Description + +

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

+ +

Note:

+ +
    +
  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
  • +
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.
  • +
+ +

 

+

Example 1:

+ +
+Input: n = 00000000000000000000000000001011
+Output: 3
+Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
+
+ +

Example 2:

+ +
+Input: n = 00000000000000000000000010000000
+Output: 1
+Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
+
+ +

Example 3:

+ +
+Input: n = 11111111111111111111111111111101
+Output: 31
+Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
+
+ +

 

+

Constraints:

+ +
    +
  • The input must be a binary string of length 32.
  • +
+ +

 

+Follow up: If this function is called many times, how would you optimize it? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def hammingWeight(self, n: int) -> int: + res = 0 + while n: + n &= (n - 1) + res += 1 + return res +``` + +### **Java** + +```java +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int res = 0; + while (n != 0) { + n &= (n - 1); + ++res; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} n - a positive integer + * @return {number} + */ +var hammingWeight = function (n) { + let res = 0; + while (n) { + n &= n - 1; + ++res; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0192.Word Frequency/README_EN.md b/assets/0100-0199/0192.Word Frequency/README_EN.md new file mode 100644 index 00000000..f74948be --- /dev/null +++ b/assets/0100-0199/0192.Word Frequency/README_EN.md @@ -0,0 +1,80 @@ +# [192. Word Frequency](https://leetcode.com/problems/word-frequency) + + + +## Description + +

Write a bash script to calculate the frequency of each word in a text file words.txt.

+ + + +

For simplicity sake, you may assume:

+ + + +
    +
  • words.txt contains only lowercase characters and space ' ' characters.
  • +
  • Each word must consist of lowercase characters only.
  • +
  • Words are separated by one or more whitespace characters.
  • +
+ + + +

Example:

+ + + +

Assume that words.txt has the following content:

+ + + +
+
+the day is sunny the the
+
+the sunny is is
+
+
+ + + +

Your script should output the following, sorted by descending frequency:

+ + + +
+
+the 4
+
+is 3
+
+sunny 2
+
+day 1
+
+
+ + + +

Note:

+ + + +
    +
  • Don't worry about handling ties, it is guaranteed that each word's frequency count is unique.
  • +
  • Could you write it in one-line using Unix pipes?
  • +
+ + + +## Solutions + + + +### **Bash** + +```sh + +``` + + diff --git a/assets/0100-0199/0193.Valid Phone Numbers/README_EN.md b/assets/0100-0199/0193.Valid Phone Numbers/README_EN.md new file mode 100644 index 00000000..2d54d2cb --- /dev/null +++ b/assets/0100-0199/0193.Valid Phone Numbers/README_EN.md @@ -0,0 +1,41 @@ +# [193. Valid Phone Numbers](https://leetcode.com/problems/valid-phone-numbers) + + + +## Description + +

Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.

+ +

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)

+ +

You may also assume each line in the text file must not contain leading or trailing white spaces.

+ +

Example:

+ +

Assume that file.txt has the following content:

+ +
+987-123-4567
+123 456 7890
+(123) 456-7890
+
+ +

Your script should output the following valid phone numbers:

+ +
+987-123-4567
+(123) 456-7890
+
+ + +## Solutions + + + +### **Bash** + +```sh + +``` + + diff --git a/assets/0100-0199/0194.Transpose File/README_EN.md b/assets/0100-0199/0194.Transpose File/README_EN.md new file mode 100644 index 00000000..82fbae4e --- /dev/null +++ b/assets/0100-0199/0194.Transpose File/README_EN.md @@ -0,0 +1,39 @@ +# [194. Transpose File](https://leetcode.com/problems/transpose-file) + + + +## Description + +

Given a text file file.txt, transpose its content.

+ +

You may assume that each row has the same number of columns, and each field is separated by the ' ' character.

+ +

Example:

+ +

If file.txt has the following content:

+ +
+name age
+alice 21
+ryan 30
+
+ +

Output the following:

+ +
+name alice ryan
+age 21 30
+
+ + +## Solutions + + + +### **Bash** + +```sh + +``` + + diff --git a/assets/0100-0199/0195.Tenth Line/README_EN.md b/assets/0100-0199/0195.Tenth Line/README_EN.md new file mode 100644 index 00000000..74b97480 --- /dev/null +++ b/assets/0100-0199/0195.Tenth Line/README_EN.md @@ -0,0 +1,75 @@ +# [195. Tenth Line](https://leetcode.com/problems/tenth-line) + + + +## Description + +

Given a text file file.txt, print just the 10th line of the file.

+ + + +

Example:

+ + + +

Assume that file.txt has the following content:

+ + + +
+
+Line 1
+
+Line 2
+
+Line 3
+
+Line 4
+
+Line 5
+
+Line 6
+
+Line 7
+
+Line 8
+
+Line 9
+
+Line 10
+
+
+ + + +

Your script should output the tenth line, which is:

+ + + +
+
+Line 10
+
+
+ + + +
Note:
+ +1. If the file contains less than 10 lines, what should you output?
+ +2. There's at least three different solutions. Try to explore all possibilities.
+ + + +## Solutions + + + +### **Bash** + +```sh + +``` + + diff --git a/assets/0100-0199/0196.Delete Duplicate Emails/README_EN.md b/assets/0100-0199/0196.Delete Duplicate Emails/README_EN.md new file mode 100644 index 00000000..c67d9175 --- /dev/null +++ b/assets/0100-0199/0196.Delete Duplicate Emails/README_EN.md @@ -0,0 +1,73 @@ +# [196. Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails) + + + +## Description + +

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

+ + + +
+
++----+------------------+
+
+| Id | Email            |
+
++----+------------------+
+
+| 1  | john@example.com |
+
+| 2  | bob@example.com  |
+
+| 3  | john@example.com |
+
++----+------------------+
+
+Id is the primary key column for this table.
+
+
+ + + +

For example, after running your query, the above Person table should have the following rows:

+ + + +
+
++----+------------------+
+
+| Id | Email            |
+
++----+------------------+
+
+| 1  | john@example.com |
+
+| 2  | bob@example.com  |
+
++----+------------------+
+
+
+ + + +

Note:

+ + + +

Your output is the whole Person table after executing your sql. Use delete statement.

+ + + +## Solutions + + + +### **SQL** + +``` +delete from Person where Id not in (select min(Id) from (select * from Person) as p group by p.Email) +``` + + diff --git a/assets/0100-0199/0197.Rising Temperature/README_EN.md b/assets/0100-0199/0197.Rising Temperature/README_EN.md new file mode 100644 index 00000000..390e9fbf --- /dev/null +++ b/assets/0100-0199/0197.Rising Temperature/README_EN.md @@ -0,0 +1,67 @@ +# [197. Rising Temperature](https://leetcode.com/problems/rising-temperature) + + + +## Description + +

Table: Weather

+ +
++---------------+---------+
+| Column Name   | Type    |
++---------------+---------+
+| id            | int     |
+| recordDate    | date    |
+| temperature   | int     |
++---------------+---------+
+id is the primary key for this table.
+This table contains information about the temperature in a certain day.
+
+ +

 

+ +

Write an SQL query to find all dates' id with higher temperature compared to its previous dates (yesterday).

+ +

Return the result table in any order.

+ +

The query result format is in the following example:

+ +
+Weather
++----+------------+-------------+
+| id | recordDate | Temperature |
++----+------------+-------------+
+| 1  | 2015-01-01 | 10          |
+| 2  | 2015-01-02 | 25          |
+| 3  | 2015-01-03 | 20          |
+| 4  | 2015-01-04 | 30          |
++----+------------+-------------+
+
+Result table:
++----+
+| id |
++----+
+| 2  |
+| 4  |
++----+
+In 2015-01-02, temperature was higher than the previous day (10 -> 25).
+In 2015-01-04, temperature was higher than the previous day (20 -> 30).
+
+ + +## Solutions + + + +### **SQL** + +``` +select w1.Id +from + Weather w1, + Weather w2 +where + DATEDIFF(w1.RecordDate, w2.RecordDate) = 1 and w1.Temperature > w2.Temperature +``` + + diff --git a/assets/0100-0199/0198.House Robber/README_EN.md b/assets/0100-0199/0198.House Robber/README_EN.md new file mode 100644 index 00000000..e39effa5 --- /dev/null +++ b/assets/0100-0199/0198.House Robber/README_EN.md @@ -0,0 +1,113 @@ +# [198. House Robber](https://leetcode.com/problems/house-robber) + + + +## Description + +

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

+ +

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,1]
+Output: 4
+Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
+Total amount you can rob = 1 + 3 = 4.
+
+ +

Example 2:

+ +
+Input: nums = [2,7,9,3,1]
+Output: 12
+Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
+Total amount you can rob = 2 + 9 + 1 = 12.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 400
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + a, b = 0, nums[0] + for num in nums[1:]: + a, b = b, max(num + a, b) + return b +``` + +### **Java** + +```java +class Solution { + public int rob(int[] nums) { + int a = 0, b = nums[0]; + for (int i = 1; i < nums.length; ++i) { + int c = Math.max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + int a = 0, b = nums[0]; + for (int i = 1; i < n; ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **Go** + +```go +func rob(nums []int) int { + a, b, n := 0, nums[0], len(nums) + for i := 1; i < n; i++ { + a, b = b, max(nums[i] + a, b) + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0199.Binary Tree Right Side View/README_EN.md b/assets/0100-0199/0199.Binary Tree Right Side View/README_EN.md new file mode 100644 index 00000000..414b58ec --- /dev/null +++ b/assets/0100-0199/0199.Binary Tree Right Side View/README_EN.md @@ -0,0 +1,115 @@ +# [199. Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view) + + + +## Description + +

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,null,5,null,4]
+Output: [1,3,4]
+
+ +

Example 2:

+ +
+Input: root = [1,null,3]
+Output: [1,3]
+
+ +

Example 3:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: TreeNode) -> List[int]: + if not root: + return [] + q = collections.deque([root]) + res = [] + while q: + size = len(q) + res.append(q[0].val) + for _ in range(size): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List rightSideView(TreeNode root) { + if (root == null) return Collections.emptyList(); + Deque q = new ArrayDeque<>(); + q.offer(root); + List res = new ArrayList<>(); + while (!q.isEmpty()) { + int size = q.size(); + res.add(q.peek().val); + while (size-- > 0) { + TreeNode node = q.poll(); + if (node.right != null) q.offer(node.right); + if (node.left != null) q.offer(node.left); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0100-0199/0199.Binary Tree Right Side View/images/tree.jpg b/assets/0100-0199/0199.Binary Tree Right Side View/images/tree.jpg new file mode 100644 index 00000000..d9814a96 Binary files /dev/null and b/assets/0100-0199/0199.Binary Tree Right Side View/images/tree.jpg differ diff --git a/assets/0200-0299/0200.Number of Islands/README_EN.md b/assets/0200-0299/0200.Number of Islands/README_EN.md new file mode 100644 index 00000000..87747c70 --- /dev/null +++ b/assets/0200-0299/0200.Number of Islands/README_EN.md @@ -0,0 +1,99 @@ +# [200. Number of Islands](https://leetcode.com/problems/number-of-islands) + + + +## Description + +

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

+ +

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

+ +

 

+

Example 1:

+ +
+Input: grid = [
+  ["1","1","1","1","0"],
+  ["1","1","0","1","0"],
+  ["1","1","0","0","0"],
+  ["0","0","0","0","0"]
+]
+Output: 1
+
+ +

Example 2:

+ +
+Input: grid = [
+  ["1","1","0","0","0"],
+  ["1","1","0","0","0"],
+  ["0","0","1","0","0"],
+  ["0","0","0","1","1"]
+]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • grid[i][j] is '0' or '1'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **TypeScript** + +```ts +function numIslands(grid: string[][]): number { + let m = grid.length, n = grid[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(grid, i, j); + ++ans; + } + } + } + return ans; +}; + +function dfs(grid: string[][], i: number, j: number) { + let m = grid.length, n = grid[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || grid[i][j] == '0') { + return; + } + grid[i][j] = '0'; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + dfs(grid, x, y); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md b/assets/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md new file mode 100644 index 00000000..8a2e21d5 --- /dev/null +++ b/assets/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md @@ -0,0 +1,61 @@ +# [201. Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range) + + + +## Description + +

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

+ +

 

+

Example 1:

+ +
+Input: left = 5, right = 7
+Output: 4
+
+ +

Example 2:

+ +
+Input: left = 0, right = 0
+Output: 0
+
+ +

Example 3:

+ +
+Input: left = 1, right = 2147483647
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= left <= right <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0202.Happy Number/README_EN.md b/assets/0200-0299/0202.Happy Number/README_EN.md new file mode 100644 index 00000000..54a96882 --- /dev/null +++ b/assets/0200-0299/0202.Happy Number/README_EN.md @@ -0,0 +1,101 @@ +# [202. Happy Number](https://leetcode.com/problems/happy-number) + + + +## Description + +

Write an algorithm to determine if a number n is happy.

+ +

A happy number is a number defined by the following process:

+ +
    +
  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • +
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • +
  • Those numbers for which this process ends in 1 are happy.
  • +
+ +

Return true if n is a happy number, and false if not.

+ +

 

+

Example 1:

+ +
+Input: n = 19
+Output: true
+Explanation:
+12 + 92 = 82
+82 + 22 = 68
+62 + 82 = 100
+12 + 02 + 02 = 1
+
+ +

Example 2:

+ +
+Input: n = 2
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isHappy(self, n: int) -> bool: + def get_next(n): + s = 0 + while n > 0: + n, digit = divmod(n, 10) + s += digit ** 2 + return s + + visited = set() + while n != 1 and n not in visited: + visited.add(n) + n = get_next(n) + return n == 1 +``` + +### **Java** + +```java +class Solution { + public boolean isHappy(int n) { + Set visited = new HashSet<>(); + while (n != 1 && !visited.contains(n)) { + visited.add(n); + n = getNext(n); + } + return n == 1; + } + + private int getNext(int n) { + int s = 0; + while (n > 0) { + int digit = n % 10; + s += digit * digit; + n /= 10; + } + return s; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0203.Remove Linked List Elements/README_EN.md b/assets/0200-0299/0203.Remove Linked List Elements/README_EN.md new file mode 100644 index 00000000..999ba110 --- /dev/null +++ b/assets/0200-0299/0203.Remove Linked List Elements/README_EN.md @@ -0,0 +1,165 @@ +# [203. Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements) + + + +## Description + +

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,6,3,4,5,6], val = 6
+Output: [1,2,3,4,5]
+
+ +

Example 2:

+ +
+Input: head = [], val = 1
+Output: []
+
+ +

Example 3:

+ +
+Input: head = [7,7,7,7], val = 7
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [0, 104].
  • +
  • 1 <= Node.val <= 50
  • +
  • 0 <= k <= 50
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeElements(self, head: ListNode, val: int) -> ListNode: + dummy = ListNode(-1, head) + pre = dummy + while pre and pre.next: + if pre.next.val != val: + pre = pre.next + else: + pre.next = pre.next.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeElements(ListNode head, int val) { + ListNode dummy = new ListNode(-1, head); + ListNode pre = dummy; + while (pre != null && pre.next != null) { + if (pre.next.val != val) pre = pre.next; + else pre.next = pre.next.next; + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + ListNode* dummy = new ListNode(); + dummy->next = head; + ListNode* p = dummy; + while (p->next) { + if (p->next->val == val) { + p->next = p->next->next; + } else { + p = p->next; + } + } + return dummy->next; + } +}; +``` + +### **Go** + +```go +func removeElements(head *ListNode, val int) *ListNode { + dummy := new(ListNode) + dummy.Next = head + p := dummy + for p.Next != nil { + if p.Next.Val == val { + p.Next = p.Next.Next + } else { + p = p.Next + } + } + return dummy.Next +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + + function removeElements(head: ListNode | null, val: number): ListNode | null { + let dummy: ListNode = new ListNode(0, head); + let cur: ListNode = dummy; + while (cur.next != null) { + if (cur.next.val == val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return dummy.next; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0203.Remove Linked List Elements/images/removelinked-list.jpg b/assets/0200-0299/0203.Remove Linked List Elements/images/removelinked-list.jpg new file mode 100644 index 00000000..4ae304c5 Binary files /dev/null and b/assets/0200-0299/0203.Remove Linked List Elements/images/removelinked-list.jpg differ diff --git a/assets/0200-0299/0204.Count Primes/README_EN.md b/assets/0200-0299/0204.Count Primes/README_EN.md new file mode 100644 index 00000000..c1edfb13 --- /dev/null +++ b/assets/0200-0299/0204.Count Primes/README_EN.md @@ -0,0 +1,91 @@ +# [204. Count Primes](https://leetcode.com/problems/count-primes) + + + +## Description + +

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

+ +

 

+

Example 1:

+ +
+Input: n = 10
+Output: 4
+Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
+
+ +

Example 2:

+ +
+Input: n = 0
+Output: 0
+
+ +

Example 3:

+ +
+Input: n = 1
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 5 * 106
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countPrimes(self, n: int) -> int: + if n < 2: + return 0 + res = 0 + primes = [True for _ in range(n)] + for i in range(2, n): + if primes[i]: + res += 1 + for j in range(i * i, n, i): + primes[j] = False + return res +``` + +### **Java** + +```java +class Solution { + public int countPrimes(int n) { + if (n < 2) return 0; + boolean[] primes = new boolean[n]; + Arrays.fill(primes, true); + int res = 0; + for (int i = 2; i < n; ++i) { + if (primes[i]) { + ++res; + if ((long) i * i < n) { + for (int j = i * i; j < n; j += i) { + primes[j] = false; + } + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0205.Isomorphic Strings/README_EN.md b/assets/0200-0299/0205.Isomorphic Strings/README_EN.md new file mode 100644 index 00000000..023f9c3d --- /dev/null +++ b/assets/0200-0299/0205.Isomorphic Strings/README_EN.md @@ -0,0 +1,79 @@ +# [205. Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings) + + + +## Description + +

Given two strings s and t, determine if they are isomorphic.

+ +

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

+ +

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

+ +

 

+

Example 1:

+
Input: s = "egg", t = "add"
+Output: true
+

Example 2:

+
Input: s = "foo", t = "bar"
+Output: false
+

Example 3:

+
Input: s = "paper", t = "title"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • t.length == s.length
  • +
  • s and t consist of any valid ascii character.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + a2b, b2a = {}, {} + n = len(s) + for i in range(n): + a, b = s[i], t[i] + if (a in a2b and a2b[a] != b) or (b in b2a and b2a[b] != a): + return False + a2b[a] = b + b2a[b] = a + return True +``` + +### **Java** + +```java +class Solution { + public boolean isIsomorphic(String s, String t) { + int n = s.length(); + Map a2b = new HashMap<>(); + Map b2a = new HashMap<>(); + for (int i = 0; i < n; ++i) { + char a = s.charAt(i), b = t.charAt(i); + if ((a2b.containsKey(a) && a2b.get(a) != b) || (b2a.containsKey(b) && b2a.get(b) != a)) return false; + a2b.put(a, b); + b2a.put(b, a); + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0206.Reverse Linked List/README_EN.md b/assets/0200-0299/0206.Reverse Linked List/README_EN.md new file mode 100644 index 00000000..9ff20675 --- /dev/null +++ b/assets/0200-0299/0206.Reverse Linked List/README_EN.md @@ -0,0 +1,170 @@ +# [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list) + + + +## Description + +

Given the head of a singly linked list, reverse the list, and return the reversed list.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5]
+Output: [5,4,3,2,1]
+
+ +

Example 2:

+ +
+Input: head = [1,2]
+Output: [2,1]
+
+ +

Example 3:

+ +
+Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is the range [0, 5000].
  • +
  • -5000 <= Node.val <= 5000
  • +
+ +

 

+

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + pre, p = None, head + while p: + q = p.next + p.next = pre + pre = p + p = q + return pre +``` + +### **Java** + +Iterative version: + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + ListNode pre = null, p = head; + while (p != null) { + ListNode q = p.next; + p.next = pre; + pre = p; + p = q; + } + return pre; + } +} +``` + +Recursive version: + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode res = reverseList(head.next); + head.next.next = head; + head.next = null; + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + let node = head; + let pre = null; + while (node) { + let cur = node; + node = cur.next; + cur.next = pre; + pre = cur; + } + return pre; +}; +``` + +### **Go** + +```go +func reverseList(head *ListNode) *ListNode { + if head == nil ||head.Next == nil { + return head + } + dummyHead := &ListNode{} + cur := head + for cur != nil { + tmp := cur.Next + cur.Next = dummyHead.Next + dummyHead.Next = cur + cur = tmp + } + return dummyHead.Next +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0206.Reverse Linked List/images/rev1ex1.jpg b/assets/0200-0299/0206.Reverse Linked List/images/rev1ex1.jpg new file mode 100644 index 00000000..67a5687c Binary files /dev/null and b/assets/0200-0299/0206.Reverse Linked List/images/rev1ex1.jpg differ diff --git a/assets/0200-0299/0206.Reverse Linked List/images/rev1ex2.jpg b/assets/0200-0299/0206.Reverse Linked List/images/rev1ex2.jpg new file mode 100644 index 00000000..42669cd5 Binary files /dev/null and b/assets/0200-0299/0206.Reverse Linked List/images/rev1ex2.jpg differ diff --git a/assets/0200-0299/0207.Course Schedule/README_EN.md b/assets/0200-0299/0207.Course Schedule/README_EN.md new file mode 100644 index 00000000..3eb4df76 --- /dev/null +++ b/assets/0200-0299/0207.Course Schedule/README_EN.md @@ -0,0 +1,68 @@ +# [207. Course Schedule](https://leetcode.com/problems/course-schedule) + + + +## Description + +

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

+ +
    +
  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
  • +
+ +

Return true if you can finish all courses. Otherwise, return false.

+ +

 

+

Example 1:

+ +
+Input: numCourses = 2, prerequisites = [[1,0]]
+Output: true
+Explanation: There are a total of 2 courses to take. 
+To take course 1 you should have finished course 0. So it is possible.
+
+ +

Example 2:

+ +
+Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
+Output: false
+Explanation: There are a total of 2 courses to take. 
+To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numCourses <= 105
  • +
  • 0 <= prerequisites.length <= 5000
  • +
  • prerequisites[i].length == 2
  • +
  • 0 <= ai, bi < numCourses
  • +
  • All the pairs prerequisites[i] are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md b/assets/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md new file mode 100644 index 00000000..a602fd0f --- /dev/null +++ b/assets/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md @@ -0,0 +1,237 @@ +# [208. Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree) + + + +## Description + +

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

+ +

Implement the Trie class:

+ +
    +
  • Trie() Initializes the trie object.
  • +
  • void insert(String word) Inserts the string word into the trie.
  • +
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • +
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
+[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
+Output
+[null, null, true, false, true, null, true]
+
+Explanation
+Trie trie = new Trie();
+trie.insert("apple");
+trie.search("apple");   // return True
+trie.search("app");     // return False
+trie.startsWith("app"); // return True
+trie.insert("app");
+trie.search("app");     // return True
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length, prefix.length <= 2000
  • +
  • word and prefix consist only of lowercase English letters.
  • +
  • At most 3 * 104 calls in total will be made to insert, search, and startsWith.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Trie: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.children = [None] * 26 + self.is_end = False + + def insert(self, word: str) -> None: + """ + Inserts a word into the trie. + """ + node = self + for c in word: + index = ord(c) - ord("a") + if node.children[index] is None: + node.children[index] = Trie() + node = node.children[index] + node.is_end = True + + def search(self, word: str) -> bool: + """ + Returns if the word is in the trie. + """ + node = self._search_prefix(word) + return node is not None and node.is_end + + def startsWith(self, prefix: str) -> bool: + """ + Returns if there is any word in the trie that starts with the given prefix. + """ + node = self._search_prefix(prefix) + return node is not None + + def _search_prefix(self, prefix: str): + node = self + for c in prefix: + index = ord(c) - ord("a") + if node.children[index] is None: + return None + node = node.children[index] + return node + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.search(word) +# param_3 = obj.startsWith(prefix) +``` + +### **Java** + +```java +class Trie { + private Trie[] children; + private boolean isEnd; + + /** Initialize your data structure here. */ + public Trie() { + children = new Trie[26]; + isEnd = false; + } + + /** Inserts a word into the trie. */ + public void insert(String word) { + Trie node = this; + for (int i = 0; i < word.length(); ++i) { + char c = word.charAt(i); + int index = c - 'a'; + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + node = node.children[index]; + } + node.isEnd = true; + } + + /** Returns if the word is in the trie. */ + public boolean search(String word) { + Trie node = searchPrefix(word); + return node != null && node.isEnd; + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + public boolean startsWith(String prefix) { + Trie node = searchPrefix(prefix); + return node != null; + } + + private Trie searchPrefix(String prefix) { + Trie node = this; + for (int i = 0; i < prefix.length(); ++i) { + char c = prefix.charAt(i); + int index = c - 'a'; + if (node.children[index] == null) { + return null; + } + node = node.children[index]; + } + return node; + } +} + +/** + * Your Trie object will be instantiated and called as such: + * Trie obj = new Trie(); + * obj.insert(word); + * boolean param_2 = obj.search(word); + * boolean param_3 = obj.startsWith(prefix); + */ +``` + +### **JavaScript** + +```js +/** + * Initialize your data structure here. + */ +var Trie = function() { + this.children = {}; +}; + +/** + * Inserts a word into the trie. + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function(word) { + let node = this.children; + for (let char of word) { + if (!node[char]) { + node[char] = {}; + } + node = node[char]; + } + node.isEnd = true; +}; + +/** + * Returns if the word is in the trie. + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function(word) { + let node = this.searchPrefix(word); + return node != undefined && node.isEnd != undefined; +}; + +Trie.prototype.searchPrefix = function (prefix) { + let node = this.children; + for (let char of prefix) { + if (!node[char]) return false; + node = node[char]; + } + return node; +} + +/** + * Returns if there is any word in the trie that starts with the given prefix. + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function(prefix) { + return this.searchPrefix(prefix); +}; + +/** + * Your Trie object will be instantiated and called as such: + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md b/assets/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md new file mode 100644 index 00000000..28e92337 --- /dev/null +++ b/assets/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md @@ -0,0 +1,175 @@ +# [209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum) + + + +## Description + +

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

+ +

 

+

Example 1:

+ +
+Input: target = 7, nums = [2,3,1,2,4,3]
+Output: 2
+Explanation: The subarray [4,3] has the minimal length under the problem constraint.
+
+ +

Example 2:

+ +
+Input: target = 4, nums = [1,4,4]
+Output: 1
+
+ +

Example 3:

+ +
+Input: target = 11, nums = [1,1,1,1,1,1,1,1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= target <= 109
  • +
  • 1 <= nums.length <= 105
  • +
  • 1 <= nums[i] <= 105
  • +
+ +

 

+Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)). + +## Solutions + + + +### **Python3** + +Presum and binary search. + +```python +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + pre_sum = [0] * (n + 1) + for i in range(1, n + 1): + pre_sum[i] = pre_sum[i - 1] + nums[i - 1] + res = n + 1 + for i in range(1, n + 1): + t = pre_sum[i - 1] + target + left, right = 0, n + while left < right: + mid = (left + right) >> 1 + if pre_sum[mid] >= t: + right = mid + else: + left = mid + 1 + if pre_sum[left] - pre_sum[i - 1] >= target: + res = min(res, left - i + 1) + return 0 if res == n + 1 else res +``` + +Slide window. + +```python +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + left = right = 0 + sum, res = 0, n + 1 + while right < n: + sum += nums[right] + while sum >= target: + res = min(res, right - left + 1) + sum -= nums[left] + left += 1 + right += 1 + return 0 if res == n + 1 else res +``` + +### **Java** + +Presum and binary search. + +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + int[] preSum = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + preSum[i] = preSum[i - 1] +nums[i - 1]; + } + int res = n + 1; + for (int i = 1; i <= n; ++i) { + int t = preSum[i - 1] + target; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (preSum[mid] >= t) { + right = mid; + } else { + left = mid + 1; + } + } + if (preSum[left] - preSum[i - 1] >= target) { + res = Math.min(res, left - i + 1); + } + } + return res == n + 1 ? 0 : res; + } +} +``` + +Slide window. + +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + int left = 0, right = 0; + int sum = 0, res = n + 1; + while (right < n) { + sum += nums[right]; + while (sum >= target) { + res = Math.min(res, right - left + 1); + sum -= nums[left++]; + } + ++right; + } + return res == n + 1 ? 0 : res; + } +} +``` + +### **C#** + +```cs +public class Solution { + public int MinSubArrayLen(int target, int[] nums) { + int n = nums.Length; + int left = 0, right = 0; + int sum = 0, res = n + 1; + while (right < n) + { + sum += nums[right]; + while (sum >= target) + { + res = Math.Min(res, right - left + 1); + sum -= nums[left++]; + } + ++right; + } + return res == n + 1 ? 0 : res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0210.Course Schedule II/README_EN.md b/assets/0200-0299/0210.Course Schedule II/README_EN.md new file mode 100644 index 00000000..5e760658 --- /dev/null +++ b/assets/0200-0299/0210.Course Schedule II/README_EN.md @@ -0,0 +1,75 @@ +# [210. Course Schedule II](https://leetcode.com/problems/course-schedule-ii) + + + +## Description + +

There are a total of n courses you have to take labelled from 0 to n - 1.

+ +

Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.

+ +

Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses.

+ +

If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

+ +

 

+

Example 1:

+ +
+Input: numCourses = 2, prerequisites = [[1,0]]
+Output: [0,1]
+Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
+
+ +

Example 2:

+ +
+Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
+Output: [0,2,1,3]
+Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
+So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
+
+ +

Example 3:

+ +
+Input: numCourses = 1, prerequisites = []
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= numCourses <= 2000
  • +
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • +
  • prerequisites[i].length == 2
  • +
  • 0 <= ai, bi < numCourses
  • +
  • ai != bi
  • +
  • All the pairs [ai, bi] are distinct.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md b/assets/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md new file mode 100644 index 00000000..66cafeb8 --- /dev/null +++ b/assets/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md @@ -0,0 +1,174 @@ +# [211. Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure) + + + +## Description + +

Design a data structure that supports adding new words and finding if a string matches any previously added string.

+ +

Implement the WordDictionary class:

+ +
    +
  • WordDictionary() Initializes the object.
  • +
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • +
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
  • +
+ +

 

+

Example:

+ +
+Input
+["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
+[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
+Output
+[null,null,null,null,false,true,true,true]
+
+Explanation
+WordDictionary wordDictionary = new WordDictionary();
+wordDictionary.addWord("bad");
+wordDictionary.addWord("dad");
+wordDictionary.addWord("mad");
+wordDictionary.search("pad"); // return False
+wordDictionary.search("bad"); // return True
+wordDictionary.search(".ad"); // return True
+wordDictionary.search("b.."); // return True
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 500
  • +
  • word in addWord consists lower-case English letters.
  • +
  • word in search consist of  '.' or lower-case English letters.
  • +
  • At most 50000 calls will be made to addWord and search.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Trie: + + def __init__(self): + self.children = [None] * 26 + self.is_end = False + + +class WordDictionary: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.trie = Trie() + + def addWord(self, word: str) -> None: + node = self.trie + for c in word: + index = ord(c) - ord('a') + if node.children[index] is None: + node.children[index] = Trie() + node = node.children[index] + node.is_end = True + + def search(self, word: str) -> bool: + return self._search(word, self.trie) + + def _search(self, word: str, node: Trie) -> bool: + for i in range(len(word)): + c = word[i] + index = ord(c) - ord('a') + if c != '.' and node.children[index] is None: + return False + if c == '.': + for j in range(26): + if node.children[j] is not None and self._search(word[i + 1:], node.children[j]): + return True + return False + node = node.children[index] + return node.is_end + +# Your WordDictionary object will be instantiated and called as such: +# obj = WordDictionary() +# obj.addWord(word) +# param_2 = obj.search(word) +``` + +### **Java** + +```java +class WordDictionary { + class Trie { + Trie[] children; + boolean isEnd; + Trie() { + children = new Trie[26]; + isEnd = false; + } + } + + private Trie trie; + + /** Initialize your data structure here. */ + public WordDictionary() { + trie = new Trie(); + } + + public void addWord(String word) { + Trie node = trie; + for (int i = 0; i < word.length(); ++i) { + char c = word.charAt(i); + int index = c - 'a'; + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + node = node.children[index]; + } + node.isEnd = true; + } + + public boolean search(String word) { + return search(word, trie); + } + + private boolean search(String word, Trie node) { + for (int i = 0; i < word.length(); ++i) { + char c = word.charAt(i); + int index = c - 'a'; + if (c != '.' && node.children[index] == null) { + return false; + } + if (c == '.') { + for (int j = 0; j < 26; ++j) { + if (node.children[j] != null && search(word.substring(i + 1), node.children[j])) { + return true; + } + } + return false; + } + node = node.children[index]; + } + return node.isEnd; + } +} + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary obj = new WordDictionary(); + * obj.addWord(word); + * boolean param_2 = obj.search(word); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0212.Word Search II/README_EN.md b/assets/0200-0299/0212.Word Search II/README_EN.md new file mode 100644 index 00000000..34ca9350 --- /dev/null +++ b/assets/0200-0299/0212.Word Search II/README_EN.md @@ -0,0 +1,63 @@ +# [212. Word Search II](https://leetcode.com/problems/word-search-ii) + + + +## Description + +

Given an m x n board of characters and a list of strings words, return all words on the board.

+ +

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

+ +

 

+

Example 1:

+ +
+Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
+Output: ["eat","oath"]
+
+ +

Example 2:

+ +
+Input: board = [["a","b"],["c","d"]], words = ["abcb"]
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 12
  • +
  • board[i][j] is a lowercase English letter.
  • +
  • 1 <= words.length <= 3 * 104
  • +
  • 1 <= words[i].length <= 10
  • +
  • words[i] consists of lowercase English letters.
  • +
  • All the strings of words are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0212.Word Search II/images/search1.jpg b/assets/0200-0299/0212.Word Search II/images/search1.jpg new file mode 100644 index 00000000..b3b29189 Binary files /dev/null and b/assets/0200-0299/0212.Word Search II/images/search1.jpg differ diff --git a/assets/0200-0299/0212.Word Search II/images/search2.jpg b/assets/0200-0299/0212.Word Search II/images/search2.jpg new file mode 100644 index 00000000..a7a3ab33 Binary files /dev/null and b/assets/0200-0299/0212.Word Search II/images/search2.jpg differ diff --git a/assets/0200-0299/0213.House Robber II/README_EN.md b/assets/0200-0299/0213.House Robber II/README_EN.md new file mode 100644 index 00000000..875435b9 --- /dev/null +++ b/assets/0200-0299/0213.House Robber II/README_EN.md @@ -0,0 +1,152 @@ +# [213. House Robber II](https://leetcode.com/problems/house-robber-ii) + + + +## Description + +

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

+ +

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,3,2]
+Output: 3
+Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,1]
+Output: 4
+Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
+Total amount you can rob = 1 + 3 = 4.
+
+ +

Example 3:

+ +
+Input: nums = [0]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 100
  • +
  • 0 <= nums[i] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + def robRange(nums, l, r): + a, b = 0, nums[l] + for num in nums[l + 1: r + 1]: + a, b = b, max(num + a, b) + return b + + n = len(nums) + if n == 1: + return nums[0] + s1, s2 = robRange(nums, 0, n - 2), robRange(nums, 1, n - 1) + return max(s1, s2) +``` + +### **Java** + +```java +class Solution { + public int rob(int[] nums) { + int n = nums.length; + if (n == 1) { + return nums[0]; + } + int s1 = robRange(nums, 0, n - 2); + int s2 = robRange(nums, 1, n - 1); + return Math.max(s1, s2); + } + + private int robRange(int[] nums, int l, int r) { + int a = 0, b = nums[l]; + for (int i = l + 1; i <= r; ++i) { + int c = Math.max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + if (n == 1) return nums[0]; + int s1 = robRange(nums, 0, n - 2); + int s2 = robRange(nums, 1, n - 1); + return max(s1, s2); + } + + int robRange(vector& nums, int l, int r) { + int a = 0, b = nums[l]; + for (int i = l + 1; i <= r; ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **Go** + +```go +func rob(nums []int) int { + n := len(nums) + if n == 1 { + return nums[0] + } + s1, s2 := robRange(nums, 0, n-2), robRange(nums, 1, n-1) + return max(s1, s2) +} + +func robRange(nums []int, l, r int) int { + a, b := 0, nums[l] + for i := l + 1; i <= r; i++ { + a, b = b, max(nums[i]+a, b) + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0214.Shortest Palindrome/README_EN.md b/assets/0200-0299/0214.Shortest Palindrome/README_EN.md new file mode 100644 index 00000000..f8a53acf --- /dev/null +++ b/assets/0200-0299/0214.Shortest Palindrome/README_EN.md @@ -0,0 +1,50 @@ +# [214. Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome) + + + +## Description + +

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

+ +

Return the shortest palindrome you can find by performing this transformation.

+ +

 

+

Example 1:

+
Input: s = "aacecaaa"
+Output: "aaacecaaa"
+

Example 2:

+
Input: s = "abcd"
+Output: "dcbabcd"
+
+

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 5 * 104
  • +
  • s consists of lowercase English letters only.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0215.Kth Largest Element in an Array/README_EN.md b/assets/0200-0299/0215.Kth Largest Element in an Array/README_EN.md new file mode 100644 index 00000000..a25e2209 --- /dev/null +++ b/assets/0200-0299/0215.Kth Largest Element in an Array/README_EN.md @@ -0,0 +1,169 @@ +# [215. Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array) + + + +## Description + +

Given an integer array nums and an integer k, return the kth largest element in the array.

+ +

Note that it is the kth largest element in the sorted order, not the kth distinct element.

+ +

 

+

Example 1:

+
Input: nums = [3,2,1,5,6,4], k = 2
+Output: 5
+

Example 2:

+
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
+Output: 4
+
+

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + def quickSort(nums, left, right, k): + if left == right: + return nums[left] + i, j = left - 1, right + 1 + x = nums[(left + right) >> 1] + while i < j: + while 1: + i += 1 + if nums[i] >= x: + break + while 1: + j -= 1 + if nums[j] <= x: + break + if i < j: + nums[i], nums[j] = nums[j], nums[i] + if j < k: + return quickSort(nums, j + 1, right, k) + return quickSort(nums, left, j, k) + + n = len(nums) + return quickSort(nums, 0, n - 1, n - k) +``` + +### **Java** + +```java +class Solution { + public int findKthLargest(int[] nums, int k) { + int n = nums.length; + return quickSort(nums, 0, n - 1, n - k); + } + + private int quickSort(int[] nums, int left, int right, int k) { + if (left == right) { + return nums[left]; + } + int i = left - 1, j = right + 1; + int x = nums[(left + right) >>> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + if (j < k) { + return quickSort(nums, j + 1, right, k); + } + return quickSort(nums, left, j, k); + + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int n = nums.size(); + return quickSort(nums, 0, n - 1, n - k); + } + + int quickSort(vector& nums, int left, int right, int k) { + if (left == right) { + return nums[left]; + } + int i = left - 1, j = right + 1; + int x = nums[left + right >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + swap(nums[i], nums[j]); + } + } + if (j < k) { + return quickSort(nums, j + 1, right, k); + } + return quickSort(nums, left, j, k); + } +}; +``` + +### **Go** + +```go +func findKthLargest(nums []int, k int) int { + n := len(nums) + return quickSort(nums, 0, n-1, n-k) +} + +func quickSort(nums []int, left, right, k int) int { + if left == right { + return nums[left] + } + i, j := left-1, right+1 + x := nums[(left+right)>>1] + for i < j { + for { + i++ + if nums[i] >= x { + break + } + } + for { + j-- + if nums[j] <= x { + break + } + } + if i < j { + nums[i], nums[j] = nums[j], nums[i] + } + } + if j < k { + return quickSort(nums, j+1, right, k) + } + return quickSort(nums, left, j, k) +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0216.Combination Sum III/README_EN.md b/assets/0200-0299/0216.Combination Sum III/README_EN.md new file mode 100644 index 00000000..3a94b74a --- /dev/null +++ b/assets/0200-0299/0216.Combination Sum III/README_EN.md @@ -0,0 +1,95 @@ +# [216. Combination Sum III](https://leetcode.com/problems/combination-sum-iii) + + + +## Description + +

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

+ +
    +
  • Only numbers 1 through 9 are used.
  • +
  • Each number is used at most once.
  • +
+ +

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

+ +

 

+

Example 1:

+ +
+Input: k = 3, n = 7
+Output: [[1,2,4]]
+Explanation:
+1 + 2 + 4 = 7
+There are no other valid combinations.
+ +

Example 2:

+ +
+Input: k = 3, n = 9
+Output: [[1,2,6],[1,3,5],[2,3,4]]
+Explanation:
+1 + 2 + 6 = 9
+1 + 3 + 5 = 9
+2 + 3 + 4 = 9
+There are no other valid combinations.
+
+ +

Example 3:

+ +
+Input: k = 4, n = 1
+Output: []
+Explanation: There are no valid combinations. [1,2,1] is not valid because 1 is used twice.
+
+ +

Example 4:

+ +
+Input: k = 3, n = 2
+Output: []
+Explanation: There are no valid combinations.
+
+ +

Example 5:

+ +
+Input: k = 9, n = 45
+Output: [[1,2,3,4,5,6,7,8,9]]
+Explanation:
+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
+​​​​​​​There are no other valid combinations.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= k <= 9
  • +
  • 1 <= n <= 60
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0217.Contains Duplicate/README_EN.md b/assets/0200-0299/0217.Contains Duplicate/README_EN.md new file mode 100644 index 00000000..2aff6ebc --- /dev/null +++ b/assets/0200-0299/0217.Contains Duplicate/README_EN.md @@ -0,0 +1,71 @@ +# [217. Contains Duplicate](https://leetcode.com/problems/contains-duplicate) + + + +## Description + +

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

+ +

 

+

Example 1:

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

Example 2:

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

Example 3:

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

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) +``` + +### **Java** + +```java +class Solution { + public boolean containsDuplicate(int[] nums) { + Set set = new HashSet<>(); + for (int e : nums) { + if (set.contains(e)) return true; + set.add(e); + } + return false; + } +} +``` + +### **TypeScript** + +```ts +function containsDuplicate(nums: number[]): boolean { + let unique: Set = new Set(nums); + return unique.size != nums.length; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0218.The Skyline Problem/README_EN.md b/assets/0200-0299/0218.The Skyline Problem/README_EN.md new file mode 100644 index 00000000..fd1ded69 --- /dev/null +++ b/assets/0200-0299/0218.The Skyline Problem/README_EN.md @@ -0,0 +1,74 @@ +# [218. The Skyline Problem](https://leetcode.com/problems/the-skyline-problem) + + + +## Description + +

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.

+ +

The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:

+ +
    +
  • lefti is the x coordinate of the left edge of the ith building.
  • +
  • righti is the x coordinate of the right edge of the ith building.
  • +
  • heighti is the height of the ith building.
  • +
+ +

You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

+ +

The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.

+ +

Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]

+ +

 

+

Example 1:

+ +
+Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
+Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
+Explanation:
+Figure A shows the buildings of the input.
+Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.
+
+ +

Example 2:

+ +
+Input: buildings = [[0,2,3],[2,5,3]]
+Output: [[0,3],[5,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= buildings.length <= 104
  • +
  • 0 <= lefti < righti <= 231 - 1
  • +
  • 1 <= heighti <= 231 - 1
  • +
  • buildings is sorted by lefti in non-decreasing order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0218.The Skyline Problem/images/skyline1.png b/assets/0200-0299/0218.The Skyline Problem/images/skyline1.png new file mode 100644 index 00000000..0554e830 Binary files /dev/null and b/assets/0200-0299/0218.The Skyline Problem/images/skyline1.png differ diff --git a/assets/0200-0299/0218.The Skyline Problem/images/skyline2.png b/assets/0200-0299/0218.The Skyline Problem/images/skyline2.png new file mode 100644 index 00000000..a4ded652 Binary files /dev/null and b/assets/0200-0299/0218.The Skyline Problem/images/skyline2.png differ diff --git a/assets/0200-0299/0219.Contains Duplicate II/README_EN.md b/assets/0200-0299/0219.Contains Duplicate II/README_EN.md new file mode 100644 index 00000000..c6cee0b5 --- /dev/null +++ b/assets/0200-0299/0219.Contains Duplicate II/README_EN.md @@ -0,0 +1,84 @@ +# [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) + + + +## Description + +

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

+ +

 

+

Example 1:

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

Example 2:

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

Example 3:

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

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
  • 0 <= k <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: + helper = {} + for i, v in enumerate(nums): + if v in helper and i - helper[v] <= k: + return True + helper[v] = i + return False +``` + +### **Java** + +```java +class Solution { + public boolean containsNearbyDuplicate(int[] nums, int k) { + Map helper = new HashMap<>(); + for (int i = 0, n = nums.length; i < n; ++i) { + if (helper.containsKey(nums[i])) { + int j = helper.get(nums[i]); + if (i - j <= k) { + return true; + } + } + helper.put(nums[i], i); + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0220.Contains Duplicate III/README_EN.md b/assets/0200-0299/0220.Contains Duplicate III/README_EN.md new file mode 100644 index 00000000..6905e096 --- /dev/null +++ b/assets/0200-0299/0220.Contains Duplicate III/README_EN.md @@ -0,0 +1,53 @@ +# [220. Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii) + + + +## Description + +

Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.

+ +

 

+

Example 1:

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

Example 2:

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

Example 3:

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

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 2 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • 0 <= k <= 104
  • +
  • 0 <= t <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0221.Maximal Square/README_EN.md b/assets/0200-0299/0221.Maximal Square/README_EN.md new file mode 100644 index 00000000..6b4ab982 --- /dev/null +++ b/assets/0200-0299/0221.Maximal Square/README_EN.md @@ -0,0 +1,64 @@ +# [221. Maximal Square](https://leetcode.com/problems/maximal-square) + + + +## Description + +

Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

+ +

 

+

Example 1:

+ +
+Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
+Output: 4
+
+ +

Example 2:

+ +
+Input: matrix = [["0","1"],["1","0"]]
+Output: 1
+
+ +

Example 3:

+ +
+Input: matrix = [["0"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 300
  • +
  • matrix[i][j] is '0' or '1'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0221.Maximal Square/images/max1grid.jpg b/assets/0200-0299/0221.Maximal Square/images/max1grid.jpg new file mode 100644 index 00000000..ae4199c7 Binary files /dev/null and b/assets/0200-0299/0221.Maximal Square/images/max1grid.jpg differ diff --git a/assets/0200-0299/0221.Maximal Square/images/max2grid.jpg b/assets/0200-0299/0221.Maximal Square/images/max2grid.jpg new file mode 100644 index 00000000..50b1349f Binary files /dev/null and b/assets/0200-0299/0221.Maximal Square/images/max2grid.jpg differ diff --git a/assets/0200-0299/0222.Count Complete Tree Nodes/README_EN.md b/assets/0200-0299/0222.Count Complete Tree Nodes/README_EN.md new file mode 100644 index 00000000..0b9e6823 --- /dev/null +++ b/assets/0200-0299/0222.Count Complete Tree Nodes/README_EN.md @@ -0,0 +1,240 @@ +# [222. Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes) + + + +## Description + +

Given the root of a complete binary tree, return the number of the nodes in the tree.

+ +

According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,4,5,6]
+Output: 6
+
+ +

Example 2:

+ +
+Input: root = []
+Output: 0
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 5 * 104].
  • +
  • 0 <= Node.val <= 5 * 104
  • +
  • The tree is guaranteed to be complete.
  • +
+ +

 

+Follow up: Traversing the tree to count the number of nodes in the tree is an easy solution but with O(n) complexity. Could you find a faster algorithm? + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countNodes(self, root: TreeNode) -> int: + def depth(root): + res = 0 + while root: + res += 1 + root = root.left + return res + + if root is None: + return 0 + left_depth = depth(root.left) + right_depth = depth(root.right) + if left_depth > right_depth: + return (1 << right_depth) + self.countNodes(root.left) + return (1 << left_depth) + self.countNodes(root.right) +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int countNodes(TreeNode root) { + if (root == null) { + return 0; + } + int leftDepth = depth(root.left); + int rightDepth = depth(root.right); + if (leftDepth > rightDepth) { + return (1 << rightDepth) + countNodes(root.left); + } + return (1 << leftDepth) + countNodes(root.right); + } + + private int depth(TreeNode root) { + int res = 0; + while (root != null) { + ++res; + root = root.left; + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int countNodes(TreeNode* root) { + if (!root) { + return 0; + } + int leftDepth = depth(root->left); + int rightDepth = depth(root->right); + if (leftDepth > rightDepth) { + return (1 << rightDepth) + countNodes(root->left); + } + return (1 << leftDepth) + countNodes(root->right); + } + +private: + int depth(TreeNode* root) { + int res = 0; + while (root) { + ++res; + root = root->left; + } + return res; + } +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func countNodes(root *TreeNode) int { + if root == nil { + return 0 + } + leftDepth := depth(root.Left) + rightDepth := depth(root.Right) + if leftDepth > rightDepth { + return (1 << rightDepth) + countNodes(root.Left) + } + return (1 << leftDepth) + countNodes(root.Right) +} + +func depth(root *TreeNode) int { + res := 0 + for root != nil { + res++ + root = root.Left + } + return res +} +``` + +### **C#** + +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int CountNodes(TreeNode root) { + if (root == null) + { + return 0; + } + int leftDepth = depth(root.left); + int rightDepth = depth(root.right); + if (leftDepth > rightDepth) + { + return (1 << rightDepth) + CountNodes(root.left); + } + return (1 << leftDepth) + CountNodes(root.right); + } + + private int depth(TreeNode root) { + int res = 0; + while (root != null) + { + ++res; + root = root.left; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0222.Count Complete Tree Nodes/images/complete.jpg b/assets/0200-0299/0222.Count Complete Tree Nodes/images/complete.jpg new file mode 100644 index 00000000..74718c02 Binary files /dev/null and b/assets/0200-0299/0222.Count Complete Tree Nodes/images/complete.jpg differ diff --git a/assets/0200-0299/0223.Rectangle Area/README_EN.md b/assets/0200-0299/0223.Rectangle Area/README_EN.md new file mode 100644 index 00000000..a7d54ff9 --- /dev/null +++ b/assets/0200-0299/0223.Rectangle Area/README_EN.md @@ -0,0 +1,58 @@ +# [223. Rectangle Area](https://leetcode.com/problems/rectangle-area) + + + +## Description + +

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

+ +

The first rectangle is defined by its bottom-left corner (A, B) and its top-right corner (C, D).

+ +

The second rectangle is defined by its bottom-left corner (E, F) and its top-right corner (G, H).

+ +

 

+

Example 1:

+Rectangle Area +
+Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
+Output: 45
+
+ +

Example 2:

+ +
+Input: A = -2, B = -2, C = 2, D = 2, E = -2, F = -2, G = 2, H = 2
+Output: 16
+
+ +

 

+

Constraints:

+ +
    +
  • -104 <= A, B, C, D, E, F, G, H <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0223.Rectangle Area/images/rectangle_area.png b/assets/0200-0299/0223.Rectangle Area/images/rectangle_area.png new file mode 100644 index 00000000..477e3d29 Binary files /dev/null and b/assets/0200-0299/0223.Rectangle Area/images/rectangle_area.png differ diff --git a/assets/0200-0299/0224.Basic Calculator/README_EN.md b/assets/0200-0299/0224.Basic Calculator/README_EN.md new file mode 100644 index 00000000..a7488db4 --- /dev/null +++ b/assets/0200-0299/0224.Basic Calculator/README_EN.md @@ -0,0 +1,63 @@ +# [224. Basic Calculator](https://leetcode.com/problems/basic-calculator) + + + +## Description + +

Given a string s representing an expression, implement a basic calculator to evaluate it.

+ +

 

+

Example 1:

+ +
+Input: s = "1 + 1"
+Output: 2
+
+ +

Example 2:

+ +
+Input: s = " 2-1 + 2 "
+Output: 3
+
+ +

Example 3:

+ +
+Input: s = "(1+(4+5+2)-3)+(6+8)"
+Output: 23
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 3 * 105
  • +
  • s consists of digits, '+', '-', '(', ')', and ' '.
  • +
  • s represents a valid expression.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0225.Implement Stack using Queues/README_EN.md b/assets/0200-0299/0225.Implement Stack using Queues/README_EN.md new file mode 100644 index 00000000..4849f69c --- /dev/null +++ b/assets/0200-0299/0225.Implement Stack using Queues/README_EN.md @@ -0,0 +1,166 @@ +# [225. Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues) + + + +## Description + +

Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty).

+ +

Implement the MyStack class:

+ +
    +
  • void push(int x) Pushes element x to the top of the stack.
  • +
  • int pop() Removes the element on the top of the stack and returns it.
  • +
  • int top() Returns the element on the top of the stack.
  • +
  • boolean empty() Returns true if the stack is empty, false otherwise.
  • +
+ +

Notes:

+ +
    +
  • You must use only standard operations of a queue, which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • +
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue), as long as you use only a queue's standard operations.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MyStack", "push", "push", "top", "pop", "empty"]
+[[], [1], [2], [], [], []]
+Output
+[null, null, null, 2, 2, false]
+
+Explanation
+MyStack myStack = new MyStack();
+myStack.push(1);
+myStack.push(2);
+myStack.top(); // return 2
+myStack.pop(); // return 2
+myStack.empty(); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x <= 9
  • +
  • At most 100 calls will be made to push, pop, top, and empty.
  • +
  • All the calls to pop and top are valid.
  • +
+ +

 

+

Follow-up: Can you implement the stack such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer. You can use more than two queues.

+ + +## Solutions + + + +### **Python3** + +```python +class MyStack: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.q = [] + + + def push(self, x: int) -> None: + """ + Push element x onto stack. + """ + self.q.append(x) + n = len(self.q) + for i in range(1, n): + self.q.append(self.q.pop(0)) + + + def pop(self) -> int: + """ + Removes the element on top of the stack and returns that element. + """ + return self.q.pop(0) + + + def top(self) -> int: + """ + Get the top element. + """ + return self.q[0] + + + def empty(self) -> bool: + """ + Returns whether the stack is empty. + """ + return len(self.q) == 0 + + + +# Your MyStack object will be instantiated and called as such: +# obj = MyStack() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.top() +# param_4 = obj.empty() +``` + +### **Java** + +```java +class MyStack { + + private Deque q; + + /** Initialize your data structure here. */ + public MyStack() { + q = new ArrayDeque<>(); + } + + /** Push element x onto stack. */ + public void push(int x) { + q.offerLast(x); + int n = q.size(); + while (n-- > 1) { + q.offerLast(q.pollFirst()); + } + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + return q.pollFirst(); + } + + /** Get the top element. */ + public int top() { + return q.peekFirst(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return q.isEmpty(); + } +} + +/** + * Your MyStack object will be instantiated and called as such: + * MyStack obj = new MyStack(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.top(); + * boolean param_4 = obj.empty(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0226.Invert Binary Tree/README_EN.md b/assets/0200-0299/0226.Invert Binary Tree/README_EN.md new file mode 100644 index 00000000..942c191a --- /dev/null +++ b/assets/0200-0299/0226.Invert Binary Tree/README_EN.md @@ -0,0 +1,140 @@ +# [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree) + + + +## Description + +

Given the root of a binary tree, invert the tree, and return its root.

+ +

 

+

Example 1:

+ +
+Input: root = [4,2,7,1,3,6,9]
+Output: [4,7,2,9,6,3,1]
+
+ +

Example 2:

+ +
+Input: root = [2,1,3]
+Output: [2,3,1]
+
+ +

Example 3:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if root is None: + return None + root.left, root.right = root.right, root.left + self.invertTree(root.left) + self.invertTree(root.right) + return root +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) return null; + TreeNode t = root.left; + root.left = root.right; + root.right = t; + invertTree(root.left); + invertTree(root.right); + return root; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = function (root) { + if (!root) return null; + [root.left, root.right] = [root.right, root.left]; + invertTree(root.left); + invertTree(root.right); + return root; +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func invertTree(root *TreeNode) *TreeNode { + if (root == nil) { + return nil + } + root.Left, root.Right = root.Right, root.Left + invertTree(root.Left) + invertTree(root.Right) + return root +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0226.Invert Binary Tree/images/invert1-tree.jpg b/assets/0200-0299/0226.Invert Binary Tree/images/invert1-tree.jpg new file mode 100644 index 00000000..91bfe2cb Binary files /dev/null and b/assets/0200-0299/0226.Invert Binary Tree/images/invert1-tree.jpg differ diff --git a/assets/0200-0299/0226.Invert Binary Tree/images/invert2-tree.jpg b/assets/0200-0299/0226.Invert Binary Tree/images/invert2-tree.jpg new file mode 100644 index 00000000..bf8672d3 Binary files /dev/null and b/assets/0200-0299/0226.Invert Binary Tree/images/invert2-tree.jpg differ diff --git a/assets/0200-0299/0227.Basic Calculator II/README_EN.md b/assets/0200-0299/0227.Basic Calculator II/README_EN.md new file mode 100644 index 00000000..52810e5d --- /dev/null +++ b/assets/0200-0299/0227.Basic Calculator II/README_EN.md @@ -0,0 +1,113 @@ +# [227. Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii) + + + +## Description + +

Given a string s which represents an expression, evaluate this expression and return its value

+ +

The integer division should truncate toward zero.

+ +

 

+

Example 1:

+
Input: s = "3+2*2"
+Output: 7
+

Example 2:

+
Input: s = " 3/2 "
+Output: 1
+

Example 3:

+
Input: s = " 3+5 / 2 "
+Output: 5
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 3 * 105
  • +
  • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
  • +
  • s represents a valid expression.
  • +
  • All the integers in the expression are non-negative integers in the range [0, 231 - 1].
  • +
  • The answer is guaranteed to fit in a 32-bit integer.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def calculate(self, s: str) -> int: + num, n = 0, len(s) + pre_sign = '+' + stack = [] + for i in range(n): + if s[i].isdigit(): + num = num * 10 + int(s[i]) + if i == n - 1 or (not s[i].isdigit() and s[i] != ' '): + if pre_sign == '+': + stack.append(num) + elif pre_sign == '-': + stack.append(-num) + elif pre_sign == '*': + stack.append(stack.pop() * num) + else: + stack.append(int(stack.pop() / num)) + pre_sign = s[i] + num = 0 + res = 0 + while stack: + res += stack.pop() + return res +``` + +### **Java** + +```java +class Solution { + public int calculate(String s) { + int num = 0; + char preSign = '+'; + Deque stack = new ArrayDeque<>(); + for (int i = 0, n = s.length(); i < n; ++i) { + if (Character.isDigit(s.charAt(i))) { + num = num * 10 + (s.charAt(i) - '0'); + } + if (i == n - 1 || (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ')) { + switch (preSign) { + case '+': + stack.push(num); + break; + case '-': + stack.push(-num); + break; + case '*': + stack.push(stack.pop() * num); + break; + case '/': + stack.push(stack.pop() / num); + break; + } + preSign = s.charAt(i); + num = 0; + } + } + + int res = 0; + while (!stack.isEmpty()) { + res += stack.pop(); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0228.Summary Ranges/README_EN.md b/assets/0200-0299/0228.Summary Ranges/README_EN.md new file mode 100644 index 00000000..1b1df52e --- /dev/null +++ b/assets/0200-0299/0228.Summary Ranges/README_EN.md @@ -0,0 +1,96 @@ +# [228. Summary Ranges](https://leetcode.com/problems/summary-ranges) + + + +## Description + +

You are given a sorted unique integer array nums.

+ +

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

+ +

Each range [a,b] in the list should be output as:

+ +
    +
  • "a->b" if a != b
  • +
  • "a" if a == b
  • +
+ +

 

+

Example 1:

+ +
+Input: nums = [0,1,2,4,5,7]
+Output: ["0->2","4->5","7"]
+Explanation: The ranges are:
+[0,2] --> "0->2"
+[4,5] --> "4->5"
+[7,7] --> "7"
+
+ +

Example 2:

+ +
+Input: nums = [0,2,3,4,6,8,9]
+Output: ["0","2->4","6","8->9"]
+Explanation: The ranges are:
+[0,0] --> "0"
+[2,4] --> "2->4"
+[6,6] --> "6"
+[8,9] --> "8->9"
+
+ +

Example 3:

+ +
+Input: nums = []
+Output: []
+
+ +

Example 4:

+ +
+Input: nums = [-1]
+Output: ["-1"]
+
+ +

Example 5:

+ +
+Input: nums = [0]
+Output: ["0"]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 20
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • All the values of nums are unique.
  • +
  • nums is sorted in ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0229.Majority Element II/README_EN.md b/assets/0200-0299/0229.Majority Element II/README_EN.md new file mode 100644 index 00000000..681cc288 --- /dev/null +++ b/assets/0200-0299/0229.Majority Element II/README_EN.md @@ -0,0 +1,64 @@ +# [229. Majority Element II](https://leetcode.com/problems/majority-element-ii) + + + +## Description + +

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

+ +

Follow-up: Could you solve the problem in linear time and in O(1) space?

+ +

 

+

Example 1:

+ +
+Input: nums = [3,2,3]
+Output: [3]
+
+ +

Example 2:

+ +
+Input: nums = [1]
+Output: [1]
+
+ +

Example 3:

+ +
+Input: nums = [1,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md b/assets/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md new file mode 100644 index 00000000..b6c790ff --- /dev/null +++ b/assets/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md @@ -0,0 +1,113 @@ +# [230. Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst) + + + +## Description + +

Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.

+ +

 

+

Example 1:

+ +
+Input: root = [3,1,4,null,2], k = 1
+Output: 1
+
+ +

Example 2:

+ +
+Input: root = [5,3,6,2,4,null,null,1], k = 3
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is n.
  • +
  • 1 <= k <= n <= 104
  • +
  • 0 <= Node.val <= 104
  • +
+ +

 

+Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthSmallest(self, root: TreeNode, k: int) -> int: + def inorder(root): + if root is None: + return + inorder(root.left) + self.k -= 1 + if self.k == 0: + self.res = root.val + return + inorder(root.right) + self.k = k + inorder(root) + return self.res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int k; + private int res; + + public int kthSmallest(TreeNode root, int k) { + this.k = k; + inorder(root); + return res; + } + + private void inorder(TreeNode root) { + if (root == null) { + return; + } + inorder(root.left); + if (--k == 0) { + res = root.val; + return; + } + inorder(root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0230.Kth Smallest Element in a BST/images/kthtree1.jpg b/assets/0200-0299/0230.Kth Smallest Element in a BST/images/kthtree1.jpg new file mode 100644 index 00000000..afb0864b Binary files /dev/null and b/assets/0200-0299/0230.Kth Smallest Element in a BST/images/kthtree1.jpg differ diff --git a/assets/0200-0299/0230.Kth Smallest Element in a BST/images/kthtree2.jpg b/assets/0200-0299/0230.Kth Smallest Element in a BST/images/kthtree2.jpg new file mode 100644 index 00000000..655e018c Binary files /dev/null and b/assets/0200-0299/0230.Kth Smallest Element in a BST/images/kthtree2.jpg differ diff --git a/assets/0200-0299/0231.Power of Two/README_EN.md b/assets/0200-0299/0231.Power of Two/README_EN.md new file mode 100644 index 00000000..70799319 --- /dev/null +++ b/assets/0200-0299/0231.Power of Two/README_EN.md @@ -0,0 +1,126 @@ +# [231. Power of Two](https://leetcode.com/problems/power-of-two) + + + +## Description + +

Given an integer n, return true if it is a power of two. Otherwise, return false.

+ +

An integer n is a power of two, if there exists an integer x such that n == 2x.

+ +

 

+

Example 1:

+ +
+Input: n = 1
+Output: true
+Explanation: 20 = 1
+
+ +

Example 2:

+ +
+Input: n = 16
+Output: true
+Explanation: 24 = 16
+
+ +

Example 3:

+ +
+Input: n = 3
+Output: false
+
+ +

Example 4:

+ +
+Input: n = 4
+Output: true
+
+ +

Example 5:

+ +
+Input: n = 5
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 +``` + +### **Java** + +```java +class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function(n) { + return n > 0 && (n & (n - 1)) == 0; +}; +``` + +### **Go** + +```go +func isPowerOfTwo(n int) bool { + return n > 0 && (n & (n - 1)) == 0 +} +``` + +### **TypeScript** + +```ts +function isPowerOfTwo(n: number): boolean { + return n > 0 && (n & (n - 1)) == 0; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0232.Implement Queue using Stacks/README_EN.md b/assets/0200-0299/0232.Implement Queue using Stacks/README_EN.md new file mode 100644 index 00000000..293d3eec --- /dev/null +++ b/assets/0200-0299/0232.Implement Queue using Stacks/README_EN.md @@ -0,0 +1,180 @@ +# [232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks) + + + +## Description + +

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

+ +

Implement the MyQueue class:

+ +
    +
  • void push(int x) Pushes element x to the back of the queue.
  • +
  • int pop() Removes the element from the front of the queue and returns it.
  • +
  • int peek() Returns the element at the front of the queue.
  • +
  • boolean empty() Returns true if the queue is empty, false otherwise.
  • +
+ +

Notes:

+ +
    +
  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • +
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
  • +
+ +

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

+ +

 

+

Example 1:

+ +
+Input
+["MyQueue", "push", "push", "peek", "pop", "empty"]
+[[], [1], [2], [], [], []]
+Output
+[null, null, null, 1, 1, false]
+
+Explanation
+MyQueue myQueue = new MyQueue();
+myQueue.push(1); // queue is: [1]
+myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
+myQueue.peek(); // return 1
+myQueue.pop(); // return 1, queue is [2]
+myQueue.empty(); // return false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= x <= 9
  • +
  • At most 100 calls will be made to push, pop, peek, and empty.
  • +
  • All the calls to pop and peek are valid.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class MyQueue: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.s1 = [] + self.s2 = [] + + + def push(self, x: int) -> None: + """ + Push element x to the back of queue. + """ + self.s1.append(x) + + + def pop(self) -> int: + """ + Removes the element from in front of queue and returns that element. + """ + self._move() + return self.s2.pop() + + def peek(self) -> int: + """ + Get the front element. + """ + self._move() + return self.s2[-1] + + + def empty(self) -> bool: + """ + Returns whether the queue is empty. + """ + return len(self.s1) + len(self.s2) == 0 + + + def _move(self): + """ + Move elements from s1 to s2. + """ + if len(self.s2) == 0: + while len(self.s1) > 0: + self.s2.append(self.s1.pop()) + + +# Your MyQueue object will be instantiated and called as such: +# obj = MyQueue() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.peek() +# param_4 = obj.empty() +``` + +### **Java** + +```java +class MyQueue { + + private Deque s1 = new ArrayDeque<>(); + private Deque s2 = new ArrayDeque<>(); + + /** Initialize your data structure here. */ + public MyQueue() { + + } + + /** Push element x to the back of queue. */ + public void push(int x) { + s1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + move(); + return s2.pop(); + } + + /** Get the front element. */ + public int peek() { + move(); + return s2.peek(); + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return s1.isEmpty() && s2.isEmpty(); + } + + /** Move elements from s1 to s2. */ + private void move() { + if (s2.isEmpty()) { + while (!s1.isEmpty()) { + s2.push(s1.pop()); + } + } + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0233.Number of Digit One/README_EN.md b/assets/0200-0299/0233.Number of Digit One/README_EN.md new file mode 100644 index 00000000..8b91f757 --- /dev/null +++ b/assets/0200-0299/0233.Number of Digit One/README_EN.md @@ -0,0 +1,54 @@ +# [233. Number of Digit One](https://leetcode.com/problems/number-of-digit-one) + + + +## Description + +

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

+ +

 

+

Example 1:

+ +
+Input: n = 13
+Output: 6
+
+ +

Example 2:

+ +
+Input: n = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 2 * 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0234.Palindrome Linked List/README_EN.md b/assets/0200-0299/0234.Palindrome Linked List/README_EN.md new file mode 100644 index 00000000..05de0a83 --- /dev/null +++ b/assets/0200-0299/0234.Palindrome Linked List/README_EN.md @@ -0,0 +1,255 @@ +# [234. Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list) + + + +## Description + +

Given the head of a singly linked list, return true if it is a palindrome.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,2,1]
+Output: true
+
+ +

Example 2:

+ +
+Input: head = [1,2]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 105].
  • +
  • 0 <= Node.val <= 9
  • +
+ +

 

+Follow up: Could you do it in O(n) time and O(1) space? + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + if head is None or head.next is None: + return True + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + pre, cur = None, slow.next + while cur: + t = cur.next + cur.next = pre + pre, cur = cur, t + while pre: + if pre.val != head.val: + return False + pre, head = pre.next, head.next + return True +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public boolean isPalindrome(ListNode head) { + if (head == null || head.next == null) { + return true; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode cur = slow.next; + slow.next = null; + ListNode pre = null; + while (cur != null) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + while (pre != null) { + if (pre.val != head.val) { + return false; + } + pre = pre.next; + head = head.next; + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {boolean} + */ +var isPalindrome = function(head) { + if (!head || !head.next) { + return true; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + let cur = slow.next; + slow.next = null; + let pre = null; + while (cur) { + let t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + while (pre) { + if (pre.val !== head.val) { + return false; + } + pre = pre.next; + head = head.next; + } + return true; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public bool IsPalindrome(ListNode head) { + if (head == null || head.next == null) + { + return true; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + ListNode cur = slow.next; + slow.next = null; + ListNode pre = null; + while (cur != null) + { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + while (pre != null) + { + if (pre.val != head.val) + { + return false; + } + pre = pre.next; + head = head.next; + } + return true; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function isPalindrome(head: ListNode | null): boolean { + if (head == null || head.next == null) return true; + // 快慢指针定位到中点 + let slow: ListNode = head, fast: ListNode = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + // 翻转链表 + let cur: ListNode = slow.next; + slow.next = null; + let prev: ListNode = null; + while (cur != null) { + let t: ListNode = cur.next; + cur.next = prev; + prev = cur; + cur = t; + } + // 判断回文 + while (prev != null) { + if (prev.val != head.val) return false; + prev = prev.next; + head = head.next; + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0234.Palindrome Linked List/images/pal1linked-list.jpg b/assets/0200-0299/0234.Palindrome Linked List/images/pal1linked-list.jpg new file mode 100644 index 00000000..39f1839f Binary files /dev/null and b/assets/0200-0299/0234.Palindrome Linked List/images/pal1linked-list.jpg differ diff --git a/assets/0200-0299/0234.Palindrome Linked List/images/pal2linked-list.jpg b/assets/0200-0299/0234.Palindrome Linked List/images/pal2linked-list.jpg new file mode 100644 index 00000000..16be6c11 Binary files /dev/null and b/assets/0200-0299/0234.Palindrome Linked List/images/pal2linked-list.jpg differ diff --git a/assets/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md b/assets/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md new file mode 100644 index 00000000..5ded26c3 --- /dev/null +++ b/assets/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md @@ -0,0 +1,205 @@ +# [235. Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree) + + + +## Description + +

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

+ +

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

+ +

 

+

Example 1:

+ +
+Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
+Output: 6
+Explanation: The LCA of nodes 2 and 8 is 6.
+
+ +

Example 2:

+ +
+Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
+Output: 2
+Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
+
+ +

Example 3:

+ +
+Input: root = [2,1], p = 2, q = 1
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 105].
  • +
  • -109 <= Node.val <= 109
  • +
  • All Node.val are unique.
  • +
  • p != q
  • +
  • p and q will exist in the BST.
  • +
+ + +## Solutions + + + +### **Python3** + +Iterative: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + while root: + if root.val < p.val and root.val < q.val: + root = root.right + elif root.val > p.val and root.val > q.val: + root = root.left + else: + return root +``` + +Recursive: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if root is None: + return None + if root.val < p.val and root.val < q.val: + return self.lowestCommonAncestor(root.right, p, q) + if root.val > p.val and root.val > q.val: + return self.lowestCommonAncestor(root.left, p, q) + return root +``` + +### **Java** + +Iterative: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + while (root != null) { + if (root.val < p.val && root.val < q.val) root = root.right; + else if (root.val > p.val && root.val > q.val) root = root.left; + else return root; + } + return root; + } +} +``` + +Recursive: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) return null; + if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); + if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); + return root; + } +} +``` + +### **Go** + +Iterative: + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + for root != nil { + if root.Val > p.Val && root.Val > q.Val { + root = root.Left + } else if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } else { + return root + } + } + return nil +} +``` + +Recursive: + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root == nil { + return root + } + if root.Val < p.Val && root.Val < q.Val { + return lowestCommonAncestor(root.Right, p, q) + } + if root.Val > p.Val && root.Val > q.Val { + return lowestCommonAncestor(root.Left, p, q) + } + return root +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/images/binarysearchtree_improved.png b/assets/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/images/binarysearchtree_improved.png new file mode 100644 index 00000000..bede0837 Binary files /dev/null and b/assets/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/images/binarysearchtree_improved.png differ diff --git a/assets/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md b/assets/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md new file mode 100644 index 00000000..2a1f099e --- /dev/null +++ b/assets/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md @@ -0,0 +1,130 @@ +# [236. Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree) + + + +## Description + +

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

+ +

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

+ +

 

+

Example 1:

+ +
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
+Output: 3
+Explanation: The LCA of nodes 5 and 1 is 3.
+
+ +

Example 2:

+ +
+Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
+Output: 5
+Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
+
+ +

Example 3:

+ +
+Input: root = [1,2], p = 1, q = 2
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [2, 105].
  • +
  • -109 <= Node.val <= 109
  • +
  • All Node.val are unique.
  • +
  • p != q
  • +
  • p and q will exist in the tree.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if root is None or root == p or root == q: + return root + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + if left is None: + return right + if right is None: + return left + return root +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + if (left == null) return right; + if (right == null) return left; + return root; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + if (!root || root == p || root == q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (!left) return right; + if (!right) return left; + return root; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/images/binarytree.png b/assets/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/images/binarytree.png new file mode 100644 index 00000000..06323f17 Binary files /dev/null and b/assets/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/images/binarytree.png differ diff --git a/assets/0200-0299/0237.Delete Node in a Linked List/README_EN.md b/assets/0200-0299/0237.Delete Node in a Linked List/README_EN.md new file mode 100644 index 00000000..6e11175c --- /dev/null +++ b/assets/0200-0299/0237.Delete Node in a Linked List/README_EN.md @@ -0,0 +1,158 @@ +# [237. Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list) + + + +## Description + +

Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.

+ +

It is guaranteed that the node to be deleted is not a tail node in the list.

+ +

 

+

Example 1:

+ +
+Input: head = [4,5,1,9], node = 5
+Output: [4,1,9]
+Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
+
+ +

Example 2:

+ +
+Input: head = [4,5,1,9], node = 1
+Output: [4,5,9]
+Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
+
+ +

Example 3:

+ +
+Input: head = [1,2,3,4], node = 3
+Output: [1,2,4]
+
+ +

Example 4:

+ +
+Input: head = [0,1], node = 0
+Output: [1]
+
+ +

Example 5:

+ +
+Input: head = [-3,5,-99], node = -3
+Output: [5,-99]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the given list is in the range [2, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • The value of each node in the list is unique.
  • +
  • The node to be deleted is in the list and is not a tail node
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def deleteNode(self, node): + """ + :type node: ListNode + :rtype: void Do not return anything, modify node in-place instead. + """ + node.val = node.next.val + node.next = node.next.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public void deleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} node + * @return {void} Do not return anything, modify node in-place instead. + */ +var deleteNode = function (node) { + node.val = node.next.val; + node.next = node.next.next; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func deleteNode(node *ListNode) { + node.Val = node.Next.Val + node.Next = node.Next.Next +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + node->val = node->next->val; + node->next = node->next->next; + } +}; +``` + + diff --git a/assets/0200-0299/0237.Delete Node in a Linked List/images/237_example.png b/assets/0200-0299/0237.Delete Node in a Linked List/images/237_example.png new file mode 100644 index 00000000..26ab1478 Binary files /dev/null and b/assets/0200-0299/0237.Delete Node in a Linked List/images/237_example.png differ diff --git a/assets/0200-0299/0238.Product of Array Except Self/README_EN.md b/assets/0200-0299/0238.Product of Array Except Self/README_EN.md new file mode 100644 index 00000000..bba71893 --- /dev/null +++ b/assets/0200-0299/0238.Product of Array Except Self/README_EN.md @@ -0,0 +1,106 @@ +# [238. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self) + + + +## Description + +

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

+ +

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3,4]
+Output: [24,12,8,6]
+

Example 2:

+
Input: nums = [-1,1,0,-3,3]
+Output: [0,0,9,0,0]
+
+

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 105
  • +
  • -30 <= nums[i] <= 30
  • +
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you solve it in O(n) time complexity and without using division?
  • +
  • Could you solve it with O(1) constant space complexity? (The output array does not count as extra space for space complexity analysis.)
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + output = [1 for _ in nums] + left = right = 1 + for i in range(n): + output[i] = left + left *= nums[i] + for i in range(n - 1, -1, -1): + output[i] *= right + right *= nums[i] + return output +``` + +### **Java** + +```java +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] output = new int[n]; + for (int i = 0, left = 1; i < n; ++i) { + output[i] = left; + left *= nums[i]; + } + for (int i = n - 1, right = 1; i >= 0; --i) { + output[i] *= right; + right *= nums[i]; + } + return output; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function (nums) { + const n = nums.length; + let output = new Array(n); + for (let i = 0, left = 1; i < n; ++i) { + output[i] = left; + left *= nums[i]; + } + for (let i = n - 1, right = 1; i >= 0; --i) { + output[i] *= right; + right *= nums[i]; + } + return output; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0239.Sliding Window Maximum/README_EN.md b/assets/0200-0299/0239.Sliding Window Maximum/README_EN.md new file mode 100644 index 00000000..fdb8abe8 --- /dev/null +++ b/assets/0200-0299/0239.Sliding Window Maximum/README_EN.md @@ -0,0 +1,118 @@ +# [239. Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum) + + + +## Description + +

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

+ +

Return the max sliding window.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
+Output: [3,3,5,5,6,7]
+Explanation: 
+Window position                Max
+---------------               -----
+[1  3  -1] -3  5  3  6  7       3
+ 1 [3  -1  -3] 5  3  6  7       3
+ 1  3 [-1  -3  5] 3  6  7       5
+ 1  3  -1 [-3  5  3] 6  7       5
+ 1  3  -1  -3 [5  3  6] 7       6
+ 1  3  -1  -3  5 [3  6  7]      7
+
+ +

Example 2:

+ +
+Input: nums = [1], k = 1
+Output: [1]
+
+ +

Example 3:

+ +
+Input: nums = [1,-1], k = 1
+Output: [1,-1]
+
+ +

Example 4:

+ +
+Input: nums = [9,11], k = 2
+Output: [11]
+
+ +

Example 5:

+ +
+Input: nums = [4,-2], k = 2
+Output: [4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
  • 1 <= k <= nums.length
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function (nums, k) { + let len = nums.length; + if (len < k) return []; + let res = [], win = []; + for (let i = 0; i < k; i++) { + while (win.length > 0 && nums[i] >= nums[win[win.length - 1]]) + win.pop(); + win.push(i); + } + res.push(nums[win[0]]); + for (let i = k; i < len; i++) { + while (win.length > 0 && nums[i] >= nums[win[win.length - 1]]) + win.pop(); + if (win.length > 0 && win[0] < i - k + 1) + win.shift(); + win.push(i); + res.push(nums[win[0]]); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0240.Search a 2D Matrix II/README_EN.md b/assets/0200-0299/0240.Search a 2D Matrix II/README_EN.md new file mode 100644 index 00000000..ea101c98 --- /dev/null +++ b/assets/0200-0299/0240.Search a 2D Matrix II/README_EN.md @@ -0,0 +1,154 @@ +# [240. Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii) + + + +## Description + +

Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:

+ +
    +
  • Integers in each row are sorted in ascending from left to right.
  • +
  • Integers in each column are sorted in ascending from top to bottom.
  • +
+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
+Output: true
+
+ +

Example 2:

+ +
+Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= n, m <= 300
  • +
  • -109 <= matix[i][j] <= 109
  • +
  • All the integers in each row are sorted in ascending order.
  • +
  • All the integers in each column are sorted in ascending order.
  • +
  • -109 <= target <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False +``` + +### **Java** + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` + +### **TypeScript** + +```ts +function searchMatrix(matrix: number[][], target: number): boolean { + let m = matrix.length, n = matrix[0].length; + let i = m - 1, j = 0; + while (i >= 0 && j < n) { + let cur = matrix[i][j]; + if (cur == target) return true; + if (cur > target) { + --i; + } else { + ++j; + } + } + return false; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +}; +``` + +### **Go** + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + i, j := m-1, 0 + for i >= 0 && j < n { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0240.Search a 2D Matrix II/images/searchgrid.jpg b/assets/0200-0299/0240.Search a 2D Matrix II/images/searchgrid.jpg new file mode 100644 index 00000000..d19d38cf Binary files /dev/null and b/assets/0200-0299/0240.Search a 2D Matrix II/images/searchgrid.jpg differ diff --git a/assets/0200-0299/0240.Search a 2D Matrix II/images/searchgrid2.jpg b/assets/0200-0299/0240.Search a 2D Matrix II/images/searchgrid2.jpg new file mode 100644 index 00000000..b4815df7 Binary files /dev/null and b/assets/0200-0299/0240.Search a 2D Matrix II/images/searchgrid2.jpg differ diff --git a/assets/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md b/assets/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md new file mode 100644 index 00000000..7b5513a4 --- /dev/null +++ b/assets/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md @@ -0,0 +1,64 @@ +# [241. Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses) + + + +## Description + +

Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: expression = "2-1-1"
+Output: [0,2]
+Explanation:
+((2-1)-1) = 0 
+(2-(1-1)) = 2
+
+ +

Example 2:

+ +
+Input: expression = "2*3-4*5"
+Output: [-34,-14,-10,-10,10]
+Explanation:
+(2*(3-(4*5))) = -34 
+((2*3)-(4*5)) = -14 
+((2*(3-4))*5) = -10 
+(2*((3-4)*5)) = -10 
+(((2*3)-4)*5) = 10
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= expression.length <= 20
  • +
  • expression consists of digits and the operator '+', '-', and '*'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0242.Valid Anagram/README_EN.md b/assets/0200-0299/0242.Valid Anagram/README_EN.md new file mode 100644 index 00000000..35e15d37 --- /dev/null +++ b/assets/0200-0299/0242.Valid Anagram/README_EN.md @@ -0,0 +1,141 @@ +# [242. Valid Anagram](https://leetcode.com/problems/valid-anagram) + + + +## Description + +

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

+ +

 

+

Example 1:

+
Input: s = "anagram", t = "nagaram"
+Output: true
+

Example 2:

+
Input: s = "rat", t = "car"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length, t.length <= 5 * 104
  • +
  • s and t consist of lowercase English letters.
  • +
+ +

 

+

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + n = len(s) + chars = [0] * 26 + for i in range(n): + chars[ord(s[i]) - ord('a')] += 1 + chars[ord(t[i]) - ord('a')] -= 1 + for i in range(26): + if chars[i] != 0: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean isAnagram(String s, String t) { + int n; + if ((n = s.length()) != t.length()) { + return false; + } + int[] chars = new int[26]; + for (int i = 0; i < n; ++i) { + ++chars[s.charAt(i) - 'a']; + --chars[t.charAt(i) - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (chars[i] != 0) { + return false; + } + } + return true; + } +} +``` + +### **TypeScript** + +```ts +function isAnagram(s: string, t: string): boolean { + if (s.length != t.length) return false; + let record = new Array(26).fill(0); + let base = 'a'.charCodeAt(0); + for (let i = 0; i < s.length; ++i) { + ++record[s.charCodeAt(i) - base]; + --record[t.charCodeAt(i) - base]; + } + return record.every(v => v == 0); +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.size() != t.size()) { + return false; + } + vector chars(26, 0); + for (int i = 0, n = s.size(); i < n; ++i) { + ++chars[s[i] - 'a']; + --chars[t[i] - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (chars[i] != 0) { + return false; + } + } + return true; + } +}; +``` + +### **Go** + +```go +func isAnagram(s string, t string) bool { + if len(s) != len(t) { + return false + } + var chars [26]int + for i := 0; i < len(s); i++ { + chars[s[i]-'a']++ + chars[t[i]-'a']-- + } + for i := 0; i < 26; i++ { + if chars[i] != 0 { + return false + } + } + return true +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0243.Shortest Word Distance/README_EN.md b/assets/0200-0299/0243.Shortest Word Distance/README_EN.md new file mode 100644 index 00000000..572b7fd7 --- /dev/null +++ b/assets/0200-0299/0243.Shortest Word Distance/README_EN.md @@ -0,0 +1,84 @@ +# [243. Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance) + + + +## Description + +

Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

+ +

 

+

Example 1:

+ +
+Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
+Output: 3
+
+ +

Example 2:

+ +
+Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= wordsDict.length <= 3 * 104
  • +
  • 1 <= wordsDict[i].length <= 10
  • +
  • wordsDict[i] consists of lowercase English letters.
  • +
  • word1 and word2 are in wordsDict.
  • +
  • word1 != word2
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: + i1 = i2 = -1 + shortest_distance = len(wordsDict) + for i in range(len(wordsDict)): + if wordsDict[i] == word1: + i1 = i + elif wordsDict[i] == word2: + i2 = i + if i1 != -1 and i2 != -1: + shortest_distance = min(shortest_distance, abs(i1 - i2)) + return shortest_distance +``` + +### **Java** + +```java +class Solution { + public int shortestDistance(String[] wordsDict, String word1, String word2) { + int i1 = -1, i2 = -1; + int shortestDistance = wordsDict.length; + for (int i = 0; i < wordsDict.length; ++i) { + if (word1.equals(wordsDict[i])) { + i1 = i; + } else if (word2.equals(wordsDict[i])) { + i2 = i; + } + if (i1 != -1 && i2 != -1) { + shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2)); + } + } + return shortestDistance; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0244.Shortest Word Distance II/README_EN.md b/assets/0200-0299/0244.Shortest Word Distance II/README_EN.md new file mode 100644 index 00000000..594374ad --- /dev/null +++ b/assets/0200-0299/0244.Shortest Word Distance II/README_EN.md @@ -0,0 +1,124 @@ +# [244. Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii) + + + +## Description + +

Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.

+ +

Implement the WordDistance class:

+ +
    +
  • WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict.
  • +
  • int shortest(String word1, String word2) returns the shortest distance between word1 and word2 in the array wordsDict.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["WordDistance", "shortest", "shortest"]
+[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
+Output
+[null, 3, 1]
+
+Explanation
+WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
+wordDistance.shortest("coding", "practice"); // return 3
+wordDistance.shortest("makes", "coding");    // return 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= wordsDict.length <= 3 * 104
  • +
  • 1 <= wordsDict[i].length <= 10
  • +
  • wordsDict[i] consists of lowercase English letters.
  • +
  • word1 and word2 are in wordsDict.
  • +
  • word1 != word2
  • +
  • At most 5000 calls will be made to shortest.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class WordDistance: + + def __init__(self, wordsDict: List[str]): + self.words = {} + for i, word in enumerate(wordsDict): + indexes = self.words.get(word, []) + indexes.append(i) + self.words[word] = indexes + + def shortest(self, word1: str, word2: str) -> int: + idx1, idx2 = self.words[word1], self.words[word2] + i1 = i2 = 0 + shortest = float('inf') + while i1 < len(idx1) and i2 < len(idx2): + shortest = min(shortest, abs(idx1[i1] - idx2[i2])) + smaller = idx1[i1] < idx2[i2] + if smaller: + i1 += 1 + else: + i2 += 1 + return shortest + + +# Your WordDistance object will be instantiated and called as such: +# obj = WordDistance(wordsDict) +# param_1 = obj.shortest(word1,word2) +``` + +### **Java** + +```java +class WordDistance { + private Map> words; + + public WordDistance(String[] wordsDict) { + words = new HashMap<>(); + for (int i = 0; i < wordsDict.length; ++i) { + List indexes = words.getOrDefault(wordsDict[i], new ArrayList<>()); + indexes.add(i); + words.put(wordsDict[i], indexes); + } + } + + public int shortest(String word1, String word2) { + List idx1 = words.get(word1); + List idx2 = words.get(word2); + int i1 = 0, i2 = 0, shortest = Integer.MAX_VALUE; + while (i1 < idx1.size() && i2 < idx2.size()) { + shortest = Math.min(shortest, Math.abs(idx1.get(i1) - idx2.get(i2))); + boolean smaller = idx1.get(i1) < idx2.get(i2); + if (smaller) { + ++i1; + } else { + ++i2; + } + } + return shortest; + } +} + +/** + * Your WordDistance object will be instantiated and called as such: + * WordDistance obj = new WordDistance(wordsDict); + * int param_1 = obj.shortest(word1,word2); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0245.Shortest Word Distance III/README_EN.md b/assets/0200-0299/0245.Shortest Word Distance III/README_EN.md new file mode 100644 index 00000000..3eececbf --- /dev/null +++ b/assets/0200-0299/0245.Shortest Word Distance III/README_EN.md @@ -0,0 +1,97 @@ +# [245. Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii) + + + +## Description + +

Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

+ +

Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.

+ +

 

+

Example 1:

+
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
+Output: 1
+

Example 2:

+
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
+Output: 3
+
+

 

+

Constraints:

+ +
    +
  • 1 <= wordsDict.length <= 3 * 104
  • +
  • 1 <= wordsDict[i].length <= 10
  • +
  • wordsDict[i] consists of lowercase English letters.
  • +
  • word1 and word2 are in wordsDict.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: + i1 = i2 = -1 + shortest_distance = len(wordsDict) + same = word1 == word2 + for i in range(len(wordsDict)): + if same: + if word1 == wordsDict[i]: + if i1 != -1: + shortest_distance = min(shortest_distance, i - i1) + i1 = i + else: + if word1 == wordsDict[i]: + i1 = i + if word2 == wordsDict[i]: + i2 = i + if i1 != -1 and i2 != -1: + shortest_distance = min(shortest_distance, abs(i1 - i2)) + return shortest_distance +``` + +### **Java** + +```java +class Solution { + public int shortestWordDistance(String[] wordsDict, String word1, String word2) { + int i1 = -1, i2 = -1; + int shortestDistance = wordsDict.length; + boolean same = word1.equals(word2); + for (int i = 0; i < wordsDict.length; ++i) { + if (same) { + if (word1.equals(wordsDict[i])) { + if (i1 != -1) { + shortestDistance = Math.min(shortestDistance, i - i1); + } + i1 = i; + } + } else { + if (word1.equals(wordsDict[i])) { + i1 = i; + } + if (word2.equals(wordsDict[i])) { + i2 = i; + } + if (i1 != -1 && i2 != -1) { + shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2)); + } + } + } + return shortestDistance; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0246.Strobogrammatic Number/README_EN.md b/assets/0200-0299/0246.Strobogrammatic Number/README_EN.md new file mode 100644 index 00000000..ee46a593 --- /dev/null +++ b/assets/0200-0299/0246.Strobogrammatic Number/README_EN.md @@ -0,0 +1,97 @@ +# [246. Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number) + + + +## Description + +

Given a string num which represents an integer, return true if num is a strobogrammatic number.

+ +

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

+ +

 

+

Example 1:

+
Input: num = "69"
+Output: true
+

Example 2:

+
Input: num = "88"
+Output: true
+

Example 3:

+
Input: num = "962"
+Output: false
+

Example 4:

+
Input: num = "1"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= num.length <= 50
  • +
  • num consists of only digits.
  • +
  • num does not contain any leading zeros except for zero itself.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isStrobogrammatic(self, num: str) -> bool: + def match(a, b): + if a in {'0', '1', '8'}: + return a == b + if a == '6': + return b == '9' + if a == '9': + return b == '6' + return False + n = len(num) + i, j = 0, n - 1 + while i <= j: + if not match(num[i], num[j]): + return False + i += 1 + j -= 1 + return True +``` + +### **Java** + +```java +class Solution { + public boolean isStrobogrammatic(String num) { + int n = num.length(); + for (int i = 0, j = n - 1; i <= j; ++i, --j) { + if (!match(num.charAt(i), num.charAt(j))) return false; + } + return true; + } + + private boolean match(char a, char b) { + switch (a) { + case '0': + case '1': + case '8': + return a == b; + case '6': + return b == '9'; + case '9': + return b == '6'; + default: + return false; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0247.Strobogrammatic Number II/README_EN.md b/assets/0200-0299/0247.Strobogrammatic Number II/README_EN.md new file mode 100644 index 00000000..ff60a1f8 --- /dev/null +++ b/assets/0200-0299/0247.Strobogrammatic Number II/README_EN.md @@ -0,0 +1,49 @@ +# [247. Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii) + + + +## Description + +

Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order.

+ +

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

+ +

 

+

Example 1:

+
Input: n = 2
+Output: ["11","69","88","96"]
+

Example 2:

+
Input: n = 1
+Output: ["0","1","8"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 14
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0248.Strobogrammatic Number III/README_EN.md b/assets/0200-0299/0248.Strobogrammatic Number III/README_EN.md new file mode 100644 index 00000000..41e8aed1 --- /dev/null +++ b/assets/0200-0299/0248.Strobogrammatic Number III/README_EN.md @@ -0,0 +1,52 @@ +# [248. Strobogrammatic Number III](https://leetcode.com/problems/strobogrammatic-number-iii) + + + +## Description + +

Given two strings low and high that represent two integers low and high where low <= high, return the number of strobogrammatic numbers in the range [low, high].

+ +

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

+ +

 

+

Example 1:

+
Input: low = "50", high = "100"
+Output: 3
+

Example 2:

+
Input: low = "0", high = "0"
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= low.length, high.length <= 15
  • +
  • low and high consist of only digits.
  • +
  • low <= high
  • +
  • low and high do not contain any leading zeros except for zero itself.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0249.Group Shifted Strings/README_EN.md b/assets/0200-0299/0249.Group Shifted Strings/README_EN.md new file mode 100644 index 00000000..56a7442c --- /dev/null +++ b/assets/0200-0299/0249.Group Shifted Strings/README_EN.md @@ -0,0 +1,61 @@ +# [249. Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings) + + + +## Description + +

We can shift a string by shifting each of its letters to its successive letter.

+ +
    +
  • For example, "abc" can be shifted to be "bcd".
  • +
+ +

We can keep shifting the string to form a sequence.

+ +
    +
  • For example, we can keep shifting "abc" to form the sequence: "abc" -> "bcd" -> ... -> "xyz".
  • +
+ +

Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order.

+ +

 

+

Example 1:

+
Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"]
+Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]
+

Example 2:

+
Input: strings = ["a"]
+Output: [["a"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= strings.length <= 200
  • +
  • 1 <= strings[i].length <= 50
  • +
  • strings[i] consists of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0250.Count Univalue Subtrees/README_EN.md b/assets/0200-0299/0250.Count Univalue Subtrees/README_EN.md new file mode 100644 index 00000000..53d8ac0c --- /dev/null +++ b/assets/0200-0299/0250.Count Univalue Subtrees/README_EN.md @@ -0,0 +1,64 @@ +# [250. Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees) + + + +## Description + +

Given the root of a binary tree, return the number of uni-value subtrees.

+ +

A uni-value subtree means all nodes of the subtree have the same value.

+ +

 

+

Example 1:

+ +
+Input: root = [5,1,5,5,5,null,5]
+Output: 4
+
+ +

Example 2:

+ +
+Input: root = []
+Output: 0
+
+ +

Example 3:

+ +
+Input: root = [5,5,5,5,5,null,5]
+Output: 6
+
+ +

 

+

Constraints:

+ +
    +
  • The numbrt of the node in the tree will be in the range [0, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0250.Count Univalue Subtrees/images/unival_e1.jpg b/assets/0200-0299/0250.Count Univalue Subtrees/images/unival_e1.jpg new file mode 100644 index 00000000..9777a06a Binary files /dev/null and b/assets/0200-0299/0250.Count Univalue Subtrees/images/unival_e1.jpg differ diff --git a/assets/0200-0299/0251.Flatten 2D Vector/README_EN.md b/assets/0200-0299/0251.Flatten 2D Vector/README_EN.md new file mode 100644 index 00000000..efa77bac --- /dev/null +++ b/assets/0200-0299/0251.Flatten 2D Vector/README_EN.md @@ -0,0 +1,94 @@ +# [251. Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector) + + + +## Description + +

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

+ +

Implement the Vector2D class:

+ +
    +
  • Vector2D(int[][] vec) initializes the object with the 2D vector vec.
  • +
  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
  • +
  • hasNext() returns true if there are still some elements in the vector, and false otherwise.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
+[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
+Output
+[null, 1, 2, 3, true, true, 4, false]
+
+Explanation
+Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
+vector2D.next();    // return 1
+vector2D.next();    // return 2
+vector2D.next();    // return 3
+vector2D.hasNext(); // return True
+vector2D.hasNext(); // return True
+vector2D.next();    // return 4
+vector2D.hasNext(); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= vec.length <= 200
  • +
  • 0 <= vec[i].length <= 500
  • +
  • -500 <= vec[i][j] <= 500
  • +
  • At most 105 calls will be made to next and hasNext.
  • +
+ +

 

+

Follow up: As an added challenge, try to code it using only iterators in C++ or iterators in Java.

+ + +## Solutions + + + +### **Python3** + +```python +class Vector2D: + + def __init__(self, vec: List[List[int]]): + self.flatten = [] + for item in vec: + for e in item: + self.flatten.append(e) + self.cur = -1 + + def next(self) -> int: + self.cur += 1 + return self.flatten[self.cur] + + def hasNext(self) -> bool: + return self.cur < len(self.flatten) - 1 + + +# Your Vector2D object will be instantiated and called as such: +# obj = Vector2D(vec) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0252.Meeting Rooms/README_EN.md b/assets/0200-0299/0252.Meeting Rooms/README_EN.md new file mode 100644 index 00000000..9cf223f4 --- /dev/null +++ b/assets/0200-0299/0252.Meeting Rooms/README_EN.md @@ -0,0 +1,63 @@ +# [252. Meeting Rooms](https://leetcode.com/problems/meeting-rooms) + + + +## Description + +

Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.

+ +

 

+

Example 1:

+
Input: intervals = [[0,30],[5,10],[15,20]]
+Output: false
+

Example 2:

+
Input: intervals = [[7,10],[2,4]]
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 0 <= intervals.length <= 104
  • +
  • intervals[i].length == 2
  • +
  • 0 <= starti < endi <= 106
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canAttendMeetings(self, intervals: List[List[int]]) -> bool: + intervals.sort(key=lambda x: x[0]) + for i in range(len(intervals) - 1): + if intervals[i][1] > intervals[i + 1][0]: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean canAttendMeetings(int[][] intervals) { + Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); + for (int i = 0, n = intervals.length; i < n - 1; ++i) { + if (intervals[i][1] > intervals[i + 1][0]) return false; + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0253.Meeting Rooms II/README_EN.md b/assets/0200-0299/0253.Meeting Rooms II/README_EN.md new file mode 100644 index 00000000..0664a68e --- /dev/null +++ b/assets/0200-0299/0253.Meeting Rooms II/README_EN.md @@ -0,0 +1,48 @@ +# [253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii) + + + +## Description + +

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

+ +

 

+

Example 1:

+
Input: intervals = [[0,30],[5,10],[15,20]]
+Output: 2
+

Example 2:

+
Input: intervals = [[7,10],[2,4]]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 104
  • +
  • 0 <= starti < endi <= 106
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0254.Factor Combinations/README_EN.md b/assets/0200-0299/0254.Factor Combinations/README_EN.md new file mode 100644 index 00000000..135e5843 --- /dev/null +++ b/assets/0200-0299/0254.Factor Combinations/README_EN.md @@ -0,0 +1,61 @@ +# [254. Factor Combinations](https://leetcode.com/problems/factor-combinations) + + + +## Description + +

Numbers can be regarded as the product of their factors.

+ +
    +
  • For example, 8 = 2 x 2 x 2 = 2 x 4.
  • +
+ +

Given an integer n, return all possible combinations of its factors. You may return the answer in any order.

+ +

Note that the factors should be in the range [2, n - 1].

+ +

 

+

Example 1:

+
Input: n = 1
+Output: []
+

Example 2:

+
Input: n = 12
+Output: [[2,6],[3,4],[2,2,3]]
+

Example 3:

+
Input: n = 37
+Output: []
+

Example 4:

+
Input: n = 32
+Output: [[2,16],[4,8],[2,2,8],[2,4,4],[2,2,2,4],[2,2,2,2,2]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 108
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md b/assets/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md new file mode 100644 index 00000000..b9e6a4a1 --- /dev/null +++ b/assets/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md @@ -0,0 +1,59 @@ +# [255. Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree) + + + +## Description + +

Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.

+ +

 

+

Example 1:

+ +
+Input: preorder = [5,2,1,3,6]
+Output: true
+
+ +

Example 2:

+ +
+Input: preorder = [5,2,6,1,3]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 104
  • +
  • 1 <= preorder[i] <= 104
  • +
  • All the elements of preorder are unique.
  • +
+ +

 

+

Follow up: Could you do it using only constant space complexity?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/images/preorder-tree.jpg b/assets/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/images/preorder-tree.jpg new file mode 100644 index 00000000..90e5db7d Binary files /dev/null and b/assets/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/images/preorder-tree.jpg differ diff --git a/assets/0200-0299/0256.Paint House/README_EN.md b/assets/0200-0299/0256.Paint House/README_EN.md new file mode 100644 index 00000000..d77d8713 --- /dev/null +++ b/assets/0200-0299/0256.Paint House/README_EN.md @@ -0,0 +1,67 @@ +# [256. Paint House](https://leetcode.com/problems/paint-house) + + + +## Description + +

There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

+ +

The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs.

+ +
    +
  • For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on...
  • +
+ +

Return the minimum cost to paint all houses.

+ +

 

+

Example 1:

+ +
+Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
+Output: 10
+Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
+Minimum cost: 2 + 5 + 3 = 10.
+
+ +

Example 2:

+ +
+Input: costs = [[7,6,2]]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • costs.length == n
  • +
  • costs[i].length == 3
  • +
  • 1 <= n <= 100
  • +
  • 1 <= costs[i][j] <= 20
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0257.Binary Tree Paths/README_EN.md b/assets/0200-0299/0257.Binary Tree Paths/README_EN.md new file mode 100644 index 00000000..06d8a78e --- /dev/null +++ b/assets/0200-0299/0257.Binary Tree Paths/README_EN.md @@ -0,0 +1,147 @@ +# [257. Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) + + + +## Description + +

Given the root of a binary tree, return all root-to-leaf paths in any order.

+ +

A leaf is a node with no children.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,null,5]
+Output: ["1->2->5","1->3"]
+
+ +

Example 2:

+ +
+Input: root = [1]
+Output: ["1"]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def binaryTreePaths(self, root: TreeNode) -> List[str]: + def dfs(root): + if root is None: + return + path.append(str(root.val)) + if root.left is None and root.right is None: + res.append("->".join(path)) + dfs(root.left) + dfs(root.right) + path.pop() + res = [] + path = [] + dfs(root) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private List res; + private List path; + + public List binaryTreePaths(TreeNode root) { + if (root == null) return Collections.emptyList(); + res = new ArrayList<>(); + path = new ArrayList<>(); + dfs(root); + return res; + } + + private void dfs(TreeNode root) { + if (root == null) return; + path.add(String.valueOf(root.val)); + if (root.left == null && root.right == null) { + res.add(String.join("->", path)); + } + dfs(root.left); + dfs(root.right); + path.remove(path.size() - 1); + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function binaryTreePaths(root: TreeNode | null): string[] { + let ans = []; + let pre = ''; + dfs(root, pre, ans); + return ans; +}; + +function dfs(root: TreeNode | null, pre: string, ans: string[]): void { + if (root == null) return; + let val = String(root.val); + pre = pre.length > 0 ? `${pre}->${val}` : pre + val; + // 叶子节点 + if (root.left == null && root.right == null) { + ans.push(pre); + return; + } + dfs(root.left, pre, ans); + dfs(root.right, pre, ans); +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0257.Binary Tree Paths/images/paths-tree.jpg b/assets/0200-0299/0257.Binary Tree Paths/images/paths-tree.jpg new file mode 100644 index 00000000..1073fe79 Binary files /dev/null and b/assets/0200-0299/0257.Binary Tree Paths/images/paths-tree.jpg differ diff --git a/assets/0200-0299/0258.Add Digits/README_EN.md b/assets/0200-0299/0258.Add Digits/README_EN.md new file mode 100644 index 00000000..30f2614c --- /dev/null +++ b/assets/0200-0299/0258.Add Digits/README_EN.md @@ -0,0 +1,78 @@ +# [258. Add Digits](https://leetcode.com/problems/add-digits) + + + +## Description + +

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

+ +

 

+

Example 1:

+ +
+Input: num = 38
+Output: 2
+Explanation: The process is
+38 --> 3 + 8 --> 11
+11 --> 1 + 1 --> 2 
+Since 2 has only one digit, return it.
+
+ +

Example 2:

+ +
+Input: num = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 231 - 1
  • +
+ +

 

+

Follow up: Could you do it without any loop/recursion in O(1) runtime?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def addDigits(self, num: int) -> int: + return 0 if num == 0 else (num - 1) % 9 + 1 +``` + +### **Java** + +```java +class Solution { + public int addDigits(int num) { + return (num - 1) % 9 + 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int addDigits(int num) { + return (num - 1) % 9 + 1; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0259.3Sum Smaller/README_EN.md b/assets/0200-0299/0259.3Sum Smaller/README_EN.md new file mode 100644 index 00000000..fafede5c --- /dev/null +++ b/assets/0200-0299/0259.3Sum Smaller/README_EN.md @@ -0,0 +1,139 @@ +# [259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller) + + + +## Description + +

Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

+ +

Follow up: Could you solve it in O(n2) runtime?

+ +

 

+

Example 1:

+ +
+Input: nums = [-2,0,1,3], target = 2
+Output: 2
+Explanation: Because there are two triplets which sums are less than 2:
+[-2,0,1]
+[-2,0,3]
+
+ +

Example 2:

+ +
+Input: nums = [], target = 0
+Output: 0
+
+ +

Example 3:

+ +
+Input: nums = [0], target = 0
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 0 <= n <= 300
  • +
  • -100 <= nums[i] <= 100
  • +
  • -100 <= target <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def threeSumSmaller(self, nums: List[int], target: int) -> int: + def threeSumSmaller(nums, start, end, target): + count = 0 + while start < end: + if nums[start] + nums[end] < target: + count += (end - start) + start += 1 + else: + end -= 1 + return count + + nums.sort() + n, count = len(nums), 0 + for i in range(n - 2): + count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]) + return count +``` + +### **Java** + +```java +class Solution { + public int threeSumSmaller(int[] nums, int target) { + Arrays.sort(nums); + int n = nums.length; + int count = 0; + for (int i = 0; i < n - 2; ++i) { + count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]); + } + return count; + } + + private int threeSumSmaller(int[] nums, int start, int end, int target) { + int count = 0; + while (start < end) { + if (nums[start] + nums[end] < target) { + count += (end - start); + ++start; + } else { + --end; + } + } + return count; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumSmaller = function (nums, target) { + let len = nums.length; + if (len < 3) return 0; + nums.sort((a, b) => a - b) + let res = 0; + for (let i = 0; i < len - 2; i++) { + let left = i + 1, right = len - 1; + if (nums[i] + nums[left] + nums[i + 2] >= target) break; + while (left < right) { + if (nums[i] + nums[left] + nums[right] < target) { + res += (right - left); + left++; + continue; + } else { + right--; + continue; + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0260.Single Number III/README_EN.md b/assets/0200-0299/0260.Single Number III/README_EN.md new file mode 100644 index 00000000..c6018ae0 --- /dev/null +++ b/assets/0200-0299/0260.Single Number III/README_EN.md @@ -0,0 +1,93 @@ +# [260. Single Number III](https://leetcode.com/problems/single-number-iii) + + + +## Description + +

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

+ +

Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,1,3,2,5]
+Output: [3,5]
+Explanation:  [5, 3] is also a valid answer.
+
+ +

Example 2:

+ +
+Input: nums = [-1,0]
+Output: [-1,0]
+
+ +

Example 3:

+ +
+Input: nums = [0,1]
+Output: [1,0]
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 3 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • Each integer in nums will appear twice, only two integers will appear once.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + eor = 0 + for num in nums: + eor ^= num + diff = eor & (~eor + 1) + a = 0 + for num in nums: + if (num & diff) == 0: + a ^= num + b = eor ^ a + return [a, b] +``` + +### **Java** + +```java +class Solution { + public int[] singleNumber(int[] nums) { + int eor = 0; + for (int num : nums) { + eor ^= num; + } + int diff = eor & (~eor + 1); + int a = 0; + for (int num : nums) { + if ((num & diff) == 0) { + a ^= num; + } + } + int b = eor ^ a; + return new int[]{a, b}; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0261.Graph Valid Tree/README_EN.md b/assets/0200-0299/0261.Graph Valid Tree/README_EN.md new file mode 100644 index 00000000..d3439019 --- /dev/null +++ b/assets/0200-0299/0261.Graph Valid Tree/README_EN.md @@ -0,0 +1,61 @@ +# [261. Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree) + + + +## Description + +

You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.

+ +

Return true if the edges of the given graph make up a valid tree, and false otherwise.

+ +

 

+

Example 1:

+ +
+Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
+Output: true
+
+ +

Example 2:

+ +
+Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= 2000 <= n
  • +
  • 0 <= edges.length <= 5000
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • There are no self-loops or repeated edges.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0261.Graph Valid Tree/images/tree1-graph.jpg b/assets/0200-0299/0261.Graph Valid Tree/images/tree1-graph.jpg new file mode 100644 index 00000000..f504afa2 Binary files /dev/null and b/assets/0200-0299/0261.Graph Valid Tree/images/tree1-graph.jpg differ diff --git a/assets/0200-0299/0261.Graph Valid Tree/images/tree2-graph.jpg b/assets/0200-0299/0261.Graph Valid Tree/images/tree2-graph.jpg new file mode 100644 index 00000000..3a6b0c05 Binary files /dev/null and b/assets/0200-0299/0261.Graph Valid Tree/images/tree2-graph.jpg differ diff --git a/assets/0200-0299/0262.Trips and Users/README_EN.md b/assets/0200-0299/0262.Trips and Users/README_EN.md new file mode 100644 index 00000000..8b9265dd --- /dev/null +++ b/assets/0200-0299/0262.Trips and Users/README_EN.md @@ -0,0 +1,122 @@ +# [262. Trips and Users](https://leetcode.com/problems/trips-and-users) + + + +## Description + +

Table: Trips

+ +
++-------------+----------+
+| Column Name | Type     |
++-------------+----------+
+| Id          | int      |
+| Client_Id   | int      |
+| Driver_Id   | int      |
+| City_Id     | int      |
+| Status      | enum     |
+| Request_at  | date     |     
++-------------+----------+
+Id is the primary key for this table.
+The table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are foreign keys to the Users_Id at the Users table.
+Status is an ENUM type of (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’).
+
+ +

 

+ +

Table: Users

+ +
++-------------+----------+
+| Column Name | Type     |
++-------------+----------+
+| Users_Id    | int      |
+| Banned      | enum     |
+| Role        | enum     |
++-------------+----------+
+Users_Id is the primary key for this table.
+The table holds all users. Each user has a unique Users_Id, and Role is an ENUM type of (‘client’, ‘driver’, ‘partner’).
+Status is an ENUM type of (‘Yes’, ‘No’).
+
+ +

 

+ +

Write a SQL query to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01" and "2013-10-03".

+ +

The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.

+ +

Return the result table in any order. Round Cancellation Rate to two decimal points.

+ +

The query result format is in the following example:

+ +

 

+ +
+Trips table:
++----+-----------+-----------+---------+---------------------+------------+
+| Id | Client_Id | Driver_Id | City_Id | Status              | Request_at |
++----+-----------+-----------+---------+---------------------+------------+
+| 1  | 1         | 10        | 1       | completed           | 2013-10-01 |
+| 2  | 2         | 11        | 1       | cancelled_by_driver | 2013-10-01 |
+| 3  | 3         | 12        | 6       | completed           | 2013-10-01 |
+| 4  | 4         | 13        | 6       | cancelled_by_client | 2013-10-01 |
+| 5  | 1         | 10        | 1       | completed           | 2013-10-02 |
+| 6  | 2         | 11        | 6       | completed           | 2013-10-02 |
+| 7  | 3         | 12        | 6       | completed           | 2013-10-02 |
+| 8  | 2         | 12        | 12      | completed           | 2013-10-03 |
+| 9  | 3         | 10        | 12      | completed           | 2013-10-03 |
+| 10 | 4         | 13        | 12      | cancelled_by_driver | 2013-10-03 |
++----+-----------+-----------+---------+---------------------+------------+
+
+Users table:
++----------+--------+--------+
+| Users_Id | Banned | Role   |
++----------+--------+--------+
+| 1        | No     | client |
+| 2        | Yes    | client |
+| 3        | No     | client |
+| 4        | No     | client |
+| 10       | No     | driver |
+| 11       | No     | driver |
+| 12       | No     | driver |
+| 13       | No     | driver |
++----------+--------+--------+
+
+Result table:
++------------+-------------------+
+| Day        | Cancellation Rate |
++------------+-------------------+
+| 2013-10-01 | 0.33              |
+| 2013-10-02 | 0.00              |
+| 2013-10-03 | 0.50              |
++------------+-------------------+
+
+On 2013-10-01:
+  - There were 4 requests in total, 2 of which were canceled.
+  - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation.
+  - Hence there are 3 unbanned requests in total, 1 of which was canceled.
+  - The Cancellation Rate is (1 / 3) = 0.33
+On 2013-10-02:
+  - There were 3 requests in total, 0 of which were canceled.
+  - The request with Id=6 was made by a banned client, so it is ignored.
+  - Hence there are 2 unbanned requests in total, 0 of which were canceled.
+  - The Cancellation Rate is (0 / 2) = 0.00
+On 2013-10-03:
+  - There were 3 requests in total, 1 of which was canceled.
+  - The request with Id=8 was made by a banned client, so it is ignored.
+  - Hence there are 2 unbanned request in total, 1 of which were canceled.
+  - The Cancellation Rate is (1 / 2) = 0.50
+
+ + +## Solutions + + + +### **SQL** + +``` + +``` + + diff --git a/assets/0200-0299/0263.Ugly Number/README_EN.md b/assets/0200-0299/0263.Ugly Number/README_EN.md new file mode 100644 index 00000000..f90902f2 --- /dev/null +++ b/assets/0200-0299/0263.Ugly Number/README_EN.md @@ -0,0 +1,140 @@ +# [263. Ugly Number](https://leetcode.com/problems/ugly-number) + + + +## Description + +

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

+ +

Given an integer n, return true if n is an ugly number.

+ +

 

+

Example 1:

+ +
+Input: n = 6
+Output: true
+Explanation: 6 = 2 × 3
+ +

Example 2:

+ +
+Input: n = 8
+Output: true
+Explanation: 8 = 2 × 2 × 2
+
+ +

Example 3:

+ +
+Input: n = 14
+Output: false
+Explanation: 14 is not ugly since it includes the prime factor 7.
+
+ +

Example 4:

+ +
+Input: n = 1
+Output: true
+Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isUgly(self, n: int) -> bool: + if n < 1: + return False + while n % 2 == 0: + n //= 2 + while n % 3 == 0: + n //= 3 + while n % 5 == 0: + n //= 5 + return n == 1 +``` + +### **Java** + +```java +class Solution { + public boolean isUgly(int n) { + if (n < 1) return false; + while (n % 2 == 0) { + n /= 2; + } + while (n % 3 == 0) { + n /= 3; + } + while (n % 5 == 0) { + n /= 5; + } + return n == 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isUgly(int n) { + if (n < 1) return false; + while (n % 2 == 0) { + n /= 2; + } + while (n % 3 == 0) { + n /= 3; + } + while (n % 5 == 0) { + n /= 5; + } + return n == 1; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isUgly = function (n) { + if (n < 1) return false; + while (n % 2 == 0) { + n /= 2; + } + while (n % 3 == 0) { + n /= 3; + } + while (n % 5 == 0) { + n /= 5; + } + return n == 1; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0264.Ugly Number II/README_EN.md b/assets/0200-0299/0264.Ugly Number II/README_EN.md new file mode 100644 index 00000000..84c3774d --- /dev/null +++ b/assets/0200-0299/0264.Ugly Number II/README_EN.md @@ -0,0 +1,193 @@ +# [264. Ugly Number II](https://leetcode.com/problems/ugly-number-ii) + + + +## Description + +

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

+ +

Given an integer n, return the nth ugly number.

+ +

 

+

Example 1:

+ +
+Input: n = 10
+Output: 12
+Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 1
+Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 1690
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] +``` + +### **Java** + +```java +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {number} + */ +var nthUglyNumber = function (n) { + let dp = [1]; + let p2 = 0, + p3 = 0, + p5 = 0; + for (let i = 1; i < n; ++i) { + const next2 = dp[p2] * 2, + next3 = dp[p3] * 3, + next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + dp.push(dp[i]); + } + return dp[n - 1]; +}; +``` + +### **Go** + +```go +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int NthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) + { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.Min(next2, Math.Min(next3, next5)); + if (dp[i] == next2) + { + ++p2; + } + if (dp[i] == next3) + { + ++p3; + } + if (dp[i] == next5) + { + ++p5; + } + } + return dp[n - 1]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0265.Paint House II/README_EN.md b/assets/0200-0299/0265.Paint House II/README_EN.md new file mode 100644 index 00000000..020edbe8 --- /dev/null +++ b/assets/0200-0299/0265.Paint House II/README_EN.md @@ -0,0 +1,72 @@ +# [265. Paint House II](https://leetcode.com/problems/paint-house-ii) + + + +## Description + +

There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

+ +

The cost of painting each house with a certain color is represented by an n x k cost matrix costs.

+ +
    +
  • For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on...
  • +
+ +

Return the minimum cost to paint all houses.

+ +

 

+

Example 1:

+ +
+Input: costs = [[1,5,3],[2,9,4]]
+Output: 5
+Explanation:
+Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; 
+Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.
+
+ +

Example 2:

+ +
+Input: costs = [[1,3],[2,4]]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • costs.length == n
  • +
  • costs[i].length == k
  • +
  • 1 <= n <= 100
  • +
  • 1 <= k <= 20
  • +
  • 1 <= costs[i][j] <= 20
  • +
+ +

 

+

Follow up: Could you solve it in O(nk) runtime?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0266.Palindrome Permutation/README_EN.md b/assets/0200-0299/0266.Palindrome Permutation/README_EN.md new file mode 100644 index 00000000..5b45178b --- /dev/null +++ b/assets/0200-0299/0266.Palindrome Permutation/README_EN.md @@ -0,0 +1,86 @@ +# [266. Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) + + + +## Description + +

Given a string s, return true if a permutation of the string could form a palindrome.

+ +

 

+

Example 1:

+ +
+Input: s = "code"
+Output: false
+
+ +

Example 2:

+ +
+Input: s = "aab"
+Output: true
+
+ +

Example 3:

+ +
+Input: s = "carerac"
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5000
  • +
  • s consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canPermutePalindrome(self, s: str) -> bool: + mapper = {} + for ch in s: + mapper[ch] = mapper.get(ch, 0) + 1 + cnt = 0 + for _, v in mapper.items(): + if v % 2 != 0: + cnt += 1 + return cnt <= 1 +``` + +### **Java** + +```java +class Solution { + public boolean canPermutePalindrome(String s) { + Map map = new HashMap<>(); + for (int i = 0, n = s.length(); i < n; ++i) { + char ch = s.charAt(i); + map.put(ch, map.getOrDefault(ch, 0) + 1); + } + int cnt = 0; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() % 2 != 0) { + ++cnt; + } + } + return cnt <= 1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0267.Palindrome Permutation II/README_EN.md b/assets/0200-0299/0267.Palindrome Permutation II/README_EN.md new file mode 100644 index 00000000..29ca5028 --- /dev/null +++ b/assets/0200-0299/0267.Palindrome Permutation II/README_EN.md @@ -0,0 +1,50 @@ +# [267. Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii) + + + +## Description + +

Given a string s, return all the palindromic permutations (without duplicates) of it.

+ +

You may return the answer in any order. If s has no palindromic permutation, return an empty list.

+ +

 

+

Example 1:

+
Input: s = "aabb"
+Output: ["abba","baab"]
+

Example 2:

+
Input: s = "abc"
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 16
  • +
  • s consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0268.Missing Number/README_EN.md b/assets/0200-0299/0268.Missing Number/README_EN.md new file mode 100644 index 00000000..08348e75 --- /dev/null +++ b/assets/0200-0299/0268.Missing Number/README_EN.md @@ -0,0 +1,106 @@ +# [268. Missing Number](https://leetcode.com/problems/missing-number) + + + +## Description + +

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

+ +

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

+ +

 

+

Example 1:

+ +
+Input: nums = [3,0,1]
+Output: 2
+Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
+
+ +

Example 2:

+ +
+Input: nums = [0,1]
+Output: 2
+Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
+
+ +

Example 3:

+ +
+Input: nums = [9,6,4,2,3,5,7,0,1]
+Output: 8
+Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
+
+ +

Example 4:

+ +
+Input: nums = [0]
+Output: 1
+Explanation: n = 1 since there is 1 number, so all numbers are in the range [0,1]. 1 is the missing number in the range since it does not appear in nums.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 104
  • +
  • 0 <= nums[i] <= n
  • +
  • All the numbers of nums are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def missingNumber(self, nums: List[int]) -> int: + res = len(nums) + for i, v in enumerate(nums): + res ^= (i ^ v) + return res +``` + +### **Java** + +- XOR + +```java +class Solution { + public int missingNumber(int[] nums) { + int res = nums.length; + for (int i = 0, n = res; i < n; ++i) { + res ^= (i ^ nums[i]); + } + return res; + } +} +``` + +- Math + +```java +class Solution { + public int missingNumber(int[] nums) { + int res = nums.length; + for (int i = 0, n = res; i < n; ++i) { + res += (i - nums[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0269.Alien Dictionary/README_EN.md b/assets/0200-0299/0269.Alien Dictionary/README_EN.md new file mode 100644 index 00000000..29688a19 --- /dev/null +++ b/assets/0200-0299/0269.Alien Dictionary/README_EN.md @@ -0,0 +1,70 @@ +# [269. Alien Dictionary](https://leetcode.com/problems/alien-dictionary) + + + +## Description + +

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.

+ +

You are given a list of strings words from the alien language's dictionary, where the strings in words are sorted lexicographically by the rules of this new language.

+ +

Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there is no solution, return "". If there are multiple solutions, return any of them.

+ +

A string s is lexicographically smaller than a string t if at the first letter where they differ, the letter in s comes before the letter in t in the alien language. If the first min(s.length, t.length) letters are the same, then s is smaller if and only if s.length < t.length.

+ +

 

+

Example 1:

+ +
+Input: words = ["wrt","wrf","er","ett","rftt"]
+Output: "wertf"
+
+ +

Example 2:

+ +
+Input: words = ["z","x"]
+Output: "zx"
+
+ +

Example 3:

+ +
+Input: words = ["z","x","z"]
+Output: ""
+Explanation: The order is invalid, so return "".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 100
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md b/assets/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md new file mode 100644 index 00000000..77a19f21 --- /dev/null +++ b/assets/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md @@ -0,0 +1,212 @@ +# [270. Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value) + + + +## Description + +

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

+ +

 

+

Example 1:

+ +
+Input: root = [4,2,5,1,3], target = 3.714286
+Output: 4
+
+ +

Example 2:

+ +
+Input: root = [1], target = 4.428571
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 0 <= Node.val <= 109
  • +
  • -109 <= target <= 109
  • +
+ + +## Solutions + +Binary search. + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def closestValue(self, root: TreeNode, target: float) -> int: + res, min_diff = root.val, float('inf') + while root: + val = abs(root.val - target) + if min_diff > val: + min_diff = val + res = root.val + if root.val > target: + root = root.left + else: + root = root.right + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int closestValue(TreeNode root, double target) { + int res = root.val; + double minDiff = Double.MAX_VALUE; + while (root != null) { + double val = Math.abs(root.val - target); + if (minDiff > val) { + minDiff = val; + res = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} target + * @return {number} + */ +var closestValue = function(root, target) { + let res = root.val; + let minDiff = Math.abs(root.val - target); + while (root) { + const val = Math.abs(root.val - target); + if (minDiff > val) { + minDiff = val; + res = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return res; +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int closestValue(TreeNode* root, double target) { + int res = root->val; + double minDiff = abs(root->val - target); + while (root != nullptr) { + double val = abs(root->val - target); + if (minDiff > val) { + minDiff = val; + res = root->val; + } + if (root->val > target) { + root = root->left; + } else { + root = root->right; + } + } + return res; + } +}; +``` + +### **Go** + +```go +import "math" + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func closestValue(root *TreeNode, target float64) int { + res := root.Val + minDiff := math.Abs(float64(root.Val) - float64(target)) + for root != nil { + val := math.Abs(float64(root.Val) - float64(target)) + if minDiff > val { + minDiff = val + res = root.Val + } + if float64(root.Val) > target { + root = root.Left + } else { + root = root.Right + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0270.Closest Binary Search Tree Value/images/closest1-1-tree.jpg b/assets/0200-0299/0270.Closest Binary Search Tree Value/images/closest1-1-tree.jpg new file mode 100644 index 00000000..7abeb628 Binary files /dev/null and b/assets/0200-0299/0270.Closest Binary Search Tree Value/images/closest1-1-tree.jpg differ diff --git a/assets/0200-0299/0271.Encode and Decode Strings/README_EN.md b/assets/0200-0299/0271.Encode and Decode Strings/README_EN.md new file mode 100644 index 00000000..4118ecd0 --- /dev/null +++ b/assets/0200-0299/0271.Encode and Decode Strings/README_EN.md @@ -0,0 +1,105 @@ +# [271. Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings) + + + +## Description + +

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

+ +

Machine 1 (sender) has the function:

+ +
+string encode(vector<string> strs) {
+  // ... your code
+  return encoded_string;
+}
+Machine 2 (receiver) has the function: + +
+vector<string> decode(string s) {
+  //... your code
+  return strs;
+}
+
+ +

So Machine 1 does:

+ +
+string encoded_string = encode(strs);
+
+ +

and Machine 2 does:

+ +
+vector<string> strs2 = decode(encoded_string);
+
+ +

strs2 in Machine 2 should be the same as strs in Machine 1.

+ +

Implement the encode and decode methods.

+ +

 

+

Example 1:

+ +
+Input: dummy_input = ["Hello","World"]
+Output: ["Hello","World"]
+Explanation:
+Machine 1:
+Codec encoder = new Codec();
+String msg = encoder.encode(strs);
+Machine 1 ---msg---> Machine 2
+
+Machine 2:
+Codec decoder = new Codec();
+String[] strs = decoder.decode(msg);
+
+ +

Example 2:

+ +
+Input: dummy_input = [""]
+Output: [""]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 200
  • +
  • 0 <= strs[i].length <= 200
  • +
  • strs[i] contains any possible characters out of 256 valid ASCII characters.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you write a generalized algorithm to work on any possible characters?
  • +
  • Could you solve the problem without using any serialize methods (such as eval)?
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md b/assets/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md new file mode 100644 index 00000000..f0a40fe6 --- /dev/null +++ b/assets/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md @@ -0,0 +1,62 @@ +# [272. Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii) + + + +## Description + +

Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order.

+ +

You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

+ +

 

+

Example 1:

+ +
+Input: root = [4,2,5,1,3], target = 3.714286, k = 2
+Output: [4,3]
+
+ +

Example 2:

+ +
+Input: root = [1], target = 0.000000, k = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is n.
  • +
  • 1 <= k <= n <= 104.
  • +
  • 0 <= Node.val <= 109
  • +
  • -109 <= target <= 109
  • +
+ +

 

+

Follow up: Assume that the BST is balanced. Could you solve it in less than O(n) runtime (where n = total nodes)?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0272.Closest Binary Search Tree Value II/images/closest1-1-tree.jpg b/assets/0200-0299/0272.Closest Binary Search Tree Value II/images/closest1-1-tree.jpg new file mode 100644 index 00000000..7abeb628 Binary files /dev/null and b/assets/0200-0299/0272.Closest Binary Search Tree Value II/images/closest1-1-tree.jpg differ diff --git a/assets/0200-0299/0273.Integer to English Words/README_EN.md b/assets/0200-0299/0273.Integer to English Words/README_EN.md new file mode 100644 index 00000000..c172854e --- /dev/null +++ b/assets/0200-0299/0273.Integer to English Words/README_EN.md @@ -0,0 +1,53 @@ +# [273. Integer to English Words](https://leetcode.com/problems/integer-to-english-words) + + + +## Description + +

Convert a non-negative integer num to its English words representation.

+ +

 

+

Example 1:

+
Input: num = 123
+Output: "One Hundred Twenty Three"
+

Example 2:

+
Input: num = 12345
+Output: "Twelve Thousand Three Hundred Forty Five"
+

Example 3:

+
Input: num = 1234567
+Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
+

Example 4:

+
Input: num = 1234567891
+Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
+
+

 

+

Constraints:

+ +
    +
  • 0 <= num <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0274.H-Index/README_EN.md b/assets/0200-0299/0274.H-Index/README_EN.md new file mode 100644 index 00000000..15b41739 --- /dev/null +++ b/assets/0200-0299/0274.H-Index/README_EN.md @@ -0,0 +1,155 @@ +# [274. H-Index](https://leetcode.com/problems/h-index) + + + +## Description + +

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index.

+ +

According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.

+ +

If there are several possible values for h, the maximum one is taken as the h-index.

+ +

 

+

Example 1:

+ +
+Input: citations = [3,0,6,1,5]
+Output: 3
+Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
+Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
+
+ +

Example 2:

+ +
+Input: citations = [1,3,1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == citations.length
  • +
  • 1 <= n <= 5000
  • +
  • 0 <= citations[i] <= 1000
  • +
+ + +## Solutions + +The simplest solution is to judge after sort, but because `H` cannot be greater than the total number of papers, it can be optimized by counting sort. + + + +### **Python3** + +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + cnt = [0 for i in range(n + 1)] + for c in citations: + if c <= n: + cnt[c] += 1 + else: + cnt[n] += 1 + sum = 0 + for i in range(n, -1, -1): + sum += cnt[i] + if sum >= i: + return i + return 0 +``` + +### **Java** + +```java +class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int[] cnt = new int[n + 1]; + for (int c : citations) { + if (c <= n) { + ++cnt[c]; + } else { + ++cnt[n]; + } + } + int sum = 0; + for (int i = n; i >= 0; --i) { + sum += cnt[i]; + if (sum >= i) { + return i; + } + } + return 0; + } +} +``` + +### **TypeScript** + +```ts +function hIndex(citations: number[]): number { + let n = citations.length; + let cnt = new Array(n + 1).fill(0); + for (let c of citations) { + if ( c <= n) { + ++cnt[c]; + } else { + ++cnt[n]; + } + } + let sum = 0; + for (let i = n; i > -1; --i) { + sum += cnt[i]; + if (sum >= i) { + return i; + } + } + return 0; +}; +``` + +### **Go** + +Use binary search to locate the maximum value that meets the conditions + +```go +func hIndex(citations []int) int { + n := len(citations) + left, right := 0, n + for left+1 < right { + mid := int(uint(left+right) >> 1) + if check(citations, mid) { + left = mid + } else { + right = mid + } + } + if check(citations, right) { + return right + } + return left +} + +func check(citations []int, mid int) bool { + cnt := 0 + for _, citation := range citations { + if citation >= mid { + cnt++ + } + } + return cnt >= mid +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0275.H-Index II/README_EN.md b/assets/0200-0299/0275.H-Index II/README_EN.md new file mode 100644 index 00000000..6c69732d --- /dev/null +++ b/assets/0200-0299/0275.H-Index II/README_EN.md @@ -0,0 +1,131 @@ +# [275. H-Index II](https://leetcode.com/problems/h-index-ii) + + + +## Description + +

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in an ascending order, return compute the researcher's h-index.

+ +

According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.

+ +

If there are several possible values for h, the maximum one is taken as the h-index.

+ +

 

+

Example 1:

+ +
+Input: citations = [0,1,3,5,6]
+Output: 3
+Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.
+Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
+
+ +

Example 2:

+ +
+Input: citations = [1,2,100]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • n == citations.length
  • +
  • 1 <= n <= 105
  • +
  • 0 <= citations[i] <= 1000
  • +
  • citations is sorted in ascending order.
  • +
+ +

 

+

Follow up: Could you solve it in logarithmic time complexity?

+ + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + left, right = 0, n + while left < right: + mid = (left + right) >> 1 + if citations[mid] >= n - mid: + right = mid + else: + left = mid + 1 + return n - left +``` + +### **Java** + +```java +class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (citations[mid] >= n - mid) { + right = mid; + } else { + left = mid + 1; + } + } + return n - left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int hIndex(vector& citations) { + int n = citations.size(); + int left = 0, right = n; + while (left < right) { + int mid = left + right >> 1; + if (citations[mid] >= n - mid) { + right = mid; + } else { + left = mid + 1; + } + } + return n - left; + } +}; +``` + +### **Go** + +```go +func hIndex(citations []int) int { + n := len(citations) + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if citations[mid] >= n-mid { + right = mid + } else { + left = mid + 1 + } + } + return n - left +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0276.Paint Fence/README_EN.md b/assets/0200-0299/0276.Paint Fence/README_EN.md new file mode 100644 index 00000000..93411e6e --- /dev/null +++ b/assets/0200-0299/0276.Paint Fence/README_EN.md @@ -0,0 +1,72 @@ +# [276. Paint Fence](https://leetcode.com/problems/paint-fence) + + + +## Description + +

You are painting a fence of n posts with k different colors. You must paint the posts following these rules:

+ +
    +
  • Every post must be painted exactly one color.
  • +
  • At most one pair of adjacent fence posts can have the same color.
  • +
+ +

Given the two integers n and k, return the number of ways you can paint the fence.

+ +

 

+

Example 1:

+ +
+Input: n = 3, k = 2
+Output: 6
+Explanation: All the possibilities are shown.
+Note that painting all the posts red or all the posts green is invalid because there can only be at most one pair of adjacent posts that are the same color.
+
+ +

Example 2:

+ +
+Input: n = 1, k = 1
+Output: 1
+
+ +

Example 3:

+ +
+Input: n = 7, k = 2
+Output: 42
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 50
  • +
  • 1 <= k <= 105
  • +
  • The answer is guaranteed to be in the range [0, 231 - 1] for the given n and k.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0276.Paint Fence/images/paintfenceex1.png b/assets/0200-0299/0276.Paint Fence/images/paintfenceex1.png new file mode 100644 index 00000000..4473e017 Binary files /dev/null and b/assets/0200-0299/0276.Paint Fence/images/paintfenceex1.png differ diff --git a/assets/0200-0299/0277.Find the Celebrity/README_EN.md b/assets/0200-0299/0277.Find the Celebrity/README_EN.md new file mode 100644 index 00000000..933e7cfc --- /dev/null +++ b/assets/0200-0299/0277.Find the Celebrity/README_EN.md @@ -0,0 +1,66 @@ +# [277. Find the Celebrity](https://leetcode.com/problems/find-the-celebrity) + + + +## Description + +

Suppose you are at a party with n people (labeled from 0 to n - 1), and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her, but he/she does not know any of them.

+ +

Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).

+ +

You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.

+ +

 

+

Example 1:

+ +
+Input: graph = [[1,1,0],[0,1,0],[1,1,1]]
+Output: 1
+Explanation: There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody.
+
+ +

Example 2:

+ +
+Input: graph = [[1,0,1],[1,1,0],[0,1,1]]
+Output: -1
+Explanation: There is no celebrity.
+
+ +

 

+

Constraints:

+ +
    +
  • n == graph.length
  • +
  • n == graph[i].length
  • +
  • 2 <= n <= 100
  • +
  • graph[i][j] is 0 or 1.
  • +
  • graph[i][i] == 1
  • +
+ +

 

+Follow up: If the maximum number of allowed calls to the API knows is 3 * n, could you find a solution without exceeding the maximum number of calls? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0277.Find the Celebrity/images/277_example_1_bold.png b/assets/0200-0299/0277.Find the Celebrity/images/277_example_1_bold.png new file mode 100644 index 00000000..f4f70164 Binary files /dev/null and b/assets/0200-0299/0277.Find the Celebrity/images/277_example_1_bold.png differ diff --git a/assets/0200-0299/0277.Find the Celebrity/images/277_example_2.png b/assets/0200-0299/0277.Find the Celebrity/images/277_example_2.png new file mode 100644 index 00000000..00ea91bd Binary files /dev/null and b/assets/0200-0299/0277.Find the Celebrity/images/277_example_2.png differ diff --git a/assets/0200-0299/0278.First Bad Version/README_EN.md b/assets/0200-0299/0278.First Bad Version/README_EN.md new file mode 100644 index 00000000..d91fdcb2 --- /dev/null +++ b/assets/0200-0299/0278.First Bad Version/README_EN.md @@ -0,0 +1,183 @@ +# [278. First Bad Version](https://leetcode.com/problems/first-bad-version) + + + +## Description + +

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

+ +

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

+ +

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

+ +

 

+

Example 1:

+ +
+Input: n = 5, bad = 4
+Output: 4
+Explanation:
+call isBadVersion(3) -> false
+call isBadVersion(5) -> true
+call isBadVersion(4) -> true
+Then 4 is the first bad version.
+
+ +

Example 2:

+ +
+Input: n = 1, bad = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= bad <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return an integer +# def isBadVersion(version): + +class Solution: + def firstBadVersion(self, n): + """ + :type n: int + :rtype: int + """ + left, right = 1, n + while left < right: + mid = (left + right) >> 1 + if isBadVersion(mid): + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +/* The isBadVersion API is defined in the parent class VersionControl. + boolean isBadVersion(int version); */ + +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int left = 1, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +// The API isBadVersion is defined for you. +// bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for isBadVersion() + * + * @param {integer} version number + * @return {boolean} whether the version is bad + * isBadVersion = function(version) { + * ... + * }; + */ + +/** + * @param {function} isBadVersion() + * @return {function} + */ +var solution = function(isBadVersion) { + /** + * @param {integer} n Total versions + * @return {integer} The first bad version + */ + return function(n) { + let left = 1; + let right = n; + while (left < right) { + const mid = (left + right) >>> 1; + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; +}; +``` + +### **Go** + +```go +/** + * Forward declaration of isBadVersion API. + * @param version your guess about first bad version + * @return true if current version is bad + * false if current version is good + * func isBadVersion(version int) bool; + */ + +func firstBadVersion(n int) int { + left, right := 1, n + for left < right { + mid := (left + right) >> 1 + if isBadVersion(mid) { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0279.Perfect Squares/README_EN.md b/assets/0200-0299/0279.Perfect Squares/README_EN.md new file mode 100644 index 00000000..5273a2ff --- /dev/null +++ b/assets/0200-0299/0279.Perfect Squares/README_EN.md @@ -0,0 +1,127 @@ +# [279. Perfect Squares](https://leetcode.com/problems/perfect-squares) + + + +## Description + +

Given an integer n, return the least number of perfect square numbers that sum to n.

+ +

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

+ +

 

+

Example 1:

+ +
+Input: n = 12
+Output: 3
+Explanation: 12 = 4 + 4 + 4.
+
+ +

Example 2:

+ +
+Input: n = 13
+Output: 2
+Explanation: 13 = 4 + 9.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
+ + +## Solutions + +For dynamic programming, define `dp[i]` to represent the least number of perfect square numbers that sum to `i`. + + + +### **Python3** + +```python +class Solution: + def numSquares(self, n: int) -> int: + dp = [0 for i in range(n + 1)] + for i in range(1, n + 1): + j, mi = 1, 0x3f3f3f3f + while j * j <= i: + mi = min(mi, dp[i - j * j]) + j += 1 + dp[i] = mi + 1 + return dp[n] +``` + +### **Java** + +```java +class Solution { + public int numSquares(int n) { + List ans = new ArrayList<>(); + ans.add(0); + while (ans.size() <= n) { + int m = ans.size(), val = Integer.MAX_VALUE; + for (int i = 1; i * i <= m; i++) { + val = Math.min(val, ans.get(m - i * i) + 1); + } + ans.add(val); + } + return ans.get(n); + } +} +``` + +### **TypeScript** + +```ts +function numSquares(n: number): number { + let dp = new Array(n + 1).fill(0); + for (let i = 1; i <= n; ++i) { + let min = Infinity; + for (let j = 1; j * j <= i; ++j) { + min = Math.min(min, dp[i - j * j]); + } + dp[i] = min + 1; + } + return dp.pop(); +}; +``` + +### **Go** + +```go +/* + * @lc app=leetcode.cn id=279 lang=golang + * 动态规划的思路,状态转移方程:dp[n] = min(dp[n-1*1]+1, dp[n-2*2]+1, ..., dp[n-k*k]+1), ( 0< k*k <=n ) + */ +func numSquares(n int) int { + if n <= 0 { + return 0 + } + dp := make([]int, n+1) // 多申请了一份整形,使代码更容易理解, dp[n] 就是 n 的完全平方数的求解 + for i := 1; i <= n; i++ { + dp[i] = i // 初始值 dp[n] 的最大值的解,也是最容易求的解 + for j := 0; j*j <= i; j++ { + dp[i] = minInt(dp[i-j*j]+1, dp[i]) + } + } + return dp[n] +} + +func minInt(x, y int) int { + if x < y { + return x + } + return y +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0280.Wiggle Sort/README_EN.md b/assets/0200-0299/0280.Wiggle Sort/README_EN.md new file mode 100644 index 00000000..b3b81c0e --- /dev/null +++ b/assets/0200-0299/0280.Wiggle Sort/README_EN.md @@ -0,0 +1,109 @@ +# [280. Wiggle Sort](https://leetcode.com/problems/wiggle-sort) + + + +## Description + +

Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

+ +

You may assume the input array always has a valid answer.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,5,2,1,6,4]
+Output: [3,5,1,6,2,4]
+Explanation: [1,6,2,5,3,4] is also accepted.
+
+ +

Example 2:

+ +
+Input: nums = [6,6,5,6,3,8]
+Output: [6,6,5,6,3,8]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 0 <= nums[i] <= 104
  • +
  • It is guaranteed that there will be an answer for the given input nums.
  • +
+ +

 

+Follow up: Could you do it without sorting the array? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def wiggleSort(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + for i in range(1, len(nums)): + if (i % 2 == 1 and nums[i] < nums[i - 1]) or (i % 2 == 0 and nums[i] > nums[i - 1]): + nums[i], nums[i - 1] = nums[i - 1], nums[i] +``` + +### **Java** + +```java +class Solution { + public void wiggleSort(int[] nums) { + for (int i = 1; i < nums.length; ++i) { + if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { + swap(nums, i, i - 1); + } + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + void wiggleSort(vector& nums) { + for (int i = 1; i < nums.size(); ++i) { + if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { + swap(nums[i], nums[i - 1]); + } + } + } +}; +``` + +### **Go** + +```go +func wiggleSort(nums []int) { + for i := 1; i < len(nums); i++ { + if (i%2 == 1 && nums[i] < nums[i-1]) || (i%2 == 0 && nums[i] > nums[i-1]) { + nums[i], nums[i-1] = nums[i-1], nums[i] + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0281.Zigzag Iterator/README_EN.md b/assets/0200-0299/0281.Zigzag Iterator/README_EN.md new file mode 100644 index 00000000..0e9cd7a6 --- /dev/null +++ b/assets/0200-0299/0281.Zigzag Iterator/README_EN.md @@ -0,0 +1,152 @@ +# [281. Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator) + + + +## Description + +

Given two vectors of integers v1 and v2, implement an iterator to return their elements alternately.

+ +

Implement the ZigzagIterator class:

+ +
    +
  • ZigzagIterator(List<int> v1, List<int> v2) initializes the object with the two vectors v1 and v2.
  • +
  • boolean hasNext() returns true if the iterator still has elements, and false otherwise.
  • +
  • int next() returns the current element of the iterator and moves the iterator to the next element.
  • +
+ +

 

+

Example 1:

+ +
+Input: v1 = [1,2], v2 = [3,4,5,6]
+Output: [1,3,2,4,5,6]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6].
+
+ +

Example 2:

+ +
+Input: v1 = [1], v2 = []
+Output: [1]
+
+ +

Example 3:

+ +
+Input: v1 = [], v2 = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= v1.length, v2.length <= 1000
  • +
  • 1 <= v1.length + v2.length <= 2000
  • +
  • -231 <= v1[i], v2[i] <= 231 - 1
  • +
+ +

 

+

Follow up: What if you are given k vectors? How well can your code be extended to such cases?

+ +

Clarification for the follow-up question:

+ +

The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".

+ +

Example:

+ +
+Input: v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9]
+Output: [1,4,8,2,5,9,3,6,7]
+
+ + +## Solutions + + + +### **Python3** + +```python +class ZigzagIterator: + def __init__(self, v1: List[int], v2: List[int]): + self.cur = 0 + self.size = 2 + self.indexes = [0] * self.size + self.vectors = [v1, v2] + + def next(self) -> int: + vector = self.vectors[self.cur] + index = self.indexes[self.cur] + res = vector[index] + self.indexes[self.cur] = index + 1 + self.cur = (self.cur + 1) % self.size + return res + + def hasNext(self) -> bool: + start = self.cur + while self.indexes[self.cur] == len(self.vectors[self.cur]): + self.cur = (self.cur + 1) % self.size + if self.cur == start: + return False + return True + + +# Your ZigzagIterator object will be instantiated and called as such: +# i, v = ZigzagIterator(v1, v2), [] +# while i.hasNext(): v.append(i.next()) +``` + +### **Java** + +```java +public class ZigzagIterator { + private int cur; + private int size; + private List indexes = new ArrayList<>(); + private List> vectors = new ArrayList<>(); + + public ZigzagIterator(List v1, List v2) { + cur = 0; + size = 2; + indexes.add(0); + indexes.add(0); + vectors.add(v1); + vectors.add(v2); + } + + public int next() { + List vector = vectors.get(cur); + int index = indexes.get(cur); + int res = vector.get(index); + indexes.set(cur, index + 1); + cur = (cur + 1) % size; + return res; + } + + public boolean hasNext() { + int start = cur; + while (indexes.get(cur) == vectors.get(cur).size()) { + cur = (cur + 1) % size; + if (start == cur) { + return false; + } + } + return true; + } +} + +/** + * Your ZigzagIterator object will be instantiated and called as such: + * ZigzagIterator i = new ZigzagIterator(v1, v2); + * while (i.hasNext()) v[f()] = i.next(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0282.Expression Add Operators/README_EN.md b/assets/0200-0299/0282.Expression Add Operators/README_EN.md new file mode 100644 index 00000000..67bb3e56 --- /dev/null +++ b/assets/0200-0299/0282.Expression Add Operators/README_EN.md @@ -0,0 +1,58 @@ +# [282. Expression Add Operators](https://leetcode.com/problems/expression-add-operators) + + + +## Description + +

Given a string num that contains only digits and an integer target, return all possibilities to add the binary operators '+', '-', or '*' between the digits of num so that the resultant expression evaluates to the target value.

+ +

 

+

Example 1:

+
Input: num = "123", target = 6
+Output: ["1*2*3","1+2+3"]
+

Example 2:

+
Input: num = "232", target = 8
+Output: ["2*3+2","2+3*2"]
+

Example 3:

+
Input: num = "105", target = 5
+Output: ["1*0+5","10-5"]
+

Example 4:

+
Input: num = "00", target = 0
+Output: ["0*0","0+0","0-0"]
+

Example 5:

+
Input: num = "3456237490", target = 9191
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • 1 <= num.length <= 10
  • +
  • num consists of only digits.
  • +
  • -231 <= target <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0283.Move Zeroes/README_EN.md b/assets/0200-0299/0283.Move Zeroes/README_EN.md new file mode 100644 index 00000000..5d0bc5ad --- /dev/null +++ b/assets/0200-0299/0283.Move Zeroes/README_EN.md @@ -0,0 +1,105 @@ +# [283. Move Zeroes](https://leetcode.com/problems/move-zeroes) + + + +## Description + +

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

+ +

Note that you must do this in-place without making a copy of the array.

+ +

 

+

Example 1:

+
Input: nums = [0,1,0,3,12]
+Output: [1,3,12,0,0]
+

Example 2:

+
Input: nums = [0]
+Output: [0]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Could you minimize the total number of operations done? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + if not nums: + return + n = len(nums) + zero_count = 0 + for i in range(n): + if nums[i] == 0: + zero_count += 1 + else: + nums[i - zero_count] = nums[i] + while zero_count > 0: + nums[n - zero_count] = 0 + zero_count -= 1 +``` + +### **Java** + +```java +class Solution { + public void moveZeroes(int[] nums) { + int n; + if (nums == null || (n = nums.length) < 1) { + return; + } + int zeroCount = 0; + for (int i = 0; i < n; ++i) { + if (nums[i] == 0) { + ++zeroCount; + } else { + nums[i - zeroCount] = nums[i]; + } + } + while (zeroCount > 0) { + nums[n - zeroCount--] = 0; + } + } +} +``` +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function (nums) { + if (!nums.length) return nums; + let j = 0; + for (i = 0; i < nums.length; i++) { + if (nums[i]) { + if (i > j) [nums[i], nums[j]] = [nums[j], nums[i]]; + j++; + } + } + return nums; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0284.Peeking Iterator/README_EN.md b/assets/0200-0299/0284.Peeking Iterator/README_EN.md new file mode 100644 index 00000000..27646f7f --- /dev/null +++ b/assets/0200-0299/0284.Peeking Iterator/README_EN.md @@ -0,0 +1,174 @@ +# [284. Peeking Iterator](https://leetcode.com/problems/peeking-iterator) + + + +## Description + +

Design an iterator that supports the peek operation on a list in addition to the hasNext and the next operations.

+ +

Implement the PeekingIterator class:

+ +
    +
  • PeekingIterator(int[] nums) Initializes the object with the given integer array nums.
  • +
  • int next() Returns the next element in the array and moves the pointer to the next element.
  • +
  • bool hasNext() Returns true if there are still elements in the array.
  • +
  • int peek() Returns the next element in the array without moving the pointer.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
+[[[1, 2, 3]], [], [], [], [], []]
+Output
+[null, 1, 2, 2, 3, false]
+
+Explanation
+PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
+peekingIterator.next();    // return 1, the pointer moves to the next element [1,2,3].
+peekingIterator.peek();    // return 2, the pointer does not move [1,2,3].
+peekingIterator.next();    // return 2, the pointer moves to the next element [1,2,3]
+peekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]
+peekingIterator.hasNext(); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 1000
  • +
  • All the calls to next and peek are valid.
  • +
  • At most 1000 calls will be made to next, hasNext, and peek.
  • +
+ +

 

+Follow up: How would you extend your design to be generic and work with all types, not just integer? + +## Solutions + + + +### **Python3** + +```python +# Below is the interface for Iterator, which is already defined for you. +# +# class Iterator: +# def __init__(self, nums): +# """ +# Initializes an iterator object to the beginning of a list. +# :type nums: List[int] +# """ +# +# def hasNext(self): +# """ +# Returns true if the iteration has more elements. +# :rtype: bool +# """ +# +# def next(self): +# """ +# Returns the next element in the iteration. +# :rtype: int +# """ + +class PeekingIterator: + def __init__(self, iterator): + """ + Initialize your data structure here. + :type iterator: Iterator + """ + self.iterator = iterator + self.has_peeked = False + self.peeked_element = None + + def peek(self): + """ + Returns the next element in the iteration without advancing the iterator. + :rtype: int + """ + if not self.has_peeked: + self.peeked_element = self.iterator.next() + self.has_peeked = True + return self.peeked_element + + def next(self): + """ + :rtype: int + """ + if not self.has_peeked: + return self.iterator.next() + result = self.peeked_element + self.has_peeked = False + self.peeked_element = None + return result + + def hasNext(self): + """ + :rtype: bool + """ + return self.has_peeked or self.iterator.hasNext() + + +# Your PeekingIterator object will be instantiated and called as such: +# iter = PeekingIterator(Iterator(nums)) +# while iter.hasNext(): +# val = iter.peek() # Get the next element but not advance the iterator. +# iter.next() # Should return the same value as [val]. +``` + +### **Java** + +```java +// Java Iterator interface reference: +// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html + +class PeekingIterator implements Iterator { + private Iterator iterator; + private boolean hasPeeked; + private Integer peekedElement; + + public PeekingIterator(Iterator iterator) { + // initialize any member here. + this.iterator = iterator; + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + if (!hasPeeked) { + peekedElement = iterator.next(); + hasPeeked = true; + } + return peekedElement; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + if (!hasPeeked) { + return iterator.next(); + } + Integer result = peekedElement; + hasPeeked = false; + peekedElement = null; + return result; + } + + @Override + public boolean hasNext() { + return hasPeeked || iterator.hasNext(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0285.Inorder Successor in BST/README_EN.md b/assets/0200-0299/0285.Inorder Successor in BST/README_EN.md new file mode 100644 index 00000000..3144c7fe --- /dev/null +++ b/assets/0200-0299/0285.Inorder Successor in BST/README_EN.md @@ -0,0 +1,106 @@ +# [285. Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst) + + + +## Description + +

Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null.

+ +

The successor of a node p is the node with the smallest key greater than p.val.

+ +

 

+

Example 1:

+ +
+Input: root = [2,1,3], p = 1
+Output: 2
+Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
+
+ +

Example 2:

+ +
+Input: root = [5,3,6,2,4,null,null,1], p = 6
+Output: null
+Explanation: There is no in-order successor of the current node, so the answer is null.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • All Nodes will have unique values.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @return {TreeNode} + */ +var inorderSuccessor = function (root, p) { + function findMin(root) { + if (!root) { + return null; + } + while (root.left) { + root = root.left; + } + return root; + } + if (!root) { + return null; + } + let successor = null; + while (root) { + if (root.val > p.val) { + successor = root; + root = root.left; + } else if (root.val < p.val) { + root = root.right; + } else { + if (root.right) { + successor = findMin(root.right); + } + break; + } + } + return successor; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0285.Inorder Successor in BST/images/285_example_1.png b/assets/0200-0299/0285.Inorder Successor in BST/images/285_example_1.png new file mode 100644 index 00000000..ca017f96 Binary files /dev/null and b/assets/0200-0299/0285.Inorder Successor in BST/images/285_example_1.png differ diff --git a/assets/0200-0299/0285.Inorder Successor in BST/images/285_example_2.png b/assets/0200-0299/0285.Inorder Successor in BST/images/285_example_2.png new file mode 100644 index 00000000..b02f931a Binary files /dev/null and b/assets/0200-0299/0285.Inorder Successor in BST/images/285_example_2.png differ diff --git a/assets/0200-0299/0286.Walls and Gates/README_EN.md b/assets/0200-0299/0286.Walls and Gates/README_EN.md new file mode 100644 index 00000000..c8c80ead --- /dev/null +++ b/assets/0200-0299/0286.Walls and Gates/README_EN.md @@ -0,0 +1,79 @@ +# [286. Walls and Gates](https://leetcode.com/problems/walls-and-gates) + + + +## Description + +

You are given an m x n grid rooms initialized with these three possible values.

+ +
    +
  • -1 A wall or an obstacle.
  • +
  • 0 A gate.
  • +
  • INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
  • +
+ +

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

+ +

 

+

Example 1:

+ +
+Input: rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
+Output: [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
+
+ +

Example 2:

+ +
+Input: rooms = [[-1]]
+Output: [[-1]]
+
+ +

Example 3:

+ +
+Input: rooms = [[2147483647]]
+Output: [[2147483647]]
+
+ +

Example 4:

+ +
+Input: rooms = [[0]]
+Output: [[0]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == rooms.length
  • +
  • n == rooms[i].length
  • +
  • 1 <= m, n <= 250
  • +
  • rooms[i][j] is -1, 0, or 231 - 1.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0286.Walls and Gates/images/grid.jpg b/assets/0200-0299/0286.Walls and Gates/images/grid.jpg new file mode 100644 index 00000000..d89e2ba6 Binary files /dev/null and b/assets/0200-0299/0286.Walls and Gates/images/grid.jpg differ diff --git a/assets/0200-0299/0287.Find the Duplicate Number/README_EN.md b/assets/0200-0299/0287.Find the Duplicate Number/README_EN.md new file mode 100644 index 00000000..4e1ed5eb --- /dev/null +++ b/assets/0200-0299/0287.Find the Duplicate Number/README_EN.md @@ -0,0 +1,116 @@ +# [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number) + + + +## Description + +

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

+ +

There is only one repeated number in nums, return this repeated number.

+ +

 

+

Example 1:

+
Input: nums = [1,3,4,2,2]
+Output: 2
+

Example 2:

+
Input: nums = [3,1,3,4,2]
+Output: 3
+

Example 3:

+
Input: nums = [1,1]
+Output: 1
+

Example 4:

+
Input: nums = [1,1,2]
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 2 <= n <= 3 * 104
  • +
  • nums.length == n + 1
  • +
  • 1 <= nums[i] <= n
  • +
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
  • +
+ +

 

+

Follow up:

+ +
    +
  • How can we prove that at least one duplicate number must exist in nums?
  • +
  • Can you solve the problem without modifying the array nums?
  • +
  • Can you solve the problem using only constant, O(1) extra space?
  • +
  • Can you solve the problem with runtime complexity less than O(n2)?
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + while l < r: + mid = (l + r) >> 1 + cnt = 0 + for e in nums: + if e <= mid: + cnt += 1 + if cnt <= mid: + l = mid + 1 + else: + r = mid + return l +``` + +### **Java** + +```java +class Solution { + public int findDuplicate(int[] nums) { + int l = 1, r = nums.length - 1; + while (l < r) { + int mid = (l + r) >>> 1; + int cnt = 0; + for (int e : nums) { + if (e <= mid) ++cnt; + } + if (cnt <= mid) l = mid + 1; + else r = mid; + } + return l; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findDuplicate(vector& nums) { + int l = 0, r = nums.size() - 1; + while (l < r) { + int mid = l + ((r - l) >> 1); + int cnt = 0; + for (auto e : nums) { + if (e <= mid) ++cnt; + } + if (cnt <= mid) l = mid + 1; + else r = mid; + } + return l; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0288.Unique Word Abbreviation/README_EN.md b/assets/0200-0299/0288.Unique Word Abbreviation/README_EN.md new file mode 100644 index 00000000..f8d008af --- /dev/null +++ b/assets/0200-0299/0288.Unique Word Abbreviation/README_EN.md @@ -0,0 +1,142 @@ +# [288. Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation) + + + +## Description + +

The abbreviation of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an abbreviation of itself.

+ +

For example:

+ +
    +
  • dog --> d1g because there is one letter between the first letter 'd' and the last letter 'g'.
  • +
  • internationalization --> i18n because there are 18 letters between the first letter 'i' and the last letter 'n'.
  • +
  • it --> it because any word with only two characters is an abbreviation of itself.
  • +
+ +

Implement the ValidWordAbbr class:

+ +
    +
  • ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words.
  • +
  • boolean isUnique(string word) Returns true if either of the following conditions are met (otherwise returns false): +
      +
    • There is no word in dictionary whose abbreviation is equal to word's abbreviation.
    • +
    • For any word in dictionary whose abbreviation is equal to word's abbreviation, that word and word are the same.
    • +
    +
  • +
+ +

 

+

Example 1:

+ +
+Input
+["ValidWordAbbr", "isUnique", "isUnique", "isUnique", "isUnique"]
+[[["deer", "door", "cake", "card"]], ["dear"], ["cart"], ["cane"], ["make"]]
+Output
+[null, false, true, false, true]
+
+Explanation
+ValidWordAbbr validWordAbbr = new ValidWordAbbr(["deer", "door", "cake", "card"]);
+validWordAbbr.isUnique("dear"); // return false, dictionary word "deer" and word "dear" have the same abbreviation
+                                // "d2r" but are not the same.
+validWordAbbr.isUnique("cart"); // return true, no words in the dictionary have the abbreviation "c2t".
+validWordAbbr.isUnique("cane"); // return false, dictionary word "cake" and word "cane" have the same abbreviation 
+                                // "c2e" but are not the same.
+validWordAbbr.isUnique("make"); // return true, no words in the dictionary have the abbreviation "m2e".
+validWordAbbr.isUnique("cake"); // return true, because "cake" is already in the dictionary and no other word in the dictionary has "c2e" abbreviation.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= dictionary.length <= 3 * 104
  • +
  • 1 <= dictionary[i].length <= 20
  • +
  • dictionary[i] consists of lowercase English letters.
  • +
  • 1 <= word.length <= 20
  • +
  • word consists of lowercase English letters.
  • +
  • At most 5000 calls will be made to isUnique.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class ValidWordAbbr: + + def __init__(self, dictionary: List[str]): + self.words = {} + for word in dictionary: + abbr = self._word_abbr(word) + vals = self.words.get(abbr, set()) + vals.add(word) + self.words[abbr] = vals + + def isUnique(self, word: str) -> bool: + abbr = self._word_abbr(word) + vals = self.words.get(abbr) + return vals is None or (len(vals) == 1 and word in vals) + + def _word_abbr(self, word: str) -> str: + n = len(word) + if n < 3: + return word + return f'{word[0]}{n - 2}{word[n - 1]}' + + +# Your ValidWordAbbr object will be instantiated and called as such: +# obj = ValidWordAbbr(dictionary) +# param_1 = obj.isUnique(word) +``` + +### **Java** + +```java +class ValidWordAbbr { + private Map> words; + + public ValidWordAbbr(String[] dictionary) { + words = new HashMap<>(); + for (String word : dictionary) { + String abbr = wordAbbr(word); + Set vals = words.getOrDefault(abbr, new HashSet<>()); + vals.add(word); + words.put(abbr, vals); + } + } + + public boolean isUnique(String word) { + String abbr = wordAbbr(word); + Set vals = words.get(abbr); + return vals == null || (vals.size() == 1 && vals.contains(word)); + } + + private String wordAbbr(String word) { + int n = word.length(); + if (n < 3) { + return word; + } + StringBuilder sb = new StringBuilder(); + sb.append(word.charAt(0)).append(n - 2).append(word.charAt(n - 1)); + return sb.toString(); + } +} + +/** + * Your ValidWordAbbr object will be instantiated and called as such: + * ValidWordAbbr obj = new ValidWordAbbr(dictionary); + * boolean param_1 = obj.isUnique(word); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0289.Game of Life/README_EN.md b/assets/0200-0299/0289.Game of Life/README_EN.md new file mode 100644 index 00000000..354456d5 --- /dev/null +++ b/assets/0200-0299/0289.Game of Life/README_EN.md @@ -0,0 +1,76 @@ +# [289. Game of Life](https://leetcode.com/problems/game-of-life) + + + +## Description + +

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

+ +

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

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

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

+ +

 

+

Example 1:

+ +
+Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
+Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
+
+ +

Example 2:

+ +
+Input: board = [[1,1],[1,0]]
+Output: [[1,1],[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 25
  • +
  • board[i][j] is 0 or 1.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
  • +
  • In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0289.Game of Life/images/grid1.jpg b/assets/0200-0299/0289.Game of Life/images/grid1.jpg new file mode 100644 index 00000000..73ed58ca Binary files /dev/null and b/assets/0200-0299/0289.Game of Life/images/grid1.jpg differ diff --git a/assets/0200-0299/0289.Game of Life/images/grid2.jpg b/assets/0200-0299/0289.Game of Life/images/grid2.jpg new file mode 100644 index 00000000..38d8ecdf Binary files /dev/null and b/assets/0200-0299/0289.Game of Life/images/grid2.jpg differ diff --git a/assets/0200-0299/0290.Word Pattern/README_EN.md b/assets/0200-0299/0290.Word Pattern/README_EN.md new file mode 100644 index 00000000..ea940f71 --- /dev/null +++ b/assets/0200-0299/0290.Word Pattern/README_EN.md @@ -0,0 +1,111 @@ +# [290. Word Pattern](https://leetcode.com/problems/word-pattern) + + + +## Description + +

Given a pattern and a string s, find if s follows the same pattern.

+ +

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

+ +

 

+

Example 1:

+ +
+Input: pattern = "abba", s = "dog cat cat dog"
+Output: true
+
+ +

Example 2:

+ +
+Input: pattern = "abba", s = "dog cat cat fish"
+Output: false
+
+ +

Example 3:

+ +
+Input: pattern = "aaaa", s = "dog cat cat dog"
+Output: false
+
+ +

Example 4:

+ +
+Input: pattern = "abba", s = "dog dog dog dog"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pattern.length <= 300
  • +
  • pattern contains only lower-case English letters.
  • +
  • 1 <= s.length <= 3000
  • +
  • s contains only lower-case English letters and spaces ' '.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • All the words in s are separated by a single space.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + ch2str, str2ch = {}, {} + ss = s.split(' ') + n = len(pattern) + if n != len(ss): + return False + for i in range(n): + if ch2str.get(pattern[i]) is not None and ch2str.get(pattern[i]) != ss[i]: + return False + if str2ch.get(ss[i]) is not None and str2ch.get(ss[i]) != pattern[i]: + return False + ch2str[pattern[i]] = ss[i] + str2ch[ss[i]] = pattern[i] + return True +``` + +### **Java** + +```java +class Solution { + public boolean wordPattern(String pattern, String s) { + Map ch2str = new HashMap<>(); + Map str2ch = new HashMap<>(); + String[] ss = s.split(" "); + int n = pattern.length(); + if (n != ss.length) { + return false; + } + for (int i = 0; i < n; ++i) { + char ch = pattern.charAt(i); + if (ch2str.containsKey(ch) && !ch2str.get(ch).equals(ss[i])) { + return false; + } + if (str2ch.containsKey(ss[i]) && !str2ch.get(ss[i]).equals(ch)) { + return false; + } + ch2str.put(ch, ss[i]); + str2ch.put(ss[i], ch); + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0291.Word Pattern II/README_EN.md b/assets/0200-0299/0291.Word Pattern II/README_EN.md new file mode 100644 index 00000000..f70437cb --- /dev/null +++ b/assets/0200-0299/0291.Word Pattern II/README_EN.md @@ -0,0 +1,79 @@ +# [291. Word Pattern II](https://leetcode.com/problems/word-pattern-ii) + + + +## Description + +

Given a pattern and a string s, return true if s matches the pattern.

+ +

A string s matches a pattern if there is some bijective mapping of single characters to strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.

+ +

 

+

Example 1:

+ +
+Input: pattern = "abab", s = "redblueredblue"
+Output: true
+Explanation: One possible mapping is as follows:
+'a' -> "red"
+'b' -> "blue"
+ +

Example 2:

+ +
+Input: pattern = "aaaa", s = "asdasdasdasd"
+Output: true
+Explanation: One possible mapping is as follows:
+'a' -> "asd"
+
+ +

Example 3:

+ +
+Input: pattern = "abab", s = "asdasdasdasd"
+Output: true
+Explanation: One possible mapping is as follows:
+'a' -> "a"
+'b' -> "sdasd"
+Note that 'a' and 'b' cannot both map to "asd" since the mapping is a bijection.
+
+ +

Example 4:

+ +
+Input: pattern = "aabb", s = "xyzabcxzyabc"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= pattern.length, s.length <= 20
  • +
  • pattern and s consist of only lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0292.Nim Game/README_EN.md b/assets/0200-0299/0292.Nim Game/README_EN.md new file mode 100644 index 00000000..17bd318f --- /dev/null +++ b/assets/0200-0299/0292.Nim Game/README_EN.md @@ -0,0 +1,75 @@ +# [292. Nim Game](https://leetcode.com/problems/nim-game) + + + +## Description + +

You are playing the following Nim Game with your friend:

+ +
    +
  • Initially, there is a heap of stones on the table.
  • +
  • You and your friend will alternate taking turns, and you go first.
  • +
  • On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
  • +
  • The one who removes the last stone is the winner.
  • +
+ +

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

+ +

 

+

Example 1:

+ +
+Input: n = 4
+Output: false
+Explanation: These are the possible outcomes:
+1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
+2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
+3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
+In all outcomes, your friend wins.
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: true
+
+ +

Example 3:

+ +
+Input: n = 2
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0293.Flip Game/README_EN.md b/assets/0200-0299/0293.Flip Game/README_EN.md new file mode 100644 index 00000000..4bec6bc7 --- /dev/null +++ b/assets/0200-0299/0293.Flip Game/README_EN.md @@ -0,0 +1,82 @@ +# [293. Flip Game](https://leetcode.com/problems/flip-game) + + + +## Description + +

You are playing a Flip Game with your friend.

+ +

You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner.

+ +

Return all possible states of the string currentState after one valid move. You may return the answer in any order. If there is no valid move, return an empty list [].

+ +

 

+

Example 1:

+ +
+Input: currentState = "++++"
+Output: ["--++","+--+","++--"]
+
+ +

Example 2:

+ +
+Input: currentState = "+"
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= currentState.length <= 500
  • +
  • currentState[i] is either '+' or '-'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def generatePossibleNextMoves(self, s: str) -> List[str]: + if not s or len(s) < 2: + return [] + n = len(s) + res = [] + for i in range(n - 1): + if s[i] == '+' and s[i + 1] == '+': + res.append(s[:i] + "--" + s[i + 2:]) + return res +``` + +### **Java** + +```java +class Solution { + public List generatePossibleNextMoves(String s) { + int n; + if (s == null || (n = s.length()) < 2) return Collections.emptyList(); + List res = new ArrayList<>(); + for (int i = 0; i < n - 1; ++i) { + if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') { + StringBuilder sb = new StringBuilder(s); + sb.replace(i, i + 2, "--"); + res.add(sb.toString()); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0294.Flip Game II/README_EN.md b/assets/0200-0299/0294.Flip Game II/README_EN.md new file mode 100644 index 00000000..cf42a0d9 --- /dev/null +++ b/assets/0200-0299/0294.Flip Game II/README_EN.md @@ -0,0 +1,62 @@ +# [294. Flip Game II](https://leetcode.com/problems/flip-game-ii) + + + +## Description + +

You are playing a Flip Game with your friend.

+ +

You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner.

+ +

Return true if the starting player can guarantee a win, and false otherwise.

+ +

 

+

Example 1:

+ +
+Input: currentState = "++++"
+Output: true
+Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+".
+
+ +

Example 2:

+ +
+Input: currentState = "+"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= currentState.length <= 60
  • +
  • currentState[i] is either '+' or '-'.
  • +
+ +

 

+Follow up: Derive your algorithm's runtime complexity. + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0295.Find Median from Data Stream/README_EN.md b/assets/0200-0299/0295.Find Median from Data Stream/README_EN.md new file mode 100644 index 00000000..647f0f9f --- /dev/null +++ b/assets/0200-0299/0295.Find Median from Data Stream/README_EN.md @@ -0,0 +1,135 @@ +# [295. Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream) + + + +## Description + +

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

+ +
    +
  • For example, for arr = [2,3,4], the median is 3.
  • +
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
  • +
+ +

Implement the MedianFinder class:

+ +
    +
  • MedianFinder() initializes the MedianFinder object.
  • +
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • +
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
+[[], [1], [2], [], [3], []]
+Output
+[null, null, null, 1.5, null, 2.0]
+
+Explanation
+MedianFinder medianFinder = new MedianFinder();
+medianFinder.addNum(1);    // arr = [1]
+medianFinder.addNum(2);    // arr = [1, 2]
+medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
+medianFinder.addNum(3);    // arr[1, 2, 3]
+medianFinder.findMedian(); // return 2.0
+
+ +

 

+

Constraints:

+ +
    +
  • -105 <= num <= 105
  • +
  • There will be at least one element in the data structure before calling findMedian.
  • +
  • At most 5 * 104 calls will be made to addNum and findMedian.
  • +
+ +

 

+

Follow up:

+ +
    +
  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • +
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • +
+ +## Solutions + + + +### **Python3** + +```python +class MedianFinder: + + def __init__(self): + """ + initialize your data structure here. + """ + self.min_heap = [] + self.max_heap = [] + + def addNum(self, num: int) -> None: + heapq.heappush(self.min_heap, num) + heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap)) + if len(self.max_heap) - len(self.min_heap) > 1: + heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap)) + + def findMedian(self) -> float: + if len(self.max_heap) > len(self.min_heap): + return -self.max_heap[0] + return (self.min_heap[0] - self.max_heap[0]) / 2 + + +# Your MedianFinder object will be instantiated and called as such: +# obj = MedianFinder() +# obj.addNum(num) +# param_2 = obj.findMedian() +``` + +### **Java** + +```java +class MedianFinder { + private PriorityQueue minHeap; + private PriorityQueue maxHeap; + + /** initialize your data structure here. */ + public MedianFinder() { + minHeap = new PriorityQueue<>(); + maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + } + + public void addNum(int num) { + minHeap.offer(num); + maxHeap.offer(minHeap.poll()); + if (maxHeap.size() - minHeap.size() > 1) { + minHeap.offer(maxHeap.poll()); + } + } + + public double findMedian() { + if (maxHeap.size() > minHeap.size()) { + return maxHeap.peek(); + } + return (minHeap.peek() + maxHeap.peek()) * 1.0 / 2; + } +} + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder obj = new MedianFinder(); + * obj.addNum(num); + * double param_2 = obj.findMedian(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0296.Best Meeting Point/README_EN.md b/assets/0200-0299/0296.Best Meeting Point/README_EN.md new file mode 100644 index 00000000..975e7793 --- /dev/null +++ b/assets/0200-0299/0296.Best Meeting Point/README_EN.md @@ -0,0 +1,65 @@ +# [296. Best Meeting Point](https://leetcode.com/problems/best-meeting-point) + + + +## Description + +

Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance.

+ +

The total travel distance is the sum of the distances between the houses of the friends and the meeting point.

+ +

The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

+ +

 

+

Example 1:

+ +
+Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
+Output: 6
+Explanation: Given three friends living at (0,0), (0,4), and (2,2).
+The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
+So return 6.
+
+ +

Example 2:

+ +
+Input: grid = [[1,1]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • grid[i][j] is either 0 or 1.
  • +
  • There will be at least two friends in the grid.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0296.Best Meeting Point/images/meetingpoint-grid.jpg b/assets/0200-0299/0296.Best Meeting Point/images/meetingpoint-grid.jpg new file mode 100644 index 00000000..311b8a76 Binary files /dev/null and b/assets/0200-0299/0296.Best Meeting Point/images/meetingpoint-grid.jpg differ diff --git a/assets/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md b/assets/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md new file mode 100644 index 00000000..e73e619d --- /dev/null +++ b/assets/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md @@ -0,0 +1,73 @@ +# [297. Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree) + + + +## Description + +

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

+ +

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

+ +

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,null,null,4,5]
+Output: [1,2,3,null,null,4,5]
+
+ +

Example 2:

+ +
+Input: root = []
+Output: []
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
+Input: root = [1,2]
+Output: [1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0297.Serialize and Deserialize Binary Tree/images/serdeser.jpg b/assets/0200-0299/0297.Serialize and Deserialize Binary Tree/images/serdeser.jpg new file mode 100644 index 00000000..3ddbec0c Binary files /dev/null and b/assets/0200-0299/0297.Serialize and Deserialize Binary Tree/images/serdeser.jpg differ diff --git a/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md b/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md new file mode 100644 index 00000000..47dd13c2 --- /dev/null +++ b/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md @@ -0,0 +1,59 @@ +# [298. Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence) + + + +## Description + +

Given the root of a binary tree, return the length of the longest consecutive sequence path.

+ +

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path needs to be from parent to child (cannot be the reverse).

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,3,2,4,null,null,null,5]
+Output: 3
+Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
+
+ +

Example 2:

+ +
+Input: root = [2,null,3,2,null,1]
+Output: 2
+Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3 * 104].
  • +
  • -3 * 104 <= Node.val <= 3 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/images/consec1-1-tree.jpg b/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/images/consec1-1-tree.jpg new file mode 100644 index 00000000..aaf5f2d8 Binary files /dev/null and b/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/images/consec1-1-tree.jpg differ diff --git a/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/images/consec1-2-tree.jpg b/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/images/consec1-2-tree.jpg new file mode 100644 index 00000000..7d8256fb Binary files /dev/null and b/assets/0200-0299/0298.Binary Tree Longest Consecutive Sequence/images/consec1-2-tree.jpg differ diff --git a/assets/0200-0299/0299.Bulls and Cows/README_EN.md b/assets/0200-0299/0299.Bulls and Cows/README_EN.md new file mode 100644 index 00000000..f197d2ce --- /dev/null +++ b/assets/0200-0299/0299.Bulls and Cows/README_EN.md @@ -0,0 +1,124 @@ +# [299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows) + + + +## Description + +

You are playing the Bulls and Cows game with your friend.

+ +

You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:

+ +
    +
  • The number of "bulls", which are digits in the guess that are in the correct position.
  • +
  • The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
  • +
+ +

Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.

+ +

The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.

+ +

 

+

Example 1:

+ +
+Input: secret = "1807", guess = "7810"
+Output: "1A3B"
+Explanation: Bulls are connected with a '|' and cows are underlined:
+"1807"
+  |
+"7810"
+ +

Example 2:

+ +
+Input: secret = "1123", guess = "0111"
+Output: "1A1B"
+Explanation: Bulls are connected with a '|' and cows are underlined:
+"1123"        "1123"
+  |      or     |
+"0111"        "0111"
+Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
+
+ +

Example 3:

+ +
+Input: secret = "1", guess = "0"
+Output: "0A0B"
+
+ +

Example 4:

+ +
+Input: secret = "1", guess = "1"
+Output: "1A0B"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= secret.length, guess.length <= 1000
  • +
  • secret.length == guess.length
  • +
  • secret and guess consist of digits only.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def getHint(self, secret: str, guess: str) -> str: + a_cnt = b_cnt = 0 + nums1 = dict() + nums2 = dict() + for i in range(len(secret)): + if secret[i] == guess[i]: + a_cnt += 1 + else: + nums1[secret[i]] = nums1.get(secret[i], 0) + 1 + nums2[guess[i]] = nums2.get(guess[i], 0) + 1 + for i, v in nums1.items(): + if i in nums2: + b_cnt += min(v, nums2[i]) + return f'{a_cnt}A{b_cnt}B' +``` + +### **Java** + +```java +class Solution { + public String getHint(String secret, String guess) { + int aCnt = 0, bCnt = 0; + Map nums1 = new HashMap<>(); + Map nums2 = new HashMap<>(); + for (int i = 0; i < secret.length(); ++i) { + if (secret.charAt(i) == guess.charAt(i)) { + ++aCnt; + } else { + nums1.put(secret.charAt(i), nums1.getOrDefault(secret.charAt(i), 0) + 1); + nums2.put(guess.charAt(i), nums2.getOrDefault(guess.charAt(i), 0) + 1); + } + } + + for (Map.Entry entry : nums1.entrySet()) { + if (nums2.containsKey(entry.getKey())) { + bCnt += Math.min(entry.getValue(), nums2.get(entry.getKey())); + } + } + return String.format("%dA%dB", aCnt, bCnt); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0300.Longest Increasing Subsequence/README_EN.md b/assets/0300-0399/0300.Longest Increasing Subsequence/README_EN.md new file mode 100644 index 00000000..4399ec8e --- /dev/null +++ b/assets/0300-0399/0300.Longest Increasing Subsequence/README_EN.md @@ -0,0 +1,101 @@ +# [300. Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence) + + + +## Description + +

Given an integer array nums, return the length of the longest strictly increasing subsequence.

+ +

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

+ +

 

+

Example 1:

+ +
+Input: nums = [10,9,2,5,3,7,101,18]
+Output: 4
+Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
+
+ +

Example 2:

+ +
+Input: nums = [0,1,0,3,2,3]
+Output: 4
+
+ +

Example 3:

+ +
+Input: nums = [7,7,7,7,7,7,7]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2500
  • +
  • -104 <= nums[i] <= 104
  • +
+ +

 

+

Follow up:

+ +
    +
  • Could you come up with the O(n2) solution?
  • +
  • Could you improve it to O(n log(n)) time complexity?
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + n = len(nums) + if n < 2: + return n + dp = [1] * n + res = 1 + for i in range(1, n): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + res = max(res, dp[i]) + return res +``` + +### **Java** + +```java +class Solution { + public int lengthOfLIS(int[] nums) { + int n = nums.length; + int[] dp = new int[n]; + Arrays.fill(dp, 1); + int res = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + res = Math.max(res, dp[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0301.Remove Invalid Parentheses/README_EN.md b/assets/0300-0399/0301.Remove Invalid Parentheses/README_EN.md new file mode 100644 index 00000000..300406c8 --- /dev/null +++ b/assets/0300-0399/0301.Remove Invalid Parentheses/README_EN.md @@ -0,0 +1,65 @@ +# [301. Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses) + + + +## Description + +

Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.

+ +

Return all the possible results. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: s = "()())()"
+Output: ["(())()","()()()"]
+
+ +

Example 2:

+ +
+Input: s = "(a)())()"
+Output: ["(a())()","(a)()()"]
+
+ +

Example 3:

+ +
+Input: s = ")("
+Output: [""]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 25
  • +
  • s consists of lowercase English letters and parentheses '(' and ')'.
  • +
  • There will be at most 20 parentheses in s.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md b/assets/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md new file mode 100644 index 00000000..6c3420d9 --- /dev/null +++ b/assets/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md @@ -0,0 +1,65 @@ +# [302. Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels) + + + +## Description + +

You are given an image that is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel.

+ +

The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically.

+ +

Given two integers x and y that represent the location of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.

+ +

 

+

Example 1:

+ +
+Input: image = [["0","0","1","0"],["0","1","1","0"],["0","1","0","0"]], x = 0, y = 2
+Output: 6
+
+ +

Example 2:

+ +
+Input: image = [["1"]], x = 0, y = 0
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == image.length
  • +
  • n == image[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • image[i][j] is either '0' or '1'.
  • +
  • 1 <= x < m
  • +
  • 1 <= y < n
  • +
  • image[x][y] == '1'.
  • +
  • The black pixels in the image only form one component.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/images/302_smallest_rectangle_enclosing_black_pixels.png b/assets/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/images/302_smallest_rectangle_enclosing_black_pixels.png new file mode 100644 index 00000000..1bfef02b Binary files /dev/null and b/assets/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/images/302_smallest_rectangle_enclosing_black_pixels.png differ diff --git a/assets/0300-0399/0303.Range Sum Query - Immutable/README_EN.md b/assets/0300-0399/0303.Range Sum Query - Immutable/README_EN.md new file mode 100644 index 00000000..d2eddf87 --- /dev/null +++ b/assets/0300-0399/0303.Range Sum Query - Immutable/README_EN.md @@ -0,0 +1,102 @@ +# [303. Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable) + + + +## Description + +

Given an integer array nums, find the sum of the elements between indices left and right inclusive, where (left <= right).

+ +

Implement the NumArray class:

+ +
    +
  • NumArray(int[] nums) initializes the object with the integer array nums.
  • +
  • int sumRange(int left, int right) returns the sum of the elements of the nums array in the range [left, right] inclusive (i.e., sum(nums[left], nums[left + 1], ... , nums[right])).
  • +
+ +

 

+

Example 1:

+ +
+Input
+["NumArray", "sumRange", "sumRange", "sumRange"]
+[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
+Output
+[null, 1, -1, -3]
+
+Explanation
+NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
+numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
+numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) 
+numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -105 <= nums[i] <= 105
  • +
  • 0 <= left <= right < nums.length
  • +
  • At most 104 calls will be made to sumRange.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class NumArray: + + def __init__(self, nums: List[int]): + n = len(nums) + self.sums = [0] * (n + 1) + for i in range(n): + self.sums[i + 1] = nums[i] + self.sums[i] + + + def sumRange(self, i: int, j: int) -> int: + return self.sums[j + 1] - self.sums[i] + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# param_1 = obj.sumRange(i,j) +``` + +### **Java** + +```java +class NumArray { + + private int[] sums; + + public NumArray(int[] nums) { + int n = nums.length; + sums = new int[n + 1]; + for (int i = 0; i < n; ++i) { + sums[i + 1] = nums[i] + sums[i]; + } + } + + public int sumRange(int i, int j) { + return sums[j + 1] - sums[i]; + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * int param_1 = obj.sumRange(i,j); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md b/assets/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md new file mode 100644 index 00000000..0b877d32 --- /dev/null +++ b/assets/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md @@ -0,0 +1,169 @@ +# [304. Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable) + + + +## Description + +

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

+ +

Implement the NumMatrix class:

+ +
    +
  • NumMatrix(int[][] matrix) initializes the object with the integer matrix matrix.
  • +
  • int sumRegion(int row1, int col1, int row2, int col2) returns the sum of the elements of the matrix array inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
  • +
+ +

 

+

Example 1:

+ +
+Input
+["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
+[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
+Output
+[null, 8, 11, 12]
+
+Explanation
+NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
+numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangele).
+numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangele).
+numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangele).
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • -105 <= matrix[i][j] <= 105
  • +
  • 0 <= row1 <= row2 < m
  • +
  • 0 <= col1 <= col2 < n
  • +
  • At most 104 calls will be made to sumRegion.
  • +
+ + +## Solutions + +Dynamic programming - 2D preSum. + + + +### **Python3** + +```python +class NumMatrix: + + def __init__(self, matrix: List[List[int]]): + m, n = len(matrix), len(matrix[0]) + self.pre = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + self.pre[i][j] = self.pre[i - 1][j] + self.pre[i][j - 1] - self.pre[i - 1][j - 1] + matrix[i - 1][j - 1] + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return self.pre[row2 + 1][col2 + 1] - self.pre[row2 + 1][col1] - self.pre[row1][col2 + 1] + self.pre[row1][col1] + + +# Your NumMatrix object will be instantiated and called as such: +# obj = NumMatrix(matrix) +# param_1 = obj.sumRegion(row1,col1,row2,col2) +``` + +### **Java** + +```java +class NumMatrix { + private int[][] pre; + + public NumMatrix(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + pre = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + return pre[row2 + 1][col2 + 1] - pre[row2 + 1][col1] - pre[row1][col2 + 1] + pre[row1][col1]; + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * int param_1 = obj.sumRegion(row1,col1,row2,col2); + */ +``` + +### **C++** + +```cpp +class NumMatrix { +public: + vector> pre; + + NumMatrix(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + pre.resize(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return pre[row2 + 1][col2 + 1] - pre[row2 + 1][col1] - pre[row1][col2 + 1] + pre[row1][col1]; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * int param_1 = obj->sumRegion(row1,col1,row2,col2); + */ +``` + +### **C++** + +```cpp +type NumMatrix struct { + pre [][]int +} + +func Constructor(matrix [][]int) NumMatrix { + m, n := len(matrix), len(matrix[0]) + pre := make([][]int, m+1) + for i := 0; i < m+1; i++ { + pre[i] = make([]int, n+1) + } + for i := 1; i < m+1; i++ { + for j := 1; j < n+1; j++ { + pre[i][j] = pre[i-1][j] + pre[i][j-1] + -pre[i-1][j-1] + matrix[i-1][j-1] + } + } + return NumMatrix{pre} +} + +func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { + return this.pre[row2+1][col2+1] - this.pre[row2+1][col1] - this.pre[row1][col2+1] + this.pre[row1][col1] +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * obj := Constructor(matrix); + * param_1 := obj.SumRegion(row1,col1,row2,col2); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0304.Range Sum Query 2D - Immutable/images/304.png b/assets/0300-0399/0304.Range Sum Query 2D - Immutable/images/304.png new file mode 100644 index 00000000..1f8c315e Binary files /dev/null and b/assets/0300-0399/0304.Range Sum Query 2D - Immutable/images/304.png differ diff --git a/assets/0300-0399/0305.Number of Islands II/README_EN.md b/assets/0300-0399/0305.Number of Islands II/README_EN.md new file mode 100644 index 00000000..1449b480 --- /dev/null +++ b/assets/0300-0399/0305.Number of Islands II/README_EN.md @@ -0,0 +1,73 @@ +# [305. Number of Islands II](https://leetcode.com/problems/number-of-islands-ii) + + + +## Description + +

You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's).

+ +

We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.

+ +

Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.

+ +

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

+ +

 

+

Example 1:

+ +
+Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
+Output: [1,1,2,3]
+Explanation:
+Initially, the 2d grid is filled with water.
+- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
+- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
+- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
+- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
+
+ +

Example 2:

+ +
+Input: m = 1, n = 1, positions = [[0,0]]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n, positions.length <= 104
  • +
  • 1 <= m * n <= 104
  • +
  • positions[i].length == 2
  • +
  • 0 <= ri < m
  • +
  • 0 <= ci < n
  • +
+ +

 

+

Follow up: Could you solve it in time complexity O(k log(mn)), where k == positions.length?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0305.Number of Islands II/images/tmp-grid.jpg b/assets/0300-0399/0305.Number of Islands II/images/tmp-grid.jpg new file mode 100644 index 00000000..a53b186c Binary files /dev/null and b/assets/0300-0399/0305.Number of Islands II/images/tmp-grid.jpg differ diff --git a/assets/0300-0399/0306.Additive Number/README_EN.md b/assets/0300-0399/0306.Additive Number/README_EN.md new file mode 100644 index 00000000..a9779b88 --- /dev/null +++ b/assets/0300-0399/0306.Additive Number/README_EN.md @@ -0,0 +1,68 @@ +# [306. Additive Number](https://leetcode.com/problems/additive-number) + + + +## Description + +

Additive number is a string whose digits can form additive sequence.

+ +

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

+ +

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.

+ +

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

+ +

 

+

Example 1:

+ +
+Input: "112358"
+Output: true
+Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 
+             1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
+
+ +

Example 2:

+ +
+Input: "199100199"
+Output: true
+Explanation: The additive sequence is: 1, 99, 100, 199. 
+             1 + 99 = 100, 99 + 100 = 199
+
+ +

 

+

Constraints:

+ +
    +
  • num consists only of digits '0'-'9'.
  • +
  • 1 <= num.length <= 35
  • +
+ +

Follow up:
+How would you handle overflow for very large input integers?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0307.Range Sum Query - Mutable/README_EN.md b/assets/0300-0399/0307.Range Sum Query - Mutable/README_EN.md new file mode 100644 index 00000000..0e8c6236 --- /dev/null +++ b/assets/0300-0399/0307.Range Sum Query - Mutable/README_EN.md @@ -0,0 +1,69 @@ +# [307. Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable) + + + +## Description + +

Given an array nums and two types of queries where you should update the value of an index in the array, and retrieve the sum of a range in the array.

+ +

Implement the NumArray class:

+ +
    +
  • NumArray(int[] nums) initializes the object with the integer array nums.
  • +
  • void update(int index, int val) updates the value of nums[index] to be val.
  • +
  • int sumRange(int left, int right) returns the sum of the subarray nums[left, right] (i.e., nums[left] + nums[left + 1], ..., nums[right]).
  • +
+ +

 

+

Example 1:

+ +
+Input
+["NumArray", "sumRange", "update", "sumRange"]
+[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
+Output
+[null, 9, null, 8]
+
+Explanation
+NumArray numArray = new NumArray([1, 3, 5]);
+numArray.sumRange(0, 2); // return 9 = sum([1,3,5])
+numArray.update(1, 2);   // nums = [1,2,5]
+numArray.sumRange(0, 2); // return 8 = sum([1,2,5])
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 3 * 104
  • +
  • -100 <= nums[i] <= 100
  • +
  • 0 <= index < nums.length
  • +
  • -100 <= val <= 100
  • +
  • 0 <= left <= right < nums.length
  • +
  • At most 3 * 104 calls will be made to update and sumRange.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md b/assets/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md new file mode 100644 index 00000000..845ebee0 --- /dev/null +++ b/assets/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md @@ -0,0 +1,73 @@ +# [308. Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable) + + + +## Description + +

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

+ +

Implement the NumMatrix class:

+ +
    +
  • NumMatrix(int[][] matrix) initializes the object with the integer matrix matrix.
  • +
  • void update(int row, int col, int val) updates the value of matrix[row][col] to be val.
  • +
  • int sumRegion(int row1, int col1, int row2, int col2) returns the sum of the elements of the matrix array inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
  • +
+ +

 

+

Example 1:

+ +
+Input
+["NumMatrix", "sumRegion", "update", "sumRegion"]
+[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]]
+Output
+[null, 8, null, 10]
+
+Explanation
+NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);
+numMatrix.sumRegion(2, 1, 4, 3); // return 8
+numMatrix.update(3, 2, 2);
+numMatrix.sumRegion(2, 1, 4, 3); // return 10
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • -105 <= matrix[i][j] <= 105
  • +
  • 0 <= row < m
  • +
  • 0 <= col < n
  • +
  • -105 <= val <= 105
  • +
  • 0 <= row1 <= row2 < m
  • +
  • 0 <= col1 <= col2 < n
  • +
  • At most 104 calls will be made to sumRegion and update.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0308.Range Sum Query 2D - Mutable/images/308_range_sum_query_2d_mutable.png b/assets/0300-0399/0308.Range Sum Query 2D - Mutable/images/308_range_sum_query_2d_mutable.png new file mode 100644 index 00000000..978018e1 Binary files /dev/null and b/assets/0300-0399/0308.Range Sum Query 2D - Mutable/images/308_range_sum_query_2d_mutable.png differ diff --git a/assets/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md b/assets/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md new file mode 100644 index 00000000..3b5cd88b --- /dev/null +++ b/assets/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md @@ -0,0 +1,123 @@ +# [309. Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) + + + +## Description + +

You are given an array prices where prices[i] is the price of a given stock on the ith day.

+ +

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

+ +
    +
  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
  • +
+ +

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

+ +

 

+

Example 1:

+ +
+Input: prices = [1,2,3,0,2]
+Output: 3
+Explanation: transactions = [buy, sell, cooldown, buy, sell]
+
+ +

Example 2:

+ +
+Input: prices = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= prices.length <= 5000
  • +
  • 0 <= prices[i] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f1, f2, f3 = -prices[0], 0, 0 + for price in prices[1:]: + pf1, pf2, pf3 = f1, f2, f3 + f1 = max(pf1, pf3 - price) + f2 = max(pf2, pf1 + price) + f3 = max(pf3, pf2) + return f2 +``` + +### **Java** + +```java +class Solution { + public int maxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0, f3 = 0; + for (int i = 1; i < prices.length; ++i) { + int pf1 = f1, pf2 = f2, pf3 = f3; + f1 = Math.max(pf1, pf3 - prices[i]); + f2 = Math.max(pf2, pf1 + prices[i]); + f3 = Math.max(pf3, pf2); + } + return f2; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f1 = -prices[0], f2 = 0, f3 = 0; + for (int i = 1; i < prices.size(); ++i) { + int pf1 = f1, pf2 = f2, pf3 = f3; + f1 = max(pf1, pf3 - prices[i]); + f2 = max(pf2, pf1 + prices[i]); + f3 = max(pf3, pf2); + } + return f2; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int) int { + f1, f2, f3 := -prices[0], 0, 0 + for i := 1; i < len(prices); i++ { + pf1, pf2, pf3 := f1, f2, f3 + f1 = max(pf1, pf3-prices[i]) + f2 = max(pf2, pf1+prices[i]) + f3 = max(pf3, pf2) + } + return f2 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0310.Minimum Height Trees/README_EN.md b/assets/0300-0399/0310.Minimum Height Trees/README_EN.md new file mode 100644 index 00000000..1fbf322e --- /dev/null +++ b/assets/0300-0399/0310.Minimum Height Trees/README_EN.md @@ -0,0 +1,80 @@ +# [310. Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees) + + + +## Description + +

A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

+ +

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).

+ +

Return a list of all MHTs' root labels. You can return the answer in any order.

+ +

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

+ +

 

+

Example 1:

+ +
+Input: n = 4, edges = [[1,0],[1,2],[1,3]]
+Output: [1]
+Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
+
+ +

Example 2:

+ +
+Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
+Output: [3,4]
+
+ +

Example 3:

+ +
+Input: n = 1, edges = []
+Output: [0]
+
+ +

Example 4:

+ +
+Input: n = 2, edges = [[0,1]]
+Output: [0,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2 * 104
  • +
  • edges.length == n - 1
  • +
  • 0 <= ai, bi < n
  • +
  • ai != bi
  • +
  • All the pairs (ai, bi) are distinct.
  • +
  • The given input is guaranteed to be a tree and there will be no repeated edges.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0310.Minimum Height Trees/images/e1.jpg b/assets/0300-0399/0310.Minimum Height Trees/images/e1.jpg new file mode 100644 index 00000000..73c5c0a8 Binary files /dev/null and b/assets/0300-0399/0310.Minimum Height Trees/images/e1.jpg differ diff --git a/assets/0300-0399/0310.Minimum Height Trees/images/e2.jpg b/assets/0300-0399/0310.Minimum Height Trees/images/e2.jpg new file mode 100644 index 00000000..51834b35 Binary files /dev/null and b/assets/0300-0399/0310.Minimum Height Trees/images/e2.jpg differ diff --git a/assets/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md b/assets/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md new file mode 100644 index 00000000..effa34bf --- /dev/null +++ b/assets/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md @@ -0,0 +1,58 @@ +# [311. Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication) + + + +## Description + +

Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible.

+ +

 

+

Example 1:

+ +
+Input: mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
+Output: [[7,0,0],[-7,0,3]]
+
+ +

Example 2:

+ +
+Input: mat1 = [[0]], mat2 = [[0]]
+Output: [[0]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat1.length
  • +
  • k == mat1[i].length == mat2.length
  • +
  • n == mat2[i].length
  • +
  • 1 <= m, n, k <= 100
  • +
  • -100 <= mat1[i][j], mat2[i][j] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0311.Sparse Matrix Multiplication/images/mult-grid.jpg b/assets/0300-0399/0311.Sparse Matrix Multiplication/images/mult-grid.jpg new file mode 100644 index 00000000..980b9600 Binary files /dev/null and b/assets/0300-0399/0311.Sparse Matrix Multiplication/images/mult-grid.jpg differ diff --git a/assets/0300-0399/0312.Burst Balloons/README_EN.md b/assets/0300-0399/0312.Burst Balloons/README_EN.md new file mode 100644 index 00000000..662d6108 --- /dev/null +++ b/assets/0300-0399/0312.Burst Balloons/README_EN.md @@ -0,0 +1,62 @@ +# [312. Burst Balloons](https://leetcode.com/problems/burst-balloons) + + + +## Description + +

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

+ +

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

+ +

Return the maximum coins you can collect by bursting the balloons wisely.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,1,5,8]
+Output: 167
+Explanation:
+nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
+coins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167
+ +

Example 2:

+ +
+Input: nums = [1,5]
+Output: 10
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 500
  • +
  • 0 <= nums[i] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0313.Super Ugly Number/README_EN.md b/assets/0300-0399/0313.Super Ugly Number/README_EN.md new file mode 100644 index 00000000..1f04646e --- /dev/null +++ b/assets/0300-0399/0313.Super Ugly Number/README_EN.md @@ -0,0 +1,64 @@ +# [313. Super Ugly Number](https://leetcode.com/problems/super-ugly-number) + + + +## Description + +

A super ugly number is a positive integer whose prime factors are in the array primes.

+ +

Given an integer n and an array of integers primes, return the nth super ugly number.

+ +

The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

+ +

 

+

Example 1:

+ +
+Input: n = 12, primes = [2,7,13,19]
+Output: 32
+Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
+
+ +

Example 2:

+ +
+Input: n = 1, primes = [2,3,5]
+Output: 1
+Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 106
  • +
  • 1 <= primes.length <= 100
  • +
  • 2 <= primes[i] <= 1000
  • +
  • primes[i] is guaranteed to be a prime number.
  • +
  • All the values of primes are unique and sorted in ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md new file mode 100644 index 00000000..aae76ade --- /dev/null +++ b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md @@ -0,0 +1,136 @@ +# [314. Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal) + + + +## Description + +

Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).

+ +

If two nodes are in the same row and column, the order should be from left to right.

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: [[9],[3,15],[20],[7]]
+
+ +

Example 2:

+ +
+Input: root = [3,9,8,4,0,1,7]
+Output: [[4],[9],[3,0,1],[8],[7]]
+
+ +

Example 3:

+ +
+Input: root = [3,9,8,4,0,1,7,null,null,null,2,5]
+Output: [[4],[9,5],[3,0,1],[8,2],[7]]
+
+ +

Example 4:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def verticalOrder(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + q = collections.deque([(root, 0)]) + offset_vals = collections.defaultdict(list) + while q: + node, offset = q.popleft() + offset_vals[offset].append(node.val) + if node.left: + q.append((node.left, offset - 1)) + if node.right: + q.append((node.right, offset + 1)) + res = [] + for _, vals in sorted(offset_vals.items(), key=lambda x: x[0]): + res.append(vals) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> verticalOrder(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Map> offsetVals = new TreeMap<>(); + Map nodeOffsets = new HashMap<>(); + Deque q = new ArrayDeque<>(); + q.offer(root); + nodeOffsets.put(root, 0); + + while (!q.isEmpty()) { + TreeNode node = q.poll(); + int offset = nodeOffsets.get(node); + if (!offsetVals.containsKey(offset)) { + offsetVals.put(offset, new ArrayList<>()); + } + offsetVals.get(offset).add(node.val); + if (node.left != null) { + q.offer(node.left); + nodeOffsets.put(node.left, offset - 1); + } + if (node.right != null) { + q.offer(node.right); + nodeOffsets.put(node.right, offset + 1); + } + } + return new ArrayList<>(offsetVals.values()); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree1.jpg b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree1.jpg new file mode 100644 index 00000000..0ba7f62d Binary files /dev/null and b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree1.jpg differ diff --git a/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree2-1.jpg b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree2-1.jpg new file mode 100644 index 00000000..7af22e72 Binary files /dev/null and b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree2-1.jpg differ diff --git a/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree2.jpg b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree2.jpg new file mode 100644 index 00000000..54494274 Binary files /dev/null and b/assets/0300-0399/0314.Binary Tree Vertical Order Traversal/images/vtree2.jpg differ diff --git a/assets/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md b/assets/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md new file mode 100644 index 00000000..275db974 --- /dev/null +++ b/assets/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md @@ -0,0 +1,67 @@ +# [315. Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self) + + + +## Description + +

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

+ +

 

+

Example 1:

+ +
+Input: nums = [5,2,6,1]
+Output: [2,1,1,0]
+Explanation:
+To the right of 5 there are 2 smaller elements (2 and 1).
+To the right of 2 there is only 1 smaller element (1).
+To the right of 6 there is 1 smaller element (1).
+To the right of 1 there is 0 smaller element.
+
+ +

Example 2:

+ +
+Input: nums = [-1]
+Output: [0]
+
+ +

Example 3:

+ +
+Input: nums = [-1,-1]
+Output: [0,0]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -104 <= nums[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0316.Remove Duplicate Letters/README_EN.md b/assets/0300-0399/0316.Remove Duplicate Letters/README_EN.md new file mode 100644 index 00000000..c5002138 --- /dev/null +++ b/assets/0300-0399/0316.Remove Duplicate Letters/README_EN.md @@ -0,0 +1,57 @@ +# [316. Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters) + + + +## Description + +

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

+ +

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

+ +

 

+

Example 1:

+ +
+Input: s = "bcabc"
+Output: "abc"
+
+ +

Example 2:

+ +
+Input: s = "cbacdcbc"
+Output: "acdb"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md b/assets/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md new file mode 100644 index 00000000..58315dcd --- /dev/null +++ b/assets/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md @@ -0,0 +1,82 @@ +# [317. Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings) + + + +## Description + +

You are given an m x n grid grid of values 0, 1, or 2, where:

+ +
    +
  • each 0 marks an empty land that you can pass by freely,
  • +
  • each 1 marks a building that you cannot pass through, and
  • +
  • each 2 marks an obstacle that you cannot pass through.
  • +
+ +

You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.

+ +

Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1.

+ +

The total travel distance is the sum of the distances between the houses of the friends and the meeting point.

+ +

The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

+ +

 

+

Example 1:

+ +
+Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
+Output: 7
+Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2).
+The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal.
+So return 7.
+
+ +

Example 2:

+ +
+Input: grid = [[1,0]]
+Output: 1
+
+ +

Example 3:

+ +
+Input: grid = [[1]]
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • grid[i][j] is either 0, 1, or 2.
  • +
  • There will be at least one building in the grid.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0317.Shortest Distance from All Buildings/images/buildings-grid.jpg b/assets/0300-0399/0317.Shortest Distance from All Buildings/images/buildings-grid.jpg new file mode 100644 index 00000000..8f026f8b Binary files /dev/null and b/assets/0300-0399/0317.Shortest Distance from All Buildings/images/buildings-grid.jpg differ diff --git a/assets/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md b/assets/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md new file mode 100644 index 00000000..fe47a594 --- /dev/null +++ b/assets/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md @@ -0,0 +1,66 @@ +# [318. Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths) + + + +## Description + +

Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.

+ +

 

+

Example 1:

+ +
+Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
+Output: 16
+Explanation: The two words can be "abcw", "xtfn".
+
+ +

Example 2:

+ +
+Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
+Output: 4
+Explanation: The two words can be "ab", "cd".
+
+ +

Example 3:

+ +
+Input: words = ["a","aa","aaa","aaaa"]
+Output: 0
+Explanation: No such pair of words.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= words.length <= 1000
  • +
  • 1 <= words[i].length <= 1000
  • +
  • words[i] consists only of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0319.Bulb Switcher/README_EN.md b/assets/0300-0399/0319.Bulb Switcher/README_EN.md new file mode 100644 index 00000000..9ca8d03d --- /dev/null +++ b/assets/0300-0399/0319.Bulb Switcher/README_EN.md @@ -0,0 +1,69 @@ +# [319. Bulb Switcher](https://leetcode.com/problems/bulb-switcher) + + + +## Description + +

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.

+ +

On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.

+ +

Return the number of bulbs that are on after n rounds.

+ +

 

+

Example 1:

+ +
+Input: n = 3
+Output: 1
+Explanation: At first, the three bulbs are [off, off, off].
+After the first round, the three bulbs are [on, on, on].
+After the second round, the three bulbs are [on, off, on].
+After the third round, the three bulbs are [on, off, off]. 
+So you should return 1 because there is only one bulb is on.
+ +

Example 2:

+ +
+Input: n = 0
+Output: 0
+
+ +

Example 3:

+ +
+Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0319.Bulb Switcher/images/bulb.jpg b/assets/0300-0399/0319.Bulb Switcher/images/bulb.jpg new file mode 100644 index 00000000..70010b9f Binary files /dev/null and b/assets/0300-0399/0319.Bulb Switcher/images/bulb.jpg differ diff --git a/assets/0300-0399/0320.Generalized Abbreviation/README_EN.md b/assets/0300-0399/0320.Generalized Abbreviation/README_EN.md new file mode 100644 index 00000000..9fca2e94 --- /dev/null +++ b/assets/0300-0399/0320.Generalized Abbreviation/README_EN.md @@ -0,0 +1,50 @@ +# [320. Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation) + + + +## Description + +

A word's generalized abbreviation can be constructed by taking any number of non-overlapping substrings and replacing them with their respective lengths. For example, "abcde" can be abbreviated into "a3e" ("bcd" turned into "3"), "1bcd1" ("a" and "e" both turned into "1"), and "23" ("ab" turned into "2" and "cde" turned into "3").

+ +

Given a string word, return a list of all the possible generalized abbreviations of word. Return the answer in any order.

+ +

 

+

Example 1:

+
Input: word = "word"
+Output: ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
+

Example 2:

+
Input: word = "a"
+Output: ["1","a"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= word.length <= 15
  • +
  • word consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0321.Create Maximum Number/README_EN.md b/assets/0300-0399/0321.Create Maximum Number/README_EN.md new file mode 100644 index 00000000..61534dab --- /dev/null +++ b/assets/0300-0399/0321.Create Maximum Number/README_EN.md @@ -0,0 +1,72 @@ +# [321. Create Maximum Number](https://leetcode.com/problems/create-maximum-number) + + + +## Description + +

You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k.

+ +

Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.

+ +

Return an array of the k digits representing the answer.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
+Output: [9,8,6,5,3]
+
+ +

Example 2:

+ +
+Input: nums1 = [6,7], nums2 = [6,0,4], k = 5
+Output: [6,7,6,0,4]
+
+ +

Example 3:

+ +
+Input: nums1 = [3,9], nums2 = [8,9], k = 3
+Output: [9,8,9]
+
+ +

 

+

Constraints:

+ +
    +
  • m == nums1.length
  • +
  • n == nums2.length
  • +
  • 1 <= m, n <= 500
  • +
  • 0 <= nums1[i], nums2[i] <= 9
  • +
  • 1 <= k <= m + n
  • +
+ +

 

+

Follow up: Try to optimize your time and space complexity.

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0322.Coin Change/README_EN.md b/assets/0300-0399/0322.Coin Change/README_EN.md new file mode 100644 index 00000000..0427b646 --- /dev/null +++ b/assets/0300-0399/0322.Coin Change/README_EN.md @@ -0,0 +1,135 @@ +# [322. Coin Change](https://leetcode.com/problems/coin-change) + + + +## Description + +

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

+ +

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

+ +

You may assume that you have an infinite number of each kind of coin.

+ +

 

+

Example 1:

+ +
+Input: coins = [1,2,5], amount = 11
+Output: 3
+Explanation: 11 = 5 + 5 + 1
+
+ +

Example 2:

+ +
+Input: coins = [2], amount = 3
+Output: -1
+
+ +

Example 3:

+ +
+Input: coins = [1], amount = 0
+Output: 0
+
+ +

Example 4:

+ +
+Input: coins = [1], amount = 1
+Output: 1
+
+ +

Example 5:

+ +
+Input: coins = [1], amount = 2
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= coins.length <= 12
  • +
  • 1 <= coins[i] <= 231 - 1
  • +
  • 0 <= amount <= 104
  • +
+ + +## Solutions + +Similar to the idea of ​​a complete backpack, there is no limit to the number of coins. Find the minimum number of coins required to make up the total amount. + + + +### **Python3** + +```python +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + for coin in coins: + for j in range(coin, amount + 1): + dp[j] = min(dp[j], dp[j - coin] + 1) + return -1 if dp[amount] > amount else dp[amount] +``` + +### **Java** + +```java +class Solution { + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount + 1]; + Arrays.fill(dp, amount + 1); + dp[0] = 0; + for (int coin : coins) { + for (int j = coin; j <= amount; j++) { + dp[j] = Math.min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function (coins, amount) { + let dp = Array(amount + 1).fill(amount + 1); + dp[0] = 0; + for (const coin of coins) { + for (let j = coin; j <= amount; ++j) { + dp[j] = Math.min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); + dp[0] = 0; + for (auto coin : coins) { + for (int j = coin; j <= amount; ++j) { + dp[j] = min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } +}; +``` + + diff --git a/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md b/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md new file mode 100644 index 00000000..27092e51 --- /dev/null +++ b/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md @@ -0,0 +1,61 @@ +# [323. Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph) + + + +## Description + +

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.

+ +

Return the number of connected components in the graph.

+ +

 

+

Example 1:

+ +
+Input: n = 5, edges = [[0,1],[1,2],[3,4]]
+Output: 2
+
+ +

Example 2:

+ +
+Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 2000
  • +
  • 1 <= edges.length <= 5000
  • +
  • edges[i].length == 2
  • +
  • 0 <= ai <= bi < n
  • +
  • ai != bi
  • +
  • There are no repeated edges.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/images/conn1-graph.jpg b/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/images/conn1-graph.jpg new file mode 100644 index 00000000..999b444d Binary files /dev/null and b/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/images/conn1-graph.jpg differ diff --git a/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/images/conn2-graph.jpg b/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/images/conn2-graph.jpg new file mode 100644 index 00000000..759209b3 Binary files /dev/null and b/assets/0300-0399/0323.Number of Connected Components in an Undirected Graph/images/conn2-graph.jpg differ diff --git a/assets/0300-0399/0324.Wiggle Sort II/README_EN.md b/assets/0300-0399/0324.Wiggle Sort II/README_EN.md new file mode 100644 index 00000000..d22f3297 --- /dev/null +++ b/assets/0300-0399/0324.Wiggle Sort II/README_EN.md @@ -0,0 +1,61 @@ +# [324. Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii) + + + +## Description + +

Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

+ +

You may assume the input array always has a valid answer.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,5,1,1,6,4]
+Output: [1,6,1,5,1,4]
+Explanation: [1,4,1,5,1,6] is also accepted.
+
+ +

Example 2:

+ +
+Input: nums = [1,3,2,2,3,1]
+Output: [2,3,1,3,1,2]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 0 <= nums[i] <= 5000
  • +
  • It is guaranteed that there will be an answer for the given input nums.
  • +
+ +

 

+Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md b/assets/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md new file mode 100644 index 00000000..6dc43a85 --- /dev/null +++ b/assets/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md @@ -0,0 +1,61 @@ +# [325. Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k) + + + +## Description + +

Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,-1,5,-2,3], k = 3
+Output: 4
+Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
+
+ +

Example 2:

+ +
+Input: nums = [-2,-1,2,1], k = 1
+Output: 2
+Explanation: The subarray [-1, 2] sums to 1 and is the longest.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
  • -105 <= k <= 105
  • +
+ +

 

+

Follow Up: Can you do it in O(n) time?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0326.Power of Three/README_EN.md b/assets/0300-0399/0326.Power of Three/README_EN.md new file mode 100644 index 00000000..2bb1620e --- /dev/null +++ b/assets/0300-0399/0326.Power of Three/README_EN.md @@ -0,0 +1,57 @@ +# [326. Power of Three](https://leetcode.com/problems/power-of-three) + + + +## Description + +

Given an integer n, return true if it is a power of three. Otherwise, return false.

+ +

An integer n is a power of three, if there exists an integer x such that n == 3x.

+ +

 

+

Example 1:

+
Input: n = 27
+Output: true
+

Example 2:

+
Input: n = 0
+Output: false
+

Example 3:

+
Input: n = 9
+Output: true
+

Example 4:

+
Input: n = 45
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0327.Count of Range Sum/README_EN.md b/assets/0300-0399/0327.Count of Range Sum/README_EN.md new file mode 100644 index 00000000..1a1a78de --- /dev/null +++ b/assets/0300-0399/0327.Count of Range Sum/README_EN.md @@ -0,0 +1,61 @@ +# [327. Count of Range Sum](https://leetcode.com/problems/count-of-range-sum) + + + +## Description + +

Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.

+ +

Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.

+ +

 

+

Example 1:

+ +
+Input: nums = [-2,5,-1], lower = -2, upper = 2
+Output: 3
+Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.
+
+ +

Example 2:

+ +
+Input: nums = [0], lower = 0, upper = 0
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • -3 * 104 <= lower <= upper <= 3 * 104
  • +
+ +

 

+Follow up: A naive algorithm of O(n2) is trivial, Could you do better than that? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0328.Odd Even Linked List/README_EN.md b/assets/0300-0399/0328.Odd Even Linked List/README_EN.md new file mode 100644 index 00000000..0f8a5c83 --- /dev/null +++ b/assets/0300-0399/0328.Odd Even Linked List/README_EN.md @@ -0,0 +1,194 @@ +# [328. Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list) + + + +## Description + +

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

+ +

The first node is considered odd, and the second node is even, and so on.

+ +

Note that the relative order inside both the even and odd groups should remain as it was in the input.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5]
+Output: [1,3,5,2,4]
+
+ +

Example 2:

+ +
+Input: head = [2,1,3,5,6,4,7]
+Output: [2,3,6,7,1,5,4]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the linked list is in the range [0, 104].
  • +
  • -106 <= Node.val <= 106
  • +
+ +

 

+Follow up: Could you solve it in O(1) space complexity and O(nodes) time complexity? + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def oddEvenList(self, head: ListNode) -> ListNode: + if head is None: + return head + odd, even = head, head.next + even_head = even + while even and even.next: + odd.next = even.next + odd = odd.next + even.next = odd.next + even = even.next + odd.next = even_head + return head +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode oddEvenList(ListNode head) { + if (head == null) { + return head; + } + ListNode odd = head, even = head.next; + ListNode evenHead = even; + while (even != null && even.next != null) { + odd.next = even.next; + odd = odd.next; + even.next = odd.next; + even = even.next; + } + odd.next = evenHead; + return head; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function oddEvenList(head: ListNode | null): ListNode | null { + if (head == null) return head; + let odd: ListNode = head, even: ListNode = head.next; + let evenHead = even; + while (even != null && even.next != null) { + odd.next = even.next; + odd = odd.next; + even.next = odd.next; + even = even.next; + } + odd.next = evenHead; + return head; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + if (!head) { + return head; + } + ListNode *odd = head, *even = head->next; + ListNode *evenHead = even; + while (even && even->next) { + odd->next = even->next; + odd = odd->next; + even->next = odd->next; + even = even->next; + } + odd->next = evenHead; + return head; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func oddEvenList(head *ListNode) *ListNode { + if head == nil { + return head + } + odd, even := head, head.Next + evenHead := even + for even != nil && even.Next != nil { + odd.Next = even.Next + odd = odd.Next + even.Next = odd.Next + even = even.Next + } + odd.Next = evenHead + return head +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0328.Odd Even Linked List/images/oddeven-linked-list.jpg b/assets/0300-0399/0328.Odd Even Linked List/images/oddeven-linked-list.jpg new file mode 100644 index 00000000..d981f2d6 Binary files /dev/null and b/assets/0300-0399/0328.Odd Even Linked List/images/oddeven-linked-list.jpg differ diff --git a/assets/0300-0399/0328.Odd Even Linked List/images/oddeven2-linked-list.jpg b/assets/0300-0399/0328.Odd Even Linked List/images/oddeven2-linked-list.jpg new file mode 100644 index 00000000..e910a528 Binary files /dev/null and b/assets/0300-0399/0328.Odd Even Linked List/images/oddeven2-linked-list.jpg differ diff --git a/assets/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md b/assets/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md new file mode 100644 index 00000000..5ccd58b5 --- /dev/null +++ b/assets/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md @@ -0,0 +1,68 @@ +# [329. Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix) + + + +## Description + +

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

+ +

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

+ +

 

+

Example 1:

+ +
+Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
+Output: 4
+Explanation: The longest increasing path is [1, 2, 6, 9].
+
+ +

Example 2:

+ +
+Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
+Output: 4
+Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
+
+ +

Example 3:

+ +
+Input: matrix = [[1]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 0 <= matrix[i][j] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0329.Longest Increasing Path in a Matrix/images/grid1.jpg b/assets/0300-0399/0329.Longest Increasing Path in a Matrix/images/grid1.jpg new file mode 100644 index 00000000..332e9bdd Binary files /dev/null and b/assets/0300-0399/0329.Longest Increasing Path in a Matrix/images/grid1.jpg differ diff --git a/assets/0300-0399/0329.Longest Increasing Path in a Matrix/images/tmp-grid.jpg b/assets/0300-0399/0329.Longest Increasing Path in a Matrix/images/tmp-grid.jpg new file mode 100644 index 00000000..bc2831d6 Binary files /dev/null and b/assets/0300-0399/0329.Longest Increasing Path in a Matrix/images/tmp-grid.jpg differ diff --git a/assets/0300-0399/0330.Patching Array/README_EN.md b/assets/0300-0399/0330.Patching Array/README_EN.md new file mode 100644 index 00000000..f36cbe8b --- /dev/null +++ b/assets/0300-0399/0330.Patching Array/README_EN.md @@ -0,0 +1,72 @@ +# [330. Patching Array](https://leetcode.com/problems/patching-array) + + + +## Description + +

Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.

+ +

Return the minimum number of patches required.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,3], n = 6
+Output: 1
+Explanation:
+Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
+Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
+Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
+So we only need 1 patch.
+
+ +

Example 2:

+ +
+Input: nums = [1,5,10], n = 20
+Output: 2
+Explanation: The two patches can be [2, 4].
+
+ +

Example 3:

+ +
+Input: nums = [1,2,2], n = 5
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 104
  • +
  • nums is sorted in ascending order.
  • +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md b/assets/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md new file mode 100644 index 00000000..3702fafc --- /dev/null +++ b/assets/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md @@ -0,0 +1,66 @@ +# [331. Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree) + + + +## Description + +

One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.

+ +

For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a null node.

+ +

Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.

+ +

It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer.

+ +

You may assume that the input format is always valid.

+ +
    +
  • For example, it could never contain two consecutive commas, such as "1,,3".
  • +
+ +

 

+

Example 1:

+
Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
+Output: true
+

Example 2:

+
Input: preorder = "1,#"
+Output: false
+

Example 3:

+
Input: preorder = "9,#,#,1"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= preorder.length <= 104
  • +
  • preoder consist of integers in the range [0, 100] and '#' separated by commas ','.
  • +
+ +

 

+

Follow up: Find an algorithm without reconstructing the tree.

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/images/pre-tree.jpg b/assets/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/images/pre-tree.jpg new file mode 100644 index 00000000..c7573830 Binary files /dev/null and b/assets/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/images/pre-tree.jpg differ diff --git a/assets/0300-0399/0332.Reconstruct Itinerary/README_EN.md b/assets/0300-0399/0332.Reconstruct Itinerary/README_EN.md new file mode 100644 index 00000000..09a242fc --- /dev/null +++ b/assets/0300-0399/0332.Reconstruct Itinerary/README_EN.md @@ -0,0 +1,68 @@ +# [332. Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary) + + + +## Description + +

You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

+ +

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

+ +
    +
  • For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
  • +
+ +

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

+ +

 

+

Example 1:

+ +
+Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
+Output: ["JFK","MUC","LHR","SFO","SJC"]
+
+ +

Example 2:

+ +
+Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
+Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
+Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= tickets.length <= 300
  • +
  • tickets[i].length == 2
  • +
  • fromi.length == 3
  • +
  • toi.length == 3
  • +
  • fromi and toi consist of uppercase English letters.
  • +
  • fromi != toi
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0332.Reconstruct Itinerary/images/itinerary1-graph.jpg b/assets/0300-0399/0332.Reconstruct Itinerary/images/itinerary1-graph.jpg new file mode 100644 index 00000000..4e79c7c1 Binary files /dev/null and b/assets/0300-0399/0332.Reconstruct Itinerary/images/itinerary1-graph.jpg differ diff --git a/assets/0300-0399/0332.Reconstruct Itinerary/images/itinerary2-graph.jpg b/assets/0300-0399/0332.Reconstruct Itinerary/images/itinerary2-graph.jpg new file mode 100644 index 00000000..fa6ed2ae Binary files /dev/null and b/assets/0300-0399/0332.Reconstruct Itinerary/images/itinerary2-graph.jpg differ diff --git a/assets/0300-0399/0333.Largest BST Subtree/README_EN.md b/assets/0300-0399/0333.Largest BST Subtree/README_EN.md new file mode 100644 index 00000000..1e227cea --- /dev/null +++ b/assets/0300-0399/0333.Largest BST Subtree/README_EN.md @@ -0,0 +1,68 @@ +# [333. Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree) + + + +## Description + +

Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.

+ +

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties:

+ +
    +
  • The left subtree values are less than the value of their parent (root) node's value.
  • +
  • The right subtree values are greater than the value of their parent (root) node's value.
  • +
+ +

Note: A subtree must include all of its descendants.

+ +

Follow up: Can you figure out ways to solve it with O(n) time complexity?

+ +

 

+

Example 1:

+ +

+ +
+Input: root = [10,5,15,1,8,null,7]
+Output: 3
+Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
+ +

Example 2:

+ +
+Input: root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -104 <= Node.val <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0333.Largest BST Subtree/images/tmp.jpg b/assets/0300-0399/0333.Largest BST Subtree/images/tmp.jpg new file mode 100644 index 00000000..5476aca3 Binary files /dev/null and b/assets/0300-0399/0333.Largest BST Subtree/images/tmp.jpg differ diff --git a/assets/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md b/assets/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md new file mode 100644 index 00000000..692681e0 --- /dev/null +++ b/assets/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md @@ -0,0 +1,67 @@ +# [334. Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence) + + + +## Description + +

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,4,5]
+Output: true
+Explanation: Any triplet where i < j < k is valid.
+
+ +

Example 2:

+ +
+Input: nums = [5,4,3,2,1]
+Output: false
+Explanation: No triplet exists.
+
+ +

Example 3:

+ +
+Input: nums = [2,1,5,0,4,6]
+Output: true
+Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0335.Self Crossing/README_EN.md b/assets/0300-0399/0335.Self Crossing/README_EN.md new file mode 100644 index 00000000..72c357bb --- /dev/null +++ b/assets/0300-0399/0335.Self Crossing/README_EN.md @@ -0,0 +1,69 @@ +# [335. Self Crossing](https://leetcode.com/problems/self-crossing) + + + +## Description + +

You are given an array of integers distance.

+ +

You start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.

+ +

Return true if your path crosses itself, and false if it does not.

+ +

 

+

Example 1:

+ +
+Input: distance = [2,1,1,2]
+Output: true
+
+ +

Example 2:

+ +
+Input: distance = [1,2,3,4]
+Output: false
+
+ +

Example 3:

+ +
+Input: distance = [1,1,1,1]
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= distance.length <= 500
  • +
  • 1 <= distance[i] <= 500
  • +
+ +

 

+

Follow up: Could you write a one-pass algorithm with O(1) extra space?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0335.Self Crossing/images/selfcross1-plane.jpg b/assets/0300-0399/0335.Self Crossing/images/selfcross1-plane.jpg new file mode 100644 index 00000000..81b208be Binary files /dev/null and b/assets/0300-0399/0335.Self Crossing/images/selfcross1-plane.jpg differ diff --git a/assets/0300-0399/0335.Self Crossing/images/selfcross2-plane.jpg b/assets/0300-0399/0335.Self Crossing/images/selfcross2-plane.jpg new file mode 100644 index 00000000..d895df44 Binary files /dev/null and b/assets/0300-0399/0335.Self Crossing/images/selfcross2-plane.jpg differ diff --git a/assets/0300-0399/0335.Self Crossing/images/selfcross3-plane.jpg b/assets/0300-0399/0335.Self Crossing/images/selfcross3-plane.jpg new file mode 100644 index 00000000..3faaadf6 Binary files /dev/null and b/assets/0300-0399/0335.Self Crossing/images/selfcross3-plane.jpg differ diff --git a/assets/0300-0399/0336.Palindrome Pairs/README_EN.md b/assets/0300-0399/0336.Palindrome Pairs/README_EN.md new file mode 100644 index 00000000..318e2d19 --- /dev/null +++ b/assets/0300-0399/0336.Palindrome Pairs/README_EN.md @@ -0,0 +1,65 @@ +# [336. Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs) + + + +## Description + +

Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome.

+ +

 

+

Example 1:

+ +
+Input: words = ["abcd","dcba","lls","s","sssll"]
+Output: [[0,1],[1,0],[3,2],[2,4]]
+Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
+
+ +

Example 2:

+ +
+Input: words = ["bat","tab","cat"]
+Output: [[0,1],[1,0]]
+Explanation: The palindromes are ["battab","tabbat"]
+
+ +

Example 3:

+ +
+Input: words = ["a",""]
+Output: [[0,1],[1,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 5000
  • +
  • 0 <= words[i].length <= 300
  • +
  • words[i] consists of lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0337.House Robber III/README_EN.md b/assets/0300-0399/0337.House Robber III/README_EN.md new file mode 100644 index 00000000..ef34d036 --- /dev/null +++ b/assets/0300-0399/0337.House Robber III/README_EN.md @@ -0,0 +1,61 @@ +# [337. House Robber III](https://leetcode.com/problems/house-robber-iii) + + + +## Description + +

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

+ +

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

+ +

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

+ +

 

+

Example 1:

+ +
+Input: root = [3,2,3,null,3,null,1]
+Output: 7
+Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
+
+ +

Example 2:

+ +
+Input: root = [3,4,5,1,3,null,1]
+Output: 9
+Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • 0 <= Node.val <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0337.House Robber III/images/rob1-tree.jpg b/assets/0300-0399/0337.House Robber III/images/rob1-tree.jpg new file mode 100644 index 00000000..b8b0afad Binary files /dev/null and b/assets/0300-0399/0337.House Robber III/images/rob1-tree.jpg differ diff --git a/assets/0300-0399/0337.House Robber III/images/rob2-tree.jpg b/assets/0300-0399/0337.House Robber III/images/rob2-tree.jpg new file mode 100644 index 00000000..d782ae46 Binary files /dev/null and b/assets/0300-0399/0337.House Robber III/images/rob2-tree.jpg differ diff --git a/assets/0300-0399/0338.Counting Bits/README_EN.md b/assets/0300-0399/0338.Counting Bits/README_EN.md new file mode 100644 index 00000000..0c6f1290 --- /dev/null +++ b/assets/0300-0399/0338.Counting Bits/README_EN.md @@ -0,0 +1,74 @@ +# [338. Counting Bits](https://leetcode.com/problems/counting-bits) + + + +## Description + +

Given an integer num, return an array of the number of 1's in the binary representation of every number in the range [0, num].

+ +

 

+

Example 1:

+ +
+Input: num = 2
+Output: [0,1,1]
+Explanation:
+0 --> 0
+1 --> 1
+2 --> 10
+
+ +

Example 2:

+ +
+Input: num = 5
+Output: [0,1,1,2,1,2]
+Explanation:
+0 --> 0
+1 --> 1
+2 --> 10
+3 --> 11
+4 --> 100
+5 --> 101
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= num <= 105
  • +
+ +

 

+

Follow up:

+ +
    +
  • It is very easy to come up with a solution with run time O(32n). Can you do it in linear time O(n) and possibly in a single pass?
  • +
  • Could you solve it in O(n) space complexity?
  • +
  • Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0339.Nested List Weight Sum/README_EN.md b/assets/0300-0399/0339.Nested List Weight Sum/README_EN.md new file mode 100644 index 00000000..10994d82 --- /dev/null +++ b/assets/0300-0399/0339.Nested List Weight Sum/README_EN.md @@ -0,0 +1,224 @@ +# [339. Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum) + + + +## Description + +

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists.

+ +

The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth.

+ +

Return the sum of each integer in nestedList multiplied by its depth.

+ +

 

+

Example 1:

+ +
+Input: nestedList = [[1,1],2,[1,1]]
+Output: 10
+Explanation: Four 1's at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10.
+
+ +

Example 2:

+ +
+Input: nestedList = [1,[4,[6]]]
+Output: 27
+Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.
+ +

Example 3:

+ +
+Input: nestedList = [0]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nestedList.length <= 50
  • +
  • The values of the integers in the nested list is in the range [-100, 100].
  • +
  • The maximum depth of any integer is less than or equal to 50.
  • +
+ +## Solutions + + + +### **Python3** + +```python +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger: +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ +class Solution: + def depthSum(self, nestedList: List[NestedInteger]) -> int: + def dfs(nestedList, depth): + depth_sum = 0 + for item in nestedList: + if item.isInteger(): + depth_sum += item.getInteger() * depth + else: + depth_sum += dfs(item.getList(), depth + 1) + return depth_sum + return dfs(nestedList, 1) +``` + +### **Java** + +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public int depthSum(List nestedList) { + return dfs(nestedList, 1); + } + + private int dfs(List nestedList, int depth) { + int depthSum = 0; + for (NestedInteger item : nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth + 1); + } + } + return depthSum; + } +} +``` + +### **JavaScript** + +```js +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * function NestedInteger() { + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * @return {boolean} + * this.isInteger = function() { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * @return {integer} + * this.getInteger = function() { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * @return {void} + * this.setInteger = function(value) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * @return {void} + * this.add = function(elem) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, if it holds a nested list + * Return null if this NestedInteger holds a single integer + * @return {NestedInteger[]} + * this.getList = function() { + * ... + * }; + * }; + */ +/** + * @param {NestedInteger[]} nestedList + * @return {number} + */ +var depthSum = function (nestedList) { + const dfs = (nestedList, depth) => { + let depthSum = 0; + for (const item of nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth + 1); + } + } + return depthSum; + }; + return dfs(nestedList, 1); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0339.Nested List Weight Sum/images/nestedlistweightsumex1.png b/assets/0300-0399/0339.Nested List Weight Sum/images/nestedlistweightsumex1.png new file mode 100644 index 00000000..d630f773 Binary files /dev/null and b/assets/0300-0399/0339.Nested List Weight Sum/images/nestedlistweightsumex1.png differ diff --git a/assets/0300-0399/0339.Nested List Weight Sum/images/nestedlistweightsumex2.png b/assets/0300-0399/0339.Nested List Weight Sum/images/nestedlistweightsumex2.png new file mode 100644 index 00000000..56519871 Binary files /dev/null and b/assets/0300-0399/0339.Nested List Weight Sum/images/nestedlistweightsumex2.png differ diff --git a/assets/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md b/assets/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md new file mode 100644 index 00000000..05de0d53 --- /dev/null +++ b/assets/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md @@ -0,0 +1,56 @@ +# [340. Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters) + + + +## Description + +

Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.

+ +

 

+

Example 1:

+ +
+Input: s = "eceba", k = 2
+Output: 3
+Explanation: The substring is "ece" with length 3.
+ +

Example 2:

+ +
+Input: s = "aa", k = 1
+Output: 2
+Explanation: The substring is "aa" with length 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • 0 <= k <= 50
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0341.Flatten Nested List Iterator/README_EN.md b/assets/0300-0399/0341.Flatten Nested List Iterator/README_EN.md new file mode 100644 index 00000000..d858ce7b --- /dev/null +++ b/assets/0300-0399/0341.Flatten Nested List Iterator/README_EN.md @@ -0,0 +1,164 @@ +# [341. Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator) + + + +## Description + +

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

+ +

Implement the NestedIterator class:

+ +
    +
  • NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
  • +
  • int next() Returns the next integer in the nested list.
  • +
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
  • +
+ +

 

+

Example 1:

+ +
+Input: nestedList = [[1,1],2,[1,1]]
+Output: [1,1,2,1,1]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
+
+ +

Example 2:

+ +
+Input: nestedList = [1,[4,[6]]]
+Output: [1,4,6]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nestedList.length <= 500
  • +
  • The values of the integers in the nested list is in the range [-106, 106].
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger: +# def isInteger(self) -> bool: +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# """ +# +# def getInteger(self) -> int: +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# """ +# +# def getList(self) -> [NestedInteger]: +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# """ + +class NestedIterator: + def __init__(self, nestedList: [NestedInteger]): + def dfs(nestedList): + for e in nestedList: + if e.isInteger(): + self.vals.append(e.getInteger()) + else: + dfs(e.getList()) + + self.vals = [] + dfs(nestedList) + self.cur = 0 + + def next(self) -> int: + res = self.vals[self.cur] + self.cur += 1 + return res + + def hasNext(self) -> bool: + return self.cur < len(self.vals) + +# Your NestedIterator object will be instantiated and called as such: +# i, v = NestedIterator(nestedList), [] +# while i.hasNext(): v.append(i.next()) +``` + +### **Java** + +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return null if this NestedInteger holds a single integer + * public List getList(); + * } + */ +public class NestedIterator implements Iterator { + + private List vals; + + private Iterator cur; + + public NestedIterator(List nestedList) { + vals = new ArrayList<>(); + dfs(nestedList); + cur = vals.iterator(); + } + + @Override + public Integer next() { + return cur.next(); + } + + @Override + public boolean hasNext() { + return cur.hasNext(); + } + + private void dfs(List nestedList) { + for (NestedInteger e : nestedList) { + if (e.isInteger()) { + vals.add(e.getInteger()); + } else { + dfs(e.getList()); + } + } + } +} + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i = new NestedIterator(nestedList); + * while (i.hasNext()) v[f()] = i.next(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0342.Power of Four/README_EN.md b/assets/0300-0399/0342.Power of Four/README_EN.md new file mode 100644 index 00000000..f61292d3 --- /dev/null +++ b/assets/0300-0399/0342.Power of Four/README_EN.md @@ -0,0 +1,99 @@ +# [342. Power of Four](https://leetcode.com/problems/power-of-four) + + + +## Description + +

Given an integer n, return true if it is a power of four. Otherwise, return false.

+ +

An integer n is a power of four, if there exists an integer x such that n == 4x.

+ +

 

+

Example 1:

+
Input: n = 16
+Output: true
+

Example 2:

+
Input: n = 5
+Output: false
+

Example 3:

+
Input: n = 1
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • -231 <= n <= 231 - 1
  • +
+ +

 

+Follow up: Could you solve it without loops/recursion? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 and (n & 0xaaaaaaaa) == 0 +``` + +### **Java** + +```java +class Solution { + public boolean isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function(n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; +}; +``` + +### **Go** + +```go +func isPowerOfFour(n int) bool { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0 +} +``` + +### **TypeScript** + +```ts +function isPowerOfFour(n: number): boolean { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0343.Integer Break/README_EN.md b/assets/0300-0399/0343.Integer Break/README_EN.md new file mode 100644 index 00000000..4048dfa4 --- /dev/null +++ b/assets/0300-0399/0343.Integer Break/README_EN.md @@ -0,0 +1,58 @@ +# [343. Integer Break](https://leetcode.com/problems/integer-break) + + + +## Description + +

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

+ +

Return the maximum product you can get.

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 1
+Explanation: 2 = 1 + 1, 1 × 1 = 1.
+
+ +

Example 2:

+ +
+Input: n = 10
+Output: 36
+Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 58
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0344.Reverse String/README_EN.md b/assets/0300-0399/0344.Reverse String/README_EN.md new file mode 100644 index 00000000..c15a29c0 --- /dev/null +++ b/assets/0300-0399/0344.Reverse String/README_EN.md @@ -0,0 +1,69 @@ +# [344. Reverse String](https://leetcode.com/problems/reverse-string) + + + +## Description + +

Write a function that reverses a string. The input string is given as an array of characters s.

+ +

 

+

Example 1:

+
Input: s = ["h","e","l","l","o"]
+Output: ["o","l","l","e","h"]
+

Example 2:

+
Input: s = ["H","a","n","n","a","h"]
+Output: ["h","a","n","n","a","H"]
+
+

 

+

Constraints:

+ + + +

 

+

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

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + s[:] = s[::-1] +``` + +### **Java** + +```java +class Solution { + public void reverseString(char[] s) { + int n; + if (s == null || (n = s.length) < 2) return; + int i = 0, j = n - 1; + while (i < j) { + char t = s[i]; + s[i] = s[j]; + s[j] = t; + ++i; + --j; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0345.Reverse Vowels of a String/README_EN.md b/assets/0300-0399/0345.Reverse Vowels of a String/README_EN.md new file mode 100644 index 00000000..32530e4c --- /dev/null +++ b/assets/0300-0399/0345.Reverse Vowels of a String/README_EN.md @@ -0,0 +1,87 @@ +# [345. Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string) + + + +## Description + +

Given a string s, reverse only all the vowels in the string and return it.

+ +

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

+ +

 

+

Example 1:

+
Input: s = "hello"
+Output: "holle"
+

Example 2:

+
Input: s = "leetcode"
+Output: "leotcede"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 3 * 105
  • +
  • s consist of printable ASCII characters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def reverseVowels(self, s: str) -> str: + vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} + i, j = 0, len(s) - 1 + chars = list(s) + while i < j: + if chars[i] not in vowels: + i += 1 + continue + if chars[j] not in vowels: + j -= 1 + continue + chars[i], chars[j] = chars[j], chars[i] + i += 1 + j -= 1 + return ''.join(chars) +``` + +### **Java** + +```java +class Solution { + public String reverseVowels(String s) { + Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); + int i = 0, j = s.length() - 1; + char[] chars = s.toCharArray(); + while (i < j) { + if (!vowels.contains(chars[i])) { + ++i; + continue; + } + if (!vowels.contains(chars[j])) { + --j; + continue; + } + char t = chars[i]; + chars[i] = chars[j]; + chars[j] = t; + ++i; + --j; + } + return new String(chars); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0346.Moving Average from Data Stream/README_EN.md b/assets/0300-0399/0346.Moving Average from Data Stream/README_EN.md new file mode 100644 index 00000000..c622c9a6 --- /dev/null +++ b/assets/0300-0399/0346.Moving Average from Data Stream/README_EN.md @@ -0,0 +1,113 @@ +# [346. Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream) + + + +## Description + +

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

+ +

Implement the MovingAverage class:

+ +
    +
  • MovingAverage(int size) Initializes the object with the size of the window size.
  • +
  • double next(int val) Returns the moving average of the last size values of the stream.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MovingAverage", "next", "next", "next", "next"]
+[[3], [1], [10], [3], [5]]
+Output
+[null, 1.0, 5.5, 4.66667, 6.0]
+
+Explanation
+MovingAverage movingAverage = new MovingAverage(3);
+movingAverage.next(1); // return 1.0 = 1 / 1
+movingAverage.next(10); // return 5.5 = (1 + 10) / 2
+movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
+movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= size <= 1000
  • +
  • -105 <= val <= 105
  • +
  • At most 104 calls will be made to next.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class MovingAverage: + + def __init__(self, size: int): + """ + Initialize your data structure here. + """ + self.size = size + self.data = [0] * size + self.count = 0 + self.s = 0 + + def next(self, val: int) -> float: + idx = self.count % self.size + old_val = self.data[idx] + self.data[idx] = val + self.s += (val - old_val) + self.count += 1 + return self.s / min(self.size, self.count) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) +``` + +### **Java** + +```java +class MovingAverage { + private int size; + private int[] data; + private int count; + private int s; + + /** Initialize your data structure here. */ + public MovingAverage(int size) { + this.size = size; + this.data = new int[size]; + } + + public double next(int val) { + int idx = count % size; + int oldVal = data[idx]; + data[idx] = val; + s += (val - oldVal); + ++count; + return s * 1.0 / Math.min(size, count); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0347.Top K Frequent Elements/README_EN.md b/assets/0300-0399/0347.Top K Frequent Elements/README_EN.md new file mode 100644 index 00000000..193c5759 --- /dev/null +++ b/assets/0300-0399/0347.Top K Frequent Elements/README_EN.md @@ -0,0 +1,95 @@ +# [347. Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements) + + + +## Description + +

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

+ +

 

+

Example 1:

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

Example 2:

+
Input: nums = [1], k = 1
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • k is in the range [1, the number of unique elements in the array].
  • +
  • It is guaranteed that the answer is unique.
  • +
+ +

 

+

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + counter = collections.Counter(nums) + buckets = [[] for _ in range(len(nums) + 1)] + for num, freq in counter.items(): + buckets[freq].append(num) + i, res = len(nums), [] + while k > 0 and i >= 0: + if buckets[i]: + for num in buckets[i]: + if k <= 0: + break + res.append(num) + k -= 1 + i -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map counter = new HashMap<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + List[] buckets = new List[nums.length + 1]; + for (Map.Entry entry : counter.entrySet()) { + int num = entry.getKey(); + int freq = entry.getValue(); + if (buckets[freq] == null) { + buckets[freq] = new ArrayList<>(); + } + buckets[freq].add(num); + } + int[] res = new int[k]; + for (int i = nums.length; i >= 0 && k > 0; --i) { + if (buckets[i] != null) { + for (int num : buckets[i]) { + if (k <= 0) { + break; + } + res[--k] = num; + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md b/assets/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md new file mode 100644 index 00000000..30d95b62 --- /dev/null +++ b/assets/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md @@ -0,0 +1,179 @@ +# [348. Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe) + + + +## Description + +

Assume the following rules are for the tic-tac-toe game on an n x n board between two players:

+ +
    +
  1. A move is guaranteed to be valid and is placed on an empty block.
  2. +
  3. Once a winning condition is reached, no more moves are allowed.
  4. +
  5. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
  6. +
+ +

Implement the TicTacToe class:

+ +
    +
  • TicTacToe(int n) Initializes the object the size of the board n.
  • +
  • int move(int row, int col, int player) Indicates that player with id player plays at the cell (row, col) of the board. The move is guaranteed to be a valid move.
  • +
+ +

Follow up:
+Could you do better than O(n2) per move() operation?

+ +

 

+

Example 1:

+ +
+Input
+["TicTacToe", "move", "move", "move", "move", "move", "move", "move"]
+[[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]]
+Output
+[null, 0, 0, 0, 0, 0, 0, 1]
+
+Explanation
+TicTacToe ticTacToe = new TicTacToe(3);
+Assume that player 1 is "X" and player 2 is "O" in the board.
+ticTacToe.move(0, 0, 1); // return 0 (no one wins)
+|X| | |
+| | | |    // Player 1 makes a move at (0, 0).
+| | | |
+
+ticTacToe.move(0, 2, 2); // return 0 (no one wins)
+|X| |O|
+| | | |    // Player 2 makes a move at (0, 2).
+| | | |
+
+ticTacToe.move(2, 2, 1); // return 0 (no one wins)
+|X| |O|
+| | | |    // Player 1 makes a move at (2, 2).
+| | |X|
+
+ticTacToe.move(1, 1, 2); // return 0 (no one wins)
+|X| |O|
+| |O| |    // Player 2 makes a move at (1, 1).
+| | |X|
+
+ticTacToe.move(2, 0, 1); // return 0 (no one wins)
+|X| |O|
+| |O| |    // Player 1 makes a move at (2, 0).
+|X| |X|
+
+ticTacToe.move(1, 0, 2); // return 0 (no one wins)
+|X| |O|
+|O|O| |    // Player 2 makes a move at (1, 0).
+|X| |X|
+
+ticTacToe.move(2, 1, 1); // return 1 (player 1 wins)
+|X| |O|
+|O|O| |    // Player 1 makes a move at (2, 1).
+|X|X|X|
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= n <= 100
  • +
  • player is 1 or 2.
  • +
  • 1 <= row, col <= n
  • +
  • (row, col) are unique for each different call to move.
  • +
  • At most n2 calls will be made to move.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class TicTacToe: + + def __init__(self, n: int): + """ + Initialize your data structure here. + """ + self.n = n + self.counter = [[0] * ((n << 1) + 2) for _ in range(2)] + + def move(self, row: int, col: int, player: int) -> int: + """ + Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. + """ + n = self.n + self.counter[player - 1][row] += 1 + self.counter[player - 1][col + n] += 1 + if row == col: + self.counter[player - 1][n << 1] += 1 + if row + col == n - 1: + self.counter[player - 1][(n << 1) + 1] += 1 + if self.counter[player - 1][row] == n or self.counter[player - 1][col + n] == n or self.counter[player - 1][n << 1] == n or self.counter[player - 1][(n << 1) + 1] == n: + return player + return 0 + + +# Your TicTacToe object will be instantiated and called as such: +# obj = TicTacToe(n) +# param_1 = obj.move(row,col,player) +``` + +### **Java** + +```java +class TicTacToe { + private int n; + private int[][] counter; + + /** Initialize your data structure here. */ + public TicTacToe(int n) { + counter = new int[2][(n << 1) + 2]; + this.n = n; + } + + /** Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. */ + public int move(int row, int col, int player) { + counter[player - 1][row] += 1; + counter[player - 1][col + n] += 1; + if (row == col) { + counter[player - 1][n << 1] += 1; + } + if (row + col == n - 1) { + counter[player - 1][(n << 1) + 1] += 1; + } + if (counter[player - 1][row] == n || counter[player - 1][col + n] == n || counter[player - 1][n << 1] == n || counter[player - 1][(n << 1) + 1] == n) { + return player; + } + return 0; + } +} + +/** + * Your TicTacToe object will be instantiated and called as such: + * TicTacToe obj = new TicTacToe(n); + * int param_1 = obj.move(row,col,player); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0349.Intersection of Two Arrays/README_EN.md b/assets/0300-0399/0349.Intersection of Two Arrays/README_EN.md new file mode 100644 index 00000000..ae7a2ee6 --- /dev/null +++ b/assets/0300-0399/0349.Intersection of Two Arrays/README_EN.md @@ -0,0 +1,105 @@ +# [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays) + + + +## Description + +

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [1,2,2,1], nums2 = [2,2]
+Output: [2]
+
+ +

Example 2:

+ +
+Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+Output: [9,4]
+Explanation: [4,9] is also accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + s = set(nums1) + res = set() + for num in nums2: + if num in s: + res.add(num) + return list(res) +``` + +### **Java** + +```java +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + Set s = new HashSet<>(); + for (int num : nums1) { + s.add(num); + } + Set res = new HashSet<>(); + for (int num : nums2) { + if (s.contains(num)) { + res.add(num); + } + } + int[] output = new int[res.size()]; + int i = 0; + for (int num : res) { + output[i++] = num; + } + return output; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function(nums1, nums2) { + const s = new Set(); + for (const num of nums1) { + s.add(num); + } + let res = new Set(); + for (const num of nums2) { + if (s.has(num)) { + res.add(num); + } + } + return [...res]; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0350.Intersection of Two Arrays II/README_EN.md b/assets/0300-0399/0350.Intersection of Two Arrays II/README_EN.md new file mode 100644 index 00000000..ea710f0d --- /dev/null +++ b/assets/0300-0399/0350.Intersection of Two Arrays II/README_EN.md @@ -0,0 +1,117 @@ +# [350. Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii) + + + +## Description + +

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [1,2,2,1], nums2 = [2,2]
+Output: [2,2]
+
+ +

Example 2:

+ +
+Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
+Output: [4,9]
+Explanation: [9,4] is also accepted.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 1000
  • +
+ +

 

+

Follow up:

+ +
    +
  • What if the given array is already sorted? How would you optimize your algorithm?
  • +
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • +
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + counter = collections.Counter(nums1) + res = [] + for num in nums2: + if counter[num] > 0: + res.append(num) + counter[num] -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public int[] intersect(int[] nums1, int[] nums2) { + Map counter = new HashMap<>(); + for (int num : nums1) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + List intersection = new ArrayList<>(); + for (int num : nums2) { + int val = counter.getOrDefault(num, 0); + if (val > 0) { + intersection.add(num); + counter.put(num, val - 1); + } + } + int i = 0; + int[] res = new int[intersection.size()]; + for (int num : intersection) { + res[i++] = num; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function(nums1, nums2) { + const counter = {}; + for (const num of nums1) { + counter[num] = (counter[num] || 0) + 1; + } + let res = []; + for (const num of nums2) { + if (counter[num] > 0) { + res.push(num); + counter[num] -= 1; + } + } + return res; +}; + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0351.Android Unlock Patterns/README_EN.md b/assets/0300-0399/0351.Android Unlock Patterns/README_EN.md new file mode 100644 index 00000000..b28116dd --- /dev/null +++ b/assets/0300-0399/0351.Android Unlock Patterns/README_EN.md @@ -0,0 +1,74 @@ +# [351. Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns) + + + +## Description + +

Android devices have a special lock screen with a 3 x 3 grid of dots. Users can set an "unlock pattern" by connecting the dots in a specific sequence, forming a series of joined line segments where each segment's endpoints are two consecutive dots in the sequence. A sequence of k dots is a valid unlock pattern if both of the following are true:

+ +
    +
  • All the dots in the sequence are distinct.
  • +
  • If the line segment connecting two consecutive dots in the sequence passes through any other dot, the other dot must have previously appeared in the sequence. No jumps through non-selected dots are allowed.
  • +
+ +

Here are some example valid and invalid unlock patterns:

+ +

+ +
    +
  • The 1st pattern [4,1,3,6] is invalid because the line connecting dots 1 and 3 pass through dot 2, but dot 2 did not previously appear in the sequence.
  • +
  • The 2nd pattern [4,1,9,2] is invalid because the line connecting dots 1 and 9 pass through dot 5, but dot 5 did not previously appear in the sequence.
  • +
  • The 3rd pattern [2,4,1,3,6] is valid because it follows the conditions. The line connecting dots 1 and 3 meets the condition because dot 2 previously appeared in the sequence.
  • +
  • The 4th pattern [6,5,4,1,9,2] is valid because it follows the conditions. The line connecting dots 1 and 9 meets the condition because dot 5 previously appeared in the sequence.
  • +
+ +

Given two integers m and n, return the number of unique and valid unlock patterns of the Android grid lock screen that consist of at least m keys and at most n keys.

+ +

Two unlock patterns are considered unique if there is a dot in one sequence that is not in the other, or the order of the dots is different.

+ +

 

+

Example 1:

+ +
+Input: m = 1, n = 1
+Output: 9
+
+ +

Example 2:

+ +
+Input: m = 1, n = 2
+Output: 65
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 9
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0351.Android Unlock Patterns/images/android-unlock.png b/assets/0300-0399/0351.Android Unlock Patterns/images/android-unlock.png new file mode 100644 index 00000000..3f6cb572 Binary files /dev/null and b/assets/0300-0399/0351.Android Unlock Patterns/images/android-unlock.png differ diff --git a/assets/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md b/assets/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md new file mode 100644 index 00000000..1fbedd14 --- /dev/null +++ b/assets/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md @@ -0,0 +1,75 @@ +# [352. Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals) + + + +## Description + +

Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.

+ +

Implement the SummaryRanges class:

+ +
    +
  • SummaryRanges() Initializes the object with an empty stream.
  • +
  • void addNum(int val) Adds the integer val to the stream.
  • +
  • int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi].
  • +
+ +

 

+

Example 1:

+ +
+Input
+["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
+[[], [1], [], [3], [], [7], [], [2], [], [6], []]
+Output
+[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
+
+Explanation
+SummaryRanges summaryRanges = new SummaryRanges();
+summaryRanges.addNum(1);      // arr = [1]
+summaryRanges.getIntervals(); // return [[1, 1]]
+summaryRanges.addNum(3);      // arr = [1, 3]
+summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
+summaryRanges.addNum(7);      // arr = [1, 3, 7]
+summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
+summaryRanges.addNum(2);      // arr = [1, 2, 3, 7]
+summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
+summaryRanges.addNum(6);      // arr = [1, 2, 3, 6, 7]
+summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= val <= 104
  • +
  • At most 3 * 104 calls will be made to addNum and getIntervals.
  • +
+ +

 

+

Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0353.Design Snake Game/README_EN.md b/assets/0300-0399/0353.Design Snake Game/README_EN.md new file mode 100644 index 00000000..fb5e6193 --- /dev/null +++ b/assets/0300-0399/0353.Design Snake Game/README_EN.md @@ -0,0 +1,84 @@ +# [353. Design Snake Game](https://leetcode.com/problems/design-snake-game) + + + +## Description + +

Design a Snake game that is played on a device with screen size height x width. Play the game online if you are not familiar with the game.

+ +

The snake is initially positioned at the top left corner (0, 0) with a length of 1 unit.

+ +

You are given an array food where food[i] = (ri, ci) is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game's score both increase by 1.

+ +

Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.

+ +

When a piece of food appears on the screen, it is guaranteed that it will not appear on a block occupied by the snake.

+ +

The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies after moving (i.e. a snake of length 4 cannot run into itself).

+ +

Implement the SnakeGame class:

+ +
    +
  • SnakeGame(int width, int height, int[][] food) Initializes the object with a screen of size height x width and the positions of the food.
  • +
  • int move(String direction) Returns the score of the game after applying one direction move by the snake. If the game is over, return -1.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["SnakeGame", "move", "move", "move", "move", "move", "move"]
+[[3, 2, [[1, 2], [0, 1]]], ["R"], ["D"], ["R"], ["U"], ["L"], ["U"]]
+Output
+[null, 0, 0, 1, 1, 2, -1]
+
+Explanation
+SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]);
+snakeGame.move("R"); // return 0
+snakeGame.move("D"); // return 0
+snakeGame.move("R"); // return 1, snake eats the first piece of food. The second piece of food appears
+                     // at (0, 1).
+snakeGame.move("U"); // return 1
+snakeGame.move("L"); // return 2, snake eats the second food. No more food appears.
+snakeGame.move("U"); // return -1, game over because snake collides with border
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= width, height <= 104
  • +
  • 1 <= food.length <= 50
  • +
  • food[i].length == 2
  • +
  • 0 <= ri < height
  • +
  • 0 <= ci < width
  • +
  • direction.length == 1
  • +
  • direction is 'U', 'D', 'L', or 'R'.
  • +
  • At most 104 calls will be made to move.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0353.Design Snake Game/images/snake.jpg b/assets/0300-0399/0353.Design Snake Game/images/snake.jpg new file mode 100644 index 00000000..26b3c18b Binary files /dev/null and b/assets/0300-0399/0353.Design Snake Game/images/snake.jpg differ diff --git a/assets/0300-0399/0354.Russian Doll Envelopes/README_EN.md b/assets/0300-0399/0354.Russian Doll Envelopes/README_EN.md new file mode 100644 index 00000000..efdbe988 --- /dev/null +++ b/assets/0300-0399/0354.Russian Doll Envelopes/README_EN.md @@ -0,0 +1,97 @@ +# [354. Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes) + + + +## Description + +

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

+ +

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

+ +

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

+ +

Note: You cannot rotate an envelope.

+ +

 

+

Example 1:

+ +
+Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
+Output: 3
+Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
+
+ +

Example 2:

+ +
+Input: envelopes = [[1,1],[1,1],[1,1]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= envelopes.length <= 5000
  • +
  • envelopes[i].length == 2
  • +
  • 1 <= wi, hi <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: + if not envelopes: + return 0 + envelopes.sort(key=lambda x: (x[0], -x[1])) + nums = [x[1] for x in envelopes] + n = len(nums) + dp = [1] * n + res = 1 + for i in range(1, n): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + res = max(res, dp[i]) + return res +``` + +### **Java** + +```java +class Solution { + public int maxEnvelopes(int[][] envelopes) { + int n; + if (envelopes == null || (n = envelopes.length) == 0) return 0; + Arrays.sort(envelopes, (a, b) -> { + return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]; + }); + int[] dp = new int[n]; + Arrays.fill(dp, 1); + int res = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (envelopes[j][1] < envelopes[i][1]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + res = Math.max(res, dp[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0355.Design Twitter/README_EN.md b/assets/0300-0399/0355.Design Twitter/README_EN.md new file mode 100644 index 00000000..a25ec7de --- /dev/null +++ b/assets/0300-0399/0355.Design Twitter/README_EN.md @@ -0,0 +1,188 @@ +# [355. Design Twitter](https://leetcode.com/problems/design-twitter) + + + +## Description + +

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed.

+ +

Implement the Twitter class:

+ +
    +
  • Twitter() Initializes your twitter object.
  • +
  • void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.
  • +
  • List<Integer> getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.
  • +
  • void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.
  • +
  • void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
+[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
+Output
+[null, null, [5], null, null, [6, 5], null, [5]]
+
+Explanation
+Twitter twitter = new Twitter();
+twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
+twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
+twitter.follow(1, 2);    // User 1 follows user 2.
+twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
+twitter.getNewsFeed(1);  // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
+twitter.unfollow(1, 2);  // User 1 unfollows user 2.
+twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= userId, followerId, followeeId <= 500
  • +
  • 0 <= tweetId <= 104
  • +
  • All the tweets have unique IDs.
  • +
  • At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Twitter: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.user_tweets = collections.defaultdict(list) + self.user_following = collections.defaultdict(set) + self.tweets = collections.defaultdict() + self.time = 0 + + def postTweet(self, userId: int, tweetId: int) -> None: + """ + Compose a new tweet. + """ + self.time += 1 + self.user_tweets[userId].append(tweetId) + self.tweets[tweetId] = self.time + + def getNewsFeed(self, userId: int) -> List[int]: + """ + Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. + """ + following = self.user_following[userId] + users = set(following) + users.add(userId) + tweets = [self.user_tweets[u][::-1][:10] for u in users] + tweets = sum(tweets, []) + return heapq.nlargest(10, tweets, key=lambda tweet: self.tweets[tweet]) + + def follow(self, followerId: int, followeeId: int) -> None: + """ + Follower follows a followee. If the operation is invalid, it should be a no-op. + """ + self.user_following[followerId].add(followeeId) + + def unfollow(self, followerId: int, followeeId: int) -> None: + """ + Follower unfollows a followee. If the operation is invalid, it should be a no-op. + """ + following = self.user_following[followerId] + if followeeId in following: + following.remove(followeeId) + + + +# Your Twitter object will be instantiated and called as such: +# obj = Twitter() +# obj.postTweet(userId,tweetId) +# param_2 = obj.getNewsFeed(userId) +# obj.follow(followerId,followeeId) +# obj.unfollow(followerId,followeeId) +``` + +### **Java** + +```java +class Twitter { + private Map> userTweets; + private Map> userFollowing; + private Map tweets; + private int time; + + /** Initialize your data structure here. */ + public Twitter() { + userTweets = new HashMap<>(); + userFollowing = new HashMap<>(); + tweets = new HashMap<>(); + time = 0; + } + + /** Compose a new tweet. */ + public void postTweet(int userId, int tweetId) { + List userTweet = userTweets.getOrDefault(userId, new ArrayList<>()); + userTweet.add(tweetId); + userTweets.put(userId, userTweet); + tweets.put(tweetId, ++time); + } + + /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ + public List getNewsFeed(int userId) { + Set following = userFollowing.getOrDefault(userId, new HashSet<>()); + Set users = new HashSet<>(following); + users.add(userId); + PriorityQueue pq = new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a))); + for (Integer u : users) { + List userTweet = userTweets.get(u); + if (userTweet != null && !userTweet.isEmpty()) { + for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) { + pq.offer(userTweet.get(i)); + } + } + } + List res = new ArrayList<>(); + while (!pq.isEmpty() && res.size() < 10) { + res.add(pq.poll()); + } + return res; + } + + /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ + public void follow(int followerId, int followeeId) { + Set following = userFollowing.getOrDefault(followerId, new HashSet<>()); + following.add(followeeId); + userFollowing.put(followerId, following); + } + + /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ + public void unfollow(int followerId, int followeeId) { + Set following = userFollowing.getOrDefault(followerId, new HashSet<>()); + following.remove(followeeId); + userFollowing.put(followerId, following); + } +} + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter obj = new Twitter(); + * obj.postTweet(userId,tweetId); + * List param_2 = obj.getNewsFeed(userId); + * obj.follow(followerId,followeeId); + * obj.unfollow(followerId,followeeId); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0356.Line Reflection/README_EN.md b/assets/0300-0399/0356.Line Reflection/README_EN.md new file mode 100644 index 00000000..b211d700 --- /dev/null +++ b/assets/0300-0399/0356.Line Reflection/README_EN.md @@ -0,0 +1,92 @@ +# [356. Line Reflection](https://leetcode.com/problems/line-reflection) + + + +## Description + +

Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points symmetrically, in other words, answer whether or not if there exists a line that after reflecting all points over the given line the set of the original points is the same that the reflected ones.

+ +

Note that there can be repeated points.

+ +

Follow up:
+Could you do better than O(n2) ?

+ +

 

+

Example 1:

+ +
+Input: points = [[1,1],[-1,1]]
+Output: true
+Explanation: We can choose the line x = 0.
+
+ +

Example 2:

+ +
+Input: points = [[1,1],[-1,-1]]
+Output: false
+Explanation: We can't choose a line.
+
+ +

 

+

Constraints:

+ +
    +
  • n == points.length
  • +
  • 1 <= n <= 10^4
  • +
  • -10^8 <= points[i][j] <= 10^8
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isReflected(self, points: List[List[int]]) -> bool: + min_x, max_x = float('inf'), float('-inf') + point_set = set() + for x, y in points: + min_x = min(min_x, x) + max_x = max(max_x, x) + point_set.add((x, y)) + s = min_x + max_x + for x, y in points: + if (s - x, y) not in point_set: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean isReflected(int[][] points) { + int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; + Set pointSet = new HashSet<>(); + for (int[] point : points) { + minX = Math.min(minX, point[0]); + maxX = Math.max(maxX, point[0]); + pointSet.add(point[0] + "." + point[1]); + } + long s = minX + maxX; + for (int[] point : points) { + if (!pointSet.contains((s - point[0]) + "." + point[1])) { + return false; + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0356.Line Reflection/images/356_example_1.png b/assets/0300-0399/0356.Line Reflection/images/356_example_1.png new file mode 100644 index 00000000..bb24e3f0 Binary files /dev/null and b/assets/0300-0399/0356.Line Reflection/images/356_example_1.png differ diff --git a/assets/0300-0399/0356.Line Reflection/images/356_example_2.png b/assets/0300-0399/0356.Line Reflection/images/356_example_2.png new file mode 100644 index 00000000..fa9b71e7 Binary files /dev/null and b/assets/0300-0399/0356.Line Reflection/images/356_example_2.png differ diff --git a/assets/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md b/assets/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md new file mode 100644 index 00000000..b9c8116d --- /dev/null +++ b/assets/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md @@ -0,0 +1,55 @@ +# [357. Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits) + + + +## Description + +

Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 91
+Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99
+
+ +

Example 2:

+ +
+Input: n = 0
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 8
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md b/assets/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md new file mode 100644 index 00000000..0f613908 --- /dev/null +++ b/assets/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md @@ -0,0 +1,66 @@ +# [358. Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart) + + + +## Description + +

Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. If it is not possible to rearrange the string, return an empty string "".

+ +

 

+

Example 1:

+ +
+Input: s = "aabbcc", k = 3
+Output: "abcabc"
+Explanation: The same letters are at least a distance of 3 from each other.
+
+ +

Example 2:

+ +
+Input: s = "aaabc", k = 3
+Output: ""
+Explanation: It is not possible to rearrange the string.
+
+ +

Example 3:

+ +
+Input: s = "aaadbbcc", k = 2
+Output: "abacabcd"
+Explanation: The same letters are at least a distance of 2 from each other.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 3 * 105
  • +
  • s consists of only lowercase English letters.
  • +
  • 0 <= k <= s.length
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0359.Logger Rate Limiter/README_EN.md b/assets/0300-0399/0359.Logger Rate Limiter/README_EN.md new file mode 100644 index 00000000..6d45c4b9 --- /dev/null +++ b/assets/0300-0399/0359.Logger Rate Limiter/README_EN.md @@ -0,0 +1,154 @@ +# [359. Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter) + + + +## Description + +

Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t will prevent other identical messages from being printed until timestamp t + 10).

+ +

All messages will come in chronological order. Several messages may arrive at the same timestamp.

+ +

Implement the Logger class:

+ +
    +
  • Logger() Initializes the logger object.
  • +
  • bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given timestamp, otherwise returns false.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]
+[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
+Output
+[null, true, true, false, false, false, true]
+
+Explanation
+Logger logger = new Logger();
+logger.shouldPrintMessage(1, "foo");  // return true, next allowed timestamp for "foo" is 1 + 10 = 11
+logger.shouldPrintMessage(2, "bar");  // return true, next allowed timestamp for "bar" is 2 + 10 = 12
+logger.shouldPrintMessage(3, "foo");  // 3 < 11, return false
+logger.shouldPrintMessage(8, "bar");  // 8 < 12, return false
+logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false
+logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is
+                                      // 11 + 10 = 21
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= timestamp <= 109
  • +
  • Every timestamp will be passed in non-decreasing order (chronological order).
  • +
  • 1 <= message.length <= 30
  • +
  • At most 104 calls will be made to shouldPrintMessage.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Logger: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.limiter = {} + + def shouldPrintMessage(self, timestamp: int, message: str) -> bool: + """ + Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. + """ + t = self.limiter.get(message, 0) + if t > timestamp: + return False + self.limiter[message] = timestamp + 10 + return True + + +# Your Logger object will be instantiated and called as such: +# obj = Logger() +# param_1 = obj.shouldPrintMessage(timestamp,message) +``` + +### **Java** + +```java +class Logger { + + private Map limiter; + + /** Initialize your data structure here. */ + public Logger() { + limiter = new HashMap<>(); + } + + /** Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. */ + public boolean shouldPrintMessage(int timestamp, String message) { + int t = limiter.getOrDefault(message, 0); + if (t > timestamp) { + return false; + } + limiter.put(message, timestamp + 10); + return true; + } +} + +/** + * Your Logger object will be instantiated and called as such: + * Logger obj = new Logger(); + * boolean param_1 = obj.shouldPrintMessage(timestamp,message); + */ +``` + +### **JavaScript** + +```js +/** + * Initialize your data structure here. + */ +var Logger = function () { + this.limiter = {}; +}; + +/** + * Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. + * @param {number} timestamp + * @param {string} message + * @return {boolean} + */ +Logger.prototype.shouldPrintMessage = function (timestamp, message) { + const t = this.limiter[message] || 0; + if (t > timestamp) { + return false; + } + this.limiter[message] = timestamp + 10; + return true; +}; + +/** + * Your Logger object will be instantiated and called as such: + * var obj = new Logger() + * var param_1 = obj.shouldPrintMessage(timestamp,message) + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0360.Sort Transformed Array/README_EN.md b/assets/0300-0399/0360.Sort Transformed Array/README_EN.md new file mode 100644 index 00000000..cc4295b7 --- /dev/null +++ b/assets/0300-0399/0360.Sort Transformed Array/README_EN.md @@ -0,0 +1,52 @@ +# [360. Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array) + + + +## Description + +

Given a sorted integer array nums and three integers a, b and c, apply a quadratic function of the form f(x) = ax2 + bx + c to each element nums[i] in the array, and return the array in a sorted order.

+ +

 

+

Example 1:

+
Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
+Output: [3,9,15,33]
+

Example 2:

+
Input: nums = [-4,-2,2,4], a = -1, b = 3, c = 5
+Output: [-23,-5,1,7]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -100 <= nums[i], a, b, c <= 100
  • +
  • nums is sorted in ascending order.
  • +
+ +

 

+

Follow up: Could you solve it in O(n) time?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0361.Bomb Enemy/README_EN.md b/assets/0300-0399/0361.Bomb Enemy/README_EN.md new file mode 100644 index 00000000..cade54ed --- /dev/null +++ b/assets/0300-0399/0361.Bomb Enemy/README_EN.md @@ -0,0 +1,59 @@ +# [361. Bomb Enemy](https://leetcode.com/problems/bomb-enemy) + + + +## Description + +

Given an m x n matrix grid where each cell is either a wall 'W', an enemy 'E' or empty '0', return the maximum enemies you can kill using one bomb. You can only place the bomb in an empty cell.

+ +

The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.

+ +

 

+

Example 1:

+ +
+Input: grid = [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
+Output: 3
+
+ +

Example 2:

+ +
+Input: grid = [["W","W","W"],["0","0","0"],["E","E","E"]]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • m == grid.length
  • +
  • n == grid[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • grid[i][j] is either 'W', 'E', or '0'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0361.Bomb Enemy/images/361_Bomb_Enemy.gif b/assets/0300-0399/0361.Bomb Enemy/images/361_Bomb_Enemy.gif new file mode 100644 index 00000000..a02bdf72 Binary files /dev/null and b/assets/0300-0399/0361.Bomb Enemy/images/361_Bomb_Enemy.gif differ diff --git a/assets/0300-0399/0362.Design Hit Counter/README_EN.md b/assets/0300-0399/0362.Design Hit Counter/README_EN.md new file mode 100644 index 00000000..d426ddd3 --- /dev/null +++ b/assets/0300-0399/0362.Design Hit Counter/README_EN.md @@ -0,0 +1,134 @@ +# [362. Design Hit Counter](https://leetcode.com/problems/design-hit-counter) + + + +## Description + +

Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds).

+ +

Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). Several hits may arrive roughly at the same time.

+ +

Implement the HitCounter class:

+ +
    +
  • HitCounter() Initializes the object of the hit counter system.
  • +
  • void hit(int timestamp) Records a hit that happened at timestamp (in seconds). Several hits may happen at the same timestamp.
  • +
  • int getHits(int timestamp) Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).
  • +
+ +

 

+

Example 1:

+ +
+Input
+["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"]
+[[], [1], [2], [3], [4], [300], [300], [301]]
+Output
+[null, null, null, null, 3, null, 4, 3]
+
+Explanation
+HitCounter hitCounter = new HitCounter();
+hitCounter.hit(1);       // hit at timestamp 1.
+hitCounter.hit(2);       // hit at timestamp 2.
+hitCounter.hit(3);       // hit at timestamp 3.
+hitCounter.getHits(4);   // get hits at timestamp 4, return 3.
+hitCounter.hit(300);     // hit at timestamp 300.
+hitCounter.getHits(300); // get hits at timestamp 300, return 4.
+hitCounter.getHits(301); // get hits at timestamp 301, return 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= timestamp <= 2 * 109
  • +
  • All the calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing).
  • +
  • At most 300 calls will be made to hit and getHits.
  • +
+ +

 

+

Follow up: What if the number of hits per second could be huge? Does your design scale?

+ +## Solutions + + + +### **Python3** + +```python +class HitCounter: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.counter = collections.Counter() + + def hit(self, timestamp: int) -> None: + """ + Record a hit. + @param timestamp - The current timestamp (in seconds granularity). + """ + self.counter[timestamp] += 1 + + + def getHits(self, timestamp: int) -> int: + """ + Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). + """ + return sum([v for t, v in self.counter.items() if t + 300 > timestamp]) + + +# Your HitCounter object will be instantiated and called as such: +# obj = HitCounter() +# obj.hit(timestamp) +# param_2 = obj.getHits(timestamp) +``` + +### **Java** + +```java +class HitCounter { + + private Map counter; + + /** Initialize your data structure here. */ + public HitCounter() { + counter = new HashMap<>(); + } + + /** Record a hit. + @param timestamp - The current timestamp (in seconds granularity). */ + public void hit(int timestamp) { + counter.put(timestamp, counter.getOrDefault(timestamp, 0) + 1); + } + + /** Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). */ + public int getHits(int timestamp) { + int hits = 0; + for (Map.Entry entry : counter.entrySet()) { + if (entry.getKey() + 300 > timestamp) { + hits += entry.getValue(); + } + } + return hits; + } +} + +/** + * Your HitCounter object will be instantiated and called as such: + * HitCounter obj = new HitCounter(); + * obj.hit(timestamp); + * int param_2 = obj.getHits(timestamp); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md b/assets/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md new file mode 100644 index 00000000..d0b34100 --- /dev/null +++ b/assets/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md @@ -0,0 +1,64 @@ +# [363. Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k) + + + +## Description + +

Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.

+ +

It is guaranteed that there will be a rectangle with a sum no larger than k.

+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,0,1],[0,-2,3]], k = 2
+Output: 2
+Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).
+
+ +

Example 2:

+ +
+Input: matrix = [[2,2,-1]], k = 3
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • m == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • -100 <= matrix[i][j] <= 100
  • +
  • -105 <= k <= 105
  • +
+ +

 

+

Follow up: What if the number of rows is much larger than the number of columns?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0363.Max Sum of Rectangle No Larger Than K/images/sum-grid.jpg b/assets/0300-0399/0363.Max Sum of Rectangle No Larger Than K/images/sum-grid.jpg new file mode 100644 index 00000000..3624ab40 Binary files /dev/null and b/assets/0300-0399/0363.Max Sum of Rectangle No Larger Than K/images/sum-grid.jpg differ diff --git a/assets/0300-0399/0364.Nested List Weight Sum II/README_EN.md b/assets/0300-0399/0364.Nested List Weight Sum II/README_EN.md new file mode 100644 index 00000000..c5d728a0 --- /dev/null +++ b/assets/0300-0399/0364.Nested List Weight Sum II/README_EN.md @@ -0,0 +1,255 @@ +# [364. Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii) + + + +## Description + +

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists.

+ +

The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Let maxDepth be the maximum depth of any integer.

+ +

The weight of an integer is maxDepth - (the depth of the integer) + 1.

+ +

Return the sum of each integer in nestedList multiplied by its weight.

+ +

 

+

Example 1:

+ +
+Input: nestedList = [[1,1],2,[1,1]]
+Output: 8
+Explanation: Four 1's with a weight of 1, one 2 with a weight of 2.
+1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8
+
+ +

Example 2:

+ +
+Input: nestedList = [1,[4,[6]]]
+Output: 17
+Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1.
+1*3 + 4*2 + 6*1 = 17
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nestedList.length <= 50
  • +
  • The values of the integers in the nested list is in the range [-100, 100].
  • +
  • The maximum depth of any integer is less than or equal to 50.
  • +
+ +## Solutions + + + +### **Python3** + +```python +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger: +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ +class Solution: + def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: + def max_depth(nestedList): + depth = 1 + for item in nestedList: + if item.isInteger(): + continue + depth = max(depth, max_depth(item.getList()) + 1) + return depth + + def dfs(nestedList, max_depth): + depth_sum = 0 + for item in nestedList: + if item.isInteger(): + depth_sum += item.getInteger() * max_depth + else: + depth_sum += dfs(item.getList(), max_depth - 1) + return depth_sum + + depth = max_depth(nestedList) + return dfs(nestedList, depth) +``` + +### **Java** + +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public int depthSumInverse(List nestedList) { + int depth = maxDepth(nestedList); + return dfs(nestedList, depth); + } + + private int maxDepth(List nestedList) { + int depth = 1; + for (NestedInteger item : nestedList) { + if (item.isInteger()) { + continue; + } + depth = Math.max(depth, 1 + maxDepth(item.getList())); + } + return depth; + } + + private int dfs(List nestedList, int depth) { + int depthSum = 0; + for (NestedInteger item : nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth - 1); + } + } + return depthSum; + } +} +``` + +### **JavaScript** + +```js +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * function NestedInteger() { + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * @return {boolean} + * this.isInteger = function() { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * @return {integer} + * this.getInteger = function() { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * @return {void} + * this.setInteger = function(value) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * @return {void} + * this.add = function(elem) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, if it holds a nested list + * Return null if this NestedInteger holds a single integer + * @return {NestedInteger[]} + * this.getList = function() { + * ... + * }; + * }; + */ +/** + * @param {NestedInteger[]} nestedList + * @return {number} + */ +var depthSumInverse = function (nestedList) { + const maxDepth = (nestedList) => { + let depth = 1; + for (const item of nestedList) { + if (item.isInteger()) { + continue; + } + depth = Math.max(depth, 1 + maxDepth(item.getList())); + } + return depth; + }; + const dfs = (nestedList, depth) => { + let depthSum = 0; + for (const item of nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth - 1); + } + } + return depthSum; + }; + const depth = maxDepth(nestedList); + return dfs(nestedList, depth); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0364.Nested List Weight Sum II/images/nestedlistweightsumiiex1.png b/assets/0300-0399/0364.Nested List Weight Sum II/images/nestedlistweightsumiiex1.png new file mode 100644 index 00000000..b7d6cfcd Binary files /dev/null and b/assets/0300-0399/0364.Nested List Weight Sum II/images/nestedlistweightsumiiex1.png differ diff --git a/assets/0300-0399/0364.Nested List Weight Sum II/images/nestedlistweightsumiiex2.png b/assets/0300-0399/0364.Nested List Weight Sum II/images/nestedlistweightsumiiex2.png new file mode 100644 index 00000000..5a9335b0 Binary files /dev/null and b/assets/0300-0399/0364.Nested List Weight Sum II/images/nestedlistweightsumiiex2.png differ diff --git a/assets/0300-0399/0365.Water and Jug Problem/README_EN.md b/assets/0300-0399/0365.Water and Jug Problem/README_EN.md new file mode 100644 index 00000000..67a88524 --- /dev/null +++ b/assets/0300-0399/0365.Water and Jug Problem/README_EN.md @@ -0,0 +1,72 @@ +# [365. Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem) + + + +## Description + +

You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.

+ +

If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.

+ +

Operations allowed:

+ +
    +
  • Fill any of the jugs with water.
  • +
  • Empty any of the jugs.
  • +
  • Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.
  • +
+ +

 

+

Example 1:

+ +
+Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
+Output: true
+Explanation: The famous Die Hard example 
+
+ +

Example 2:

+ +
+Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
+Output: false
+
+ +

Example 3:

+ +
+Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md b/assets/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md new file mode 100644 index 00000000..75feb990 --- /dev/null +++ b/assets/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md @@ -0,0 +1,63 @@ +# [366. Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree) + + + +## Description + +

Given the root of a binary tree, collect a tree's nodes as if you were doing this:

+ +
    +
  • Collect all the leaf nodes.
  • +
  • Remove all the leaf nodes.
  • +
  • Repeat until the tree is empty.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,4,5]
+Output: [[4,5,3],[2],[1]]
+Explanation:
+[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
+
+ +

Example 2:

+ +
+Input: root = [1]
+Output: [[1]]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 100].
  • +
  • 1 <= Node.val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0366.Find Leaves of Binary Tree/images/remleaves-tree.jpg b/assets/0300-0399/0366.Find Leaves of Binary Tree/images/remleaves-tree.jpg new file mode 100644 index 00000000..a6583740 Binary files /dev/null and b/assets/0300-0399/0366.Find Leaves of Binary Tree/images/remleaves-tree.jpg differ diff --git a/assets/0300-0399/0367.Valid Perfect Square/README_EN.md b/assets/0300-0399/0367.Valid Perfect Square/README_EN.md new file mode 100644 index 00000000..9311fb5c --- /dev/null +++ b/assets/0300-0399/0367.Valid Perfect Square/README_EN.md @@ -0,0 +1,107 @@ +# [367. Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square) + + + +## Description + +

Given a positive integer num, write a function which returns True if num is a perfect square else False.

+ +

Follow up: Do not use any built-in library function such as sqrt.

+ +

 

+

Example 1:

+
Input: num = 16
+Output: true
+

Example 2:

+
Input: num = 14
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= num <= 2^31 - 1
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPerfectSquare(self, num: int) -> bool: + left, right = 1, num + while left < right: + mid = left + ((right - left) >> 1) + if num // mid <= mid: + right = mid + else: + left = mid + 1 + return left * left == num +``` + +### **Java** + +```java +class Solution { + public boolean isPerfectSquare(int num) { + int left = 1, right = num; + while (left < right) { + int mid = (left + right) >>> 1; + if (num / mid <= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return left * left == num; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPerfectSquare(int num) { + long left = 1, right = num; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (num / mid <= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return left * left == num; + } +}; +``` + +### **Go** + +```go +func isPerfectSquare(num int) bool { + left, right := 1, num + for left < right { + mid := left + (right-left)>>1 + if num/mid <= mid { + right = mid + } else { + left = mid + 1 + } + } + return left*left == num +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0368.Largest Divisible Subset/README_EN.md b/assets/0300-0399/0368.Largest Divisible Subset/README_EN.md new file mode 100644 index 00000000..ab1b1771 --- /dev/null +++ b/assets/0300-0399/0368.Largest Divisible Subset/README_EN.md @@ -0,0 +1,64 @@ +# [368. Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset) + + + +## Description + +

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

+ +
    +
  • answer[i] % answer[j] == 0, or
  • +
  • answer[j] % answer[i] == 0
  • +
+ +

If there are multiple solutions, return any of them.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3]
+Output: [1,2]
+Explanation: [1,3] is also accepted.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,4,8]
+Output: [1,2,4,8]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 1 <= nums[i] <= 2 * 109
  • +
  • All the integers in nums are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0369.Plus One Linked List/README_EN.md b/assets/0300-0399/0369.Plus One Linked List/README_EN.md new file mode 100644 index 00000000..e765f46a --- /dev/null +++ b/assets/0300-0399/0369.Plus One Linked List/README_EN.md @@ -0,0 +1,96 @@ +# [369. Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list) + + + +## Description + +

Given a non-negative integer represented as a linked list of digits, plus one to the integer.

+ +

The digits are stored such that the most significant digit is at the head of the list.

+ +

 

+

Example 1:

+
Input: head = [1,2,3]
+Output: [1,2,4]
+

Example 2:

+
Input: head = [0]
+Output: [1]
+
+

 

+

Constraints:

+ +
    +
  • The number of nodes in the linked list is in the range [1, 100].
  • +
  • 0 <= Node.val <= 9
  • +
  • The number represented by the linked list does not contain leading zeros except for the zero itself. 
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def plusOne(self, head: ListNode) -> ListNode: + dummy = ListNode(val=0, next=head) + target = dummy + while head: + if head.val != 9: + target = head + head = head.next + target.val += 1 + target = target.next + while target: + target.val = 0 + target = target.next + return dummy if dummy.val else dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode plusOne(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode target = dummy; + while (head != null) { + if (head.val != 9) { + target = head; + } + head = head.next; + } + target.val += 1; + target = target.next; + while (target != null) { + target.val = 0; + target = target.next; + } + return dummy.val == 1 ? dummy : dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0370.Range Addition/README_EN.md b/assets/0300-0399/0370.Range Addition/README_EN.md new file mode 100644 index 00000000..bbc2b69f --- /dev/null +++ b/assets/0300-0399/0370.Range Addition/README_EN.md @@ -0,0 +1,61 @@ +# [370. Range Addition](https://leetcode.com/problems/range-addition) + + + +## Description + +

You are given an integer length and an array updates where updates[i] = [startIdxi, endIdxi, inci].

+ +

You have an array arr of length length with all zeros, and you have some operation to apply on arr. In the ith operation, you should increment all the elements arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.

+ +

Return arr after applying all the updates.

+ +

 

+

Example 1:

+ +
+Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
+Output: [-2,0,3,5,3]
+
+ +

Example 2:

+ +
+Input: length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]]
+Output: [0,-4,2,2,2,4,4,-4,-4,-4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= length <= 105
  • +
  • 0 <= updates.length <= 104
  • +
  • 0 <= startIdxi <= endIdxi < length
  • +
  • -1000 <= inci <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0370.Range Addition/images/rangeadd-grid.jpg b/assets/0300-0399/0370.Range Addition/images/rangeadd-grid.jpg new file mode 100644 index 00000000..40dce36c Binary files /dev/null and b/assets/0300-0399/0370.Range Addition/images/rangeadd-grid.jpg differ diff --git a/assets/0300-0399/0371.Sum of Two Integers/README_EN.md b/assets/0300-0399/0371.Sum of Two Integers/README_EN.md new file mode 100644 index 00000000..8a330a4b --- /dev/null +++ b/assets/0300-0399/0371.Sum of Two Integers/README_EN.md @@ -0,0 +1,47 @@ +# [371. Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers) + + + +## Description + +

Given two integers a and b, return the sum of the two integers without using the operators + and -.

+ +

 

+

Example 1:

+
Input: a = 1, b = 2
+Output: 3
+

Example 2:

+
Input: a = 2, b = 3
+Output: 5
+
+

 

+

Constraints:

+ +
    +
  • -1000 <= a, b <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0372.Super Pow/README_EN.md b/assets/0300-0399/0372.Super Pow/README_EN.md new file mode 100644 index 00000000..30b2f99c --- /dev/null +++ b/assets/0300-0399/0372.Super Pow/README_EN.md @@ -0,0 +1,56 @@ +# [372. Super Pow](https://leetcode.com/problems/super-pow) + + + +## Description + +

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

+ +

 

+

Example 1:

+
Input: a = 2, b = [3]
+Output: 8
+

Example 2:

+
Input: a = 2, b = [1,0]
+Output: 1024
+

Example 3:

+
Input: a = 1, b = [4,3,3,8,5,2]
+Output: 1
+

Example 4:

+
Input: a = 2147483647, b = [2,0,0]
+Output: 1198
+
+

 

+

Constraints:

+ +
    +
  • 1 <= a <= 231 - 1
  • +
  • 1 <= b.length <= 2000
  • +
  • 0 <= b[i] <= 9
  • +
  • b doesn't contain leading zeros.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md b/assets/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md new file mode 100644 index 00000000..8fc5f0f9 --- /dev/null +++ b/assets/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md @@ -0,0 +1,71 @@ +# [373. Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums) + + + +## Description + +

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

+ +

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

+ +

Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
+Output: [[1,2],[1,4],[1,6]]
+Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
+
+ +

Example 2:

+ +
+Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
+Output: [[1,1],[1,1]]
+Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
+
+ +

Example 3:

+ +
+Input: nums1 = [1,2], nums2 = [3], k = 3
+Output: [[1,3],[2,3]]
+Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length, nums2.length <= 104
  • +
  • -109 <= nums1[i], nums2[i] <= 109
  • +
  • nums1 and nums2 both are sorted in ascending order.
  • +
  • 1 <= k <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0374.Guess Number Higher or Lower/README_EN.md b/assets/0300-0399/0374.Guess Number Higher or Lower/README_EN.md new file mode 100644 index 00000000..c0ef327e --- /dev/null +++ b/assets/0300-0399/0374.Guess Number Higher or Lower/README_EN.md @@ -0,0 +1,191 @@ +# [374. Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower) + + + +## Description + +

We are playing the Guess Game. The game is as follows:

+ +

I pick a number from 1 to n. You have to guess which number I picked.

+ +

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

+ +

You call a pre-defined API int guess(int num), which returns 3 possible results:

+ +
    +
  • -1: The number I picked is lower than your guess (i.e. pick < num).
  • +
  • 1: The number I picked is higher than your guess (i.e. pick > num).
  • +
  • 0: The number I picked is equal to your guess (i.e. pick == num).
  • +
+ +

Return the number that I picked.

+ +

 

+

Example 1:

+
Input: n = 10, pick = 6
+Output: 6
+

Example 2:

+
Input: n = 1, pick = 1
+Output: 1
+

Example 3:

+
Input: n = 2, pick = 1
+Output: 1
+

Example 4:

+
Input: n = 2, pick = 2
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
  • 1 <= pick <= n
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +# def guess(num: int) -> int: + +class Solution: + def guessNumber(self, n: int) -> int: + left, right = 1, n + while left < right: + mid = (left + right) >> 1 + if guess(mid) <= 0: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * int guess(int num); + */ + +public class Solution extends GuessGame { + public int guessNumber(int n) { + int left = 1, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (guess(mid) <= 0) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * int guess(int num); + */ + +class Solution { +public: + int guessNumber(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (guess(mid) <= 0) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * func guess(num int) int; + */ + +func guessNumber(n int) int { + left, right := 1, n + for left < right { + mid := (left + right) >> 1 + if guess(mid) <= 0 { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **C#** + +```cs +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * int guess(int num); + */ + +public class Solution : GuessGame { + public int GuessNumber(int n) { + int left = 1, right = n; + while (left < right) + { + int mid = left + ((right - left) >> 1); + if (guess(mid) <= 0) + { + right = mid; + } + else + { + left = mid + 1; + } + } + return left; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md b/assets/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md new file mode 100644 index 00000000..9b7a4cc6 --- /dev/null +++ b/assets/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md @@ -0,0 +1,94 @@ +# [375. Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii) + + + +## Description + +

We are playing the Guessing Game. The game will work as follows:

+ +
    +
  1. I pick a number between 1 and n.
  2. +
  3. You guess a number.
  4. +
  5. If you guess the right number, you win the game.
  6. +
  7. If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.
  8. +
  9. Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game.
  10. +
+ +

Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.

+ +

 

+

Example 1:

+ +
+Input: n = 10
+Output: 16
+Explanation: The winning strategy is as follows:
+- The range is [1,10]. Guess 7.
+    - If this is my number, your total is $0. Otherwise, you pay $7.
+    - If my number is higher, the range is [8,10]. Guess 9.
+        - If this is my number, your total is $7. Otherwise, you pay $9.
+        - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.
+        - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.
+    - If my number is lower, the range is [1,6]. Guess 3.
+        - If this is my number, your total is $7. Otherwise, you pay $3.
+        - If my number is higher, the range is [4,6]. Guess 5.
+            - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.
+            - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.
+            - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.
+        - If my number is lower, the range is [1,2]. Guess 1.
+            - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.
+            - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.
+The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 0
+Explanation: There is only one possible number, so you can guess 1 and not have to pay anything.
+
+ +

Example 3:

+ +
+Input: n = 2
+Output: 1
+Explanation: There are two possible numbers, 1 and 2.
+- Guess 1.
+    - If this is my number, your total is $0. Otherwise, you pay $1.
+    - If my number is higher, it must be 2. Guess 2. Your total is $1.
+The worst case is that you pay $1.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 200
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0375.Guess Number Higher or Lower II/images/graph.png b/assets/0300-0399/0375.Guess Number Higher or Lower II/images/graph.png new file mode 100644 index 00000000..76e4cf29 Binary files /dev/null and b/assets/0300-0399/0375.Guess Number Higher or Lower II/images/graph.png differ diff --git a/assets/0300-0399/0376.Wiggle Subsequence/README_EN.md b/assets/0300-0399/0376.Wiggle Subsequence/README_EN.md new file mode 100644 index 00000000..768dd83b --- /dev/null +++ b/assets/0300-0399/0376.Wiggle Subsequence/README_EN.md @@ -0,0 +1,77 @@ +# [376. Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence) + + + +## Description + +

A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with two or fewer elements is trivially a wiggle sequence.

+ +
    +
  • For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
  • +
  • In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
  • +
+ +

A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.

+ +

Given an integer array nums, return the length of the longest wiggle subsequence of nums.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,7,4,9,2,5]
+Output: 6
+Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
+
+ +

Example 2:

+ +
+Input: nums = [1,17,5,10,13,15,10,5,16,8]
+Output: 7
+Explanation: There are several subsequences that achieve this length.
+One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).
+
+ +

Example 3:

+ +
+Input: nums = [1,2,3,4,5,6,7,8,9]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
+ +

 

+

Follow up: Could you solve this in O(n) time?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0377.Combination Sum IV/README_EN.md b/assets/0300-0399/0377.Combination Sum IV/README_EN.md new file mode 100644 index 00000000..2cf6f544 --- /dev/null +++ b/assets/0300-0399/0377.Combination Sum IV/README_EN.md @@ -0,0 +1,95 @@ +# [377. Combination Sum IV](https://leetcode.com/problems/combination-sum-iv) + + + +## Description + +

Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

+ +

The answer is guaranteed to fit in a 32-bit integer.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3], target = 4
+Output: 7
+Explanation:
+The possible combination ways are:
+(1, 1, 1, 1)
+(1, 1, 2)
+(1, 2, 1)
+(1, 3)
+(2, 1, 1)
+(2, 2)
+(3, 1)
+Note that different sequences are counted as different combinations.
+
+ +

Example 2:

+ +
+Input: nums = [9], target = 3
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • 1 <= nums[i] <= 1000
  • +
  • All the elements of nums are unique.
  • +
  • 1 <= target <= 1000
  • +
+ +

 

+

Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?

+ + +## Solutions + +`dp[i]` represents the number of element combinations whose sum is `i`. + + + +### **Python3** + +```python +class Solution: + def combinationSum4(self, nums: List[int], target: int) -> int: + dp = [0 for i in range(target + 1)] + dp[0] = 1 + for i in range(1, target + 1): + for num in nums: + if i - num >= 0: + dp[i] += dp[i - num] + return dp[target] +``` + +### **Java** + +```java +class Solution { + public int combinationSum4(int[] nums, int target) { + int[] dp = new int[target + 1]; + dp[0] = 1; + for (int i = 1; i <= target; i++) { + for (int num : nums) { + if (i - num >= 0) { + dp[i] += dp[i - num]; + } + } + } + return dp[target]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md b/assets/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md new file mode 100644 index 00000000..e5026b6f --- /dev/null +++ b/assets/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md @@ -0,0 +1,180 @@ +# [378. Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix) + + + +## Description + +

Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.

+ +

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

+ +

 

+

Example 1:

+ +
+Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
+Output: 13
+Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
+
+ +

Example 2:

+ +
+Input: matrix = [[-5]], k = 1
+Output: -5
+
+ +

 

+

Constraints:

+ +
    +
  • n == matrix.length
  • +
  • n == matrix[i].length
  • +
  • 1 <= n <= 300
  • +
  • -109 <= matrix[i][j] <= 109
  • +
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • +
  • 1 <= k <= n2
  • +
+ +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def kthSmallest(self, matrix: List[List[int]], k: int) -> int: + def check(matrix, mid, k, n): + count = 0 + i, j = n - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] <= mid: + count += (i + 1) + j += 1 + else: + i -= 1 + return count >= k + + n = len(matrix) + left, right = matrix[0][0], matrix[n - 1][n - 1] + while left < right: + mid = (left + right) >> 1 + if check(matrix, mid, k, n): + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int kthSmallest(int[][] matrix, int k) { + int n = matrix.length; + int left = matrix[0][0], right = matrix[n - 1][n - 1]; + while (left < right) { + int mid = (left + right) >>> 1; + if (check(matrix, mid, k, n)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean check(int[][] matrix, int mid, int k, int n) { + int count = 0; + int i = n - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] <= mid) { + count += (i + 1); + ++j; + } else { + --i; + } + } + return count >= k; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int kthSmallest(vector>& matrix, int k) { + int n = matrix.size(); + int left = matrix[0][0], right = matrix[n - 1][n - 1]; + while (left < right) { + int mid = left + right >> 1; + if (check(matrix, mid, k, n)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + +private: + bool check(vector>& matrix, int mid, int k, int n) { + int count = 0; + int i = n - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] <= mid) { + count += (i + 1); + ++j; + } else { + --i; + } + } + return count >= k; + } +}; +``` + +### **Go** + +```go +func kthSmallest(matrix [][]int, k int) int { + n := len(matrix) + left, right := matrix[0][0], matrix[n-1][n-1] + for left < right { + mid := (left + right) >> 1 + if check(matrix, mid, k, n) { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func check(matrix [][]int, mid, k, n int) bool { + count := 0 + i, j := n-1, 0 + for i >= 0 && j < n { + if matrix[i][j] <= mid { + count += (i + 1) + j++ + } else { + i-- + } + } + return count >= k +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0379.Design Phone Directory/README_EN.md b/assets/0300-0399/0379.Design Phone Directory/README_EN.md new file mode 100644 index 00000000..05c5583d --- /dev/null +++ b/assets/0300-0399/0379.Design Phone Directory/README_EN.md @@ -0,0 +1,147 @@ +# [379. Design Phone Directory](https://leetcode.com/problems/design-phone-directory) + + + +## Description + +

Design a phone directory that initially has maxNumbers empty slots that can store numbers. The directory should store numbers, check if a certain slot is empty or not, and empty a given slot.

+ +

Implement the PhoneDirectory class:

+ +
    +
  • PhoneDirectory(int maxNumbers) Initializes the phone directory with the number of available slots maxNumbers.
  • +
  • int get() Provides a number that is not assigned to anyone. Returns -1 if no number is available.
  • +
  • bool check(int number) Returns true if the slot number is available and false otherwise.
  • +
  • void release(int number) Recycles or releases the slot number.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["PhoneDirectory", "get", "get", "check", "get", "check", "release", "check"]
+[[3], [], [], [2], [], [2], [2], [2]]
+Output
+[null, 0, 1, true, 2, false, null, true]
+
+Explanation
+PhoneDirectory phoneDirectory = new PhoneDirectory(3);
+phoneDirectory.get();      // It can return any available phone number. Here we assume it returns 0.
+phoneDirectory.get();      // Assume it returns 1.
+phoneDirectory.check(2);   // The number 2 is available, so return true.
+phoneDirectory.get();      // It returns 2, the only number that is left.
+phoneDirectory.check(2);   // The number 2 is no longer available, so return false.
+phoneDirectory.release(2); // Release number 2 back to the pool.
+phoneDirectory.check(2);   // Number 2 is available again, return true.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= maxNumbers <= 104
  • +
  • 0 <= number < maxNumbers
  • +
  • At most 2 * 104 calls will be made to get, check, and release.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class PhoneDirectory: + + def __init__(self, maxNumbers: int): + """ + Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. + """ + self.provided = [False] * maxNumbers + + def get(self) -> int: + """ + Provide a number which is not assigned to anyone. + @return - Return an available number. Return -1 if none is available. + """ + for i in range(len(self.provided)): + if not self.provided[i]: + self.provided[i] = True + return i + return -1 + + def check(self, number: int) -> bool: + """ + Check if a number is available or not. + """ + return not self.provided[number] + + def release(self, number: int) -> None: + """ + Recycle or release a number. + """ + self.provided[number] = False + + +# Your PhoneDirectory object will be instantiated and called as such: +# obj = PhoneDirectory(maxNumbers) +# param_1 = obj.get() +# param_2 = obj.check(number) +# obj.release(number) +``` + +### **Java** + +```java +class PhoneDirectory { + + private boolean[] provided; + + /** Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ + public PhoneDirectory(int maxNumbers) { + provided = new boolean[maxNumbers]; + } + + /** Provide a number which is not assigned to anyone. + @return - Return an available number. Return -1 if none is available. */ + public int get() { + for (int i = 0; i < provided.length; ++i) { + if (!provided[i]) { + provided[i] = true; + return i; + } + } + return -1; + } + + /** Check if a number is available or not. */ + public boolean check(int number) { + return !provided[number]; + } + + /** Recycle or release a number. */ + public void release(int number) { + provided[number] = false; + } +} + +/** + * Your PhoneDirectory object will be instantiated and called as such: + * PhoneDirectory obj = new PhoneDirectory(maxNumbers); + * int param_1 = obj.get(); + * boolean param_2 = obj.check(number); + * obj.release(number); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md b/assets/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md new file mode 100644 index 00000000..fd5cfa17 --- /dev/null +++ b/assets/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md @@ -0,0 +1,164 @@ +# [380. Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1) + + + +## Description + +

Implement the RandomizedSet class:

+ +
    +
  • RandomizedSet() Initializes the RandomizedSet object.
  • +
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • +
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • +
  • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
+[[], [1], [2], [2], [], [1], [2], []]
+Output
+[null, true, false, true, 2, true, false, 2]
+
+Explanation
+RandomizedSet randomizedSet = new RandomizedSet();
+randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
+randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
+randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
+randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
+randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
+randomizedSet.insert(2); // 2 was already in the set, so return false.
+randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= val <= 231 - 1
  • +
  • At most 105 calls will be made to insert, remove, and getRandom.
  • +
  • There will be at least one element in the data structure when getRandom is called.
  • +
+ +

 

+Follow up: Could you implement the functions of the class with each function works in average O(1) time? + +## Solutions + + + +### **Python3** + +```python +class RandomizedSet: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.m = {} + self.l = [] + + def insert(self, val: int) -> bool: + """ + Inserts a value to the set. Returns true if the set did not already contain the specified element. + """ + if val in self.m: + return False + self.m[val] = len(self.l) + self.l.append(val) + return True + + def remove(self, val: int) -> bool: + """ + Removes a value from the set. Returns true if the set contained the specified element. + """ + if val not in self.m: + return False + idx = self.m[val] + last_idx = len(self.l) - 1 + self.m[self.l[last_idx]] = idx + self.m.pop(val) + self.l[idx] = self.l[last_idx] + self.l.pop() + return True + + def getRandom(self) -> int: + """ + Get a random element from the set. + """ + return random.choice(self.l) + + +# Your RandomizedSet object will be instantiated and called as such: +# obj = RandomizedSet() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() +``` + +### **Java** + +```java +class RandomizedSet { + private Map m; + private List l; + private Random rnd; + + /** Initialize your data structure here. */ + public RandomizedSet() { + m = new HashMap<>(); + l = new ArrayList<>(); + rnd = new Random(); + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + public boolean insert(int val) { + if (m.containsKey(val)) { + return false; + } + m.put(val, l.size()); + l.add(val); + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + public boolean remove(int val) { + if (!m.containsKey(val)) { + return false; + } + int idx = m.get(val); + int lastIdx = l.size() - 1; + m.put(l.get(lastIdx), idx); + m.remove(val); + l.set(idx, l.get(lastIdx)); + l.remove(lastIdx); + return true; + } + + /** Get a random element from the set. */ + public int getRandom() { + int idx = rnd.nextInt(l.size()); + return l.get(idx); + } +} + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md b/assets/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md new file mode 100644 index 00000000..0d4a2b79 --- /dev/null +++ b/assets/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md @@ -0,0 +1,180 @@ +# [381. Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed) + + + +## Description + +

Implement the RandomizedCollection class:

+ +
    +
  • RandomizedCollection() Initializes the RandomizedCollection object.
  • +
  • bool insert(int val) Inserts an item val into the multiset if not present. Returns true if the item was not present, false otherwise.
  • +
  • bool remove(int val) Removes an item val from the multiset if present. Returns true if the item was present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
  • +
  • int getRandom() Returns a random element from the current multiset of elements (it's guaranteed that at least one element exists when this method is called). The probability of each element being returned is linearly related to the number of same values the multiset contains.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
+[[], [1], [1], [2], [], [1], []]
+Output
+[null, true, false, true, 2, true, 1]
+
+Explanation
+RandomizedCollection randomizedCollection = new RandomizedCollection();
+randomizedCollection.insert(1);   // return True. Inserts 1 to the collection. Returns true as the collection did not contain 1.
+randomizedCollection.insert(1);   // return False. Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
+randomizedCollection.insert(2);   // return True. Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
+randomizedCollection.getRandom(); // getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
+randomizedCollection.remove(1);   // return True. Removes 1 from the collection, returns true. Collection now contains [1,2].
+randomizedCollection.getRandom(); // getRandom should return 1 and 2 both equally likely.
+
+ +

 

+

Constraints:

+ +
    +
  • -231 <= val <= 231 - 1
  • +
  • At most 105 calls will be made to insert, remove, and getRandom.
  • +
  • There will be at least one element in the data structure when getRandom is called.
  • +
+ +

 

+Follow up: Could you implement the functions of the class with each function works in average O(1) time? + +## Solutions + + + +### **Python3** + +```python +class RandomizedCollection: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.m = {} + self.l = [] + + def insert(self, val: int) -> bool: + """ + Inserts a value to the collection. Returns true if the collection did not already contain the specified element. + """ + idx_set = self.m.get(val, set()) + idx_set.add(len(self.l)) + self.m[val] = idx_set + self.l.append(val) + return len(idx_set) == 1 + + def remove(self, val: int) -> bool: + """ + Removes a value from the collection. Returns true if the collection contained the specified element. + """ + if val not in self.m: + return False + idx_set = self.m[val] + idx = list(idx_set)[0] + last_idx = len(self.l) - 1 + self.l[idx] = self.l[last_idx] + idx_set.remove(idx) + + last_idx_set = self.m[self.l[last_idx]] + if last_idx in last_idx_set: + last_idx_set.remove(last_idx) + if idx < last_idx: + last_idx_set.add(idx) + if not idx_set: + self.m.pop(val) + self.l.pop() + return True + + def getRandom(self) -> int: + """ + Get a random element from the collection. + """ + return -1 if len(self.l) == 0 else random.choice(self.l) + + + +# Your RandomizedCollection object will be instantiated and called as such: +# obj = RandomizedCollection() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() +``` + +### **Java** + +```java +class RandomizedCollection { + private Map> m; + private List l; + private Random rnd; + + /** Initialize your data structure here. */ + public RandomizedCollection() { + m = new HashMap<>(); + l = new ArrayList<>(); + rnd = new Random(); + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + public boolean insert(int val) { + Set idxSet = m.getOrDefault(val, new HashSet<>()); + idxSet.add(l.size()); + m.put(val, idxSet); + l.add(val); + return idxSet.size() == 1; + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + public boolean remove(int val) { + if (!m.containsKey(val)) { + return false; + } + Set idxSet = m.get(val); + int idx = idxSet.iterator().next(); + int lastIdx = l.size() - 1; + l.set(idx, l.get(lastIdx)); + idxSet.remove(idx); + + Set lastIdxSet = m.get(l.get(lastIdx)); + lastIdxSet.remove(lastIdx); + if (idx < lastIdx) { + lastIdxSet.add(idx); + } + if (idxSet.isEmpty()) { + m.remove(val); + } + l.remove(lastIdx); + return true; + } + + /** Get a random element from the collection. */ + public int getRandom() { + int size = l.size(); + return size == 0 ? -1 : l.get(rnd.nextInt(size)); + } +} + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * RandomizedCollection obj = new RandomizedCollection(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0382.Linked List Random Node/README_EN.md b/assets/0300-0399/0382.Linked List Random Node/README_EN.md new file mode 100644 index 00000000..a46c41fc --- /dev/null +++ b/assets/0300-0399/0382.Linked List Random Node/README_EN.md @@ -0,0 +1,69 @@ +# [382. Linked List Random Node](https://leetcode.com/problems/linked-list-random-node) + + + +## Description + +

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

+ +

 

+

Example 1:

+ +
+Input
+["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
+[[[1, 2, 3]], [], [], [], [], []]
+Output
+[null, 1, 3, 2, 2, 3]
+
+Explanation
+Solution solution = new Solution([1, 2, 3]);
+solution.getRandom(); // return 1
+solution.getRandom(); // return 3
+solution.getRandom(); // return 2
+solution.getRandom(); // return 2
+solution.getRandom(); // return 3
+// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the linked list will be in the range [1, 104].
  • +
  • -104 <= Node.val <= 104
  • +
  • At most 104 calls will be made to getRandom.
  • +
+ +

 

+

Follow up:

+ +
    +
  • What if the linked list is extremely large and its length is unknown to you?
  • +
  • Could you solve this efficiently without using extra space?
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0382.Linked List Random Node/images/getrand-linked-list.jpg b/assets/0300-0399/0382.Linked List Random Node/images/getrand-linked-list.jpg new file mode 100644 index 00000000..949d1f4f Binary files /dev/null and b/assets/0300-0399/0382.Linked List Random Node/images/getrand-linked-list.jpg differ diff --git a/assets/0300-0399/0383.Ransom Note/README_EN.md b/assets/0300-0399/0383.Ransom Note/README_EN.md new file mode 100644 index 00000000..b73c0a57 --- /dev/null +++ b/assets/0300-0399/0383.Ransom Note/README_EN.md @@ -0,0 +1,75 @@ +# [383. Ransom Note](https://leetcode.com/problems/ransom-note) + + + +## Description + +

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

+ +

Each letter in the magazine string can only be used once in your ransom note.

+ +

 

+

Example 1:

+
Input: ransomNote = "a", magazine = "b"
+Output: false
+

Example 2:

+
Input: ransomNote = "aa", magazine = "ab"
+Output: false
+

Example 3:

+
Input: ransomNote = "aa", magazine = "aab"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • You may assume that both strings contain only lowercase letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + chars = {} + for i in magazine: + chars[i] = chars.get(i, 0) + 1 + for i in ransomNote: + if not chars.get(i): + return False + chars[i] -= 1 + return True +``` + +### **Java** + +```java +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + int[] chars = new int[26]; + for (int i = 0, n = magazine.length(); i < n; ++i) { + int idx = magazine.charAt(i) - 'a'; + ++chars[idx]; + } + for (int i = 0, n = ransomNote.length(); i < n; ++i) { + int idx = ransomNote.charAt(i) - 'a'; + if (chars[idx] == 0) return false; + --chars[idx]; + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0384.Shuffle an Array/README_EN.md b/assets/0300-0399/0384.Shuffle an Array/README_EN.md new file mode 100644 index 00000000..99583d62 --- /dev/null +++ b/assets/0300-0399/0384.Shuffle an Array/README_EN.md @@ -0,0 +1,68 @@ +# [384. Shuffle an Array](https://leetcode.com/problems/shuffle-an-array) + + + +## Description + +

Given an integer array nums, design an algorithm to randomly shuffle the array.

+ +

Implement the Solution class:

+ +
    +
  • Solution(int[] nums) Initializes the object with the integer array nums.
  • +
  • int[] reset() Resets the array to its original configuration and returns it.
  • +
  • int[] shuffle() Returns a random shuffling of the array.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Solution", "shuffle", "reset", "shuffle"]
+[[[1, 2, 3]], [], [], []]
+Output
+[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
+
+Explanation
+Solution solution = new Solution([1, 2, 3]);
+solution.shuffle();    // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must be equally likely to be returned. Example: return [3, 1, 2]
+solution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
+solution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
+
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • -106 <= nums[i] <= 106
  • +
  • All the elements of nums are unique.
  • +
  • At most 5 * 104 calls will be made to reset and shuffle.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0385.Mini Parser/README_EN.md b/assets/0300-0399/0385.Mini Parser/README_EN.md new file mode 100644 index 00000000..c6cfb5f0 --- /dev/null +++ b/assets/0300-0399/0385.Mini Parser/README_EN.md @@ -0,0 +1,65 @@ +# [385. Mini Parser](https://leetcode.com/problems/mini-parser) + + + +## Description + +

Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger.

+ +

Each element is either an integer or a list whose elements may also be integers or other lists.

+ +

 

+

Example 1:

+ +
+Input: s = "324"
+Output: 324
+Explanation: You should return a NestedInteger object which contains a single integer 324.
+
+ +

Example 2:

+ +
+Input: s = "[123,[456,[789]]]"
+Output: [123,[456,[789]]]
+Explanation: Return a NestedInteger object containing a nested list with 2 elements:
+1. An integer containing value 123.
+2. A nested list containing two elements:
+    i.  An integer containing value 456.
+    ii. A nested list with one element:
+         a. An integer containing value 789
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s consists of digits, square brackets "[]", negative sign '-', and commas ','.
  • +
  • s is the serialization of valid NestedInteger.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0386.Lexicographical Numbers/README_EN.md b/assets/0300-0399/0386.Lexicographical Numbers/README_EN.md new file mode 100644 index 00000000..04d056ea --- /dev/null +++ b/assets/0300-0399/0386.Lexicographical Numbers/README_EN.md @@ -0,0 +1,50 @@ +# [386. Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers) + + + +## Description + +

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.

+ +

 

+

Example 1:

+
Input: n = 13
+Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
+

Example 2:

+
Input: n = 2
+Output: [1,2]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 5 * 104
  • +
+ +

 

+

Follow up: Could you optimize your solution to use O(n) runtime and O(1) space?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0387.First Unique Character in a String/README_EN.md b/assets/0300-0399/0387.First Unique Character in a String/README_EN.md new file mode 100644 index 00000000..ba245d6d --- /dev/null +++ b/assets/0300-0399/0387.First Unique Character in a String/README_EN.md @@ -0,0 +1,75 @@ +# [387. First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string) + + + +## Description + +

Given a string s, return the first non-repeating character in it and return its index. If it does not exist, return -1.

+ +

 

+

Example 1:

+
Input: s = "leetcode"
+Output: 0
+

Example 2:

+
Input: s = "loveleetcode"
+Output: 2
+

Example 3:

+
Input: s = "aabb"
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def firstUniqChar(self, s: str) -> int: + chars = {} + for ch in s: + ch = ord(ch) + chars[ch] = chars.get(ch, 0) + 1 + for i, ch in enumerate(s): + ch = ord(ch) + if chars[ch] == 1: + return i + return -1 +``` + +### **Java** + +```java +class Solution { + public int firstUniqChar(String s) { + Map chars = new HashMap<>(26); + int n = s.length(); + for (int i = 0; i < n; ++i) { + char ch = s.charAt(i); + chars.put(ch, chars.getOrDefault(ch, 0) + 1); + } + for (int i = 0; i < n; ++i) { + char ch = s.charAt(i); + if (chars.get(ch) == 1) return i; + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0388.Longest Absolute File Path/README_EN.md b/assets/0300-0399/0388.Longest Absolute File Path/README_EN.md new file mode 100644 index 00000000..ee89af7a --- /dev/null +++ b/assets/0300-0399/0388.Longest Absolute File Path/README_EN.md @@ -0,0 +1,99 @@ +# [388. Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path) + + + +## Description + +

Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:

+ +

+ +

Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext.

+ +

In text form, it looks like this (with ⟶ representing the tab character):

+ +
+dir
+⟶ subdir1
+⟶ ⟶ file1.ext
+⟶ ⟶ subsubdir1
+⟶ subdir2
+⟶ ⟶ subsubdir2
+⟶ ⟶ ⟶ file2.ext
+
+ +

If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters.

+ +

Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces.

+ +

Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.

+ +

 

+

Example 1:

+ +
+Input: input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
+Output: 20
+Explanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20.
+
+ +

Example 2:

+ +
+Input: input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
+Output: 32
+Explanation: We have two files:
+"dir/subdir1/file1.ext" of length 21
+"dir/subdir2/subsubdir2/file2.ext" of length 32.
+We return 32 since it is the longest absolute path to a file.
+
+ +

Example 3:

+ +
+Input: input = "a"
+Output: 0
+Explanation: We do not have any files, just a single directory named "a".
+
+ +

Example 4:

+ +
+Input: input = "file1.txt\nfile2.txt\nlongfile.txt"
+Output: 12
+Explanation: There are 3 files at the root directory.
+Since the absolute path for anything at the root directory is just the name itself, the answer is "longfile.txt" with length 12.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= input.length <= 104
  • +
  • input may contain lowercase or uppercase English letters, a new line character '\n', a tab character '\t', a dot '.', a space ' ', and digits.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0388.Longest Absolute File Path/images/dir1.jpg b/assets/0300-0399/0388.Longest Absolute File Path/images/dir1.jpg new file mode 100644 index 00000000..ff603e0a Binary files /dev/null and b/assets/0300-0399/0388.Longest Absolute File Path/images/dir1.jpg differ diff --git a/assets/0300-0399/0388.Longest Absolute File Path/images/dir2.jpg b/assets/0300-0399/0388.Longest Absolute File Path/images/dir2.jpg new file mode 100644 index 00000000..b9957f35 Binary files /dev/null and b/assets/0300-0399/0388.Longest Absolute File Path/images/dir2.jpg differ diff --git a/assets/0300-0399/0388.Longest Absolute File Path/images/mdir.jpg b/assets/0300-0399/0388.Longest Absolute File Path/images/mdir.jpg new file mode 100644 index 00000000..eddc7e54 Binary files /dev/null and b/assets/0300-0399/0388.Longest Absolute File Path/images/mdir.jpg differ diff --git a/assets/0300-0399/0389.Find the Difference/README_EN.md b/assets/0300-0399/0389.Find the Difference/README_EN.md new file mode 100644 index 00000000..25f122a1 --- /dev/null +++ b/assets/0300-0399/0389.Find the Difference/README_EN.md @@ -0,0 +1,97 @@ +# [389. Find the Difference](https://leetcode.com/problems/find-the-difference) + + + +## Description + +

You are given two strings s and t.

+ +

String t is generated by random shuffling string s and then add one more letter at a random position.

+ +

Return the letter that was added to t.

+ +

 

+

Example 1:

+ +
+Input: s = "abcd", t = "abcde"
+Output: "e"
+Explanation: 'e' is the letter that was added.
+
+ +

Example 2:

+ +
+Input: s = "", t = "y"
+Output: "y"
+
+ +

Example 3:

+ +
+Input: s = "a", t = "aa"
+Output: "a"
+
+ +

Example 4:

+ +
+Input: s = "ae", t = "aea"
+Output: "a"
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 1000
  • +
  • t.length == s.length + 1
  • +
  • s and t consist of lower-case English letters.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + counter = collections.Counter(s) + for c in t: + if counter[c] <= 0: + return c + counter[c] -= 1 + return None +``` + +### **Java** + +```java +class Solution { + public char findTheDifference(String s, String t) { + int[] counter = new int[26]; + for (int i = 0; i < s.length(); ++i) { + int index = s.charAt(i) - 'a'; + ++counter[index]; + } + for (int i = 0; i < t.length(); ++i) { + int index = t.charAt(i) - 'a'; + if (counter[index] <= 0) { + return t.charAt(i); + } + --counter[index]; + } + return ' '; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0390.Elimination Game/README_EN.md b/assets/0300-0399/0390.Elimination Game/README_EN.md new file mode 100644 index 00000000..cfeedf42 --- /dev/null +++ b/assets/0300-0399/0390.Elimination Game/README_EN.md @@ -0,0 +1,67 @@ +# [390. Elimination Game](https://leetcode.com/problems/elimination-game) + + + +## Description + +

You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:

+ +
    +
  • Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
  • +
  • Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.
  • +
  • Keep repeating the steps again, alternating left to right and right to left, until a single number remains.
  • +
+ +

Given the integer n, return the last number that remains in arr.

+ +

 

+

Example 1:

+ +
+Input: n = 9
+Output: 6
+Explanation:
+arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
+arr = [2, 4, 6, 8]
+arr = [2, 6]
+arr = [6]
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0391.Perfect Rectangle/README_EN.md b/assets/0300-0399/0391.Perfect Rectangle/README_EN.md new file mode 100644 index 00000000..cbda6c53 --- /dev/null +++ b/assets/0300-0399/0391.Perfect Rectangle/README_EN.md @@ -0,0 +1,76 @@ +# [391. Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle) + + + +## Description + +

Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).

+ +

Return true if all the rectangles together form an exact cover of a rectangular region.

+ +

 

+

Example 1:

+ +
+Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]
+Output: true
+Explanation: All 5 rectangles together form an exact cover of a rectangular region.
+
+ +

Example 2:

+ +
+Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]
+Output: false
+Explanation: Because there is a gap between the two rectangular regions.
+
+ +

Example 3:

+ +
+Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]
+Output: false
+Explanation: Because there is a gap in the top center.
+
+ +

Example 4:

+ +
+Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]
+Output: false
+Explanation: Because two of the rectangles overlap with each other.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= rectangles.length <= 2 * 104
  • +
  • rectangles[i].length == 4
  • +
  • -105 <= xi, yi, ai, bi <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_hole.gif b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_hole.gif new file mode 100644 index 00000000..1709d297 Binary files /dev/null and b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_hole.gif differ diff --git a/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_intersect.gif b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_intersect.gif new file mode 100644 index 00000000..26c2d539 Binary files /dev/null and b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_intersect.gif differ diff --git a/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_perfect.gif b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_perfect.gif new file mode 100644 index 00000000..7c6bd0fb Binary files /dev/null and b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_perfect.gif differ diff --git a/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_separated.gif b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_separated.gif new file mode 100644 index 00000000..3ed1b501 Binary files /dev/null and b/assets/0300-0399/0391.Perfect Rectangle/images/rectangle_separated.gif differ diff --git a/assets/0300-0399/0392.Is Subsequence/README_EN.md b/assets/0300-0399/0392.Is Subsequence/README_EN.md new file mode 100644 index 00000000..b6596960 --- /dev/null +++ b/assets/0300-0399/0392.Is Subsequence/README_EN.md @@ -0,0 +1,92 @@ +# [392. Is Subsequence](https://leetcode.com/problems/is-subsequence) + + + +## Description + +

Given two strings s and t, check if s is a subsequence of t.

+ +

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

+ +

 

+

Example 1:

+
Input: s = "abc", t = "ahbgdc"
+Output: true
+

Example 2:

+
Input: s = "axc", t = "ahbgdc"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 100
  • +
  • 0 <= t.length <= 104
  • +
  • s and t consist only of lowercase English letters.
  • +
+ +

 

+Follow up: If there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + m, n = len(s), len(t) + i = j = 0 + while i < m and j < n: + if s[i] == t[j]: + i += 1 + j += 1 + return i == m +``` + +### **Java** + +```java +class Solution { + public boolean isSubsequence(String s, String t) { + int m = s.length(), n = t.length(); + int i = 0, j = 0; + while (i < m && j < n) { + if (s.charAt(i) == t.charAt(j)) { + ++i; + } + ++j; + } + return i == m; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isSubsequence(string s, string t) { + int m = s.size(), n = t.size(); + int i = 0, j = 0; + while (i < m && j < n) { + if (s[i] == t[j]) { + ++i; + } + ++j; + } + return i == m; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0393.UTF-8 Validation/README_EN.md b/assets/0300-0399/0393.UTF-8 Validation/README_EN.md new file mode 100644 index 00000000..e5cfd48c --- /dev/null +++ b/assets/0300-0399/0393.UTF-8 Validation/README_EN.md @@ -0,0 +1,82 @@ +# [393. UTF-8 Validation](https://leetcode.com/problems/utf-8-validation) + + + +## Description + +

Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.

+ +

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

+ +
    +
  1. For a 1-byte character, the first bit is a 0, followed by its Unicode code.
  2. +
  3. For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.
  4. +
+ +

This is how the UTF-8 encoding would work:

+ +
+   Char. number range  |        UTF-8 octet sequence
+      (hexadecimal)    |              (binary)
+   --------------------+---------------------------------------------
+   0000 0000-0000 007F | 0xxxxxxx
+   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
+   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
+   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+
+ +

Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

+ +

 

+

Example 1:

+ +
+Input: data = [197,130,1]
+Output: true
+Explanation: data represents the octet sequence: 11000101 10000010 00000001.
+It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
+
+ +

Example 2:

+ +
+Input: data = [235,140,4]
+Output: false
+Explanation: data represented the octet sequence: 11101011 10001100 00000100.
+The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
+The next byte is a continuation byte which starts with 10 and that's correct.
+But the second continuation byte does not start with 10, so it is invalid.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= data.length <= 2 * 104
  • +
  • 0 <= data[i] <= 255
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0394.Decode String/README_EN.md b/assets/0300-0399/0394.Decode String/README_EN.md new file mode 100644 index 00000000..73db8d81 --- /dev/null +++ b/assets/0300-0399/0394.Decode String/README_EN.md @@ -0,0 +1,62 @@ +# [394. Decode String](https://leetcode.com/problems/decode-string) + + + +## Description + +

Given an encoded string, return its decoded string.

+ +

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

+ +

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

+ +

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

+ +

 

+

Example 1:

+
Input: s = "3[a]2[bc]"
+Output: "aaabcbc"
+

Example 2:

+
Input: s = "3[a2[c]]"
+Output: "accaccacc"
+

Example 3:

+
Input: s = "2[abc]3[cd]ef"
+Output: "abcabccdcdcdef"
+

Example 4:

+
Input: s = "abc3[cd]xyz"
+Output: "abccdcdcdxyz"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 30
  • +
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • +
  • s is guaranteed to be a valid input.
  • +
  • All the integers in s are in the range [1, 300].
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md b/assets/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md new file mode 100644 index 00000000..677bc86c --- /dev/null +++ b/assets/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md @@ -0,0 +1,58 @@ +# [395. Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters) + + + +## Description + +

Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.

+ +

 

+

Example 1:

+ +
+Input: s = "aaabb", k = 3
+Output: 3
+Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.
+
+ +

Example 2:

+ +
+Input: s = "ababbc", k = 2
+Output: 5
+Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of only lowercase English letters.
  • +
  • 1 <= k <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0396.Rotate Function/README_EN.md b/assets/0300-0399/0396.Rotate Function/README_EN.md new file mode 100644 index 00000000..223a6bcc --- /dev/null +++ b/assets/0300-0399/0396.Rotate Function/README_EN.md @@ -0,0 +1,70 @@ +# [396. Rotate Function](https://leetcode.com/problems/rotate-function) + + + +## Description + +

You are given an integer array nums of length n.

+ +

Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:

+ +
    +
  • F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
  • +
+ +

Return the maximum value of F(0), F(1), ..., F(n-1).

+ +

 

+

Example 1:

+ +
+Input: nums = [4,3,2,6]
+Output: 26
+Explanation:
+F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
+F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
+F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
+F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
+So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
+
+ +

Example 2:

+ +
+Input: nums = [1000000007]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0397.Integer Replacement/README_EN.md b/assets/0300-0399/0397.Integer Replacement/README_EN.md new file mode 100644 index 00000000..35b8072b --- /dev/null +++ b/assets/0300-0399/0397.Integer Replacement/README_EN.md @@ -0,0 +1,71 @@ +# [397. Integer Replacement](https://leetcode.com/problems/integer-replacement) + + + +## Description + +

Given a positive integer n, you can apply one of the following operations:

+ +
    +
  1. If n is even, replace n with n / 2.
  2. +
  3. If n is odd, replace n with either n + 1 or n - 1.
  4. +
+ +

Return the minimum number of operations needed for n to become 1.

+ +

 

+

Example 1:

+ +
+Input: n = 8
+Output: 3
+Explanation: 8 -> 4 -> 2 -> 1
+
+ +

Example 2:

+ +
+Input: n = 7
+Output: 4
+Explanation: 7 -> 8 -> 4 -> 2 -> 1
+or 7 -> 6 -> 3 -> 2 -> 1
+
+ +

Example 3:

+ +
+Input: n = 4
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0398.Random Pick Index/README_EN.md b/assets/0300-0399/0398.Random Pick Index/README_EN.md new file mode 100644 index 00000000..f6b67601 --- /dev/null +++ b/assets/0300-0399/0398.Random Pick Index/README_EN.md @@ -0,0 +1,66 @@ +# [398. Random Pick Index](https://leetcode.com/problems/random-pick-index) + + + +## Description + +

Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

+ +

Implement the Solution class:

+ +
    +
  • Solution(int[] nums) Initializes the object with the array nums.
  • +
  • int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Solution", "pick", "pick", "pick"]
+[[[1, 2, 3, 3, 3]], [3], [1], [3]]
+Output
+[null, 4, 0, 2]
+
+Explanation
+Solution solution = new Solution([1, 2, 3, 3, 3]);
+solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
+solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.
+solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
  • target is an integer from nums.
  • +
  • At most 104 calls will be made to pick.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0300-0399/0399.Evaluate Division/README_EN.md b/assets/0300-0399/0399.Evaluate Division/README_EN.md new file mode 100644 index 00000000..35a53671 --- /dev/null +++ b/assets/0300-0399/0399.Evaluate Division/README_EN.md @@ -0,0 +1,79 @@ +# [399. Evaluate Division](https://leetcode.com/problems/evaluate-division) + + + +## Description + +

You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.

+ +

You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.

+ +

Return the answers to all queries. If a single answer cannot be determined, return -1.0.

+ +

Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.

+ +

 

+

Example 1:

+ +
+Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
+Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
+Explanation: 
+Given: a / b = 2.0, b / c = 3.0
+queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
+return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
+
+ +

Example 2:

+ +
+Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
+Output: [3.75000,0.40000,5.00000,0.20000]
+
+ +

Example 3:

+ +
+Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
+Output: [0.50000,2.00000,-1.00000,-1.00000]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= equations.length <= 20
  • +
  • equations[i].length == 2
  • +
  • 1 <= Ai.length, Bi.length <= 5
  • +
  • values.length == equations.length
  • +
  • 0.0 < values[i] <= 20.0
  • +
  • 1 <= queries.length <= 20
  • +
  • queries[i].length == 2
  • +
  • 1 <= Cj.length, Dj.length <= 5
  • +
  • Ai, Bi, Cj, Dj consist of lower case English letters and digits.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0400.Nth Digit/README_EN.md b/assets/0400-0499/0400.Nth Digit/README_EN.md new file mode 100644 index 00000000..3e2d1a36 --- /dev/null +++ b/assets/0400-0499/0400.Nth Digit/README_EN.md @@ -0,0 +1,55 @@ +# [400. Nth Digit](https://leetcode.com/problems/nth-digit) + + + +## Description + +

Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].

+ +

 

+

Example 1:

+ +
+Input: n = 3
+Output: 3
+
+ +

Example 2:

+ +
+Input: n = 11
+Output: 0
+Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0401.Binary Watch/README_EN.md b/assets/0400-0499/0401.Binary Watch/README_EN.md new file mode 100644 index 00000000..15a32304 --- /dev/null +++ b/assets/0400-0499/0401.Binary Watch/README_EN.md @@ -0,0 +1,81 @@ +# [401. Binary Watch](https://leetcode.com/problems/binary-watch) + + + +## Description + +

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

+ +
    +
  • For example, the below binary watch reads "4:51".
  • +
+ +

+ +

Given an integer turnedOn which represents the number of LEDs that are currently on, return all possible times the watch could represent. You may return the answer in any order.

+ +

The hour must not contain a leading zero.

+ +
    +
  • For example, "01:00" is not valid. It should be "1:00".
  • +
+ +

The minute must be consist of two digits and may contain a leading zero.

+ +
    +
  • For example, "10:2" is not valid. It should be "10:02".
  • +
+ +

 

+

Example 1:

+
Input: turnedOn = 1
+Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
+

Example 2:

+
Input: turnedOn = 9
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • 0 <= turnedOn <= 10
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def readBinaryWatch(self, num: int) -> List[str]: + return ['{:d}:{:02d}'.format(i, j) for i in range(12) for j in range(60) if (bin(i) + bin(j)).count('1') == num] +``` + +### **Java** + +```java +class Solution { + public List readBinaryWatch(int num) { + List res = new ArrayList<>(); + for (int i = 0; i < 12; ++i) { + for (int j = 0; j < 60; ++j) { + if (Integer.bitCount(i) + Integer.bitCount(j) == num) { + res.add(String.format("%d:%02d", i, j)); + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0401.Binary Watch/images/binary_clock_samui_moon.jpg b/assets/0400-0499/0401.Binary Watch/images/binary_clock_samui_moon.jpg new file mode 100644 index 00000000..d7b120ec Binary files /dev/null and b/assets/0400-0499/0401.Binary Watch/images/binary_clock_samui_moon.jpg differ diff --git a/assets/0400-0499/0401.Binary Watch/images/binarywatch.jpg b/assets/0400-0499/0401.Binary Watch/images/binarywatch.jpg new file mode 100644 index 00000000..08144388 Binary files /dev/null and b/assets/0400-0499/0401.Binary Watch/images/binarywatch.jpg differ diff --git a/assets/0400-0499/0402.Remove K Digits/README_EN.md b/assets/0400-0499/0402.Remove K Digits/README_EN.md new file mode 100644 index 00000000..d077fded --- /dev/null +++ b/assets/0400-0499/0402.Remove K Digits/README_EN.md @@ -0,0 +1,66 @@ +# [402. Remove K Digits](https://leetcode.com/problems/remove-k-digits) + + + +## Description + +

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

+ +

 

+

Example 1:

+ +
+Input: num = "1432219", k = 3
+Output: "1219"
+Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
+
+ +

Example 2:

+ +
+Input: num = "10200", k = 1
+Output: "200"
+Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
+
+ +

Example 3:

+ +
+Input: num = "10", k = 2
+Output: "0"
+Explanation: Remove all the digits from the number and it is left with nothing which is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= num.length <= 105
  • +
  • num consists of only digits.
  • +
  • num does not have any leading zeros except for the zero itself.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0403.Frog Jump/README_EN.md b/assets/0400-0499/0403.Frog Jump/README_EN.md new file mode 100644 index 00000000..ec324677 --- /dev/null +++ b/assets/0400-0499/0403.Frog Jump/README_EN.md @@ -0,0 +1,98 @@ +# [403. Frog Jump](https://leetcode.com/problems/frog-jump) + + + +## Description + +

A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

+ +

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.

+ +

If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.

+ +

 

+

Example 1:

+ +
+Input: stones = [0,1,3,5,6,8,12,17]
+Output: true
+Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
+
+ +

Example 2:

+ +
+Input: stones = [0,1,2,3,4,8,9,11]
+Output: false
+Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
+
+ +

 

+

Constraints:

+ +
    +
  • 2 <= stones.length <= 2000
  • +
  • 0 <= stones[i] <= 231 - 1
  • +
  • stones[0] == 0
  • +
+ + +## Solutions + +DP, use `dp[i][k]` to indicate whether `i` can be reached when the last jump was `k` units, and define the base case as `dp[0][0] = True` (starting point is at index 0). + +Because "the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units", so if any of `dp[j][k-1], dp[j][k], dp[j][k + 1]` is true, frog can jump from `j` to `i`. + + + +### **Python3** + +```python +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + dp = [[False] * n for i in range(n)] + dp[0][0] = True + for i in range(1, n): + for j in range(i): + k = stones[i] - stones[j]; + if k > j + 1: + continue + dp[i][k] = dp[j][k - 1] or dp[j][k] or dp[j][k + 1] + if i == n - 1 and dp[i][k]: + return True + return False +``` + +### **Java** + +```java +class Solution { + public boolean canCross(int[] stones) { + int n = stones.length; + boolean[][] dp = new boolean[n][n]; + dp[0][0] = true; + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + int k = stones[i] - stones[j]; + if (k > j + 1) { + continue; + } + dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; + if (i == n - 1 && dp[i][k]) { + return true; + } + } + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0404.Sum of Left Leaves/README_EN.md b/assets/0400-0499/0404.Sum of Left Leaves/README_EN.md new file mode 100644 index 00000000..118bb8ea --- /dev/null +++ b/assets/0400-0499/0404.Sum of Left Leaves/README_EN.md @@ -0,0 +1,94 @@ +# [404. Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves) + + + +## Description + +

Given the root of a binary tree, return the sum of all left leaves.

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: 24
+Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
+
+ +

Example 2:

+ +
+Input: root = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 1000].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def sumOfLeftLeaves(self, root: TreeNode) -> int: + if root is None: + return 0 + res = 0 + if root.left and root.left.left is None and root.left.right is None: + res += root.left.val + res += self.sumOfLeftLeaves(root.left) + res += self.sumOfLeftLeaves(root.right) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) { + return 0; + } + int res = 0; + if (root.left != null && root.left.left == null && root.left.right == null) { + res += root.left.val; + } + res += sumOfLeftLeaves(root.left); + res += sumOfLeftLeaves(root.right); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0404.Sum of Left Leaves/images/leftsum-tree.jpg b/assets/0400-0499/0404.Sum of Left Leaves/images/leftsum-tree.jpg new file mode 100644 index 00000000..d77a04e7 Binary files /dev/null and b/assets/0400-0499/0404.Sum of Left Leaves/images/leftsum-tree.jpg differ diff --git a/assets/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md b/assets/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md new file mode 100644 index 00000000..0fae0ec5 --- /dev/null +++ b/assets/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md @@ -0,0 +1,52 @@ +# [405. Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal) + + + +## Description + +

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

+ +

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

+ +

 

+

Example 1:

+
Input: num = 26
+Output: "1a"
+

Example 2:

+
Input: num = -1
+Output: "ffffffff"
+
+

 

+

Constraints:

+ +
    +
  • -231 <= num <= 231 - 1
  • +
+ +

 

+

Follow up: Could you solve it without using any built-in library method?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0406.Queue Reconstruction by Height/README_EN.md b/assets/0400-0499/0406.Queue Reconstruction by Height/README_EN.md new file mode 100644 index 00000000..fdf6980a --- /dev/null +++ b/assets/0400-0499/0406.Queue Reconstruction by Height/README_EN.md @@ -0,0 +1,67 @@ +# [406. Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height) + + + +## Description + +

You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.

+ +

Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).

+ +

 

+

Example 1:

+ +
+Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
+Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
+Explanation:
+Person 0 has height 5 with no other people taller or the same height in front.
+Person 1 has height 7 with no other people taller or the same height in front.
+Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
+Person 3 has height 6 with one person taller or the same height in front, which is person 1.
+Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
+Person 5 has height 7 with one person taller or the same height in front, which is person 1.
+Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.
+
+ +

Example 2:

+ +
+Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
+Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= people.length <= 2000
  • +
  • 0 <= hi <= 106
  • +
  • 0 <= ki < people.length
  • +
  • It is guaranteed that the queue can be reconstructed.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0407.Trapping Rain Water II/README_EN.md b/assets/0400-0499/0407.Trapping Rain Water II/README_EN.md new file mode 100644 index 00000000..004b196e --- /dev/null +++ b/assets/0400-0499/0407.Trapping Rain Water II/README_EN.md @@ -0,0 +1,60 @@ +# [407. Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii) + + + +## Description + +

Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.

+ +

 

+

Example 1:

+ +
+Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
+Output: 4
+Explanation: After the rain, water is trapped between the blocks.
+We have two small pounds 1 and 3 units trapped.
+The total volume of water trapped is 4.
+
+ +

Example 2:

+ +
+Input: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
+Output: 10
+
+ +

 

+

Constraints:

+ +
    +
  • m == heightMap.length
  • +
  • n == heightMap[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 0 <= heightMap[i][j] <= 2 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0407.Trapping Rain Water II/images/rainwater_empty.png b/assets/0400-0499/0407.Trapping Rain Water II/images/rainwater_empty.png new file mode 100644 index 00000000..50ec51e4 Binary files /dev/null and b/assets/0400-0499/0407.Trapping Rain Water II/images/rainwater_empty.png differ diff --git a/assets/0400-0499/0407.Trapping Rain Water II/images/rainwater_fill.png b/assets/0400-0499/0407.Trapping Rain Water II/images/rainwater_fill.png new file mode 100644 index 00000000..7adc9882 Binary files /dev/null and b/assets/0400-0499/0407.Trapping Rain Water II/images/rainwater_fill.png differ diff --git a/assets/0400-0499/0408.Valid Word Abbreviation/README_EN.md b/assets/0400-0499/0408.Valid Word Abbreviation/README_EN.md new file mode 100644 index 00000000..81c4cb9f --- /dev/null +++ b/assets/0400-0499/0408.Valid Word Abbreviation/README_EN.md @@ -0,0 +1,61 @@ +# [408. Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation) + + + +## Description + +

A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to):

+ +
    +
  • "s10n" ("s ubstitutio n")
  • +
  • "sub4u4" ("sub stit u tion")
  • +
  • "12" ("substitution")
  • +
  • "su3i1u2on" ("su bst i t u ti on")
  • +
  • "substitution" (no substrings replaced)
  • +
+ +

Note that "s55n" ("s ubsti tutio n") is not a valid abbreviation of "substitution" because the replaced substrings are adjacent.

+ +

Given a string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

+ +

 

+

Example 1:

+
Input: word = "internationalization", abbr = "i12iz4n"
+Output: true
+

Example 2:

+
Input: word = "apple", abbr = "a2e"
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= word.length, abbr.length <= 20
  • +
  • word consists of only lowercase English letters.
  • +
  • abbr consists of lowercase English letters and digits.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0409.Longest Palindrome/README_EN.md b/assets/0400-0499/0409.Longest Palindrome/README_EN.md new file mode 100644 index 00000000..4b0569dc --- /dev/null +++ b/assets/0400-0499/0409.Longest Palindrome/README_EN.md @@ -0,0 +1,87 @@ +# [409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome) + + + +## Description + +

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

+ +

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

+ +

 

+

Example 1:

+ +
+Input: s = "abccccdd"
+Output: 7
+Explanation:
+One longest palindrome that can be built is "dccaccd", whose length is 7.
+
+ +

Example 2:

+ +
+Input: s = "a"
+Output: 1
+
+ +

Example 3:

+ +
+Input: s = "bb"
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 2000
  • +
  • s consists of lowercase and/or uppercase English letters only.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def longestPalindrome(self, s: str) -> int: + res = [0] * 128 + for ch in s: + res[ord(ch)] += 1 + odd_cnt, n = 0, len(s) + for e in res: + odd_cnt += (e % 2) + return n if odd_cnt == 0 else n - odd_cnt + 1 +``` + +### **Java** + +```java +class Solution { + public int longestPalindrome(String s) { + int[] res = new int[128]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + res[s.charAt(i)]++; + } + int oddCnt = 0; + for (int e : res) { + oddCnt += (e % 2); + } + return oddCnt == 0 ? n : n - oddCnt + 1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0410.Split Array Largest Sum/README_EN.md b/assets/0400-0499/0410.Split Array Largest Sum/README_EN.md new file mode 100644 index 00000000..5fd5a4dc --- /dev/null +++ b/assets/0400-0499/0410.Split Array Largest Sum/README_EN.md @@ -0,0 +1,69 @@ +# [410. Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum) + + + +## Description + +

Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.

+ +

Write an algorithm to minimize the largest sum among these m subarrays.

+ +

 

+

Example 1:

+ +
+Input: nums = [7,2,5,10,8], m = 2
+Output: 18
+Explanation:
+There are four ways to split nums into two subarrays.
+The best way is to split it into [7,2,5] and [10,8],
+where the largest sum among the two subarrays is only 18.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4,5], m = 2
+Output: 9
+
+ +

Example 3:

+ +
+Input: nums = [1,4,4], m = 3
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 106
  • +
  • 1 <= m <= min(50, nums.length)
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md b/assets/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md new file mode 100644 index 00000000..ffe7adf1 --- /dev/null +++ b/assets/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md @@ -0,0 +1,81 @@ +# [411. Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation) + + + +## Description + +

A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to):

+ +
    +
  • "s10n" ("s ubstitutio n")
  • +
  • "sub4u4" ("sub stit u tion")
  • +
  • "12" ("substitution")
  • +
  • "su3i1u2on" ("su bst i t u ti on")
  • +
  • "substitution" (no substrings replaced)
  • +
+ +

Note that "s55n" ("s ubsti tutio n") is not a valid abbreviation of "substitution" because the replaced substrings are adjacent.

+ +

The length of an abbreviation is the number of letters that were not replaced plus the number of substrings that were replaced. For example, the abbreviation "s10n" has a length of 3 (2 letters + 1 substring) and "su3i1u2on" has a length of 9 (6 letters + 3 substrings).

+ +

Given a target string target and an array of strings dictionary, return an abbreviation of target with the shortest possible length such that it is not an abbreviation of any string in dictionary. If there are multiple shortest abbreviations, return any of them.

+ +

 

+

Example 1:

+ +
+Input: target = "apple", dictionary = ["blade"]
+Output: "a4"
+Explanation: The shortest abbreviation of "apple" is "5", but this is also an abbreviation of "blade".
+The next shortest abbreviations are "a4" and "4e". "4e" is an abbreviation of blade while "a4" is not.
+Hence, return "a4".
+
+ +

Example 2:

+ +
+Input: target = "apple", dictionary = ["blade","plain","amber"]
+Output: "1p3"
+Explanation: "5" is an abbreviation of both "apple" but also every word in the dictionary.
+"a4" is an abbreviation of "apple" but also "amber".
+"4e" is an abbreviation of "apple" but also "blade".
+"1p3", "2p2", and "3l1" are the next shortest abbreviations of "apple".
+Since none of them are abbreviations of words in the dictionary, returning any of them is correct.
+
+ +

 

+

Constraints:

+ +
    +
  • target.length == m
  • +
  • dictionary.length == n
  • +
  • 1 <= m <= 21
  • +
  • 0 <= n <= 1000
  • +
  • 1 <= dictionary[i] <= 100
  • +
  • log2(n) + m <= 21 if n > 0
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0412.Fizz Buzz/README_EN.md b/assets/0400-0499/0412.Fizz Buzz/README_EN.md new file mode 100644 index 00000000..8e0570b7 --- /dev/null +++ b/assets/0400-0499/0412.Fizz Buzz/README_EN.md @@ -0,0 +1,57 @@ +# [412. Fizz Buzz](https://leetcode.com/problems/fizz-buzz) + + + +## Description + +

Given an integer n, return a string array answer (1-indexed) where:

+ +
    +
  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • +
  • answer[i] == "Fizz" if i is divisible by 3.
  • +
  • answer[i] == "Buzz" if i is divisible by 5.
  • +
  • answer[i] == i if non of the above conditions are true.
  • +
+ +

 

+

Example 1:

+
Input: n = 3
+Output: ["1","2","Fizz"]
+

Example 2:

+
Input: n = 5
+Output: ["1","2","Fizz","4","Buzz"]
+

Example 3:

+
Input: n = 15
+Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0413.Arithmetic Slices/README_EN.md b/assets/0400-0499/0413.Arithmetic Slices/README_EN.md new file mode 100644 index 00000000..ccd159b9 --- /dev/null +++ b/assets/0400-0499/0413.Arithmetic Slices/README_EN.md @@ -0,0 +1,128 @@ +# [413. Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices) + + + +## Description + +

An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

+ +
    +
  • For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
  • +
+ +

Given an integer array nums, return the number of arithmetic subarrays of nums.

+ +

A subarray is a contiguous subsequence of the array.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,4]
+Output: 3
+Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
+
+ +

Example 2:

+ +
+Input: nums = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -1000 <= nums[i] <= 1000
  • +
+ +## Solutions + +Dynamic programming. + + + +### **Python3** + +```python +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + n = len(nums) + dp = [0] * n + for i in range(2, n): + if nums[i] + nums[i - 2] == (nums[i - 1] << 1): + dp[i] = 1 + dp[i - 1] + return sum(dp) +``` + +### **Java** + +```java +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int n = nums.length; + int[] dp = new int[n]; + for (int i = 2; i < n; ++i) { + if (nums[i] + nums[i - 2] == (nums[i - 1] << 1)) { + dp[i] = 1 + dp[i - 1]; + } + } + int res = 0; + for (int e : dp) { + res += e; + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int n = nums.size(); + vector dp(n, 0); + for (int i = 2; i < n; ++i) { + if (nums[i] + nums[i - 2] == (nums[i - 1] * 2)) { + dp[i] = 1 + dp[i - 1]; + } + } + int res = 0; + for (auto e : dp) { + res += e; + } + return res; + } +}; +``` + +### **Go** + +```go +func numberOfArithmeticSlices(nums []int) int { + n := len(nums) + dp := make([]int, n) + for i := 2; i < n; i++ { + if nums[i]-nums[i-1] == nums[i-1]-nums[i-2] { + dp[i] = 1 + dp[i-1] + } + } + res := 0 + for _, e := range dp { + res += e + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0414.Third Maximum Number/README_EN.md b/assets/0400-0499/0414.Third Maximum Number/README_EN.md new file mode 100644 index 00000000..1ca76dac --- /dev/null +++ b/assets/0400-0499/0414.Third Maximum Number/README_EN.md @@ -0,0 +1,153 @@ +# [414. Third Maximum Number](https://leetcode.com/problems/third-maximum-number) + + + +## Description + +

Given integer array nums, return the third maximum number in this array. If the third maximum does not exist, return the maximum number.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,2,1]
+Output: 1
+Explanation: The third maximum is 1.
+
+ +

Example 2:

+ +
+Input: nums = [1,2]
+Output: 2
+Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
+
+ +

Example 3:

+ +
+Input: nums = [2,2,3,1]
+Output: 1
+Explanation: Note that the third maximum here means the third maximum distinct number.
+Both numbers with value 2 are both considered as second maximum.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ +

 

+Follow up: Can you find an O(n) solution? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def thirdMax(self, nums: List[int]) -> int: + m1 = m2 = m3 = float('-inf') + for num in nums: + if num == m1 or num == m2 or num == m3: + continue + if num > m1: + m3, m2, m1 = m2, m1, num + elif num > m2: + m3, m2 = m2, num + elif num > m3: + m3 = num + return m1 if m3 == float('-inf') else m3 +``` + +### **Java** + +```java +class Solution { + public int thirdMax(int[] nums) { + long m1 = Long.MIN_VALUE; + long m2 = Long.MIN_VALUE; + long m3 = Long.MIN_VALUE; + for (int num : nums) { + if (num == m1 || num == m2 || num == m3) { + continue; + } + if (num > m1) { + m3 = m2; + m2 = m1; + m1 = num; + } else if (num > m2) { + m3 = m2; + m2 = num; + } else if (num > m3) { + m3 = num; + } + } + return (int) (m3 == Long.MIN_VALUE ? m1 : m3); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int thirdMax(vector& nums) { + long m1 = LONG_MIN, m2 = LONG_MIN, m3 = LONG_MIN; + for (int& num : nums) { + if (num == m1 || num == m2 || num == m3) continue; + if (num > m1) { + m3 = m2; + m2 = m1; + m1 = num; + } else if (num > m2) { + m3 = m2; + m2 = num; + } else if (num > m3) { + m3 = num; + } + } + return (int) (m3 == LONG_MIN ? m1 : m3); + } +}; +``` + +### **Go** + +```go +import "math" + +func thirdMax(nums []int) int { + m1, m2, m3 := math.MinInt64, math.MinInt64, math.MinInt64 + for _, num := range nums { + if num == m1 || num == m2 || num == m3 { + continue + } + if num > m1 { + m3, m2, m1 = m2, m1, num + } else if num > m2 { + m3, m2 = m2, num + } else if num > m3 { + m3 = num + } + } + if m3 == math.MinInt64 { + return m1 + } + return m3 +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0415.Add Strings/README_EN.md b/assets/0400-0499/0415.Add Strings/README_EN.md new file mode 100644 index 00000000..8188aa10 --- /dev/null +++ b/assets/0400-0499/0415.Add Strings/README_EN.md @@ -0,0 +1,88 @@ +# [415. Add Strings](https://leetcode.com/problems/add-strings) + + + +## Description + +

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

+ +

 

+

Example 1:

+ +
+Input: num1 = "11", num2 = "123"
+Output: "134"
+
+ +

Example 2:

+ +
+Input: num1 = "456", num2 = "77"
+Output: "533"
+
+ +

Example 3:

+ +
+Input: num1 = "0", num2 = "0"
+Output: "0"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num1.length, num2.length <= 104
  • +
  • num1 and num2 consist of only digits.
  • +
  • num1 and num2 don't have any leading zeros except for the zero itself.
  • +
+ +

 

+

Follow up: Could you solve it without using any built-in BigInteger library or converting the inputs to integer directly?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + n1, n2 = len(num1) - 1, len(num2) - 1 + carry = 0 + res = [] + while n1 >= 0 or n2 >= 0 or carry > 0: + carry += (0 if n1 < 0 else int(num1[n1])) + (0 if n2 < 0 else int(num2[n2])) + res.append(str(carry % 10)) + carry //= 10 + n1, n2 = n1 - 1, n2 - 1 + return ''.join(res[::-1]) +``` + +### **Java** + +```java +class Solution { + public String addStrings(String num1, String num2) { + int n1 = num1.length() - 1, n2 = num2.length() - 1; + int carry = 0; + StringBuilder sb = new StringBuilder(); + while (n1 >= 0 || n2 >= 0 || carry > 0) { + carry += (n1 < 0 ? 0 : num1.charAt(n1--) - '0') + (n2 < 0 ? 0 : num2.charAt(n2--) - '0'); + sb.append(carry % 10); + carry /= 10; + } + return sb.reverse().toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0416.Partition Equal Subset Sum/README_EN.md b/assets/0400-0499/0416.Partition Equal Subset Sum/README_EN.md new file mode 100644 index 00000000..169b24f7 --- /dev/null +++ b/assets/0400-0499/0416.Partition Equal Subset Sum/README_EN.md @@ -0,0 +1,57 @@ +# [416. Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum) + + + +## Description + +

Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,5,11,5]
+Output: true
+Explanation: The array can be partitioned as [1, 5, 5] and [11].
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,5]
+Output: false
+Explanation: The array cannot be partitioned into equal sum subsets.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 200
  • +
  • 1 <= nums[i] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md b/assets/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md new file mode 100644 index 00000000..a6214b95 --- /dev/null +++ b/assets/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md @@ -0,0 +1,61 @@ +# [417. Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow) + + + +## Description + +

You are given an m x n integer matrix heights representing the height of each unit cell in a continent. The Pacific ocean touches the continent's left and top edges, and the Atlantic ocean touches the continent's right and bottom edges.

+ +

Water can only flow in four directions: up, down, left, and right. Water flows from a cell to an adjacent one with an equal or lower height.

+ +

Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.

+ +

 

+

Example 1:

+ +
+Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
+Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
+
+ +

Example 2:

+ +
+Input: heights = [[2,1],[1,2]]
+Output: [[0,0],[0,1],[1,0],[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • m == heights.length
  • +
  • n == heights[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • 1 <= heights[i][j] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0417.Pacific Atlantic Water Flow/images/ocean-grid.jpg b/assets/0400-0499/0417.Pacific Atlantic Water Flow/images/ocean-grid.jpg new file mode 100644 index 00000000..7cdb7406 Binary files /dev/null and b/assets/0400-0499/0417.Pacific Atlantic Water Flow/images/ocean-grid.jpg differ diff --git a/assets/0400-0499/0418.Sentence Screen Fitting/README_EN.md b/assets/0400-0499/0418.Sentence Screen Fitting/README_EN.md new file mode 100644 index 00000000..b4252dad --- /dev/null +++ b/assets/0400-0499/0418.Sentence Screen Fitting/README_EN.md @@ -0,0 +1,81 @@ +# [418. Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting) + + + +## Description + +

Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen.

+ +

The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.

+ +

 

+

Example 1:

+ +
+Input: sentence = ["hello","world"], rows = 2, cols = 8
+Output: 1
+Explanation:
+hello---
+world---
+The character '-' signifies an empty space on the screen.
+
+ +

Example 2:

+ +
+Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
+Output: 2
+Explanation:
+a-bcd- 
+e-a---
+bcd-e-
+The character '-' signifies an empty space on the screen.
+
+ +

Example 3:

+ +
+Input: sentence = ["i","had","apple","pie"], rows = 4, cols = 5
+Output: 1
+Explanation:
+i-had
+apple
+pie-i
+had--
+The character '-' signifies an empty space on the screen.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= sentemce.length <= 100
  • +
  • 1 <= sentence[i].length <= 10
  • +
  • sentence[i] consists of lowercase English letters.
  • +
  • 1 <= rows, cols <= 2 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0419.Battleships in a Board/README_EN.md b/assets/0400-0499/0419.Battleships in a Board/README_EN.md new file mode 100644 index 00000000..3d26c664 --- /dev/null +++ b/assets/0400-0499/0419.Battleships in a Board/README_EN.md @@ -0,0 +1,62 @@ +# [419. Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board) + + + +## Description + +

Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.

+ +

Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).

+ +

 

+

Example 1:

+ +
+Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
+Output: 2
+
+ +

Example 2:

+ +
+Input: board = [["."]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == board.length
  • +
  • n == board[i].length
  • +
  • 1 <= m, n <= 200
  • +
  • board[i][j] is either '.' or 'X'.
  • +
+ +

 

+

Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0419.Battleships in a Board/images/battelship-grid.jpg b/assets/0400-0499/0419.Battleships in a Board/images/battelship-grid.jpg new file mode 100644 index 00000000..a0d282ce Binary files /dev/null and b/assets/0400-0499/0419.Battleships in a Board/images/battelship-grid.jpg differ diff --git a/assets/0400-0499/0420.Strong Password Checker/README_EN.md b/assets/0400-0499/0420.Strong Password Checker/README_EN.md new file mode 100644 index 00000000..8d9c79f2 --- /dev/null +++ b/assets/0400-0499/0420.Strong Password Checker/README_EN.md @@ -0,0 +1,67 @@ +# [420. Strong Password Checker](https://leetcode.com/problems/strong-password-checker) + + + +## Description + +

A password is considered strong if the below conditions are all met:

+ +
    +
  • It has at least 6 characters and at most 20 characters.
  • +
  • It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.
  • +
  • It does not contain three repeating characters in a row (i.e., "...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).
  • +
+ +

Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0.

+ +

In one step, you can:

+ +
    +
  • Insert one character to password,
  • +
  • Delete one character from password, or
  • +
  • Replace one character of password with another character.
  • +
+ +

 

+

Example 1:

+
Input: password = "a"
+Output: 5
+

Example 2:

+
Input: password = "aA1"
+Output: 3
+

Example 3:

+
Input: password = "1337C0d3"
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 1 <= password.length <= 50
  • +
  • password consists of letters, digits, dot '.' or exclamation mark '!'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md b/assets/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md new file mode 100644 index 00000000..1b1568cb --- /dev/null +++ b/assets/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md @@ -0,0 +1,78 @@ +# [421. Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array) + + + +## Description + +

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n.

+ +

Follow up: Could you do this in O(n) runtime?

+ +

 

+

Example 1:

+ +
+Input: nums = [3,10,5,25,2,8]
+Output: 28
+Explanation: The maximum result is 5 XOR 25 = 28.
+ +

Example 2:

+ +
+Input: nums = [0]
+Output: 0
+
+ +

Example 3:

+ +
+Input: nums = [2,4]
+Output: 6
+
+ +

Example 4:

+ +
+Input: nums = [8,10,2]
+Output: 10
+
+ +

Example 5:

+ +
+Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
+Output: 127
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • 0 <= nums[i] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0422.Valid Word Square/README_EN.md b/assets/0400-0499/0422.Valid Word Square/README_EN.md new file mode 100644 index 00000000..a99b6eeb --- /dev/null +++ b/assets/0400-0499/0422.Valid Word Square/README_EN.md @@ -0,0 +1,80 @@ +# [422. Valid Word Square](https://leetcode.com/problems/valid-word-square) + + + +## Description + +

Given an array of strings words, return true if it forms a valid word square.

+ +

A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns).

+ +

 

+

Example 1:

+ +
+Input: words = ["abcd","bnrt","crmy","dtye"]
+Output: true
+Explanation:
+The 1st row and 1st column both read "abcd".
+The 2nd row and 2nd column both read "bnrt".
+The 3rd row and 3rd column both read "crmy".
+The 4th row and 4th column both read "dtye".
+Therefore, it is a valid word square.
+
+ +

Example 2:

+ +
+Input: words = ["abcd","bnrt","crm","dt"]
+Output: true
+Explanation:
+The 1st row and 1st column both read "abcd".
+The 2nd row and 2nd column both read "bnrt".
+The 3rd row and 3rd column both read "crm".
+The 4th row and 4th column both read "dt".
+Therefore, it is a valid word square.
+
+ +

Example 3:

+ +
+Input: words = ["ball","area","read","lady"]
+Output: false
+Explanation:
+The 3rd row reads "read" while the 3rd column reads "lead".
+Therefore, it is NOT a valid word square.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 500
  • +
  • 1 <= words[i].length <= 500
  • +
  • words[i] consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0422.Valid Word Square/images/validsq1-grid.jpg b/assets/0400-0499/0422.Valid Word Square/images/validsq1-grid.jpg new file mode 100644 index 00000000..14202bbb Binary files /dev/null and b/assets/0400-0499/0422.Valid Word Square/images/validsq1-grid.jpg differ diff --git a/assets/0400-0499/0422.Valid Word Square/images/validsq2-grid.jpg b/assets/0400-0499/0422.Valid Word Square/images/validsq2-grid.jpg new file mode 100644 index 00000000..ec06366c Binary files /dev/null and b/assets/0400-0499/0422.Valid Word Square/images/validsq2-grid.jpg differ diff --git a/assets/0400-0499/0422.Valid Word Square/images/validsq3-grid.jpg b/assets/0400-0499/0422.Valid Word Square/images/validsq3-grid.jpg new file mode 100644 index 00000000..05b5428d Binary files /dev/null and b/assets/0400-0499/0422.Valid Word Square/images/validsq3-grid.jpg differ diff --git a/assets/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md b/assets/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md new file mode 100644 index 00000000..878687d2 --- /dev/null +++ b/assets/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md @@ -0,0 +1,49 @@ +# [423. Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english) + + + +## Description + +

Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.

+ +

 

+

Example 1:

+
Input: s = "owoztneoer"
+Output: "012"
+

Example 2:

+
Input: s = "fviefuro"
+Output: "45"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"].
  • +
  • s is guaranteed to be valid.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md b/assets/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md new file mode 100644 index 00000000..1c2efe40 --- /dev/null +++ b/assets/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md @@ -0,0 +1,61 @@ +# [424. Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement) + + + +## Description + +

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

+ +

Return the length of the longest substring containing the same letter you can get after performing the above operations.

+ +

 

+

Example 1:

+ +
+Input: s = "ABAB", k = 2
+Output: 4
+Explanation: Replace the two 'A's with two 'B's or vice versa.
+
+ +

Example 2:

+ +
+Input: s = "AABABBA", k = 1
+Output: 4
+Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
+The substring "BBBB" has the longest repeating letters, which is 4.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of only uppercase English letters.
  • +
  • 0 <= k <= s.length
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0425.Word Squares/README_EN.md b/assets/0400-0499/0425.Word Squares/README_EN.md new file mode 100644 index 00000000..e6b2ba08 --- /dev/null +++ b/assets/0400-0499/0425.Word Squares/README_EN.md @@ -0,0 +1,68 @@ +# [425. Word Squares](https://leetcode.com/problems/word-squares) + + + +## Description + +

Given an array of unique strings words, return all the word squares you can build from words. You can return the answer in any order.

+ +

A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns).

+ +
    +
  • For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.
  • +
+ +

 

+

Example 1:

+ +
+Input: words = ["area","lead","wall","lady","ball"]
+Output: [["ball","area","lead","lady"],["wall","area","lead","lady"]]
+Explanation:
+The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
+
+ +

Example 2:

+ +
+Input: words = ["abat","baba","atan","atal"]
+Output: [["baba","abat","baba","atal"],["baba","abat","baba","atan"]]
+Explanation:
+The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 1000
  • +
  • 1 <= words[i].length <= 5
  • +
  • All words[i] have the same length.
  • +
  • words[i] consists of only lowercase English letters.
  • +
  • All words[i] are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md new file mode 100644 index 00000000..5ff07655 --- /dev/null +++ b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md @@ -0,0 +1,185 @@ +# [426. Convert Binary Search Tree to Sorted Doubly Linked List](https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list) + + + +## Description + +

Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.

+ +

You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.

+ +

We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

+ +

 

+

Example 1:

+ +

+ +
+Input: root = [4,2,5,1,3]
+
+
+Output: [1,2,3,4,5]
+
+Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
+
+
+ +

Example 2:

+ +
+Input: root = [2,1,3]
+Output: [1,2,3]
+
+ +

Example 3:

+ +
+Input: root = []
+Output: []
+Explanation: Input is an empty tree. Output is also an empty Linked List.
+
+ +

Example 4:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 2000].
  • +
  • -1000 <= Node.val <= 1000
  • +
  • All the values of the tree are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val, left=None, right=None): + self.val = val + self.left = left + self.right = right +""" +class Solution: + def treeToDoublyList(self, root: 'Node') -> 'Node': + def dfs(cur): + if cur is None: + return + dfs(cur.left) + if self.pre is None: + self.head = cur + else: + self.pre.right = cur + cur.left = self.pre + self.pre = cur + dfs(cur.right) + if root is None: + return None + self.head = self.pre = None + dfs(root) + self.head.left = self.pre + self.pre.right = self.head + return self.head +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val,Node _left,Node _right) { + val = _val; + left = _left; + right = _right; + } +}; +*/ + +class Solution { + private Node head; + private Node pre; + + public Node treeToDoublyList(Node root) { + if (root == null) return null; + dfs(root); + head.left = pre; + pre.right = head; + return head; + } + + private void dfs(Node cur) { + if (cur == null) return; + dfs(cur.left); + if (pre == null) head = cur; + else pre.right = cur; + cur.left = pre; + pre = cur; + dfs(cur.right); + } +} +``` + +### **JavaScript** + +```js +/** + * // Definition for a Node. + * function Node(val,left,right) { + * this.val = val; + * this.left = left; + * this.right = right; + * }; + */ +/** + * @param {Node} root + * @return {Node} + */ +var treeToDoublyList = function (root) { + function dfs(cur) { + if (!cur) return; + dfs(cur.left); + if (!pre) head = cur; + else pre.right = cur; + cur.left = pre; + pre = cur; + dfs(cur.right); + } + if (!root) return null; + let head, pre; + dfs(root); + head.left = pre; + pre.right = head; + return head; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdlloriginalbst.png b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdlloriginalbst.png new file mode 100644 index 00000000..05b9a44b Binary files /dev/null and b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdlloriginalbst.png differ diff --git a/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdllreturnbst.png b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdllreturnbst.png new file mode 100644 index 00000000..b4d82a1a Binary files /dev/null and b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdllreturnbst.png differ diff --git a/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdllreturndll.png b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdllreturndll.png new file mode 100644 index 00000000..70d713ec Binary files /dev/null and b/assets/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/images/bstdllreturndll.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/README_EN.md b/assets/0400-0499/0427.Construct Quad Tree/README_EN.md new file mode 100644 index 00000000..b069627e --- /dev/null +++ b/assets/0400-0499/0427.Construct Quad Tree/README_EN.md @@ -0,0 +1,158 @@ +# [427. Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree) + + + +## Description + +

Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.

+ + + +

Return the root of the Quad-Tree representing the grid.

+ + + +

Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.

+ + + +

A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:

+ + + +
    +
  • val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. 
  • +
  • isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
  • +
+ + + +
+
+class Node {
+
+    public boolean val;
+
+    public boolean isLeaf;
+
+    public Node topLeft;
+
+    public Node topRight;
+
+    public Node bottomLeft;
+
+    public Node bottomRight;
+
+}
+ + + +

We can construct a Quad-Tree from a two-dimensional area using the following steps:

+ + + +
    +
  1. If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
  2. +
  3. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
  4. +
  5. Recurse for each of the children with the proper sub-grid.
  6. +
+ + + +

If you want to know more about the Quad-Tree, you can refer to the wiki.

+ + + +

Quad-Tree format:

+ + + +

The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.

+ + + +

It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].

+ + + +

If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.

+ + +

 

+

Example 1:

+ +
+Input: grid = [[0,1],[1,0]]
+Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
+Explanation: The explanation of this example is shown below:
+Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
+
+
+ +

Example 2:

+ +

+ +
+Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
+Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
+Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
+The topLeft, bottomLeft and bottomRight each has the same value.
+The topRight have different values so we divide it into 4 sub-grids where each has the same value.
+Explanation is shown in the photo below:
+
+
+ +

Example 3:

+ +
+Input: grid = [[1,1],[1,1]]
+Output: [[1,1]]
+
+ +

Example 4:

+ +
+Input: grid = [[0]]
+Output: [[1,0]]
+
+ +

Example 5:

+ +
+Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
+Output: [[0,1],[1,1],[1,0],[1,0],[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • n == grid.length == grid[i].length
  • +
  • n == 2^x where 0 <= x <= 6
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/962_grid.png b/assets/0400-0499/0427.Construct Quad Tree/images/962_grid.png new file mode 100644 index 00000000..5dbd5d43 Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/962_grid.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/962_grid_divided.png b/assets/0400-0499/0427.Construct Quad Tree/images/962_grid_divided.png new file mode 100644 index 00000000..bde7df95 Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/962_grid_divided.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/962_quad_tree.png b/assets/0400-0499/0427.Construct Quad Tree/images/962_quad_tree.png new file mode 100644 index 00000000..db8b2cef Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/962_quad_tree.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/e1tree.png b/assets/0400-0499/0427.Construct Quad Tree/images/e1tree.png new file mode 100644 index 00000000..c0dafa51 Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/e1tree.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/e2mat.png b/assets/0400-0499/0427.Construct Quad Tree/images/e2mat.png new file mode 100644 index 00000000..a08c6334 Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/e2mat.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/e2tree.png b/assets/0400-0499/0427.Construct Quad Tree/images/e2tree.png new file mode 100644 index 00000000..ba20a1e1 Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/e2tree.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/grid1.png b/assets/0400-0499/0427.Construct Quad Tree/images/grid1.png new file mode 100644 index 00000000..f28911b8 Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/grid1.png differ diff --git a/assets/0400-0499/0427.Construct Quad Tree/images/new_top.png b/assets/0400-0499/0427.Construct Quad Tree/images/new_top.png new file mode 100644 index 00000000..920e497d Binary files /dev/null and b/assets/0400-0499/0427.Construct Quad Tree/images/new_top.png differ diff --git a/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md b/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md new file mode 100644 index 00000000..157287f8 --- /dev/null +++ b/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md @@ -0,0 +1,75 @@ +# [428. Serialize and Deserialize N-ary Tree](https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree) + + + +## Description + +

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

+ + + +

Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure.

+ + + +

For example, you may serialize the following 3-ary tree

+ + + +

+ + + +

as [1 [3[5 6] 2 4]]. Note that this is just an example, you do not necessarily need to follow this format.

+ + + +

Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value.

+ + + +

+ + + +

For example, the above tree may be serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

+ + + +

You do not necessarily need to follow the above suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.

+ + +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The height of the n-ary tree is less than or equal to 1000
  • +
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/images/narytreeexample.png b/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/images/narytreeexample.png new file mode 100644 index 00000000..2542862c Binary files /dev/null and b/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/images/narytreeexample.png differ diff --git a/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/images/sample_4_964.png b/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/0400-0499/0428.Serialize and Deserialize N-ary Tree/images/sample_4_964.png differ diff --git a/assets/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md b/assets/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md new file mode 100644 index 00000000..c49523e1 --- /dev/null +++ b/assets/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md @@ -0,0 +1,127 @@ +# [429. N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal) + + + +## Description + +

Given an n-ary tree, return the level order traversal of its nodes' values.

+ + + +

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

+ + +

 

+

Example 1:

+ +

+ +
+Input: root = [1,null,3,2,4,null,5,6]
+Output: [[1],[3,2,4],[5,6]]
+
+ +

Example 2:

+ +

+ +
+Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
+
+ +

 

+

Constraints:

+ +
    +
  • The height of the n-ary tree is less than or equal to 1000
  • +
  • The total number of nodes is between [0, 104]
  • +
+ + +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + if root is None: + return [] + q = collections.deque([root]) + res = [] + while q: + n = len(q) + t = [] + for _ in range(n): + node = q.popleft() + t.append(node.val) + if node.children: + q.extend(node.children) + res.append(t) + return res +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + public List> levelOrder(Node root) { + if (root == null) { + return Collections.emptyList(); + } + Deque q = new ArrayDeque<>(); + List> res = new ArrayList<>(); + q.offer(root); + while (!q.isEmpty()) { + List t = new ArrayList<>(); + for (int i = 0, n = q.size(); i < n; ++i) { + Node node = q.poll(); + t.add(node.val); + if (node.children != null) { + q.addAll(node.children); + } + } + res.add(t); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0429.N-ary Tree Level Order Traversal/images/narytreeexample.png b/assets/0400-0499/0429.N-ary Tree Level Order Traversal/images/narytreeexample.png new file mode 100644 index 00000000..8f8544cf Binary files /dev/null and b/assets/0400-0499/0429.N-ary Tree Level Order Traversal/images/narytreeexample.png differ diff --git a/assets/0400-0499/0429.N-ary Tree Level Order Traversal/images/sample_4_964.png b/assets/0400-0499/0429.N-ary Tree Level Order Traversal/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/0400-0499/0429.N-ary Tree Level Order Traversal/images/sample_4_964.png differ diff --git a/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md b/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md new file mode 100644 index 00000000..d5e30f23 --- /dev/null +++ b/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md @@ -0,0 +1,175 @@ +# [430. Flatten a Multilevel Doubly Linked List](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list) + + + +## Description + +

You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

+ +

Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
+Output: [1,2,3,7,8,11,12,9,10,4,5,6]
+Explanation:
+
+The multilevel linked list in the input is as follows:
+
+
+
+After flattening the multilevel linked list it becomes:
+
+
+
+ +

Example 2:

+ +
+Input: head = [1,2,null,3]
+Output: [1,3,2]
+Explanation:
+
+The input multilevel linked list is as follows:
+
+  1---2---NULL
+  |
+  3---NULL
+
+ +

Example 3:

+ +
+Input: head = []
+Output: []
+
+ +

 

+ +

How multilevel linked list is represented in test case:

+ +

We use the multilevel linked list from Example 1 above:

+ +
+ 1---2---3---4---5---6--NULL
+         |
+         7---8---9---10--NULL
+             |
+             11--12--NULL
+ +

The serialization of each level is as follows:

+ +
+[1,2,3,4,5,6,null]
+[7,8,9,10,null]
+[11,12,null]
+
+ +

To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:

+ +
+[1,2,3,4,5,6,null]
+[null,null,7,8,9,10,null]
+[null,11,12,null]
+
+ +

Merging the serialization of each level and removing trailing nulls we obtain:

+ +
+[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
+ +

 

+

Constraints:

+ +
    +
  • The number of Nodes will not exceed 1000.
  • +
  • 1 <= Node.val <= 105
  • +
+ +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val, prev, next, child): + self.val = val + self.prev = prev + self.next = next + self.child = child +""" + +class Solution: + def flatten(self, head: 'Node') -> 'Node': + def preorder(pre, cur): + if cur is None: + return pre + cur.prev = pre + pre.next = cur + + t = cur.next + tail = preorder(cur, cur.child) + cur.child = None + return preorder(tail, t) + + if head is None: + return None + dummy = Node(0, None, head, None) + preorder(dummy, head) + dummy.next.prev = None + return dummy.next +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node prev; + public Node next; + public Node child; +}; +*/ + +class Solution { + public Node flatten(Node head) { + if (head == null) { + return null; + } + Node dummy = new Node(); + dummy.next = head; + preorder(dummy, head); + dummy.next.prev = null; + return dummy.next; + } + + private Node preorder(Node pre, Node cur) { + if (cur == null) { + return pre; + } + cur.prev = pre; + pre.next = cur; + + Node t = cur.next; + Node tail = preorder(cur, cur.child); + cur.child = null; + return preorder(tail, t); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/images/multilevellinkedlist.png b/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/images/multilevellinkedlist.png new file mode 100644 index 00000000..b84d1c42 Binary files /dev/null and b/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/images/multilevellinkedlist.png differ diff --git a/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/images/multilevellinkedlistflattened.png b/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/images/multilevellinkedlistflattened.png new file mode 100644 index 00000000..0cb972d5 Binary files /dev/null and b/assets/0400-0499/0430.Flatten a Multilevel Doubly Linked List/images/multilevellinkedlistflattened.png differ diff --git a/assets/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md b/assets/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md new file mode 100644 index 00000000..9813a064 --- /dev/null +++ b/assets/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md @@ -0,0 +1,56 @@ +# [431. Encode N-ary Tree to Binary Tree](https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree) + + + +## Description + +

Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.

+ +

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).

+ +

For example, you may encode the following 3-ary tree to a binary tree in this way:

+ +

+ +
+Input: root = [1,null,3,2,4,null,5,6]
+
+ +

Note that the above is just an example which might or might not work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

+ +
    +
+ +

 

+

Constraints:

+ +
    +
  • The height of the n-ary tree is less than or equal to 1000
  • +
  • The total number of nodes is between [0, 10^4]
  • +
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0431.Encode N-ary Tree to Binary Tree/images/narytreebinarytreeexample.png b/assets/0400-0499/0431.Encode N-ary Tree to Binary Tree/images/narytreebinarytreeexample.png new file mode 100644 index 00000000..f4ff6c40 Binary files /dev/null and b/assets/0400-0499/0431.Encode N-ary Tree to Binary Tree/images/narytreebinarytreeexample.png differ diff --git a/assets/0400-0499/0432.All O`one Data Structure/README_EN.md b/assets/0400-0499/0432.All O`one Data Structure/README_EN.md new file mode 100644 index 00000000..f54ff1b2 --- /dev/null +++ b/assets/0400-0499/0432.All O`one Data Structure/README_EN.md @@ -0,0 +1,76 @@ +# [432. All O one Data Structure](https://leetcode.com/problems/all-oone-data-structure) + + + +## Description + +

Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.

+ +

Implement the AllOne class:

+ +
    +
  • AllOne() Initializes the object of the data structure.
  • +
  • inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1.
  • +
  • dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.
  • +
  • getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "".
  • +
  • getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "".
  • +
+ +

 

+

Example 1:

+ +
+Input
+["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"]
+[[], ["hello"], ["hello"], [], [], ["leet"], [], []]
+Output
+[null, null, null, "hello", "hello", null, "hello", "leet"]
+
+Explanation
+AllOne allOne = new AllOne();
+allOne.inc("hello");
+allOne.inc("hello");
+allOne.getMaxKey(); // return "hello"
+allOne.getMinKey(); // return "hello"
+allOne.inc("leet");
+allOne.getMaxKey(); // return "hello"
+allOne.getMinKey(); // return "leet"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= key.length <= 10
  • +
  • key consists of lowercase English letters.
  • +
  • It is guaranteed that for each call to dec, key is existing in the data structure.
  • +
  • At most 3 * 104 calls will be made to inc, dec, getMaxKey, and getMinKey.
  • +
+ +

 

+

Follow up: Could you apply all the operations in O(1) time complexity?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0433.Minimum Genetic Mutation/README_EN.md b/assets/0400-0499/0433.Minimum Genetic Mutation/README_EN.md new file mode 100644 index 00000000..3e801404 --- /dev/null +++ b/assets/0400-0499/0433.Minimum Genetic Mutation/README_EN.md @@ -0,0 +1,77 @@ +# [433. Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation) + + + +## Description + +

A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.

+ +

Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.

+ +
    +
  • For example, "AACCGGTT" --> "AACCGGTA" is one mutation.
  • +
+ +

There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.

+ +

Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.

+ +

Note that the starting point is assumed to be valid, so it might not be included in the bank.

+ +

 

+

Example 1:

+ +
+Input: start = "AACCGGTT", end = "AACCGGTA", bank = ["AACCGGTA"]
+Output: 1
+
+ +

Example 2:

+ +
+Input: start = "AACCGGTT", end = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]
+Output: 2
+
+ +

Example 3:

+ +
+Input: start = "AAAAACCC", end = "AACCCCCC", bank = ["AAAACCCC","AAACCCCC","AACCCCCC"]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • start.length == 8
  • +
  • end.length == 8
  • +
  • 0 <= bank.length <= 10
  • +
  • bank[i].length == 8
  • +
  • start, end, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0434.Number of Segments in a String/README_EN.md b/assets/0400-0499/0434.Number of Segments in a String/README_EN.md new file mode 100644 index 00000000..1af009cb --- /dev/null +++ b/assets/0400-0499/0434.Number of Segments in a String/README_EN.md @@ -0,0 +1,73 @@ +# [434. Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string) + + + +## Description + +

You are given a string s, return the number of segments in the string

+ +

A segment is defined to be a contiguous sequence of non-space characters.

+ +

 

+

Example 1:

+ +
+Input: s = "Hello, my name is John"
+Output: 5
+Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
+
+ +

Example 2:

+ +
+Input: s = "Hello"
+Output: 1
+
+ +

Example 3:

+ +
+Input: s = "love live! mu'sic forever"
+Output: 4
+
+ +

Example 4:

+ +
+Input: s = ""
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 300
  • +
  • s consists of lower-case and upper-case English letters, digits or one of the following characters "!@#$%^&*()_+-=',.:".
  • +
  • The only space character in s is ' '.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0435.Non-overlapping Intervals/README_EN.md b/assets/0400-0499/0435.Non-overlapping Intervals/README_EN.md new file mode 100644 index 00000000..8acc4d11 --- /dev/null +++ b/assets/0400-0499/0435.Non-overlapping Intervals/README_EN.md @@ -0,0 +1,66 @@ +# [435. Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals) + + + +## Description + +

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

+ +

 

+

Example 1:

+ +
+Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
+Output: 1
+Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
+
+ +

Example 2:

+ +
+Input: intervals = [[1,2],[1,2],[1,2]]
+Output: 2
+Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
+
+ +

Example 3:

+ +
+Input: intervals = [[1,2],[2,3]]
+Output: 0
+Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 2 * 104
  • +
  • intervals[i].length == 2
  • +
  • -2 * 104 <= starti < endi <= 2 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0436.Find Right Interval/README_EN.md b/assets/0400-0499/0436.Find Right Interval/README_EN.md new file mode 100644 index 00000000..5b9d73e9 --- /dev/null +++ b/assets/0400-0499/0436.Find Right Interval/README_EN.md @@ -0,0 +1,74 @@ +# [436. Find Right Interval](https://leetcode.com/problems/find-right-interval) + + + +## Description + +

You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.

+ +

The right interval for an interval i is an interval j such that startj >= endi and startj is minimized.

+ +

Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.

+ +

 

+

Example 1:

+ +
+Input: intervals = [[1,2]]
+Output: [-1]
+Explanation: There is only one interval in the collection, so it outputs -1.
+
+ +

Example 2:

+ +
+Input: intervals = [[3,4],[2,3],[1,2]]
+Output: [-1,0,1]
+Explanation: There is no right interval for [3,4].
+The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.
+The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.
+
+ +

Example 3:

+ +
+Input: intervals = [[1,4],[2,3],[3,4]]
+Output: [-1,2,-1]
+Explanation: There is no right interval for [1,4] and [3,4].
+The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= intervals.length <= 2 * 104
  • +
  • intervals[i].length == 2
  • +
  • -106 <= starti <= endi <= 106
  • +
  • The start point of each interval is unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0437.Path Sum III/README_EN.md b/assets/0400-0499/0437.Path Sum III/README_EN.md new file mode 100644 index 00000000..ae2b6833 --- /dev/null +++ b/assets/0400-0499/0437.Path Sum III/README_EN.md @@ -0,0 +1,59 @@ +# [437. Path Sum III](https://leetcode.com/problems/path-sum-iii) + + + +## Description + +

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

+ +

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

+ +

 

+

Example 1:

+ +
+Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
+Output: 3
+Explanation: The paths that sum to 8 are shown.
+
+ +

Example 2:

+ +
+Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 1000].
  • +
  • -109 <= Node.val <= 109
  • +
  • -1000 <= targetSum <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0437.Path Sum III/images/pathsum3-1-tree.jpg b/assets/0400-0499/0437.Path Sum III/images/pathsum3-1-tree.jpg new file mode 100644 index 00000000..daff736d Binary files /dev/null and b/assets/0400-0499/0437.Path Sum III/images/pathsum3-1-tree.jpg differ diff --git a/assets/0400-0499/0438.Find All Anagrams in a String/README_EN.md b/assets/0400-0499/0438.Find All Anagrams in a String/README_EN.md new file mode 100644 index 00000000..b18e49c4 --- /dev/null +++ b/assets/0400-0499/0438.Find All Anagrams in a String/README_EN.md @@ -0,0 +1,99 @@ +# [438. Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string) + + + +## Description + +

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: s = "cbaebabacd", p = "abc"
+Output: [0,6]
+Explanation:
+The substring with start index = 0 is "cba", which is an anagram of "abc".
+The substring with start index = 6 is "bac", which is an anagram of "abc".
+
+ +

Example 2:

+ +
+Input: s = "abab", p = "ab"
+Output: [0,1,2]
+Explanation:
+The substring with start index = 0 is "ab", which is an anagram of "ab".
+The substring with start index = 1 is "ba", which is an anagram of "ab".
+The substring with start index = 2 is "ab", which is an anagram of "ab".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length, p.length <= 3 * 104
  • +
  • s and p consist of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + counter = collections.Counter(p) + res = [] + left = right = 0 + t = collections.Counter() + while right < len(s): + t[s[right]] += 1 + while t[s[right]] > counter[s[right]]: + t[s[left]] -= 1 + left += 1 + if right - left == len(p) - 1: + res.append(left) + right += 1 + return res +``` + +### **Java** + +```java +class Solution { + public List findAnagrams(String s, String p) { + int[] counter = new int[26]; + for (int i = 0; i < p.length(); ++i) { + ++counter[p.charAt(i) - 'a']; + } + List res = new ArrayList<>(); + int left = 0, right = 0; + int[] t = new int[26]; + while (right < s.length()) { + int i = s.charAt(right) - 'a'; + ++t[i]; + while (t[i] > counter[i]) { + --t[s.charAt(left) - 'a']; + ++left; + } + if (right - left == p.length() - 1) { + res.add(left); + } + ++right; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0439.Ternary Expression Parser/README_EN.md b/assets/0400-0499/0439.Ternary Expression Parser/README_EN.md new file mode 100644 index 00000000..4d5b4399 --- /dev/null +++ b/assets/0400-0499/0439.Ternary Expression Parser/README_EN.md @@ -0,0 +1,74 @@ +# [439. Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser) + + + +## Description + +

Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it.

+ +

You can always assume that the given expression is valid and only contains digits, '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the expression are one-digit numbers (i.e., in the range [0, 9]).

+ +

The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, 'T' or 'F'.

+ +

 

+

Example 1:

+ +
+Input: expression = "T?2:3"
+Output: "2"
+Explanation: If true, then result is 2; otherwise result is 3.
+
+ +

Example 2:

+ +
+Input: expression = "F?1:T?4:5"
+Output: "4"
+Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
+"(F ? 1 : (T ? 4 : 5))" --> "(F ? 1 : 4)" --> "4"
+or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4"
+
+ +

Example 3:

+ +
+Input: expression = "T?T?F:5:3"
+Output: "F"
+Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
+"(T ? (T ? F : 5) : 3)" --> "(T ? F : 3)" --> "F"
+"(T ? (T ? F : 5) : 3)" --> "(T ? F : 5)" --> "F"
+
+ +

 

+

Constraints:

+ +
    +
  • 5 <= expression.length <= 104
  • +
  • expression consists of digits, 'T', 'F', '?', and ':'.
  • +
  • It is guaranteed that expression is a valid ternary expression and that each number is a one-digit number.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md b/assets/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md new file mode 100644 index 00000000..fa507f1b --- /dev/null +++ b/assets/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md @@ -0,0 +1,55 @@ +# [440. K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order) + + + +## Description + +

Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].

+ +

 

+

Example 1:

+ +
+Input: n = 13, k = 2
+Output: 10
+Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
+
+ +

Example 2:

+ +
+Input: n = 1, k = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= n <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0441.Arranging Coins/README_EN.md b/assets/0400-0499/0441.Arranging Coins/README_EN.md new file mode 100644 index 00000000..3d104131 --- /dev/null +++ b/assets/0400-0499/0441.Arranging Coins/README_EN.md @@ -0,0 +1,64 @@ +# [441. Arranging Coins](https://leetcode.com/problems/arranging-coins) + + + +## Description + +

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

+ +

Given the integer n, return the number of complete rows of the staircase you will build.

+ +

 

+

Example 1:

+ +
+Input: n = 5
+Output: 2
+Explanation: Because the 3rd row is incomplete, we return 2.
+
+ +

Example 2:

+ +
+Input: n = 8
+Output: 3
+Explanation: Because the 4th row is incomplete, we return 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def arrangeCoins(self, n: int) -> int: + return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5) +``` + +### **Java** + +```java +class Solution { + public int arrangeCoins(int n) { + return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0441.Arranging Coins/images/arrangecoins1-grid.jpg b/assets/0400-0499/0441.Arranging Coins/images/arrangecoins1-grid.jpg new file mode 100644 index 00000000..dcc1f02f Binary files /dev/null and b/assets/0400-0499/0441.Arranging Coins/images/arrangecoins1-grid.jpg differ diff --git a/assets/0400-0499/0441.Arranging Coins/images/arrangecoins2-grid.jpg b/assets/0400-0499/0441.Arranging Coins/images/arrangecoins2-grid.jpg new file mode 100644 index 00000000..1832a021 Binary files /dev/null and b/assets/0400-0499/0441.Arranging Coins/images/arrangecoins2-grid.jpg differ diff --git a/assets/0400-0499/0442.Find All Duplicates in an Array/README_EN.md b/assets/0400-0499/0442.Find All Duplicates in an Array/README_EN.md new file mode 100644 index 00000000..5f45d612 --- /dev/null +++ b/assets/0400-0499/0442.Find All Duplicates in an Array/README_EN.md @@ -0,0 +1,56 @@ +# [442. Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array) + + + +## Description + +

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

+ +

 

+

Example 1:

+
Input: nums = [4,3,2,7,8,2,3,1]
+Output: [2,3]
+

Example 2:

+
Input: nums = [1,1,2]
+Output: [1]
+

Example 3:

+
Input: nums = [1]
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i] <= n
  • +
  • Each element in nums appears once or twice.
  • +
+ +

 

+

Follow up: Could you do it without extra space and in O(n) runtime?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0443.String Compression/README_EN.md b/assets/0400-0499/0443.String Compression/README_EN.md new file mode 100644 index 00000000..ea7fa987 --- /dev/null +++ b/assets/0400-0499/0443.String Compression/README_EN.md @@ -0,0 +1,87 @@ +# [443. String Compression](https://leetcode.com/problems/string-compression) + + + +## Description + +

Given an array of characters chars, compress it using the following algorithm:

+ +

Begin with an empty string s. For each group of consecutive repeating characters in chars:

+ +
    +
  • If the group's length is 1, append the character to s.
  • +
  • Otherwise, append the character followed by the group's length.
  • +
+ +

The compressed string s should not be returned separately, but instead be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

+ +

After you are done modifying the input array, return the new length of the array.

+  + +

Follow up:
+Could you solve it using only O(1) extra space?

+ +

 

+

Example 1:

+ +
+Input: chars = ["a","a","b","b","c","c","c"]
+Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
+Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
+
+ +

Example 2:

+ +
+Input: chars = ["a"]
+Output: Return 1, and the first character of the input array should be: ["a"]
+Explanation: The only group is "a", which remains uncompressed since it's a single character.
+
+ +

Example 3:

+ +
+Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
+Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
+Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
+ +

Example 4:

+ +
+Input: chars = ["a","a","a","b","b","a","a"]
+Output: Return 6, and the first 6 characters of the input array should be: ["a","3","b","2","a","2"].
+Explanation: The groups are "aaa", "bb", and "aa". This compresses to "a3b2a2". Note that each group is independent even if two groups have the same character.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= chars.length <= 2000
  • +
  • chars[i] is a lower-case English letter, upper-case English letter, digit, or symbol.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0444.Sequence Reconstruction/README_EN.md b/assets/0400-0499/0444.Sequence Reconstruction/README_EN.md new file mode 100644 index 00000000..73afb5f5 --- /dev/null +++ b/assets/0400-0499/0444.Sequence Reconstruction/README_EN.md @@ -0,0 +1,79 @@ +# [444. Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction) + + + +## Description + +

Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.

+ +

 

+

Example 1:

+ +
+Input: org = [1,2,3], seqs = [[1,2],[1,3]]
+Output: false
+Explanation: [1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.
+
+ +

Example 2:

+ +
+Input: org = [1,2,3], seqs = [[1,2]]
+Output: false
+Explanation: The reconstructed sequence can only be [1,2].
+
+ +

Example 3:

+ +
+Input: org = [1,2,3], seqs = [[1,2],[1,3],[2,3]]
+Output: true
+Explanation: The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3].
+
+ +

Example 4:

+ +
+Input: org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]]
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 10^4
  • +
  • org is a permutation of {1,2,...,n}.
  • +
  • 1 <= segs[i].length <= 10^5
  • +
  • seqs[i][j] fits in a 32-bit signed integer.
  • +
+ +

 

+ +

UPDATE (2017/1/8):
+The seqs parameter had been changed to a list of list of strings (instead of a 2d array of strings). Please reload the code definition to get the latest changes.

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0445.Add Two Numbers II/README_EN.md b/assets/0400-0499/0445.Add Two Numbers II/README_EN.md new file mode 100644 index 00000000..34a544d1 --- /dev/null +++ b/assets/0400-0499/0445.Add Two Numbers II/README_EN.md @@ -0,0 +1,119 @@ +# [445. Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii) + + + +## Description + +

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

+ +

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

+ +

 

+

Example 1:

+ +
+Input: l1 = [7,2,4,3], l2 = [5,6,4]
+Output: [7,8,0,7]
+
+ +

Example 2:

+ +
+Input: l1 = [2,4,3], l2 = [5,6,4]
+Output: [8,0,7]
+
+ +

Example 3:

+ +
+Input: l1 = [0], l2 = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in each linked list is in the range [1, 100].
  • +
  • 0 <= Node.val <= 9
  • +
  • It is guaranteed that the list represents a number that does not have leading zeros.
  • +
+ +

 

+

Follow up: Could you solve it without reversing the input lists?

+ + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + s1, s2 = [], [] + while l1: + s1.append(l1.val) + l1 = l1.next + while l2: + s2.append(l2.val) + l2 = l2.next + carry, dummy = 0, ListNode(-1) + while s1 or s2 or carry: + carry += (0 if not s1 else s1.pop()) + (0 if not s2 else s2.pop()) + node = ListNode(carry % 10) + node.next = dummy.next + dummy.next = node + carry //= 10 + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + Deque s1 = new ArrayDeque<>(); + Deque s2 = new ArrayDeque<>(); + for (; l1 != null; l1 = l1.next) { + s1.push(l1.val); + } + for (; l2 != null; l2 = l2.next) { + s2.push(l2.val); + } + int carry = 0; + ListNode dummy = new ListNode(-1); + while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) { + carry += (s1.isEmpty() ? 0 : s1.pop()) + (s2.isEmpty() ? 0 : s2.pop()); + ListNode node = new ListNode(carry % 10); + node.next = dummy.next; + dummy.next = node; + carry /= 10; + } + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0445.Add Two Numbers II/images/sumii-linked-list.jpg b/assets/0400-0499/0445.Add Two Numbers II/images/sumii-linked-list.jpg new file mode 100644 index 00000000..63f9f896 Binary files /dev/null and b/assets/0400-0499/0445.Add Two Numbers II/images/sumii-linked-list.jpg differ diff --git a/assets/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md b/assets/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md new file mode 100644 index 00000000..fd002d54 --- /dev/null +++ b/assets/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md @@ -0,0 +1,79 @@ +# [446. Arithmetic Slices II - Subsequence](https://leetcode.com/problems/arithmetic-slices-ii-subsequence) + + + +## Description + +

Given an integer array nums, return the number of all the arithmetic subsequences of nums.

+ +

A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

+ +
    +
  • For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
  • +
  • For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
  • +
+ +

A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

+ +
    +
  • For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
  • +
+ +

The answer is guaranteed to fit in 32-bit integer.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,4,6,8,10]
+Output: 7
+Explanation: All arithmetic subsequence slices are:
+[2,4,6]
+[4,6,8]
+[6,8,10]
+[2,4,6,8]
+[4,6,8,10]
+[2,4,6,8,10]
+[2,6,10]
+
+ +

Example 2:

+ +
+Input: nums = [7,7,7,7,7]
+Output: 16
+Explanation: Any subsequence of this array is arithmetic.
+
+ +

 

+

Constraints:

+ +
    +
  • 1  <= nums.length <= 1000
  • +
  • -231 <= nums[i] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0447.Number of Boomerangs/README_EN.md b/assets/0400-0499/0447.Number of Boomerangs/README_EN.md new file mode 100644 index 00000000..5d096dad --- /dev/null +++ b/assets/0400-0499/0447.Number of Boomerangs/README_EN.md @@ -0,0 +1,108 @@ +# [447. Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs) + + + +## Description + +

You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

+ +

Return the number of boomerangs.

+ +

 

+

Example 1:

+ +
+Input: points = [[0,0],[1,0],[2,0]]
+Output: 2
+Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].
+
+ +

Example 2:

+ +
+Input: points = [[1,1],[2,2],[3,3]]
+Output: 2
+
+ +

Example 3:

+ +
+Input: points = [[1,1]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • n == points.length
  • +
  • 1 <= n <= 500
  • +
  • points[i].length == 2
  • +
  • -104 <= xi, yi <= 104
  • +
  • All the points are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + n = len(points) + if n < 3: + return 0 + number = 0 + for i in range(n): + distance_counter = collections.Counter() + for j in range(n): + if i == j: + continue + x1, y1 = points[i][0], points[i][1] + x2, y2 = points[j][0], points[j][1] + distance = (x1 - x2) ** 2 + (y1 - y2) ** 2 + distance_counter[distance] += 1 + number += sum([val * (val - 1) for val in distance_counter.values()]) + return number +``` + +### **Java** + +```java +class Solution { + public int numberOfBoomerangs(int[][] points) { + int n = points.length; + if (n < 3) { + return 0; + } + int number = 0; + for (int i = 0; i < n; ++i) { + Map distanceCounter = new HashMap<>(); + for (int j = 0; j < n; ++j) { + if (i == j) { + continue; + } + int x1 = points[i][0], y1 = points[i][1]; + int x2 = points[j][0], y2 = points[j][1]; + int distance = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + distanceCounter.put(distance, distanceCounter.getOrDefault(distance, 0) + 1); + } + for (int val : distanceCounter.values()) { + number += val * (val - 1); + } + } + return number; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md b/assets/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md new file mode 100644 index 00000000..831dcbf1 --- /dev/null +++ b/assets/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md @@ -0,0 +1,79 @@ +# [448. Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array) + + + +## Description + +

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

+ +

 

+

Example 1:

+
Input: nums = [4,3,2,7,8,2,3,1]
+Output: [5,6]
+

Example 2:

+
Input: nums = [1,1]
+Output: [2]
+
+

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 105
  • +
  • 1 <= nums[i] <= n
  • +
+ +

 

+

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for num in nums: + index = abs(num) - 1 + if nums[index] > 0: + nums[index] *= -1 + res = [] + for i, v in enumerate(nums): + if v > 0: + res.append(i + 1) + return res +``` + +### **Java** + +```java +class Solution { + public List findDisappearedNumbers(int[] nums) { + int n = nums.length; + for (int i = 0; i < n; ++i) { + int index = Math.abs(nums[i]) - 1; + if (nums[index] > 0) { + nums[index] *= -1; + } + } + List res = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (nums[i] > 0) { + res.add(i + 1); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0449.Serialize and Deserialize BST/README_EN.md b/assets/0400-0499/0449.Serialize and Deserialize BST/README_EN.md new file mode 100644 index 00000000..5dc1da00 --- /dev/null +++ b/assets/0400-0499/0449.Serialize and Deserialize BST/README_EN.md @@ -0,0 +1,53 @@ +# [449. Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst) + + + +## Description + +

Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

+ +

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.

+ +

The encoded string should be as compact as possible.

+ +

 

+

Example 1:

+
Input: root = [2,1,3]
+Output: [2,1,3]
+

Example 2:

+
Input: root = []
+Output: []
+
+

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The input tree is guaranteed to be a binary search tree.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0450.Delete Node in a BST/README_EN.md b/assets/0400-0499/0450.Delete Node in a BST/README_EN.md new file mode 100644 index 00000000..fa8c6759 --- /dev/null +++ b/assets/0400-0499/0450.Delete Node in a BST/README_EN.md @@ -0,0 +1,79 @@ +# [450. Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst) + + + +## Description + +

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

+ +

Basically, the deletion can be divided into two stages:

+ +
    +
  1. Search for a node to remove.
  2. +
  3. If the node is found, delete the node.
  4. +
+ +

Follow up: Can you solve it with time complexity O(height of tree)?

+ +

 

+

Example 1:

+ +
+Input: root = [5,3,6,2,4,null,7], key = 3
+Output: [5,4,6,2,null,null,7]
+Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
+One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
+Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
+
+
+ +

Example 2:

+ +
+Input: root = [5,3,6,2,4,null,7], key = 0
+Output: [5,3,6,2,4,null,7]
+Explanation: The tree does not contain a node with value = 0.
+
+ +

Example 3:

+ +
+Input: root = [], key = 0
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • Each node has a unique value.
  • +
  • root is a valid binary search tree.
  • +
  • -105 <= key <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0450.Delete Node in a BST/images/del_node_1.jpg b/assets/0400-0499/0450.Delete Node in a BST/images/del_node_1.jpg new file mode 100644 index 00000000..083fb215 Binary files /dev/null and b/assets/0400-0499/0450.Delete Node in a BST/images/del_node_1.jpg differ diff --git a/assets/0400-0499/0450.Delete Node in a BST/images/del_node_supp.jpg b/assets/0400-0499/0450.Delete Node in a BST/images/del_node_supp.jpg new file mode 100644 index 00000000..5d898f3a Binary files /dev/null and b/assets/0400-0499/0450.Delete Node in a BST/images/del_node_supp.jpg differ diff --git a/assets/0400-0499/0451.Sort Characters By Frequency/README_EN.md b/assets/0400-0499/0451.Sort Characters By Frequency/README_EN.md new file mode 100644 index 00000000..93c83dc4 --- /dev/null +++ b/assets/0400-0499/0451.Sort Characters By Frequency/README_EN.md @@ -0,0 +1,133 @@ +# [451. Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency) + + + +## Description + +

Given a string s, sort it in decreasing order based on the frequency of characters, and return the sorted string.

+ +

 

+

Example 1:

+ +
+Input: s = "tree"
+Output: "eert"
+Explanation: 'e' appears twice while 'r' and 't' both appear once.
+So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
+
+ +

Example 2:

+ +
+Input: s = "cccaaa"
+Output: "aaaccc"
+Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
+Note that "cacaca" is incorrect, as the same characters must be together.
+
+ +

Example 3:

+ +
+Input: s = "Aabb"
+Output: "bbAa"
+Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
+Note that 'A' and 'a' are treated as two different characters.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 105
  • +
  • s consists of English letters and digits.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def frequencySort(self, s: str) -> str: + counter = collections.Counter(s) + buckets = collections.defaultdict(list) + for c, freq in counter.items(): + buckets[freq].append(c) + res = [] + for i in range(len(s), -1, -1): + if buckets[i]: + for c in buckets[i]: + res.append(c * i) + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String frequencySort(String s) { + Map counter = new HashMap<>(); + for (char c : s.toCharArray()) { + counter.put(c, counter.getOrDefault(c, 0) + 1); + } + List[] buckets = new List[s.length() + 1]; + for (Map.Entry entry : counter.entrySet()) { + char c = entry.getKey(); + int freq = entry.getValue(); + if (buckets[freq] == null) { + buckets[freq] = new ArrayList<>(); + } + buckets[freq].add(c); + } + StringBuilder sb = new StringBuilder(); + for (int i = s.length(); i >= 0; --i) { + if (buckets[i] != null) { + for (char c : buckets[i]) { + for (int j = 0; j < i; ++j) { + sb.append(c); + } + } + } + } + return sb.toString(); + } +} +``` + +### **Go** + +Simulation with structure sorting. + +```go +type pair struct { + b byte + cnt int +} + +func frequencySort(s string) string { + freq := make(map[byte]int) + for _, r := range s { + freq[byte(r)]++ + } + a := make([]pair, 0) + for k, v := range freq { + a = append(a, pair{b: k, cnt: v}) + } + sort.Slice(a, func(i, j int) bool { return a[i].cnt > a[j].cnt }) + var sb strings.Builder + for _, p := range a { + sb.Write(bytes.Repeat([]byte{p.b}, p.cnt)) + } + return sb.String() +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md b/assets/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md new file mode 100644 index 00000000..f8049a01 --- /dev/null +++ b/assets/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md @@ -0,0 +1,68 @@ +# [452. Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons) + + + +## Description + +

There are some spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter, and hence the x-coordinates of start and end of the diameter suffice. The start is always smaller than the end.

+ +

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps traveling up infinitely.

+ +

Given an array points where points[i] = [xstart, xend], return the minimum number of arrows that must be shot to burst all balloons.

+ +

 

+

Example 1:

+ +
+Input: points = [[10,16],[2,8],[1,6],[7,12]]
+Output: 2
+Explanation: One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
+
+ +

Example 2:

+ +
+Input: points = [[1,2],[3,4],[5,6],[7,8]]
+Output: 4
+
+ +

Example 3:

+ +
+Input: points = [[1,2],[2,3],[3,4],[4,5]]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= points.length <= 104
  • +
  • points[i].length == 2
  • +
  • -231 <= xstart < xend <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md b/assets/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md new file mode 100644 index 00000000..c8d0f729 --- /dev/null +++ b/assets/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md @@ -0,0 +1,60 @@ +# [453. Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements) + + + +## Description + +

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

+ +

In one move, you can increment n - 1 elements of the array by 1.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3]
+Output: 3
+Explanation: Only three moves are needed (remember each move increments two elements):
+[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
+
+ +

Example 2:

+ +
+Input: nums = [1,1,1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0454.4Sum II/README_EN.md b/assets/0400-0499/0454.4Sum II/README_EN.md new file mode 100644 index 00000000..437a5209 --- /dev/null +++ b/assets/0400-0499/0454.4Sum II/README_EN.md @@ -0,0 +1,68 @@ +# [454. 4Sum II](https://leetcode.com/problems/4sum-ii) + + + +## Description + +

Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:

+ +
    +
  • 0 <= i, j, k, l < n
  • +
  • nums1[i] + nums2[j] + nums3[k] + nums[l] == 0
  • +
+ +

 

+

Example 1:

+ +
+Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
+Output: 2
+Explanation:
+The two tuples are:
+1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
+2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
+
+ +

Example 2:

+ +
+Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums1.length
  • +
  • n == nums2.length
  • +
  • n == nums3.length
  • +
  • n == nums4.length
  • +
  • 1 <= n <= 200
  • +
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0455.Assign Cookies/README_EN.md b/assets/0400-0499/0455.Assign Cookies/README_EN.md new file mode 100644 index 00000000..9b7bfa2e --- /dev/null +++ b/assets/0400-0499/0455.Assign Cookies/README_EN.md @@ -0,0 +1,89 @@ +# [455. Assign Cookies](https://leetcode.com/problems/assign-cookies) + + + +## Description + +

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

+ +

Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

+ +

 

+

Example 1:

+ +
+Input: g = [1,2,3], s = [1,1]
+Output: 1
+Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
+And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
+You need to output 1.
+
+ +

Example 2:

+ +
+Input: g = [1,2], s = [1,2,3]
+Output: 2
+Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 
+You have 3 cookies and their sizes are big enough to gratify all of the children, 
+You need to output 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= g.length <= 3 * 104
  • +
  • 0 <= s.length <= 3 * 104
  • +
  • 1 <= g[i], s[j] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **JavaScript** + +```js +/** + * @param {number[]} g + * @param {number[]} s + * @return {number} + */ +var findContentChildren = function (g, s) { + let len1 = g.length, len2 = s.length; + if (len2 === 0) return 0; + g.sort((a, b) => a - b); + s.sort((a, b) => a - b); + let i = 0, j = 0; + while (i < len1 && j < len2) { + while (s[j] < g[i]) j++; + if (s[j] >= g[i]) { + i++; + j++; + } else break; + } + return i; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0456.132 Pattern/README_EN.md b/assets/0400-0499/0456.132 Pattern/README_EN.md new file mode 100644 index 00000000..5548639f --- /dev/null +++ b/assets/0400-0499/0456.132 Pattern/README_EN.md @@ -0,0 +1,95 @@ +# [456. 132 Pattern](https://leetcode.com/problems/132-pattern) + + + +## Description + +

Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

+ +

Return true if there is a 132 pattern in nums, otherwise, return false.

+ +

Follow up: The O(n^2) is trivial, could you come up with the O(n logn) or the O(n) solution?

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,4]
+Output: false
+Explanation: There is no 132 pattern in the sequence.
+
+ +

Example 2:

+ +
+Input: nums = [3,1,4,2]
+Output: true
+Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
+
+ +

Example 3:

+ +
+Input: nums = [-1,3,2,0]
+Output: true
+Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def find132pattern(self, nums: List[int]) -> bool: + ak = float('-inf') + stack = [] + for num in nums[::-1]: + if num < ak: + return True + while stack and num > stack[-1]: + ak = stack.pop() + stack.append(num) + return False +``` + +### **Java** + +```java +class Solution { + public boolean find132pattern(int[] nums) { + int ak = Integer.MIN_VALUE; + Deque stack = new ArrayDeque<>(); + for (int i = nums.length - 1; i >= 0; --i) { + if (nums[i] < ak) { + return true; + } + while (!stack.isEmpty() && nums[i] > stack.peek()) { + ak = stack.pop(); + } + stack.push(nums[i]); + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0457.Circular Array Loop/README_EN.md b/assets/0400-0499/0457.Circular Array Loop/README_EN.md new file mode 100644 index 00000000..476e6a01 --- /dev/null +++ b/assets/0400-0499/0457.Circular Array Loop/README_EN.md @@ -0,0 +1,92 @@ +# [457. Circular Array Loop](https://leetcode.com/problems/circular-array-loop) + + + +## Description + +

You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:

+ +
    +
  • If nums[i] is positive, move nums[i] steps forward, and
  • +
  • If nums[i] is negative, move nums[i] steps backward.
  • +
+ +

Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.

+ +

A cycle in the array consists of a sequence of indices seq of length k where:

+ +
    +
  • Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
  • +
  • Every nums[seq[j]] is either all positive or all negative.
  • +
  • k > 1
  • +
+ +

Return true if there is a cycle in nums, or false otherwise.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,-1,1,2,2]
+Output: true
+Explanation:
+There is a cycle from index 0 -> 2 -> 3 -> 0 -> ...
+The cycle's length is 3.
+
+ +

Example 2:

+ +
+Input: nums = [-1,2]
+Output: false
+Explanation:
+The sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.
+By definition the sequence's length must be strictly greater than 1 to be a cycle.
+
+ +

Example 3:

+ +
+Input: nums = [-2,1,-1,-2,-2]
+Output: false
+Explanation:
+The sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.
+Every nums[seq[j]] must be either all positive or all negative.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5000
  • +
  • -1000 <= nums[i] <= 1000
  • +
  • nums[i] != 0
  • +
+ +

 

+

Follow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0458.Poor Pigs/README_EN.md b/assets/0400-0499/0458.Poor Pigs/README_EN.md new file mode 100644 index 00000000..9dc8ef03 --- /dev/null +++ b/assets/0400-0499/0458.Poor Pigs/README_EN.md @@ -0,0 +1,63 @@ +# [458. Poor Pigs](https://leetcode.com/problems/poor-pigs) + + + +## Description + +

There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

+ +

You can feed the pigs according to these steps:

+ +
    +
  1. Choose some live pigs to feed.
  2. +
  3. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  4. +
  5. Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  6. +
  7. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  8. +
  9. Repeat this process until you run out of time.
  10. +
+ +

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

+ +

 

+

Example 1:

+
Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60
+Output: 5
+

Example 2:

+
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
+Output: 2
+

Example 3:

+
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
+Output: 2
+
+

 

+

Constraints:

+ +
    +
  • 1 <= buckets <= 1000
  • +
  • 1 <= minutesToDie <= minutesToTest <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0459.Repeated Substring Pattern/README_EN.md b/assets/0400-0499/0459.Repeated Substring Pattern/README_EN.md new file mode 100644 index 00000000..cf7cc27f --- /dev/null +++ b/assets/0400-0499/0459.Repeated Substring Pattern/README_EN.md @@ -0,0 +1,64 @@ +# [459. Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern) + + + +## Description + +

Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

+ +

 

+

Example 1:

+ +
+Input: s = "abab"
+Output: true
+Explanation: It is the substring "ab" twice.
+
+ +

Example 2:

+ +
+Input: s = "aba"
+Output: false
+
+ +

Example 3:

+ +
+Input: s = "abcabcabcabc"
+Output: true
+Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0460.LFU Cache/README_EN.md b/assets/0400-0499/0460.LFU Cache/README_EN.md new file mode 100644 index 00000000..a4dbeb82 --- /dev/null +++ b/assets/0400-0499/0460.LFU Cache/README_EN.md @@ -0,0 +1,86 @@ +# [460. LFU Cache](https://leetcode.com/problems/lfu-cache) + + + +## Description + +

Design and implement a data structure for a Least Frequently Used (LFU) cache.

+ +

Implement the LFUCache class:

+ +
    +
  • LFUCache(int capacity) Initializes the object with the capacity of the data structure.
  • +
  • int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.
  • +
  • void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.
  • +
+ +

To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.

+ +

When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.

+ +

 

+

Example 1:

+ +
+Input
+["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
+[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
+Output
+[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
+
+Explanation
+// cnt(x) = the use counter for key x
+// cache=[] will show the last used order for tiebreakers (leftmost element is  most recent)
+LFUCache lfu = new LFUCache(2);
+lfu.put(1, 1);   // cache=[1,_], cnt(1)=1
+lfu.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1
+lfu.get(1);      // return 1
+                 // cache=[1,2], cnt(2)=1, cnt(1)=2
+lfu.put(3, 3);   // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
+                 // cache=[3,1], cnt(3)=1, cnt(1)=2
+lfu.get(2);      // return -1 (not found)
+lfu.get(3);      // return 3
+                 // cache=[3,1], cnt(3)=2, cnt(1)=2
+lfu.put(4, 4);   // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
+                 // cache=[4,3], cnt(4)=1, cnt(3)=2
+lfu.get(1);      // return -1 (not found)
+lfu.get(3);      // return 3
+                 // cache=[3,4], cnt(4)=1, cnt(3)=3
+lfu.get(4);      // return 4
+                 // cache=[3,4], cnt(4)=2, cnt(3)=3
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= capacity, key, value <= 104
  • +
  • At most 105 calls will be made to get and put.
  • +
+ +

 

+Follow up: Could you do both operations in O(1) time complexity?  + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0461.Hamming Distance/README_EN.md b/assets/0400-0499/0461.Hamming Distance/README_EN.md new file mode 100644 index 00000000..210e12eb --- /dev/null +++ b/assets/0400-0499/0461.Hamming Distance/README_EN.md @@ -0,0 +1,113 @@ +# [461. Hamming Distance](https://leetcode.com/problems/hamming-distance) + + + +## Description + +

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

+ +

Given two integers x and y, return the Hamming distance between them.

+ +

 

+

Example 1:

+ +
+Input: x = 1, y = 4
+Output: 2
+Explanation:
+1   (0 0 0 1)
+4   (0 1 0 0)
+       ↑   ↑
+The above arrows point to positions where the corresponding bits are different.
+
+ +

Example 2:

+ +
+Input: x = 3, y = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= x, y <= 231 - 1
  • +
+ + +## Solutions + +Use xor operation to find different bits. + +- 0 ^ 0 = 0 +- 1 ^ 1 = 0 +- 0 ^ 1 = 1 +- 1 ^ 0 = 1 + + + +### **Python3** + +```python +class Solution: + def hammingDistance(self, x: int, y: int) -> int: + num, count = x ^ y, 0 + while num != 0: + num &= num - 1 + count += 1 + return count +``` + +### **Java** + +```java +class Solution { + public int hammingDistance(int x, int y) { + int num = x ^ y; + int count = 0; + while (num != 0) { + num &= num - 1; + count++; + } + return count; + } +} +``` + +Or use the library function `Integer.bitCount()` + +```java +class Solution { + public int hammingDistance(int x, int y) { + return Integer.bitCount(x ^ y); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @param {number} y + * @return {number} + */ +var hammingDistance = function(x, y) { + let distance = x ^ y; + let count = 0; + while (distance != 0) { + count++; + distance &= (distance - 1); + } + return count; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md b/assets/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md new file mode 100644 index 00000000..206bb560 --- /dev/null +++ b/assets/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md @@ -0,0 +1,61 @@ +# [462. Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii) + + + +## Description + +

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

+ +

In one move, you can increment or decrement an element of the array by 1.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3]
+Output: 2
+Explanation:
+Only two moves are needed (remember each move increments or decrements one element):
+[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
+
+ +

Example 2:

+ +
+Input: nums = [1,10,2,9]
+Output: 16
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= nums.length <= 105
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0463.Island Perimeter/README_EN.md b/assets/0400-0499/0463.Island Perimeter/README_EN.md new file mode 100644 index 00000000..fbf85546 --- /dev/null +++ b/assets/0400-0499/0463.Island Perimeter/README_EN.md @@ -0,0 +1,100 @@ +# [463. Island Perimeter](https://leetcode.com/problems/island-perimeter) + + + +## Description + +

You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.

+ +

Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

+ +

The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

+ +

 

+

Example 1:

+ +
+Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
+Output: 16
+Explanation: The perimeter is the 16 yellow stripes in the image above.
+
+ +

Example 2:

+ +
+Input: grid = [[1]]
+Output: 4
+
+ +

Example 3:

+ +
+Input: grid = [[1,0]]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • row == grid.length
  • +
  • col == grid[i].length
  • +
  • 1 <= row, col <= 100
  • +
  • grid[i][j] is 0 or 1.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **TypeScript** + +```ts +function islandPerimeter(grid: number[][]): number { + let m = grid.length, n = grid[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + let top = 0, left = 0; + if (i > 0) { + top = grid[i - 1][j]; + } + if (j > 0) { + left = grid[i][j - 1]; + } + let cur = grid[i][j]; + if (cur != top) ++ans; + if (cur != left) ++ans; + } + } + // 最后一行, 最后一列 + for (let i = 0; i < m; ++i) { + if (grid[i][n - 1] == 1) ++ans; + } + for (let j = 0; j < n; ++j) { + if (grid[m - 1][j] == 1) ++ans; + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0463.Island Perimeter/images/island.png b/assets/0400-0499/0463.Island Perimeter/images/island.png new file mode 100644 index 00000000..370efdf6 Binary files /dev/null and b/assets/0400-0499/0463.Island Perimeter/images/island.png differ diff --git a/assets/0400-0499/0464.Can I Win/README_EN.md b/assets/0400-0499/0464.Can I Win/README_EN.md new file mode 100644 index 00000000..fc1effa6 --- /dev/null +++ b/assets/0400-0499/0464.Can I Win/README_EN.md @@ -0,0 +1,74 @@ +# [464. Can I Win](https://leetcode.com/problems/can-i-win) + + + +## Description + +

In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.

+ +

What if we change the game so that players cannot re-use integers?

+ +

For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100.

+ +

Given two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally.

+ +

 

+

Example 1:

+ +
+Input: maxChoosableInteger = 10, desiredTotal = 11
+Output: false
+Explanation:
+No matter which integer the first player choose, the first player will lose.
+The first player can choose an integer from 1 up to 10.
+If the first player choose 1, the second player can only choose integers from 2 up to 10.
+The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
+Same with other integers chosen by the first player, the second player will always win.
+
+ +

Example 2:

+ +
+Input: maxChoosableInteger = 10, desiredTotal = 0
+Output: true
+
+ +

Example 3:

+ +
+Input: maxChoosableInteger = 10, desiredTotal = 1
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= maxChoosableInteger <= 20
  • +
  • 0 <= desiredTotal <= 300
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0465.Optimal Account Balancing/README_EN.md b/assets/0400-0499/0465.Optimal Account Balancing/README_EN.md new file mode 100644 index 00000000..4510b60e --- /dev/null +++ b/assets/0400-0499/0465.Optimal Account Balancing/README_EN.md @@ -0,0 +1,70 @@ +# [465. Optimal Account Balancing](https://leetcode.com/problems/optimal-account-balancing) + + + +## Description + +

You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi.

+ +

Return the minimum number of transactions required to settle the debt.

+ +

 

+

Example 1:

+ +
+Input: transactions = [[0,1,10],[2,0,5]]
+Output: 2
+Explanation:
+Person #0 gave person #1 $10.
+Person #2 gave person #0 $5.
+Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
+
+ +

Example 2:

+ +
+Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
+Output: 1
+Explanation:
+Person #0 gave person #1 $10.
+Person #1 gave person #0 $1.
+Person #1 gave person #2 $5.
+Person #2 gave person #0 $5.
+Therefore, person #1 only need to give person #0 $4, and all debt is settled.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= transactions.length <= 8
  • +
  • transactions[i].length == 3
  • +
  • 0 <= fromi, toi <= 20
  • +
  • fromi != toi
  • +
  • 1 <= amounti <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0466.Count The Repetitions/README_EN.md b/assets/0400-0499/0466.Count The Repetitions/README_EN.md new file mode 100644 index 00000000..83641275 --- /dev/null +++ b/assets/0400-0499/0466.Count The Repetitions/README_EN.md @@ -0,0 +1,63 @@ +# [466. Count The Repetitions](https://leetcode.com/problems/count-the-repetitions) + + + +## Description + +

We define str = [s, n] as the string str which consists of the string s concatenated n times.

+ +
    +
  • For example, str == ["abc", 3] =="abcabcabc".
  • +
+ +

We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.

+ +
    +
  • For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by removing the bolded underlined characters.
  • +
+ +

You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2].

+ +

Return the maximum integer m such that str = [str2, m] can be obtained from str1.

+ +

 

+

Example 1:

+
Input: s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
+Output: 2
+

Example 2:

+
Input: s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
+Output: 1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s1.length, s2.length <= 100
  • +
  • s1 and s2 consist of lowercase English letters.
  • +
  • 1 <= n1, n2 <= 106
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md b/assets/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md new file mode 100644 index 00000000..2d3f195c --- /dev/null +++ b/assets/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md @@ -0,0 +1,71 @@ +# [467. Unique Substrings in Wraparound String](https://leetcode.com/problems/unique-substrings-in-wraparound-string) + + + +## Description + +

We define the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this:

+ +
    +
  • "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
  • +
+ +

Given a string p, return the number of unique non-empty substrings of p are present in s.

+ +

 

+

Example 1:

+ +
+Input: p = "a"
+Output: 1
+Explanation: Only the substring "a" of p is in s.
+
+ +

Example 2:

+ +
+Input: p = "cac"
+Output: 2
+Explanation: There are two substrings ("a", "c") of p in s.
+
+ +

Example 3:

+ +
+Input: p = "zab"
+Output: 6
+Explanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of p in s.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= p.length <= 105
  • +
  • p consists of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0468.Validate IP Address/README_EN.md b/assets/0400-0499/0468.Validate IP Address/README_EN.md new file mode 100644 index 00000000..d413f004 --- /dev/null +++ b/assets/0400-0499/0468.Validate IP Address/README_EN.md @@ -0,0 +1,90 @@ +# [468. Validate IP Address](https://leetcode.com/problems/validate-ip-address) + + + +## Description + +

Given a string IP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type.

+ +

A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses but "192.168.01.1", while "192.168.1.00" and "192.168@1.1" are invalid IPv4 addresses.

+ +

A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where:

+ +
    +
  • 1 <= xi.length <= 4
  • +
  • xi is a hexadecimal string which may contain digits, lower-case English letter ('a' to 'f') and upper-case English letters ('A' to 'F').
  • +
  • Leading zeros are allowed in xi.
  • +
+ +

For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and "2001:db8:85a3:0:0:8A2E:0370:7334" are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334" and "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses.

+ +

 

+

Example 1:

+ +
+Input: IP = "172.16.254.1"
+Output: "IPv4"
+Explanation: This is a valid IPv4 address, return "IPv4".
+
+ +

Example 2:

+ +
+Input: IP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
+Output: "IPv6"
+Explanation: This is a valid IPv6 address, return "IPv6".
+
+ +

Example 3:

+ +
+Input: IP = "256.256.256.256"
+Output: "Neither"
+Explanation: This is neither a IPv4 address nor a IPv6 address.
+
+ +

Example 4:

+ +
+Input: IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:"
+Output: "Neither"
+
+ +

Example 5:

+ +
+Input: IP = "1e1.4.5.6"
+Output: "Neither"
+
+ +

 

+

Constraints:

+ +
    +
  • IP consists only of English letters, digits and the characters '.' and ':'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0469.Convex Polygon/README_EN.md b/assets/0400-0499/0469.Convex Polygon/README_EN.md new file mode 100644 index 00000000..148372e2 --- /dev/null +++ b/assets/0400-0499/0469.Convex Polygon/README_EN.md @@ -0,0 +1,61 @@ +# [469. Convex Polygon](https://leetcode.com/problems/convex-polygon) + + + +## Description + +

You are given an array of points on the X-Y plane points where points[i] = [xi, yi]. The points form a polygon when joined sequentially.

+ +

Return true if this polygon is convex and false otherwise.

+ +

You may assume the polygon formed by given points is always a simple polygon. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other.

+ +

 

+

Example 1:

+ +
+Input: points = [[0,0],[0,5],[5,5],[5,0]]
+Output: true
+
+ +

Example 2:

+ +
+Input: points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 3 <= points.length <= 104
  • +
  • points[i].length == 2
  • +
  • -104 <= xi, yi <= 104
  • +
  • All the given points are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0469.Convex Polygon/images/polygon_convex.png b/assets/0400-0499/0469.Convex Polygon/images/polygon_convex.png new file mode 100644 index 00000000..12b79781 Binary files /dev/null and b/assets/0400-0499/0469.Convex Polygon/images/polygon_convex.png differ diff --git a/assets/0400-0499/0469.Convex Polygon/images/polygon_not_convex.png b/assets/0400-0499/0469.Convex Polygon/images/polygon_not_convex.png new file mode 100644 index 00000000..9fad9a5b Binary files /dev/null and b/assets/0400-0499/0469.Convex Polygon/images/polygon_not_convex.png differ diff --git a/assets/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md b/assets/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md new file mode 100644 index 00000000..ee17494c --- /dev/null +++ b/assets/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md @@ -0,0 +1,59 @@ +# [470. Implement Rand10() Using Rand7()](https://leetcode.com/problems/implement-rand10-using-rand7) + + + +## Description + +

Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.

+ +

Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().

+ +

Follow up:

+ +
    +
  • What is the expected value for the number of calls to rand7() function?
  • +
  • Could you minimize the number of calls to rand7()?
  • +
+ +

 

+

Example 1:

+
Input: n = 1
+Output: [2]
+

Example 2:

+
Input: n = 2
+Output: [2,8]
+

Example 3:

+
Input: n = 3
+Output: [3,8,10]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0471.Encode String with Shortest Length/README_EN.md b/assets/0400-0499/0471.Encode String with Shortest Length/README_EN.md new file mode 100644 index 00000000..ad4d60f8 --- /dev/null +++ b/assets/0400-0499/0471.Encode String with Shortest Length/README_EN.md @@ -0,0 +1,85 @@ +# [471. Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length) + + + +## Description + +

Given a string s, encode the string such that its encoded length is the shortest.

+ +

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. k should be a positive integer.

+ +

If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return any of them.

+ +

 

+

Example 1:

+ +
+Input: s = "aaa"
+Output: "aaa"
+Explanation: There is no way to encode it such that it is shorter than the input string, so we do not encode it.
+
+ +

Example 2:

+ +
+Input: s = "aaaaa"
+Output: "5[a]"
+Explanation: "5[a]" is shorter than "aaaaa" by 1 character.
+
+ +

Example 3:

+ +
+Input: s = "aaaaaaaaaa"
+Output: "10[a]"
+Explanation: "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
+
+ +

Example 4:

+ +
+Input: s = "aabcaabcd"
+Output: "2[aabc]d"
+Explanation: "aabc" occurs twice, so one answer can be "2[aabc]d".
+
+ +

Example 5:

+ +
+Input: s = "abbbabbbcabbbabbbc"
+Output: "2[2[abbb]c]"
+Explanation: "abbbabbbc" occurs twice, but "abbbabbbc" can also be encoded to "2[abbb]c", so one answer can be "2[2[abbb]c]".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 150
  • +
  • s consists of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0472.Concatenated Words/README_EN.md b/assets/0400-0499/0472.Concatenated Words/README_EN.md new file mode 100644 index 00000000..472fc8f5 --- /dev/null +++ b/assets/0400-0499/0472.Concatenated Words/README_EN.md @@ -0,0 +1,61 @@ +# [472. Concatenated Words](https://leetcode.com/problems/concatenated-words) + + + +## Description + +

Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.

+ +

A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

+ +

 

+

Example 1:

+ +
+Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
+Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
+Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 
+"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; 
+"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
+ +

Example 2:

+ +
+Input: words = ["cat","dog","catdog"]
+Output: ["catdog"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 104
  • +
  • 0 <= words[i].length <= 1000
  • +
  • words[i] consists of only lowercase English letters.
  • +
  • 0 <= sum(words[i].length) <= 6 * 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0473.Matchsticks to Square/README_EN.md b/assets/0400-0499/0473.Matchsticks to Square/README_EN.md new file mode 100644 index 00000000..77b06e9c --- /dev/null +++ b/assets/0400-0499/0473.Matchsticks to Square/README_EN.md @@ -0,0 +1,59 @@ +# [473. Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square) + + + +## Description + +

You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

+ +

Return true if you can make this square and false otherwise.

+ +

 

+

Example 1:

+ +
+Input: matchsticks = [1,1,2,2,2]
+Output: true
+Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
+
+ +

Example 2:

+ +
+Input: matchsticks = [3,3,3,3,4]
+Output: false
+Explanation: You cannot find a way to form a square with all the matchsticks.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= matchsticks.length <= 15
  • +
  • 0 <= matchsticks[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0473.Matchsticks to Square/images/matchsticks1-grid.jpg b/assets/0400-0499/0473.Matchsticks to Square/images/matchsticks1-grid.jpg new file mode 100644 index 00000000..34f01cc9 Binary files /dev/null and b/assets/0400-0499/0473.Matchsticks to Square/images/matchsticks1-grid.jpg differ diff --git a/assets/0400-0499/0474.Ones and Zeroes/README_EN.md b/assets/0400-0499/0474.Ones and Zeroes/README_EN.md new file mode 100644 index 00000000..8cf0a26c --- /dev/null +++ b/assets/0400-0499/0474.Ones and Zeroes/README_EN.md @@ -0,0 +1,65 @@ +# [474. Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes) + + + +## Description + +

You are given an array of binary strings strs and two integers m and n.

+ +

Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.

+ +

A set x is a subset of a set y if all elements of x are also elements of y.

+ +

 

+

Example 1:

+ +
+Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
+Output: 4
+Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
+Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
+{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
+
+ +

Example 2:

+ +
+Input: strs = ["10","0","1"], m = 1, n = 1
+Output: 2
+Explanation: The largest subset is {"0", "1"}, so the answer is 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= strs.length <= 600
  • +
  • 1 <= strs[i].length <= 100
  • +
  • strs[i] consists only of digits '0' and '1'.
  • +
  • 1 <= m, n <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0475.Heaters/README_EN.md b/assets/0400-0499/0475.Heaters/README_EN.md new file mode 100644 index 00000000..881641bb --- /dev/null +++ b/assets/0400-0499/0475.Heaters/README_EN.md @@ -0,0 +1,70 @@ +# [475. Heaters](https://leetcode.com/problems/heaters) + + + +## Description + +

Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.

+ +

Every house can be warmed, as long as the house is within the heater's warm radius range. 

+ +

Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.

+ +

Notice that all the heaters follow your radius standard, and the warm radius will the same.

+ +

 

+

Example 1:

+ +
+Input: houses = [1,2,3], heaters = [2]
+Output: 1
+Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
+
+ +

Example 2:

+ +
+Input: houses = [1,2,3,4], heaters = [1,4]
+Output: 1
+Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
+
+ +

Example 3:

+ +
+Input: houses = [1,5], heaters = [2]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= houses.length, heaters.length <= 3 * 104
  • +
  • 1 <= houses[i], heaters[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0476.Number Complement/README_EN.md b/assets/0400-0499/0476.Number Complement/README_EN.md new file mode 100644 index 00000000..ceb0e808 --- /dev/null +++ b/assets/0400-0499/0476.Number Complement/README_EN.md @@ -0,0 +1,59 @@ +# [476. Number Complement](https://leetcode.com/problems/number-complement) + + + +## Description + +

Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.

+ +

 

+

Example 1:

+ +
+Input: num = 5
+Output: 2
+Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
+
+ +

Example 2:

+ +
+Input: num = 1
+Output: 0
+Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
+
+ +

 

+

Constraints:

+ + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0477.Total Hamming Distance/README_EN.md b/assets/0400-0499/0477.Total Hamming Distance/README_EN.md new file mode 100644 index 00000000..36325c4a --- /dev/null +++ b/assets/0400-0499/0477.Total Hamming Distance/README_EN.md @@ -0,0 +1,61 @@ +# [477. Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance) + + + +## Description + +

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

+ +

Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.

+ +

 

+

Example 1:

+ +
+Input: nums = [4,14,2]
+Output: 6
+Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
+showing the four bits relevant in this case).
+The answer will be:
+HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
+
+ +

Example 2:

+ +
+Input: nums = [4,14,4]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0478.Generate Random Point in a Circle/README_EN.md b/assets/0400-0499/0478.Generate Random Point in a Circle/README_EN.md new file mode 100644 index 00000000..fc1e9d5c --- /dev/null +++ b/assets/0400-0499/0478.Generate Random Point in a Circle/README_EN.md @@ -0,0 +1,65 @@ +# [478. Generate Random Point in a Circle](https://leetcode.com/problems/generate-random-point-in-a-circle) + + + +## Description + +

Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.

+ +

Implement the Solution class:

+ +
    +
  • Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).
  • +
  • randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].
  • +
+ +

 

+

Example 1:

+ +
+Input
+["Solution", "randPoint", "randPoint", "randPoint"]
+[[1.0, 0.0, 0.0], [], [], []]
+Output
+[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
+
+Explanation
+Solution solution = new Solution(1.0, 0.0, 0.0);
+solution.randPoint(); // return [-0.02493, -0.38077]
+solution.randPoint(); // return [0.82314, 0.38945]
+solution.randPoint(); // return [0.36572, 0.17248]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 < radius <= 108
  • +
  • -107 <= x_center, y_center <= 107
  • +
  • At most 3 * 104 calls will be made to randPoint.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0479.Largest Palindrome Product/README_EN.md b/assets/0400-0499/0479.Largest Palindrome Product/README_EN.md new file mode 100644 index 00000000..e3de9b99 --- /dev/null +++ b/assets/0400-0499/0479.Largest Palindrome Product/README_EN.md @@ -0,0 +1,55 @@ +# [479. Largest Palindrome Product](https://leetcode.com/problems/largest-palindrome-product) + + + +## Description + +

Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 987
+Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0480.Sliding Window Median/README_EN.md b/assets/0400-0499/0480.Sliding Window Median/README_EN.md new file mode 100644 index 00000000..4a3bcb9f --- /dev/null +++ b/assets/0400-0499/0480.Sliding Window Median/README_EN.md @@ -0,0 +1,73 @@ +# [480. Sliding Window Median](https://leetcode.com/problems/sliding-window-median) + + + +## Description + +

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.

+ +
    +
  • For examples, if arr = [2,3,4], the median is 3.
  • +
  • For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
  • +
+ +

You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

+ +

Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
+Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
+Explanation: 
+Window position                Median
+---------------                -----
+[1  3  -1] -3  5  3  6  7        1
+ 1 [3  -1  -3] 5  3  6  7       -1
+ 1  3 [-1  -3  5] 3  6  7       -1
+ 1  3  -1 [-3  5  3] 6  7        3
+ 1  3  -1  -3 [5  3  6] 7        5
+ 1  3  -1  -3  5 [3  6  7]       6
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4,2,3,1,4,2], k = 3
+Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= nums.length <= 105
  • +
  • 231 <= nums[i] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0481.Magical String/README_EN.md b/assets/0400-0499/0481.Magical String/README_EN.md new file mode 100644 index 00000000..89b79a64 --- /dev/null +++ b/assets/0400-0499/0481.Magical String/README_EN.md @@ -0,0 +1,63 @@ +# [481. Magical String](https://leetcode.com/problems/magical-string) + + + +## Description + +

A magical string s consists of only '1' and '2' and obeys the following rules:

+ +
    +
  • The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.
  • +
+ +

The first few elements of s is s = "1221121221221121122……". If we group the consecutive 1's and 2's in s, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......" and the occurrences of 1's or 2's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......". You can see that the occurrence sequence is s itself.

+ +

Given an integer n, return the number of 1's in the first n number in the magical string s.

+ +

 

+

Example 1:

+ +
+Input: n = 6
+Output: 3
+Explanation: The first 6 elements of magical string s is "12211" and it contains three 1's, so return 3.
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0482.License Key Formatting/README_EN.md b/assets/0400-0499/0482.License Key Formatting/README_EN.md new file mode 100644 index 00000000..028a35ca --- /dev/null +++ b/assets/0400-0499/0482.License Key Formatting/README_EN.md @@ -0,0 +1,63 @@ +# [482. License Key Formatting](https://leetcode.com/problems/license-key-formatting) + + + +## Description + +

You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.

+ +

We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.

+ +

Return the reformatted license key.

+ +

 

+

Example 1:

+ +
+Input: s = "5F3Z-2e-9-w", k = 4
+Output: "5F3Z-2E9W"
+Explanation: The string s has been split into two parts, each part has 4 characters.
+Note that the two extra dashes are not needed and can be removed.
+
+ +

Example 2:

+ +
+Input: s = "2-5g-3-J", k = 2
+Output: "2-5G-3J"
+Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s consists of English letters, digits, and dashes '-'.
  • +
  • 1 <= k <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0483.Smallest Good Base/README_EN.md b/assets/0400-0499/0483.Smallest Good Base/README_EN.md new file mode 100644 index 00000000..54299bdf --- /dev/null +++ b/assets/0400-0499/0483.Smallest Good Base/README_EN.md @@ -0,0 +1,67 @@ +# [483. Smallest Good Base](https://leetcode.com/problems/smallest-good-base) + + + +## Description + +

Given an integer n represented as a string, return the smallest good base of n.

+ +

We call k >= 2 a good base of n, if all digits of n base k are 1's.

+ +

 

+

Example 1:

+ +
+Input: n = "13"
+Output: "3"
+Explanation: 13 base 3 is 111.
+
+ +

Example 2:

+ +
+Input: n = "4681"
+Output: "8"
+Explanation: 4681 base 8 is 11111.
+
+ +

Example 3:

+ +
+Input: n = "1000000000000000000"
+Output: "999999999999999999"
+Explanation: 1000000000000000000 base 999999999999999999 is 11.
+
+ +

 

+

Constraints:

+ +
    +
  • n is an integer in the range [3, 1018].
  • +
  • n does not contain any leading zeros.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0484.Find Permutation/README_EN.md b/assets/0400-0499/0484.Find Permutation/README_EN.md new file mode 100644 index 00000000..08bc85af --- /dev/null +++ b/assets/0400-0499/0484.Find Permutation/README_EN.md @@ -0,0 +1,64 @@ +# [484. Find Permutation](https://leetcode.com/problems/find-permutation) + + + +## Description + +

A permutation perm of n integers of all the integers in the range [1, n] can be represented as a string s of length n - 1 where:

+ +
    +
  • s[i] == 'I' if perm[i] < perm[i + 1], and
  • +
  • s[i] == 'D' if perm[i] > perm[i + 1].
  • +
+ +

Given a string s, reconstruct the lexicographically smallest permutation perm and return it.

+ +

 

+

Example 1:

+ +
+Input: s = "I"
+Output: [1,2]
+Explanation: [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
+
+ +

Example 2:

+ +
+Input: s = "DI"
+Output: [2,1,3]
+Explanation: Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is either 'I' or 'D'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0485.Max Consecutive Ones/README_EN.md b/assets/0400-0499/0485.Max Consecutive Ones/README_EN.md new file mode 100644 index 00000000..35b3e4b9 --- /dev/null +++ b/assets/0400-0499/0485.Max Consecutive Ones/README_EN.md @@ -0,0 +1,100 @@ +# [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones) + + + +## Description + +

Given a binary array nums, return the maximum number of consecutive 1's in the array.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,1,0,1,1,1]
+Output: 3
+Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
+
+ +

Example 2:

+ +
+Input: nums = [1,0,1,1,0,1]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + res = t = 0 + for num in nums: + if num == 1: + t += 1 + else: + res = max(res, t) + t = 0 + return max(res, t) +``` + +### **Java** + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int res = 0, t = 0; + for (int num : nums) { + if (num == 1) { + ++t; + } else { + res = Math.max(res, t); + t = 0; + } + } + return Math.max(res, t); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function (nums) { + let res = 0, + t = 0; + for (let num of nums) { + if (num == 1) { + ++t; + } else { + res = Math.max(res, t); + t = 0; + } + } + return Math.max(res, t); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0486.Predict the Winner/README_EN.md b/assets/0400-0499/0486.Predict the Winner/README_EN.md new file mode 100644 index 00000000..73ea6cfc --- /dev/null +++ b/assets/0400-0499/0486.Predict the Winner/README_EN.md @@ -0,0 +1,65 @@ +# [486. Predict the Winner](https://leetcode.com/problems/predict-the-winner) + + + +## Description + +

You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.

+ +

Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.

+ +

Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,5,2]
+Output: false
+Explanation: Initially, player 1 can choose between 1 and 2. 
+If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). 
+So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. 
+Hence, player 1 will never be the winner and you need to return false.
+
+ +

Example 2:

+ +
+Input: nums = [1,5,233,7]
+Output: true
+Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
+Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 20
  • +
  • 0 <= nums[i] <= 107
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0487.Max Consecutive Ones II/README_EN.md b/assets/0400-0499/0487.Max Consecutive Ones II/README_EN.md new file mode 100644 index 00000000..a83a01d1 --- /dev/null +++ b/assets/0400-0499/0487.Max Consecutive Ones II/README_EN.md @@ -0,0 +1,138 @@ +# [487. Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii) + + + +## Description + +

Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,0,1,1,0]
+Output: 4
+Explanation: Flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.
+
+ +

Example 2:

+ +
+Input: nums = [1,0,1,1,0,1]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • nums[i] is either 0 or 1.
  • +
+ +

 

+

Follow up: What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?

+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + n = len(nums) + prefix = [0] * n + suffix = [0] * n + res = 0 + for i in range(n): + if i == 0: + prefix[i] = nums[i] + else: + prefix[i] = 0 if nums[i] == 0 else prefix[i - 1] + 1 + res = max(res, prefix[i]) + + for i in range(n - 1, -1, -1): + if i == n - 1: + suffix[i] = nums[i] + else: + suffix[i] = 0 if nums[i] == 0 else suffix[i + 1] + 1 + + for i in range(n): + if nums[i] == 0: + t = 1 + if i > 0: + t += prefix[i - 1] + if i < n - 1: + t += suffix[i + 1] + res = max(res, t) + return res +``` + +### **Java** + +- Two Pointers, time complexity: O(n²), memory complexity: O(1) + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int n = nums.length; + int res = 0; + for (int i = 0; i < n; ++i) { + int cnt = 1; + int j = i; + while (j < n && (cnt > 0 || nums[j] == 1)) { + if (nums[j] == 0) --cnt; + ++j; + } + res = Math.max(res, j - i); + } + return res; + } +} +``` + +- Prefix Array & Suffix Array, time complexity: O(n), memory complexity: O(n) + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int n = nums.length; + + int[] prefix = new int[n]; + int[] suffix = new int[n]; + + int res = 0; + for (int i = 0; i < n; ++i) { + if (i == 0) prefix[0] = nums[0]; + else prefix[i] = nums[i] == 0 ? 0 : prefix[i - 1] + 1; + res = Math.max(res, prefix[i]); + } + + for (int i = n - 1; i >= 0; --i) { + if (i == n - 1) suffix[n - 1] = nums[n - 1]; + else suffix[i] = nums[i] == 0 ? 0 : suffix[i + 1] + 1; + } + + for (int i = 0; i < n; ++i) { + if (nums[i] == 0) { + int t = 1; + if (i > 0) t += prefix[i - 1]; + if (i < n - 1) t += suffix[i + 1]; + res = Math.max(res, t); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0488.Zuma Game/README_EN.md b/assets/0400-0499/0488.Zuma Game/README_EN.md new file mode 100644 index 00000000..915d1e8a --- /dev/null +++ b/assets/0400-0499/0488.Zuma Game/README_EN.md @@ -0,0 +1,79 @@ +# [488. Zuma Game](https://leetcode.com/problems/zuma-game) + + + +## Description + +

Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.

+ +

Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.

+ +

Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.

+ +

 

+

Example 1:

+ +
+Input: board = "WRRBBW", hand = "RB"
+Output: -1
+Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
+
+ +

Example 2:

+ +
+Input: board = "WWRRBBWW", hand = "WRBRW"
+Output: 2
+Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty
+
+ +

Example 3:

+ +
+Input: board = "G", hand = "GGGGG"
+Output: 2
+Explanation: G -> G[G] -> GG[G] -> empty 
+
+ +

Example 4:

+ +
+Input: board = "RBYYBBRRB", hand = "YRBGB"
+Output: 3
+Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty 
+
+ +

 

+

Constraints:

+ +
    +
  • You may assume that the initial row of balls on the table won’t have any 3 or more consecutive balls with the same color.
  • +
  • 1 <= board.length <= 16
  • +
  • 1 <= hand.length <= 5
  • +
  • Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0489.Robot Room Cleaner/README_EN.md b/assets/0400-0499/0489.Robot Room Cleaner/README_EN.md new file mode 100644 index 00000000..272c0f7e --- /dev/null +++ b/assets/0400-0499/0489.Robot Room Cleaner/README_EN.md @@ -0,0 +1,137 @@ +# [489. Robot Room Cleaner](https://leetcode.com/problems/robot-room-cleaner) + + + +## Description + +

Given a robot cleaner in a room modeled as a grid.

+ + + +

Each cell in the grid can be empty or blocked.

+ + + +

The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees.

+ + + +

When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.

+ + + +

Design an algorithm to clean the entire room using only the 4 given APIs shown below.

+ + + +
+
+interface Robot {
+
+  // returns true if next cell is open and robot moves into the cell.
+
+  // returns false if next cell is obstacle and robot stays on the current cell.
+
+  boolean move();
+
+
+
+  // Robot will stay on the same cell after calling turnLeft/turnRight.
+
+  // Each turn will be 90 degrees.
+
+  void turnLeft();
+
+  void turnRight();
+
+
+
+  // Clean the current cell.
+
+  void clean();
+
+}
+
+
+ + + +

Example:

+ + + +
+
+Input:
+
+room = [
+
+  [1,1,1,1,1,0,1,1],
+
+  [1,1,1,1,1,0,1,1],
+
+  [1,0,1,1,1,1,1,1],
+
+  [0,0,0,1,0,0,0,0],
+
+  [1,1,1,1,1,1,1,1]
+
+],
+
+row = 1,
+
+col = 3
+
+
+
+Explanation:
+
+All grids in the room are marked by either 0 or 1.
+
+0 means the cell is blocked, while 1 means the cell is accessible.
+
+The robot initially starts at the position of row=1, col=3.
+
+From the top left corner, its position is one row below and three columns right.
+
+
+ + + +

Notes:

+ + + +
    +
  1. The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the mentioned 4 APIs, without knowing the room layout and the initial robot's position.
  2. +
  3. The robot's initial position will always be in an accessible cell.
  4. +
  5. The initial direction of the robot will be facing up.
  6. +
  7. All accessible cells are connected, which means the all cells marked as 1 will be accessible by the robot.
  8. +
  9. Assume all four edges of the grid are all surrounded by wall.
  10. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0490.The Maze/README_EN.md b/assets/0400-0499/0490.The Maze/README_EN.md new file mode 100644 index 00000000..6c8ca059 --- /dev/null +++ b/assets/0400-0499/0490.The Maze/README_EN.md @@ -0,0 +1,136 @@ +# [490. The Maze](https://leetcode.com/problems/the-maze) + + + +## Description + +

There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

+ +

Given the m x n maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return true if the ball can stop at the destination, otherwise return false.

+ +

You may assume that the borders of the maze are all walls (see examples).

+ +

 

+

Example 1:

+ +
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
+Output: true
+Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.
+
+ +

Example 2:

+ +
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
+Output: false
+Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
+
+ +

Example 3:

+ +
+Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • m == maze.length
  • +
  • n == maze[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • maze[i][j] is 0 or 1.
  • +
  • start.length == 2
  • +
  • destination.length == 2
  • +
  • 0 <= startrow, destinationrow <= m
  • +
  • 0 <= startcol, destinationcol <= n
  • +
  • Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
  • +
  • The maze contains at least 2 empty spaces.
  • +
+ + +## Solutions + + + +### **Python3** + +DFS. + +```python +class Solution: + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: + def dfs(maze, start, destination): + if visited[start[0]][start[1]]: + return False + if start[0] == destination[0] and start[1] == destination[1]: + return True + visited[start[0]][start[1]] = True + l, r, u, d = start[1] - 1, start[1] + 1, start[0] - 1, start[0] + 1 + while l >= 0 and maze[start[0]][l] == 0: + l -= 1 + if dfs(maze, [start[0], l + 1], destination): + return True + while r < len(maze[0]) and maze[start[0]][r] == 0: + r += 1 + if dfs(maze, [start[0], r - 1], destination): + return True + while u >= 0 and maze[u][start[1]] == 0: + u -= 1 + if dfs(maze, [u + 1, start[1]], destination): + return True + while d < len(maze) and maze[d][start[1]] == 0: + d += 1 + if dfs(maze, [d - 1, start[1]], destination): + return True + return False + + visited = [[False for _ in maze[0]] for _ in maze] + return dfs(maze, start, destination) +``` + +### **Java** + +```java +class Solution { + private boolean[][] visited; + + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + int m = maze.length, n = maze[0].length; + visited = new boolean[m][n]; + return dfs(maze, start, destination); + } + + private boolean dfs(int[][] maze, int[] start, int[] destination) { + if (visited[start[0]][start[1]]) return false; + if (start[0] == destination[0] && start[1] == destination[1]) return true; + visited[start[0]][start[1]] = true; + + int l = start[1] - 1, r = start[1] + 1, u = start[0] - 1, d = start[0] + 1; + + while (l >= 0 && maze[start[0]][l] == 0) --l; + if (dfs(maze, new int[]{start[0], l + 1}, destination)) return true; + + while (r < maze[0].length && maze[start[0]][r] == 0) ++r; + if (dfs(maze, new int[]{start[0], r - 1}, destination)) return true; + + while (u >= 0 && maze[u][start[1]] == 0) --u; + if (dfs(maze, new int[]{u + 1, start[1]}, destination)) return true; + + while (d < maze.length && maze[d][start[1]] == 0) ++d; + if (dfs(maze, new int[]{d - 1, start[1]}, destination)) return true; + + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0490.The Maze/images/maze_1_example_1.png b/assets/0400-0499/0490.The Maze/images/maze_1_example_1.png new file mode 100644 index 00000000..fe3fd795 Binary files /dev/null and b/assets/0400-0499/0490.The Maze/images/maze_1_example_1.png differ diff --git a/assets/0400-0499/0490.The Maze/images/maze_1_example_2.png b/assets/0400-0499/0490.The Maze/images/maze_1_example_2.png new file mode 100644 index 00000000..4629d821 Binary files /dev/null and b/assets/0400-0499/0490.The Maze/images/maze_1_example_2.png differ diff --git a/assets/0400-0499/0490.The Maze/images/maze_2_example_1.png b/assets/0400-0499/0490.The Maze/images/maze_2_example_1.png new file mode 100644 index 00000000..d1eb0f5b Binary files /dev/null and b/assets/0400-0499/0490.The Maze/images/maze_2_example_1.png differ diff --git a/assets/0400-0499/0490.The Maze/images/maze_2_example_2.png b/assets/0400-0499/0490.The Maze/images/maze_2_example_2.png new file mode 100644 index 00000000..189100a3 Binary files /dev/null and b/assets/0400-0499/0490.The Maze/images/maze_2_example_2.png differ diff --git a/assets/0400-0499/0491.Increasing Subsequences/README_EN.md b/assets/0400-0499/0491.Increasing Subsequences/README_EN.md new file mode 100644 index 00000000..b1054689 --- /dev/null +++ b/assets/0400-0499/0491.Increasing Subsequences/README_EN.md @@ -0,0 +1,57 @@ +# [491. Increasing Subsequences](https://leetcode.com/problems/increasing-subsequences) + + + +## Description + +

Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.

+ +

The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.

+ +

 

+

Example 1:

+ +
+Input: nums = [4,6,7,7]
+Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
+
+ +

Example 2:

+ +
+Input: nums = [4,4,3,2,1]
+Output: [[4,4]]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 15
  • +
  • -100 <= nums[i] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0492.Construct the Rectangle/README_EN.md b/assets/0400-0499/0492.Construct the Rectangle/README_EN.md new file mode 100644 index 00000000..8a8b6101 --- /dev/null +++ b/assets/0400-0499/0492.Construct the Rectangle/README_EN.md @@ -0,0 +1,95 @@ +# [492. Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle) + + + +## Description + +

A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

+ +
    +
  1. The area of the rectangular web page you designed must equal to the given target area.
  2. +
  3. The width W should not be larger than the length L, which means L >= W.
  4. +
  5. The difference between length L and width W should be as small as possible.
  6. +
+ +

Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.

+ +

 

+

Example 1:

+ +
+Input: area = 4
+Output: [2,2]
+Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 
+But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
+
+ +

Example 2:

+ +
+Input: area = 37
+Output: [37,1]
+
+ +

Example 3:

+ +
+Input: area = 122122
+Output: [427,286]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= area <= 107
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def constructRectangle(self, area: int) -> List[int]: + sr = int(math.sqrt(area)) + l = w = sr + while l <= area and w >= 1: + s = l * w + if s == area: + break + if s > area: + w -= 1 + else: + l += 1 + return [l, w] +``` + +### **Java** + +```java +class Solution { + public int[] constructRectangle(int area) { + int sr = (int) Math.sqrt(area); + int l = sr, w = sr; + while (l <= area && w >= 1) { + int s = l * w; + if (s == area) break; + if (s > area) --w; + else ++l; + } + return new int[]{l, w}; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0493.Reverse Pairs/README_EN.md b/assets/0400-0499/0493.Reverse Pairs/README_EN.md new file mode 100644 index 00000000..361b0590 --- /dev/null +++ b/assets/0400-0499/0493.Reverse Pairs/README_EN.md @@ -0,0 +1,50 @@ +# [493. Reverse Pairs](https://leetcode.com/problems/reverse-pairs) + + + +## Description + +

Given an integer array nums, return the number of reverse pairs in the array.

+ +

A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].

+ +

 

+

Example 1:

+
Input: nums = [1,3,2,3,1]
+Output: 2
+

Example 2:

+
Input: nums = [2,4,3,5,1]
+Output: 3
+
+

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 5 * 104
  • +
  • 231 <= nums[i] <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0494.Target Sum/README_EN.md b/assets/0400-0499/0494.Target Sum/README_EN.md new file mode 100644 index 00000000..bfd8bb8a --- /dev/null +++ b/assets/0400-0499/0494.Target Sum/README_EN.md @@ -0,0 +1,134 @@ +# [494. Target Sum](https://leetcode.com/problems/target-sum) + + + +## Description + +

You are given an integer array nums and an integer target.

+ +

You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.

+ +
    +
  • For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
  • +
+ +

Return the number of different expressions that you can build, which evaluates to target.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,1,1,1,1], target = 3
+Output: 5
+Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
+-1 + 1 + 1 + 1 + 1 = 3
++1 - 1 + 1 + 1 + 1 = 3
++1 + 1 - 1 + 1 + 1 = 3
++1 + 1 + 1 - 1 + 1 = 3
++1 + 1 + 1 + 1 - 1 = 3
+
+ +

Example 2:

+ +
+Input: nums = [1], target = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 20
  • +
  • 0 <= nums[i] <= 1000
  • +
  • 0 <= sum(nums[i]) <= 1000
  • +
  • -1000 <= target <= 1000
  • +
+ + +## Solutions + +It is similar to the backpack problem, except that the index may appear negative, which requires special handling. + + + +### **Python3** + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + if target < -1000 or target > 1000: + return 0 + n = len(nums) + dp = [[0] * 2001 for i in range(n)] + dp[0][nums[0] + 1000] += 1 + dp[0][-nums[0] + 1000] += 1 + for i in range(1, n): + for j in range(-1000, 1001): + if dp[i - 1][j + 1000] > 0: + dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000] + dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000] + return dp[n - 1][target + 1000] +``` + +### **Java** + +```java +class Solution { + public int findTargetSumWays(int[] nums, int target) { + if (target < -1000 || target > 1000) { + return 0; + } + + int n = nums.length; + int[][] dp = new int[n][2001]; + + dp[0][nums[0] + 1000] += 1; + dp[0][-nums[0] + 1000] += 1; + + for (int i = 1; i < n; i++) { + for (int j = -1000; j <= 1000; j++) { + if (dp[i - 1][j + 1000] > 0) { + dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000]; + dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000]; + } + } + } + return dp[n - 1][target + 1000]; + } +} +``` + +### **Go** + +```go +func findTargetSumWays(nums []int, target int) int { + if target < -1000 || target > 1000 { + return 0 + } + n := len(nums) + dp := make([][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([]int, 2001) + } + dp[0][nums[0]+1000] += 1 + dp[0][-nums[0]+1000] += 1 + for i := 1; i < n; i++ { + for j := -1000; j <= 1000; j++ { + if dp[i-1][j+1000] > 0 { + dp[i][j+nums[i]+1000] += dp[i-1][j+1000] + dp[i][j-nums[i]+1000] += dp[i-1][j+1000] + } + } + } + return dp[n-1][target+1000] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0495.Teemo Attacking/README_EN.md b/assets/0400-0499/0495.Teemo Attacking/README_EN.md new file mode 100644 index 00000000..0d168137 --- /dev/null +++ b/assets/0400-0499/0495.Teemo Attacking/README_EN.md @@ -0,0 +1,67 @@ +# [495. Teemo Attacking](https://leetcode.com/problems/teemo-attacking) + + + +## Description + +

You are given an integer array timeSeries and an integer duration. Our hero Teemo has attacked an enemy where the ith attack was done at the timeSeries[i]. When Teemo attacks their enemy, the enemy gets poisoned for duration time (i.e., the enemy is poisoned for the time interval [timeSeries[i], timeSeries[i] + duration - 1] inclusive).

+ +

Return the total time that the enemy is in a poisoned condition.

+ +

 

+

Example 1:

+ +
+Input: timeSeries = [1,4], duration = 2
+Output: 4
+Explanation: At time point 1, Teemo starts attacking the enemy and makes them be poisoned immediately. 
+This poisoned status will last 2 seconds until the end of time point 2. 
+And at time point 4, Teemo attacks the enemy again and causes them to be in poisoned status for another 2 seconds. 
+So you finally need to output 4.
+
+ +

Example 2:

+ +
+Input: timeSeries = [1,2], duration = 2
+Output: 3
+Explanation: At time point 1, Teemo starts attacking the enemy and makes them be poisoned. 
+This poisoned status will last 2 seconds until the end of time point 2. 
+However, at the beginning of time point 2, Teemo attacks the enemy again who is already in poisoned status. 
+Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3. 
+So you finally need to output 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= timeSeries.length <= 104
  • +
  • 0 <= timeSeries[i], duration <= 107
  • +
  • timeSeries is sorted in non-decreasing order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0496.Next Greater Element I/README_EN.md b/assets/0400-0499/0496.Next Greater Element I/README_EN.md new file mode 100644 index 00000000..656e5348 --- /dev/null +++ b/assets/0400-0499/0496.Next Greater Element I/README_EN.md @@ -0,0 +1,115 @@ +# [496. Next Greater Element I](https://leetcode.com/problems/next-greater-element-i) + + + +## Description + +

You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2.

+ +

Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

+ +

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, return -1 for this number.

+ +

 

+

Example 1:

+ +
+Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
+Output: [-1,3,-1]
+Explanation:
+For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
+For number 1 in the first array, the next greater number for it in the second array is 3.
+For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
+ +

Example 2:

+ +
+Input: nums1 = [2,4], nums2 = [1,2,3,4]
+Output: [3,-1]
+Explanation:
+For number 2 in the first array, the next greater number for it in the second array is 3.
+For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums1.length <= nums2.length <= 1000
  • +
  • 0 <= nums1[i], nums2[i] <= 104
  • +
  • All integers in nums1 and nums2 are unique.
  • +
  • All the integers of nums1 also appear in nums2.
  • +
+ +

 

+Follow up: Could you find an O(nums1.length + nums2.length) solution? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + mapper = {} + for num in nums2: + while stack and stack[-1] < num: + mapper[stack.pop()] = num + stack.append(num) + return [mapper.get(num, -1) for num in nums1] +``` + +### **Java** + +```java +class Solution { + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + Deque stack = new ArrayDeque<>(); + Map map = new HashMap<>(); + for (int num : nums2) { + while (!stack.isEmpty() && stack.peek() < num) { + map.put(stack.pop(), num); + } + stack.push(num); + } + int n = nums1.length; + int[] res = new int[n]; + for (int i = 0; i < n; ++i) { + res[i] = map.getOrDefault(nums1[i], -1); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function(nums1, nums2) { + let stack = []; + let nextGreater = {}; + for (let num of nums2) { + while (stack.length > 0 && stack[stack.length - 1] < num) { + nextGreater[stack.pop()] = num; + } + stack.push(num); + } + let res = nums1.map(d => nextGreater[d] || -1); + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md b/assets/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md new file mode 100644 index 00000000..34b3e7ac --- /dev/null +++ b/assets/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md @@ -0,0 +1,115 @@ +# [497. Random Point in Non-overlapping Rectangles](https://leetcode.com/problems/random-point-in-non-overlapping-rectangles) + + + +## Description + +

Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles.

+ + + +

Note:

+ + + +
    +
  1. An integer point is a point that has integer coordinates. 
  2. +
  3. A point on the perimeter of a rectangle is included in the space covered by the rectangles. 
  4. +
  5. ith rectangle = rects[i][x1,y1,x2,y2], where [x1, y1] are the integer coordinates of the bottom-left corner, and [x2, y2] are the integer coordinates of the top-right corner.
  6. +
  7. length and width of each rectangle does not exceed 2000.
  8. +
  9. 1 <= rects.length <= 100
  10. +
  11. pick return a point as an array of integer coordinates [p_x, p_y]
  12. +
  13. pick is called at most 10000 times.
  14. +
+ + + +
+ +

Example 1:

+ + + +
+
+Input: 
+
+["Solution","pick","pick","pick"]
+
+[[[[1,1,5,5]]],[],[],[]]
+
+Output: 
+
+[null,[4,1],[4,1],[3,3]]
+
+
+ + + +
+ +

Example 2:

+ + + +
+
+Input: 
+
+["Solution","pick","pick","pick","pick","pick"]
+
+[[[[-2,-2,-1,-1],[1,0,3,0]]],[],[],[],[],[]]
+
+Output: 
+
+[null,[-1,-2],[2,0],[-2,-1],[3,0],[-2,-2]]
+ +
+ + + +
+ +

Explanation of Input Syntax:

+ + + +

The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array of rectangles rects. pick has no arguments. Arguments are always wrapped with a list, even if there aren't any.

+ +
+ +
+ + + +
+ +
 
+ +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0498.Diagonal Traverse/README_EN.md b/assets/0400-0499/0498.Diagonal Traverse/README_EN.md new file mode 100644 index 00000000..e102ea5d --- /dev/null +++ b/assets/0400-0499/0498.Diagonal Traverse/README_EN.md @@ -0,0 +1,58 @@ +# [498. Diagonal Traverse](https://leetcode.com/problems/diagonal-traverse) + + + +## Description + +

Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

+ +

 

+

Example 1:

+ +
+Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
+Output: [1,2,4,7,5,3,6,8,9]
+
+ +

Example 2:

+ +
+Input: mat = [[1,2],[3,4]]
+Output: [1,2,3,4]
+
+ +

 

+

Constraints:

+ +
    +
  • m == mat.length
  • +
  • n == mat[i].length
  • +
  • 1 <= m, n <= 104
  • +
  • 1 <= m * n <= 104
  • +
  • -105 <= mat[i][j] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0498.Diagonal Traverse/images/diagonal_traverse.png b/assets/0400-0499/0498.Diagonal Traverse/images/diagonal_traverse.png new file mode 100644 index 00000000..9139dfb6 Binary files /dev/null and b/assets/0400-0499/0498.Diagonal Traverse/images/diagonal_traverse.png differ diff --git a/assets/0400-0499/0499.The Maze III/README_EN.md b/assets/0400-0499/0499.The Maze III/README_EN.md new file mode 100644 index 00000000..5299baa5 --- /dev/null +++ b/assets/0400-0499/0499.The Maze III/README_EN.md @@ -0,0 +1,83 @@ +# [499. The Maze III](https://leetcode.com/problems/the-maze-iii) + + + +## Description + +

There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.

+ +

Given the m x n maze, the ball's position ball and the hole's position hole, where ball = [ballrow, ballcol] and hole = [holerow, holecol], return a string instructions of all the instructions that the ball should follow to drop in the hole with the shortest distance possible. If there are multiple valid instructions, return the lexicographically minimum one. If the ball can't drop in the hole, return "impossible".

+ +

If there is a way for the ball to drop in the hole, the answer instructions should contain the characters 'u' (i.e., up), 'd' (i.e., down), 'l' (i.e., left), and 'r' (i.e., right).

+ +

The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included).

+ +

You may assume that the borders of the maze are all walls (see examples).

+ +

 

+

Example 1:

+ +
+Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [0,1]
+Output: "lul"
+Explanation: There are two shortest ways for the ball to drop into the hole.
+The first way is left -> up -> left, represented by "lul".
+The second way is up -> left, represented by 'ul'.
+Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul".
+
+ +

Example 2:

+ +
+Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], ball = [4,3], hole = [3,0]
+Output: "impossible"
+Explanation: The ball cannot reach the hole.
+
+ +

Example 3:

+ +
+Input: maze = [[0,0,0,0,0,0,0],[0,0,1,0,0,1,0],[0,0,0,0,1,0,0],[0,0,0,0,0,0,1]], ball = [0,4], hole = [3,5]
+Output: "dldr"
+
+ +

 

+

Constraints:

+ +
    +
  • m == maze.length
  • +
  • n == maze[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • maze[i][j] is 0 or 1.
  • +
  • ball.length == 2
  • +
  • hole.length == 2
  • +
  • 0 <= ballrow, holerow <= m
  • +
  • 0 <= ballcol, holecol <= n
  • +
  • Both the ball and the hole exist in an empty space, and they will not be in the same position initially.
  • +
  • The maze contains at least 2 empty spaces.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0400-0499/0499.The Maze III/images/maze3-1-grid.jpg b/assets/0400-0499/0499.The Maze III/images/maze3-1-grid.jpg new file mode 100644 index 00000000..47ddb5b4 Binary files /dev/null and b/assets/0400-0499/0499.The Maze III/images/maze3-1-grid.jpg differ diff --git a/assets/0400-0499/0499.The Maze III/images/maze3-2-grid.jpg b/assets/0400-0499/0499.The Maze III/images/maze3-2-grid.jpg new file mode 100644 index 00000000..ee1f478e Binary files /dev/null and b/assets/0400-0499/0499.The Maze III/images/maze3-2-grid.jpg differ diff --git a/assets/0400-0499/0499.The Maze III/images/maze_2_example_1.png b/assets/0400-0499/0499.The Maze III/images/maze_2_example_1.png new file mode 100644 index 00000000..d1eb0f5b Binary files /dev/null and b/assets/0400-0499/0499.The Maze III/images/maze_2_example_1.png differ diff --git a/assets/0400-0499/0499.The Maze III/images/maze_2_example_2.png b/assets/0400-0499/0499.The Maze III/images/maze_2_example_2.png new file mode 100644 index 00000000..189100a3 Binary files /dev/null and b/assets/0400-0499/0499.The Maze III/images/maze_2_example_2.png differ diff --git a/assets/0400-0499/0499.The Maze III/maze_2_example_1.png b/assets/0400-0499/0499.The Maze III/maze_2_example_1.png new file mode 100644 index 00000000..d1eb0f5b Binary files /dev/null and b/assets/0400-0499/0499.The Maze III/maze_2_example_1.png differ diff --git a/assets/0400-0499/0499.The Maze III/maze_2_example_2.png b/assets/0400-0499/0499.The Maze III/maze_2_example_2.png new file mode 100644 index 00000000..189100a3 Binary files /dev/null and b/assets/0400-0499/0499.The Maze III/maze_2_example_2.png differ diff --git a/assets/0500-0599/0500.Keyboard Row/README_EN.md b/assets/0500-0599/0500.Keyboard Row/README_EN.md new file mode 100644 index 00000000..d40af043 --- /dev/null +++ b/assets/0500-0599/0500.Keyboard Row/README_EN.md @@ -0,0 +1,105 @@ +# [500. Keyboard Row](https://leetcode.com/problems/keyboard-row) + + + +## Description + +

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

+ +

In the American keyboard:

+ +
    +
  • the first row consists of the characters "qwertyuiop",
  • +
  • the second row consists of the characters "asdfghjkl", and
  • +
  • the third row consists of the characters "zxcvbnm".
  • +
+ +

 

+

Example 1:

+ +
+Input: words = ["Hello","Alaska","Dad","Peace"]
+Output: ["Alaska","Dad"]
+
+ +

Example 2:

+ +
+Input: words = ["omk"]
+Output: []
+
+ +

Example 3:

+ +
+Input: words = ["adsdf","sfd"]
+Output: ["adsdf","sfd"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= words.length <= 20
  • +
  • 1 <= words[i].length <= 100
  • +
  • words[i] consists of English letters (both lowercase and uppercase). 
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findWords(self, words: List[str]) -> List[str]: + s1 = set('qwertyuiop') + s2 = set('asdfghjkl') + s3 = set('zxcvbnm') + res = [] + for word in words: + t = set(word.lower()) + if t <= s1 or t <= s2 or t <= s3: + res.append(word) + return res +``` + +### **Java** + +```java +class Solution { + public String[] findWords(String[] words) { + String s1 = "qwertyuiopQWERTYUIOP"; + String s2 = "asdfghjklASDFGHJKL"; + String s3 = "zxcvbnmZXCVBNM"; + List res = new ArrayList<>(); + for (String word : words) { + int n1 = 0, n2 = 0, n3 = 0; + int n = word.length(); + for (int i = 0; i < n; ++i) { + if (s1.contains(String.valueOf(word.charAt(i)))) { + ++n1; + } else if (s2.contains(String.valueOf(word.charAt(i)))) { + ++n2; + } else { + ++n3; + } + } + if (n1 == n || n2 == n || n3 == n) { + res.add(word); + } + } + return res.toArray(new String[0]); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0500.Keyboard Row/images/keyboard.png b/assets/0500-0599/0500.Keyboard Row/images/keyboard.png new file mode 100644 index 00000000..4fd75b6c Binary files /dev/null and b/assets/0500-0599/0500.Keyboard Row/images/keyboard.png differ diff --git a/assets/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md b/assets/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md new file mode 100644 index 00000000..158931cf --- /dev/null +++ b/assets/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md @@ -0,0 +1,67 @@ +# [501. Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree) + + + +## Description + +

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

+ +

If the tree has more than one mode, return them in any order.

+ +

Assume a BST is defined as follows:

+ +
    +
  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [1,null,2,2]
+Output: [2]
+
+ +

Example 2:

+ +
+Input: root = [0]
+Output: [0]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
+ +

 

+Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0501.Find Mode in Binary Search Tree/images/mode-tree.jpg b/assets/0500-0599/0501.Find Mode in Binary Search Tree/images/mode-tree.jpg new file mode 100644 index 00000000..fde1c161 Binary files /dev/null and b/assets/0500-0599/0501.Find Mode in Binary Search Tree/images/mode-tree.jpg differ diff --git a/assets/0500-0599/0502.IPO/README_EN.md b/assets/0500-0599/0502.IPO/README_EN.md new file mode 100644 index 00000000..f9b2c9ed --- /dev/null +++ b/assets/0500-0599/0502.IPO/README_EN.md @@ -0,0 +1,95 @@ +# [502. IPO](https://leetcode.com/problems/ipo) + + + +## Description + +

+ +Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. + +

+ + + +

+ +You are given several projects. For each project i, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. Initially, you have W capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. + +

+ + + +

+ +To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital. + +

+ + + +

Example 1:
+ +

+
+Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].
+
+
+
+Output: 4
+
+
+
+Explanation: Since your initial capital is 0, you can only start the project indexed 0.
+
+             After finishing it you will obtain profit 1 and your capital becomes 1.
+
+             With capital 1, you can either start the project indexed 1 or the project indexed 2.
+
+             Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
+
+             Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. You may assume all numbers in the input are non-negative integers.
  2. + +
  3. The length of Profits array and Capital array will not exceed 50,000.
  4. + +
  5. The answer is guaranteed to fit in a 32-bit signed integer.
  6. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0503.Next Greater Element II/README_EN.md b/assets/0500-0599/0503.Next Greater Element II/README_EN.md new file mode 100644 index 00000000..3b59a6ff --- /dev/null +++ b/assets/0500-0599/0503.Next Greater Element II/README_EN.md @@ -0,0 +1,105 @@ +# [503. Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii) + + + +## Description + +

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

+ +

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,1]
+Output: [2,-1,2]
+Explanation: The first 1's next greater number is 2; 
+The number 2 can't find next greater number. 
+The second 1's next greater number needs to search circularly, which is also 2.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4,3]
+Output: [2,3,4,-1,4]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + stack = [] + n = len(nums) + res = [-1] * n + for i in range(n << 1): + while stack and nums[stack[-1]] < nums[i % n]: + res[stack.pop()] = nums[i % n] + stack.append(i % n) + return res +``` + +### **Java** + +```java +class Solution { + public int[] nextGreaterElements(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + Arrays.fill(res, -1); + Deque stack = new ArrayDeque<>(); + for (int i = 0; i < (n << 1); ++i) { + while (!stack.isEmpty() && nums[stack.peek()] < nums[i % n]) { + res[stack.pop()] = nums[i % n]; + } + stack.push(i % n); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ + var nextGreaterElements = function(nums) { + let n = nums.length; + let stack = []; + let res = new Array(n).fill(-1); + for (let i = 0; i < 2 * n; i++) { + let cur = nums[i % n]; + while (stack.length > 0 && nums[stack[stack.length - 1]] < cur) { + res[stack.pop()] = cur; + } + stack.push(i % n); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0504.Base 7/README_EN.md b/assets/0500-0599/0504.Base 7/README_EN.md new file mode 100644 index 00000000..77694b1a --- /dev/null +++ b/assets/0500-0599/0504.Base 7/README_EN.md @@ -0,0 +1,67 @@ +# [504. Base 7](https://leetcode.com/problems/base-7) + + + +## Description + +

Given an integer, return its base 7 string representation.

+ + + +

Example 1:
+ +

+
+Input: 100
+
+Output: "202"
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: -7
+
+Output: "-10"
+
+
+ +

+ + + +

Note: + +The input will be in range of [-1e7, 1e7]. + +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0505.The Maze II/README_EN.md b/assets/0500-0599/0505.The Maze II/README_EN.md new file mode 100644 index 00000000..0d606bd3 --- /dev/null +++ b/assets/0500-0599/0505.The Maze II/README_EN.md @@ -0,0 +1,79 @@ +# [505. The Maze II](https://leetcode.com/problems/the-maze-ii) + + + +## Description + +

There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

+ +

Given the m x n maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return the shortest distance for the ball to stop at the destination. If the ball cannot stop at destination, return -1.

+ +

The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included).

+ +

You may assume that the borders of the maze are all walls (see examples).

+ +

 

+

Example 1:

+ +
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
+Output: 12
+Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.
+The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.
+
+ +

Example 2:

+ +
+Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
+Output: -1
+Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
+
+ +

Example 3:

+ +
+Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • m == maze.length
  • +
  • n == maze[i].length
  • +
  • 1 <= m, n <= 100
  • +
  • maze[i][j] is 0 or 1.
  • +
  • start.length == 2
  • +
  • destination.length == 2
  • +
  • 0 <= startrow, destinationrow <= m
  • +
  • 0 <= startcol, destinationcol <= n
  • +
  • Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
  • +
  • The maze contains at least 2 empty spaces.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0505.The Maze II/images/maze_1_example_1.png b/assets/0500-0599/0505.The Maze II/images/maze_1_example_1.png new file mode 100644 index 00000000..fe3fd795 Binary files /dev/null and b/assets/0500-0599/0505.The Maze II/images/maze_1_example_1.png differ diff --git a/assets/0500-0599/0505.The Maze II/images/maze_1_example_2.png b/assets/0500-0599/0505.The Maze II/images/maze_1_example_2.png new file mode 100644 index 00000000..4629d821 Binary files /dev/null and b/assets/0500-0599/0505.The Maze II/images/maze_1_example_2.png differ diff --git a/assets/0500-0599/0506.Relative Ranks/README_EN.md b/assets/0500-0599/0506.Relative Ranks/README_EN.md new file mode 100644 index 00000000..4f65f2d2 --- /dev/null +++ b/assets/0500-0599/0506.Relative Ranks/README_EN.md @@ -0,0 +1,70 @@ +# [506. Relative Ranks](https://leetcode.com/problems/relative-ranks) + + + +## Description + +

You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.

+ +

The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:

+ +
    +
  • The 1st place athlete's rank is "Gold Medal".
  • +
  • The 2nd place athlete's rank is "Silver Medal".
  • +
  • The 3rd place athlete's rank is "Bronze Medal".
  • +
  • For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").
  • +
+ +

Return an array answer of size n where answer[i] is the rank of the ith athlete.

+ +

 

+

Example 1:

+ +
+Input: score = [5,4,3,2,1]
+Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
+Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
+ +

Example 2:

+ +
+Input: score = [10,3,8,9,4]
+Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
+Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
+
+
+ +

 

+

Constraints:

+ +
    +
  • n == score.length
  • +
  • 1 <= n <= 104
  • +
  • 0 <= score[i] <= 106
  • +
  • All the values in score are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0507.Perfect Number/README_EN.md b/assets/0500-0599/0507.Perfect Number/README_EN.md new file mode 100644 index 00000000..a27d55dd --- /dev/null +++ b/assets/0500-0599/0507.Perfect Number/README_EN.md @@ -0,0 +1,79 @@ +# [507. Perfect Number](https://leetcode.com/problems/perfect-number) + + + +## Description + +

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.

+ +

Given an integer n, return true if n is a perfect number, otherwise return false.

+ +

 

+

Example 1:

+ +
+Input: num = 28
+Output: true
+Explanation: 28 = 1 + 2 + 4 + 7 + 14
+1, 2, 4, 7, and 14 are all divisors of 28.
+
+ +

Example 2:

+ +
+Input: num = 6
+Output: true
+
+ +

Example 3:

+ +
+Input: num = 496
+Output: true
+
+ +

Example 4:

+ +
+Input: num = 8128
+Output: true
+
+ +

Example 5:

+ +
+Input: num = 2
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= num <= 108
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md b/assets/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md new file mode 100644 index 00000000..5a3704be --- /dev/null +++ b/assets/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md @@ -0,0 +1,83 @@ +# [508. Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum) + + + +## Description + +

+ +Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. + +

+ + + +

Examples 1
+ +Input: + +

+
+  5
+
+ /  \
+
+2   -3
+
+
+ +return [2, -3, 4], since all the values happen only once, return all of them in any order. + +

+ + + +

Examples 2
+ +Input: + +

+
+  5
+
+ /  \
+
+2   -5
+
+
+ +return [2], since 2 happens twice, however -5 only occur once. + +

+ + + +

Note: + +You may assume the sum of values in any subtree is in the range of 32-bit signed integer. + +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0509.Fibonacci Number/README_EN.md b/assets/0500-0599/0509.Fibonacci Number/README_EN.md new file mode 100644 index 00000000..f9ccf065 --- /dev/null +++ b/assets/0500-0599/0509.Fibonacci Number/README_EN.md @@ -0,0 +1,135 @@ +# [509. Fibonacci Number](https://leetcode.com/problems/fibonacci-number) + + + +## Description + +

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

+ +
+F(0) = 0, F(1) = 1
+F(n) = F(n - 1) + F(n - 2), for n > 1.
+
+ +

Given n, calculate F(n).

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 1
+Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
+
+ +

Example 2:

+ +
+Input: n = 3
+Output: 2
+Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
+
+ +

Example 3:

+ +
+Input: n = 4
+Output: 3
+Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= n <= 30
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def fib(self, n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return a +``` + +### **Java** + +```java +class Solution { + public int fib(int n) { + int a = 0, b = 1; + while (n-- > 0) { + int c = a + b; + a = b; + b = c; + } + return a; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int fib(int n) { + int a = 0, b = 1; + while (n--) { + int c = a + b; + a = b; + b = c; + } + return a; + } +}; +``` + +### **Go** + +```go +func fib(n int) int { + a, b := 0, 1 + for i := 0; i < n; i++ { + a, b = b, a+b + } + return a +} +``` + +### **JavaScript** + + +```js +/** + * @param {number} n + * @return {number} + */ +var fib = function(n) { + let a = 0; + let b = 1; + while (n--) { + const c = a + b; + a = b; + b = c; + } + return a; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0510.Inorder Successor in BST II/README_EN.md b/assets/0500-0599/0510.Inorder Successor in BST II/README_EN.md new file mode 100644 index 00000000..9febb876 --- /dev/null +++ b/assets/0500-0599/0510.Inorder Successor in BST II/README_EN.md @@ -0,0 +1,95 @@ +# [510. Inorder Successor in BST II](https://leetcode.com/problems/inorder-successor-in-bst-ii) + + + +## Description + +

Given a node in a binary search tree, return the in-order successor of that node in the BST. If that node has no in-order successor, return null.

+ +

The successor of a node is the node with the smallest key greater than node.val.

+ +

You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for Node:

+ +
+class Node {
+    public int val;
+    public Node left;
+    public Node right;
+    public Node parent;
+}
+
+ +

 

+

Example 1:

+ +
+Input: tree = [2,1,3], node = 1
+Output: 2
+Explanation: 1's in-order successor node is 2. Note that both the node and the return value is of Node type.
+
+ +

Example 2:

+ +
+Input: tree = [5,3,6,2,4,null,null,1], node = 6
+Output: null
+Explanation: There is no in-order successor of the current node, so the answer is null.
+
+ +

Example 3:

+ +
+Input: tree = [15,6,18,3,7,17,20,2,4,null,13,null,null,null,null,null,null,null,null,9], node = 15
+Output: 17
+
+ +

Example 4:

+ +
+Input: tree = [15,6,18,3,7,17,20,2,4,null,13,null,null,null,null,null,null,null,null,9], node = 13
+Output: 15
+
+ +

Example 5:

+ +
+Input: tree = [0], node = 0
+Output: null
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -105 <= Node.val <= 105
  • +
  • All Nodes will have unique values.
  • +
+ +

 

+

Follow up: Could you solve it without looking up any of the node's values?

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_1.png b/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_1.png new file mode 100644 index 00000000..08361599 Binary files /dev/null and b/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_1.png differ diff --git a/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_2.png b/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_2.png new file mode 100644 index 00000000..b02f931a Binary files /dev/null and b/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_2.png differ diff --git a/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_34.png b/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_34.png new file mode 100644 index 00000000..ede45d44 Binary files /dev/null and b/assets/0500-0599/0510.Inorder Successor in BST II/images/285_example_34.png differ diff --git a/assets/0500-0599/0511.Game Play Analysis I/README_EN.md b/assets/0500-0599/0511.Game Play Analysis I/README_EN.md new file mode 100644 index 00000000..8165665a --- /dev/null +++ b/assets/0500-0599/0511.Game Play Analysis I/README_EN.md @@ -0,0 +1,62 @@ +# [511. Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i) + + + +## Description + +

Table: Activity

+ +
++--------------+---------+
+| Column Name  | Type    |
++--------------+---------+
+| player_id    | int     |
+| device_id    | int     |
+| event_date   | date    |
+| games_played | int     |
++--------------+---------+
+(player_id, event_date) is the primary key of this table.
+This table shows the activity of players of some game.
+Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
+
+ +

 

+ +

Write an SQL query that reports the first login date for each player.

+ +

The query result format is in the following example:

+ +
+Activity table:
++-----------+-----------+------------+--------------+
+| player_id | device_id | event_date | games_played |
++-----------+-----------+------------+--------------+
+| 1         | 2         | 2016-03-01 | 5            |
+| 1         | 2         | 2016-05-02 | 6            |
+| 2         | 3         | 2017-06-25 | 1            |
+| 3         | 1         | 2016-03-02 | 0            |
+| 3         | 4         | 2018-07-03 | 5            |
++-----------+-----------+------------+--------------+
+
+Result table:
++-----------+-------------+
+| player_id | first_login |
++-----------+-------------+
+| 1         | 2016-03-01  |
+| 2         | 2017-06-25  |
+| 3         | 2016-03-02  |
++-----------+-------------+
+
+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0512.Game Play Analysis II/README_EN.md b/assets/0500-0599/0512.Game Play Analysis II/README_EN.md new file mode 100644 index 00000000..4809d7f8 --- /dev/null +++ b/assets/0500-0599/0512.Game Play Analysis II/README_EN.md @@ -0,0 +1,61 @@ +# [512. Game Play Analysis II](https://leetcode.com/problems/game-play-analysis-ii) + + + +## Description + +

Table: Activity

+ +
++--------------+---------+
+| Column Name  | Type    |
++--------------+---------+
+| player_id    | int     |
+| device_id    | int     |
+| event_date   | date    |
+| games_played | int     |
++--------------+---------+
+(player_id, event_date) is the primary key of this table.
+This table shows the activity of players of some game.
+Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
+
+ +

 

+ +

Write a SQL query that reports the device that is first logged in for each player.

+ +

The query result format is in the following example:

+ +
+Activity table:
++-----------+-----------+------------+--------------+
+| player_id | device_id | event_date | games_played |
++-----------+-----------+------------+--------------+
+| 1         | 2         | 2016-03-01 | 5            |
+| 1         | 2         | 2016-05-02 | 6            |
+| 2         | 3         | 2017-06-25 | 1            |
+| 3         | 1         | 2016-03-02 | 0            |
+| 3         | 4         | 2018-07-03 | 5            |
++-----------+-----------+------------+--------------+
+
+Result table:
++-----------+-----------+
+| player_id | device_id |
++-----------+-----------+
+| 1         | 2         |
+| 2         | 3         |
+| 3         | 1         |
++-----------+-----------+
+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md b/assets/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md new file mode 100644 index 00000000..c03d7e12 --- /dev/null +++ b/assets/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md @@ -0,0 +1,107 @@ +# [513. Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value) + + + +## Description + +

Given the root of a binary tree, return the leftmost value in the last row of the tree.

+ +

 

+

Example 1:

+ +
+Input: root = [2,1,3]
+Output: 1
+
+ +

Example 2:

+ +
+Input: root = [1,2,3,4,null,5,6,null,null,7]
+Output: 7
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findBottomLeftValue(self, root: TreeNode) -> int: + res = 0 + q = collections.deque([root]) + while q: + res = q[0].val + n = len(q) + for _ in range(n): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int findBottomLeftValue(TreeNode root) { + Deque q = new ArrayDeque<>(); + q.offer(root); + int res = 0; + while (!q.isEmpty()) { + res = q.peek().val; + for (int i = 0, n = q.size(); i < n; ++i) { + TreeNode node = q.poll(); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0513.Find Bottom Left Tree Value/images/tree1.jpg b/assets/0500-0599/0513.Find Bottom Left Tree Value/images/tree1.jpg new file mode 100644 index 00000000..905159e8 Binary files /dev/null and b/assets/0500-0599/0513.Find Bottom Left Tree Value/images/tree1.jpg differ diff --git a/assets/0500-0599/0513.Find Bottom Left Tree Value/images/tree2.jpg b/assets/0500-0599/0513.Find Bottom Left Tree Value/images/tree2.jpg new file mode 100644 index 00000000..5624843d Binary files /dev/null and b/assets/0500-0599/0513.Find Bottom Left Tree Value/images/tree2.jpg differ diff --git a/assets/0500-0599/0514.Freedom Trail/README_EN.md b/assets/0500-0599/0514.Freedom Trail/README_EN.md new file mode 100644 index 00000000..a6769146 --- /dev/null +++ b/assets/0500-0599/0514.Freedom Trail/README_EN.md @@ -0,0 +1,72 @@ +# [514. Freedom Trail](https://leetcode.com/problems/freedom-trail) + + + +## Description + +

In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.

+ +

Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.

+ +

Initially, the first character of the ring is aligned at the "12:00" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the "12:00" direction and then by pressing the center button.

+ +

At the stage of rotating the ring to spell the key character key[i]:

+ +
    +
  1. You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the "12:00" direction, where this character must equal key[i].
  2. +
  3. If the character key[i] has been aligned at the "12:00" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.
  4. +
+ +

 

+

Example 1:

+ +
+Input: ring = "godding", key = "gd"
+Output: 4
+Explanation:
+For the first key character 'g', since it is already in place, we just need 1 step to spell this character. 
+For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
+Also, we need 1 more step for spelling.
+So the final output is 4.
+
+ +

Example 2:

+ +
+Input: ring = "godding", key = "godding"
+Output: 13
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= ring.length, key.length <= 100
  • +
  • ring and key consist of only lower case English letters.
  • +
  • It is guaranteed that key could always be spelled by rotating ring.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0514.Freedom Trail/images/ring.jpg b/assets/0500-0599/0514.Freedom Trail/images/ring.jpg new file mode 100644 index 00000000..96d75b07 Binary files /dev/null and b/assets/0500-0599/0514.Freedom Trail/images/ring.jpg differ diff --git a/assets/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md b/assets/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md new file mode 100644 index 00000000..05df04c2 --- /dev/null +++ b/assets/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md @@ -0,0 +1,139 @@ +# [515. Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row) + + + +## Description + +

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

+ +

 

+ +

 

+

Example 1:

+ +
+Input: root = [1,3,2,5,3,null,9]
+Output: [1,3,9]
+
+ +

Example 2:

+ +
+Input: root = [1,2,3]
+Output: [1,3]
+
+ +

Example 3:

+ +
+Input: root = [1]
+Output: [1]
+
+ +

Example 4:

+ +
+Input: root = [1,null,2]
+Output: [1,2]
+
+ +

Example 5:

+ +
+Input: root = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree will be in the range [0, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: TreeNode) -> List[int]: + if root is None: + return [] + q = collections.deque([root]) + res = [] + while q: + n = len(q) + t = float('-inf') + for _ in range(n): + node = q.popleft() + t = max(t, node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + res.append(t) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List largestValues(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Deque q = new ArrayDeque<>(); + q.offer(root); + List res = new ArrayList<>(); + while (!q.isEmpty()) { + int t = Integer.MIN_VALUE; + for (int i = 0, n = q.size(); i < n; ++i) { + TreeNode node = q.poll(); + t = Math.max(t, node.val); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + res.add(t); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0515.Find Largest Value in Each Tree Row/images/largest_e1.jpg b/assets/0500-0599/0515.Find Largest Value in Each Tree Row/images/largest_e1.jpg new file mode 100644 index 00000000..58851d9f Binary files /dev/null and b/assets/0500-0599/0515.Find Largest Value in Each Tree Row/images/largest_e1.jpg differ diff --git a/assets/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md b/assets/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md new file mode 100644 index 00000000..fe3ef1de --- /dev/null +++ b/assets/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md @@ -0,0 +1,59 @@ +# [516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence) + + + +## Description + +

Given a string s, find the longest palindromic subsequence's length in s.

+ +

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

+ +

 

+

Example 1:

+ +
+Input: s = "bbbab"
+Output: 4
+Explanation: One possible longest palindromic subsequence is "bbbb".
+
+ +

Example 2:

+ +
+Input: s = "cbbd"
+Output: 2
+Explanation: One possible longest palindromic subsequence is "bb".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s consists only of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0517.Super Washing Machines/README_EN.md b/assets/0500-0599/0517.Super Washing Machines/README_EN.md new file mode 100644 index 00000000..71be1fec --- /dev/null +++ b/assets/0500-0599/0517.Super Washing Machines/README_EN.md @@ -0,0 +1,125 @@ +# [517. Super Washing Machines](https://leetcode.com/problems/super-washing-machines) + + + +## Description + +

You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty. + +

+ + + +

For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time .

+ + + +

Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.

+ + + +

Example1 + +

+
+Input: [1,0,5]
+
+
+
+Output: 3
+
+
+
+Explanation: 
+
+1st move:    1     0 <-- 5    =>    1     1     4
+
+2nd move:    1 <-- 1 <-- 4    =>    2     1     3    
+
+3rd move:    2     1 <-- 3    =>    2     2     2   
+
+
+ + + +

Example2 + +

+
+Input: [0,3,0]
+
+
+
+Output: 2
+
+
+
+Explanation: 
+
+1st move:    0 <-- 3     0    =>    1     2     0    
+
+2nd move:    1     2 --> 0    =>    1     1     1     
+
+
+ + + +

Example3 + +

+
+Input: [0,2,0]
+
+
+
+Output: -1
+
+
+
+Explanation: 
+
+It's impossible to make all the three washing machines have the same number of dresses. 
+
+
+ + + +

+ + + +

Note:
+ +

    + +
  1. The range of n is [1, 10000].
  2. + +
  3. The range of dresses number in a super washing machine is [0, 1e5].
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0518.Coin Change 2/README_EN.md b/assets/0500-0599/0518.Coin Change 2/README_EN.md new file mode 100644 index 00000000..9d757c5f --- /dev/null +++ b/assets/0500-0599/0518.Coin Change 2/README_EN.md @@ -0,0 +1,168 @@ +# [518. Coin Change 2](https://leetcode.com/problems/coin-change-2) + + + +## Description + +

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

+ + + +
    + +
+ + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: amount = 5, coins = [1, 2, 5]
+
+Output: 4
+
+Explanation: there are four ways to make up the amount:
+
+5=5
+
+5=2+2+1
+
+5=2+1+1+1
+
+5=1+1+1+1+1
+
+
+ + + +

Example 2:

+ + + +
+
+Input: amount = 3, coins = [2]
+
+Output: 0
+
+Explanation: the amount of 3 cannot be made up just with coins of 2.
+
+
+ + + +

Example 3:

+ + + +
+
+Input: amount = 10, coins = [10]
+
+Output: 1
+
+
+ + + +

 

+ + + +

Note:

+ + + +

You can assume that

+ + + +
    +
  • 0 <= amount <= 5000
  • +
  • 1 <= coin <= 5000
  • +
  • the number of coins is less than 500
  • +
  • the answer is guaranteed to fit into signed 32-bit integer
  • +
+ + + +## Solutions + +Complete knapsack problem + + + +### **Python3** + +```python +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + dp = [0 for i in range(amount + 1)] + dp[0] = 1 + for coin in coins: + for j in range(coin, amount + 1): + dp[j] += dp[j - coin] + return dp[amount] +``` + +### **Java** + +```java +class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; + for (int coin : coins) { + for (int j = coin; j <= amount; j++) { + dp[j] += dp[j - coin]; + } + } + return dp[amount]; + } +} +``` + +### **TypeScript** + +```ts +function change(amount: number, coins: number[]): number { + let dp = new Array(amount + 1).fill(0); + dp[0] = 1; + for (let coin of coins) { + for (let i = coin; i <= amount; ++i) { + dp[i] += dp[i - coin]; + } + } + return dp.pop(); +}; +``` + +### **Go** + +```go +func change(amount int, coins []int) int { + dp := make([]int, amount+1) + dp[0] = 1 + for _, coin := range coins { + for j := coin; j <= amount; j++ { + dp[j] += dp[j-coin] + } + } + return dp[amount] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0519.Random Flip Matrix/README_EN.md b/assets/0500-0599/0519.Random Flip Matrix/README_EN.md new file mode 100644 index 00000000..9eff3cc8 --- /dev/null +++ b/assets/0500-0599/0519.Random Flip Matrix/README_EN.md @@ -0,0 +1,92 @@ +# [519. Random Flip Matrix](https://leetcode.com/problems/random-flip-matrix) + + + +## Description + +

You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all values are initially 0. Write a function flip which chooses a 0 value uniformly at random, changes it to 1, and then returns the position [row.id, col.id] of that value. Also, write a function reset which sets all values back to 0. Try to minimize the number of calls to system's Math.random() and optimize the time and space complexity.

+ + + +

Note:

+ + + +
    +
  1. 1 <= n_rows, n_cols <= 10000
  2. +
  3. 0 <= row.id < n_rows and 0 <= col.id < n_cols
  4. +
  5. flip will not be called when the matrix has no 0 values left.
  6. +
  7. the total number of calls to flip and reset will not exceed 1000.
  8. +
+ + + +

Example 1:

+ + + +
+
+Input: 
+
+["Solution","flip","flip","flip","flip"]
+
+[[2,3],[],[],[],[]]
+
+Output: [null,[0,1],[1,2],[1,0],[1,1]]
+
+
+ + + +
+ +

Example 2:

+ + + +
+
+Input: 
+
+["Solution","flip","flip","reset","flip"]
+
+[[1,2],[],[],[],[]]
+
+Output: [null,[0,0],[0,1],null,[0,0]]
+ +
+ + + +

Explanation of Input Syntax:

+ + + +

The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments, n_rows and n_colsflip and reset have no arguments. Arguments are always wrapped with a list, even if there aren't any.

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0520.Detect Capital/README_EN.md b/assets/0500-0599/0520.Detect Capital/README_EN.md new file mode 100644 index 00000000..a746fb75 --- /dev/null +++ b/assets/0500-0599/0520.Detect Capital/README_EN.md @@ -0,0 +1,91 @@ +# [520. Detect Capital](https://leetcode.com/problems/detect-capital) + + + +## Description + +

Given a word, you need to judge whether the usage of capitals in it is right or not.

+ + + +

We define the usage of capitals in a word to be right when one of the following cases holds:

+ + + +
    +
  1. All letters in this word are capitals, like "USA".
  2. +
  3. All letters in this word are not capitals, like "leetcode".
  4. +
  5. Only the first letter in this word is capital, like "Google".
  6. +
+ +Otherwise, we define that this word doesn't use capitals in a right way. + + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: "USA"
+
+Output: True
+
+
+ + + +

 

+ + + +

Example 2:

+ + + +
+
+Input: "FlaG"
+
+Output: False
+
+
+ + + +

 

+ + + +

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md b/assets/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md new file mode 100644 index 00000000..af5ae60a --- /dev/null +++ b/assets/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md @@ -0,0 +1,72 @@ +# [521. Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i) + + + +## Description + +

Given two strings a and b, find the length of the longest uncommon subsequence between them.

+ +

subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc""aeb", and "" (empty string).

+ +

An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.

+ +

Return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence doesn't exist, return -1.

+ +

 

+

Example 1:

+ +
+Input: a = "aba", b = "cdc"
+Output: 3
+Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
+Note that "cdc" is also a longest uncommon subsequence.
+
+ +

Example 2:

+ +
+Input: a = "aaa", b = "bbb"
+Output: 3
+Explanation: The longest uncommon subsequences are "aaa" and "bbb".
+
+ +

Example 3:

+ +
+Input: a = "aaa", b = "aaa"
+Output: -1
+Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= a.length, b.length <= 100
  • +
  • a and b consist of lower-case English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md b/assets/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md new file mode 100644 index 00000000..bce5a916 --- /dev/null +++ b/assets/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md @@ -0,0 +1,79 @@ +# [522. Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii) + + + +## Description + +

+ +Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings. + +

+ + + +

+ +A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. + +

+ + + +

+ +The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1. + +

+ + + +

Example 1:
+ +

+
+Input: "aba", "cdc", "eae"
+
+Output: 3
+
+
+ +

+ + + +

Note: + +

    + +
  1. All the given strings' lengths will not exceed 10.
  2. + +
  3. The length of the given list will be in the range of [2, 50].
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0523.Continuous Subarray Sum/README_EN.md b/assets/0500-0599/0523.Continuous Subarray Sum/README_EN.md new file mode 100644 index 00000000..25936f15 --- /dev/null +++ b/assets/0500-0599/0523.Continuous Subarray Sum/README_EN.md @@ -0,0 +1,69 @@ +# [523. Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum) + + + +## Description + +

Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.

+ +

An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.

+ +

 

+

Example 1:

+ +
+Input: nums = [23,2,4,6,7], k = 6
+Output: true
+Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
+
+ +

Example 2:

+ +
+Input: nums = [23,2,6,4,7], k = 6
+Output: true
+Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
+42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
+
+ +

Example 3:

+ +
+Input: nums = [23,2,6,4,7], k = 13
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 105
  • +
  • 0 <= nums[i] <= 109
  • +
  • 0 <= sum(nums[i]) <= 231 - 1
  • +
  • 1 <= k <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md b/assets/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md new file mode 100644 index 00000000..d4a09ebe --- /dev/null +++ b/assets/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md @@ -0,0 +1,57 @@ +# [524. Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting) + + + +## Description + +

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

+ +

 

+

Example 1:

+ +
+Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
+Output: "apple"
+
+ +

Example 2:

+ +
+Input: s = "abpcplea", dictionary = ["a","b","c"]
+Output: "a"
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • 1 <= dictionary.length <= 1000
  • +
  • 1 <= dictionary[i].length <= 1000
  • +
  • s and dictionary[i] consist of lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0525.Contiguous Array/README_EN.md b/assets/0500-0599/0525.Contiguous Array/README_EN.md new file mode 100644 index 00000000..f8780289 --- /dev/null +++ b/assets/0500-0599/0525.Contiguous Array/README_EN.md @@ -0,0 +1,73 @@ +# [525. Contiguous Array](https://leetcode.com/problems/contiguous-array) + + + +## Description + +

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

+ + + + + +

Example 1:
+ +

+
+Input: [0,1]
+
+Output: 2
+
+Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: [0,1,0]
+
+Output: 2
+
+Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
+
+
+ +

+ + + +

Note: + +The length of the given binary array will not exceed 50,000. + +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0526.Beautiful Arrangement/README_EN.md b/assets/0500-0599/0526.Beautiful Arrangement/README_EN.md new file mode 100644 index 00000000..402e44db --- /dev/null +++ b/assets/0500-0599/0526.Beautiful Arrangement/README_EN.md @@ -0,0 +1,68 @@ +# [526. Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement) + + + +## Description + +

Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:

+ +
    +
  • perm[i] is divisible by i.
  • +
  • i is divisible by perm[i].
  • +
+ +

Given an integer n, return the number of the beautiful arrangements that you can construct.

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 2
+Explanation: 
+The first beautiful arrangement is [1,2]:
+    - perm[1] = 1 is divisible by i = 1
+    - perm[2] = 2 is divisible by i = 2
+The second beautiful arrangement is [2,1]:
+    - perm[1] = 2 is divisible by i = 1
+    - i = 2 is divisible by perm[2] = 1
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 15
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0527.Word Abbreviation/README_EN.md b/assets/0500-0599/0527.Word Abbreviation/README_EN.md new file mode 100644 index 00000000..830369ee --- /dev/null +++ b/assets/0500-0599/0527.Word Abbreviation/README_EN.md @@ -0,0 +1,75 @@ +# [527. Word Abbreviation](https://leetcode.com/problems/word-abbreviation) + + + +## Description + +

Given an array of n distinct non-empty strings, you need to generate minimal possible abbreviations for every word following rules below.

+ + + +
    + +
  1. Begin with the first character and then the number of characters abbreviated, which followed by the last character.
  2. + +
  3. If there are any conflict, that is more than one words share the same abbreviation, a longer prefix is used instead of only the first character until making the map from word to abbreviation become unique. In other words, a final abbreviation cannot map to more than one original words.
  4. + +
  5. If the abbreviation doesn't make the word shorter, then keep it as original.
  6. + +
+ + + +

Example:
+ +

+
+Input: ["like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"]
+
+Output: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]
+
+
+ +

+ + + + + +Note: + +
    + +
  1. Both n and the length of each word will not exceed 400.
  2. + +
  3. The length of each word is greater than 1.
  4. + +
  5. The words consist of lowercase English letters only.
  6. + +
  7. The return answers should be in the same order as the original array.
  8. + +
+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0528.Random Pick with Weight/README_EN.md b/assets/0500-0599/0528.Random Pick with Weight/README_EN.md new file mode 100644 index 00000000..9d5aaad1 --- /dev/null +++ b/assets/0500-0599/0528.Random Pick with Weight/README_EN.md @@ -0,0 +1,87 @@ +# [528. Random Pick with Weight](https://leetcode.com/problems/random-pick-with-weight) + + + +## Description + +

You are given an array of positive integers w where w[i] describes the weight of ith index (0-indexed).

+ +

We need to call the function pickIndex() which randomly returns an integer in the range [0, w.length - 1]pickIndex() should return the integer proportional to its weight in the w array. For example, for w = [1, 3], the probability of picking the index 0 is 1 / (1 + 3) = 0.25 (i.e 25%) while the probability of picking the index 1 is 3 / (1 + 3) = 0.75 (i.e 75%).

+ +

More formally, the probability of picking index i is w[i] / sum(w).

+ +

 

+

Example 1:

+ +
+Input
+["Solution","pickIndex"]
+[[[1]],[]]
+Output
+[null,0]
+
+Explanation
+Solution solution = new Solution([1]);
+solution.pickIndex(); // return 0. Since there is only one single element on the array the only option is to return the first element.
+
+ +

Example 2:

+ +
+Input
+["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
+[[[1,3]],[],[],[],[],[]]
+Output
+[null,1,1,1,1,0]
+
+Explanation
+Solution solution = new Solution([1, 3]);
+solution.pickIndex(); // return 1. It's returning the second element (index = 1) that has probability of 3/4.
+solution.pickIndex(); // return 1
+solution.pickIndex(); // return 1
+solution.pickIndex(); // return 1
+solution.pickIndex(); // return 0. It's returning the first element (index = 0) that has probability of 1/4.
+
+Since this is a randomization problem, multiple answers are allowed so the following outputs can be considered correct :
+[null,1,1,1,1,0]
+[null,1,1,1,1,1]
+[null,1,1,1,0,0]
+[null,1,1,1,0,1]
+[null,1,0,1,0,0]
+......
+and so on.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= w.length <= 10000
  • +
  • 1 <= w[i] <= 10^5
  • +
  • pickIndex will be called at most 10000 times.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0529.Minesweeper/README_EN.md b/assets/0500-0599/0529.Minesweeper/README_EN.md new file mode 100644 index 00000000..afabfc0f --- /dev/null +++ b/assets/0500-0599/0529.Minesweeper/README_EN.md @@ -0,0 +1,163 @@ +# [529. Minesweeper](https://leetcode.com/problems/minesweeper) + + + +## Description + +

Let's play the minesweeper game (Wikipedia, online game)!

+ + + +

You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine.

+ + + +

Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:

+ + + +
    +
  1. If a mine ('M') is revealed, then the game is over - change it to 'X'.
  2. +
  3. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
  4. +
  5. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
  6. +
  7. Return the board when no more squares will be revealed.
  8. +
+ + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: 
+
+
+
+[['E', 'E', 'E', 'E', 'E'],
+
+ ['E', 'E', 'M', 'E', 'E'],
+
+ ['E', 'E', 'E', 'E', 'E'],
+
+ ['E', 'E', 'E', 'E', 'E']]
+
+
+
+Click : [3,0]
+
+
+
+Output: 
+
+
+
+[['B', '1', 'E', '1', 'B'],
+
+ ['B', '1', 'M', '1', 'B'],
+
+ ['B', '1', '1', '1', 'B'],
+
+ ['B', 'B', 'B', 'B', 'B']]
+
+
+
+Explanation:
+
+
+
+
+ + + +

Example 2:

+ + + +
+
+Input: 
+
+
+
+[['B', '1', 'E', '1', 'B'],
+
+ ['B', '1', 'M', '1', 'B'],
+
+ ['B', '1', '1', '1', 'B'],
+
+ ['B', 'B', 'B', 'B', 'B']]
+
+
+
+Click : [1,2]
+
+
+
+Output: 
+
+
+
+[['B', '1', 'E', '1', 'B'],
+
+ ['B', '1', 'X', '1', 'B'],
+
+ ['B', '1', '1', '1', 'B'],
+
+ ['B', 'B', 'B', 'B', 'B']]
+
+
+
+Explanation:
+
+
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. The range of the input matrix's height and width is [1,50].
  2. +
  3. The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square.
  4. +
  5. The input board won't be a stage when game is over (some mines have been revealed).
  6. +
  7. For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.
  8. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0529.Minesweeper/images/minesweeper_example_1.png b/assets/0500-0599/0529.Minesweeper/images/minesweeper_example_1.png new file mode 100644 index 00000000..6c0258b1 Binary files /dev/null and b/assets/0500-0599/0529.Minesweeper/images/minesweeper_example_1.png differ diff --git a/assets/0500-0599/0529.Minesweeper/images/minesweeper_example_2.png b/assets/0500-0599/0529.Minesweeper/images/minesweeper_example_2.png new file mode 100644 index 00000000..85c8eb51 Binary files /dev/null and b/assets/0500-0599/0529.Minesweeper/images/minesweeper_example_2.png differ diff --git a/assets/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md b/assets/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md new file mode 100644 index 00000000..4bb5ab2e --- /dev/null +++ b/assets/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md @@ -0,0 +1,106 @@ +# [530. Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst) + + + +## Description + +

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

+ +

Example:

+ +
+Input:
+
+   1
+    \
+     3
+    /
+   2
+
+Output:
+1
+
+Explanation:
+The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
+
+ +

 

+ +

Note:

+ + + + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def getMinimumDifference(self, root: TreeNode) -> int: + def inorder(root): + if not root: + return + inorder(root.left) + if self.pre is not None: + self.min_diff = min(self.min_diff, abs(root.val - self.pre)) + self.pre = root.val + inorder(root.right) + + self.pre = None + self.min_diff = 10 ** 5 + inorder(root) + return self.min_diff +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + + private int minDiff = Integer.MAX_VALUE; + private Integer pre; + + public int getMinimumDifference(TreeNode root) { + inorder(root); + return minDiff; + } + + private void inorder(TreeNode root) { + if (root == null) return; + inorder(root.left); + if (pre != null) minDiff = Math.min(minDiff, Math.abs(root.val - pre)); + pre = root.val; + inorder(root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0531.Lonely Pixel I/README_EN.md b/assets/0500-0599/0531.Lonely Pixel I/README_EN.md new file mode 100644 index 00000000..979f404c --- /dev/null +++ b/assets/0500-0599/0531.Lonely Pixel I/README_EN.md @@ -0,0 +1,60 @@ +# [531. Lonely Pixel I](https://leetcode.com/problems/lonely-pixel-i) + + + +## Description + +

Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels.

+ +

A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.

+ +

 

+

Example 1:

+ +
+Input: picture = [["W","W","B"],["W","B","W"],["B","W","W"]]
+Output: 3
+Explanation: All the three 'B's are black lonely pixels.
+
+ +

Example 2:

+ +
+Input: picture = [["B","B","B"],["B","B","B"],["B","B","B"]]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • m == picture.length
  • +
  • n == picture[i].length
  • +
  • 1 <= m, n <= 500
  • +
  • picture[i][j] is 'W' or 'B'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0531.Lonely Pixel I/images/pixel1.jpg b/assets/0500-0599/0531.Lonely Pixel I/images/pixel1.jpg new file mode 100644 index 00000000..f985d8cb Binary files /dev/null and b/assets/0500-0599/0531.Lonely Pixel I/images/pixel1.jpg differ diff --git a/assets/0500-0599/0531.Lonely Pixel I/images/pixel2.jpg b/assets/0500-0599/0531.Lonely Pixel I/images/pixel2.jpg new file mode 100644 index 00000000..ec3f5870 Binary files /dev/null and b/assets/0500-0599/0531.Lonely Pixel I/images/pixel2.jpg differ diff --git a/assets/0500-0599/0532.K-diff Pairs in an Array/README_EN.md b/assets/0500-0599/0532.K-diff Pairs in an Array/README_EN.md new file mode 100644 index 00000000..e6fd36b7 --- /dev/null +++ b/assets/0500-0599/0532.K-diff Pairs in an Array/README_EN.md @@ -0,0 +1,91 @@ +# [532. K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array) + + + +## Description + +

Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.

+ +

A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:

+ +
    +
  • 0 <= i, j < nums.length
  • +
  • i != j
  • +
  • |nums[i] - nums[j]| == k
  • +
+ +

Notice that |val| denotes the absolute value of val.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,1,4,1,5], k = 2
+Output: 2
+Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
+Although we have two 1s in the input, we should only return the number of unique pairs.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4,5], k = 1
+Output: 4
+Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
+
+ +

Example 3:

+ +
+Input: nums = [1,3,1,5,4], k = 0
+Output: 1
+Explanation: There is one 0-diff pair in the array, (1, 1).
+
+ +

Example 4:

+ +
+Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3
+Output: 2
+
+ +

Example 5:

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

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -107 <= nums[i] <= 107
  • +
  • 0 <= k <= 107
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0533.Lonely Pixel II/README_EN.md b/assets/0500-0599/0533.Lonely Pixel II/README_EN.md new file mode 100644 index 00000000..1aca66a3 --- /dev/null +++ b/assets/0500-0599/0533.Lonely Pixel II/README_EN.md @@ -0,0 +1,107 @@ +# [533. Lonely Pixel II](https://leetcode.com/problems/lonely-pixel-ii) + + + +## Description + +

Given a picture consisting of black and white pixels, and a positive integer N, find the number of black pixels located at some specific row R and column C that align with all the following rules:

+ + + +
    + +
  1. Row R and column C both contain exactly N black pixels.
  2. + +
  3. For all rows that have a black pixel at column C, they should be exactly the same as row R
  4. + +
+ + + +

The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.

+ + + +

Example:
+ +

+
+Input:                                            
+
+[['W', 'B', 'W', 'B', 'B', 'W'],    
+
+ ['W', 'B', 'W', 'B', 'B', 'W'],    
+
+ ['W', 'B', 'W', 'B', 'B', 'W'],    
+
+ ['W', 'W', 'B', 'W', 'B', 'W']] 
+
+
+
+N = 3
+
+Output: 6
+
+Explanation: All the bold 'B' are the black pixels we need (all 'B's at column 1 and 3).
+
+        0    1    2    3    4    5         column index                                            
+
+0    [['W', 'B', 'W', 'B', 'B', 'W'],    
+
+1     ['W', 'B', 'W', 'B', 'B', 'W'],    
+
+2     ['W', 'B', 'W', 'B', 'B', 'W'],    
+
+3     ['W', 'W', 'B', 'W', 'B', 'W']]    
+
+row index
+
+
+
+Take 'B' at row R = 0 and column C = 1 as an example:
+
+Rule 1, row R = 0 and column C = 1 both have exactly N = 3 black pixels. 
+
+Rule 2, the rows have black pixel at column C = 1 are row 0, row 1 and row 2. They are exactly the same as row R = 0.
+
+
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The range of width and height of the input 2D array is [1,200].
  2. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0534.Game Play Analysis III/README_EN.md b/assets/0500-0599/0534.Game Play Analysis III/README_EN.md new file mode 100644 index 00000000..f32ba525 --- /dev/null +++ b/assets/0500-0599/0534.Game Play Analysis III/README_EN.md @@ -0,0 +1,67 @@ +# [534. Game Play Analysis III](https://leetcode.com/problems/game-play-analysis-iii) + + + +## Description + +

Table: Activity

+ +
++--------------+---------+
+| Column Name  | Type    |
++--------------+---------+
+| player_id    | int     |
+| device_id    | int     |
+| event_date   | date    |
+| games_played | int     |
++--------------+---------+
+(player_id, event_date) is the primary key of this table.
+This table shows the activity of players of some game.
+Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
+
+ +

 

+ +

Write an SQL query that reports for each player and date, how many games played so far by the player. That is, the total number of games played by the player until that date. Check the example for clarity.

+ +

The query result format is in the following example:

+ +
+Activity table:
++-----------+-----------+------------+--------------+
+| player_id | device_id | event_date | games_played |
++-----------+-----------+------------+--------------+
+| 1         | 2         | 2016-03-01 | 5            |
+| 1         | 2         | 2016-05-02 | 6            |
+| 1         | 3         | 2017-06-25 | 1            |
+| 3         | 1         | 2016-03-02 | 0            |
+| 3         | 4         | 2018-07-03 | 5            |
++-----------+-----------+------------+--------------+
+
+Result table:
++-----------+------------+---------------------+
+| player_id | event_date | games_played_so_far |
++-----------+------------+---------------------+
+| 1         | 2016-03-01 | 5                   |
+| 1         | 2016-05-02 | 11                  |
+| 1         | 2017-06-25 | 12                  |
+| 3         | 2016-03-02 | 0                   |
+| 3         | 2018-07-03 | 5                   |
++-----------+------------+---------------------+
+For the player with id 1, 5 + 6 = 11 games played by 2016-05-02, and 5 + 6 + 1 = 12 games played by 2017-06-25.
+For the player with id 3, 0 + 5 = 5 games played by 2018-07-03.
+Note that for each player we only care about the days when the player logged in.
+
+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0535.Encode and Decode TinyURL/README_EN.md b/assets/0500-0599/0535.Encode and Decode TinyURL/README_EN.md new file mode 100644 index 00000000..828e56e3 --- /dev/null +++ b/assets/0500-0599/0535.Encode and Decode TinyURL/README_EN.md @@ -0,0 +1,78 @@ +# [535. Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl) + + + +## Description + +
Note: This is a companion problem to the System Design problem: Design TinyURL.
+ +

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

+ +

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

+ +## Solutions + + + +### **Python3** + +```python +class Codec: + def __init__(self): + self.code_url = {} + self.count = 0 + self.prefix_url = 'http://tinyurl.com/' + + def encode(self, longUrl: str) -> str: + """Encodes a URL to a shortened URL. + """ + self.count += 1 + code = str(hex(self.count))[2:] + self.code_url[code] = longUrl + return self.prefix_url + code + + def decode(self, shortUrl: str) -> str: + """Decodes a shortened URL to its original URL. + """ + code = shortUrl.replace(self.prefix_url, '') + return self.code_url[code] + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(url)) +``` + +### **Java** + +```java +public class Codec { + private Map code2Url = new HashMap<>(); + private int count = 0; + private static final String prefixUrl = "http://tinyurl.com/"; + + // Encodes a URL to a shortened URL. + public String encode(String longUrl) { + String code = Integer.toHexString(++count); + code2Url.put(code, longUrl); + return prefixUrl + code; + } + + // Decodes a shortened URL to its original URL. + public String decode(String shortUrl) { + String code = shortUrl.replace(prefixUrl, ""); + return code2Url.get(code); + } +} + +// Your Codec object will be instantiated and called as such: +// Codec codec = new Codec(); +// codec.decode(codec.encode(url)); +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0536.Construct Binary Tree from String/README_EN.md b/assets/0500-0599/0536.Construct Binary Tree from String/README_EN.md new file mode 100644 index 00000000..1a584e89 --- /dev/null +++ b/assets/0500-0599/0536.Construct Binary Tree from String/README_EN.md @@ -0,0 +1,66 @@ +# [536. Construct Binary Tree from String](https://leetcode.com/problems/construct-binary-tree-from-string) + + + +## Description + +

You need to construct a binary tree from a string consisting of parenthesis and integers.

+ +

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

+ +

You always start to construct the left child node of the parent first if it exists.

+ +

 

+

Example 1:

+ +
+Input: s = "4(2(3)(1))(6(5))"
+Output: [4,2,6,3,1,5]
+
+ +

Example 2:

+ +
+Input: s = "4(2(3)(1))(6(5)(7))"
+Output: [4,2,6,3,1,5,7]
+
+ +

Example 3:

+ +
+Input: s = "-4(2(3)(1))(6(5)(7))"
+Output: [-4,2,6,3,1,5,7]
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= s.length <= 3 * 104
  • +
  • s consists of digits, '(', ')', and '-' only.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0536.Construct Binary Tree from String/images/butree.jpg b/assets/0500-0599/0536.Construct Binary Tree from String/images/butree.jpg new file mode 100644 index 00000000..5cb2b5a8 Binary files /dev/null and b/assets/0500-0599/0536.Construct Binary Tree from String/images/butree.jpg differ diff --git a/assets/0500-0599/0537.Complex Number Multiplication/README_EN.md b/assets/0500-0599/0537.Complex Number Multiplication/README_EN.md new file mode 100644 index 00000000..c1074572 --- /dev/null +++ b/assets/0500-0599/0537.Complex Number Multiplication/README_EN.md @@ -0,0 +1,87 @@ +# [537. Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication) + + + +## Description + +

+ +Given two strings representing two complex numbers.

+ + + +

+ +You need to return a string representing their multiplication. Note i2 = -1 according to the definition. + +

+ + + +

Example 1:
+ +

+
+Input: "1+1i", "1+1i"
+
+Output: "0+2i"
+
+Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: "1+-1i", "1+-1i"
+
+Output: "0+-2i"
+
+Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
+
+
+ +

+ + + +

Note: + +

    + +
  1. The input strings will not have extra blank.
  2. + +
  3. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0538.Convert BST to Greater Tree/README_EN.md b/assets/0500-0599/0538.Convert BST to Greater Tree/README_EN.md new file mode 100644 index 00000000..2298122c --- /dev/null +++ b/assets/0500-0599/0538.Convert BST to Greater Tree/README_EN.md @@ -0,0 +1,120 @@ +# [538. Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree) + + + +## Description + +

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

+ + + +

As a reminder, a binary search tree is a tree that satisfies these constraints:

+ + + +
    +
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • +
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • +
  • Both the left and right subtrees must also be binary search trees.
  • +
+ + + +

Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/

+ + + +

 

+ +

Example 1:

+ + + +
+
+Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
+
+Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
+
+
+ + + +

Example 2:

+ + + +
+
+Input: root = [0,null,1]
+
+Output: [1,null,1]
+
+
+ + + +

Example 3:

+ + + +
+
+Input: root = [1,0,2]
+
+Output: [3,3,2]
+
+
+ + + +

Example 4:

+ + + +
+
+Input: root = [3,2,4,1]
+
+Output: [7,9,4,10]
+
+
+ + + +

 

+ +

Constraints:

+ + + +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -104 <= Node.val <= 104
  • +
  • All the values in the tree are unique.
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0538.Convert BST to Greater Tree/images/tree.png b/assets/0500-0599/0538.Convert BST to Greater Tree/images/tree.png new file mode 100644 index 00000000..a26e4360 Binary files /dev/null and b/assets/0500-0599/0538.Convert BST to Greater Tree/images/tree.png differ diff --git a/assets/0500-0599/0539.Minimum Time Difference/README_EN.md b/assets/0500-0599/0539.Minimum Time Difference/README_EN.md new file mode 100644 index 00000000..c932945d --- /dev/null +++ b/assets/0500-0599/0539.Minimum Time Difference/README_EN.md @@ -0,0 +1,47 @@ +# [539. Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference) + + + +## Description + +Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list. +

 

+

Example 1:

+
Input: timePoints = ["23:59","00:00"]
+Output: 1
+

Example 2:

+
Input: timePoints = ["00:00","23:59","00:00"]
+Output: 0
+
+

 

+

Constraints:

+ +
    +
  • 2 <= timePoints <= 2 * 104
  • +
  • timePoints[i] is in the format "HH:MM".
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0540.Single Element in a Sorted Array/README_EN.md b/assets/0500-0599/0540.Single Element in a Sorted Array/README_EN.md new file mode 100644 index 00000000..a58c4378 --- /dev/null +++ b/assets/0500-0599/0540.Single Element in a Sorted Array/README_EN.md @@ -0,0 +1,129 @@ +# [540. Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array) + + + +## Description + +

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

+ + + +

Follow up: Your solution should run in O(log n) time and O(1) space.

+ + + +

 

+ +

Example 1:

+ +
Input: nums = [1,1,2,3,3,4,4,8,8]
+
+Output: 2
+
+

Example 2:

+ +
Input: nums = [3,3,7,7,10,11,11]
+
+Output: 10
+
+
+ +

 

+ +

Constraints:

+ + + +
    +
  • 1 <= nums.length <= 10^5
  • +
  • 0 <= nums[i] <= 10^5
  • +
+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def singleNonDuplicate(self, nums: List[int]) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if (mid & 1) == 1: + mid -= 1 + if nums[mid] == nums[mid + 1]: + left = mid + 2 + else: + right = mid + return nums[left] +``` + +### **Java** + +```java +class Solution { + public int singleNonDuplicate(int[] nums) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >>> 1; + if ((mid & 1) == 1) { + --mid; + } + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } + return nums[left]; + } +} +``` + +### **TypeScript** + +```ts +function singleNonDuplicate(nums: number[]): number { + let left = 0, right = nums.length - 1; + while (left < right) { + let mid = (left + right) >> 1; + if ((mid & 1) == 1) --mid; + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } + return nums[left]; +}; +``` + +### **Go** + +```go +func singleNonDuplicate(nums []int) int { + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if (mid & 1) == 1 { + mid-- + } + if nums[mid] == nums[mid+1] { + left = mid + 2 + } else { + right = mid + } + } + return nums[left] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0541.Reverse String II/README_EN.md b/assets/0500-0599/0541.Reverse String II/README_EN.md new file mode 100644 index 00000000..3e44e6bd --- /dev/null +++ b/assets/0500-0599/0541.Reverse String II/README_EN.md @@ -0,0 +1,51 @@ +# [541. Reverse String II](https://leetcode.com/problems/reverse-string-ii) + + + +## Description + +

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

+ +

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

+ +

 

+

Example 1:

+
Input: s = "abcdefg", k = 2
+Output: "bacdfeg"
+

Example 2:

+
Input: s = "abcd", k = 2
+Output: "bacd"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 104
  • +
  • s consists of only lowercase English letters.
  • +
  • 1 <= k <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0542.01 Matrix/README_EN.md b/assets/0500-0599/0542.01 Matrix/README_EN.md new file mode 100644 index 00000000..47fc31b9 --- /dev/null +++ b/assets/0500-0599/0542.01 Matrix/README_EN.md @@ -0,0 +1,113 @@ +# [542. 01 Matrix](https://leetcode.com/problems/01-matrix) + + + +## Description + +

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

+ + + +

The distance between two adjacent cells is 1.

+ + + +

 

+ + + +

Example 1:

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

Example 2:

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

 

+ + + +

Note:

+ + + +
    +
  1. The number of elements of the given matrix will not exceed 10,000.
  2. +
  3. There are at least one 0 in the given matrix.
  4. +
  5. The cells are adjacent in only four directions: up, down, left and right.
  6. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0543.Diameter of Binary Tree/README_EN.md b/assets/0500-0599/0543.Diameter of Binary Tree/README_EN.md new file mode 100644 index 00000000..e2139cf2 --- /dev/null +++ b/assets/0500-0599/0543.Diameter of Binary Tree/README_EN.md @@ -0,0 +1,60 @@ +# [543. Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree) + + + +## Description + +

Given the root of a binary tree, return the length of the diameter of the tree.

+ +

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

+ +

The length of a path between two nodes is represented by the number of edges between them.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,4,5]
+Output: 3
+Explanation: 3is the length of the path [4,2,1,3] or [5,2,1,3].
+
+ +

Example 2:

+ +
+Input: root = [1,2]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0543.Diameter of Binary Tree/images/diamtree.jpg b/assets/0500-0599/0543.Diameter of Binary Tree/images/diamtree.jpg new file mode 100644 index 00000000..cdb3fc71 Binary files /dev/null and b/assets/0500-0599/0543.Diameter of Binary Tree/images/diamtree.jpg differ diff --git a/assets/0500-0599/0544.Output Contest Matches/README_EN.md b/assets/0500-0599/0544.Output Contest Matches/README_EN.md new file mode 100644 index 00000000..8b4014cf --- /dev/null +++ b/assets/0500-0599/0544.Output Contest Matches/README_EN.md @@ -0,0 +1,121 @@ +# [544. Output Contest Matches](https://leetcode.com/problems/output-contest-matches) + + + +## Description + +

+ +During the NBA playoffs, we always arrange the rather strong team to play with the rather weak team, like make the rank 1 team play with the rank nth team, which is a good strategy to make the contest more interesting. Now, you're given n teams, you need to output their final contest matches in the form of a string. + +

+ + + +

The n teams are given in the form of positive integers from 1 to n, which represents their initial rank. (Rank 1 is the strongest team and Rank n is the weakest team.) We'll use parentheses('(', ')') and commas(',') to represent the contest team pairing - parentheses('(' , ')') for pairing and commas(',') for partition. During the pairing process in each round, you always need to follow the strategy of making the rather strong one pair with the rather weak one.

+ + + +

Example 1:
+ +

+
+Input: 2
+
+Output: (1,2)
+
+Explanation: 
+
+Initially, we have the team 1 and the team 2, placed like: 1,2.
+
+Then we pair the team (1,2) together with '(', ')' and ',', which is the final answer.
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: 4
+
+Output: ((1,4),(2,3))
+
+Explanation: 
+
+In the first round, we pair the team 1 and 4, the team 2 and 3 together, as we need to make the strong team and weak team together.
+
+And we got (1,4),(2,3).
+
+In the second round, the winners of (1,4) and (2,3) need to play again to generate the final winner, so you need to add the paratheses outside them.
+
+And we got the final answer ((1,4),(2,3)).
+
+
+ +

+ + + +

Example 3:
+ +

+
+Input: 8
+
+Output: (((1,8),(4,5)),((2,7),(3,6)))
+
+Explanation: 
+
+First round: (1,8),(2,7),(3,6),(4,5)
+
+Second round: ((1,8),(4,5)),((2,7),(3,6))
+
+Third round: (((1,8),(4,5)),((2,7),(3,6)))
+
+Since the third round will generate the final winner, you need to output the answer (((1,8),(4,5)),((2,7),(3,6))).
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The n is in range [2, 212].
  2. + +
  3. We ensure that the input n can be converted into the form 2k, where k is a positive integer.
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0545.Boundary of Binary Tree/README_EN.md b/assets/0500-0599/0545.Boundary of Binary Tree/README_EN.md new file mode 100644 index 00000000..f01b0b50 --- /dev/null +++ b/assets/0500-0599/0545.Boundary of Binary Tree/README_EN.md @@ -0,0 +1,205 @@ +# [545. Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree) + + + +## Description + +

The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered from left-to-right, and the reverse order of the right boundary.

+ +

The left boundary is the set of nodes defined by the following:

+ +
    +
  • The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is empty.
  • +
  • If a node in the left boundary and has a left child, then the left child is in the left boundary.
  • +
  • If a node is in the left boundary, has no left child, but has a right child, then the right child is in the left boundary.
  • +
  • The leftmost leaf is not in the left boundary.
  • +
+ +

The right boundary is similar to the left boundary, except it is the right side of the root's right subtree. Again, the leaf is not part of the right boundary, and the right boundary is empty if the root does not have a right child.

+ +

The leaves are nodes that do not have any children. For this problem, the root is not a leaf.

+ +

Given the root of a binary tree, return the values of its boundary.

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,2,3,4]
+Output: [1,3,4,2]
+Explanation:
+- The left boundary is empty because the root does not have a left child.
+- The right boundary follows the path starting from the root's right child 2 -> 4.
+  4 is a leaf, so the right boundary is [2].
+- The leaves from left to right are [3,4].
+Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2].
+
+ +

Example 2:

+ +
+Input: root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
+Output: [1,2,4,7,8,9,10,6,3]
+Explanation:
+- The left boundary follows the path starting from the root's left child 2 -> 4.
+  4 is a leaf, so the left boundary is [2].
+- The right boundary follows the path starting from the root's right child 3 -> 6 -> 10.
+  10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3].
+- The leaves from left to right are [4,7,8,9,10].
+Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3].
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]: + self.res = [] + if not root: + return self.res + # root + if not self.is_leaf(root): + self.res.append(root.val) + + # left boundary + t = root.left + while t: + if not self.is_leaf(t): + self.res.append(t.val) + t = t.left if t.left else t.right + + # leaves + self.add_leaves(root) + + # right boundary(reverse order) + s = [] + t = root.right + while t: + if not self.is_leaf(t): + s.append(t.val) + t = t.right if t.right else t.left + while s: + self.res.append(s.pop()) + + # output + return self.res + + def add_leaves(self, root): + if self.is_leaf(root): + self.res.append(root.val) + return + if root.left: + self.add_leaves(root.left) + if root.right: + self.add_leaves(root.right) + + def is_leaf(self, node) -> bool: + return node and node.left is None and node.right is None + +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List res; + + public List boundaryOfBinaryTree(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + res = new ArrayList<>(); + + // root + if (!isLeaf(root)) { + res.add(root.val); + } + + // left boundary + TreeNode t = root.left; + while (t != null) { + if (!isLeaf(t)) { + res.add(t.val); + } + t = t.left == null ? t.right : t.left; + } + + // leaves + addLeaves(root); + + // right boundary(reverse order) + Deque s = new ArrayDeque<>(); + t = root.right; + while (t != null) { + if (!isLeaf(t)) { + s.offer(t.val); + } + t = t.right == null ? t.left : t.right; + } + while (!s.isEmpty()) { + res.add(s.pollLast()); + } + + // output + return res; + } + + private void addLeaves(TreeNode root) { + if (isLeaf(root)) { + res.add(root.val); + return; + } + if (root.left != null) { + addLeaves(root.left); + } + if (root.right != null) { + addLeaves(root.right); + } + } + + private boolean isLeaf(TreeNode node) { + return node != null && node.left == null && node.right == null; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0545.Boundary of Binary Tree/images/boundary1.jpg b/assets/0500-0599/0545.Boundary of Binary Tree/images/boundary1.jpg new file mode 100644 index 00000000..123147c3 Binary files /dev/null and b/assets/0500-0599/0545.Boundary of Binary Tree/images/boundary1.jpg differ diff --git a/assets/0500-0599/0545.Boundary of Binary Tree/images/boundary2.jpg b/assets/0500-0599/0545.Boundary of Binary Tree/images/boundary2.jpg new file mode 100644 index 00000000..aef83b4c Binary files /dev/null and b/assets/0500-0599/0545.Boundary of Binary Tree/images/boundary2.jpg differ diff --git a/assets/0500-0599/0546.Remove Boxes/README_EN.md b/assets/0500-0599/0546.Remove Boxes/README_EN.md new file mode 100644 index 00000000..2be63905 --- /dev/null +++ b/assets/0500-0599/0546.Remove Boxes/README_EN.md @@ -0,0 +1,72 @@ +# [546. Remove Boxes](https://leetcode.com/problems/remove-boxes) + + + +## Description + +

You are given several boxes with different colors represented by different positive numbers.

+ +

You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points.

+ +

Return the maximum points you can get.

+ +

 

+

Example 1:

+ +
+Input: boxes = [1,3,2,2,2,3,4,3,1]
+Output: 23
+Explanation:
+[1, 3, 2, 2, 2, 3, 4, 3, 1] 
+----> [1, 3, 3, 4, 3, 1] (3*3=9 points) 
+----> [1, 3, 3, 3, 1] (1*1=1 points) 
+----> [1, 1] (3*3=9 points) 
+----> [] (2*2=4 points)
+
+ +

Example 2:

+ +
+Input: boxes = [1,1,1]
+Output: 9
+
+ +

Example 3:

+ +
+Input: boxes = [1]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= boxes.length <= 100
  • +
  • 1 <= boxes[i] <= 100
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0547.Number of Provinces/README_EN.md b/assets/0500-0599/0547.Number of Provinces/README_EN.md new file mode 100644 index 00000000..a1defd82 --- /dev/null +++ b/assets/0500-0599/0547.Number of Provinces/README_EN.md @@ -0,0 +1,102 @@ +# [547. Number of Provinces](https://leetcode.com/problems/number-of-provinces) + + + +## Description + +

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.

+ +

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

+ +

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

+ +

Return the total number of provinces.

+ +

 

+

Example 1:

+ +
+Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
+Output: 2
+
+ +

Example 2:

+ +
+Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
+Output: 3
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 200
  • +
  • n == isConnected.length
  • +
  • n == isConnected[i].length
  • +
  • isConnected[i][j] is 1 or 0.
  • +
  • isConnected[i][i] == 1
  • +
  • isConnected[i][j] == isConnected[j][i]
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def dfs(i): + for j in range(n): + if not visited[j] and isConnected[i][j] == 1: + visited[j] = True + dfs(j) + + n = len(isConnected) + visited = [False] * n + num = 0 + for i in range(n): + if not visited[i]: + dfs(i) + num += 1 + return num +``` + +### **Java** + +```java +class Solution { + public int findCircleNum(int[][] isConnected) { + int n = isConnected.length; + boolean[] visited = new boolean[n]; + int num = 0; + for (int i = 0; i < n; ++i) { + if (!visited[i]) { + dfs(isConnected, visited, i, n); + ++num; + } + } + return num; + } + + private void dfs(int[][] isConnected, boolean[] visited, int i, int n) { + for (int j = 0; j < n; ++j) { + if (!visited[j] && isConnected[i][j] == 1) { + visited[j] = true; + dfs(isConnected, visited, j, n); + } + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0547.Number of Provinces/images/graph1.jpg b/assets/0500-0599/0547.Number of Provinces/images/graph1.jpg new file mode 100644 index 00000000..bb9ef400 Binary files /dev/null and b/assets/0500-0599/0547.Number of Provinces/images/graph1.jpg differ diff --git a/assets/0500-0599/0547.Number of Provinces/images/graph2.jpg b/assets/0500-0599/0547.Number of Provinces/images/graph2.jpg new file mode 100644 index 00000000..6358db1f Binary files /dev/null and b/assets/0500-0599/0547.Number of Provinces/images/graph2.jpg differ diff --git a/assets/0500-0599/0548.Split Array with Equal Sum/README_EN.md b/assets/0500-0599/0548.Split Array with Equal Sum/README_EN.md new file mode 100644 index 00000000..6a6be92f --- /dev/null +++ b/assets/0500-0599/0548.Split Array with Equal Sum/README_EN.md @@ -0,0 +1,83 @@ +# [548. Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum) + + + +## Description + +

+ +Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions: + +

    + +
  1. 0 < i, i + 1 < j, j + 1 < k < n - 1
  2. + +
  3. Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal.
  4. + +
+ +where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R. + +

+ + + +

Example:
+ +

+
+Input: [1,2,1,2,1,2,1]
+
+Output: True
+
+Explanation:
+
+i = 1, j = 3, k = 5. 
+
+sum(0, i - 1) = sum(0, 0) = 1
+
+sum(i + 1, j - 1) = sum(2, 2) = 1
+
+sum(j + 1, k - 1) = sum(4, 4) = 1
+
+sum(k + 1, n - 1) = sum(6, 6) = 1
+
+
+ +

+ + + +Note: + +
    + +
  1. 1 <= n <= 2000.
  2. + +
  3. Elements in the given array will be in range [-1,000,000, 1,000,000].
  4. + +
+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md b/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md new file mode 100644 index 00000000..c8fafb3d --- /dev/null +++ b/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md @@ -0,0 +1,65 @@ +# [549. Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii) + + + +## Description + +

Given the root of a binary tree, return the length of the longest consecutive path in the tree.

+ +

This path can be either increasing or decreasing.

+ +
    +
  • For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid.
  • +
+ +

On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3]
+Output: 2
+Explanation: The longest consecutive path is [1, 2] or [2, 1].
+
+ +

Example 2:

+ +
+Input: root = [2,1,3]
+Output: 3
+Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 3 * 104].
  • +
  • -3 * 104 <= Node.val <= 3 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/images/consec2-1-tree.jpg b/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/images/consec2-1-tree.jpg new file mode 100644 index 00000000..63774a3b Binary files /dev/null and b/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/images/consec2-1-tree.jpg differ diff --git a/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/images/consec2-2-tree.jpg b/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/images/consec2-2-tree.jpg new file mode 100644 index 00000000..a0ca0a07 Binary files /dev/null and b/assets/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/images/consec2-2-tree.jpg differ diff --git a/assets/0500-0599/0550.Game Play Analysis IV/README_EN.md b/assets/0500-0599/0550.Game Play Analysis IV/README_EN.md new file mode 100644 index 00000000..e898abfe --- /dev/null +++ b/assets/0500-0599/0550.Game Play Analysis IV/README_EN.md @@ -0,0 +1,61 @@ +# [550. Game Play Analysis IV](https://leetcode.com/problems/game-play-analysis-iv) + + + +## Description + +

Table: Activity

+ +
++--------------+---------+
+| Column Name  | Type    |
++--------------+---------+
+| player_id    | int     |
+| device_id    | int     |
+| event_date   | date    |
+| games_played | int     |
++--------------+---------+
+(player_id, event_date) is the primary key of this table.
+This table shows the activity of players of some game.
+Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
+
+ +

 

+ +

Write an SQL query that reports the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.

+ +

The query result format is in the following example:

+ +
+Activity table:
++-----------+-----------+------------+--------------+
+| player_id | device_id | event_date | games_played |
++-----------+-----------+------------+--------------+
+| 1         | 2         | 2016-03-01 | 5            |
+| 1         | 2         | 2016-03-02 | 6            |
+| 2         | 3         | 2017-06-25 | 1            |
+| 3         | 1         | 2016-03-02 | 0            |
+| 3         | 4         | 2018-07-03 | 5            |
++-----------+-----------+------------+--------------+
+
+Result table:
++-----------+
+| fraction  |
++-----------+
+| 0.33      |
++-----------+
+Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33
+
+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0551.Student Attendance Record I/README_EN.md b/assets/0500-0599/0551.Student Attendance Record I/README_EN.md new file mode 100644 index 00000000..821b65a9 --- /dev/null +++ b/assets/0500-0599/0551.Student Attendance Record I/README_EN.md @@ -0,0 +1,79 @@ +# [551. Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i) + + + +## Description + +

You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:

+ +
    +
  • 'A': Absent.
  • +
  • 'L': Late.
  • +
  • 'P': Present.
  • +
+ +

The student is eligible for an attendance award if they meet both of the following criteria:

+ +
    +
  • The student was absent ('A') for strictly fewer than 2 days total.
  • +
  • The student was never late ('L') for 3 or more consecutive days.
  • +
+ +

Return true if the student is eligible for an attendance award, or false otherwise.

+ +

 

+

Example 1:

+ +
+Input: s = "PPALLP"
+Output: true
+Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.
+
+ +

Example 2:

+ +
+Input: s = "PPALLL"
+Output: false
+Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 1000
  • +
  • s[i] is either 'A', 'L', or 'P'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def checkRecord(self, s: str) -> bool: + return s.count('A') <= 1 and 'LLL' not in s +``` + +### **Java** + +```java +class Solution { + public boolean checkRecord(String s) { + int i = s.indexOf("A"); + return (i == -1 || s.lastIndexOf("A") == i) && !s.contains("LLL"); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0552.Student Attendance Record II/README_EN.md b/assets/0500-0599/0552.Student Attendance Record II/README_EN.md new file mode 100644 index 00000000..b5fbcb1e --- /dev/null +++ b/assets/0500-0599/0552.Student Attendance Record II/README_EN.md @@ -0,0 +1,79 @@ +# [552. Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii) + + + +## Description + +

An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:

+ +
    +
  • 'A': Absent.
  • +
  • 'L': Late.
  • +
  • 'P': Present.
  • +
+ +

Any student is eligible for an attendance award if they meet both of the following criteria:

+ +
    +
  • The student was absent ('A') for strictly fewer than 2 days total.
  • +
  • The student was never late ('L') for 3 or more consecutive days.
  • +
+ +

Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
+Input: n = 2
+Output: 8
+Explanation: There are 8 records with length 2 that are eligible for an award:
+"PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL"
+Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2).
+
+ +

Example 2:

+ +
+Input: n = 1
+Output: 3
+
+ +

Example 3:

+ +
+Input: n = 10101
+Output: 183236316
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0553.Optimal Division/README_EN.md b/assets/0500-0599/0553.Optimal Division/README_EN.md new file mode 100644 index 00000000..a00a47cf --- /dev/null +++ b/assets/0500-0599/0553.Optimal Division/README_EN.md @@ -0,0 +1,83 @@ +# [553. Optimal Division](https://leetcode.com/problems/optimal-division) + + + +## Description + +

Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.

+ + + +

However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.

+ + + +

Example:
+ +

+
+Input: [1000,100,10,2]
+
+Output: "1000/(100/10/2)"
+
+Explanation:
+
+1000/(100/10/2) = 1000/((100/10)/2) = 200
+
+However, the bold parenthesis in "1000/((100/10)/2)" are redundant, 
since they don't influence the operation priority. So you should return "1000/(100/10/2)". + + + +Other cases: + +1000/(100/10)/2 = 50 + +1000/(100/(10/2)) = 50 + +1000/100/10/2 = 0.5 + +1000/100/(10/2) = 2 + +
+ +

+ + + +

Note: + +

    + +
  1. The length of the input array is [1, 10].
  2. + +
  3. Elements in the given array will be in range [2, 1000].
  4. + +
  5. There is only one optimal division for each test case.
  6. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0554.Brick Wall/README_EN.md b/assets/0500-0599/0554.Brick Wall/README_EN.md new file mode 100644 index 00000000..6c67eae2 --- /dev/null +++ b/assets/0500-0599/0554.Brick Wall/README_EN.md @@ -0,0 +1,147 @@ +# [554. Brick Wall](https://leetcode.com/problems/brick-wall) + + + +## Description + +

There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

+ +

The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

+ +

If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

+ +

You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

+ +

 

+ +

Example:

+ +
+
+Input: [[1,2,2,1],
+
+        [3,1,2],
+
+        [1,3,2],
+
+        [2,4],
+
+        [3,1,2],
+
+        [1,3,1,1]]
+
+
+
+Output: 2
+
+
+
+Explanation: 
+
+
+
+
+ +

 

+ +

Note:

+ +
    +
  1. The width sum of bricks in different rows are the same and won't exceed INT_MAX.
  2. +
  3. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.
  4. +
+ +## Solutions + +The question can be understood as, let the vertical line pass through the edge of the brick as much as possible, use the hash table to process the frequency of the brick edge in different positions (not including the two vertical edges), and the final answer is the total number of rows minus the maximum Frequency. + + + +### **Python3** + +```python +class Solution: + def leastBricks(self, wall: List[List[int]]) -> int: + cnt = collections.defaultdict(int) + for row in wall: + width = 0 + for brick in row[:-1]: + width += brick + cnt[width] += 1 + if not cnt: + return len(wall) + return len(wall) - cnt[max(cnt, key=cnt.get)] +``` + +### **Java** + +```java +class Solution { + public int leastBricks(List> wall) { + Map cnt = new HashMap<>(); + for (List row : wall) { + int width = 0; + for (int i = 0, n = row.size() - 1; i < n; i++) { + width += row.get(i); + cnt.merge(width, 1, Integer::sum); + } + } + int max = cnt.values().stream().max(Comparator.naturalOrder()).orElse(0); + return wall.size() - max; + } +} +``` + +### **Go** + +```go +func leastBricks(wall [][]int) int { + cnt := make(map[int]int) + for _, row := range wall { + width := 0 + for _, brick := range row[:len(row)-1] { + width += brick + cnt[width]++ + } + } + max := 0 + for _, v := range cnt { + if v > max { + max = v + } + } + return len(wall) - max +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} wall + * @return {number} + */ +var leastBricks = function (wall) { + const cnt = new Map(); + for (const row of wall) { + let width = 0; + for (let i = 0, n = row.length - 1; i < n; ++i) { + width += row[i]; + cnt.set(width, (cnt.get(width) || 0) + 1); + } + } + let max = 0; + for (const v of cnt.values()) { + max = Math.max(max, v); + } + return wall.length - max; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0554.Brick Wall/images/brick_wall.png b/assets/0500-0599/0554.Brick Wall/images/brick_wall.png new file mode 100644 index 00000000..a5088499 Binary files /dev/null and b/assets/0500-0599/0554.Brick Wall/images/brick_wall.png differ diff --git a/assets/0500-0599/0555.Split Concatenated Strings/README_EN.md b/assets/0500-0599/0555.Split Concatenated Strings/README_EN.md new file mode 100644 index 00000000..044d0be0 --- /dev/null +++ b/assets/0500-0599/0555.Split Concatenated Strings/README_EN.md @@ -0,0 +1,81 @@ +# [555. Split Concatenated Strings](https://leetcode.com/problems/split-concatenated-strings) + + + +## Description + +

Given a list of strings, you could concatenate these strings together into a loop, where for each string you could choose to reverse it or not. Among all the possible loops, you need to find the lexicographically biggest string after cutting the loop, which will make the looped string into a regular one.

+ + + +

Specifically, to find the lexicographically biggest string, you need to experience two phases: + +

    + +
  1. Concatenate all the strings into a loop, where you can reverse some strings or not and connect them in the same order as given.
  2. + +
  3. Cut and make one breakpoint in any place of the loop, which will make the looped string into a regular one starting from the character at the cutpoint.
  4. + +
+ +

+ + + +

And your job is to find the lexicographically biggest one among all the possible regular strings.

+ + + + + +

Example:
+ +

+
+Input: "abc", "xyz"
+
+Output: "zyxcba"
+
+Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", 
where '-' represents the looped status.
The answer string came from the fourth looped one,
where you could cut from the middle character 'a' and get "zyxcba". + +
+ +

+ + + +

Note:
+ +

    + +
  1. The input strings will only contain lowercase letters.
  2. + +
  3. The total length of all the strings will not over 1,000.
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0556.Next Greater Element III/README_EN.md b/assets/0500-0599/0556.Next Greater Element III/README_EN.md new file mode 100644 index 00000000..cc4c0c02 --- /dev/null +++ b/assets/0500-0599/0556.Next Greater Element III/README_EN.md @@ -0,0 +1,49 @@ +# [556. Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii) + + + +## Description + +

Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.

+ +

Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

+ +

 

+

Example 1:

+
Input: n = 12
+Output: 21
+

Example 2:

+
Input: n = 21
+Output: -1
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0557.Reverse Words in a String III/README_EN.md b/assets/0500-0599/0557.Reverse Words in a String III/README_EN.md new file mode 100644 index 00000000..defe6923 --- /dev/null +++ b/assets/0500-0599/0557.Reverse Words in a String III/README_EN.md @@ -0,0 +1,51 @@ +# [557. Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii) + + + +## Description + +

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

+ +

 

+

Example 1:

+
Input: s = "Let's take LeetCode contest"
+Output: "s'teL ekat edoCteeL tsetnoc"
+

Example 2:

+
Input: s = "God Ding"
+Output: "doG gniD"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 5 * 104
  • +
  • s contains printable ASCII characters.
  • +
  • s does not contain any leading or trailing spaces.
  • +
  • There is at least one word in s.
  • +
  • All the words in s are separated by a single space.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md new file mode 100644 index 00000000..b2dc6672 --- /dev/null +++ b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md @@ -0,0 +1,163 @@ +# [558. Logical OR of Two Binary Grids Represented as Quad-Trees](https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees) + + + +## Description + +

A Binary Matrix is a matrix in which all the elements are either 0 or 1.

+ + + +

Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 represents another n * n binary matrix. 

+ + + +

Return a Quad-Tree representing the n * n binary matrix which is the result of logical bitwise OR of the two binary matrixes represented by quadTree1 and quadTree2.

+ + + +

Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.

+ + + +

A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:

+ + + +
    +
  • val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. 
  • +
  • isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
  • +
+ + + +
+
+class Node {
+
+    public boolean val;
+
+    public boolean isLeaf;
+
+    public Node topLeft;
+
+    public Node topRight;
+
+    public Node bottomLeft;
+
+    public Node bottomRight;
+
+}
+ + + +

We can construct a Quad-Tree from a two-dimensional area using the following steps:

+ + + +
    +
  1. If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
  2. +
  3. If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
  4. +
  5. Recurse for each of the children with the proper sub-grid.
  6. +
+ + + +

If you want to know more about the Quad-Tree, you can refer to the wiki.

+ + + +

Quad-Tree format:

+ + + +

The input/output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.

+ + + +

It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].

+ + + +

If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.

+ + +

 

+

Example 1:

+ +
+Input: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
+, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
+Output: [[0,0],[1,1],[1,1],[1,1],[1,0]]
+Explanation: quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
+If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
+Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
+
+
+ +

Example 2:

+ +
+Input: quadTree1 = [[1,0]]
+, quadTree2 = [[1,0]]
+Output: [[1,0]]
+Explanation: Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.
+The resulting matrix is of size 1*1 with also zero.
+
+ +

Example 3:

+ +
+Input: quadTree1 = [[0,0],[1,0],[1,0],[1,1],[1,1]]
+, quadTree2 = [[0,0],[1,1],[1,1],[1,0],[1,1]]
+Output: [[1,1]]
+
+ +

Example 4:

+ +
+Input: quadTree1 = [[0,0],[1,1],[1,0],[1,1],[1,1]]
+, quadTree2 = [[0,0],[1,1],[0,1],[1,1],[1,1],null,null,null,null,[1,1],[1,0],[1,0],[1,1]]
+Output: [[0,0],[1,1],[0,1],[1,1],[1,1],null,null,null,null,[1,1],[1,0],[1,0],[1,1]]
+
+ +

Example 5:

+ +
+Input: quadTree1 = [[0,1],[1,0],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
+, quadTree2 = [[0,1],[0,1],[1,0],[1,1],[1,0],[1,0],[1,0],[1,1],[1,1]]
+Output: [[0,0],[0,1],[0,1],[1,1],[1,0],[1,0],[1,0],[1,1],[1,1],[1,0],[1,0],[1,1],[1,1]]
+
+ +

 

+

Constraints:

+ +
    +
  • quadTree1 and quadTree2 are both valid Quad-Trees each representing a n * n grid.
  • +
  • n == 2^x where 0 <= x <= 9.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/new_top.png b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/new_top.png new file mode 100644 index 00000000..920e497d Binary files /dev/null and b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/new_top.png differ diff --git a/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qt1.png b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qt1.png new file mode 100644 index 00000000..0ea36809 Binary files /dev/null and b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qt1.png differ diff --git a/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qt2.png b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qt2.png new file mode 100644 index 00000000..c5e754d8 Binary files /dev/null and b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qt2.png differ diff --git a/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qtr.png b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qtr.png new file mode 100644 index 00000000..f64fa467 Binary files /dev/null and b/assets/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/images/qtr.png differ diff --git a/assets/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md b/assets/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md new file mode 100644 index 00000000..5e223b36 --- /dev/null +++ b/assets/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md @@ -0,0 +1,107 @@ +# [559. Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) + + + +## Description + +

Given a n-ary tree, find its maximum depth.

+ +

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

+ +

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

+ +

 

+

Example 1:

+ +

+ +
+Input: root = [1,null,3,2,4,null,5,6]
+Output: 3
+
+ +

Example 2:

+ +

+ +
+Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: 5
+
+ +

 

+

Constraints:

+ +
    +
  • The depth of the n-ary tree is less than or equal to 1000.
  • +
  • The total number of nodes is between [0, 104].
  • +
+ +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def maxDepth(self, root: 'Node') -> int: + if not root: + return 0 + max_depth = 1 + for child in root.children: + max_depth = max(max_depth, 1 + self.maxDepth(child)) + return max_depth +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + public int maxDepth(Node root) { + if (root == null) { + return 0; + } + int maxDepth = 1; + for (Node child : root.children) { + maxDepth = Math.max(maxDepth, 1 + maxDepth(child)); + } + return maxDepth; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0559.Maximum Depth of N-ary Tree/images/narytreeexample.png b/assets/0500-0599/0559.Maximum Depth of N-ary Tree/images/narytreeexample.png new file mode 100644 index 00000000..0585a485 Binary files /dev/null and b/assets/0500-0599/0559.Maximum Depth of N-ary Tree/images/narytreeexample.png differ diff --git a/assets/0500-0599/0559.Maximum Depth of N-ary Tree/images/sample_4_964.png b/assets/0500-0599/0559.Maximum Depth of N-ary Tree/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/0500-0599/0559.Maximum Depth of N-ary Tree/images/sample_4_964.png differ diff --git a/assets/0500-0599/0560.Subarray Sum Equals K/README_EN.md b/assets/0500-0599/0560.Subarray Sum Equals K/README_EN.md new file mode 100644 index 00000000..3cd3a10e --- /dev/null +++ b/assets/0500-0599/0560.Subarray Sum Equals K/README_EN.md @@ -0,0 +1,49 @@ +# [560. Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k) + + + +## Description + +

Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

+ +

 

+

Example 1:

+
Input: nums = [1,1,1], k = 2
+Output: 2
+

Example 2:

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

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -1000 <= nums[i] <= 1000
  • +
  • -107 <= k <= 107
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0561.Array Partition I/README_EN.md b/assets/0500-0599/0561.Array Partition I/README_EN.md new file mode 100644 index 00000000..cd762c63 --- /dev/null +++ b/assets/0500-0599/0561.Array Partition I/README_EN.md @@ -0,0 +1,89 @@ +# [561. Array Partition I](https://leetcode.com/problems/array-partition-i) + + + +## Description + +

Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,4,3,2]
+Output: 4
+Explanation: All possible pairings (ignoring the ordering of elements) are:
+1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
+2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
+3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
+So the maximum possible sum is 4.
+ +

Example 2:

+ +
+Input: nums = [6,2,6,5,1,2]
+Output: 9
+Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 104
  • +
  • nums.length == 2 * n
  • +
  • -104 <= nums[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + return sum(sorted(nums)[::2]) +``` + +### **Java** + +```java +class Solution { + public int arrayPairSum(int[] nums) { + Arrays.sort(nums); + int res = 0; + for (int i = 0, n = nums.length; i < n; i += 2) { + res += nums[i]; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var arrayPairSum = function (nums) { + nums.sort((a, b) => a - b); + let res = 0; + for (let i = 0, n = nums.length; i < n; i += 2) { + res += nums[i]; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md b/assets/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md new file mode 100644 index 00000000..82ddde55 --- /dev/null +++ b/assets/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md @@ -0,0 +1,61 @@ +# [562. Longest Line of Consecutive One in Matrix](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix) + + + +## Description + +Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal. + + + +

Example:
+ +

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

+ + + +

+ +Hint: + +The number of elements in the given matrix will not exceed 10,000. + +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0563.Binary Tree Tilt/README_EN.md b/assets/0500-0599/0563.Binary Tree Tilt/README_EN.md new file mode 100644 index 00000000..a2a059dc --- /dev/null +++ b/assets/0500-0599/0563.Binary Tree Tilt/README_EN.md @@ -0,0 +1,77 @@ +# [563. Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) + + + +## Description + +

Given the root of a binary tree, return the sum of every tree node's tilt.

+ +

The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if there the node does not have a right child.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3]
+Output: 1
+Explanation: 
+Tilt of node 2 : |0-0| = 0 (no children)
+Tilt of node 3 : |0-0| = 0 (no children)
+Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
+Sum of every tilt : 0 + 0 + 1 = 1
+
+ +

Example 2:

+ +
+Input: root = [4,2,9,3,5,null,7]
+Output: 15
+Explanation: 
+Tilt of node 3 : |0-0| = 0 (no children)
+Tilt of node 5 : |0-0| = 0 (no children)
+Tilt of node 7 : |0-0| = 0 (no children)
+Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
+Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
+Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
+Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
+
+ +

Example 3:

+ +
+Input: root = [21,7,14,1,1,2,2,3,3]
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -1000 <= Node.val <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0563.Binary Tree Tilt/images/tilt1.jpg b/assets/0500-0599/0563.Binary Tree Tilt/images/tilt1.jpg new file mode 100644 index 00000000..932aca91 Binary files /dev/null and b/assets/0500-0599/0563.Binary Tree Tilt/images/tilt1.jpg differ diff --git a/assets/0500-0599/0563.Binary Tree Tilt/images/tilt2.jpg b/assets/0500-0599/0563.Binary Tree Tilt/images/tilt2.jpg new file mode 100644 index 00000000..167a8231 Binary files /dev/null and b/assets/0500-0599/0563.Binary Tree Tilt/images/tilt2.jpg differ diff --git a/assets/0500-0599/0563.Binary Tree Tilt/images/tilt3.jpg b/assets/0500-0599/0563.Binary Tree Tilt/images/tilt3.jpg new file mode 100644 index 00000000..62e250a3 Binary files /dev/null and b/assets/0500-0599/0563.Binary Tree Tilt/images/tilt3.jpg differ diff --git a/assets/0500-0599/0564.Find the Closest Palindrome/README_EN.md b/assets/0500-0599/0564.Find the Closest Palindrome/README_EN.md new file mode 100644 index 00000000..0f0c4083 --- /dev/null +++ b/assets/0500-0599/0564.Find the Closest Palindrome/README_EN.md @@ -0,0 +1,60 @@ +# [564. Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome) + + + +## Description + +

Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

+ +

The closest is defined as the absolute difference minimized between two integers.

+ +

 

+

Example 1:

+ +
+Input: n = "123"
+Output: "121"
+
+ +

Example 2:

+ +
+Input: n = "1"
+Output: "0"
+Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n.length <= 18
  • +
  • n consists of only digits.
  • +
  • n does not have leading zeros.
  • +
  • n is representing an integer in the range [1, 1018 - 1].
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0565.Array Nesting/README_EN.md b/assets/0500-0599/0565.Array Nesting/README_EN.md new file mode 100644 index 00000000..9394875d --- /dev/null +++ b/assets/0500-0599/0565.Array Nesting/README_EN.md @@ -0,0 +1,81 @@ +# [565. Array Nesting](https://leetcode.com/problems/array-nesting) + + + +## Description + +

A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below.

+ + + +

Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.

+ + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: A = [5,4,0,3,1,6,2]
+
+Output: 4
+
+Explanation: 
+
+A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
+
+
+
+One of the longest S[K]:
+
+S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. N is an integer within the range [1, 20,000].
  2. +
  3. The elements of A are all distinct.
  4. +
  5. Each element of A is an integer within the range [0, N-1].
  6. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0566.Reshape the Matrix/README_EN.md b/assets/0500-0599/0566.Reshape the Matrix/README_EN.md new file mode 100644 index 00000000..07db57b5 --- /dev/null +++ b/assets/0500-0599/0566.Reshape the Matrix/README_EN.md @@ -0,0 +1,157 @@ +# [566. Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix) + + + +## Description + +

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. + +

+ + + +

+ +You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

+ + + +

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. + +

+ + + +

+ +If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. + +

+ + + +

Example 1:
+ +

+
+Input: 
+
+nums = 
+
+[[1,2],
+
+ [3,4]]
+
+r = 1, c = 4
+
+Output: 
+
+[[1,2,3,4]]
+
+Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. + +
+ +

+ + + +

Example 2:
+ +

+
+Input: 
+
+nums = 
+
+[[1,2],
+
+ [3,4]]
+
+r = 2, c = 4
+
+Output: 
+
+[[1,2],
+
+ [3,4]]
+
+Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. + +
+ +

+ + + +

Note:
+ +

    + +
  1. The height and width of the given matrix is in range [1, 100].
  2. + +
  3. The given r and c are all positive.
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: + m, n = len(nums), len(nums[0]) + if m * n != r * c: + return nums + res = [[0] * c for _ in range(r)] + for x in range(m * n): + res[x // c][x % c] = nums[x // n][x % n] + return res +``` + +### **Java** + +```java +class Solution { + public int[][] matrixReshape(int[][] nums, int r, int c) { + int m = nums.length, n = nums[0].length; + if (m * n != r * c) return nums; + int[][] res = new int[r][c]; + for (int i = 0; i < m * n; ++i) { + res[i / c][i % c] = nums[i / n][i % n]; + } + return res; + } +} +``` + +### **TypeScrpt** + +```ts +function matrixReshape(mat: number[][], r: number, c: number): number[][] { + let m = mat.length, n = mat[0].length; + if (m * n != r * c) return mat; + let ans = Array.from({length: r}, v => new Array(c).fill(0)); + let k = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + ans[Math.floor(k / c)][k % c] = mat[i][j]; + ++k; + } + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0567.Permutation in String/README_EN.md b/assets/0500-0599/0567.Permutation in String/README_EN.md new file mode 100644 index 00000000..f6849271 --- /dev/null +++ b/assets/0500-0599/0567.Permutation in String/README_EN.md @@ -0,0 +1,57 @@ +# [567. Permutation in String](https://leetcode.com/problems/permutation-in-string) + + + +## Description + +

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

+ +

 

+ +

Example 1:

+ +
+Input: s1 = "ab" s2 = "eidbaooo"
+Output: True
+Explanation: s2 contains one permutation of s1 ("ba").
+
+ +

Example 2:

+ +
+Input:s1= "ab" s2 = "eidboaoo"
+Output: False
+
+ +

 

+

Constraints:

+ +
    +
  • The input strings only contain lower case letters.
  • +
  • The length of both given strings is in range [1, 10,000].
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0568.Maximum Vacation Days/README_EN.md b/assets/0500-0599/0568.Maximum Vacation Days/README_EN.md new file mode 100644 index 00000000..2afad345 --- /dev/null +++ b/assets/0500-0599/0568.Maximum Vacation Days/README_EN.md @@ -0,0 +1,147 @@ +# [568. Maximum Vacation Days](https://leetcode.com/problems/maximum-vacation-days) + + + +## Description + +

+ +LeetCode wants to give one of its best employees the option to travel among N cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could take, but there are certain rules and restrictions you need to follow. + +

+ + + +

Rules and restrictions:
+ +

    + +
  1. You can only travel among N cities, represented by indexes from 0 to N-1. Initially, you are in the city indexed 0 on Monday.
  2. + +
  3. The cities are connected by flights. The flights are represented as a N*N matrix (not necessary symmetrical), called flights representing the airline status from the city i to the city j. If there is no flight from the city i to the city j, flights[i][j] = 0; Otherwise, flights[i][j] = 1. Also, flights[i][i] = 0 for all i.
  4. + +
  5. You totally have K weeks (each week has 7 days) to travel. You can only take flights at most once per day and can only take flights on each week's Monday morning. Since flight time is so short, we don't consider the impact of flight time.
  6. + +
  7. For each city, you can only have restricted vacation days in different weeks, given an N*K matrix called days representing this relationship. For the value of days[i][j], it represents the maximum days you could take vacation in the city i in the week j.
  8. + +
+ +

+ + + +

You're given the flights matrix and days matrix, and you need to output the maximum vacation days you could take during K weeks.

+ + + +

Example 1:
+ +

+
+Input:flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
+
+Output: 12
+
+Explanation: 
Ans = 6 + 3 + 3 = 12.
+ +One of the best strategies is: + +1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.) + +2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days. + +3rd week : stay at city 2, and play 3 days and work 4 days. + +
+ +

+ + + +

Example 2:
+ +

+
+Input:flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
+
+Output: 3
+
+Explanation: 
Ans = 1 + 1 + 1 = 3.
+ +Since there is no flights enable you to move to another city, you have to stay at city 0 for the whole 3 weeks.
For each week, you only have one day to play and six days to work.
So the maximum number of vacation days is 3. + +
+ +

+ + + +

Example 3:
+ +

+
+Input:flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
+
+Output: 21
+
+Explanation:
Ans = 7 + 7 + 7 = 21
+ +One of the best strategies is: + +1st week : stay at city 0, and play 7 days. + +2nd week : fly from city 0 to city 1 on Monday, and play 7 days. + +3rd week : fly from city 1 to city 2 on Monday, and play 7 days. + +
+ +

+ + + + + +

Note:
+ +

    + +
  1. N and K are positive integers, which are in the range of [1, 100].
  2. + +
  3. In the matrix flights, all the values are integers in the range of [0, 1].
  4. + +
  5. In the matrix days, all the values are integers in the range [0, 7].
  6. + +
  7. You could stay at a city beyond the number of vacation days, but you should work on the extra days, which won't be counted as vacation days.
  8. + +
  9. If you fly from the city A to the city B and take the vacation on that day, the deduction towards vacation days will count towards the vacation days of city B in that week.
  10. + +
  11. We don't consider the impact of flight hours towards the calculation of vacation days.
  12. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0569.Median Employee Salary/README_EN.md b/assets/0500-0599/0569.Median Employee Salary/README_EN.md new file mode 100644 index 00000000..949d742f --- /dev/null +++ b/assets/0500-0599/0569.Median Employee Salary/README_EN.md @@ -0,0 +1,97 @@ +# [569. Median Employee Salary](https://leetcode.com/problems/median-employee-salary) + + + +## Description + +

The Employee table holds all employees. The employee table has three columns: Employee Id, Company Name, and Salary.

+ + + +
+
++-----+------------+--------+
+
+|Id   | Company    | Salary |
+
++-----+------------+--------+
+
+|1    | A          | 2341   |
+
+|2    | A          | 341    |
+
+|3    | A          | 15     |
+
+|4    | A          | 15314  |
+
+|5    | A          | 451    |
+
+|6    | A          | 513    |
+
+|7    | B          | 15     |
+
+|8    | B          | 13     |
+
+|9    | B          | 1154   |
+
+|10   | B          | 1345   |
+
+|11   | B          | 1221   |
+
+|12   | B          | 234    |
+
+|13   | C          | 2345   |
+
+|14   | C          | 2645   |
+
+|15   | C          | 2645   |
+
+|16   | C          | 2652   |
+
+|17   | C          | 65     |
+
++-----+------------+--------+
+
+
+ + + +

Write a SQL query to find the median salary of each company. Bonus points if you can solve it without using any built-in SQL functions.

+ + + +
+
++-----+------------+--------+
+
+|Id   | Company    | Salary |
+
++-----+------------+--------+
+
+|5    | A          | 451    |
+
+|6    | A          | 513    |
+
+|12   | B          | 234    |
+
+|9    | B          | 1154   |
+
+|14   | C          | 2645   |
+
++-----+------------+--------+
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md b/assets/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md new file mode 100644 index 00000000..f24f703a --- /dev/null +++ b/assets/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md @@ -0,0 +1,74 @@ +# [570. Managers with at Least 5 Direct Reports](https://leetcode.com/problems/managers-with-at-least-5-direct-reports) + + + +## Description + +

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

+ + + +
+
++------+----------+-----------+----------+
+
+|Id    |Name 	  |Department |ManagerId |
+
++------+----------+-----------+----------+
+
+|101   |John 	  |A 	      |null      |
+
+|102   |Dan 	  |A 	      |101       |
+
+|103   |James 	  |A 	      |101       |
+
+|104   |Amy 	  |A 	      |101       |
+
+|105   |Anne 	  |A 	      |101       |
+
+|106   |Ron 	  |B 	      |101       |
+
++------+----------+-----------+----------+
+
+
+ + + +

Given the Employee table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return:

+ + + +
+
++-------+
+
+| Name  |
+
++-------+
+
+| John  |
+
++-------+
+
+
+ + + +

Note:
+ +No one would report to himself.

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + + diff --git a/assets/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md b/assets/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md new file mode 100644 index 00000000..b39a1201 --- /dev/null +++ b/assets/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md @@ -0,0 +1,79 @@ +# [571. Find Median Given Frequency of Numbers](https://leetcode.com/problems/find-median-given-frequency-of-numbers) + + + +## Description + +

The Numbers table keeps the value of number and its frequency.

+ + + +
+
++----------+-------------+
+
+|  Number  |  Frequency  |
+
++----------+-------------|
+
+|  0       |  7          |
+
+|  1       |  1          |
+
+|  2       |  3          |
+
+|  3       |  1          |
+
++----------+-------------+
+
+
+ + + +

In this table, the numbers are 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, so the median is (0 + 0) / 2 = 0.

+ + + +
+
++--------+
+
+| median |
+
++--------|
+
+| 0.0000 |
+
++--------+
+
+
+ + + +

Write a query to find the median of all numbers and name the result as median.

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0572.Subtree of Another Tree/README_EN.md b/assets/0500-0599/0572.Subtree of Another Tree/README_EN.md new file mode 100644 index 00000000..74061eb9 --- /dev/null +++ b/assets/0500-0599/0572.Subtree of Another Tree/README_EN.md @@ -0,0 +1,76 @@ +# [572. Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree) + + + +## Description + +

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

+ +

Example 1:
+Given tree s:

+ +
+     3
+    / \
+   4   5
+  / \
+ 1   2
+
+Given tree t: + +
+   4 
+  / \
+ 1   2
+
+Return true, because t has the same structure and node values with a subtree of s. + +

 

+ +

Example 2:
+Given tree s:

+ +
+     3
+    / \
+   4   5
+  / \
+ 1   2
+    /
+   0
+
+Given tree t: + +
+   4
+  / \
+ 1   2
+
+Return false. + +

 

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0573.Squirrel Simulation/README_EN.md b/assets/0500-0599/0573.Squirrel Simulation/README_EN.md new file mode 100644 index 00000000..bde55d27 --- /dev/null +++ b/assets/0500-0599/0573.Squirrel Simulation/README_EN.md @@ -0,0 +1,73 @@ +# [573. Squirrel Simulation](https://leetcode.com/problems/squirrel-simulation) + + + +## Description + +There's a tree, a squirrel, and several nuts. Positions are represented by the cells in a 2D grid. Your goal is to find the minimal distance for the squirrel to collect all the nuts and put them under the tree one by one. The squirrel can only take at most one nut at one time and can move in four directions - up, down, left and right, to the adjacent cell. The distance is represented by the number of moves. + +

Example 1:

+ + + +
+
+Input: 
+
+Height : 5
+
+Width : 7
+
+Tree position : [2,2]
+
+Squirrel : [4,4]
+
+Nuts : [[3,0], [2,5]]
+
+Output: 12
+
+Explanation:
+
+​​​​​
+
+
+ + + +

Note:

+ + + +
    +
  1. All given positions won't overlap.
  2. +
  3. The squirrel can take at most one nut at one time.
  4. +
  5. The given positions of nuts have no order.
  6. +
  7. Height and width are positive integers. 3 <= height * width <= 10,000.
  8. +
  9. The given positions contain at least one nut, only one tree and one squirrel.
  10. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0573.Squirrel Simulation/images/squirrel_simulation.png b/assets/0500-0599/0573.Squirrel Simulation/images/squirrel_simulation.png new file mode 100644 index 00000000..efad1490 Binary files /dev/null and b/assets/0500-0599/0573.Squirrel Simulation/images/squirrel_simulation.png differ diff --git a/assets/0500-0599/0574.Winning Candidate/README_EN.md b/assets/0500-0599/0574.Winning Candidate/README_EN.md new file mode 100644 index 00000000..671aebe4 --- /dev/null +++ b/assets/0500-0599/0574.Winning Candidate/README_EN.md @@ -0,0 +1,67 @@ +# [574. Winning Candidate](https://leetcode.com/problems/winning-candidate) + + + +## Description + +

Table: Candidate

+ +
++-----+---------+
+| id  | Name    |
++-----+---------+
+| 1   | A       |
+| 2   | B       |
+| 3   | C       |
+| 4   | D       |
+| 5   | E       |
++-----+---------+  
+
+ +

Table: Vote

+ +
++-----+--------------+
+| id  | CandidateId  |
++-----+--------------+
+| 1   |     2        |
+| 2   |     4        |
+| 3   |     3        |
+| 4   |     2        |
+| 5   |     5        |
++-----+--------------+
+id is the auto-increment primary key,
+CandidateId is the id appeared in Candidate table.
+
+ +

Write a sql to find the name of the winning candidate, the above example will return the winner B.

+ +
++------+
+| Name |
++------+
+| B    |
++------+
+
+ +

Notes:

+ +
    +
  1. You may assume there is no tie, in other words there will be only one winning candidate.
  2. +
+ +

 

+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + + diff --git a/assets/0500-0599/0575.Distribute Candies/README_EN.md b/assets/0500-0599/0575.Distribute Candies/README_EN.md new file mode 100644 index 00000000..77b4c58e --- /dev/null +++ b/assets/0500-0599/0575.Distribute Candies/README_EN.md @@ -0,0 +1,71 @@ +# [575. Distribute Candies](https://leetcode.com/problems/distribute-candies) + + + +## Description + +

Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.

+ +

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.

+ +

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.

+ +

 

+

Example 1:

+ +
+Input: candyType = [1,1,2,2,3,3]
+Output: 3
+Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
+
+ +

Example 2:

+ +
+Input: candyType = [1,1,2,3]
+Output: 2
+Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
+
+ +

Example 3:

+ +
+Input: candyType = [6,6,6,6]
+Output: 1
+Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
+
+ +

 

+

Constraints:

+ +
    +
  • n == candyType.length
  • +
  • 2 <= n <= 104
  • +
  • n is even.
  • +
  • -105 <= candyType[i] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0576.Out of Boundary Paths/README_EN.md b/assets/0500-0599/0576.Out of Boundary Paths/README_EN.md new file mode 100644 index 00000000..86c5d88d --- /dev/null +++ b/assets/0500-0599/0576.Out of Boundary Paths/README_EN.md @@ -0,0 +1,89 @@ +# [576. Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths) + + + +## Description + +

There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.

+ + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: m = 2, n = 2, N = 2, i = 0, j = 0
+
+Output: 6
+
+Explanation:
+
+
+
+
+ + + +

Example 2:

+ + + +
+
+Input: m = 1, n = 3, N = 3, i = 0, j = 1
+
+Output: 12
+
+Explanation:
+
+
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. Once you move the ball out of boundary, you cannot move it back.
  2. +
  3. The length and height of the grid is in range [1,50].
  4. +
  5. N is in range [0,50].
  6. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0576.Out of Boundary Paths/images/out_of_boundary_paths_1.png b/assets/0500-0599/0576.Out of Boundary Paths/images/out_of_boundary_paths_1.png new file mode 100644 index 00000000..a2df4e9b Binary files /dev/null and b/assets/0500-0599/0576.Out of Boundary Paths/images/out_of_boundary_paths_1.png differ diff --git a/assets/0500-0599/0576.Out of Boundary Paths/images/out_of_boundary_paths_2.png b/assets/0500-0599/0576.Out of Boundary Paths/images/out_of_boundary_paths_2.png new file mode 100644 index 00000000..e5eef709 Binary files /dev/null and b/assets/0500-0599/0576.Out of Boundary Paths/images/out_of_boundary_paths_2.png differ diff --git a/assets/0500-0599/0577.Employee Bonus/README_EN.md b/assets/0500-0599/0577.Employee Bonus/README_EN.md new file mode 100644 index 00000000..38b9483a --- /dev/null +++ b/assets/0500-0599/0577.Employee Bonus/README_EN.md @@ -0,0 +1,97 @@ +# [577. Employee Bonus](https://leetcode.com/problems/employee-bonus) + + + +## Description + +

Select all employee's name and bonus whose bonus is < 1000.

+ + + +

Table:Employee

+ + + +
+
++-------+--------+-----------+--------+
+
+| empId |  name  | supervisor| salary |
+
++-------+--------+-----------+--------+
+
+|   1   | John   |  3        | 1000   |
+
+|   2   | Dan    |  3        | 2000   |
+
+|   3   | Brad   |  null     | 4000   |
+
+|   4   | Thomas |  3        | 4000   |
+
++-------+--------+-----------+--------+
+
+empId is the primary key column for this table.
+
+
+ + + +

Table: Bonus

+ + + +
+
++-------+-------+
+
+| empId | bonus |
+
++-------+-------+
+
+| 2     | 500   |
+
+| 4     | 2000  |
+
++-------+-------+
+
+empId is the primary key column for this table.
+
+
+ + + +

Example ouput:

+ + + +
+
++-------+-------+
+
+| name  | bonus |
+
++-------+-------+
+
+| John  | null  |
+
+| Dan   | 500   |
+
+| Brad  | null  |
+
++-------+-------+
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md b/assets/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md new file mode 100644 index 00000000..a90eb33f --- /dev/null +++ b/assets/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md @@ -0,0 +1,50 @@ +# [578. Get Highest Answer Rate Question](https://leetcode.com/problems/get-highest-answer-rate-question) + + + +## Description + +

Get the highest answer rate question from a table survey_log with these columns: id, action, question_id, answer_id, q_num, timestamp.

+ +

id means user id; action has these kind of values: "show", "answer", "skip"; answer_id is not null when action column is "answer", while is null for "show" and "skip"; q_num is the numeral order of the question in current session.

+ +

Write a sql query to identify the question which has the highest answer rate.

+ +

Example:

+ +
+Input:
++------+-----------+--------------+------------+-----------+------------+
+| id   | action    | question_id  | answer_id  | q_num     | timestamp  |
++------+-----------+--------------+------------+-----------+------------+
+| 5    | show      | 285          | null       | 1         | 123        |
+| 5    | answer    | 285          | 124124     | 1         | 124        |
+| 5    | show      | 369          | null       | 2         | 125        |
+| 5    | skip      | 369          | null       | 2         | 126        |
++------+-----------+--------------+------------+-----------+------------+
+Output:
++-------------+
+| survey_log  |
++-------------+
+|    285      |
++-------------+
+Explanation:
+question 285 has answer rate 1/1, while question 369 has 0/1 answer rate, so output 285.
+
+ +

 

+ +

Note: The highest answer rate meaning is: answer number's ratio in show number in the same question.

+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md b/assets/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md new file mode 100644 index 00000000..f549fd7a --- /dev/null +++ b/assets/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md @@ -0,0 +1,155 @@ +# [579. Find Cumulative Salary of an Employee](https://leetcode.com/problems/find-cumulative-salary-of-an-employee) + + + +## Description + +

The Employee table holds the salary information in a year.

+ + + +

Write a SQL to get the cumulative sum of an employee's salary over a period of 3 months but exclude the most recent month.

+ + + +

The result should be displayed by 'Id' ascending, and then by 'Month' descending.

+ + + +

Example
+ +Input

+ + + +
+
+| Id | Month | Salary |
+
+|----|-------|--------|
+
+| 1  | 1     | 20     |
+
+| 2  | 1     | 20     |
+
+| 1  | 2     | 30     |
+
+| 2  | 2     | 30     |
+
+| 3  | 2     | 40     |
+
+| 1  | 3     | 40     |
+
+| 3  | 3     | 60     |
+
+| 1  | 4     | 60     |
+
+| 3  | 4     | 70     |
+
+
+ +Output + + + +
+
+
+
+| Id | Month | Salary |
+
+|----|-------|--------|
+
+| 1  | 3     | 90     |
+
+| 1  | 2     | 50     |
+
+| 1  | 1     | 20     |
+
+| 2  | 1     | 20     |
+
+| 3  | 3     | 100    |
+
+| 3  | 2     | 40     |
+
+
+ + + +

 

+ +Explanation + + + +

Employee '1' has 3 salary records for the following 3 months except the most recent month '4': salary 40 for month '3', 30 for month '2' and 20 for month '1'
+ +So the cumulative sum of salary of this employee over 3 months is 90(40+30+20), 50(30+20) and 20 respectively.

+ + + +
+
+| Id | Month | Salary |
+
+|----|-------|--------|
+
+| 1  | 3     | 90     |
+
+| 1  | 2     | 50     |
+
+| 1  | 1     | 20     |
+
+
+ +Employee '2' only has one salary record (month '1') except its most recent month '2'. + + + +
+
+| Id | Month | Salary |
+
+|----|-------|--------|
+
+| 2  | 1     | 20     |
+
+
+ + + +

 

+ +Employ '3' has two salary records except its most recent pay month '4': month '3' with 60 and month '2' with 40. So the cumulative salary is as following. + + + +
+
+| Id | Month | Salary |
+
+|----|-------|--------|
+
+| 3  | 3     | 100    |
+
+| 3  | 2     | 40     |
+
+
+ + + +

 

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0580.Count Student Number in Departments/README_EN.md b/assets/0500-0599/0580.Count Student Number in Departments/README_EN.md new file mode 100644 index 00000000..483ee757 --- /dev/null +++ b/assets/0500-0599/0580.Count Student Number in Departments/README_EN.md @@ -0,0 +1,139 @@ +# [580. Count Student Number in Departments](https://leetcode.com/problems/count-student-number-in-departments) + + + +## Description + +

A university uses 2 data tables, student and department, to store data about its students and the departments associated with each major.

+ + + +

Write a query to print the respective department name and number of students majoring in each department for all departments in the department table (even ones with no current students).

+ + + +

Sort your results by descending number of students; if two or more departments have the same number of students, then sort those departments alphabetically by department name.

+ + + +

The student is described as follow:

+ + + +
+
+| Column Name  | Type      |
+
+|--------------|-----------|
+
+| student_id   | Integer   |
+
+| student_name | String    |
+
+| gender       | Character |
+
+| dept_id      | Integer   |
+
+
+ + + +

where student_id is the student's ID number, student_name is the student's name, gender is their gender, and dept_id is the department ID associated with their declared major.

+ + + +

And the department table is described as below:

+ + + +
+
+| Column Name | Type    |
+
+|-------------|---------|
+
+| dept_id     | Integer |
+
+| dept_name   | String  |
+
+
+ + + +

where dept_id is the department's ID number and dept_name is the department name.

+ + + +

Here is an example input:
+ +student table:

+ + + +
+
+| student_id | student_name | gender | dept_id |
+
+|------------|--------------|--------|---------|
+
+| 1          | Jack         | M      | 1       |
+
+| 2          | Jane         | F      | 1       |
+
+| 3          | Mark         | M      | 2       |
+
+
+ + + +

department table:

+ + + +
+
+| dept_id | dept_name   |
+
+|---------|-------------|
+
+| 1       | Engineering |
+
+| 2       | Science     |
+
+| 3       | Law         |
+
+
+ + + +

The Output should be:

+ + + +
+
+| dept_name   | student_number |
+
+|-------------|----------------|
+
+| Engineering | 2              |
+
+| Science     | 1              |
+
+| Law         | 0              |
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md b/assets/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md new file mode 100644 index 00000000..75b9c79a --- /dev/null +++ b/assets/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md @@ -0,0 +1,67 @@ +# [581. Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray) + + + +## Description + +

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

+ +

Return the shortest such subarray and output its length.

+ +

 

+

Example 1:

+ +
+Input: nums = [2,6,4,8,10,9,15]
+Output: 5
+Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4]
+Output: 0
+
+ +

Example 3:

+ +
+Input: nums = [1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -105 <= nums[i] <= 105
  • +
+ +

 

+Follow up: Can you solve it in O(n) time complexity? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0582.Kill Process/README_EN.md b/assets/0500-0599/0582.Kill Process/README_EN.md new file mode 100644 index 00000000..da9b574d --- /dev/null +++ b/assets/0500-0599/0582.Kill Process/README_EN.md @@ -0,0 +1,68 @@ +# [582. Kill Process](https://leetcode.com/problems/kill-process) + + + +## Description + +

You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process.

+ +

Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has no parent process (the root of the tree).

+ +

When a process is killed, all of its children processes will also be killed.

+ +

Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer in any order.

+ +

 

+

Example 1:

+ +
+Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
+Output: [5,10]
+Explanation: The processes colored in red are the processes that should be killed.
+
+ +

Example 2:

+ +
+Input: pid = [1], ppid = [0], kill = 1
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • n == pid.length
  • +
  • n == ppid.length
  • +
  • 1 <= n <= 5 * 104
  • +
  • 1 <= pid[i] <= 5 * 104
  • +
  • 0 <= ppid[i] <= 5 * 104
  • +
  • Only one process has no parent.
  • +
  • All the values of pid are unique.
  • +
  • kill is guaranteed to be in pid.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0582.Kill Process/images/ptree.jpg b/assets/0500-0599/0582.Kill Process/images/ptree.jpg new file mode 100644 index 00000000..2be01ae0 Binary files /dev/null and b/assets/0500-0599/0582.Kill Process/images/ptree.jpg differ diff --git a/assets/0500-0599/0583.Delete Operation for Two Strings/README_EN.md b/assets/0500-0599/0583.Delete Operation for Two Strings/README_EN.md new file mode 100644 index 00000000..ecbd722f --- /dev/null +++ b/assets/0500-0599/0583.Delete Operation for Two Strings/README_EN.md @@ -0,0 +1,58 @@ +# [583. Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings) + + + +## Description + +

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

+ +

In one step, you can delete exactly one character in either string.

+ +

 

+

Example 1:

+ +
+Input: word1 = "sea", word2 = "eat"
+Output: 2
+Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
+
+ +

Example 2:

+ +
+Input: word1 = "leetcode", word2 = "etco"
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= word1.length, word2.length <= 500
  • +
  • word1 and word2 consist of only lowercase English letters.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0584.Find Customer Referee/README_EN.md b/assets/0500-0599/0584.Find Customer Referee/README_EN.md new file mode 100644 index 00000000..484e7263 --- /dev/null +++ b/assets/0500-0599/0584.Find Customer Referee/README_EN.md @@ -0,0 +1,77 @@ +# [584. Find Customer Referee](https://leetcode.com/problems/find-customer-referee) + + + +## Description + +

Given a table customer holding customers information and the referee.

+ + + +
+
++------+------+-----------+
+
+| id   | name | referee_id|
+
++------+------+-----------+
+
+|    1 | Will |      NULL |
+
+|    2 | Jane |      NULL |
+
+|    3 | Alex |         2 |
+
+|    4 | Bill |      NULL |
+
+|    5 | Zack |         1 |
+
+|    6 | Mark |         2 |
+
++------+------+-----------+
+
+
+ + + +

Write a query to return the list of customers NOT referred by the person with id '2'.

+ + + +

For the sample data above, the result is:

+ + + +
+
++------+
+
+| name |
+
++------+
+
+| Will |
+
+| Jane |
+
+| Bill |
+
+| Zack |
+
++------+
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0500-0599/0585.Investments in 2016/README_EN.md b/assets/0500-0599/0585.Investments in 2016/README_EN.md new file mode 100644 index 00000000..1c9c3b41 --- /dev/null +++ b/assets/0500-0599/0585.Investments in 2016/README_EN.md @@ -0,0 +1,120 @@ +# [585. Investments in 2016](https://leetcode.com/problems/investments-in-2016) + + + +## Description + +

Write a query to print the sum of all total investment values in 2016 (TIV_2016), to a scale of 2 decimal places, for all policy holders who meet the following criteria:

+ + + +
    +
  1. Have the same TIV_2015 value as one or more other policyholders.
  2. +
  3. Are not located in the same city as any other policyholder (i.e.: the (latitude, longitude) attribute pairs must be unique).
  4. +
+ + + +

Input Format:
+ +The insurance table is described as follows:

+ + + +
+
+| Column Name | Type          |
+
+|-------------|---------------|
+
+| PID         | INTEGER(11)   |
+
+| TIV_2015    | NUMERIC(15,2) |
+
+| TIV_2016    | NUMERIC(15,2) |
+
+| LAT         | NUMERIC(5,2)  |
+
+| LON         | NUMERIC(5,2)  |
+
+
+ + + +

where PID is the policyholder's policy ID, TIV_2015 is the total investment value in 2015, TIV_2016 is the total investment value in 2016, LAT is the latitude of the policy holder's city, and LON is the longitude of the policy holder's city.

+ + + +

Sample Input

+ + + +
+
+| PID | TIV_2015 | TIV_2016 | LAT | LON |
+
+|-----|----------|----------|-----|-----|
+
+| 1   | 10       | 5        | 10  | 10  |
+
+| 2   | 20       | 20       | 20  | 20  |
+
+| 3   | 10       | 30       | 20  | 20  |
+
+| 4   | 10       | 40       | 40  | 40  |
+
+
+ + + +

Sample Output

+ + + +
+
+| TIV_2016 |
+
+|----------|
+
+| 45.00    |
+
+
+ + + +

Explanation

+ + + +
+
+The first record in the table, like the last record, meets both of the two criteria.
+
+The TIV_2015 value '10' is as the same as the third and forth record, and its location unique.
+
+
+
+The second record does not meet any of the two criteria. Its TIV_2015 is not like any other policyholders.
+
+
+
+And its location is the same with the third record, which makes the third record fail, too.
+
+
+
+So, the result is the sum of TIV_2016 of the first and last record, which is 45.
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md b/assets/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md new file mode 100644 index 00000000..65cf27f4 --- /dev/null +++ b/assets/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md @@ -0,0 +1,64 @@ +# [586. Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders) + + + +## Description + +

Table: Orders

+ +
++-----------------+----------+
+| Column Name     | Type     |
++-----------------+----------+
+| order_number    | int      |
+| customer_number | int      |
++-----------------+----------+
+order_number is the primary key for this table.
+This table contains information about the order ID and the customer ID.
+
+ +

 

+ +

Write an SQL query to find the customer_number for the customer who has placed the largest number of orders.

+ +

It is guaranteed that exactly one customer will have placed more orders than any other customer.

+ +

The query result format is in the following example:

+ +

 

+ +
+Orders table:
++--------------+-----------------+
+| order_number | customer_number |
++--------------+-----------------+
+| 1            | 1               |
+| 2            | 2               |
+| 3            | 3               |
+| 4            | 3               |
++--------------+-----------------+
+
+Result table:
++-----------------+
+| customer_number |
++-----------------+
+| 3               |
++-----------------+
+The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. 
+So the result is customer_number 3.
+
+ +

 

+Follow up: What if more than one customer have the largest number of orders, can you find all the customer_number in this case? + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0500-0599/0587.Erect the Fence/README_EN.md b/assets/0500-0599/0587.Erect the Fence/README_EN.md new file mode 100644 index 00000000..9fdff298 --- /dev/null +++ b/assets/0500-0599/0587.Erect the Fence/README_EN.md @@ -0,0 +1,94 @@ +# [587. Erect the Fence](https://leetcode.com/problems/erect-the-fence) + + + +## Description + +

There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.

+ + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
+
+Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]
+
+Explanation:
+
+
+
+
+ + + +

Example 2:

+ + + +
+
+Input: [[1,2],[2,2],[4,2]]
+
+Output: [[1,2],[2,2],[4,2]]
+
+Explanation:
+
+
+
+Even you only have trees in a line, you need to use rope to enclose them. 
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them in more than one group.
  2. +
  3. All input integers will range from 0 to 100.
  4. +
  5. The garden has at least one tree.
  6. +
  7. All coordinates are distinct.
  8. +
  9. Input points have NO order. No order required for output.
  10. +
  11. input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
  12. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0587.Erect the Fence/images/erect_the_fence_1.png b/assets/0500-0599/0587.Erect the Fence/images/erect_the_fence_1.png new file mode 100644 index 00000000..67d8c786 Binary files /dev/null and b/assets/0500-0599/0587.Erect the Fence/images/erect_the_fence_1.png differ diff --git a/assets/0500-0599/0587.Erect the Fence/images/erect_the_fence_2.png b/assets/0500-0599/0587.Erect the Fence/images/erect_the_fence_2.png new file mode 100644 index 00000000..78e34e38 Binary files /dev/null and b/assets/0500-0599/0587.Erect the Fence/images/erect_the_fence_2.png differ diff --git a/assets/0500-0599/0588.Design In-Memory File System/README_EN.md b/assets/0500-0599/0588.Design In-Memory File System/README_EN.md new file mode 100644 index 00000000..b6a3f97f --- /dev/null +++ b/assets/0500-0599/0588.Design In-Memory File System/README_EN.md @@ -0,0 +1,97 @@ +# [588. Design In-Memory File System](https://leetcode.com/problems/design-in-memory-file-system) + + + +## Description + +

Design an in-memory file system to simulate the following functions:

+ + + +

ls: Given a path in string format. If it is a file path, return a list that only contains this file's name. If it is a directory path, return the list of file and directory names in this directory. Your output (file and directory names together) should in lexicographic order.

+ + + +

mkdir: Given a directory path that does not exist, you should make a new directory according to the path. If the middle directories in the path don't exist either, you should create them as well. This function has void return type.

+ + + +

addContentToFile: Given a file path and file content in string format. If the file doesn't exist, you need to create that file containing given content. If the file already exists, you need to append given content to original content. This function has void return type.

+ + + +

readContentFromFile: Given a file path, return its content in string format.

+ + + +

 

+ + + +

Example:

+ + + +
+
+Input: 
+
+["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"]
+
+[[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]]
+
+
+
+Output:
+
+[null,[],null,null,["a"],"hello"]
+
+
+
+Explanation:
+
+filesystem
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. You can assume all file or directory paths are absolute paths which begin with / and do not end with / except that the path is just "/".
  2. +
  3. You can assume that all operations will be passed valid parameters and users will not attempt to retrieve file content or list a directory or file that does not exist.
  4. +
  5. You can assume that all directory names and file names only contain lower-case letters, and same names won't exist in the same directory.
  6. +
+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0588.Design In-Memory File System/images/filesystem.png b/assets/0500-0599/0588.Design In-Memory File System/images/filesystem.png new file mode 100644 index 00000000..c0a0d00e Binary files /dev/null and b/assets/0500-0599/0588.Design In-Memory File System/images/filesystem.png differ diff --git a/assets/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md b/assets/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md new file mode 100644 index 00000000..cb5c1b62 --- /dev/null +++ b/assets/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md @@ -0,0 +1,83 @@ +# [589. N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal) + + + +## Description + +

Given the root of an n-ary tree, return the preorder traversal of its nodes' values.

+ +

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

+ +

 

+

Example 1:

+ +

+ +
+Input: root = [1,null,3,2,4,null,5,6]
+Output: [1,3,5,6,2,4]
+
+ +

Example 2:

+ +

+ +
+Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The height of the n-ary tree is less than or equal to 1000.
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+ + +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def preorder(self, root: 'Node') -> List[int]: + if not root: + return [] + def PO(root): + res.append(root.val) + for i in root.children: + PO(i) + res=[] + PO(root) + return res +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0589.N-ary Tree Preorder Traversal/images/narytreeexample.png b/assets/0500-0599/0589.N-ary Tree Preorder Traversal/images/narytreeexample.png new file mode 100644 index 00000000..50286a14 Binary files /dev/null and b/assets/0500-0599/0589.N-ary Tree Preorder Traversal/images/narytreeexample.png differ diff --git a/assets/0500-0599/0589.N-ary Tree Preorder Traversal/images/sample_4_964.png b/assets/0500-0599/0589.N-ary Tree Preorder Traversal/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/0500-0599/0589.N-ary Tree Preorder Traversal/images/sample_4_964.png differ diff --git a/assets/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md b/assets/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md new file mode 100644 index 00000000..705ab6d2 --- /dev/null +++ b/assets/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md @@ -0,0 +1,83 @@ +# [590. N-ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal) + + + +## Description + +

Given the root of an n-ary tree, return the postorder traversal of its nodes' values.

+ +

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

+ +

 

+

Example 1:

+ +
+Input: root = [1,null,3,2,4,null,5,6]
+Output: [5,6,3,2,4,1]
+
+ +

Example 2:

+ +
+Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
+Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The height of the n-ary tree is less than or equal to 1000.
  • +
+ +

 

+

Follow up: Recursive solution is trivial, could you do it iteratively?

+ + +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def postorder(self, root: 'Node') -> List[int]: + if not root: + return [] + def PO(root): + if root==None: + return res + else: + for i in root.children: + PO(i) + res.append(i.val) + res=[] + PO(root) + res.append(root.val) + return res +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0590.N-ary Tree Postorder Traversal/images/narytreeexample.png b/assets/0500-0599/0590.N-ary Tree Postorder Traversal/images/narytreeexample.png new file mode 100644 index 00000000..eebcd578 Binary files /dev/null and b/assets/0500-0599/0590.N-ary Tree Postorder Traversal/images/narytreeexample.png differ diff --git a/assets/0500-0599/0590.N-ary Tree Postorder Traversal/images/sample_4_964.png b/assets/0500-0599/0590.N-ary Tree Postorder Traversal/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/0500-0599/0590.N-ary Tree Postorder Traversal/images/sample_4_964.png differ diff --git a/assets/0500-0599/0591.Tag Validator/README_EN.md b/assets/0500-0599/0591.Tag Validator/README_EN.md new file mode 100644 index 00000000..3f696e6a --- /dev/null +++ b/assets/0500-0599/0591.Tag Validator/README_EN.md @@ -0,0 +1,161 @@ +# [591. Tag Validator](https://leetcode.com/problems/tag-validator) + + + +## Description + +

Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:

+ +

    + +
  1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
  2. + +
  3. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.
  4. + +
  5. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
  6. + +
  7. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.
  8. + +
  9. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
  10. + +
  11. A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).
  12. + +
  13. The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.
  14. + +
  15. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.
  16. + +
+ + + +

Valid Code Examples:
+ +

+
+Input: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"
+ +Output: True
+ +Explanation:
+ +The code is wrapped in a closed tag : <DIV> and </DIV>.
+ +The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
+ +Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.
+ +So TAG_CONTENT is valid, and then the code is valid. Thus return true.
+ + + +Input: "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"
+ +Output: True
+ +Explanation:
+ +We first separate the code into : start_tag|tag_content|end_tag.
+ +start_tag -> "<DIV>"
+ +end_tag -> "</DIV>"
+ +tag_content could also be separated into : text1|cdata|text2.
+ +text1 -> ">> ![cdata[]] "
+ +cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"
+ +text2 -> "]]>>]"
+ + + +The reason why start_tag is NOT "<DIV>>>" is because of the rule 6. + +The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7. + +
+ +

+ + + +

Invalid Code Examples:
+ +

+
+Input: "<A>  <B> </A>   </B>"
+
+Output: False
+
+Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.
+
+
+
+Input: "<DIV>  div tag is not closed  <DIV>"
+
+Output: False
+
+
+
+Input: "<DIV>  unmatched <  </DIV>"
+
+Output: False
+
+
+
+Input: "<DIV> closed tags with invalid tag name  <b>123</b> </DIV>"
+
+Output: False
+
+
+
+Input: "<DIV> unmatched tags with invalid tag name  </1234567890> and <CDATA[[]]>  </DIV>"
+
+Output: False
+
+
+
+Input: "<DIV>  unmatched start tag <B>  and unmatched end tag </C>  </DIV>"
+
+Output: False
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. For simplicity, you could assume the input code (including the any characters mentioned above) only contain letters, digits, '<','>','/','!','[',']' and ' '.
  2. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md b/assets/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md new file mode 100644 index 00000000..2a02fe48 --- /dev/null +++ b/assets/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md @@ -0,0 +1,107 @@ +# [592. Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction) + + + +## Description + +

Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.

+ + + +

Example 1:
+ +

+
+Input:"-1/2+1/2"
+
+Output: "0/1"
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input:"-1/2+1/2+1/3"
+
+Output: "1/3"
+
+
+ +

+ + + +

Example 3:
+ +

+
+Input:"1/3-1/2"
+
+Output: "-1/6"
+
+
+ +

+ + + +

Example 4:
+ +

+
+Input:"5/3+1/3"
+
+Output: "2/1"
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  2. + +
  3. Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  4. + +
  5. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  6. + +
  7. The number of given fractions will be in the range [1,10].
  8. + +
  9. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
  10. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0593.Valid Square/README_EN.md b/assets/0500-0599/0593.Valid Square/README_EN.md new file mode 100644 index 00000000..9922382d --- /dev/null +++ b/assets/0500-0599/0593.Valid Square/README_EN.md @@ -0,0 +1,66 @@ +# [593. Valid Square](https://leetcode.com/problems/valid-square) + + + +## Description + +

Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.

+ +

The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.

+ +

A valid square has four equal sides with positive length and four equal angles (90-degree angles).

+ +

 

+

Example 1:

+ +
+Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
+Output: true
+
+ +

Example 2:

+ +
+Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
+Output: false
+
+ +

Example 3:

+ +
+Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • p1.length == p2.length == p3.length == p4.length == 2
  • +
  • -104 <= xi, yi <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md b/assets/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md new file mode 100644 index 00000000..ad8d9c14 --- /dev/null +++ b/assets/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md @@ -0,0 +1,67 @@ +# [594. Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence) + + + +## Description + +

We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.

+ +

Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.

+ +

A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,3,2,2,5,2,3,7]
+Output: 5
+Explanation: The longest harmonious subsequence is [3,2,2,2,3].
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,4]
+Output: 2
+
+ +

Example 3:

+ +
+Input: nums = [1,1,1,1]
+Output: 0
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2 * 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0595.Big Countries/README_EN.md b/assets/0500-0599/0595.Big Countries/README_EN.md new file mode 100644 index 00000000..d8cc1d42 --- /dev/null +++ b/assets/0500-0599/0595.Big Countries/README_EN.md @@ -0,0 +1,84 @@ +# [595. Big Countries](https://leetcode.com/problems/big-countries) + + + +## Description + +

There is a table World

+ + + +
+
++-----------------+------------+------------+--------------+---------------+
+
+| name            | continent  | area       | population   | gdp           |
+
++-----------------+------------+------------+--------------+---------------+
+
+| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
+
+| Albania         | Europe     | 28748      | 2831741      | 12960000      |
+
+| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
+
+| Andorra         | Europe     | 468        | 78115        | 3712000       |
+
+| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
+
++-----------------+------------+------------+--------------+---------------+
+
+
+ + + +

A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.

+ + + +

Write a SQL solution to output big countries' name, population and area.

+ + + +

For example, according to the above table, we should output:

+ + + +
+
++--------------+-------------+--------------+
+
+| name         | population  | area         |
+
++--------------+-------------+--------------+
+
+| Afghanistan  | 25500100    | 652230       |
+
+| Algeria      | 37100000    | 2381741      |
+
++--------------+-------------+--------------+
+
+
+ + + +

 

+ + + +## Solutions + + + +### **SQL** + +``` +SELECT name, + population, + area +FROM World +WHERE area>3000000 + OR population>25000000 +``` + + diff --git a/assets/0500-0599/0596.Classes More Than 5 Students/README_EN.md b/assets/0500-0599/0596.Classes More Than 5 Students/README_EN.md new file mode 100644 index 00000000..5ac6ad27 --- /dev/null +++ b/assets/0500-0599/0596.Classes More Than 5 Students/README_EN.md @@ -0,0 +1,98 @@ +# [596. Classes More Than 5 Students](https://leetcode.com/problems/classes-more-than-5-students) + + + +## Description + +

There is a table courses with columns: student and class

+ + + +

Please list out all classes which have more than or equal to 5 students.

+ + + +

For example, the table:

+ + + +
+
++---------+------------+
+
+| student | class      |
+
++---------+------------+
+
+| A       | Math       |
+
+| B       | English    |
+
+| C       | Math       |
+
+| D       | Biology    |
+
+| E       | Math       |
+
+| F       | Computer   |
+
+| G       | Math       |
+
+| H       | Math       |
+
+| I       | Math       |
+
++---------+------------+
+
+
+ + + +

Should output:

+ + + +
+
++---------+
+
+| class   |
+
++---------+
+
+| Math    |
+
++---------+
+
+
+ + + +

 

+ + + +

Note:
+ +The students should not be counted duplicate in each course.

+ + + +## Solutions + + + +### **SQL** + +``` +select + c.class +from + (select distinct courses.student, courses.class from courses) c +group by + c.class +having + count(c.class)>=5 +``` + + diff --git a/assets/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md b/assets/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md new file mode 100644 index 00000000..f83f9e60 --- /dev/null +++ b/assets/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md @@ -0,0 +1,103 @@ +# [597. Friend Requests I Overall Acceptance Rate](https://leetcode.com/problems/friend-requests-i-overall-acceptance-rate) + + + +## Description + +

Table: FriendRequest

+ +
++----------------+---------+
+| Column Name    | Type    |
++----------------+---------+
+| sender_id      | int     |
+| send_to_id     | int     |
+| request_date   | date    |
++----------------+---------+
+There is no primary key for this table, it may contain duplicates.
+This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date of the request.
+
+ +

 

+ +

Table: RequestAccepted

+ +
++----------------+---------+
+| Column Name    | Type    |
++----------------+---------+
+| requester_id   | int     |
+| accepter_id    | int     |
+| accept_date    | date    |
++----------------+---------+
+There is no primary key for this table, it may contain duplicates.
+This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.
+
+ +

 

+ +

Write an SQL query to find the overall acceptance rate of requests, which is the number of acceptance divided by the number of requests. Return the answer rounded to 2 decimals places.

+ +

Note that:

+ +
    +
  • The accepted requests are not necessarily from the table friend_request. In this case, you just need to simply count the total accepted requests (no matter whether they are in the original requests), and divide it by the number of requests to get the acceptance rate.
  • +
  • It is possible that a sender sends multiple requests to the same receiver, and a request could be accepted more than once. In this case, the ‘duplicated’ requests or acceptances are only counted once.
  • +
  • If there are no requests at all, you should return 0.00 as the accept_rate.
  • +
+ +

The query result format is in the following example:

+ +

 

+ +
+FriendRequest table:
++-----------+------------+--------------+
+| sender_id | send_to_id | request_date |
++-----------+------------+--------------+
+| 1         | 2          | 2016/06/01   |
+| 1         | 3          | 2016/06/01   |
+| 1         | 4          | 2016/06/01   |
+| 2         | 3          | 2016/06/02   |
+| 3         | 4          | 2016/06/09   |
++-----------+------------+--------------+
+
+RequestAccepted table:
++--------------+-------------+-------------+
+| requester_id | accepter_id | accept_date |
++--------------+-------------+-------------+
+| 1            | 2           | 2016/06/03  |
+| 1            | 3           | 2016/06/08  |
+| 2            | 3           | 2016/06/08  |
+| 3            | 4           | 2016/06/09  |
+| 3            | 4           | 2016/06/10  |
++--------------+-------------+-------------+
+
+Result table:
++-------------+
+| accept_rate |
++-------------+
+| 0.8         |
++-------------+
+There are 4 unique accepted requests, and there are 5 requests in total. So the rate is 0.80.
+
+ +

 

+Follow up: +
    +
  • Could you write a query to return the acceptance rate for every month?
  • +
  • Could you write a query to return the cumulative acceptance rate for every day?
  • +
+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0500-0599/0598.Range Addition II/README_EN.md b/assets/0500-0599/0598.Range Addition II/README_EN.md new file mode 100644 index 00000000..902205e8 --- /dev/null +++ b/assets/0500-0599/0598.Range Addition II/README_EN.md @@ -0,0 +1,68 @@ +# [598. Range Addition II](https://leetcode.com/problems/range-addition-ii) + + + +## Description + +

You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.

+ +

Count and return the number of maximum integers in the matrix after performing all the operations.

+ +

 

+

Example 1:

+ +
+Input: m = 3, n = 3, ops = [[2,2],[3,3]]
+Output: 4
+Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
+
+ +

Example 2:

+ +
+Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]
+Output: 4
+
+ +

Example 3:

+ +
+Input: m = 3, n = 3, ops = []
+Output: 9
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= m, n <= 4 * 104
  • +
  • 1 <= ops.length <= 104
  • +
  • ops[i].length == 2
  • +
  • 1 <= ai <= m
  • +
  • 1 <= bi <= n
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0500-0599/0598.Range Addition II/images/ex1.jpg b/assets/0500-0599/0598.Range Addition II/images/ex1.jpg new file mode 100644 index 00000000..0f4dc8ca Binary files /dev/null and b/assets/0500-0599/0598.Range Addition II/images/ex1.jpg differ diff --git a/assets/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md b/assets/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md new file mode 100644 index 00000000..f06c667f --- /dev/null +++ b/assets/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md @@ -0,0 +1,83 @@ +# [599. Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists) + + + +## Description + +

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

+ +

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

+ +

 

+

Example 1:

+ +
+Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
+Output: ["Shogun"]
+Explanation: The only restaurant they both like is "Shogun".
+
+ +

Example 2:

+ +
+Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]
+Output: ["Shogun"]
+Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
+
+ +

Example 3:

+ +
+Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Burger King","Tapioca Express","Shogun"]
+Output: ["KFC","Burger King","Tapioca Express","Shogun"]
+
+ +

Example 4:

+ +
+Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KNN","KFC","Burger King","Tapioca Express","Shogun"]
+Output: ["KFC","Burger King","Tapioca Express","Shogun"]
+
+ +

Example 5:

+ +
+Input: list1 = ["KFC"], list2 = ["KFC"]
+Output: ["KFC"]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= list1.length, list2.length <= 1000
  • +
  • 1 <= list1[i].length, list2[i].length <= 30
  • +
  • list1[i] and list2[i] consist of spaces ' ' and English letters.
  • +
  • All the stings of list1 are unique.
  • +
  • All the stings of list2 are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md b/assets/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md new file mode 100644 index 00000000..e7095c80 --- /dev/null +++ b/assets/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md @@ -0,0 +1,73 @@ +# [600. Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones) + + + +## Description + +

Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.

+ + + +

Example 1:
+ +

+
+Input: 5
+
+Output: 5
+
+Explanation: 
+
+Here are the non-negative integers <= 5 with their corresponding binary representations:
+
+0 : 0
+
+1 : 1
+
+2 : 10
+
+3 : 11
+
+4 : 100
+
+5 : 101
+
+Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. 
+
+
+ +

+ + + +

Note: + +1 <= n <= 109 + +

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0601.Human Traffic of Stadium/README_EN.md b/assets/0600-0699/0601.Human Traffic of Stadium/README_EN.md new file mode 100644 index 00000000..9ea3d7dd --- /dev/null +++ b/assets/0600-0699/0601.Human Traffic of Stadium/README_EN.md @@ -0,0 +1,82 @@ +# [601. Human Traffic of Stadium](https://leetcode.com/problems/human-traffic-of-stadium) + + + +## Description + +

Table: Stadium

+ +
++---------------+---------+
+| Column Name   | Type    |
++---------------+---------+
+| id            | int     |
+| visit_date    | date    |
+| people        | int     |
++---------------+---------+
+visit_date is the primary key for this table.
+Each row of this table contains the visit date and visit id to the stadium with the number of people during the visit.
+No two rows will have the same visit_date, and as the id increases, the dates increase as well.
+
+ +

 

+ +

Write an SQL query to display the records with three or more rows with consecutive id's, and the number of people is greater than or equal to 100 for each.

+ +

Return the result table ordered by visit_date in ascending order.

+ +

The query result format is in the following example.

+ +

 

+ +
+Stadium table:
++------+------------+-----------+
+| id   | visit_date | people    |
++------+------------+-----------+
+| 1    | 2017-01-01 | 10        |
+| 2    | 2017-01-02 | 109       |
+| 3    | 2017-01-03 | 150       |
+| 4    | 2017-01-04 | 99        |
+| 5    | 2017-01-05 | 145       |
+| 6    | 2017-01-06 | 1455      |
+| 7    | 2017-01-07 | 199       |
+| 8    | 2017-01-09 | 188       |
++------+------------+-----------+
+
+Result table:
++------+------------+-----------+
+| id   | visit_date | people    |
++------+------------+-----------+
+| 5    | 2017-01-05 | 145       |
+| 6    | 2017-01-06 | 1455      |
+| 7    | 2017-01-07 | 199       |
+| 8    | 2017-01-09 | 188       |
++------+------------+-----------+
+The four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has >= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7.
+The rows with ids 2 and 3 are not included because we need at least three consecutive ids.
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md b/assets/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md new file mode 100644 index 00000000..8ad3f2bf --- /dev/null +++ b/assets/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md @@ -0,0 +1,60 @@ +# [602. Friend Requests II Who Has the Most Friends](https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends) + + + +## Description + +

In social network like Facebook or Twitter, people send friend requests and accept others' requests as well.

+ +

 

+ +

Table request_accepted

+ +
++--------------+-------------+------------+
+| requester_id | accepter_id | accept_date|
+|--------------|-------------|------------|
+| 1            | 2           | 2016_06-03 |
+| 1            | 3           | 2016-06-08 |
+| 2            | 3           | 2016-06-08 |
+| 3            | 4           | 2016-06-09 |
++--------------+-------------+------------+
+This table holds the data of friend acceptance, while requester_id and accepter_id both are the id of a person.
+
+ +

 

+ +

Write a query to find the the people who has most friends and the most friends number under the following rules:

+ +
    +
  • It is guaranteed there is only 1 people having the most friends.
  • +
  • The friend request could only been accepted once, which mean there is no multiple records with the same requester_id and accepter_id value.
  • +
+ +

For the sample data above, the result is:

+ +
+Result table:
++------+------+
+| id   | num  |
+|------|------|
+| 3    | 3    |
++------+------+
+The person with id '3' is a friend of people '1', '2' and '4', so he has 3 friends in total, which is the most number than any others.
+
+ +

Follow-up:
+In the real world, multiple people could have the same most number of friends, can you find all these people in this case?

+ + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0603.Consecutive Available Seats/README_EN.md b/assets/0600-0699/0603.Consecutive Available Seats/README_EN.md new file mode 100644 index 00000000..187d6767 --- /dev/null +++ b/assets/0600-0699/0603.Consecutive Available Seats/README_EN.md @@ -0,0 +1,76 @@ +# [603. Consecutive Available Seats](https://leetcode.com/problems/consecutive-available-seats) + + + +## Description + +Several friends at a cinema ticket office would like to reserve consecutive available seats.
+ +Can you help to query all the consecutive available seats order by the seat_id using the following cinema table? + +
+
+| seat_id | free |
+
+|---------|------|
+
+| 1       | 1    |
+
+| 2       | 0    |
+
+| 3       | 1    |
+
+| 4       | 1    |
+
+| 5       | 1    |
+
+
+ + + +

 

+ +Your query should return the following result for the sample case above. + + + +

 

+ + + +
+
+| seat_id |
+
+|---------|
+
+| 3       |
+
+| 4       |
+
+| 5       |
+
+
+ +Note: + + + +
    +
  • The seat_id is an auto increment int, and free is bool ('1' means free, and '0' means occupied.).
  • +
  • Consecutive available seats are more than 2(inclusive) seats consecutively available.
  • +
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0600-0699/0604.Design Compressed String Iterator/README_EN.md b/assets/0600-0699/0604.Design Compressed String Iterator/README_EN.md new file mode 100644 index 00000000..262246c5 --- /dev/null +++ b/assets/0600-0699/0604.Design Compressed String Iterator/README_EN.md @@ -0,0 +1,72 @@ +# [604. Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator) + + + +## Description + +

Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.

+ +

Implement the StringIterator class:

+ +
    +
  • next() Returns the next character if the original string still has uncompressed characters, otherwise returns a white space.
  • +
  • hasNext() Returns true if there is any letter needs to be uncompressed in the original string, otherwise returns false.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["StringIterator", "next", "next", "next", "next", "next", "next", "hasNext", "next", "hasNext"]
+[["L1e2t1C1o1d1e1"], [], [], [], [], [], [], [], [], []]
+Output
+[null, "L", "e", "e", "t", "C", "o", true, "d", true]
+
+Explanation
+StringIterator stringIterator = new StringIterator("L1e2t1C1o1d1e1");
+stringIterator.next(); // return "L"
+stringIterator.next(); // return "e"
+stringIterator.next(); // return "e"
+stringIterator.next(); // return "t"
+stringIterator.next(); // return "C"
+stringIterator.next(); // return "o"
+stringIterator.hasNext(); // return True
+stringIterator.next(); // return "d"
+stringIterator.hasNext(); // return True
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= compressedString.length <= 1000
  • +
  • compressedString consists of lower-case an upper-case English letters and digits.
  • +
  • The number of a single character repetitions in compressedString is in the range [1, 10^9]
  • +
  • At most 100 calls will be made to next and hasNext.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0605.Can Place Flowers/README_EN.md b/assets/0600-0699/0605.Can Place Flowers/README_EN.md new file mode 100644 index 00000000..f1e70a2f --- /dev/null +++ b/assets/0600-0699/0605.Can Place Flowers/README_EN.md @@ -0,0 +1,52 @@ +# [605. Can Place Flowers](https://leetcode.com/problems/can-place-flowers) + + + +## Description + +

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

+ +

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.

+ +

 

+

Example 1:

+
Input: flowerbed = [1,0,0,0,1], n = 1
+Output: true
+

Example 2:

+
Input: flowerbed = [1,0,0,0,1], n = 2
+Output: false
+
+

 

+

Constraints:

+ +
    +
  • 1 <= flowerbed.length <= 2 * 104
  • +
  • flowerbed[i] is 0 or 1.
  • +
  • There are no two adjacent flowers in flowerbed.
  • +
  • 0 <= n <= flowerbed.length
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0606.Construct String from Binary Tree/README_EN.md b/assets/0600-0699/0606.Construct String from Binary Tree/README_EN.md new file mode 100644 index 00000000..6e9f8f6c --- /dev/null +++ b/assets/0600-0699/0606.Construct String from Binary Tree/README_EN.md @@ -0,0 +1,91 @@ +# [606. Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree) + + + +## Description + +

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

+ + + +

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

+ + + +

Example 1:
+ +

+
+Input: Binary tree: [1,2,3,4]
+
+       1
+
+     /   \
+
+    2     3
+
+   /    
+
+  4     
+
+
+
+Output: "1(2(4))(3)"
+
+
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)". + +
+ +

+ + + +

Example 2:
+ +

+
+Input: Binary tree: [1,2,3,null,4]
+
+       1
+
+     /   \
+
+    2     3
+
+     \  
+
+      4 
+
+
+
+Output: "1(2()(4))(3)"
+
+
Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0607.Sales Person/README_EN.md b/assets/0600-0699/0607.Sales Person/README_EN.md new file mode 100644 index 00000000..03a0dd47 --- /dev/null +++ b/assets/0600-0699/0607.Sales Person/README_EN.md @@ -0,0 +1,95 @@ +# [607. Sales Person](https://leetcode.com/problems/sales-person) + + + +## Description + +

Description

+ +

Given three tables: salesperson, company, orders.
+Output all the names in the table salesperson, who didn’t have sales to company 'RED'.

+ +

Example
+Input

+ +

Table: salesperson

+ +
++----------+------+--------+-----------------+-----------+
+| sales_id | name | salary | commission_rate | hire_date |
++----------+------+--------+-----------------+-----------+
+|   1      | John | 100000 |     6           | 4/1/2006  |
+|   2      | Amy  | 120000 |     5           | 5/1/2010  |
+|   3      | Mark | 65000  |     12          | 12/25/2008|
+|   4      | Pam  | 25000  |     25          | 1/1/2005  |
+|   5      | Alex | 50000  |     10          | 2/3/2007  |
++----------+------+--------+-----------------+-----------+
+
+The table salesperson holds the salesperson information. Every salesperson has a sales_id and a name. + +

Table: company

+ +
++---------+--------+------------+
+| com_id  |  name  |    city    |
++---------+--------+------------+
+|   1     |  RED   |   Boston   |
+|   2     | ORANGE |   New York |
+|   3     | YELLOW |   Boston   |
+|   4     | GREEN  |   Austin   |
++---------+--------+------------+
+
+The table company holds the company information. Every company has a com_id and a name. + +

Table: orders

+ +
++----------+------------+---------+----------+--------+
+| order_id | order_date | com_id  | sales_id | amount |
++----------+------------+---------+----------+--------+
+| 1        |   1/1/2014 |    3    |    4     | 100000 |
+| 2        |   2/1/2014 |    4    |    5     | 5000   |
+| 3        |   3/1/2014 |    1    |    1     | 50000  |
+| 4        |   4/1/2014 |    1    |    4     | 25000  |
++----------+----------+---------+----------+--------+
+
+The table orders holds the sales record information, salesperson and customer company are represented by sales_id and com_id. + +

output

+ +
++------+
+| name | 
++------+
+| Amy  | 
+| Mark | 
+| Alex |
++------+
+
+ +

Explanation

+ +

According to order '3' and '4' in table orders, it is easy to tell only salesperson 'John' and 'Pam' have sales to company 'RED',
+so we need to output all the other names in the table salesperson.

+ + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT name +FROM salesperson +WHERE sales_id +NOT IN ( + SELECT s.sales_id FROM orders o + INNER JOIN salesperson s ON o.sales_id = s.sales_id + INNER JOIN company c ON o.com_id = c.com_id + WHERE c.name = 'RED' +); +``` + + diff --git a/assets/0600-0699/0608.Tree Node/README_EN.md b/assets/0600-0699/0608.Tree Node/README_EN.md new file mode 100644 index 00000000..6cdd2d5a --- /dev/null +++ b/assets/0600-0699/0608.Tree Node/README_EN.md @@ -0,0 +1,128 @@ +# [608. Tree Node](https://leetcode.com/problems/tree-node) + + + +## Description + +

Given a table tree, id is identifier of the tree node and p_id is its parent node's id.

+ + + +
+
++----+------+
+
+| id | p_id |
+
++----+------+
+
+| 1  | null |
+
+| 2  | 1    |
+
+| 3  | 1    |
+
+| 4  | 2    |
+
+| 5  | 2    |
+
++----+------+
+
+
+ +Each node in the tree can be one of three types: + + + +
    +
  • Leaf: if the node is a leaf node.
  • +
  • Root: if the node is the root of the tree.
  • +
  • Inner: If the node is neither a leaf node nor a root node.
  • +
+ + + +

 

+ +Write a query to print the node id and the type of the node. Sort your output by the node id. The result for the above sample is: + + + +

 

+ + + +
+
++----+------+
+
+| id | Type |
+
++----+------+
+
+| 1  | Root |
+
+| 2  | Inner|
+
+| 3  | Leaf |
+
+| 4  | Leaf |
+
+| 5  | Leaf |
+
++----+------+
+
+
+ + + +

 

+ + + +

Explanation

+ + + +

 

+ + + +
    +
  • Node '1' is root node, because its parent node is NULL and it has child node '2' and '3'.
  • +
  • Node '2' is inner node, because it has parent node '1' and child node '4' and '5'.
  • +
  • Node '3', '4' and '5' is Leaf node, because they have parent node and they don't have child node.
  • +
    +
  • And here is the image of the sample tree as below: +

     

    +
    +
    +			  1
    +
    +			/   \
    +
    +                      2       3
    +
    +                    /   \
    +
    +                  4       5
    +
    +
    +

    Note

    +

    If there is only one node on the tree, you only need to output its root attributes.

    +
  • +
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0609.Find Duplicate File in System/README_EN.md b/assets/0600-0699/0609.Find Duplicate File in System/README_EN.md new file mode 100644 index 00000000..d6d65310 --- /dev/null +++ b/assets/0600-0699/0609.Find Duplicate File in System/README_EN.md @@ -0,0 +1,79 @@ +# [609. Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system) + + + +## Description + +

Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.

+ +

A group of duplicate files consists of at least two files that have the same content.

+ +

A single directory info string in the input list has the following format:

+ +
    +
  • "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
  • +
+ +

It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

+ +

The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

+ +
    +
  • "directory_path/file_name.txt"
  • +
+ +

 

+

Example 1:

+
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
+Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
+

Example 2:

+
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
+Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= paths.length <= 2 * 104
  • +
  • 1 <= paths[i].length <= 3000
  • +
  • 1 <= sum(paths[i].length) <= 5 * 105
  • +
  • paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
  • +
  • You may assume no files or directories share the same name in the same directory.
  • +
  • You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
  • +
+ +

 

+

Follow up:

+ +
    +
  • Imagine you are given a real file system, how will you search files? DFS or BFS?
  • +
  • If the file content is very large (GB level), how will you modify your solution?
  • +
  • If you can only read the file by 1kb each time, how will you modify your solution?
  • +
  • What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
  • +
  • How to make sure the duplicated files you find are not false positive?
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0610.Triangle Judgement/README_EN.md b/assets/0600-0699/0610.Triangle Judgement/README_EN.md new file mode 100644 index 00000000..7d4bee69 --- /dev/null +++ b/assets/0600-0699/0610.Triangle Judgement/README_EN.md @@ -0,0 +1,65 @@ +# [610. Triangle Judgement](https://leetcode.com/problems/triangle-judgement) + + + +## Description + +A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. + +

 

+ +However, this assignment is very heavy because there are hundreds of records to calculate. + + + +

 

+ +Could you help Tim by writing a query to judge whether these three sides can form a triangle, assuming table triangle holds the length of the three sides x, y and z. + + + +

 

+ + + +
+
+| x  | y  | z  |
+
+|----|----|----|
+
+| 13 | 15 | 30 |
+
+| 10 | 20 | 15 |
+
+
+ +For the sample data above, your query should return the follow result: + + + +
+
+| x  | y  | z  | triangle |
+
+|----|----|----|----------|
+
+| 13 | 15 | 30 | No       |
+
+| 10 | 20 | 15 | Yes      |
+
+
+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/0600-0699/0611.Valid Triangle Number/README_EN.md b/assets/0600-0699/0611.Valid Triangle Number/README_EN.md new file mode 100644 index 00000000..62ad76ba --- /dev/null +++ b/assets/0600-0699/0611.Valid Triangle Number/README_EN.md @@ -0,0 +1,71 @@ +# [611. Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number) + + + +## Description + +Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. + + + +

Example 1:
+ +

+
+Input: [2,2,3,4]
+
+Output: 3
+
+Explanation:
+
+Valid combinations are: 
+
+2,3,4 (using the first 2)
+
+2,3,4 (using the second 2)
+
+2,2,3
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The length of the given array won't exceed 1000.
  2. + +
  3. The integers in the given array are in the range of [0, 1000].
  4. + +
+ +

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0612.Shortest Distance in a Plane/README_EN.md b/assets/0600-0699/0612.Shortest Distance in a Plane/README_EN.md new file mode 100644 index 00000000..32d99139 --- /dev/null +++ b/assets/0600-0699/0612.Shortest Distance in a Plane/README_EN.md @@ -0,0 +1,77 @@ +# [612. Shortest Distance in a Plane](https://leetcode.com/problems/shortest-distance-in-a-plane) + + + +## Description + +Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane. + +

 

+ +Write a query to find the shortest distance between these points rounded to 2 decimals. + + + +

 

+ + + +
+
+| x  | y  |
+
+|----|----|
+
+| -1 | -1 |
+
+| 0  | 0  |
+
+| -1 | -2 |
+
+
+ + + +

 

+ +The shortest distance is 1.00 from point (-1,-1) to (-1,2). So the output should be: + + + +

 

+ + + +
+
+| shortest |
+
+|----------|
+
+| 1.00     |
+
+
+ + + +

 

+ +Note: The longest distance among all the points are less than 10000. + + + +

 

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0613.Shortest Distance in a Line/README_EN.md b/assets/0600-0699/0613.Shortest Distance in a Line/README_EN.md new file mode 100644 index 00000000..85595307 --- /dev/null +++ b/assets/0600-0699/0613.Shortest Distance in a Line/README_EN.md @@ -0,0 +1,83 @@ +# [613. Shortest Distance in a Line](https://leetcode.com/problems/shortest-distance-in-a-line) + + + +## Description + +Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. + +

 

+ +Write a query to find the shortest distance between two points in these points. + + + +

 

+ + + +
+
+| x   |
+
+|-----|
+
+| -1  |
+
+| 0   |
+
+| 2   |
+
+
+ + + +

 

+ +The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below: + + + +

 

+ + + +
+
+| shortest|
+
+|---------|
+
+| 1       |
+
+
+ + + +

 

+ +Note: Every point is unique, which means there is no duplicates in table point. + + + +

 

+ +Follow-up: What if all these points have an id and are arranged from the left most to the right most of x axis? + + + +

 

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0614.Second Degree Follower/README_EN.md b/assets/0600-0699/0614.Second Degree Follower/README_EN.md new file mode 100644 index 00000000..40c2ae37 --- /dev/null +++ b/assets/0600-0699/0614.Second Degree Follower/README_EN.md @@ -0,0 +1,89 @@ +# [614. Second Degree Follower](https://leetcode.com/problems/second-degree-follower) + + + +## Description + +

In facebook, there is a follow table with two columns: followee, follower.

+ + + +

Please write a sql query to get the amount of each follower’s follower if he/she has one.

+ + + +

For example:

+ + + +
+
++-------------+------------+
+
+| followee    | follower   |
+
++-------------+------------+
+
+|     A       |     B      |
+
+|     B       |     C      |
+
+|     B       |     D      |
+
+|     D       |     E      |
+
++-------------+------------+
+
+
+ +should output: + + + +
+
++-------------+------------+
+
+| follower    | num        |
+
++-------------+------------+
+
+|     B       |  2         |
+
+|     D       |  1         |
+
++-------------+------------+
+
+
+ +Explaination:
+ +Both B and D exist in the follower list, when as a followee, B's follower is C and D, and D's follower is E. A does not exist in follower list. + +

 

+ + + +

 

+ +Note:
+ +Followee would not follow himself/herself in all cases.
+ +Please display the result in follower's alphabet order. + +

 

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0615.Average Salary Departments VS Company/README_EN.md b/assets/0600-0699/0615.Average Salary Departments VS Company/README_EN.md new file mode 100644 index 00000000..4c4a2de9 --- /dev/null +++ b/assets/0600-0699/0615.Average Salary Departments VS Company/README_EN.md @@ -0,0 +1,135 @@ +# [615. Average Salary Departments VS Company](https://leetcode.com/problems/average-salary-departments-vs-company) + + + +## Description + +Given two tables as below, write a query to display the comparison result (higher/lower/same) of the average salary of employees in a department to the company's average salary. + +

 

+ +Table: salary + + + +
+
+| id | employee_id | amount | pay_date   |
+
+|----|-------------|--------|------------|
+
+| 1  | 1           | 9000   | 2017-03-31 |
+
+| 2  | 2           | 6000   | 2017-03-31 |
+
+| 3  | 3           | 10000  | 2017-03-31 |
+
+| 4  | 1           | 7000   | 2017-02-28 |
+
+| 5  | 2           | 6000   | 2017-02-28 |
+
+| 6  | 3           | 8000   | 2017-02-28 |
+
+
+ + + +

 

+ +The employee_id column refers to the employee_id in the following table employee. + + + +

 

+ + + +
+
+| employee_id | department_id |
+
+|-------------|---------------|
+
+| 1           | 1             |
+
+| 2           | 2             |
+
+| 3           | 2             |
+
+
+ + + +

 

+ +So for the sample data above, the result is: + + + +

 

+ + + +
+
+| pay_month | department_id | comparison  |
+
+|-----------|---------------|-------------|
+
+| 2017-03   | 1             | higher      |
+
+| 2017-03   | 2             | lower       |
+
+| 2017-02   | 1             | same        |
+
+| 2017-02   | 2             | same        |
+
+
+ + + +

 

+ +Explanation + + + +

 

+ +In March, the company's average salary is (9000+6000+10000)/3 = 8333.33... + + + +

 

+ +The average salary for department '1' is 9000, which is the salary of employee_id '1' since there is only one employee in this department. So the comparison result is 'higher' since 9000 > 8333.33 obviously. + + + +

 

+ +The average salary of department '2' is (6000 + 10000)/2 = 8000, which is the average of employee_id '2' and '3'. So the comparison result is 'lower' since 8000 < 8333.33. + + + +

 

+ +With he same formula for the average salary comparison in February, the result is 'same' since both the department '1' and '2' have the same average salary with the company, which is 7000. + + + +

 

+ + + +## Solutions + + + +### **SQL** + +``` + +``` + + diff --git a/assets/0600-0699/0616.Add Bold Tag in String/README_EN.md b/assets/0600-0699/0616.Add Bold Tag in String/README_EN.md new file mode 100644 index 00000000..3b900726 --- /dev/null +++ b/assets/0600-0699/0616.Add Bold Tag in String/README_EN.md @@ -0,0 +1,64 @@ +# [616. Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string) + + + +## Description + +Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two substrings wrapped by bold tags are consecutive, you need to combine them. +

Example 1:

+ +
+Input: 
+s = "abcxyz123"
+dict = ["abc","123"]
+Output:
+"<b>abc</b>xyz<b>123</b>"
+
+ +

 

+ +

Example 2:

+ +
+Input: 
+s = "aaabbcc"
+dict = ["aaa","aab","bc"]
+Output:
+"<b>aaabbc</b>c"
+
+ +

 

+ +

Constraints:

+ +
    +
  • The given dict won't contain duplicates, and its length won't exceed 100.
  • +
  • All the strings in input have length in range [1, 1000].
  • +
+ +

Note: This question is the same as 758: https://leetcode.com/problems/bold-words-in-string/

+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0617.Merge Two Binary Trees/README_EN.md b/assets/0600-0699/0617.Merge Two Binary Trees/README_EN.md new file mode 100644 index 00000000..f701a42d --- /dev/null +++ b/assets/0600-0699/0617.Merge Two Binary Trees/README_EN.md @@ -0,0 +1,187 @@ +# [617. Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees) + + + +## Description + +

You are given two binary trees root1 and root2.

+ +

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

+ +

Return the merged tree.

+ +

Note: The merging process must start from the root nodes of both trees.

+ +

 

+

Example 1:

+ +
+Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
+Output: [3,4,5,5,4,null,7]
+
+ +

Example 2:

+ +
+Input: root1 = [1], root2 = [1,2]
+Output: [2,2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in both trees is in the range [0, 2000].
  • +
  • -104 <= Node.val <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: + if root1 is None: + return root2 + if root2 is None: + return root1 + node = TreeNode(root1.val + root2.val) + node.left = self.mergeTrees(root1.left, root2.left) + node.right = self.mergeTrees(root1.right, root2.right) + return node +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + TreeNode node = new TreeNode(root1.val + root2.val); + node.left = mergeTrees(root1.left, root2.left); + node.right = mergeTrees(root1.right, root2.right); + return node; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + + function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { + if (root1 == null && root2 == null) return null; + if (root1 == null) return root2; + if (root2 == null) return root1; + let left = mergeTrees(root1.left, root2.left); + let right = mergeTrees(root1.right, root2.right); + return new TreeNode(root1.val + root2.val, left, right); +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { + if (root1 == nullptr) { + return root2; + } + if (root2 == nullptr) { + return root1; + } + TreeNode *node = new TreeNode(root1->val + root2->val); + node->left = mergeTrees(root1->left, root2->left); + node->right = mergeTrees(root1->right, root2->right); + return node; + } +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode { + if root1 == nil { + return root2 + } + if root2 == nil { + return root1 + } + node := &TreeNode{Val: root1.Val + root2.Val} + node.Left = mergeTrees(root1.Left, root2.Left) + node.Right = mergeTrees(root1.Right, root2.Right) + return node +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0617.Merge Two Binary Trees/images/merge.jpg b/assets/0600-0699/0617.Merge Two Binary Trees/images/merge.jpg new file mode 100644 index 00000000..5edaa11e Binary files /dev/null and b/assets/0600-0699/0617.Merge Two Binary Trees/images/merge.jpg differ diff --git a/assets/0600-0699/0618.Students Report By Geography/README_EN.md b/assets/0600-0699/0618.Students Report By Geography/README_EN.md new file mode 100644 index 00000000..18f2759d --- /dev/null +++ b/assets/0600-0699/0618.Students Report By Geography/README_EN.md @@ -0,0 +1,81 @@ +# [618. Students Report By Geography](https://leetcode.com/problems/students-report-by-geography) + + + +## Description + +A U.S graduate school has students from Asia, Europe and America. The students' location information are stored in table student as below. + +

 

+ + + +
+
+| name   | continent |
+
+|--------|-----------|
+
+| Jack   | America   |
+
+| Pascal | Europe    |
+
+| Xi     | Asia      |
+
+| Jane   | America   |
+
+
+ + + +

 

+ + Pivot the continent column in this table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia and Europe respectively. It is guaranteed that the student number from America is no less than either Asia or Europe. + + + +

 

+ +For the sample input, the output is: + + + +

 

+ + + +
+
+| America | Asia | Europe |
+
+|---------|------|--------|
+
+| Jack    | Xi   | Pascal |
+
+| Jane    |      |        |
+
+
+ + + +

 

+ +Follow-up: If it is unknown which continent has the most students, can you write a query to generate the student report? + + + +

 

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0619.Biggest Single Number/README_EN.md b/assets/0600-0699/0619.Biggest Single Number/README_EN.md new file mode 100644 index 00000000..4c5ce297 --- /dev/null +++ b/assets/0600-0699/0619.Biggest Single Number/README_EN.md @@ -0,0 +1,75 @@ +# [619. Biggest Single Number](https://leetcode.com/problems/biggest-single-number) + + + +## Description + +

Table my_numbers contains many numbers in column num including duplicated ones.
+ +Can you write a SQL query to find the biggest number, which only appears once.

+ + + +
+
++---+
+
+|num|
+
++---+
+
+| 8 |
+
+| 8 |
+
+| 3 |
+
+| 3 |
+
+| 1 |
+
+| 4 |
+
+| 5 |
+
+| 6 | 
+
+
+ +For the sample data above, your query should return the following result: + + + +
+
++---+
+
+|num|
+
++---+
+
+| 6 |
+
+
+ +Note:
+ +If there is no such number, just output null. + + + +

 

+ + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/0600-0699/0620.Not Boring Movies/README_EN.md b/assets/0600-0699/0620.Not Boring Movies/README_EN.md new file mode 100644 index 00000000..b1090cd4 --- /dev/null +++ b/assets/0600-0699/0620.Not Boring Movies/README_EN.md @@ -0,0 +1,83 @@ +# [620. Not Boring Movies](https://leetcode.com/problems/not-boring-movies) + + + +## Description + +X city opened a new cinema, many people would like to go to this cinema. The cinema also gives out a poster indicating the movies’ ratings and descriptions. + +

Please write a SQL query to output movies with an odd numbered ID and a description that is not 'boring'. Order the result by rating.

+ + + +

 

+ + + +

For example, table cinema:

+ + + +
+
++---------+-----------+--------------+-----------+
+
+|   id    | movie     |  description |  rating   |
+
++---------+-----------+--------------+-----------+
+
+|   1     | War       |   great 3D   |   8.9     |
+
+|   2     | Science   |   fiction    |   8.5     |
+
+|   3     | irish     |   boring     |   6.2     |
+
+|   4     | Ice song  |   Fantacy    |   8.6     |
+
+|   5     | House card|   Interesting|   9.1     |
+
++---------+-----------+--------------+-----------+
+
+
+ +For the example above, the output should be: + + + +
+
++---------+-----------+--------------+-----------+
+
+|   id    | movie     |  description |  rating   |
+
++---------+-----------+--------------+-----------+
+
+|   5     | House card|   Interesting|   9.1     |
+
+|   1     | War       |   great 3D   |   8.9     |
+
++---------+-----------+--------------+-----------+
+
+
+ + + +

 

+ + + +## Solutions + + + +### **SQL** + +``` +SELECT * +FROM cinema +WHERE description NOT LIKE '%boring%' + AND mod(id,2)=1 +ORDER BY rating desc; +``` + + diff --git a/assets/0600-0699/0621.Task Scheduler/README_EN.md b/assets/0600-0699/0621.Task Scheduler/README_EN.md new file mode 100644 index 00000000..9933aea6 --- /dev/null +++ b/assets/0600-0699/0621.Task Scheduler/README_EN.md @@ -0,0 +1,79 @@ +# [621. Task Scheduler](https://leetcode.com/problems/task-scheduler) + + + +## Description + +

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

+ +

However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

+ +

Return the least number of units of times that the CPU will take to finish all the given tasks.

+ +

 

+

Example 1:

+ +
+Input: tasks = ["A","A","A","B","B","B"], n = 2
+Output: 8
+Explanation: 
+A -> B -> idle -> A -> B -> idle -> A -> B
+There is at least 2 units of time between any two same tasks.
+
+ +

Example 2:

+ +
+Input: tasks = ["A","A","A","B","B","B"], n = 0
+Output: 6
+Explanation: On this case any permutation of size 6 would work since n = 0.
+["A","A","A","B","B","B"]
+["A","B","A","B","A","B"]
+["B","B","B","A","A","A"]
+...
+And so on.
+
+ +

Example 3:

+ +
+Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
+Output: 16
+Explanation: 
+One possible solution is
+A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= task.length <= 104
  • +
  • tasks[i] is upper-case English letter.
  • +
  • The integer n is in the range [0, 100].
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0622.Design Circular Queue/README_EN.md b/assets/0600-0699/0622.Design Circular Queue/README_EN.md new file mode 100644 index 00000000..dd047907 --- /dev/null +++ b/assets/0600-0699/0622.Design Circular Queue/README_EN.md @@ -0,0 +1,191 @@ +# [622. Design Circular Queue](https://leetcode.com/problems/design-circular-queue) + + + +## Description + +

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".

+ +

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

+ +

Implementation the MyCircularQueue class:

+ +
    +
  • MyCircularQueue(k) Initializes the object with the size of the queue to be k.
  • +
  • int Front() Gets the front item from the queue. If the queue is empty, return -1.
  • +
  • int Rear() Gets the last item from the queue. If the queue is empty, return -1.
  • +
  • boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.
  • +
  • boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.
  • +
  • boolean isEmpty() Checks whether the circular queue is empty or not.
  • +
  • boolean isFull() Checks whether the circular queue is full or not.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]
+[[3], [1], [2], [3], [4], [], [], [], [4], []]
+Output
+[null, true, true, true, false, 3, true, true, true, 4]
+
+Explanation
+MyCircularQueue myCircularQueue = new MyCircularQueue(3);
+myCircularQueue.enQueue(1); // return True
+myCircularQueue.enQueue(2); // return True
+myCircularQueue.enQueue(3); // return True
+myCircularQueue.enQueue(4); // return False
+myCircularQueue.Rear();     // return 3
+myCircularQueue.isFull();   // return True
+myCircularQueue.deQueue();  // return True
+myCircularQueue.enQueue(4); // return True
+myCircularQueue.Rear();     // return 4
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k <= 1000
  • +
  • 0 <= value <= 1000
  • +
  • At most 3000 calls will be made to enQueue, deQueueFrontRearisEmpty, and isFull.
  • +
+ +

 

+Follow up: Could you solve the problem without using the built-in queue?  + +## Solutions + + + +### **Python3** + +```python +class MyCircularQueue: + + def __init__(self, k: int): + self.q = [0] * k + self.front = 0 + self.size = 0 + self.capacity = k + + def enQueue(self, value: int) -> bool: + if self.isFull(): + return False + idx = (self.front + self.size) % self.capacity + self.q[idx] = value + self.size += 1 + return True + + def deQueue(self) -> bool: + if self.isEmpty(): + return False + self.front = (self.front + 1) % self.capacity + self.size -= 1 + return True + + def Front(self) -> int: + if self.isEmpty(): + return -1 + return self.q[self.front] + + def Rear(self) -> int: + if self.isEmpty(): + return -1 + idx = (self.front + self.size - 1) % self.capacity + return self.q[idx] + + def isEmpty(self) -> bool: + return self.size == 0 + + def isFull(self) -> bool: + return self.size == self.capacity + + +# Your MyCircularQueue object will be instantiated and called as such: +# obj = MyCircularQueue(k) +# param_1 = obj.enQueue(value) +# param_2 = obj.deQueue() +# param_3 = obj.Front() +# param_4 = obj.Rear() +# param_5 = obj.isEmpty() +# param_6 = obj.isFull() +``` + +### **Java** + +```java +class MyCircularQueue { + private int[] q; + private int front; + private int size; + private int capacity; + + public MyCircularQueue(int k) { + q = new int[k]; + capacity = k; + } + + public boolean enQueue(int value) { + if (isFull()) { + return false; + } + int idx = (front + size) % capacity; + q[idx] = value; + ++size; + return true; + } + + public boolean deQueue() { + if (isEmpty()) { + return false; + } + front = (front + 1) % capacity; + --size; + return true; + } + + public int Front() { + if (isEmpty()) { + return -1; + } + return q[front]; + } + + public int Rear() { + if (isEmpty()) { + return -1; + } + int idx = (front + size - 1) % capacity; + return q[idx]; + } + + public boolean isEmpty() { + return size == 0; + } + + public boolean isFull() { + return size == capacity; + } +} + +/** + * Your MyCircularQueue object will be instantiated and called as such: + * MyCircularQueue obj = new MyCircularQueue(k); + * boolean param_1 = obj.enQueue(value); + * boolean param_2 = obj.deQueue(); + * int param_3 = obj.Front(); + * int param_4 = obj.Rear(); + * boolean param_5 = obj.isEmpty(); + * boolean param_6 = obj.isFull(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0623.Add One Row to Tree/README_EN.md b/assets/0600-0699/0623.Add One Row to Tree/README_EN.md new file mode 100644 index 00000000..82d4953f --- /dev/null +++ b/assets/0600-0699/0623.Add One Row to Tree/README_EN.md @@ -0,0 +1,69 @@ +# [623. Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree) + + + +## Description + +

Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

+ +

Note that the root node is at depth 1.

+ +

The adding rule is:

+ +
    +
  • Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
  • +
  • cur's original left subtree should be the left subtree of the new left subtree root.
  • +
  • cur's original right subtree should be the right subtree of the new right subtree root.
  • +
  • If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
  • +
+ +

 

+

Example 1:

+ +
+Input: root = [4,2,6,3,1,5], val = 1, depth = 2
+Output: [4,1,1,2,null,null,6,3,1,5]
+
+ +

Example 2:

+ +
+Input: root = [4,2,null,3,1], val = 1, depth = 3
+Output: [4,2,null,1,1,3,null,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • The depth of the tree is in the range [1, 104].
  • +
  • -100 <= Node.val <= 100
  • +
  • -105 <= val <= 105
  • +
  • 1 <= depth <= the depth of tree + 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0623.Add One Row to Tree/images/add2-tree.jpg b/assets/0600-0699/0623.Add One Row to Tree/images/add2-tree.jpg new file mode 100644 index 00000000..209bdea2 Binary files /dev/null and b/assets/0600-0699/0623.Add One Row to Tree/images/add2-tree.jpg differ diff --git a/assets/0600-0699/0623.Add One Row to Tree/images/addrow-tree.jpg b/assets/0600-0699/0623.Add One Row to Tree/images/addrow-tree.jpg new file mode 100644 index 00000000..1439ea2c Binary files /dev/null and b/assets/0600-0699/0623.Add One Row to Tree/images/addrow-tree.jpg differ diff --git a/assets/0600-0699/0624.Maximum Distance in Arrays/README_EN.md b/assets/0600-0699/0624.Maximum Distance in Arrays/README_EN.md new file mode 100644 index 00000000..76f15aad --- /dev/null +++ b/assets/0600-0699/0624.Maximum Distance in Arrays/README_EN.md @@ -0,0 +1,78 @@ +# [624. Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays) + + + +## Description + +

You are given m arrays, where each array is sorted in ascending order.

+ +

You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.

+ +

Return the maximum distance.

+ +

 

+

Example 1:

+ +
+Input: arrays = [[1,2,3],[4,5],[1,2,3]]
+Output: 4
+Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.
+
+ +

Example 2:

+ +
+Input: arrays = [[1],[1]]
+Output: 0
+
+ +

Example 3:

+ +
+Input: arrays = [[1],[2]]
+Output: 1
+
+ +

Example 4:

+ +
+Input: arrays = [[1,4],[0,5]]
+Output: 4
+
+ +

 

+

Constraints:

+ +
    +
  • m == arrays.length
  • +
  • 2 <= m <= 105
  • +
  • 1 <= arrays[i].length <= 500
  • +
  • -104 <= arrays[i][j] <= 104
  • +
  • arrays[i] is sorted in ascending order.
  • +
  • There will be at most 105 integers in all the arrays.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0625.Minimum Factorization/README_EN.md b/assets/0600-0699/0625.Minimum Factorization/README_EN.md new file mode 100644 index 00000000..4db8427c --- /dev/null +++ b/assets/0600-0699/0625.Minimum Factorization/README_EN.md @@ -0,0 +1,71 @@ +# [625. Minimum Factorization](https://leetcode.com/problems/minimum-factorization) + + + +## Description + +

Given a positive integer a, find the smallest positive integer b whose multiplication of each digit equals to a.

+ + + +

+ +If there is no answer or the answer is not fit in 32-bit signed integer, then return 0.

+ + + +

+ +Example 1
+ +Input: + +

48 
+ +Output: + +
68
+ +

+ + + +

+ +Example 2
+ +Input: + +

15
+ + + +Output: + +
35
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0626.Exchange Seats/README_EN.md b/assets/0600-0699/0626.Exchange Seats/README_EN.md new file mode 100644 index 00000000..931bc4c8 --- /dev/null +++ b/assets/0600-0699/0626.Exchange Seats/README_EN.md @@ -0,0 +1,64 @@ +# [626. Exchange Seats](https://leetcode.com/problems/exchange-seats) + + + +## Description + +

Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids.

+ +

The column id is continuous increment.

+ +

Mary wants to change seats for the adjacent students.

+ +

Can you write a SQL query to output the result for Mary?

+ +

 

+ +
++---------+---------+
+|    id   | student |
++---------+---------+
+|    1    | Abbot   |
+|    2    | Doris   |
+|    3    | Emerson |
+|    4    | Green   |
+|    5    | Jeames  |
++---------+---------+
+
+ +

For the sample input, the output is:

+ +
++---------+---------+
+|    id   | student |
++---------+---------+
+|    1    | Doris   |
+|    2    | Abbot   |
+|    3    | Green   |
+|    4    | Emerson |
+|    5    | Jeames  |
++---------+---------+
+
+ +

Note:

+ +

If the number of students is odd, there is no need to change the last one's seat.

+ + +## Solutions + + + +### **SQL** + +``` +SELECT + s1.id, COALESCE(s2.student, s1.student) AS student +FROM + seat s1 + LEFT JOIN + seat s2 ON (s1.id+1)^1-1 = s2.id +ORDER BY s1.id; +``` + + diff --git a/assets/0600-0699/0627.Swap Salary/README_EN.md b/assets/0600-0699/0627.Swap Salary/README_EN.md new file mode 100644 index 00000000..72d4a7bd --- /dev/null +++ b/assets/0600-0699/0627.Swap Salary/README_EN.md @@ -0,0 +1,73 @@ +# [627. Swap Salary](https://leetcode.com/problems/swap-salary) + + + +## Description + +

Table: Salary

+ +
++-------------+----------+
+| Column Name | Type     |
++-------------+----------+
+| id          | int      |
+| name        | varchar  |
+| sex         | ENUM     |
+| salary      | int      |
++-------------+----------+
+id is the primary key for this table.
+The sex column is ENUM value of type ('m', 'f').
+The table contains information about an employee.
+
+ +

 

+ +

Write an SQL query to swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a single update statement and no intermediate temp table(s).

+ +

Note that you must write a single update statement, DO NOT write any select statement for this problem.

+ +

The query result format is in the following example:

+ +

 

+ +
+Salary table:
++----+------+-----+--------+
+| id | name | sex | salary |
++----+------+-----+--------+
+| 1  | A    | m   | 2500   |
+| 2  | B    | f   | 1500   |
+| 3  | C    | m   | 5500   |
+| 4  | D    | f   | 500    |
++----+------+-----+--------+
+
+Result table:
++----+------+-----+--------+
+| id | name | sex | salary |
++----+------+-----+--------+
+| 1  | A    | f   | 2500   |
+| 2  | B    | m   | 1500   |
+| 3  | C    | f   | 5500   |
+| 4  | D    | m   | 500    |
++----+------+-----+--------+
+(1, A) and (3, C) were changed from 'm' to 'f'.
+(2, B) and (4, D) were changed from 'f' to 'm'.
+
+ + +## Solutions + + + +### **SQL** + +``` +UPDATE salary +SET + sex = CASE sex + WHEN 'm' THEN 'f' + ELSE 'm' + END; +``` + + diff --git a/assets/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md b/assets/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md new file mode 100644 index 00000000..a7bda997 --- /dev/null +++ b/assets/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md @@ -0,0 +1,61 @@ +# [628. Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers) + + + +## Description + +

Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

+ +

 

+

Example 1:

+
Input: nums = [1,2,3]
+Output: 6
+

Example 2:

+
Input: nums = [1,2,3,4]
+Output: 24
+

Example 3:

+
Input: nums = [-1,-2,-3]
+Output: -6
+
+

 

+

Constraints:

+ +
    +
  • 3 <= nums.length <= 104
  • +
  • -1000 <= nums[i] <= 1000
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + n = len(nums) + nums.sort() + return max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]) +``` + +### **Java** + +```java +class Solution { + public int maximumProduct(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return Math.max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0629.K Inverse Pairs Array/README_EN.md b/assets/0600-0699/0629.K Inverse Pairs Array/README_EN.md new file mode 100644 index 00000000..a5666b48 --- /dev/null +++ b/assets/0600-0699/0629.K Inverse Pairs Array/README_EN.md @@ -0,0 +1,99 @@ +# [629. K Inverse Pairs Array](https://leetcode.com/problems/k-inverse-pairs-array) + + + +## Description + +

Given two integers n and k, find how many different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs.

+ + + +

We define an inverse pair as following: For ith and jth element in the array, if i < j and a[i] > a[j] then it's an inverse pair; Otherwise, it's not.

+ + + +

Since the answer may be very large, the answer should be modulo 109 + 7.

+ + + +

Example 1:

+ + + +
+
+Input: n = 3, k = 0
+
+Output: 1
+
+Explanation: 
+
+Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair.
+
+
+ + + +

 

+ + + +

Example 2:

+ + + +
+
+Input: n = 3, k = 1
+
+Output: 2
+
+Explanation: 
+
+The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. The integer n is in the range [1, 1000] and k is in the range [0, 1000].
  2. +
+ + + +

 

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0630.Course Schedule III/README_EN.md b/assets/0600-0699/0630.Course Schedule III/README_EN.md new file mode 100644 index 00000000..5cc05712 --- /dev/null +++ b/assets/0600-0699/0630.Course Schedule III/README_EN.md @@ -0,0 +1,82 @@ +# [630. Course Schedule III](https://leetcode.com/problems/course-schedule-iii) + + + +## Description + +

There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.

+ + + +

Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

+ + + +

Example:

+ + + +
+
+Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
+
+Output: 3
+
+Explanation: 
+
+There're totally 4 courses, but you can take 3 courses at most:
+
+First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
+
+Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. 
+
+Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. 
+
+The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. The integer 1 <= d, t, n <= 10,000.
  2. +
  3. You can't take two courses simultaneously.
  4. +
+ + + +

 

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0631.Design Excel Sum Formula/README_EN.md b/assets/0600-0699/0631.Design Excel Sum Formula/README_EN.md new file mode 100644 index 00000000..816c33ce --- /dev/null +++ b/assets/0600-0699/0631.Design Excel Sum Formula/README_EN.md @@ -0,0 +1,143 @@ +# [631. Design Excel Sum Formula](https://leetcode.com/problems/design-excel-sum-formula) + + + +## Description + +

Your task is to design the basic function of Excel and implement the function of sum formula. Specifically, you need to implement the following functions:

+ + + + + + + +

Excel(int H, char W): This is the constructor. The inputs represents the height and width of the Excel form. H is a positive integer, range from 1 to 26. It represents the height. W is a character range from 'A' to 'Z'. It represents that the width is the number of characters from 'A' to W. The Excel form content is represented by a height * width 2D integer array C, it should be initialized to zero. You should assume that the first row of C starts from 1, and the first column of C starts from 'A'.

+ + + +
+ + + +

void Set(int row, char column, int val): Change the value at C(row, column) to be val.

+ +
+ +

int Get(int row, char column): Return the value at C(row, column).

+ +
+ +

int Sum(int row, char column, List of Strings : numbers): This function calculate and set the value at C(row, column), where the value should be the sum of cells represented by numbers. This function return the sum result at C(row, column). This sum formula should exist until this cell is overlapped by another value or another sum formula.

+ + + +

numbers is a list of strings that each string represent a cell or a range of cells. If the string represent a single cell, then it has the following format : ColRow. For example, "F7" represents the cell at (7, F).

+ + + +

If the string represent a range of cells, then it has the following format : ColRow1:ColRow2. The range will always be a rectangle, and ColRow1 represent the position of the top-left cell, and ColRow2 represents the position of the bottom-right cell.

+ +
+ +

Example 1:
+ +

+
+Excel(3,"C"); 
+
+// construct a 3*3 2D array with all zero.
+
+//   A B C
+
+// 1 0 0 0
+
+// 2 0 0 0
+
+// 3 0 0 0
+
+
+
+Set(1, "A", 2);
+
+// set C(1,"A") to be 2.
+
+//   A B C
+
+// 1 2 0 0
+
+// 2 0 0 0
+
+// 3 0 0 0
+
+
+
+Sum(3, "C", ["A1", "A1:B2"]);
+
+// set C(3,"C") to be the sum of value at C(1,"A") and the values sum of the rectangle range whose top-left cell is C(1,"A") and bottom-right cell is C(2,"B"). Return 4. 
+
+//   A B C
+
+// 1 2 0 0
+
+// 2 0 0 0
+
+// 3 0 0 4
+
+
+
+Set(2, "B", 2);
+
+// set C(2,"B") to be 2. Note C(3, "C") should also be changed.
+
+//   A B C
+
+// 1 2 0 0
+
+// 2 0 2 0
+
+// 3 0 0 6
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. You could assume that there won't be any circular sum reference. For example, A1 = sum(B1) and B1 = sum(A1).
  2. + +
  3. The test cases are using double-quotes to represent a character.
  4. + +
  5. Please remember to RESET your class variables declared in class Excel, as static/class variables are persisted across multiple test cases. Please see here for more details.
  6. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md b/assets/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md new file mode 100644 index 00000000..6d2bf7c5 --- /dev/null +++ b/assets/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md @@ -0,0 +1,85 @@ +# [632. Smallest Range Covering Elements from K Lists](https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists) + + + +## Description + +

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.

+ +

We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

+ +

 

+

Example 1:

+ +
+Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
+Output: [20,24]
+Explanation: 
+List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
+List 2: [0, 9, 12, 20], 20 is in range [20,24].
+List 3: [5, 18, 22, 30], 22 is in range [20,24].
+
+ +

Example 2:

+ +
+Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
+Output: [1,1]
+
+ +

Example 3:

+ +
+Input: nums = [[10,10],[11,11]]
+Output: [10,11]
+
+ +

Example 4:

+ +
+Input: nums = [[10],[11]]
+Output: [10,11]
+
+ +

Example 5:

+ +
+Input: nums = [[1],[2],[3],[4],[5],[6],[7]]
+Output: [1,7]
+
+ +

 

+

Constraints:

+ +
    +
  • nums.length == k
  • +
  • 1 <= k <= 3500
  • +
  • 1 <= nums[i].length <= 50
  • +
  • -105 <= nums[i][j] <= 105
  • +
  • nums[i] is sorted in non-decreasing order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0633.Sum of Square Numbers/README_EN.md b/assets/0600-0699/0633.Sum of Square Numbers/README_EN.md new file mode 100644 index 00000000..d746b738 --- /dev/null +++ b/assets/0600-0699/0633.Sum of Square Numbers/README_EN.md @@ -0,0 +1,162 @@ +# [633. Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers) + + + +## Description + +

Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.

+ +

 

+

Example 1:

+ +
+Input: c = 5
+Output: true
+Explanation: 1 * 1 + 2 * 2 = 5
+
+ +

Example 2:

+ +
+Input: c = 3
+Output: false
+
+ +

Example 3:

+ +
+Input: c = 4
+Output: true
+
+ +

Example 4:

+ +
+Input: c = 2
+Output: true
+
+ +

Example 5:

+ +
+Input: c = 1
+Output: true
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= c <= 231 - 1
  • +
+ +## Solutions + +![](https://cdn.jsdelivr.net/gh/yanglr/leetcode-ac@master/assets/0600-0699/0633.Sum%20of%20Square%20Numbers/images/table.png) + +The picture above shows the relationship between `a`, `b`, and `c`. This question is actually looking up `c` in this table + +From the upper right corner of the table, it is not difficult to find that it is similar to a binary search tree, so just start from the upper right corner and search according to the law of the binary search tree + + + +### **Python3** + +```python +class Solution(object): + def judgeSquareSum(self, c): + i, j = 0, int(math.sqrt(c)) + while i <= j: + s = i * i + j * j + if s < c: + i += 1 + elif s > c: + j -= 1 + else: + return True + return False +``` + +### **Java** + +```java +class Solution { + public boolean judgeSquareSum(int c) { + int i = 0, j = (int) Math.sqrt(c); + while (i <= j) { + int s = i * i + j * j; + if (s < c) { + ++i; + } else if (s > c) { + --j; + } else { + return true; + } + } + return false; + } +} +``` + +### **TypeScript** + +```ts +function judgeSquareSum(c: number): boolean { + let a = 0, b = Math.floor(Math.sqrt(c)); + while (a <= b) { + let sum = a ** 2 + b ** 2; + if (sum == c) return true; + if (sum < c) { + ++a; + } else { + --b; + } + } + return false; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool judgeSquareSum(int c) { + long i = 0, j = (long) sqrt(c); + while (i <= j) { + long s = i * i + j * j; + if (s < c) ++i; + else if (s > c) --j; + else return true; + } + return false; + } +}; +``` + +### **Go** + +```go +func judgeSquareSum(c int) bool { + i, j := 0, int(math.Sqrt(float64(c))) + for i <= j { + s := i*i + j*j + if s < c { + i++ + } else if s > c { + j-- + } else { + return true + } + } + return false +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0633.Sum of Square Numbers/images/table.png b/assets/0600-0699/0633.Sum of Square Numbers/images/table.png new file mode 100644 index 00000000..a2724805 Binary files /dev/null and b/assets/0600-0699/0633.Sum of Square Numbers/images/table.png differ diff --git a/assets/0600-0699/0634.Find the Derangement of An Array/README_EN.md b/assets/0600-0699/0634.Find the Derangement of An Array/README_EN.md new file mode 100644 index 00000000..28260ea4 --- /dev/null +++ b/assets/0600-0699/0634.Find the Derangement of An Array/README_EN.md @@ -0,0 +1,75 @@ +# [634. Find the Derangement of An Array](https://leetcode.com/problems/find-the-derangement-of-an-array) + + + +## Description + +

+ +In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position. + +

+ + + +

+ +There's originally an array consisting of n integers from 1 to n in ascending order, you need to find the number of derangement it can generate. + +

+ + + +

+ +Also, since the answer may be very large, you should return the output mod 109 + 7. + +

+ + + +

Example 1:
+ +

+
+Input: 3
+
+Output: 2
+
+Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
+
+
+ +

+ + + +

Note:
+ +n is in the range of [1, 106]. + +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0635.Design Log Storage System/README_EN.md b/assets/0600-0699/0635.Design Log Storage System/README_EN.md new file mode 100644 index 00000000..2363e83e --- /dev/null +++ b/assets/0600-0699/0635.Design Log Storage System/README_EN.md @@ -0,0 +1,78 @@ +# [635. Design Log Storage System](https://leetcode.com/problems/design-log-storage-system) + + + +## Description + +

You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.

+ +

Implement the LogSystem class:

+ +
    +
  • LogSystem() Initializes the LogSystem object.
  • +
  • void put(int id, string timestamp) Stores the given log (id, timestamp) in your storage system.
  • +
  • int[] retrieve(string start, string end, string granularity) Returns the IDs of the logs whose timestamps are within the range from start to end inclusive. start and end all have the same format as timestamp, and granularity means how precise the range should be (i.e. to the exact Day, Minute, etc.). For example, start = "2017:01:01:23:59:59", end = "2017:01:02:23:59:59", and granularity = "Day" means that we need to find the logs within the inclusive range from Jan. 1st 2017 to Jan. 2nd 2017, and the Hour, Minute, and Second for each log entry can be ignored.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["LogSystem", "put", "put", "put", "retrieve", "retrieve"]
+[[], [1, "2017:01:01:23:59:59"], [2, "2017:01:01:22:59:59"], [3, "2016:01:01:00:00:00"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Year"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour"]]
+Output
+[null, null, null, null, [3, 2, 1], [2, 1]]
+
+Explanation
+LogSystem logSystem = new LogSystem();
+logSystem.put(1, "2017:01:01:23:59:59");
+logSystem.put(2, "2017:01:01:22:59:59");
+logSystem.put(3, "2016:01:01:00:00:00");
+
+// return [3,2,1], because you need to return all logs between 2016 and 2017.
+logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00", "Year");
+
+// return [2,1], because you need to return all logs between Jan. 1, 2016 01:XX:XX and Jan. 1, 2017 23:XX:XX.
+// Log 3 is not returned because Jan. 1, 2016 00:00:00 comes before the start of the range.
+logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour");
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= id <= 500
  • +
  • 2000 <= Year <= 2017
  • +
  • 1 <= Month <= 12
  • +
  • 1 <= Day <= 31
  • +
  • 0 <= Hour <= 23
  • +
  • 0 <= Minute, Second <= 59
  • +
  • granularity is one of the values ["Year", "Month", "Day", "Hour", "Minute", "Second"].
  • +
  • At most 500 calls will be made to put and retrieve.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0636.Exclusive Time of Functions/README_EN.md b/assets/0600-0699/0636.Exclusive Time of Functions/README_EN.md new file mode 100644 index 00000000..7e5810c9 --- /dev/null +++ b/assets/0600-0699/0636.Exclusive Time of Functions/README_EN.md @@ -0,0 +1,108 @@ +# [636. Exclusive Time of Functions](https://leetcode.com/problems/exclusive-time-of-functions) + + + +## Description + +

On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.

+ +

Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.

+ +

You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.

+ +

A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.

+ +

Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.

+ +

 

+

Example 1:

+ +
+Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
+Output: [3,4]
+Explanation:
+Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.
+Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.
+Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.
+So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.
+
+ +

Example 2:

+ +
+Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]
+Output: [8]
+Explanation:
+Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
+Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
+Function 0 (initial call) resumes execution then immediately calls itself again.
+Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.
+Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.
+So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.
+
+ +

Example 3:

+ +
+Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]
+Output: [7,1]
+Explanation:
+Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
+Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
+Function 0 (initial call) resumes execution then immediately calls function 1.
+Function 1 starts at the beginning of time 6, executes 1 units of time, and ends at the end of time 6.
+Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time.
+So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.
+
+ +

Example 4:

+ +
+Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:7","1:end:7","0:end:8"]
+Output: [8,1]
+
+ +

Example 5:

+ +
+Input: n = 1, logs = ["0:start:0","0:end:0"]
+Output: [1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= n <= 100
  • +
  • 1 <= logs.length <= 500
  • +
  • 0 <= function_id < n
  • +
  • 0 <= timestamp <= 109
  • +
  • No two start events will happen at the same timestamp.
  • +
  • No two end events will happen at the same timestamp.
  • +
  • Each function has an "end" log for each "start" log.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0636.Exclusive Time of Functions/images/diag1b.png b/assets/0600-0699/0636.Exclusive Time of Functions/images/diag1b.png new file mode 100644 index 00000000..b4675ec5 Binary files /dev/null and b/assets/0600-0699/0636.Exclusive Time of Functions/images/diag1b.png differ diff --git a/assets/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md b/assets/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md new file mode 100644 index 00000000..7d2ddf12 --- /dev/null +++ b/assets/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md @@ -0,0 +1,150 @@ +# [637. Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree) + + + +## Description + +Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,15,7]
+Output: [3.00000,14.50000,11.00000]
+Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
+Hence return [3, 14.5, 11].
+
+ +

Example 2:

+ +
+Input: root = [3,9,20,15,7]
+Output: [3.00000,14.50000,11.00000]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -231 <= Node.val <= 231 - 1
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def averageOfLevels(self, root: TreeNode) -> List[float]: + res = [] + q = collections.deque([root]) + while q: + n = len(q) + s = 0 + for _ in range(n): + node = q.popleft() + s += node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + res.append(s / n) + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List averageOfLevels(TreeNode root) { + List res = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + double s = 0, n = q.size(); + for (int i = 0; i < n; ++i) { + TreeNode node = q.poll(); + s += node.val; + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + res.add(s / n); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var averageOfLevels = function(root) { + let res = []; + let queue = [root]; + while (queue.length > 0) { + n = queue.length; + let sum = 0; + for (let i = 0; i < n; i++) { + let node = queue.shift(); + sum += node.val; + if (node.left) { + queue.push(node.left); + } + if (node.right) { + queue.push(node.right); + } + } + res.push(sum / n); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0637.Average of Levels in Binary Tree/images/avg1-tree.jpg b/assets/0600-0699/0637.Average of Levels in Binary Tree/images/avg1-tree.jpg new file mode 100644 index 00000000..d77a04e7 Binary files /dev/null and b/assets/0600-0699/0637.Average of Levels in Binary Tree/images/avg1-tree.jpg differ diff --git a/assets/0600-0699/0637.Average of Levels in Binary Tree/images/avg2-tree.jpg b/assets/0600-0699/0637.Average of Levels in Binary Tree/images/avg2-tree.jpg new file mode 100644 index 00000000..ef96508b Binary files /dev/null and b/assets/0600-0699/0637.Average of Levels in Binary Tree/images/avg2-tree.jpg differ diff --git a/assets/0600-0699/0638.Shopping Offers/README_EN.md b/assets/0600-0699/0638.Shopping Offers/README_EN.md new file mode 100644 index 00000000..979781a9 --- /dev/null +++ b/assets/0600-0699/0638.Shopping Offers/README_EN.md @@ -0,0 +1,75 @@ +# [638. Shopping Offers](https://leetcode.com/problems/shopping-offers) + + + +## Description + +

In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

+ +

You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.

+ +

You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.

+ +

Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.

+ +

 

+

Example 1:

+ +
+Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
+Output: 14
+Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. 
+In special offer 1, you can pay $5 for 3A and 0B
+In special offer 2, you can pay $10 for 1A and 2B. 
+You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
+
+ +

Example 2:

+ +
+Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
+Output: 11
+Explanation: The price of A is $2, and $3 for B, $4 for C. 
+You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. 
+You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. 
+You cannot add more items, though only $9 for 2A ,2B and 1C.
+
+ +

 

+

Constraints:

+ +
    +
  • n == price.length
  • +
  • n == needs.length
  • +
  • 1 <= n <= 6
  • +
  • 0 <= price[i] <= 10
  • +
  • 0 <= needs[i] <= 10
  • +
  • 1 <= special.length <= 100
  • +
  • special[i].length == n + 1
  • +
  • 0 <= special[i][j] <= 50
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0639.Decode Ways II/README_EN.md b/assets/0600-0699/0639.Decode Ways II/README_EN.md new file mode 100644 index 00000000..0df01b24 --- /dev/null +++ b/assets/0600-0699/0639.Decode Ways II/README_EN.md @@ -0,0 +1,93 @@ +# [639. Decode Ways II](https://leetcode.com/problems/decode-ways-ii) + + + +## Description + +

A message containing letters from A-Z can be encoded into numbers using the following mapping:

+ +
+'A' -> "1"
+'B' -> "2"
+...
+'Z' -> "26"
+
+ +

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

+ +
    +
  • "AAJF" with the grouping (1 1 10 6)
  • +
  • "KJF" with the grouping (11 10 6)
  • +
+ +

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

+ +

In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.

+ +

Given a string s containing digits and the '*' character, return the number of ways to decode it.

+ +

Since the answer may be very large, return it modulo 109 + 7.

+ +

 

+

Example 1:

+ +
+Input: s = "*"
+Output: 9
+Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
+Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
+Hence, there are a total of 9 ways to decode "*".
+
+ +

Example 2:

+ +
+Input: s = "1*"
+Output: 18
+Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
+Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
+Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
+
+ +

Example 3:

+ +
+Input: s = "2*"
+Output: 15
+Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
+"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
+Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 105
  • +
  • s[i] is a digit or '*'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0640.Solve the Equation/README_EN.md b/assets/0600-0699/0640.Solve the Equation/README_EN.md new file mode 100644 index 00000000..e17c3b7b --- /dev/null +++ b/assets/0600-0699/0640.Solve the Equation/README_EN.md @@ -0,0 +1,125 @@ +# [640. Solve the Equation](https://leetcode.com/problems/solve-the-equation) + + + +## Description + +

+ +Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient. + +

+ + + +

+ +If there is no solution for the equation, return "No solution". + +

+ +

+ +If there are infinite solutions for the equation, return "Infinite solutions". + +

+ +

+ +If there is exactly one solution for the equation, we ensure that the value of x is an integer. + +

+ + + +

Example 1:
+ +

+
+Input: "x+5-3+x=6+x-2"
+
+Output: "x=2"
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: "x=x"
+
+Output: "Infinite solutions"
+
+
+ +

+ + + +

Example 3:
+ +

+
+Input: "2x=x"
+
+Output: "x=0"
+
+
+ +

+ + + +

Example 4:
+ +

+
+Input: "2x+3x-6x=x+2"
+
+Output: "x=-1"
+
+
+ +

+ + + +

Example 5:
+ +

+
+Input: "x=x+2"
+
+Output: "No solution"
+
+
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0641.Design Circular Deque/README_EN.md b/assets/0600-0699/0641.Design Circular Deque/README_EN.md new file mode 100644 index 00000000..ea2ecb61 --- /dev/null +++ b/assets/0600-0699/0641.Design Circular Deque/README_EN.md @@ -0,0 +1,269 @@ +# [641. Design Circular Deque](https://leetcode.com/problems/design-circular-deque) + + + +## Description + +

Design your implementation of the circular double-ended queue (deque).

+ +

Your implementation should support following operations:

+ +
    +
  • MyCircularDeque(k): Constructor, set the size of the deque to be k.
  • +
  • insertFront(): Adds an item at the front of Deque. Return true if the operation is successful.
  • +
  • insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful.
  • +
  • deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful.
  • +
  • deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful.
  • +
  • getFront(): Gets the front item from the Deque. If the deque is empty, return -1.
  • +
  • getRear(): Gets the last item from Deque. If the deque is empty, return -1.
  • +
  • isEmpty(): Checks whether Deque is empty or not. 
  • +
  • isFull(): Checks whether Deque is full or not.
  • +
+ +

 

+ +

Example:

+ +
+
+MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3
+
+circularDeque.insertLast(1);			// return true
+
+circularDeque.insertLast(2);			// return true
+
+circularDeque.insertFront(3);			// return true
+
+circularDeque.insertFront(4);			// return false, the queue is full
+
+circularDeque.getRear();  			// return 2
+
+circularDeque.isFull();				// return true
+
+circularDeque.deleteLast();			// return true
+
+circularDeque.insertFront(4);			// return true
+
+circularDeque.getFront();			// return 4
+
+
+ +

 

+ +

Note:

+ +
    +
  • All values will be in the range of [0, 1000].
  • +
  • The number of operations will be in the range of [1, 1000].
  • +
  • Please do not use the built-in Deque library.
  • +
+ +## Solutions + + + +### **Python3** + +```python +class MyCircularDeque: + + def __init__(self, k: int): + """ + Initialize your data structure here. Set the size of the deque to be k. + """ + self.q = [0] * k + self.front = 0 + self.size = 0 + self.capacity = k + + def insertFront(self, value: int) -> bool: + """ + Adds an item at the front of Deque. Return true if the operation is successful. + """ + if self.isFull(): + return False + if not self.isEmpty(): + self.front = (self.front - 1 + self.capacity) % self.capacity + self.q[self.front] = value + self.size += 1 + return True + + def insertLast(self, value: int) -> bool: + """ + Adds an item at the rear of Deque. Return true if the operation is successful. + """ + if self.isFull(): + return False + idx = (self.front + self.size) % self.capacity + self.q[idx] = value + self.size += 1 + return True + + def deleteFront(self) -> bool: + """ + Deletes an item from the front of Deque. Return true if the operation is successful. + """ + if self.isEmpty(): + return False + self.front = (self.front + 1) % self.capacity + self.size -= 1 + return True + + def deleteLast(self) -> bool: + """ + Deletes an item from the rear of Deque. Return true if the operation is successful. + """ + if self.isEmpty(): + return False + self.size -= 1 + return True + + def getFront(self) -> int: + """ + Get the front item from the deque. + """ + if self.isEmpty(): + return -1 + return self.q[self.front] + + def getRear(self) -> int: + """ + Get the last item from the deque. + """ + if self.isEmpty(): + return -1 + idx = (self.front + self.size - 1) % self.capacity + return self.q[idx] + + def isEmpty(self) -> bool: + """ + Checks whether the circular deque is empty or not. + """ + return self.size == 0 + + def isFull(self) -> bool: + """ + Checks whether the circular deque is full or not. + """ + return self.size == self.capacity + + +# Your MyCircularDeque object will be instantiated and called as such: +# obj = MyCircularDeque(k) +# param_1 = obj.insertFront(value) +# param_2 = obj.insertLast(value) +# param_3 = obj.deleteFront() +# param_4 = obj.deleteLast() +# param_5 = obj.getFront() +# param_6 = obj.getRear() +# param_7 = obj.isEmpty() +# param_8 = obj.isFull() +``` + +### **Java** + +```java +class MyCircularDeque { + private int[] q; + private int front; + private int size; + private int capacity; + + /** Initialize your data structure here. Set the size of the deque to be k. */ + public MyCircularDeque(int k) { + q = new int[k]; + capacity = k; + } + + /** Adds an item at the front of Deque. Return true if the operation is successful. */ + public boolean insertFront(int value) { + if (isFull()) { + return false; + } + if (!isEmpty()) { + front = (front - 1 + capacity) % capacity; + } + q[front] = value; + ++size; + return true; + } + + /** Adds an item at the rear of Deque. Return true if the operation is successful. */ + public boolean insertLast(int value) { + if (isFull()) { + return false; + } + int idx = (front + size) % capacity; + q[idx] = value; + ++size; + return true; + } + + /** Deletes an item from the front of Deque. Return true if the operation is successful. */ + public boolean deleteFront() { + if (isEmpty()) { + return false; + } + front = (front + 1) % capacity; + --size; + return true; + } + + /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ + public boolean deleteLast() { + if (isEmpty()) { + return false; + } + --size; + return true; + } + + /** Get the front item from the deque. */ + public int getFront() { + if (isEmpty()) { + return -1; + } + return q[front]; + } + + /** Get the last item from the deque. */ + public int getRear() { + if (isEmpty()) { + return -1; + } + int idx = (front + size - 1) % capacity; + return q[idx]; + } + + /** Checks whether the circular deque is empty or not. */ + public boolean isEmpty() { + return size == 0; + } + + /** Checks whether the circular deque is full or not. */ + public boolean isFull() { + return size == capacity; + } +} + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * MyCircularDeque obj = new MyCircularDeque(k); + * boolean param_1 = obj.insertFront(value); + * boolean param_2 = obj.insertLast(value); + * boolean param_3 = obj.deleteFront(); + * boolean param_4 = obj.deleteLast(); + * int param_5 = obj.getFront(); + * int param_6 = obj.getRear(); + * boolean param_7 = obj.isEmpty(); + * boolean param_8 = obj.isFull(); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0642.Design Search Autocomplete System/README_EN.md b/assets/0600-0699/0642.Design Search Autocomplete System/README_EN.md new file mode 100644 index 00000000..6c82de41 --- /dev/null +++ b/assets/0600-0699/0642.Design Search Autocomplete System/README_EN.md @@ -0,0 +1,141 @@ +# [642. Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system) + + + +## Description + +

Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except '#', you need to return the top 3 historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:

+ + + +
    +
  1. The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
  2. +
  3. The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).
  4. +
  5. If less than 3 hot sentences exist, then just return as many as you can.
  6. +
  7. When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.
  8. +
+ + + +

Your job is to implement the following functions:

+ + + +

The constructor function:

+ + + +

AutocompleteSystem(String[] sentences, int[] times): This is the constructor. The input is historical data. Sentences is a string array consists of previously typed sentences. Times is the corresponding times a sentence has been typed. Your system should record these historical data.

+ + + +

Now, the user wants to input a new sentence. The following function will provide the next character the user types:

+ + + +

List<String> input(char c): The input c is the next character typed by the user. The character will only be lower-case letters ('a' to 'z'), blank space (' ') or a special character ('#'). Also, the previously typed sentence should be recorded in your system. The output will be the top 3 historical hot sentences that have prefix the same as the part of sentence already typed.

+ +  + + + +

Example:
+ +Operation: AutocompleteSystem(["i love you", "island","ironman", "i love leetcode"], [5,3,2,2])
+ +The system have already tracked down the following sentences and their corresponding times:
+ +"i love you" : 5 times
+ +"island" : 3 times
+ +"ironman" : 2 times
+ +"i love leetcode" : 2 times
+ +Now, the user begins another search:
+ +
+ +Operation: input('i')
+ +Output: ["i love you", "island","i love leetcode"]
+ +Explanation:
+ +There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored.
+ +
+ +Operation: input(' ')
+ +Output: ["i love you","i love leetcode"]
+ +Explanation:
+ +There are only two sentences that have prefix "i ".
+ +
+ +Operation: input('a')
+ +Output: []
+ +Explanation:
+ +There are no sentences that have prefix "i a".
+ +
+ +Operation: input('#')
+ +Output: []
+ +Explanation:
+ +The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.

+ +  + + + +

Note:

+ + + +
    +
  1. The input sentence will always start with a letter and end with '#', and only one blank space will exist between two words.
  2. +
  3. The number of complete sentences that to be searched won't exceed 100. The length of each sentence including those in the historical data won't exceed 100.
  4. +
  5. Please use double-quote instead of single-quote when you write test cases even for a character input.
  6. +
  7. Please remember to RESET your class variables declared in class AutocompleteSystem, as static/class variables are persisted across multiple test cases. Please see here for more details.
  8. +
+ + + +

 

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0643.Maximum Average Subarray I/README_EN.md b/assets/0600-0699/0643.Maximum Average Subarray I/README_EN.md new file mode 100644 index 00000000..6d67fae6 --- /dev/null +++ b/assets/0600-0699/0643.Maximum Average Subarray I/README_EN.md @@ -0,0 +1,110 @@ +# [643. Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i) + + + +## Description + +

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

+ + + +

Example 1:

+ + + +
+
+Input: [1,12,-5,-6,50,3], k = 4
+
+Output: 12.75
+
+Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. 1 <= k <= n <= 30,000.
  2. +
  3. Elements of the given array will be in the range [-10,000, 10,000].
  4. +
+ + + +

 

+ + + +## Solutions + +Slide window. + + + +### **Python3** + +```python +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + s = sum(nums[:k]) + ans = s + for i in range(k, len(nums)): + s += (nums[i] - nums[i - k]) + ans = max(ans, s) + return ans / k +``` + +### **Java** + +```java +class Solution { + public double findMaxAverage(int[] nums, int k) { + int s = 0; + for (int i = 0; i < k; ++i) { + s += nums[i]; + } + int ans = s; + for (int i = k; i < nums.length; ++i) { + s += (nums[i] - nums[i - k]); + ans = Math.max(ans, s); + } + return ans * 1.0 / k; + } +} +``` + +### **TypeScript** + +```ts +function findMaxAverage(nums: number[], k: number): number { + let n = nums.length; + let ans = 0; + let sum = 0; + // 前k + for (let i = 0; i < k; i++) { + sum += nums[i]; + } + ans = sum; + for (let i = k; i < n; i++) { + sum += (nums[i] - nums[i - k]); + ans = Math.max(ans, sum); + } + return ans / k; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0644.Maximum Average Subarray II/README_EN.md b/assets/0600-0699/0644.Maximum Average Subarray II/README_EN.md new file mode 100644 index 00000000..b806ced9 --- /dev/null +++ b/assets/0600-0699/0644.Maximum Average Subarray II/README_EN.md @@ -0,0 +1,64 @@ +# [644. Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii) + + + +## Description + +

You are given an integer array nums consisting of n elements, and an integer k.

+ +

Find a contiguous subarray whose length is greater than or equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,12,-5,-6,50,3], k = 4
+Output: 12.75000
+Explanation:
+- When the length is 4, averages are [0.5, 12.75, 10.5] and the maximum average is 12.75
+- When the length is 5, averages are [10.4, 10.8] and the maximum average is 10.8
+- When the length is 6, averages are [9.16667] and the maximum average is 9.16667
+The maximum average is when we choose a subarray of length 4 (i.e., the sub array [12, -5, -6, 50]) which has the max average 12.75, so we return 12.75
+Note that we do not consider the subarrays of length < 4.
+
+ +

Example 2:

+ +
+Input: nums = [5], k = 1
+Output: 5.00000
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= k <= n <= 104
  • +
  • -104 <= nums[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0645.Set Mismatch/README_EN.md b/assets/0600-0699/0645.Set Mismatch/README_EN.md new file mode 100644 index 00000000..fcc1d806 --- /dev/null +++ b/assets/0600-0699/0645.Set Mismatch/README_EN.md @@ -0,0 +1,176 @@ +# [645. Set Mismatch](https://leetcode.com/problems/set-mismatch) + + + +## Description + +

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

+ +

You are given an integer array nums representing the data status of this set after the error.

+ +

Find the number that occurs twice and the number that is missing and return them in the form of an array.

+ +

 

+

Example 1:

+
Input: nums = [1,2,2,4]
+Output: [2,3]
+

Example 2:

+
Input: nums = [1,1]
+Output: [1,2]
+
+

 

+

Constraints:

+ +
    +
  • 2 <= nums.length <= 104
  • +
  • 1 <= nums[i] <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + eor, n = 0, len(nums) + for i in range(1, n + 1): + eor ^= (i ^ nums[i - 1]) + diff = eor & (~eor + 1) + a = 0 + for i in range(1, n + 1): + if (nums[i - 1] & diff) == 0: + a ^= nums[i - 1] + if (i & diff) == 0: + a ^= i + b = eor ^ a + for num in nums: + if a == num: + return [a, b] + return [b, a] +``` + +### **Java** + +```java +class Solution { + public int[] findErrorNums(int[] nums) { + int eor = 0; + for (int i = 1; i <= nums.length; ++i) { + eor ^= (i ^ nums[i - 1]); + } + int diff = eor & (~eor + 1); + int a = 0; + for (int i = 1; i <= nums.length; ++i) { + if ((nums[i - 1] & diff) == 0) { + a ^= nums[i - 1]; + } + if ((i & diff) == 0) { + a ^= i; + } + } + int b = eor ^ a; + for (int num : nums) { + if (a == num) { + return new int[]{a, b}; + } + } + return new int[]{b, a}; + } +} +``` + +### **TypeScript** + +```ts +function findErrorNums(nums: number[]): number[] { + let xor = 0; + for (let i = 0; i < nums.length; ++i) { + xor ^= ((i + 1) ^ nums[i]); + } + + let divide = 1; + while ((xor & divide) == 0) { + divide <<= 1; + } + + let ans1 = 0, ans2 = 0; + for (let i = 0; i < nums.length; ++i) { + let cur = nums[i]; + if (divide & cur) { + ans1 ^= cur; + } else { + ans2 ^= cur; + } + + let idx = i + 1; + if (divide & idx) { + ans1 ^= idx; + } else { + ans2 ^= idx; + } + } + return nums.includes(ans1) ? [ans1, ans2] : [ans2, ans1]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int eor = 0, n = nums.size(); + for (int i = 1; i <= n; ++i) { + eor ^= (i ^ nums[i - 1]); + } + int diff = eor & (~eor + 1); + int a = 0; + for (int i = 1; i <= n; ++i) { + if ((nums[i - 1] & diff) == 0) { + a ^= nums[i - 1]; + } + if ((i & diff) == 0) { + a ^= i; + } + } + int b = eor ^ a; + for (int num : nums) { + if (a == num) { + return {a, b}; + } + } + return {b, a}; + } +}; +``` + +### **Go** + +```go +func findErrorNums(nums []int) []int { + n := len(nums) + for i := 0; i < n; i++ { + for nums[i] != i+1 && nums[nums[i]-1] != nums[i] { + nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] + } + } + for i := 0; i < n; i++ { + if nums[i] != i+1 { + return []int{nums[i], i + 1} + } + } + return []int{-1, -1} +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md b/assets/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md new file mode 100644 index 00000000..636adc4c --- /dev/null +++ b/assets/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md @@ -0,0 +1,81 @@ +# [646. Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain) + + + +## Description + +

+ +You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. + +

+ + + +

+ +Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion. + +

+ + + +

+ +Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order. + +

+ + + + + +

Example 1:
+ +

+
+Input: [[1,2], [2,3], [3,4]]
+
+Output: 2
+
+Explanation: The longest chain is [1,2] -> [3,4]
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The number of given pairs will be in the range [1, 1000].
  2. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0647.Palindromic Substrings/README_EN.md b/assets/0600-0699/0647.Palindromic Substrings/README_EN.md new file mode 100644 index 00000000..de2b9392 --- /dev/null +++ b/assets/0600-0699/0647.Palindromic Substrings/README_EN.md @@ -0,0 +1,89 @@ +# [647. Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings) + + + +## Description + +

Given a string, your task is to count how many palindromic substrings in this string.

+ + + +

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

+ + + +

Example 1:

+ + + +
+
+Input: "abc"
+
+Output: 3
+
+Explanation: Three palindromic strings: "a", "b", "c".
+
+
+ + + +

 

+ + + +

Example 2:

+ + + +
+
+Input: "aaa"
+
+Output: 6
+
+Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. The input string length won't exceed 1000.
  2. +
+ + + +

 

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0648.Replace Words/README_EN.md b/assets/0600-0699/0648.Replace Words/README_EN.md new file mode 100644 index 00000000..2bfa13cc --- /dev/null +++ b/assets/0600-0699/0648.Replace Words/README_EN.md @@ -0,0 +1,68 @@ +# [648. Replace Words](https://leetcode.com/problems/replace-words) + + + +## Description + +

In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".

+ +

Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.

+ +

Return the sentence after the replacement.

+ +

 

+

Example 1:

+
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
+Output: "the cat was rat by the bat"
+

Example 2:

+
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
+Output: "a a b c"
+

Example 3:

+
Input: dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
+Output: "a a a a a a a a bbb baba a"
+

Example 4:

+
Input: dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
+Output: "the cat was rat by the bat"
+

Example 5:

+
Input: dictionary = ["ac","ab"], sentence = "it is abnormal that this solution is accepted"
+Output: "it is ab that this solution is ac"
+
+

 

+

Constraints:

+ +
    +
  • 1 <= dictionary.length <= 1000
  • +
  • 1 <= dictionary[i].length <= 100
  • +
  • dictionary[i] consists of only lower-case letters.
  • +
  • 1 <= sentence.length <= 10^6
  • +
  • sentence consists of only lower-case letters and spaces.
  • +
  • The number of words in sentence is in the range [1, 1000]
  • +
  • The length of each word in sentence is in the range [1, 1000]
  • +
  • Each two consecutive words in sentence will be separated by exactly one space.
  • +
  • sentence does not have leading or trailing spaces.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0649.Dota2 Senate/README_EN.md b/assets/0600-0699/0649.Dota2 Senate/README_EN.md new file mode 100644 index 00000000..88cc8dfc --- /dev/null +++ b/assets/0600-0699/0649.Dota2 Senate/README_EN.md @@ -0,0 +1,128 @@ +# [649. Dota2 Senate](https://leetcode.com/problems/dota2-senate) + + + +## Description + +

In the world of Dota2, there are two parties: the Radiant and the Dire.

+ + + +

The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:

+ + + +
    +
  1. Ban one senator's right:
    + A senator can make another senator lose all his rights in this and all the following rounds.
  2. +
  3. Announce the victory:
    + If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
  4. +
+ + + +

 

+ + + +

Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.

+ + + +

The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.

+ + + +

Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.

+ + + +

Example 1:

+ + + +
+
+Input: "RD"
+
+Output: "Radiant"
+
+Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. 
+
+And the second senator can't exercise any rights any more since his right has been banned. 
+
+And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
+
+
+ + + +

 

+ + + +

Example 2:

+ + + +
+
+Input: "RDD"
+
+Output: "Dire"
+
+Explanation: 
+
+The first senator comes from Radiant and he can just ban the next senator's right in the round 1. 
+
+And the second senator can't exercise any rights anymore since his right has been banned. 
+
+And the third senator comes from Dire and he can ban the first senator's right in the round 1. 
+
+And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. The length of the given string will in the range [1, 10,000].
  2. +
+ + + +

 

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0650.2 Keys Keyboard/README_EN.md b/assets/0600-0699/0650.2 Keys Keyboard/README_EN.md new file mode 100644 index 00000000..dea2910b --- /dev/null +++ b/assets/0600-0699/0650.2 Keys Keyboard/README_EN.md @@ -0,0 +1,90 @@ +# [650. 2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard) + + + +## Description + +

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

+ + + +
    +
  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. +
  3. Paste: You can paste the characters which are copied last time.
  4. +
+ + + +

 

+ + + +

Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.

+ + + +

Example 1:

+ + + +
+
+Input: 3
+
+Output: 3
+
+Explanation:
+
+Intitally, we have one character 'A'.
+
+In step 1, we use Copy All operation.
+
+In step 2, we use Paste operation to get 'AA'.
+
+In step 3, we use Paste operation to get 'AAA'.
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. The n will be in the range [1, 1000].
  2. +
+ + + +

 

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0651.4 Keys Keyboard/README_EN.md b/assets/0600-0699/0651.4 Keys Keyboard/README_EN.md new file mode 100644 index 00000000..00b7a9e1 --- /dev/null +++ b/assets/0600-0699/0651.4 Keys Keyboard/README_EN.md @@ -0,0 +1,105 @@ +# [651. 4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard) + + + +## Description + +

Imagine you have a special keyboard with the following keys:

+ +

Key 1: (A): Print one 'A' on screen.

+ +

Key 2: (Ctrl-A): Select the whole screen.

+ +

Key 3: (Ctrl-C): Copy selection to buffer.

+ +

Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.

+ + + + + + + +

Now, you can only press the keyboard for N times (with the above four keys), find out the maximum numbers of 'A' you can print on screen.

+ + + + + +

Example 1:
+ +

+
+Input: N = 3
+
+Output: 3
+
+Explanation: 
+
+We can at most get 3 A's on screen by pressing following key sequence:
+
+A, A, A
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: N = 7
+
+Output: 9
+
+Explanation: 
+
+We can at most get 9 A's on screen by pressing following key sequence:
+
+A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. 1 <= N <= 50
  2. + +
  3. Answers will be in the range of 32-bit signed integer.
  4. + +
+ +

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0652.Find Duplicate Subtrees/README_EN.md b/assets/0600-0699/0652.Find Duplicate Subtrees/README_EN.md new file mode 100644 index 00000000..ed15d7cc --- /dev/null +++ b/assets/0600-0699/0652.Find Duplicate Subtrees/README_EN.md @@ -0,0 +1,66 @@ +# [652. Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees) + + + +## Description + +

Given the root of a binary tree, return all duplicate subtrees.

+ +

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

+ +

Two trees are duplicate if they have the same structure with the same node values.

+ +

 

+

Example 1:

+ +
+Input: root = [1,2,3,4,null,2,4,null,null,4]
+Output: [[2,4],[4]]
+
+ +

Example 2:

+ +
+Input: root = [2,1,1]
+Output: [[1]]
+
+ +

Example 3:

+ +
+Input: root = [2,2,2,3,null,3,null]
+Output: [[2,3],[3]]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of the nodes in the tree will be in the range [1, 10^4]
  • +
  • -200 <= Node.val <= 200
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0652.Find Duplicate Subtrees/images/e1.jpg b/assets/0600-0699/0652.Find Duplicate Subtrees/images/e1.jpg new file mode 100644 index 00000000..afc8a036 Binary files /dev/null and b/assets/0600-0699/0652.Find Duplicate Subtrees/images/e1.jpg differ diff --git a/assets/0600-0699/0652.Find Duplicate Subtrees/images/e2.jpg b/assets/0600-0699/0652.Find Duplicate Subtrees/images/e2.jpg new file mode 100644 index 00000000..c8f4582c Binary files /dev/null and b/assets/0600-0699/0652.Find Duplicate Subtrees/images/e2.jpg differ diff --git a/assets/0600-0699/0652.Find Duplicate Subtrees/images/e33.jpg b/assets/0600-0699/0652.Find Duplicate Subtrees/images/e33.jpg new file mode 100644 index 00000000..170e0914 Binary files /dev/null and b/assets/0600-0699/0652.Find Duplicate Subtrees/images/e33.jpg differ diff --git a/assets/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md b/assets/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md new file mode 100644 index 00000000..665efeb3 --- /dev/null +++ b/assets/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md @@ -0,0 +1,78 @@ +# [653. Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst) + + + +## Description + +

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

+ +

 

+

Example 1:

+ +
+Input: root = [5,3,6,2,4,null,7], k = 9
+Output: true
+
+ +

Example 2:

+ +
+Input: root = [5,3,6,2,4,null,7], k = 28
+Output: false
+
+ +

Example 3:

+ +
+Input: root = [2,1,3], k = 4
+Output: true
+
+ +

Example 4:

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

Example 5:

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

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 104].
  • +
  • -104 <= Node.val <= 104
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
  • -105 <= k <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0653.Two Sum IV - Input is a BST/images/sum_tree_1.jpg b/assets/0600-0699/0653.Two Sum IV - Input is a BST/images/sum_tree_1.jpg new file mode 100644 index 00000000..41983f26 Binary files /dev/null and b/assets/0600-0699/0653.Two Sum IV - Input is a BST/images/sum_tree_1.jpg differ diff --git a/assets/0600-0699/0653.Two Sum IV - Input is a BST/images/sum_tree_2.jpg b/assets/0600-0699/0653.Two Sum IV - Input is a BST/images/sum_tree_2.jpg new file mode 100644 index 00000000..a6efafce Binary files /dev/null and b/assets/0600-0699/0653.Two Sum IV - Input is a BST/images/sum_tree_2.jpg differ diff --git a/assets/0600-0699/0654.Maximum Binary Tree/README_EN.md b/assets/0600-0699/0654.Maximum Binary Tree/README_EN.md new file mode 100644 index 00000000..f1206f79 --- /dev/null +++ b/assets/0600-0699/0654.Maximum Binary Tree/README_EN.md @@ -0,0 +1,74 @@ +# [654. Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree) + + + +## Description + +

You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

+ +
    +
  1. Create a root node whose value is the maximum value in nums.
  2. +
  3. Recursively build the left subtree on the subarray prefix to the left of the maximum value.
  4. +
  5. Recursively build the right subtree on the subarray suffix to the right of the maximum value.
  6. +
+ +

Return the maximum binary tree built from nums.

+ +

 

+

Example 1:

+ +
+Input: nums = [3,2,1,6,0,5]
+Output: [6,3,5,null,2,0,null,null,1]
+Explanation: The recursive calls are as follow:
+- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
+    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
+        - Empty array, so no child.
+        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
+            - Empty array, so no child.
+            - Only one element, so child is a node with value 1.
+    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
+        - Only one element, so child is a node with value 0.
+        - Empty array, so no child.
+
+ +

Example 2:

+ +
+Input: nums = [3,2,1]
+Output: [3,null,2,null,1]
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 1000
  • +
  • 0 <= nums[i] <= 1000
  • +
  • All integers in nums are unique.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0654.Maximum Binary Tree/images/tree1.jpg b/assets/0600-0699/0654.Maximum Binary Tree/images/tree1.jpg new file mode 100644 index 00000000..f4fabec0 Binary files /dev/null and b/assets/0600-0699/0654.Maximum Binary Tree/images/tree1.jpg differ diff --git a/assets/0600-0699/0654.Maximum Binary Tree/images/tree2.jpg b/assets/0600-0699/0654.Maximum Binary Tree/images/tree2.jpg new file mode 100644 index 00000000..663082b2 Binary files /dev/null and b/assets/0600-0699/0654.Maximum Binary Tree/images/tree2.jpg differ diff --git a/assets/0600-0699/0655.Print Binary Tree/README_EN.md b/assets/0600-0699/0655.Print Binary Tree/README_EN.md new file mode 100644 index 00000000..84e9151e --- /dev/null +++ b/assets/0600-0699/0655.Print Binary Tree/README_EN.md @@ -0,0 +1,149 @@ +# [655. Print Binary Tree](https://leetcode.com/problems/print-binary-tree) + + + +## Description + +

Print a binary tree in an m*n 2D string array following these rules:

+ + + +
    + +
  1. The row number m should be equal to the height of the given binary tree.
  2. + +
  3. The column number n should always be an odd number.
  4. + +
  5. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
  6. + +
  7. Each unused space should contain an empty string "".
  8. + +
  9. Print the subtrees following the same rules.
  10. + +
+ + + +

Example 1:
+ +

+
+Input:
+
+     1
+
+    /
+
+   2
+
+Output:
+
+[["", "1", ""],
+
+ ["2", "", ""]]
+
+
+ +

+ + + + + +

Example 2:
+ +

+
+Input:
+
+     1
+
+    / \
+
+   2   3
+
+    \
+
+     4
+
+Output:
+
+[["", "", "", "1", "", "", ""],
+
+ ["", "2", "", "", "", "3", ""],
+
+ ["", "", "4", "", "", "", ""]]
+
+
+ +

+ + + +

Example 3:
+ +

+
+Input:
+
+      1
+
+     / \
+
+    2   5
+
+   / 
+
+  3 
+
+ / 
+
+4 
+
+Output:
+
+
+
+[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
+
+ ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
+
+ ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
+
+ ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]
+
+
+ +

+ + + +

Note: + +The height of binary tree is in the range of [1, 10]. + +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0656.Coin Path/README_EN.md b/assets/0600-0699/0656.Coin Path/README_EN.md new file mode 100644 index 00000000..5cb8d03a --- /dev/null +++ b/assets/0600-0699/0656.Coin Path/README_EN.md @@ -0,0 +1,98 @@ +# [656. Coin Path](https://leetcode.com/problems/coin-path) + + + +## Description + +

Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B. The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to any one of the place in the array A indexed i+1, i+2, …, i+B if this place can be jumped to. Also, if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the place indexed i in the array.

+ + + +

Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed N using the minimum coins. You need to return the path of indexes (starting from 1 to N) in the array you should take to get to the place indexed N using minimum coins.

+ + + +

If there are multiple paths with the same cost, return the lexicographically smallest such path.

+ + + +

If it's not possible to reach the place indexed N then you need to return an empty array.

+ + + +

Example 1:

+ + + +
+
+Input: [1,2,4,-1,2], 2
+
+Output: [1,3,5]
+
+
+ + + +

 

+ + + +

Example 2:

+ + + +
+
+Input: [1,2,4,-1,2], 1
+
+Output: []
+
+
+ + + +

 

+ + + +

Note:

+ + + +
    +
  1. Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if at the first i where Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.
  2. +
  3. A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100].
  4. +
  5. Length of A is in the range of [1, 1000].
  6. +
  7. B is in the range of [1, 100].
  8. +
+ + + +

 

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0657.Robot Return to Origin/README_EN.md b/assets/0600-0699/0657.Robot Return to Origin/README_EN.md new file mode 100644 index 00000000..a0e9794a --- /dev/null +++ b/assets/0600-0699/0657.Robot Return to Origin/README_EN.md @@ -0,0 +1,99 @@ +# [657. Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin) + + + +## Description + +

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

+ +

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

+ +

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

+ +

 

+

Example 1:

+ +
+Input: moves = "UD"
+Output: true
+Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
+
+ +

Example 2:

+ +
+Input: moves = "LL"
+Output: false
+Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
+
+ +

Example 3:

+ +
+Input: moves = "RRDD"
+Output: false
+
+ +

Example 4:

+ +
+Input: moves = "LDRRLRUULR"
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= moves.length <= 2 * 104
  • +
  • moves only contains the characters 'U', 'D', 'L' and 'R'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def judgeCircle(self, moves: str) -> bool: + x = y = 0 + for c in moves: + if c == 'R': + x += 1 + elif c == 'L': + x -= 1 + elif c == 'U': + y += 1 + elif c == 'D': + y -= 1 + return x == 0 and y == 0 +``` + +### **Java** + +```java +class Solution { + public boolean judgeCircle(String moves) { + int x = 0, y = 0; + for (int i = 0; i < moves.length(); ++i) { + char c = moves.charAt(i); + if (c == 'R') ++x; + else if (c == 'L') --x; + else if (c == 'U') ++y; + else if (c == 'D') --y; + } + return x == 0 && y == 0; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0658.Find K Closest Elements/README_EN.md b/assets/0600-0699/0658.Find K Closest Elements/README_EN.md new file mode 100644 index 00000000..fc99f16f --- /dev/null +++ b/assets/0600-0699/0658.Find K Closest Elements/README_EN.md @@ -0,0 +1,57 @@ +# [658. Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements) + + + +## Description + +

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

+ +

An integer a is closer to x than an integer b if:

+ +
    +
  • |a - x| < |b - x|, or
  • +
  • |a - x| == |b - x| and a < b
  • +
+ +

 

+

Example 1:

+
Input: arr = [1,2,3,4,5], k = 4, x = 3
+Output: [1,2,3,4]
+

Example 2:

+
Input: arr = [1,2,3,4,5], k = 4, x = -1
+Output: [1,2,3,4]
+
+

 

+

Constraints:

+ +
    +
  • 1 <= k <= arr.length
  • +
  • 1 <= arr.length <= 104
  • +
  • arr is sorted in ascending order.
  • +
  • -104 <= arr[i], x <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md b/assets/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md new file mode 100644 index 00000000..25ec9e9c --- /dev/null +++ b/assets/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md @@ -0,0 +1,71 @@ +# [659. Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences) + + + +## Description + +

Given an integer array nums that is sorted in ascending order, return true if and only if you can split it into one or more subsequences such that each subsequence consists of consecutive integers and has a length of at least 3.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,2,3,3,4,5]
+Output: true
+Explanation:
+You can split them into two consecutive subsequences : 
+1, 2, 3
+3, 4, 5
+
+ +

Example 2:

+ +
+Input: nums = [1,2,3,3,4,4,5,5]
+Output: true
+Explanation:
+You can split them into two consecutive subsequences : 
+1, 2, 3, 4, 5
+3, 4, 5
+
+ +

Example 3:

+ +
+Input: nums = [1,2,3,4,4,5]
+Output: false
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 104
  • +
  • -1000 <= nums[i] <= 1000
  • +
  • nums is sorted in an ascending order.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0660.Remove 9/README_EN.md b/assets/0600-0699/0660.Remove 9/README_EN.md new file mode 100644 index 00000000..0b330ba3 --- /dev/null +++ b/assets/0600-0699/0660.Remove 9/README_EN.md @@ -0,0 +1,48 @@ +# [660. Remove 9](https://leetcode.com/problems/remove-9) + + + +## Description + +

Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...

+ +

So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...

+ +

Given a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer.

+ +

 

+

Example 1:

+
Input: n = 9
+Output: 10
+
+

 

+

Constraints:

+ +
    +
  • 1 <= n <= 8 x 10^8
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0661.Image Smoother/README_EN.md b/assets/0600-0699/0661.Image Smoother/README_EN.md new file mode 100644 index 00000000..ddf40fad --- /dev/null +++ b/assets/0600-0699/0661.Image Smoother/README_EN.md @@ -0,0 +1,79 @@ +# [661. Image Smoother](https://leetcode.com/problems/image-smoother) + + + +## Description + +

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

+ + + +

Example 1:
+ +

+
+Input:
+
+[[1,1,1],
+
+ [1,0,1],
+
+ [1,1,1]]
+
+Output:
+
+[[0, 0, 0],
+
+ [0, 0, 0],
+
+ [0, 0, 0]]
+
+Explanation:
+
+For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
+
+For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
+
+For the point (1,1): floor(8/9) = floor(0.88888889) = 0
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The value in the given matrix is in the range of [0, 255].
  2. + +
  3. The length and width of the given matrix are in the range of [1, 150].
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md b/assets/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md new file mode 100644 index 00000000..1045125f --- /dev/null +++ b/assets/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md @@ -0,0 +1,104 @@ +# [662. Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree) + + + +## Description + +

Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.

+ +

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

+ +

It is guaranteed that the answer will in the range of 32-bit signed integer.

+ +

Example 1:

+ +
+Input: 
+
+           1
+         /   \
+        3     2
+       / \     \  
+      5   3     9 
+
+Output: 4
+Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
+
+ +

Example 2:

+ +
+Input: 
+
+          1
+         /  
+        3    
+       / \       
+      5   3     
+
+Output: 2
+Explanation: The maximum width existing in the third level with the length 2 (5,3).
+
+ +

Example 3:

+ +
+Input: 
+
+          1
+         / \
+        3   2 
+       /        
+      5      
+
+Output: 2
+Explanation: The maximum width existing in the second level with the length 2 (3,2).
+
+ +

Example 4:

+ +
+Input: 
+
+          1
+         / \
+        3   2
+       /     \  
+      5       9 
+     /         \
+    6           7
+Output: 8
+Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
+
+ +

 

+

Constraints:

+ +
    +
  • The given binary tree will have between 1 and 3000 nodes.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0663.Equal Tree Partition/README_EN.md b/assets/0600-0699/0663.Equal Tree Partition/README_EN.md new file mode 100644 index 00000000..ae6aa8a5 --- /dev/null +++ b/assets/0600-0699/0663.Equal Tree Partition/README_EN.md @@ -0,0 +1,129 @@ +# [663. Equal Tree Partition](https://leetcode.com/problems/equal-tree-partition) + + + +## Description + +

+ +Given a binary tree with n nodes, your task is to check if it's possible to partition the tree to two trees which have the equal sum of values after removing exactly one edge on the original tree. + +

+ + + +

Example 1:
+ +

+
+Input:     
+
+    5
+
+   / \
+
+  10 10
+
+    /  \
+
+   2   3
+
+
+
+Output: True
+
+Explanation: 
+
+    5
+
+   / 
+
+  10
+
+      
+
+Sum: 15
+
+
+
+   10
+
+  /  \
+
+ 2    3
+
+
+
+Sum: 15
+
+
+ +

+ + + + + +

Example 2:
+ +

+
+Input:     
+
+    1
+
+   / \
+
+  2  10
+
+    /  \
+
+   2   20
+
+
+
+Output: False
+
+Explanation: You can't split the tree into two trees with equal sum after removing exactly one edge on the tree.
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The range of tree node value is in the range of [-100000, 100000].
  2. + +
  3. 1 <= n <= 10000
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0664.Strange Printer/README_EN.md b/assets/0600-0699/0664.Strange Printer/README_EN.md new file mode 100644 index 00000000..56937a6a --- /dev/null +++ b/assets/0600-0699/0664.Strange Printer/README_EN.md @@ -0,0 +1,91 @@ +# [664. Strange Printer](https://leetcode.com/problems/strange-printer) + + + +## Description + +

+ +There is a strange printer with the following two special requirements: + + + +

    + +
  1. The printer can only print a sequence of the same character each time.
  2. + +
  3. At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.
  4. + +
+ + + +

+ + + +

+ +Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it. + +

+ + + +

Example 1:
+ +

+
+Input: "aaabbb"
+
+Output: 2
+
+Explanation: Print "aaa" first and then print "bbb".
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: "aba"
+
+Output: 2
+
+Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
+
+
+ +

+ + + +

Hint: Length of the given string will not exceed 100.

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0665.Non-decreasing Array/README_EN.md b/assets/0600-0699/0665.Non-decreasing Array/README_EN.md new file mode 100644 index 00000000..57a05c1a --- /dev/null +++ b/assets/0600-0699/0665.Non-decreasing Array/README_EN.md @@ -0,0 +1,60 @@ +# [665. Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array) + + + +## Description + +

Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.

+ +

We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

+ +

 

+

Example 1:

+ +
+Input: nums = [4,2,3]
+Output: true
+Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
+
+ +

Example 2:

+ +
+Input: nums = [4,2,1]
+Output: false
+Explanation: You can't get a non-decreasing array by modify at most one element.
+
+ +

 

+

Constraints:

+ +
    +
  • n == nums.length
  • +
  • 1 <= n <= 104
  • +
  • -105 <= nums[i] <= 105
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0666.Path Sum IV/README_EN.md b/assets/0600-0699/0666.Path Sum IV/README_EN.md new file mode 100644 index 00000000..11f9beb3 --- /dev/null +++ b/assets/0600-0699/0666.Path Sum IV/README_EN.md @@ -0,0 +1,74 @@ +# [666. Path Sum IV](https://leetcode.com/problems/path-sum-iv) + + + +## Description + +

If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.

+ +

For each integer in this list:

+ +
    +
  1. The hundreds digit represents the depth D of this node, 1 <= D <= 4.
  2. +
  3. The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The position is the same as that in a full binary tree.
  4. +
  5. The units digit represents the value V of this node, 0 <= V <= 9.
  6. +
+ +

Given a list of ascending three-digits integers representing a binary tree with the depth smaller than 5, you need to return the sum of all paths from the root towards the leaves.

+ +

It's guaranteed that the given list represents a valid connected binary tree.

+ +

Example 1:

+ +
+Input: [113, 215, 221]
+Output: 12
+Explanation: 
+The tree that the list represents is:
+    3
+   / \
+  5   1
+
+The path sum is (3 + 5) + (3 + 1) = 12.
+
+ +

 

+ +

Example 2:

+ +
+Input: [113, 221]
+Output: 4
+Explanation: 
+The tree that the list represents is: 
+    3
+     \
+      1
+
+The path sum is (3 + 1) = 4.
+
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0667.Beautiful Arrangement II/README_EN.md b/assets/0600-0699/0667.Beautiful Arrangement II/README_EN.md new file mode 100644 index 00000000..4b21f3c7 --- /dev/null +++ b/assets/0600-0699/0667.Beautiful Arrangement II/README_EN.md @@ -0,0 +1,62 @@ +# [667. Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii) + + + +## Description + +

Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:

+ +
    +
  • Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
  • +
+ +

Return the list answer. If there multiple valid answers, return any of them.

+ +

 

+

Example 1:

+ +
+Input: n = 3, k = 1
+Output: [1,2,3]
+Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
+
+ +

Example 2:

+ +
+Input: n = 3, k = 2
+Output: [1,3,2]
+Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= k < n <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md b/assets/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md new file mode 100644 index 00000000..70997171 --- /dev/null +++ b/assets/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md @@ -0,0 +1,115 @@ +# [668. Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table) + + + +## Description + +

+ +Nearly every one have used the Multiplication Table. But could you find out the k-th smallest number quickly from the multiplication table? + +

+ + + +

+ +Given the height m and the length n of a m * n Multiplication Table, and a positive integer k, you need to return the k-th smallest number in this table. + +

+ + + +

Example 1:
+ +

+
+Input: m = 3, n = 3, k = 5
+
+Output: 
+
+Explanation: 
+
+The Multiplication Table:
+
+1	2	3
+
+2	4	6
+
+3	6	9
+
+
+
+The 5-th smallest number is 3 (1, 2, 2, 3, 3).
+
+
+ +

+ + + + + +

Example 2:
+ +

+
+Input: m = 2, n = 3, k = 6
+
+Output: 
+
+Explanation: 
+
+The Multiplication Table:
+
+1	2	3
+
+2	4	6
+
+
+
+The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).
+
+
+ +

+ + + + + +

Note:
+ +

    + +
  1. The m and n will be in the range [1, 30000].
  2. + +
  3. The k will be in the range [1, m * n]
  4. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0669.Trim a Binary Search Tree/README_EN.md b/assets/0600-0699/0669.Trim a Binary Search Tree/README_EN.md new file mode 100644 index 00000000..54f50681 --- /dev/null +++ b/assets/0600-0699/0669.Trim a Binary Search Tree/README_EN.md @@ -0,0 +1,81 @@ +# [669. Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree) + + + +## Description + +

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

+ +

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

+ +

 

+

Example 1:

+ +
+Input: root = [1,0,2], low = 1, high = 2
+Output: [1,null,2]
+
+ +

Example 2:

+ +
+Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
+Output: [3,2,null,1]
+
+ +

Example 3:

+ +
+Input: root = [1], low = 1, high = 2
+Output: [1]
+
+ +

Example 4:

+ +
+Input: root = [1,null,2], low = 1, high = 3
+Output: [1,null,2]
+
+ +

Example 5:

+ +
+Input: root = [1,null,2], low = 2, high = 4
+Output: [2]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree in the range [1, 104].
  • +
  • 0 <= Node.val <= 104
  • +
  • The value of each node in the tree is unique.
  • +
  • root is guaranteed to be a valid binary search tree.
  • +
  • 0 <= low <= high <= 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0669.Trim a Binary Search Tree/images/trim1.jpg b/assets/0600-0699/0669.Trim a Binary Search Tree/images/trim1.jpg new file mode 100644 index 00000000..7d4d29b3 Binary files /dev/null and b/assets/0600-0699/0669.Trim a Binary Search Tree/images/trim1.jpg differ diff --git a/assets/0600-0699/0669.Trim a Binary Search Tree/images/trim2.jpg b/assets/0600-0699/0669.Trim a Binary Search Tree/images/trim2.jpg new file mode 100644 index 00000000..8f5ebb2e Binary files /dev/null and b/assets/0600-0699/0669.Trim a Binary Search Tree/images/trim2.jpg differ diff --git a/assets/0600-0699/0670.Maximum Swap/README_EN.md b/assets/0600-0699/0670.Maximum Swap/README_EN.md new file mode 100644 index 00000000..ce7989b1 --- /dev/null +++ b/assets/0600-0699/0670.Maximum Swap/README_EN.md @@ -0,0 +1,81 @@ +# [670. Maximum Swap](https://leetcode.com/problems/maximum-swap) + + + +## Description + +

+ +Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. + +

+ + + +

Example 1:
+ +

+
+Input: 2736
+
+Output: 7236
+
+Explanation: Swap the number 2 and the number 7.
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: 9973
+
+Output: 9973
+
+Explanation: No swap.
+
+
+ +

+ + + + + +

Note:
+ +

    + +
  1. The given number is in the range [0, 108]
  2. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md b/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md new file mode 100644 index 00000000..90038cc4 --- /dev/null +++ b/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md @@ -0,0 +1,115 @@ +# [671. Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree) + + + +## Description + +

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

+ +

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

+ +

If no such second minimum value exists, output -1 instead.

+ +

 

+ +

 

+

Example 1:

+ +
+Input: root = [2,2,5,null,null,5,7]
+Output: 5
+Explanation: The smallest value is 2, the second smallest value is 5.
+
+ +

Example 2:

+ +
+Input: root = [2,2,2]
+Output: -1
+Explanation: The smallest value is 2, but there isn't any second smallest value.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [1, 25].
  • +
  • 1 <= Node.val <= 231 - 1
  • +
  • root.val == min(root.left.val, root.right.val) for each internal node of the tree.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findSecondMinimumValue(self, root: TreeNode) -> int: + def traverse(root, val): + if root is None: + return + traverse(root.left, val) + traverse(root.right, val) + if root.val > val: + self.res = root.val if self.res == -1 else min(self.res, root.val) + + self.res = -1 + traverse(root, root.val) + return self.res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int res; + public int findSecondMinimumValue(TreeNode root) { + res = -1; + traverse(root, root.val); + return res; + } + + private void traverse(TreeNode root, int min) { + if (root == null) { + return; + } + traverse(root.left, min); + traverse(root.right, min); + if (root.val > min) { + res = res == -1 ? root.val : Math.min(res, root.val); + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/images/smbt1.jpg b/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/images/smbt1.jpg new file mode 100644 index 00000000..b7916705 Binary files /dev/null and b/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/images/smbt1.jpg differ diff --git a/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/images/smbt2.jpg b/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/images/smbt2.jpg new file mode 100644 index 00000000..39e99843 Binary files /dev/null and b/assets/0600-0699/0671.Second Minimum Node In a Binary Tree/images/smbt2.jpg differ diff --git a/assets/0600-0699/0672.Bulb Switcher II/README_EN.md b/assets/0600-0699/0672.Bulb Switcher II/README_EN.md new file mode 100644 index 00000000..5f7806cd --- /dev/null +++ b/assets/0600-0699/0672.Bulb Switcher II/README_EN.md @@ -0,0 +1,114 @@ +# [672. Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii) + + + +## Description + +

There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be.

+ + + +

Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:

+ + + +
    +
  1. Flip all the lights.
  2. +
  3. Flip lights with even numbers.
  4. +
  5. Flip lights with odd numbers.
  6. +
  7. Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...
  8. +
+ + + +

 

+ + + +

Example 1:

+ + + +
+
+Input: n = 1, m = 1.
+
+Output: 2
+
+Explanation: Status can be: [on], [off]
+
+
+ + + +

 

+ + + +

Example 2:

+ + + +
+
+Input: n = 2, m = 1.
+
+Output: 3
+
+Explanation: Status can be: [on, off], [off, on], [off, off]
+
+
+ + + +

 

+ + + +

Example 3:

+ + + +
+
+Input: n = 3, m = 1.
+
+Output: 4
+
+Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].
+
+
+ + + +

 

+ + + +

Note: n and m both fit in range [0, 1000].

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md b/assets/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md new file mode 100644 index 00000000..1e84c781 --- /dev/null +++ b/assets/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md @@ -0,0 +1,60 @@ +# [673. Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence) + + + +## Description + +

Given an integer array nums, return the number of longest increasing subsequences.

+ +

Notice that the sequence has to be strictly increasing.

+ +

 

+

Example 1:

+ +
+Input: nums = [1,3,5,4,7]
+Output: 2
+Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
+
+ +

Example 2:

+ +
+Input: nums = [2,2,2,2,2]
+Output: 5
+Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
+
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= nums.length <= 2000
  • +
  • -106 <= nums[i] <= 106
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md b/assets/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md new file mode 100644 index 00000000..99202ea4 --- /dev/null +++ b/assets/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md @@ -0,0 +1,82 @@ +# [674. Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence) + + + +## Description + +

Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.

+ +

A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].

+ +

 

+

Example 1:

+ +
+Input: nums = [1,3,5,4,7]
+Output: 3
+Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
+Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
+4.
+
+ +

Example 2:

+ +
+Input: nums = [2,2,2,2,2]
+Output: 1
+Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
+increasing.
+
+ +

 

+

Constraints:

+ +
    +
  • 0 <= nums.length <= 104
  • +
  • -109 <= nums[i] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + n = len(nums) + if n < 2: + return n + res = f = 1 + for i in range(1, n): + f = 1 + (f if nums[i - 1] < nums[i] else 0) + res = max(res, f) + return res +``` + +### **Java** + +```java +class Solution { + public int findLengthOfLCIS(int[] nums) { + int n; + if ((n = nums.length) < 2) return n; + int res = 1, f = 1; + for (int i = 1; i < n; ++i) { + f = 1 + (nums[i - 1] < nums[i] ? f : 0); + res = Math.max(res, f); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md b/assets/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md new file mode 100644 index 00000000..bddfc7ea --- /dev/null +++ b/assets/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md @@ -0,0 +1,82 @@ +# [675. Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event) + + + +## Description + +

You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:

+ +
    +
  • 0 means the cell cannot be walked through.
  • +
  • 1 represents an empty cell that can be walked through.
  • +
  • A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.
  • +
+ +

In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.

+ +

You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).

+ +

Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.

+ +

You are guaranteed that no two trees have the same height, and there is at least one tree needs to be cut off.

+ +

 

+

Example 1:

+ +
+Input: forest = [[1,2,3],[0,0,4],[7,6,5]]
+Output: 6
+Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
+
+ +

Example 2:

+ +
+Input: forest = [[1,2,3],[0,0,0],[7,6,5]]
+Output: -1
+Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.
+
+ +

Example 3:

+ +
+Input: forest = [[2,3,4],[0,0,5],[8,7,6]]
+Output: 6
+Explanation: You can follow the same path as Example 1 to cut off all the trees.
+Note that you can cut off the first tree at (0, 0) before making any steps.
+
+ +

 

+

Constraints:

+ +
    +
  • m == forest.length
  • +
  • n == forest[i].length
  • +
  • 1 <= m, n <= 50
  • +
  • 0 <= forest[i][j] <= 109
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0675.Cut Off Trees for Golf Event/images/trees1.jpg b/assets/0600-0699/0675.Cut Off Trees for Golf Event/images/trees1.jpg new file mode 100644 index 00000000..d9f07e60 Binary files /dev/null and b/assets/0600-0699/0675.Cut Off Trees for Golf Event/images/trees1.jpg differ diff --git a/assets/0600-0699/0675.Cut Off Trees for Golf Event/images/trees2.jpg b/assets/0600-0699/0675.Cut Off Trees for Golf Event/images/trees2.jpg new file mode 100644 index 00000000..e5a0980d Binary files /dev/null and b/assets/0600-0699/0675.Cut Off Trees for Golf Event/images/trees2.jpg differ diff --git a/assets/0600-0699/0676.Implement Magic Dictionary/README_EN.md b/assets/0600-0699/0676.Implement Magic Dictionary/README_EN.md new file mode 100644 index 00000000..65a1ef0c --- /dev/null +++ b/assets/0600-0699/0676.Implement Magic Dictionary/README_EN.md @@ -0,0 +1,73 @@ +# [676. Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary) + + + +## Description + +

Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.

+ +

Implement the MagicDictionary class:

+ +
    +
  • MagicDictionary() Initializes the object.
  • +
  • void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.
  • +
  • bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MagicDictionary", "buildDict", "search", "search", "search", "search"]
+[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
+Output
+[null, null, false, true, false, false]
+
+Explanation
+MagicDictionary magicDictionary = new MagicDictionary();
+magicDictionary.buildDict(["hello", "leetcode"]);
+magicDictionary.search("hello"); // return False
+magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
+magicDictionary.search("hell"); // return False
+magicDictionary.search("leetcoded"); // return False
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= dictionary.length <= 100
  • +
  • 1 <= dictionary[i].length <= 100
  • +
  • dictionary[i] consists of only lower-case English letters.
  • +
  • All the strings in dictionary are distinct.
  • +
  • 1 <= searchWord.length <= 100
  • +
  • searchWord consists of only lower-case English letters.
  • +
  • buildDict will be called only once before search.
  • +
  • At most 100 calls will be made to search.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0677.Map Sum Pairs/README_EN.md b/assets/0600-0699/0677.Map Sum Pairs/README_EN.md new file mode 100644 index 00000000..e9521f79 --- /dev/null +++ b/assets/0600-0699/0677.Map Sum Pairs/README_EN.md @@ -0,0 +1,66 @@ +# [677. Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs) + + + +## Description + +

Implement the MapSum class:

+ +
    +
  • MapSum() Initializes the MapSum object.
  • +
  • void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
  • +
  • int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.
  • +
+ +

 

+

Example 1:

+ +
+Input
+["MapSum", "insert", "sum", "insert", "sum"]
+[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
+Output
+[null, null, 3, null, 5]
+
+Explanation
+MapSum mapSum = new MapSum();
+mapSum.insert("apple", 3);  
+mapSum.sum("ap");           // return 3 (apple = 3)
+mapSum.insert("app", 2);    
+mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= key.length, prefix.length <= 50
  • +
  • key and prefix consist of only lowercase English letters.
  • +
  • 1 <= val <= 1000
  • +
  • At most 50 calls will be made to insert and sum.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0678.Valid Parenthesis String/README_EN.md b/assets/0600-0699/0678.Valid Parenthesis String/README_EN.md new file mode 100644 index 00000000..5f40bcb1 --- /dev/null +++ b/assets/0600-0699/0678.Valid Parenthesis String/README_EN.md @@ -0,0 +1,60 @@ +# [678. Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string) + + + +## Description + +

Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.

+ +

The following rules define a valid string:

+ +
    +
  • Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  • +
  • Any right parenthesis ')' must have a corresponding left parenthesis '('.
  • +
  • Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  • +
  • '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
  • +
+ +

 

+

Example 1:

+
Input: s = "()"
+Output: true
+

Example 2:

+
Input: s = "(*)"
+Output: true
+

Example 3:

+
Input: s = "(*))"
+Output: true
+
+

 

+

Constraints:

+ +
    +
  • 1 <= s.length <= 100
  • +
  • s[i] is '(', ')' or '*'.
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0679.24 Game/README_EN.md b/assets/0600-0699/0679.24 Game/README_EN.md new file mode 100644 index 00000000..e726d79a --- /dev/null +++ b/assets/0600-0699/0679.24 Game/README_EN.md @@ -0,0 +1,83 @@ +# [679. 24 Game](https://leetcode.com/problems/24-game) + + + +## Description + +

+ +You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24. + +

+ + + +

Example 1:
+ +

+
+Input: [4, 1, 8, 7]
+
+Output: True
+
+Explanation: (8-4) * (7-1) = 24
+
+
+ +

+ + + +

Example 2:
+ +

+
+Input: [1, 2, 1, 2]
+
+Output: False
+
+
+ +

+ + + +

Note:
+ +

    + +
  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
  2. + +
  3. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
  4. + +
  5. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.
  6. + +
+ +

+ +

+ +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0680.Valid Palindrome II/README_EN.md b/assets/0600-0699/0680.Valid Palindrome II/README_EN.md new file mode 100644 index 00000000..97859993 --- /dev/null +++ b/assets/0600-0699/0680.Valid Palindrome II/README_EN.md @@ -0,0 +1,130 @@ +# [680. Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii) + + + +## Description + +

+ +Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. + +

+ +

Example 1:
+ +

+
+Input: "aba"
+
+Output: True
+
+
+ +

+ +

Example 2:
+ +

+
+Input: "abca"
+
+Output: True
+
+Explanation: You could delete the character 'c'.
+
+
+ +

+ +

Note:
+ +

    + +
  1. The string will only contain lowercase characters a-z. + +The maximum length of the string is 50000.
  2. + +
+ +

+ +## Solutions + + + +### **Python3** + +```python +class Solution: + def validPalindrome(self, s: str) -> bool: + def isPalindrome(s): + i, j = 0, len(s) - 1 + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True + + i, j = 0, len(s) - 1 + while i < j: + if s[i] != s[j]: + return isPalindrome(s[i: j]) or isPalindrome(s[i + 1: j + 1]) + i += 1 + j -= 1 + return True +``` + +### **Java** + +```java +class Solution { + public boolean validPalindrome(String s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalindrome(s.substring(i, j)) || isPalindrome(s.substring(i + 1, j + 1)); + } + } + return true; + } + + private boolean isPalindrome(String s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; + } +} +``` + +### **TypeScript** + +```ts +function validPalindrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalinddrome(s.slice(i, j)) || isPalinddrome(s.slice(i + 1, j + 1)); + } + } + return true; +}; + +function isPalinddrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0681.Next Closest Time/README_EN.md b/assets/0600-0699/0681.Next Closest Time/README_EN.md new file mode 100644 index 00000000..1c4cfe4b --- /dev/null +++ b/assets/0600-0699/0681.Next Closest Time/README_EN.md @@ -0,0 +1,63 @@ +# [681. Next Closest Time](https://leetcode.com/problems/next-closest-time) + + + +## Description + +

Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

+ +

You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.

+ +

 

+

Example 1:

+ +
+Input: time = "19:34"
+Output: "19:39"
+Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later.
+It is not 19:33, because this occurs 23 hours and 59 minutes later.
+
+ +

Example 2:

+ +
+Input: time = "23:59"
+Output: "22:22"
+Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22.
+It may be assumed that the returned time is next day's time since it is smaller than the input time numerically.
+
+ +

 

+

Constraints:

+ +
    +
  • time.length == 5
  • +
  • time is a valid time in the form "HH:MM".
  • +
  • 0 <= HH < 24
  • +
  • 0 <= MM < 60
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0682.Baseball Game/README_EN.md b/assets/0600-0699/0682.Baseball Game/README_EN.md new file mode 100644 index 00000000..a9be3e8a --- /dev/null +++ b/assets/0600-0699/0682.Baseball Game/README_EN.md @@ -0,0 +1,127 @@ +# [682. Baseball Game](https://leetcode.com/problems/baseball-game) + + + +## Description + +

You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.

+ +

At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:

+ +
    +
  1. An integer x - Record a new score of x.
  2. +
  3. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
  4. +
  5. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
  6. +
  7. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
  8. +
+ +

Return the sum of all the scores on the record.

+ +

 

+

Example 1:

+ +
+Input: ops = ["5","2","C","D","+"]
+Output: 30
+Explanation:
+"5" - Add 5 to the record, record is now [5].
+"2" - Add 2 to the record, record is now [5, 2].
+"C" - Invalidate and remove the previous score, record is now [5].
+"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
+"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
+The total sum is 5 + 10 + 15 = 30.
+
+ +

Example 2:

+ +
+Input: ops = ["5","-2","4","C","D","9","+","+"]
+Output: 27
+Explanation:
+"5" - Add 5 to the record, record is now [5].
+"-2" - Add -2 to the record, record is now [5, -2].
+"4" - Add 4 to the record, record is now [5, -2, 4].
+"C" - Invalidate and remove the previous score, record is now [5, -2].
+"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
+"9" - Add 9 to the record, record is now [5, -2, -4, 9].
+"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
+"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
+The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
+
+ +

Example 3:

+ +
+Input: ops = ["1"]
+Output: 1
+
+ +

 

+

Constraints:

+ +
    +
  • 1 <= ops.length <= 1000
  • +
  • ops[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104].
  • +
  • For operation "+", there will always be at least two previous scores on the record.
  • +
  • For operations "C" and "D", there will always be at least one previous score on the record.
  • +
+ + +## Solutions + + + +### **Python3** + +```python +class Solution: + def calPoints(self, ops: List[str]) -> int: + stack = [] + for op in ops: + if op == 'C': + stack.pop() + elif op == 'D': + stack.append(stack[-1] << 1) + elif op == '+': + stack.append(stack[-1] + stack[-2]) + else: + stack.append(int(op)) + return sum(stack) +``` + +### **Java** + +```java +class Solution { + public int calPoints(String[] ops) { + Deque stack = new ArrayDeque<>(); + for (String op : ops) { + if ("C".equals(op)) { + stack.pop(); + } else if ("D".equals(op)) { + stack.push(stack.peek() << 1); + } else if ("+".equals(op)) { + Integer a = stack.pop(); + Integer b = stack.peek(); + stack.push(a); + stack.push(a + b); + } else { + stack.push(Integer.valueOf(op)); + } + } + int res = 0; + for (Integer score : stack) { + res += score; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0683.K Empty Slots/README_EN.md b/assets/0600-0699/0683.K Empty Slots/README_EN.md new file mode 100644 index 00000000..21f19b54 --- /dev/null +++ b/assets/0600-0699/0683.K Empty Slots/README_EN.md @@ -0,0 +1,66 @@ +# [683. K Empty Slots](https://leetcode.com/problems/k-empty-slots) + + + +## Description + +

You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off. We turn on exactly one bulb every day until all bulbs are on after n days.

+ +

You are given an array bulbs of length n where bulbs[i] = x means that on the (i+1)th day, we will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.

+ +

Given an integer k, return the minimum day number such that there exists two turned on bulbs that have exactly k bulbs between them that are all turned off. If there isn't such day, return -1.

+ +

 

+

Example 1:

+ +
+Input: bulbs = [1,3,2], k = 1
+Output: 2
+Explanation:
+On the first day: bulbs[0] = 1, first bulb is turned on: [1,0,0]
+On the second day: bulbs[1] = 3, third bulb is turned on: [1,0,1]
+On the third day: bulbs[2] = 2, second bulb is turned on: [1,1,1]
+We return 2 because on the second day, there were two on bulbs with one off bulb between them.
+ +

Example 2:

+ +
+Input: bulbs = [1,2,3], k = 1
+Output: -1
+
+ +

 

+

Constraints:

+ +
    +
  • n == bulbs.length
  • +
  • 1 <= n <= 2 * 104
  • +
  • 1 <= bulbs[i] <= n
  • +
  • bulbs is a permutation of numbers from 1 to n.
  • +
  • 0 <= k <= 2 * 104
  • +
+ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0684.Redundant Connection/README_EN.md b/assets/0600-0699/0684.Redundant Connection/README_EN.md new file mode 100644 index 00000000..ea7a56a9 --- /dev/null +++ b/assets/0600-0699/0684.Redundant Connection/README_EN.md @@ -0,0 +1,107 @@ +# [684. Redundant Connection](https://leetcode.com/problems/redundant-connection) + + + +## Description + +

+ +In this problem, a tree is an undirected graph that is connected and has no cycles. + +

+ +The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed. + +

+ +The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v. + +

+ +Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v. + +

Example 1:
+ +

+
+Input: [[1,2], [1,3], [2,3]]
+
+Output: [2,3]
+
+Explanation: The given undirected graph will be like this:
+
+  1
+
+ / \
+
+2 - 3
+
+
+ +

+ +

Example 2:
+ +

+
+Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
+
+Output: [1,4]
+
+Explanation: The given undirected graph will be like this:
+
+5 - 1 - 2
+
+    |   |
+
+    4 - 3
+
+
+ +

+ +

Note:
+ +

  • The size of the input 2D-array will be between 3 and 1000.
  • + +
  • Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
  • + +

    + + + +
    + + + +

    + +Update (2017-09-26):
    + +We have overhauled the problem description + test cases and specified clearly the graph is an undirected graph. For the directed graph follow up please see Redundant Connection II). We apologize for any inconvenience caused. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0685.Redundant Connection II/README_EN.md b/assets/0600-0699/0685.Redundant Connection II/README_EN.md new file mode 100644 index 00000000..7780a5bb --- /dev/null +++ b/assets/0600-0699/0685.Redundant Connection II/README_EN.md @@ -0,0 +1,63 @@ +# [685. Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii) + + + +## Description + +

    In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

    + +

    The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.

    + +

    The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.

    + +

    Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.

    + +

     

    +

    Example 1:

    + +
    +Input: edges = [[1,2],[1,3],[2,3]]
    +Output: [2,3]
    +
    + +

    Example 2:

    + +
    +Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
    +Output: [4,1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == edges.length
    • +
    • 3 <= n <= 1000
    • +
    • edges[i].length == 2
    • +
    • 1 <= ui, vi <= n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0685.Redundant Connection II/images/graph1.jpg b/assets/0600-0699/0685.Redundant Connection II/images/graph1.jpg new file mode 100644 index 00000000..928dcfb0 Binary files /dev/null and b/assets/0600-0699/0685.Redundant Connection II/images/graph1.jpg differ diff --git a/assets/0600-0699/0685.Redundant Connection II/images/graph2.jpg b/assets/0600-0699/0685.Redundant Connection II/images/graph2.jpg new file mode 100644 index 00000000..513b7a69 Binary files /dev/null and b/assets/0600-0699/0685.Redundant Connection II/images/graph2.jpg differ diff --git a/assets/0600-0699/0686.Repeated String Match/README_EN.md b/assets/0600-0699/0686.Repeated String Match/README_EN.md new file mode 100644 index 00000000..2548d806 --- /dev/null +++ b/assets/0600-0699/0686.Repeated String Match/README_EN.md @@ -0,0 +1,73 @@ +# [686. Repeated String Match](https://leetcode.com/problems/repeated-string-match) + + + +## Description + +

    Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.

    + +

    Notice: string "abc" repeated 0 times is "",  repeated 1 time is "abc" and repeated 2 times is "abcabc".

    + +

     

    +

    Example 1:

    + +
    +Input: a = "abcd", b = "cdabcdab"
    +Output: 3
    +Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
    +
    + +

    Example 2:

    + +
    +Input: a = "a", b = "aa"
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: a = "a", b = "a"
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: a = "abc", b = "wxyz"
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= a.length <= 104
    • +
    • 1 <= b.length <= 104
    • +
    • a and b consist of lower-case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0687.Longest Univalue Path/README_EN.md b/assets/0600-0699/0687.Longest Univalue Path/README_EN.md new file mode 100644 index 00000000..edffc577 --- /dev/null +++ b/assets/0600-0699/0687.Longest Univalue Path/README_EN.md @@ -0,0 +1,58 @@ +# [687. Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path) + + + +## Description + +

    Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

    + +

    The length of the path between two nodes is represented by the number of edges between them.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [5,4,5,1,1,5]
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: root = [1,4,5,4,4,5]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [0, 104].
    • +
    • -1000 <= Node.val <= 1000
    • +
    • The depth of the tree will not exceed 1000.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0687.Longest Univalue Path/images/ex1.jpg b/assets/0600-0699/0687.Longest Univalue Path/images/ex1.jpg new file mode 100644 index 00000000..e9d012cf Binary files /dev/null and b/assets/0600-0699/0687.Longest Univalue Path/images/ex1.jpg differ diff --git a/assets/0600-0699/0687.Longest Univalue Path/images/ex2.jpg b/assets/0600-0699/0687.Longest Univalue Path/images/ex2.jpg new file mode 100644 index 00000000..31be2383 Binary files /dev/null and b/assets/0600-0699/0687.Longest Univalue Path/images/ex2.jpg differ diff --git a/assets/0600-0699/0688.Knight Probability in Chessboard/README_EN.md b/assets/0600-0699/0688.Knight Probability in Chessboard/README_EN.md new file mode 100644 index 00000000..c72c6dd5 --- /dev/null +++ b/assets/0600-0699/0688.Knight Probability in Chessboard/README_EN.md @@ -0,0 +1,97 @@ +# [688. Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard) + + + +## Description + +

    On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).

    + + + +

    A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

    + + + +

     

    + + + +

    + + + +

     

    + + + +

    Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.

    + + + +

    The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.

    + + + +

     

    + + + +

    Example:

    + + + +
    +
    +Input: 3, 2, 0, 0
    +
    +Output: 0.0625
    +
    +Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
    +
    +From each of those positions, there are also two moves that will keep the knight on the board.
    +
    +The total probability the knight stays on the board is 0.0625.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • N will be between 1 and 25.
    • +
    • K will be between 0 and 100.
    • +
    • The knight always initially starts on the board.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0688.Knight Probability in Chessboard/images/knight.png b/assets/0600-0699/0688.Knight Probability in Chessboard/images/knight.png new file mode 100644 index 00000000..1ab55680 Binary files /dev/null and b/assets/0600-0699/0688.Knight Probability in Chessboard/images/knight.png differ diff --git a/assets/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md b/assets/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md new file mode 100644 index 00000000..8bdbc6b9 --- /dev/null +++ b/assets/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md @@ -0,0 +1,79 @@ +# [689. Maximum Sum of 3 Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays) + + + +## Description + +

    In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.

    + + + +

    Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.

    + + + +

    Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.

    + + + +

    Example:

    + + + +
    +
    +Input: [1,2,1,2,6,7,5,1], 2
    +
    +Output: [0, 3, 5]
    +
    +Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
    +
    +We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • nums.length will be between 1 and 20000.
    • +
    • nums[i] will be between 1 and 65535.
    • +
    • k will be between 1 and floor(nums.length / 3).
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0690.Employee Importance/README_EN.md b/assets/0600-0699/0690.Employee Importance/README_EN.md new file mode 100644 index 00000000..4031087c --- /dev/null +++ b/assets/0600-0699/0690.Employee Importance/README_EN.md @@ -0,0 +1,137 @@ +# [690. Employee Importance](https://leetcode.com/problems/employee-importance) + + + +## Description + +

    You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.

    + +

    For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

    + +

    Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates.

    + +

    Example 1:

    + +
    +Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
    +Output: 11
    +Explanation:
    +Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. One employee has at most one direct leader and may have several subordinates.
    2. +
    3. The maximum number of employees won't exceed 2000.
    4. +
    + +## Solutions + +"all their subordinates" include "subordinates of subordinates", first use a hash table to store the mapping relationship between `employee.id` and `employee`, and then recursively solve it (it can also be implemented with BFS) + + + +### **Python3** + +```python +""" +# Definition for Employee. +class Employee: + def __init__(self, id: int, importance: int, subordinates: List[int]): + self.id = id + self.importance = importance + self.subordinates = subordinates +""" + +class Solution: + def getImportance(self, employees: List['Employee'], id: int) -> int: + m = {emp.id: emp for emp in employees} + + def dfs(id: int) -> int: + emp = m[id] + s = emp.importance + for sub in emp.subordinates: + s += dfs(sub) + return s + + return dfs(id) +``` + +### **Java** + +```java +/* +// Definition for Employee. +class Employee { + public int id; + public int importance; + public List subordinates; +}; +*/ + +class Solution { + + private final Map map = new HashMap<>(); + + public int getImportance(List employees, int id) { + for (Employee employee : employees) { + map.put(employee.id, employee); + } + return dfs(id); + } + + private int dfs(int id) { + Employee employee = map.get(id); + int sum = employee.importance; + for (Integer subordinate : employee.subordinates) { + sum += dfs(subordinate); + } + return sum; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for Employee. + * function Employee(id, importance, subordinates) { + * this.id = id; + * this.importance = importance; + * this.subordinates = subordinates; + * } + */ + +/** + * @param {Employee[]} employees + * @param {number} id + * @return {number} + */ +var GetImportance = function (employees, id) { + const map = new Map(); + for (const employee of employees) { + map.set(employee.id, employee); + } + const dfs = (id) => { + const employee = map.get(id); + let sum = employee.importance; + for (const subId of employee.subordinates) { + sum += dfs(subId); + } + return sum; + }; + return dfs(id); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0691.Stickers to Spell Word/README_EN.md b/assets/0600-0699/0691.Stickers to Spell Word/README_EN.md new file mode 100644 index 00000000..5db77fce --- /dev/null +++ b/assets/0600-0699/0691.Stickers to Spell Word/README_EN.md @@ -0,0 +1,119 @@ +# [691. Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word) + + + +## Description + +

    + +We are given N different types of stickers. Each sticker has a lowercase English word on it. + +

    + +You would like to spell out the given target string by cutting individual letters from your collection of stickers and rearranging them. + +

    + +You can use each sticker more than once if you want, and you have infinite quantities of each sticker. + +

    + +What is the minimum number of stickers that you need to spell out the target? If the task is impossible, return -1. + +

    + + + +

    Example 1:

    + +

    Input:

    +
    +["with", "example", "science"], "thehat"
    +
    +

    + + + +

    Output:

    +
    +3
    +
    +

    + + + +

    Explanation:

    +
    +We can use 2 "with" stickers, and 1 "example" sticker.
    +
    +After cutting and rearrange the letters of those stickers, we can form the target "thehat".
    +
    +Also, this is the minimum number of stickers necessary to form the target string.
    +
    +

    + + + +

    Example 2:

    + +

    Input:

    +
    +["notice", "possible"], "basicbasic"
    +
    +

    + + + +

    Output:

    +
    +-1
    +
    +

    + + + +

    Explanation:

    +
    +We can't form the target "basicbasic" from cutting letters from the given stickers.
    +
    +

    + + + +

    Note: + +

  • stickers has length in the range [1, 50].
  • + +
  • stickers consists of lowercase English words (without apostrophes).
  • + +
  • target has length in the range [1, 15], and consists of lowercase English letters.
  • + +
  • In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.
  • + +
  • The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0692.Top K Frequent Words/README_EN.md b/assets/0600-0699/0692.Top K Frequent Words/README_EN.md new file mode 100644 index 00000000..a2d2cc69 --- /dev/null +++ b/assets/0600-0699/0692.Top K Frequent Words/README_EN.md @@ -0,0 +1,116 @@ +# [692. Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words) + + + +## Description + +

    Given a non-empty list of words, return the k most frequent elements.

    + +

    Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

    + +

    Example 1:
    + +

    +
    +Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
    +
    +Output: ["i", "love"]
    +
    +Explanation: "i" and "love" are the two most frequent words.
    +
    +    Note that "i" comes before "love" due to a lower alphabetical order.
    +
    +
    + +

    + +

    Example 2:
    + +

    +
    +Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
    +
    +Output: ["the", "is", "sunny", "day"]
    +
    +Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    +
    +    with the number of occurrence being 4, 3, 2 and 1 respectively.
    +
    +
    + +

    + +

    Note:
    + +

      + +
    1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
    2. + +
    3. Input words contain only lowercase letters.
    4. + +
    + +

    + +

    Follow up:
    + +

      + +
    1. Try to solve it in O(n log k) time and O(n) extra space.
    2. + +
    + +

    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def topKFrequent(self, words: List[str], k: int) -> List[str]: + counter = collections.Counter(words) + res = sorted(counter, key=lambda word: (-counter[word], word)) + return res[:k] +``` + +### **Java** + +```java +class Solution { + public List topKFrequent(String[] words, int k) { + Map counter = new HashMap<>(); + for (String word : words) { + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> { + if (counter.get(a).equals(counter.get(b))) { + return b.compareTo(a); + } + return counter.get(a) - counter.get(b); + }); + for (String word : counter.keySet()) { + minHeap.offer(word); + if (minHeap.size() > k) { + minHeap.poll(); + } + } + List res = new ArrayList<>(); + while (!minHeap.isEmpty()) { + res.add(minHeap.poll()); + } + Collections.reverse(res); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md b/assets/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md new file mode 100644 index 00000000..2f949868 --- /dev/null +++ b/assets/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md @@ -0,0 +1,96 @@ +# [693. Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits) + + + +## Description + +

    Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5
    +Output: true
    +Explanation: The binary representation of 5 is: 101
    +
    + +

    Example 2:

    + +
    +Input: n = 7
    +Output: false
    +Explanation: The binary representation of 7 is: 111.
    + +

    Example 3:

    + +
    +Input: n = 11
    +Output: false
    +Explanation: The binary representation of 11 is: 1011.
    + +

    Example 4:

    + +
    +Input: n = 10
    +Output: true
    +Explanation: The binary representation of 10 is: 1010.
    + +

    Example 5:

    + +
    +Input: n = 3
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + n = (n ^ (n >> 1)) + 1 + return (n & (n - 1)) == 0 +``` + +### **Java** + +```java +class Solution { + public boolean hasAlternatingBits(int n) { + n = (n ^ (n >> 1)) + 1; + return (n & (n - 1)) == 0; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & ((long) n + 1)) == 0; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0694.Number of Distinct Islands/README_EN.md b/assets/0600-0699/0694.Number of Distinct Islands/README_EN.md new file mode 100644 index 00000000..4abdf42d --- /dev/null +++ b/assets/0600-0699/0694.Number of Distinct Islands/README_EN.md @@ -0,0 +1,101 @@ +# [694. Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands) + + + +## Description + +

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    + + + +

    Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.

    + + + +

    Example 1:
    + +

    +
    +11000
    +
    +11000
    +
    +00011
    +
    +00011
    +
    +
    + +Given the above grid map, return 1. + +

    + + + +

    Example 2:
    + +

    11011
    +
    +10000
    +
    +00001
    +
    +11011
    + +Given the above grid map, return 3.

    + +Notice that: + +
    +
    +11
    +
    +1
    +
    +
    + +and + +
    +
    + 1
    +
    +11
    +
    +
    + +are considered different island shapes, because we do not consider reflection / rotation. + +

    + + + +

    Note: + +The length of each dimension in the given grid does not exceed 50. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0695.Max Area of Island/README_EN.md b/assets/0600-0699/0695.Max Area of Island/README_EN.md new file mode 100644 index 00000000..d7132a9a --- /dev/null +++ b/assets/0600-0699/0695.Max Area of Island/README_EN.md @@ -0,0 +1,188 @@ +# [695. Max Area of Island](https://leetcode.com/problems/max-area-of-island) + + + +## Description + +

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    + + + +

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    + + + +

    Example 1:

    + + + +
    +
    +[[0,0,1,0,0,0,0,1,0,0,0,0,0],
    +
    + [0,0,0,0,0,0,0,1,1,1,0,0,0],
    +
    + [0,1,1,0,1,0,0,0,0,0,0,0,0],
    +
    + [0,1,0,0,1,1,0,0,1,0,1,0,0],
    +
    + [0,1,0,0,1,1,0,0,1,1,1,0,0],
    +
    + [0,0,0,0,0,0,0,0,0,0,1,0,0],
    +
    + [0,0,0,0,0,0,0,1,1,1,0,0,0],
    +
    + [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    +
    +
    + +Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. + + + +

    Example 2:

    + + + +
    +
    +[[0,0,0,0,0,0,0,0]]
    + +Given the above grid, return 0. + + + +

    Note: The length of each dimension in the given grid does not exceed 50.

    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + def dfs(grid, i, j, m, n): + if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0: + return 0 + grid[i][j] = 0 + res = 1 + for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + res += dfs(grid, i + x, j + y, m, n) + return res + + m, n = len(grid), len(grid[0]) + res = 0 + for i in range(m): + for j in range(n): + t = dfs(grid, i, j, m, n) + res = max(res, t) + return res +``` + +### **Java** + +```java +class Solution { + private int[][] directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + + public int maxAreaOfIsland(int[][] grid) { + int m = grid.length, n = grid[0].length; + int res = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int t = dfs(grid, i, j, m, n); + res = Math.max(res, t); + } + } + return res; + } + + private int dfs(int[][] grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + int res = 1; + for (int[] direction : directions) { + res += dfs(grid, i + direction[0], j + direction[1], m, n); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function maxAreaOfIsland(grid: number[][]): number { + let m = grid.length, n = grid[0].length; + let res = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + res = Math.max(dfs(grid, i, j), res); + } + } + } + return res; +}; + +function dfs(grid: number[][], i: number, j: number): number { + let m = grid.length, n = grid[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + let res = 1; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + res += dfs(grid, i + dx, j + dy); + } + return res; +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int res = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int t = dfs(grid, i, j, m, n); + res = max(res, t); + } + } + return res; + } +private: + vector> directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + + int dfs(vector>& grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + int res = 1; + for (auto direction : directions) { + res += dfs(grid, i + direction[0], j + direction[1], m, n); + } + return res; + } + +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0696.Count Binary Substrings/README_EN.md b/assets/0600-0699/0696.Count Binary Substrings/README_EN.md new file mode 100644 index 00000000..e67f1dea --- /dev/null +++ b/assets/0600-0699/0696.Count Binary Substrings/README_EN.md @@ -0,0 +1,81 @@ +# [696. Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings) + + + +## Description + +

    Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. + +

    + +

    Substrings that occur multiple times are counted the number of times they occur.

    + + + +

    Example 1:
    + +

    +
    +Input: "00110011"
    +
    +Output: 6
    +
    +Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
    +
    +
    Notice that some of these substrings repeat and are counted the number of times they occur. + +
    Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. + +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: "10101"
    +
    +Output: 4
    +
    +Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
    +
    +
    + +

    + + + +

    Note: + +

  • s.length will be between 1 and 50,000.
  • + +
  • s will only consist of "0" or "1" characters.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0697.Degree of an Array/README_EN.md b/assets/0600-0699/0697.Degree of an Array/README_EN.md new file mode 100644 index 00000000..357223e6 --- /dev/null +++ b/assets/0600-0699/0697.Degree of an Array/README_EN.md @@ -0,0 +1,109 @@ +# [697. Degree of an Array](https://leetcode.com/problems/degree-of-an-array) + + + +## Description + +

    Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

    + +

    Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,2,3,1]
    +Output: 2
    +Explanation: 
    +The input array has a degree of 2 because both elements 1 and 2 appear twice.
    +Of the subarrays that have the same degree:
    +[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
    +The shortest length is 2. So return 2.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,2,3,1,4,2]
    +Output: 6
    +Explanation: 
    +The degree is 3 because the element 2 is repeated 3 times.
    +So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • nums.length will be between 1 and 50,000.
    • +
    • nums[i] will be an integer between 0 and 49,999.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findShortestSubArray(self, nums: List[int]) -> int: + mapper = {} + for i, v in enumerate(nums): + if v in mapper: + arr = mapper[v] + arr[0] += 1 + arr[2] = i + else: + arr = [1, i, i] + mapper[v] = arr + max_degree = min_len = 0 + for arr in mapper.values(): + if max_degree < arr[0]: + max_degree = arr[0] + min_len = arr[2] - arr[1] + 1 + elif max_degree == arr[0]: + min_len = min(min_len, arr[2] - arr[1] + 1) + return min_len +``` + +### **Java** + +```java +class Solution { + public int findShortestSubArray(int[] nums) { + Map mapper = new HashMap<>(); + for (int i = 0, n = nums.length; i < n; ++i) { + if (mapper.containsKey(nums[i])) { + int[] arr = mapper.get(nums[i]); + ++arr[0]; + arr[2] = i; + } else { + int[] arr = new int[]{1, i, i}; + mapper.put(nums[i], arr); + } + } + + int maxDegree = 0, minLen = 0; + for (Map.Entry entry : mapper.entrySet()) { + int[] arr = entry.getValue(); + if (maxDegree < arr[0]) { + maxDegree = arr[0]; + minLen = arr[2] - arr[1] + 1; + } else if (maxDegree == arr[0]) { + minLen = Math.min(minLen, arr[2] - arr[1] + 1); + } + } + return minLen; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md b/assets/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md new file mode 100644 index 00000000..d035dffa --- /dev/null +++ b/assets/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md @@ -0,0 +1,56 @@ +# [698. Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets) + + + +## Description + +

    Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [4,3,2,3,5,2,1], k = 4
    +Output: true
    +Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
    +
    + +

    Example 2:

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

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= nums.length <= 16
    • +
    • 0 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0600-0699/0699.Falling Squares/README_EN.md b/assets/0600-0699/0699.Falling Squares/README_EN.md new file mode 100644 index 00000000..70d9b159 --- /dev/null +++ b/assets/0600-0699/0699.Falling Squares/README_EN.md @@ -0,0 +1,121 @@ +# [699. Falling Squares](https://leetcode.com/problems/falling-squares) + + + +## Description + +

    On an infinite number line (x-axis), we drop given squares in the order they are given.

    + + + +

    The i-th square dropped (positions[i] = (left, side_length)) is a square with the left-most point being positions[i][0] and sidelength positions[i][1].

    + + + +

    The square is dropped with the bottom edge parallel to the number line, and from a higher height than all currently landed squares. We wait for each square to stick before dropping the next.

    + + + +

    The squares are infinitely sticky on their bottom edge, and will remain fixed to any positive length surface they touch (either the number line or another square). Squares dropped adjacent to each other will not stick together prematurely.

    + +  + + + +

    Return a list ans of heights. Each height ans[i] represents the current highest height of any square we have dropped, after dropping squares represented by positions[0], positions[1], ..., positions[i].

    + + + +

    Example 1:

    + + + +
    +
    +Input: [[1, 2], [2, 3], [6, 1]]
    +
    +Output: [2, 5, 5]
    +
    +Explanation:
    +
    +
    + + + +

    After the first drop of positions[0] = [1, 2]: _aa _aa ------- The maximum height of any square is 2.

    + + + +

    After the second drop of positions[1] = [2, 3]: __aaa __aaa __aaa _aa__ _aa__ -------------- The maximum height of any square is 5. The larger square stays on top of the smaller square despite where its center of gravity is, because squares are infinitely sticky on their bottom edge.

    + + + +

    After the third drop of positions[1] = [6, 1]: __aaa __aaa __aaa _aa _aa___a -------------- The maximum height of any square is still 5. Thus, we return an answer of [2, 5, 5].

    + + + +

     

    + +  + + + +

    Example 2:

    + + + +
    +
    +Input: [[100, 100], [200, 100]]
    +
    +Output: [100, 100]
    +
    +Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= positions.length <= 1000.
    • +
    • 1 <= positions[i][0] <= 10^8.
    • +
    • 1 <= positions[i][1] <= 10^6.
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0700.Search in a Binary Search Tree/README_EN.md b/assets/0700-0799/0700.Search in a Binary Search Tree/README_EN.md new file mode 100644 index 00000000..39396f61 --- /dev/null +++ b/assets/0700-0799/0700.Search in a Binary Search Tree/README_EN.md @@ -0,0 +1,59 @@ +# [700. Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree) + + + +## Description + +

    You are given the root of a binary search tree (BST) and an integer val.

    + +

    Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [4,2,7,1,3], val = 2
    +Output: [2,1,3]
    +
    + +

    Example 2:

    + +
    +Input: root = [4,2,7,1,3], val = 5
    +Output: []
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 5000].
    • +
    • 1 <= Node.val <= 107
    • +
    • root is a binary search tree.
    • +
    • 1 <= val <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0700.Search in a Binary Search Tree/images/tree1.jpg b/assets/0700-0799/0700.Search in a Binary Search Tree/images/tree1.jpg new file mode 100644 index 00000000..90bf654d Binary files /dev/null and b/assets/0700-0799/0700.Search in a Binary Search Tree/images/tree1.jpg differ diff --git a/assets/0700-0799/0700.Search in a Binary Search Tree/images/tree2.jpg b/assets/0700-0799/0700.Search in a Binary Search Tree/images/tree2.jpg new file mode 100644 index 00000000..4efd306b Binary files /dev/null and b/assets/0700-0799/0700.Search in a Binary Search Tree/images/tree2.jpg differ diff --git a/assets/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md b/assets/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md new file mode 100644 index 00000000..187bf333 --- /dev/null +++ b/assets/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md @@ -0,0 +1,69 @@ +# [701. Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree) + + + +## Description + +

    You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

    + +

    Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [4,2,7,1,3], val = 5
    +Output: [4,2,7,1,3,5]
    +Explanation: Another accepted tree is:
    +
    +
    + +

    Example 2:

    + +
    +Input: root = [40,20,60,10,30,50,70], val = 25
    +Output: [40,20,60,10,30,50,70,null,null,25]
    +
    + +

    Example 3:

    + +
    +Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
    +Output: [4,2,7,1,3,5]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree will be in the range [0, 104].
    • +
    • -108 <= Node.val <= 108
    • +
    • All the values Node.val are unique.
    • +
    • -108 <= val <= 108
    • +
    • It's guaranteed that val does not exist in the original BST.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0701.Insert into a Binary Search Tree/images/bst.jpg b/assets/0700-0799/0701.Insert into a Binary Search Tree/images/bst.jpg new file mode 100644 index 00000000..a625fc8c Binary files /dev/null and b/assets/0700-0799/0701.Insert into a Binary Search Tree/images/bst.jpg differ diff --git a/assets/0700-0799/0701.Insert into a Binary Search Tree/images/insertbst.jpg b/assets/0700-0799/0701.Insert into a Binary Search Tree/images/insertbst.jpg new file mode 100644 index 00000000..acd8d57f Binary files /dev/null and b/assets/0700-0799/0701.Insert into a Binary Search Tree/images/insertbst.jpg differ diff --git a/assets/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md b/assets/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md new file mode 100644 index 00000000..6d434d82 --- /dev/null +++ b/assets/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md @@ -0,0 +1,160 @@ +# [702. Search in a Sorted Array of Unknown Size](https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size) + + + +## Description + +

    Given an integer array sorted in ascending order, write a function to search target in nums.  If target exists, then return its index, otherwise return -1. However, the array size is unknown to you. You may only access the array using an ArrayReader interface, where ArrayReader.get(k) returns the element of the array at index k (0-indexed).

    + +

    You may assume all integers in the array are less than 10000, and if you access the array out of bounds, ArrayReader.get will return 2147483647.

    + +

     

    + +

    Example 1:

    + +
    +Input: array = [-1,0,3,5,9,12], target = 9
    +Output: 4
    +Explanation: 9 exists in nums and its index is 4
    +
    + +

    Example 2:

    + +
    +Input: array = [-1,0,3,5,9,12], target = 2
    +Output: -1
    +Explanation: 2 does not exist in nums so return -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • You may assume that all elements in the array are unique.
    • +
    • The value of each element in the array will be in the range [-9999, 9999].
    • +
    • The length of the array will be in the range [1, 10^4].
    • +
    + +## Solutions + + + +### **Python3** + +```python +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class ArrayReader: +# def get(self, index: int) -> int: + +class Solution: + def search(self, reader, target): + """ + :type reader: ArrayReader + :type target: int + :rtype: int + """ + left, right = 0, 20000 + while left < right: + mid = (left + right) >> 1 + if reader.get(mid) >= target: + right = mid + else: + left = mid + 1 + return left if reader.get(left) == target else -1 +``` + +### **Java** + +```java +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * public int get(int index) {} + * } + */ + +class Solution { + public int search(ArrayReader reader, int target) { + int left = 0, right = 20000; + while (left < right) { + int mid = left + right >> 1; + if (reader.get(mid) >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return reader.get(left) == target ? left : -1; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * int get(int index); + * }; + */ + +class Solution { +public: + int search(const ArrayReader& reader, int target) { + int left = 0, right = 20000; + while (left < right) { + int mid = left + right >> 1; + if (reader.get(mid) >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return reader.get(left) == target ? left : -1; + } +}; +``` + +### **Go** + +```go +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * type ArrayReader struct { + * } + * + * func (this *ArrayReader) get(index int) int {} + */ + +func search(reader ArrayReader, target int) int { + left, right := 0, 20000 + for left < right { + mid := (left + right) >> 1 + if reader.get(mid) >= target { + right = mid + } else { + left = mid + 1 + } + } + if reader.get(left) == target { + return left + } + return -1 +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md b/assets/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md new file mode 100644 index 00000000..f486e9b2 --- /dev/null +++ b/assets/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md @@ -0,0 +1,111 @@ +# [703. Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream) + + + +## Description + +

    Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

    + +

    Implement KthLargest class:

    + +
      +
    • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
    • +
    • int add(int val) Returns the element representing the kth largest element in the stream.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["KthLargest", "add", "add", "add", "add", "add"]
    +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
    +Output
    +[null, 4, 5, 5, 8, 8]
    +
    +Explanation
    +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
    +kthLargest.add(3);   // return 4
    +kthLargest.add(5);   // return 5
    +kthLargest.add(10);  // return 5
    +kthLargest.add(9);   // return 8
    +kthLargest.add(4);   // return 8
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= 104
    • +
    • 0 <= nums.length <= 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • -104 <= val <= 104
    • +
    • At most 104 calls will be made to add.
    • +
    • It is guaranteed that there will be at least k elements in the array when you search for the kth element.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class KthLargest: + + def __init__(self, k: int, nums: List[int]): + self.q = [] + self.size = k + for num in nums: + self.add(num) + + def add(self, val: int) -> int: + heapq.heappush(self.q, val) + if len(self.q) > self.size: + heapq.heappop(self.q) + return self.q[0] + + +# Your KthLargest object will be instantiated and called as such: +# obj = KthLargest(k, nums) +# param_1 = obj.add(val) +``` + +### **Java** + +```java +class KthLargest { + private PriorityQueue q; + private int size; + + public KthLargest(int k, int[] nums) { + q = new PriorityQueue<>(k); + size = k; + for (int num : nums) { + add(num); + } + } + + public int add(int val) { + q.offer(val); + if (q.size() > size) { + q.poll(); + } + return q.peek(); + } +} + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest obj = new KthLargest(k, nums); + * int param_1 = obj.add(val); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0704.Binary Search/README_EN.md b/assets/0700-0799/0704.Binary Search/README_EN.md new file mode 100644 index 00000000..0e3a62fc --- /dev/null +++ b/assets/0700-0799/0704.Binary Search/README_EN.md @@ -0,0 +1,121 @@ +# [704. Binary Search](https://leetcode.com/problems/binary-search) + + + +## Description + +

    Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [-1,0,3,5,9,12], target = 9
    +Output: 4
    +Explanation: 9 exists in nums and its index is 4
    +
    + +

    Example 2:

    + +
    +Input: nums = [-1,0,3,5,9,12], target = 2
    +Output: -1
    +Explanation: 2 does not exist in nums so return -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -9999 <= nums[i], target <= 9999
    • +
    • All the integers in nums are unique.
    • +
    • nums is sorted in an ascending order.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def search(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + return left if nums[left] == target else -1 +``` + +### **Java** + +```java +class Solution { + public int search(int[] nums, int target) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; + } +}; +``` + +### **Go** + +```go +func search(nums []int, target int) int { + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= target { + right = mid + } else { + left = mid + 1 + } + } + if nums[left] == target { + return left + } + return -1 +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0705.Design HashSet/README_EN.md b/assets/0700-0799/0705.Design HashSet/README_EN.md new file mode 100644 index 00000000..a8927563 --- /dev/null +++ b/assets/0700-0799/0705.Design HashSet/README_EN.md @@ -0,0 +1,126 @@ +# [705. Design HashSet](https://leetcode.com/problems/design-hashset) + + + +## Description + +

    Design a HashSet without using any built-in hash table libraries.

    + +

    Implement MyHashSet class:

    + +
      +
    • void add(key) Inserts the value key into the HashSet.
    • +
    • bool contains(key) Returns whether the value key exists in the HashSet or not.
    • +
    • void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
    +[[], [1], [2], [1], [3], [2], [2], [2], [2]]
    +Output
    +[null, null, null, true, false, null, true, null, false]
    +
    +Explanation
    +MyHashSet myHashSet = new MyHashSet();
    +myHashSet.add(1);      // set = [1]
    +myHashSet.add(2);      // set = [1, 2]
    +myHashSet.contains(1); // return True
    +myHashSet.contains(3); // return False, (not found)
    +myHashSet.add(2);      // set = [1, 2]
    +myHashSet.contains(2); // return True
    +myHashSet.remove(2);   // set = [1]
    +myHashSet.contains(2); // return False, (already removed)
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= key <= 106
    • +
    • At most 104 calls will be made to add, remove, and contains.
    • +
    + +

     

    +Follow up: Could you solve the problem without using the built-in HashSet library? + +## Solutions + + + +### **Python3** + +```python +class MyHashSet: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.data = [False] * 1000001 + + def add(self, key: int) -> None: + self.data[key] = True + + def remove(self, key: int) -> None: + self.data[key] = False + + def contains(self, key: int) -> bool: + """ + Returns true if this set contains the specified element + """ + return self.data[key] + + + +# Your MyHashSet object will be instantiated and called as such: +# obj = MyHashSet() +# obj.add(key) +# obj.remove(key) +# param_3 = obj.contains(key) +``` + +### **Java** + +```java +class MyHashSet { + + private boolean[] data; + + /** Initialize your data structure here. */ + public MyHashSet() { + data = new boolean[1000001]; + } + + public void add(int key) { + data[key] = true; + } + + public void remove(int key) { + data[key] = false; + } + + /** Returns true if this set contains the specified element */ + public boolean contains(int key) { + return data[key]; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0706.Design HashMap/README_EN.md b/assets/0700-0799/0706.Design HashMap/README_EN.md new file mode 100644 index 00000000..dc1ee735 --- /dev/null +++ b/assets/0700-0799/0706.Design HashMap/README_EN.md @@ -0,0 +1,138 @@ +# [706. Design HashMap](https://leetcode.com/problems/design-hashmap) + + + +## Description + +

    Design a HashMap without using any built-in hash table libraries.

    + +

    Implement the MyHashMap class:

    + +
      +
    • MyHashMap() initializes the object with an empty map.
    • +
    • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
    • +
    • int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
    • +
    • void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
    +[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
    +Output
    +[null, null, null, 1, -1, null, 1, null, -1]
    +
    +Explanation
    +MyHashMap myHashMap = new MyHashMap();
    +myHashMap.put(1, 1); // The map is now [[1,1]]
    +myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
    +myHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]
    +myHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
    +myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
    +myHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]
    +myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
    +myHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= key, value <= 106
    • +
    • At most 104 calls will be made to put, get, and remove.
    • +
    + +

     

    +

    Follow up: Please do not use the built-in HashMap library.

    + + +## Solutions + + + +### **Python3** + +```python +class MyHashMap: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.data = [-1] * 1000001 + + def put(self, key: int, value: int) -> None: + """ + value will always be non-negative. + """ + self.data[key] = value + + def get(self, key: int) -> int: + """ + Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key + """ + return self.data[key] + + def remove(self, key: int) -> None: + """ + Removes the mapping of the specified value key if this map contains a mapping for the key + """ + self.data[key] = -1 + + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key) +``` + +### **Java** + +```java +class MyHashMap { + + private int[] data; + + /** Initialize your data structure here. */ + public MyHashMap() { + data = new int[1000001]; + Arrays.fill(data, -1); + } + + /** value will always be non-negative. */ + public void put(int key, int value) { + data[key] = value; + } + + /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ + public int get(int key) { + return data[key]; + } + + /** Removes the mapping of the specified value key if this map contains a mapping for the key */ + public void remove(int key) { + data[key] = -1; + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap obj = new MyHashMap(); + * obj.put(key,value); + * int param_2 = obj.get(key); + * obj.remove(key); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0707.Design Linked List/README_EN.md b/assets/0700-0799/0707.Design Linked List/README_EN.md new file mode 100644 index 00000000..b898a648 --- /dev/null +++ b/assets/0700-0799/0707.Design Linked List/README_EN.md @@ -0,0 +1,234 @@ +# [707. Design Linked List](https://leetcode.com/problems/design-linked-list) + + + +## Description + +

    Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
    +A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
    +If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.

    + +

    Implement the MyLinkedList class:

    + +
      +
    • MyLinkedList() Initializes the MyLinkedList object.
    • +
    • int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
    • +
    • void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
    • +
    • void addAtTail(int val) Append a node of value val as the last element of the linked list.
    • +
    • void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
    • +
    • void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
    +[[], [1], [3], [1, 2], [1], [1], [1]]
    +Output
    +[null, null, null, null, 2, null, 3]
    +
    +Explanation
    +MyLinkedList myLinkedList = new MyLinkedList();
    +myLinkedList.addAtHead(1);
    +myLinkedList.addAtTail(3);
    +myLinkedList.addAtIndex(1, 2);    // linked list becomes 1->2->3
    +myLinkedList.get(1);              // return 2
    +myLinkedList.deleteAtIndex(1);    // now the linked list is 1->3
    +myLinkedList.get(1);              // return 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= index, val <= 1000
    • +
    • Please do not use the built-in LinkedList library.
    • +
    • At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class ListNode: + + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class MyLinkedList: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.dummy = ListNode() + self.count = 0 + + + def get(self, index: int) -> int: + """ + Get the value of the index-th node in the linked list. If the index is invalid, return -1. + """ + if index < 0 or index >= self.count: + return -1 + cur = self.dummy.next + for _ in range(index): + cur = cur.next + return cur.val + + + def addAtHead(self, val: int) -> None: + """ + Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. + """ + self.addAtIndex(0, val) + + + def addAtTail(self, val: int) -> None: + """ + Append a node of value val to the last element of the linked list. + """ + self.addAtIndex(self.count, val) + + + def addAtIndex(self, index: int, val: int) -> None: + """ + Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. + """ + if index > self.count: + return + pre = self.dummy + for _ in range(index): + pre = pre.next + pre.next = ListNode(val, pre.next) + self.count += 1 + + + def deleteAtIndex(self, index: int) -> None: + """ + Delete the index-th node in the linked list, if the index is valid. + """ + if index < 0 or index >= self.count: + return + pre = self.dummy + for _ in range(index): + pre = pre.next + t = pre.next + pre.next = t.next + t.next = None + self.count -= 1 + + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) +``` + +### **Java** + +```java +class MyLinkedList { + + private class ListNode { + int val; + ListNode next; + ListNode(int val) { + this(val, null); + } + ListNode(int val, ListNode next) { + this.val = val; + this.next = next; + } + } + + private ListNode dummy; + private int count; + + /** Initialize your data structure here. */ + public MyLinkedList() { + dummy = new ListNode(0); + count = 0; + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + public int get(int index) { + if (index < 0 || index >= count) { + return -1; + } + ListNode cur = dummy.next; + while (index-- > 0) { + cur = cur.next; + } + return cur.val; + } + + /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ + public void addAtHead(int val) { + addAtIndex(0, val); + } + + /** Append a node of value val to the last element of the linked list. */ + public void addAtTail(int val) { + addAtIndex(count, val); + } + + /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ + public void addAtIndex(int index, int val) { + if (index > count) { + return; + } + ListNode pre = dummy; + while (index-- > 0) { + pre = pre.next; + } + pre.next = new ListNode(val, pre.next); + ++count; + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + public void deleteAtIndex(int index) { + if (index < 0 || index >= count) { + return; + } + ListNode pre = dummy; + while (index-- > 0) { + pre = pre.next; + } + ListNode t = pre.next; + pre.next = t.next; + t.next = null; + --count; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList obj = new MyLinkedList(); + * int param_1 = obj.get(index); + * obj.addAtHead(val); + * obj.addAtTail(val); + * obj.addAtIndex(index,val); + * obj.deleteAtIndex(index); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md b/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md new file mode 100644 index 00000000..76ed7ecd --- /dev/null +++ b/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md @@ -0,0 +1,136 @@ +# [708. Insert into a Sorted Circular Linked List](https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list) + + + +## Description + +

    Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the circular list.

    + +

    If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.

    + +

    If the list is empty (i.e., given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the original given node.

    + +

     

    +

    Example 1:

    +
    +  +
    +Input: head = [3,4,1], insertVal = 2
    +Output: [3,4,1,2]
    +Explanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.
    +
    +
    +
    +
    + +

    Example 2:

    + +
    +Input: head = [], insertVal = 1
    +Output: [1]
    +Explanation: The list is empty (given head is null). We create a new single circular list and return the reference to that single node.
    +
    + +

    Example 3:

    + +
    +Input: head = [1], insertVal = 0
    +Output: [1,0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= Number of Nodes <= 5 * 10^4
    • +
    • -10^6 <= Node.val <= 10^6
    • +
    • -10^6 <= insertVal <= 10^6
    • +
    + +## Solutions + + + +### **Python3** + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, next=None): + self.val = val + self.next = next +""" + +class Solution: + def insert(self, head: 'Node', insertVal: int) -> 'Node': + node = Node(val=insertVal) + if head is None: + node.next = node + return node + pre, cur = head, head.next + while 1: + if pre.val <= insertVal <= cur.val or (pre.val > cur.val and (insertVal >= pre.val or insertVal <= cur.val)): + break + pre, cur = cur, cur.next + if pre == head: + break + pre.next = node + node.next = cur + return head +``` + +### **Java** + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _next) { + val = _val; + next = _next; + } +}; +*/ + +class Solution { + public Node insert(Node head, int insertVal) { + Node node = new Node(insertVal); + if (head == null) { + node.next = node; + return node; + } + Node pre = head, cur = head.next; + while (true) { + if ((pre.val <= insertVal && insertVal <= cur.val) || (pre.val > cur.val && (insertVal >= pre.val || cur.val >= insertVal))) { + break; + } + pre = cur; + cur = cur.next; + if (pre == head) { + break; + } + } + pre.next = node; + node.next = cur; + return head; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/images/example_1_after_65p.jpg b/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/images/example_1_after_65p.jpg new file mode 100644 index 00000000..33d654aa Binary files /dev/null and b/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/images/example_1_after_65p.jpg differ diff --git a/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/images/example_1_before_65p.jpg b/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/images/example_1_before_65p.jpg new file mode 100644 index 00000000..403af331 Binary files /dev/null and b/assets/0700-0799/0708.Insert into a Sorted Circular Linked List/images/example_1_before_65p.jpg differ diff --git a/assets/0700-0799/0709.To Lower Case/README_EN.md b/assets/0700-0799/0709.To Lower Case/README_EN.md new file mode 100644 index 00000000..d14bf1ea --- /dev/null +++ b/assets/0700-0799/0709.To Lower Case/README_EN.md @@ -0,0 +1,111 @@ +# [709. To Lower Case](https://leetcode.com/problems/to-lower-case) + + + +## Description + +

    Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: "Hello"
    +
    +Output: "hello"
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "here"
    +
    +Output: "here"
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "LOVELY"
    +
    +Output: "lovely"
    +
    +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def toLowerCase(self, str: str) -> str: + if not str: + return str + n = len(str) + res = [] + for i in range(n): + c = ord(str[i]) + if c >= 65 and c <= 90: + c += 32 + res.append(chr(c)) + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String toLowerCase(String str) { + int n; + if (str == null || (n = str.length()) == 0) return str; + char[] chars = str.toCharArray(); + for (int i = 0; i < chars.length; ++i) { + boolean isUpper = chars[i] >= 'A' && chars[i] <= 'Z'; + if (isUpper) chars[i] += 32; + } + return new String(chars); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0710.Random Pick with Blacklist/README_EN.md b/assets/0700-0799/0710.Random Pick with Blacklist/README_EN.md new file mode 100644 index 00000000..de882125 --- /dev/null +++ b/assets/0700-0799/0710.Random Pick with Blacklist/README_EN.md @@ -0,0 +1,129 @@ +# [710. Random Pick with Blacklist](https://leetcode.com/problems/random-pick-with-blacklist) + + + +## Description + +

    Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer from [0, N) which is NOT in B.

    + + + +

    Optimize it such that it minimizes the call to system’s Math.random().

    + + + +

    Note:

    + + + +
      +
    1. 1 <= N <= 1000000000
    2. +
    3. 0 <= B.length < min(100000, N)
    4. +
    5. [0, N) does NOT include N. See interval notation.
    6. +
    + + + +

    Example 1:

    + + + +
    +
    +Input: 
    +
    +["Solution","pick","pick","pick"]
    +
    +[[1,[]],[],[],[]]
    +
    +Output: [null,0,0,0]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: 
    +
    +["Solution","pick","pick","pick"]
    +
    +[[2,[]],[],[],[]]
    +
    +Output: [null,1,1,1]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: 
    +
    +["Solution","pick","pick","pick"]
    +
    +[[3,[1]],[],[],[]]
    +
    +Output: [null,0,0,2]
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: 
    +
    +["Solution","pick","pick","pick"]
    +
    +[[4,[2]],[],[],[]]
    +
    +Output: [null,1,3,1]
    +
    +
    + + + +

    Explanation of Input Syntax:

    + + + +

    The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments, N and the blacklist B. pick has no arguments. Arguments are always wrapped with a list, even if there aren't any.

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0711.Number of Distinct Islands II/README_EN.md b/assets/0700-0799/0711.Number of Distinct Islands II/README_EN.md new file mode 100644 index 00000000..35daab62 --- /dev/null +++ b/assets/0700-0799/0711.Number of Distinct Islands II/README_EN.md @@ -0,0 +1,151 @@ +# [711. Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii) + + + +## Description + +

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    + + + +

    Count the number of distinct islands. An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).

    + + + +

    Example 1:
    + +

    +
    +11000
    +
    +10000
    +
    +00001
    +
    +00011
    +
    +
    + +Given the above grid map, return 1. + +

    + +Notice that: + +
    +
    +11
    +
    +1
    +
    +
    + +and + +
    +
    + 1
    +
    +11
    +
    +
    + +are considered same island shapes. Because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes. + +

    + + + +

    Example 2:
    + +

    +
    +11100
    +
    +10001
    +
    +01001
    +
    +01110
    + +Given the above grid map, return 2.
    + +
    + +Here are the two distinct islands: + +
    +
    +111
    +
    +1
    +
    +
    + +and + +
    +
    +1
    +
    +1
    +
    +
    + +
    + +Notice that: + +
    +
    +111
    +
    +1
    +
    +
    + +and + +
    +
    +1
    +
    +111
    +
    +
    + +are considered same island shapes. Because if we flip the first array in the up/down direction, then they have the same shapes. + +

    + + + +

    Note: + +The length of each dimension in the given grid does not exceed 50. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md b/assets/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md new file mode 100644 index 00000000..9d8b9308 --- /dev/null +++ b/assets/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md @@ -0,0 +1,83 @@ +# [712. Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings) + + + +## Description + +

    Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.

    + + + +

    Example 1:
    + +

    +
    +Input: s1 = "sea", s2 = "eat"
    +
    +Output: 231
    +
    +Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
    +
    +Deleting "t" from "eat" adds 116 to the sum.
    +
    +At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: s1 = "delete", s2 = "leet"
    +
    +Output: 403
    +
    +Explanation: Deleting "dee" from "delete" to turn the string into "let",
    +
    +adds 100[d]+101[e]+101[e] to the sum.  Deleting "e" from "leet" adds 101[e] to the sum.
    +
    +At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
    +
    +If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
    +
    +
    + +

    + + + +

    Note: + +

  • 0 < s1.length, s2.length <= 1000.
  • + +
  • All elements of each string will have an ASCII value in [97, 122].
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0713.Subarray Product Less Than K/README_EN.md b/assets/0700-0799/0713.Subarray Product Less Than K/README_EN.md new file mode 100644 index 00000000..78e6b438 --- /dev/null +++ b/assets/0700-0799/0713.Subarray Product Less Than K/README_EN.md @@ -0,0 +1,63 @@ +# [713. Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k) + + + +## Description + +

    Your are given an array of positive integers nums.

    + +

    Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.

    + + + +

    Example 1:
    + +

    +
    +Input: nums = [10, 5, 2, 6], k = 100
    +
    +Output: 8
    +
    +Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
    +
    +Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
    +
    +
    + +

    + + + +

    Note: + +

  • 0 < nums.length <= 50000.
  • + +
  • 0 < nums[i] < 1000.
  • + +
  • 0 <= k < 10^6.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md b/assets/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md new file mode 100644 index 00000000..ca2092b6 --- /dev/null +++ b/assets/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md @@ -0,0 +1,117 @@ +# [714. Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee) + + + +## Description + +

    You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

    + +

    Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

    + +

    Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

    + +

     

    +

    Example 1:

    + +
    +Input: prices = [1,3,2,8,4,9], fee = 2
    +Output: 8
    +Explanation: The maximum profit can be achieved by:
    +- Buying at prices[0] = 1
    +- Selling at prices[3] = 8
    +- Buying at prices[4] = 4
    +- Selling at prices[5] = 9
    +The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
    +
    + +

    Example 2:

    + +
    +Input: prices = [1,3,7,5,10,3], fee = 3
    +Output: 6
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= prices.length <= 5 * 104
    • +
    • 1 <= prices[i] < 5 * 104
    • +
    • 0 <= fee < 5 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + f1, f2 = -prices[0], 0 + for price in prices[1:]: + f1 = max(f1, f2 - price) + f2 = max(f2, f1 + price - fee) + return f2 +``` + +### **Java** + +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, f2 - prices[i]); + f2 = Math.max(f2, f1 + prices[i] - fee); + } + return f2; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.size(); ++i) { + f1 = max(f1, f2 - prices[i]); + f2 = max(f2, f1 + prices[i] - fee); + } + return f2; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int, fee int) int { + f1, f2 := -prices[0], 0 + for i := 1; i < len(prices); i++ { + f1 = max(f1, f2-prices[i]) + f2 = max(f2, f1+prices[i]-fee) + } + return f2 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0715.Range Module/README_EN.md b/assets/0700-0799/0715.Range Module/README_EN.md new file mode 100644 index 00000000..44324858 --- /dev/null +++ b/assets/0700-0799/0715.Range Module/README_EN.md @@ -0,0 +1,83 @@ +# [715. Range Module](https://leetcode.com/problems/range-module) + + + +## Description + +

    A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.

    + + + +

  • addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.
  • + + + +

  • queryRange(int left, int right) Returns true if and only if every real number in the interval [left, right) + + is currently being tracked.
  • + + + +

  • removeRange(int left, int right) Stops tracking every real number currently being tracked in the interval [left, right).
  • + + + +

    Example 1:
    + +

    +
    +addRange(10, 20): null
    +
    +removeRange(14, 16): null
    +
    +queryRange(10, 14): true (Every number in [10, 14) is being tracked)
    +
    +queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)
    +
    +queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)
    +
    +
    + +

    + + + +

    Note: + +

  • A half open interval [left, right) denotes all real numbers left <= x < right.
  • + + + +
  • 0 < left < right < 10^9 in all calls to addRange, queryRange, removeRange.
  • + +
  • The total number of calls to addRange in a single test case is at most 1000.
  • + +
  • The total number of calls to queryRange in a single test case is at most 5000.
  • + +
  • The total number of calls to removeRange in a single test case is at most 1000.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0716.Max Stack/README_EN.md b/assets/0700-0799/0716.Max Stack/README_EN.md new file mode 100644 index 00000000..b4d813e5 --- /dev/null +++ b/assets/0700-0799/0716.Max Stack/README_EN.md @@ -0,0 +1,77 @@ +# [716. Max Stack](https://leetcode.com/problems/max-stack) + + + +## Description + +

    Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.

    + +

    Implement the MaxStack class:

    + +
      +
    • MaxStack() Initializes the stack object.
    • +
    • void push(int x) Pushes element x onto the stack.
    • +
    • int pop() Removes the element on top of the stack and returns it.
    • +
    • int top() Gets the element on the top of the stack without removing it.
    • +
    • int peekMax() Retrieves the maximum element in the stack without removing it.
    • +
    • int popMax() Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"]
    +[[], [5], [1], [5], [], [], [], [], [], []]
    +Output
    +[null, null, null, null, 5, 5, 1, 5, 1, 5]
    +
    +Explanation
    +MaxStack stk = new MaxStack();
    +stk.push(5);   // [5] the top of the stack and the maximum number is 5.
    +stk.push(1);   // [5, 1] the top of the stack is 1, but the maximum is 5.
    +stk.push(5);   // [5, 1, 5] the top of the stack is 5, which is also the maximum, because it is the top most one.
    +stk.top();     // return 5, [5, 1, 5] the stack did not change.
    +stk.popMax();  // return 5, [5, 1] the stack is changed now, and the top is different from the max.
    +stk.top();     // return 1, [5, 1] the stack did not change.
    +stk.peekMax(); // return 5, [5, 1] the stack did not change.
    +stk.pop();     // return 1, [5] the top of the stack and the max element is now 5.
    +stk.top();     // return 5, [5] the stack did not change.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • -107 <= x <= 107
    • +
    • At most 104 calls will be made to push, pop, top, peekMax, and popMax.
    • +
    • There will be at least one element in the stack when pop, top, peekMax, or popMax is called.
    • +
    + +

     

    +Follow up: Could you come up with a solution that supports O(1) for each top call and O(logn) for each other call?  + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md b/assets/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md new file mode 100644 index 00000000..848fe6d3 --- /dev/null +++ b/assets/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md @@ -0,0 +1,85 @@ +# [717. 1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters) + + + +## Description + +

    We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

    + + + +

    Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

    + + + +

    Example 1:
    + +

    +
    +Input: 
    +
    +bits = [1, 0, 0]
    +
    +Output: True
    +
    +Explanation: 
    +
    +The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: 
    +
    +bits = [1, 1, 1, 0]
    +
    +Output: False
    +
    +Explanation: 
    +
    +The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
    +
    +
    + +

    + + + +

    Note: + +

  • 1 <= len(bits) <= 1000.
  • + +
  • bits[i] is always 0 or 1.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md b/assets/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md new file mode 100644 index 00000000..2d454ab6 --- /dev/null +++ b/assets/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md @@ -0,0 +1,56 @@ +# [718. Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray) + + + +## Description + +

    Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
    +Output: 3
    +Explanation: The repeated subarray with maximum length is [3,2,1].
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 1000
    • +
    • 0 <= nums1[i], nums2[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md b/assets/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md new file mode 100644 index 00000000..d250ab9e --- /dev/null +++ b/assets/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md @@ -0,0 +1,77 @@ +# [719. Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance) + + + +## Description + +

    Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.

    + + + +

    Example 1:
    + +

    +
    +Input:
    +
    +nums = [1,3,1]
    +
    +k = 1
    +
    +Output: 0 
    +
    +Explanation:
    +
    +Here are all the pairs:
    +
    +(1,3) -> 2
    +
    +(1,1) -> 0
    +
    +(3,1) -> 2
    +
    +Then the 1st smallest distance pair is (1,1), and its distance is 0.
    +
    +
    + +

    + + + +

    Note:
    + +

      + +
    1. 2 <= len(nums) <= 10000.
    2. + +
    3. 0 <= nums[i] < 1000000.
    4. + +
    5. 1 <= k <= len(nums) * (len(nums) - 1) / 2.
    6. + +
    + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0720.Longest Word in Dictionary/README_EN.md b/assets/0700-0799/0720.Longest Word in Dictionary/README_EN.md new file mode 100644 index 00000000..3e4245d8 --- /dev/null +++ b/assets/0700-0799/0720.Longest Word in Dictionary/README_EN.md @@ -0,0 +1,60 @@ +# [720. Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary) + + + +## Description + +

    Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.

    + +

    If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["w","wo","wor","worl","world"]
    +Output: "world"
    +Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
    +
    + +

    Example 2:

    + +
    +Input: words = ["a","banana","app","appl","ap","apply","apple"]
    +Output: "apple"
    +Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 1000
    • +
    • 1 <= words[i].length <= 30
    • +
    • words[i] consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0721.Accounts Merge/README_EN.md b/assets/0700-0799/0721.Accounts Merge/README_EN.md new file mode 100644 index 00000000..3b815fbc --- /dev/null +++ b/assets/0700-0799/0721.Accounts Merge/README_EN.md @@ -0,0 +1,67 @@ +# [721. Accounts Merge](https://leetcode.com/problems/accounts-merge) + + + +## Description + +

    Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

    + +

    Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

    + +

    After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
    +Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
    +Explanation:
    +The first and third John's are the same person as they have the common email "johnsmith@mail.com".
    +The second John and Mary are different people as none of their email addresses are used by other accounts.
    +We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
    +['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
    +
    + +

    Example 2:

    + +
    +Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
    +Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= accounts.length <= 1000
    • +
    • 2 <= accounts[i].length <= 10
    • +
    • 1 <= accounts[i][j] <= 30
    • +
    • accounts[i][0] consists of English letters.
    • +
    • accounts[i][j] (for j > 0) is a valid email.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0722.Remove Comments/README_EN.md b/assets/0700-0799/0722.Remove Comments/README_EN.md new file mode 100644 index 00000000..1fc67d35 --- /dev/null +++ b/assets/0700-0799/0722.Remove Comments/README_EN.md @@ -0,0 +1,167 @@ +# [722. Remove Comments](https://leetcode.com/problems/remove-comments) + + + +## Description + +

    Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.

    + + + +

    In C++, there are two types of comments, line comments, and block comments.

    + +

    + +The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored. + +

    + +The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */ should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning. + +

    + +The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored. + +

    + +If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. + +

    + +There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.) + +

    + +It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment. + +

    + +Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. + +

    + + + +

    After removing the comments from the source code, return the source code in the same format.

    + + + +

    Example 1:
    + +

    +
    +Input: 
    +
    +source = ["/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"]
    +
    +
    +
    +The line by line code is visualized as below:
    +
    +/*Test program */
    +
    +int main()
    +
    +{ 
    +
    +  // variable declaration 
    +
    +int a, b, c;
    +
    +/* This is a test
    +
    +   multiline  
    +
    +   comment for 
    +
    +   testing */
    +
    +a = b + c;
    +
    +}
    +
    +
    +
    +Output: ["int main()","{ ","  ","int a, b, c;","a = b + c;","}"]
    +
    +
    +
    +The line by line code is visualized as below:
    +
    +int main()
    +
    +{ 
    +
    +  
    +
    +int a, b, c;
    +
    +a = b + c;
    +
    +}
    +
    +
    +
    +Explanation: 
    +
    +The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: 
    +
    +source = ["a/*comment", "line", "more_comment*/b"]
    +
    +Output: ["ab"]
    +
    +Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters.  After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].
    +
    +
    + +

    + + + +

    Note: + +

  • The length of source is in the range [1, 100].
  • + +
  • The length of source[i] is in the range [0, 80].
  • + +
  • Every open block comment is eventually closed.
  • + +
  • There are no single-quote, double-quote, or control characters in the source code.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0723.Candy Crush/README_EN.md b/assets/0700-0799/0723.Candy Crush/README_EN.md new file mode 100644 index 00000000..2802136f --- /dev/null +++ b/assets/0700-0799/0723.Candy Crush/README_EN.md @@ -0,0 +1,98 @@ +# [723. Candy Crush](https://leetcode.com/problems/candy-crush) + + + +## Description + +

    This question is about implementing a basic elimination algorithm for Candy Crush.

    + + + +

    Given a 2D integer array board representing the grid of candy, different positive integers board[i][j] represent different types of candies. A value of board[i][j] = 0 represents that the cell at position (i, j) is empty. The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:

    + + + +
      +
    1. If three or more candies of the same type are adjacent vertically or horizontally, "crush" them all at the same time - these positions become empty.
    2. +
    3. After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. (No new candies will drop outside the top boundary.)
    4. +
    5. After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
    6. +
    7. If there does not exist more candies that can be crushed (ie. the board is stable), then return the current board.
    8. +
    + + + +

    You need to perform the above rules until the board becomes stable, then return the current board.

    + + + +

     

    + + + +

    Example:

    + + + +
    +
    +Input:
    +
    +board = 
    +
    +[[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]]
    +
    +
    +
    +Output:
    +
    +[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
    +
    +
    +
    +Explanation: 
    +
    +
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. The length of board will be in the range [3, 50].
    2. +
    3. The length of board[i] will be in the range [3, 50].
    4. +
    5. Each board[i][j] will initially start as an integer in the range [1, 2000].
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0723.Candy Crush/images/candy_crush_example_2.png b/assets/0700-0799/0723.Candy Crush/images/candy_crush_example_2.png new file mode 100644 index 00000000..a3d29811 Binary files /dev/null and b/assets/0700-0799/0723.Candy Crush/images/candy_crush_example_2.png differ diff --git a/assets/0700-0799/0724.Find Pivot Index/README_EN.md b/assets/0700-0799/0724.Find Pivot Index/README_EN.md new file mode 100644 index 00000000..7ad601a5 --- /dev/null +++ b/assets/0700-0799/0724.Find Pivot Index/README_EN.md @@ -0,0 +1,101 @@ +# [724. Find Pivot Index](https://leetcode.com/problems/find-pivot-index) + + + +## Description + +

    Given an array of integers nums, calculate the pivot index of this array.

    + +

    The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

    + +

    If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

    + +

    Return the leftmost pivot index. If no such index exists, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,7,3,6,5,6]
    +Output: 3
    +Explanation:
    +The pivot index is 3.
    +Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
    +Right sum = nums[4] + nums[5] = 5 + 6 = 11
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3]
    +Output: -1
    +Explanation:
    +There is no index that satisfies the conditions in the problem statement.
    + +

    Example 3:

    + +
    +Input: nums = [2,1,-1]
    +Output: 0
    +Explanation:
    +The pivot index is 0.
    +Left sum = 0 (no elements to the left of index 0)
    +Right sum = nums[1] + nums[2] = 1 + -1 = 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -1000 <= nums[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def pivotIndex(self, nums: List[int]) -> int: + sums = sum(nums) + pre_sum = 0 + for i, v in enumerate(nums): + if (pre_sum << 1) == sums - v: + return i + pre_sum += v + return -1 +``` + +### **Java** + +```java +class Solution { + public int pivotIndex(int[] nums) { + int sums = 0; + for (int e : nums) { + sums += e; + } + int preSum = 0; + for (int i = 0; i < nums.length; ++i) { + // preSum == sums - nums[i] - preSum + if (preSum << 1 == sums - nums[i]) { + return i; + } + preSum += nums[i]; + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0725.Split Linked List in Parts/README_EN.md b/assets/0700-0799/0725.Split Linked List in Parts/README_EN.md new file mode 100644 index 00000000..06dd7b97 --- /dev/null +++ b/assets/0700-0799/0725.Split Linked List in Parts/README_EN.md @@ -0,0 +1,177 @@ +# [725. Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts) + + + +## Description + +

    Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts". + +

    + +The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null. + +

    + +The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later. + +

    + +Return a List of ListNode's representing the linked list parts that are formed. + +

    + + + +Examples + +1->2->3->4, k = 5 // 5 equal parts + +[ [1], + +[2], + +[3], + +[4], + +null ] + + + +

    Example 1:
    + +

    +
    +Input: 
    +
    +root = [1, 2, 3], k = 5
    +
    +Output: [[1],[2],[3],[],[]]
    +
    +Explanation:
    +
    +The input and each element of the output are ListNodes, not arrays.
    +
    +For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
    +
    +The first element output[0] has output[0].val = 1, output[0].next = null.
    +
    +The last element output[4] is null, but it's string representation as a ListNode is [].
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: 
    +
    +root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
    +
    +Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
    +
    +Explanation:
    +
    +The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
    +
    +
    + +

    + + + +

    Note: + +

  • The length of root will be in the range [0, 1000].
  • + +
  • Each value of a node in the input will be an integer in the range [0, 999].
  • + +
  • k will be an integer in the range [1, 50].
  • + +

    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: + n, cur = 0, root + while cur: + n += 1 + cur = cur.next + cur = root + width, remainder = divmod(n, k) + res = [None for _ in range(k)] + for i in range(k): + head = cur + for j in range(width + (i < remainder) - 1): + if cur: + cur = cur.next + if cur: + cur.next, cur = None, cur.next + res[i] = head + return res +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode[] splitListToParts(ListNode root, int k) { + int n = 0; + ListNode cur = root; + while (cur != null) { + ++n; + cur = cur.next; + } + int width = n / k, remainder = n % k; + ListNode[] res = new ListNode[k]; + cur = root; + for (int i = 0; i < k; ++i) { + ListNode head = cur; + for (int j = 0; j < width + ((i < remainder) ? 1 : 0) - 1; ++j) { + if (cur != null) { + cur = cur.next; + } + } + if (cur != null) { + ListNode t = cur.next; + cur.next = null; + cur = t; + } + res[i] = head; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0726.Number of Atoms/README_EN.md b/assets/0700-0799/0726.Number of Atoms/README_EN.md new file mode 100644 index 00000000..ee2e54d3 --- /dev/null +++ b/assets/0700-0799/0726.Number of Atoms/README_EN.md @@ -0,0 +1,85 @@ +# [726. Number of Atoms](https://leetcode.com/problems/number-of-atoms) + + + +## Description + +

    Given a chemical formula (given as a string), return the count of each atom.

    + +

    The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

    + +

    One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.

    + +

    Two formulas concatenated together to produce another formula. For example, H2O2He3Mg4 is also a formula.

    + +

    A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.

    + +

    Given a formula, return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

    + +

     

    + +

     

    +

    Example 1:

    + +
    +Input: formula = "H2O"
    +Output: "H2O"
    +Explanation: The count of elements are {'H': 2, 'O': 1}.
    +
    + +

    Example 2:

    + +
    +Input: formula = "Mg(OH)2"
    +Output: "H2MgO2"
    +Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
    +
    + +

    Example 3:

    + +
    +Input: formula = "K4(ON(SO3)2)2"
    +Output: "K4N2O14S4"
    +Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
    +
    + +

    Example 4:

    + +
    +Input: formula = "Be32"
    +Output: "Be32"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= formula.length <= 1000
    • +
    • formula consists of English letters, digits, '(', and ')'.
    • +
    • formula is always valid.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0727.Minimum Window Subsequence/README_EN.md b/assets/0700-0799/0727.Minimum Window Subsequence/README_EN.md new file mode 100644 index 00000000..2c3a02e5 --- /dev/null +++ b/assets/0700-0799/0727.Minimum Window Subsequence/README_EN.md @@ -0,0 +1,79 @@ +# [727. Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence) + + + +## Description + +

    Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.

    + + + +

    If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.

    + + + +

    Example 1:

    + + + +
    +
    +Input: 
    +
    +S = "abcdebdde", T = "bde"
    +
    +Output: "bcde"
    +
    +Explanation: 
    +
    +"bcde" is the answer because it occurs before "bdde" which has the same length.
    +
    +"deb" is not a smaller window because the elements of T in the window must occur in order.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • All the strings in the input will only contain lowercase letters.
    • +
    • The length of S will be in the range [1, 20000].
    • +
    • The length of T will be in the range [1, 100].
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0728.Self Dividing Numbers/README_EN.md b/assets/0700-0799/0728.Self Dividing Numbers/README_EN.md new file mode 100644 index 00000000..e53f1713 --- /dev/null +++ b/assets/0700-0799/0728.Self Dividing Numbers/README_EN.md @@ -0,0 +1,69 @@ +# [728. Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers) + + + +## Description + +

    + +A self-dividing number is a number that is divisible by every digit it contains. + +

    + +For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. + +

    + +Also, a self-dividing number is not allowed to contain the digit zero. + +

    + +Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. + +

    + +

    Example 1:
    + +

    +
    +Input: 
    +
    +left = 1, right = 22
    +
    +Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
    +
    +
    + +

    + + + +

    Note: + +

  • The boundaries of each input argument are 1 <= left <= right <= 10000.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0729.My Calendar I/README_EN.md b/assets/0700-0799/0729.My Calendar I/README_EN.md new file mode 100644 index 00000000..2da18e3d --- /dev/null +++ b/assets/0700-0799/0729.My Calendar I/README_EN.md @@ -0,0 +1,90 @@ +# [729. My Calendar I](https://leetcode.com/problems/my-calendar-i) + + + +## Description + +

    Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking.

    + + + +

    Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.

    + + + +

    A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)

    + + + +

    For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.

    + +Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) + + + +

    Example 1:

    + + + +
    +
    +MyCalendar();
    +
    +MyCalendar.book(10, 20); // returns true
    +
    +MyCalendar.book(15, 25); // returns false
    +
    +MyCalendar.book(20, 30); // returns true
    +
    +Explanation: 
    +
    +The first event can be booked.  The second can't because time 15 is already booked by another event.
    +
    +The third event can be booked, as the first event takes every time less than 20, but not including 20.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • The number of calls to MyCalendar.book per test case will be at most 1000.
    • +
    • In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md b/assets/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md new file mode 100644 index 00000000..f030f8e8 --- /dev/null +++ b/assets/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md @@ -0,0 +1,99 @@ +# [730. Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences) + + + +## Description + +

    + +Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^9 + 7. + +

    + +A subsequence of a string S is obtained by deleting 0 or more characters from S. + +

    + +A sequence is palindromic if it is equal to the sequence reversed. + +

    + +Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i. + +

    + + + +

    Example 1:
    + +

    +
    +Input: 
    +
    +S = 'bccb'
    +
    +Output: 6
    +
    +Explanation: 
    +
    +The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
    +
    +Note that 'bcb' is counted only once, even though it occurs twice.
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: 
    +
    +S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
    +
    +Output: 104860361
    +
    +Explanation: 
    +
    +There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.
    +
    +
    + +

    + + + +

    Note: + +

  • The length of S will be in the range [1, 1000].
  • + +
  • Each character S[i] will be in the set {'a', 'b', 'c', 'd'}.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0731.My Calendar II/README_EN.md b/assets/0700-0799/0731.My Calendar II/README_EN.md new file mode 100644 index 00000000..9bd84fee --- /dev/null +++ b/assets/0700-0799/0731.My Calendar II/README_EN.md @@ -0,0 +1,100 @@ +# [731. My Calendar II](https://leetcode.com/problems/my-calendar-ii) + + + +## Description + +

    Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking.

    + + + +

    Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.

    + + + +

    A triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)

    + + + +

    For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.

    + +Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) + + + +

    Example 1:

    + + + +
    +
    +MyCalendar();
    +
    +MyCalendar.book(10, 20); // returns true
    +
    +MyCalendar.book(50, 60); // returns true
    +
    +MyCalendar.book(10, 40); // returns true
    +
    +MyCalendar.book(5, 15); // returns false
    +
    +MyCalendar.book(5, 10); // returns true
    +
    +MyCalendar.book(25, 55); // returns true
    +
    +Explanation: 
    +
    +The first two events can be booked.  The third event can be double booked.
    +
    +The fourth event (5, 15) can't be booked, because it would result in a triple booking.
    +
    +The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.
    +
    +The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event;
    +
    +the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • The number of calls to MyCalendar.book per test case will be at most 1000.
    • +
    • In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
    • +
    + + + +

     

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0732.My Calendar III/README_EN.md b/assets/0700-0799/0732.My Calendar III/README_EN.md new file mode 100644 index 00000000..66264588 --- /dev/null +++ b/assets/0700-0799/0732.My Calendar III/README_EN.md @@ -0,0 +1,69 @@ +# [732. My Calendar III](https://leetcode.com/problems/my-calendar-iii) + + + +## Description + +

    A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)

    + +

    You are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events.

    + +

    Implement the MyCalendarThree class:

    + +
      +
    • MyCalendarThree() Initializes the object.
    • +
    • int book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["MyCalendarThree", "book", "book", "book", "book", "book", "book"]
    +[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
    +Output
    +[null, 1, 1, 2, 3, 3, 3]
    +
    +Explanation
    +MyCalendarThree myCalendarThree = new MyCalendarThree();
    +myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
    +myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
    +myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.
    +myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.
    +myCalendarThree.book(5, 10); // return 3
    +myCalendarThree.book(25, 55); // return 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= start < end <= 109
    • +
    • At most 400 calls will be made to book.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0733.Flood Fill/README_EN.md b/assets/0700-0799/0733.Flood Fill/README_EN.md new file mode 100644 index 00000000..82372de9 --- /dev/null +++ b/assets/0700-0799/0733.Flood Fill/README_EN.md @@ -0,0 +1,85 @@ +# [733. Flood Fill](https://leetcode.com/problems/flood-fill) + + + +## Description + +

    + +An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). + +

    + +Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. + +

    + +To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. + +

    + +At the end, return the modified image. + +

    + +

    Example 1:
    + +

    +
    +Input: 
    +
    +image = [[1,1,1],[1,1,0],[1,0,1]]
    +
    +sr = 1, sc = 1, newColor = 2
    +
    +Output: [[2,2,2],[2,2,0],[2,0,1]]
    +
    +Explanation: 
    +
    +From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected 
    +
    +by a path of the same color as the starting pixel are colored with the new color.
    +
    +Note the bottom corner is not colored 2, because it is not 4-directionally connected
    +
    +to the starting pixel.
    +
    +
    + +

    + + + +

    Note: + +

  • The length of image and image[0] will be in the range [1, 50].
  • + +
  • The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
  • + +
  • The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0734.Sentence Similarity/README_EN.md b/assets/0700-0799/0734.Sentence Similarity/README_EN.md new file mode 100644 index 00000000..03f87e65 --- /dev/null +++ b/assets/0700-0799/0734.Sentence Similarity/README_EN.md @@ -0,0 +1,109 @@ +# [734. Sentence Similarity](https://leetcode.com/problems/sentence-similarity) + + + +## Description + +

    We can represent a sentence as an array of words, for example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"].

    + +

    Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two words xi and yi are similar.

    + +

    Return true if sentence1 and sentence2 are similar, or false if they are not similar.

    + +

    Two sentences are similar if:

    + +
      +
    • They have the same length (i.e. the same number of words)
    • +
    • sentence1[i] and sentence2[i] are similar.
    • +
    + +

    Notice that a word is always similar to itself, also notice that the similarity relation is not transitive. For example, if the words a and b are similar and the words b and c are similar, a and c are not necessarily similar.

    + +

     

    +

    Example 1:

    + +
    +Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]
    +Output: true
    +Explanation: The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.
    +
    + +

    Example 2:

    + +
    +Input: sentence1 = ["great"], sentence2 = ["great"], similarPairs = []
    +Output: true
    +Explanation: A word is similar to itself.
    +
    + +

    Example 3:

    + +
    +Input: sentence1 = ["great"], sentence2 = ["doubleplus","good"], similarPairs = [["great","doubleplus"]]
    +Output: false
    +Explanation: As they don't have the same length, we return false.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= sentence1.length, sentence2.length <= 1000
    • +
    • 1 <= sentence1[i].length, sentence2[i].length <= 20
    • +
    • sentence1[i] and sentence2[i] consist of lower-case and upper-case English letters.
    • +
    • 0 <= similarPairs.length <= 1000
    • +
    • similarPairs[i].length == 2
    • +
    • 1 <= xi.length, yi.length <= 20
    • +
    • xi and yi consist of lower-case and upper-case English letters.
    • +
    • All the pairs (xi, yi) are distinct.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def areSentencesSimilar(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool: + if len(sentence1) != len(sentence2): + return False + pairs = {(word1, word2) for word1, word2 in similarPairs} + for i in range(len(sentence1)): + similar = (sentence1[i], sentence2[i]) in pairs or (sentence2[i], sentence1[i]) in pairs or sentence1[i] == sentence2[i] + if not similar: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean areSentencesSimilar(String[] sentence1, String[] sentence2, List> similarPairs) { + if (sentence1.length != sentence2.length) { + return false; + } + Set pairs = new HashSet<>(); + for (List pair : similarPairs) { + pairs.add(pair.get(0) + "." + pair.get(1)); + } + for (int i = 0; i < sentence1.length; ++i) { + boolean similar = pairs.contains(sentence1[i] + "." + sentence2[i]) || pairs.contains(sentence2[i] + "." + sentence1[i]) || sentence1[i].equals(sentence2[i]); + if (!similar) { + return false; + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0735.Asteroid Collision/README_EN.md b/assets/0700-0799/0735.Asteroid Collision/README_EN.md new file mode 100644 index 00000000..75b56871 --- /dev/null +++ b/assets/0700-0799/0735.Asteroid Collision/README_EN.md @@ -0,0 +1,78 @@ +# [735. Asteroid Collision](https://leetcode.com/problems/asteroid-collision) + + + +## Description + +

    We are given an array asteroids of integers representing asteroids in a row.

    + +

    For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

    + +

    Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

    + +

     

    +

    Example 1:

    + +
    +Input: asteroids = [5,10,-5]
    +Output: [5,10]
    +Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
    +
    + +

    Example 2:

    + +
    +Input: asteroids = [8,-8]
    +Output: []
    +Explanation: The 8 and -8 collide exploding each other.
    +
    + +

    Example 3:

    + +
    +Input: asteroids = [10,2,-5]
    +Output: [10]
    +Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
    +
    + +

    Example 4:

    + +
    +Input: asteroids = [-2,-1,1,2]
    +Output: [-2,-1,1,2]
    +Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= asteroids.length <= 104
    • +
    • -1000 <= asteroids[i] <= 1000
    • +
    • asteroids[i] != 0
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0736.Parse Lisp Expression/README_EN.md b/assets/0700-0799/0736.Parse Lisp Expression/README_EN.md new file mode 100644 index 00000000..fbf65d56 --- /dev/null +++ b/assets/0700-0799/0736.Parse Lisp Expression/README_EN.md @@ -0,0 +1,153 @@ +# [736. Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression) + + + +## Description + +

    + +You are given a string expression representing a Lisp-like expression to return the integer value of. + +

    + +The syntax for these expressions is given as follows. + +

    + +

  • An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.
  • + +

    + +

  • (An integer could be positive or negative.)
  • + +

    + +

  • A let-expression takes the form (let v1 e1 v2 e2 ... vn en expr), where let is always the string "let", then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let-expression is the value of the expression expr.
  • + +

    + +

  • An add-expression takes the form (add e1 e2) where add is always the string "add", there are always two expressions e1, e2, and this expression evaluates to the addition of the evaluation of e1 and the evaluation of e2.
  • + +

    + +

  • A mult-expression takes the form (mult e1 e2) where mult is always the string "mult", there are always two expressions e1, e2, and this expression evaluates to the multiplication of the evaluation of e1 and the evaluation of e2.
  • + +

    + +

  • For the purposes of this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally for your convenience, the names "add", "let", or "mult" are protected and will never be used as variable names.
  • + +

    + +

  • Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on scope.
  • + +

    + + + +

    Evaluation Examples:
    + +

    +
    +Input: (add 1 2)
    +
    +Output: 3
    +
    +
    +
    +Input: (mult 3 (add 2 3))
    +
    +Output: 15
    +
    +
    +
    +Input: (let x 2 (mult x 5))
    +
    +Output: 10
    +
    +
    +
    +Input: (let x 2 (mult x (let x 3 y 4 (add x y))))
    +
    +Output: 14
    +
    +Explanation: In the expression (add x y), when checking for the value of the variable x,
    +
    +we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
    +
    +Since x = 3 is found first, the value of x is 3.
    +
    +
    +
    +Input: (let x 3 x 2 x)
    +
    +Output: 2
    +
    +Explanation: Assignment in let statements is processed sequentially.
    +
    +
    +
    +Input: (let x 1 y 2 x (add x y) (add x y))
    +
    +Output: 5
    +
    +Explanation: The first (add x y) evaluates as 3, and is assigned to x.
    +
    +The second (add x y) evaluates as 3+2 = 5.
    +
    +
    +
    +Input: (let x 2 (add (let x 3 (let x 4 x)) x))
    +
    +Output: 6
    +
    +Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context
    +
    +of the final x in the add-expression.  That final x will equal 2.
    +
    +
    +
    +Input: (let a1 3 b2 (add a1 1) b2) 
    +
    +Output 4
    +
    +Explanation: Variable names can contain digits after the first character.
    +
    +
    +
    +
    + + + +

    Note: + +

  • The given string expression is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.
  • + +
  • The length of expression is at most 2000. (It is also non-empty, as that would not be a legal expression.)
  • + +
  • The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0737.Sentence Similarity II/README_EN.md b/assets/0700-0799/0737.Sentence Similarity II/README_EN.md new file mode 100644 index 00000000..67c4334d --- /dev/null +++ b/assets/0700-0799/0737.Sentence Similarity II/README_EN.md @@ -0,0 +1,70 @@ +# [737. Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii) + + + +## Description + +

    Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar.

    + + + +

    For example, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].

    + + + +

    Note that the similarity relation is transitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.

    + + + +

    Similarity is also symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.

    + + + +

    Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs.

    + + + +

    Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].

    + + + +

    Note:

    + + + +
      +
    • The length of words1 and words2 will not exceed 1000.
    • +
    • The length of pairs will not exceed 2000.
    • +
    • The length of each pairs[i] will be 2.
    • +
    • The length of each words[i] and pairs[i][j] will be in the range [1, 20].
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0738.Monotone Increasing Digits/README_EN.md b/assets/0700-0799/0738.Monotone Increasing Digits/README_EN.md new file mode 100644 index 00000000..41b59768 --- /dev/null +++ b/assets/0700-0799/0738.Monotone Increasing Digits/README_EN.md @@ -0,0 +1,89 @@ +# [738. Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits) + + + +## Description + +

    + +Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. + +

    + +(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.) + +

    + + + +

    Example 1:
    + +

    +
    +Input: N = 10
    +
    +Output: 9
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: N = 1234
    +
    +Output: 1234
    +
    +
    + +

    + + + +

    Example 3:
    + +

    +
    +Input: N = 332
    +
    +Output: 299
    +
    +
    + +

    + + + +

    Note: + +N is an integer in the range [0, 10^9]. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0739.Daily Temperatures/README_EN.md b/assets/0700-0799/0739.Daily Temperatures/README_EN.md new file mode 100644 index 00000000..2d78a643 --- /dev/null +++ b/assets/0700-0799/0739.Daily Temperatures/README_EN.md @@ -0,0 +1,116 @@ +# [739. Daily Temperatures](https://leetcode.com/problems/daily-temperatures) + + + +## Description + +

    + +Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. + +

    + +For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. + +

    + + + +

    Note: + +The length of temperatures will be in the range [1, 30000]. + +Each temperature will be an integer in the range [30, 100]. + +

    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def dailyTemperatures(self, T: List[int]) -> List[int]: + n = len(T) + res = [0 for _ in range(n)] + s = [] + for i in range(n): + while s and T[s[-1]] < T[i]: + j = s.pop() + res[j] = i - j + s.append(i) + return res +``` + +### **Java** + +```java +class Solution { + public int[] dailyTemperatures(int[] T) { + int n = T.length; + int[] res = new int[n]; + Deque s = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + while (!s.isEmpty() && T[s.peek()] < T[i]) { + int j = s.pop(); + res[j] = i - j; + } + s.push(i); + } + return res; + } +} +``` + +### **C++** + + + +```cpp +class Solution { +public: + vector dailyTemperatures(vector& T) { + int n = T.size(); + vector ans(n); + stack s; + for(int i = 0; i < n; ++i) { + while(!s.empty() && T[s.top()] < T[i]) { + int pre = s.top(); + s.pop(); + ans[pre] = i - pre; + } + s.push(i); + } + return ans; + } +}; +``` + +### **Go** + +```go +func dailyTemperatures(T []int) []int { + n := len(T) + res := make([]int, n) + stack := make([]int, 0) + for i, v := range T { + for len(stack) != 0 && T[stack[len(stack)-1]] < v { + j := stack[len(stack)-1] + stack = stack[:len(stack)-1] + res[j] = i - j + } + stack = append(stack, i) + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0740.Delete and Earn/README_EN.md b/assets/0700-0799/0740.Delete and Earn/README_EN.md new file mode 100644 index 00000000..481ba2c1 --- /dev/null +++ b/assets/0700-0799/0740.Delete and Earn/README_EN.md @@ -0,0 +1,175 @@ +# [740. Delete and Earn](https://leetcode.com/problems/delete-and-earn) + + + +## Description + +

    Given an array nums of integers, you can perform operations on the array.

    + +

    In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.

    + +

    You start with 0 points. Return the maximum number of points you can earn by applying such operations.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,4,2]
    +Output: 6
    +Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted.
    +Then, delete 2 to earn 2 points.
    +6 total points are earned.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,2,3,3,3,4]
    +Output: 9
    +Explanation: Delete 3 to earn 3 points, deleting both 2's and the 4.
    +Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
    +9 total points are earned.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 2 * 104
    • +
    • 1 <= nums[i] <= 104
    • +
    + + +## Solutions + +Intuition: **If we take a number, we will take all of the copies of it**. + +First calculate the sum of each number as **sums**, and keep updating two dp arrays: **select** and **nonSelect** + +- `sums[i]` represents the sum of elements whose value is i; +- `select[i]` represents the maximum sum of processing from 0 to i if the number i is selected; +- `nonSelect[i]` represents the maximum sum of processing from 0 to i if the number i is not selected; + +Then we have the following conclusions: + +- If i is selected, then i-1 must not be selected; +- If you do not choose i, then i-1 can choose or not, so we choose the larger one; + +```java +select[i] = nonSelect[i-1] + sums[i]; +nonSelect[i] = Math.max(select[i-1], nonSelect[i-1]); +``` + + + +### **Python3** + +```python +class Solution: + def deleteAndEarn(self, nums: List[int]) -> int: + mx = float('-inf') + for num in nums: + mx = max(mx, num) + total = [0] * (mx + 1) + for num in nums: + total[num] += num + first = total[0] + second = max(total[0], total[1]) + for i in range(2, mx + 1): + cur = max(first + total[i], second) + first = second + second = cur + return second +``` + +### **Java** + +```java +class Solution { + public int deleteAndEarn(int[] nums) { + if (nums.length == 0) { + return 0; + } + + int[] sums = new int[10010]; + int[] select = new int[10010]; + int[] nonSelect = new int[10010]; + + int maxV = 0; + for (int x : nums) { + sums[x] += x; + maxV = Math.max(maxV, x); + } + + for (int i = 1; i <= maxV; i++) { + select[i] = nonSelect[i - 1] + sums[i]; + nonSelect[i] = Math.max(select[i - 1], nonSelect[i - 1]); + } + return Math.max(select[maxV], nonSelect[maxV]); + } +} +``` + +### **Go** + +```go +func deleteAndEarn(nums []int) int { + + max := func(x, y int) int { + if x > y { + return x + } + return y + } + + mx := math.MinInt32 + for _, num := range nums { + mx = max(mx, num) + } + total := make([]int, mx+1) + for _, num := range nums { + total[num] += num + } + first := total[0] + second := max(total[0], total[1]) + for i := 2; i <= mx; i++ { + cur := max(first+total[i], second) + first = second + second = cur + } + return second +} +``` + +### **C++** + +```cpp +class Solution { +public: + int deleteAndEarn(vector& nums) { + vector vals(10010); + for (int& num : nums) { + vals[num] += num; + } + return rob(vals); + } + + int rob(vector& nums) { + int a = 0, b = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0741.Cherry Pickup/README_EN.md b/assets/0700-0799/0741.Cherry Pickup/README_EN.md new file mode 100644 index 00000000..1cb8e47d --- /dev/null +++ b/assets/0700-0799/0741.Cherry Pickup/README_EN.md @@ -0,0 +1,78 @@ +# [741. Cherry Pickup](https://leetcode.com/problems/cherry-pickup) + + + +## Description + +

    You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.

    + +
      +
    • 0 means the cell is empty, so you can pass through,
    • +
    • 1 means the cell contains a cherry that you can pick up and pass through, or
    • +
    • -1 means the cell contains a thorn that blocks your way.
    • +
    + +

    Return the maximum number of cherries you can collect by following the rules below:

    + +
      +
    • Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).
    • +
    • After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.
    • +
    • When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.
    • +
    • If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]
    +Output: 5
    +Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).
    +4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
    +Then, the player went left, up, up, left to return home, picking up one more cherry.
    +The total number of cherries picked up is 5, and this is the maximum possible.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 50
    • +
    • grid[i][j] is -1, 0, or 1.
    • +
    • grid[0][0] != -1
    • +
    • grid[n - 1][n - 1] != -1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0741.Cherry Pickup/images/grid.jpg b/assets/0700-0799/0741.Cherry Pickup/images/grid.jpg new file mode 100644 index 00000000..c25970b0 Binary files /dev/null and b/assets/0700-0799/0741.Cherry Pickup/images/grid.jpg differ diff --git a/assets/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md b/assets/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md new file mode 100644 index 00000000..2ed942d0 --- /dev/null +++ b/assets/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md @@ -0,0 +1,147 @@ +# [742. Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree) + + + +## Description + +

    Given a binary tree where every node has a unique value, and a target key k, find the value of the nearest leaf node to target k in the tree. + +

    + +Here, nearest to a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children. + +

    + +In the following examples, the input tree is represented in flattened form row by row. + +The actual root tree given will be a TreeNode object. + +

    + +Example 1: + +

    +
    +Input:
    +
    +root = [1, 3, 2], k = 1
    +
    +Diagram of binary tree:
    +
    +          1
    +
    +         / \
    +
    +        3   2
    +
    +
    +
    +Output: 2 (or 3)
    +
    +
    +
    +Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
    +
    +
    + +

    + +Example 2: + +

    +
    +Input:
    +
    +root = [1], k = 1
    +
    +Output: 1
    +
    +
    +
    +Explanation: The nearest leaf node is the root node itself.
    +
    +
    + +

    + + + +

    + +Example 3: + +

    +
    +Input:
    +
    +root = [1,2,3,4,null,null,null,5,null,6], k = 2
    +
    +Diagram of binary tree:
    +
    +             1
    +
    +            / \
    +
    +           2   3
    +
    +          /
    +
    +         4
    +
    +        /
    +
    +       5
    +
    +      /
    +
    +     6
    +
    +
    +
    +Output: 3
    +
    +Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
    +
    +
    + +

    + + + +

    Note:
    + +

      + +
    1. root represents a binary tree with at least 1 node and at most 1000 nodes.
    2. + +
    3. Every node has a unique node.val in range [1, 1000].
    4. + +
    5. There exists some node in the given binary tree for which node.val == k.
    6. + +
    + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0743.Network Delay Time/README_EN.md b/assets/0700-0799/0743.Network Delay Time/README_EN.md new file mode 100644 index 00000000..85c6f953 --- /dev/null +++ b/assets/0700-0799/0743.Network Delay Time/README_EN.md @@ -0,0 +1,69 @@ +# [743. Network Delay Time](https://leetcode.com/problems/network-delay-time) + + + +## Description + +

    You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.

    + +

    We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: times = [[1,2,1]], n = 2, k = 1
    +Output: 1
    +
    + +

    Example 3:

    + +
    +Input: times = [[1,2,1]], n = 2, k = 2
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= n <= 100
    • +
    • 1 <= times.length <= 6000
    • +
    • times[i].length == 3
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 0 <= wi <= 100
    • +
    • All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0743.Network Delay Time/images/931_example_1.png b/assets/0700-0799/0743.Network Delay Time/images/931_example_1.png new file mode 100644 index 00000000..ced749ca Binary files /dev/null and b/assets/0700-0799/0743.Network Delay Time/images/931_example_1.png differ diff --git a/assets/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md b/assets/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md new file mode 100644 index 00000000..8d222042 --- /dev/null +++ b/assets/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md @@ -0,0 +1,196 @@ +# [744. Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target) + + + +## Description + +

    + +Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. + +

    + +Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'. + +

    + +

    Examples:
    + +

    +
    +Input:
    +
    +letters = ["c", "f", "j"]
    +
    +target = "a"
    +
    +Output: "c"
    +
    +
    +
    +Input:
    +
    +letters = ["c", "f", "j"]
    +
    +target = "c"
    +
    +Output: "f"
    +
    +
    +
    +Input:
    +
    +letters = ["c", "f", "j"]
    +
    +target = "d"
    +
    +Output: "f"
    +
    +
    +
    +Input:
    +
    +letters = ["c", "f", "j"]
    +
    +target = "g"
    +
    +Output: "j"
    +
    +
    +
    +Input:
    +
    +letters = ["c", "f", "j"]
    +
    +target = "j"
    +
    +Output: "c"
    +
    +
    +
    +Input:
    +
    +letters = ["c", "f", "j"]
    +
    +target = "k"
    +
    +Output: "c"
    +
    +
    + +

    + +

    Note:
    + +

      + +
    1. letters has a length in range [2, 10000].
    2. + +
    3. letters consists of lowercase letters, and contains at least 2 unique letters.
    4. + +
    5. target is a lowercase letter.
    6. + +
    + +

    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def nextGreatestLetter(self, letters: List[str], target: str) -> str: + left, right = 0, len(letters) + while left < right: + mid = (left + right) >> 1 + if ord(letters[mid]) > ord(target): + right = mid + else: + left = mid + 1 + return letters[left % len(letters)] +``` + +### **Java** + +```java +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + int left = 0, right = letters.length; + while (left < right) { + int mid = (left + right) >> 1; + if (letters[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % letters.length]; + } +} +``` + +### **TypeScript** + +```ts +function nextGreatestLetter(letters: string[], target: string): string { + let left = 0, right = letters.length; + let x = target.charCodeAt(0); + while (left < right) { + let mid = (left + right) >> 1; + if (x < letters[mid].charCodeAt(0)) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % letters.length]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + char nextGreatestLetter(vector& letters, char target) { + int left = 0, right = letters.size(); + while (left < right) { + int mid = left + right >> 1; + if (letters[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % letters.size()]; + } +}; +``` + +### **Go** + +```go +func nextGreatestLetter(letters []byte, target byte) byte { + left, right := 0, len(letters) + for left < right { + mid := (left + right) >> 1 + if letters[mid] > target { + right = mid + } else { + left = mid + 1 + } + } + return letters[left%len(letters)] +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0745.Prefix and Suffix Search/README_EN.md b/assets/0700-0799/0745.Prefix and Suffix Search/README_EN.md new file mode 100644 index 00000000..b7553efc --- /dev/null +++ b/assets/0700-0799/0745.Prefix and Suffix Search/README_EN.md @@ -0,0 +1,65 @@ +# [745. Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search) + + + +## Description + +

    Design a special dictionary which has some words and allows you to search the words in it by a prefix and a suffix.

    + +

    Implement the WordFilter class:

    + +
      +
    • WordFilter(string[] words) Initializes the object with the words in the dictionary.
    • +
    • f(string prefix, string suffix) Returns the index of the word in the dictionary which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["WordFilter", "f"]
    +[[["apple"]], ["a", "e"]]
    +Output
    +[null, 0]
    +
    +Explanation
    +WordFilter wordFilter = new WordFilter(["apple"]);
    +wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = 'e".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 15000
    • +
    • 1 <= words[i].length <= 10
    • +
    • 1 <= prefix.length, suffix.length <= 10
    • +
    • words[i], prefix and suffix consist of lower-case English letters only.
    • +
    • At most 15000 calls will be made to the function f.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md b/assets/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md new file mode 100644 index 00000000..39029ef9 --- /dev/null +++ b/assets/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md @@ -0,0 +1,124 @@ +# [746. Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs) + + + +## Description + +

    You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

    + +

    You can either start from the step with index 0, or the step with index 1.

    + +

    Return the minimum cost to reach the top of the floor.

    + +

     

    +

    Example 1:

    + +
    +Input: cost = [10,15,20]
    +Output: 15
    +Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top.
    +
    + +

    Example 2:

    + +
    +Input: cost = [1,100,1,1,1,100,1,1,100,1]
    +Output: 6
    +Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= cost.length <= 1000
    • +
    • 0 <= cost[i] <= 999
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + a = b = 0 + for i in range(1, len(cost)): + a, b = b, min(a + cost[i - 1], b + cost[i]) + return b +``` + +### **Java** + +```java +class Solution { + public int minCostClimbingStairs(int[] cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.length; ++i) { + int c = Math.min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; + } + return b; + } +} +``` + +### **TypeScript** + +```ts +function minCostClimbingStairs(cost: number[]): number { + let a = 0, b = 0; + for (let i = 1; i < cost.length; ++i) { + [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + } + return b; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.size(); ++i) { + int c = min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; + } + return b; + } +}; +``` + +### **Go** + +```go +func minCostClimbingStairs(cost []int) int { + a, b := 0, 0 + for i := 1; i < len(cost); i++ { + a, b = b, min(a+cost[i-1], b+cost[i]) + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md b/assets/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md new file mode 100644 index 00000000..174eb21b --- /dev/null +++ b/assets/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md @@ -0,0 +1,62 @@ +# [747. Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others) + + + +## Description + +

    You are given an integer array nums where the largest integer is unique.

    + +

    Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,6,1,0]
    +Output: 1
    +Explanation: 6 is the largest integer and for every other number in the array x,
    +6 is more than twice as big as x.
    +The index of value 6 is 1, so we return 1.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3,4]
    +Output: -1
    +Explanation: 4 is not at least as big as twice the value of 3, so we return -1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 50
    • +
    • 0 <= nums[i] <= 100
    • +
    • The largest element in nums is unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0748.Shortest Completing Word/README_EN.md b/assets/0700-0799/0748.Shortest Completing Word/README_EN.md new file mode 100644 index 00000000..bf559286 --- /dev/null +++ b/assets/0700-0799/0748.Shortest Completing Word/README_EN.md @@ -0,0 +1,92 @@ +# [748. Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word) + + + +## Description + +

    Given a string licensePlate and an array of strings words, find the shortest completing word in words.

    + +

    A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.

    + +

    For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".

    + +

    Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.

    + +

     

    +

    Example 1:

    + +
    +Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
    +Output: "steps"
    +Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
    +"step" contains 't' and 'p', but only contains 1 's'.
    +"steps" contains 't', 'p', and both 's' characters.
    +"stripe" is missing an 's'.
    +"stepple" is missing an 's'.
    +Since "steps" is the only word containing all the letters, that is the answer.
    +
    + +

    Example 2:

    + +
    +Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]
    +Output: "pest"
    +Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.
    +
    + +

    Example 3:

    + +
    +Input: licensePlate = "Ah71752", words = ["suggest","letter","of","husband","easy","education","drug","prevent","writer","old"]
    +Output: "husband"
    +
    + +

    Example 4:

    + +
    +Input: licensePlate = "OgEu755", words = ["enough","these","play","wide","wonder","box","arrive","money","tax","thus"]
    +Output: "enough"
    +
    + +

    Example 5:

    + +
    +Input: licensePlate = "iMSlpe4", words = ["claim","consumer","student","camera","public","never","wonder","simple","thought","use"]
    +Output: "simple"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= licensePlate.length <= 7
    • +
    • licensePlate contains digits, letters (uppercase or lowercase), or space ' '.
    • +
    • 1 <= words.length <= 1000
    • +
    • 1 <= words[i].length <= 15
    • +
    • words[i] consists of lower case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0749.Contain Virus/README_EN.md b/assets/0700-0799/0749.Contain Virus/README_EN.md new file mode 100644 index 00000000..840700e1 --- /dev/null +++ b/assets/0700-0799/0749.Contain Virus/README_EN.md @@ -0,0 +1,153 @@ +# [749. Contain Virus](https://leetcode.com/problems/contain-virus) + + + +## Description + +

    + +A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. + +

    + +The world is modeled as a 2-D array of cells, where 0 represents uninfected cells, and 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary. + +

    + +Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. + +Resources are limited. Each day, you can install walls around only one region -- the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night. There will never be a tie. + +

    + +Can you save the day? If so, what is the number of walls required? If not, and the world becomes fully infected, return the number of walls used. + +

    + + + +

    Example 1:
    + +

    +
    +Input: grid = 
    +
    +[[0,1,0,0,0,0,0,1],
    +
    + [0,1,0,0,0,0,0,1],
    +
    + [0,0,0,0,0,0,0,1],
    +
    + [0,0,0,0,0,0,0,0]]
    +
    +Output: 10
    +
    +Explanation:
    +
    +There are 2 contaminated regions.
    +
    +On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
    +
    +
    +
    +[[0,1,0,0,0,0,1,1],
    +
    + [0,1,0,0,0,0,1,1],
    +
    + [0,0,0,0,0,0,1,1],
    +
    + [0,0,0,0,0,0,0,1]]
    +
    +
    +
    +On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: grid = 
    +
    +[[1,1,1],
    +
    + [1,0,1],
    +
    + [1,1,1]]
    +
    +Output: 4
    +
    +Explanation: Even though there is only one cell saved, there are 4 walls built.
    +
    +Notice that walls are only built on the shared boundary of two different cells.
    +
    +
    + +

    + + + +

    Example 3:
    + +

    +
    +Input: grid = 
    +
    +[[1,1,1,0,0,0,0,0,0],
    +
    + [1,0,1,0,1,1,1,1,1],
    +
    + [1,1,1,0,0,0,0,0,0]]
    +
    +Output: 13
    +
    +Explanation: The region on the left only builds two new walls.
    +
    +
    + +

    + + + +

    Note:
    + +

      + +
    1. The number of rows and columns of grid will each be in the range [1, 50].
    2. + +
    3. Each grid[i][j] will be either 0 or 1.
    4. + +
    5. Throughout the described process, there is always a contiguous viral region that will infect strictly more uncontaminated squares in the next round.
    6. + +
    + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0750.Number Of Corner Rectangles/README_EN.md b/assets/0700-0799/0750.Number Of Corner Rectangles/README_EN.md new file mode 100644 index 00000000..279565f9 --- /dev/null +++ b/assets/0700-0799/0750.Number Of Corner Rectangles/README_EN.md @@ -0,0 +1,133 @@ +# [750. Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles) + + + +## Description + +

    Given a grid where each entry is only 0 or 1, find the number of corner rectangles.

    + + + +

    A corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: grid = 
    +
    +[[1, 0, 0, 1, 0],
    +
    + [0, 0, 1, 0, 1],
    +
    + [0, 0, 0, 1, 0],
    +
    + [1, 0, 1, 0, 1]]
    +
    +Output: 1
    +
    +Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].
    +
    +
    + + + +

     

    + + + +

    Example 2:

    + + + +
    +
    +Input: grid = 
    +
    +[[1, 1, 1],
    +
    + [1, 1, 1],
    +
    + [1, 1, 1]]
    +
    +Output: 9
    +
    +Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
    +
    +
    + + + +

     

    + + + +

    Example 3:

    + + + +
    +
    +Input: grid = 
    +
    +[[1, 1, 1, 1]]
    +
    +Output: 0
    +
    +Explanation: Rectangles must have four distinct corners.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. The number of rows and columns of grid will each be in the range [1, 200].
    2. +
    3. Each grid[i][j] will be either 0 or 1.
    4. +
    5. The number of 1s in the grid will be at most 6000.
    6. +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0751.IP to CIDR/README_EN.md b/assets/0700-0799/0751.IP to CIDR/README_EN.md new file mode 100644 index 00000000..6f101573 --- /dev/null +++ b/assets/0700-0799/0751.IP to CIDR/README_EN.md @@ -0,0 +1,129 @@ +# [751. IP to CIDR](https://leetcode.com/problems/ip-to-cidr) + + + +## Description + +

    + +Given a start IP address ip and a number of ips we need to cover n, return a representation of the range as a list (of smallest possible length) of CIDR blocks. + +

    + +A CIDR block is a string consisting of an IP, followed by a slash, and then the prefix length. For example: "123.45.67.89/20". That prefix length "20" represents the number of common prefix bits in the specified range. + +

    + + + +

    Example 1:
    + +

    +
    +Input: ip = "255.0.0.7", n = 10
    +
    +Output: ["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"]
    +
    +Explanation:
    +
    +The initial ip address, when converted to binary, looks like this (spaces added for clarity):
    +
    +255.0.0.7 -> 11111111 00000000 00000000 00000111
    +
    +The address "255.0.0.7/32" specifies all addresses with a common prefix of 32 bits to the given address,
    +
    +ie. just this one address.
    +
    +
    +
    +The address "255.0.0.8/29" specifies all addresses with a common prefix of 29 bits to the given address:
    +
    +255.0.0.8 -> 11111111 00000000 00000000 00001000
    +
    +Addresses with common prefix of 29 bits are:
    +
    +11111111 00000000 00000000 00001000
    +
    +11111111 00000000 00000000 00001001
    +
    +11111111 00000000 00000000 00001010
    +
    +11111111 00000000 00000000 00001011
    +
    +11111111 00000000 00000000 00001100
    +
    +11111111 00000000 00000000 00001101
    +
    +11111111 00000000 00000000 00001110
    +
    +11111111 00000000 00000000 00001111
    +
    +
    +
    +The address "255.0.0.16/32" specifies all addresses with a common prefix of 32 bits to the given address,
    +
    +ie. just 11111111 00000000 00000000 00010000.
    +
    +
    +
    +In total, the answer specifies the range of 10 ips starting with the address 255.0.0.7 .
    +
    +
    +
    +There were other representations, such as:
    +
    +["255.0.0.7/32","255.0.0.8/30", "255.0.0.12/30", "255.0.0.16/32"],
    +
    +but our answer was the shortest possible.
    +
    +
    +
    +Also note that a representation beginning with say, "255.0.0.7/30" would be incorrect,
    +
    +because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100 
    +
    +that are outside the specified range.
    +
    +
    + +

    + + + +

    Note:
    + +

      + +
    1. ip will be a valid IPv4 address.
    2. + +
    3. Every implied address ip + x (for x < n) will be a valid IPv4 address.
    4. + +
    5. n will be an integer in the range [1, 1000].
    6. + +
    + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0752.Open the Lock/README_EN.md b/assets/0700-0799/0752.Open the Lock/README_EN.md new file mode 100644 index 00000000..7c5a8cd7 --- /dev/null +++ b/assets/0700-0799/0752.Open the Lock/README_EN.md @@ -0,0 +1,86 @@ +# [752. Open the Lock](https://leetcode.com/problems/open-the-lock) + + + +## Description + +

    You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

    + +

    The lock initially starts at '0000', a string representing the state of the 4 wheels.

    + +

    You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

    + +

    Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

    + +

     

    +

    Example 1:

    + +
    +Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
    +Output: 6
    +Explanation:
    +A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
    +Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
    +because the wheels of the lock become stuck after the display becomes the dead end "0102".
    +
    + +

    Example 2:

    + +
    +Input: deadends = ["8888"], target = "0009"
    +Output: 1
    +Explanation:
    +We can turn the last wheel in reverse to move from "0000" -> "0009".
    +
    + +

    Example 3:

    + +
    +Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
    +Output: -1
    +Explanation:
    +We can't reach the target without getting stuck.
    +
    + +

    Example 4:

    + +
    +Input: deadends = ["0000"], target = "8888"
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= deadends.length <= 500
    • +
    • deadends[i].length == 4
    • +
    • target.length == 4
    • +
    • target will not be in the list deadends.
    • +
    • target and deadends[i] consist of digits only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0753.Cracking the Safe/README_EN.md b/assets/0700-0799/0753.Cracking the Safe/README_EN.md new file mode 100644 index 00000000..8d1fb65d --- /dev/null +++ b/assets/0700-0799/0753.Cracking the Safe/README_EN.md @@ -0,0 +1,68 @@ +# [753. Cracking the Safe](https://leetcode.com/problems/cracking-the-safe) + + + +## Description + +

    There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, ..., k-1.

    + +

    While entering a password, the last n digits entered will automatically be matched against the correct password.

    + +

    For example, assuming the correct password is "345", if you type "012345", the box will open because the correct password matches the suffix of the entered password.

    + +

    Return any password of minimum length that is guaranteed to open the box at some point of entering it.

    + +

     

    + +

    Example 1:

    + +
    +Input: n = 1, k = 2
    +Output: "01"
    +Note: "10" will be accepted too.
    +
    + +

    Example 2:

    + +
    +Input: n = 2, k = 2
    +Output: "00110"
    +Note: "01100", "10011", "11001" will be accepted too.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. n will be in the range [1, 4].
    2. +
    3. k will be in the range [1, 10].
    4. +
    5. k^n will be at most 4096.
    6. +
    + +

     

    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0754.Reach a Number/README_EN.md b/assets/0700-0799/0754.Reach a Number/README_EN.md new file mode 100644 index 00000000..04d5c3e1 --- /dev/null +++ b/assets/0700-0799/0754.Reach a Number/README_EN.md @@ -0,0 +1,93 @@ +# [754. Reach a Number](https://leetcode.com/problems/reach-a-number) + + + +## Description + +

    + +You are standing at position 0 on an infinite number line. There is a goal at position target. + +

    + +On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps. + +

    + +Return the minimum number of steps required to reach the destination. + +

    + + + +

    Example 1:
    + +

    +
    +Input: target = 3
    +
    +Output: 2
    +
    +Explanation:
    +
    +On the first move we step from 0 to 1.
    +
    +On the second step we step from 1 to 3.
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: target = 2
    +
    +Output: 3
    +
    +Explanation:
    +
    +On the first move we step from 0 to 1.
    +
    +On the second move we step  from 1 to -1.
    +
    +On the third move we step from -1 to 2.
    +
    +
    + +

    + + + +

    Note:
    + +

  • target will be a non-zero integer in the range [-10^9, 10^9].
  • + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0755.Pour Water/README_EN.md b/assets/0700-0799/0755.Pour Water/README_EN.md new file mode 100644 index 00000000..245a3d59 --- /dev/null +++ b/assets/0700-0799/0755.Pour Water/README_EN.md @@ -0,0 +1,275 @@ +# [755. Pour Water](https://leetcode.com/problems/pour-water) + + + +## Description + +

    + +We are given an elevation map, heights[i] representing the height of the terrain at that index. The width at each index is 1. After V units of water fall at index K, how much water is at each index? + +

    + +Water first drops at index K and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules: + +

  • If the droplet would eventually fall by moving left, then move left.
  • + +
  • Otherwise, if the droplet would eventually fall by moving right, then move right.
  • + +
  • Otherwise, rise at it's current position.
  • + +Here, "eventually fall" means that the droplet will eventually be at a lower level if it moves in that direction. + +Also, "level" means the height of the terrain plus any water in that column. + +

    + +We can assume there's infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than 1 grid block - each unit of water has to be in exactly one block. + +

    + + + +

    Example 1:
    + +

    +
    +Input: heights = [2,1,1,2,1,2,2], V = 4, K = 3
    +
    +Output: [2,2,2,3,2,2,2]
    +
    +Explanation:
    +
    +#       #
    +
    +#       #
    +
    +##  # ###
    +
    +#########
    +
    + 0123456    <- index
    +
    +
    +
    +The first drop of water lands at index K = 3:
    +
    +
    +
    +#       #
    +
    +#   w   #
    +
    +##  # ###
    +
    +#########
    +
    + 0123456    
    +
    +
    +
    +When moving left or right, the water can only move to the same level or a lower level.
    +
    +(By level, we mean the total height of the terrain plus any water in that column.)
    +
    +Since moving left will eventually make it fall, it moves left.
    +
    +(A droplet "made to fall" means go to a lower height than it was at previously.)
    +
    +
    +
    +#       #
    +
    +#       #
    +
    +## w# ###
    +
    +#########
    +
    + 0123456    
    +
    +
    +
    +Since moving left will not make it fall, it stays in place.  The next droplet falls:
    +
    +
    +
    +#       #
    +
    +#   w   #
    +
    +## w# ###
    +
    +#########
    +
    + 0123456  
    +
    +
    +
    +Since the new droplet moving left will eventually make it fall, it moves left.
    +
    +Notice that the droplet still preferred to move left,
    +
    +even though it could move right (and moving right makes it fall quicker.)
    +
    +
    +
    +#       #
    +
    +#  w    #
    +
    +## w# ###
    +
    +#########
    +
    + 0123456  
    +
    +
    +
    +#       #
    +
    +#       #
    +
    +##ww# ###
    +
    +#########
    +
    + 0123456  
    +
    +
    +
    +After those steps, the third droplet falls.
    +
    +Since moving left would not eventually make it fall, it tries to move right.
    +
    +Since moving right would eventually make it fall, it moves right.
    +
    +
    +
    +#       #
    +
    +#   w   #
    +
    +##ww# ###
    +
    +#########
    +
    + 0123456  
    +
    +
    +
    +#       #
    +
    +#       #
    +
    +##ww#w###
    +
    +#########
    +
    + 0123456  
    +
    +
    +
    +Finally, the fourth droplet falls.
    +
    +Since moving left would not eventually make it fall, it tries to move right.
    +
    +Since moving right would not eventually make it fall, it stays in place:
    +
    +
    +
    +#       #
    +
    +#   w   #
    +
    +##ww#w###
    +
    +#########
    +
    + 0123456  
    +
    +
    +
    +The final answer is [2,2,2,3,2,2,2]:
    +
    +
    +
    +    #    
    +
    + ####### 
    +
    + ####### 
    +
    + 0123456 
    +
    +
    + +

    + + + +

    Example 2:
    + +

    +
    +Input: heights = [1,2,3,4], V = 2, K = 2
    +
    +Output: [2,3,3,4]
    +
    +Explanation:
    +
    +The last droplet settles at index 1, since moving further left would not cause it to eventually fall to a lower height.
    +
    +
    + +

    + + + +

    Example 3:
    + +

    +
    +Input: heights = [3,1,3], V = 5, K = 1
    +
    +Output: [4,4,4]
    +
    +
    + +

    + + + +

    Note:

      + +
    1. heights will have length in [1, 100] and contain integers in [0, 99].
    2. + +
    3. V will be in range [0, 2000].
    4. + +
    5. K will be in range [0, heights.length - 1].
    6. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0756.Pyramid Transition Matrix/README_EN.md b/assets/0700-0799/0756.Pyramid Transition Matrix/README_EN.md new file mode 100644 index 00000000..e6273b7a --- /dev/null +++ b/assets/0700-0799/0756.Pyramid Transition Matrix/README_EN.md @@ -0,0 +1,75 @@ +# [756. Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix) + + + +## Description + +

    We are stacking blocks to form a pyramid. Each block has a color which is a one-letter string.

    + +

    We are allowed to place any color block C on top of two adjacent blocks of colors A and B, if and only if ABC is an allowed triple.

    + +

    We start with a bottom row of bottom, represented as a single string. We also start with a list of allowed triples allowed. Each allowed triple is represented as a string of length 3.

    + +

    Return true if we can build the pyramid all the way to the top, otherwise false.

    + +

     

    +

    Example 1:

    + +
    +Input: bottom = "BCD", allowed = ["BCG","CDE","GEA","FFF"]
    +Output: true
    +Explanation:
    +We can stack the pyramid like this:
    +    A
    +   / \
    +  G   E
    + / \ / \
    +B   C   D
    +
    +We are allowed to place G on top of B and C because BCG is an allowed triple.  Similarly, we can place E on top of C and D, then A on top of G and E.
    +
    + +

    Example 2:

    + +
    +Input: bottom = "AABA", allowed = ["AAA","AAB","ABA","ABB","BAC"]
    +Output: false
    +Explanation:
    +We cannot stack the pyramid to the top.
    +Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= bottom.length <= 8
    • +
    • 0 <= allowed.length <= 200
    • +
    • allowed[i].length == 3
    • +
    • The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md b/assets/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md new file mode 100644 index 00000000..c1bd38b8 --- /dev/null +++ b/assets/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md @@ -0,0 +1,62 @@ +# [757. Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two) + + + +## Description + +

    An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b.

    + +

    Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has a size of at least two.

    + +

     

    +

    Example 1:

    + +
    +Input: intervals = [[1,3],[1,4],[2,5],[3,5]]
    +Output: 3
    +Explanation: Consider the set S = {2, 3, 4}.  For each interval, there are at least 2 elements from S in the interval.
    +Also, there isn't a smaller size set that fulfills the above condition.
    +Thus, we output the size of this set, which is 3.
    +
    + +

    Example 2:

    + +
    +Input: intervals = [[1,2],[2,3],[2,4],[4,5]]
    +Output: 5
    +Explanation: An example of a minimum sized set is {1, 2, 3, 4, 5}.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= intervals.length <= 3000
    • +
    • intervals[i].length == 2
    • +
    • 0 <= ai < bi <= 108
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0758.Bold Words in String/README_EN.md b/assets/0700-0799/0758.Bold Words in String/README_EN.md new file mode 100644 index 00000000..d2ea72bd --- /dev/null +++ b/assets/0700-0799/0758.Bold Words in String/README_EN.md @@ -0,0 +1,47 @@ +# [758. Bold Words in String](https://leetcode.com/problems/bold-words-in-string) + + + +## Description + +

    Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.

    + +

    The returned string should use the least number of tags possible, and of course the tags should form a valid combination.

    + +

    For example, given that words = ["ab", "bc"] and S = "aabcd", we should return "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect.

    + +

    Constraints:

    + +
      +
    • words has length in range [0, 50].
    • +
    • words[i] has length in range [1, 10].
    • +
    • S has length in range [0, 500].
    • +
    • All characters in words[i] and S are lowercase letters.
    • +
    + +

    Note: This question is the same as 616: https://leetcode.com/problems/add-bold-tag-in-string/

    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0759.Employee Free Time/README_EN.md b/assets/0700-0799/0759.Employee Free Time/README_EN.md new file mode 100644 index 00000000..09490611 --- /dev/null +++ b/assets/0700-0799/0759.Employee Free Time/README_EN.md @@ -0,0 +1,71 @@ +# [759. Employee Free Time](https://leetcode.com/problems/employee-free-time) + + + +## Description + +

    We are given a list schedule of employees, which represents the working time for each employee.

    + + + +

    Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.

    + + + +

    Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.

    + + + +

    (Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined).  Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.

    + + +

     

    +

    Example 1:

    + +
    +Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
    +Output: [[3,4]]
    +Explanation: There are a total of three employees, and all common
    +free time intervals would be [-inf, 1], [3, 4], [10, inf].
    +We discard any intervals that contain inf as they aren't finite.
    +
    + +

    Example 2:

    + +
    +Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
    +Output: [[5,6],[7,9]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= schedule.length , schedule[i].length <= 50
    • +
    • 0 <= schedule[i].start < schedule[i].end <= 10^8
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0760.Find Anagram Mappings/README_EN.md b/assets/0700-0799/0760.Find Anagram Mappings/README_EN.md new file mode 100644 index 00000000..d8db8f69 --- /dev/null +++ b/assets/0700-0799/0760.Find Anagram Mappings/README_EN.md @@ -0,0 +1,106 @@ +# [760. Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings) + + + +## Description + +

    + +Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A. + +

    + +We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j. + +

    + +These lists A and B may contain duplicates. If there are multiple answers, output any of them. + +

    + + + +

    + +For example, given + +

    +
    +A = [12, 28, 46, 32, 50]
    +
    +B = [50, 12, 32, 46, 28]
    +
    +
    + +

    + +We should return + +
    +
    +[1, 4, 3, 2, 0]
    +
    +
    + +as P[0] = 1 because the 0th element of A appears at B[1], + +and P[1] = 4 because the 1st element of A appears at B[4], + +and so on. + +

    + + + +

    Note:

      + +
    1. A, B have equal lengths in range [1, 100].
    2. + +
    3. A[i], B[i] are integers in range [0, 10^5].
    4. + +

    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]: + mapper = collections.defaultdict(set) + for i, num in enumerate(nums2): + mapper[num].add(i) + return [mapper[num].pop() for num in nums1] +``` + +### **Java** + +```java +class Solution { + public int[] anagramMappings(int[] nums1, int[] nums2) { + Map> map = new HashMap<>(); + for (int i = 0; i < nums2.length; ++i) { + Set s = map.getOrDefault(nums2[i], new HashSet<>()); + s.add(i); + map.put(nums2[i], s); + } + int[] res = new int[nums1.length]; + for (int i = 0; i < nums1.length; ++i) { + int idx = map.get(nums1[i]).iterator().next(); + res[i] = idx; + map.get(nums1[i]).remove(idx); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0761.Special Binary String/README_EN.md b/assets/0700-0799/0761.Special Binary String/README_EN.md new file mode 100644 index 00000000..0140b458 --- /dev/null +++ b/assets/0700-0799/0761.Special Binary String/README_EN.md @@ -0,0 +1,79 @@ +# [761. Special Binary String](https://leetcode.com/problems/special-binary-string) + + + +## Description + +

    + +Special binary strings are binary strings with the following two properties: + +

    + +

  • The number of 0's is equal to the number of 1's.
  • + +
  • Every prefix of the binary string has at least as many 1's as 0's.
  • + +

    + +Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.) + +

    + +At the end of any number of moves, what is the lexicographically largest resulting string possible? + +

    + + + +

    Example 1:
    + +

    +
    +Input: S = "11011000"
    +
    +Output: "11100100"
    +
    +Explanation:
    +
    +The strings "10" [occuring at S[1]] and "1100" [at S[3]] are swapped.
    +
    +This is the lexicographically largest string possible after some number of swaps.
    +
    +
    + +

    + + + +

    Note:

      + +
    1. S has length at most 50.
    2. + +
    3. S is guaranteed to be a special binary string as defined above.
    4. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md b/assets/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md new file mode 100644 index 00000000..f83f78a0 --- /dev/null +++ b/assets/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md @@ -0,0 +1,93 @@ +# [762. Prime Number of Set Bits in Binary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation) + + + +## Description + +

    + +Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation. + +

    + +(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.) + +

    + + + +

    Example 1:

    +
    +Input: L = 6, R = 10
    +
    +Output: 4
    +
    +Explanation:
    +
    +6 -> 110 (2 set bits, 2 is prime)
    +
    +7 -> 111 (3 set bits, 3 is prime)
    +
    +9 -> 1001 (2 set bits , 2 is prime)
    +
    +10->1010 (2 set bits , 2 is prime)
    +
    +

    + + + +

    Example 2:

    +
    +Input: L = 10, R = 15
    +
    +Output: 5
    +
    +Explanation:
    +
    +10 -> 1010 (2 set bits, 2 is prime)
    +
    +11 -> 1011 (3 set bits, 3 is prime)
    +
    +12 -> 1100 (2 set bits, 2 is prime)
    +
    +13 -> 1101 (3 set bits, 3 is prime)
    +
    +14 -> 1110 (3 set bits, 3 is prime)
    +
    +15 -> 1111 (4 set bits, 4 is not prime)
    +
    +

    + + + +

    Note:

      + +
    1. L, R will be integers L <= R in the range [1, 10^6].
    2. + +
    3. R - L will be at most 10000.
    4. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0763.Partition Labels/README_EN.md b/assets/0700-0799/0763.Partition Labels/README_EN.md new file mode 100644 index 00000000..db8957b1 --- /dev/null +++ b/assets/0700-0799/0763.Partition Labels/README_EN.md @@ -0,0 +1,56 @@ +# [763. Partition Labels](https://leetcode.com/problems/partition-labels) + + + +## Description + +

    A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

    + +

     

    + +

    Example 1:

    + +
    +Input: S = "ababcbacadefegdehijhklij"
    +Output: [9,7,8]
    +Explanation:
    +The partition is "ababcbaca", "defegde", "hijhklij".
    +This is a partition so that each letter appears in at most one part.
    +A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
    +
    + +

     

    + +

    Note:

    + +
      +
    • S will have length in range [1, 500].
    • +
    • S will consist of lowercase English letters ('a' to 'z') only.
    • +
    + +

     

    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0764.Largest Plus Sign/README_EN.md b/assets/0700-0799/0764.Largest Plus Sign/README_EN.md new file mode 100644 index 00000000..ba764cb4 --- /dev/null +++ b/assets/0700-0799/0764.Largest Plus Sign/README_EN.md @@ -0,0 +1,151 @@ +# [764. Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign) + + + +## Description + +

    + +In a 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the given list mines which are 0. What is the largest axis-aligned plus sign of 1s contained in the grid? Return the order of the plus sign. If there is none, return 0. + +

    + +An "axis-aligned plus sign of 1s of order k" has some center grid[x][y] = 1 along with 4 arms of length k-1 going up, down, left, and right, and made of 1s. This is demonstrated in the diagrams below. Note that there could be 0s or 1s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1s. + +

    + + + +

    Examples of Axis-Aligned Plus Signs of Order k:

    +
    +Order 1:
    +
    +000
    +
    +010
    +
    +000
    +
    +
    +
    +Order 2:
    +
    +00000
    +
    +00100
    +
    +01110
    +
    +00100
    +
    +00000
    +
    +
    +
    +Order 3:
    +
    +0000000
    +
    +0001000
    +
    +0001000
    +
    +0111110
    +
    +0001000
    +
    +0001000
    +
    +0000000
    +
    +

    + + + +

    Example 1:

    +
    +Input: N = 5, mines = [[4, 2]]
    +
    +Output: 2
    +
    +Explanation:
    +
    +11111
    +
    +11111
    +
    +11111
    +
    +11111
    +
    +11011
    +
    +In the above grid, the largest plus sign can only be order 2.  One of them is marked in bold.
    +
    +

    + + + +

    Example 2:

    +
    +Input: N = 2, mines = []
    +
    +Output: 1
    +
    +Explanation:
    +
    +There is no plus sign of order 2, but there is of order 1.
    +
    +

    + + + +

    Example 3:

    +
    +Input: N = 1, mines = [[0, 0]]
    +
    +Output: 0
    +
    +Explanation:
    +
    +There is no plus sign, so return 0.
    +
    +

    + + + +

    Note:

      + +
    1. N will be an integer in the range [1, 500].
    2. + +
    3. mines will have length at most 5000.
    4. + +
    5. mines[i] will be length 2 and consist of integers in the range [0, N-1].
    6. + +
    7. (Additionally, programs submitted in C, C++, or C# will be judged with a slightly smaller time limit.)
    8. + +

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0765.Couples Holding Hands/README_EN.md b/assets/0700-0799/0765.Couples Holding Hands/README_EN.md new file mode 100644 index 00000000..0701f480 --- /dev/null +++ b/assets/0700-0799/0765.Couples Holding Hands/README_EN.md @@ -0,0 +1,79 @@ +# [765. Couples Holding Hands](https://leetcode.com/problems/couples-holding-hands) + + + +## Description + +

    + +N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. + +

    + +The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). + +

    + +The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat. + + + +

    Example 1:

    +
    +Input: row = [0, 2, 1, 3]
    +
    +Output: 1
    +
    +Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
    +
    +

    + + + +

    Example 2:

    +
    +Input: row = [3, 2, 0, 1]
    +
    +Output: 0
    +
    +Explanation: All couples are already seated side by side.
    +
    +

    + + + +

    + +Note: + +

      + +
    1. len(row) is even and in the range of [4, 60].
    2. + +
    3. row is guaranteed to be a permutation of 0...len(row)-1.
    4. + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0766.Toeplitz Matrix/README_EN.md b/assets/0700-0799/0766.Toeplitz Matrix/README_EN.md new file mode 100644 index 00000000..babfa18c --- /dev/null +++ b/assets/0700-0799/0766.Toeplitz Matrix/README_EN.md @@ -0,0 +1,92 @@ +# [766. Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix) + + + +## Description + +

    Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.

    + +

    A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
    +Output: true
    +Explanation:
    +In the above grid, the diagonals are:
    +"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
    +In each diagonal all elements are the same, so the answer is True.
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[1,2],[2,2]]
    +Output: false
    +Explanation:
    +The diagonal "[1, 2]" has different elements.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 20
    • +
    • 0 <= matrix[i][j] <= 99
    • +
    + +

     

    +

    Follow up:

    + +
      +
    • What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
    • +
    • What if the matrix is so large that you can only load up a partial row into the memory at once?
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: + m, n = len(matrix), len(matrix[0]) + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] != matrix[i - 1][j - 1]: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean isToeplitzMatrix(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] != matrix[i - 1][j - 1]) { + return false; + } + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0766.Toeplitz Matrix/images/ex1.jpg b/assets/0700-0799/0766.Toeplitz Matrix/images/ex1.jpg new file mode 100644 index 00000000..a373b550 Binary files /dev/null and b/assets/0700-0799/0766.Toeplitz Matrix/images/ex1.jpg differ diff --git a/assets/0700-0799/0766.Toeplitz Matrix/images/ex2.jpg b/assets/0700-0799/0766.Toeplitz Matrix/images/ex2.jpg new file mode 100644 index 00000000..34437746 Binary files /dev/null and b/assets/0700-0799/0766.Toeplitz Matrix/images/ex2.jpg differ diff --git a/assets/0700-0799/0767.Reorganize String/README_EN.md b/assets/0700-0799/0767.Reorganize String/README_EN.md new file mode 100644 index 00000000..75524129 --- /dev/null +++ b/assets/0700-0799/0767.Reorganize String/README_EN.md @@ -0,0 +1,79 @@ +# [767. Reorganize String](https://leetcode.com/problems/reorganize-string) + + + +## Description + +

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

    + + + +

    If possible, output any possible result.  If not possible, return the empty string.

    + + + +

    Example 1:

    + + + +
    +
    +Input: S = "aab"
    +
    +Output: "aba"
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: S = "aaab"
    +
    +Output: ""
    +
    +
    + + + +

    Note:

    + + + +
      +
    • S will consist of lowercase letters and have length in range [1, 500].
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md b/assets/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md new file mode 100644 index 00000000..50c5bdd3 --- /dev/null +++ b/assets/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md @@ -0,0 +1,100 @@ +# [768. Max Chunks To Make Sorted II](https://leetcode.com/problems/max-chunks-to-make-sorted-ii) + + + +## Description + +

    This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.

    + + + +
    + + + +

    Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

    + + + +

    What is the most number of chunks we could have made?

    + + + +

    Example 1:

    + + + +
    +
    +Input: arr = [5,4,3,2,1]
    +
    +Output: 1
    +
    +Explanation:
    +
    +Splitting into two or more chunks will not return the required result.
    +
    +For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [2,1,3,4,4]
    +
    +Output: 4
    +
    +Explanation:
    +
    +We can split into two chunks, such as [2, 1], [3, 4, 4].
    +
    +However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • arr will have length in range [1, 2000].
    • +
    • arr[i] will be an integer in range [0, 10**8].
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md b/assets/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md new file mode 100644 index 00000000..74aa5586 --- /dev/null +++ b/assets/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md @@ -0,0 +1,93 @@ +# [769. Max Chunks To Make Sorted](https://leetcode.com/problems/max-chunks-to-make-sorted) + + + +## Description + +

    Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

    + + + +

    What is the most number of chunks we could have made?

    + + + +

    Example 1:

    + + + +
    +
    +Input: arr = [4,3,2,1,0]
    +
    +Output: 1
    +
    +Explanation:
    +
    +Splitting into two or more chunks will not return the required result.
    +
    +For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [1,0,2,3,4]
    +
    +Output: 4
    +
    +Explanation:
    +
    +We can split into two chunks, such as [1, 0], [2, 3, 4].
    +
    +However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • arr will have length in range [1, 10].
    • +
    • arr[i] will be a permutation of [0, 1, ..., arr.length - 1].
    • + +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0770.Basic Calculator IV/README_EN.md b/assets/0700-0799/0770.Basic Calculator IV/README_EN.md new file mode 100644 index 00000000..674a093d --- /dev/null +++ b/assets/0700-0799/0770.Basic Calculator IV/README_EN.md @@ -0,0 +1,118 @@ +# [770. Basic Calculator IV](https://leetcode.com/problems/basic-calculator-iv) + + + +## Description + +

    Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]

    + + + +
      +
    • An expression alternates chunks and symbols, with a space separating each chunk and symbol.
    • +
    • A chunk is either an expression in parentheses, a variable, or a non-negative integer.
    • +
    • A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".
    • +
    + + + +

    Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, expression = "1 + 2 * 3" has an answer of ["7"].

    + + + +

    The format of the output is as follows:

    + + + +
      +
    • For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like "b*a*c", only "a*b*c".
    • +
    • Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, "a*a*b*c" has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
    • +
    • The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.)  A leading coefficient of 1 is still printed.
    • +
    • An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] 
    • +
    • Terms (including constant terms) with coefficient 0 are not included.  For example, an expression of "0" has an output of [].
    • +
    + + + +

    Examples:

    + + + +
    +
    +Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
    +
    +Output: ["-1*a","14"]
    +
    +
    +
    +Input: expression = "e - 8 + temperature - pressure",
    +
    +evalvars = ["e", "temperature"], evalints = [1, 12]
    +
    +Output: ["-1*pressure","5"]
    +
    +
    +
    +Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
    +
    +Output: ["1*e*e","-64"]
    +
    +
    +
    +Input: expression = "7 - 7", evalvars = [], evalints = []
    +
    +Output: []
    +
    +
    +
    +Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
    +
    +Output: ["5*a*b*c"]
    +
    +
    +
    +Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
    +
    +evalvars = [], evalints = []
    +
    +Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. expression will have length in range [1, 250].
    2. +
    3. evalvars, evalints will have equal lengths in range [0, 100].
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0771.Jewels and Stones/README_EN.md b/assets/0700-0799/0771.Jewels and Stones/README_EN.md new file mode 100644 index 00000000..53c5de5e --- /dev/null +++ b/assets/0700-0799/0771.Jewels and Stones/README_EN.md @@ -0,0 +1,84 @@ +# [771. Jewels and Stones](https://leetcode.com/problems/jewels-and-stones) + + + +## Description + +

    You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

    + +

    Letters are case sensitive, so "a" is considered a different type of stone from "A".

    + +

     

    +

    Example 1:

    +
    Input: jewels = "aA", stones = "aAAbbbb"
    +Output: 3
    +

    Example 2:

    +
    Input: jewels = "z", stones = "ZZ"
    +Output: 0
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= jewels.length, stones.length <= 50
    • +
    • jewels and stones consist of only English letters.
    • +
    • All the characters of jewels are unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + jewel_set = {c for c in jewels} + return sum([1 for c in stones if c in jewel_set]) +``` + +### **Java** + +```java +class Solution { + public int numJewelsInStones(String jewels, String stones) { + Set jewelSet = new HashSet<>(); + for (char ch : jewels.toCharArray()) { + jewelSet.add(ch); + } + int res = 0; + for (char ch : stones.toCharArray()) { + res += (jewelSet.contains(ch) ? 1 : 0); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numJewelsInStones(string jewels, string stones) { + unordered_set jewelsSet; + for (int i = 0; i < jewels.length(); ++i) { + jewelsSet.insert(jewels[i]); + } + int res = 0; + for (int i = 0; i < stones.length(); ++i) { + res += jewelsSet.count(stones[i]); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0772.Basic Calculator III/README_EN.md b/assets/0700-0799/0772.Basic Calculator III/README_EN.md new file mode 100644 index 00000000..be6e5500 --- /dev/null +++ b/assets/0700-0799/0772.Basic Calculator III/README_EN.md @@ -0,0 +1,83 @@ +# [772. Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii) + + + +## Description + +

    Implement a basic calculator to evaluate a simple expression string.

    + +

    The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. The integer division should truncate toward zero.

    + +

    You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

    + +

     

    +

    Example 1:

    + +
    +Input: s = "1+1"
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: s = "6-4/2"
    +Output: 4
    +
    + +

    Example 3:

    + +
    +Input: s = "2*(5+5*2)/3+(6/2+8)"
    +Output: 21
    +
    + +

    Example 4:

    + +
    +Input: s = "(2+6*3+5-(3*14/7+2)*5)+3"
    +Output: -12
    +
    + +

    Example 5:

    + +
    +Input: s = "0"
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s <= 104
    • +
    • s consists of digits, '+', '-', '*', '/', '(', and ')'.
    • +
    • s is a valid expression.
    • +
    + +

     

    +Follow up: Could you solve the problem without using built-in library functions? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0773.Sliding Puzzle/README_EN.md b/assets/0700-0799/0773.Sliding Puzzle/README_EN.md new file mode 100644 index 00000000..ee2e0e16 --- /dev/null +++ b/assets/0700-0799/0773.Sliding Puzzle/README_EN.md @@ -0,0 +1,120 @@ +# [773. Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle) + + + +## Description + +

    On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.

    + + + +

    A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.

    + + + +

    The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].

    + + + +

    Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.

    + + + +

    Examples:

    + + + +
    +
    +Input: board = [[1,2,3],[4,0,5]]
    +
    +Output: 1
    +
    +Explanation: Swap the 0 and the 5 in one move.
    +
    +
    + + + +
    +
    +Input: board = [[1,2,3],[5,4,0]]
    +
    +Output: -1
    +
    +Explanation: No number of moves will make the board solved.
    +
    +
    + + + +
    +
    +Input: board = [[4,1,2],[5,0,3]]
    +
    +Output: 5
    +
    +Explanation: 5 is the smallest number of moves that solves the board.
    +
    +An example path:
    +
    +After move 0: [[4,1,2],[5,0,3]]
    +
    +After move 1: [[4,1,2],[0,5,3]]
    +
    +After move 2: [[0,1,2],[4,5,3]]
    +
    +After move 3: [[1,0,2],[4,5,3]]
    +
    +After move 4: [[1,2,0],[4,5,3]]
    +
    +After move 5: [[1,2,3],[4,5,0]]
    +
    +
    + + + +
    +
    +Input: board = [[3,2,4],[1,5,0]]
    +
    +Output: 14
    +
    +
    + + + +

    Note:

    + + + +
      +
    • board will be a 2 x 3 array as described above.
    • +
    • board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5].
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md b/assets/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md new file mode 100644 index 00000000..b10ef87c --- /dev/null +++ b/assets/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md @@ -0,0 +1,56 @@ +# [774. Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station) + + + +## Description + +

    You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k.

    + +

    You should add k new gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an integer position.

    + +

    Let penalty() be the maximum distance between adjacent gas stations after adding the k new stations.

    + +

    Return the smallest possible value of penalty(). Answers within 10-6 of the actual answer will be accepted.

    + +

     

    +

    Example 1:

    +
    Input: stations = [1,2,3,4,5,6,7,8,9,10], k = 9
    +Output: 0.50000
    +

    Example 2:

    +
    Input: stations = [23,24,36,39,46,56,57,65,84,98], k = 1
    +Output: 14.00000
    +
    +

     

    +

    Constraints:

    + +
      +
    • 10 <= stations.length <= 2000
    • +
    • 0 <= stations[i] <= 108
    • +
    • stations is sorted in a strictly increasing order.
    • +
    • 1 <= k <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0775.Global and Local Inversions/README_EN.md b/assets/0700-0799/0775.Global and Local Inversions/README_EN.md new file mode 100644 index 00000000..222e9a17 --- /dev/null +++ b/assets/0700-0799/0775.Global and Local Inversions/README_EN.md @@ -0,0 +1,76 @@ +# [775. Global and Local Inversions](https://leetcode.com/problems/global-and-local-inversions) + + + +## Description + +

    You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].

    + +

    The number of global inversions is the number of the different pairs (i, j) where:

    + +
      +
    • 0 <= i < j < n
    • +
    • nums[i] > nums[j]
    • +
    + +

    The number of local inversions is the number of indices i where:

    + +
      +
    • 0 <= i < n - 1
    • +
    • nums[i] > nums[i + 1]
    • +
    + +

    Return true if the number of global inversions is equal to the number of local inversions.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,0,2]
    +Output: true
    +Explanation: There is 1 global inversion and 1 local inversion.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,0]
    +Output: false
    +Explanation: There are 2 global inversions and 1 local inversion.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 5000
    • +
    • 0 <= nums[i] < n
    • +
    • All the integers of nums are unique.
    • +
    • nums is a permutation of all the numbers in the range [0, n - 1].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0776.Split BST/README_EN.md b/assets/0700-0799/0776.Split BST/README_EN.md new file mode 100644 index 00000000..9d6bbcdb --- /dev/null +++ b/assets/0700-0799/0776.Split BST/README_EN.md @@ -0,0 +1,100 @@ +# [776. Split BST](https://leetcode.com/problems/split-bst) + + + +## Description + +

    Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value.  It's not necessarily the case that the tree contains a node with value V.

    + + + +

    Additionally, most of the structure of the original tree should remain.  Formally, for any child C with parent P in the original tree, if they are both in the same subtree after the split, then node C should still have the parent P.

    + + + +

    You should output the root TreeNode of both subtrees after splitting, in any order.

    + + + +

    Example 1:

    + + + +
    +
    +Input: root = [4,2,6,1,3,5,7], V = 2
    +
    +Output: [[2,1],[4,3,6,null,null,5,7]]
    +
    +Explanation:
    +
    +Note that root, output[0], and output[1] are TreeNode objects, not arrays.
    +
    +
    +
    +The given tree [4,2,6,1,3,5,7] is represented by the following diagram:
    +
    +
    +
    +          4
    +
    +        /   \
    +
    +      2      6
    +
    +     / \    / \
    +
    +    1   3  5   7
    +
    +
    +
    +while the diagrams for the outputs are:
    +
    +
    +
    +          4
    +
    +        /   \
    +
    +      3      6      and    2
    +
    +            / \           /
    +
    +           5   7         1
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. The size of the BST will not exceed 50.
    2. +
    3. The BST is always valid and each node's value is different.
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0777.Swap Adjacent in LR String/README_EN.md b/assets/0700-0799/0777.Swap Adjacent in LR String/README_EN.md new file mode 100644 index 00000000..b6d25655 --- /dev/null +++ b/assets/0700-0799/0777.Swap Adjacent in LR String/README_EN.md @@ -0,0 +1,83 @@ +# [777. Swap Adjacent in LR String](https://leetcode.com/problems/swap-adjacent-in-lr-string) + + + +## Description + +

    In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.

    + +

     

    +

    Example 1:

    + +
    +Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
    +Output: true
    +Explanation: We can transform start to end following these steps:
    +RXXLRXRXL ->
    +XRXLRXRXL ->
    +XRLXRXRXL ->
    +XRLXXRRXL ->
    +XRLXXRRLX
    +
    + +

    Example 2:

    + +
    +Input: start = "X", end = "L"
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: start = "LLR", end = "RRL"
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: start = "XL", end = "LX"
    +Output: true
    +
    + +

    Example 5:

    + +
    +Input: start = "XLLR", end = "LXLX"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= start.length <= 104
    • +
    • start.length == end.length
    • +
    • Both start and end will only consist of characters in 'L', 'R', and 'X'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0778.Swim in Rising Water/README_EN.md b/assets/0700-0799/0778.Swim in Rising Water/README_EN.md new file mode 100644 index 00000000..2bbb2998 --- /dev/null +++ b/assets/0700-0799/0778.Swim in Rising Water/README_EN.md @@ -0,0 +1,159 @@ +# [778. Swim in Rising Water](https://leetcode.com/problems/swim-in-rising-water) + + + +## Description + +

    On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).

    + + + +

    Now rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.

    + + + +

    You start at the top left square (0, 0). What is the least time until you can reach the bottom right square (N-1, N-1)?

    + + + +

    Example 1:

    + + + +
    +
    +Input: [[0,2],[1,3]]
    +
    +Output: 3
    +
    +Explanation:
    +
    +At time 0, you are in grid location (0, 0).
    +
    +You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
    +
    +
    +
    +You cannot reach point (1, 1) until time 3.
    +
    +When the depth of water is 3, we can swim anywhere inside the grid.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
    +
    +Output: 16
    +
    +Explanation:
    +
    + 0  1  2  3  4
    +
    +24 23 22 21  5
    +
    +12 13 14 15 16
    +
    +11 17 18 19 20
    +
    +10  9  8  7  6
    +
    +
    +
    +The final route is marked in bold.
    +
    +We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 2 <= N <= 50.
    2. +
    3. grid[i][j] is a permutation of [0, ..., N*N - 1].
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java +class Solution { + // x、y方向向量 + public static final int[] dx = {0, 0, 1, -1}; + public static final int[] dy = {1, -1, 0, 0}; + /** + * https://blog.csdn.net/fuxuemingzhu/article/details/82926674 + *

    + * 参考这篇文章的第二种解题方法做的 + *

    + * 通过优先级队列找寻局部最优解 最终的得到的结果就是全局最优解 + * + * @param grid + * @return + */ + // 以grid左上角为原点,横向为X轴,纵向为Y轴 + public int swimInWater(int[][] grid) { + // 定义一个优先级队列 按照h从小到大排列 + Queue>> queue = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + queue.add(new Pair<>(grid[0][0], new Pair<>(0, 0))); + // 已经遍历过的点 + Set> visitSet = new HashSet<>(); + visitSet.add(new Pair<>(0, 0)); + + int res = 0; + int length = grid.length; + + while (!queue.isEmpty()) { + Pair> top = queue.poll(); + Integer x = top.getValue().getKey(); + Integer y = top.getValue().getValue(); + res = Math.max(res, top.getKey()); + // 2 <= N <= 50 这个范围内可以直接使用==进行Integer的比较 + if (x == top.getValue().getValue() && y == length - 1) { + break; + } + + for (int i = 0; i < 4; i++) { + int newY = y + dy[i]; + int newX = x + dx[i]; + if (newX < 0 || newY < 0 || newX >= length || newY >= length || visitSet.contains(new Pair<>(newX, newY))) { + // 直接忽略 + continue; + } + queue.add(new Pair<>(grid[newX][newY], new Pair<>(newX, newY))); + visitSet.add(new Pair<>(newX, newY)); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0779.K-th Symbol in Grammar/README_EN.md b/assets/0700-0799/0779.K-th Symbol in Grammar/README_EN.md new file mode 100644 index 00000000..3a0e27db --- /dev/null +++ b/assets/0700-0799/0779.K-th Symbol in Grammar/README_EN.md @@ -0,0 +1,90 @@ +# [779. K-th Symbol in Grammar](https://leetcode.com/problems/k-th-symbol-in-grammar) + + + +## Description + +

    On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

    + + + +

    Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).

    + + + +
    +
    +Examples:
    +
    +Input: N = 1, K = 1
    +
    +Output: 0
    +
    +
    +
    +Input: N = 2, K = 1
    +
    +Output: 0
    +
    +
    +
    +Input: N = 2, K = 2
    +
    +Output: 1
    +
    +
    +
    +Input: N = 4, K = 5
    +
    +Output: 1
    +
    +
    +
    +Explanation:
    +
    +row 1: 0
    +
    +row 2: 01
    +
    +row 3: 0110
    +
    +row 4: 01101001
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. N will be an integer in the range [1, 30].
    2. +
    3. K will be an integer in the range [1, 2^(N-1)].
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0780.Reaching Points/README_EN.md b/assets/0700-0799/0780.Reaching Points/README_EN.md new file mode 100644 index 00000000..8a928008 --- /dev/null +++ b/assets/0700-0799/0780.Reaching Points/README_EN.md @@ -0,0 +1,83 @@ +# [780. Reaching Points](https://leetcode.com/problems/reaching-points) + + + +## Description + +

    A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

    + + + +

    Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.

    + + + +
    +
    +Examples:
    +
    +Input: sx = 1, sy = 1, tx = 3, ty = 5
    +
    +Output: True
    +
    +Explanation:
    +
    +One series of moves that transforms the starting point to the target is:
    +
    +(1, 1) -> (1, 2)
    +
    +(1, 2) -> (3, 2)
    +
    +(3, 2) -> (3, 5)
    +
    +
    +
    +Input: sx = 1, sy = 1, tx = 2, ty = 2
    +
    +Output: False
    +
    +
    +
    +Input: sx = 1, sy = 1, tx = 1, ty = 1
    +
    +Output: True
    +
    +
    +
    +
    + + + +

    Note:

    + + + +
      +
    • sx, sy, tx, ty will all be integers in the range [1, 10^9].
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0781.Rabbits in Forest/README_EN.md b/assets/0700-0799/0781.Rabbits in Forest/README_EN.md new file mode 100644 index 00000000..44b87bc9 --- /dev/null +++ b/assets/0700-0799/0781.Rabbits in Forest/README_EN.md @@ -0,0 +1,100 @@ +# [781. Rabbits in Forest](https://leetcode.com/problems/rabbits-in-forest) + + + +## Description + +

    In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.

    + + + +

    Return the minimum number of rabbits that could be in the forest.

    + + + +
    +
    +Examples:
    +
    +Input: answers = [1, 1, 2]
    +
    +Output: 5
    +
    +Explanation:
    +
    +The two rabbits that answered "1" could both be the same color, say red.
    +
    +The rabbit than answered "2" can't be red or the answers would be inconsistent.
    +
    +Say the rabbit that answered "2" was blue.
    +
    +Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
    +
    +The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
    +
    +
    +
    +Input: answers = [10, 10, 10]
    +
    +Output: 11
    +
    +
    +
    +Input: answers = []
    +
    +Output: 0
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. answers will have length at most 1000.
    2. +
    3. Each answers[i] will be an integer in the range [0, 999].
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numRabbits(self, answers: List[int]) -> int: + counter = collections.Counter(answers) + return sum([math.ceil(v / (k + 1)) * (k + 1) for k, v in counter.items()]) +``` + +### **Java** + +```java +class Solution { + public int numRabbits(int[] answers) { + Map counter = new HashMap<>(); + for (int e : answers) { + counter.put(e, counter.getOrDefault(e, 0) + 1); + } + int res = 0; + for (Map.Entry entry : counter.entrySet()) { + int answer = entry.getKey(), count = entry.getValue(); + res += (int) Math.ceil(count / ((answer + 1) * 1.0)) * (answer + 1); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0782.Transform to Chessboard/README_EN.md b/assets/0700-0799/0782.Transform to Chessboard/README_EN.md new file mode 100644 index 00000000..28e44be7 --- /dev/null +++ b/assets/0700-0799/0782.Transform to Chessboard/README_EN.md @@ -0,0 +1,110 @@ +# [782. Transform to Chessboard](https://leetcode.com/problems/transform-to-chessboard) + + + +## Description + +

    An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.

    + + + +

    What is the minimum number of moves to transform the board into a "chessboard" - a board where no 0s and no 1s are 4-directionally adjacent? If the task is impossible, return -1.

    + + + +
    +
    +Examples:
    +
    +Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
    +
    +Output: 2
    +
    +Explanation:
    +
    +One potential sequence of moves is shown below, from left to right:
    +
    +
    +
    +0110     1010     1010
    +
    +0110 --> 1010 --> 0101
    +
    +1001     0101     1010
    +
    +1001     0101     0101
    +
    +
    +
    +The first move swaps the first and second column.
    +
    +The second move swaps the second and third row.
    +
    +
    +
    +
    +
    +Input: board = [[0, 1], [1, 0]]
    +
    +Output: 0
    +
    +Explanation:
    +
    +Also note that the board with 0 in the top left corner,
    +
    +01
    +
    +10
    +
    +
    +
    +is also a valid chessboard.
    +
    +
    +
    +Input: board = [[1, 0], [1, 0]]
    +
    +Output: -1
    +
    +Explanation:
    +
    +No matter what sequence of moves you make, you cannot end with a valid chessboard.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • board will have the same number of rows and columns, a number in the range [2, 30].
    • +
    • board[i][j] will be only 0s or 1s.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md b/assets/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md new file mode 100644 index 00000000..533185be --- /dev/null +++ b/assets/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md @@ -0,0 +1,109 @@ +# [783. Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes) + + + +## Description + +

    Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

    + +

    Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/

    + +

     

    +

    Example 1:

    + +
    +Input: root = [4,2,6,1,3]
    +Output: 1
    +
    + +

    Example 2:

    + +
    +Input: root = [1,0,48,null,null,12,49]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [2, 100].
    • +
    • 0 <= Node.val <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDiffInBST(self, root: TreeNode) -> int: + def inorder(root): + if not root: + return + inorder(root.left) + if self.pre is not None: + self.min_diff = min(self.min_diff, abs(root.val - self.pre)) + self.pre = root.val + inorder(root.right) + + self.pre = None + self.min_diff = 10 ** 5 + inorder(root) + return self.min_diff +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private int minDiff = Integer.MAX_VALUE; + private Integer pre; + + public int minDiffInBST(TreeNode root) { + inorder(root); + return minDiff; + } + + private void inorder(TreeNode root) { + if (root == null) return; + inorder(root.left); + if (pre != null) minDiff = Math.min(minDiff, Math.abs(root.val - pre)); + pre = root.val; + inorder(root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0783.Minimum Distance Between BST Nodes/images/bst1.jpg b/assets/0700-0799/0783.Minimum Distance Between BST Nodes/images/bst1.jpg new file mode 100644 index 00000000..7185a35c Binary files /dev/null and b/assets/0700-0799/0783.Minimum Distance Between BST Nodes/images/bst1.jpg differ diff --git a/assets/0700-0799/0783.Minimum Distance Between BST Nodes/images/bst2.jpg b/assets/0700-0799/0783.Minimum Distance Between BST Nodes/images/bst2.jpg new file mode 100644 index 00000000..002e111d Binary files /dev/null and b/assets/0700-0799/0783.Minimum Distance Between BST Nodes/images/bst2.jpg differ diff --git a/assets/0700-0799/0784.Letter Case Permutation/README_EN.md b/assets/0700-0799/0784.Letter Case Permutation/README_EN.md new file mode 100644 index 00000000..9997cafd --- /dev/null +++ b/assets/0700-0799/0784.Letter Case Permutation/README_EN.md @@ -0,0 +1,71 @@ +# [784. Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation) + + + +## Description + +

    Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.

    + +

    Return a list of all possible strings we could create. You can return the output in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: S = "a1b2"
    +Output: ["a1b2","a1B2","A1b2","A1B2"]
    +
    + +

    Example 2:

    + +
    +Input: S = "3z4"
    +Output: ["3z4","3Z4"]
    +
    + +

    Example 3:

    + +
    +Input: S = "12345"
    +Output: ["12345"]
    +
    + +

    Example 4:

    + +
    +Input: S = "0"
    +Output: ["0"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • S will be a string with length between 1 and 12.
    • +
    • S will consist only of letters or digits.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0785.Is Graph Bipartite/README_EN.md b/assets/0700-0799/0785.Is Graph Bipartite/README_EN.md new file mode 100644 index 00000000..e86733a6 --- /dev/null +++ b/assets/0700-0799/0785.Is Graph Bipartite/README_EN.md @@ -0,0 +1,71 @@ +# [785. Is Graph Bipartite](https://leetcode.com/problems/is-graph-bipartite) + + + +## Description + +

    There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:

    + +
      +
    • There are no self-edges (graph[u] does not contain u).
    • +
    • There are no parallel edges (graph[u] does not contain duplicate values).
    • +
    • If v is in graph[u], then u is in graph[v] (the graph is undirected).
    • +
    • The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
    • +
    + +

    A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.

    + +

    Return true if and only if it is bipartite.

    + +

     

    +

    Example 1:

    + +
    +Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
    +Output: false
    +Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
    + +

    Example 2:

    + +
    +Input: graph = [[1,3],[0,2],[1,3],[0,2]]
    +Output: true
    +Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
    + +

     

    +

    Constraints:

    + +
      +
    • graph.length == n
    • +
    • 1 <= n <= 100
    • +
    • 0 <= graph[u].length < n
    • +
    • 0 <= graph[u][i] <= n - 1
    • +
    • graph[u] does not contain u.
    • +
    • All the values of graph[u] are unique.
    • +
    • If graph[u] contains v, then graph[v] contains u.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0785.Is Graph Bipartite/images/bi1.jpg b/assets/0700-0799/0785.Is Graph Bipartite/images/bi1.jpg new file mode 100644 index 00000000..659cb9df Binary files /dev/null and b/assets/0700-0799/0785.Is Graph Bipartite/images/bi1.jpg differ diff --git a/assets/0700-0799/0785.Is Graph Bipartite/images/bi2.jpg b/assets/0700-0799/0785.Is Graph Bipartite/images/bi2.jpg new file mode 100644 index 00000000..3ed55560 Binary files /dev/null and b/assets/0700-0799/0785.Is Graph Bipartite/images/bi2.jpg differ diff --git a/assets/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md b/assets/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md new file mode 100644 index 00000000..e293f873 --- /dev/null +++ b/assets/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md @@ -0,0 +1,66 @@ +# [786. K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction) + + + +## Description + +

    You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.

    + +

    For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].

    + +

    Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,3,5], k = 3
    +Output: [2,5]
    +Explanation: The fractions to be considered in sorted order are:
    +1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
    +The third fraction is 2/5.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,7], k = 1
    +Output: [1,7]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 3 * 104
    • +
    • arr[0] == 1
    • +
    • arr[i] is a prime number for i > 0.
    • +
    • All the numbers of arr are unique and sorted in strictly increasing order.
    • +
    • 1 <= k <= arr.length * (arr.length - 1) / 2
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md b/assets/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md new file mode 100644 index 00000000..7c675e00 --- /dev/null +++ b/assets/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md @@ -0,0 +1,71 @@ +# [787. Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops) + + + +## Description + +

    There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.

    + +

    Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

    + +
    +Example 1:
    +Input: 
    +n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
    +src = 0, dst = 2, k = 1
    +Output: 200
    +Explanation: 
    +The graph looks like this:
    +
    +
    +The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
    + +
    +Example 2:
    +Input: 
    +n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
    +src = 0, dst = 2, k = 0
    +Output: 500
    +Explanation: 
    +The graph looks like this:
    +
    +
    +The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
    • +
    • The size of flights will be in range [0, n * (n - 1) / 2].
    • +
    • The format of each flight will be (src, dst, price).
    • +
    • The price of each flight will be in the range [1, 10000].
    • +
    • k is in the range of [0, n - 1].
    • +
    • There will not be any duplicated flights or self cycles.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0787.Cheapest Flights Within K Stops/images/995.png b/assets/0700-0799/0787.Cheapest Flights Within K Stops/images/995.png new file mode 100644 index 00000000..af24316f Binary files /dev/null and b/assets/0700-0799/0787.Cheapest Flights Within K Stops/images/995.png differ diff --git a/assets/0700-0799/0788.Rotated Digits/README_EN.md b/assets/0700-0799/0788.Rotated Digits/README_EN.md new file mode 100644 index 00000000..e40508de --- /dev/null +++ b/assets/0700-0799/0788.Rotated Digits/README_EN.md @@ -0,0 +1,51 @@ +# [788. Rotated Digits](https://leetcode.com/problems/rotated-digits) + + + +## Description + +

    X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X.  Each digit must be rotated - we cannot choose to leave it alone.

    + +

    A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other (on this case they are rotated in a different direction, in other words 2 or 5 gets mirrored); 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

    + +

    Now given a positive number N, how many numbers X from 1 to N are good?

    + +
    +Example:
    +Input: 10
    +Output: 4
    +Explanation: 
    +There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
    +Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
    +
    + +

    Note:

    + +
      +
    • N  will be in range [1, 10000].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0789.Escape The Ghosts/README_EN.md b/assets/0700-0799/0789.Escape The Ghosts/README_EN.md new file mode 100644 index 00000000..0ff4e150 --- /dev/null +++ b/assets/0700-0799/0789.Escape The Ghosts/README_EN.md @@ -0,0 +1,89 @@ +# [789. Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts) + + + +## Description + +

    You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget], which you are trying to get to. There are several ghosts on the map with their starting positions given as an array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.

    + +

    Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west or stay still. All actions happen simultaneously.

    + +

    You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.

    + +

    Return true if it is possible to escape, otherwise return false.

    + +

     

    +

    Example 1:

    + +
    +Input: ghosts = [[1,0],[0,3]], target = [0,1]
    +Output: true
    +Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.
    +
    + +

    Example 2:

    + +
    +Input: ghosts = [[1,0]], target = [2,0]
    +Output: false
    +Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
    +
    + +

    Example 3:

    + +
    +Input: ghosts = [[2,0]], target = [1,0]
    +Output: false
    +Explanation: The ghost can reach the target at the same time as you.
    +
    + +

    Example 4:

    + +
    +Input: ghosts = [[5,0],[-10,-2],[0,-5],[-2,-2],[-7,1]], target = [7,7]
    +Output: false
    +
    + +

    Example 5:

    + +
    +Input: ghosts = [[-1,0],[0,1],[-1,0],[0,1],[-1,0]], target = [0,0]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= ghosts.length <= 100
    • +
    • ghosts[i].length == 2
    • +
    • -104 <= xi, yi <= 104
    • +
    • There can be multiple ghosts in the same location.
    • +
    • target.length == 2
    • +
    • -104 <= xtarget, ytarget <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0790.Domino and Tromino Tiling/README_EN.md b/assets/0700-0799/0790.Domino and Tromino Tiling/README_EN.md new file mode 100644 index 00000000..82e76a5c --- /dev/null +++ b/assets/0700-0799/0790.Domino and Tromino Tiling/README_EN.md @@ -0,0 +1,89 @@ +# [790. Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling) + + + +## Description + +

    We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated.

    + + + +
    +
    +XX  <- domino
    +
    +
    +
    +XX  <- "L" tromino
    +
    +X
    +
    +
    + + + +

    Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7.

    + + + +

    (In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.)

    + + + + + +
    +
    +Example:
    +
    +Input: 3
    +
    +Output: 5
    +
    +Explanation: 
    +
    +The five different ways are listed below, different letters indicates different tiles:
    +
    +XYZ XXZ XYY XXY XYY
    +
    +XYZ YYZ XZZ XYY XXY
    + + + +

    Note:

    + + + +
      +
    • N  will be in range [1, 1000].
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0791.Custom Sort String/README_EN.md b/assets/0700-0799/0791.Custom Sort String/README_EN.md new file mode 100644 index 00000000..7745d1b0 --- /dev/null +++ b/assets/0700-0799/0791.Custom Sort String/README_EN.md @@ -0,0 +1,79 @@ +# [791. Custom Sort String](https://leetcode.com/problems/custom-sort-string) + + + +## Description + +

    S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

    + + + +

    S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

    + + + +

    Return any permutation of T (as a string) that satisfies this property.

    + + + +
    +
    +Example :
    +
    +Input: 
    +
    +S = "cba"
    +
    +T = "abcd"
    +
    +Output: "cbad"
    +
    +Explanation: 
    +
    +"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". 
    +
    +Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • S has length at most 26, and no character is repeated in S.
    • +
    • T has length at most 200.
    • +
    • S and T consist of lowercase letters only.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0792.Number of Matching Subsequences/README_EN.md b/assets/0700-0799/0792.Number of Matching Subsequences/README_EN.md new file mode 100644 index 00000000..5c183214 --- /dev/null +++ b/assets/0700-0799/0792.Number of Matching Subsequences/README_EN.md @@ -0,0 +1,64 @@ +# [792. Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences) + + + +## Description + +

    Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

    + +

    A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

    + +
      +
    • For example, "ace" is a subsequence of "abcde".
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcde", words = ["a","bb","acd","ace"]
    +Output: 3
    +Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
    +
    + +

    Example 2:

    + +
    +Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 5 * 104
    • +
    • 1 <= words.length <= 5000
    • +
    • 1 <= words[i].length <= 50
    • +
    • s and words[i] consist of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md b/assets/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md new file mode 100644 index 00000000..111dd819 --- /dev/null +++ b/assets/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md @@ -0,0 +1,71 @@ +# [793. Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function) + + + +## Description + +

    Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * ... * x, and by convention, 0! = 1.)

    + + + +

    For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.

    + + + +
    +
    +Example 1:
    +
    +Input: K = 0
    +
    +Output: 5
    +
    +Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.
    +
    +
    +
    +Example 2:
    +
    +Input: K = 5
    +
    +Output: 0
    +
    +Explanation: There is no x such that x! ends in K = 5 zeroes.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • K will be an integer in the range [0, 10^9].
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md b/assets/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md new file mode 100644 index 00000000..e999adbe --- /dev/null +++ b/assets/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md @@ -0,0 +1,103 @@ +# [794. Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state) + + + +## Description + +

    A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

    + + + +

    The board is a 3 x 3 array, and consists of characters " ", "X", and "O".  The " " character represents an empty square.

    + + + +

    Here are the rules of Tic-Tac-Toe:

    + + + +
      +
    • Players take turns placing characters into empty squares (" ").
    • +
    • The first player always places "X" characters, while the second player always places "O" characters.
    • +
    • "X" and "O" characters are always placed into empty squares, never filled ones.
    • +
    • The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
    • +
    • The game also ends if all squares are non-empty.
    • +
    • No more moves can be played if the game is over.
    • +
    + + + +
    +
    +Example 1:
    +
    +Input: board = ["O  ", "   ", "   "]
    +
    +Output: false
    +
    +Explanation: The first player always plays "X".
    +
    +
    +
    +Example 2:
    +
    +Input: board = ["XOX", " X ", "   "]
    +
    +Output: false
    +
    +Explanation: Players take turns making moves.
    +
    +
    +
    +Example 3:
    +
    +Input: board = ["XXX", "   ", "OOO"]
    +
    +Output: false
    +
    +
    +
    +Example 4:
    +
    +Input: board = ["XOX", "O O", "XOX"]
    +
    +Output: true
    +
    +
    + + + +

    Note:

    + + + +
      +
    • board is a length-3 array of strings, where each string board[i] has length 3.
    • +
    • Each board[i][j] is a character in the set {" ", "X", "O"}.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md b/assets/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md new file mode 100644 index 00000000..2fd87d4d --- /dev/null +++ b/assets/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md @@ -0,0 +1,68 @@ +# [795. Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum) + + + +## Description + +

    We are given an array A of positive integers, and two positive integers L and R (L <= R).

    + + + +

    Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.

    + + + +
    +
    +Example :
    +
    +Input: 
    +
    +A = [2, 1, 4, 3]
    +
    +L = 2
    +
    +R = 3
    +
    +Output: 3
    +
    +Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
    +
    +
    + + + +

    Note:

    + + + +
      +
    • L, R  and A[i] will be an integer in the range [0, 10^9].
    • +
    • The length of A will be in the range of [1, 50000].
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0796.Rotate String/README_EN.md b/assets/0700-0799/0796.Rotate String/README_EN.md new file mode 100644 index 00000000..e7cd57d4 --- /dev/null +++ b/assets/0700-0799/0796.Rotate String/README_EN.md @@ -0,0 +1,67 @@ +# [796. Rotate String](https://leetcode.com/problems/rotate-string) + + + +## Description + +

    We are given two strings, A and B.

    + + + +

    A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.

    + + + +
    +
    +Example 1:
    +
    +Input: A = 'abcde', B = 'cdeab'
    +
    +Output: true
    +
    +
    +
    +Example 2:
    +
    +Input: A = 'abcde', B = 'abced'
    +
    +Output: false
    +
    +
    + + + +

    Note:

    + + + +
      +
    • A and B will have length at most 100.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0797.All Paths From Source to Target/README_EN.md b/assets/0700-0799/0797.All Paths From Source to Target/README_EN.md new file mode 100644 index 00000000..c8e48b74 --- /dev/null +++ b/assets/0700-0799/0797.All Paths From Source to Target/README_EN.md @@ -0,0 +1,82 @@ +# [797. All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target) + + + +## Description + +

    Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1, and return them in any order.

    + +

    The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).

    + +

     

    +

    Example 1:

    + +
    +Input: graph = [[1,2],[3],[3],[]]
    +Output: [[0,1,3],[0,2,3]]
    +Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
    +
    + +

    Example 2:

    + +
    +Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
    +Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
    +
    + +

    Example 3:

    + +
    +Input: graph = [[1],[]]
    +Output: [[0,1]]
    +
    + +

    Example 4:

    + +
    +Input: graph = [[1,2,3],[2],[3],[]]
    +Output: [[0,1,2,3],[0,2,3],[0,3]]
    +
    + +

    Example 5:

    + +
    +Input: graph = [[1,3],[2],[3],[]]
    +Output: [[0,1,2,3],[0,3]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == graph.length
    • +
    • 2 <= n <= 15
    • +
    • 0 <= graph[i][j] < n
    • +
    • graph[i][j] != i (i.e., there will be no self-loops).
    • +
    • The input graph is guaranteed to be a DAG.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0797.All Paths From Source to Target/images/all_1.jpg b/assets/0700-0799/0797.All Paths From Source to Target/images/all_1.jpg new file mode 100644 index 00000000..fe05dc1c Binary files /dev/null and b/assets/0700-0799/0797.All Paths From Source to Target/images/all_1.jpg differ diff --git a/assets/0700-0799/0797.All Paths From Source to Target/images/all_2.jpg b/assets/0700-0799/0797.All Paths From Source to Target/images/all_2.jpg new file mode 100644 index 00000000..fa162b9d Binary files /dev/null and b/assets/0700-0799/0797.All Paths From Source to Target/images/all_2.jpg differ diff --git a/assets/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md b/assets/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md new file mode 100644 index 00000000..84867173 --- /dev/null +++ b/assets/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md @@ -0,0 +1,102 @@ +# [798. Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score) + + + +## Description + +

     Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1].  Afterward, any entries that are less than or equal to their index are worth 1 point. 

    + + + +

    For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, it becomes [1, 3, 0, 2, 4].  This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].

    + + + +

    Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive.  If there are multiple answers, return the smallest such index K.

    + + + +
    +
    +Example 1:
    +
    +Input: [2, 3, 1, 4, 0]
    +
    +Output: 3
    +
    +Explanation:  
    +
    +Scores for each K are listed below: 
    +
    +K = 0,  A = [2,3,1,4,0],    score 2
    +
    +K = 1,  A = [3,1,4,0,2],    score 3
    +
    +K = 2,  A = [1,4,0,2,3],    score 3
    +
    +K = 3,  A = [4,0,2,3,1],    score 4
    +
    +K = 4,  A = [0,2,3,1,4],    score 3
    +
    +
    + + + +

    So we should choose K = 3, which has the highest score.

    + + + +

     

    + + + +
    +
    +Example 2:
    +
    +Input: [1, 3, 0, 2, 4]
    +
    +Output: 0
    +
    +Explanation:  A will always have 3 points no matter how it shifts.
    +
    +So we will choose the smallest K, which is 0.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • A will have length at most 20000.
    • +
    • A[i] will be in the range [0, A.length].
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0799.Champagne Tower/README_EN.md b/assets/0700-0799/0799.Champagne Tower/README_EN.md new file mode 100644 index 00000000..f3a547ac --- /dev/null +++ b/assets/0700-0799/0799.Champagne Tower/README_EN.md @@ -0,0 +1,108 @@ +# [799. Champagne Tower](https://leetcode.com/problems/champagne-tower) + + + +## Description + +

    We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne.

    + + + +

    Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.)

    + + + +

    For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.

    + + + +

    + + + +

    Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: poured = 1, query_row = 1, query_glass = 1
    +
    +Output: 0.00000
    +
    +Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: poured = 2, query_row = 1, query_glass = 1
    +
    +Output: 0.50000
    +
    +Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: poured = 100000009, query_row = 33, query_glass = 17
    +
    +Output: 1.00000
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= poured <= 109
    • +
    • 0 <= query_glass <= query_row < 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0700-0799/0799.Champagne Tower/images/tower.png b/assets/0700-0799/0799.Champagne Tower/images/tower.png new file mode 100644 index 00000000..6cd621ca Binary files /dev/null and b/assets/0700-0799/0799.Champagne Tower/images/tower.png differ diff --git a/assets/0800-0899/0800.Similar RGB Color/README_EN.md b/assets/0800-0899/0800.Similar RGB Color/README_EN.md new file mode 100644 index 00000000..ba3a99e4 --- /dev/null +++ b/assets/0800-0899/0800.Similar RGB Color/README_EN.md @@ -0,0 +1,76 @@ +# [800. Similar RGB Color](https://leetcode.com/problems/similar-rgb-color) + + + +## Description + +

    In the following, every capital letter represents some hexadecimal digit from 0 to f.

    + + + +

    The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.  For example, "#15c" is shorthand for the color "#1155cc".

    + + + +

    Now, say the similarity between two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2.

    + + + +

    Given the color "#ABCDEF", return a 7 character color that is most similar to #ABCDEF, and has a shorthand (that is, it can be represented as some "#XYZ"

    + + + +
    +
    +Example 1:
    +
    +Input: color = "#09f166"
    +
    +Output: "#11ee66"
    +
    +Explanation:  
    +
    +The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73.
    +
    +This is the highest among any shorthand color.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • color is a string of length 7.
    • +
    • color is a valid RGB color: for i > 0, color[i] is a hexadecimal digit from 0 to f
    • +
    • Any answer which has the same (highest) similarity as the best answer will be accepted.
    • +
    • All inputs and outputs should use lowercase letters, and the output is 7 characters.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md b/assets/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md new file mode 100644 index 00000000..96ab40e6 --- /dev/null +++ b/assets/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md @@ -0,0 +1,76 @@ +# [801. Minimum Swaps To Make Sequences Increasing](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing) + + + +## Description + +

    We have two integer sequences A and B of the same non-zero length.

    + + + +

    We are allowed to swap elements A[i] and B[i].  Note that both elements are in the same index position in their respective sequences.

    + + + +

    At the end of some number of swaps, A and B are both strictly increasing.  (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1].)

    + + + +

    Given A and B, return the minimum number of swaps to make both sequences strictly increasing.  It is guaranteed that the given input always makes it possible.

    + + + +
    +
    +Example:
    +
    +Input: A = [1,3,5,4], B = [1,2,3,7]
    +
    +Output: 1
    +
    +Explanation: 
    +
    +Swap A[3] and B[3].  Then the sequences are:
    +
    +A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
    +
    +which are both strictly increasing.
    +
    +
    + + + +

    Note:

    + + + +
      +
    • A, B are arrays with the same length, and that length will be in the range [1, 1000].
    • +
    • A[i], B[i] are integer values in the range [0, 2000].
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0802.Find Eventual Safe States/README_EN.md b/assets/0800-0899/0802.Find Eventual Safe States/README_EN.md new file mode 100644 index 00000000..1699d3d6 --- /dev/null +++ b/assets/0800-0899/0802.Find Eventual Safe States/README_EN.md @@ -0,0 +1,66 @@ +# [802. Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states) + + + +## Description + +

    We start at some node in a directed graph, and every turn, we walk along a directed edge of the graph. If we reach a terminal node (that is, it has no outgoing directed edges), we stop.

    + +

    We define a starting node to be safe if we must eventually walk to a terminal node. More specifically, there is a natural number k, so that we must have stopped at a terminal node in less than k steps for any choice of where to walk.

    + +

    Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

    + +

    The directed graph has n nodes with labels from 0 to n - 1, where n is the length of graph. The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph, going from node i to node j.

    + +

     

    +

    Example 1:

    +Illustration of graph +
    +Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
    +Output: [2,4,5,6]
    +Explanation: The given graph is shown above.
    +
    + +

    Example 2:

    + +
    +Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
    +Output: [4]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == graph.length
    • +
    • 1 <= n <= 104
    • +
    • 0 <= graph[i].legnth <= n
    • +
    • graph[i] is sorted in a strictly increasing order.
    • +
    • The graph may contain self-loops.
    • +
    • The number of edges in the graph will be in the range [1, 4 * 104].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0802.Find Eventual Safe States/images/picture1.png b/assets/0800-0899/0802.Find Eventual Safe States/images/picture1.png new file mode 100644 index 00000000..02511c36 Binary files /dev/null and b/assets/0800-0899/0802.Find Eventual Safe States/images/picture1.png differ diff --git a/assets/0800-0899/0803.Bricks Falling When Hit/README_EN.md b/assets/0800-0899/0803.Bricks Falling When Hit/README_EN.md new file mode 100644 index 00000000..8cf34043 --- /dev/null +++ b/assets/0800-0899/0803.Bricks Falling When Hit/README_EN.md @@ -0,0 +1,97 @@ +# [803. Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit) + + + +## Description + +

    You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:

    + +
      +
    • It is directly connected to the top of the grid, or
    • +
    • At least one other brick in its four adjacent cells is stable.
    • +
    + +

    You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).

    + +

    Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.

    + +

    Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
    +Output: [2]
    +Explanation: Starting with the grid:
    +[[1,0,0,0],
    + [1,1,1,0]]
    +We erase the underlined brick at (1,0), resulting in the grid:
    +[[1,0,0,0],
    + [0,1,1,0]]
    +The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
    +[[1,0,0,0],
    + [0,0,0,0]]
    +Hence the result is [2].
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
    +Output: [0,0]
    +Explanation: Starting with the grid:
    +[[1,0,0,0],
    + [1,1,0,0]]
    +We erase the underlined brick at (1,1), resulting in the grid:
    +[[1,0,0,0],
    + [1,0,0,0]]
    +All remaining bricks are still stable, so no bricks fall. The grid remains the same:
    +[[1,0,0,0],
    + [1,0,0,0]]
    +Next, we erase the underlined brick at (1,0), resulting in the grid:
    +[[1,0,0,0],
    + [0,0,0,0]]
    +Once again, all remaining bricks are still stable, so no bricks fall.
    +Hence the result is [0,0].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • grid[i][j] is 0 or 1.
    • +
    • 1 <= hits.length <= 4 * 104
    • +
    • hits[i].length == 2
    • +
    • 0 <= x<= m - 1
    • +
    • 0 <= yi <= n - 1
    • +
    • All (xi, yi) are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0804.Unique Morse Code Words/README_EN.md b/assets/0800-0899/0804.Unique Morse Code Words/README_EN.md new file mode 100644 index 00000000..7b6a3785 --- /dev/null +++ b/assets/0800-0899/0804.Unique Morse Code Words/README_EN.md @@ -0,0 +1,63 @@ +# [804. Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words) + + + +## Description + +

    International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.

    + +

    For convenience, the full table for the 26 letters of the English alphabet is given below:

    + +
    +[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    + +

    Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", (which is the concatenation "-.-." + ".-" + "-..."). We'll call such a concatenation, the transformation of a word.

    + +

    Return the number of different transformations among all words we have.

    + +
    +Example:
    +Input: words = ["gin", "zen", "gig", "msg"]
    +Output: 2
    +Explanation: 
    +The transformation of each word is:
    +"gin" -> "--...-."
    +"zen" -> "--...-."
    +"gig" -> "--...--."
    +"msg" -> "--...--."
    +
    +There are 2 different transformations, "--...-." and "--...--.".
    +
    + +

    Note:

    + +
      +
    • The length of words will be at most 100.
    • +
    • Each words[i] will have length in range [1, 12].
    • +
    • words[i] will only consist of lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0805.Split Array With Same Average/README_EN.md b/assets/0800-0899/0805.Split Array With Same Average/README_EN.md new file mode 100644 index 00000000..b87b2203 --- /dev/null +++ b/assets/0800-0899/0805.Split Array With Same Average/README_EN.md @@ -0,0 +1,62 @@ +# [805. Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average) + + + +## Description + +

    You are given an integer array nums.

    + +

    You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).

    + +

    Return true if it is possible to achieve that and false otherwise.

    + +

    Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4,5,6,7,8]
    +Output: true
    +Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,1]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 30
    • +
    • 0 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0806.Number of Lines To Write String/README_EN.md b/assets/0800-0899/0806.Number of Lines To Write String/README_EN.md new file mode 100644 index 00000000..386bf3b6 --- /dev/null +++ b/assets/0800-0899/0806.Number of Lines To Write String/README_EN.md @@ -0,0 +1,73 @@ +# [806. Number of Lines To Write String](https://leetcode.com/problems/number-of-lines-to-write-string) + + + +## Description + +

    You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.

    + +

    You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.

    + +

    Return an array result of length 2 where:

    + +
      +
    • result[0] is the total number of lines.
    • +
    • result[1] is the width of the last line in pixels.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"
    +Output: [3,60]
    +Explanation: You can write s as follows:
    +abcdefghij  // 100 pixels wide
    +klmnopqrst  // 100 pixels wide
    +uvwxyz      // 60 pixels wide
    +There are a total of 3 lines, and the last line is 60 pixels wide.
    + +

    Example 2:

    + +
    +Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa"
    +Output: [2,4]
    +Explanation: You can write s as follows:
    +bbbcccdddaa  // 98 pixels wide
    +a            // 4 pixels wide
    +There are a total of 2 lines, and the last line is 4 pixels wide.
    + +

     

    +

    Constraints:

    + +
      +
    • widths.length == 26
    • +
    • 2 <= widths[i] <= 10
    • +
    • 1 <= s.length <= 1000
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md b/assets/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md new file mode 100644 index 00000000..3523a5e3 --- /dev/null +++ b/assets/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md @@ -0,0 +1,99 @@ +# [807. Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline) + + + +## Description + +

    In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well. 

    + + + +

    At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.

    + + + +

    What is the maximum total sum that the height of the buildings can be increased?

    + + + +
    +
    +Example:
    +
    +Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
    +
    +Output: 35
    +
    +Explanation: 
    +
    +The grid is:
    +
    +[ [3, 0, 8, 4], 
    +
    +  [2, 4, 5, 7],
    +
    +  [9, 2, 6, 3],
    +
    +  [0, 3, 1, 0] ]
    +
    +
    +
    +The skyline viewed from top or bottom is: [9, 4, 8, 7]
    +
    +The skyline viewed from left or right is: [8, 7, 9, 3]
    +
    +
    +
    +The grid after increasing the height of buildings without affecting skylines is:
    +
    +
    +
    +gridNew = [ [8, 4, 8, 7],
    +
    +            [7, 4, 7, 7],
    +
    +            [9, 4, 8, 7],
    +
    +            [3, 3, 3, 3] ]
    +
    +
    +
    +
    + + + +

    Notes:

    + + + +
      +
    • 1 < grid.length = grid[0].length <= 50.
    • +
    • All heights grid[i][j] are in the range [0, 100].
    • +
    • All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0808.Soup Servings/README_EN.md b/assets/0800-0899/0808.Soup Servings/README_EN.md new file mode 100644 index 00000000..c15e51fc --- /dev/null +++ b/assets/0800-0899/0808.Soup Servings/README_EN.md @@ -0,0 +1,87 @@ +# [808. Soup Servings](https://leetcode.com/problems/soup-servings) + + + +## Description + +

    There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:

    + + + +
      +
    1. Serve 100 ml of soup A and 0 ml of soup B
    2. +
    3. Serve 75 ml of soup A and 25 ml of soup B
    4. +
    5. Serve 50 ml of soup A and 50 ml of soup B
    6. +
    7. Serve 25 ml of soup A and 75 ml of soup B
    8. +
    + + + +

    When we serve some soup, we give it to someone and we no longer have it.  Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can.  We stop once we no longer have some quantity of both types of soup.

    + + + +

    Note that we do not have the operation where all 100 ml's of soup B are used first.  

    + + + +

    Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.

    + + + +

     

    + + + +
    +
    +Example:
    +
    +Input: N = 50
    +
    +Output: 0.625
    +
    +Explanation: 
    +
    +If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
    +
    +
    +
    +
    + + + +

    Notes:

    + + + +
      +
    • 0 <= N <= 10^9
    • +
    • Answers within 10^-6 of the true value will be accepted as correct.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0809.Expressive Words/README_EN.md b/assets/0800-0899/0809.Expressive Words/README_EN.md new file mode 100644 index 00000000..c44db406 --- /dev/null +++ b/assets/0800-0899/0809.Expressive Words/README_EN.md @@ -0,0 +1,61 @@ +# [809. Expressive Words](https://leetcode.com/problems/expressive-words) + + + +## Description + +

    Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii".  In these strings like "heeellooo", we have groups of adjacent letters that are all the same:  "h", "eee", "ll", "ooo".

    + +

    For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.

    + +

    For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has size less than 3.  Also, we could do another extension like "ll" -> "lllll" to get "helllllooo".  If S = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = S.

    + +

    Given a list of query words, return the number of words that are stretchy. 

    + +

     

    + +
    +Example:
    +Input: 
    +S = "heeellooo"
    +words = ["hello", "hi", "helo"]
    +Output: 1
    +Explanation: 
    +We can extend "e" and "o" in the word "hello" to get "heeellooo".
    +We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= len(S) <= 100.
    • +
    • 0 <= len(words) <= 100.
    • +
    • 0 <= len(words[i]) <= 100.
    • +
    • S and all words in words consist only of lowercase letters
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0810.Chalkboard XOR Game/README_EN.md b/assets/0800-0899/0810.Chalkboard XOR Game/README_EN.md new file mode 100644 index 00000000..6ff78c5c --- /dev/null +++ b/assets/0800-0899/0810.Chalkboard XOR Game/README_EN.md @@ -0,0 +1,78 @@ +# [810. Chalkboard XOR Game](https://leetcode.com/problems/chalkboard-xor-game) + + + +## Description + +

    We are given non-negative integers nums[i] which are written on a chalkboard.  Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first.  If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses.  (Also, we'll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)

    + + + +

    Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.

    + + + +

    Return True if and only if Alice wins the game, assuming both players play optimally.

    + + + +
    +
    +Example:
    +
    +Input: nums = [1, 1, 2]
    +
    +Output: false
    +
    +Explanation: 
    +
    +Alice has two choices: erase 1 or erase 2. 
    +
    +If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. 
    +
    +If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
    +
    +
    +
    +
    + + + +

    Notes:

    + + + +
      +
    • 1 <= N <= 1000
    • +
    • 0 <= nums[i] <= 2^16.
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0811.Subdomain Visit Count/README_EN.md b/assets/0800-0899/0811.Subdomain Visit Count/README_EN.md new file mode 100644 index 00000000..1d98ae8b --- /dev/null +++ b/assets/0800-0899/0811.Subdomain Visit Count/README_EN.md @@ -0,0 +1,128 @@ +# [811. Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count) + + + +## Description + +

    A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.

    + + + +

    Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".

    + + + +

    We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.

    + + + +
    +
    +Example 1:
    +
    +Input: 
    +
    +["9001 discuss.leetcode.com"]
    +
    +Output: 
    +
    +["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
    +
    +Explanation: 
    +
    +We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
    +
    +
    +
    +
    + + + +
    +
    +Example 2:
    +
    +Input: 
    +
    +["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
    +
    +Output: 
    +
    +["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
    +
    +Explanation: 
    +
    +We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
    +
    +
    +
    +
    + + + +

    Notes:

    + + + +
      +
    • The length of cpdomains will not exceed 100
    • +
    • The length of each domain name will not exceed 100.
    • +
    • Each address will have either 1 or 2 "." characters.
    • +
    • The input count in any count-paired domain will not exceed 10000.
    • +
    • The answer output can be returned in any order.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def subdomainVisits(self, cpdomains: List[str]) -> List[str]: + domains = collections.Counter() + for item in cpdomains: + count, domain = item.split() + count = int(count) + subs = domain.split('.') + for i in range(len(subs)): + key = '.'.join(subs[i:]) + domains[key] += count + return [f'{cnt} {domain}' for domain, cnt in domains.items()] +``` + +### **Java** + +```java +class Solution { + public List subdomainVisits(String[] cpdomains) { + Map domains = new HashMap<>(); + for (String domain : cpdomains) { + String[] t = domain.split(" "); + int count = Integer.parseInt(t[0]); + String[] subs = t[1].split("\\."); + String cur = ""; + for (int i = subs.length - 1; i >= 0; --i) { + cur = subs[i] + (i == subs.length - 1 ? "" : ".") + cur; + domains.put(cur, domains.getOrDefault(cur, 0) + count); + } + } + List res = new ArrayList<>(); + domains.forEach((domain, count) -> { + res.add(count + " " + domain); + }); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0812.Largest Triangle Area/README_EN.md b/assets/0800-0899/0812.Largest Triangle Area/README_EN.md new file mode 100644 index 00000000..5bcf97eb --- /dev/null +++ b/assets/0800-0899/0812.Largest Triangle Area/README_EN.md @@ -0,0 +1,70 @@ +# [812. Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area) + + + +## Description + +

    You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.

    + + + +
    +
    +Example:
    +
    +Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
    +
    +Output: 2
    +
    +Explanation: 
    +
    +The five points are show in the figure below. The red triangle is the largest.
    +
    +
    + + + +

    + + + +

    Notes:

    + + + +
      +
    • 3 <= points.length <= 50.
    • +
    • No points will be duplicated.
    • +
    •  -50 <= points[i][j] <= 50.
    • +
    • Answers within 10^-6 of the true value will be accepted as correct.
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0812.Largest Triangle Area/images/1027.png b/assets/0800-0899/0812.Largest Triangle Area/images/1027.png new file mode 100644 index 00000000..3e6f271a Binary files /dev/null and b/assets/0800-0899/0812.Largest Triangle Area/images/1027.png differ diff --git a/assets/0800-0899/0813.Largest Sum of Averages/README_EN.md b/assets/0800-0899/0813.Largest Sum of Averages/README_EN.md new file mode 100644 index 00000000..c3a0ac05 --- /dev/null +++ b/assets/0800-0899/0813.Largest Sum of Averages/README_EN.md @@ -0,0 +1,78 @@ +# [813. Largest Sum of Averages](https://leetcode.com/problems/largest-sum-of-averages) + + + +## Description + +

    We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?

    + + + +

    Note that our partition must use every number in A, and that scores are not necessarily integers.

    + + + +
    +
    +Example:
    +
    +Input: 
    +
    +A = [9,1,2,3,9]
    +
    +K = 3
    +
    +Output: 20
    +
    +Explanation: 
    +
    +The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
    +
    +We could have also partitioned A into [9, 1], [2], [3, 9], for example.
    +
    +That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= A.length <= 100.
    • +
    • 1 <= A[i] <= 10000.
    • +
    • 1 <= K <= A.length.
    • +
    • Answers within 10^-6 of the correct answer will be accepted as correct.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0814.Binary Tree Pruning/README_EN.md b/assets/0800-0899/0814.Binary Tree Pruning/README_EN.md new file mode 100644 index 00000000..972ef65f --- /dev/null +++ b/assets/0800-0899/0814.Binary Tree Pruning/README_EN.md @@ -0,0 +1,73 @@ +# [814. Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning) + + + +## Description + +

    We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.

    + +

    Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

    + +

    (Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

    + +
    +Example 1:
    +Input: [1,null,0,0,1]
    +Output: [1,null,0,null,1]
    + 
    +Explanation: 
    +Only the red nodes satisfy the property "every subtree not containing a 1".
    +The diagram on the right represents the answer.
    +
    +
    +
    + +
    +Example 2:
    +Input: [1,0,1,0,0,0,1]
    +Output: [1,null,1,null,1]
    +
    +
    +
    +
    + +
    +Example 3:
    +Input: [1,1,0,1,1,0,1,0]
    +Output: [1,1,0,1,1,null,1]
    +
    +
    +
    +
    + +

    Note:

    + +
      +
    • The binary tree will have at most 200 nodes.
    • +
    • The value of each node will only be 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0814.Binary Tree Pruning/images/1028.png b/assets/0800-0899/0814.Binary Tree Pruning/images/1028.png new file mode 100644 index 00000000..2521be81 Binary files /dev/null and b/assets/0800-0899/0814.Binary Tree Pruning/images/1028.png differ diff --git a/assets/0800-0899/0814.Binary Tree Pruning/images/1028_1.png b/assets/0800-0899/0814.Binary Tree Pruning/images/1028_1.png new file mode 100644 index 00000000..877ec484 Binary files /dev/null and b/assets/0800-0899/0814.Binary Tree Pruning/images/1028_1.png differ diff --git a/assets/0800-0899/0814.Binary Tree Pruning/images/1028_2.png b/assets/0800-0899/0814.Binary Tree Pruning/images/1028_2.png new file mode 100644 index 00000000..de3fb9d8 Binary files /dev/null and b/assets/0800-0899/0814.Binary Tree Pruning/images/1028_2.png differ diff --git a/assets/0800-0899/0815.Bus Routes/README_EN.md b/assets/0800-0899/0815.Bus Routes/README_EN.md new file mode 100644 index 00000000..2c15b581 --- /dev/null +++ b/assets/0800-0899/0815.Bus Routes/README_EN.md @@ -0,0 +1,68 @@ +# [815. Bus Routes](https://leetcode.com/problems/bus-routes) + + + +## Description + +

    You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.

    + +
      +
    • For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
    • +
    + +

    You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.

    + +

    Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.

    + +

     

    +

    Example 1:

    + +
    +Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
    +Output: 2
    +Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
    +
    + +

    Example 2:

    + +
    +Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= routes.length <= 500.
    • +
    • 1 <= routes[i].length <= 105
    • +
    • All the values of routes[i] are unique.
    • +
    • sum(routes[i].length) <= 105
    • +
    • 0 <= routes[i][j] < 106
    • +
    • 0 <= source, target < 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0816.Ambiguous Coordinates/README_EN.md b/assets/0800-0899/0816.Ambiguous Coordinates/README_EN.md new file mode 100644 index 00000000..fbbcc9b4 --- /dev/null +++ b/assets/0800-0899/0816.Ambiguous Coordinates/README_EN.md @@ -0,0 +1,116 @@ +# [816. Ambiguous Coordinates](https://leetcode.com/problems/ambiguous-coordinates) + + + +## Description + +

    We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)".  Then, we removed all commas, decimal points, and spaces, and ended up with the string S.  Return a list of strings representing all possibilities for what our original coordinates could have been.

    + + + +

    Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with less digits.  Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like ".1".

    + + + +

    The final answer list can be returned in any order.  Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)

    + + + +
    +
    +Example 1:
    +
    +Input: "(123)"
    +
    +Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]
    +
    +
    + + + +
    +
    +Example 2:
    +
    +Input: "(00011)"
    +
    +Output:  ["(0.001, 1)", "(0, 0.011)"]
    +
    +Explanation: 
    +
    +0.0, 00, 0001 or 00.01 are not allowed.
    +
    +
    + + + +
    +
    +Example 3:
    +
    +Input: "(0123)"
    +
    +Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"]
    +
    +
    + + + +
    +
    +Example 4:
    +
    +Input: "(100)"
    +
    +Output: [(10, 0)]
    +
    +Explanation: 
    +
    +1.0 is not allowed.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 4 <= S.length <= 12.
    • +
    • S[0] = "(", S[S.length - 1] = ")", and the other elements in S are digits.
    • +
    + + + +

     

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0817.Linked List Components/README_EN.md b/assets/0800-0899/0817.Linked List Components/README_EN.md new file mode 100644 index 00000000..f6ceba8e --- /dev/null +++ b/assets/0800-0899/0817.Linked List Components/README_EN.md @@ -0,0 +1,128 @@ +# [817. Linked List Components](https://leetcode.com/problems/linked-list-components) + + + +## Description + +

    We are given head, the head node of a linked list containing unique integer values.

    + +

    We are also given the list G, a subset of the values in the linked list.

    + +

    Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.

    + +

    Example 1:

    + +
    +
    +Input: 
    +
    +head: 0->1->2->3
    +
    +G = [0, 1, 3]
    +
    +Output: 2
    +
    +Explanation: 
    +
    +0 and 1 are connected, so [0, 1] and [3] are the two connected components.
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: 
    +
    +head: 0->1->2->3->4
    +
    +G = [0, 3, 1, 4]
    +
    +Output: 2
    +
    +Explanation: 
    +
    +0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
    +
    +
    + +

    Note:

    + +
      +
    • If N is the length of the linked list given by head1 <= N <= 10000.
    • +
    • The value of each node in the linked list will be in the range [0, N - 1].
    • +
    • 1 <= G.length <= 10000.
    • +
    • G is a subset of all values in the linked list.
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def numComponents(self, head: ListNode, nums: List[int]) -> int: + s = set(nums) + res, pre = 0, True + while head: + if head.val in s: + if pre: + res += 1 + pre = False + else: + pre = True + head = head.next + return res +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int numComponents(ListNode head, int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + s.add(num); + } + int res = 0; + boolean pre = true; + while (head != null) { + if (s.contains(head.val)) { + if (pre) { + ++res; + pre = false; + } + } else { + pre = true; + } + head = head.next; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0818.Race Car/README_EN.md b/assets/0800-0899/0818.Race Car/README_EN.md new file mode 100644 index 00000000..47370804 --- /dev/null +++ b/assets/0800-0899/0818.Race Car/README_EN.md @@ -0,0 +1,107 @@ +# [818. Race Car](https://leetcode.com/problems/race-car) + + + +## Description + +

    Your car starts at position 0 and speed +1 on an infinite number line.  (Your car can go into negative positions.)

    + + + +

    Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).

    + + + +

    When you get an instruction "A", your car does the following: position += speed, speed *= 2.

    + + + +

    When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1.  (Your position stays the same.)

    + + + +

    For example, after commands "AAR", your car goes to positions 0->1->3->3, and your speed goes to 1->2->4->-1.

    + + + +

    Now for some target position, say the length of the shortest sequence of instructions to get there.

    + + + +
    +
    +Example 1:
    +
    +Input: 
    +
    +target = 3
    +
    +Output: 2
    +
    +Explanation: 
    +
    +The shortest instruction sequence is "AA".
    +
    +Your position goes from 0->1->3.
    +
    +
    + + + +
    +
    +Example 2:
    +
    +Input: 
    +
    +target = 6
    +
    +Output: 5
    +
    +Explanation: 
    +
    +The shortest instruction sequence is "AAARA".
    +
    +Your position goes from 0->1->3->7->7->6.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= target <= 10000.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0819.Most Common Word/README_EN.md b/assets/0800-0899/0819.Most Common Word/README_EN.md new file mode 100644 index 00000000..118f1e63 --- /dev/null +++ b/assets/0800-0899/0819.Most Common Word/README_EN.md @@ -0,0 +1,99 @@ +# [819. Most Common Word](https://leetcode.com/problems/most-common-word) + + + +## Description + +

    Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

    + +

    The words in paragraph are case-insensitive and the answer should be returned in lowercase.

    + +

     

    +

    Example 1:

    + +
    +Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
    +Output: "ball"
    +Explanation: 
    +"hit" occurs 3 times, but it is a banned word.
    +"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 
    +Note that words in the paragraph are not case sensitive,
    +that punctuation is ignored (even if adjacent to words, such as "ball,"), 
    +and that "hit" isn't the answer even though it occurs more because it is banned.
    +
    + +

    Example 2:

    + +
    +Input: paragraph = "a.", banned = []
    +Output: "a"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= paragraph.length <= 1000
    • +
    • paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
    • +
    • 0 <= banned.length <= 100
    • +
    • 1 <= banned[i].length <= 10
    • +
    • banned[i] consists of only lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: + paragraph = collections.Counter(re.findall('[a-z]+', paragraph.lower())) + banned_words = set(banned) + for word, _ in paragraph.most_common(): + if word not in banned_words: + return word +``` + +### **Java** + +```java +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class Solution { + public String mostCommonWord(String paragraph, String[] banned) { + Set bannedWords = new HashSet<>(); + for (String word : banned) { + bannedWords.add(word); + } + Map counter = new HashMap<>(); + Matcher matcher = Pattern.compile("[a-z]+").matcher(paragraph.toLowerCase()); + while (matcher.find()) { + String word = matcher.group(); + if (bannedWords.contains(word)) { + continue; + } + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + int max = Integer.MIN_VALUE; + String res = null; + for (Map.Entry entry : counter.entrySet()) { + if (entry.getValue() > max) { + max = entry.getValue(); + res = entry.getKey(); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0820.Short Encoding of Words/README_EN.md b/assets/0800-0899/0820.Short Encoding of Words/README_EN.md new file mode 100644 index 00000000..38979dc5 --- /dev/null +++ b/assets/0800-0899/0820.Short Encoding of Words/README_EN.md @@ -0,0 +1,69 @@ +# [820. Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words) + + + +## Description + +

    A valid encoding of an array of words is any reference string s and array of indices indices such that:

    + +
      +
    • words.length == indices.length
    • +
    • The reference string s ends with the '#' character.
    • +
    • For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
    • +
    + +

    Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["time", "me", "bell"]
    +Output: 10
    +Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
    +words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
    +words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
    +words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
    +
    + +

    Example 2:

    + +
    +Input: words = ["t"]
    +Output: 2
    +Explanation: A valid encoding would be s = "t#" and indices = [0].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 2000
    • +
    • 1 <= words[i].length <= 7
    • +
    • words[i] consists of only lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0821.Shortest Distance to a Character/README_EN.md b/assets/0800-0899/0821.Shortest Distance to a Character/README_EN.md new file mode 100644 index 00000000..7391724f --- /dev/null +++ b/assets/0800-0899/0821.Shortest Distance to a Character/README_EN.md @@ -0,0 +1,63 @@ +# [821. Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character) + + + +## Description + +

    Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.

    + +

    The distance between two indices i and j is abs(i - j), where abs is the absolute value function.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "loveleetcode", c = "e"
    +Output: [3,2,1,0,1,0,0,1,2,2,1,0]
    +Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
    +The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
    +The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 3.
    +For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
    +The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
    +
    + +

    Example 2:

    + +
    +Input: s = "aaab", c = "b"
    +Output: [3,2,1,0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s[i] and c are lowercase English letters.
    • +
    • It is guaranteed that c occurs at least once in s.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0822.Card Flipping Game/README_EN.md b/assets/0800-0899/0822.Card Flipping Game/README_EN.md new file mode 100644 index 00000000..b806ef65 --- /dev/null +++ b/assets/0800-0899/0822.Card Flipping Game/README_EN.md @@ -0,0 +1,85 @@ +# [822. Card Flipping Game](https://leetcode.com/problems/card-flipping-game) + + + +## Description + +

    On a table are N cards, with a positive integer printed on the front and back of each card (possibly different).

    + + + +

    We flip any number of cards, and after we choose one card. 

    + + + +

    If the number X on the back of the chosen card is not on the front of any card, then this number X is good.

    + + + +

    What is the smallest number that is good?  If no number is good, output 0.

    + + + +

    Here, fronts[i] and backs[i] represent the number on the front and back of card i

    + + + +

    A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.

    + + + +

    Example:

    + + + +
    +
    +Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
    +
    +Output: 2
    +
    +Explanation: If we flip the second card, the fronts are [1,3,4,4,7] and the backs are [1,2,4,1,3].
    +
    +We choose the second card, which has number 2 on the back, and it isn't on the front of any card, so 2 is good.
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= fronts.length == backs.length <= 1000.
    2. +
    3. 1 <= fronts[i] <= 2000.
    4. +
    5. 1 <= backs[i] <= 2000.
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0823.Binary Trees With Factors/README_EN.md b/assets/0800-0899/0823.Binary Trees With Factors/README_EN.md new file mode 100644 index 00000000..27aabef3 --- /dev/null +++ b/assets/0800-0899/0823.Binary Trees With Factors/README_EN.md @@ -0,0 +1,60 @@ +# [823. Binary Trees With Factors](https://leetcode.com/problems/binary-trees-with-factors) + + + +## Description + +

    Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.

    + +

    We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.

    + +

    Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [2,4]
    +Output: 3
    +Explanation: We can make these trees: [2], [4], [4, 2, 2]
    + +

    Example 2:

    + +
    +Input: arr = [2,4,5,10]
    +Output: 7
    +Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 2 <= arr[i] <= 109
    • +
    • All the values of arr are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0824.Goat Latin/README_EN.md b/assets/0800-0899/0824.Goat Latin/README_EN.md new file mode 100644 index 00000000..788adbe6 --- /dev/null +++ b/assets/0800-0899/0824.Goat Latin/README_EN.md @@ -0,0 +1,105 @@ +# [824. Goat Latin](https://leetcode.com/problems/goat-latin) + + + +## Description + +

    A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

    + + + +

    We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)

    + + + +

    The rules of Goat Latin are as follows:

    + + + +
      +
    • If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word.
      + For example, the word 'apple' becomes 'applema'.
      +  
    • +
    • If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma".
      + For example, the word "goat" becomes "oatgma".
      +  
    • +
    • Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
      + For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.
    • +
    + + + +

    Return the final sentence representing the conversion from S to Goat Latin. 

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "I speak Goat Latin"
    +
    +Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: "The quick brown fox jumped over the lazy dog"
    +
    +Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
    +
    +
    + + + +

     

    + + + +

    Notes:

    + + + +
      +
    • S contains only uppercase, lowercase and spaces. Exactly one space between each word.
    • +
    • 1 <= S.length <= 150.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md b/assets/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md new file mode 100644 index 00000000..08646056 --- /dev/null +++ b/assets/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md @@ -0,0 +1,78 @@ +# [825. Friends Of Appropriate Ages](https://leetcode.com/problems/friends-of-appropriate-ages) + + + +## Description + +

    Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person. 

    + +

    Person A will NOT friend request person B (B != A) if any of the following conditions are true:

    + +
      +
    • age[B] <= 0.5 * age[A] + 7
    • +
    • age[B] > age[A]
    • +
    • age[B] > 100 && age[A] < 100
    • +
    + +

    Otherwise, A will friend request B.

    + +

    Note that if A requests B, B does not necessarily request A.  Also, people will not friend request themselves.

    + +

    How many total friend requests are made?

    + +

    Example 1:

    + +
    +Input: [16,16]
    +Output: 2
    +Explanation: 2 people friend request each other.
    +
    + +

    Example 2:

    + +
    +Input: [16,17,18]
    +Output: 2
    +Explanation: Friend requests are made 17 -> 16, 18 -> 17.
    + +

    Example 3:

    + +
    +Input: [20,30,100,110,120]
    +Output: 3
    +Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
    +
    + +

     

    + +

    Notes:

    + +
      +
    • 1 <= ages.length <= 20000.
    • +
    • 1 <= ages[i] <= 120.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0826.Most Profit Assigning Work/README_EN.md b/assets/0800-0899/0826.Most Profit Assigning Work/README_EN.md new file mode 100644 index 00000000..09953e15 --- /dev/null +++ b/assets/0800-0899/0826.Most Profit Assigning Work/README_EN.md @@ -0,0 +1,75 @@ +# [826. Most Profit Assigning Work](https://leetcode.com/problems/most-profit-assigning-work) + + + +## Description + +

    We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job. 

    + + + +

    Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i]

    + + + +

    Every worker can be assigned at most one job, but one job can be completed multiple times.

    + + + +

    For example, if 3 people attempt the same job that pays $1, then the total profit will be $3.  If a worker cannot complete any job, his profit is $0.

    + + + +

    What is the most profit we can make?

    + + + +

    Example 1:

    + + + +
    +
    +Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
    +
    +Output: 100 
    +
    +Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
    + + + +

    Notes:

    + + + +
      +
    • 1 <= difficulty.length = profit.length <= 10000
    • +
    • 1 <= worker.length <= 10000
    • +
    • difficulty[i], profit[i], worker[i]  are in range [1, 10^5]
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0827.Making A Large Island/README_EN.md b/assets/0800-0899/0827.Making A Large Island/README_EN.md new file mode 100644 index 00000000..21cd3105 --- /dev/null +++ b/assets/0800-0899/0827.Making A Large Island/README_EN.md @@ -0,0 +1,102 @@ +# [827. Making A Large Island](https://leetcode.com/problems/making-a-large-island) + + + +## Description + +

    You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.

    + + + +

    Return the size of the largest island in grid after applying this operation.

    + + + +

    An island is a 4-directionally connected group of 1s.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: grid = [[1,0],[0,1]]
    +
    +Output: 3
    +
    +Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: grid = [[1,1],[1,0]]
    +
    +Output: 4
    +
    +Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
    + + + +

    Example 3:

    + + + +
    +
    +Input: grid = [[1,1],[1,1]]
    +
    +Output: 4
    +
    +Explanation: Can't change any 0 to 1, only one island with area = 4.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 500
    • +
    • grid[i][j] is either 0 or 1.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md b/assets/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md new file mode 100644 index 00000000..370fadb4 --- /dev/null +++ b/assets/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md @@ -0,0 +1,70 @@ +# [828. Count Unique Characters of All Substrings of a Given String](https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string) + + + +## Description + +

    Let's define a function countUniqueChars(s) that returns the number of unique characters on s, for example if s = "LEETCODE" then "L", "T","C","O","D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
    +
    +On this problem given a string s we need to return the sum of countUniqueChars(t) where t is a substring of s. Notice that some substrings can be repeated so on this case you have to count the repeated ones too.

    + +

    Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "ABC"
    +Output: 10
    +Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
    +Evey substring is composed with only unique letters.
    +Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
    +
    + +

    Example 2:

    + +
    +Input: s = "ABA"
    +Output: 8
    +Explanation: The same as example 1, except countUniqueChars("ABA") = 1.
    +
    + +

    Example 3:

    + +
    +Input: s = "LEETCODE"
    +Output: 92
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= s.length <= 10^4
    • +
    • s contain upper-case English letters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0829.Consecutive Numbers Sum/README_EN.md b/assets/0800-0899/0829.Consecutive Numbers Sum/README_EN.md new file mode 100644 index 00000000..2412dc33 --- /dev/null +++ b/assets/0800-0899/0829.Consecutive Numbers Sum/README_EN.md @@ -0,0 +1,79 @@ +# [829. Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum) + + + +## Description + +

    Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?

    + + + +

    Example 1:

    + + + +
    +
    +Input: 5
    +
    +Output: 2
    +
    +Explanation: 5 = 5 = 2 + 3
    + + + +

    Example 2:

    + + + +
    +
    +Input: 9
    +
    +Output: 3
    +
    +Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
    + + + +

    Example 3:

    + + + +
    +
    +Input: 15
    +
    +Output: 4
    +
    +Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
    + + + +

    Note: 1 <= N <= 10 ^ 9.

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0830.Positions of Large Groups/README_EN.md b/assets/0800-0899/0830.Positions of Large Groups/README_EN.md new file mode 100644 index 00000000..e04edb35 --- /dev/null +++ b/assets/0800-0899/0830.Positions of Large Groups/README_EN.md @@ -0,0 +1,80 @@ +# [830. Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups) + + + +## Description + +

    In a string s of lowercase letters, these letters form consecutive groups of the same character.

    + +

    For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy".

    + +

    A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6].

    + +

    A group is considered large if it has 3 or more characters.

    + +

    Return the intervals of every large group sorted in increasing order by start index.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abbxxxxzzy"
    +Output: [[3,6]]
    +Explanation: "xxxx" is the only large group with start index 3 and end index 6.
    +
    + +

    Example 2:

    + +
    +Input: s = "abc"
    +Output: []
    +Explanation: We have groups "a", "b", and "c", none of which are large groups.
    +
    + +

    Example 3:

    + +
    +Input: s = "abcdddeeeeaabbbcd"
    +Output: [[3,5],[6,9],[12,14]]
    +Explanation: The large groups are "ddd", "eeee", and "bbb".
    +
    + +

    Example 4:

    + +
    +Input: s = "aba"
    +Output: []
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s contains lower-case English letters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0831.Masking Personal Information/README_EN.md b/assets/0800-0899/0831.Masking Personal Information/README_EN.md new file mode 100644 index 00000000..13665c55 --- /dev/null +++ b/assets/0800-0899/0831.Masking Personal Information/README_EN.md @@ -0,0 +1,179 @@ +# [831. Masking Personal Information](https://leetcode.com/problems/masking-personal-information) + + + +## Description + +

    We are given a personal information string S, which may represent either an email address or a phone number.

    + + + +

    We would like to mask this personal information according to the following rules:

    + + + +


    + +1. Email address:

    + + + +

    We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z.

    + + + +

    An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and followed by a name. 

    + + + +

    All email addresses are guaranteed to be valid and in the format of "name1@name2.name3".

    + + + +

    To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the first name must be replaced by 5 asterisks '*'.

    + + + +


    + +2. Phone number:

    + + + +

    A phone number is a string consisting of only the digits 0-9 or the characters from the set {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits.

    + + + +

    The last 10 digits make up the local number, while the digits before those make up the country code. Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits.

    + + + +

    The local number should be formatted and masked as "***-***-1111", where 1 represents the exposed digits.

    + + + +

    To mask a phone number with country code like "+111 111 111 1111", we write it in the form "+***-***-***-1111".  The '+' sign and the first '-' sign before the local number should only exist if there is a country code.  For example, a 12 digit phone number mask should start with "+**-".

    + + + +

    Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of the above formatting scheme should be removed.

    + + + +

     

    + + + +

    Return the correct "mask" of the information provided.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "LeetCode@LeetCode.com"
    +
    +Output: "l*****e@leetcode.com"
    +
    +Explanation: All names are converted to lowercase, and the letters between the
    +
    +             first and last letter of the first name is replaced by 5 asterisks.
    +
    +             Therefore, "leetcode" -> "l*****e".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: "AB@qq.com"
    +
    +Output: "a*****b@qq.com"
    +
    +Explanation: There must be 5 asterisks between the first and last letter 
    +
    +             of the first name "ab". Therefore, "ab" -> "a*****b".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: "1(234)567-890"
    +
    +Output: "***-***-7890"
    +
    +Explanation: 10 digits in the phone number, which means all digits make up the local number.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: "86-(10)12345678"
    +
    +Output: "+**-***-***-5678"
    +
    +Explanation: 12 digits, 2 digits for country code and 10 digits for local number. 
    +
    +
    + + + +

    Notes:

    + + + +
      +
    1. S.length <= 40.
    2. +
    3. Emails have length at least 8.
    4. +
    5. Phone numbers have length at least 10.
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0832.Flipping an Image/README_EN.md b/assets/0800-0899/0832.Flipping an Image/README_EN.md new file mode 100644 index 00000000..67141150 --- /dev/null +++ b/assets/0800-0899/0832.Flipping an Image/README_EN.md @@ -0,0 +1,129 @@ +# [832. Flipping an Image](https://leetcode.com/problems/flipping-an-image) + + + +## Description + +

    Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

    + +

    To flip an image horizontally means that each row of the image is reversed.

    + +
      +
    • For example, flipping [1,1,0] horizontally results in [0,1,1].
    • +
    + +

    To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

    + +
      +
    • For example, inverting [0,1,1] results in [1,0,0].
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: image = [[1,1,0],[1,0,1],[0,0,0]]
    +Output: [[1,0,0],[0,1,0],[1,1,1]]
    +Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
    +Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
    +
    + +

    Example 2:

    + +
    +Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
    +Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
    +Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
    +Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == image.length
    • +
    • n == image[i].length
    • +
    • 1 <= n <= 20
    • +
    • images[i][j] is either 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: + m, n = len(A), len(A[0]) + for i in range(m): + p, q = 0, n - 1 + while p < q: + t = A[i][p] ^ 1 + A[i][p] = A[i][q] ^ 1 + A[i][q] = t + p += 1 + q -= 1 + if p == q: + A[i][p] ^= 1 + return A +``` + +### **Java** + +```java +class Solution { + public int[][] flipAndInvertImage(int[][] A) { + int m = A.length, n = A[0].length; + for (int i = 0; i < m; ++i) { + int p = 0, q = n - 1; + while (p < q) { + int t = A[i][p] ^ 1; + A[i][p] = A[i][q] ^ 1; + A[i][q] = t; + ++p; + --q; + } + if (p == q) { + A[i][p] ^= 1; + } + } + return A; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> flipAndInvertImage(vector>& A) { + int m = A.size(), n = A[0].size(); + for (int i = 0; i < m; ++i) { + int p = 0, q = n - 1; + while (p < q) { + int t = A[i][p] ^ 1; + A[i][p] = A[i][q] ^ 1; + A[i][q] = t; + ++p; + --q; + } + if (p == q) { + A[i][p] ^= 1; + } + } + return A; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0833.Find And Replace in String/README_EN.md b/assets/0800-0899/0833.Find And Replace in String/README_EN.md new file mode 100644 index 00000000..57796c83 --- /dev/null +++ b/assets/0800-0899/0833.Find And Replace in String/README_EN.md @@ -0,0 +1,75 @@ +# [833. Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string) + + + +## Description + +

    To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).

    + +

    Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y.  The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y.  If not, we do nothing.

    + +

    For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we will replace it with "ffff".

    + +

    Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.

    + +

    All these operations occur simultaneously.  It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case.

    + +

     

    +

    Example 1:

    + +
    +Input: S = "abcd", indexes = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
    +Output: "eeebffff"
    +Explanation:
    +"a" starts at index 0 in S, so it's replaced by "eee".
    +"cd" starts at index 2 in S, so it's replaced by "ffff".
    +
    + +

    Example 2:

    + +
    +Input: S = "abcd", indexes = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"]
    +Output: "eeecd"
    +Explanation:
    +"ab" starts at index 0 in S, so it's replaced by "eee".
    +"ec" doesn't starts at index 2 in the original S, so we do nothing.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= S.length <= 1000
    • +
    • S consists of only lowercase English letters.
    • +
    • 0 <= indexes.length <= 100
    • +
    • 0 <= indexes[i] < S.length
    • +
    • sources.length == indexes.length
    • +
    • targets.length == indexes.length
    • +
    • 1 <= sources[i].length, targets[i].length <= 50
    • +
    • sources[i] and targets[i] consist of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0834.Sum of Distances in Tree/README_EN.md b/assets/0800-0899/0834.Sum of Distances in Tree/README_EN.md new file mode 100644 index 00000000..d94136a8 --- /dev/null +++ b/assets/0800-0899/0834.Sum of Distances in Tree/README_EN.md @@ -0,0 +1,77 @@ +# [834. Sum of Distances in Tree](https://leetcode.com/problems/sum-of-distances-in-tree) + + + +## Description + +

    An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given.

    + + + +

    The ith edge connects nodes edges[i][0] and edges[i][1] together.

    + + + +

    Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes.

    + + + +

    Example 1:

    + + + +
    +
    +Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
    +
    +Output: [8,12,6,10,10,10]
    +
    +Explanation: 
    +
    +Here is a diagram of the given tree:
    +
    +  0
    +
    + / \
    +
    +1   2
    +
    +   /|\
    +
    +  3 4 5
    +
    +We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
    +
    +equals 1 + 1 + 2 + 2 + 2 = 8.  Hence, answer[0] = 8, and so on.
    +
    +
    + + + +

    Note: 1 <= N <= 10000

    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0835.Image Overlap/README_EN.md b/assets/0800-0899/0835.Image Overlap/README_EN.md new file mode 100644 index 00000000..1d58e5dd --- /dev/null +++ b/assets/0800-0899/0835.Image Overlap/README_EN.md @@ -0,0 +1,77 @@ +# [835. Image Overlap](https://leetcode.com/problems/image-overlap) + + + +## Description + +

    You are given two images img1 and img2 both of size n x n, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)

    + +

    We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image.  After, the overlap of this translation is the number of positions that have a 1 in both images.

    + +

    (Note also that a translation does not include any kind of rotation.)

    + +

    What is the largest possible overlap?

    + +

     

    +

    Example 1:

    + +
    +Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
    +Output: 3
    +Explanation: We slide img1 to right by 1 unit and down by 1 unit.
    +
    +The number of positions that have a 1 in both images is 3. (Shown in red)
    +
    +
    + +

    Example 2:

    + +
    +Input: img1 = [[1]], img2 = [[1]]
    +Output: 1
    +
    + +

    Example 3:

    + +
    +Input: img1 = [[0]], img2 = [[0]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == img1.length
    • +
    • n == img1[i].length
    • +
    • n == img2.length
    • +
    • n == img2[i].length
    • +
    • 1 <= n <= 30
    • +
    • img1[i][j] is 0 or 1.
    • +
    • img2[i][j] is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0835.Image Overlap/images/overlap1.jpg b/assets/0800-0899/0835.Image Overlap/images/overlap1.jpg new file mode 100644 index 00000000..86485c26 Binary files /dev/null and b/assets/0800-0899/0835.Image Overlap/images/overlap1.jpg differ diff --git a/assets/0800-0899/0835.Image Overlap/images/overlap_step1.jpg b/assets/0800-0899/0835.Image Overlap/images/overlap_step1.jpg new file mode 100644 index 00000000..3d6e2412 Binary files /dev/null and b/assets/0800-0899/0835.Image Overlap/images/overlap_step1.jpg differ diff --git a/assets/0800-0899/0835.Image Overlap/images/overlap_step2.jpg b/assets/0800-0899/0835.Image Overlap/images/overlap_step2.jpg new file mode 100644 index 00000000..7df85318 Binary files /dev/null and b/assets/0800-0899/0835.Image Overlap/images/overlap_step2.jpg differ diff --git a/assets/0800-0899/0836.Rectangle Overlap/README_EN.md b/assets/0800-0899/0836.Rectangle Overlap/README_EN.md new file mode 100644 index 00000000..5cb5d57d --- /dev/null +++ b/assets/0800-0899/0836.Rectangle Overlap/README_EN.md @@ -0,0 +1,58 @@ +# [836. Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap) + + + +## Description + +

    An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.

    + +

    Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.

    + +

    Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.

    + +

     

    +

    Example 1:

    +
    Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
    +Output: true
    +

    Example 2:

    +
    Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
    +Output: false
    +

    Example 3:

    +
    Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
    +Output: false
    +
    +

     

    +

    Constraints:

    + +
      +
    • rect1.length == 4
    • +
    • rect2.length == 4
    • +
    • -109 <= rec1[i], rec2[i] <= 109
    • +
    • rec1[0] <= rec1[2] and rec1[1] <= rec1[3]
    • +
    • rec2[0] <= rec2[2] and rec2[1] <= rec2[3]
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0837.New 21 Game/README_EN.md b/assets/0800-0899/0837.New 21 Game/README_EN.md new file mode 100644 index 00000000..4b290eb1 --- /dev/null +++ b/assets/0800-0899/0837.New 21 Game/README_EN.md @@ -0,0 +1,100 @@ +# [837. New 21 Game](https://leetcode.com/problems/new-21-game) + + + +## Description + +

    Alice plays the following game, loosely based on the card game "21".

    + + + +

    Alice starts with 0 points, and draws numbers while she has less than K points.  During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer.  Each draw is independent and the outcomes have equal probabilities.

    + + + +

    Alice stops drawing numbers when she gets K or more points.  What is the probability that she has N or less points?

    + + + +

    Example 1:

    + + + +
    +
    +Input: N = 10, K = 1, W = 10
    +
    +Output: 1.00000
    +
    +Explanation:  Alice gets a single card, then stops.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: N = 6, K = 1, W = 10
    +
    +Output: 0.60000
    +
    +Explanation:  Alice gets a single card, then stops.
    +
    +In 6 out of W = 10 possibilities, she is at or below N = 6 points.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: N = 21, K = 17, W = 10
    +
    +Output: 0.73278
    + + + +

    Note:

    + + + +
      +
    1. 0 <= K <= N <= 10000
    2. +
    3. 1 <= W <= 10000
    4. +
    5. Answers will be accepted as correct if they are within 10^-5 of the correct answer.
    6. +
    7. The judging time limit has been reduced for this question.
    8. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0838.Push Dominoes/README_EN.md b/assets/0800-0899/0838.Push Dominoes/README_EN.md new file mode 100644 index 00000000..13357b9e --- /dev/null +++ b/assets/0800-0899/0838.Push Dominoes/README_EN.md @@ -0,0 +1,106 @@ +# [838. Push Dominoes](https://leetcode.com/problems/push-dominoes) + + + +## Description + +

    There are N dominoes in a line, and we place each domino vertically upright.

    + + + +

    In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

    + + + +

    + + + +

    After each second, each domino that is falling to the left pushes the adjacent domino on the left.

    + + + +

    Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.

    + + + +

    When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.

    + + + +

    For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.

    + + + +

    Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.

    + + + +

    Return a string representing the final state. 

    + + + +

    Example 1:

    + + + +
    +
    +Input: ".L.R...LR..L.."
    +
    +Output: "LL.RR.LLRRLL.."
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: "RR.L"
    +
    +Output: "RR.L"
    +
    +Explanation: The first domino expends no additional force on the second domino.
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 0 <= N <= 10^5
    2. +
    3. String dominoes contains only 'L', 'R' and '.'
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0838.Push Dominoes/images/domino.png b/assets/0800-0899/0838.Push Dominoes/images/domino.png new file mode 100644 index 00000000..78e3a36b Binary files /dev/null and b/assets/0800-0899/0838.Push Dominoes/images/domino.png differ diff --git a/assets/0800-0899/0839.Similar String Groups/README_EN.md b/assets/0800-0899/0839.Similar String Groups/README_EN.md new file mode 100644 index 00000000..18d26382 --- /dev/null +++ b/assets/0800-0899/0839.Similar String Groups/README_EN.md @@ -0,0 +1,63 @@ +# [839. Similar String Groups](https://leetcode.com/problems/similar-string-groups) + + + +## Description + +

    Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal.

    + +

    For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".

    + +

    Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}.  Notice that "tars" and "arts" are in the same group even though they are not similar.  Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.

    + +

    We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?

    + +

     

    +

    Example 1:

    + +
    +Input: strs = ["tars","rats","arts","star"]
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: strs = ["omv","ovm"]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= strs.length <= 300
    • +
    • 1 <= strs[i].length <= 300
    • +
    • strs[i] consists of lowercase letters only.
    • +
    • All words in strs have the same length and are anagrams of each other.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0840.Magic Squares In Grid/README_EN.md b/assets/0800-0899/0840.Magic Squares In Grid/README_EN.md new file mode 100644 index 00000000..c6f0c49a --- /dev/null +++ b/assets/0800-0899/0840.Magic Squares In Grid/README_EN.md @@ -0,0 +1,79 @@ +# [840. Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid) + + + +## Description + +

    A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

    + +

    Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there?  (Each subgrid is contiguous).

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
    +Output: 1
    +Explanation: 
    +The following subgrid is a 3 x 3 magic square:
    +
    +while this one is not:
    +
    +In total, there is only one magic square inside the given grid.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[8]]
    +Output: 0
    +
    + +

    Example 3:

    + +
    +Input: grid = [[4,4],[3,3]]
    +Output: 0
    +
    + +

    Example 4:

    + +
    +Input: grid = [[4,7,8],[9,5,1],[2,3,6]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • row == grid.length
    • +
    • col == grid[i].length
    • +
    • 1 <= row, col <= 10
    • +
    • 0 <= grid[i][j] <= 15
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0840.Magic Squares In Grid/images/magic_invalid.jpg b/assets/0800-0899/0840.Magic Squares In Grid/images/magic_invalid.jpg new file mode 100644 index 00000000..483113fd Binary files /dev/null and b/assets/0800-0899/0840.Magic Squares In Grid/images/magic_invalid.jpg differ diff --git a/assets/0800-0899/0840.Magic Squares In Grid/images/magic_main.jpg b/assets/0800-0899/0840.Magic Squares In Grid/images/magic_main.jpg new file mode 100644 index 00000000..826f5406 Binary files /dev/null and b/assets/0800-0899/0840.Magic Squares In Grid/images/magic_main.jpg differ diff --git a/assets/0800-0899/0840.Magic Squares In Grid/images/magic_valid.jpg b/assets/0800-0899/0840.Magic Squares In Grid/images/magic_valid.jpg new file mode 100644 index 00000000..040ec983 Binary files /dev/null and b/assets/0800-0899/0840.Magic Squares In Grid/images/magic_valid.jpg differ diff --git a/assets/0800-0899/0841.Keys and Rooms/README_EN.md b/assets/0800-0899/0841.Keys and Rooms/README_EN.md new file mode 100644 index 00000000..814146a8 --- /dev/null +++ b/assets/0800-0899/0841.Keys and Rooms/README_EN.md @@ -0,0 +1,107 @@ +# [841. Keys and Rooms](https://leetcode.com/problems/keys-and-rooms) + + + +## Description + +

    There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. 

    + + + +

    Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j] = v opens the room with number v.

    + + + +

    Initially, all the rooms start locked (except for room 0). 

    + + + +

    You can walk back and forth between rooms freely.

    + + + +

    Return true if and only if you can enter every room.

    + + + +
      + +
    + + + +

    Example 1:

    + + + +
    +
    +Input: [[1],[2],[3],[]]
    +
    +Output: true
    +
    +Explanation:  
    +
    +We start in room 0, and pick up key 1.
    +
    +We then go to room 1, and pick up key 2.
    +
    +We then go to room 2, and pick up key 3.
    +
    +We then go to room 3.  Since we were able to go to every room, we return true.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: [[1,3],[3,0,1],[2],[0]]
    +
    +Output: false
    +
    +Explanation: We can't enter the room with number 2.
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= rooms.length <= 1000
    2. +
    3. 0 <= rooms[i].length <= 1000
    4. +
    5. The number of keys in all rooms combined is at most 3000.
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md b/assets/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md new file mode 100644 index 00000000..92cf40d9 --- /dev/null +++ b/assets/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md @@ -0,0 +1,140 @@ +# [842. Split Array into Fibonacci Sequence](https://leetcode.com/problems/split-array-into-fibonacci-sequence) + + + +## Description + +

    Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579].

    + + + +

    Formally, a Fibonacci-like sequence is a list F of non-negative integers such that:

    + + + +
      +
    • 0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type);
    • +
    • F.length >= 3;
    • +
    • and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2.
    • +
    + + + +

    Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.

    + + + +

    Return any Fibonacci-like sequence split from S, or return [] if it cannot be done.

    + + + +

    Example 1:

    + + + +
    +
    +Input: "123456579"
    +
    +Output: [123,456,579]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: "11235813"
    +
    +Output: [1,1,2,3,5,8,13]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: "112358130"
    +
    +Output: []
    +
    +Explanation: The task is impossible.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: "0123"
    +
    +Output: []
    +
    +Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: "1101111"
    +
    +Output: [110, 1, 111]
    +
    +Explanation: The output [11, 0, 11, 11] would also be accepted.
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length <= 200
    2. +
    3. S contains only digits.
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0843.Guess the Word/README_EN.md b/assets/0800-0899/0843.Guess the Word/README_EN.md new file mode 100644 index 00000000..ac3bd7f6 --- /dev/null +++ b/assets/0800-0899/0843.Guess the Word/README_EN.md @@ -0,0 +1,74 @@ +# [843. Guess the Word](https://leetcode.com/problems/guess-the-word) + + + +## Description + +

    This is an interactive problem.

    + +

    You are given an array of unique strings wordlist where wordlist[i] is 6 letters long, and one word in this list is chosen as secret.

    + +

    You may call Master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters.

    + +

    This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead.

    + +

    For each test case, you have exactly 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or fewer calls to Master.guess and at least one of these guesses was secret, then you pass the test case.

    + +

     

    +

    Example 1:

    + +
    +Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"], numguesses = 10
    +Output: You guessed the secret word correctly.
    +Explanation:
    +master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.
    +master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.
    +master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.
    +master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.
    +master.guess("abcczz") returns 4, because "abcczz" has 4 matches.
    +We made 5 calls to master.guess and one of them was the secret, so we pass the test case.
    +
    + +

    Example 2:

    + +
    +Input: secret = "hamada", wordlist = ["hamada","khaled"], numguesses = 10
    +Output: You guessed the secret word correctly.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= wordlist.length <= 100
    • +
    • wordlist[i].length == 6
    • +
    • wordlist[i] consist of lowercase English letters.
    • +
    • All the strings of wordlist are unique.
    • +
    • secret exists in wordlist.
    • +
    • numguesses == 10
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0844.Backspace String Compare/README_EN.md b/assets/0800-0899/0844.Backspace String Compare/README_EN.md new file mode 100644 index 00000000..7192446a --- /dev/null +++ b/assets/0800-0899/0844.Backspace String Compare/README_EN.md @@ -0,0 +1,78 @@ +# [844. Backspace String Compare](https://leetcode.com/problems/backspace-string-compare) + + + +## Description + +

    Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.

    + +

    Note that after backspacing an empty text, the text will continue empty.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "ab#c", t = "ad#c"
    +Output: true
    +Explanation: Both s and t become "ac".
    +
    + +

    Example 2:

    + +
    +Input: s = "ab##", t = "c#d#"
    +Output: true
    +Explanation: Both s and t become "".
    +
    + +

    Example 3:

    + +
    +Input: s = "a##c", t = "#a#c"
    +Output: true
    +Explanation: Both s and t become "c".
    +
    + +

    Example 4:

    + +
    +Input: s = "a#c", t = "b"
    +Output: false
    +Explanation: s becomes "c" while t becomes "b".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length, t.length <= 200
    • +
    • s and t only contain lowercase letters and '#' characters.
    • +
    + +

     

    +

    Follow up: Can you solve it in O(n) time and O(1) space?

    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0845.Longest Mountain in Array/README_EN.md b/assets/0800-0899/0845.Longest Mountain in Array/README_EN.md new file mode 100644 index 00000000..fcf061cb --- /dev/null +++ b/assets/0800-0899/0845.Longest Mountain in Array/README_EN.md @@ -0,0 +1,77 @@ +# [845. Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array) + + + +## Description + +

    You may recall that an array arr is a mountain array if and only if:

    + +
      +
    • arr.length >= 3
    • +
    • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: +
        +
      • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
      • +
      • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

    Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [2,1,4,7,3,2,5]
    +Output: 5
    +Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
    +
    + +

    Example 2:

    + +
    +Input: arr = [2,2,2]
    +Output: 0
    +Explanation: There is no mountain.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 0 <= arr[i] <= 104
    • +
    + +

     

    +

    Follow up:

    + +
      +
    • Can you solve it using only one pass?
    • +
    • Can you solve it in O(1) space?
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0846.Hand of Straights/README_EN.md b/assets/0800-0899/0846.Hand of Straights/README_EN.md new file mode 100644 index 00000000..ac2c4840 --- /dev/null +++ b/assets/0800-0899/0846.Hand of Straights/README_EN.md @@ -0,0 +1,65 @@ +# [846. Hand of Straights](https://leetcode.com/problems/hand-of-straights) + + + +## Description + +

    Alice has a hand of cards, given as an array of integers.

    + +

    Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.

    + +

    Return true if and only if she can.

    + +

    Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/

    + +

     

    +

    Example 1:

    + +
    +Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
    +Output: true
    +Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
    +
    + +

    Example 2:

    + +
    +Input: hand = [1,2,3,4,5], W = 4
    +Output: false
    +Explanation: Alice's hand can't be rearranged into groups of 4.
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= hand.length <= 10000
    • +
    • 0 <= hand[i] <= 10^9
    • +
    • 1 <= W <= hand.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md b/assets/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md new file mode 100644 index 00000000..a697e28e --- /dev/null +++ b/assets/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md @@ -0,0 +1,96 @@ +# [847. Shortest Path Visiting All Nodes](https://leetcode.com/problems/shortest-path-visiting-all-nodes) + + + +## Description + +

    An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph.

    + + + +

    graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j are connected.

    + + + +

    Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

    + + + +

     

    + + + +
      + +
    + + + +

    Example 1:

    + + + +
    +
    +Input: [[1,2,3],[0],[0],[0]]
    +
    +Output: 4
    +
    +Explanation: One possible path is [1,0,2,0,3]
    + + + +

    Example 2:

    + + + +
    +
    +Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
    +
    +Output: 4
    +
    +Explanation: One possible path is [0,1,4,2,3]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= graph.length <= 12
    2. +
    3. 0 <= graph[i].length < graph.length
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0848.Shifting Letters/README_EN.md b/assets/0800-0899/0848.Shifting Letters/README_EN.md new file mode 100644 index 00000000..9da67399 --- /dev/null +++ b/assets/0800-0899/0848.Shifting Letters/README_EN.md @@ -0,0 +1,84 @@ +# [848. Shifting Letters](https://leetcode.com/problems/shifting-letters) + + + +## Description + +

    We have a string S of lowercase letters, and an integer array shifts.

    + + + +

    Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). 

    + + + +

    For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.

    + + + +

    Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times.

    + + + +

    Return the final string after all such shifts to S are applied.

    + + + +

    Example 1:

    + + + +
    +
    +Input: S = "abc", shifts = [3,5,9]
    +
    +Output: "rpl"
    +
    +Explanation: 
    +
    +We start with "abc".
    +
    +After shifting the first 1 letters of S by 3, we have "dbc".
    +
    +After shifting the first 2 letters of S by 5, we have "igc".
    +
    +After shifting the first 3 letters of S by 9, we have "rpl", the answer.
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length = shifts.length <= 20000
    2. +
    3. 0 <= shifts[i] <= 10 ^ 9
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md b/assets/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md new file mode 100644 index 00000000..b422598b --- /dev/null +++ b/assets/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md @@ -0,0 +1,77 @@ +# [849. Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person) + + + +## Description + +

    You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).

    + +

    There is at least one empty seat, and at least one person sitting.

    + +

    Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. 

    + +

    Return that maximum distance to the closest person.

    + +

     

    +

    Example 1:

    + +
    +Input: seats = [1,0,0,0,1,0,1]
    +Output: 2
    +Explanation: 
    +If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
    +If Alex sits in any other open seat, the closest person has distance 1.
    +Thus, the maximum distance to the closest person is 2.
    +
    + +

    Example 2:

    + +
    +Input: seats = [1,0,0,0]
    +Output: 3
    +Explanation: 
    +If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
    +This is the maximum distance possible, so the answer is 3.
    +
    + +

    Example 3:

    + +
    +Input: seats = [0,1]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= seats.length <= 2 * 104
    • +
    • seats[i] is 0 or 1.
    • +
    • At least one seat is empty.
    • +
    • At least one seat is occupied.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0849.Maximize Distance to Closest Person/images/distance.jpg b/assets/0800-0899/0849.Maximize Distance to Closest Person/images/distance.jpg new file mode 100644 index 00000000..6531c509 Binary files /dev/null and b/assets/0800-0899/0849.Maximize Distance to Closest Person/images/distance.jpg differ diff --git a/assets/0800-0899/0850.Rectangle Area II/README_EN.md b/assets/0800-0899/0850.Rectangle Area II/README_EN.md new file mode 100644 index 00000000..8d09aec3 --- /dev/null +++ b/assets/0800-0899/0850.Rectangle Area II/README_EN.md @@ -0,0 +1,61 @@ +# [850. Rectangle Area II](https://leetcode.com/problems/rectangle-area-ii) + + + +## Description + +

    We are given a list of (axis-aligned) rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] , where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner of the ith rectangle.

    + +

    Find the total area covered by all rectangles in the plane. Since the answer may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
    +Output: 6
    +Explanation: As illustrated in the picture.
    +
    + +

    Example 2:

    + +
    +Input: rectangles = [[0,0,1000000000,1000000000]]
    +Output: 49
    +Explanation: The answer is 1018 modulo (109 + 7), which is (109)2 = (-7)2 = 49.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= rectangles.length <= 200
    • +
    • rectanges[i].length = 4
    • +
    • 0 <= rectangles[i][j] <= 109
    • +
    • The total area covered by all rectangles will never exceed 263 - 1 and thus will fit in a 64-bit signed integer.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0850.Rectangle Area II/images/rectangle_area_ii_pic.png b/assets/0800-0899/0850.Rectangle Area II/images/rectangle_area_ii_pic.png new file mode 100644 index 00000000..b572f10c Binary files /dev/null and b/assets/0800-0899/0850.Rectangle Area II/images/rectangle_area_ii_pic.png differ diff --git a/assets/0800-0899/0851.Loud and Rich/README_EN.md b/assets/0800-0899/0851.Loud and Rich/README_EN.md new file mode 100644 index 00000000..cf15023b --- /dev/null +++ b/assets/0800-0899/0851.Loud and Rich/README_EN.md @@ -0,0 +1,111 @@ +# [851. Loud and Rich](https://leetcode.com/problems/loud-and-rich) + + + +## Description + +

    In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness.

    + + + +

    For convenience, we'll call the person with label x, simply "person x".

    + + + +

    We'll say that richer[i] = [x, y] if person x definitely has more money than person y.  Note that richer may only be a subset of valid observations.

    + + + +

    Also, we'll say quiet[x] = q if person x has quietness q.

    + + + +

    Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
    +
    +Output: [5,5,2,5,4,5,6,7]
    +
    +Explanation: 
    +
    +answer[0] = 5.
    +
    +Person 5 has more money than 3, which has more money than 1, which has more money than 0.
    +
    +The only person who is quieter (has lower quiet[x]) is person 7, but
    +
    +it isn't clear if they have more money than person 0.
    +
    +
    +
    +answer[7] = 7.
    +
    +Among all people that definitely have equal to or more money than person 7
    +
    +(which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x])
    +
    +is person 7.
    +
    +
    +
    +The other answers can be filled out with similar reasoning.
    +
    +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= quiet.length = N <= 500
    2. +
    3. 0 <= quiet[i] < N, all quiet[i] are different.
    4. +
    5. 0 <= richer.length <= N * (N-1) / 2
    6. +
    7. 0 <= richer[i][j] < N
    8. +
    9. richer[i][0] != richer[i][1]
    10. +
    11. richer[i]'s are all different.
    12. +
    13. The observations in richer are all logically consistent.
    14. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md b/assets/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md new file mode 100644 index 00000000..d4c8fbdd --- /dev/null +++ b/assets/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md @@ -0,0 +1,158 @@ +# [852. Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array) + + + +## Description + +

    Let's call an array arr a mountain if the following properties hold:

    + +
      +
    • arr.length >= 3
    • +
    • There exists some i with 0 < i < arr.length - 1 such that: +
        +
      • arr[0] < arr[1] < ... arr[i-1] < arr[i]
      • +
      • arr[i] > arr[i+1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

    Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

    + +

     

    +

    Example 1:

    +
    Input: arr = [0,1,0]
    +Output: 1
    +

    Example 2:

    +
    Input: arr = [0,2,1,0]
    +Output: 1
    +

    Example 3:

    +
    Input: arr = [0,10,5,2]
    +Output: 1
    +

    Example 4:

    +
    Input: arr = [3,4,5,1]
    +Output: 2
    +

    Example 5:

    +
    Input: arr = [24,69,100,99,79,78,67,36,26,19]
    +Output: 2
    +
    +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 104
    • +
    • 0 <= arr[i] <= 106
    • +
    • arr is guaranteed to be a mountain array.
    • +
    + +

     

    +Follow up: Finding the O(n) is straightforward, could you find an O(log(n)) solution? + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def peakIndexInMountainArray(self, arr: List[int]) -> int: + n = len(arr) + left, right = 1, n - 2 + while left < right: + mid = (left + right) // 2 + if arr[mid] < arr[mid + 1]: + left = mid + 1 + else: + right = mid + return right +``` + +### **Java** + +```java +class Solution { + public int peakIndexInMountainArray(int[] arr) { + int n = arr.length; + int left = 1, right = n - 2; + while (left < right) { + int mid = left + (right - left) / 2; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } +} +``` + +### **Go** + +```go +func peakIndexInMountainArray(arr []int) int { + n := len(arr) + left, right := 1, n-2 + for left < right { + mid := left + (right-left)/2 + if arr[mid] < arr[mid+1] { + left = mid + 1 + } else { + right = mid + } + } + return right +} +``` + +### **C++** + +```cpp +class Solution { +public: + int peakIndexInMountainArray(vector& arr) { + int left = 1, right = arr.size() - 2; + while (left < right) { + int mid = left + right >> 1; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @return {number} + */ +var peakIndexInMountainArray = function(arr) { + let left = 1; + let right = arr.length - 2; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0853.Car Fleet/README_EN.md b/assets/0800-0899/0853.Car Fleet/README_EN.md new file mode 100644 index 00000000..398a7d4f --- /dev/null +++ b/assets/0800-0899/0853.Car Fleet/README_EN.md @@ -0,0 +1,101 @@ +# [853. Car Fleet](https://leetcode.com/problems/car-fleet) + + + +## Description + +

    N cars are going to the same destination along a one lane road.  The destination is target miles away.

    + + + +

    Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road.

    + + + +

    A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed.

    + + + +

    The distance between these two cars is ignored - they are assumed to have the same position.

    + + + +

    A car fleet is some non-empty set of cars driving at the same position and same speed.  Note that a single car is also a car fleet.

    + + + +

    If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.

    + + + +


    + +How many car fleets will arrive at the destination?

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
    +
    +Output: 3
    +
    +Explanation:
    +
    +The cars starting at 10 and 8 become a fleet, meeting each other at 12.
    +
    +The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself.
    +
    +The cars starting at 5 and 3 become a fleet, meeting each other at 6.
    +
    +Note that no other cars meet these fleets before the destination, so the answer is 3.
    +
    +
    + + + +


    + +Note:

    + + + +
      +
    1. 0 <= N <= 10 ^ 4
    2. +
    3. 0 < target <= 10 ^ 6
    4. +
    5. 0 < speed[i] <= 10 ^ 6
    6. +
    7. 0 <= position[i] < target
    8. +
    9. All initial positions are different.
    10. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0854.K-Similar Strings/README_EN.md b/assets/0800-0899/0854.K-Similar Strings/README_EN.md new file mode 100644 index 00000000..d173b61d --- /dev/null +++ b/assets/0800-0899/0854.K-Similar Strings/README_EN.md @@ -0,0 +1,58 @@ +# [854. K-Similar Strings](https://leetcode.com/problems/k-similar-strings) + + + +## Description + +

    Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.

    + +

    Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.

    + +

     

    +

    Example 1:

    +
    Input: s1 = "ab", s2 = "ba"
    +Output: 1
    +

    Example 2:

    +
    Input: s1 = "abc", s2 = "bca"
    +Output: 2
    +

    Example 3:

    +
    Input: s1 = "abac", s2 = "baca"
    +Output: 2
    +

    Example 4:

    +
    Input: s1 = "aabc", s2 = "abca"
    +Output: 2
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= s1.length <= 20
    • +
    • s2.length == s1.length
    • +
    • s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.
    • +
    • s2 is an anagram of s1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0855.Exam Room/README_EN.md b/assets/0800-0899/0855.Exam Room/README_EN.md new file mode 100644 index 00000000..a89e9707 --- /dev/null +++ b/assets/0800-0899/0855.Exam Room/README_EN.md @@ -0,0 +1,91 @@ +# [855. Exam Room](https://leetcode.com/problems/exam-room) + + + +## Description + +

    In an exam room, there are N seats in a single row, numbered 0, 1, 2, ..., N-1.

    + + + +

    When a student enters the room, they must sit in the seat that maximizes the distance to the closest person.  If there are multiple such seats, they sit in the seat with the lowest number.  (Also, if no one is in the room, then the student sits at seat number 0.)

    + + + +

    Return a class ExamRoom(int N) that exposes two functions: ExamRoom.seat() returning an int representing what seat the student sat in, and ExamRoom.leave(int p) representing that the student in seat number p now leaves the room.  It is guaranteed that any calls to ExamRoom.leave(p) have a student sitting in seat p.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]
    +
    +Output: [null,0,9,4,2,null,5]
    +
    +Explanation:
    +
    +ExamRoom(10) -> null
    +
    +seat() -> 0, no one is in the room, then the student sits at seat number 0.
    +
    +seat() -> 9, the student sits at the last seat number 9.
    +
    +seat() -> 4, the student sits at the last seat number 4.
    +
    +seat() -> 2, the student sits at the last seat number 2.
    +
    +leave(4) -> null
    +
    +seat() -> 5, the student sits at the last seat number 5.
    +
    +
    + + + +

    ​​​​​​​

    + + + +

    Note:

    + + + +
      +
    1. 1 <= N <= 10^9
    2. +
    3. ExamRoom.seat() and ExamRoom.leave() will be called at most 10^4 times across all test cases.
    4. +
    5. Calls to ExamRoom.leave(p) are guaranteed to have a student currently sitting in seat number p.
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0856.Score of Parentheses/README_EN.md b/assets/0800-0899/0856.Score of Parentheses/README_EN.md new file mode 100644 index 00000000..a1aca8c9 --- /dev/null +++ b/assets/0800-0899/0856.Score of Parentheses/README_EN.md @@ -0,0 +1,132 @@ +# [856. Score of Parentheses](https://leetcode.com/problems/score-of-parentheses) + + + +## Description + +

    Given a balanced parentheses string S, compute the score of the string based on the following rule:

    + + + +
      +
    • () has score 1
    • +
    • AB has score A + B, where A and B are balanced parentheses strings.
    • +
    • (A) has score 2 * A, where A is a balanced parentheses string.
    • +
    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: "()"
    +
    +Output: 1
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "(())"
    +
    +Output: 2
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "()()"
    +
    +Output: 2
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: "(()(()))"
    +
    +Output: 6
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. S is a balanced parentheses string, containing only ( and ).
    2. +
    3. 2 <= S.length <= 50
    4. +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md b/assets/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md new file mode 100644 index 00000000..5f02986e --- /dev/null +++ b/assets/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md @@ -0,0 +1,115 @@ +# [857. Minimum Cost to Hire K Workers](https://leetcode.com/problems/minimum-cost-to-hire-k-workers) + + + +## Description + +

    There are N workers.  The i-th worker has a quality[i] and a minimum wage expectation wage[i].

    + + + +

    Now we want to hire exactly K workers to form a paid group.  When hiring a group of K workers, we must pay them according to the following rules:

    + + + +
      +
    1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
    2. +
    3. Every worker in the paid group must be paid at least their minimum wage expectation.
    4. +
    + + + +

    Return the least amount of money needed to form a paid group satisfying the above conditions.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: quality = [10,20,5], wage = [70,50,30], K = 2
    +
    +Output: 105.00000
    +
    +Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
    +
    +Output: 30.66667
    +
    +Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately. 
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= K <= N <= 10000, where N = quality.length = wage.length
    2. +
    3. 1 <= quality[i] <= 10000
    4. +
    5. 1 <= wage[i] <= 10000
    6. +
    7. Answers within 10^-5 of the correct answer will be considered correct.
    8. +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0858.Mirror Reflection/README_EN.md b/assets/0800-0899/0858.Mirror Reflection/README_EN.md new file mode 100644 index 00000000..e63117f3 --- /dev/null +++ b/assets/0800-0899/0858.Mirror Reflection/README_EN.md @@ -0,0 +1,56 @@ +# [858. Mirror Reflection](https://leetcode.com/problems/mirror-reflection) + + + +## Description + +

    There is a special square room with mirrors on each of the four walls.  Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.

    + +

    The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.

    + +

    Return the number of the receptor that the ray meets first.  (It is guaranteed that the ray will meet a receptor eventually.)

    + +

     

    + +
    +

    Example 1:

    + +
    +Input: p = 2, q = 1
    +Output: 2
    +Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
    +
    +
    + +

    Note:

    + +
      +
    1. 1 <= p <= 1000
    2. +
    3. 0 <= q <= p
    4. +
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0858.Mirror Reflection/images/reflection.png b/assets/0800-0899/0858.Mirror Reflection/images/reflection.png new file mode 100644 index 00000000..8ad12374 Binary files /dev/null and b/assets/0800-0899/0858.Mirror Reflection/images/reflection.png differ diff --git a/assets/0800-0899/0859.Buddy Strings/README_EN.md b/assets/0800-0899/0859.Buddy Strings/README_EN.md new file mode 100644 index 00000000..92200cc6 --- /dev/null +++ b/assets/0800-0899/0859.Buddy Strings/README_EN.md @@ -0,0 +1,78 @@ +# [859. Buddy Strings](https://leetcode.com/problems/buddy-strings) + + + +## Description + +

    Given two strings a and b, return true if you can swap two letters in a so the result is equal to b, otherwise, return false.

    + +

    Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at a[i] and a[j].

    + +
      +
    • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: a = "ab", b = "ba"
    +Output: true
    +Explanation: You can swap a[0] = 'a' and a[1] = 'b' to get "ba", which is equal to b.
    +
    + +

    Example 2:

    + +
    +Input: a = "ab", b = "ab"
    +Output: false
    +Explanation: The only letters you can swap are a[0] = 'a' and a[1] = 'b', which results in "ba" != b.
    +
    + +

    Example 3:

    + +
    +Input: a = "aa", b = "aa"
    +Output: true
    +Explanation: You can swap a[0] = 'a' and a[1] = 'a' to get "aa", which is equal to b.
    +
    + +

    Example 4:

    + +
    +Input: a = "aaaaaaabc", b = "aaaaaaacb"
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= a.length, b.length <= 2 * 104
    • +
    • a and b consist of lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0860.Lemonade Change/README_EN.md b/assets/0800-0899/0860.Lemonade Change/README_EN.md new file mode 100644 index 00000000..b582c7db --- /dev/null +++ b/assets/0800-0899/0860.Lemonade Change/README_EN.md @@ -0,0 +1,160 @@ +# [860. Lemonade Change](https://leetcode.com/problems/lemonade-change) + + + +## Description + +

    At a lemonade stand, each lemonade costs $5

    + + + +

    Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).

    + + + +

    Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill.  You must provide the correct change to each customer, so that the net transaction is that the customer pays $5.

    + + + +

    Note that you don't have any change in hand at first.

    + + + +

    Return true if and only if you can provide every customer with correct change.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: [5,5,5,10,20]
    +
    +Output: true
    +
    +Explanation: 
    +
    +From the first 3 customers, we collect three $5 bills in order.
    +
    +From the fourth customer, we collect a $10 bill and give back a $5.
    +
    +From the fifth customer, we give a $10 bill and a $5 bill.
    +
    +Since all customers got correct change, we output true.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [5,5,10]
    +
    +Output: true
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: [10,10]
    +
    +Output: false
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: [5,5,10,10,20]
    +
    +Output: false
    +
    +Explanation: 
    +
    +From the first two customers in order, we collect two $5 bills.
    +
    +For the next two customers in order, we collect a $10 bill and give back a $5 bill.
    +
    +For the last customer, we can't give change of $15 back because we only have two $10 bills.
    +
    +Since not every customer received correct change, the answer is false.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 0 <= bills.length <= 10000
    • +
    • bills[i] will be either 5, 10, or 20.
    • +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0861.Score After Flipping Matrix/README_EN.md b/assets/0800-0899/0861.Score After Flipping Matrix/README_EN.md new file mode 100644 index 00000000..0d21db57 --- /dev/null +++ b/assets/0800-0899/0861.Score After Flipping Matrix/README_EN.md @@ -0,0 +1,93 @@ +# [861. Score After Flipping Matrix](https://leetcode.com/problems/score-after-flipping-matrix) + + + +## Description + +

    We have a two dimensional matrix A where each value is 0 or 1.

    + + + +

    A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.

    + + + +

    After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.

    + + + +

    Return the highest possible score.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
    +
    +Output: 39
    +
    +Explanation:
    +
    +Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
    +
    +0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 20
    2. +
    3. 1 <= A[0].length <= 20
    4. +
    5. A[i][j] is 0 or 1.
    6. +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md b/assets/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md new file mode 100644 index 00000000..669c259e --- /dev/null +++ b/assets/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md @@ -0,0 +1,117 @@ +# [862. Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k) + + + +## Description + +

    Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.

    + + + +

    If there is no non-empty subarray with sum at least K, return -1.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [1], K = 1
    +
    +Output: 1
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [1,2], K = 4
    +
    +Output: -1
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [2,-1,2], K = 3
    +
    +Output: 3
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. -10 ^ 5 <= A[i] <= 10 ^ 5
    4. +
    5. 1 <= K <= 10 ^ 9
    6. +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md b/assets/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md new file mode 100644 index 00000000..b27cf222 --- /dev/null +++ b/assets/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md @@ -0,0 +1,102 @@ +# [863. All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree) + + + +## Description + +

    We are given a binary tree (with root node root), a target node, and an integer value K.

    + + + +

    Return a list of the values of all nodes that have a distance K from the target node.  The answer can be returned in any order.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
    +
    +
    +
    +Output: [7,4,1]
    +
    +
    +
    +Explanation: 
    +
    +The nodes that are a distance 2 from the target node (with value 5)
    +
    +have values 7, 4, and 1.
    +
    +
    +
    +
    +
    +
    +
    +Note that the inputs "root" and "target" are actually TreeNodes.
    +
    +The descriptions of the inputs above are just serializations of these objects.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. The given tree is non-empty.
    2. +
    3. Each node in the tree has unique values 0 <= node.val <= 500.
    4. +
    5. The target node is a node in the tree.
    6. +
    7. 0 <= K <= 1000.
    8. +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0863.All Nodes Distance K in Binary Tree/images/sketch0.png b/assets/0800-0899/0863.All Nodes Distance K in Binary Tree/images/sketch0.png new file mode 100644 index 00000000..16fec75f Binary files /dev/null and b/assets/0800-0899/0863.All Nodes Distance K in Binary Tree/images/sketch0.png differ diff --git a/assets/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md b/assets/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md new file mode 100644 index 00000000..80c899fc --- /dev/null +++ b/assets/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md @@ -0,0 +1,102 @@ +# [864. Shortest Path to Get All Keys](https://leetcode.com/problems/shortest-path-to-get-all-keys) + + + +## Description + +

    We are given a 2-dimensional grid"." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A""B", ...) are locks.

    + + + +

    We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions.  We cannot walk outside the grid, or walk into a wall.  If we walk over a key, we pick it up.  We can't walk over a lock unless we have the corresponding key.

    + + + +

    For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid.  This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

    + + + +

    Return the lowest number of moves to acquire all keys.  If it's impossible, return -1.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: ["@.a.#","###.#","b.A.B"]
    +
    +Output: 8
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: ["@..aA","..B#.","....b"]
    +
    +Output: 6
    +
    +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= grid.length <= 30
    2. +
    3. 1 <= grid[0].length <= 30
    4. +
    5. grid[i][j] contains only '.', '#', '@''a'-'f' and 'A'-'F'
    6. +
    7. The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.
    8. +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md b/assets/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md new file mode 100644 index 00000000..04ceba8d --- /dev/null +++ b/assets/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md @@ -0,0 +1,115 @@ +# [865. Smallest Subtree with all the Deepest Nodes](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes) + + + +## Description + +

    Given the root of a binary tree, the depth of each node is the shortest distance to the root.

    + + + +

    Return the smallest subtree such that it contains all the deepest nodes in the original tree.

    + + + +

    A node is called the deepest if it has the largest depth possible among any node in the entire tree.

    + + + +

    The subtree of a node is tree consisting of that node, plus the set of all descendants of that node.

    + + + +

    Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4]
    +
    +Output: [2,7,4]
    +
    +Explanation: We return the node with value 2, colored in yellow in the diagram.
    +
    +The nodes coloured in blue are the deepest nodes of the tree.
    +
    +Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: root = [1]
    +
    +Output: [1]
    +
    +Explanation: The root is the deepest node in the tree.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: root = [0,1,3,null,2]
    +
    +Output: [2]
    +
    +Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree will be in the range [1, 500].
    • +
    • 0 <= Node.val <= 500
    • +
    • The values of the nodes in the tree are unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/images/sketch1.png b/assets/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/images/sketch1.png new file mode 100644 index 00000000..8bab5352 Binary files /dev/null and b/assets/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/images/sketch1.png differ diff --git a/assets/0800-0899/0866.Prime Palindrome/README_EN.md b/assets/0800-0899/0866.Prime Palindrome/README_EN.md new file mode 100644 index 00000000..a358902c --- /dev/null +++ b/assets/0800-0899/0866.Prime Palindrome/README_EN.md @@ -0,0 +1,120 @@ +# [866. Prime Palindrome](https://leetcode.com/problems/prime-palindrome) + + + +## Description + +

    Find the smallest prime palindrome greater than or equal to N.

    + + + +

    Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1. 

    + + + +

    For example, 2,3,5,7,11 and 13 are primes.

    + + + +

    Recall that a number is a palindrome if it reads the same from left to right as it does from right to left. 

    + + + +

    For example, 12321 is a palindrome.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: 6
    +
    +Output: 7
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: 8
    +
    +Output: 11
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: 13
    +
    +Output: 101
    + +
    + +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= N <= 10^8
    • +
    • The answer is guaranteed to exist and be less than 2 * 10^8.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0867.Transpose Matrix/README_EN.md b/assets/0800-0899/0867.Transpose Matrix/README_EN.md new file mode 100644 index 00000000..9debdef8 --- /dev/null +++ b/assets/0800-0899/0867.Transpose Matrix/README_EN.md @@ -0,0 +1,101 @@ +# [867. Transpose Matrix](https://leetcode.com/problems/transpose-matrix) + + + +## Description + +

    Given a 2D integer array matrix, return the transpose of matrix.

    + +

    The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

    + +

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
    +Output: [[1,4,7],[2,5,8],[3,6,9]]
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[1,2,3],[4,5,6]]
    +Output: [[1,4],[2,5],[3,6]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 1000
    • +
    • 1 <= m * n <= 105
    • +
    • -109 <= matrix[i][j] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def transpose(self, matrix: List[List[int]]) -> List[List[int]]: + m, n = len(matrix), len(matrix[0]) + res = [[0] * m for _ in range(n)] + for i in range(n): + for j in range(m): + res[i][j] = matrix[j][i] + return res +``` + +### **Java** + +```java +class Solution { + public int[][] transpose(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[][] res = new int[n][m]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < m; ++j) { + res[i][j] = matrix[j][i]; + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} matrix + * @return {number[][]} + */ +var transpose = function (matrix) { + const m = matrix.length, + n = matrix[0].length; + let res = []; + for (let i = 0; i < n; ++i) { + res[i] = []; + for (let j = 0; j < m; ++j) { + res[i][j] = matrix[j][i]; + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0867.Transpose Matrix/images/hint_transpose.png b/assets/0800-0899/0867.Transpose Matrix/images/hint_transpose.png new file mode 100644 index 00000000..b3a5c250 Binary files /dev/null and b/assets/0800-0899/0867.Transpose Matrix/images/hint_transpose.png differ diff --git a/assets/0800-0899/0868.Binary Gap/README_EN.md b/assets/0800-0899/0868.Binary Gap/README_EN.md new file mode 100644 index 00000000..4358a537 --- /dev/null +++ b/assets/0800-0899/0868.Binary Gap/README_EN.md @@ -0,0 +1,86 @@ +# [868. Binary Gap](https://leetcode.com/problems/binary-gap) + + + +## Description + +

    Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.

    + +

    Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 22
    +Output: 2
    +Explanation: 22 in binary is "10110".
    +The first adjacent pair of 1's is "10110" with a distance of 2.
    +The second adjacent pair of 1's is "10110" with a distance of 1.
    +The answer is the largest of these two distances, which is 2.
    +Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
    +
    + +

    Example 2:

    + +
    +Input: n = 5
    +Output: 2
    +Explanation: 5 in binary is "101".
    +
    + +

    Example 3:

    + +
    +Input: n = 6
    +Output: 1
    +Explanation: 6 in binary is "110".
    +
    + +

    Example 4:

    + +
    +Input: n = 8
    +Output: 0
    +Explanation: 8 in binary is "1000".
    +There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.
    +
    + +

    Example 5:

    + +
    +Input: n = 1
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0869.Reordered Power of 2/README_EN.md b/assets/0800-0899/0869.Reordered Power of 2/README_EN.md new file mode 100644 index 00000000..0ffd69b5 --- /dev/null +++ b/assets/0800-0899/0869.Reordered Power of 2/README_EN.md @@ -0,0 +1,77 @@ +# [869. Reordered Power of 2](https://leetcode.com/problems/reordered-power-of-2) + + + +## Description + +

    You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.

    + +

    Return true if and only if we can do this so that the resulting number is a power of two.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: true
    +
    + +

    Example 2:

    + +
    +Input: n = 10
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: n = 16
    +Output: true
    +
    + +

    Example 4:

    + +
    +Input: n = 24
    +Output: false
    +
    + +

    Example 5:

    + +
    +Input: n = 46
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0870.Advantage Shuffle/README_EN.md b/assets/0800-0899/0870.Advantage Shuffle/README_EN.md new file mode 100644 index 00000000..5e900a8a --- /dev/null +++ b/assets/0800-0899/0870.Advantage Shuffle/README_EN.md @@ -0,0 +1,93 @@ +# [870. Advantage Shuffle](https://leetcode.com/problems/advantage-shuffle) + + + +## Description + +

    Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i].

    + + + +

    Return any permutation of A that maximizes its advantage with respect to B.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [2,7,11,15], B = [1,10,4,11]
    +
    +Output: [2,11,7,15]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [12,24,8,32], B = [13,25,32,11]
    +
    +Output: [24,32,8,12]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length = B.length <= 10000
    2. +
    3. 0 <= A[i] <= 10^9
    4. +
    5. 0 <= B[i] <= 10^9
    6. +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md b/assets/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md new file mode 100644 index 00000000..9dd92c2a --- /dev/null +++ b/assets/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md @@ -0,0 +1,143 @@ +# [871. Minimum Number of Refueling Stops](https://leetcode.com/problems/minimum-number-of-refueling-stops) + + + +## Description + +

    A car travels from a starting position to a destination which is target miles east of the starting position.

    + + + +

    Along the way, there are gas stations.  Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.

    + + + +

    The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it.  It uses 1 liter of gas per 1 mile that it drives.

    + + + +

    When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

    + + + +

    What is the least number of refueling stops the car must make in order to reach its destination?  If it cannot reach the destination, return -1.

    + + + +

    Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there.  If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: target = 1, startFuel = 1, stations = []
    +
    +Output: 0
    +
    +Explanation: We can reach the target without refueling.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: target = 100, startFuel = 1, stations = [[10,100]]
    +
    +Output: -1
    +
    +Explanation: We can't reach the target (or even the first gas station).
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
    +
    +Output: 2
    +
    +Explanation: 
    +
    +We start with 10 liters of fuel.
    +
    +We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
    +
    +Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
    +
    +and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
    +
    +We made 2 refueling stops along the way, so we return 2.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= target, startFuel, stations[i][1] <= 10^9
    2. +
    3. 0 <= stations.length <= 500
    4. +
    5. 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
    6. +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0872.Leaf-Similar Trees/README_EN.md b/assets/0800-0899/0872.Leaf-Similar Trees/README_EN.md new file mode 100644 index 00000000..2c493719 --- /dev/null +++ b/assets/0800-0899/0872.Leaf-Similar Trees/README_EN.md @@ -0,0 +1,164 @@ +# [872. Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees) + + + +## Description + +

    Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

    + +

    + +

    For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

    + +

    Two binary trees are considered leaf-similar if their leaf value sequence is the same.

    + +

    Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

    + +

     

    +

    Example 1:

    + +
    +Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
    +Output: true
    +
    + +

    Example 2:

    + +
    +Input: root1 = [1], root2 = [1]
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: root1 = [1], root2 = [2]
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: root1 = [1,2], root2 = [2,2]
    +Output: true
    +
    + +

    Example 5:

    + +
    +Input: root1 = [1,2,3], root2 = [1,3,2]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in each tree will be in the range [1, 200].
    • +
    • Both of the given trees will have values in the range [0, 200].
    • +
    + + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: + def dfs(root, leaves): + if root is None: + return + if root.left is None and root.right is None: + leaves.append(root.val) + return + dfs(root.left, leaves) + dfs(root.right, leaves) + l1, l2 = [], [] + dfs(root1, l1) + dfs(root2, l2) + return l1 == l2 +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + List l1 = new ArrayList<>(); + List l2 = new ArrayList<>(); + dfs(root1, l1); + dfs(root2, l2); + return l1.equals(l2); + } + + private void dfs(TreeNode root, List leaves) { + if (root == null) return; + if (root.left == null && root.right == null) { + leaves.add(root.val); + return; + } + dfs(root.left, leaves); + dfs(root.right, leaves); + } +} +``` + +### **Go** + +```go +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + var l1, l2 []int + if root1 != nil { + dfs(root1, &l1) + } + if root2 != nil { + dfs(root2, &l2) + } + return reflect.DeepEqual(l1, l2) +} + +func dfs(root *TreeNode, leaves *[]int) { + if root.Left == nil && root.Right == nil { + *leaves = append(*leaves, root.Val) + } else { + if root.Left != nil { + dfs(root.Left, leaves) + } + if root.Right != nil { + dfs(root.Right, leaves) + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0872.Leaf-Similar Trees/images/tree.png b/assets/0800-0899/0872.Leaf-Similar Trees/images/tree.png new file mode 100644 index 00000000..011a3192 Binary files /dev/null and b/assets/0800-0899/0872.Leaf-Similar Trees/images/tree.png differ diff --git a/assets/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md b/assets/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md new file mode 100644 index 00000000..5e88266b --- /dev/null +++ b/assets/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md @@ -0,0 +1,64 @@ +# [873. Length of Longest Fibonacci Subsequence](https://leetcode.com/problems/length-of-longest-fibonacci-subsequence) + + + +## Description + +

    A sequence X1, X2, ..., Xn is Fibonacci-like if:

    + +
      +
    • n >= 3
    • +
    • Xi + Xi+1 = Xi+2 for all i + 2 <= n
    • +
    + +

    Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.

    + +

    A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,3,4,5,6,7,8]
    +Output: 5
    +Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
    + +

    Example 2:

    + +
    +Input: arr = [1,3,7,11,12,14,18]
    +Output: 3
    +Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 1000
    • +
    • 1 <= arr[i] < arr[i + 1] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0874.Walking Robot Simulation/README_EN.md b/assets/0800-0899/0874.Walking Robot Simulation/README_EN.md new file mode 100644 index 00000000..897922c7 --- /dev/null +++ b/assets/0800-0899/0874.Walking Robot Simulation/README_EN.md @@ -0,0 +1,91 @@ +# [874. Walking Robot Simulation](https://leetcode.com/problems/walking-robot-simulation) + + + +## Description + +

    A robot on an infinite XY-plane starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:

    + +
      +
    • -2: turn left 90 degrees,
    • +
    • -1: turn right 90 degrees, or
    • +
    • 1 <= k <= 9: move forward k units.
    • +
    + +

    Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi).

    + +

    If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)

    + +

    Return the maximum Euclidean distance that the robot will be from the origin squared (i.e. if the distance is 5, return 25).

    + +

    Note:

    + +
      +
    • North means +Y direction.
    • +
    • East means +X direction.
    • +
    • South means -Y direction.
    • +
    • West means -X direction.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: commands = [4,-1,3], obstacles = []
    +Output: 25
    +Explanation: The robot starts at (0, 0):
    +1. Move north 4 units to (0, 4).
    +2. Turn right.
    +3. Move east 3 units to (3, 4).
    +The furthest point away from the origin is (3, 4), which is 32 + 42 = 25 units away.
    +
    + +

    Example 2:

    + +
    +Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
    +Output: 65
    +Explanation: The robot starts at (0, 0):
    +1. Move north 4 units to (0, 4).
    +2. Turn right.
    +3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
    +4. Turn left.
    +5. Move north 4 units to (1, 8).
    +The furthest point away from the origin is (1, 8), which is 12 + 82 = 65 units away.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= commands.length <= 104
    • +
    • commands[i] is one of the values in the list [-2,-1,1,2,3,4,5,6,7,8,9].
    • +
    • 0 <= obstacles.length <= 104
    • +
    • -3 * 104 <= xi, yi <= 3 * 104
    • +
    • The answer is guaranteed to be less than 231.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0875.Koko Eating Bananas/README_EN.md b/assets/0800-0899/0875.Koko Eating Bananas/README_EN.md new file mode 100644 index 00000000..8e2fefc3 --- /dev/null +++ b/assets/0800-0899/0875.Koko Eating Bananas/README_EN.md @@ -0,0 +1,190 @@ +# [875. Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas) + + + +## Description + +

    Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

    + +

    Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

    + +

    Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

    + +

    Return the minimum integer k such that she can eat all the bananas within h hours.

    + +

     

    +

    Example 1:

    + +
    +Input: piles = [3,6,7,11], h = 8
    +Output: 4
    +
    + +

    Example 2:

    + +
    +Input: piles = [30,11,23,4,20], h = 5
    +Output: 30
    +
    + +

    Example 3:

    + +
    +Input: piles = [30,11,23,4,20], h = 6
    +Output: 23
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= piles.length <= 104
    • +
    • piles.length <= h <= 109
    • +
    • 1 <= piles[i] <= 109
    • +
    + + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: + left, right = 1, max(piles) + while left < right: + mid = (left + right) >> 1 + s = sum([(pile + mid - 1) // mid for pile in piles]) + if s <= h: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int minEatingSpeed(int[] piles, int h) { + int mx = 0; + for (int pile : piles) { + mx = Math.max(mx, pile); + } + int left = 1, right = mx; + while (left < right) { + int mid = (left + right) >>> 1; + int s = 0; + for (int pile : piles) { + s += (pile + mid - 1) / mid; + } + if (s <= h) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + int mx = 0; + for (auto pile : piles) { + mx = max(mx, pile); + } + int left = 1, right = mx; + while (left < right) { + int mid = left + right >> 1; + int s = 0; + for (auto pile : piles) { + s += (pile + mid - 1) / mid; + } + if (s <= h) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func minEatingSpeed(piles []int, h int) int { + mx := 0 + for _, pile := range piles { + mx = max(mx, pile) + } + left, right := 1, mx + for left < right { + mid := (left + right) >> 1 + s := 0 + for _, pile := range piles { + s += (pile + mid - 1) / mid + } + if s <= h { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int MinEatingSpeed(int[] piles, int h) { + int left = 1, right = piles.Max(); + while (left < right) + { + int mid = (left + right) >> 1; + int s = 0; + foreach (int pile in piles) + { + s += (pile + mid - 1) / mid; + } + if (s <= h) + { + right = mid; + } + else + { + left = mid + 1; + } + } + return left; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0876.Middle of the Linked List/README_EN.md b/assets/0800-0899/0876.Middle of the Linked List/README_EN.md new file mode 100644 index 00000000..2429a63e --- /dev/null +++ b/assets/0800-0899/0876.Middle of the Linked List/README_EN.md @@ -0,0 +1,178 @@ +# [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list) + + + +## Description + +

    Given a non-empty, singly linked list with head node head, return a middle node of linked list.

    + +

    If there are two middle nodes, return the second middle node.

    + +

     

    + +
    + +

    Example 1:

    + +
    +
    +Input: [1,2,3,4,5]
    +
    +Output: Node 3 from this list (Serialization: [3,4,5])
    +
    +The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
    +
    +Note that we returned a ListNode object ans, such that:
    +
    +ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
    +
    +
    + +
    + +

    Example 2:

    + +
    +
    +Input: [1,2,3,4,5,6]
    +
    +Output: Node 4 from this list (Serialization: [4,5,6])
    +
    +Since the list has two middle nodes with values 3 and 4, we return the second one.
    +
    +
    + +

     

    + +

    Note:

    + +
      +
    • The number of nodes in the given list will be between 1 and 100.
    • +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def middleNode(self, head: ListNode) -> ListNode: + slow = fast = head + while fast and fast.next: + slow, fast = slow.next, fast.next.next + return slow +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode middleNode(ListNode head) { + ListNode slow = head, fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function middleNode(head: ListNode | null): ListNode | null { + let fast = head, slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + return slow; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* middleNode(ListNode* head) { + ListNode *slow = head, *fast = head; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + return slow; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func middleNode(head *ListNode) *ListNode { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + return slow +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0877.Stone Game/README_EN.md b/assets/0800-0899/0877.Stone Game/README_EN.md new file mode 100644 index 00000000..92353641 --- /dev/null +++ b/assets/0800-0899/0877.Stone Game/README_EN.md @@ -0,0 +1,62 @@ +# [877. Stone Game](https://leetcode.com/problems/stone-game) + + + +## Description + +

    Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

    + +

    The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.

    + +

    Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins.

    + +

    Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

    + +

     

    +

    Example 1:

    + +
    +Input: piles = [5,3,4,5]
    +Output: true
    +Explanation: 
    +Alex starts first, and can only take the first 5 or the last 5.
    +Say he takes the first 5, so that the row becomes [3, 4, 5].
    +If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
    +If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
    +This demonstrated that taking the first 5 was a winning move for Alex, so we return true.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= piles.length <= 500
    • +
    • piles.length is even.
    • +
    • 1 <= piles[i] <= 500
    • +
    • sum(piles) is odd.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0878.Nth Magical Number/README_EN.md b/assets/0800-0899/0878.Nth Magical Number/README_EN.md new file mode 100644 index 00000000..1a49504b --- /dev/null +++ b/assets/0800-0899/0878.Nth Magical Number/README_EN.md @@ -0,0 +1,56 @@ +# [878. Nth Magical Number](https://leetcode.com/problems/nth-magical-number) + + + +## Description + +

    A positive integer is magical if it is divisible by either a or b.

    + +

    Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    +
    Input: n = 1, a = 2, b = 3
    +Output: 2
    +

    Example 2:

    +
    Input: n = 4, a = 2, b = 3
    +Output: 6
    +

    Example 3:

    +
    Input: n = 5, a = 2, b = 4
    +Output: 10
    +

    Example 4:

    +
    Input: n = 3, a = 6, b = 4
    +Output: 8
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 109
    • +
    • 2 <= a, b <= 4 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0879.Profitable Schemes/README_EN.md b/assets/0800-0899/0879.Profitable Schemes/README_EN.md new file mode 100644 index 00000000..1db3fde3 --- /dev/null +++ b/assets/0800-0899/0879.Profitable Schemes/README_EN.md @@ -0,0 +1,65 @@ +# [879. Profitable Schemes](https://leetcode.com/problems/profitable-schemes) + + + +## Description + +

    There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.

    + +

    Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.

    + +

    Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]
    +Output: 2
    +Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
    +In total, there are 2 schemes.
    + +

    Example 2:

    + +
    +Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
    +Output: 7
    +Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
    +There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 100
    • +
    • 0 <= minProfit <= 100
    • +
    • 1 <= group.length <= 100
    • +
    • 1 <= group[i] <= 100
    • +
    • profit.length == group.length
    • +
    • 0 <= profit[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0880.Decoded String at Index/README_EN.md b/assets/0800-0899/0880.Decoded String at Index/README_EN.md new file mode 100644 index 00000000..be8912f4 --- /dev/null +++ b/assets/0800-0899/0880.Decoded String at Index/README_EN.md @@ -0,0 +1,87 @@ +# [880. Decoded String at Index](https://leetcode.com/problems/decoded-string-at-index) + + + +## Description + +

    An encoded string S is given.  To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:

    + +
      +
    • If the character read is a letter, that letter is written onto the tape.
    • +
    • If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total.
    • +
    + +

    Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string.

    + +

     

    + +
    +

    Example 1:

    + +
    +Input: S = "leet2code3", K = 10
    +Output: "o"
    +Explanation: 
    +The decoded string is "leetleetcodeleetleetcodeleetleetcode".
    +The 10th letter in the string is "o".
    +
    + +
    +

    Example 2:

    + +
    +Input: S = "ha22", K = 5
    +Output: "h"
    +Explanation: 
    +The decoded string is "hahahaha".  The 5th letter is "h".
    +
    + +
    +

    Example 3:

    + +
    +Input: S = "a2345678999999999999999", K = 1
    +Output: "a"
    +Explanation: 
    +The decoded string is "a" repeated 8301530446056247680 times.  The 1st letter is "a".
    +
    +
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= S.length <= 100
    • +
    • S will only contain lowercase letters and digits 2 through 9.
    • +
    • S starts with a letter.
    • +
    • 1 <= K <= 10^9
    • +
    • It's guaranteed that K is less than or equal to the length of the decoded string.
    • +
    • The decoded string is guaranteed to have less than 2^63 letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0881.Boats to Save People/README_EN.md b/assets/0800-0899/0881.Boats to Save People/README_EN.md new file mode 100644 index 00000000..eab04a5b --- /dev/null +++ b/assets/0800-0899/0881.Boats to Save People/README_EN.md @@ -0,0 +1,90 @@ +# [881. Boats to Save People](https://leetcode.com/problems/boats-to-save-people) + + + +## Description + +

    You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.

    + +

    Return the minimum number of boats to carry every given person.

    + +

     

    +

    Example 1:

    + +
    +Input: people = [1,2], limit = 3
    +Output: 1
    +Explanation: 1 boat (1, 2)
    +
    + +

    Example 2:

    + +
    +Input: people = [3,2,2,1], limit = 3
    +Output: 3
    +Explanation: 3 boats (1, 2), (2) and (3)
    +
    + +

    Example 3:

    + +
    +Input: people = [3,5,3,4], limit = 5
    +Output: 4
    +Explanation: 4 boats (3), (3), (4), (5)
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= people.length <= 5 * 104
    • +
    • 1 <= people[i] <= limit <= 3 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numRescueBoats(self, people: List[int], limit: int) -> int: + people.sort() + num, i, j = 0, 0, len(people) - 1 + while i <= j: + if people[i] + people[j] <= limit: + i += 1 + j -= 1 + num += 1 + return num +``` + +### **Java** + +```java +class Solution { + public int numRescueBoats(int[] people, int limit) { + Arrays.sort(people); + int num = 0; + int i = 0, j = people.length - 1; + while (i <= j) { + if (people[i] + people[j] <= limit) { + ++i; + } + --j; + ++num; + } + return num; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md b/assets/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md new file mode 100644 index 00000000..b019d313 --- /dev/null +++ b/assets/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md @@ -0,0 +1,78 @@ +# [882. Reachable Nodes In Subdivided Graph](https://leetcode.com/problems/reachable-nodes-in-subdivided-graph) + + + +## Description + +

    You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.

    + +

    The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.

    + +

    To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti+1, xcnti], [xcnti, vi].

    + +

    In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.

    + +

    Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.

    + +

     

    +

    Example 1:

    + +
    +Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
    +Output: 13
    +Explanation: The edge subdivisions are shown in the image above.
    +The nodes that are reachable are highlighted in yellow.
    +
    + +

    Example 2:

    + +
    +Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
    +Output: 23
    +
    + +

    Example 3:

    + +
    +Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
    +Output: 1
    +Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= edges.length <= min(n * (n - 1) / 2, 104)
    • +
    • edges[i].length == 3
    • +
    • 0 <= ui < vi < n
    • +
    • There are no multiple edges in the graph.
    • +
    • 0 <= cnti <= 104
    • +
    • 0 <= maxMoves <= 109
    • +
    • 1 <= n <= 3000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0882.Reachable Nodes In Subdivided Graph/images/origfinal.png b/assets/0800-0899/0882.Reachable Nodes In Subdivided Graph/images/origfinal.png new file mode 100644 index 00000000..7be9f722 Binary files /dev/null and b/assets/0800-0899/0882.Reachable Nodes In Subdivided Graph/images/origfinal.png differ diff --git a/assets/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md b/assets/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md new file mode 100644 index 00000000..dae4d20c --- /dev/null +++ b/assets/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md @@ -0,0 +1,87 @@ +# [883. Projection Area of 3D Shapes](https://leetcode.com/problems/projection-area-of-3d-shapes) + + + +## Description + +

    You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.

    + +

    Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).

    + +

    We view the projection of these cubes onto the xy, yz, and zx planes.

    + +

    A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side.

    + +

    Return the total area of all three projections.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,2],[3,4]]
    +Output: 17
    +Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[2]]
    +Output: 5
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0],[0,2]]
    +Output: 8
    +
    + +

    Example 4:

    + +
    +Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
    +Output: 14
    +
    + +

    Example 5:

    + +
    +Input: grid = [[2,2,2],[2,1,2],[2,2,2]]
    +Output: 21
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 50
    • +
    • 0 <= grid[i][j] <= 50
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0883.Projection Area of 3D Shapes/images/shadow.png b/assets/0800-0899/0883.Projection Area of 3D Shapes/images/shadow.png new file mode 100644 index 00000000..445d970d Binary files /dev/null and b/assets/0800-0899/0883.Projection Area of 3D Shapes/images/shadow.png differ diff --git a/assets/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md b/assets/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md new file mode 100644 index 00000000..80208c0a --- /dev/null +++ b/assets/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md @@ -0,0 +1,107 @@ +# [884. Uncommon Words from Two Sentences](https://leetcode.com/problems/uncommon-words-from-two-sentences) + + + +## Description + +

    We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)

    + + + +

    A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

    + + + +

    Return a list of all uncommon words. 

    + + + +

    You may return the list in any order.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = "this apple is sweet", B = "this apple is sour"
    +
    +Output: ["sweet","sour"]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = "apple apple", B = "banana"
    +
    +Output: ["banana"]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 0 <= A.length <= 200
    2. +
    3. 0 <= B.length <= 200
    4. +
    5. A and B both contain only spaces and lowercase letters.
    6. +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0885.Spiral Matrix III/README_EN.md b/assets/0800-0899/0885.Spiral Matrix III/README_EN.md new file mode 100644 index 00000000..59878548 --- /dev/null +++ b/assets/0800-0899/0885.Spiral Matrix III/README_EN.md @@ -0,0 +1,120 @@ +# [885. Spiral Matrix III](https://leetcode.com/problems/spiral-matrix-iii) + + + +## Description + +

    On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.

    + + + +

    Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.

    + + + +

    Now, we walk in a clockwise spiral shape to visit every position in this grid. 

    + + + +

    Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.) 

    + + + +

    Eventually, we reach all R * C spaces of the grid.

    + + + +

    Return a list of coordinates representing the positions of the grid in the order they were visited.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: R = 1, C = 4, r0 = 0, c0 = 0
    +
    +Output: [[0,0],[0,1],[0,2],[0,3]]
    +
    +
    +
    +
    +
    +
    + + + +

     

    + + + +

    Example 2:

    + + + +
    +
    +Input: R = 5, C = 6, r0 = 1, c0 = 4
    +
    +Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
    +
    +
    +
    +
    +
    +
    + + + +
    + +
    + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= R <= 100
    2. +
    3. 1 <= C <= 100
    4. +
    5. 0 <= r0 < R
    6. +
    7. 0 <= c0 < C
    8. +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0885.Spiral Matrix III/images/example_1.png b/assets/0800-0899/0885.Spiral Matrix III/images/example_1.png new file mode 100644 index 00000000..66796843 Binary files /dev/null and b/assets/0800-0899/0885.Spiral Matrix III/images/example_1.png differ diff --git a/assets/0800-0899/0885.Spiral Matrix III/images/example_2.png b/assets/0800-0899/0885.Spiral Matrix III/images/example_2.png new file mode 100644 index 00000000..c39ff804 Binary files /dev/null and b/assets/0800-0899/0885.Spiral Matrix III/images/example_2.png differ diff --git a/assets/0800-0899/0886.Possible Bipartition/README_EN.md b/assets/0800-0899/0886.Possible Bipartition/README_EN.md new file mode 100644 index 00000000..7321cac9 --- /dev/null +++ b/assets/0800-0899/0886.Possible Bipartition/README_EN.md @@ -0,0 +1,134 @@ +# [886. Possible Bipartition](https://leetcode.com/problems/possible-bipartition) + + + +## Description + +

    Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size.

    + + + +

    Each person may dislike some other people, and they should not go into the same group. 

    + + + +

    Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.

    + + + +

    Return true if and only if it is possible to split everyone into two groups in this way.

    + + + +

     

    + + + +
    + +
    + +
      + +
    + +
    + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
    +
    +Output: true
    +
    +Explanation: group1 [1,4], group2 [2,3]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
    +
    +Output: false
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
    +
    +Output: false
    +
    +
    + +
    + +
    + +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= N <= 2000
    • +
    • 0 <= dislikes.length <= 10000
    • +
    • dislikes[i].length == 2
    • +
    • 1 <= dislikes[i][j] <= N
    • +
    • dislikes[i][0] < dislikes[i][1]
    • +
    • There does not exist i != j for which dislikes[i] == dislikes[j].
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0887.Super Egg Drop/README_EN.md b/assets/0800-0899/0887.Super Egg Drop/README_EN.md new file mode 100644 index 00000000..15dd47fd --- /dev/null +++ b/assets/0800-0899/0887.Super Egg Drop/README_EN.md @@ -0,0 +1,73 @@ +# [887. Super Egg Drop](https://leetcode.com/problems/super-egg-drop) + + + +## Description + +

    You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.

    + +

    You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.

    + +

    Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.

    + +

    Return the minimum number of moves that you need to determine with certainty what the value of f is.

    + +

     

    +

    Example 1:

    + +
    +Input: k = 1, n = 2
    +Output: 2
    +Explanation: 
    +Drop the egg from floor 1. If it breaks, we know that f = 0.
    +Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.
    +If it does not break, then we know f = 2.
    +Hence, we need at minimum 2 moves to determine with certainty what the value of f is.
    +
    + +

    Example 2:

    + +
    +Input: k = 2, n = 6
    +Output: 3
    +
    + +

    Example 3:

    + +
    +Input: k = 3, n = 14
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= 100
    • +
    • 1 <= n <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0888.Fair Candy Swap/README_EN.md b/assets/0800-0899/0888.Fair Candy Swap/README_EN.md new file mode 100644 index 00000000..c3292a00 --- /dev/null +++ b/assets/0800-0899/0888.Fair Candy Swap/README_EN.md @@ -0,0 +1,190 @@ +# [888. Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap) + + + +## Description + +

    Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has.

    + + + +

    Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy.  (The total amount of candy a person has is the sum of the sizes of candy bars they have.)

    + + + +

    Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange.

    + + + +

    If there are multiple answers, you may return any one of them.  It is guaranteed an answer exists.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [1,1], B = [2,2]
    +
    +Output: [1,2]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [1,2], B = [2,3]
    +
    +Output: [1,2]
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [2], B = [1,3]
    +
    +Output: [2,3]
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: A = [1,2,5], B = [2,4]
    +
    +Output: [5,4]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= A.length <= 10000
    • +
    • 1 <= B.length <= 10000
    • +
    • 1 <= A[i] <= 100000
    • +
    • 1 <= B[i] <= 100000
    • +
    • It is guaranteed that Alice and Bob have different total amounts of candy.
    • +
    • It is guaranteed there exists an answer.
    • +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]: + diff = (sum(aliceSizes) - sum(bobSizes)) >> 1 + s = set(bobSizes) + for a in aliceSizes: + target = a - diff + if target in s: + return [a, target] +``` + +### **Java** + +```java +class Solution { + public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { + int s1 = 0, s2 = 0; + Set s = new HashSet<>(); + for (int a : aliceSizes) { + s1 += a; + } + for (int b : bobSizes) { + s.add(b); + s2 += b; + } + int diff = (s1 - s2) >> 1; + for (int a : aliceSizes) { + int target = a - diff; + if (s.contains(target)) { + return new int[]{a, target}; + } + } + return null; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector fairCandySwap(vector& aliceSizes, vector& bobSizes) { + int s1 = accumulate(aliceSizes.begin(), aliceSizes.end(), 0); + int s2 = accumulate(bobSizes.begin(), bobSizes.end(), 0); + int diff = (s1 - s2) >> 1; + unordered_set s(bobSizes.begin(), bobSizes.end()); + vector ans; + for (int& a : aliceSizes) { + int target = a - diff; + if (s.count(target)) { + ans = vector{a, target}; + break; + } + } + return ans; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md b/assets/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md new file mode 100644 index 00000000..361e39fc --- /dev/null +++ b/assets/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md @@ -0,0 +1,75 @@ +# [889. Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal) + + + +## Description + +

    Return any binary tree that matches the given preorder and postorder traversals.

    + + + +

    Values in the traversals pre and post are distinct positive integers.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
    +
    +Output: [1,2,3,4,5,6,7]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= pre.length == post.length <= 30
    • +
    • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
    • +
    • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
    • +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0890.Find and Replace Pattern/README_EN.md b/assets/0800-0899/0890.Find and Replace Pattern/README_EN.md new file mode 100644 index 00000000..668fda6d --- /dev/null +++ b/assets/0800-0899/0890.Find and Replace Pattern/README_EN.md @@ -0,0 +1,90 @@ +# [890. Find and Replace Pattern](https://leetcode.com/problems/find-and-replace-pattern) + + + +## Description + +

    You have a list of words and a pattern, and you want to know which words in words matches the pattern.

    + + + +

    A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

    + + + +

    (Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)

    + + + +

    Return a list of the words in words that match the given pattern. 

    + + + +

    You may return the answer in any order.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
    +
    +Output: ["mee","aqq"]
    +
    +Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. 
    +
    +"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
    +
    +since a and b map to the same letter.
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= words.length <= 50
    • +
    • 1 <= pattern.length = words[i].length <= 20
    • +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0891.Sum of Subsequence Widths/README_EN.md b/assets/0800-0899/0891.Sum of Subsequence Widths/README_EN.md new file mode 100644 index 00000000..091aa7d3 --- /dev/null +++ b/assets/0800-0899/0891.Sum of Subsequence Widths/README_EN.md @@ -0,0 +1,90 @@ +# [891. Sum of Subsequence Widths](https://leetcode.com/problems/sum-of-subsequence-widths) + + + +## Description + +

    Given an array of integers A, consider all non-empty subsequences of A.

    + + + +

    For any sequence S, let the width of S be the difference between the maximum and minimum element of S.

    + + + +

    Return the sum of the widths of all subsequences of A. 

    + + + +

    As the answer may be very large, return the answer modulo 10^9 + 7.

    + + + +
    + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [2,1,3]
    +
    +Output: 6
    +
    +Explanation:
    +
    +Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
    +
    +The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
    +
    +The sum of these widths is 6.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= A.length <= 20000
    • +
    • 1 <= A[i] <= 20000
    • +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md b/assets/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md new file mode 100644 index 00000000..9751371f --- /dev/null +++ b/assets/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md @@ -0,0 +1,84 @@ +# [892. Surface Area of 3D Shapes](https://leetcode.com/problems/surface-area-of-3d-shapes) + + + +## Description + +

    You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).

    + +

    After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.

    + +

    Return the total surface area of the resulting shapes.

    + +

    Note: The bottom face of each shape counts toward its surface area.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[2]]
    +Output: 10
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,2],[3,4]]
    +Output: 34
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0],[0,2]]
    +Output: 16
    +
    + +

    Example 4:

    + +
    +Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
    +Output: 32
    +
    + +

    Example 5:

    + +
    +Input: grid = [[2,2,2],[2,1,2],[2,2,2]]
    +Output: 46
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 50
    • +
    • 0 <= grid[i][j] <= 50
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid1.jpg b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid1.jpg new file mode 100644 index 00000000..a94cea6b Binary files /dev/null and b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid1.jpg differ diff --git a/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid2.jpg b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid2.jpg new file mode 100644 index 00000000..d2c7870f Binary files /dev/null and b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid2.jpg differ diff --git a/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid3.jpg b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid3.jpg new file mode 100644 index 00000000..4cc55843 Binary files /dev/null and b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid3.jpg differ diff --git a/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid4.jpg b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid4.jpg new file mode 100644 index 00000000..da3aad7d Binary files /dev/null and b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid4.jpg differ diff --git a/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid5.jpg b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid5.jpg new file mode 100644 index 00000000..8ec9ad36 Binary files /dev/null and b/assets/0800-0899/0892.Surface Area of 3D Shapes/images/tmp-grid5.jpg differ diff --git a/assets/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md b/assets/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md new file mode 100644 index 00000000..c40182d0 --- /dev/null +++ b/assets/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md @@ -0,0 +1,139 @@ +# [893. Groups of Special-Equivalent Strings](https://leetcode.com/problems/groups-of-special-equivalent-strings) + + + +## Description + +

    You are given an array A of strings.

    + + + +

    A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.

    + + + +

    Two strings S and T are special-equivalent if after any number of moves onto S, S == T.

    + + + +

    For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].

    + + + +

    Now, a group of special-equivalent strings from A is a non-empty subset of A such that:

    + + + +
      +
    1. Every pair of strings in the group are special equivalent, and;
    2. +
    3. The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
    4. +
    + + + +

    Return the number of groups of special-equivalent strings from A.

    + + + +
     
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
    +
    +Output: 3
    +
    +Explanation: 
    +
    +One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
    +
    +
    +
    +The other two groups are ["xyzz", "zzxy"] and ["zzyx"].  Note that in particular, "zzxy" is not special equivalent to "zzyx".
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: ["abc","acb","bac","bca","cab","cba"]
    +
    +Output: 3
    + + + +

     

    + +
    + +
    + + + +
    + +
    + +
    + +
    + +

    Note:

    + + + +
      +
    • 1 <= A.length <= 1000
    • +
    • 1 <= A[i].length <= 20
    • +
    • All A[i] have the same length.
    • +
    • All A[i] consist of only lowercase letters.
    • +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0894.All Possible Full Binary Trees/README_EN.md b/assets/0800-0899/0894.All Possible Full Binary Trees/README_EN.md new file mode 100644 index 00000000..6faa9ba2 --- /dev/null +++ b/assets/0800-0899/0894.All Possible Full Binary Trees/README_EN.md @@ -0,0 +1,58 @@ +# [894. All Possible Full Binary Trees](https://leetcode.com/problems/all-possible-full-binary-trees) + + + +## Description + +

    Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.

    + +

    Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.

    + +

    A full binary tree is a binary tree where each node has exactly 0 or 2 children.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 7
    +Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
    +
    + +

    Example 2:

    + +
    +Input: n = 3
    +Output: [[0,0,0]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 20
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0894.All Possible Full Binary Trees/images/fivetrees.png b/assets/0800-0899/0894.All Possible Full Binary Trees/images/fivetrees.png new file mode 100644 index 00000000..da18b4b8 Binary files /dev/null and b/assets/0800-0899/0894.All Possible Full Binary Trees/images/fivetrees.png differ diff --git a/assets/0800-0899/0895.Maximum Frequency Stack/README_EN.md b/assets/0800-0899/0895.Maximum Frequency Stack/README_EN.md new file mode 100644 index 00000000..03538772 --- /dev/null +++ b/assets/0800-0899/0895.Maximum Frequency Stack/README_EN.md @@ -0,0 +1,77 @@ +# [895. Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack) + + + +## Description + +

    Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.

    + +

    Implement the FreqStack class:

    + +
      +
    • FreqStack() constructs an empty frequency stack.
    • +
    • void push(int val) pushes an integer val onto the top of the stack.
    • +
    • int pop() removes and returns the most frequent element in the stack. +
        +
      • If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
      • +
      +
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
    +[[], [5], [7], [5], [7], [4], [5], [], [], [], []]
    +Output
    +[null, null, null, null, null, null, null, 5, 7, 5, 4]
    +
    +Explanation
    +FreqStack freqStack = new FreqStack();
    +freqStack.push(5); // The stack is [5]
    +freqStack.push(7); // The stack is [5,7]
    +freqStack.push(5); // The stack is [5,7,5]
    +freqStack.push(7); // The stack is [5,7,5,7]
    +freqStack.push(4); // The stack is [5,7,5,7,4]
    +freqStack.push(5); // The stack is [5,7,5,7,4,5]
    +freqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].
    +freqStack.pop();   // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].
    +freqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,4].
    +freqStack.pop();   // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= val <= 109
    • +
    • At most 2 * 104 calls will be made to push and pop.
    • +
    • It is guaranteed that there will be at least one element in the stack before calling pop.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0896.Monotonic Array/README_EN.md b/assets/0800-0899/0896.Monotonic Array/README_EN.md new file mode 100644 index 00000000..ef01124c --- /dev/null +++ b/assets/0800-0899/0896.Monotonic Array/README_EN.md @@ -0,0 +1,176 @@ +# [896. Monotonic Array](https://leetcode.com/problems/monotonic-array) + + + +## Description + +

    An array is monotonic if it is either monotone increasing or monotone decreasing.

    + + + +

    An array A is monotone increasing if for all i <= j, A[i] <= A[j].  An array A is monotone decreasing if for all i <= j, A[i] >= A[j].

    + + + +

    Return true if and only if the given array A is monotonic.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

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

    Example 2:

    + + + +
    +
    +Input: [6,5,4,4]
    +
    +Output: true
    +
    +
    + + + +
    + +

    Example 3:

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

    Example 4:

    + + + +
    +
    +Input: [1,2,4,5]
    +
    +Output: true
    +
    +
    + + + +
    + +

    Example 5:

    + + + +
    +
    +Input: [1,1,1]
    +
    +Output: true
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. -100000 <= A[i] <= 100000
    4. +
    + +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isMonotonic(self, A: List[int]) -> bool: + increase = decrease = True + for i in range(1, len(A)): + if not increase and not decrease: + return False + if A[i] < A[i - 1]: + increase = False + elif A[i] > A[i - 1]: + decrease = False + return increase or decrease +``` + +### **Java** + +```java +class Solution { + public boolean isMonotonic(int[] A) { + boolean increase = true, decrease = true; + for (int i = 1, n = A.length; i < n; ++i) { + if (!increase && !decrease) return false; + if (A[i] < A[i - 1]) decrease = false; + else if (A[i] > A[i - 1]) increase = false; + } + return increase || decrease; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0897.Increasing Order Search Tree/README_EN.md b/assets/0800-0899/0897.Increasing Order Search Tree/README_EN.md new file mode 100644 index 00000000..048c9214 --- /dev/null +++ b/assets/0800-0899/0897.Increasing Order Search Tree/README_EN.md @@ -0,0 +1,128 @@ +# [897. Increasing Order Search Tree](https://leetcode.com/problems/increasing-order-search-tree) + + + +## Description + +

    Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
    +
    +Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: root = [5,1,7]
    +
    +Output: [1,null,5,null,7]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the given tree will be in the range [1, 100].
    • +
    • 0 <= Node.val <= 1000
    • +
    + +## Solutions + +See [17.12. BiNode](/lcci/17.12.BiNode/README_EN.md). + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def increasingBST(self, root: TreeNode) -> TreeNode: + if root is None: + return None + left = self.increasingBST(root.left) + right = self.increasingBST(root.right) + if left is None: + root.right = right + return root + res = left + while left and left.right: + left = left.right + left.right = root + root.right = right + root.left = None + return res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode increasingBST(TreeNode root) { + if (root == null) return null; + TreeNode left = increasingBST(root.left); + TreeNode right = increasingBST(root.right); + if (left == null) { + root.right = right; + return root; + } + TreeNode res = left; + while (left != null && left.right != null) left = left.right; + left.right = root; + root.right = right; + root.left = null; + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0897.Increasing Order Search Tree/images/ex1.jpg b/assets/0800-0899/0897.Increasing Order Search Tree/images/ex1.jpg new file mode 100644 index 00000000..a60f693f Binary files /dev/null and b/assets/0800-0899/0897.Increasing Order Search Tree/images/ex1.jpg differ diff --git a/assets/0800-0899/0897.Increasing Order Search Tree/images/ex2.jpg b/assets/0800-0899/0897.Increasing Order Search Tree/images/ex2.jpg new file mode 100644 index 00000000..6311e41d Binary files /dev/null and b/assets/0800-0899/0897.Increasing Order Search Tree/images/ex2.jpg differ diff --git a/assets/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md b/assets/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md new file mode 100644 index 00000000..e2506ea9 --- /dev/null +++ b/assets/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md @@ -0,0 +1,71 @@ +# [898. Bitwise ORs of Subarrays](https://leetcode.com/problems/bitwise-ors-of-subarrays) + + + +## Description + +

    We have an array arr of non-negative integers.

    + +

    For every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j].

    + +

    Return the number of possible results. Results that occur more than once are only counted once in the final answer

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [0]
    +Output: 1
    +Explanation: There is only one possible result: 0.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,1,2]
    +Output: 3
    +Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
    +These yield the results 1, 1, 2, 1, 3, 3.
    +There are 3 unique values, so the answer is 3.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,2,4]
    +Output: 6
    +Explanation: The possible results are 1, 2, 3, 4, 6, and 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 0 <= nums[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0800-0899/0899.Orderly Queue/README_EN.md b/assets/0800-0899/0899.Orderly Queue/README_EN.md new file mode 100644 index 00000000..e5b4d9e2 --- /dev/null +++ b/assets/0800-0899/0899.Orderly Queue/README_EN.md @@ -0,0 +1,108 @@ +# [899. Orderly Queue](https://leetcode.com/problems/orderly-queue) + + + +## Description + +

    A string S of lowercase letters is given.  Then, we may make any number of moves.

    + + + +

    In each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string.

    + + + +

    Return the lexicographically smallest string we could have after any number of moves.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: S = "cba", K = 1
    +
    +Output: "acb"
    +
    +Explanation: 
    +
    +In the first move, we move the 1st character ("c") to the end, obtaining the string "bac".
    +
    +In the second move, we move the 1st character ("b") to the end, obtaining the final result "acb".
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: S = "baaca", K = 3
    +
    +Output: "aaabc"
    +
    +Explanation: 
    +
    +In the first move, we move the 1st character ("b") to the end, obtaining the string "aacab".
    +
    +In the second move, we move the 3rd character ("c") to the end, obtaining the final result "aaabc".
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= K <= S.length <= 1000
    2. +
    3. S consists of lowercase letters only.
    4. +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0900.RLE Iterator/README_EN.md b/assets/0900-0999/0900.RLE Iterator/README_EN.md new file mode 100644 index 00000000..0bf95654 --- /dev/null +++ b/assets/0900-0999/0900.RLE Iterator/README_EN.md @@ -0,0 +1,105 @@ +# [900. RLE Iterator](https://leetcode.com/problems/rle-iterator) + + + +## Description + +

    Write an iterator that iterates through a run-length encoded sequence.

    + + + +

    The iterator is initialized by RLEIterator(int[] A), where A is a run-length encoding of some sequence.  More specifically, for all even iA[i] tells us the number of times that the non-negative integer value A[i+1] is repeated in the sequence.

    + + + +

    The iterator supports one function: next(int n), which exhausts the next n elements (n >= 1) and returns the last element exhausted in this way.  If there is no element left to exhaust, next returns -1 instead.

    + + + +

    For example, we start with A = [3,8,0,9,2,5], which is a run-length encoding of the sequence [8,8,8,5,5].  This is because the sequence can be read as "three eights, zero nines, two fives".

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: ["RLEIterator","next","next","next","next"], [[[3,8,0,9,2,5]],[2],[1],[1],[2]]
    +
    +Output: [null,8,8,5,-1]
    +
    +Explanation: 
    +
    +RLEIterator is initialized with RLEIterator([3,8,0,9,2,5]).
    +
    +This maps to the sequence [8,8,8,5,5].
    +
    +RLEIterator.next is then called 4 times:
    +
    +
    +
    +.next(2) exhausts 2 terms of the sequence, returning 8.  The remaining sequence is now [8, 5, 5].
    +
    +
    +
    +.next(1) exhausts 1 term of the sequence, returning 8.  The remaining sequence is now [5, 5].
    +
    +
    +
    +.next(1) exhausts 1 term of the sequence, returning 5.  The remaining sequence is now [5].
    +
    +
    +
    +.next(2) exhausts 2 terms, returning -1.  This is because the first term exhausted was 5,
    +
    +but the second term did not exist.  Since the last term exhausted does not exist, we return -1.
    +
    +
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 0 <= A.length <= 1000
    2. +
    3. A.length is an even integer.
    4. +
    5. 0 <= A[i] <= 10^9
    6. +
    7. There are at most 1000 calls to RLEIterator.next(int n) per test case.
    8. +
    9. Each call to RLEIterator.next(int n) will have 1 <= n <= 10^9.
    10. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0901.Online Stock Span/README_EN.md b/assets/0900-0999/0901.Online Stock Span/README_EN.md new file mode 100644 index 00000000..d892b44f --- /dev/null +++ b/assets/0900-0999/0901.Online Stock Span/README_EN.md @@ -0,0 +1,104 @@ +# [901. Online Stock Span](https://leetcode.com/problems/online-stock-span) + + + +## Description + +

    Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock's price for the current day.

    + + + +

    The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today's price.

    + + + +

    For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
    +
    +Output: [null,1,1,1,2,1,4,6]
    +
    +Explanation: 
    +
    +First, S = StockSpanner() is initialized.  Then:
    +
    +S.next(100) is called and returns 1,
    +
    +S.next(80) is called and returns 1,
    +
    +S.next(60) is called and returns 1,
    +
    +S.next(70) is called and returns 2,
    +
    +S.next(60) is called and returns 1,
    +
    +S.next(75) is called and returns 4,
    +
    +S.next(85) is called and returns 6.
    +
    +
    +
    +Note that (for example) S.next(75) returned 4, because the last 4 prices
    +
    +(including today's price of 75) were less than or equal to today's price.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5.
    2. +
    3. There will be at most 10000 calls to StockSpanner.next per test case.
    4. +
    5. There will be at most 150000 calls to StockSpanner.next across all test cases.
    6. +
    7. The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.
    8. +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md b/assets/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md new file mode 100644 index 00000000..cee4f990 --- /dev/null +++ b/assets/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md @@ -0,0 +1,76 @@ +# [902. Numbers At Most N Given Digit Set](https://leetcode.com/problems/numbers-at-most-n-given-digit-set) + + + +## Description + +

    Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.

    + +

    Return the number of positive integers that can be generated that are less than or equal to a given integer n.

    + +

     

    +

    Example 1:

    + +
    +Input: digits = ["1","3","5","7"], n = 100
    +Output: 20
    +Explanation: 
    +The 20 numbers that can be written are:
    +1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
    +
    + +

    Example 2:

    + +
    +Input: digits = ["1","4","9"], n = 1000000000
    +Output: 29523
    +Explanation: 
    +We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
    +81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
    +2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
    +In total, this is 29523 integers that can be written using the digits array.
    +
    + +

    Example 3:

    + +
    +Input: digits = ["7"], n = 8
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= digits.length <= 9
    • +
    • digits[i].length == 1
    • +
    • digits[i] is a digit from '1' to '9'.
    • +
    • All the values in digits are unique.
    • +
    • digits is sorted in non-decreasing order.
    • +
    • 1 <= n <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md b/assets/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md new file mode 100644 index 00000000..8a533606 --- /dev/null +++ b/assets/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md @@ -0,0 +1,103 @@ +# [903. Valid Permutations for DI Sequence](https://leetcode.com/problems/valid-permutations-for-di-sequence) + + + +## Description + +

    We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".)

    + + + +

    valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i:

    + + + +
      +
    • If S[i] == 'D', then P[i] > P[i+1], and;
    • +
    • If S[i] == 'I', then P[i] < P[i+1].
    • +
    + + + +

    How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "DID"
    +
    +Output: 5
    +
    +Explanation: 
    +
    +The 5 valid permutations of (0, 1, 2, 3) are:
    +
    +(1, 0, 3, 2)
    +
    +(2, 0, 3, 1)
    +
    +(2, 1, 3, 0)
    +
    +(3, 0, 2, 1)
    +
    +(3, 1, 2, 0)
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length <= 200
    2. +
    3. S consists only of characters from the set {'D', 'I'}.
    4. +
    + + + +
    + +

     

    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0904.Fruit Into Baskets/README_EN.md b/assets/0900-0999/0904.Fruit Into Baskets/README_EN.md new file mode 100644 index 00000000..9ad22d1e --- /dev/null +++ b/assets/0900-0999/0904.Fruit Into Baskets/README_EN.md @@ -0,0 +1,186 @@ +# [904. Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets) + + + +## Description + +

    In a row of trees, the i-th tree produces fruit with type tree[i].

    + + + +

    You start at any tree of your choice, then repeatedly perform the following steps:

    + + + +
      +
    1. Add one piece of fruit from this tree to your baskets.  If you cannot, stop.
    2. +
    3. Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.
    4. +
    + + + +

    Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

    + + + +

    You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

    + + + +

    What is the total amount of fruit you can collect with this procedure?

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [1,2,1]
    +
    +Output: 3
    +
    +Explanation: We can collect [1,2,1].
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [0,1,2,2]
    +
    +Output: 3
    +
    +Explanation: We can collect [1,2,2].
    +
    +If we started at the first tree, we would only collect [0, 1].
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: [1,2,3,2,2]
    +
    +Output: 4
    +
    +Explanation: We can collect [2,3,2,2].
    +
    +If we started at the first tree, we would only collect [1, 2].
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: [3,3,3,1,2,1,1,2,3,3,4]
    +
    +Output: 5
    +
    +Explanation: We can collect [1,2,1,1,2].
    +
    +If we started at the first tree or the eighth tree, we would only collect 4 fruits.
    +
    +
    + + + +

     

    + +
    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= tree.length <= 40000
    2. +
    3. 0 <= tree[i] < tree.length
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def totalFruit(self, tree: List[int]) -> int: + counter = collections.Counter() + i = res = 0 + for j, type in enumerate(tree): + counter[type] += 1 + while len(counter) > 2: + counter[tree[i]] -= 1 + if counter[tree[i]] == 0: + counter.pop(tree[i]) + i += 1 + res = max(res, j - i + 1) + return res +``` + +### **Java** + +```java +class Solution { + public int totalFruit(int[] tree) { + Map counter = new HashMap<>(); + int i = 0, res = 0; + for (int j = 0; j < tree.length; ++j) { + counter.put(tree[j], counter.getOrDefault(tree[j], 0) + 1); + while (counter.size() > 2) { + counter.put(tree[i], counter.get(tree[i]) - 1); + if (counter.get(tree[i]) == 0) { + counter.remove(tree[i]); + } + ++i; + } + res = Math.max(res, j - i + 1); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0905.Sort Array By Parity/README_EN.md b/assets/0900-0999/0905.Sort Array By Parity/README_EN.md new file mode 100644 index 00000000..0d3af472 --- /dev/null +++ b/assets/0900-0999/0905.Sort Array By Parity/README_EN.md @@ -0,0 +1,115 @@ +# [905. Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity) + + + +## Description + +

    Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

    + +

    You may return any answer array that satisfies this condition.

    + +

     

    + +
    + +

    Example 1:

    + +
    +
    +Input: [3,1,2,4]
    +
    +Output: [2,4,3,1]
    +
    +The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
    +
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 1 <= A.length <= 5000
    2. +
    3. 0 <= A[i] <= 5000
    4. +
    + +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sortArrayByParity(self, A: List[int]) -> List[int]: + i, j = 0, len(A) - 1 + while i < j: + if (A[i] & 1) > (A[j] & 1): + A[i], A[j] = A[j], A[i] + if A[i] & 1 == 0: + i += 1 + if A[j] & 1 == 1: + j -= 1 + return A +``` + +### **Java** + +```java +class Solution { + public int[] sortArrayByParity(int[] A) { + int i = 0, j = A.length - 1; + while (i < j) { + if ((A[i] & 1) > (A[j] & 1)) { + int t = A[i]; + A[i] = A[j]; + A[j] = t; + } + if ((A[i] & 1) == 0) { + ++i; + } + if ((A[j] & 1) == 1) { + --j; + } + } + return A; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} A + * @return {number[]} + */ +var sortArrayByParity = function (A) { + let i = 0; + let j = A.length - 1; + while (i < j) { + if ((A[i] & 1) > (A[j] & 1)) { + const t = A[i]; + A[i] = A[j]; + A[j] = t; + } + if ((A[i] & 1) == 0) { + ++i; + } + if ((A[j] & 1) == 1) { + --j; + } + } + return A; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0906.Super Palindromes/README_EN.md b/assets/0900-0999/0906.Super Palindromes/README_EN.md new file mode 100644 index 00000000..67bab63f --- /dev/null +++ b/assets/0900-0999/0906.Super Palindromes/README_EN.md @@ -0,0 +1,62 @@ +# [906. Super Palindromes](https://leetcode.com/problems/super-palindromes) + + + +## Description + +

    Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.

    + +

    Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].

    + +

     

    +

    Example 1:

    + +
    +Input: left = "4", right = "1000"
    +Output: 4
    +Explanation: 4, 9, 121, and 484 are superpalindromes.
    +Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.
    +
    + +

    Example 2:

    + +
    +Input: left = "1", right = "2"
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= left.length, right.length <= 18
    • +
    • left and right consist of only digits.
    • +
    • left and right cannot have leading zeros.
    • +
    • left and right represent integers in the range [1, 1018].
    • +
    • left is less than or equal to right.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0907.Sum of Subarray Minimums/README_EN.md b/assets/0900-0999/0907.Sum of Subarray Minimums/README_EN.md new file mode 100644 index 00000000..8cc15747 --- /dev/null +++ b/assets/0900-0999/0907.Sum of Subarray Minimums/README_EN.md @@ -0,0 +1,59 @@ +# [907. Sum of Subarray Minimums](https://leetcode.com/problems/sum-of-subarray-minimums) + + + +## Description + +

    Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,1,2,4]
    +Output: 17
    +Explanation: 
    +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
    +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
    +Sum is 17.
    +
    + +

    Example 2:

    + +
    +Input: arr = [11,81,94,43,3]
    +Output: 444
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 3 * 104
    • +
    • 1 <= arr[i] <= 3 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0908.Smallest Range I/README_EN.md b/assets/0900-0999/0908.Smallest Range I/README_EN.md new file mode 100644 index 00000000..33d1ad1e --- /dev/null +++ b/assets/0900-0999/0908.Smallest Range I/README_EN.md @@ -0,0 +1,125 @@ +# [908. Smallest Range I](https://leetcode.com/problems/smallest-range-i) + + + +## Description + +

    Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].

    + + + +

    After this process, we have some array B.

    + + + +

    Return the smallest possible difference between the maximum value of B and the minimum value of B.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [1], K = 0
    +
    +Output: 0
    +
    +Explanation: B = [1]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [0,10], K = 2
    +
    +Output: 6
    +
    +Explanation: B = [2,8]
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [1,3,6], K = 3
    +
    +Output: 0
    +
    +Explanation: B = [3,3,3] or B = [4,4,4]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. 0 <= A[i] <= 10000
    4. +
    5. 0 <= K <= 10000
    6. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0909.Snakes and Ladders/README_EN.md b/assets/0900-0999/0909.Snakes and Ladders/README_EN.md new file mode 100644 index 00000000..fc6c255c --- /dev/null +++ b/assets/0900-0999/0909.Snakes and Ladders/README_EN.md @@ -0,0 +1,121 @@ +# [909. Snakes and Ladders](https://leetcode.com/problems/snakes-and-ladders) + + + +## Description + +

    On an N x N board, the numbers from 1 to N*N are written boustrophedonically starting from the bottom left of the board, and alternating direction each row.  For example, for a 6 x 6 board, the numbers are written as follows:

    + + + +
    +
    +
    +
    +
    + + + +

    You start on square 1 of the board (which is always in the last row and first column).  Each move, starting from square x, consists of the following:

    + + + +
      +
    • You choose a destination square S with number x+1, x+2, x+3, x+4, x+5, or x+6, provided this number is <= N*N. +
        +
      • (This choice simulates the result of a standard 6-sided die roll: ie., there are always at most 6 destinations, regardless of the size of the board.)
      • +
      +
    • +
    • If S has a snake or ladder, you move to the destination of that snake or ladder.  Otherwise, you move to S.
    • +
    + + + +

    A board square on row r and column c has a "snake or ladder" if board[r][c] != -1.  The destination of that snake or ladder is board[r][c].

    + + + +

    Note that you only take a snake or ladder at most once per move: if the destination to a snake or ladder is the start of another snake or ladder, you do not continue moving.  (For example, if the board is `[[4,-1],[-1,3]]`, and on the first move your destination square is `2`, then you finish your first move at `3`, because you do not continue moving to `4`.)

    + + + +

    Return the least number of moves required to reach square N*N.  If it is not possible, return -1.

    + + + +

    Example 1:

    + + + +
    +
    +Input: [
    +
    +[-1,-1,-1,-1,-1,-1],
    +
    +[-1,-1,-1,-1,-1,-1],
    +
    +[-1,-1,-1,-1,-1,-1],
    +
    +[-1,35,-1,-1,13,-1],
    +
    +[-1,-1,-1,-1,-1,-1],
    +
    +[-1,15,-1,-1,-1,-1]]
    +
    +Output: 4
    +
    +Explanation: 
    +
    +At the beginning, you start at square 1 [at row 5, column 0].
    +
    +You decide to move to square 2, and must take the ladder to square 15.
    +
    +You then decide to move to square 17 (row 3, column 5), and must take the snake to square 13.
    +
    +You then decide to move to square 14, and must take the ladder to square 35.
    +
    +You then decide to move to square 36, ending the game.
    +
    +It can be shown that you need at least 4 moves to reach the N*N-th square, so the answer is 4.
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 2 <= board.length = board[0].length <= 20
    2. +
    3. board[i][j] is between 1 and N*N or is equal to -1.
    4. +
    5. The board square with number 1 has no snake or ladder.
    6. +
    7. The board square with number N*N has no snake or ladder.
    8. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0909.Snakes and Ladders/images/snakes.png b/assets/0900-0999/0909.Snakes and Ladders/images/snakes.png new file mode 100644 index 00000000..263e1601 Binary files /dev/null and b/assets/0900-0999/0909.Snakes and Ladders/images/snakes.png differ diff --git a/assets/0900-0999/0910.Smallest Range II/README_EN.md b/assets/0900-0999/0910.Smallest Range II/README_EN.md new file mode 100644 index 00000000..81044400 --- /dev/null +++ b/assets/0900-0999/0910.Smallest Range II/README_EN.md @@ -0,0 +1,125 @@ +# [910. Smallest Range II](https://leetcode.com/problems/smallest-range-ii) + + + +## Description + +

    Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).

    + + + +

    After this process, we have some array B.

    + + + +

    Return the smallest possible difference between the maximum value of B and the minimum value of B.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [1], K = 0
    +
    +Output: 0
    +
    +Explanation: B = [1]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [0,10], K = 2
    +
    +Output: 6
    +
    +Explanation: B = [2,8]
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [1,3,6], K = 3
    +
    +Output: 3
    +
    +Explanation: B = [4,6,3]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. 0 <= A[i] <= 10000
    4. +
    5. 0 <= K <= 10000
    6. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0911.Online Election/README_EN.md b/assets/0900-0999/0911.Online Election/README_EN.md new file mode 100644 index 00000000..eaf6f961 --- /dev/null +++ b/assets/0900-0999/0911.Online Election/README_EN.md @@ -0,0 +1,91 @@ +# [911. Online Election](https://leetcode.com/problems/online-election) + + + +## Description + +

    In an election, the i-th vote was cast for persons[i] at time times[i].

    + + + +

    Now, we would like to implement the following query function: TopVotedCandidate.q(int t) will return the number of the person that was leading the election at time t.  

    + + + +

    Votes cast at time t will count towards our query.  In the case of a tie, the most recent vote (among tied candidates) wins.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: ["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]
    +
    +Output: [null,0,1,1,0,0,1]
    +
    +Explanation: 
    +
    +At time 3, the votes are [0], and 0 is leading.
    +
    +At time 12, the votes are [0,1,1], and 1 is leading.
    +
    +At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)
    +
    +This continues for 3 more queries at time 15, 24, and 8.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= persons.length = times.length <= 5000
    2. +
    3. 0 <= persons[i] <= persons.length
    4. +
    5. times is a strictly increasing array with all elements in [0, 10^9].
    6. +
    7. TopVotedCandidate.q is called at most 10000 times per test case.
    8. +
    9. TopVotedCandidate.q(int t) is always called with t >= times[0].
    10. +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0912.Sort an Array/README_EN.md b/assets/0900-0999/0912.Sort an Array/README_EN.md new file mode 100644 index 00000000..ac1076dc --- /dev/null +++ b/assets/0900-0999/0912.Sort an Array/README_EN.md @@ -0,0 +1,48 @@ +# [912. Sort an Array](https://leetcode.com/problems/sort-an-array) + + + +## Description + +

    Given an array of integers nums, sort the array in ascending order.

    + +

     

    +

    Example 1:

    +
    Input: nums = [5,2,3,1]
    +Output: [1,2,3,5]
    +

    Example 2:

    +
    Input: nums = [5,1,1,2,0,0]
    +Output: [0,0,1,1,2,5]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • -5 * 104 <= nums[i] <= 5 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0913.Cat and Mouse/README_EN.md b/assets/0900-0999/0913.Cat and Mouse/README_EN.md new file mode 100644 index 00000000..43a523c8 --- /dev/null +++ b/assets/0900-0999/0913.Cat and Mouse/README_EN.md @@ -0,0 +1,83 @@ +# [913. Cat and Mouse](https://leetcode.com/problems/cat-and-mouse) + + + +## Description + +

    A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.

    + +

    The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.

    + +

    The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.

    + +

    During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1].

    + +

    Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)

    + +

    Then, the game can end in three ways:

    + +
      +
    • If ever the Cat occupies the same node as the Mouse, the Cat wins.
    • +
    • If ever the Mouse reaches the Hole, the Mouse wins.
    • +
    • If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
    • +
    + +

    Given a graph, and assuming both players play optimally, return

    + +
      +
    • 1 if the mouse wins the game,
    • +
    • 2 if the cat wins the game, or
    • +
    • 0 if the game is a draw.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
    +Output: 0
    +
    + +

    Example 2:

    + +
    +Input: graph = [[1,3],[0],[3],[0,2]]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= graph.length <= 50
    • +
    • 1 <= graph[i].length < graph.length
    • +
    • 0 <= graph[i][j] < graph.length
    • +
    • graph[i][j] != i
    • +
    • graph[i] is unique.
    • +
    • The mouse and the cat can always move. 
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0913.Cat and Mouse/images/cat1.jpg b/assets/0900-0999/0913.Cat and Mouse/images/cat1.jpg new file mode 100644 index 00000000..dfc1d833 Binary files /dev/null and b/assets/0900-0999/0913.Cat and Mouse/images/cat1.jpg differ diff --git a/assets/0900-0999/0913.Cat and Mouse/images/cat2.jpg b/assets/0900-0999/0913.Cat and Mouse/images/cat2.jpg new file mode 100644 index 00000000..84de077e Binary files /dev/null and b/assets/0900-0999/0913.Cat and Mouse/images/cat2.jpg differ diff --git a/assets/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md b/assets/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md new file mode 100644 index 00000000..8fcc5a0a --- /dev/null +++ b/assets/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md @@ -0,0 +1,88 @@ +# [914. X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards) + + + +## Description + +

    In a deck of cards, each card has an integer written on it.

    + +

    Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

    + +
      +
    • Each group has exactly X cards.
    • +
    • All the cards in each group have the same integer.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: deck = [1,2,3,4,4,3,2,1]
    +Output: true
    +Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
    +
    + +

    Example 2:

    + +
    +Input: deck = [1,1,1,2,2,2,3,3]
    +Output: false
    +Explanation: No possible partition.
    +
    + +

    Example 3:

    + +
    +Input: deck = [1]
    +Output: false
    +Explanation: No possible partition.
    +
    + +

    Example 4:

    + +
    +Input: deck = [1,1]
    +Output: true
    +Explanation: Possible partition [1,1].
    +
    + +

    Example 5:

    + +
    +Input: deck = [1,1,2,2,2,2]
    +Output: true
    +Explanation: Possible partition [1,1],[2,2],[2,2].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= deck.length <= 104
    • +
    • 0 <= deck[i] < 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md b/assets/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md new file mode 100644 index 00000000..38b88f67 --- /dev/null +++ b/assets/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md @@ -0,0 +1,109 @@ +# [915. Partition Array into Disjoint Intervals](https://leetcode.com/problems/partition-array-into-disjoint-intervals) + + + +## Description + +

    Given an array A, partition it into two (contiguous) subarrays left and right so that:

    + + + +
      +
    • Every element in left is less than or equal to every element in right.
    • +
    • left and right are non-empty.
    • +
    • left has the smallest possible size.
    • +
    + + + +

    Return the length of left after such a partitioning.  It is guaranteed that such a partitioning exists.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [5,0,3,8,6]
    +
    +Output: 3
    +
    +Explanation: left = [5,0,3], right = [8,6]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [1,1,1,0,6,12]
    +
    +Output: 4
    +
    +Explanation: left = [1,1,1,0], right = [6,12]
    +
    +
    + + + +

     

    + +
    + + + +

    Note:

    + + + +
      +
    1. 2 <= A.length <= 30000
    2. +
    3. 0 <= A[i] <= 10^6
    4. +
    5. It is guaranteed there is at least one way to partition A as described.
    6. +
    + + + +
    + +
     
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0916.Word Subsets/README_EN.md b/assets/0900-0999/0916.Word Subsets/README_EN.md new file mode 100644 index 00000000..3621089b --- /dev/null +++ b/assets/0900-0999/0916.Word Subsets/README_EN.md @@ -0,0 +1,162 @@ +# [916. Word Subsets](https://leetcode.com/problems/word-subsets) + + + +## Description + +

    We are given two arrays A and B of words.  Each word is a string of lowercase letters.

    + + + +

    Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity.  For example, "wrr" is a subset of "warrior", but is not a subset of "world".

    + + + +

    Now say a word a from A is universal if for every b in B, b is a subset of a

    + + + +

    Return a list of all universal words in A.  You can return the words in any order.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
    +
    +Output: ["facebook","google","leetcode"]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
    +
    +Output: ["apple","google","leetcode"]
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
    +
    +Output: ["facebook","google"]
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
    +
    +Output: ["google","leetcode"]
    +
    +
    + + + +
    + +

    Example 5:

    + + + +
    +
    +Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
    +
    +Output: ["facebook","leetcode"]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length, B.length <= 10000
    2. +
    3. 1 <= A[i].length, B[i].length <= 10
    4. +
    5. A[i] and B[i] consist only of lowercase letters.
    6. +
    7. All words in A[i] are unique: there isn't i != j with A[i] == A[j].
    8. +
    + +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0917.Reverse Only Letters/README_EN.md b/assets/0900-0999/0917.Reverse Only Letters/README_EN.md new file mode 100644 index 00000000..951e915f --- /dev/null +++ b/assets/0900-0999/0917.Reverse Only Letters/README_EN.md @@ -0,0 +1,127 @@ +# [917. Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters) + + + +## Description + +

    Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

    + + + +

     

    + + + +
    + +
    + +
    + +
      + +
    + +
    + +
    + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: "ab-cd"
    +
    +Output: "dc-ba"
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "a-bC-dEf-ghIj"
    +
    +Output: "j-Ih-gfE-dCba"
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "Test1ng-Leet=code-Q!"
    +
    +Output: "Qedo1ct-eeLg=ntse-T!"
    +
    +
    + + + +

     

    + + + +
    + +

    Note:

    + + + +
      +
    1. S.length <= 100
    2. +
    3. 33 <= S[i].ASCIIcode <= 122 
    4. +
    5. S doesn't contain \ or "
    6. +
    + +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md b/assets/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md new file mode 100644 index 00000000..e1542864 --- /dev/null +++ b/assets/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md @@ -0,0 +1,249 @@ +# [918. Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray) + + + +## Description + +

    Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.

    + + + +

    Here, a circular array means the end of the array connects to the beginning of the array.  (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)

    + + + +

    Also, a subarray may only include each element of the fixed buffer A at most once.  (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: [1,-2,3,-2]
    +
    +Output: 3
    +
    +Explanation: Subarray [3] has maximum sum 3
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [5,-3,5]
    +
    +Output: 10
    +
    +Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: [3,-1,2,-1]
    +
    +Output: 4
    +
    +Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: [3,-2,2,-3]
    +
    +Output: 3
    +
    +Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: [-2,-3,-1]
    +
    +Output: -1
    +
    +Explanation: Subarray [-1] has maximum sum -1
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. -30000 <= A[i] <= 30000
    2. +
    3. 1 <= A.length <= 30000
    4. +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + s1 = s2 = f1 = f2 = nums[0] + for num in nums[1:]: + f1 = num + max(f1, 0) + f2 = num + min(f2, 0) + s1 = max(s1, f1) + s2 = min(s2, f2) + return s1 if s1 <= 0 else max(s1, sum(nums) - s2) +``` + +### **Java** + +```java +class Solution { + public int maxSubarraySumCircular(int[] nums) { + int s1 = nums[0], s2 = nums[0], f1 = nums[0], f2 = nums[0], total = nums[0]; + for (int i = 1; i < nums.length; ++i) { + total += nums[i]; + f1 = nums[i] + Math.max(f1, 0); + f2 = nums[i] + Math.min(f2, 0); + s1 = Math.max(s1, f1); + s2 = Math.min(s2, f2); + } + return s1 > 0 ? Math.max(s1, total - s2) : s1; + } +} +``` + +### **TypeScript** + +```ts +function maxSubarraySumCircular(nums: number[]): number { + let pre1 = nums[0], pre2 = nums[0]; + let ans1 = nums[0], ans2 = nums[0]; + let sum = nums[0]; + + for (let i = 1; i < nums.length; ++i) { + let cur = nums[i]; + sum += cur; + pre1 = Math.max(pre1 + cur, cur); + ans1 = Math.max(pre1, ans1); + + pre2 = Math.min(pre2 + cur, cur); + ans2 = Math.min(pre2, ans2); + } + return ans1 > 0 ? Math.max(ans1, sum - ans2) : ans1; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + int s1 = nums[0], s2 = nums[0], f1 = nums[0], f2 = nums[0], total = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + total += nums[i]; + f1 = nums[i] + max(f1, 0); + f2 = nums[i] + min(f2, 0); + s1 = max(s1, f1); + s2 = min(s2, f2); + } + return s1 > 0 ? max(s1, total - s2) : s1; + } +}; +``` + +### **Go** + +```go +func maxSubarraySumCircular(nums []int) int { + s1, s2, f1, f2, total := nums[0], nums[0], nums[0], nums[0], nums[0] + for i := 1; i < len(nums); i++ { + total += nums[i] + f1 = nums[i] + max(f1, 0) + f2 = nums[i] + min(f2, 0) + s1 = max(s1, f1) + s2 = min(s2, f2) + } + if s1 <= 0 { + return s1 + } + return max(s1, total-s2) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md b/assets/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md new file mode 100644 index 00000000..a2098320 --- /dev/null +++ b/assets/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md @@ -0,0 +1,121 @@ +# [919. Complete Binary Tree Inserter](https://leetcode.com/problems/complete-binary-tree-inserter) + + + +## Description + +

    A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

    + + + +

    Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations:

    + + + +
      +
    • CBTInserter(TreeNode root) initializes the data structure on a given tree with head node root;
    • +
    • CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;
    • +
    • CBTInserter.get_root() will return the head node of the tree.
    • +
    + + + +
      + +
    + + + +
    + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
    +
    +Output: [null,1,[1,2]]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
    +
    +Output: [null,3,4,[1,2,3,4,5,6,7,8]]
    + +
    + + + +
    + +

     

    + + + +

    Note:

    + + + +
      +
    1. The initial given tree is complete and contains between 1 and 1000 nodes.
    2. +
    3. CBTInserter.insert is called at most 10000 times per test case.
    4. +
    5. Every value of a given or inserted node is between 0 and 5000.
    6. +
    + +
    + +
    + + + +
    + +

     

    + + + +
     
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0920.Number of Music Playlists/README_EN.md b/assets/0900-0999/0920.Number of Music Playlists/README_EN.md new file mode 100644 index 00000000..ed04d9ac --- /dev/null +++ b/assets/0900-0999/0920.Number of Music Playlists/README_EN.md @@ -0,0 +1,128 @@ +# [920. Number of Music Playlists](https://leetcode.com/problems/number-of-music-playlists) + + + +## Description + +

    Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip.  You create a playlist so that:

    + + + +
      +
    • Every song is played at least once
    • +
    • A song can only be played again only if K other songs have been played
    • +
    + + + +

    Return the number of possible playlists.  As the answer can be very large, return it modulo 10^9 + 7.

    + + + +

     

    + + + +
    + +
    + +
    + +

    Example 1:

    + + + +
    +
    +Input: N = 3, L = 3, K = 1
    +
    +Output: 6
    +
    +Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: N = 2, L = 3, K = 0
    +
    +Output: 6
    +
    +Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: N = 2, L = 3, K = 1
    +
    +Output: 2
    +
    +Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]
    +
    +
    + +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 0 <= K < N <= L <= 100
    2. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md b/assets/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md new file mode 100644 index 00000000..04c0816b --- /dev/null +++ b/assets/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md @@ -0,0 +1,148 @@ +# [921. Minimum Add to Make Parentheses Valid](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid) + + + +## Description + +

    Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

    + + + +

    Formally, a parentheses string is valid if and only if:

    + + + +
      +
    • It is the empty string, or
    • +
    • It can be written as AB (A concatenated with B), where A and B are valid strings, or
    • +
    • It can be written as (A), where A is a valid string.
    • +
    + + + +

    Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "())"
    +
    +Output: 1
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "((("
    +
    +Output: 3
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "()"
    +
    +Output: 0
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: "()))(("
    +
    +Output: 4
    + + + +

     

    + +
    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. S.length <= 1000
    2. +
    3. S only consists of '(' and ')' characters.
    4. +
    + + + +
    + +
    + +
    + +
     
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0922.Sort Array By Parity II/README_EN.md b/assets/0900-0999/0922.Sort Array By Parity II/README_EN.md new file mode 100644 index 00000000..63685bba --- /dev/null +++ b/assets/0900-0999/0922.Sort Array By Parity II/README_EN.md @@ -0,0 +1,62 @@ +# [922. Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii) + + + +## Description + +

    Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

    + +

    Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

    + +

    Return any answer array that satisfies this condition.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [4,2,5,7]
    +Output: [4,5,2,7]
    +Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,3]
    +Output: [2,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 2 * 104
    • +
    • nums.length is even.
    • +
    • Half of the integers in nums are even.
    • +
    • 0 <= nums[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0923.3Sum With Multiplicity/README_EN.md b/assets/0900-0999/0923.3Sum With Multiplicity/README_EN.md new file mode 100644 index 00000000..912bd35c --- /dev/null +++ b/assets/0900-0999/0923.3Sum With Multiplicity/README_EN.md @@ -0,0 +1,68 @@ +# [923. 3Sum With Multiplicity](https://leetcode.com/problems/3sum-with-multiplicity) + + + +## Description + +

    Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.

    + +

    As the answer can be very large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
    +Output: 20
    +Explanation: 
    +Enumerating by the values (arr[i], arr[j], arr[k]):
    +(1, 2, 5) occurs 8 times;
    +(1, 3, 4) occurs 8 times;
    +(2, 2, 4) occurs 2 times;
    +(2, 3, 3) occurs 2 times.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,1,2,2,2,2], target = 5
    +Output: 12
    +Explanation: 
    +arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
    +We choose one 1 from [1,1] in 2 ways,
    +and two 2s from [2,2,2,2] in 6 ways.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 3000
    • +
    • 0 <= arr[i] <= 100
    • +
    • 0 <= target <= 300
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0924.Minimize Malware Spread/README_EN.md b/assets/0900-0999/0924.Minimize Malware Spread/README_EN.md new file mode 100644 index 00000000..c07513f2 --- /dev/null +++ b/assets/0900-0999/0924.Minimize Malware Spread/README_EN.md @@ -0,0 +1,66 @@ +# [924. Minimize Malware Spread](https://leetcode.com/problems/minimize-malware-spread) + + + +## Description + +

    You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.

    + +

    Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.

    + +

    Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.

    + +

    Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

    + +

    Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.

    + +

     

    +

    Example 1:

    +
    Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
    +Output: 0
    +

    Example 2:

    +
    Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
    +Output: 0
    +

    Example 3:

    +
    Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
    +Output: 1
    +
    +

     

    +

    Constraints:

    + +
      +
    • n == graph.length
    • +
    • n == graph[i].length
    • +
    • 2 <= n <= 300
    • +
    • graph[i][j] is 0 or 1.
    • +
    • graph[i][j] == graph[j][i]
    • +
    • graph[i][i] == 1
    • +
    • 1 <= initial.length <= n
    • +
    • 0 <= initial[i] <= n - 1
    • +
    • All the integers in initial are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0925.Long Pressed Name/README_EN.md b/assets/0900-0999/0925.Long Pressed Name/README_EN.md new file mode 100644 index 00000000..63dfdf33 --- /dev/null +++ b/assets/0900-0999/0925.Long Pressed Name/README_EN.md @@ -0,0 +1,75 @@ +# [925. Long Pressed Name](https://leetcode.com/problems/long-pressed-name) + + + +## Description + +

    Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

    + +

    You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

    + +

     

    +

    Example 1:

    + +
    +Input: name = "alex", typed = "aaleex"
    +Output: true
    +Explanation: 'a' and 'e' in 'alex' were long pressed.
    +
    + +

    Example 2:

    + +
    +Input: name = "saeed", typed = "ssaaedd"
    +Output: false
    +Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
    +
    + +

    Example 3:

    + +
    +Input: name = "leelee", typed = "lleeelee"
    +Output: true
    +
    + +

    Example 4:

    + +
    +Input: name = "laiden", typed = "laiden"
    +Output: true
    +Explanation: It's not necessary to long press any character.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= name.length <= 1000
    • +
    • 1 <= typed.length <= 1000
    • +
    • name and typed contain only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md b/assets/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md new file mode 100644 index 00000000..70361205 --- /dev/null +++ b/assets/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md @@ -0,0 +1,118 @@ +# [926. Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing) + + + +## Description + +

    A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)

    + + + +

    We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.

    + + + +

    Return the minimum number of flips to make S monotone increasing.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: "00110"
    +
    +Output: 1
    +
    +Explanation: We flip the last digit to get 00111.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "010110"
    +
    +Output: 2
    +
    +Explanation: We flip to get 011111, or alternatively 000111.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "00011000"
    +
    +Output: 2
    +
    +Explanation: We flip to get 00000000.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length <= 20000
    2. +
    3. S only consists of '0' and '1' characters.
    4. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0927.Three Equal Parts/README_EN.md b/assets/0900-0999/0927.Three Equal Parts/README_EN.md new file mode 100644 index 00000000..c09521b6 --- /dev/null +++ b/assets/0900-0999/0927.Three Equal Parts/README_EN.md @@ -0,0 +1,64 @@ +# [927. Three Equal Parts](https://leetcode.com/problems/three-equal-parts) + + + +## Description + +

    You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.

    + +

    If it is possible, return any [i, j] with i + 1 < j, such that:

    + +
      +
    • arr[0], arr[1], ..., arr[i] is the first part,
    • +
    • arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and
    • +
    • arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.
    • +
    • All three parts have equal binary values.
    • +
    + +

    If it is not possible, return [-1, -1].

    + +

    Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.

    + +

     

    +

    Example 1:

    +
    Input: arr = [1,0,1,0,1]
    +Output: [0,3]
    +

    Example 2:

    +
    Input: arr = [1,1,0,1,1]
    +Output: [-1,-1]
    +

    Example 3:

    +
    Input: arr = [1,1,0,0,1]
    +Output: [0,2]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 3 * 104
    • +
    • arr[i] is 0 or 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0928.Minimize Malware Spread II/README_EN.md b/assets/0900-0999/0928.Minimize Malware Spread II/README_EN.md new file mode 100644 index 00000000..c6386bc2 --- /dev/null +++ b/assets/0900-0999/0928.Minimize Malware Spread II/README_EN.md @@ -0,0 +1,66 @@ +# [928. Minimize Malware Spread II](https://leetcode.com/problems/minimize-malware-spread-ii) + + + +## Description + +

    You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.

    + +

    Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.

    + +

    Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.

    + +

    We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.

    + +

    Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

    + +

     

    +

    Example 1:

    +
    Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
    +Output: 0
    +

    Example 2:

    +
    Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
    +Output: 1
    +

    Example 3:

    +
    Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
    +Output: 1
    +
    +

     

    +

    Constraints:

    + +
      +
    • n == graph.length
    • +
    • n == graph[i].length
    • +
    • 2 <= n <= 300
    • +
    • graph[i][j] is 0 or 1.
    • +
    • graph[i][j] == graph[j][i]
    • +
    • graph[i][i] == 1
    • +
    • 1 <= initial.length < n
    • +
    • 0 <= initial[i] <= n - 1
    • +
    • All the integers in initial are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0929.Unique Email Addresses/README_EN.md b/assets/0900-0999/0929.Unique Email Addresses/README_EN.md new file mode 100644 index 00000000..2f2ac95b --- /dev/null +++ b/assets/0900-0999/0929.Unique Email Addresses/README_EN.md @@ -0,0 +1,80 @@ +# [929. Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses) + + + +## Description + +

    Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.

    + +
      +
    • For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name.
    • +
    + +

    If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.

    + +
      +
    • For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.
    • +
    + +

    If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.

    + +
      +
    • For example, "m.y+name@email.com" will be forwarded to "my@email.com".
    • +
    + +

    It is possible to use both of these rules at the same time.

    + +

    Given an array of strings emails where we send one email to each email[i], return the number of different addresses that actually receive mails.

    + +

     

    +

    Example 1:

    + +
    +Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
    +Output: 2
    +Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails.
    +
    + +

    Example 2:

    + +
    +Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= emails.length <= 100
    • +
    • 1 <= emails[i].length <= 100
    • +
    • email[i] consist of lowercase English letters, '+', '.' and '@'.
    • +
    • Each emails[i] contains exactly one '@' character.
    • +
    • All local and domain names are non-empty.
    • +
    • Local names do not start with a '+' character.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0930.Binary Subarrays With Sum/README_EN.md b/assets/0900-0999/0930.Binary Subarrays With Sum/README_EN.md new file mode 100644 index 00000000..d58fc8fd --- /dev/null +++ b/assets/0900-0999/0930.Binary Subarrays With Sum/README_EN.md @@ -0,0 +1,77 @@ +# [930. Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum) + + + +## Description + +

    In an array A of 0s and 1s, how many non-empty subarrays have sum S?

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = [1,0,1,0,1], S = 2
    +
    +Output: 4
    +
    +Explanation: 
    +
    +The 4 subarrays are bolded below:
    +
    +[1,0,1,0,1]
    +
    +[1,0,1,0,1]
    +
    +[1,0,1,0,1]
    +
    +[1,0,1,0,1]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. A.length <= 30000
    2. +
    3. 0 <= S <= A.length
    4. +
    5. A[i] is either 0 or 1.
    6. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0931.Minimum Falling Path Sum/README_EN.md b/assets/0900-0999/0931.Minimum Falling Path Sum/README_EN.md new file mode 100644 index 00000000..5a5a6fcc --- /dev/null +++ b/assets/0900-0999/0931.Minimum Falling Path Sum/README_EN.md @@ -0,0 +1,158 @@ +# [931. Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum) + + + +## Description + +

    Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.

    + +

    A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
    +Output: 13
    +Explanation: There are two falling paths with a minimum sum underlined below:
    +[[2,1,3],      [[2,1,3],
    + [6,5,4],       [6,5,4],
    + [7,8,9]]       [7,8,9]]
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[-19,57],[-40,-5]]
    +Output: -59
    +Explanation: The falling path with a minimum sum is underlined below:
    +[[-19,57],
    + [-40,-5]]
    +
    + +

    Example 3:

    + +
    +Input: matrix = [[-48]]
    +Output: -48
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= n <= 100
    • +
    • -100 <= matrix[i][j] <= 100
    • +
    + + +## Solutions + +Dynamic programming. + + + +### **Python3** + +```python +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + n = len(matrix) + for i in range(1, n): + for j in range(n): + mi = matrix[i - 1][j] + if j > 0: + mi = min(mi, matrix[i - 1][j - 1]) + if j < n - 1: + mi = min(mi, matrix[i - 1][j + 1]) + matrix[i][j] += mi + return min(matrix[n - 1]) +``` + +### **Java** + +```java +class Solution { + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int mi = matrix[i - 1][j]; + if (j > 0) { + mi = Math.min(mi, matrix[i - 1][j - 1]); + } + if (j < n - 1) { + mi = Math.min(mi, matrix[i - 1][j + 1]); + } + matrix[i][j] += mi; + } + } + int res = Integer.MAX_VALUE; + for (int j = 0; j < n; ++j) { + res = Math.min(res, matrix[n - 1][j]); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minFallingPathSum(vector>& matrix) { + int n = matrix.size(); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int mi = matrix[i - 1][j]; + if (j > 0) mi = min(mi, matrix[i - 1][j - 1]); + if (j < n - 1) mi = min(mi, matrix[i - 1][j + 1]); + matrix[i][j] += mi; + } + } + int res = INT_MAX; + for (int j = 0; j < n; ++j) { + res = min(res, matrix[n - 1][j]); + } + return res; + } +}; +``` + +### **Go** + +```go +func minFallingPathSum(matrix [][]int) int { + n := len(matrix) + for i := 1; i < n; i++ { + for j := 0; j < n; j++ { + mi := matrix[i - 1][j] + if j > 0 && mi > matrix[i - 1][j - 1] { + mi = matrix[i - 1][j - 1] + } + if j < n - 1 && mi > matrix[i - 1][j + 1] { + mi = matrix[i - 1][j + 1] + } + matrix[i][j] += mi + } + } + res := 10000 + for j := 0; j < n; j++ { + if res > matrix[n - 1][j] { + res = matrix[n - 1][j] + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0932.Beautiful Array/README_EN.md b/assets/0900-0999/0932.Beautiful Array/README_EN.md new file mode 100644 index 00000000..2ed8fdcf --- /dev/null +++ b/assets/0900-0999/0932.Beautiful Array/README_EN.md @@ -0,0 +1,95 @@ +# [932. Beautiful Array](https://leetcode.com/problems/beautiful-array) + + + +## Description + +

    For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:

    + + + +

    For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].

    + + + +

    Given N, return any beautiful array A.  (It is guaranteed that one exists.)

    + + + +

     

    + + + +

    Example 1:

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

    Example 2:

    + + + +
    +
    +Input: 5
    +
    +Output: [3,1,2,5,4]
    + + + +

     

    + +
    + + + +

    Note:

    + + + +
      +
    • 1 <= N <= 1000
    • +
    + + + +
    + +
     
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0933.Number of Recent Calls/README_EN.md b/assets/0900-0999/0933.Number of Recent Calls/README_EN.md new file mode 100644 index 00000000..8253be0f --- /dev/null +++ b/assets/0900-0999/0933.Number of Recent Calls/README_EN.md @@ -0,0 +1,128 @@ +# [933. Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls) + + + +## Description + +

    You have a RecentCounter class which counts the number of recent requests within a certain time frame.

    + +

    Implement the RecentCounter class:

    + +
      +
    • RecentCounter() Initializes the counter with zero recent requests.
    • +
    • int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
    • +
    + +

    It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

    + +

     

    +

    Example 1:

    + +
    +Input
    +["RecentCounter", "ping", "ping", "ping", "ping"]
    +[[], [1], [100], [3001], [3002]]
    +Output
    +[null, 1, 2, 3, 3]
    +
    +Explanation
    +RecentCounter recentCounter = new RecentCounter();
    +recentCounter.ping(1);     // requests = [1], range is [-2999,1], return 1
    +recentCounter.ping(100);   // requests = [1, 100], range is [-2900,100], return 2
    +recentCounter.ping(3001);  // requests = [1, 100, 3001], range is [1,3001], return 3
    +recentCounter.ping(3002);  // requests = [1, 100, 3001, 3002], range is [2,3002], return 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= t <= 109
    • +
    • Each test case will call ping with strictly increasing values of t.
    • +
    • At most 104 calls will be made to ping.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class RecentCounter: + + def __init__(self): + self.q = collections.deque() + + def ping(self, t: int) -> int: + self.q.append(t) + while self.q[0] < t - 3000: + self.q.popleft() + return len(self.q) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) +``` + +### **Java** + +```java +class RecentCounter { + + private Deque q; + + public RecentCounter() { + q = new ArrayDeque<>(); + } + + public int ping(int t) { + q.offerLast(t); + while (q.peekFirst() < t - 3000) { + q.pollFirst(); + } + return q.size(); + } +} + +/** + * Your RecentCounter object will be instantiated and called as such: + * RecentCounter obj = new RecentCounter(); + * int param_1 = obj.ping(t); + */ +``` + +### **JavaScript** + +```js +var RecentCounter = function () { + this.q = []; +}; + +/** + * @param {number} t + * @return {number} + */ +RecentCounter.prototype.ping = function (t) { + this.q.push(t); + while (this.q[0] < t - 3000) { + this.q.shift(); + } + return this.q.length; +}; + +/** + * Your RecentCounter object will be instantiated and called as such: + * var obj = new RecentCounter() + * var param_1 = obj.ping(t) + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0934.Shortest Bridge/README_EN.md b/assets/0900-0999/0934.Shortest Bridge/README_EN.md new file mode 100644 index 00000000..5ccfaaa1 --- /dev/null +++ b/assets/0900-0999/0934.Shortest Bridge/README_EN.md @@ -0,0 +1,55 @@ +# [934. Shortest Bridge](https://leetcode.com/problems/shortest-bridge) + + + +## Description + +

    In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.)

    + +

    Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.

    + +

    Return the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is at least 1.)

    + +

     

    +

    Example 1:

    +
    Input: A = [[0,1],[1,0]]
    +Output: 1
    +

    Example 2:

    +
    Input: A = [[0,1,0],[0,0,0],[0,0,1]]
    +Output: 2
    +

    Example 3:

    +
    Input: A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
    +Output: 1
    +
    +

     

    +

    Constraints:

    + +
      +
    • 2 <= A.length == A[0].length <= 100
    • +
    • A[i][j] == 0 or A[i][j] == 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0935.Knight Dialer/README_EN.md b/assets/0900-0999/0935.Knight Dialer/README_EN.md new file mode 100644 index 00000000..4709dca2 --- /dev/null +++ b/assets/0900-0999/0935.Knight Dialer/README_EN.md @@ -0,0 +1,88 @@ +# [935. Knight Dialer](https://leetcode.com/problems/knight-dialer) + + + +## Description + +

    The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:

    + +

    A chess knight can move as indicated in the chess diagram below:

    + +

    We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).

    + +

    Given an integer n, return how many distinct phone numbers of length n we can dial.

    + +

    You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.

    + +

    As the answer may be very large, return the answer modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 10
    +Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 20
    +Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
    +
    + +

    Example 3:

    + +
    +Input: n = 3
    +Output: 46
    +
    + +

    Example 4:

    + +
    +Input: n = 4
    +Output: 104
    +
    + +

    Example 5:

    + +
    +Input: n = 3131
    +Output: 136006598
    +Explanation: Please take care of the mod.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 5000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0935.Knight Dialer/images/keypad.png b/assets/0900-0999/0935.Knight Dialer/images/keypad.png new file mode 100644 index 00000000..5f0c9794 Binary files /dev/null and b/assets/0900-0999/0935.Knight Dialer/images/keypad.png differ diff --git a/assets/0900-0999/0935.Knight Dialer/images/knight.png b/assets/0900-0999/0935.Knight Dialer/images/knight.png new file mode 100644 index 00000000..1ab55680 Binary files /dev/null and b/assets/0900-0999/0935.Knight Dialer/images/knight.png differ diff --git a/assets/0900-0999/0936.Stamping The Sequence/README_EN.md b/assets/0900-0999/0936.Stamping The Sequence/README_EN.md new file mode 100644 index 00000000..7c851dcd --- /dev/null +++ b/assets/0900-0999/0936.Stamping The Sequence/README_EN.md @@ -0,0 +1,112 @@ +# [936. Stamping The Sequence](https://leetcode.com/problems/stamping-the-sequence) + + + +## Description + +

    You want to form a target string of lowercase letters.

    + + + +

    At the beginning, your sequence is target.length '?' marks.  You also have a stamp of lowercase letters.

    + + + +

    On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp.  You can make up to 10 * target.length turns.

    + + + +

    For example, if the initial sequence is "?????", and your stamp is "abc",  then you may make "abc??", "?abc?", "??abc" in the first turn.  (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)

    + + + +

    If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn.  If the sequence is not possible to stamp, return an empty array.

    + + + +

    For example, if the sequence is "ababc", and the stamp is "abc", then we could return the answer [0, 2], corresponding to the moves "?????" -> "abc??" -> "ababc".

    + + + +

    Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within 10 * target.length moves.  Any answers specifying more than this number of moves will not be accepted.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: stamp = "abc", target = "ababc"
    +
    +Output: [0,2]
    +
    +([1,0,2] would also be accepted as an answer, as well as some other answers.)
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: stamp = "abca", target = "aabcaca"
    +
    +Output: [3,0,1]
    +
    +
    + + + +
    + +

     

    + + + +

    Note:

    + +
    + +
    + + + +
      +
    1. 1 <= stamp.length <= target.length <= 1000
    2. +
    3. stamp and target only contain lowercase letters.
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0937.Reorder Data in Log Files/README_EN.md b/assets/0900-0999/0937.Reorder Data in Log Files/README_EN.md new file mode 100644 index 00000000..8132be40 --- /dev/null +++ b/assets/0900-0999/0937.Reorder Data in Log Files/README_EN.md @@ -0,0 +1,77 @@ +# [937. Reorder Data in Log Files](https://leetcode.com/problems/reorder-data-in-log-files) + + + +## Description + +

    You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

    + +

    There are two types of logs:

    + +
      +
    • Letter-logs: All words (except the identifier) consist of lowercase English letters.
    • +
    • Digit-logs: All words (except the identifier) consist of digits.
    • +
    + +

    Reorder these logs so that:

    + +
      +
    1. The letter-logs come before all digit-logs.
    2. +
    3. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
    4. +
    5. The digit-logs maintain their relative ordering.
    6. +
    + +

    Return the final order of the logs.

    + +

     

    +

    Example 1:

    + +
    +Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
    +Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
    +Explanation:
    +The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
    +The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
    +
    + +

    Example 2:

    + +
    +Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
    +Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= logs.length <= 100
    • +
    • 3 <= logs[i].length <= 100
    • +
    • All the tokens of logs[i] are separated by a single space.
    • +
    • logs[i] is guaranteed to have an identifier and at least one word after the identifier.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0938.Range Sum of BST/README_EN.md b/assets/0900-0999/0938.Range Sum of BST/README_EN.md new file mode 100644 index 00000000..31e15e77 --- /dev/null +++ b/assets/0900-0999/0938.Range Sum of BST/README_EN.md @@ -0,0 +1,76 @@ +# [938. Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst) + + + +## Description + +

    Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
    +
    +Output: 32
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
    +
    +Output: 23
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is in the range [1, 2 * 104].
    • +
    • 1 <= Node.val <= 105
    • +
    • 1 <= low <= high <= 105
    • +
    • All Node.val are unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0938.Range Sum of BST/images/bst1.jpg b/assets/0900-0999/0938.Range Sum of BST/images/bst1.jpg new file mode 100644 index 00000000..42de4a78 Binary files /dev/null and b/assets/0900-0999/0938.Range Sum of BST/images/bst1.jpg differ diff --git a/assets/0900-0999/0938.Range Sum of BST/images/bst2.jpg b/assets/0900-0999/0938.Range Sum of BST/images/bst2.jpg new file mode 100644 index 00000000..91f3f64b Binary files /dev/null and b/assets/0900-0999/0938.Range Sum of BST/images/bst2.jpg differ diff --git a/assets/0900-0999/0939.Minimum Area Rectangle/README_EN.md b/assets/0900-0999/0939.Minimum Area Rectangle/README_EN.md new file mode 100644 index 00000000..27263bb4 --- /dev/null +++ b/assets/0900-0999/0939.Minimum Area Rectangle/README_EN.md @@ -0,0 +1,92 @@ +# [939. Minimum Area Rectangle](https://leetcode.com/problems/minimum-area-rectangle) + + + +## Description + +

    Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.

    + + + +

    If there isn't any rectangle, return 0.

    + + + +

     

    + + + +
    + +

    Example 1:

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

    Example 2:

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

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= points.length <= 500
    2. +
    3. 0 <= points[i][0] <= 40000
    4. +
    5. 0 <= points[i][1] <= 40000
    6. +
    7. All points are distinct.
    8. +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0940.Distinct Subsequences II/README_EN.md b/assets/0900-0999/0940.Distinct Subsequences II/README_EN.md new file mode 100644 index 00000000..a999c3b6 --- /dev/null +++ b/assets/0900-0999/0940.Distinct Subsequences II/README_EN.md @@ -0,0 +1,130 @@ +# [940. Distinct Subsequences II](https://leetcode.com/problems/distinct-subsequences-ii) + + + +## Description + +

    Given a string S, count the number of distinct, non-empty subsequences of S .

    + + + +

    Since the result may be large, return the answer modulo 10^9 + 7.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "abc"
    +
    +Output: 7
    +
    +Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "aba"
    +
    +Output: 6
    +
    +Explanation: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa" and "aba".
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "aaa"
    +
    +Output: 3
    +
    +Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".
    +
    +
    + +
    + +
    + + + +

     

    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. S contains only lowercase letters.
    2. +
    3. 1 <= S.length <= 2000
    4. +
    + + + +
    + +

     

    + + + +
    + +
     
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0941.Valid Mountain Array/README_EN.md b/assets/0900-0999/0941.Valid Mountain Array/README_EN.md new file mode 100644 index 00000000..457030de --- /dev/null +++ b/assets/0900-0999/0941.Valid Mountain Array/README_EN.md @@ -0,0 +1,63 @@ +# [941. Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array) + + + +## Description + +

    Given an array of integers arr, return true if and only if it is a valid mountain array.

    + +

    Recall that arr is a mountain array if and only if:

    + +
      +
    • arr.length >= 3
    • +
    • There exists some i with 0 < i < arr.length - 1 such that: +
        +
      • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
      • +
      • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

     

    +

    Example 1:

    +
    Input: arr = [2,1]
    +Output: false
    +

    Example 2:

    +
    Input: arr = [3,5,5]
    +Output: false
    +

    Example 3:

    +
    Input: arr = [0,3,2,1]
    +Output: true
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 0 <= arr[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0941.Valid Mountain Array/images/hint_valid_mountain_array.png b/assets/0900-0999/0941.Valid Mountain Array/images/hint_valid_mountain_array.png new file mode 100644 index 00000000..faa205a2 Binary files /dev/null and b/assets/0900-0999/0941.Valid Mountain Array/images/hint_valid_mountain_array.png differ diff --git a/assets/0900-0999/0942.DI String Match/README_EN.md b/assets/0900-0999/0942.DI String Match/README_EN.md new file mode 100644 index 00000000..e0154b54 --- /dev/null +++ b/assets/0900-0999/0942.DI String Match/README_EN.md @@ -0,0 +1,58 @@ +# [942. DI String Match](https://leetcode.com/problems/di-string-match) + + + +## Description + +

    A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

    + +
      +
    • s[i] == 'I' if perm[i] < perm[i + 1], and
    • +
    • s[i] == 'D' if perm[i] > perm[i + 1].
    • +
    + +

    Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

    + +

     

    +

    Example 1:

    +
    Input: s = "IDID"
    +Output: [0,4,1,3,2]
    +

    Example 2:

    +
    Input: s = "III"
    +Output: [0,1,2,3]
    +

    Example 3:

    +
    Input: s = "DDI"
    +Output: [3,2,0,1]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s[i] is either 'I' or 'D'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0943.Find the Shortest Superstring/README_EN.md b/assets/0900-0999/0943.Find the Shortest Superstring/README_EN.md new file mode 100644 index 00000000..cdf9e3af --- /dev/null +++ b/assets/0900-0999/0943.Find the Shortest Superstring/README_EN.md @@ -0,0 +1,60 @@ +# [943. Find the Shortest Superstring](https://leetcode.com/problems/find-the-shortest-superstring) + + + +## Description + +

    Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.

    + +

    You may assume that no string in words is a substring of another string in words.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["alex","loves","leetcode"]
    +Output: "alexlovesleetcode"
    +Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
    +
    + +

    Example 2:

    + +
    +Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"]
    +Output: "gctaagttcatgcatc"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 12
    • +
    • 1 <= words[i].length <= 20
    • +
    • words[i] consists of lowercase English letters.
    • +
    • All the strings of words are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md b/assets/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md new file mode 100644 index 00000000..ee860907 --- /dev/null +++ b/assets/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md @@ -0,0 +1,90 @@ +# [944. Delete Columns to Make Sorted](https://leetcode.com/problems/delete-columns-to-make-sorted) + + + +## Description + +

    You are given an array of n strings strs, all of the same length.

    + +

    The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as:

    + +
    +abc
    +bce
    +cae
    +
    + +

    You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.

    + +

    Return the number of columns that you will delete.

    + +

     

    +

    Example 1:

    + +
    +Input: strs = ["cba","daf","ghi"]
    +Output: 1
    +Explanation: The grid looks as follows:
    +  cba
    +  daf
    +  ghi
    +Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
    +
    + +

    Example 2:

    + +
    +Input: strs = ["a","b"]
    +Output: 0
    +Explanation: The grid looks as follows:
    +  a
    +  b
    +Column 0 is the only column and is sorted, so you will not delete any columns.
    +
    + +

    Example 3:

    + +
    +Input: strs = ["zyx","wvu","tsr"]
    +Output: 3
    +Explanation: The grid looks as follows:
    +  zyx
    +  wvu
    +  tsr
    +All 3 columns are not sorted, so you will delete all 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == strs.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= strs[i].length <= 1000
    • +
    • strs[i] consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0944.Delete Columns to Make Sorted/images/944_1.png b/assets/0900-0999/0944.Delete Columns to Make Sorted/images/944_1.png new file mode 100644 index 00000000..2db2aa1c Binary files /dev/null and b/assets/0900-0999/0944.Delete Columns to Make Sorted/images/944_1.png differ diff --git a/assets/0900-0999/0944.Delete Columns to Make Sorted/images/944_2.png b/assets/0900-0999/0944.Delete Columns to Make Sorted/images/944_2.png new file mode 100644 index 00000000..3839f2f6 Binary files /dev/null and b/assets/0900-0999/0944.Delete Columns to Make Sorted/images/944_2.png differ diff --git a/assets/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md b/assets/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md new file mode 100644 index 00000000..86fb322d --- /dev/null +++ b/assets/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md @@ -0,0 +1,100 @@ +# [945. Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique) + + + +## Description + +

    Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.

    + + + +

    Return the least number of moves to make every value in A unique.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [1,2,2]
    +
    +Output: 1
    +
    +Explanation:  After 1 move, the array could be [1, 2, 3].
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [3,2,1,2,1,7]
    +
    +Output: 6
    +
    +Explanation:  After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
    +
    +It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
    +
    +
    + + + +

     

    + +
    + + + +

    Note:

    + + + +
      +
    1. 0 <= A.length <= 40000
    2. +
    3. 0 <= A[i] < 40000
    4. +
    + + + +
    + +
     
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0946.Validate Stack Sequences/README_EN.md b/assets/0900-0999/0946.Validate Stack Sequences/README_EN.md new file mode 100644 index 00000000..0121723b --- /dev/null +++ b/assets/0900-0999/0946.Validate Stack Sequences/README_EN.md @@ -0,0 +1,66 @@ +# [946. Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences) + + + +## Description + +

    Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

    + +

     

    + +
    +

    Example 1:

    + +
    +Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    +Output: true
    +Explanation: We might do the following sequence:
    +push(1), push(2), push(3), push(4), pop() -> 4,
    +push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
    +
    + +
    +

    Example 2:

    + +
    +Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
    +Output: false
    +Explanation: 1 cannot be popped before 2.
    +
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= pushed.length == popped.length <= 1000
    • +
    • 0 <= pushed[i], popped[i] < 1000
    • +
    • pushed is a permutation of popped.
    • +
    • pushed and popped have distinct values.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md b/assets/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md new file mode 100644 index 00000000..8c591ef1 --- /dev/null +++ b/assets/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md @@ -0,0 +1,80 @@ +# [947. Most Stones Removed with Same Row or Column](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column) + + + +## Description + +

    On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.

    + +

    A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.

    + +

    Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.

    + +

     

    +

    Example 1:

    + +
    +Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
    +Output: 5
    +Explanation: One way to remove 5 stones is as follows:
    +1. Remove stone [2,2] because it shares the same row as [2,1].
    +2. Remove stone [2,1] because it shares the same column as [0,1].
    +3. Remove stone [1,2] because it shares the same row as [1,0].
    +4. Remove stone [1,0] because it shares the same column as [0,0].
    +5. Remove stone [0,1] because it shares the same row as [0,0].
    +Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.
    +
    + +

    Example 2:

    + +
    +Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
    +Output: 3
    +Explanation: One way to make 3 moves is as follows:
    +1. Remove stone [2,2] because it shares the same row as [2,0].
    +2. Remove stone [2,0] because it shares the same column as [0,0].
    +3. Remove stone [0,2] because it shares the same row as [0,0].
    +Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.
    +
    + +

    Example 3:

    + +
    +Input: stones = [[0,0]]
    +Output: 0
    +Explanation: [0,0] is the only stone on the plane, so you cannot remove it.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= stones.length <= 1000
    • +
    • 0 <= xi, yi <= 104
    • +
    • No two stones are at the same coordinate point.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0948.Bag of Tokens/README_EN.md b/assets/0900-0999/0948.Bag of Tokens/README_EN.md new file mode 100644 index 00000000..165ee631 --- /dev/null +++ b/assets/0900-0999/0948.Bag of Tokens/README_EN.md @@ -0,0 +1,123 @@ +# [948. Bag of Tokens](https://leetcode.com/problems/bag-of-tokens) + + + +## Description + +

    You have an initial power of P, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed).

    + + + +

    Your goal is to maximize your total score by potentially playing each token in one of two ways:

    + + + +
      +
    • If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score.
    • +
    • If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score.
    • +
    + + + +

    Each token may be played at most once and in any order. You do not have to play all the tokens.

    + + + +

    Return the largest possible score you can achieve after playing any number of tokens.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: tokens = [100], P = 50
    +
    +Output: 0
    +
    +Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: tokens = [100,200], P = 150
    +
    +Output: 1
    +
    +Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
    +
    +There is no need to play the 1st token since you cannot play it face up to add to your score.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: tokens = [100,200,300,400], P = 200
    +
    +Output: 2
    +
    +Explanation: Play the tokens in this order to get a score of 2:
    +
    +1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
    +
    +2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
    +
    +3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
    +
    +4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= tokens.length <= 1000
    • +
    • 0 <= tokens[i], P < 104
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0949.Largest Time for Given Digits/README_EN.md b/assets/0900-0999/0949.Largest Time for Given Digits/README_EN.md new file mode 100644 index 00000000..d2a912ca --- /dev/null +++ b/assets/0900-0999/0949.Largest Time for Given Digits/README_EN.md @@ -0,0 +1,75 @@ +# [949. Largest Time for Given Digits](https://leetcode.com/problems/largest-time-for-given-digits) + + + +## Description + +

    Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.

    + +

    24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.

    + +

    Return the latest 24-hour time in "HH:MM" format.  If no valid time can be made, return an empty string.

    + +

     

    +

    Example 1:

    + +
    +Input: A = [1,2,3,4]
    +Output: "23:41"
    +Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.
    +
    + +

    Example 2:

    + +
    +Input: A = [5,5,5,5]
    +Output: ""
    +Explanation: There are no valid 24-hour times as "55:55" is not valid.
    +
    + +

    Example 3:

    + +
    +Input: A = [0,0,0,0]
    +Output: "00:00"
    +
    + +

    Example 4:

    + +
    +Input: A = [0,0,1,0]
    +Output: "10:00"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • arr.length == 4
    • +
    • 0 <= arr[i] <= 9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md b/assets/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md new file mode 100644 index 00000000..36c25359 --- /dev/null +++ b/assets/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md @@ -0,0 +1,121 @@ +# [950. Reveal Cards In Increasing Order](https://leetcode.com/problems/reveal-cards-in-increasing-order) + + + +## Description + +

    In a deck of cards, every card has a unique integer.  You can order the deck in any order you want.

    + + + +

    Initially, all the cards start face down (unrevealed) in one deck.

    + + + +

    Now, you do the following steps repeatedly, until all cards are revealed:

    + + + +
      +
    1. Take the top card of the deck, reveal it, and take it out of the deck.
    2. +
    3. If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.
    4. +
    5. If there are still unrevealed cards, go back to step 1.  Otherwise, stop.
    6. +
    + + + +

    Return an ordering of the deck that would reveal the cards in increasing order.

    + + + +

    The first entry in the answer is considered to be the top of the deck.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: [17,13,11,2,3,5,7]
    +
    +Output: [2,13,3,11,5,17,7]
    +
    +Explanation: 
    +
    +We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
    +
    +After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
    +
    +We reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].
    +
    +We reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].
    +
    +We reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].
    +
    +We reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].
    +
    +We reveal 11, and move 17 to the bottom.  The deck is now [13,17].
    +
    +We reveal 13, and move 17 to the bottom.  The deck is now [17].
    +
    +We reveal 17.
    +
    +Since all the cards revealed are in increasing order, the answer is correct.
    +
    +
    + + + +
    + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 1000
    2. +
    3. 1 <= A[i] <= 10^6
    4. +
    5. A[i] != A[j] for all i != j
    6. +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md b/assets/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md new file mode 100644 index 00000000..86ad765d --- /dev/null +++ b/assets/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md @@ -0,0 +1,81 @@ +# [951. Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees) + + + +## Description + +

    For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.

    + +

    A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.

    + +

    Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivelent or false otherwise.

    + +

     

    +

    Example 1:

    +Flipped Trees Diagram +
    +Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
    +Output: true
    +Explanation: We flipped at nodes with values 1, 3, and 5.
    +
    + +

    Example 2:

    + +
    +Input: root1 = [], root2 = []
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: root1 = [], root2 = [1]
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: root1 = [0,null,1], root2 = []
    +Output: false
    +
    + +

    Example 5:

    + +
    +Input: root1 = [0,null,1], root2 = [0,1]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in each tree is in the range [0, 100].
    • +
    • Each tree will have unique node values in the range [0, 99].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0951.Flip Equivalent Binary Trees/images/tree_ex.png b/assets/0900-0999/0951.Flip Equivalent Binary Trees/images/tree_ex.png new file mode 100644 index 00000000..b77b5f16 Binary files /dev/null and b/assets/0900-0999/0951.Flip Equivalent Binary Trees/images/tree_ex.png differ diff --git a/assets/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md b/assets/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md new file mode 100644 index 00000000..00b22e09 --- /dev/null +++ b/assets/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md @@ -0,0 +1,125 @@ +# [952. Largest Component Size by Common Factor](https://leetcode.com/problems/largest-component-size-by-common-factor) + + + +## Description + +

    Given a non-empty array of unique positive integers A, consider the following graph:

    + + + +
      +
    • There are A.length nodes, labelled A[0] to A[A.length - 1];
    • +
    • There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1.
    • +
    + + + +

    Return the size of the largest connected component in the graph.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: [4,6,15,35]
    +
    +Output: 4
    +
    +
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [20,50,9,63]
    +
    +Output: 2
    +
    +
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: [2,3,6,7,4,12,21,39]
    +
    +Output: 8
    +
    +
    +
    +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 20000
    2. +
    3. 1 <= A[i] <= 100000
    4. +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex1.png b/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex1.png new file mode 100644 index 00000000..6d2e836d Binary files /dev/null and b/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex1.png differ diff --git a/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex2.png b/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex2.png new file mode 100644 index 00000000..e50c7ec5 Binary files /dev/null and b/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex2.png differ diff --git a/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex3.png b/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex3.png new file mode 100644 index 00000000..40445d1d Binary files /dev/null and b/assets/0900-0999/0952.Largest Component Size by Common Factor/images/ex3.png differ diff --git a/assets/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md b/assets/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md new file mode 100644 index 00000000..b55e6cff --- /dev/null +++ b/assets/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md @@ -0,0 +1,105 @@ +# [953. Verifying an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary) + + + +## Description + +

    In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

    + +

    Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

    +

     

    +

    Example 1:

    + +
    +Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
    +Output: true
    +Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
    +
    + +

    Example 2:

    + +
    +Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
    +Output: false
    +Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
    +
    + +

    Example 3:

    + +
    +Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
    +Output: false
    +Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 100
    • +
    • 1 <= words[i].length <= 20
    • +
    • order.length == 26
    • +
    • All characters in words[i] and order are English lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isAlienSorted(self, words: List[str], order: str) -> bool: + index = {v: k for k, v in enumerate(order)} + for i in range(len(words) - 1): + word1, word2 = words[i], words[i + 1] + len1, len2 = len(word1), len(word2) + flag = True + for j in range(min(len1, len2)): + diff = index[word1[j]] - index[word2[j]] + if diff > 0: + return False + if diff < 0: + flag = False + break + if flag and len1 > len2: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean isAlienSorted(String[] words, String order) { + int[] index = new int[26]; + for (int i = 0; i < 26; ++i) { + index[order.charAt(i) - 'a'] = i; + } + for (int i = 0, m = words.length; i < m - 1; ++i) { + String word1 = words[i]; + String word2 = words[i + 1]; + int len1 = word1.length(); + int len2 = word2.length(); + boolean flag = true; + for (int j = 0, n = Math.min(len1, len2); j < n && flag; ++j) { + int diff = index[word1.charAt(j) - 'a'] - index[word2.charAt(j) - 'a']; + if (diff > 0) return false; + if (diff < 0) flag = false; + } + if (flag && len1 > len2) return false; + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0954.Array of Doubled Pairs/README_EN.md b/assets/0900-0999/0954.Array of Doubled Pairs/README_EN.md new file mode 100644 index 00000000..f1f93243 --- /dev/null +++ b/assets/0900-0999/0954.Array of Doubled Pairs/README_EN.md @@ -0,0 +1,71 @@ +# [954. Array of Doubled Pairs](https://leetcode.com/problems/array-of-doubled-pairs) + + + +## Description + +

    Given an array of integers arr of even length, return true if and only if it is possible to reorder it such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,1,3,6]
    +Output: false
    +
    + +

    Example 2:

    + +
    +Input: arr = [2,1,2,6]
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: arr = [4,-2,2,-4]
    +Output: true
    +Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
    +
    + +

    Example 4:

    + +
    +Input: arr = [1,2,4,16,8,4]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= arr.length <= 3 * 104
    • +
    • arr.length is even.
    • +
    • -105 <= arr[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md b/assets/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md new file mode 100644 index 00000000..ef5692f9 --- /dev/null +++ b/assets/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md @@ -0,0 +1,79 @@ +# [955. Delete Columns to Make Sorted II](https://leetcode.com/problems/delete-columns-to-make-sorted-ii) + + + +## Description + +

    You are given an array of n strings strs, all of the same length.

    + +

    We may choose any deletion indices, and we delete all the characters in those indices for each string.

    + +

    For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"].

    + +

    Suppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.

    + +

     

    +

    Example 1:

    + +
    +Input: strs = ["ca","bb","ac"]
    +Output: 1
    +Explanation: 
    +After deleting the first column, strs = ["a", "b", "c"].
    +Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).
    +We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
    +
    + +

    Example 2:

    + +
    +Input: strs = ["xc","yb","za"]
    +Output: 0
    +Explanation: 
    +strs is already in lexicographic order, so we do not need to delete anything.
    +Note that the rows of strs are not necessarily in lexicographic order:
    +i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)
    +
    + +

    Example 3:

    + +
    +Input: strs = ["zyx","wvu","tsr"]
    +Output: 3
    +Explanation: We have to delete every column.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == strs.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= strs[i].length <= 100
    • +
    • strs[i] consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0956.Tallest Billboard/README_EN.md b/assets/0900-0999/0956.Tallest Billboard/README_EN.md new file mode 100644 index 00000000..a7728eb0 --- /dev/null +++ b/assets/0900-0999/0956.Tallest Billboard/README_EN.md @@ -0,0 +1,70 @@ +# [956. Tallest Billboard](https://leetcode.com/problems/tallest-billboard) + + + +## Description + +

    You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.

    + +

    You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.

    + +

    Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.

    + +

     

    +

    Example 1:

    + +
    +Input: rods = [1,2,3,6]
    +Output: 6
    +Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
    +
    + +

    Example 2:

    + +
    +Input: rods = [1,2,3,4,5,6]
    +Output: 10
    +Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
    +
    + +

    Example 3:

    + +
    +Input: rods = [1,2]
    +Output: 0
    +Explanation: The billboard cannot be supported, so we return 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= rods.length <= 20
    • +
    • 1 <= rods[i] <= 1000
    • +
    • sum(rods[i]) <= 5000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0957.Prison Cells After N Days/README_EN.md b/assets/0900-0999/0957.Prison Cells After N Days/README_EN.md new file mode 100644 index 00000000..19b47b43 --- /dev/null +++ b/assets/0900-0999/0957.Prison Cells After N Days/README_EN.md @@ -0,0 +1,78 @@ +# [957. Prison Cells After N Days](https://leetcode.com/problems/prison-cells-after-n-days) + + + +## Description + +

    There are 8 prison cells in a row and each cell is either occupied or vacant.

    + +

    Each day, whether the cell is occupied or vacant changes according to the following rules:

    + +
      +
    • If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
    • +
    • Otherwise, it becomes vacant.
    • +
    + +

    Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.

    + +

    You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.

    + +

    Return the state of the prison after n days (i.e., n such changes described above).

    + +

     

    +

    Example 1:

    + +
    +Input: cells = [0,1,0,1,1,0,0,1], n = 7
    +Output: [0,0,1,1,0,0,0,0]
    +Explanation: The following table summarizes the state of the prison on each day:
    +Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
    +Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
    +Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
    +Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
    +Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
    +Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
    +Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
    +Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
    +
    + +

    Example 2:

    + +
    +Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000
    +Output: [0,0,1,1,1,1,1,0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • cells.length == 8
    • +
    • cells[i] is either 0 or 1.
    • +
    • 1 <= n <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md b/assets/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md new file mode 100644 index 00000000..307b03d5 --- /dev/null +++ b/assets/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md @@ -0,0 +1,59 @@ +# [958. Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree) + + + +## Description + +

    Given the root of a binary tree, determine if it is a complete binary tree.

    + +

    In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,2,3,4,5,6]
    +Output: true
    +Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
    +
    + +

    Example 2:

    + +
    +Input: root = [1,2,3,4,5,null,7]
    +Output: false
    +Explanation: The node with value 7 isn't as far left as possible.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 100].
    • +
    • 1 <= Node.val <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0958.Check Completeness of a Binary Tree/images/complete-binary-tree-1.png b/assets/0900-0999/0958.Check Completeness of a Binary Tree/images/complete-binary-tree-1.png new file mode 100644 index 00000000..c66927b8 Binary files /dev/null and b/assets/0900-0999/0958.Check Completeness of a Binary Tree/images/complete-binary-tree-1.png differ diff --git a/assets/0900-0999/0958.Check Completeness of a Binary Tree/images/complete-binary-tree-2.png b/assets/0900-0999/0958.Check Completeness of a Binary Tree/images/complete-binary-tree-2.png new file mode 100644 index 00000000..9907668f Binary files /dev/null and b/assets/0900-0999/0958.Check Completeness of a Binary Tree/images/complete-binary-tree-2.png differ diff --git a/assets/0900-0999/0959.Regions Cut By Slashes/README_EN.md b/assets/0900-0999/0959.Regions Cut By Slashes/README_EN.md new file mode 100644 index 00000000..6f706a07 --- /dev/null +++ b/assets/0900-0999/0959.Regions Cut By Slashes/README_EN.md @@ -0,0 +1,238 @@ +# [959. Regions Cut By Slashes](https://leetcode.com/problems/regions-cut-by-slashes) + + + +## Description + +

    In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space.  These characters divide the square into contiguous regions.

    + + + +

    (Note that backslash characters are escaped, so a \ is represented as "\\".)

    + + + +

    Return the number of regions.

    + + + +

     

    + + + +
    + +
    + +
    + +
    + +
    + +
      + +
    + +
    + +
    + +
    + +
    + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input:
    +
    +[
    +
    +  " /",
    +
    +  "/ "
    +
    +]
    +
    +Output: 2
    +
    +Explanation: The 2x2 grid is as follows:
    +
    +
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input:
    +
    +[
    +
    +  " /",
    +
    +  "  "
    +
    +]
    +
    +Output: 1
    +
    +Explanation: The 2x2 grid is as follows:
    +
    +
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input:
    +
    +[
    +
    +  "\\/",
    +
    +  "/\\"
    +
    +]
    +
    +Output: 4
    +
    +Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.)
    +
    +The 2x2 grid is as follows:
    +
    +
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input:
    +
    +[
    +
    +  "/\\",
    +
    +  "\\/"
    +
    +]
    +
    +Output: 5
    +
    +Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.)
    +
    +The 2x2 grid is as follows:
    +
    +
    +
    +
    + + + +
    + +

    Example 5:

    + + + +
    +
    +Input:
    +
    +[
    +
    +  "//",
    +
    +  "/ "
    +
    +]
    +
    +Output: 3
    +
    +Explanation: The 2x2 grid is as follows:
    +
    +
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= grid.length == grid[0].length <= 30
    2. +
    3. grid[i][j] is either '/', '\', or ' '.
    4. +
    + +
    + +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0959.Regions Cut By Slashes/images/1.png b/assets/0900-0999/0959.Regions Cut By Slashes/images/1.png new file mode 100644 index 00000000..affa4207 Binary files /dev/null and b/assets/0900-0999/0959.Regions Cut By Slashes/images/1.png differ diff --git a/assets/0900-0999/0959.Regions Cut By Slashes/images/2.png b/assets/0900-0999/0959.Regions Cut By Slashes/images/2.png new file mode 100644 index 00000000..815909f9 Binary files /dev/null and b/assets/0900-0999/0959.Regions Cut By Slashes/images/2.png differ diff --git a/assets/0900-0999/0959.Regions Cut By Slashes/images/3.png b/assets/0900-0999/0959.Regions Cut By Slashes/images/3.png new file mode 100644 index 00000000..87b813ab Binary files /dev/null and b/assets/0900-0999/0959.Regions Cut By Slashes/images/3.png differ diff --git a/assets/0900-0999/0959.Regions Cut By Slashes/images/4.png b/assets/0900-0999/0959.Regions Cut By Slashes/images/4.png new file mode 100644 index 00000000..ec0025ef Binary files /dev/null and b/assets/0900-0999/0959.Regions Cut By Slashes/images/4.png differ diff --git a/assets/0900-0999/0959.Regions Cut By Slashes/images/5.png b/assets/0900-0999/0959.Regions Cut By Slashes/images/5.png new file mode 100644 index 00000000..96b334eb Binary files /dev/null and b/assets/0900-0999/0959.Regions Cut By Slashes/images/5.png differ diff --git a/assets/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md b/assets/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md new file mode 100644 index 00000000..67908621 --- /dev/null +++ b/assets/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md @@ -0,0 +1,78 @@ +# [960. Delete Columns to Make Sorted III](https://leetcode.com/problems/delete-columns-to-make-sorted-iii) + + + +## Description + +

    You are given an array of n strings strs, all of the same length.

    + +

    We may choose any deletion indices, and we delete all the characters in those indices for each string.

    + +

    For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"].

    + +

    Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.

    + +

     

    +

    Example 1:

    + +
    +Input: strs = ["babca","bbazb"]
    +Output: 3
    +Explanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].
    +Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).
    +Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.
    + +

    Example 2:

    + +
    +Input: strs = ["edcba"]
    +Output: 4
    +Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.
    +
    + +

    Example 3:

    + +
    +Input: strs = ["ghi","def","abc"]
    +Output: 0
    +Explanation: All rows are already lexicographically sorted.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == strs.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= strs[i].length <= 100
    • +
    • strs[i] consists of lowercase English letters.
    • +
    + +
      +
    •  
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md b/assets/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md new file mode 100644 index 00000000..11f9b445 --- /dev/null +++ b/assets/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md @@ -0,0 +1,130 @@ +# [961. N-Repeated Element in Size 2N Array](https://leetcode.com/problems/n-repeated-element-in-size-2n-array) + + + +## Description + +

    In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

    + +

    Return the element repeated N times.

    + +

     

    + +
      +
    + +
    +

    Example 1:

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

    Example 2:

    + +
    +Input: [2,1,2,5,3,2]
    +Output: 2
    +
    + +
    +

    Example 3:

    + +
    +Input: [5,1,5,2,5,3,5,4]
    +Output: 5
    +
    + +

     

    + +

    Note:

    + +
      +
    • 4 <= A.length <= 10000
    • +
    • 0 <= A[i] < 10000
    • +
    • A.length is even
    • +
    +
    +
    +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def repeatedNTimes(self, nums: List[int]) -> int: + s = set() + for num in nums: + if num in s: + return num + s.add(num) +``` + +### **Java** + +```java +class Solution { + public int repeatedNTimes(int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + if (s.contains(num)) { + return num; + } + s.add(num); + } + return -1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int repeatedNTimes(vector& nums) { + unordered_set s; + for (auto &num : nums) { + if (s.find(num) != s.end()) { + return num; + } + s.insert(num); + } + return -1; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var repeatedNTimes = function(nums) { + const s = new Set(); + for (const num of nums) { + if (s.has(num)) { + return num; + } + s.add(num); + } + return -1; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0962.Maximum Width Ramp/README_EN.md b/assets/0900-0999/0962.Maximum Width Ramp/README_EN.md new file mode 100644 index 00000000..2bef641a --- /dev/null +++ b/assets/0900-0999/0962.Maximum Width Ramp/README_EN.md @@ -0,0 +1,112 @@ +# [962. Maximum Width Ramp](https://leetcode.com/problems/maximum-width-ramp) + + + +## Description + +

    Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j].  The width of such a ramp is j - i.

    + + + +

    Find the maximum width of a ramp in A.  If one doesn't exist, return 0.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [6,0,8,2,1,5]
    +
    +Output: 4
    +
    +Explanation: 
    +
    +The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [9,8,1,0,1,9,4,0,4,1]
    +
    +Output: 7
    +
    +Explanation: 
    +
    +The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.
    +
    +
    + +
    + + + +
    + +
    + +

     

    + + + +

    Note:

    + + + +
      +
    1. 2 <= A.length <= 50000
    2. +
    3. 0 <= A[i] <= 50000
    4. +
    + +
    + +
    + + + +
    + +
     
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0963.Minimum Area Rectangle II/README_EN.md b/assets/0900-0999/0963.Minimum Area Rectangle II/README_EN.md new file mode 100644 index 00000000..78290938 --- /dev/null +++ b/assets/0900-0999/0963.Minimum Area Rectangle II/README_EN.md @@ -0,0 +1,151 @@ +# [963. Minimum Area Rectangle II](https://leetcode.com/problems/minimum-area-rectangle-ii) + + + +## Description + +

    Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.

    + + + +

    If there isn't any rectangle, return 0.

    + + + +

     

    + + + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: [[1,2],[2,1],[1,0],[0,1]]
    +
    +Output: 2.00000
    +
    +Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
    +
    +Output: 1.00000
    +
    +Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: [[0,3],[1,2],[3,1],[1,3],[2,1]]
    +
    +Output: 0
    +
    +Explanation: There is no possible rectangle to form from these points.
    +
    +
    + + + +
    + +

    Example 4:

    + + + +

    + + + +
    +
    +Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
    +
    +Output: 2.00000
    +
    +Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.
    +
    +
    + +
    + + + +

     

    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= points.length <= 50
    2. +
    3. 0 <= points[i][0] <= 40000
    4. +
    5. 0 <= points[i][1] <= 40000
    6. +
    7. All points are distinct.
    8. +
    9. Answers within 10^-5 of the actual value will be accepted as correct.
    10. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0963.Minimum Area Rectangle II/images/1a.png b/assets/0900-0999/0963.Minimum Area Rectangle II/images/1a.png new file mode 100644 index 00000000..6d76c285 Binary files /dev/null and b/assets/0900-0999/0963.Minimum Area Rectangle II/images/1a.png differ diff --git a/assets/0900-0999/0963.Minimum Area Rectangle II/images/2.png b/assets/0900-0999/0963.Minimum Area Rectangle II/images/2.png new file mode 100644 index 00000000..85a7b4d5 Binary files /dev/null and b/assets/0900-0999/0963.Minimum Area Rectangle II/images/2.png differ diff --git a/assets/0900-0999/0963.Minimum Area Rectangle II/images/3.png b/assets/0900-0999/0963.Minimum Area Rectangle II/images/3.png new file mode 100644 index 00000000..c049c044 Binary files /dev/null and b/assets/0900-0999/0963.Minimum Area Rectangle II/images/3.png differ diff --git a/assets/0900-0999/0963.Minimum Area Rectangle II/images/4c.png b/assets/0900-0999/0963.Minimum Area Rectangle II/images/4c.png new file mode 100644 index 00000000..5c35a6c3 Binary files /dev/null and b/assets/0900-0999/0963.Minimum Area Rectangle II/images/4c.png differ diff --git a/assets/0900-0999/0964.Least Operators to Express Number/README_EN.md b/assets/0900-0999/0964.Least Operators to Express Number/README_EN.md new file mode 100644 index 00000000..2fc2a958 --- /dev/null +++ b/assets/0900-0999/0964.Least Operators to Express Number/README_EN.md @@ -0,0 +1,79 @@ +# [964. Least Operators to Express Number](https://leetcode.com/problems/least-operators-to-express-number) + + + +## Description + +

    Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.

    + +

    When writing such an expression, we adhere to the following conventions:

    + +
      +
    • The division operator (/) returns rational numbers.
    • +
    • There are no parentheses placed anywhere.
    • +
    • We use the usual order of operations: multiplication and division happen before addition and subtraction.
    • +
    • It is not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation.
    • +
    + +

    We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.

    + +

     

    +

    Example 1:

    + +
    +Input: x = 3, target = 19
    +Output: 5
    +Explanation: 3 * 3 + 3 * 3 + 3 / 3.
    +The expression contains 5 operations.
    +
    + +

    Example 2:

    + +
    +Input: x = 5, target = 501
    +Output: 8
    +Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.
    +The expression contains 8 operations.
    +
    + +

    Example 3:

    + +
    +Input: x = 100, target = 100000000
    +Output: 3
    +Explanation: 100 * 100 * 100 * 100.
    +The expression contains 3 operations.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= x <= 100
    • +
    • 1 <= target <= 2 * 108
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0965.Univalued Binary Tree/README_EN.md b/assets/0900-0999/0965.Univalued Binary Tree/README_EN.md new file mode 100644 index 00000000..5dd54c63 --- /dev/null +++ b/assets/0900-0999/0965.Univalued Binary Tree/README_EN.md @@ -0,0 +1,88 @@ +# [965. Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree) + + + +## Description + +

    A binary tree is univalued if every node in the tree has the same value.

    + + + +

    Return true if and only if the given tree is univalued.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [1,1,1,1,1,null,1]
    +
    +Output: true
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [2,2,2,5,2]
    +
    +Output: false
    +
    +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. The number of nodes in the given tree will be in the range [1, 100].
    2. +
    3. Each node's value will be an integer in the range [0, 99].
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0965.Univalued Binary Tree/images/screen-shot-2018-12-25-at-50050-pm.png b/assets/0900-0999/0965.Univalued Binary Tree/images/screen-shot-2018-12-25-at-50050-pm.png new file mode 100644 index 00000000..0b2fb03e Binary files /dev/null and b/assets/0900-0999/0965.Univalued Binary Tree/images/screen-shot-2018-12-25-at-50050-pm.png differ diff --git a/assets/0900-0999/0965.Univalued Binary Tree/images/screen-shot-2018-12-25-at-50104-pm.png b/assets/0900-0999/0965.Univalued Binary Tree/images/screen-shot-2018-12-25-at-50104-pm.png new file mode 100644 index 00000000..97471b6b Binary files /dev/null and b/assets/0900-0999/0965.Univalued Binary Tree/images/screen-shot-2018-12-25-at-50104-pm.png differ diff --git a/assets/0900-0999/0965.Univalued Binary Tree/images/unival_bst_1.png b/assets/0900-0999/0965.Univalued Binary Tree/images/unival_bst_1.png new file mode 100644 index 00000000..ef2b30b1 Binary files /dev/null and b/assets/0900-0999/0965.Univalued Binary Tree/images/unival_bst_1.png differ diff --git a/assets/0900-0999/0965.Univalued Binary Tree/images/unival_bst_2.png b/assets/0900-0999/0965.Univalued Binary Tree/images/unival_bst_2.png new file mode 100644 index 00000000..2c747dcc Binary files /dev/null and b/assets/0900-0999/0965.Univalued Binary Tree/images/unival_bst_2.png differ diff --git a/assets/0900-0999/0966.Vowel Spellchecker/README_EN.md b/assets/0900-0999/0966.Vowel Spellchecker/README_EN.md new file mode 100644 index 00000000..3a569b5f --- /dev/null +++ b/assets/0900-0999/0966.Vowel Spellchecker/README_EN.md @@ -0,0 +1,80 @@ +# [966. Vowel Spellchecker](https://leetcode.com/problems/vowel-spellchecker) + + + +## Description + +

    Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.

    + +

    For a given query word, the spell checker handles two categories of spelling mistakes:

    + +
      +
    • Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist. + +
        +
      • Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow"
      • +
      • Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow"
      • +
      • Example: wordlist = ["yellow"], query = "yellow": correct = "yellow"
      • +
      +
    • +
    • Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist. +
        +
      • Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw"
      • +
      • Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match)
      • +
      • Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match)
      • +
      +
    • +
    + +

    In addition, the spell checker operates under the following precedence rules:

    + +
      +
    • When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.
    • +
    • When the query matches a word up to capitlization, you should return the first such match in the wordlist.
    • +
    • When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
    • +
    • If the query has no matches in the wordlist, you should return the empty string.
    • +
    + +

    Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].

    + +

     

    +

    Example 1:

    +
    Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
    +Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]
    +

    Example 2:

    +
    Input: wordlist = ["yellow"], queries = ["YellOw"]
    +Output: ["yellow"]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= wordlist.length, queries.length <= 5000
    • +
    • 1 <= wordlist[i].length, queries[i].length <= 7
    • +
    • wordlist[i] and queries[i] consist only of only English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md b/assets/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md new file mode 100644 index 00000000..ea0b69c4 --- /dev/null +++ b/assets/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md @@ -0,0 +1,74 @@ +# [967. Numbers With Same Consecutive Differences](https://leetcode.com/problems/numbers-with-same-consecutive-differences) + + + +## Description + +

    Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k.

    + +

    Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid.

    + +

    You may return the answer in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, k = 7
    +Output: [181,292,707,818,929]
    +Explanation: Note that 070 is not a valid number, because it has leading zeroes.
    +
    + +

    Example 2:

    + +
    +Input: n = 2, k = 1
    +Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
    +
    + +

    Example 3:

    + +
    +Input: n = 2, k = 0
    +Output: [11,22,33,44,55,66,77,88,99]
    +
    + +

    Example 4:

    + +
    +Input: n = 2, k = 2
    +Output: [13,20,24,31,35,42,46,53,57,64,68,75,79,86,97]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 9
    • +
    • 0 <= k <= 9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0968.Binary Tree Cameras/README_EN.md b/assets/0900-0999/0968.Binary Tree Cameras/README_EN.md new file mode 100644 index 00000000..a916adf3 --- /dev/null +++ b/assets/0900-0999/0968.Binary Tree Cameras/README_EN.md @@ -0,0 +1,98 @@ +# [968. Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras) + + + +## Description + +

    Given a binary tree, we install cameras on the nodes of the tree. 

    + + + +

    Each camera at a node can monitor its parent, itself, and its immediate children.

    + + + +

    Calculate the minimum number of cameras needed to monitor all nodes of the tree.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    + +
    +
    +Input: [0,0,null,0,0]
    +
    +Output: 1
    +
    +Explanation: One camera is enough to monitor all nodes if placed as shown.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [0,0,null,0,null,0,null,null,0]
    +
    +Output: 2
    +
    +Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
    +
    +
    + + + +


    + +Note:

    + + + +
      +
    1. The number of nodes in the given tree will be in the range [1, 1000].
    2. +
    3. Every node has value 0.
    4. +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0968.Binary Tree Cameras/images/bst_cameras_01.png b/assets/0900-0999/0968.Binary Tree Cameras/images/bst_cameras_01.png new file mode 100644 index 00000000..78106bbf Binary files /dev/null and b/assets/0900-0999/0968.Binary Tree Cameras/images/bst_cameras_01.png differ diff --git a/assets/0900-0999/0968.Binary Tree Cameras/images/bst_cameras_02.png b/assets/0900-0999/0968.Binary Tree Cameras/images/bst_cameras_02.png new file mode 100644 index 00000000..e2886e71 Binary files /dev/null and b/assets/0900-0999/0968.Binary Tree Cameras/images/bst_cameras_02.png differ diff --git a/assets/0900-0999/0969.Pancake Sorting/README_EN.md b/assets/0900-0999/0969.Pancake Sorting/README_EN.md new file mode 100644 index 00000000..b7b19c48 --- /dev/null +++ b/assets/0900-0999/0969.Pancake Sorting/README_EN.md @@ -0,0 +1,76 @@ +# [969. Pancake Sorting](https://leetcode.com/problems/pancake-sorting) + + + +## Description + +

    Given an array of integers arr, sort the array by performing a series of pancake flips.

    + +

    In one pancake flip we do the following steps:

    + +
      +
    • Choose an integer k where 1 <= k <= arr.length.
    • +
    • Reverse the sub-array arr[0...k-1] (0-indexed).
    • +
    + +

    For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.

    + +

    Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,2,4,1]
    +Output: [4,2,4,3]
    +Explanation: 
    +We perform 4 pancake flips, with k values 4, 2, 4, and 3.
    +Starting state: arr = [3, 2, 4, 1]
    +After 1st flip (k = 4): arr = [1, 4, 2, 3]
    +After 2nd flip (k = 2): arr = [4, 1, 2, 3]
    +After 3rd flip (k = 4): arr = [3, 2, 1, 4]
    +After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,2,3]
    +Output: []
    +Explanation: The input is already sorted, so there is no need to flip anything.
    +Note that other answers, such as [3, 3], would also be accepted.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= arr.length
    • +
    • All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0970.Powerful Integers/README_EN.md b/assets/0900-0999/0970.Powerful Integers/README_EN.md new file mode 100644 index 00000000..6bc0ab96 --- /dev/null +++ b/assets/0900-0999/0970.Powerful Integers/README_EN.md @@ -0,0 +1,124 @@ +# [970. Powerful Integers](https://leetcode.com/problems/powerful-integers) + + + +## Description + +

    Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.

    + +

    An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.

    + +

    You may return the answer in any order. In your answer, each value should occur at most once.

    + +

     

    +

    Example 1:

    + +
    +Input: x = 2, y = 3, bound = 10
    +Output: [2,3,4,5,7,9,10]
    +Explanation:
    +2 = 20 + 30
    +3 = 21 + 30
    +4 = 20 + 31
    +5 = 21 + 31
    +7 = 22 + 31
    +9 = 23 + 30
    +10 = 20 + 32
    +
    + +

    Example 2:

    + +
    +Input: x = 3, y = 5, bound = 15
    +Output: [2,4,6,8,10,14]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= x, y <= 100
    • +
    • 0 <= bound <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: + s = set() + i = 1 + while i < bound: + j = 1 + while j < bound: + if i + j <= bound: + s.add(i + j) + if y == 1: + break + j *= y + if x == 1: + break + i *= x + return list(s) +``` + +### **Java** + +```java +class Solution { + public List powerfulIntegers(int x, int y, int bound) { + Set s = new HashSet<>(); + for (int i = 1; i < bound; i *= x) { + for (int j = 1; j < bound; j *= y) { + if (i + j <= bound) { + s.add(i + j); + } + if (y == 1) { + break; + } + } + if (x == 1) { + break; + } + } + return new ArrayList<>(s); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @param {number} y + * @param {number} bound + * @return {number[]} + */ +var powerfulIntegers = function(x, y, bound) { + let res = new Set(); + for (let i = 1; i < bound; i *= x) { + for (let j = 1; j < bound; j *= y) { + if ((i + j) <= bound) { + res.add(i + j); + } + if (y == 1) break; + } + if (x == 1) break; + } + return [...res]; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md b/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md new file mode 100644 index 00000000..34a4ecb2 --- /dev/null +++ b/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md @@ -0,0 +1,74 @@ +# [971. Flip Binary Tree To Match Preorder Traversal](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal) + + + +## Description + +

    You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.

    + +

    Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:

    + +

    Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.

    + +

    Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,2], voyage = [2,1]
    +Output: [-1]
    +Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.
    +
    + +

    Example 2:

    + +
    +Input: root = [1,2,3], voyage = [1,3,2]
    +Output: [1]
    +Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
    + +

    Example 3:

    + +
    +Input: root = [1,2,3], voyage = [1,2,3]
    +Output: []
    +Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is n.
    • +
    • n == voyage.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= Node.val, voyage[i] <= n
    • +
    • All the values in the tree are unique.
    • +
    • All the values in voyage are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/images/1219-01.png b/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/images/1219-01.png new file mode 100644 index 00000000..1c9c917a Binary files /dev/null and b/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/images/1219-01.png differ diff --git a/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/images/1219-02.png b/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/images/1219-02.png new file mode 100644 index 00000000..7f8ff81a Binary files /dev/null and b/assets/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/images/1219-02.png differ diff --git a/assets/0900-0999/0972.Equal Rational Numbers/README_EN.md b/assets/0900-0999/0972.Equal Rational Numbers/README_EN.md new file mode 100644 index 00000000..cb00d511 --- /dev/null +++ b/assets/0900-0999/0972.Equal Rational Numbers/README_EN.md @@ -0,0 +1,95 @@ +# [972. Equal Rational Numbers](https://leetcode.com/problems/equal-rational-numbers) + + + +## Description + +

    Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.

    + +

    A rational number can be represented using up to three parts: <IntegerPart>, <NonRepeatingPart>, and a <RepeatingPart>. The number will be represented in one of the following three ways:

    + +
      +
    • <IntegerPart> + +
        +
      • For example, 12, 0, and 123.
      • +
      +
    • +
    • <IntegerPart><.><NonRepeatingPart> +
        +
      • For example, 0.5, 1., 2.12, and 123.0001.
      • +
      +
    • +
    • <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> +
        +
      • For example, 0.1(6), 1.(9), 123.00(1212).
      • +
      +
    • +
    + +

    The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:

    + +
      +
    • 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: s = "0.(52)", t = "0.5(25)"
    +Output: true
    +Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.
    +
    + +

    Example 2:

    + +
    +Input: s = "0.1666(6)", t = "0.166(66)"
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: s = "0.9(9)", t = "1."
    +Output: true
    +Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1.  [See this link for an explanation.]
    +"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • Each part consists only of digits.
    • +
    • The <IntegerPart> does not have leading zeros (except for the zero itself).
    • +
    • 1 <= <IntegerPart>.length <= 4
    • +
    • 0 <= <NonRepeatingPart>.length <= 4
    • +
    • 1 <= <RepeatingPart>.length <= 4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0973.K Closest Points to Origin/README_EN.md b/assets/0900-0999/0973.K Closest Points to Origin/README_EN.md new file mode 100644 index 00000000..efe62f9e --- /dev/null +++ b/assets/0900-0999/0973.K Closest Points to Origin/README_EN.md @@ -0,0 +1,65 @@ +# [973. K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin) + + + +## Description + +

    Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

    + +

    The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

    + +

    You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

    + +

     

    +

    Example 1:

    + +
    +Input: points = [[1,3],[-2,2]], k = 1
    +Output: [[-2,2]]
    +Explanation:
    +The distance between (1, 3) and the origin is sqrt(10).
    +The distance between (-2, 2) and the origin is sqrt(8).
    +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
    +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
    +
    + +

    Example 2:

    + +
    +Input: points = [[3,3],[5,-1],[-2,4]], k = 2
    +Output: [[3,3],[-2,4]]
    +Explanation: The answer [[-2,4],[3,3]] would also be accepted.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= points.length <= 104
    • +
    • -104 < xi, yi < 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0973.K Closest Points to Origin/images/closestplane1.jpg b/assets/0900-0999/0973.K Closest Points to Origin/images/closestplane1.jpg new file mode 100644 index 00000000..12c601ca Binary files /dev/null and b/assets/0900-0999/0973.K Closest Points to Origin/images/closestplane1.jpg differ diff --git a/assets/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md b/assets/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md new file mode 100644 index 00000000..3ecdac95 --- /dev/null +++ b/assets/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md @@ -0,0 +1,73 @@ +# [974. Subarray Sums Divisible by K](https://leetcode.com/problems/subarray-sums-divisible-by-k) + + + +## Description + +

    Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [4,5,0,-2,-3,1], K = 5
    +
    +Output: 7
    +
    +Explanation: There are 7 subarrays with a sum divisible by K = 5:
    +
    +[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 30000
    2. +
    3. -10000 <= A[i] <= 10000
    4. +
    5. 2 <= K <= 10000
    6. +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0975.Odd Even Jump/README_EN.md b/assets/0900-0999/0975.Odd Even Jump/README_EN.md new file mode 100644 index 00000000..408d8458 --- /dev/null +++ b/assets/0900-0999/0975.Odd Even Jump/README_EN.md @@ -0,0 +1,95 @@ +# [975. Odd Even Jump](https://leetcode.com/problems/odd-even-jump) + + + +## Description + +

    You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.

    + +

    You may jump forward from index i to index j (with i < j) in the following way:

    + +
      +
    • During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.
    • +
    • During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.
    • +
    • It may be the case that for some index i, there are no legal jumps.
    • +
    + +

    A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).

    + +

    Return the number of good starting indices.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [10,13,12,14,15]
    +Output: 2
    +Explanation: 
    +From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.
    +From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.
    +From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.
    +From starting index i = 4, we have reached the end already.
    +In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of
    +jumps.
    +
    + +

    Example 2:

    + +
    +Input: arr = [2,3,1,1,4]
    +Output: 3
    +Explanation: 
    +From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:
    +During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].
    +During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3
    +During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].
    +We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.
    +In a similar manner, we can deduce that:
    +From starting index i = 1, we jump to i = 4, so we reach the end.
    +From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
    +From starting index i = 3, we jump to i = 4, so we reach the end.
    +From starting index i = 4, we are already at the end.
    +In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some
    +number of jumps.
    +
    + +

    Example 3:

    + +
    +Input: arr = [5,1,3,4,2]
    +Output: 3
    +Explanation: We can reach the end from starting indices 1, 2, and 4.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 2 * 104
    • +
    • 0 <= arr[i] < 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0976.Largest Perimeter Triangle/README_EN.md b/assets/0900-0999/0976.Largest Perimeter Triangle/README_EN.md new file mode 100644 index 00000000..e2ec75bd --- /dev/null +++ b/assets/0900-0999/0976.Largest Perimeter Triangle/README_EN.md @@ -0,0 +1,54 @@ +# [976. Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle) + + + +## Description + +

    Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.

    + +

     

    +

    Example 1:

    +
    Input: nums = [2,1,2]
    +Output: 5
    +

    Example 2:

    +
    Input: nums = [1,2,1]
    +Output: 0
    +

    Example 3:

    +
    Input: nums = [3,2,3,4]
    +Output: 10
    +

    Example 4:

    +
    Input: nums = [3,6,2,3]
    +Output: 8
    +
    +

     

    +

    Constraints:

    + +
      +
    • 3 <= nums.length <= 104
    • +
    • 1 <= nums[i] <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0977.Squares of a Sorted Array/README_EN.md b/assets/0900-0999/0977.Squares of a Sorted Array/README_EN.md new file mode 100644 index 00000000..90c23ab5 --- /dev/null +++ b/assets/0900-0999/0977.Squares of a Sorted Array/README_EN.md @@ -0,0 +1,153 @@ +# [977. Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array) + + + +## Description + +

    Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [-4,-1,0,3,10]
    +Output: [0,1,9,16,100]
    +Explanation: After squaring, the array becomes [16,1,0,9,100].
    +After sorting, it becomes [0,1,9,16,100].
    +
    + +

    Example 2:

    + +
    +Input: nums = [-7,-3,2,3,11]
    +Output: [4,9,9,49,121]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • nums is sorted in non-decreasing order.
    • +
    + +

     

    +Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + res = [0] * n + i, j, k = 0, n - 1, n - 1 + while i <= j: + if nums[i] * nums[i] > nums[j] * nums[j]: + res[k] = nums[i] * nums[i] + i += 1 + else: + res[k] = nums[j] * nums[j] + j -= 1 + k -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public int[] sortedSquares(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + for (int i = 0, j = n - 1, k = n - 1; i <= j;) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector sortedSquares(vector& nums) { + int n = nums.size(); + vector res(n); + for (int i = 0, j = n - 1, k = n - 1; i <= j;) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; + } +}; +``` + +### **Go** + +```go +func sortedSquares(nums []int) []int { + n := len(nums) + res := make([]int, n) + for i, j, k := 0, n-1, n-1; i <= j; { + if nums[i]*nums[i] > nums[j]*nums[j] { + res[k] = nums[i] * nums[i] + i++ + } else { + res[k] = nums[j] * nums[j] + j-- + } + k-- + } + return res +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortedSquares = function(nums) { + const n = nums.length; + const res = new Array(n); + for (let i = 0, j = n - 1, k = n - 1; i <= j;) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0978.Longest Turbulent Subarray/README_EN.md b/assets/0900-0999/0978.Longest Turbulent Subarray/README_EN.md new file mode 100644 index 00000000..96de4b3b --- /dev/null +++ b/assets/0900-0999/0978.Longest Turbulent Subarray/README_EN.md @@ -0,0 +1,83 @@ +# [978. Longest Turbulent Subarray](https://leetcode.com/problems/longest-turbulent-subarray) + + + +## Description + +

    Given an integer array arr, return the length of a maximum size turbulent subarray of arr.

    + +

    A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

    + +

    More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:

    + +
      +
    • For i <= k < j: + +
        +
      • arr[k] > arr[k + 1] when k is odd, and
      • +
      • arr[k] < arr[k + 1] when k is even.
      • +
      +
    • +
    • Or, for i <= k < j: +
        +
      • arr[k] > arr[k + 1] when k is even, and
      • +
      • arr[k] < arr[k + 1] when k is odd.
      • +
      +
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: arr = [9,4,2,10,7,8,8,1,9]
    +Output: 5
    +Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]
    +
    + +

    Example 2:

    + +
    +Input: arr = [4,8,12,16]
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: arr = [100]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 4 * 104
    • +
    • 0 <= arr[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md b/assets/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md new file mode 100644 index 00000000..950b4c7b --- /dev/null +++ b/assets/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md @@ -0,0 +1,77 @@ +# [979. Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree) + + + +## Description + +

    You are given the root of a binary tree with n nodes where each node in the tree has node.val coins and there are n coins total.

    + +

    In one move, we may choose two adjacent nodes and move one coin from one node to another. (A move may be from parent to child, or from child to parent.)

    + +

    Return the number of moves required to make every node have exactly one coin.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,0,0]
    +Output: 2
    +Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
    +
    + +

    Example 2:

    + +
    +Input: root = [0,3,0]
    +Output: 3
    +Explanation: From the left child of the root, we move two coins to the root [taking two moves].  Then, we move one coin from the root of the tree to the right child.
    +
    + +

    Example 3:

    + +
    +Input: root = [1,0,2]
    +Output: 2
    +
    + +

    Example 4:

    + +
    +Input: root = [1,0,0,null,3]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is n.
    • +
    • 1 <= n <= 100
    • +
    • 0 <= Node.val <= n
    • +
    • The sum of Node.val is n.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree1.png b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree1.png new file mode 100644 index 00000000..046754ad Binary files /dev/null and b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree1.png differ diff --git a/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree2.png b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree2.png new file mode 100644 index 00000000..b81a741e Binary files /dev/null and b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree2.png differ diff --git a/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree3.png b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree3.png new file mode 100644 index 00000000..2167dad0 Binary files /dev/null and b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree3.png differ diff --git a/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree4.png b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree4.png new file mode 100644 index 00000000..e29f950a Binary files /dev/null and b/assets/0900-0999/0979.Distribute Coins in Binary Tree/images/tree4.png differ diff --git a/assets/0900-0999/0980.Unique Paths III/README_EN.md b/assets/0900-0999/0980.Unique Paths III/README_EN.md new file mode 100644 index 00000000..403ce999 --- /dev/null +++ b/assets/0900-0999/0980.Unique Paths III/README_EN.md @@ -0,0 +1,134 @@ +# [980. Unique Paths III](https://leetcode.com/problems/unique-paths-iii) + + + +## Description + +

    On a 2-dimensional grid, there are 4 types of squares:

    + + + +
      +
    • 1 represents the starting square.  There is exactly one starting square.
    • +
    • 2 represents the ending square.  There is exactly one ending square.
    • +
    • 0 represents empty squares we can walk over.
    • +
    • -1 represents obstacles that we cannot walk over.
    • +
    + + + +

    Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
    +
    +Output: 2
    +
    +Explanation: We have the following two paths: 
    +
    +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
    +
    +2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
    +
    +Output: 4
    +
    +Explanation: We have the following four paths: 
    +
    +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
    +
    +2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
    +
    +3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
    +
    +4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: [[0,1],[2,0]]
    +
    +Output: 0
    +
    +Explanation: 
    +
    +There is no path that walks over every empty square exactly once.
    +
    +Note that the starting and ending square can be anywhere in the grid.
    +
    +
    + +
    + +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= grid.length * grid[0].length <= 20
    2. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0981.Time Based Key-Value Store/README_EN.md b/assets/0900-0999/0981.Time Based Key-Value Store/README_EN.md new file mode 100644 index 00000000..c50c352d --- /dev/null +++ b/assets/0900-0999/0981.Time Based Key-Value Store/README_EN.md @@ -0,0 +1,192 @@ +# [981. Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store) + + + +## Description + +

    Create a timebased key-value store class TimeMap, that supports two operations.

    + +

    1. set(string key, string value, int timestamp)

    + +
      +
    • Stores the key and value, along with the given timestamp.
    • +
    + +

    2. get(string key, int timestamp)

    + +
      +
    • Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
    • +
    • If there are multiple such values, it returns the one with the largest timestamp_prev.
    • +
    • If there are no values, it returns the empty string ("").
    • +
    + +

     

    + +
    + +

    Example 1:

    + +
    +
    +Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
    +
    +Output: [null,null,"bar","bar",null,"bar2","bar2"]
    +
    +Explanation:  
    +
    +TimeMap kv;  
    +
    +kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1  
    +
    +kv.get("foo", 1);  // output "bar"  
    +
    +kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"  
    +
    +kv.set("foo", "bar2", 4);  
    +
    +kv.get("foo", 4); // output "bar2"  
    +
    +kv.get("foo", 5); //output "bar2"  
    +
    +
    +
    +
    + +
    + +

    Example 2:

    + +
    +
    +Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
    +
    +Output: [null,null,null,"","high","high","low","low"]
    +
    +
    + +
    + +
    + +

     

    + +

    Note:

    + +
      +
    1. All key/value strings are lowercase.
    2. +
    3. All key/value strings have length in the range [1, 100]
    4. +
    5. The timestamps for all TimeMap.set operations are strictly increasing.
    6. +
    7. 1 <= timestamp <= 10^7
    8. +
    9. TimeMap.set and TimeMap.get functions will be called a total of 120000 times (combined) per test case.
    10. +
    + +## Solutions + + + +### **Python3** + +```python +class TimeMap: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.ktv = collections.defaultdict(list) + + def set(self, key: str, value: str, timestamp: int) -> None: + self.ktv[key].append((timestamp, value)) + + def get(self, key: str, timestamp: int) -> str: + if key not in self.ktv: + return '' + tv = self.ktv[key] + i = bisect.bisect_right(tv, (timestamp, chr(127))) + return tv[i - 1][1] if i else '' + + + +# Your TimeMap object will be instantiated and called as such: +# obj = TimeMap() +# obj.set(key,value,timestamp) +# param_2 = obj.get(key,timestamp) +``` + +### **Java** + +```java +class TimeMap { + private Map> ktv; + + /** Initialize your data structure here. */ + public TimeMap() { + ktv = new HashMap<>(); + } + + public void set(String key, String value, int timestamp) { + TreeMap tv = ktv.getOrDefault(key, new TreeMap<>()); + tv.put(timestamp, value); + ktv.put(key, tv); + } + + public String get(String key, int timestamp) { + if (!ktv.containsKey(key)) { + return ""; + } + TreeMap tv = ktv.get(key); + Integer t = tv.floorKey(timestamp); + return t == null ? "" : tv.get(t); + } +} + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap obj = new TimeMap(); + * obj.set(key,value,timestamp); + * String param_2 = obj.get(key,timestamp); + */ +``` + +### **Go** + +Because timestamp is always increasing, you can use binary search to quickly find the value + +```go +type pair struct { + timestamp int + value string +} + +type TimeMap struct { + data map[string][]pair +} + +func Constructor() TimeMap { + return TimeMap{data: make(map[string][]pair)} +} + +func (m *TimeMap) Set(key string, value string, timestamp int) { + m.data[key] = append(m.data[key], pair{timestamp, value}) +} + +func (m *TimeMap) Get(key string, timestamp int) string { + pairs := m.data[key] + // sort.Search return the smallest index i in [0, n) at which f(i) is true + i := sort.Search(len(pairs), func(i int) bool { + return pairs[i].timestamp > timestamp + }) + if i > 0 { + return pairs[i-1].value + } + return "" +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md b/assets/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md new file mode 100644 index 00000000..1d7bc337 --- /dev/null +++ b/assets/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md @@ -0,0 +1,101 @@ +# [982. Triples with Bitwise AND Equal To Zero](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero) + + + +## Description + +

    Given an array of integers A, find the number of triples of indices (i, j, k) such that:

    + + + +
      +
    • 0 <= i < A.length
    • +
    • 0 <= j < A.length
    • +
    • 0 <= k < A.length
    • +
    • A[i] & A[j] & A[k] == 0, where & represents the bitwise-AND operator.
    • +
    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [2,1,3]
    +
    +Output: 12
    +
    +Explanation: We could choose the following i, j, k triples:
    +
    +(i=0, j=0, k=1) : 2 & 2 & 1
    +
    +(i=0, j=1, k=0) : 2 & 1 & 2
    +
    +(i=0, j=1, k=1) : 2 & 1 & 1
    +
    +(i=0, j=1, k=2) : 2 & 1 & 3
    +
    +(i=0, j=2, k=1) : 2 & 3 & 1
    +
    +(i=1, j=0, k=0) : 1 & 2 & 2
    +
    +(i=1, j=0, k=1) : 1 & 2 & 1
    +
    +(i=1, j=0, k=2) : 1 & 2 & 3
    +
    +(i=1, j=1, k=0) : 1 & 1 & 2
    +
    +(i=1, j=2, k=0) : 1 & 3 & 2
    +
    +(i=2, j=0, k=1) : 3 & 2 & 1
    +
    +(i=2, j=1, k=0) : 3 & 1 & 2
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 1000
    2. +
    3. 0 <= A[i] < 2^16
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0983.Minimum Cost For Tickets/README_EN.md b/assets/0900-0999/0983.Minimum Cost For Tickets/README_EN.md new file mode 100644 index 00000000..9001d967 --- /dev/null +++ b/assets/0900-0999/0983.Minimum Cost For Tickets/README_EN.md @@ -0,0 +1,129 @@ +# [983. Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets) + + + +## Description + +

    In a country popular for train travel, you have planned some train travelling one year in advance.  The days of the year that you will travel is given as an array days.  Each day is an integer from 1 to 365.

    + + + +

    Train tickets are sold in 3 different ways:

    + + + +
      +
    • a 1-day pass is sold for costs[0] dollars;
    • +
    • a 7-day pass is sold for costs[1] dollars;
    • +
    • a 30-day pass is sold for costs[2] dollars.
    • +
    + + + +

    The passes allow that many days of consecutive travel.  For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.

    + + + +

    Return the minimum number of dollars you need to travel every day in the given list of days.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: days = [1,4,6,7,8,20], costs = [2,7,15]
    +
    +Output: 11
    +
    +Explanation: 
    +
    +For example, here is one way to buy passes that lets you travel your travel plan:
    +
    +On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
    +
    +On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
    +
    +On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
    +
    +In total you spent $11 and covered all the days of your travel.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
    +
    +Output: 17
    +
    +Explanation: 
    +
    +For example, here is one way to buy passes that lets you travel your travel plan:
    +
    +On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
    +
    +On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
    +
    +In total you spent $17 and covered all the days of your travel.
    +
    +
    + + + +

     

    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= days.length <= 365
    2. +
    3. 1 <= days[i] <= 365
    4. +
    5. days is in strictly increasing order.
    6. +
    7. costs.length == 3
    8. +
    9. 1 <= costs[i] <= 1000
    10. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0984.String Without AAA or BBB/README_EN.md b/assets/0900-0999/0984.String Without AAA or BBB/README_EN.md new file mode 100644 index 00000000..3f1c09e6 --- /dev/null +++ b/assets/0900-0999/0984.String Without AAA or BBB/README_EN.md @@ -0,0 +1,62 @@ +# [984. String Without AAA or BBB](https://leetcode.com/problems/string-without-aaa-or-bbb) + + + +## Description + +

    Given two integers a and b, return any string s such that:

    + +
      +
    • s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,
    • +
    • The substring 'aaa' does not occur in s, and
    • +
    • The substring 'bbb' does not occur in s.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: a = 1, b = 2
    +Output: "abb"
    +Explanation: "abb", "bab" and "bba" are all correct answers.
    +
    + +

    Example 2:

    + +
    +Input: a = 4, b = 1
    +Output: "aabaa"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= a, b <= 100
    • +
    • It is guaranteed such an s exists for the given a and b.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md b/assets/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md new file mode 100644 index 00000000..fe6546ae --- /dev/null +++ b/assets/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md @@ -0,0 +1,93 @@ +# [985. Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries) + + + +## Description + +

    We have an array A of integers, and an array queries of queries.

    + + + +

    For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the answer to the i-th query is the sum of the even values of A.

    + + + +

    (Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

    + + + +

    Return the answer to all queries.  Your answer array should have answer[i] as the answer to the i-th query.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
    +
    +Output: [8,6,2,4]
    +
    +Explanation: 
    +
    +At the beginning, the array is [1,2,3,4].
    +
    +After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
    +
    +After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
    +
    +After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
    +
    +After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. -10000 <= A[i] <= 10000
    4. +
    5. 1 <= queries.length <= 10000
    6. +
    7. -10000 <= queries[i][0] <= 10000
    8. +
    9. 0 <= queries[i][1] < A.length
    10. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0986.Interval List Intersections/README_EN.md b/assets/0900-0999/0986.Interval List Intersections/README_EN.md new file mode 100644 index 00000000..5c72368f --- /dev/null +++ b/assets/0900-0999/0986.Interval List Intersections/README_EN.md @@ -0,0 +1,79 @@ +# [986. Interval List Intersections](https://leetcode.com/problems/interval-list-intersections) + + + +## Description + +

    You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

    + +

    Return the intersection of these two interval lists.

    + +

    A closed interval [a, b] (with a < b) denotes the set of real numbers x with a <= x <= b.

    + +

    The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

    + +

     

    +

    Example 1:

    + +
    +Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
    +Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
    +
    + +

    Example 2:

    + +
    +Input: firstList = [[1,3],[5,9]], secondList = []
    +Output: []
    +
    + +

    Example 3:

    + +
    +Input: firstList = [], secondList = [[4,8],[10,12]]
    +Output: []
    +
    + +

    Example 4:

    + +
    +Input: firstList = [[1,7]], secondList = [[3,10]]
    +Output: [[3,7]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= firstList.length, secondList.length <= 1000
    • +
    • firstList.length + secondList.length >= 1
    • +
    • 0 <= starti < endi <= 109
    • +
    • endi < starti+1
    • +
    • 0 <= startj < endj <= 109
    • +
    • endj < startj+1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0986.Interval List Intersections/images/interval1.png b/assets/0900-0999/0986.Interval List Intersections/images/interval1.png new file mode 100644 index 00000000..e000b70e Binary files /dev/null and b/assets/0900-0999/0986.Interval List Intersections/images/interval1.png differ diff --git a/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md b/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md new file mode 100644 index 00000000..be0d4faf --- /dev/null +++ b/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md @@ -0,0 +1,83 @@ +# [987. Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree) + + + +## Description + +

    Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

    + +

    For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

    + +

    The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

    + +

    Return the vertical order traversal of the binary tree.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,9,20,null,null,15,7]
    +Output: [[9],[3,15],[20],[7]]
    +Explanation:
    +Column -1: Only node 9 is in this column.
    +Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
    +Column 1: Only node 20 is in this column.
    +Column 2: Only node 7 is in this column.
    + +

    Example 2:

    + +
    +Input: root = [1,2,3,4,5,6,7]
    +Output: [[4],[2],[1,5,6],[3],[7]]
    +Explanation:
    +Column -2: Only node 4 is in this column.
    +Column -1: Only node 2 is in this column.
    +Column 0: Nodes 1, 5, and 6 are in this column.
    +          1 is at the top, so it comes first.
    +          5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
    +Column 1: Only node 3 is in this column.
    +Column 2: Only node 7 is in this column.
    +
    + +

    Example 3:

    + +
    +Input: root = [1,2,3,4,6,5,7]
    +Output: [[4],[2],[1,5,6],[3],[7]]
    +Explanation:
    +This case is the exact same as example 2, but with nodes 5 and 6 swapped.
    +Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 1000].
    • +
    • 0 <= Node.val <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/images/1236_example_1.png b/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/images/1236_example_1.png new file mode 100644 index 00000000..3802d8a6 Binary files /dev/null and b/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/images/1236_example_1.png differ diff --git a/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/images/tree2.png b/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/images/tree2.png new file mode 100644 index 00000000..314f1e62 Binary files /dev/null and b/assets/0900-0999/0987.Vertical Order Traversal of a Binary Tree/images/tree2.png differ diff --git a/assets/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md b/assets/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md new file mode 100644 index 00000000..91461761 --- /dev/null +++ b/assets/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md @@ -0,0 +1,138 @@ +# [988. Smallest String Starting From Leaf](https://leetcode.com/problems/smallest-string-starting-from-leaf) + + + +## Description + +

    Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on.

    + + + +

    Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

    + + + +

    (As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba".  A leaf of a node is a node that has no children.)

    + + + +
    + +
    + +

     

    + + + +
      + +
    + +
    + +
    + + + +
    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: [0,1,2,3,4,3,4]
    +
    +Output: "dba"
    +
    +
    + + + +
    + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: [25,1,3,1,3,0,2]
    +
    +Output: "adz"
    +
    +
    + + + +
    + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: [2,2,1,null,1,0,null,0]
    +
    +Output: "abc"
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. The number of nodes in the given tree will be between 1 and 8500.
    2. +
    3. Each node in the tree will have a value between 0 and 25.
    4. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree1.png b/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree1.png new file mode 100644 index 00000000..b34c0b61 Binary files /dev/null and b/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree1.png differ diff --git a/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree2.png b/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree2.png new file mode 100644 index 00000000..2526dff1 Binary files /dev/null and b/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree2.png differ diff --git a/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree3.png b/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree3.png new file mode 100644 index 00000000..602df624 Binary files /dev/null and b/assets/0900-0999/0988.Smallest String Starting From Leaf/images/tree3.png differ diff --git a/assets/0900-0999/0989.Add to Array-Form of Integer/README_EN.md b/assets/0900-0999/0989.Add to Array-Form of Integer/README_EN.md new file mode 100644 index 00000000..8855575c --- /dev/null +++ b/assets/0900-0999/0989.Add to Array-Form of Integer/README_EN.md @@ -0,0 +1,106 @@ +# [989. Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer) + + + +## Description + +

    The array-form of an integer num is an array representing its digits in left to right order.

    + +
      +
    • For example, for num = 1321, the array form is [1,3,2,1].
    • +
    + +

    Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

    + +

     

    +

    Example 1:

    + +
    +Input: num = [1,2,0,0], k = 34
    +Output: [1,2,3,4]
    +Explanation: 1200 + 34 = 1234
    +
    + +

    Example 2:

    + +
    +Input: num = [2,7,4], k = 181
    +Output: [4,5,5]
    +Explanation: 274 + 181 = 455
    +
    + +

    Example 3:

    + +
    +Input: num = [2,1,5], k = 806
    +Output: [1,0,2,1]
    +Explanation: 215 + 806 = 1021
    +
    + +

    Example 4:

    + +
    +Input: num = [9,9,9,9,9,9,9,9,9,9], k = 1
    +Output: [1,0,0,0,0,0,0,0,0,0,0]
    +Explanation: 9999999999 + 1 = 10000000000
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= num.length <= 104
    • +
    • 0 <= num[i] <= 9
    • +
    • num does not contain any leading zeros except for the zero itself.
    • +
    • 1 <= k <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def addToArrayForm(self, A: List[int], K: int) -> List[int]: + n = len(A) - 1 + carry, res = 0, [] + while n >= 0 or K != 0 or carry != 0: + carry += (0 if n < 0 else A[n]) + (K % 10) + res.append(carry % 10) + K //= 10 + carry //= 10 + n -= 1 + return res[::-1] +``` + +### **Java** + +```java +class Solution { + public List addToArrayForm(int[] A, int K) { + int n = A.length - 1; + List res = new ArrayList<>(); + int carry = 0; + while (n >= 0 || K != 0 || carry != 0) { + carry += (n < 0 ? 0 : A[n]) + (K % 10); + res.add(carry % 10); + K /= 10; + carry /= 10; + --n; + } + Collections.reverse(res); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md b/assets/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md new file mode 100644 index 00000000..b6120c4d --- /dev/null +++ b/assets/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md @@ -0,0 +1,159 @@ +# [990. Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations) + + + +## Description + +

    Given an array equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: "a==b" or "a!=b".  Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.

    + + + +

    Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: ["a==b","b!=a"]
    +
    +Output: false
    +
    +Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.  There is no way to assign the variables to satisfy both equations.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: ["b==a","a==b"]
    +
    +Output: true
    +
    +Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: ["a==b","b==c","a==c"]
    +
    +Output: true
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: ["a==b","b!=c","c==a"]
    +
    +Output: false
    +
    +
    + + + +
    + +

    Example 5:

    + + + +
    +
    +Input: ["c==c","b==d","x!=z"]
    +
    +Output: true
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= equations.length <= 500
    2. +
    3. equations[i].length == 4
    4. +
    5. equations[i][0] and equations[i][3] are lowercase letters
    6. +
    7. equations[i][1] is either '=' or '!'
    8. +
    9. equations[i][2] is '='
    10. +
    + +
    + +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0991.Broken Calculator/README_EN.md b/assets/0900-0999/0991.Broken Calculator/README_EN.md new file mode 100644 index 00000000..e54671f3 --- /dev/null +++ b/assets/0900-0999/0991.Broken Calculator/README_EN.md @@ -0,0 +1,129 @@ +# [991. Broken Calculator](https://leetcode.com/problems/broken-calculator) + + + +## Description + +

    On a broken calculator that has a number showing on its display, we can perform two operations:

    + + + +
      +
    • Double: Multiply the number on the display by 2, or;
    • +
    • Decrement: Subtract 1 from the number on the display.
    • +
    + + + +

    Initially, the calculator is displaying the number X.

    + + + +

    Return the minimum number of operations needed to display the number Y.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: X = 2, Y = 3
    +
    +Output: 2
    +
    +Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: X = 5, Y = 8
    +
    +Output: 2
    +
    +Explanation: Use decrement and then double {5 -> 4 -> 8}.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: X = 3, Y = 10
    +
    +Output: 3
    +
    +Explanation:  Use double, decrement and double {3 -> 6 -> 5 -> 10}.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: X = 1024, Y = 1
    +
    +Output: 1023
    +
    +Explanation: Use decrement operations 1023 times.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= X <= 10^9
    2. +
    3. 1 <= Y <= 10^9
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0992.Subarrays with K Different Integers/README_EN.md b/assets/0900-0999/0992.Subarrays with K Different Integers/README_EN.md new file mode 100644 index 00000000..7cf9bedd --- /dev/null +++ b/assets/0900-0999/0992.Subarrays with K Different Integers/README_EN.md @@ -0,0 +1,91 @@ +# [992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers) + + + +## Description + +

    Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.

    + + + +

    (For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)

    + + + +

    Return the number of good subarrays of A.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = [1,2,1,2,3], K = 2
    +
    +Output: 7
    +
    +Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: A = [1,2,1,3,4], K = 3
    +
    +Output: 3
    +
    +Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 20000
    2. +
    3. 1 <= A[i] <= A.length
    4. +
    5. 1 <= K <= A.length
    6. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0993.Cousins in Binary Tree/README_EN.md b/assets/0900-0999/0993.Cousins in Binary Tree/README_EN.md new file mode 100644 index 00000000..a445a3c4 --- /dev/null +++ b/assets/0900-0999/0993.Cousins in Binary Tree/README_EN.md @@ -0,0 +1,77 @@ +# [993. Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree) + + + +## Description + +

    In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

    + +

    Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

    + +

    We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.

    + +

    Return true if and only if the nodes corresponding to the values x and y are cousins.

    + +

     

    + +

    Example 1:
    +

    + +
    +Input: root = [1,2,3,4], x = 4, y = 3
    +Output: false
    +
    + +
    +

    Example 2:
    +

    + +
    +Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
    +Output: true
    +
    + +
    +

    Example 3:

    + +

    + +
    +Input: root = [1,2,3,null,4], x = 2, y = 3
    +Output: false
    +
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree will be between 2 and 100.
    • +
    • Each node has a unique integer value from 1 to 100.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-01.png b/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-01.png new file mode 100644 index 00000000..4076a3f4 Binary files /dev/null and b/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-01.png differ diff --git a/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-02.png b/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-02.png new file mode 100644 index 00000000..c69e6ff3 Binary files /dev/null and b/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-02.png differ diff --git a/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-03.png b/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-03.png new file mode 100644 index 00000000..ad5b3fdb Binary files /dev/null and b/assets/0900-0999/0993.Cousins in Binary Tree/images/q1248-03.png differ diff --git a/assets/0900-0999/0994.Rotting Oranges/README_EN.md b/assets/0900-0999/0994.Rotting Oranges/README_EN.md new file mode 100644 index 00000000..46403596 --- /dev/null +++ b/assets/0900-0999/0994.Rotting Oranges/README_EN.md @@ -0,0 +1,76 @@ +# [994. Rotting Oranges](https://leetcode.com/problems/rotting-oranges) + + + +## Description + +

    You are given an m x n grid where each cell can have one of three values:

    + +
      +
    • 0 representing an empty cell,
    • +
    • 1 representing a fresh orange, or
    • +
    • 2 representing a rotten orange.
    • +
    + +

    Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

    + +

    Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
    +Output: 4
    +
    + +

    Example 2:

    + +
    +Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
    +Output: -1
    +Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
    +
    + +

    Example 3:

    + +
    +Input: grid = [[0,2]]
    +Output: 0
    +Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 10
    • +
    • grid[i][j] is 0, 1, or 2.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0994.Rotting Oranges/images/oranges.png b/assets/0900-0999/0994.Rotting Oranges/images/oranges.png new file mode 100644 index 00000000..5a6c57ae Binary files /dev/null and b/assets/0900-0999/0994.Rotting Oranges/images/oranges.png differ diff --git a/assets/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md b/assets/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md new file mode 100644 index 00000000..38c2d3e4 --- /dev/null +++ b/assets/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md @@ -0,0 +1,116 @@ +# [995. Minimum Number of K Consecutive Bit Flips](https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips) + + + +## Description + +

    In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.

    + + + +

    Return the minimum number of K-bit flips required so that there is no 0 in the array.  If it is not possible, return -1.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = [0,1,0], K = 1
    +
    +Output: 2
    +
    +Explanation: Flip A[0], then flip A[2].
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [1,1,0], K = 2
    +
    +Output: -1
    +
    +Explanation: No matter how we flip subarrays of size 2, we can't make the array become [1,1,1].
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [0,0,0,1,0,1,1,0], K = 3
    +
    +Output: 3
    +
    +Explanation:
    +
    +Flip A[0],A[1],A[2]: A becomes [1,1,1,1,0,1,1,0]
    +
    +Flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0,0]
    +
    +Flip A[5],A[6],A[7]: A becomes [1,1,1,1,1,1,1,1]
    +
    +
    + + + +

     

    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 30000
    2. +
    3. 1 <= K <= A.length
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0996.Number of Squareful Arrays/README_EN.md b/assets/0900-0999/0996.Number of Squareful Arrays/README_EN.md new file mode 100644 index 00000000..938e1417 --- /dev/null +++ b/assets/0900-0999/0996.Number of Squareful Arrays/README_EN.md @@ -0,0 +1,86 @@ +# [996. Number of Squareful Arrays](https://leetcode.com/problems/number-of-squareful-arrays) + + + +## Description + +

    Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.

    + + + +

    Return the number of permutations of A that are squareful.  Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [1,17,8]
    +
    +Output: 2
    +
    +Explanation: 
    +
    +[1,8,17] and [17,8,1] are the valid permutations.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: [2,2,2]
    +
    +Output: 1
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 12
    2. +
    3. 0 <= A[i] <= 1e9
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0997.Find the Town Judge/README_EN.md b/assets/0900-0999/0997.Find the Town Judge/README_EN.md new file mode 100644 index 00000000..345d33f3 --- /dev/null +++ b/assets/0900-0999/0997.Find the Town Judge/README_EN.md @@ -0,0 +1,117 @@ +# [997. Find the Town Judge](https://leetcode.com/problems/find-the-town-judge) + + + +## Description + +

    In a town, there are N people labelled from 1 to N.  There is a rumor that one of these people is secretly the town judge.

    + + + +

    If the town judge exists, then:

    + + + +
      +
    1. The town judge trusts nobody.
    2. +
    3. Everybody (except for the town judge) trusts the town judge.
    4. +
    5. There is exactly one person that satisfies properties 1 and 2.
    6. +
    + + + +

    You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.

    + + + +

    If the town judge exists and can be identified, return the label of the town judge.  Otherwise, return -1.

    + + + +

     

    + +

    Example 1:

    + +
    Input: N = 2, trust = [[1,2]]
    +
    +Output: 2
    +
    +

    Example 2:

    + +
    Input: N = 3, trust = [[1,3],[2,3]]
    +
    +Output: 3
    +
    +

    Example 3:

    + +
    Input: N = 3, trust = [[1,3],[2,3],[3,1]]
    +
    +Output: -1
    +
    +

    Example 4:

    + +
    Input: N = 3, trust = [[1,2],[2,3]]
    +
    +Output: -1
    +
    +

    Example 5:

    + +
    Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
    +
    +Output: 3
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= N <= 1000
    • +
    • 0 <= trust.length <= 10^4
    • +
    • trust[i].length == 2
    • +
    • trust[i] are all different
    • +
    • trust[i][0] != trust[i][1]
    • +
    • 1 <= trust[i][0], trust[i][1] <= N
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + if n == 1 and len(trust) == 0: + return 1 + dic = {} + values = set() + for i in trust: + values.add(i[0]) + if i[1] in dic: + dic[i[1]].append(i[0]) + else: dic[i[1]] = [i[0]] + + for key, value in dic.items(): + if len(dic[key]) == n-1 and key not in values: + return key + return -1 +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/README_EN.md b/assets/0900-0999/0998.Maximum Binary Tree II/README_EN.md new file mode 100644 index 00000000..37a62fca --- /dev/null +++ b/assets/0900-0999/0998.Maximum Binary Tree II/README_EN.md @@ -0,0 +1,86 @@ +# [998. Maximum Binary Tree II](https://leetcode.com/problems/maximum-binary-tree-ii) + + + +## Description + +

    We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.

    + +

    Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

    + +
      +
    • If A is empty, return null.
    • +
    • Otherwise, let A[i] be the largest element of A.  Create a root node with value A[i].
    • +
    • The left child of root will be Construct([A[0], A[1], ..., A[i-1]])
    • +
    • The right child of root will be Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
    • +
    • Return root.
    • +
    + +

    Note that we were not given A directly, only a root node root = Construct(A).

    + +

    Suppose B is a copy of A with the value val appended to it.  It is guaranteed that B has unique values.

    + +

    Return Construct(B).

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [4,1,3,null,null,2], val = 5
    +Output: [5,4,null,1,3,null,null,2]
    +Explanation: A = [1,4,2,3], B = [1,4,2,3,5]
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [5,2,4,null,1], val = 3
    +Output: [5,2,4,null,1,null,3]
    +Explanation: A = [2,1,5,4], B = [2,1,5,4,3]
    +
    + +

    Example 3:

    + +

    + +
    +Input: root = [5,2,3,null,1], val = 4
    +Output: [5,2,4,null,1,3]
    +Explanation: A = [2,1,5,3], B = [2,1,5,3,4]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= B.length <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-1-1.png b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-1-1.png new file mode 100644 index 00000000..7d799f22 Binary files /dev/null and b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-1-1.png differ diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-1-2.png b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-1-2.png new file mode 100644 index 00000000..6ab46752 Binary files /dev/null and b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-1-2.png differ diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-2-1.png b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-2-1.png new file mode 100644 index 00000000..aa1e4d5e Binary files /dev/null and b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-2-1.png differ diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-2-2.png b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-2-2.png new file mode 100644 index 00000000..bdf567ce Binary files /dev/null and b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-2-2.png differ diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-3-1.png b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-3-1.png new file mode 100644 index 00000000..18e49f8a Binary files /dev/null and b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-3-1.png differ diff --git a/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-3-2.png b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-3-2.png new file mode 100644 index 00000000..dc4a6d7a Binary files /dev/null and b/assets/0900-0999/0998.Maximum Binary Tree II/images/maximum-binary-tree-3-2.png differ diff --git a/assets/0900-0999/0999.Available Captures for Rook/README_EN.md b/assets/0900-0999/0999.Available Captures for Rook/README_EN.md new file mode 100644 index 00000000..c916f414 --- /dev/null +++ b/assets/0900-0999/0999.Available Captures for Rook/README_EN.md @@ -0,0 +1,114 @@ +# [999. Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook) + + + +## Description + +

    On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.

    + +

    When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.

    + +

    Return the number of available captures for the white rook.

    + +

     

    +

    Example 1:

    + +
    +Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
    +Output: 3
    +Explanation: In this example, the rook is attacking all the pawns.
    +
    + +

    Example 2:

    + +
    +Input: board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
    +Output: 0
    +Explanation: The bishops are blocking the rook from attacking any of the pawns.
    +
    + +

    Example 3:

    + +
    +Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
    +Output: 3
    +Explanation: The rook is attacking the pawns at positions b5, d6, and f5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • board.length == 8
    • +
    • board[i].length == 8
    • +
    • board[i][j] is either 'R', '.', 'B', or 'p'
    • +
    • There is exactly one cell with board[i][j] == 'R'
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numRookCaptures(self, board: List[List[str]]) -> int: + + def search(board, i, j, direction): + while i >= 0 and i < 8 and j >= 0 and j < 8: + if board[i][j] == 'B': return 0 + if board[i][j] == 'p': return 1 + i += direction[0] + j += direction[1] + return 0 + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + res = 0; + for i in range(8): + for j in range(8): + if board[i][j] == 'R': + for direction in directions: + res += search(board, i, j, direction) + return res +``` + +### **Java** + +```java +class Solution { + public int numRookCaptures(char[][] board) { + int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; + int res = 0; + for (int i = 0; i < 8; ++i) { + for (int j = 0; j < 8; ++j) { + if (board[i][j] == 'R') { + for (int[] direction : directions) { + res += search(board, i, j, direction); + } + return res; + } + } + } + return res; + } + + private int search(char[][] board, int i, int j, int[] direction) { + while (i >= 0 && i < 8 && j >= 0 && j < 8) { + if (board[i][j] == 'B') return 0; + if (board[i][j] == 'p') return 1; + i += direction[0]; + j += direction[1]; + } + return 0; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_1_improved.png b/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_1_improved.png new file mode 100644 index 00000000..2694f64b Binary files /dev/null and b/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_1_improved.png differ diff --git a/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_2_improved.png b/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_2_improved.png new file mode 100644 index 00000000..beab5cab Binary files /dev/null and b/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_2_improved.png differ diff --git a/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_3_improved.png b/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_3_improved.png new file mode 100644 index 00000000..11019321 Binary files /dev/null and b/assets/0900-0999/0999.Available Captures for Rook/images/1253_example_3_improved.png differ diff --git a/assets/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md b/assets/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md new file mode 100644 index 00000000..a5914391 --- /dev/null +++ b/assets/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md @@ -0,0 +1,138 @@ +# [1000. Minimum Cost to Merge Stones](https://leetcode.com/problems/minimum-cost-to-merge-stones) + + + +## Description + +

    There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones.

    + + + +

    A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.

    + + + +

    Find the minimum cost to merge all piles of stones into one pile.  If it is impossible, return -1.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: stones = [3,2,4,1], K = 2
    +
    +Output: 20
    +
    +Explanation: 
    +
    +We start with [3, 2, 4, 1].
    +
    +We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
    +
    +We merge [4, 1] for a cost of 5, and we are left with [5, 5].
    +
    +We merge [5, 5] for a cost of 10, and we are left with [10].
    +
    +The total cost was 20, and this is the minimum possible.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: stones = [3,2,4,1], K = 3
    +
    +Output: -1
    +
    +Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore.  So the task is impossible.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: stones = [3,5,1,2,6], K = 3
    +
    +Output: 25
    +
    +Explanation: 
    +
    +We start with [3, 5, 1, 2, 6].
    +
    +We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
    +
    +We merge [3, 8, 6] for a cost of 17, and we are left with [17].
    +
    +The total cost was 25, and this is the minimum possible.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= stones.length <= 30
    • +
    • 2 <= K <= 30
    • +
    • 1 <= stones[i] <= 100
    • +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1001.Grid Illumination/README_EN.md b/assets/1000-1099/1001.Grid Illumination/README_EN.md new file mode 100644 index 00000000..7a87cd8f --- /dev/null +++ b/assets/1000-1099/1001.Grid Illumination/README_EN.md @@ -0,0 +1,81 @@ +# [1001. Grid Illumination](https://leetcode.com/problems/grid-illumination) + + + +## Description + +

    There is a 2D grid of size N x N where each cell of this grid has a lamp that is initially turned off.

    + +

    You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.

    + +

    When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.

    + +

    You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].

    + +

    Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.

    + +

     

    +

    Example 1:

    + +
    +Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
    +Output: [1,0]
    +Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].
    +The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.
    +
    +The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.
    +
    +
    + +

    Example 2:

    + +
    +Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]
    +Output: [1,1]
    +
    + +

    Example 3:

    + +
    +Input: N = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]
    +Output: [1,1,0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= N <= 109
    • +
    • 0 <= lamps.length <= 20000
    • +
    • 0 <= queries.length <= 20000
    • +
    • lamps[i].length == 2
    • +
    • 0 <= rowi, coli < N
    • +
    • queries[j].length == 2
    • +
    • 0 <= rowj, colj < N
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1001.Grid Illumination/images/illu_1.jpg b/assets/1000-1099/1001.Grid Illumination/images/illu_1.jpg new file mode 100644 index 00000000..5495f44f Binary files /dev/null and b/assets/1000-1099/1001.Grid Illumination/images/illu_1.jpg differ diff --git a/assets/1000-1099/1001.Grid Illumination/images/illu_step1.jpg b/assets/1000-1099/1001.Grid Illumination/images/illu_step1.jpg new file mode 100644 index 00000000..1f5b7714 Binary files /dev/null and b/assets/1000-1099/1001.Grid Illumination/images/illu_step1.jpg differ diff --git a/assets/1000-1099/1001.Grid Illumination/images/illu_step2.jpg b/assets/1000-1099/1001.Grid Illumination/images/illu_step2.jpg new file mode 100644 index 00000000..744c8935 Binary files /dev/null and b/assets/1000-1099/1001.Grid Illumination/images/illu_step2.jpg differ diff --git a/assets/1000-1099/1002.Find Common Characters/README_EN.md b/assets/1000-1099/1002.Find Common Characters/README_EN.md new file mode 100644 index 00000000..1fce1462 --- /dev/null +++ b/assets/1000-1099/1002.Find Common Characters/README_EN.md @@ -0,0 +1,92 @@ +# [1002. Find Common Characters](https://leetcode.com/problems/find-common-characters) + + + +## Description + +

    Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates).  For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

    + + + +

    You may return the answer in any order.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: ["bella","label","roller"]
    +
    +Output: ["e","l","l"]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: ["cool","lock","cook"]
    +
    +Output: ["c","o"]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 100
    2. +
    3. 1 <= A[i].length <= 100
    4. +
    5. A[i][j] is a lowercase letter
    6. +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md b/assets/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md new file mode 100644 index 00000000..7361c3d6 --- /dev/null +++ b/assets/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md @@ -0,0 +1,85 @@ +# [1003. Check If Word Is Valid After Substitutions](https://leetcode.com/problems/check-if-word-is-valid-after-substitutions) + + + +## Description + +

    Given a string s, determine if it is valid.

    + +

    A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:

    + +
      +
    • Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.
    • +
    + +

    Return true if s is a valid string, otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aabcbc"
    +Output: true
    +Explanation:
    +"" -> "abc" -> "aabcbc"
    +Thus, "aabcbc" is valid.
    + +

    Example 2:

    + +
    +Input: s = "abcabcababcc"
    +Output: true
    +Explanation:
    +"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
    +Thus, "abcabcababcc" is valid.
    +
    + +

    Example 3:

    + +
    +Input: s = "abccba"
    +Output: false
    +Explanation: It is impossible to get "abccba" using the operation.
    +
    + +

    Example 4:

    + +
    +Input: s = "cababc"
    +Output: false
    +Explanation: It is impossible to get "cababc" using the operation.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 2 * 104
    • +
    • s consists of letters 'a', 'b', and 'c'
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1004.Max Consecutive Ones III/README_EN.md b/assets/1000-1099/1004.Max Consecutive Ones III/README_EN.md new file mode 100644 index 00000000..480504ed --- /dev/null +++ b/assets/1000-1099/1004.Max Consecutive Ones III/README_EN.md @@ -0,0 +1,60 @@ +# [1004. Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii) + + + +## Description + +

    Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
    +Output: 6
    +Explanation: [1,1,1,0,0,1,1,1,1,1,1]
    +Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
    + +

    Example 2:

    + +
    +Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
    +Output: 10
    +Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
    +Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • nums[i] is either 0 or 1.
    • +
    • 0 <= k <= nums.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md b/assets/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md new file mode 100644 index 00000000..971624ac --- /dev/null +++ b/assets/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md @@ -0,0 +1,114 @@ +# [1005. Maximize Sum Of Array After K Negations](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations) + + + +## Description + +

    Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total.  (We may choose the same index i multiple times.)

    + + + +

    Return the largest possible sum of the array after modifying it in this way.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = [4,2,3], K = 1
    +
    +Output: 5
    +
    +Explanation: Choose indices (1,) and A becomes [4,-2,3].
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [3,-1,0,2], K = 3
    +
    +Output: 6
    +
    +Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [2,-3,-1,5,-4], K = 2
    +
    +Output: 13
    +
    +Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].
    +
    +
    + +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. 1 <= K <= 10000
    4. +
    5. -100 <= A[i] <= 100
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1006.Clumsy Factorial/README_EN.md b/assets/1000-1099/1006.Clumsy Factorial/README_EN.md new file mode 100644 index 00000000..d39b09a3 --- /dev/null +++ b/assets/1000-1099/1006.Clumsy Factorial/README_EN.md @@ -0,0 +1,138 @@ +# [1006. Clumsy Factorial](https://leetcode.com/problems/clumsy-factorial) + + + +## Description + +

    Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n.  For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

    + + + +

    We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.

    + + + +

    For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.  However, these operations are still applied using the usual order of operations of arithmetic: we do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

    + + + +

    Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11.  This guarantees the result is an integer.

    + + + +

    Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: 4
    +
    +Output: 7
    +
    +Explanation: 7 = 4 * 3 / 2 + 1
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: 10
    +
    +Output: 12
    +
    +Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= N <= 10000
    2. +
    3. -2^31 <= answer <= 2^31 - 1  (The answer is guaranteed to fit within a 32-bit integer.)
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def clumsy(self, N: int) -> int: + op = 0 + s = [N] + for i in range(N - 1, 0, -1): + if op == 0: + s.append(s.pop() * i) + elif op == 1: + s.append(int(s.pop() / i)) + elif op == 2: + s.append(i) + else: + s.append(-i) + op = (op + 1) % 4 + return sum(s) +``` + +### **Java** + +```java +class Solution { + public int clumsy(int N) { + Deque s = new ArrayDeque<>(); + s.offerLast(N); + int op = 0; + for (int i = N - 1; i > 0; --i) { + if (op == 0) { + s.offerLast(s.pollLast() * i); + } else if (op == 1) { + s.offerLast(s.pollLast() / i); + } else if (op == 2) { + s.offerLast(i); + } else { + s.offerLast(-i); + } + op = (op + 1) % 4; + } + int res = 0; + while (!s.isEmpty()) { + res += s.pollLast(); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md b/assets/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md new file mode 100644 index 00000000..be616b81 --- /dev/null +++ b/assets/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md @@ -0,0 +1,67 @@ +# [1007. Minimum Domino Rotations For Equal Row](https://leetcode.com/problems/minimum-domino-rotations-for-equal-row) + + + +## Description + +

    In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino.  (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

    + +

    We may rotate the ith domino, so that A[i] and B[i] swap values.

    + +

    Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.

    + +

    If it cannot be done, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
    +Output: 2
    +Explanation: 
    +The first figure represents the dominoes as given by A and B: before we do any rotations.
    +If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
    +
    + +

    Example 2:

    + +
    +Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
    +Output: -1
    +Explanation: 
    +In this case, it is not possible to rotate the dominoes to make one row of values equal.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= A.length == B.length <= 2 * 104
    • +
    • 1 <= A[i], B[i] <= 6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1007.Minimum Domino Rotations For Equal Row/images/domino.png b/assets/1000-1099/1007.Minimum Domino Rotations For Equal Row/images/domino.png new file mode 100644 index 00000000..51e89ecf Binary files /dev/null and b/assets/1000-1099/1007.Minimum Domino Rotations For Equal Row/images/domino.png differ diff --git a/assets/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md b/assets/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md new file mode 100644 index 00000000..baa09406 --- /dev/null +++ b/assets/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md @@ -0,0 +1,63 @@ +# [1008. Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal) + + + +## Description + +

    Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

    + +

    It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

    + +

    A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

    + +

    A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.

    + +

     

    +

    Example 1:

    + +
    +Input: preorder = [8,5,1,7,10,12]
    +Output: [8,5,10,1,7,null,12]
    +
    + +

    Example 2:

    + +
    +Input: preorder = [1,3]
    +Output: [1,null,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= preorder.length <= 100
    • +
    • 1 <= preorder[i] <= 108
    • +
    • All the values of preorder are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/images/1266.png b/assets/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/images/1266.png new file mode 100644 index 00000000..d6615dcf Binary files /dev/null and b/assets/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/images/1266.png differ diff --git a/assets/1000-1099/1009.Complement of Base 10 Integer/README_EN.md b/assets/1000-1099/1009.Complement of Base 10 Integer/README_EN.md new file mode 100644 index 00000000..11595be2 --- /dev/null +++ b/assets/1000-1099/1009.Complement of Base 10 Integer/README_EN.md @@ -0,0 +1,81 @@ +# [1009. Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer) + + + +## Description + +

    Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation.

    + +

    The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1.  For example, the complement of "101" in binary is "010" in binary.

    + +

    For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.

    + +

     

    + +
      +
    + +
    +

    Example 1:

    + +
    +Input: 5
    +Output: 2
    +Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
    +
    + +
    +

    Example 2:

    + +
    +Input: 7
    +Output: 0
    +Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
    +
    + +
    +

    Example 3:

    + +
    +Input: 10
    +Output: 5
    +Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 0 <= N < 10^9
    2. +
    3. This question is the same as 476: https://leetcode.com/problems/number-complement/
    4. +
    +
    +
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md b/assets/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md new file mode 100644 index 00000000..4f8a3ea5 --- /dev/null +++ b/assets/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md @@ -0,0 +1,63 @@ +# [1010. Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) + + + +## Description + +

    You are given a list of songs where the ith song has a duration of time[i] seconds.

    + +

    Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

    + +

     

    +

    Example 1:

    + +
    +Input: time = [30,20,150,100,40]
    +Output: 3
    +Explanation: Three pairs have a total duration divisible by 60:
    +(time[0] = 30, time[2] = 150): total duration 180
    +(time[1] = 20, time[3] = 100): total duration 120
    +(time[1] = 20, time[4] = 40): total duration 60
    +
    + +

    Example 2:

    + +
    +Input: time = [60,60,60]
    +Output: 3
    +Explanation: All three pairs have a total duration of 120, which is divisible by 60.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= time.length <= 6 * 104
    • +
    • 1 <= time[i] <= 500
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md b/assets/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md new file mode 100644 index 00000000..285c5beb --- /dev/null +++ b/assets/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md @@ -0,0 +1,84 @@ +# [1011. Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days) + + + +## Description + +

    A conveyor belt has packages that must be shipped from one port to another within D days.

    + +

    The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

    + +

    Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.

    + +

     

    +

    Example 1:

    + +
    +Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
    +Output: 15
    +Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
    +1st day: 1, 2, 3, 4, 5
    +2nd day: 6, 7
    +3rd day: 8
    +4th day: 9
    +5th day: 10
    +
    +Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
    +
    + +

    Example 2:

    + +
    +Input: weights = [3,2,2,4,1,4], D = 3
    +Output: 6
    +Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
    +1st day: 3, 2
    +2nd day: 2, 4
    +3rd day: 1, 4
    +
    + +

    Example 3:

    + +
    +Input: weights = [1,2,3,1,1], D = 4
    +Output: 3
    +Explanation:
    +1st day: 1
    +2nd day: 2
    +3rd day: 3
    +4th day: 1, 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= D <= weights.length <= 5 * 104
    • +
    • 1 <= weights[i] <= 500
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + + diff --git a/assets/1000-1099/1012.Numbers With Repeated Digits/README_EN.md b/assets/1000-1099/1012.Numbers With Repeated Digits/README_EN.md new file mode 100644 index 00000000..83ed799d --- /dev/null +++ b/assets/1000-1099/1012.Numbers With Repeated Digits/README_EN.md @@ -0,0 +1,107 @@ +# [1012. Numbers With Repeated Digits](https://leetcode.com/problems/numbers-with-repeated-digits) + + + +## Description + +

    Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: 20
    +
    +Output: 1
    +
    +Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: 100
    +
    +Output: 10
    +
    +Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: 1000
    +
    +Output: 262
    +
    +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= N <= 10^9
    2. +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md b/assets/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md new file mode 100644 index 00000000..e8fc4eab --- /dev/null +++ b/assets/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md @@ -0,0 +1,66 @@ +# [1013. Partition Array Into Three Parts With Equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum) + + + +## Description + +

    Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.

    + +

    Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1]
    +Output: true
    +Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
    +
    + +

    Example 2:

    + +
    +Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: arr = [3,3,6,5,-2,2,5,1,-9,4]
    +Output: true
    +Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 5 * 104
    • +
    • -104 <= arr[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1014.Best Sightseeing Pair/README_EN.md b/assets/1000-1099/1014.Best Sightseeing Pair/README_EN.md new file mode 100644 index 00000000..79830d7c --- /dev/null +++ b/assets/1000-1099/1014.Best Sightseeing Pair/README_EN.md @@ -0,0 +1,111 @@ +# [1014. Best Sightseeing Pair](https://leetcode.com/problems/best-sightseeing-pair) + + + +## Description + +

    You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.

    + +

    The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.

    + +

    Return the maximum score of a pair of sightseeing spots.

    + +

     

    +

    Example 1:

    + +
    +Input: values = [8,1,5,2,6]
    +Output: 11
    +Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
    +
    + +

    Example 2:

    + +
    +Input: values = [1,2]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= values.length <= 5 * 104
    • +
    • 1 <= values[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxScoreSightseeingPair(self, values: List[int]) -> int: + res, mx = 0, values[0] + for i in range(1, len(values)): + res = max(res, values[i] - i + mx) + mx = max(mx, values[i] + i) + return res +``` + +### **Java** + +```java +class Solution { + public int maxScoreSightseeingPair(int[] values) { + int res = 0, mx = values[0]; + for (int i = 1; i < values.length; ++i) { + res = Math.max(res, values[i] - i + mx); + mx = Math.max(mx, values[i] + i); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxScoreSightseeingPair(vector& values) { + int res = 0, mx = values[0]; + for (int i = 1; i < values.size(); ++i) { + res = max(res, values[i] - i + mx); + mx = max(mx, values[i] + i); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxScoreSightseeingPair(values []int) int { + res, mx := 0, values[0] + for i := 1; i < len(values); i++ { + res = max(res, values[i]-i+mx) + mx = max(mx, values[i]+i) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md b/assets/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md new file mode 100644 index 00000000..f501a8bc --- /dev/null +++ b/assets/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md @@ -0,0 +1,68 @@ +# [1015. Smallest Integer Divisible by K](https://leetcode.com/problems/smallest-integer-divisible-by-k) + + + +## Description + +

    Given a positive integer K, you need to find the length of the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.

    + +

    Return the length of N. If there is no such N, return -1.

    + +

    Note: N may not fit in a 64-bit signed integer.

    + +

     

    +

    Example 1:

    + +
    +Input: K = 1
    +Output: 1
    +Explanation: The smallest answer is N = 1, which has length 1.
    +
    + +

    Example 2:

    + +
    +Input: K = 2
    +Output: -1
    +Explanation: There is no such positive integer N divisible by 2.
    +
    + +

    Example 3:

    + +
    +Input: K = 3
    +Output: 3
    +Explanation: The smallest answer is N = 111, which has length 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= K <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md b/assets/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md new file mode 100644 index 00000000..07d54bd9 --- /dev/null +++ b/assets/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md @@ -0,0 +1,80 @@ +# [1016. Binary String With Substrings Representing 1 To N](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n) + + + +## Description + +

    Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: S = "0110", N = 3
    +
    +Output: true
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: S = "0110", N = 4
    +
    +Output: false
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length <= 1000
    2. +
    3. 1 <= N <= 10^9
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1017.Convert to Base -2/README_EN.md b/assets/1000-1099/1017.Convert to Base -2/README_EN.md new file mode 100644 index 00000000..c5e00175 --- /dev/null +++ b/assets/1000-1099/1017.Convert to Base -2/README_EN.md @@ -0,0 +1,113 @@ +# [1017. Convert to Base -2](https://leetcode.com/problems/convert-to-base-2) + + + +## Description + +

    Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).

    + + + +

    The returned string must have no leading zeroes, unless the string is "0".

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: 2
    +
    +Output: "110"
    +
    +Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: 3
    +
    +Output: "111"
    +
    +Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: 4
    +
    +Output: "100"
    +
    +Explantion: (-2) ^ 2 = 4
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 0 <= N <= 10^9
    2. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md b/assets/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md new file mode 100644 index 00000000..9d27b11b --- /dev/null +++ b/assets/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md @@ -0,0 +1,112 @@ +# [1018. Binary Prefix Divisible By 5](https://leetcode.com/problems/binary-prefix-divisible-by-5) + + + +## Description + +

    Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.)

    + + + +

    Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5.

    + + + +

    Example 1:

    + + + +
    +
    +Input: [0,1,1]
    +
    +Output: [true,false,false]
    +
    +Explanation: 
    +
    +The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.  Only the first number is divisible by 5, so answer[0] is true.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: [1,1,1]
    +
    +Output: [false,false,false]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: [0,1,1,1,1,1]
    +
    +Output: [true,false,false,false,true,false]
    +
    +
    + + + +

    Example 4:

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

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 30000
    2. +
    3. A[i] is 0 or 1
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1019.Next Greater Node In Linked List/README_EN.md b/assets/1000-1099/1019.Next Greater Node In Linked List/README_EN.md new file mode 100644 index 00000000..e460380e --- /dev/null +++ b/assets/1000-1099/1019.Next Greater Node In Linked List/README_EN.md @@ -0,0 +1,167 @@ +# [1019. Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list) + + + +## Description + +

    We are given a linked list with head as the first node.  Let's number the nodes in the list: node_1, node_2, node_3, ... etc.

    + +

    Each node may have a next larger value: for node_inext_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice.  If such a j does not exist, the next larger value is 0.

    + +

    Return an array of integers answer, where answer[i] = next_larger(node_{i+1}).

    + +

    Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5.

    + +

     

    + +
    + +

    Example 1:

    + +
    +
    +Input: [2,1,5]
    +
    +Output: [5,5,0]
    +
    +
    + +
    + +

    Example 2:

    + +
    +
    +Input: [2,7,4,3,5]
    +
    +Output: [7,0,5,5,0]
    +
    +
    + +
    + +

    Example 3:

    + +
    +
    +Input: [1,7,5,1,9,2,5,1]
    +
    +Output: [7,9,9,9,0,5,0,0]
    +
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 1 <= node.val <= 10^9 for each node in the linked list.
    2. +
    3. The given list has length in the range [0, 10000].
    4. +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def nextLargerNodes(self, head: ListNode) -> List[int]: + nums = [] + while head: + nums.append(head.val) + head = head.next + s = [] + larger = [0] * len(nums) + for i, num in enumerate(nums): + while s and nums[s[-1]] < num: + larger[s.pop()] = num + s.append(i) + return larger +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public int[] nextLargerNodes(ListNode head) { + List nums = new ArrayList<>(); + while (head != null) { + nums.add(head.val); + head = head.next; + } + Deque s = new ArrayDeque<>(); + int[] larger = new int[nums.size()]; + for (int i = 0; i < nums.size(); ++i) { + while (!s.isEmpty() && nums.get(s.peek()) < nums.get(i)) { + larger[s.pop()] = nums.get(i); + } + s.push(i); + } + return larger; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var nextLargerNodes = function(head) { + let nums = []; + while (head != null) { + nums.push(head.val); + head = head.next; + } + const n = nums.length; + let larger = new Array(n).fill(0); + let stack = []; + for (let i = 0; i < n; i++) { + let num = nums[i]; + while (stack.length > 0 && nums[stack[stack.length - 1]] < num) { + larger[stack.pop()] = num; + } + stack.push(i); + } + return larger; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1020.Number of Enclaves/README_EN.md b/assets/1000-1099/1020.Number of Enclaves/README_EN.md new file mode 100644 index 00000000..586c9b41 --- /dev/null +++ b/assets/1000-1099/1020.Number of Enclaves/README_EN.md @@ -0,0 +1,63 @@ +# [1020. Number of Enclaves](https://leetcode.com/problems/number-of-enclaves) + + + +## Description + +

    You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.

    + +

    A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.

    + +

    Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
    +Output: 3
    +Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
    +Output: 0
    +Explanation: All 1s are either on the boundary or can reach the boundary.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • grid[i][j] is either 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1020.Number of Enclaves/images/enclaves1.jpg b/assets/1000-1099/1020.Number of Enclaves/images/enclaves1.jpg new file mode 100644 index 00000000..78e18846 Binary files /dev/null and b/assets/1000-1099/1020.Number of Enclaves/images/enclaves1.jpg differ diff --git a/assets/1000-1099/1020.Number of Enclaves/images/enclaves2.jpg b/assets/1000-1099/1020.Number of Enclaves/images/enclaves2.jpg new file mode 100644 index 00000000..931b0e29 Binary files /dev/null and b/assets/1000-1099/1020.Number of Enclaves/images/enclaves2.jpg differ diff --git a/assets/1000-1099/1021.Remove Outermost Parentheses/README_EN.md b/assets/1000-1099/1021.Remove Outermost Parentheses/README_EN.md new file mode 100644 index 00000000..79908db6 --- /dev/null +++ b/assets/1000-1099/1021.Remove Outermost Parentheses/README_EN.md @@ -0,0 +1,143 @@ +# [1021. Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses) + + + +## Description + +

    A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.  For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

    + + + +

    A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

    + + + +

    Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

    + + + +

    Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "(()())(())"
    +
    +Output: "()()()"
    +
    +Explanation: 
    +
    +The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
    +
    +After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: "(()())(())(()(()))"
    +
    +Output: "()()()()(())"
    +
    +Explanation: 
    +
    +The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
    +
    +After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: "()()"
    +
    +Output: ""
    +
    +Explanation: 
    +
    +The input string is "()()", with primitive decomposition "()" + "()".
    +
    +After removing outer parentheses of each part, this is "" + "" = "".
    +
    +
    + + + +

     

    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. S.length <= 10000
    2. +
    3. S[i] is "(" or ")"
    4. +
    5. S is a valid parentheses string
    6. +
    + + + +
    + +
    + +
     
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md b/assets/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md new file mode 100644 index 00000000..47718fcd --- /dev/null +++ b/assets/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md @@ -0,0 +1,74 @@ +# [1022. Sum of Root To Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers) + + + +## Description + +

    You are given the root of a binary tree where each node has a value 0 or 1.  Each root-to-leaf path represents a binary number starting with the most significant bit.  For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

    + +

    For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

    + +

    Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits integer.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,0,1,0,1,0,1]
    +Output: 22
    +Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
    +
    + +

    Example 2:

    + +
    +Input: root = [0]
    +Output: 0
    +
    + +

    Example 3:

    + +
    +Input: root = [1]
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: root = [1,1]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 1000].
    • +
    • Node.val is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1022.Sum of Root To Leaf Binary Numbers/images/sum-of-root-to-leaf-binary-numbers.png b/assets/1000-1099/1022.Sum of Root To Leaf Binary Numbers/images/sum-of-root-to-leaf-binary-numbers.png new file mode 100644 index 00000000..6469d2f7 Binary files /dev/null and b/assets/1000-1099/1022.Sum of Root To Leaf Binary Numbers/images/sum-of-root-to-leaf-binary-numbers.png differ diff --git a/assets/1000-1099/1023.Camelcase Matching/README_EN.md b/assets/1000-1099/1023.Camelcase Matching/README_EN.md new file mode 100644 index 00000000..0a3cd6c4 --- /dev/null +++ b/assets/1000-1099/1023.Camelcase Matching/README_EN.md @@ -0,0 +1,116 @@ +# [1023. Camelcase Matching](https://leetcode.com/problems/camelcase-matching) + + + +## Description + +

    A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.)

    + + + +

    Given a list of queries, and a pattern, return an answer list of booleans, where answer[i] is true if and only if queries[i] matches the pattern.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
    +
    +Output: [true,false,true,true,false]
    +
    +Explanation: 
    +
    +"FooBar" can be generated like this "F" + "oo" + "B" + "ar".
    +
    +"FootBall" can be generated like this "F" + "oot" + "B" + "all".
    +
    +"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".
    + + + +

    Example 2:

    + + + +
    +
    +Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
    +
    +Output: [true,false,true,false,false]
    +
    +Explanation: 
    +
    +"FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".
    +
    +"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
    +
    +Output: [false,true,false,false,false]
    +
    +Explanation: 
    +
    +"FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= queries.length <= 100
    2. +
    3. 1 <= queries[i].length <= 100
    4. +
    5. 1 <= pattern.length <= 100
    6. +
    7. All strings consists only of lower and upper case English letters.
    8. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1024.Video Stitching/README_EN.md b/assets/1000-1099/1024.Video Stitching/README_EN.md new file mode 100644 index 00000000..b7243bef --- /dev/null +++ b/assets/1000-1099/1024.Video Stitching/README_EN.md @@ -0,0 +1,86 @@ +# [1024. Video Stitching](https://leetcode.com/problems/video-stitching) + + + +## Description + +

    You are given a series of video clips from a sporting event that lasted T seconds.  These video clips can be overlapping with each other and have varied lengths.

    + +

    Each video clip clips[i] is an interval: it starts at time clips[i][0] and ends at time clips[i][1].  We can cut these clips into segments freely: for example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].

    + +

    Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event ([0, T]).  If the task is impossible, return -1.

    + +

     

    + +

    Example 1:

    + +
    +Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10
    +Output: 3
    +Explanation: 
    +We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.
    +Then, we can reconstruct the sporting event as follows:
    +We cut [1,9] into segments [1,2] + [2,8] + [8,9].
    +Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].
    +
    + +

    Example 2:

    + +
    +Input: clips = [[0,1],[1,2]], T = 5
    +Output: -1
    +Explanation: 
    +We can't cover [0,5] with only [0,1] and [1,2].
    +
    + +

    Example 3:

    + +
    +Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], T = 9
    +Output: 3
    +Explanation: 
    +We can take clips [0,4], [4,7], and [6,9].
    +
    + +

    Example 4:

    + +
    +Input: clips = [[0,4],[2,8]], T = 5
    +Output: 2
    +Explanation: 
    +Notice you can have extra video after the event ends.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= clips.length <= 100
    • +
    • 0 <= clips[i][0] <= clips[i][1] <= 100
    • +
    • 0 <= T <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1025.Divisor Game/README_EN.md b/assets/1000-1099/1025.Divisor Game/README_EN.md new file mode 100644 index 00000000..ccb9e820 --- /dev/null +++ b/assets/1000-1099/1025.Divisor Game/README_EN.md @@ -0,0 +1,67 @@ +# [1025. Divisor Game](https://leetcode.com/problems/divisor-game) + + + +## Description + +

    Alice and Bob take turns playing a game, with Alice starting first.

    + +

    Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:

    + +
      +
    • Choosing any x with 0 < x < n and n % x == 0.
    • +
    • Replacing the number n on the chalkboard with n - x.
    • +
    + +

    Also, if a player cannot make a move, they lose the game.

    + +

    Return true if and only if Alice wins the game, assuming both players play optimally.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 2
    +Output: true
    +Explanation: Alice chooses 1, and Bob has no more moves.
    +
    + +

    Example 2:

    + +
    +Input: n = 3
    +Output: false
    +Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md b/assets/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md new file mode 100644 index 00000000..59ee2667 --- /dev/null +++ b/assets/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md @@ -0,0 +1,62 @@ +# [1026. Maximum Difference Between Node and Ancestor](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor) + + + +## Description + +

    Given the root of a binary tree, find the maximum value V for which there exist different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.

    + +

    A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
    +Output: 7
    +Explanation: We have various ancestor-node differences, some of which are given below :
    +|8 - 3| = 5
    +|3 - 7| = 4
    +|8 - 1| = 7
    +|10 - 13| = 3
    +Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
    + +

    Example 2:

    + +
    +Input: root = [1,null,2,null,0,3]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [2, 5000].
    • +
    • 0 <= Node.val <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1026.Maximum Difference Between Node and Ancestor/images/2whqcep.jpg b/assets/1000-1099/1026.Maximum Difference Between Node and Ancestor/images/2whqcep.jpg new file mode 100644 index 00000000..23752c79 Binary files /dev/null and b/assets/1000-1099/1026.Maximum Difference Between Node and Ancestor/images/2whqcep.jpg differ diff --git a/assets/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md b/assets/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md new file mode 100644 index 00000000..0c2bca8a --- /dev/null +++ b/assets/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md @@ -0,0 +1,70 @@ +# [1027. Longest Arithmetic Subsequence](https://leetcode.com/problems/longest-arithmetic-subsequence) + + + +## Description + +

    Given an array A of integers, return the length of the longest arithmetic subsequence in A.

    + +

    Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).

    + +

     

    +

    Example 1:

    + +
    +Input: A = [3,6,9,12]
    +Output: 4
    +Explanation: 
    +The whole array is an arithmetic sequence with steps of length = 3.
    +
    + +

    Example 2:

    + +
    +Input: A = [9,4,7,2,10]
    +Output: 3
    +Explanation: 
    +The longest arithmetic subsequence is [4,7,10].
    +
    + +

    Example 3:

    + +
    +Input: A = [20,1,15,3,10,5,8]
    +Output: 4
    +Explanation: 
    +The longest arithmetic subsequence is [20,15,10,5].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= A.length <= 1000
    • +
    • 0 <= A[i] <= 500
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md new file mode 100644 index 00000000..e0d8bc5e --- /dev/null +++ b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md @@ -0,0 +1,68 @@ +# [1028. Recover a Tree From Preorder Traversal](https://leetcode.com/problems/recover-a-tree-from-preorder-traversal) + + + +## Description + +

    We run a preorder depth-first search (DFS) on the root of a binary tree.

    + +

    At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0.

    + +

    If a node has only one child, that child is guaranteed to be the left child.

    + +

    Given the output S of this traversal, recover the tree and return its root.

    + +

     

    +

    Example 1:

    + +
    +Input: S = "1-2--3--4-5--6--7"
    +Output: [1,2,5,3,4,6,7]
    +
    + +

    Example 2:

    + +
    +Input: S = "1-2--3---4-5--6---7"
    +Output: [1,2,5,3,null,6,null,4,null,7]
    +
    + +

    Example 3:

    + +
    +Input: S = "1-401--349---90--88"
    +Output: [1,401,null,349,88,90]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the original tree is in the range [1, 1000].
    • +
    • 1 <= Node.val <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/recover-a-tree-from-preorder-traversal.png b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/recover-a-tree-from-preorder-traversal.png new file mode 100644 index 00000000..a3bf3998 Binary files /dev/null and b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/recover-a-tree-from-preorder-traversal.png differ diff --git a/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/screen-shot-2019-04-10-at-114101-pm.png b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/screen-shot-2019-04-10-at-114101-pm.png new file mode 100644 index 00000000..d3468aa0 Binary files /dev/null and b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/screen-shot-2019-04-10-at-114101-pm.png differ diff --git a/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/screen-shot-2019-04-10-at-114955-pm.png b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/screen-shot-2019-04-10-at-114955-pm.png new file mode 100644 index 00000000..3fe30f60 Binary files /dev/null and b/assets/1000-1099/1028.Recover a Tree From Preorder Traversal/images/screen-shot-2019-04-10-at-114955-pm.png differ diff --git a/assets/1000-1099/1029.Two City Scheduling/README_EN.md b/assets/1000-1099/1029.Two City Scheduling/README_EN.md new file mode 100644 index 00000000..526dc3d6 --- /dev/null +++ b/assets/1000-1099/1029.Two City Scheduling/README_EN.md @@ -0,0 +1,73 @@ +# [1029. Two City Scheduling](https://leetcode.com/problems/two-city-scheduling) + + + +## Description + +

    A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.

    + +

    Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.

    + +

     

    +

    Example 1:

    + +
    +Input: costs = [[10,20],[30,200],[400,50],[30,20]]
    +Output: 110
    +Explanation: 
    +The first person goes to city A for a cost of 10.
    +The second person goes to city A for a cost of 30.
    +The third person goes to city B for a cost of 50.
    +The fourth person goes to city B for a cost of 20.
    +
    +The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
    +
    + +

    Example 2:

    + +
    +Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
    +Output: 1859
    +
    + +

    Example 3:

    + +
    +Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
    +Output: 3086
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 * n == costs.length
    • +
    • 2 <= costs.length <= 100
    • +
    • costs.length is even.
    • +
    • 1 <= aCosti, bCosti <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md b/assets/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md new file mode 100644 index 00000000..39d90b30 --- /dev/null +++ b/assets/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md @@ -0,0 +1,126 @@ +# [1030. Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order) + + + +## Description + +

    We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 <= r < R and 0 <= c < C.

    + + + +

    Additionally, we are given a cell in that matrix with coordinates (r0, c0).

    + + + +

    Return the coordinates of all cells in the matrix, sorted by their distance from (r0, c0) from smallest distance to largest distance.  Here, the distance between two cells (r1, c1) and (r2, c2) is the Manhattan distance, |r1 - r2| + |c1 - c2|.  (You may return the answer in any order that satisfies this condition.)

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: R = 1, C = 2, r0 = 0, c0 = 0
    +
    +Output: [[0,0],[0,1]]
    +
    +Explanation: The distances from (r0, c0) to other cells are: [0,1]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: R = 2, C = 2, r0 = 0, c0 = 1
    +
    +Output: [[0,1],[0,0],[1,1],[1,0]]
    +
    +Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2]
    +
    +The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: R = 2, C = 3, r0 = 1, c0 = 2
    +
    +Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
    +
    +Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3]
    +
    +There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= R <= 100
    2. +
    3. 1 <= C <= 100
    4. +
    5. 0 <= r0 < R
    6. +
    7. 0 <= c0 < C
    8. +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md b/assets/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md new file mode 100644 index 00000000..7a9f9569 --- /dev/null +++ b/assets/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md @@ -0,0 +1,131 @@ +# [1031. Maximum Sum of Two Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays) + + + +## Description + +

    Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M.  (For clarification, the L-length subarray could occur before or after the M-length subarray.)

    + + + +

    Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) and either:

    + + + +
      +
    • 0 <= i < i + L - 1 < j < j + M - 1 < A.length, or
    • +
    • 0 <= j < j + M - 1 < i < i + L - 1 < A.length.
    • +
    + + + +

     

    + + + +
      + +
    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
    +
    +Output: 20
    +
    +Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
    +
    +Output: 29
    +
    +Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
    +
    +Output: 31
    +
    +Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. L >= 1
    2. +
    3. M >= 1
    4. +
    5. L + M <= A.length <= 1000
    6. +
    7. 0 <= A[i] <= 1000
    8. +
    + +
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1032.Stream of Characters/README_EN.md b/assets/1000-1099/1032.Stream of Characters/README_EN.md new file mode 100644 index 00000000..e04ca747 --- /dev/null +++ b/assets/1000-1099/1032.Stream of Characters/README_EN.md @@ -0,0 +1,98 @@ +# [1032. Stream of Characters](https://leetcode.com/problems/stream-of-characters) + + + +## Description + +

    Implement the StreamChecker class as follows:

    + + + +
      +
    • StreamChecker(words): Constructor, init the data structure with the given words.
    • +
    • query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.
    • +
    + + + +

     

    + + + +

    Example:

    + + + +
    +
    +StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
    +
    +streamChecker.query('a');          // return false
    +
    +streamChecker.query('b');          // return false
    +
    +streamChecker.query('c');          // return false
    +
    +streamChecker.query('d');          // return true, because 'cd' is in the wordlist
    +
    +streamChecker.query('e');          // return false
    +
    +streamChecker.query('f');          // return true, because 'f' is in the wordlist
    +
    +streamChecker.query('g');          // return false
    +
    +streamChecker.query('h');          // return false
    +
    +streamChecker.query('i');          // return false
    +
    +streamChecker.query('j');          // return false
    +
    +streamChecker.query('k');          // return false
    +
    +streamChecker.query('l');          // return true, because 'kl' is in the wordlist
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= words.length <= 2000
    • +
    • 1 <= words[i].length <= 2000
    • +
    • Words will only consist of lowercase English letters.
    • +
    • Queries will only consist of lowercase English letters.
    • +
    • The number of queries is at most 40000.
    • +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md b/assets/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md new file mode 100644 index 00000000..978165e9 --- /dev/null +++ b/assets/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md @@ -0,0 +1,138 @@ +# [1033. Moving Stones Until Consecutive](https://leetcode.com/problems/moving-stones-until-consecutive) + + + +## Description + +

    Three stones are on a number line at positions a, b, and c.

    + + + +

    Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints.  Formally, let's say the stones are currently at positions x, y, z with x < y < z.  You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.

    + + + +

    The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.

    + + + +

    When the game ends, what is the minimum and maximum number of moves that you could have made?  Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: a = 1, b = 2, c = 5
    +
    +Output: [1,2]
    +
    +Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: a = 4, b = 3, c = 2
    +
    +Output: [0,0]
    +
    +Explanation: We cannot make any moves.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: a = 3, b = 5, c = 1
    +
    +Output: [1,2]
    +
    +Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.
    +
    +
    + + + +

     

    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= a <= 100
    2. +
    3. 1 <= b <= 100
    4. +
    5. 1 <= c <= 100
    6. +
    7. a != b, b != c, c != a
    8. +
    + + + +
    + +

     

    + + + +
    + +
     
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1034.Coloring A Border/README_EN.md b/assets/1000-1099/1034.Coloring A Border/README_EN.md new file mode 100644 index 00000000..eb87a661 --- /dev/null +++ b/assets/1000-1099/1034.Coloring A Border/README_EN.md @@ -0,0 +1,114 @@ +# [1034. Coloring A Border](https://leetcode.com/problems/coloring-a-border) + + + +## Description + +

    Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location.

    + + + +

    Two squares belong to the same connected component if and only if they have the same color and are next to each other in any of the 4 directions.

    + + + +

    The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).

    + + + +

    Given a square at location (r0, c0) in the grid and a color, color the border of the connected component of that square with the given color, and return the final grid.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
    +
    +Output: [[3, 3], [3, 2]]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
    +
    +Output: [[1, 3, 3], [2, 3, 3]]
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
    +
    +Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]
    + +
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= grid.length <= 50
    2. +
    3. 1 <= grid[0].length <= 50
    4. +
    5. 1 <= grid[i][j] <= 1000
    6. +
    7. 0 <= r0 < grid.length
    8. +
    9. 0 <= c0 < grid[0].length
    10. +
    11. 1 <= color <= 1000
    12. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1035.Uncrossed Lines/README_EN.md b/assets/1000-1099/1035.Uncrossed Lines/README_EN.md new file mode 100644 index 00000000..6e8abafe --- /dev/null +++ b/assets/1000-1099/1035.Uncrossed Lines/README_EN.md @@ -0,0 +1,174 @@ +# [1035. Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines) + + + +## Description + +

    We write the integers of A and B (in the order they are given) on two separate horizontal lines.

    + + + +

    Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:

    + + + +
      +
    • A[i] == B[j];
    • +
    • The line we draw does not intersect any other connecting (non-horizontal) line.
    • +
    + + + +

    Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.

    + + + +

    Return the maximum number of connecting lines we can draw in this way.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = [1,4,2], B = [1,2,4]
    +
    +Output: 2
    +
    +Explanation: We can draw 2 uncrossed lines as in the diagram.
    +
    +We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
    +
    +Output: 3
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
    +
    +Output: 2
    + + + +

     

    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 500
    2. +
    3. 1 <= B.length <= 500
    4. +
    5. 1 <= A[i], B[i] <= 2000
    6. +
    + + + +## Solutions + +Longest common sub-sequences + + + +### **Python3** + +```python +class Solution: + def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: + m, n = len(nums1), len(nums2) + dp = [[0] * (n + 1) for i in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + if nums1[i - 1] == nums2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + 1 + else: + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + return dp[m][n] +``` + +### **Java** + +```java +class Solution { + public int maxUncrossedLines(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; + int[][] dp = new int[m + 1][n + 1]; + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (nums1[i - 1] == nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[m][n]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxUncrossedLines(vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + vector> dp(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (nums1[i - 1] == nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[m][n]; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1035.Uncrossed Lines/images/142.png b/assets/1000-1099/1035.Uncrossed Lines/images/142.png new file mode 100644 index 00000000..d4929b5e Binary files /dev/null and b/assets/1000-1099/1035.Uncrossed Lines/images/142.png differ diff --git a/assets/1000-1099/1036.Escape a Large Maze/README_EN.md b/assets/1000-1099/1036.Escape a Large Maze/README_EN.md new file mode 100644 index 00000000..d9d1418e --- /dev/null +++ b/assets/1000-1099/1036.Escape a Large Maze/README_EN.md @@ -0,0 +1,70 @@ +# [1036. Escape a Large Maze](https://leetcode.com/problems/escape-a-large-maze) + + + +## Description + +

    There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y).

    + +

    We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi).

    + +

    Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid.

    + +

    Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.

    + +

     

    +

    Example 1:

    + +
    +Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
    +Output: false
    +Explanation: The target square is inaccessible starting from the source square because we cannot move.
    +We cannot move north or east because those squares are blocked.
    +We cannot move south or west because we cannot go outside of the grid.
    +
    + +

    Example 2:

    + +
    +Input: blocked = [], source = [0,0], target = [999999,999999]
    +Output: true
    +Explanation: Because there are no blocked cells, it is possible to reach the target square.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= blocked.length <= 200
    • +
    • blocked[i].length == 2
    • +
    • 0 <= xi, yi < 106
    • +
    • source.length == target.length == 2
    • +
    • 0 <= sx, sy, tx, ty < 106
    • +
    • source != target
    • +
    • It is guaranteed that source and target are not blocked.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1037.Valid Boomerang/README_EN.md b/assets/1000-1099/1037.Valid Boomerang/README_EN.md new file mode 100644 index 00000000..d9ff7d96 --- /dev/null +++ b/assets/1000-1099/1037.Valid Boomerang/README_EN.md @@ -0,0 +1,51 @@ +# [1037. Valid Boomerang](https://leetcode.com/problems/valid-boomerang) + + + +## Description + +

    Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.

    + +

    A boomerang is a set of three points that are all distinct and not in a straight line.

    + +

     

    +

    Example 1:

    +
    Input: points = [[1,1],[2,3],[3,2]]
    +Output: true
    +

    Example 2:

    +
    Input: points = [[1,1],[2,2],[3,3]]
    +Output: false
    +
    +

     

    +

    Constraints:

    + +
      +
    • points.length == 3
    • +
    • points[i].length == 2
    • +
    • 0 <= xi, yi <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md b/assets/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md new file mode 100644 index 00000000..e28eb358 --- /dev/null +++ b/assets/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md @@ -0,0 +1,120 @@ +# [1038. Binary Search Tree to Greater Sum Tree](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree) + + + +## Description + +

    Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

    + + + +

    As a reminder, a binary search tree is a tree that satisfies these constraints:

    + + + +
      +
    • The left subtree of a node contains only nodes with keys less than the node's key.
    • +
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • +
    • Both the left and right subtrees must also be binary search trees.
    • +
    + + + +

    Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
    +
    +Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: root = [0,null,1]
    +
    +Output: [1,null,1]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: root = [1,0,2]
    +
    +Output: [3,3,2]
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: root = [3,2,4,1]
    +
    +Output: [7,9,4,10]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is in the range [1, 100].
    • +
    • 0 <= Node.val <= 100
    • +
    • All the values in the tree are unique.
    • +
    • root is guaranteed to be a valid binary search tree.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1038.Binary Search Tree to Greater Sum Tree/images/tree.png b/assets/1000-1099/1038.Binary Search Tree to Greater Sum Tree/images/tree.png new file mode 100644 index 00000000..a26e4360 Binary files /dev/null and b/assets/1000-1099/1038.Binary Search Tree to Greater Sum Tree/images/tree.png differ diff --git a/assets/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md b/assets/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md new file mode 100644 index 00000000..98a308b3 --- /dev/null +++ b/assets/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md @@ -0,0 +1,71 @@ +# [1039. Minimum Score Triangulation of Polygon](https://leetcode.com/problems/minimum-score-triangulation-of-polygon) + + + +## Description + +

    You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).

    + +

    You will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.

    + +

    Return the smallest possible total score that you can achieve with some triangulation of the polygon.

    + +

     

    +

    Example 1:

    + +
    +Input: values = [1,2,3]
    +Output: 6
    +Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
    +
    + +

    Example 2:

    + +
    +Input: values = [3,7,4,5]
    +Output: 144
    +Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.
    +The minimum score is 144.
    +
    + +

    Example 3:

    + +
    +Input: values = [1,3,1,4,1,5]
    +Output: 13
    +Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == values.length
    • +
    • 3 <= n <= 50
    • +
    • 1 <= values[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1039.Minimum Score Triangulation of Polygon/images/minimum-score-triangulation-of-polygon-1.png b/assets/1000-1099/1039.Minimum Score Triangulation of Polygon/images/minimum-score-triangulation-of-polygon-1.png new file mode 100644 index 00000000..84e37185 Binary files /dev/null and b/assets/1000-1099/1039.Minimum Score Triangulation of Polygon/images/minimum-score-triangulation-of-polygon-1.png differ diff --git a/assets/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md b/assets/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md new file mode 100644 index 00000000..9e484ab3 --- /dev/null +++ b/assets/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md @@ -0,0 +1,141 @@ +# [1040. Moving Stones Until Consecutive II](https://leetcode.com/problems/moving-stones-until-consecutive-ii) + + + +## Description + +

    On an infinite number line, the position of the i-th stone is given by stones[i].  Call a stone an endpoint stone if it has the smallest or largest position.

    + + + +

    Each turn, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.

    + + + +

    In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone.

    + + + +

    The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.

    + + + +

    When the game ends, what is the minimum and maximum number of moves that you could have made?  Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [7,4,9]
    +
    +Output: [1,2]
    +
    +Explanation: 
    +
    +We can move 4 -> 8 for one move to finish the game.
    +
    +Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: [6,5,4,3,10]
    +
    +Output: [2,3]
    +
    +We can move 3 -> 8 then 10 -> 7 to finish the game.
    +
    +Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.
    +
    +Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: [100,101,104,102,103]
    +
    +Output: [0,0]
    + + + +

     

    + +
    + +
    + + + +

    Note:

    + + + +
      +
    1. 3 <= stones.length <= 10^4
    2. +
    3. 1 <= stones[i] <= 10^9
    4. +
    5. stones[i] have distinct values.
    6. +
    + + + +
    + +
    + +
     
    + +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1041.Robot Bounded In Circle/README_EN.md b/assets/1000-1099/1041.Robot Bounded In Circle/README_EN.md new file mode 100644 index 00000000..ced7f1fa --- /dev/null +++ b/assets/1000-1099/1041.Robot Bounded In Circle/README_EN.md @@ -0,0 +1,73 @@ +# [1041. Robot Bounded In Circle](https://leetcode.com/problems/robot-bounded-in-circle) + + + +## Description + +

    On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:

    + +
      +
    • "G": go straight 1 unit;
    • +
    • "L": turn 90 degrees to the left;
    • +
    • "R": turn 90 degrees to the right.
    • +
    + +

    The robot performs the instructions given in order, and repeats them forever.

    + +

    Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

    + +

     

    +

    Example 1:

    + +
    +Input: instructions = "GGLLGG"
    +Output: true
    +Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
    +When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
    + +

    Example 2:

    + +
    +Input: instructions = "GG"
    +Output: false
    +Explanation: The robot moves north indefinitely.
    + +

    Example 3:

    + +
    +Input: instructions = "GL"
    +Output: true
    +Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= instructions.length <= 100
    • +
    • instructions[i] is 'G', 'L' or, 'R'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md b/assets/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md new file mode 100644 index 00000000..62e03159 --- /dev/null +++ b/assets/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md @@ -0,0 +1,77 @@ +# [1042. Flower Planting With No Adjacent](https://leetcode.com/problems/flower-planting-with-no-adjacent) + + + +## Description + +

    You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.

    + +

    All gardens have at most 3 paths coming into or leaving it.

    + +

    Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.

    + +

    Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, paths = [[1,2],[2,3],[3,1]]
    +Output: [1,2,3]
    +Explanation:
    +Gardens 1 and 2 have different types.
    +Gardens 2 and 3 have different types.
    +Gardens 3 and 1 have different types.
    +Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].
    +
    + +

    Example 2:

    + +
    +Input: n = 4, paths = [[1,2],[3,4]]
    +Output: [1,2,1,2]
    +
    + +

    Example 3:

    + +
    +Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
    +Output: [1,2,3,4]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 104
    • +
    • 0 <= paths.length <= 2 * 104
    • +
    • paths[i].length == 2
    • +
    • 1 <= xi, yi <= n
    • +
    • xi != yi
    • +
    • Every garden has at most 3 paths coming into or leaving it.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md b/assets/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md new file mode 100644 index 00000000..ee0e4ff0 --- /dev/null +++ b/assets/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md @@ -0,0 +1,66 @@ +# [1043. Partition Array for Maximum Sum](https://leetcode.com/problems/partition-array-for-maximum-sum) + + + +## Description + +

    Given an integer array arr, you should partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.

    + +

    Return the largest sum of the given array after partitioning.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,15,7,9,2,5,10], k = 3
    +Output: 84
    +Explanation: arr becomes [15,15,15,9,10,10,10]
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
    +Output: 83
    +
    + +

    Example 3:

    + +
    +Input: arr = [1], k = 1
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 500
    • +
    • 0 <= arr[i] <= 109
    • +
    • 1 <= k <= arr.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1044.Longest Duplicate Substring/README_EN.md b/assets/1000-1099/1044.Longest Duplicate Substring/README_EN.md new file mode 100644 index 00000000..be64f765 --- /dev/null +++ b/assets/1000-1099/1044.Longest Duplicate Substring/README_EN.md @@ -0,0 +1,50 @@ +# [1044. Longest Duplicate Substring](https://leetcode.com/problems/longest-duplicate-substring) + + + +## Description + +

    Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.

    + +

    Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".

    + +

     

    +

    Example 1:

    +
    Input: s = "banana"
    +Output: "ana"
    +

    Example 2:

    +
    Input: s = "abcd"
    +Output: ""
    +
    +

     

    +

    Constraints:

    + +
      +
    • 2 <= s.length <= 3 * 104
    • +
    • s consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1045.Customers Who Bought All Products/README_EN.md b/assets/1000-1099/1045.Customers Who Bought All Products/README_EN.md new file mode 100644 index 00000000..a46b0aa2 --- /dev/null +++ b/assets/1000-1099/1045.Customers Who Bought All Products/README_EN.md @@ -0,0 +1,96 @@ +# [1045. Customers Who Bought All Products](https://leetcode.com/problems/customers-who-bought-all-products) + + + +## Description + +

    Table: Customer

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| customer_id | int     |
    +| product_key | int     |
    ++-------------+---------+
    +product_key is a foreign key to Product table.
    +
    + +

     

    + +

    Table: Product

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_key | int     |
    ++-------------+---------+
    +product_key is the primary key column for this table.
    +
    + +

     

    + +

    Write an SQL query for a report that provides the customer ids from the Customer table that bought all the products in the Product table.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Customer table:
    ++-------------+-------------+
    +| customer_id | product_key |
    ++-------------+-------------+
    +| 1           | 5           |
    +| 2           | 6           |
    +| 3           | 5           |
    +| 3           | 6           |
    +| 1           | 6           |
    ++-------------+-------------+
    +
    +Product table:
    ++-------------+
    +| product_key |
    ++-------------+
    +| 5           |
    +| 6           |
    ++-------------+
    +
    +Result table:
    ++-------------+
    +| customer_id |
    ++-------------+
    +| 1           |
    +| 3           |
    ++-------------+
    +The customers who bought all the products (5 and 6) are customers with id 1 and 3.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + customer_id +FROM + Customer +GROUP BY + customer_id +HAVING + COUNT(DISTINCT(product_key)) = ( + SELECT + COUNT(1) + FROM + Product + ); +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1046.Last Stone Weight/README_EN.md b/assets/1000-1099/1046.Last Stone Weight/README_EN.md new file mode 100644 index 00000000..34caf0c8 --- /dev/null +++ b/assets/1000-1099/1046.Last Stone Weight/README_EN.md @@ -0,0 +1,63 @@ +# [1046. Last Stone Weight](https://leetcode.com/problems/last-stone-weight) + + + +## Description + +

    We have a collection of stones, each stone has a positive integer weight.

    + +

    Each turn, we choose the two heaviest stones and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is:

    + +
      +
    • If x == y, both stones are totally destroyed;
    • +
    • If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
    • +
    + +

    At the end, there is at most 1 stone left.  Return the weight of this stone (or 0 if there are no stones left.)

    + +

     

    + +

    Example 1:

    + +
    +Input: [2,7,4,1,8,1]
    +Output: 1
    +Explanation: 
    +We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
    +we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
    +we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
    +we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.
    + +

     

    + +

    Note:

    + +
      +
    1. 1 <= stones.length <= 30
    2. +
    3. 1 <= stones[i] <= 1000
    4. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md b/assets/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md new file mode 100644 index 00000000..0d1c959f --- /dev/null +++ b/assets/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md @@ -0,0 +1,102 @@ +# [1047. Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string) + + + +## Description + +

    Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.

    + + + +

    We repeatedly make duplicate removals on S until we no longer can.

    + + + +

    Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: "abbaca"
    +
    +Output: "ca"
    +
    +Explanation: 
    +
    +For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length <= 20000
    2. +
    3. S consists only of English lowercase letters.
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def removeDuplicates(self, S: str) -> str: + res = [] + for s in S: + if not res or res[-1] != s: + res.append(s) + else: + res.pop() + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String removeDuplicates(String S) { + StringBuilder sb = new StringBuilder(); + int top = -1; + for (int i = 0, n = S.length(); i < n; ++i) { + char s = S.charAt(i); + if (top == -1 || sb.charAt(top) != s) { + sb.append(s); + ++top; + } else { + sb.deleteCharAt(top); + --top; + } + } + return sb.toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1048.Longest String Chain/README_EN.md b/assets/1000-1099/1048.Longest String Chain/README_EN.md new file mode 100644 index 00000000..13d9efab --- /dev/null +++ b/assets/1000-1099/1048.Longest String Chain/README_EN.md @@ -0,0 +1,63 @@ +# [1048. Longest String Chain](https://leetcode.com/problems/longest-string-chain) + + + +## Description + +

    Given a list of words, each word consists of English lowercase letters.

    + +

    Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2.  For example, "abc" is a predecessor of "abac".

    + +

    A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.

    + +

    Return the longest possible length of a word chain with words chosen from the given list of words.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["a","b","ba","bca","bda","bdca"]
    +Output: 4
    +Explanation: One of the longest word chain is "a","ba","bda","bdca".
    +
    + +

    Example 2:

    + +
    +Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 1000
    • +
    • 1 <= words[i].length <= 16
    • +
    • words[i] only consists of English lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1049.Last Stone Weight II/README_EN.md b/assets/1000-1099/1049.Last Stone Weight II/README_EN.md new file mode 100644 index 00000000..5d976370 --- /dev/null +++ b/assets/1000-1099/1049.Last Stone Weight II/README_EN.md @@ -0,0 +1,135 @@ +# [1049. Last Stone Weight II](https://leetcode.com/problems/last-stone-weight-ii) + + + +## Description + +

    You are given an array of integers stones where stones[i] is the weight of the ith stone.

    + +

    We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:

    + +
      +
    • If x == y, both stones are destroyed, and
    • +
    • If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
    • +
    + +

    At the end of the game, there is at most one stone left.

    + +

    Return the smallest possible weight of the left stone. If there are no stones left, return 0.

    + +

     

    +

    Example 1:

    + +
    +Input: stones = [2,7,4,1,8,1]
    +Output: 1
    +Explanation:
    +We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,
    +we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,
    +we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,
    +we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.
    +
    + +

    Example 2:

    + +
    +Input: stones = [31,26,33,21,40]
    +Output: 5
    +
    + +

    Example 3:

    + +
    +Input: stones = [1,2]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= stones.length <= 30
    • +
    • 1 <= stones[i] <= 100
    • +
    + + +## Solutions + +This question can be converted to calculate how many stones a backpack with a capacity of `sum / 2` can hold. + + + +### **Python3** + +```python +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + s = sum(stones) + n = s // 2 + dp = [False for i in range(n + 1)] + dp[0] = True + for stone in stones: + for j in range(n, stone - 1, -1): + dp[j] = dp[j] or dp[j - stone] + for j in range(n, -1, -1): + if dp[j]: + return s - j - j +``` + +### **Java** + +```java +class Solution { + public int lastStoneWeightII(int[] stones) { + int sum = 0; + for (int stone : stones) { + sum += stone; + } + int n = sum / 2; + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int stone : stones) { + for (int j = n; j >= stone; j--) { + dp[j] = dp[j] || dp[j - stone]; + } + } + for (int j = n; ; j--) { + if (dp[j]) { + return sum - j - j; + } + } + } +} +``` + +### **Go** + +```go +func lastStoneWeightII(stones []int) int { + sum := 0 + for _, stone := range stones { + sum += stone + } + n := sum / 2 + dp := make([]bool, n+1) + dp[0] = true + for _, stone := range stones { + for j := n; j >= stone; j-- { + dp[j] = dp[j] || dp[j-stone] + } + } + for j := n; ; j-- { + if dp[j] { + return sum - j - j + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md b/assets/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md new file mode 100644 index 00000000..c8368824 --- /dev/null +++ b/assets/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md @@ -0,0 +1,109 @@ +# [1050. Actors and Directors Who Cooperated At Least Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times) + + + +## Description + +

    Table: ActorDirector

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| actor_id    | int     |
    +
    +| director_id | int     |
    +
    +| timestamp   | int     |
    +
    ++-------------+---------+
    +
    +timestamp is the primary key column for this table.
    +
    +
    + + + +

     

    + + + +

    Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor have cooperated with the director at least 3 times.

    + + + +

    Example:

    + + + +
    +
    +ActorDirector table:
    +
    ++-------------+-------------+-------------+
    +
    +| actor_id    | director_id | timestamp   |
    +
    ++-------------+-------------+-------------+
    +
    +| 1           | 1           | 0           |
    +
    +| 1           | 1           | 1           |
    +
    +| 1           | 1           | 2           |
    +
    +| 1           | 2           | 3           |
    +
    +| 1           | 2           | 4           |
    +
    +| 2           | 1           | 5           |
    +
    +| 2           | 1           | 6           |
    +
    ++-------------+-------------+-------------+
    +
    +
    +
    +Result table:
    +
    ++-------------+-------------+
    +
    +| actor_id    | director_id |
    +
    ++-------------+-------------+
    +
    +| 1           | 1           |
    +
    ++-------------+-------------+
    +
    +The only pair is (1, 1) where they cooperated exactly 3 times.
    +
    +
    + + + +## Solutions + +Use `GROUP BY` & `HAVING`. + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + actor_id, director_id +FROM + ActorDirector +GROUP BY actor_id, director_id +HAVING count(1) >= 3; +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1051.Height Checker/README_EN.md b/assets/1000-1099/1051.Height Checker/README_EN.md new file mode 100644 index 00000000..c79a6264 --- /dev/null +++ b/assets/1000-1099/1051.Height Checker/README_EN.md @@ -0,0 +1,78 @@ +# [1051. Height Checker](https://leetcode.com/problems/height-checker) + + + +## Description + +

    A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.

    + +

    You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).

    + +

    Return the number of indices where heights[i] != expected[i].

    + +

     

    +

    Example 1:

    + +
    +Input: heights = [1,1,4,2,1,3]
    +Output: 3
    +Explanation: 
    +heights:  [1,1,4,2,1,3]
    +expected: [1,1,1,2,3,4]
    +Indices 2, 4, and 5 do not match.
    +
    + +

    Example 2:

    + +
    +Input: heights = [5,1,2,3,4]
    +Output: 5
    +Explanation:
    +heights:  [5,1,2,3,4]
    +expected: [1,2,3,4,5]
    +All indices do not match.
    +
    + +

    Example 3:

    + +
    +Input: heights = [1,2,3,4,5]
    +Output: 0
    +Explanation:
    +heights:  [1,2,3,4,5]
    +expected: [1,2,3,4,5]
    +All indices match.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= heights.length <= 100
    • +
    • 1 <= heights[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md b/assets/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md new file mode 100644 index 00000000..f343fa75 --- /dev/null +++ b/assets/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md @@ -0,0 +1,109 @@ +# [1052. Grumpy Bookstore Owner](https://leetcode.com/problems/grumpy-bookstore-owner) + + + +## Description + +

    Today, the bookstore owner has a store open for customers.length minutes.  Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute.

    + + + +

    On some minutes, the bookstore owner is grumpy.  If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0.  When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.

    + + + +

    The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once.

    + + + +

    Return the maximum number of customers that can be satisfied throughout the day.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
    +
    +Output: 16
    +
    +Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. 
    +
    +The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    • 1 <= X <= customers.length == grumpy.length <= 20000
    • +
    • 0 <= customers[i] <= 1000
    • +
    • 0 <= grumpy[i] <= 1
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int: + s = t = 0 + win, n = 0, len(customers) + for i in range(n): + if grumpy[i] == 0: + s += customers[i] + else: + win += customers[i] + if i >= X and grumpy[i - X] == 1: + win -= customers[i - X] + t = max(t, win) + return s + t +``` + +### **Java** + +```java +class Solution { + public int maxSatisfied(int[] customers, int[] grumpy, int X) { + int s = 0, t = 0; + for (int i = 0, win = 0, n = customers.length; i < n; ++i) { + if (grumpy[i] == 0) { + s += customers[i]; + } else { + win += customers[i]; + } + if (i >= X && grumpy[i - X] == 1) { + win -= customers[i - X]; + } + t = Math.max(t, win); + } + return s + t; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1053.Previous Permutation With One Swap/README_EN.md b/assets/1000-1099/1053.Previous Permutation With One Swap/README_EN.md new file mode 100644 index 00000000..2f3b88ab --- /dev/null +++ b/assets/1000-1099/1053.Previous Permutation With One Swap/README_EN.md @@ -0,0 +1,73 @@ +# [1053. Previous Permutation With One Swap](https://leetcode.com/problems/previous-permutation-with-one-swap) + + + +## Description + +

    Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,2,1]
    +Output: [3,1,2]
    +Explanation: Swapping 2 and 1.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,1,5]
    +Output: [1,1,5]
    +Explanation: This is already the smallest permutation.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,9,4,6,7]
    +Output: [1,7,4,6,9]
    +Explanation: Swapping 9 and 7.
    +
    + +

    Example 4:

    + +
    +Input: arr = [3,1,1,3]
    +Output: [1,3,1,3]
    +Explanation: Swapping 1 and 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 1 <= arr[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1054.Distant Barcodes/README_EN.md b/assets/1000-1099/1054.Distant Barcodes/README_EN.md new file mode 100644 index 00000000..a0fca57a --- /dev/null +++ b/assets/1000-1099/1054.Distant Barcodes/README_EN.md @@ -0,0 +1,50 @@ +# [1054. Distant Barcodes](https://leetcode.com/problems/distant-barcodes) + + + +## Description + +

    In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].

    + +

    Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.

    + +

     

    +

    Example 1:

    +
    Input: barcodes = [1,1,1,2,2,2]
    +Output: [2,1,2,1,2,1]
    +

    Example 2:

    +
    Input: barcodes = [1,1,1,1,2,2,3,3]
    +Output: [1,3,1,3,1,2,1,2]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= barcodes.length <= 10000
    • +
    • 1 <= barcodes[i] <= 10000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1055.Shortest Way to Form String/README_EN.md b/assets/1000-1099/1055.Shortest Way to Form String/README_EN.md new file mode 100644 index 00000000..79d5267d --- /dev/null +++ b/assets/1000-1099/1055.Shortest Way to Form String/README_EN.md @@ -0,0 +1,98 @@ +# [1055. Shortest Way to Form String](https://leetcode.com/problems/shortest-way-to-form-string) + + + +## Description + +

    From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).

    + + + +

    Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: source = "abc", target = "abcbc"
    +
    +Output: 2
    +
    +Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: source = "abc", target = "acdbc"
    +
    +Output: -1
    +
    +Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target string.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: source = "xyz", target = "xzyxz"
    +
    +Output: 3
    +
    +Explanation: The target string can be constructed as follows "xz" + "y" + "xz".
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • Both the source and target strings consist of only lowercase English letters from "a"-"z".
    • +
    • The lengths of source and target string are between 1 and 1000.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1056.Confusing Number/README_EN.md b/assets/1000-1099/1056.Confusing Number/README_EN.md new file mode 100644 index 00000000..03dfcd37 --- /dev/null +++ b/assets/1000-1099/1056.Confusing Number/README_EN.md @@ -0,0 +1,142 @@ +# [1056. Confusing Number](https://leetcode.com/problems/confusing-number) + + + +## Description + +

    Given a number N, return true if and only if it is a confusing number, which satisfies the following condition:

    + + + +

    We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid. A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.

    + + + +

     

    + + + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: 6
    +
    +Output: true
    +
    +Explanation: 
    +
    +We get 9 after rotating 6, 9 is a valid number and 9!=6.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: 89
    +
    +Output: true
    +
    +Explanation: 
    +
    +We get 68 after rotating 89, 86 is a valid number and 86!=89.
    +
    +
    + + + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: 11
    +
    +Output: false
    +
    +Explanation: 
    +
    +We get 11 after rotating 11, 11 is a valid number but the value remains the same, thus 11 is not a confusing number.
    +
    +
    + + + +

    Example 4:

    + + + +

    + + + +
    +
    +Input: 25
    +
    +Output: false
    +
    +Explanation: 
    +
    +We get an invalid number after rotating 25.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 0 <= N <= 10^9
    2. +
    3. After the rotation we can ignore leading zeros, for example if after rotation we have 0008 then this number is considered as just 8.
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1056.Confusing Number/images/1268_1.png b/assets/1000-1099/1056.Confusing Number/images/1268_1.png new file mode 100644 index 00000000..d85ca06b Binary files /dev/null and b/assets/1000-1099/1056.Confusing Number/images/1268_1.png differ diff --git a/assets/1000-1099/1056.Confusing Number/images/1268_2.png b/assets/1000-1099/1056.Confusing Number/images/1268_2.png new file mode 100644 index 00000000..47c29c7d Binary files /dev/null and b/assets/1000-1099/1056.Confusing Number/images/1268_2.png differ diff --git a/assets/1000-1099/1056.Confusing Number/images/1268_3.png b/assets/1000-1099/1056.Confusing Number/images/1268_3.png new file mode 100644 index 00000000..eae482e1 Binary files /dev/null and b/assets/1000-1099/1056.Confusing Number/images/1268_3.png differ diff --git a/assets/1000-1099/1056.Confusing Number/images/1268_4.png b/assets/1000-1099/1056.Confusing Number/images/1268_4.png new file mode 100644 index 00000000..b413cfad Binary files /dev/null and b/assets/1000-1099/1056.Confusing Number/images/1268_4.png differ diff --git a/assets/1000-1099/1057.Campus Bikes/README_EN.md b/assets/1000-1099/1057.Campus Bikes/README_EN.md new file mode 100644 index 00000000..0ad3931c --- /dev/null +++ b/assets/1000-1099/1057.Campus Bikes/README_EN.md @@ -0,0 +1,109 @@ +# [1057. Campus Bikes](https://leetcode.com/problems/campus-bikes) + + + +## Description + +

    On a campus represented as a 2D grid, there are N workers and M bikes, with N <= M. Each worker and bike is a 2D coordinate on this grid.

    + + + +

    Our goal is to assign a bike to each worker. Among the available bikes and workers, we choose the (worker, bike) pair with the shortest Manhattan distance between each other, and assign the bike to that worker. (If there are multiple (worker, bike) pairs with the same shortest Manhattan distance, we choose the pair with the smallest worker index; if there are multiple ways to do that, we choose the pair with the smallest bike index). We repeat this process until there are no available workers.

    + + + +

    The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.

    + + + +

    Return a vector ans of length N, where ans[i] is the index (0-indexed) of the bike that the i-th worker is assigned to.

    + + + +

     

    + + + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
    +
    +Output: [1,0]
    +
    +Explanation: 
    +
    +Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0].
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
    +
    +Output: [0,2,1]
    +
    +Explanation: 
    +
    +Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is [0,2,1].
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 0 <= workers[i][j], bikes[i][j] < 1000
    2. +
    3. All worker and bike locations are distinct.
    4. +
    5. 1 <= workers.length <= bikes.length <= 1000
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1057.Campus Bikes/images/1261_example_1_v2.png b/assets/1000-1099/1057.Campus Bikes/images/1261_example_1_v2.png new file mode 100644 index 00000000..bb521386 Binary files /dev/null and b/assets/1000-1099/1057.Campus Bikes/images/1261_example_1_v2.png differ diff --git a/assets/1000-1099/1057.Campus Bikes/images/1261_example_2_v2.png b/assets/1000-1099/1057.Campus Bikes/images/1261_example_2_v2.png new file mode 100644 index 00000000..c275a91b Binary files /dev/null and b/assets/1000-1099/1057.Campus Bikes/images/1261_example_2_v2.png differ diff --git a/assets/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md b/assets/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md new file mode 100644 index 00000000..c879f08e --- /dev/null +++ b/assets/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md @@ -0,0 +1,68 @@ +# [1058. Minimize Rounding Error to Meet Target](https://leetcode.com/problems/minimize-rounding-error-to-meet-target) + + + +## Description + +

    Given an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target. Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi).

    + +

    Return the string "-1" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| for i from 1 to n, as a string with three places after the decimal.

    + +

     

    +

    Example 1:

    + +
    +Input: prices = ["0.700","2.800","4.900"], target = 8
    +Output: "1.000"
    +Explanation:
    +Use Floor, Ceil and Ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0 .
    +
    + +

    Example 2:

    + +
    +Input: prices = ["1.500","2.500","3.500"], target = 10
    +Output: "-1"
    +Explanation: It is impossible to meet the target.
    +
    + +

    Example 3:

    + +
    +Input: prices = ["1.500","2.500","3.500"], target = 9
    +Output: "1.500"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= prices.length <= 500
    • +
    • Each string prices[i] represents a real number in the range [0.0, 1000.0] and has exactly 3 decimal places.
    • +
    • 0 <= target <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md b/assets/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md new file mode 100644 index 00000000..270c6c2e --- /dev/null +++ b/assets/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md @@ -0,0 +1,93 @@ +# [1059. All Paths from Source Lead to Destination](https://leetcode.com/problems/all-paths-from-source-lead-to-destination) + + + +## Description + +

    Given the edges of a directed graph where edges[i] = [ai, bi] indicates there is an edge between nodes ai and bi, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually, end at destination, that is:

    + +
      +
    • At least one path exists from the source node to the destination node
    • +
    • If a path exists from the source node to a node with no outgoing edges, then that node is equal to destination.
    • +
    • The number of possible paths from source to destination is a finite number.
    • +
    + +

    Return true if and only if all roads from source lead to destination.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
    +Output: false
    +Explanation: It is possible to reach and get stuck on both node 1 and node 2.
    +
    + +

    Example 2:

    + +
    +Input: n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3
    +Output: false
    +Explanation: We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.
    +
    + +

    Example 3:

    + +
    +Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
    +Output: true
    +
    + +

    Example 4:

    + +
    +Input: n = 3, edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2
    +Output: false
    +Explanation: All paths from the source node end at the destination node, but there are an infinite number of paths, such as 0-1-2, 0-1-1-2, 0-1-1-1-2, 0-1-1-1-1-2, and so on.
    +
    + +

    Example 5:

    + +
    +Input: n = 2, edges = [[0,1],[1,1]], source = 0, destination = 1
    +Output: false
    +Explanation: There is infinite self-loop at destination node.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 104
    • +
    • 0 <= edges.length <= 104
    • +
    • edges.length == 2
    • +
    • 0 <= ai, bi <= n - 1
    • +
    • 0 <= source <= n - 1
    • +
    • 0 <= destination <= n - 1
    • +
    • The given graph may have self-loops and parallel edges.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_1.png b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_1.png new file mode 100644 index 00000000..6d2422c9 Binary files /dev/null and b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_1.png differ diff --git a/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_2.png b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_2.png new file mode 100644 index 00000000..20123930 Binary files /dev/null and b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_2.png differ diff --git a/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_3.png b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_3.png new file mode 100644 index 00000000..ab3e67c8 Binary files /dev/null and b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_3.png differ diff --git a/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_4.png b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_4.png new file mode 100644 index 00000000..7a000025 Binary files /dev/null and b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_4.png differ diff --git a/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_5.png b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_5.png new file mode 100644 index 00000000..191c8483 Binary files /dev/null and b/assets/1000-1099/1059.All Paths from Source Lead to Destination/images/485_example_5.png differ diff --git a/assets/1000-1099/1060.Missing Element in Sorted Array/README_EN.md b/assets/1000-1099/1060.Missing Element in Sorted Array/README_EN.md new file mode 100644 index 00000000..0ca122e2 --- /dev/null +++ b/assets/1000-1099/1060.Missing Element in Sorted Array/README_EN.md @@ -0,0 +1,69 @@ +# [1060. Missing Element in Sorted Array](https://leetcode.com/problems/missing-element-in-sorted-array) + + + +## Description + +

    Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [4,7,9,10], k = 1
    +Output: 5
    +Explanation: The first missing number is 5.
    +
    + +

    Example 2:

    + +
    +Input: nums = [4,7,9,10], k = 3
    +Output: 8
    +Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,4], k = 3
    +Output: 6
    +Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 1 <= nums[i] <= 107
    • +
    • nums is sorted in ascending order, and all the elements are unique.
    • +
    • 1 <= k <= 108
    • +
    + +

     

    +Follow up: Can you find a logarithmic time complexity (i.e., O(log(n))) solution? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md b/assets/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md new file mode 100644 index 00000000..4844ded5 --- /dev/null +++ b/assets/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md @@ -0,0 +1,119 @@ +# [1061. Lexicographically Smallest Equivalent String](https://leetcode.com/problems/lexicographically-smallest-equivalent-string) + + + +## Description + +

    Given strings A and B of the same length, we say A[i] and B[i] are equivalent characters. For example, if A = "abc" and B = "cde", then we have 'a' == 'c', 'b' == 'd', 'c' == 'e'.

    + + + +

    Equivalent characters follow the usual rules of any equivalence relation:

    + + + +
      +
    • Reflexivity: 'a' == 'a'
    • +
    • Symmetry: 'a' == 'b' implies 'b' == 'a'
    • +
    • Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'
    • +
    + + + +

    For example, given the equivalency information from A and B above, S = "eed", "acd", and "aab" are equivalent strings, and "aab" is the lexicographically smallest equivalent string of S.

    + + + +

    Return the lexicographically smallest equivalent string of S by using the equivalency information from A and B.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: A = "parker", B = "morris", S = "parser"
    +
    +Output: "makkek"
    +
    +Explanation: Based on the equivalency information in A and B, we can group their characters as [m,p], [a,o], [k,r,s], [e,i]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: A = "hello", B = "world", S = "hold"
    +
    +Output: "hdld"
    +
    +Explanation:  Based on the equivalency information in A and B, we can group their characters as [h,w], [d,e,o], [l,r]. So only the second letter 'o' in S is changed to 'd', the answer is "hdld".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: A = "leetcode", B = "programs", S = "sourcecode"
    +
    +Output: "aauaaaaada"
    +
    +Explanation:  We group the equivalent characters in A and B as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in S except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. String A, B and S consist of only lowercase English letters from 'a' - 'z'.
    2. +
    3. The lengths of string A, B and S are between 1 and 1000.
    4. +
    5. String A and B are of the same length.
    6. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1062.Longest Repeating Substring/README_EN.md b/assets/1000-1099/1062.Longest Repeating Substring/README_EN.md new file mode 100644 index 00000000..74ce62e6 --- /dev/null +++ b/assets/1000-1099/1062.Longest Repeating Substring/README_EN.md @@ -0,0 +1,73 @@ +# [1062. Longest Repeating Substring](https://leetcode.com/problems/longest-repeating-substring) + + + +## Description + +

    Given a string S, find out the length of the longest repeating substring(s). Return 0 if no repeating substring exists.

    + +

     

    +

    Example 1:

    + +
    +Input: S = "abcd"
    +Output: 0
    +Explanation: There is no repeating substring.
    +
    + +

    Example 2:

    + +
    +Input: S = "abbaba"
    +Output: 2
    +Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice.
    +
    + +

    Example 3:

    + +
    +Input: S = "aabcaabdaab"
    +Output: 3
    +Explanation: The longest repeating substring is "aab", which occurs 3 times.
    +
    + +

    Example 4:

    + +
    +Input: S = "aaaaa"
    +Output: 4
    +Explanation: The longest repeating substring is "aaaa", which occurs twice.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The string S consists of only lowercase English letters from 'a' - 'z'.
    • +
    • 1 <= S.length <= 1500
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1063.Number of Valid Subarrays/README_EN.md b/assets/1000-1099/1063.Number of Valid Subarrays/README_EN.md new file mode 100644 index 00000000..f43f8690 --- /dev/null +++ b/assets/1000-1099/1063.Number of Valid Subarrays/README_EN.md @@ -0,0 +1,102 @@ +# [1063. Number of Valid Subarrays](https://leetcode.com/problems/number-of-valid-subarrays) + + + +## Description + +

    Given an array A of integers, return the number of non-empty continuous subarrays that satisfy the following condition:

    + + + +

    The leftmost element of the subarray is not larger than other elements in the subarray.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [1,4,2,5,3]
    +
    +Output: 11
    +
    +Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: [3,2,1]
    +
    +Output: 3
    +
    +Explanation: The 3 valid subarrays are: [3],[2],[1].
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: [2,2,2]
    +
    +Output: 6
    +
    +Explanation: There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2].
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. 0 <= A[i] <= 100000
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1064.Fixed Point/README_EN.md b/assets/1000-1099/1064.Fixed Point/README_EN.md new file mode 100644 index 00000000..e1ecb835 --- /dev/null +++ b/assets/1000-1099/1064.Fixed Point/README_EN.md @@ -0,0 +1,128 @@ +# [1064. Fixed Point](https://leetcode.com/problems/fixed-point) + + + +## Description + +

    Given an array of distinct integers arr, where arr is sorted in ascending order, return the smallest index i that satisfies arr[i] == i. If there is no such index, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [-10,-5,0,3,7]
    +Output: 3
    +Explanation: For the given array, arr[0] = -10, arr[1] = -5, arr[2] = 0, arr[3] = 3, thus the output is 3.
    + +

    Example 2:

    + +
    +Input: arr = [0,2,5,8,17]
    +Output: 0
    +Explanation: arr[0] = 0, thus the output is 0.
    + +

    Example 3:

    + +
    +Input: arr = [-10,-5,3,4,7,9]
    +Output: -1
    +Explanation: There is no such i that arr[i] == i, thus the output is -1.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length < 104
    • +
    • -109 <= arr[i] <= 109
    • +
    + +

     

    +Follow up: The O(n) solution is very straightforward. Can we do better? + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def fixedPoint(self, arr: List[int]) -> int: + left, right = 0, len(arr) - 1 + while left < right: + mid = (left + right) >> 1 + if arr[mid] >= mid: + right = mid + else: + left = mid + 1 + return left if arr[left] == left else -1 +``` + +### **Java** + +```java +class Solution { + public int fixedPoint(int[] arr) { + int left = 0, right = arr.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] >= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == left ? left : -1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int fixedPoint(vector& arr) { + int left = 0, right = arr.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (arr[mid] >= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == left ? left : -1; + } +}; +``` + +### **Go** + +```go +func fixedPoint(arr []int) int { + left, right := 0, len(arr)-1 + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= mid { + right = mid + } else { + left = mid + 1 + } + } + if arr[left] == left { + return left + } + return -1 +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1065.Index Pairs of a String/README_EN.md b/assets/1000-1099/1065.Index Pairs of a String/README_EN.md new file mode 100644 index 00000000..c66064f0 --- /dev/null +++ b/assets/1000-1099/1065.Index Pairs of a String/README_EN.md @@ -0,0 +1,86 @@ +# [1065. Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string) + + + +## Description + +

    Given a text string and words (a list of strings), return all index pairs [i, j] so that the substring text[i]...text[j] is in the list of words.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
    +
    +Output: [[3,7],[9,13],[10,17]]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: text = "ababa", words = ["aba","ab"]
    +
    +Output: [[0,1],[0,2],[2,3],[2,4]]
    +
    +Explanation: 
    +
    +Notice that matches can overlap, see "aba" is found in [0,2] and [2,4].
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. All strings contains only lowercase English letters.
    2. +
    3. It's guaranteed that all strings in words are different.
    4. +
    5. 1 <= text.length <= 100
    6. +
    7. 1 <= words.length <= 20
    8. +
    9. 1 <= words[i].length <= 50
    10. +
    11. Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate).
    12. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1066.Campus Bikes II/1261_example_1_v2.png b/assets/1000-1099/1066.Campus Bikes II/1261_example_1_v2.png new file mode 100644 index 00000000..bb521386 Binary files /dev/null and b/assets/1000-1099/1066.Campus Bikes II/1261_example_1_v2.png differ diff --git a/assets/1000-1099/1066.Campus Bikes II/1261_example_2_v2.png b/assets/1000-1099/1066.Campus Bikes II/1261_example_2_v2.png new file mode 100644 index 00000000..c275a91b Binary files /dev/null and b/assets/1000-1099/1066.Campus Bikes II/1261_example_2_v2.png differ diff --git a/assets/1000-1099/1066.Campus Bikes II/README_EN.md b/assets/1000-1099/1066.Campus Bikes II/README_EN.md new file mode 100644 index 00000000..3d23423c --- /dev/null +++ b/assets/1000-1099/1066.Campus Bikes II/README_EN.md @@ -0,0 +1,77 @@ +# [1066. Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii) + + + +## Description + +

    On a campus represented as a 2D grid, there are N workers and M bikes, with N <= M. Each worker and bike is a 2D coordinate on this grid.

    + +

    We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized.

    + +

    The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.

    + +

    Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.

    + +

     

    +

    Example 1:

    + +
    +Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
    +Output: 6
    +Explanation: 
    +We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6.
    +
    + +

    Example 2:

    + +
    +Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
    +Output: 4
    +Explanation: 
    +We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4.
    +
    + +

    Example 3:

    + +
    +Input: workers = [[0,0],[1,0],[2,0],[3,0],[4,0]], bikes = [[0,999],[1,999],[2,999],[3,999],[4,999]]
    +Output: 4995
    +
    + +

     

    +

    Constraints:

    + +
      +
    • N == workers.length
    • +
    • M == bikes.length
    • +
    • 1 <= N <= M <= 10
    • +
    • workers[i].length == 2
    • +
    • bikes[i].length == 2
    • +
    • 0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000
    • +
    • All the workers and the bikes locations are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1066.Campus Bikes II/images/1261_example_1_v2.png b/assets/1000-1099/1066.Campus Bikes II/images/1261_example_1_v2.png new file mode 100644 index 00000000..c9ab1cf4 Binary files /dev/null and b/assets/1000-1099/1066.Campus Bikes II/images/1261_example_1_v2.png differ diff --git a/assets/1000-1099/1066.Campus Bikes II/images/1261_example_2_v2.png b/assets/1000-1099/1066.Campus Bikes II/images/1261_example_2_v2.png new file mode 100644 index 00000000..231ee5ee Binary files /dev/null and b/assets/1000-1099/1066.Campus Bikes II/images/1261_example_2_v2.png differ diff --git a/assets/1000-1099/1067.Digit Count in Range/README_EN.md b/assets/1000-1099/1067.Digit Count in Range/README_EN.md new file mode 100644 index 00000000..b0dda555 --- /dev/null +++ b/assets/1000-1099/1067.Digit Count in Range/README_EN.md @@ -0,0 +1,88 @@ +# [1067. Digit Count in Range](https://leetcode.com/problems/digit-count-in-range) + + + +## Description + +Given an integer d between 0 and 9, and two positive integers low and high as lower and upper bounds, respectively. Return the number of times that d occurs as a digit in all integers between low and high, including the bounds low and high. + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: d = 1, low = 1, high = 13
    +
    +Output: 6
    +
    +Explanation: 
    +
    +The digit d=1 occurs 6 times in 1,10,11,12,13. Note that the digit d=1 occurs twice in the number 11.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: d = 3, low = 100, high = 250
    +
    +Output: 35
    +
    +Explanation: 
    +
    +The digit d=3 occurs 35 times in 103,113,123,130,131,...,238,239,243.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 0 <= d <= 9
    2. +
    3. 1 <= low <= high <= 2×10^8
    4. +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1068.Product Sales Analysis I/README_EN.md b/assets/1000-1099/1068.Product Sales Analysis I/README_EN.md new file mode 100644 index 00000000..fddd1508 --- /dev/null +++ b/assets/1000-1099/1068.Product Sales Analysis I/README_EN.md @@ -0,0 +1,101 @@ +# [1068. Product Sales Analysis I](https://leetcode.com/problems/product-sales-analysis-i) + + + +## Description + +

    Table: Sales

    + +
    ++-------------+-------+
    +| Column Name | Type  |
    ++-------------+-------+
    +| sale_id     | int   |
    +| product_id  | int   |
    +| year        | int   |
    +| quantity    | int   |
    +| price       | int   |
    ++-------------+-------+
    +(sale_id, year) is the primary key of this table.
    +product_id is a foreign key to Product table.
    +Note that the price is per unit.
    +
    + +

     

    + +

    Table: Product

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    ++--------------+---------+
    +product_id is the primary key of this table.
    +
    + +

     

    + +

    Write an SQL query that reports the product_name, year, and price for each sale_id in the Sales table.

    + +

    Return the resulting table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Sales table:
    ++---------+------------+------+----------+-------+
    +| sale_id | product_id | year | quantity | price |
    ++---------+------------+------+----------+-------+ 
    +| 1       | 100        | 2008 | 10       | 5000  |
    +| 2       | 100        | 2009 | 12       | 5000  |
    +| 7       | 200        | 2011 | 15       | 9000  |
    ++---------+------------+------+----------+-------+
    +
    +Product table:
    ++------------+--------------+
    +| product_id | product_name |
    ++------------+--------------+
    +| 100        | Nokia        |
    +| 200        | Apple        |
    +| 300        | Samsung      |
    ++------------+--------------+
    +
    +Result table:
    ++--------------+-------+-------+
    +| product_name | year  | price |
    ++--------------+-------+-------+
    +| Nokia        | 2008  | 5000  |
    +| Nokia        | 2009  | 5000  |
    +| Apple        | 2011  | 9000  |
    ++--------------+-------+-------+
    +From sale_id = 1, we can conclude that Nokia was sold for 5000 in the year 2008.
    +From sale_id = 2, we can conclude that Nokia was sold for 5000 in the year 2009.
    +From sale_id = 7, we can conclude that Apple was sold for 9000 in the year 2011.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + p.product_name AS product_name, + s.year AS year, + s.price AS price +FROM + Sales s +LEFT JOIN + Product p +ON + s.product_id = p.product_id; +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1069.Product Sales Analysis II/README_EN.md b/assets/1000-1099/1069.Product Sales Analysis II/README_EN.md new file mode 100644 index 00000000..62ee0c58 --- /dev/null +++ b/assets/1000-1099/1069.Product Sales Analysis II/README_EN.md @@ -0,0 +1,148 @@ +# [1069. Product Sales Analysis II](https://leetcode.com/problems/product-sales-analysis-ii) + + + +## Description + +

    Table: Sales

    + + + +
    +
    ++-------------+-------+
    +
    +| Column Name | Type  |
    +
    ++-------------+-------+
    +
    +| sale_id     | int   |
    +
    +| product_id  | int   |
    +
    +| year        | int   |
    +
    +| quantity    | int   |
    +
    +| price       | int   |
    +
    ++-------------+-------+
    +
    +sale_id is the primary key of this table.
    +
    +product_id is a foreign key to Product table.
    +
    +Note that the price is per unit.
    +
    +
    + + + +

    Table: Product

    + + + +
    +
    ++--------------+---------+
    +
    +| Column Name  | Type    |
    +
    ++--------------+---------+
    +
    +| product_id   | int     |
    +
    +| product_name | varchar |
    +
    ++--------------+---------+
    +
    +product_id is the primary key of this table.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query that reports the total quantity sold for every product id.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Sales table:
    +
    ++---------+------------+------+----------+-------+
    +
    +| sale_id | product_id | year | quantity | price |
    +
    ++---------+------------+------+----------+-------+ 
    +
    +| 1       | 100        | 2008 | 10       | 5000  |
    +
    +| 2       | 100        | 2009 | 12       | 5000  |
    +
    +| 7       | 200        | 2011 | 15       | 9000  |
    +
    ++---------+------------+------+----------+-------+
    +
    +
    +
    +Product table:
    +
    ++------------+--------------+
    +
    +| product_id | product_name |
    +
    ++------------+--------------+
    +
    +| 100        | Nokia        |
    +
    +| 200        | Apple        |
    +
    +| 300        | Samsung      |
    +
    ++------------+--------------+
    +
    +
    +
    +Result table:
    +
    ++--------------+----------------+
    +
    +| product_id   | total_quantity |
    +
    ++--------------+----------------+
    +
    +| 100          | 22             |
    +
    +| 200          | 15             |
    +
    ++--------------+----------------+
    + + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + product_id, + sum(quantity) AS total_quantity +FROM + Sales +GROUP BY + product_id; +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1070.Product Sales Analysis III/README_EN.md b/assets/1000-1099/1070.Product Sales Analysis III/README_EN.md new file mode 100644 index 00000000..6de3347d --- /dev/null +++ b/assets/1000-1099/1070.Product Sales Analysis III/README_EN.md @@ -0,0 +1,158 @@ +# [1070. Product Sales Analysis III](https://leetcode.com/problems/product-sales-analysis-iii) + + + +## Description + +

    Table: Sales

    + + + +
    +
    ++-------------+-------+
    +
    +| Column Name | Type  |
    +
    ++-------------+-------+
    +
    +| sale_id     | int   |
    +
    +| product_id  | int   |
    +
    +| year        | int   |
    +
    +| quantity    | int   |
    +
    +| price       | int   |
    +
    ++-------------+-------+
    +
    +sale_id is the primary key of this table.
    +
    +product_id is a foreign key to Product table.
    +
    +Note that the price is per unit.
    +
    +
    + + + +

    Table: Product

    + + + +
    +
    ++--------------+---------+
    +
    +| Column Name  | Type    |
    +
    ++--------------+---------+
    +
    +| product_id   | int     |
    +
    +| product_name | varchar |
    +
    ++--------------+---------+
    +
    +product_id is the primary key of this table.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query that selects the product id, year, quantity, and price for the first year of every product sold.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Sales table:
    +
    ++---------+------------+------+----------+-------+
    +
    +| sale_id | product_id | year | quantity | price |
    +
    ++---------+------------+------+----------+-------+ 
    +
    +| 1       | 100        | 2008 | 10       | 5000  |
    +
    +| 2       | 100        | 2009 | 12       | 5000  |
    +
    +| 7       | 200        | 2011 | 15       | 9000  |
    +
    ++---------+------------+------+----------+-------+
    +
    +
    +
    +Product table:
    +
    ++------------+--------------+
    +
    +| product_id | product_name |
    +
    ++------------+--------------+
    +
    +| 100        | Nokia        |
    +
    +| 200        | Apple        |
    +
    +| 300        | Samsung      |
    +
    ++------------+--------------+
    +
    +
    +
    +Result table:
    +
    ++------------+------------+----------+-------+
    +
    +| product_id | first_year | quantity | price |
    +
    ++------------+------------+----------+-------+ 
    +
    +| 100        | 2008       | 10       | 5000  |
    +
    +| 200        | 2011       | 15       | 9000  |
    +
    ++------------+------------+----------+-------+
    +
    +
    + + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + product_id, + year as first_year, + quantity, + price +FROM + Sales +WHERE + (product_id, year) IN ( + SELECT + product_id, min(year) year + FROM + Sales + GROUP BY product_id + ); +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md b/assets/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md new file mode 100644 index 00000000..15d7f879 --- /dev/null +++ b/assets/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md @@ -0,0 +1,57 @@ +# [1071. Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings) + + + +## Description + +

    For two strings s and t, we say "t divides s" if and only if s = t + ... + t  (t concatenated with itself 1 or more times)

    + +

    Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

    + +

     

    +

    Example 1:

    +
    Input: str1 = "ABCABC", str2 = "ABC"
    +Output: "ABC"
    +

    Example 2:

    +
    Input: str1 = "ABABAB", str2 = "ABAB"
    +Output: "AB"
    +

    Example 3:

    +
    Input: str1 = "LEET", str2 = "CODE"
    +Output: ""
    +

    Example 4:

    +
    Input: str1 = "ABCDEF", str2 = "ABC"
    +Output: ""
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= str1.length <= 1000
    • +
    • 1 <= str2.length <= 1000
    • +
    • str1 and str2 consist of English uppercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md b/assets/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md new file mode 100644 index 00000000..3013c068 --- /dev/null +++ b/assets/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md @@ -0,0 +1,71 @@ +# [1072. Flip Columns For Maximum Number of Equal Rows](https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows) + + + +## Description + +

    You are given an m x n binary matrix matrix.

    + +

    You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).

    + +

    Return the maximum number of rows that have all values equal after some number of flips.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[0,1],[1,1]]
    +Output: 1
    +Explanation: After flipping no values, 1 row has all values equal.
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[0,1],[1,0]]
    +Output: 2
    +Explanation: After flipping values in the first column, both rows have equal values.
    +
    + +

    Example 3:

    + +
    +Input: matrix = [[0,0,0],[0,0,1],[1,1,0]]
    +Output: 2
    +Explanation: After flipping values in the first two columns, the last two rows have equal values.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 300
    • +
    • matrix[i][j] is either 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md b/assets/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md new file mode 100644 index 00000000..1f104bc3 --- /dev/null +++ b/assets/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md @@ -0,0 +1,68 @@ +# [1073. Adding Two Negabinary Numbers](https://leetcode.com/problems/adding-two-negabinary-numbers) + + + +## Description + +

    Given two numbers arr1 and arr2 in base -2, return the result of adding them together.

    + +

    Each number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.

    + +

    Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

    + +

     

    +

    Example 1:

    + +
    +Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]
    +Output: [1,0,0,0,0]
    +Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.
    +
    + +

    Example 2:

    + +
    +Input: arr1 = [0], arr2 = [0]
    +Output: [0]
    +
    + +

    Example 3:

    + +
    +Input: arr1 = [0], arr2 = [1]
    +Output: [1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 1000
    • +
    • arr1[i] and arr2[i] are 0 or 1
    • +
    • arr1 and arr2 have no leading zeros
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md b/assets/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md new file mode 100644 index 00000000..d01463d2 --- /dev/null +++ b/assets/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md @@ -0,0 +1,70 @@ +# [1074. Number of Submatrices That Sum to Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target) + + + +## Description + +

    Given a matrix and a target, return the number of non-empty submatrices that sum to target.

    + +

    A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.

    + +

    Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
    +Output: 4
    +Explanation: The four 1x1 submatrices that only contain 0.
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[1,-1],[-1,1]], target = 0
    +Output: 5
    +Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
    +
    + +

    Example 3:

    + +
    +Input: matrix = [[904]], target = 0
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= matrix.length <= 100
    • +
    • 1 <= matrix[0].length <= 100
    • +
    • -1000 <= matrix[i] <= 1000
    • +
    • -10^8 <= target <= 10^8
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1074.Number of Submatrices That Sum to Target/images/mate1.jpg b/assets/1000-1099/1074.Number of Submatrices That Sum to Target/images/mate1.jpg new file mode 100644 index 00000000..94498197 Binary files /dev/null and b/assets/1000-1099/1074.Number of Submatrices That Sum to Target/images/mate1.jpg differ diff --git a/assets/1000-1099/1075.Project Employees I/README_EN.md b/assets/1000-1099/1075.Project Employees I/README_EN.md new file mode 100644 index 00000000..facb30d4 --- /dev/null +++ b/assets/1000-1099/1075.Project Employees I/README_EN.md @@ -0,0 +1,82 @@ +# [1075. Project Employees I](https://leetcode.com/problems/project-employees-i) + + + +## Description + +

    Table: Project

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| project_id  | int     |
    +| employee_id | int     |
    ++-------------+---------+
    +(project_id, employee_id) is the primary key of this table.
    +employee_id is a foreign key to Employee table.
    +
    + +

    Table: Employee

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| employee_id      | int     |
    +| name             | varchar |
    +| experience_years | int     |
    ++------------------+---------+
    +employee_id is the primary key of this table.
    +
    + +

     

    + +

    Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.

    + +

    The query result format is in the following example:

    + +
    +Project table:
    ++-------------+-------------+
    +| project_id  | employee_id |
    ++-------------+-------------+
    +| 1           | 1           |
    +| 1           | 2           |
    +| 1           | 3           |
    +| 2           | 1           |
    +| 2           | 4           |
    ++-------------+-------------+
    +
    +Employee table:
    ++-------------+--------+------------------+
    +| employee_id | name   | experience_years |
    ++-------------+--------+------------------+
    +| 1           | Khaled | 3                |
    +| 2           | Ali    | 2                |
    +| 3           | John   | 1                |
    +| 4           | Doe    | 2                |
    ++-------------+--------+------------------+
    +
    +Result table:
    ++-------------+---------------+
    +| project_id  | average_years |
    ++-------------+---------------+
    +| 1           | 2.00          |
    +| 2           | 2.50          |
    ++-------------+---------------+
    +The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00 and for the second project is (3 + 2) / 2 = 2.50
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1076.Project Employees II/README_EN.md b/assets/1000-1099/1076.Project Employees II/README_EN.md new file mode 100644 index 00000000..9c65ad73 --- /dev/null +++ b/assets/1000-1099/1076.Project Employees II/README_EN.md @@ -0,0 +1,84 @@ +# [1076. Project Employees II](https://leetcode.com/problems/project-employees-ii) + + + +## Description + +

    Table: Project

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| project_id  | int     |
    +| employee_id | int     |
    ++-------------+---------+
    +(project_id, employee_id) is the primary key of this table.
    +employee_id is a foreign key to Employee table.
    +
    + +

     

    + +

    Table: Employee

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| employee_id      | int     |
    +| name             | varchar |
    +| experience_years | int     |
    ++------------------+---------+
    +employee_id is the primary key of this table.
    +
    + +

     

    + +

    Write an SQL query that reports all the projects that have the most employees.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Project table:
    ++-------------+-------------+
    +| project_id  | employee_id |
    ++-------------+-------------+
    +| 1           | 1           |
    +| 1           | 2           |
    +| 1           | 3           |
    +| 2           | 1           |
    +| 2           | 4           |
    ++-------------+-------------+
    +
    +Employee table:
    ++-------------+--------+------------------+
    +| employee_id | name   | experience_years |
    ++-------------+--------+------------------+
    +| 1           | Khaled | 3                |
    +| 2           | Ali    | 2                |
    +| 3           | John   | 1                |
    +| 4           | Doe    | 2                |
    ++-------------+--------+------------------+
    +
    +Result table:
    ++-------------+
    +| project_id  |
    ++-------------+
    +| 1           |
    ++-------------+
    +The first project has 3 employees while the second one has 2.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1077.Project Employees III/README_EN.md b/assets/1000-1099/1077.Project Employees III/README_EN.md new file mode 100644 index 00000000..337494ed --- /dev/null +++ b/assets/1000-1099/1077.Project Employees III/README_EN.md @@ -0,0 +1,82 @@ +# [1077. Project Employees III](https://leetcode.com/problems/project-employees-iii) + + + +## Description + +

    Table: Project

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| project_id  | int     |
    +| employee_id | int     |
    ++-------------+---------+
    +(project_id, employee_id) is the primary key of this table.
    +employee_id is a foreign key to Employee table.
    +
    + +

    Table: Employee

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| employee_id      | int     |
    +| name             | varchar |
    +| experience_years | int     |
    ++------------------+---------+
    +employee_id is the primary key of this table.
    +
    + +

     

    + +

    Write an SQL query that reports the most experienced employees in each project. In case of a tie, report all employees with the maximum number of experience years.

    + +

    The query result format is in the following example:

    + +
    +Project table:
    ++-------------+-------------+
    +| project_id  | employee_id |
    ++-------------+-------------+
    +| 1           | 1           |
    +| 1           | 2           |
    +| 1           | 3           |
    +| 2           | 1           |
    +| 2           | 4           |
    ++-------------+-------------+
    +
    +Employee table:
    ++-------------+--------+------------------+
    +| employee_id | name   | experience_years |
    ++-------------+--------+------------------+
    +| 1           | Khaled | 3                |
    +| 2           | Ali    | 2                |
    +| 3           | John   | 3                |
    +| 4           | Doe    | 2                |
    ++-------------+--------+------------------+
    +
    +Result table:
    ++-------------+---------------+
    +| project_id  | employee_id   |
    ++-------------+---------------+
    +| 1           | 1             |
    +| 1           | 3             |
    +| 2           | 1             |
    ++-------------+---------------+
    +Both employees with id 1 and 3 have the most experience among the employees of the first project. For the second project, the employee with id 1 has the most experience.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1078.Occurrences After Bigram/README_EN.md b/assets/1000-1099/1078.Occurrences After Bigram/README_EN.md new file mode 100644 index 00000000..ad8c0941 --- /dev/null +++ b/assets/1000-1099/1078.Occurrences After Bigram/README_EN.md @@ -0,0 +1,90 @@ +# [1078. Occurrences After Bigram](https://leetcode.com/problems/occurrences-after-bigram) + + + +## Description + +

    Given words first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second.

    + + + +

    For each such occurrence, add "third" to the answer, and return the answer.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
    +
    +Output: ["girl","student"]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: text = "we will we will rock you", first = "we", second = "will"
    +
    +Output: ["we","rock"]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= text.length <= 1000
    2. +
    3. text consists of space separated words, where each word consists of lowercase English letters.
    4. +
    5. 1 <= first.length, second.length <= 10
    6. +
    7. first and second consist of lowercase English letters.
    8. +
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1079.Letter Tile Possibilities/README_EN.md b/assets/1000-1099/1079.Letter Tile Possibilities/README_EN.md new file mode 100644 index 00000000..ac92c14f --- /dev/null +++ b/assets/1000-1099/1079.Letter Tile Possibilities/README_EN.md @@ -0,0 +1,65 @@ +# [1079. Letter Tile Possibilities](https://leetcode.com/problems/letter-tile-possibilities) + + + +## Description + +

    You have n  tiles, where each tile has one letter tiles[i] printed on it.

    + +

    Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.

    + +

     

    +

    Example 1:

    + +
    +Input: tiles = "AAB"
    +Output: 8
    +Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
    +
    + +

    Example 2:

    + +
    +Input: tiles = "AAABBC"
    +Output: 188
    +
    + +

    Example 3:

    + +
    +Input: tiles = "V"
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= tiles.length <= 7
    • +
    • tiles consists of uppercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md new file mode 100644 index 00000000..314c39d9 --- /dev/null +++ b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md @@ -0,0 +1,127 @@ +# [1080. Insufficient Nodes in Root to Leaf Paths](https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths) + + + +## Description + +

    Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf.  (A leaf is a node with no children.)

    + + + +

    A node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.

    + + + +

    Delete all insufficient nodes simultaneously, and return the root of the resulting binary tree.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +
    +
    +Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
    +
    +
    +
    +Output: [1,2,3,4,null,null,7,8,9,null,14]
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +
    +
    +Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
    +
    +
    +
    +Output: [5,4,8,11,null,17,4,7,null,null,null,5]
    + + + +

     

    + + + +

    Example 3:

    + + + +
    +
    +
    +
    +Input: root = [1,2,-3,-5,null,4,null], limit = -1
    +
    +
    +
    +Output: [1,null,-3,4]
    + +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. The given tree will have between 1 and 5000 nodes.
    2. +
    3. -10^5 <= node.val <= 10^5
    4. +
    5. -10^9 <= limit <= 10^9
    6. +
    + + + +
    + +
     
    + +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-1.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-1.png new file mode 100644 index 00000000..7570d678 Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-1.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-11.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-11.png new file mode 100644 index 00000000..7570d678 Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-11.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-2.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-2.png new file mode 100644 index 00000000..b20051e8 Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-2.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-3.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-3.png new file mode 100644 index 00000000..cd3f8ce7 Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-3.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-4.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-4.png new file mode 100644 index 00000000..52b4291b Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-4.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-5.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-5.png new file mode 100644 index 00000000..c9e6bde9 Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/insufficient-5.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/screen-shot-2019-06-11-at-83301-pm.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/screen-shot-2019-06-11-at-83301-pm.png new file mode 100644 index 00000000..fe8f526c Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/screen-shot-2019-06-11-at-83301-pm.png differ diff --git a/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/screen-shot-2019-06-11-at-83517-pm.png b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/screen-shot-2019-06-11-at-83517-pm.png new file mode 100644 index 00000000..6fa619b1 Binary files /dev/null and b/assets/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/images/screen-shot-2019-06-11-at-83517-pm.png differ diff --git a/assets/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md b/assets/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md new file mode 100644 index 00000000..65aca909 --- /dev/null +++ b/assets/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md @@ -0,0 +1,57 @@ +# [1081. Smallest Subsequence of Distinct Characters](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters) + + + +## Description + +

    Return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

    + +

    Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/

    + +

     

    +

    Example 1:

    + +
    +Input: s = "bcabc"
    +Output: "abc"
    +
    + +

    Example 2:

    + +
    +Input: s = "cbacdcbc"
    +Output: "acdb"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1082.Sales Analysis I/README_EN.md b/assets/1000-1099/1082.Sales Analysis I/README_EN.md new file mode 100644 index 00000000..604c4948 --- /dev/null +++ b/assets/1000-1099/1082.Sales Analysis I/README_EN.md @@ -0,0 +1,83 @@ +# [1082. Sales Analysis I](https://leetcode.com/problems/sales-analysis-i) + + + +## Description + +

    Table: Product

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    +| unit_price   | int     |
    ++--------------+---------+
    +product_id is the primary key of this table.
    +
    + +

    Table: Sales

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| seller_id   | int     |
    +| product_id  | int     |
    +| buyer_id    | int     |
    +| sale_date   | date    |
    +| quantity    | int     |
    +| price       | int     |
    ++------ ------+---------+
    +This table has no primary key, it can have repeated rows.
    +product_id is a foreign key to Product table.
    +
    + +

     

    + +

    Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.

    + +

    The query result format is in the following example:

    + +
    +Product table:
    ++------------+--------------+------------+
    +| product_id | product_name | unit_price |
    ++------------+--------------+------------+
    +| 1          | S8           | 1000       |
    +| 2          | G4           | 800        |
    +| 3          | iPhone       | 1400       |
    ++------------+--------------+------------+
    +
    +Sales table:
    ++-----------+------------+----------+------------+----------+-------+
    +| seller_id | product_id | buyer_id | sale_date  | quantity | price |
    ++-----------+------------+----------+------------+----------+-------+
    +| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
    +| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
    +| 2         | 2          | 3        | 2019-06-02 | 1        | 800   |
    +| 3         | 3          | 4        | 2019-05-13 | 2        | 2800  |
    ++-----------+------------+----------+------------+----------+-------+
    +
    +Result table:
    ++-------------+
    +| seller_id   |
    ++-------------+
    +| 1           |
    +| 3           |
    ++-------------+
    +Both sellers with id 1 and 3 sold products with the most total price of 2800.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1083.Sales Analysis II/README_EN.md b/assets/1000-1099/1083.Sales Analysis II/README_EN.md new file mode 100644 index 00000000..c593b2eb --- /dev/null +++ b/assets/1000-1099/1083.Sales Analysis II/README_EN.md @@ -0,0 +1,145 @@ +# [1083. Sales Analysis II](https://leetcode.com/problems/sales-analysis-ii) + + + +## Description + +

    Table: Product

    + + + +
    +
    ++--------------+---------+
    +
    +| Column Name  | Type    |
    +
    ++--------------+---------+
    +
    +| product_id   | int     |
    +
    +| product_name | varchar |
    +
    +| unit_price   | int     |
    +
    ++--------------+---------+
    +
    +product_id is the primary key of this table.
    +
    +
    + + + +

    Table: Sales

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| seller_id   | int     |
    +
    +| product_id  | int     |
    +
    +| buyer_id    | int     |
    +
    +| sale_date   | date    |
    +
    +| quantity    | int     |
    +
    +| price       | int     |
    +
    ++------ ------+---------+
    +
    +This table has no primary key, it can have repeated rows.
    +
    +product_id is a foreign key to Product table.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Product table:
    +
    ++------------+--------------+------------+
    +
    +| product_id | product_name | unit_price |
    +
    ++------------+--------------+------------+
    +
    +| 1          | S8           | 1000       |
    +
    +| 2          | G4           | 800        |
    +
    +| 3          | iPhone       | 1400       |
    +
    ++------------+--------------+------------+
    +
    +
    +
    +Sales table:
    +
    ++-----------+------------+----------+------------+----------+-------+
    +
    +| seller_id | product_id | buyer_id | sale_date  | quantity | price |
    +
    ++-----------+------------+----------+------------+----------+-------+
    +
    +| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
    +
    +| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
    +
    +| 2         | 1          | 3        | 2019-06-02 | 1        | 800   |
    +
    +| 3         | 3          | 3        | 2019-05-13 | 2        | 2800  |
    +
    ++-----------+------------+----------+------------+----------+-------+
    +
    +
    +
    +Result table:
    +
    ++-------------+
    +
    +| buyer_id    |
    +
    ++-------------+
    +
    +| 1           |
    +
    ++-------------+
    +
    +The buyer with id 1 bought an S8 but didn't buy an iPhone. The buyer with id 3 bought both.
    + + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1084.Sales Analysis III/README_EN.md b/assets/1000-1099/1084.Sales Analysis III/README_EN.md new file mode 100644 index 00000000..315dcea7 --- /dev/null +++ b/assets/1000-1099/1084.Sales Analysis III/README_EN.md @@ -0,0 +1,82 @@ +# [1084. Sales Analysis III](https://leetcode.com/problems/sales-analysis-iii) + + + +## Description + +

    Table: Product

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    +| unit_price   | int     |
    ++--------------+---------+
    +product_id is the primary key of this table.
    +
    + +

    Table: Sales

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| seller_id   | int     |
    +| product_id  | int     |
    +| buyer_id    | int     |
    +| sale_date   | date    |
    +| quantity    | int     |
    +| price       | int     |
    ++------ ------+---------+
    +This table has no primary key, it can have repeated rows.
    +product_id is a foreign key to Product table.
    +
    + +

     

    + +

    Write an SQL query that reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.

    + +

    The query result format is in the following example:

    + +
    +Product table:
    ++------------+--------------+------------+
    +| product_id | product_name | unit_price |
    ++------------+--------------+------------+
    +| 1          | S8           | 1000       |
    +| 2          | G4           | 800        |
    +| 3          | iPhone       | 1400       |
    ++------------+--------------+------------+
    +
    +Sales table:
    ++-----------+------------+----------+------------+----------+-------+
    +| seller_id | product_id | buyer_id | sale_date  | quantity | price |
    ++-----------+------------+----------+------------+----------+-------+
    +| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
    +| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
    +| 2         | 2          | 3        | 2019-06-02 | 1        | 800   |
    +| 3         | 3          | 4        | 2019-05-13 | 2        | 2800  |
    ++-----------+------------+----------+------------+----------+-------+
    +
    +Result table:
    ++-------------+--------------+
    +| product_id  | product_name |
    ++-------------+--------------+
    +| 1           | S8           |
    ++-------------+--------------+
    +The product with id 1 was only sold in spring 2019 while the other two were sold after.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md b/assets/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md new file mode 100644 index 00000000..b7d11182 --- /dev/null +++ b/assets/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md @@ -0,0 +1,62 @@ +# [1085. Sum of Digits in the Minimum Number](https://leetcode.com/problems/sum-of-digits-in-the-minimum-number) + + + +## Description + +

    Given an array A of positive integers, let S be the sum of the digits of the minimal element of A.

    + +

    Return 0 if S is odd, otherwise return 1.

    + +

     

    + +

    Example 1:

    + +
    +Input: [34,23,1,24,75,33,54,8]
    +Output: 0
    +Explanation: 
    +The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0.
    +
    + +

    Example 2:

    + +
    +Input: [99,77,33,66,55]
    +Output: 1
    +Explanation: 
    +The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= A.length <= 100
    • +
    • 1 <= A[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1086.High Five/README_EN.md b/assets/1000-1099/1086.High Five/README_EN.md new file mode 100644 index 00000000..01c53255 --- /dev/null +++ b/assets/1000-1099/1086.High Five/README_EN.md @@ -0,0 +1,113 @@ +# [1086. High Five](https://leetcode.com/problems/high-five) + + + +## Description + +

    Given a list of the scores of different students, items, where items[i] = [IDi, scorei] represents one score from a student with IDi, calculate each student's top five average.

    + +

    Return the answer as an array of pairs result, where result[j] = [IDj, topFiveAveragej] represents the student with IDj and their top five average. Sort result by IDj in increasing order.

    + +

    A student's top five average is calculated by taking the sum of their top five scores and dividing it by 5 using integer division.

    + +

     

    +

    Example 1:

    + +
    +Input: items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
    +Output: [[1,87],[2,88]]
    +Explanation: 
    +The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
    +The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
    +
    + +

    Example 2:

    + +
    +Input: items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]
    +Output: [[1,100],[7,100]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= items.length <= 1000
    • +
    • items[i].length == 2
    • +
    • 1 <= IDi <= 1000
    • +
    • 0 <= scorei <= 100
    • +
    • For each IDi, there will be at least five scores.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def highFive(self, items: List[List[int]]) -> List[List[int]]: + s = [None] * 101 + for i, score in items: + if s[i] is None: + s[i] = [] + s[i].append(score) + res = [] + for i, scores in enumerate(s): + if scores is None: + continue + avg = sum(heapq.nlargest(5, scores)) // 5 + res.append([i, avg]) + return res +``` + +### **Java** + +```java +class Solution { + public int[][] highFive(int[][] items) { + int size = 0; + PriorityQueue[] s = new PriorityQueue[101]; + int n = 5; + for (int[] item : items) { + int i = item[0], score = item[1]; + if (s[i] == null) { + ++size; + s[i] = new PriorityQueue<>(n); + } + s[i].offer(score); + if (s[i].size() > n) { + s[i].poll(); + } + } + int[][] res = new int[size][2]; + int j = 0; + for (int i = 0; i < 101; ++i) { + if (s[i] == null) { + continue; + } + int avg = sum(s[i]) / n; + res[j][0] = i; + res[j++][1] = avg; + } + return res; + } + + private int sum(PriorityQueue q) { + int s = 0; + while (!q.isEmpty()) { + s += q.poll(); + } + return s; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1087.Brace Expansion/README_EN.md b/assets/1000-1099/1087.Brace Expansion/README_EN.md new file mode 100644 index 00000000..2183299b --- /dev/null +++ b/assets/1000-1099/1087.Brace Expansion/README_EN.md @@ -0,0 +1,60 @@ +# [1087. Brace Expansion](https://leetcode.com/problems/brace-expansion) + + + +## Description + +

    You are given a string s representing a list of words. Each letter in the word has one or more options.

    + +
      +
    • If there is one option, the letter is represented as is.
    • +
    • If there is more than one option, then curly braces delimit the options. For example, "{a,b,c}" represents options ["a", "b", "c"].
    • +
    + +

    For example, if s = "a{b,c}", the first character is always 'a', but the second character can be 'b' or 'c'. The original list is ["ab", "ac"].

    + +

    Return all words that can be formed in this manner, sorted in lexicographical order.

    + +

     

    +

    Example 1:

    +
    Input: s = "{a,b}c{d,e}f"
    +Output: ["acdf","acef","bcdf","bcef"]
    +

    Example 2:

    +
    Input: s = "abcd"
    +Output: ["abcd"]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 50
    • +
    • s consists of curly brackets '{}', commas ',', and lowercase English letters.
    • +
    • s is guaranteed to be a valid input.
    • +
    • There are no nested curly brackets.
    • +
    • All characters inside a pair of consecutive opening and ending curly brackets are different.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1088.Confusing Number II/README_EN.md b/assets/1000-1099/1088.Confusing Number II/README_EN.md new file mode 100644 index 00000000..02f53e71 --- /dev/null +++ b/assets/1000-1099/1088.Confusing Number II/README_EN.md @@ -0,0 +1,107 @@ +# [1088. Confusing Number II](https://leetcode.com/problems/confusing-number-ii) + + + +## Description + +

    We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid.

    + + + +

    A confusing number is a number that when rotated 180 degrees becomes a different number with each digit valid.(Note that the rotated number can be greater than the original number.)

    + + + +

    Given a positive integer N, return the number of confusing numbers between 1 and N inclusive.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: 20
    +
    +Output: 6
    +
    +Explanation: 
    +
    +The confusing numbers are [6,9,10,16,18,19].
    +
    +6 converts to 9.
    +
    +9 converts to 6.
    +
    +10 converts to 01 which is just 1.
    +
    +16 converts to 91.
    +
    +18 converts to 81.
    +
    +19 converts to 61.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: 100
    +
    +Output: 19
    +
    +Explanation: 
    +
    +The confusing numbers are [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100].
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= N <= 10^9
    2. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1089.Duplicate Zeros/README_EN.md b/assets/1000-1099/1089.Duplicate Zeros/README_EN.md new file mode 100644 index 00000000..0c370000 --- /dev/null +++ b/assets/1000-1099/1089.Duplicate Zeros/README_EN.md @@ -0,0 +1,90 @@ +# [1089. Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros) + + + +## Description + +

    Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

    + + + +

    Note that elements beyond the length of the original array are not written.

    + + + +

    Do the above modifications to the input array in place, do not return anything from your function.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: [1,0,2,3,0,4,5,0]
    +
    +Output: null
    +
    +Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: [1,2,3]
    +
    +Output: null
    +
    +Explanation: After calling your function, the input array is modified to: [1,2,3]
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= arr.length <= 10000
    2. +
    3. 0 <= arr[i] <= 9
    4. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1090.Largest Values From Labels/README_EN.md b/assets/1000-1099/1090.Largest Values From Labels/README_EN.md new file mode 100644 index 00000000..4544675d --- /dev/null +++ b/assets/1000-1099/1090.Largest Values From Labels/README_EN.md @@ -0,0 +1,146 @@ +# [1090. Largest Values From Labels](https://leetcode.com/problems/largest-values-from-labels) + + + +## Description + +

    We have a set of items: the i-th item has value values[i] and label labels[i].

    + + + +

    Then, we choose a subset S of these items, such that:

    + + + +
      +
    • |S| <= num_wanted
    • +
    • For every label L, the number of items in S with label L is <= use_limit.
    • +
    + + + +

    Return the largest possible sum of the subset S.

    + + + +

     

    + + + +
    + +

    Example 1:

    + + + +
    +
    +Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
    +
    +Output: 9
    +
    +Explanation: The subset chosen is the first, third, and fifth item.
    +
    +
    + + + +
    + +

    Example 2:

    + + + +
    +
    +Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
    +
    +Output: 12
    +
    +Explanation: The subset chosen is the first, second, and third item.
    +
    +
    + + + +
    + +

    Example 3:

    + + + +
    +
    +Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
    +
    +Output: 16
    +
    +Explanation: The subset chosen is the first and fourth item.
    +
    +
    + + + +
    + +

    Example 4:

    + + + +
    +
    +Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
    +
    +Output: 24
    +
    +Explanation: The subset chosen is the first, second, and fourth item.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= values.length == labels.length <= 20000
    2. +
    3. 0 <= values[i], labels[i] <= 20000
    4. +
    5. 1 <= num_wanted, use_limit <= values.length
    6. +
    + +
    + +
    + +
    + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md b/assets/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md new file mode 100644 index 00000000..f3fe262c --- /dev/null +++ b/assets/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md @@ -0,0 +1,73 @@ +# [1091. Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix) + + + +## Description + +

    Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

    + +

    A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

    + +
      +
    • All the visited cells of the path are 0.
    • +
    • All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
    • +
    + +

    The length of a clear path is the number of visited cells of this path.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[0,1],[1,0]]
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
    +Output: 4
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 100
    • +
    • grid[i][j] is 0 or 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example1_1.png b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example1_1.png new file mode 100644 index 00000000..2cb91203 Binary files /dev/null and b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example1_1.png differ diff --git a/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example1_2.png b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example1_2.png new file mode 100644 index 00000000..a12583ce Binary files /dev/null and b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example1_2.png differ diff --git a/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example2_1.png b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example2_1.png new file mode 100644 index 00000000..84bd1bde Binary files /dev/null and b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example2_1.png differ diff --git a/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example2_2.png b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example2_2.png new file mode 100644 index 00000000..efceb383 Binary files /dev/null and b/assets/1000-1099/1091.Shortest Path in Binary Matrix/images/example2_2.png differ diff --git a/assets/1000-1099/1092.Shortest Common Supersequence/README_EN.md b/assets/1000-1099/1092.Shortest Common Supersequence/README_EN.md new file mode 100644 index 00000000..0365ebcc --- /dev/null +++ b/assets/1000-1099/1092.Shortest Common Supersequence/README_EN.md @@ -0,0 +1,56 @@ +# [1092. Shortest Common Supersequence](https://leetcode.com/problems/shortest-common-supersequence) + + + +## Description + +

    Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences.  If multiple answers exist, you may return any of them.

    + +

    (A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)

    + +

     

    + +

    Example 1:

    + +
    +Input: str1 = "abac", str2 = "cab"
    +Output: "cabac"
    +Explanation: 
    +str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
    +str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
    +The answer provided is the shortest such string that satisfies these properties.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 1 <= str1.length, str2.length <= 1000
    2. +
    3. str1 and str2 consist of lowercase English letters.
    4. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1093.Statistics from a Large Sample/README_EN.md b/assets/1000-1099/1093.Statistics from a Large Sample/README_EN.md new file mode 100644 index 00000000..8d425877 --- /dev/null +++ b/assets/1000-1099/1093.Statistics from a Large Sample/README_EN.md @@ -0,0 +1,84 @@ +# [1093. Statistics from a Large Sample](https://leetcode.com/problems/statistics-from-a-large-sample) + + + +## Description + +

    You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.

    + +

    Calculate the following statistics:

    + +
      +
    • minimum: The minimum element in the sample.
    • +
    • maximum: The maximum element in the sample.
    • +
    • mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.
    • +
    • median: +
        +
      • If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.
      • +
      • If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.
      • +
      +
    • +
    • mode: The number that appears the most in the sample. It is guaranteed to be unique.
    • +
    + +

    Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.

    + +

     

    +

    Example 1:

    + +
    +Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    +Output: [1.00000,3.00000,2.37500,2.50000,3.00000]
    +Explanation: The sample represented by count is [1,2,2,2,3,3,3,3].
    +The minimum and maximum are 1 and 3 respectively.
    +The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.
    +Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.
    +The mode is 3 as it appears the most in the sample.
    +
    + +

    Example 2:

    + +
    +Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    +Output: [1.00000,4.00000,2.18182,2.00000,1.00000]
    +Explanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].
    +The minimum and maximum are 1 and 4 respectively.
    +The mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).
    +Since the size of the sample is odd, the median is the middle element 2.
    +The mode is 1 as it appears the most in the sample.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • count.length == 256
    • +
    • 0 <= count[i] <= 109
    • +
    • 1 <= sum(count) <= 109
    • +
    • The mode of the sample that count represents is unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1094.Car Pooling/README_EN.md b/assets/1000-1099/1094.Car Pooling/README_EN.md new file mode 100644 index 00000000..3f039660 --- /dev/null +++ b/assets/1000-1099/1094.Car Pooling/README_EN.md @@ -0,0 +1,195 @@ +# [1094. Car Pooling](https://leetcode.com/problems/car-pooling) + + + +## Description + +

    You are driving a vehicle that has capacity empty seats initially available for passengers.  The vehicle only drives east (ie. it cannot turn around and drive west.)

    + +

    Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off.  The locations are given as the number of kilometers due east from your vehicle's initial location.

    + +

    Return true if and only if it is possible to pick up and drop off all passengers for all the given trips. 

    + +

     

    + +

    Example 1:

    + +
    +Input: trips = [[2,1,5],[3,3,7]], capacity = 4
    +Output: false
    +
    + +
    +

    Example 2:

    + +
    +Input: trips = [[2,1,5],[3,3,7]], capacity = 5
    +Output: true
    +
    + +
    +

    Example 3:

    + +
    +Input: trips = [[2,1,5],[3,5,7]], capacity = 3
    +Output: true
    +
    + +
    +

    Example 4:

    + +
    +Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
    +Output: true
    +
    +
    +
    +
    + +
    +
    +
    +
     
    +
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    1. trips.length <= 1000
    2. +
    3. trips[i].length == 3
    4. +
    5. 1 <= trips[i][0] <= 100
    6. +
    7. 0 <= trips[i][1] < trips[i][2] <= 1000
    8. +
    9. 1 <= capacity <= 100000
    10. +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def carPooling(self, trips: List[List[int]], capacity: int) -> bool: + delta = [0] * 1001 + for num, start, end in trips: + delta[start] += num + delta[end] -= num + cur = 0 + for num in delta: + cur += num + if cur > capacity: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean carPooling(int[][] trips, int capacity) { + int[] delta = new int[1001]; + for (int[] trip : trips) { + int num = trip[0], start = trip[1], end = trip[2]; + delta[start] += num; + delta[end] -= num; + } + int cur = 0; + for (int num : delta) { + cur += num; + if (cur > capacity) { + return false; + } + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} trips + * @param {number} capacity + * @return {boolean} + */ + var carPooling = function(trips, capacity) { + let delta = new Array(); + for (let trip of trips) { + let [num, start, end] = trip; + delta[start] = (delta[start] || 0) + num; + delta[end] = (delta[end] || 0) - num; + } + let total = 0; + for (let i = 0; i < delta.length; i++) { + let cur = delta[i]; + if (cur == undefined) continue; + total += cur; + if (total > capacity) return false; + } + return true; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool carPooling(vector>& trips, int capacity) { + vector delta(1001); + for (auto &trip : trips) { + int num = trip[0], start = trip[1], end = trip[2]; + delta[start] += num; + delta[end] -= num; + } + int cur = 0; + for (auto &num : delta) { + cur += num; + if (cur > capacity) { + return false; + } + } + return true; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} trips + * @param {number} capacity + * @return {boolean} + */ + var carPooling = function(trips, capacity) { + let delta = new Array(); + for (let trip of trips) { + let [num, start, end] = trip; + delta[start] = (delta[start] || 0) + num; + delta[end] = (delta[end] || 0) - num; + } + let total = 0; + for (let i = 0; i < delta.length; i++) { + let cur = delta[i]; + if (cur == undefined) continue; + total += cur; + if (total > capacity) return false; + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1095.Find in Mountain Array/README_EN.md b/assets/1000-1099/1095.Find in Mountain Array/README_EN.md new file mode 100644 index 00000000..2cab116b --- /dev/null +++ b/assets/1000-1099/1095.Find in Mountain Array/README_EN.md @@ -0,0 +1,83 @@ +# [1095. Find in Mountain Array](https://leetcode.com/problems/find-in-mountain-array) + + + +## Description + +

    (This problem is an interactive problem.)

    + +

    You may recall that an array A is a mountain array if and only if:

    + +
      +
    • A.length >= 3
    • +
    • There exists some i with 0 < i < A.length - 1 such that: +
        +
      • A[0] < A[1] < ... A[i-1] < A[i]
      • +
      • A[i] > A[i+1] > ... > A[A.length - 1]
      • +
      +
    • +
    + +

    Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target.  If such an index doesn't exist, return -1.

    + +

    You can't access the mountain array directly.  You may only access the array using a MountainArray interface:

    + +
      +
    • MountainArray.get(k) returns the element of the array at index k (0-indexed).
    • +
    • MountainArray.length() returns the length of the array.
    • +
    + +

    Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer.  Also, any solutions that attempt to circumvent the judge will result in disqualification.

    + +
      +
    + +

     

    +

    Example 1:

    + +
    +Input: array = [1,2,3,4,5,3,1], target = 3
    +Output: 2
    +Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
    + +

    Example 2:

    + +
    +Input: array = [0,1,2,4,2,1], target = 3
    +Output: -1
    +Explanation: 3 does not exist in the array, so we return -1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= mountain_arr.length() <= 10000
    • +
    • 0 <= target <= 10^9
    • +
    • 0 <= mountain_arr.get(index) <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1096.Brace Expansion II/README_EN.md b/assets/1000-1099/1096.Brace Expansion II/README_EN.md new file mode 100644 index 00000000..a53ff169 --- /dev/null +++ b/assets/1000-1099/1096.Brace Expansion II/README_EN.md @@ -0,0 +1,96 @@ +# [1096. Brace Expansion II](https://leetcode.com/problems/brace-expansion-ii) + + + +## Description + +

    Under a grammar given below, strings can represent a set of lowercase words.  Let's use R(expr) to denote the set of words the expression represents.

    + +

    Grammar can best be understood through simple examples:

    + +
      +
    • Single letters represent a singleton set containing that word. +
        +
      • R("a") = {"a"}
      • +
      • R("w") = {"w"}
      • +
      +
    • +
    • When we take a comma delimited list of 2 or more expressions, we take the union of possibilities. +
        +
      • R("{a,b,c}") = {"a","b","c"}
      • +
      • R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)
      • +
      +
    • +
    • When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. +
        +
      • R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
      • +
      • R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}
      • +
      +
    • +
    + +

    Formally, the 3 rules for our grammar:

    + +
      +
    • For every lowercase letter x, we have R(x) = {x}
    • +
    • For expressions e_1, e_2, ... , e_k with k >= 2, we have R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ...
    • +
    • For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, where + denotes concatenation, and × denotes the cartesian product.
    • +
    + +

    Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.

    + +

     

    + +
    +

    Example 1:

    + +
    +Input: "{a,b}{c,{d,e}}"
    +Output: ["ac","ad","ae","bc","bd","be"]
    +
    + +
    +

    Example 2:

    + +
    +Input: "{{a,z},a{b,c},{ab,z}}"
    +Output: ["a","ab","ac","z"]
    +Explanation: Each distinct word is written only once in the final answer.
    +
    + +

     

    + +

    Constraints:

    + +
      +
    1. 1 <= expression.length <= 60
    2. +
    3. expression[i] consists of '{', '}', ','or lowercase English letters.
    4. +
    5. The given expression represents a set of words based on the grammar given in the description.
    6. +
    +
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1097.Game Play Analysis V/README_EN.md b/assets/1000-1099/1097.Game Play Analysis V/README_EN.md new file mode 100644 index 00000000..c640c265 --- /dev/null +++ b/assets/1000-1099/1097.Game Play Analysis V/README_EN.md @@ -0,0 +1,67 @@ +# [1097. Game Play Analysis V](https://leetcode.com/problems/game-play-analysis-v) + + + +## Description + +

    Table: Activity

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| player_id    | int     |
    +| device_id    | int     |
    +| event_date   | date    |
    +| games_played | int     |
    ++--------------+---------+
    +(player_id, event_date) is the primary key of this table.
    +This table shows the activity of players of some game.
    +Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
    +
    + +

     

    + +

    We define the install date of a player to be the first login day of that player.

    + +

    We also define day 1 retention of some date X to be the number of players whose install date is X and they logged back in on the day right after X, divided by the number of players whose install date is X, rounded to 2 decimal places.

    + +

    Write an SQL query that reports for each install date, the number of players that installed the game on that day and the day 1 retention.

    + +

    The query result format is in the following example:

    + +
    +Activity table:
    ++-----------+-----------+------------+--------------+
    +| player_id | device_id | event_date | games_played |
    ++-----------+-----------+------------+--------------+
    +| 1         | 2         | 2016-03-01 | 5            |
    +| 1         | 2         | 2016-03-02 | 6            |
    +| 2         | 3         | 2017-06-25 | 1            |
    +| 3         | 1         | 2016-03-01 | 0            |
    +| 3         | 4         | 2016-07-03 | 5            |
    ++-----------+-----------+------------+--------------+
    +
    +Result table:
    ++------------+----------+----------------+
    +| install_dt | installs | Day1_retention |
    ++------------+----------+----------------+
    +| 2016-03-01 | 2        | 0.50           |
    +| 2017-06-25 | 1        | 0.00           |
    ++------------+----------+----------------+
    +Player 1 and 3 installed the game on 2016-03-01 but only player 1 logged back in on 2016-03-02 so the day 1 retention of 2016-03-01 is 1 / 2 = 0.50
    +Player 2 installed the game on 2017-06-25 but didn't log back in on 2017-06-26 so the day 1 retention of 2017-06-25 is 0 / 1 = 0.00
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1000-1099/1098.Unpopular Books/README_EN.md b/assets/1000-1099/1098.Unpopular Books/README_EN.md new file mode 100644 index 00000000..5a279d80 --- /dev/null +++ b/assets/1000-1099/1098.Unpopular Books/README_EN.md @@ -0,0 +1,99 @@ +# [1098. Unpopular Books](https://leetcode.com/problems/unpopular-books) + + + +## Description + +

    Table: Books

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| book_id        | int     |
    +| name           | varchar |
    +| available_from | date    |
    ++----------------+---------+
    +book_id is the primary key of this table.
    +
    + +

    Table: Orders

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| order_id       | int     |
    +| book_id        | int     |
    +| quantity       | int     |
    +| dispatch_date  | date    |
    ++----------------+---------+
    +order_id is the primary key of this table.
    +book_id is a foreign key to the Books table.
    +
    + +

     

    + +

    Write an SQL query that reports the books that have sold less than 10 copies in the last year, excluding books that have been available for less than 1 month from today. Assume today is 2019-06-23.

    + +

    The query result format is in the following example:

    + +
    +Books table:
    ++---------+--------------------+----------------+
    +| book_id | name               | available_from |
    ++---------+--------------------+----------------+
    +| 1       | "Kalila And Demna" | 2010-01-01     |
    +| 2       | "28 Letters"       | 2012-05-12     |
    +| 3       | "The Hobbit"       | 2019-06-10     |
    +| 4       | "13 Reasons Why"   | 2019-06-01     |
    +| 5       | "The Hunger Games" | 2008-09-21     |
    ++---------+--------------------+----------------+
    +
    +Orders table:
    ++----------+---------+----------+---------------+
    +| order_id | book_id | quantity | dispatch_date |
    ++----------+---------+----------+---------------+
    +| 1        | 1       | 2        | 2018-07-26    |
    +| 2        | 1       | 1        | 2018-11-05    |
    +| 3        | 3       | 8        | 2019-06-11    |
    +| 4        | 4       | 6        | 2019-06-05    |
    +| 5        | 4       | 5        | 2019-06-20    |
    +| 6        | 5       | 9        | 2009-02-02    |
    +| 7        | 5       | 8        | 2010-04-13    |
    ++----------+---------+----------+---------------+
    +
    +Result table:
    ++-----------+--------------------+
    +| book_id   | name               |
    ++-----------+--------------------+
    +| 1         | "Kalila And Demna" |
    +| 2         | "28 Letters"       |
    +| 5         | "The Hunger Games" |
    ++-----------+--------------------+
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1000-1099/1099.Two Sum Less Than K/README_EN.md b/assets/1000-1099/1099.Two Sum Less Than K/README_EN.md new file mode 100644 index 00000000..eff46392 --- /dev/null +++ b/assets/1000-1099/1099.Two Sum Less Than K/README_EN.md @@ -0,0 +1,109 @@ +# [1099. Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k) + + + +## Description + +

    Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [34,23,1,24,75,33,54,8], k = 60
    +Output: 58
    +Explanation: We can use 34 and 24 to sum 58 which is less than 60.
    +
    + +

    Example 2:

    + +
    +Input: nums = [10,20,30], k = 15
    +Output: -1
    +Explanation: In this case it is not possible to get a pair sum less that 15.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 1000
    • +
    • 1 <= k <= 2000
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def twoSumLessThanK(self, nums: List[int], k: int) -> int: + nums.sort() + low, high = 0, len(nums) - 1 + res = -1 + while low < high: + val = nums[low] + nums[high] + if val < k: + res = max(res, val) + low += 1 + else: + high -= 1 + return res +``` + +### **Java** + +```java +class Solution { + public int twoSumLessThanK(int[] nums, int k) { + Arrays.sort(nums); + int low = 0, high = nums.length - 1; + int res = -1; + while (low < high) { + int val = nums[low] + nums[high]; + if (val < k) { + res = Math.max(res, val); + ++low; + } else { + --high; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int twoSumLessThanK(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int low = 0, high = nums.size() - 1; + int res = -1; + while (low < high) { + int val = nums[low] + nums[high]; + if (val < k) { + res = max(res, val); + ++low; + } else { + --high; + } + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md b/assets/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md new file mode 100644 index 00000000..9e336554 --- /dev/null +++ b/assets/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md @@ -0,0 +1,89 @@ +# [1100. Find K-Length Substrings With No Repeated Characters](https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters) + + + +## Description + +

    Given a string S, return the number of substrings of length K with no repeated characters.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: S = "havefunonleetcode", K = 5
    +
    +Output: 6
    +
    +Explanation: 
    +
    +There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: S = "home", K = 5
    +
    +Output: 0
    +
    +Explanation: 
    +
    +Notice K can be larger than the length of S. In this case is not possible to find any substring.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= S.length <= 10^4
    2. +
    3. All characters of S are lowercase English letters.
    4. +
    5. 1 <= K <= 10^4
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md b/assets/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md new file mode 100644 index 00000000..0537b32c --- /dev/null +++ b/assets/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md @@ -0,0 +1,70 @@ +# [1101. The Earliest Moment When Everyone Become Friends](https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends) + + + +## Description + +

    In a social group, there are N people, with unique integer ids from 0 to N-1.

    + +

    We have a list of logs, where each logs[i] = [timestamp, id_A, id_B] contains a non-negative integer timestamp, and the ids of two different people.

    + +

    Each log represents the time in which two different people became friends.  Friendship is symmetric: if A is friends with B, then B is friends with A.

    + +

    Let's say that person A is acquainted with person B if A is friends with B, or A is a friend of someone acquainted with B.

    + +

    Return the earliest time for which every person became acquainted with every other person. Return -1 if there is no such earliest time.

    + +

     

    + +

    Example 1:

    + +
    +Input: logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], N = 6
    +Output: 20190301
    +Explanation: 
    +The first event occurs at timestamp = 20190101 and after 0 and 1 become friends we have the following friendship groups [0,1], [2], [3], [4], [5].
    +The second event occurs at timestamp = 20190104 and after 3 and 4 become friends we have the following friendship groups [0,1], [2], [3,4], [5].
    +The third event occurs at timestamp = 20190107 and after 2 and 3 become friends we have the following friendship groups [0,1], [2,3,4], [5].
    +The fourth event occurs at timestamp = 20190211 and after 1 and 5 become friends we have the following friendship groups [0,1,5], [2,3,4].
    +The fifth event occurs at timestamp = 20190224 and as 2 and 4 are already friend anything happens.
    +The sixth event occurs at timestamp = 20190301 and after 0 and 3 become friends we have that all become friends.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 2 <= N <= 100
    2. +
    3. 1 <= logs.length <= 10^4
    4. +
    5. 0 <= logs[i][0] <= 10^9
    6. +
    7. 0 <= logs[i][1], logs[i][2] <= N - 1
    8. +
    9. It's guaranteed that all timestamps in logs[i][0] are different.
    10. +
    11. logs are not necessarily ordered by some criteria.
    12. +
    13. logs[i][1] != logs[i][2]
    14. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md b/assets/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md new file mode 100644 index 00000000..48be82fa --- /dev/null +++ b/assets/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md @@ -0,0 +1,114 @@ +# [1102. Path With Maximum Minimum Value](https://leetcode.com/problems/path-with-maximum-minimum-value) + + + +## Description + +

    Given a matrix of integers A with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1].

    + + + +

    The score of a path is the minimum value in that path.  For example, the value of the path 8 →  4 →  5 →  9 is 4.

    + + + +

    A path moves some number of times from one visited cell to any neighbouring unvisited cell in one of the 4 cardinal directions (north, east, west, south).

    + + + +

     

    + + + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: [[5,4,5],[1,2,6],[7,4,6]]
    +
    +Output: 4
    +
    +Explanation: 
    +
    +The path with the maximum score is highlighted in yellow. 
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: [[2,2,1,2,2,2],[1,2,2,2,1,2]]
    +
    +Output: 2
    + + + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]
    +
    +Output: 3
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= R, C <= 100
    2. +
    3. 0 <= A[i][j] <= 10^9
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex1.jpeg b/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex1.jpeg new file mode 100644 index 00000000..01815a67 Binary files /dev/null and b/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex1.jpeg differ diff --git a/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex2.jpeg b/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex2.jpeg new file mode 100644 index 00000000..c849851f Binary files /dev/null and b/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex2.jpeg differ diff --git a/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex3.jpeg b/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex3.jpeg new file mode 100644 index 00000000..fd4a0b22 Binary files /dev/null and b/assets/1100-1199/1102.Path With Maximum Minimum Value/images/1313_ex3.jpeg differ diff --git a/assets/1100-1199/1103.Distribute Candies to People/README_EN.md b/assets/1100-1199/1103.Distribute Candies to People/README_EN.md new file mode 100644 index 00000000..867c4607 --- /dev/null +++ b/assets/1100-1199/1103.Distribute Candies to People/README_EN.md @@ -0,0 +1,73 @@ +# [1103. Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people) + + + +## Description + +

    We distribute some number of candies, to a row of n = num_people people in the following way:

    + +

    We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.

    + +

    Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.

    + +

    This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift).

    + +

    Return an array (of length num_people and sum candies) that represents the final distribution of candies.

    + +

     

    +

    Example 1:

    + +
    +Input: candies = 7, num_people = 4
    +Output: [1,2,3,1]
    +Explanation:
    +On the first turn, ans[0] += 1, and the array is [1,0,0,0].
    +On the second turn, ans[1] += 2, and the array is [1,2,0,0].
    +On the third turn, ans[2] += 3, and the array is [1,2,3,0].
    +On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].
    +
    + +

    Example 2:

    + +
    +Input: candies = 10, num_people = 3
    +Output: [5,2,3]
    +Explanation: 
    +On the first turn, ans[0] += 1, and the array is [1,0,0].
    +On the second turn, ans[1] += 2, and the array is [1,2,0].
    +On the third turn, ans[2] += 3, and the array is [1,2,3].
    +On the fourth turn, ans[0] += 4, and the final array is [5,2,3].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= candies <= 10^9
    • +
    • 1 <= num_people <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md b/assets/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md new file mode 100644 index 00000000..a751732e --- /dev/null +++ b/assets/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md @@ -0,0 +1,60 @@ +# [1104. Path In Zigzag Labelled Binary Tree](https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree) + + + +## Description + +

    In an infinite binary tree where every node has two children, the nodes are labelled in row order.

    + +

    In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.

    + +

    + +

    Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.

    + +

     

    +

    Example 1:

    + +
    +Input: label = 14
    +Output: [1,3,4,14]
    +
    + +

    Example 2:

    + +
    +Input: label = 26
    +Output: [1,2,6,10,26]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= label <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1104.Path In Zigzag Labelled Binary Tree/images/tree.png b/assets/1100-1199/1104.Path In Zigzag Labelled Binary Tree/images/tree.png new file mode 100644 index 00000000..a494868c Binary files /dev/null and b/assets/1100-1199/1104.Path In Zigzag Labelled Binary Tree/images/tree.png differ diff --git a/assets/1100-1199/1105.Filling Bookcase Shelves/README_EN.md b/assets/1100-1199/1105.Filling Bookcase Shelves/README_EN.md new file mode 100644 index 00000000..8c0343c5 --- /dev/null +++ b/assets/1100-1199/1105.Filling Bookcase Shelves/README_EN.md @@ -0,0 +1,60 @@ +# [1105. Filling Bookcase Shelves](https://leetcode.com/problems/filling-bookcase-shelves) + + + +## Description + +

    We have a sequence of books: the i-th book has thickness books[i][0] and height books[i][1].

    + +

    We want to place these books in order onto bookcase shelves that have total width shelf_width.

    + +

    We choose some of the books to place on this shelf (such that the sum of their thickness is <= shelf_width), then build another level of shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down.  We repeat this process until there are no more books to place.

    + +

    Note again that at each step of the above process, the order of the books we place is the same order as the given sequence of books.  For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.

    + +

    Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.

    + +

     

    +

    Example 1:

    + +
    +Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4
    +Output: 6
    +Explanation:
    +The sum of the heights of the 3 shelves are 1 + 3 + 2 = 6.
    +Notice that book number 2 does not have to be on the first shelf.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= books.length <= 1000
    • +
    • 1 <= books[i][0] <= shelf_width <= 1000
    • +
    • 1 <= books[i][1] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1105.Filling Bookcase Shelves/images/shelves.png b/assets/1100-1199/1105.Filling Bookcase Shelves/images/shelves.png new file mode 100644 index 00000000..cfb50f5e Binary files /dev/null and b/assets/1100-1199/1105.Filling Bookcase Shelves/images/shelves.png differ diff --git a/assets/1100-1199/1106.Parsing A Boolean Expression/README_EN.md b/assets/1100-1199/1106.Parsing A Boolean Expression/README_EN.md new file mode 100644 index 00000000..f86bb364 --- /dev/null +++ b/assets/1100-1199/1106.Parsing A Boolean Expression/README_EN.md @@ -0,0 +1,80 @@ +# [1106. Parsing A Boolean Expression](https://leetcode.com/problems/parsing-a-boolean-expression) + + + +## Description + +

    Return the result of evaluating a given boolean expression, represented as a string.

    + +

    An expression can either be:

    + +
      +
    • "t", evaluating to True;
    • +
    • "f", evaluating to False;
    • +
    • "!(expr)", evaluating to the logical NOT of the inner expression expr;
    • +
    • "&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;
    • +
    • "|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: expression = "!(f)"
    +Output: true
    +
    + +

    Example 2:

    + +
    +Input: expression = "|(f,t)"
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: expression = "&(t,f)"
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: expression = "|(&(t,f,t),!(t))"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= expression.length <= 20000
    • +
    • expression[i] consists of characters in {'(', ')', '&', '|', '!', 't', 'f', ','}.
    • +
    • expression is a valid expression representing a boolean, as given in the description.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1107.New Users Daily Count/README_EN.md b/assets/1100-1199/1107.New Users Daily Count/README_EN.md new file mode 100644 index 00000000..2f06808c --- /dev/null +++ b/assets/1100-1199/1107.New Users Daily Count/README_EN.md @@ -0,0 +1,71 @@ +# [1107. New Users Daily Count](https://leetcode.com/problems/new-users-daily-count) + + + +## Description + +

    Table: Traffic

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| activity      | enum    |
    +| activity_date | date    |
    ++---------------+---------+
    +There is no primary key for this table, it may have duplicate rows.
    +The activity column is an ENUM type of ('login', 'logout', 'jobs', 'groups', 'homepage').
    +
    + +

     

    + +

    Write an SQL query that reports for every date within at most 90 days from today, the number of users that logged in for the first time on that date. Assume today is 2019-06-30.

    + +

    The query result format is in the following example:

    + +
    +Traffic table:
    ++---------+----------+---------------+
    +| user_id | activity | activity_date |
    ++---------+----------+---------------+
    +| 1       | login    | 2019-05-01    |
    +| 1       | homepage | 2019-05-01    |
    +| 1       | logout   | 2019-05-01    |
    +| 2       | login    | 2019-06-21    |
    +| 2       | logout   | 2019-06-21    |
    +| 3       | login    | 2019-01-01    |
    +| 3       | jobs     | 2019-01-01    |
    +| 3       | logout   | 2019-01-01    |
    +| 4       | login    | 2019-06-21    |
    +| 4       | groups   | 2019-06-21    |
    +| 4       | logout   | 2019-06-21    |
    +| 5       | login    | 2019-03-01    |
    +| 5       | logout   | 2019-03-01    |
    +| 5       | login    | 2019-06-21    |
    +| 5       | logout   | 2019-06-21    |
    ++---------+----------+---------------+
    +
    +Result table:
    ++------------+-------------+
    +| login_date | user_count  |
    ++------------+-------------+
    +| 2019-05-01 | 1           |
    +| 2019-06-21 | 2           |
    ++------------+-------------+
    +Note that we only care about dates with non zero user count.
    +The user with id 5 first logged in on 2019-03-01 so he's not counted on 2019-06-21.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1108.Defanging an IP Address/README_EN.md b/assets/1100-1199/1108.Defanging an IP Address/README_EN.md new file mode 100644 index 00000000..0e243de1 --- /dev/null +++ b/assets/1100-1199/1108.Defanging an IP Address/README_EN.md @@ -0,0 +1,63 @@ +# [1108. Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address) + + + +## Description + +

    Given a valid (IPv4) IP address, return a defanged version of that IP address.

    + + + +

    A defanged IP address replaces every period "." with "[.]".

    + + + +

     

    + +

    Example 1:

    + +
    Input: address = "1.1.1.1"
    +
    +Output: "1[.]1[.]1[.]1"
    +
    +

    Example 2:

    + +
    Input: address = "255.100.50.0"
    +
    +Output: "255[.]100[.]50[.]0"
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • The given address is a valid IPv4 address.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1109.Corporate Flight Bookings/README_EN.md b/assets/1100-1199/1109.Corporate Flight Bookings/README_EN.md new file mode 100644 index 00000000..37e95b40 --- /dev/null +++ b/assets/1100-1199/1109.Corporate Flight Bookings/README_EN.md @@ -0,0 +1,172 @@ +# [1109. Corporate Flight Bookings](https://leetcode.com/problems/corporate-flight-bookings) + + + +## Description + +

    There are n flights that are labeled from 1 to n.

    + +

    You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.

    + +

    Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.

    + +

     

    +

    Example 1:

    + +
    +Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
    +Output: [10,55,45,25,25]
    +Explanation:
    +Flight labels:        1   2   3   4   5
    +Booking 1 reserved:  10  10
    +Booking 2 reserved:      20  20
    +Booking 3 reserved:      25  25  25  25
    +Total seats:         10  55  45  25  25
    +Hence, answer = [10,55,45,25,25]
    +
    + +

    Example 2:

    + +
    +Input: bookings = [[1,2,10],[2,2,15]], n = 2
    +Output: [10,25]
    +Explanation:
    +Flight labels:        1   2
    +Booking 1 reserved:  10  10
    +Booking 2 reserved:      15
    +Total seats:         10  25
    +Hence, answer = [10,25]
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 2 * 104
    • +
    • 1 <= bookings.length <= 2 * 104
    • +
    • bookings[i].length == 3
    • +
    • 1 <= firsti <= lasti <= n
    • +
    • 1 <= seatsi <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + delta = [0] * n + for first, last, seats in bookings: + delta[first - 1] += seats + if last < n: + delta[last] -= seats + for i in range(n - 1): + delta[i + 1] += delta[i] + return delta +``` + +### **Java** + +```java +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] delta = new int[n]; + for (int[] booking : bookings) { + int first = booking[0], last = booking[1], seats = booking[2]; + delta[first - 1] += seats; + if (last < n) { + delta[last] -= seats; + } + } + for (int i = 0; i < n - 1; ++i) { + delta[i + 1] += delta[i]; + } + return delta; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} bookings + * @param {number} n + * @return {number[]} + */ +var corpFlightBookings = function(bookings, n) { + let delta = new Array(n).fill(0); + for (let book of bookings) { + let [start, end, num] = book; + start -= 1; + delta[start] += num; + if (end != n) { + delta[end] -= num; + } + } + for (let i = 1; i < n; i++) { + delta[i] += delta[i - 1]; + } + return delta; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + vector delta(n); + for (auto &booking : bookings) { + int first = booking[0], last = booking[1], seats = booking[2]; + delta[first - 1] += seats; + if (last < n) { + delta[last] -= seats; + } + } + for (int i = 0; i < n - 1; ++i) { + delta[i + 1] += delta[i]; + } + return delta; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} bookings + * @param {number} n + * @return {number[]} + */ +var corpFlightBookings = function(bookings, n) { + let delta = new Array(n).fill(0); + for (let book of bookings) { + let [start, end, num] = book; + start -= 1; + delta[start] += num; + if (end != n) { + delta[end] -= num; + } + } + for (let i = 1; i < n; i++) { + delta[i] += delta[i - 1]; + } + return delta; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md b/assets/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md new file mode 100644 index 00000000..92545805 --- /dev/null +++ b/assets/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md @@ -0,0 +1,61 @@ +# [1110. Delete Nodes And Return Forest](https://leetcode.com/problems/delete-nodes-and-return-forest) + + + +## Description + +

    Given the root of a binary tree, each node in the tree has a distinct value.

    + +

    After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

    + +

    Return the roots of the trees in the remaining forest. You may return the result in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
    +Output: [[1,2,null,4],[6],[7]]
    +
    + +

    Example 2:

    + +
    +Input: root = [1,2,4,null,3], to_delete = [3]
    +Output: [[1,2,4]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the given tree is at most 1000.
    • +
    • Each node has a distinct value between 1 and 1000.
    • +
    • to_delete.length <= 1000
    • +
    • to_delete contains distinct values between 1 and 1000.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1110.Delete Nodes And Return Forest/images/screen-shot-2019-07-01-at-53836-pm.png b/assets/1100-1199/1110.Delete Nodes And Return Forest/images/screen-shot-2019-07-01-at-53836-pm.png new file mode 100644 index 00000000..a210fe9c Binary files /dev/null and b/assets/1100-1199/1110.Delete Nodes And Return Forest/images/screen-shot-2019-07-01-at-53836-pm.png differ diff --git a/assets/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md b/assets/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md new file mode 100644 index 00000000..8d9088c7 --- /dev/null +++ b/assets/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md @@ -0,0 +1,95 @@ +# [1111. Maximum Nesting Depth of Two Valid Parentheses Strings](https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings) + + + +## Description + +

    A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and:

    + + + +
      +
    • It is the empty string, or
    • +
    • It can be written as AB (A concatenated with B), where A and B are VPS's, or
    • +
    • It can be written as (A), where A is a VPS.
    • +
    + + + +

    We can similarly define the nesting depth depth(S) of any VPS S as follows:

    + + + +
      +
    • depth("") = 0
    • +
    • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's
    • +
    • depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
    • +
    + + + +

    For example,  """()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

    + + + +

     

    + + + +

    Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).

    + + + +

    Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.

    + + + +

    Return an answer array (of length seq.length) that encodes such a choice of A and Banswer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.

    + + +

     

    +

    Example 1:

    + +
    +Input: seq = "(()())"
    +Output: [0,1,1,1,1,0]
    +
    + +

    Example 2:

    + +
    +Input: seq = "()(())()"
    +Output: [0,0,0,1,1,0,1,1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= seq.size <= 10000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/images/1111.png b/assets/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/images/1111.png new file mode 100644 index 00000000..7749aa19 Binary files /dev/null and b/assets/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/images/1111.png differ diff --git a/assets/1100-1199/1112.Highest Grade For Each Student/README_EN.md b/assets/1100-1199/1112.Highest Grade For Each Student/README_EN.md new file mode 100644 index 00000000..83abecea --- /dev/null +++ b/assets/1100-1199/1112.Highest Grade For Each Student/README_EN.md @@ -0,0 +1,60 @@ +# [1112. Highest Grade For Each Student](https://leetcode.com/problems/highest-grade-for-each-student) + + + +## Description + +

    Table: Enrollments

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| course_id     | int     |
    +| grade         | int     |
    ++---------------+---------+
    +(student_id, course_id) is the primary key of this table.
    +
    +
    + +

    Write a SQL query to find the highest grade with its corresponding course for each student. In case of a tie, you should find the course with the smallest course_id. The output must be sorted by increasing student_id.

    + +

    The query result format is in the following example:

    + +
    +Enrollments table:
    ++------------+-------------------+
    +| student_id | course_id | grade |
    ++------------+-----------+-------+
    +| 2          | 2         | 95    |
    +| 2          | 3         | 95    |
    +| 1          | 1         | 90    |
    +| 1          | 2         | 99    |
    +| 3          | 1         | 80    |
    +| 3          | 2         | 75    |
    +| 3          | 3         | 82    |
    ++------------+-----------+-------+
    +
    +Result table:
    ++------------+-------------------+
    +| student_id | course_id | grade |
    ++------------+-----------+-------+
    +| 1          | 2         | 99    |
    +| 2          | 2         | 95    |
    +| 3          | 3         | 82    |
    ++------------+-----------+-------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1113.Reported Posts/README_EN.md b/assets/1100-1199/1113.Reported Posts/README_EN.md new file mode 100644 index 00000000..36fe0852 --- /dev/null +++ b/assets/1100-1199/1113.Reported Posts/README_EN.md @@ -0,0 +1,69 @@ +# [1113. Reported Posts](https://leetcode.com/problems/reported-posts) + + + +## Description + +

    Table: Actions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| post_id       | int     |
    +| action_date   | date    | 
    +| action        | enum    |
    +| extra         | varchar |
    ++---------------+---------+
    +There is no primary key for this table, it may have duplicate rows.
    +The action column is an ENUM type of ('view', 'like', 'reaction', 'comment', 'report', 'share').
    +The extra column has optional information about the action such as a reason for report or a type of reaction. 
    + +

     

    + +

    Write an SQL query that reports the number of posts reported yesterday for each report reason. Assume today is 2019-07-05.

    + +

    The query result format is in the following example:

    + +
    +Actions table:
    ++---------+---------+-------------+--------+--------+
    +| user_id | post_id | action_date | action | extra  |
    ++---------+---------+-------------+--------+--------+
    +| 1       | 1       | 2019-07-01  | view   | null   |
    +| 1       | 1       | 2019-07-01  | like   | null   |
    +| 1       | 1       | 2019-07-01  | share  | null   |
    +| 2       | 4       | 2019-07-04  | view   | null   |
    +| 2       | 4       | 2019-07-04  | report | spam   |
    +| 3       | 4       | 2019-07-04  | view   | null   |
    +| 3       | 4       | 2019-07-04  | report | spam   |
    +| 4       | 3       | 2019-07-02  | view   | null   |
    +| 4       | 3       | 2019-07-02  | report | spam   |
    +| 5       | 2       | 2019-07-04  | view   | null   |
    +| 5       | 2       | 2019-07-04  | report | racism |
    +| 5       | 5       | 2019-07-04  | view   | null   |
    +| 5       | 5       | 2019-07-04  | report | racism |
    ++---------+---------+-------------+--------+--------+
    +
    +Result table:
    ++---------------+--------------+
    +| report_reason | report_count |
    ++---------------+--------------+
    +| spam          | 1            |
    +| racism        | 2            |
    ++---------------+--------------+ 
    +Note that we only care about report reasons with non zero number of reports.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1114.Print in Order/README_EN.md b/assets/1100-1199/1114.Print in Order/README_EN.md new file mode 100644 index 00000000..88489a1c --- /dev/null +++ b/assets/1100-1199/1114.Print in Order/README_EN.md @@ -0,0 +1,63 @@ +# [1114. Print in Order](https://leetcode.com/problems/print-in-order) + + + +## Description + +

    Suppose we have a class:

    + +
    +public class Foo {
    +  public void first() { print("first"); }
    +  public void second() { print("second"); }
    +  public void third() { print("third"); }
    +}
    +
    + +

    The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

    + +

    Note:

    + +

    We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3]
    +Output: "firstsecondthird"
    +Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,3,2]
    +Output: "firstsecondthird"
    +Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1115.Print FooBar Alternately/README_EN.md b/assets/1100-1199/1115.Print FooBar Alternately/README_EN.md new file mode 100644 index 00000000..d3b60d3f --- /dev/null +++ b/assets/1100-1199/1115.Print FooBar Alternately/README_EN.md @@ -0,0 +1,68 @@ +# [1115. Print FooBar Alternately](https://leetcode.com/problems/print-foobar-alternately) + + + +## Description + +

    Suppose you are given the following code:

    + +
    +class FooBar {
    +  public void foo() {
    +    for (int i = 0; i < n; i++) {
    +      print("foo");
    +    }
    +  }
    +
    +  public void bar() {
    +    for (int i = 0; i < n; i++) {
    +      print("bar");
    +    }
    +  }
    +}
    +
    + +

    The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.

    + +

     

    + +

    Example 1:

    + +
    +Input: n = 1
    +Output: "foobar"
    +Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: "foobarfoobar"
    +Explanation: "foobar" is being output 2 times.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1116.Print Zero Even Odd/README_EN.md b/assets/1100-1199/1116.Print Zero Even Odd/README_EN.md new file mode 100644 index 00000000..9c294e6e --- /dev/null +++ b/assets/1100-1199/1116.Print Zero Even Odd/README_EN.md @@ -0,0 +1,68 @@ +# [1116. Print Zero Even Odd](https://leetcode.com/problems/print-zero-even-odd) + + + +## Description + +

    Suppose you are given the following code:

    + +
    +class ZeroEvenOdd {
    +  public ZeroEvenOdd(int n) { ... }      // constructor
    +  public void zero(printNumber) { ... }  // only output 0's
    +  public void even(printNumber) { ... }  // only output even numbers
    +  public void odd(printNumber) { ... }   // only output odd numbers
    +}
    +
    + +

    The same instance of ZeroEvenOdd will be passed to three different threads:

    + +
      +
    1. Thread A will call zero() which should only output 0's.
    2. +
    3. Thread B will call even() which should only ouput even numbers.
    4. +
    5. Thread C will call odd() which should only output odd numbers.
    6. +
    + +

    Each of the threads is given a printNumber method to output an integer. Modify the given program to output the series 010203040506... where the length of the series must be 2n.

    + +

     

    + +

    Example 1:

    + +
    +Input: n = 2
    +Output: "0102"
    +Explanation: There are three threads being fired asynchronously. One of them calls zero(), the other calls even(), and the last one calls odd(). "0102" is the correct output.
    +
    + +

    Example 2:

    + +
    +Input: n = 5
    +Output: "0102030405"
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1117.Building H2O/README_EN.md b/assets/1100-1199/1117.Building H2O/README_EN.md new file mode 100644 index 00000000..b7a1e289 --- /dev/null +++ b/assets/1100-1199/1117.Building H2O/README_EN.md @@ -0,0 +1,76 @@ +# [1117. Building H2O](https://leetcode.com/problems/building-h2o) + + + +## Description + +

    There are two kinds of threads, oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must be able to immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.

    + +

    In other words:

    + +
      +
    • If an oxygen thread arrives at the barrier when no hydrogen threads are present, it has to wait for two hydrogen threads.
    • +
    • If a hydrogen thread arrives at the barrier when no other threads are present, it has to wait for an oxygen thread and another hydrogen thread.
    • +
    + +

    We don’t have to worry about matching the threads up explicitly; that is, the threads do not necessarily know which other threads they are paired up with. The key is just that threads pass the barrier in complete sets; thus, if we examine the sequence of threads that bond and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.

    + +

    Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.

    + +
    +

     

    +
    + +
    +

    Example 1:

    + +
    +Input: "HOH"
    +Output: "HHO"
    +Explanation: "HOH" and "OHH" are also valid answers.
    +
    + +
    +

    Example 2:

    + +
    +Input: "OOHHHH"
    +Output: "HHOHHO"
    +Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.
    +
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • Total length of input string will be 3n, where 1 ≤ n ≤ 20.
    • +
    • Total number of H will be 2n in the input string.
    • +
    • Total number of O will be n in the input string.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1118.Number of Days in a Month/README_EN.md b/assets/1100-1199/1118.Number of Days in a Month/README_EN.md new file mode 100644 index 00000000..43403073 --- /dev/null +++ b/assets/1100-1199/1118.Number of Days in a Month/README_EN.md @@ -0,0 +1,94 @@ +# [1118. Number of Days in a Month](https://leetcode.com/problems/number-of-days-in-a-month) + + + +## Description + +

    Given a year Y and a month M, return how many days there are in that month.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: Y = 1992, M = 7
    +
    +Output: 31
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: Y = 2000, M = 2
    +
    +Output: 29
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: Y = 1900, M = 2
    +
    +Output: 28
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1583 <= Y <= 2100
    2. +
    3. 1 <= M <= 12
    4. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1119.Remove Vowels from a String/README_EN.md b/assets/1100-1199/1119.Remove Vowels from a String/README_EN.md new file mode 100644 index 00000000..df9ce7d5 --- /dev/null +++ b/assets/1100-1199/1119.Remove Vowels from a String/README_EN.md @@ -0,0 +1,71 @@ +# [1119. Remove Vowels from a String](https://leetcode.com/problems/remove-vowels-from-a-string) + + + +## Description + +

    Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "leetcodeisacommunityforcoders"
    +Output: "ltcdscmmntyfrcdrs"
    +
    + +

    Example 2:

    + +
    +Input: s = "aeiou"
    +Output: ""
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s consists of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def removeVowels(self, s: str) -> str: + res = [] + for c in s: + if c not in {'a', 'e', 'i', 'o', 'u'}: + res.append(c) + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String removeVowels(String s) { + StringBuilder res = new StringBuilder(); + for (char c : s.toCharArray()) { + if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')) { + res.append(c); + } + } + return res.toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1120.Maximum Average Subtree/README_EN.md b/assets/1100-1199/1120.Maximum Average Subtree/README_EN.md new file mode 100644 index 00000000..198cd139 --- /dev/null +++ b/assets/1100-1199/1120.Maximum Average Subtree/README_EN.md @@ -0,0 +1,60 @@ +# [1120. Maximum Average Subtree](https://leetcode.com/problems/maximum-average-subtree) + + + +## Description + +

    Given the root of a binary tree, find the maximum average value of any subtree of that tree.

    + +

    (A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes.)

    + +

     

    + +

    Example 1:

    + +

    + +
    +Input: [5,6,1]
    +Output: 6.00000
    +Explanation: 
    +For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
    +For the node with value = 6 we have an average of 6 / 1 = 6.
    +For the node with value = 1 we have an average of 1 / 1 = 1.
    +So the answer is 6 which is the maximum.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. The number of nodes in the tree is between 1 and 5000.
    2. +
    3. Each node will have a value between 0 and 100000.
    4. +
    5. Answers will be accepted as correct if they are within 10^-5 of the correct answer.
    6. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1120.Maximum Average Subtree/images/1308_example_1.png b/assets/1100-1199/1120.Maximum Average Subtree/images/1308_example_1.png new file mode 100644 index 00000000..090ff139 Binary files /dev/null and b/assets/1100-1199/1120.Maximum Average Subtree/images/1308_example_1.png differ diff --git a/assets/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md b/assets/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md new file mode 100644 index 00000000..468e8df8 --- /dev/null +++ b/assets/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md @@ -0,0 +1,89 @@ +# [1121. Divide Array Into Increasing Sequences](https://leetcode.com/problems/divide-array-into-increasing-sequences) + + + +## Description + +

    Given a non-decreasing array of positive integers nums and an integer K, find out if this array can be divided into one or more disjoint increasing subsequences of length at least K.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: nums = [1,2,2,3,3,4,4], K = 3
    +
    +Output: true
    +
    +Explanation: 
    +
    +The array can be divided into the two subsequences [1,2,3,4] and [2,3,4] with lengths at least 3 each.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [5,6,6,7,8], K = 3
    +
    +Output: false
    +
    +Explanation: 
    +
    +There is no way to divide the array using the conditions required.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= nums.length <= 10^5
    2. +
    3. 1 <= K <= nums.length
    4. +
    5. 1 <= nums[i] <= 10^5
    6. +
    + + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1122.Relative Sort Array/README_EN.md b/assets/1100-1199/1122.Relative Sort Array/README_EN.md new file mode 100644 index 00000000..8259f02d --- /dev/null +++ b/assets/1100-1199/1122.Relative Sort Array/README_EN.md @@ -0,0 +1,49 @@ +# [1122. Relative Sort Array](https://leetcode.com/problems/relative-sort-array) + + + +## Description + +

    Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

    + +

    Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2.  Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.

    + +

     

    +

    Example 1:

    +
    Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
    +Output: [2,2,2,1,4,3,3,9,6,7,19]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 1000
    • +
    • 0 <= arr1[i], arr2[i] <= 1000
    • +
    • All the elements of arr2 are distinct.
    • +
    • Each arr2[i] is in arr1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md b/assets/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md new file mode 100644 index 00000000..300a02f5 --- /dev/null +++ b/assets/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md @@ -0,0 +1,77 @@ +# [1123. Lowest Common Ancestor of Deepest Leaves](https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves) + + + +## Description + +

    Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.

    + +

    Recall that:

    + +
      +
    • The node of a binary tree is a leaf if and only if it has no children
    • +
    • The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.
    • +
    • The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.
    • +
    + +

    Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4]
    +Output: [2,7,4]
    +Explanation: We return the node with value 2, colored in yellow in the diagram.
    +The nodes coloured in blue are the deepest leaf-nodes of the tree.
    +Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.
    + +

    Example 2:

    + +
    +Input: root = [1]
    +Output: [1]
    +Explanation: The root is the deepest node in the tree, and it's the lca of itself.
    +
    + +

    Example 3:

    + +
    +Input: root = [0,1,3,null,2]
    +Output: [2]
    +Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree will be in the range [1, 1000].
    • +
    • 0 <= Node.val <= 1000
    • +
    • The values of the nodes in the tree are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/images/sketch1.png b/assets/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/images/sketch1.png new file mode 100644 index 00000000..8bab5352 Binary files /dev/null and b/assets/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/images/sketch1.png differ diff --git a/assets/1100-1199/1124.Longest Well-Performing Interval/README_EN.md b/assets/1100-1199/1124.Longest Well-Performing Interval/README_EN.md new file mode 100644 index 00000000..2ecd96cf --- /dev/null +++ b/assets/1100-1199/1124.Longest Well-Performing Interval/README_EN.md @@ -0,0 +1,55 @@ +# [1124. Longest Well-Performing Interval](https://leetcode.com/problems/longest-well-performing-interval) + + + +## Description + +

    We are given hours, a list of the number of hours worked per day for a given employee.

    + +

    A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.

    + +

    A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

    + +

    Return the length of the longest well-performing interval.

    + +

     

    +

    Example 1:

    + +
    +Input: hours = [9,9,6,0,6,6,9]
    +Output: 3
    +Explanation: The longest well-performing interval is [9,9,6].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= hours.length <= 10000
    • +
    • 0 <= hours[i] <= 16
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1125.Smallest Sufficient Team/README_EN.md b/assets/1100-1199/1125.Smallest Sufficient Team/README_EN.md new file mode 100644 index 00000000..0e40006b --- /dev/null +++ b/assets/1100-1199/1125.Smallest Sufficient Team/README_EN.md @@ -0,0 +1,67 @@ +# [1125. Smallest Sufficient Team](https://leetcode.com/problems/smallest-sufficient-team) + + + +## Description + +

    In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.

    + +

    Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.

    + +
      +
    • For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].
    • +
    + +

    Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.

    + +

    It is guaranteed an answer exists.

    + +

     

    +

    Example 1:

    +
    Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
    +Output: [0,2]
    +

    Example 2:

    +
    Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
    +Output: [1,2]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= req_skills.length <= 16
    • +
    • 1 <= req_skills[i].length <= 16
    • +
    • req_skills[i] consists of lowercase English letters.
    • +
    • All the strings of req_skills are unique.
    • +
    • 1 <= people.length <= 60
    • +
    • 0 <= people[i].length <= 16
    • +
    • 1 <= people[i][j].length <= 16
    • +
    • people[i][j] consists of lowercase English letters.
    • +
    • All the strings of people[i] are unique.
    • +
    • Every skill in people[i] is a skill in req_skills.
    • +
    • It is guaranteed a sufficient team exists.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1126.Active Businesses/README_EN.md b/assets/1100-1199/1126.Active Businesses/README_EN.md new file mode 100644 index 00000000..adf2f785 --- /dev/null +++ b/assets/1100-1199/1126.Active Businesses/README_EN.md @@ -0,0 +1,62 @@ +# [1126. Active Businesses](https://leetcode.com/problems/active-businesses) + + + +## Description + +

    Table: Events

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| business_id   | int     |
    +| event_type    | varchar |
    +| occurences    | int     | 
    ++---------------+---------+
    +(business_id, event_type) is the primary key of this table.
    +Each row in the table logs the info that an event of some type occured at some business for a number of times.
    + +

     

    + +

    Write an SQL query to find all active businesses.

    + +

    An active business is a business that has more than one event type with occurences greater than the average occurences of that event type among all businesses.

    + +

    The query result format is in the following example:

    + +
    +Events table:
    ++-------------+------------+------------+
    +| business_id | event_type | occurences |
    ++-------------+------------+------------+
    +| 1           | reviews    | 7          |
    +| 3           | reviews    | 3          |
    +| 1           | ads        | 11         |
    +| 2           | ads        | 7          |
    +| 3           | ads        | 6          |
    +| 1           | page views | 3          |
    +| 2           | page views | 12         |
    ++-------------+------------+------------+
    +
    +Result table:
    ++-------------+
    +| business_id |
    ++-------------+
    +| 1           |
    ++-------------+ 
    +Average for 'reviews', 'ads' and 'page views' are (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5 respectively.
    +Business with id 1 has 7 'reviews' events (more than 5) and 11 'ads' events (more than 8) so it is an active business.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1127.User Purchase Platform/README_EN.md b/assets/1100-1199/1127.User Purchase Platform/README_EN.md new file mode 100644 index 00000000..aec9d6f3 --- /dev/null +++ b/assets/1100-1199/1127.User Purchase Platform/README_EN.md @@ -0,0 +1,65 @@ +# [1127. User Purchase Platform](https://leetcode.com/problems/user-purchase-platform) + + + +## Description + +

    Table: Spending

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| spend_date  | date    |
    +| platform    | enum    | 
    +| amount      | int     |
    ++-------------+---------+
    +The table logs the spendings history of users that make purchases from an online shopping website which has a desktop and a mobile application.
    +(user_id, spend_date, platform) is the primary key of this table.
    +The platform column is an ENUM type of ('desktop', 'mobile').
    +
    + +

    Write an SQL query to find the total number of users and the total amount spent using mobile only, desktop only and both mobile and desktop together for each date.

    + +

    The query result format is in the following example:

    + +
    +Spending table:
    ++---------+------------+----------+--------+
    +| user_id | spend_date | platform | amount |
    ++---------+------------+----------+--------+
    +| 1       | 2019-07-01 | mobile   | 100    |
    +| 1       | 2019-07-01 | desktop  | 100    |
    +| 2       | 2019-07-01 | mobile   | 100    |
    +| 2       | 2019-07-02 | mobile   | 100    |
    +| 3       | 2019-07-01 | desktop  | 100    |
    +| 3       | 2019-07-02 | desktop  | 100    |
    ++---------+------------+----------+--------+
    +
    +Result table:
    ++------------+----------+--------------+-------------+
    +| spend_date | platform | total_amount | total_users |
    ++------------+----------+--------------+-------------+
    +| 2019-07-01 | desktop  | 100          | 1           |
    +| 2019-07-01 | mobile   | 100          | 1           |
    +| 2019-07-01 | both     | 200          | 1           |
    +| 2019-07-02 | desktop  | 100          | 1           |
    +| 2019-07-02 | mobile   | 100          | 1           |
    +| 2019-07-02 | both     | 0            | 0           |
    ++------------+----------+--------------+-------------+ 
    +On 2019-07-01, user 1 purchased using both desktop and mobile, user 2 purchased using mobile only and user 3 purchased using desktop only.
    +On 2019-07-02, user 2 purchased using mobile only, user 3 purchased using desktop only and no one purchased using both platforms.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md b/assets/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md new file mode 100644 index 00000000..49db5ec1 --- /dev/null +++ b/assets/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md @@ -0,0 +1,58 @@ +# [1128. Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs) + + + +## Description + +

    Given a list of dominoesdominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.

    + + + +

    Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].

    + + + +

     

    + +

    Example 1:

    + +
    Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
    +
    +Output: 1
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= dominoes.length <= 40000
    • +
    • 1 <= dominoes[i][j] <= 9
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md b/assets/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md new file mode 100644 index 00000000..5b54f339 --- /dev/null +++ b/assets/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md @@ -0,0 +1,89 @@ +# [1129. Shortest Path with Alternating Colors](https://leetcode.com/problems/shortest-path-with-alternating-colors) + + + +## Description + +

    Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.

    + + + +

    Each [i, j] in red_edges denotes a red directed edge from node i to node j.  Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.

    + + + +

    Return an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist).

    + + + +

     

    + +

    Example 1:

    + +
    Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
    +
    +Output: [0,1,-1]
    +
    +

    Example 2:

    + +
    Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
    +
    +Output: [0,1,-1]
    +
    +

    Example 3:

    + +
    Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
    +
    +Output: [0,-1,-1]
    +
    +

    Example 4:

    + +
    Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
    +
    +Output: [0,1,2]
    +
    +

    Example 5:

    + +
    Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
    +
    +Output: [0,1,1]
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 100
    • +
    • red_edges.length <= 400
    • +
    • blue_edges.length <= 400
    • +
    • red_edges[i].length == blue_edges[i].length == 2
    • +
    • 0 <= red_edges[i][j], blue_edges[i][j] < n
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md b/assets/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md new file mode 100644 index 00000000..c0206087 --- /dev/null +++ b/assets/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md @@ -0,0 +1,89 @@ +# [1130. Minimum Cost Tree From Leaf Values](https://leetcode.com/problems/minimum-cost-tree-from-leaf-values) + + + +## Description + +

    Given an array arr of positive integers, consider all binary trees such that:

    + + + +
      +
    • Each node has either 0 or 2 children;
    • +
    • The values of arr correspond to the values of each leaf in an in-order traversal of the tree.  (Recall that a node is a leaf if and only if it has 0 children.)
    • +
    • The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.
    • +
    + + + +

    Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node.  It is guaranteed this sum fits into a 32-bit integer.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [6,2,4]
    +
    +Output: 32
    +
    +Explanation:
    +
    +There are two possible trees.  The first has non-leaf node sum 36, and the second has non-leaf node sum 32.
    +
    +
    +
    +    24            24
    +
    +   /  \          /  \
    +
    +  12   4        6    8
    +
    + /  \               / \
    +
    +6    2             2   4
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= arr.length <= 40
    • +
    • 1 <= arr[i] <= 15
    • +
    • It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than 2^31).
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md b/assets/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md new file mode 100644 index 00000000..ac9a7a26 --- /dev/null +++ b/assets/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md @@ -0,0 +1,64 @@ +# [1131. Maximum of Absolute Value Expression](https://leetcode.com/problems/maximum-of-absolute-value-expression) + + + +## Description + +

    Given two arrays of integers with equal lengths, return the maximum value of:

    + + + +

    |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|

    + + + +

    where the maximum is taken over all 0 <= i, j < arr1.length.

    + + +

     

    +

    Example 1:

    + +
    +Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
    +Output: 13
    +
    + +

    Example 2:

    + +
    +Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
    +Output: 20
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr1.length == arr2.length <= 40000
    • +
    • -10^6 <= arr1[i], arr2[i] <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1132.Reported Posts II/README_EN.md b/assets/1100-1199/1132.Reported Posts II/README_EN.md new file mode 100644 index 00000000..7b9c36ea --- /dev/null +++ b/assets/1100-1199/1132.Reported Posts II/README_EN.md @@ -0,0 +1,92 @@ +# [1132. Reported Posts II](https://leetcode.com/problems/reported-posts-ii) + + + +## Description + +

    Table: Actions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| post_id       | int     |
    +| action_date   | date    |
    +| action        | enum    |
    +| extra         | varchar |
    ++---------------+---------+
    +There is no primary key for this table, it may have duplicate rows.
    +The action column is an ENUM type of ('view', 'like', 'reaction', 'comment', 'report', 'share').
    +The extra column has optional information about the action such as a reason for report or a type of reaction. 
    + +

    Table: Removals

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| post_id       | int     |
    +| remove_date   | date    | 
    ++---------------+---------+
    +post_id is the primary key of this table.
    +Each row in this table indicates that some post was removed as a result of being reported or as a result of an admin review.
    +
    + +

     

    + +

    Write an SQL query to find the average for daily percentage of posts that got removed after being reported as spam, rounded to 2 decimal places.

    + +

    The query result format is in the following example:

    + +
    +Actions table:
    ++---------+---------+-------------+--------+--------+
    +| user_id | post_id | action_date | action | extra  |
    ++---------+---------+-------------+--------+--------+
    +| 1       | 1       | 2019-07-01  | view   | null   |
    +| 1       | 1       | 2019-07-01  | like   | null   |
    +| 1       | 1       | 2019-07-01  | share  | null   |
    +| 2       | 2       | 2019-07-04  | view   | null   |
    +| 2       | 2       | 2019-07-04  | report | spam   |
    +| 3       | 4       | 2019-07-04  | view   | null   |
    +| 3       | 4       | 2019-07-04  | report | spam   |
    +| 4       | 3       | 2019-07-02  | view   | null   |
    +| 4       | 3       | 2019-07-02  | report | spam   |
    +| 5       | 2       | 2019-07-03  | view   | null   |
    +| 5       | 2       | 2019-07-03  | report | racism |
    +| 5       | 5       | 2019-07-03  | view   | null   |
    +| 5       | 5       | 2019-07-03  | report | racism |
    ++---------+---------+-------------+--------+--------+
    +
    +Removals table:
    ++---------+-------------+
    +| post_id | remove_date |
    ++---------+-------------+
    +| 2       | 2019-07-20  |
    +| 3       | 2019-07-18  |
    ++---------+-------------+
    +
    +Result table:
    ++-----------------------+
    +| average_daily_percent |
    ++-----------------------+
    +| 75.00                 |
    ++-----------------------+
    +The percentage for 2019-07-04 is 50% because only one post of two spam reported posts was removed.
    +The percentage for 2019-07-02 is 100% because one post was reported as spam and it was removed.
    +The other days had no spam reports so the average is (50 + 100) / 2 = 75%
    +Note that the output is only one number and that we do not care about the remove dates.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1133.Largest Unique Number/README_EN.md b/assets/1100-1199/1133.Largest Unique Number/README_EN.md new file mode 100644 index 00000000..4cce939e --- /dev/null +++ b/assets/1100-1199/1133.Largest Unique Number/README_EN.md @@ -0,0 +1,112 @@ +# [1133. Largest Unique Number](https://leetcode.com/problems/largest-unique-number) + + + +## Description + +

    Given an array of integers A, return the largest integer that only occurs once.

    + +

    If no integer occurs once, return -1.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: [5,7,3,9,4,9,8,3,1]
    +
    +Output: 8
    +
    +Explanation: 
    +
    +The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer.
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: [9,9,8,8]
    +
    +Output: -1
    +
    +Explanation: 
    +
    +There is no number that occurs only once.
    +
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 1 <= A.length <= 2000
    2. +
    3. 0 <= A[i] <= 1000
    4. +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def largestUniqueNumber(self, A: List[int]) -> int: + counter = collections.Counter(A) + for i in range(1000, -1, -1): + if counter[i] == 1: + return i + return -1 +``` + +### **Java** + +```java +class Solution { + public int largestUniqueNumber(int[] A) { + int[] counter = new int[1001]; + for (int a : A) { + ++counter[a]; + } + for (int i = 1000; i >= 0; --i) { + if (counter[i] == 1) { + return i; + } + } + return -1; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} A + * @return {number} + */ +var largestUniqueNumber = function (A) { + let counter = {}; + for (const a of A) { + counter[a] = (counter[a] || 0) + 1; + } + for (let i = 1000; i >= 0; --i) { + if (counter[i] == 1) { + return i; + } + } + return -1; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1134.Armstrong Number/README_EN.md b/assets/1100-1199/1134.Armstrong Number/README_EN.md new file mode 100644 index 00000000..d1605fc8 --- /dev/null +++ b/assets/1100-1199/1134.Armstrong Number/README_EN.md @@ -0,0 +1,93 @@ +# [1134. Armstrong Number](https://leetcode.com/problems/armstrong-number) + + + +## Description + +

    Given an integer n, return true if and only if it is an Armstrong number.

    + +

    The k-digit number n is an Armstrong number if and only if the kth power of each digit sums to n.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 153
    +Output: true
    +Explanation: 153 is a 3-digit number, and 153 = 13 + 53 + 33.
    +
    + +

    Example 2:

    + +
    +Input: n = 123
    +Output: false
    +Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 108
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isArmstrong(self, n: int) -> bool: + k = len(str(n)) + s, t = 0, n + while t: + t, v = divmod(t, 10) + s += pow(v, k) + return n == s +``` + +### **Java** + +```java +class Solution { + public boolean isArmstrong(int n) { + int k = String.valueOf(n).length(); + int s = 0, t = n; + while (t != 0) { + s += Math.pow(t % 10, k); + t /= 10; + } + return n == s; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isArmstrong = function (n) { + const k = String(n).length; + let s = 0; + let t = n; + while (t) { + s += Math.pow(t % 10, k); + t = Math.floor(t / 10); + } + return n == s; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md b/assets/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md new file mode 100644 index 00000000..e5275357 --- /dev/null +++ b/assets/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md @@ -0,0 +1,72 @@ +# [1135. Connecting Cities With Minimum Cost](https://leetcode.com/problems/connecting-cities-with-minimum-cost) + + + +## Description + +

    There are N cities numbered from 1 to N.

    + +

    You are given connections, where each connections[i] = [city1, city2, cost] represents the cost to connect city1 and city2 together.  (A connection is bidirectional: connecting city1 and city2 is the same as connecting city2 and city1.)

    + +

    Return the minimum cost so that for every pair of cities, there exists a path of connections (possibly of length 1) that connects those two cities together.  The cost is the sum of the connection costs used. If the task is impossible, return -1.

    + +

     

    + +

    Example 1:

    + +

    + +
    +Input: N = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
    +Output: 6
    +Explanation: 
    +Choosing any 2 edges will connect all cities so we choose the minimum 2.
    +
    + +

    Example 2:

    + +

    + +
    +Input: N = 4, connections = [[1,2,3],[3,4,4]]
    +Output: -1
    +Explanation: 
    +There is no way to connect all cities even if all edges are used.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 1 <= N <= 10000
    2. +
    3. 1 <= connections.length <= 10000
    4. +
    5. 1 <= connections[i][0], connections[i][1] <= N
    6. +
    7. 0 <= connections[i][2] <= 10^5
    8. +
    9. connections[i][0] != connections[i][1]
    10. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1135.Connecting Cities With Minimum Cost/images/1314_ex1.png b/assets/1100-1199/1135.Connecting Cities With Minimum Cost/images/1314_ex1.png new file mode 100644 index 00000000..f38b70b8 Binary files /dev/null and b/assets/1100-1199/1135.Connecting Cities With Minimum Cost/images/1314_ex1.png differ diff --git a/assets/1100-1199/1135.Connecting Cities With Minimum Cost/images/1314_ex2.png b/assets/1100-1199/1135.Connecting Cities With Minimum Cost/images/1314_ex2.png new file mode 100644 index 00000000..3e42fe8a Binary files /dev/null and b/assets/1100-1199/1135.Connecting Cities With Minimum Cost/images/1314_ex2.png differ diff --git a/assets/1100-1199/1136.Parallel Courses/README_EN.md b/assets/1100-1199/1136.Parallel Courses/README_EN.md new file mode 100644 index 00000000..7987239c --- /dev/null +++ b/assets/1100-1199/1136.Parallel Courses/README_EN.md @@ -0,0 +1,89 @@ +# [1136. Parallel Courses](https://leetcode.com/problems/parallel-courses) + + + +## Description + +

    You are given an integer n which indicates that we have n courses, labeled from 1 to n. You are also given an array relations where relations[i] = [a, b], representing a prerequisite relationship between course a and course b: course a has to be studied before course b.

    + + + +

    In one semester, you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.

    + + + +

    Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 3, relations = [[1,3],[2,3]]
    +
    +Output: 2
    +
    +Explanation: In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 3, relations = [[1,2],[2,3],[3,1]]
    +
    +Output: -1
    +
    +Explanation: No course can be studied because they depend on each other.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 5000
    • +
    • 1 <= relations.length <= 5000
    • +
    • 1 <= a, b <= n
    • +
    • a != b
    • +
    • All the pairs [a, b] are unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1136.Parallel Courses/images/1316_ex1.png b/assets/1100-1199/1136.Parallel Courses/images/1316_ex1.png new file mode 100644 index 00000000..58f57955 Binary files /dev/null and b/assets/1100-1199/1136.Parallel Courses/images/1316_ex1.png differ diff --git a/assets/1100-1199/1136.Parallel Courses/images/1316_ex2.png b/assets/1100-1199/1136.Parallel Courses/images/1316_ex2.png new file mode 100644 index 00000000..e11ed424 Binary files /dev/null and b/assets/1100-1199/1136.Parallel Courses/images/1316_ex2.png differ diff --git a/assets/1100-1199/1137.N-th Tribonacci Number/README_EN.md b/assets/1100-1199/1137.N-th Tribonacci Number/README_EN.md new file mode 100644 index 00000000..cca7e8c7 --- /dev/null +++ b/assets/1100-1199/1137.N-th Tribonacci Number/README_EN.md @@ -0,0 +1,155 @@ +# [1137. N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number) + + + +## Description + +

    The Tribonacci sequence Tn is defined as follows: 

    + + + +

    T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

    + + + +

    Given n, return the value of Tn.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 4
    +
    +Output: 4
    +
    +Explanation:
    +
    +T_3 = 0 + 1 + 1 = 2
    +
    +T_4 = 1 + 1 + 2 = 4
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 25
    +
    +Output: 1389537
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= n <= 37
    • +
    • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + for _ in range(n): + a, b, c = b, c, a + b + c + return a +``` + +### **Java** + +```java +class Solution { + public int tribonacci(int n) { + int a = 0, b = 1, c = 1; + while (n-- > 0) { + int d = a + b + c; + a = b; + b = c; + c = d; + } + return a; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int tribonacci(int n) { + long long a = 0, b = 1, c = 1; + while (n--) { + long long d = a + b + c; + a = b; + b = c; + c = d; + } + return (int) a; + } +}; +``` + +### **Go** + +```go +func tribonacci(n int) int { + a, b, c := 0, 1, 1 + for i := 0; i < n; i++ { + a, b, c = b, c, a+b+c + } + return a +} +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {number} + */ +var tribonacci = function(n) { + let a = 0; + let b = 1; + let c = 1; + while (n--) { + let d = a + b + c; + a = b; + b = c; + c = d; + } + return a; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1138.Alphabet Board Path/README_EN.md b/assets/1100-1199/1138.Alphabet Board Path/README_EN.md new file mode 100644 index 00000000..8b5da8b0 --- /dev/null +++ b/assets/1100-1199/1138.Alphabet Board Path/README_EN.md @@ -0,0 +1,90 @@ +# [1138. Alphabet Board Path](https://leetcode.com/problems/alphabet-board-path) + + + +## Description + +

    On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].

    + + + +

    Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

    + + + +

    + + + +

    We may make the following moves:

    + + + +
      +
    • 'U' moves our position up one row, if the position exists on the board;
    • +
    • 'D' moves our position down one row, if the position exists on the board;
    • +
    • 'L' moves our position left one column, if the position exists on the board;
    • +
    • 'R' moves our position right one column, if the position exists on the board;
    • +
    • '!' adds the character board[r][c] at our current position (r, c) to the answer.
    • +
    + + + +

    (Here, the only positions that exist on the board are positions with letters on them.)

    + + + +

    Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.

    + + + +

     

    + +

    Example 1:

    + +
    Input: target = "leet"
    +
    +Output: "DDR!UURRR!!DDD!"
    +
    +

    Example 2:

    + +
    Input: target = "code"
    +
    +Output: "RR!DDRR!UUL!R!"
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= target.length <= 100
    • +
    • target consists only of English lowercase letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1138.Alphabet Board Path/images/azboard.png b/assets/1100-1199/1138.Alphabet Board Path/images/azboard.png new file mode 100644 index 00000000..c2a8b460 Binary files /dev/null and b/assets/1100-1199/1138.Alphabet Board Path/images/azboard.png differ diff --git a/assets/1100-1199/1139.Largest 1-Bordered Square/README_EN.md b/assets/1100-1199/1139.Largest 1-Bordered Square/README_EN.md new file mode 100644 index 00000000..66da38dd --- /dev/null +++ b/assets/1100-1199/1139.Largest 1-Bordered Square/README_EN.md @@ -0,0 +1,75 @@ +# [1139. Largest 1-Bordered Square](https://leetcode.com/problems/largest-1-bordered-square) + + + +## Description + +

    Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
    +
    +Output: 9
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: grid = [[1,1,0,0]]
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= grid.length <= 100
    • +
    • 1 <= grid[0].length <= 100
    • +
    • grid[i][j] is 0 or 1
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1140.Stone Game II/README_EN.md b/assets/1100-1199/1140.Stone Game II/README_EN.md new file mode 100644 index 00000000..0026808a --- /dev/null +++ b/assets/1100-1199/1140.Stone Game II/README_EN.md @@ -0,0 +1,64 @@ +# [1140. Stone Game II](https://leetcode.com/problems/stone-game-ii) + + + +## Description + +

    Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones. 

    + +

    Alice and Bob take turns, with Alice starting first.  Initially, M = 1.

    + +

    On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X).

    + +

    The game continues until all the stones have been taken.

    + +

    Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.

    + +

     

    +

    Example 1:

    + +
    +Input: piles = [2,7,9,4,4]
    +Output: 10
    +Explanation:  If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. 
    +
    + +

    Example 2:

    + +
    +Input: piles = [1,2,3,4,5,100]
    +Output: 104
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= piles.length <= 100
    • +
    • 1 <= piles[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md b/assets/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md new file mode 100644 index 00000000..1c6be498 --- /dev/null +++ b/assets/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md @@ -0,0 +1,117 @@ +# [1141. User Activity for the Past 30 Days I](https://leetcode.com/problems/user-activity-for-the-past-30-days-i) + + + +## Description + +

    Table: Activity

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| user_id       | int     |
    +
    +| session_id    | int     |
    +
    +| activity_date | date    |
    +
    +| activity_type | enum    |
    +
    ++---------------+---------+
    +
    +There is no primary key for this table, it may have duplicate rows.
    +
    +The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message').
    +
    +The table shows the user activities for a social media website. 
    +
    +Note that each session belongs to exactly one user.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on some day if he/she made at least one activity on that day.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Activity table:
    +
    ++---------+------------+---------------+---------------+
    +
    +| user_id | session_id | activity_date | activity_type |
    +
    ++---------+------------+---------------+---------------+
    +
    +| 1       | 1          | 2019-07-20    | open_session  |
    +
    +| 1       | 1          | 2019-07-20    | scroll_down   |
    +
    +| 1       | 1          | 2019-07-20    | end_session   |
    +
    +| 2       | 4          | 2019-07-20    | open_session  |
    +
    +| 2       | 4          | 2019-07-21    | send_message  |
    +
    +| 2       | 4          | 2019-07-21    | end_session   |
    +
    +| 3       | 2          | 2019-07-21    | open_session  |
    +
    +| 3       | 2          | 2019-07-21    | send_message  |
    +
    +| 3       | 2          | 2019-07-21    | end_session   |
    +
    +| 4       | 3          | 2019-06-25    | open_session  |
    +
    +| 4       | 3          | 2019-06-25    | end_session   |
    +
    ++---------+------------+---------------+---------------+
    +
    +
    +
    +Result table:
    +
    ++------------+--------------+ 
    +
    +| day        | active_users |
    +
    ++------------+--------------+ 
    +
    +| 2019-07-20 | 2            |
    +
    +| 2019-07-21 | 2            |
    +
    ++------------+--------------+ 
    +
    +Note that we do not care about days with zero active users.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md b/assets/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md new file mode 100644 index 00000000..e2aee257 --- /dev/null +++ b/assets/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md @@ -0,0 +1,117 @@ +# [1142. User Activity for the Past 30 Days II](https://leetcode.com/problems/user-activity-for-the-past-30-days-ii) + + + +## Description + +

    Table: Activity

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| user_id       | int     |
    +
    +| session_id    | int     |
    +
    +| activity_date | date    |
    +
    +| activity_type | enum    |
    +
    ++---------------+---------+
    +
    +There is no primary key for this table, it may have duplicate rows.
    +
    +The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message').
    +
    +The table shows the user activities for a social media website.
    +
    +Note that each session belongs to exactly one user.
    + + + +

     

    + + + +

    Write an SQL query to find the average number of sessions per user for a period of 30 days ending 2019-07-27 inclusively, rounded to 2 decimal places. The sessions we want to count for a user are those with at least one activity in that time period.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Activity table:
    +
    ++---------+------------+---------------+---------------+
    +
    +| user_id | session_id | activity_date | activity_type |
    +
    ++---------+------------+---------------+---------------+
    +
    +| 1       | 1          | 2019-07-20    | open_session  |
    +
    +| 1       | 1          | 2019-07-20    | scroll_down   |
    +
    +| 1       | 1          | 2019-07-20    | end_session   |
    +
    +| 2       | 4          | 2019-07-20    | open_session  |
    +
    +| 2       | 4          | 2019-07-21    | send_message  |
    +
    +| 2       | 4          | 2019-07-21    | end_session   |
    +
    +| 3       | 2          | 2019-07-21    | open_session  |
    +
    +| 3       | 2          | 2019-07-21    | send_message  |
    +
    +| 3       | 2          | 2019-07-21    | end_session   |
    +
    +| 3       | 5          | 2019-07-21    | open_session  |
    +
    +| 3       | 5          | 2019-07-21    | scroll_down   |
    +
    +| 3       | 5          | 2019-07-21    | end_session   |
    +
    +| 4       | 3          | 2019-06-25    | open_session  |
    +
    +| 4       | 3          | 2019-06-25    | end_session   |
    +
    ++---------+------------+---------------+---------------+
    +
    +
    +
    +Result table:
    +
    ++---------------------------+ 
    +
    +| average_sessions_per_user |
    +
    ++---------------------------+ 
    +
    +| 1.33                      |
    +
    ++---------------------------+ 
    +
    +User 1 and 2 each had 1 session in the past 30 days while user 3 had 2 sessions so the average is (1 + 1 + 2) / 3 = 1.33.
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1143.Longest Common Subsequence/README_EN.md b/assets/1100-1199/1143.Longest Common Subsequence/README_EN.md new file mode 100644 index 00000000..b2ef85ef --- /dev/null +++ b/assets/1100-1199/1143.Longest Common Subsequence/README_EN.md @@ -0,0 +1,92 @@ +# [1143. Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence) + + + +## Description + +

    Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

    + +

    A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

    + +
      +
    • For example, "ace" is a subsequence of "abcde".
    • +
    + +

    A common subsequence of two strings is a subsequence that is common to both strings.

    + +

     

    +

    Example 1:

    + +
    +Input: text1 = "abcde", text2 = "ace" 
    +Output: 3  
    +Explanation: The longest common subsequence is "ace" and its length is 3.
    +
    + +

    Example 2:

    + +
    +Input: text1 = "abc", text2 = "abc"
    +Output: 3
    +Explanation: The longest common subsequence is "abc" and its length is 3.
    +
    + +

    Example 3:

    + +
    +Input: text1 = "abc", text2 = "def"
    +Output: 0
    +Explanation: There is no such common subsequence, so the result is 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text1.length, text2.length <= 1000
    • +
    • text1 and text2 consist of only lowercase English characters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + m, n = len(text1), len(text2) + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = dp[i - 1][j - 1] + 1 if text1[i - 1] == text2[j - 1] else max(dp[i - 1][j], dp[i][j - 1]) + return dp[m][n] +``` + +### **Java** + +```java +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int m = text1.length(), n = text2.length(); + int[][] dp = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + char c1 = text1.charAt(i - 1), c2 = text2.charAt(j - 1); + dp[i][j] = c1 == c2 ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp[m][n]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1143.Longest Common Subsequence/images/gif.gif b/assets/1100-1199/1143.Longest Common Subsequence/images/gif.gif new file mode 100644 index 00000000..3645eed6 Binary files /dev/null and b/assets/1100-1199/1143.Longest Common Subsequence/images/gif.gif differ diff --git a/assets/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md b/assets/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md new file mode 100644 index 00000000..581a3e73 --- /dev/null +++ b/assets/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md @@ -0,0 +1,65 @@ +# [1144. Decrease Elements To Make Array Zigzag](https://leetcode.com/problems/decrease-elements-to-make-array-zigzag) + + + +## Description + +

    Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.

    + +

    An array A is a zigzag array if either:

    + +
      +
    • Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...
    • +
    • OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...
    • +
    + +

    Return the minimum number of moves to transform the given array nums into a zigzag array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3]
    +Output: 2
    +Explanation: We can decrease 2 to 0 or 3 to 1.
    +
    + +

    Example 2:

    + +
    +Input: nums = [9,6,1,6,2]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1145.Binary Tree Coloring Game/README_EN.md b/assets/1100-1199/1145.Binary Tree Coloring Game/README_EN.md new file mode 100644 index 00000000..ec8a264c --- /dev/null +++ b/assets/1100-1199/1145.Binary Tree Coloring Game/README_EN.md @@ -0,0 +1,58 @@ +# [1145. Binary Tree Coloring Game](https://leetcode.com/problems/binary-tree-coloring-game) + + + +## Description + +

    Two players play a turn based game on a binary tree.  We are given the root of this binary tree, and the number of nodes n in the tree.  n is odd, and each node has a distinct value from 1 to n.

    + +

    Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x.  The first player colors the node with value x red, and the second player colors the node with value y blue.

    + +

    Then, the players take turns starting with the first player.  In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)

    + +

    If (and only if) a player cannot choose such a node in this way, they must pass their turn.  If both players pass their turn, the game ends, and the winner is the player that colored more nodes.

    + +

    You are the second player.  If it is possible to choose such a y to ensure you win the game, return true.  If it is not possible, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
    +Output: true
    +Explanation: The second player can choose the node with value 2.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • root is the root of a binary tree with n nodes and distinct node values from 1 to n.
    • +
    • n is odd.
    • +
    • 1 <= x <= n <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1145.Binary Tree Coloring Game/images/1480-binary-tree-coloring-game.png b/assets/1100-1199/1145.Binary Tree Coloring Game/images/1480-binary-tree-coloring-game.png new file mode 100644 index 00000000..2bdd6733 Binary files /dev/null and b/assets/1100-1199/1145.Binary Tree Coloring Game/images/1480-binary-tree-coloring-game.png differ diff --git a/assets/1100-1199/1146.Snapshot Array/README_EN.md b/assets/1100-1199/1146.Snapshot Array/README_EN.md new file mode 100644 index 00000000..8523f930 --- /dev/null +++ b/assets/1100-1199/1146.Snapshot Array/README_EN.md @@ -0,0 +1,64 @@ +# [1146. Snapshot Array](https://leetcode.com/problems/snapshot-array) + + + +## Description + +

    Implement a SnapshotArray that supports the following interface:

    + +
      +
    • SnapshotArray(int length) initializes an array-like data structure with the given length.  Initially, each element equals 0.
    • +
    • void set(index, val) sets the element at the given index to be equal to val.
    • +
    • int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
    • +
    • int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: ["SnapshotArray","set","snap","set","get"]
    +[[3],[0,5],[],[0,6],[0,0]]
    +Output: [null,null,0,null,5]
    +Explanation: 
    +SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
    +snapshotArr.set(0,5);  // Set array[0] = 5
    +snapshotArr.snap();  // Take a snapshot, return snap_id = 0
    +snapshotArr.set(0,6);
    +snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= length <= 50000
    • +
    • At most 50000 calls will be made to set, snap, and get.
    • +
    • 0 <= index < length
    • +
    • 0 <= snap_id < (the total number of times we call snap())
    • +
    • 0 <= val <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md b/assets/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md new file mode 100644 index 00000000..217ecc12 --- /dev/null +++ b/assets/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md @@ -0,0 +1,81 @@ +# [1147. Longest Chunked Palindrome Decomposition](https://leetcode.com/problems/longest-chunked-palindrome-decomposition) + + + +## Description + +

    You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:

    + +
      +
    • subtexti is a non-empty string.
    • +
    • The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).
    • +
    • subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).
    • +
    + +

    Return the largest possible value of k.

    + +

     

    +

    Example 1:

    + +
    +Input: text = "ghiabcdefhelloadamhelloabcdefghi"
    +Output: 7
    +Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
    +
    + +

    Example 2:

    + +
    +Input: text = "merchant"
    +Output: 1
    +Explanation: We can split the string on "(merchant)".
    +
    + +

    Example 3:

    + +
    +Input: text = "antaprezatepzapreanta"
    +Output: 11
    +Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".
    +
    + +

    Example 4:

    + +
    +Input: text = "aaa"
    +Output: 3
    +Explanation: We can split the string on "(a)(a)(a)".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 1000
    • +
    • text consists only of lowercase English characters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1148.Article Views I/README_EN.md b/assets/1100-1199/1148.Article Views I/README_EN.md new file mode 100644 index 00000000..29383a17 --- /dev/null +++ b/assets/1100-1199/1148.Article Views I/README_EN.md @@ -0,0 +1,69 @@ +# [1148. Article Views I](https://leetcode.com/problems/article-views-i) + + + +## Description + +

    Table: Views

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| article_id    | int     |
    +| author_id     | int     |
    +| viewer_id     | int     |
    +| view_date     | date    |
    ++---------------+---------+
    +There is no primary key for this table, it may have duplicate rows.
    +Each row of this table indicates that some viewer viewed an article (written by some author) on some date. 
    +Note that equal author_id and viewer_id indicate the same person.
    + +

     

    + +

    Write an SQL query to find all the authors that viewed at least one of their own articles, sorted in ascending order by their id.

    + +

    The query result format is in the following example:

    + +
    +Views table:
    ++------------+-----------+-----------+------------+
    +| article_id | author_id | viewer_id | view_date  |
    ++------------+-----------+-----------+------------+
    +| 1          | 3         | 5         | 2019-08-01 |
    +| 1          | 3         | 6         | 2019-08-02 |
    +| 2          | 7         | 7         | 2019-08-01 |
    +| 2          | 7         | 6         | 2019-08-02 |
    +| 4          | 7         | 1         | 2019-07-22 |
    +| 3          | 4         | 4         | 2019-07-21 |
    +| 3          | 4         | 4         | 2019-07-21 |
    ++------------+-----------+-----------+------------+
    +
    +Result table:
    ++------+
    +| id   |
    ++------+
    +| 4    |
    +| 7    |
    ++------+
    +
    + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + DISTINCT(author_id) as id +FROM + Views +WHERE + author_id = viewer_id +ORDER BY + id; +``` + + diff --git a/assets/1100-1199/1149.Article Views II/README_EN.md b/assets/1100-1199/1149.Article Views II/README_EN.md new file mode 100644 index 00000000..a6dba3a4 --- /dev/null +++ b/assets/1100-1199/1149.Article Views II/README_EN.md @@ -0,0 +1,72 @@ +# [1149. Article Views II](https://leetcode.com/problems/article-views-ii) + + + +## Description + +

    Table: Views

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| article_id    | int     |
    +| author_id     | int     |
    +| viewer_id     | int     |
    +| view_date     | date    |
    ++---------------+---------+
    +There is no primary key for this table, it may have duplicate rows.
    +Each row of this table indicates that some viewer viewed an article (written by some author) on some date. 
    +Note that equal author_id and viewer_id indicate the same person.
    + +

     

    + +

    Write an SQL query to find all the people who viewed more than one article on the same date, sorted in ascending order by their id.

    + +

    The query result format is in the following example:

    + +
    +Views table:
    ++------------+-----------+-----------+------------+
    +| article_id | author_id | viewer_id | view_date  |
    ++------------+-----------+-----------+------------+
    +| 1          | 3         | 5         | 2019-08-01 |
    +| 3          | 4         | 5         | 2019-08-01 |
    +| 1          | 3         | 6         | 2019-08-02 |
    +| 2          | 7         | 7         | 2019-08-01 |
    +| 2          | 7         | 6         | 2019-08-02 |
    +| 4          | 7         | 1         | 2019-07-22 |
    +| 3          | 4         | 4         | 2019-07-21 |
    +| 3          | 4         | 4         | 2019-07-21 |
    ++------------+-----------+-----------+------------+
    +
    +Result table:
    ++------+
    +| id   |
    ++------+
    +| 5    |
    +| 6    |
    ++------+
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + DISTINCT(viewer_id) as id +FROM + Views +GROUP BY + view_date, viewer_id +HAVING + COUNT(DISTINCT(article_id)) > 1 +ORDER BY + id; +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md b/assets/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md new file mode 100644 index 00000000..4ba8bd4b --- /dev/null +++ b/assets/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md @@ -0,0 +1,135 @@ +# [1150. Check If a Number Is Majority Element in a Sorted Array](https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) + + + +## Description + +

    Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element.

    + +

    A majority element is an element that appears more than N/2 times in an array of length N.

    + +

     

    + +

    Example 1:

    + +
    +Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
    +Output: true
    +Explanation: 
    +The value 5 appears 5 times and the length of the array is 9.
    +Thus, 5 is a majority element because 5 > 9/2 is true.
    +
    + +

    Example 2:

    + +
    +Input: nums = [10,100,101,101], target = 101
    +Output: false
    +Explanation: 
    +The value 101 appears 2 times and the length of the array is 4.
    +Thus, 101 is not a majority element because 2 > 4/2 is false.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 10^9
    • +
    • 1 <= target <= 10^9
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + def bsearch_left(nums, target, left, right): + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + return left if nums[left] == target else -1 + + def bsearch_right(nums, target, left, right): + while left < right: + mid = (left + right + 1) >> 1 + if nums[mid] <= target: + left = mid + else: + right = mid - 1 + return left if nums[left] == target else -1 + + n = len(nums) + left = bsearch_left(nums, target, 0, n - 1) + if left == -1: + return False + right = bsearch_right(nums, target, left, n - 1) + if right == -1: + return False + return right - left + 1 > n >> 1 +``` + +```python +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + left, right = bisect.bisect_left(nums, target), bisect.bisect_right(nums, target) + return right - left > (len(nums) >> 1) +``` + +### **Java** + +```java +class Solution { + public boolean isMajorityElement(int[] nums, int target) { + int n = nums.length; + int left = bsearchLeft(nums, target, 0, n - 1); + if (left == -1) { + return false; + } + int right = bsearchRight(nums, target, left, n - 1); + if (right == -1) { + return false; + } + return right - left + 1 > (n >> 1); + } + + private int bsearchLeft(int[] nums, int target, int left, int right) { + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; + } + + private int bsearchRight(int[] nums, int target, int left, int right) { + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return nums[left] == target ? left : -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md b/assets/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md new file mode 100644 index 00000000..9080688e --- /dev/null +++ b/assets/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md @@ -0,0 +1,79 @@ +# [1151. Minimum Swaps to Group All 1's Together](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together) + + + +## Description + +

    Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

    + +

     

    +

    Example 1:

    + +
    +Input: data = [1,0,1,0,1]
    +Output: 1
    +Explanation: 
    +There are 3 ways to group all 1's together:
    +[1,1,1,0,0] using 1 swap.
    +[0,1,1,1,0] using 2 swaps.
    +[0,0,1,1,1] using 1 swap.
    +The minimum is 1.
    +
    + +

    Example 2:

    + +
    +Input: data = [0,0,0,1,0]
    +Output: 0
    +Explanation: 
    +Since there is only one 1 in the array, no swaps needed.
    +
    + +

    Example 3:

    + +
    +Input: data = [1,0,1,0,1,0,0,1,1,0,1]
    +Output: 3
    +Explanation: 
    +One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
    +
    + +

    Example 4:

    + +
    +Input: data = [1,0,1,0,1,0,1,1,1,0,1,0,0,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,0,1,1,1,1,0,0,1]
    +Output: 8
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= data.length <= 105
    • +
    • data[i] is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md b/assets/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md new file mode 100644 index 00000000..33f6dbcf --- /dev/null +++ b/assets/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md @@ -0,0 +1,76 @@ +# [1152. Analyze User Website Visit Pattern](https://leetcode.com/problems/analyze-user-website-visit-pattern) + + + +## Description + +

    We are given some website visits: the user with name username[i] visited the website website[i] at time timestamp[i].

    + +

    A 3-sequence is a list of websites of length 3 sorted in ascending order by the time of their visits.  (The websites in a 3-sequence are not necessarily distinct.)

    + +

    Find the 3-sequence visited by the largest number of users. If there is more than one solution, return the lexicographically smallest such 3-sequence.

    + +

     

    + +

    Example 1:

    + +
    +Input: username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"]
    +Output: ["home","about","career"]
    +Explanation: 
    +The tuples in this example are:
    +["joe", 1, "home"]
    +["joe", 2, "about"]
    +["joe", 3, "career"]
    +["james", 4, "home"]
    +["james", 5, "cart"]
    +["james", 6, "maps"]
    +["james", 7, "home"]
    +["mary", 8, "home"]
    +["mary", 9, "about"]
    +["mary", 10, "career"]
    +The 3-sequence ("home", "about", "career") was visited at least once by 2 users.
    +The 3-sequence ("home", "cart", "maps") was visited at least once by 1 user.
    +The 3-sequence ("home", "cart", "home") was visited at least once by 1 user.
    +The 3-sequence ("home", "maps", "home") was visited at least once by 1 user.
    +The 3-sequence ("cart", "maps", "home") was visited at least once by 1 user.
    +
    + +

     

    + +

    Note:

    + +
      +
    1. 3 <= N = username.length = timestamp.length = website.length <= 50
    2. +
    3. 1 <= username[i].length <= 10
    4. +
    5. 0 <= timestamp[i] <= 10^9
    6. +
    7. 1 <= website[i].length <= 10
    8. +
    9. Both username[i] and website[i] contain only lowercase characters.
    10. +
    11. It is guaranteed that there is at least one user who visited at least 3 websites.
    12. +
    13. No user visits two websites at the same time.
    14. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1153.String Transforms Into Another String/README_EN.md b/assets/1100-1199/1153.String Transforms Into Another String/README_EN.md new file mode 100644 index 00000000..18328deb --- /dev/null +++ b/assets/1100-1199/1153.String Transforms Into Another String/README_EN.md @@ -0,0 +1,61 @@ +# [1153. String Transforms Into Another String](https://leetcode.com/problems/string-transforms-into-another-string) + + + +## Description + +

    Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions.

    + +

    In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.

    + +

    Return true if and only if you can transform str1 into str2.

    + +

     

    +

    Example 1:

    + +
    +Input: str1 = "aabcc", str2 = "ccdee"
    +Output: true
    +Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
    +
    + +

    Example 2:

    + +
    +Input: str1 = "leetcode", str2 = "codeleet"
    +Output: false
    +Explanation: There is no way to transform str1 to str2.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= str1.length == str2.length <= 104
    • +
    • str1 and str2 contain only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1154.Day of the Year/README_EN.md b/assets/1100-1199/1154.Day of the Year/README_EN.md new file mode 100644 index 00000000..9933a927 --- /dev/null +++ b/assets/1100-1199/1154.Day of the Year/README_EN.md @@ -0,0 +1,105 @@ +# [1154. Day of the Year](https://leetcode.com/problems/day-of-the-year) + + + +## Description + +

    Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: date = "2019-01-09"
    +
    +Output: 9
    +
    +Explanation: Given date is the 9th day of the year in 2019.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: date = "2019-02-10"
    +
    +Output: 41
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: date = "2003-03-01"
    +
    +Output: 60
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: date = "2004-03-01"
    +
    +Output: 61
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • date.length == 10
    • +
    • date[4] == date[7] == '-', and all other date[i]'s are digits
    • +
    • date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md b/assets/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md new file mode 100644 index 00000000..4e1b45b2 --- /dev/null +++ b/assets/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md @@ -0,0 +1,89 @@ +# [1155. Number of Dice Rolls With Target Sum](https://leetcode.com/problems/number-of-dice-rolls-with-target-sum) + + + +## Description + +

    You have d dice and each die has f faces numbered 1, 2, ..., f.

    + +

    Return the number of possible ways (out of fd total ways) modulo 109 + 7 to roll the dice so the sum of the face-up numbers equals target.

    + +

     

    +

    Example 1:

    + +
    +Input: d = 1, f = 6, target = 3
    +Output: 1
    +Explanation: 
    +You throw one die with 6 faces.  There is only one way to get a sum of 3.
    +
    + +

    Example 2:

    + +
    +Input: d = 2, f = 6, target = 7
    +Output: 6
    +Explanation: 
    +You throw two dice, each with 6 faces.  There are 6 ways to get a sum of 7:
    +1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
    +
    + +

    Example 3:

    + +
    +Input: d = 2, f = 5, target = 10
    +Output: 1
    +Explanation: 
    +You throw two dice, each with 5 faces.  There is only one way to get a sum of 10: 5+5.
    +
    + +

    Example 4:

    + +
    +Input: d = 1, f = 2, target = 3
    +Output: 0
    +Explanation: 
    +You throw one die with 2 faces.  There is no way to get a sum of 3.
    +
    + +

    Example 5:

    + +
    +Input: d = 30, f = 30, target = 500
    +Output: 222616187
    +Explanation: 
    +The answer must be returned modulo 10^9 + 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= d, f <= 30
    • +
    • 1 <= target <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md b/assets/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md new file mode 100644 index 00000000..f9375151 --- /dev/null +++ b/assets/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md @@ -0,0 +1,79 @@ +# [1156. Swap For Longest Repeated Character Substring](https://leetcode.com/problems/swap-for-longest-repeated-character-substring) + + + +## Description + +

    Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.

    + +

     

    +

    Example 1:

    + +
    +Input: text = "ababa"
    +Output: 3
    +Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.
    +
    + +

    Example 2:

    + +
    +Input: text = "aaabaaa"
    +Output: 6
    +Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.
    +
    + +

    Example 3:

    + +
    +Input: text = "aaabbaaa"
    +Output: 4
    +
    + +

    Example 4:

    + +
    +Input: text = "aaaaa"
    +Output: 5
    +Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.
    +
    + +

    Example 5:

    + +
    +Input: text = "abcdef"
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 20000
    • +
    • text consist of lowercase English characters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1157.Online Majority Element In Subarray/README_EN.md b/assets/1100-1199/1157.Online Majority Element In Subarray/README_EN.md new file mode 100644 index 00000000..001efb73 --- /dev/null +++ b/assets/1100-1199/1157.Online Majority Element In Subarray/README_EN.md @@ -0,0 +1,85 @@ +# [1157. Online Majority Element In Subarray](https://leetcode.com/problems/online-majority-element-in-subarray) + + + +## Description + +

    Implementing the class MajorityChecker, which has the following API:

    + + + +
      +
    • MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
    • +
    • int query(int left, int right, int threshold) has arguments such that: +
        +
      • 0 <= left <= right < arr.length representing a subarray of arr;
      • +
      • 2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
      • +
      +
    • +
    + + + +

    Each query(...) returns the element in arr[left], arr[left+1], ..., arr[right] that occurs at least threshold times, or -1 if no such element exists.

    + + + +

     

    + + + +

    Example:

    + + + +
    +
    +MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
    +
    +majorityChecker.query(0,5,4); // returns 1
    +
    +majorityChecker.query(0,3,3); // returns -1
    +
    +majorityChecker.query(2,3,2); // returns 2
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 20000
    • +
    • 1 <= arr[i] <= 20000
    • +
    • For each query, 0 <= left <= right < len(arr)
    • +
    • For each query, 2 * threshold > right - left + 1
    • +
    • The number of queries is at most 10000
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1158.Market Analysis I/README_EN.md b/assets/1100-1199/1158.Market Analysis I/README_EN.md new file mode 100644 index 00000000..48d67dbb --- /dev/null +++ b/assets/1100-1199/1158.Market Analysis I/README_EN.md @@ -0,0 +1,110 @@ +# [1158. Market Analysis I](https://leetcode.com/problems/market-analysis-i) + + + +## Description + +

    Table: Users

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| user_id        | int     |
    +| join_date      | date    |
    +| favorite_brand | varchar |
    ++----------------+---------+
    +user_id is the primary key of this table.
    +This table has the info of the users of an online shopping website where users can sell and buy items.
    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| item_id       | int     |
    +| buyer_id      | int     |
    +| seller_id     | int     |
    ++---------------+---------+
    +order_id is the primary key of this table.
    +item_id is a foreign key to the Items table.
    +buyer_id and seller_id are foreign keys to the Users table.
    +
    + +

    Table: Items

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| item_id       | int     |
    +| item_brand    | varchar |
    ++---------------+---------+
    +item_id is the primary key of this table.
    +
    + +

     

    + +

    Write an SQL query to find for each user, the join date and the number of orders they made as a buyer in 2019.

    + +

    The query result format is in the following example:

    + +
    +Users table:
    ++---------+------------+----------------+
    +| user_id | join_date  | favorite_brand |
    ++---------+------------+----------------+
    +| 1       | 2018-01-01 | Lenovo         |
    +| 2       | 2018-02-09 | Samsung        |
    +| 3       | 2018-01-19 | LG             |
    +| 4       | 2018-05-21 | HP             |
    ++---------+------------+----------------+
    +
    +Orders table:
    ++----------+------------+---------+----------+-----------+
    +| order_id | order_date | item_id | buyer_id | seller_id |
    ++----------+------------+---------+----------+-----------+
    +| 1        | 2019-08-01 | 4       | 1        | 2         |
    +| 2        | 2018-08-02 | 2       | 1        | 3         |
    +| 3        | 2019-08-03 | 3       | 2        | 3         |
    +| 4        | 2018-08-04 | 1       | 4        | 2         |
    +| 5        | 2018-08-04 | 1       | 3        | 4         |
    +| 6        | 2019-08-05 | 2       | 2        | 4         |
    ++----------+------------+---------+----------+-----------+
    +
    +Items table:
    ++---------+------------+
    +| item_id | item_brand |
    ++---------+------------+
    +| 1       | Samsung    |
    +| 2       | Lenovo     |
    +| 3       | LG         |
    +| 4       | HP         |
    ++---------+------------+
    +
    +Result table:
    ++-----------+------------+----------------+
    +| buyer_id  | join_date  | orders_in_2019 |
    ++-----------+------------+----------------+
    +| 1         | 2018-01-01 | 1              |
    +| 2         | 2018-02-09 | 2              |
    +| 3         | 2018-01-19 | 0              |
    +| 4         | 2018-05-21 | 0              |
    ++-----------+------------+----------------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1159.Market Analysis II/README_EN.md b/assets/1100-1199/1159.Market Analysis II/README_EN.md new file mode 100644 index 00000000..5de4f763 --- /dev/null +++ b/assets/1100-1199/1159.Market Analysis II/README_EN.md @@ -0,0 +1,115 @@ +# [1159. Market Analysis II](https://leetcode.com/problems/market-analysis-ii) + + + +## Description + +

    Table: Users

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| user_id        | int     |
    +| join_date      | date    |
    +| favorite_brand | varchar |
    ++----------------+---------+
    +user_id is the primary key of this table.
    +This table has the info of the users of an online shopping website where users can sell and buy items.
    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| item_id       | int     |
    +| buyer_id      | int     |
    +| seller_id     | int     |
    ++---------------+---------+
    +order_id is the primary key of this table.
    +item_id is a foreign key to the Items table.
    +buyer_id and seller_id are foreign keys to the Users table.
    +
    + +

    Table: Items

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| item_id       | int     |
    +| item_brand    | varchar |
    ++---------------+---------+
    +item_id is the primary key of this table.
    +
    + +

     

    + +

    Write an SQL query to find for each user, whether the brand of the second item (by date) they sold is their favorite brand. If a user sold less than two items, report the answer for that user as no.

    + +

    It is guaranteed that no seller sold more than one item on a day.

    + +

    The query result format is in the following example:

    + +
    +Users table:
    ++---------+------------+----------------+
    +| user_id | join_date  | favorite_brand |
    ++---------+------------+----------------+
    +| 1       | 2019-01-01 | Lenovo         |
    +| 2       | 2019-02-09 | Samsung        |
    +| 3       | 2019-01-19 | LG             |
    +| 4       | 2019-05-21 | HP             |
    ++---------+------------+----------------+
    +
    +Orders table:
    ++----------+------------+---------+----------+-----------+
    +| order_id | order_date | item_id | buyer_id | seller_id |
    ++----------+------------+---------+----------+-----------+
    +| 1        | 2019-08-01 | 4       | 1        | 2         |
    +| 2        | 2019-08-02 | 2       | 1        | 3         |
    +| 3        | 2019-08-03 | 3       | 2        | 3         |
    +| 4        | 2019-08-04 | 1       | 4        | 2         |
    +| 5        | 2019-08-04 | 1       | 3        | 4         |
    +| 6        | 2019-08-05 | 2       | 2        | 4         |
    ++----------+------------+---------+----------+-----------+
    +
    +Items table:
    ++---------+------------+
    +| item_id | item_brand |
    ++---------+------------+
    +| 1       | Samsung    |
    +| 2       | Lenovo     |
    +| 3       | LG         |
    +| 4       | HP         |
    ++---------+------------+
    +
    +Result table:
    ++-----------+--------------------+
    +| seller_id | 2nd_item_fav_brand |
    ++-----------+--------------------+
    +| 1         | no                 |
    +| 2         | yes                |
    +| 3         | yes                |
    +| 4         | no                 |
    ++-----------+--------------------+
    +
    +The answer for the user with id 1 is no because they sold nothing.
    +The answer for the users with id 2 and 3 is yes because the brands of their second sold items are their favorite brands.
    +The answer for the user with id 4 is no because the brand of their second sold item is not their favorite brand.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md b/assets/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md new file mode 100644 index 00000000..1a2983c6 --- /dev/null +++ b/assets/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md @@ -0,0 +1,95 @@ +# [1160. Find Words That Can Be Formed by Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters) + + + +## Description + +

    You are given an array of strings words and a string chars.

    + + + +

    A string is good if it can be formed by characters from chars (each character can only be used once).

    + + + +

    Return the sum of lengths of all good strings in words.

    + + + +

     

    + + + +

    Example 1:

    + + + +
    +
    +Input: words = ["cat","bt","hat","tree"], chars = "atach"
    +
    +Output: 6
    +
    +Explanation: 
    +
    +The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
    +
    +Output: 10
    +
    +Explanation: 
    +
    +The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
    +
    +
    + + + +

     

    + + + +

    Note:

    + + + +
      +
    1. 1 <= words.length <= 1000
    2. +
    3. 1 <= words[i].length, chars.length <= 100
    4. +
    5. All strings contain lowercase English letters only.
    6. +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md b/assets/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md new file mode 100644 index 00000000..b5c19f8d --- /dev/null +++ b/assets/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md @@ -0,0 +1,62 @@ +# [1161. Maximum Level Sum of a Binary Tree](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree) + + + +## Description + +

    Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

    + +

    Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,7,0,7,-8,null,null]
    +Output: 2
    +Explanation: 
    +Level 1 sum = 1.
    +Level 2 sum = 7 + 0 = 7.
    +Level 3 sum = 7 + -8 = -1.
    +So we return the level with the maximum sum which is level 2.
    +
    + +

    Example 2:

    + +
    +Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 104].
    • +
    • -105 <= Node.val <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1161.Maximum Level Sum of a Binary Tree/images/capture.jpeg b/assets/1100-1199/1161.Maximum Level Sum of a Binary Tree/images/capture.jpeg new file mode 100644 index 00000000..27c6c75a Binary files /dev/null and b/assets/1100-1199/1161.Maximum Level Sum of a Binary Tree/images/capture.jpeg differ diff --git a/assets/1100-1199/1162.As Far from Land as Possible/README_EN.md b/assets/1100-1199/1162.As Far from Land as Possible/README_EN.md new file mode 100644 index 00000000..95d33983 --- /dev/null +++ b/assets/1100-1199/1162.As Far from Land as Possible/README_EN.md @@ -0,0 +1,61 @@ +# [1162. As Far from Land as Possible](https://leetcode.com/problems/as-far-from-land-as-possible) + + + +## Description + +

    Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.

    + +

    The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
    +Output: 2
    +Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
    +Output: 4
    +Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 100
    • +
    • grid[i][j] is 0 or 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1162.As Far from Land as Possible/images/1336_ex1.jpeg b/assets/1100-1199/1162.As Far from Land as Possible/images/1336_ex1.jpeg new file mode 100644 index 00000000..e1cc80f9 Binary files /dev/null and b/assets/1100-1199/1162.As Far from Land as Possible/images/1336_ex1.jpeg differ diff --git a/assets/1100-1199/1162.As Far from Land as Possible/images/1336_ex2.jpeg b/assets/1100-1199/1162.As Far from Land as Possible/images/1336_ex2.jpeg new file mode 100644 index 00000000..b8d99846 Binary files /dev/null and b/assets/1100-1199/1162.As Far from Land as Possible/images/1336_ex2.jpeg differ diff --git a/assets/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md b/assets/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md new file mode 100644 index 00000000..3858dd4e --- /dev/null +++ b/assets/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md @@ -0,0 +1,56 @@ +# [1163. Last Substring in Lexicographical Order](https://leetcode.com/problems/last-substring-in-lexicographical-order) + + + +## Description + +

    Given a string s, return the last substring of s in lexicographical order.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abab"
    +Output: "bab"
    +Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
    +
    + +

    Example 2:

    + +
    +Input: s = "leetcode"
    +Output: "tcode"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 4 * 105
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1164.Product Price at a Given Date/README_EN.md b/assets/1100-1199/1164.Product Price at a Given Date/README_EN.md new file mode 100644 index 00000000..fd1a6a77 --- /dev/null +++ b/assets/1100-1199/1164.Product Price at a Given Date/README_EN.md @@ -0,0 +1,60 @@ +# [1164. Product Price at a Given Date](https://leetcode.com/problems/product-price-at-a-given-date) + + + +## Description + +

    Table: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| new_price     | int     |
    +| change_date   | date    |
    ++---------------+---------+
    +(product_id, change_date) is the primary key of this table.
    +Each row of this table indicates that the price of some product was changed to a new price at some date.
    + +

     

    + +

    Write an SQL query to find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10.

    + +

    The query result format is in the following example:

    + +
    +Products table:
    ++------------+-----------+-------------+
    +| product_id | new_price | change_date |
    ++------------+-----------+-------------+
    +| 1          | 20        | 2019-08-14  |
    +| 2          | 50        | 2019-08-14  |
    +| 1          | 30        | 2019-08-15  |
    +| 1          | 35        | 2019-08-16  |
    +| 2          | 65        | 2019-08-17  |
    +| 3          | 20        | 2019-08-18  |
    ++------------+-----------+-------------+
    +
    +Result table:
    ++------------+-------+
    +| product_id | price |
    ++------------+-------+
    +| 2          | 50    |
    +| 1          | 35    |
    +| 3          | 10    |
    ++------------+-------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1100-1199/1165.Single-Row Keyboard/README_EN.md b/assets/1100-1199/1165.Single-Row Keyboard/README_EN.md new file mode 100644 index 00000000..8a534bda --- /dev/null +++ b/assets/1100-1199/1165.Single-Row Keyboard/README_EN.md @@ -0,0 +1,127 @@ +# [1165. Single-Row Keyboard](https://leetcode.com/problems/single-row-keyboard) + + + +## Description + +

    There is a special keyboard with all keys in a single row.

    + +

    Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|.

    + +

    You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.

    + +

     

    +

    Example 1:

    + +
    +Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
    +Output: 4
    +Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
    +Total time = 2 + 1 + 1 = 4. 
    +
    + +

    Example 2:

    + +
    +Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"
    +Output: 73
    +
    + +

     

    +

    Constraints:

    + +
      +
    • keyboard.length == 26
    • +
    • keyboard contains each English lowercase letter exactly once in some order.
    • +
    • 1 <= word.length <= 104
    • +
    • word[i] is an English lowercase letter.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def calculateTime(self, keyboard: str, word: str) -> int: + index = {c: i for i, c in enumerate(keyboard)} + res = t = 0 + for c in word: + res += abs(index[c] - t) + t = index[c] + return res +``` + +### **Java** + +```java +class Solution { + public int calculateTime(String keyboard, String word) { + Map index = new HashMap<>(); + for (int i = 0; i < keyboard.length(); ++i) { + index.put(keyboard.charAt(i), i); + } + int res = 0, t = 0; + for (char c : word.toCharArray()) { + res += Math.abs(index.get(c) - t); + t = index.get(c); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int calculateTime(string keyboard, string word) { + unordered_map index; + for (int i = 0; i < keyboard.size(); ++i) { + index[keyboard[i]] = i; + } + int res = 0, t = 0; + for (char c : word) { + res += abs(index[c] - t); + t = index[c]; + } + return res; + } +}; +``` + +### **Go** + +```go +func calculateTime(keyboard string, word string) int { + index := map[byte]int{} + for i := 0; i < len(keyboard); i++ { + index[keyboard[i]] = i + } + res := 0 + t := 0 + for i := 0; i < len(word); i++ { + res += abs(index[word[i]] - t) + t = index[word[i]] + } + return res +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1166.Design File System/README_EN.md b/assets/1100-1199/1166.Design File System/README_EN.md new file mode 100644 index 00000000..c0fb3992 --- /dev/null +++ b/assets/1100-1199/1166.Design File System/README_EN.md @@ -0,0 +1,84 @@ +# [1166. Design File System](https://leetcode.com/problems/design-file-system) + + + +## Description + +

    You are asked to design a file system that allows you to create new paths and associate them with different values.

    + +

    The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string "" and "/" are not.

    + +

    Implement the FileSystem class:

    + +
      +
    • bool createPath(string path, int value) Creates a new path and associates a value to it if possible and returns true. Returns false if the path already exists or its parent path doesn't exist.
    • +
    • int get(string path) Returns the value associated with path or returns -1 if the path doesn't exist.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: 
    +["FileSystem","createPath","get"]
    +[[],["/a",1],["/a"]]
    +Output: 
    +[null,true,1]
    +Explanation: 
    +FileSystem fileSystem = new FileSystem();
    +
    +fileSystem.createPath("/a", 1); // return true
    +fileSystem.get("/a"); // return 1
    +
    + +

    Example 2:

    + +
    +Input: 
    +["FileSystem","createPath","createPath","get","createPath","get"]
    +[[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]]
    +Output: 
    +[null,true,true,2,false,-1]
    +Explanation: 
    +FileSystem fileSystem = new FileSystem();
    +
    +fileSystem.createPath("/leet", 1); // return true
    +fileSystem.createPath("/leet/code", 2); // return true
    +fileSystem.get("/leet/code"); // return 2
    +fileSystem.createPath("/c/d", 1); // return false because the parent path "/c" doesn't exist.
    +fileSystem.get("/c"); // return -1 because this path doesn't exist.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of calls to the two functions is less than or equal to 104 in total.
    • +
    • 2 <= path.length <= 100
    • +
    • 1 <= value <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md b/assets/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md new file mode 100644 index 00000000..ca0602f3 --- /dev/null +++ b/assets/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md @@ -0,0 +1,76 @@ +# [1167. Minimum Cost to Connect Sticks](https://leetcode.com/problems/minimum-cost-to-connect-sticks) + + + +## Description + +

    You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.

    + +

    You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.

    + +

    Return the minimum cost of connecting all the given sticks into one stick in this way.

    + +

     

    +

    Example 1:

    + +
    +Input: sticks = [2,4,3]
    +Output: 14
    +Explanation: You start with sticks = [2,4,3].
    +1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4].
    +2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9].
    +There is only one stick left, so you are done. The total cost is 5 + 9 = 14.
    +
    + +

    Example 2:

    + +
    +Input: sticks = [1,8,3,5]
    +Output: 30
    +Explanation: You start with sticks = [1,8,3,5].
    +1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5].
    +2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8].
    +3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17].
    +There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.
    +
    + +

    Example 3:

    + +
    +Input: sticks = [5]
    +Output: 0
    +Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= sticks.length <= 104
    • +
    • 1 <= sticks[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md b/assets/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md new file mode 100644 index 00000000..d213c29f --- /dev/null +++ b/assets/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md @@ -0,0 +1,63 @@ +# [1168. Optimize Water Distribution in a Village](https://leetcode.com/problems/optimize-water-distribution-in-a-village) + + + +## Description + +

    There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.

    + +

    For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes, where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional.

    + +

    Return the minimum total cost to supply water to all houses.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
    +Output: 3
    +Explanation: 
    +The image shows the costs of connecting houses using pipes.
    +The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 104
    • +
    • wells.length == n
    • +
    • 0 <= wells[i] <= 105
    • +
    • 1 <= pipes.length <= 104
    • +
    • pipes[j].length == 3
    • +
    • 1 <= house1j, house2j <= n
    • +
    • 0 <= costj <= 105
    • +
    • house1j != house2j
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1168.Optimize Water Distribution in a Village/images/1359_ex1.png b/assets/1100-1199/1168.Optimize Water Distribution in a Village/images/1359_ex1.png new file mode 100644 index 00000000..be15d6b0 Binary files /dev/null and b/assets/1100-1199/1168.Optimize Water Distribution in a Village/images/1359_ex1.png differ diff --git a/assets/1100-1199/1169.Invalid Transactions/README_EN.md b/assets/1100-1199/1169.Invalid Transactions/README_EN.md new file mode 100644 index 00000000..fedd5b7e --- /dev/null +++ b/assets/1100-1199/1169.Invalid Transactions/README_EN.md @@ -0,0 +1,74 @@ +# [1169. Invalid Transactions](https://leetcode.com/problems/invalid-transactions) + + + +## Description + +

    A transaction is possibly invalid if:

    + +
      +
    • the amount exceeds $1000, or;
    • +
    • if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
    • +
    + +

    You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.

    + +

    Return a list of transactions that are possibly invalid. You may return the answer in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
    +Output: ["alice,20,800,mtv","alice,50,100,beijing"]
    +Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
    + +

    Example 2:

    + +
    +Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
    +Output: ["alice,50,1200,mtv"]
    +
    + +

    Example 3:

    + +
    +Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
    +Output: ["bob,50,1200,mtv"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • transactions.length <= 1000
    • +
    • Each transactions[i] takes the form "{name},{time},{amount},{city}"
    • +
    • Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.
    • +
    • Each {time} consist of digits, and represent an integer between 0 and 1000.
    • +
    • Each {amount} consist of digits, and represent an integer between 0 and 2000.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md b/assets/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md new file mode 100644 index 00000000..90518790 --- /dev/null +++ b/assets/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md @@ -0,0 +1,63 @@ +# [1170. Compare Strings by Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character) + + + +## Description + +

    Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.

    + +

    You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.

    + +

    Return an integer array answer, where each answer[i] is the answer to the ith query.

    + +

     

    +

    Example 1:

    + +
    +Input: queries = ["cbd"], words = ["zaaaz"]
    +Output: [1]
    +Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
    +
    + +

    Example 2:

    + +
    +Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
    +Output: [1,2]
    +Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= queries.length <= 2000
    • +
    • 1 <= words.length <= 2000
    • +
    • 1 <= queries[i].length, words[i].length <= 10
    • +
    • queries[i][j], words[i][j] consist of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md b/assets/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md new file mode 100644 index 00000000..b5408949 --- /dev/null +++ b/assets/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md @@ -0,0 +1,112 @@ +# [1171. Remove Zero Sum Consecutive Nodes from Linked List](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list) + + + +## Description + +

    Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.

    + +

    After doing so, return the head of the final linked list.  You may return any such answer.

    + +

     

    +

    (Note that in the examples below, all sequences are serializations of ListNode objects.)

    + +

    Example 1:

    + +
    +Input: head = [1,2,-3,3,1]
    +Output: [3,1]
    +Note: The answer [1,2,1] would also be accepted.
    +
    + +

    Example 2:

    + +
    +Input: head = [1,2,3,-3,4]
    +Output: [1,2,4]
    +
    + +

    Example 3:

    + +
    +Input: head = [1,2,3,-3,-2]
    +Output: [1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The given linked list will contain between 1 and 1000 nodes.
    • +
    • Each node in the linked list has -1000 <= node.val <= 1000.
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def removeZeroSumSublists(self, head: ListNode) -> ListNode: + dummy = ListNode(0) + dummy.next = head + s, cur = 0, dummy + pre_sum_node = {} + while cur: + s += cur.val + pre_sum_node[s] = cur + cur = cur.next + s, cur = 0, dummy + while cur: + s += cur.val + cur.next = pre_sum_node[s].next + cur = cur.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode removeZeroSumSublists(ListNode head) { + ListNode dummy = new ListNode(0); + dummy.next = head; + Map preSumNode = new HashMap<>(); + int s = 0; + for (ListNode cur = dummy; cur != null; cur = cur.next) { + s += cur.val; + preSumNode.put(s, cur); + } + s = 0; + for (ListNode cur = dummy; cur != null; cur = cur.next) { + s += cur.val; + cur.next = preSumNode.get(s).next; + } + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1172.Dinner Plate Stacks/README_EN.md b/assets/1100-1199/1172.Dinner Plate Stacks/README_EN.md new file mode 100644 index 00000000..d2d8e539 --- /dev/null +++ b/assets/1100-1199/1172.Dinner Plate Stacks/README_EN.md @@ -0,0 +1,95 @@ +# [1172. Dinner Plate Stacks](https://leetcode.com/problems/dinner-plate-stacks) + + + +## Description + +

    You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.

    + +

    Implement the DinnerPlates class:

    + +
      +
    • DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks.
    • +
    • void push(int val) Pushes the given positive integer val into the leftmost stack with size less than capacity.
    • +
    • int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all stacks are empty.
    • +
    • int popAtStack(int index) Returns the value at the top of the stack with the given index and removes it from that stack, and returns -1 if the stack with that given index is empty.
    • +
    + +

    Example:

    + +
    +Input: 
    +["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"]
    +[[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]
    +Output: 
    +[null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]
    +
    +Explanation: 
    +DinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2
    +D.push(1);
    +D.push(2);
    +D.push(3);
    +D.push(4);
    +D.push(5);         // The stacks are now:  2  4
    +                                           1  3  5
    +                                           ﹈ ﹈ ﹈
    +D.popAtStack(0);   // Returns 2.  The stacks are now:     4
    +                                                       1  3  5
    +                                                       ﹈ ﹈ ﹈
    +D.push(20);        // The stacks are now: 20  4
    +                                           1  3  5
    +                                           ﹈ ﹈ ﹈
    +D.push(21);        // The stacks are now: 20  4 21
    +                                           1  3  5
    +                                           ﹈ ﹈ ﹈
    +D.popAtStack(0);   // Returns 20.  The stacks are now:     4 21
    +                                                        1  3  5
    +                                                        ﹈ ﹈ ﹈
    +D.popAtStack(2);   // Returns 21.  The stacks are now:     4
    +                                                        1  3  5
    +                                                        ﹈ ﹈ ﹈ 
    +D.pop()            // Returns 5.  The stacks are now:      4
    +                                                        1  3 
    +                                                        ﹈ ﹈  
    +D.pop()            // Returns 4.  The stacks are now:   1  3 
    +                                                        ﹈ ﹈   
    +D.pop()            // Returns 3.  The stacks are now:   1 
    +                                                        ﹈   
    +D.pop()            // Returns 1.  There are no stacks.
    +D.pop()            // Returns -1.  There are still no stacks.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= capacity <= 20000
    • +
    • 1 <= val <= 20000
    • +
    • 0 <= index <= 100000
    • +
    • At most 200000 calls will be made to push, pop, and popAtStack.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1173.Immediate Food Delivery I/README_EN.md b/assets/1100-1199/1173.Immediate Food Delivery I/README_EN.md new file mode 100644 index 00000000..c5dbfdd3 --- /dev/null +++ b/assets/1100-1199/1173.Immediate Food Delivery I/README_EN.md @@ -0,0 +1,63 @@ +# [1173. Immediate Food Delivery I](https://leetcode.com/problems/immediate-food-delivery-i) + + + +## Description + +

    Table: Delivery

    + +
    ++-----------------------------+---------+
    +| Column Name                 | Type    |
    ++-----------------------------+---------+
    +| delivery_id                 | int     |
    +| customer_id                 | int     |
    +| order_date                  | date    |
    +| customer_pref_delivery_date | date    |
    ++-----------------------------+---------+
    +delivery_id is the primary key of this table.
    +The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it).
    +
    + +

     

    + +

    If the preferred delivery date of the customer is the same as the order date then the order is called immediate otherwise it's called scheduled.

    + +

    Write an SQL query to find the percentage of immediate orders in the table, rounded to 2 decimal places.

    + +

    The query result format is in the following example:

    + +
    +Delivery table:
    ++-------------+-------------+------------+-----------------------------+
    +| delivery_id | customer_id | order_date | customer_pref_delivery_date |
    ++-------------+-------------+------------+-----------------------------+
    +| 1           | 1           | 2019-08-01 | 2019-08-02                  |
    +| 2           | 5           | 2019-08-02 | 2019-08-02                  |
    +| 3           | 1           | 2019-08-11 | 2019-08-11                  |
    +| 4           | 3           | 2019-08-24 | 2019-08-26                  |
    +| 5           | 4           | 2019-08-21 | 2019-08-22                  |
    +| 6           | 2           | 2019-08-11 | 2019-08-13                  |
    ++-------------+-------------+------------+-----------------------------+
    +
    +Result table:
    ++----------------------+
    +| immediate_percentage |
    ++----------------------+
    +| 33.33                |
    ++----------------------+
    +The orders with delivery id 2 and 3 are immediate while the others are scheduled.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1174.Immediate Food Delivery II/README_EN.md b/assets/1100-1199/1174.Immediate Food Delivery II/README_EN.md new file mode 100644 index 00000000..8feb4e97 --- /dev/null +++ b/assets/1100-1199/1174.Immediate Food Delivery II/README_EN.md @@ -0,0 +1,70 @@ +# [1174. Immediate Food Delivery II](https://leetcode.com/problems/immediate-food-delivery-ii) + + + +## Description + +

    Table: Delivery

    + +
    ++-----------------------------+---------+
    +| Column Name                 | Type    |
    ++-----------------------------+---------+
    +| delivery_id                 | int     |
    +| customer_id                 | int     |
    +| order_date                  | date    |
    +| customer_pref_delivery_date | date    |
    ++-----------------------------+---------+
    +delivery_id is the primary key of this table.
    +The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it).
    +
    + +

     

    + +

    If the preferred delivery date of the customer is the same as the order date then the order is called immediate otherwise it's called scheduled.

    + +

    The first order of a customer is the order with the earliest order date that customer made. It is guaranteed that a customer has exactly one first order.

    + +

    Write an SQL query to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.

    + +

    The query result format is in the following example:

    + +
    +Delivery table:
    ++-------------+-------------+------------+-----------------------------+
    +| delivery_id | customer_id | order_date | customer_pref_delivery_date |
    ++-------------+-------------+------------+-----------------------------+
    +| 1           | 1           | 2019-08-01 | 2019-08-02                  |
    +| 2           | 2           | 2019-08-02 | 2019-08-02                  |
    +| 3           | 1           | 2019-08-11 | 2019-08-12                  |
    +| 4           | 3           | 2019-08-24 | 2019-08-24                  |
    +| 5           | 3           | 2019-08-21 | 2019-08-22                  |
    +| 6           | 2           | 2019-08-11 | 2019-08-13                  |
    +| 7           | 4           | 2019-08-09 | 2019-08-09                  |
    ++-------------+-------------+------------+-----------------------------+
    +
    +Result table:
    ++----------------------+
    +| immediate_percentage |
    ++----------------------+
    +| 50.00                |
    ++----------------------+
    +The customer id 1 has a first order with delivery id 1 and it is scheduled.
    +The customer id 2 has a first order with delivery id 2 and it is immediate.
    +The customer id 3 has a first order with delivery id 5 and it is scheduled.
    +The customer id 4 has a first order with delivery id 7 and it is immediate.
    +Hence, half the customers have immediate first orders.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1175.Prime Arrangements/README_EN.md b/assets/1100-1199/1175.Prime Arrangements/README_EN.md new file mode 100644 index 00000000..5ebd00a0 --- /dev/null +++ b/assets/1100-1199/1175.Prime Arrangements/README_EN.md @@ -0,0 +1,59 @@ +# [1175. Prime Arrangements](https://leetcode.com/problems/prime-arrangements) + + + +## Description + +

    Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)

    + +

    (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)

    + +

    Since the answer may be large, return the answer modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5
    +Output: 12
    +Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
    +
    + +

    Example 2:

    + +
    +Input: n = 100
    +Output: 682289015
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1176.Diet Plan Performance/README_EN.md b/assets/1100-1199/1176.Diet Plan Performance/README_EN.md new file mode 100644 index 00000000..702e427a --- /dev/null +++ b/assets/1100-1199/1176.Diet Plan Performance/README_EN.md @@ -0,0 +1,84 @@ +# [1176. Diet Plan Performance](https://leetcode.com/problems/diet-plan-performance) + + + +## Description + +

    A dieter consumes calories[i] calories on the i-th day. 

    + +

    Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ..., calories[i+k-1] for all 0 <= i <= n-k), they look at T, the total calories consumed during that sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]):

    + +
      +
    • If T < lower, they performed poorly on their diet and lose 1 point; 
    • +
    • If T > upper, they performed well on their diet and gain 1 point;
    • +
    • Otherwise, they performed normally and there is no change in points.
    • +
    + +

    Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for calories.length days.

    + +

    Note that the total points can be negative.

    + +

     

    +

    Example 1:

    + +
    +Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
    +Output: 0
    +Explanation: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
    +calories[0] and calories[1] are less than lower so 2 points are lost.
    +calories[3] and calories[4] are greater than upper so 2 points are gained.
    +
    + +

    Example 2:

    + +
    +Input: calories = [3,2], k = 2, lower = 0, upper = 1
    +Output: 1
    +Explanation: Since k = 2, we consider subarrays of length 2.
    +calories[0] + calories[1] > upper so 1 point is gained.
    +
    + +

    Example 3:

    + +
    +Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
    +Output: 0
    +Explanation:
    +calories[0] + calories[1] > upper so 1 point is gained.
    +lower <= calories[1] + calories[2] <= upper so no change in points.
    +calories[2] + calories[3] < lower so 1 point is lost.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= calories.length <= 10^5
    • +
    • 0 <= calories[i] <= 20000
    • +
    • 0 <= lower <= upper
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md b/assets/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md new file mode 100644 index 00000000..084e6fda --- /dev/null +++ b/assets/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md @@ -0,0 +1,64 @@ +# [1177. Can Make Palindrome from Substring](https://leetcode.com/problems/can-make-palindrome-from-substring) + + + +## Description + +

    Given a string s, we make queries on substrings of s.

    + +

    For each query queries[i] = [left, right, k], we may rearrange the substring s[left], ..., s[right], and then choose up to k of them to replace with any lowercase English letter. 

    + +

    If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.

    + +

    Return an array answer[], where answer[i] is the result of the i-th query queries[i].

    + +

    Note that: Each letter is counted individually for replacement so if for example s[left..right] = "aaa", and k = 2, we can only replace two of the letters.  (Also, note that the initial string s is never modified by any query.)

    + +

     

    +

    Example :

    + +
    +Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
    +Output: [true,false,false,true,true]
    +Explanation:
    +queries[0] : substring = "d", is palidrome.
    +queries[1] : substring = "bc", is not palidrome.
    +queries[2] : substring = "abcd", is not palidrome after replacing only 1 character.
    +queries[3] : substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
    +queries[4] : substring = "abcda", could be changed to "abcba" which is palidrome.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length, queries.length <= 10^5
    • +
    • 0 <= queries[i][0] <= queries[i][1] < s.length
    • +
    • 0 <= queries[i][2] <= s.length
    • +
    • s only contains lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md b/assets/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md new file mode 100644 index 00000000..27c75bcb --- /dev/null +++ b/assets/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md @@ -0,0 +1,66 @@ +# [1178. Number of Valid Words for Each Puzzle](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle) + + + +## Description + +With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: +
      +
    • word contains the first letter of puzzle.
    • +
    • For each letter in word, that letter is in puzzle.
      + For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage"; while invalid words are "beefed" (doesn't include "a") and "based" (includes "s" which isn't in the puzzle).
    • +
    +Return an array answer, where answer[i] is the number of words in the given word list words that are valid with respect to the puzzle puzzles[i]. +

     

    +

    Example :

    + +
    +Input: 
    +words = ["aaaa","asas","able","ability","actt","actor","access"], 
    +puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
    +Output: [1,1,3,2,4,0]
    +Explanation:
    +1 valid word for "aboveyz" : "aaaa" 
    +1 valid word for "abrodyz" : "aaaa"
    +3 valid words for "abslute" : "aaaa", "asas", "able"
    +2 valid words for "absoryz" : "aaaa", "asas"
    +4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
    +There're no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 10^5
    • +
    • 4 <= words[i].length <= 50
    • +
    • 1 <= puzzles.length <= 10^4
    • +
    • puzzles[i].length == 7
    • +
    • words[i][j], puzzles[i][j] are English lowercase letters.
    • +
    • Each puzzles[i] doesn't contain repeated characters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1179.Reformat Department Table/README_EN.md b/assets/1100-1199/1179.Reformat Department Table/README_EN.md new file mode 100644 index 00000000..5498f2a5 --- /dev/null +++ b/assets/1100-1199/1179.Reformat Department Table/README_EN.md @@ -0,0 +1,75 @@ +# [1179. Reformat Department Table](https://leetcode.com/problems/reformat-department-table) + + + +## Description + +

    Table: Department

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| revenue       | int     |
    +| month         | varchar |
    ++---------------+---------+
    +(id, month) is the primary key of this table.
    +The table has information about the revenue of each department per month.
    +The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].
    +
    + +

     

    + +

    Write an SQL query to reformat the table such that there is a department id column and a revenue column for each month.

    + +

    The query result format is in the following example:

    + +
    +Department table:
    ++------+---------+-------+
    +| id   | revenue | month |
    ++------+---------+-------+
    +| 1    | 8000    | Jan   |
    +| 2    | 9000    | Jan   |
    +| 3    | 10000   | Feb   |
    +| 1    | 7000    | Feb   |
    +| 1    | 6000    | Mar   |
    ++------+---------+-------+
    +
    +Result table:
    ++------+-------------+-------------+-------------+-----+-------------+
    +| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
    ++------+-------------+-------------+-------------+-----+-------------+
    +| 1    | 8000        | 7000        | 6000        | ... | null        |
    +| 2    | 9000        | null        | null        | ... | null        |
    +| 3    | null        | 10000       | null        | ... | null        |
    ++------+-------------+-------------+-------------+-----+-------------+
    +
    +Note that the result table has 13 columns (1 for the department id + 12 for the months).
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md b/assets/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md new file mode 100644 index 00000000..22cac2b6 --- /dev/null +++ b/assets/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md @@ -0,0 +1,61 @@ +# [1180. Count Substrings with Only One Distinct Letter](https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter) + + + +## Description + +

    Given a string S, return the number of substrings that have only one distinct letter.

    + +

     

    +

    Example 1:

    + +
    +Input: S = "aaaba"
    +Output: 8
    +Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
    +"aaa" occurs 1 time.
    +"aa" occurs 2 times.
    +"a" occurs 4 times.
    +"b" occurs 1 time.
    +So the answer is 1 + 2 + 4 + 1 = 8.
    +
    + +

    Example 2:

    + +
    +Input: S = "aaaaaaaaaa"
    +Output: 55
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= S.length <= 1000
    • +
    • S[i] consists of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1181.Before and After Puzzle/README_EN.md b/assets/1100-1199/1181.Before and After Puzzle/README_EN.md new file mode 100644 index 00000000..eccfa773 --- /dev/null +++ b/assets/1100-1199/1181.Before and After Puzzle/README_EN.md @@ -0,0 +1,129 @@ +# [1181. Before and After Puzzle](https://leetcode.com/problems/before-and-after-puzzle) + + + +## Description + +

    Given a list of phrases, generate a list of Before and After puzzles.

    + +

    A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.

    + +

    Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase.

    + +

    Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j. Note that the order of matching two phrases matters, we want to consider both orders.

    + +

    You should return a list of distinct strings sorted lexicographically.

    + +

     

    +

    Example 1:

    + +
    +Input: phrases = ["writing code","code rocks"]
    +Output: ["writing code rocks"]
    +
    + +

    Example 2:

    + +
    +Input: phrases = ["mission statement",
    +                  "a quick bite to eat",
    +                  "a chip off the old block",
    +                  "chocolate bar",
    +                  "mission impossible",
    +                  "a man on a mission",
    +                  "block party",
    +                  "eat my words",
    +                  "bar of soap"]
    +Output: ["a chip off the old block party",
    +         "a man on a mission impossible",
    +         "a man on a mission statement",
    +         "a quick bite to eat my words",
    +         "chocolate bar of soap"]
    +
    + +

    Example 3:

    + +
    +Input: phrases = ["a","b","a"]
    +Output: ["a"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= phrases.length <= 100
    • +
    • 1 <= phrases[i].length <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]: + same_first_word = collections.defaultdict(set) + for i, phrase in enumerate(phrases): + same_first_word[phrase.split()[0]].add(i) + res = set() + for i, phrase in enumerate(phrases): + words = phrase.split() + last_word = words[-1] + if last_word in same_first_word: + for j in same_first_word[last_word]: + if i != j: + res.add(' '.join(words[:-1] + phrases[j].split())) + return sorted(list(res)) +``` + +### **Java** + +```java +class Solution { + public List beforeAndAfterPuzzles(String[] phrases) { + Map> sameFirstWord = new HashMap<>(); + for (int i = 0; i < phrases.length; ++i) { + String phrase = phrases[i]; + String word = phrase.split(" ")[0]; + if (!sameFirstWord.containsKey(word)) { + sameFirstWord.put(word, new HashSet<>()); + } + sameFirstWord.get(word).add(i); + } + Set res = new HashSet<>(); + for (int i = 0; i < phrases.length; ++i) { + String phrase = phrases[i]; + String[] words = phrase.split(" "); + String lastWord = words[words.length - 1]; + if (sameFirstWord.containsKey(lastWord)) { + for (int j : sameFirstWord.get(lastWord)) { + if (i != j) { + List t = new ArrayList<>(); + for (int k = 0; k < words.length - 1; ++k) { + t.add(words[k]); + } + for (String word : phrases[j].split(" ")) { + t.add(word); + } + res.add(String.join(" ", t)); + } + } + } + } + List output = new ArrayList<>(res); + Collections.sort(output); + return output; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1182.Shortest Distance to Target Color/README_EN.md b/assets/1100-1199/1182.Shortest Distance to Target Color/README_EN.md new file mode 100644 index 00000000..a2d95a37 --- /dev/null +++ b/assets/1100-1199/1182.Shortest Distance to Target Color/README_EN.md @@ -0,0 +1,130 @@ +# [1182. Shortest Distance to Target Color](https://leetcode.com/problems/shortest-distance-to-target-color) + + + +## Description + +

    You are given an array colors, in which there are three colors: 1, 2 and 3.

    + +

    You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
    +Output: [3,0,3]
    +Explanation: 
    +The nearest 3 from index 1 is at index 4 (3 steps away).
    +The nearest 2 from index 2 is at index 2 itself (0 steps away).
    +The nearest 1 from index 6 is at index 3 (3 steps away).
    +
    + +

    Example 2:

    + +
    +Input: colors = [1,2], queries = [[0,3]]
    +Output: [-1]
    +Explanation: There is no 3 in the array.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= colors.length <= 5*10^4
    • +
    • 1 <= colors[i] <= 3
    • +
    • 1 <= queries.length <= 5*10^4
    • +
    • queries[i].length == 2
    • +
    • 0 <= queries[i][0] < colors.length
    • +
    • 1 <= queries[i][1] <= 3
    • +
    + + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def shortestDistanceColor(self, colors: List[int], queries: List[List[int]]) -> List[int]: + color_indexes = collections.defaultdict(list) + for i, c in enumerate(colors): + color_indexes[c].append(i) + res = [] + for i, c in queries: + if c not in color_indexes: + res.append(-1) + else: + t = color_indexes[c] + left, right = 0, len(t) - 1 + while left < right: + mid = (left + right) >> 1 + if t[mid] >= i: + right = mid + else: + left = mid + 1 + val = abs(t[left] - i) + if left > 0: + val = min(val, abs(t[left - 1] - i)) + if left < len(t) - 1: + val = min(val, abs(t[left + 1] - i)) + res.append(val) + return res +``` + +### **Java** + +```java +class Solution { + public List shortestDistanceColor(int[] colors, int[][] queries) { + Map> colorIndexes = new HashMap<>(); + for (int i = 0; i < colors.length; ++i) { + int c = colors[i]; + if (!colorIndexes.containsKey(c)) { + colorIndexes.put(c, new ArrayList<>()); + } + colorIndexes.get(c).add(i); + } + List res = new ArrayList<>(); + for (int[] query : queries) { + int i = query[0], c = query[1]; + if (!colorIndexes.containsKey(c)) { + res.add(-1); + continue; + } + List t = colorIndexes.get(c); + int left = 0, right = t.size() - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (t.get(mid) >= i) { + right = mid; + } else { + left = mid + 1; + } + } + int val = Math.abs(t.get(left) - i); + if (left > 0) { + val = Math.min(val, Math.abs(t.get(left - 1) - i)); + } + if (left < t.size() - 1) { + val = Math.min(val, Math.abs(t.get(left + 1) - i)); + } + res.add(val); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1183.Maximum Number of Ones/README_EN.md b/assets/1100-1199/1183.Maximum Number of Ones/README_EN.md new file mode 100644 index 00000000..916a8478 --- /dev/null +++ b/assets/1100-1199/1183.Maximum Number of Ones/README_EN.md @@ -0,0 +1,68 @@ +# [1183. Maximum Number of Ones](https://leetcode.com/problems/maximum-number-of-ones) + + + +## Description + +

    Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones.

    + +

    Return the maximum possible number of ones that the matrix M can have.

    + +

     

    +

    Example 1:

    + +
    +Input: width = 3, height = 3, sideLength = 2, maxOnes = 1
    +Output: 4
    +Explanation:
    +In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one.
    +The best solution that has 4 ones is:
    +[1,0,1]
    +[0,0,0]
    +[1,0,1]
    +
    + +

    Example 2:

    + +
    +Input: width = 3, height = 3, sideLength = 2, maxOnes = 2
    +Output: 6
    +Explanation:
    +[1,0,1]
    +[1,0,1]
    +[1,0,1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= width, height <= 100
    • +
    • 1 <= sideLength <= width, height
    • +
    • 0 <= maxOnes <= sideLength * sideLength
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1184.Distance Between Bus Stops/README_EN.md b/assets/1100-1199/1184.Distance Between Bus Stops/README_EN.md new file mode 100644 index 00000000..8255397d --- /dev/null +++ b/assets/1100-1199/1184.Distance Between Bus Stops/README_EN.md @@ -0,0 +1,122 @@ +# [1184. Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops) + + + +## Description + +

    A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.

    + + + +

    The bus goes along both directions i.e. clockwise and counterclockwise.

    + + + +

    Return the shortest distance between the given start and destination stops.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: distance = [1,2,3,4], start = 0, destination = 1
    +
    +Output: 1
    +
    +Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
    + + + +

     

    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: distance = [1,2,3,4], start = 0, destination = 2
    +
    +Output: 3
    +
    +Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
    +
    +
    + + + +

     

    + + + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: distance = [1,2,3,4], start = 0, destination = 3
    +
    +Output: 4
    +
    +Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^4
    • +
    • distance.length == n
    • +
    • 0 <= start, destination < n
    • +
    • 0 <= distance[i] <= 10^4
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1-1.jpg b/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1-1.jpg new file mode 100644 index 00000000..7752c919 Binary files /dev/null and b/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1-1.jpg differ diff --git a/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1-2.jpg b/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1-2.jpg new file mode 100644 index 00000000..af2510c6 Binary files /dev/null and b/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1-2.jpg differ diff --git a/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1.jpg b/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1.jpg new file mode 100644 index 00000000..247389e9 Binary files /dev/null and b/assets/1100-1199/1184.Distance Between Bus Stops/images/untitled-diagram-1.jpg differ diff --git a/assets/1100-1199/1185.Day of the Week/README_EN.md b/assets/1100-1199/1185.Day of the Week/README_EN.md new file mode 100644 index 00000000..e3025c70 --- /dev/null +++ b/assets/1100-1199/1185.Day of the Week/README_EN.md @@ -0,0 +1,65 @@ +# [1185. Day of the Week](https://leetcode.com/problems/day-of-the-week) + + + +## Description + +

    Given a date, return the corresponding day of the week for that date.

    + +

    The input is given as three integers representing the day, month and year respectively.

    + +

    Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.

    + +

     

    +

    Example 1:

    + +
    +Input: day = 31, month = 8, year = 2019
    +Output: "Saturday"
    +
    + +

    Example 2:

    + +
    +Input: day = 18, month = 7, year = 1999
    +Output: "Sunday"
    +
    + +

    Example 3:

    + +
    +Input: day = 15, month = 8, year = 1993
    +Output: "Sunday"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The given dates are valid dates between the years 1971 and 2100.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md b/assets/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md new file mode 100644 index 00000000..2bb84224 --- /dev/null +++ b/assets/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md @@ -0,0 +1,66 @@ +# [1186. Maximum Subarray Sum with One Deletion](https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion) + + + +## Description + +

    Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.

    + +

    Note that the subarray needs to be non-empty after deleting one element.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,-2,0,3]
    +Output: 4
    +Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
    + +

    Example 2:

    + +
    +Input: arr = [1,-2,-2,3]
    +Output: 3
    +Explanation: We just choose [3] and it's the maximum sum.
    +
    + +

    Example 3:

    + +
    +Input: arr = [-1,-1,-1,-1]
    +Output: -1
    +Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • -104 <= arr[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1187.Make Array Strictly Increasing/README_EN.md b/assets/1100-1199/1187.Make Array Strictly Increasing/README_EN.md new file mode 100644 index 00000000..fd8cb3b2 --- /dev/null +++ b/assets/1100-1199/1187.Make Array Strictly Increasing/README_EN.md @@ -0,0 +1,104 @@ +# [1187. Make Array Strictly Increasing](https://leetcode.com/problems/make-array-strictly-increasing) + + + +## Description + +

    Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.

    + + + +

    In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].

    + + + +

    If there is no way to make arr1 strictly increasing, return -1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
    +
    +Output: 1
    +
    +Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
    +
    +Output: 2
    +
    +Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
    +
    +Output: -1
    +
    +Explanation: You can't make arr1 strictly increasing.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr1.length, arr2.length <= 2000
    • +
    • 0 <= arr1[i], arr2[i] <= 10^9
    • +
    + + + +

     

    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md b/assets/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md new file mode 100644 index 00000000..327134af --- /dev/null +++ b/assets/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md @@ -0,0 +1,102 @@ +# [1188. Design Bounded Blocking Queue](https://leetcode.com/problems/design-bounded-blocking-queue) + + + +## Description + +

    Implement a thread-safe bounded blocking queue that has the following methods:

    + +
      +
    • BoundedBlockingQueue(int capacity) The constructor initializes the queue with a maximum capacity.
    • +
    • void enqueue(int element) Adds an element to the front of the queue. If the queue is full, the calling thread is blocked until the queue is no longer full.
    • +
    • int dequeue() Returns the element at the rear of the queue and removes it. If the queue is empty, the calling thread is blocked until the queue is no longer empty.
    • +
    • int size() Returns the number of elements currently in the queue.
    • +
    + +

    Your implementation will be tested using multiple threads at the same time. Each thread will either be a producer thread that only makes calls to the enqueue method or a consumer thread that only makes calls to the dequeue method. The size method will be called after every test case.

    + +

    Please do not use built-in implementations of bounded blocking queue as this will not be accepted in an interview.

    + +

     

    +

    Example 1:

    + +
    +Input:
    +1
    +1
    +["BoundedBlockingQueue","enqueue","dequeue","dequeue","enqueue","enqueue","enqueue","enqueue","dequeue"]
    +[[2],[1],[],[],[0],[2],[3],[4],[]]
    +
    +Output:
    +[1,0,2,2]
    +
    +Explanation:
    +Number of producer threads = 1
    +Number of consumer threads = 1
    +
    +BoundedBlockingQueue queue = new BoundedBlockingQueue(2);   // initialize the queue with capacity = 2.
    +
    +queue.enqueue(1);   // The producer thread enqueues 1 to the queue.
    +queue.dequeue();    // The consumer thread calls dequeue and returns 1 from the queue.
    +queue.dequeue();    // Since the queue is empty, the consumer thread is blocked.
    +queue.enqueue(0);   // The producer thread enqueues 0 to the queue. The consumer thread is unblocked and returns 0 from the queue.
    +queue.enqueue(2);   // The producer thread enqueues 2 to the queue.
    +queue.enqueue(3);   // The producer thread enqueues 3 to the queue.
    +queue.enqueue(4);   // The producer thread is blocked because the queue's capacity (2) is reached.
    +queue.dequeue();    // The consumer thread returns 2 from the queue. The producer thread is unblocked and enqueues 4 to the queue.
    +queue.size();       // 2 elements remaining in the queue. size() is always called at the end of each test case.
    +
    + +

    Example 2:

    + +
    +Input:
    +3
    +4
    +["BoundedBlockingQueue","enqueue","enqueue","enqueue","dequeue","dequeue","dequeue","enqueue"]
    +[[3],[1],[0],[2],[],[],[],[3]]
    +Output:
    +[1,0,2,1]
    +
    +Explanation:
    +Number of producer threads = 3
    +Number of consumer threads = 4
    +
    +BoundedBlockingQueue queue = new BoundedBlockingQueue(3);   // initialize the queue with capacity = 3.
    +
    +queue.enqueue(1);   // Producer thread P1 enqueues 1 to the queue.
    +queue.enqueue(0);   // Producer thread P2 enqueues 0 to the queue.
    +queue.enqueue(2);   // Producer thread P3 enqueues 2 to the queue.
    +queue.dequeue();    // Consumer thread C1 calls dequeue.
    +queue.dequeue();    // Consumer thread C2 calls dequeue.
    +queue.dequeue();    // Consumer thread C3 calls dequeue.
    +queue.enqueue(3);   // One of the producer threads enqueues 3 to the queue.
    +queue.size();       // 1 element remaining in the queue.
    +
    +Since the number of threads for producer/consumer is greater than 1, we do not know how the threads will be scheduled in the operating system, even though the input seems to imply the ordering. Therefore, any of the output [1,0,2] or [1,2,0] or [0,1,2] or [0,2,1] or [2,0,1] or [2,1,0] will be accepted.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= Number of Prdoucers <= 8
    • +
    • 1 <= Number of Consumers <= 8
    • +
    • 1 <= size <= 30
    • +
    • 0 <= element <= 20
    • +
    • The number of calls to enqueue is greater than or equal to the number of calls to dequeue.
    • +
    • At most 40 calls will be made to enque, deque, and size.
    • +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1189.Maximum Number of Balloons/README_EN.md b/assets/1100-1199/1189.Maximum Number of Balloons/README_EN.md new file mode 100644 index 00000000..aa389342 --- /dev/null +++ b/assets/1100-1199/1189.Maximum Number of Balloons/README_EN.md @@ -0,0 +1,68 @@ +# [1189. Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons) + + + +## Description + +

    Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.

    + +

    You can use each character in text at most once. Return the maximum number of instances that can be formed.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: text = "nlaebolko"
    +Output: 1
    +
    + +

    Example 2:

    + +

    + +
    +Input: text = "loonbalxballpoon"
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: text = "leetcode"
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 104
    • +
    • text consists of lower case English letters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1189.Maximum Number of Balloons/images/1536_ex1_upd.jpeg b/assets/1100-1199/1189.Maximum Number of Balloons/images/1536_ex1_upd.jpeg new file mode 100644 index 00000000..6d34e3be Binary files /dev/null and b/assets/1100-1199/1189.Maximum Number of Balloons/images/1536_ex1_upd.jpeg differ diff --git a/assets/1100-1199/1189.Maximum Number of Balloons/images/1536_ex2_upd.jpeg b/assets/1100-1199/1189.Maximum Number of Balloons/images/1536_ex2_upd.jpeg new file mode 100644 index 00000000..7043c118 Binary files /dev/null and b/assets/1100-1199/1189.Maximum Number of Balloons/images/1536_ex2_upd.jpeg differ diff --git a/assets/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md b/assets/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md new file mode 100644 index 00000000..6835467d --- /dev/null +++ b/assets/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md @@ -0,0 +1,151 @@ +# [1190. Reverse Substrings Between Each Pair of Parentheses](https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses) + + + +## Description + +

    You are given a string s that consists of lower case English letters and brackets. 

    + +

    Reverse the strings in each pair of matching parentheses, starting from the innermost one.

    + +

    Your result should not contain any brackets.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "(abcd)"
    +Output: "dcba"
    +
    + +

    Example 2:

    + +
    +Input: s = "(u(love)i)"
    +Output: "iloveu"
    +Explanation: The substring "love" is reversed first, then the whole string is reversed.
    +
    + +

    Example 3:

    + +
    +Input: s = "(ed(et(oc))el)"
    +Output: "leetcode"
    +Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
    +
    + +

    Example 4:

    + +
    +Input: s = "a(bcdefghijkl(mno)p)q"
    +Output: "apmnolkjihgfedcbq"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= s.length <= 2000
    • +
    • s only contains lower case English characters and parentheses.
    • +
    • It's guaranteed that all parentheses are balanced.
    • +
    + + +## Solutions + +Use deque or stack to simulate the reversal process. + + + +### **Python3** + +```python +class Solution: + def reverseParentheses(self, s: str) -> str: + stack = [] + for c in s: + if c == ")": + tmp = [] + while stack[-1] != "(": + tmp += stack.pop() + stack.pop() + stack += tmp + else: + stack.append(c) + return "".join(stack) +``` + +### **Java** + +```java +class Solution { + public String reverseParentheses(String s) { + Deque deque = new ArrayDeque<>(); + for (char c : s.toCharArray()) { + if (c == ')') { + StringBuilder sb = new StringBuilder(); + while (deque.peekLast() != '(') { + sb.append(deque.pollLast()); + } + deque.pollLast(); + for (int i = 0, n = sb.length(); i < n; i++) { + deque.offerLast(sb.charAt(i)); + } + } else { + deque.offerLast(c); + } + } + StringBuilder sb = new StringBuilder(); + while (!deque.isEmpty()) { + sb.append(deque.pollFirst()); + } + return sb.toString(); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {string} + */ +var reverseParentheses = function(s) { + let stack = []; + let hashMap = {}; + const n = s.length; + for (let i = 0; i < n; i++) { + let cur = s.charAt(i); + if (cur == '(') { + stack.push(i); + } else if (cur == ')') { + let left = stack.pop(); + hashMap[left] = i; + hashMap[i] = left; + } + } + let res = []; + let i = 0; + let step = 1; // 1向右,-1向左 + while (i > -1 && i < n) { + let cur = s.charAt(i); + if (cur == '(' || cur == ')') { + step = -step; + i = hashMap[i]; + } else { + res.push(cur); + } + i += step; + } + return res.join(''); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md b/assets/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md new file mode 100644 index 00000000..f20032e8 --- /dev/null +++ b/assets/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md @@ -0,0 +1,69 @@ +# [1191. K-Concatenation Maximum Sum](https://leetcode.com/problems/k-concatenation-maximum-sum) + + + +## Description + +

    Given an integer array arr and an integer k, modify the array by repeating it k times.

    + +

    For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].

    + +

    Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.

    + +

    As the answer can be very large, return the answer modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2], k = 3
    +Output: 9
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,-2,1], k = 5
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: arr = [-1,-2], k = 7
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • 1 <= k <= 105
    • +
    • -104 <= arr[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1192.Critical Connections in a Network/README_EN.md b/assets/1100-1199/1192.Critical Connections in a Network/README_EN.md new file mode 100644 index 00000000..81e1454d --- /dev/null +++ b/assets/1100-1199/1192.Critical Connections in a Network/README_EN.md @@ -0,0 +1,57 @@ +# [1192. Critical Connections in a Network](https://leetcode.com/problems/critical-connections-in-a-network) + + + +## Description + +

    There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a network where connections[i] = [a, b] represents a connection between servers a and b. Any server can reach any other server directly or indirectly through the network.

    + +

    A critical connection is a connection that, if removed, will make some server unable to reach some other server.

    + +

    Return all critical connections in the network in any order.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
    +Output: [[1,3]]
    +Explanation: [[3,1]] is also accepted.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • n-1 <= connections.length <= 10^5
    • +
    • connections[i][0] != connections[i][1]
    • +
    • There are no repeated connections.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1192.Critical Connections in a Network/images/1537_ex1_2.png b/assets/1100-1199/1192.Critical Connections in a Network/images/1537_ex1_2.png new file mode 100644 index 00000000..2265ae3b Binary files /dev/null and b/assets/1100-1199/1192.Critical Connections in a Network/images/1537_ex1_2.png differ diff --git a/assets/1100-1199/1192.Critical Connections in a Network/images/critical-connections-in-a-network.png b/assets/1100-1199/1192.Critical Connections in a Network/images/critical-connections-in-a-network.png new file mode 100644 index 00000000..143377c5 Binary files /dev/null and b/assets/1100-1199/1192.Critical Connections in a Network/images/critical-connections-in-a-network.png differ diff --git a/assets/1100-1199/1193.Monthly Transactions I/README_EN.md b/assets/1100-1199/1193.Monthly Transactions I/README_EN.md new file mode 100644 index 00000000..e0fdd5ad --- /dev/null +++ b/assets/1100-1199/1193.Monthly Transactions I/README_EN.md @@ -0,0 +1,62 @@ +# [1193. Monthly Transactions I](https://leetcode.com/problems/monthly-transactions-i) + + + +## Description + +

    Table: Transactions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| country       | varchar |
    +| state         | enum    |
    +| amount        | int     |
    +| trans_date    | date    |
    ++---------------+---------+
    +id is the primary key of this table.
    +The table has information about incoming transactions.
    +The state column is an enum of type ["approved", "declined"].
    +
    + +

     

    + +

    Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount.

    + +

    The query result format is in the following example:

    + +
    +Transactions table:
    ++------+---------+----------+--------+------------+
    +| id   | country | state    | amount | trans_date |
    ++------+---------+----------+--------+------------+
    +| 121  | US      | approved | 1000   | 2018-12-18 |
    +| 122  | US      | declined | 2000   | 2018-12-19 |
    +| 123  | US      | approved | 2000   | 2019-01-01 |
    +| 124  | DE      | approved | 2000   | 2019-01-07 |
    ++------+---------+----------+--------+------------+
    +
    +Result table:
    ++----------+---------+-------------+----------------+--------------------+-----------------------+
    +| month    | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
    ++----------+---------+-------------+----------------+--------------------+-----------------------+
    +| 2018-12  | US      | 2           | 1              | 3000               | 1000                  |
    +| 2019-01  | US      | 1           | 1              | 2000               | 2000                  |
    +| 2019-01  | DE      | 1           | 1              | 2000               | 2000                  |
    ++----------+---------+-------------+----------------+--------------------+-----------------------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1194.Tournament Winners/README_EN.md b/assets/1100-1199/1194.Tournament Winners/README_EN.md new file mode 100644 index 00000000..bcd76194 --- /dev/null +++ b/assets/1100-1199/1194.Tournament Winners/README_EN.md @@ -0,0 +1,94 @@ +# [1194. Tournament Winners](https://leetcode.com/problems/tournament-winners) + + + +## Description + +

    Table: Players

    + +
    ++-------------+-------+
    +| Column Name | Type  |
    ++-------------+-------+
    +| player_id   | int   |
    +| group_id    | int   |
    ++-------------+-------+
    +player_id is the primary key of this table.
    +Each row of this table indicates the group of each player.
    +
    + +

    Table: Matches

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| match_id      | int     |
    +| first_player  | int     |
    +| second_player | int     | 
    +| first_score   | int     |
    +| second_score  | int     |
    ++---------------+---------+
    +match_id is the primary key of this table.
    +Each row is a record of a match, first_player and second_player contain the player_id of each match.
    +first_score and second_score contain the number of points of the first_player and second_player respectively.
    +You may assume that, in each match, players belongs to the same group.
    +
    + +

     

    + +

    The winner in each group is the player who scored the maximum total points within the group. In the case of a tie, the lowest player_id wins.

    + +

    Write an SQL query to find the winner in each group.

    + +

    The query result format is in the following example:

    + +
    +Players table:
    ++-----------+------------+
    +| player_id | group_id   |
    ++-----------+------------+
    +| 15        | 1          |
    +| 25        | 1          |
    +| 30        | 1          |
    +| 45        | 1          |
    +| 10        | 2          |
    +| 35        | 2          |
    +| 50        | 2          |
    +| 20        | 3          |
    +| 40        | 3          |
    ++-----------+------------+
    +
    +Matches table:
    ++------------+--------------+---------------+-------------+--------------+
    +| match_id   | first_player | second_player | first_score | second_score |
    ++------------+--------------+---------------+-------------+--------------+
    +| 1          | 15           | 45            | 3           | 0            |
    +| 2          | 30           | 25            | 1           | 2            |
    +| 3          | 30           | 15            | 2           | 0            |
    +| 4          | 40           | 20            | 5           | 2            |
    +| 5          | 35           | 50            | 1           | 1            |
    ++------------+--------------+---------------+-------------+--------------+
    +
    +Result table:
    ++-----------+------------+
    +| group_id  | player_id  |
    ++-----------+------------+ 
    +| 1         | 15         |
    +| 2         | 35         |
    +| 3         | 40         |
    ++-----------+------------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md b/assets/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md new file mode 100644 index 00000000..a6df3d0b --- /dev/null +++ b/assets/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md @@ -0,0 +1,60 @@ +# [1195. Fizz Buzz Multithreaded](https://leetcode.com/problems/fizz-buzz-multithreaded) + + + +## Description + +

    Write a program that outputs the string representation of numbers from 1 to n, however:

    + +
      +
    • If the number is divisible by 3, output "fizz".
    • +
    • If the number is divisible by 5, output "buzz".
    • +
    • If the number is divisible by both 3 and 5, output "fizzbuzz".
    • +
    + +

    For example, for n = 15, we output: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz.

    + +

    Suppose you are given the following code:

    + +
    +class FizzBuzz {
    +  public FizzBuzz(int n) { ... }               // constructor
    +  public void fizz(printFizz) { ... }          // only output "fizz"
    +  public void buzz(printBuzz) { ... }          // only output "buzz"
    +  public void fizzbuzz(printFizzBuzz) { ... }  // only output "fizzbuzz"
    +  public void number(printNumber) { ... }      // only output the numbers
    +}
    + +

    Implement a multithreaded version of FizzBuzz with four threads. The same instance of FizzBuzz will be passed to four different threads:

    + +
      +
    1. Thread A will call fizz() to check for divisibility of 3 and outputs fizz.
    2. +
    3. Thread B will call buzz() to check for divisibility of 5 and outputs buzz.
    4. +
    5. Thread C will call fizzbuzz() to check for divisibility of 3 and 5 and outputs fizzbuzz.
    6. +
    7. Thread D will call number() which should only output the numbers.
    8. +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md b/assets/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md new file mode 100644 index 00000000..3eabd603 --- /dev/null +++ b/assets/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md @@ -0,0 +1,59 @@ +# [1196. How Many Apples Can You Put into the Basket](https://leetcode.com/problems/how-many-apples-can-you-put-into-the-basket) + + + +## Description + +

    You have some apples, where arr[i] is the weight of the i-th apple.  You also have a basket that can carry up to 5000 units of weight.

    + +

    Return the maximum number of apples you can put in the basket.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [100,200,150,1000]
    +Output: 4
    +Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.
    +
    + +

    Example 2:

    + +
    +Input: arr = [900,950,800,1000,700,800]
    +Output: 5
    +Explanation: The sum of weights of the 6 apples exceeds 5000 so we choose any 5 of them.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 10^3
    • +
    • 1 <= arr[i] <= 10^3
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1197.Minimum Knight Moves/README_EN.md b/assets/1100-1199/1197.Minimum Knight Moves/README_EN.md new file mode 100644 index 00000000..b261c477 --- /dev/null +++ b/assets/1100-1199/1197.Minimum Knight Moves/README_EN.md @@ -0,0 +1,62 @@ +# [1197. Minimum Knight Moves](https://leetcode.com/problems/minimum-knight-moves) + + + +## Description + +

    In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].

    + +

    A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

    + +

    + +

    Return the minimum number of steps needed to move the knight to the square [x, y].  It is guaranteed the answer exists.

    + +

     

    +

    Example 1:

    + +
    +Input: x = 2, y = 1
    +Output: 1
    +Explanation: [0, 0] → [2, 1]
    +
    + +

    Example 2:

    + +
    +Input: x = 5, y = 5
    +Output: 4
    +Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • |x| + |y| <= 300
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1197.Minimum Knight Moves/images/knight.png b/assets/1100-1199/1197.Minimum Knight Moves/images/knight.png new file mode 100644 index 00000000..1ab55680 Binary files /dev/null and b/assets/1100-1199/1197.Minimum Knight Moves/images/knight.png differ diff --git a/assets/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md b/assets/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md new file mode 100644 index 00000000..9249f6c1 --- /dev/null +++ b/assets/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md @@ -0,0 +1,80 @@ +# [1198. Find Smallest Common Element in All Rows](https://leetcode.com/problems/find-smallest-common-element-in-all-rows) + + + +## Description + +

    Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows.

    + +

    If there is no common element, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
    +Output: 5
    +
    + +

    Example 2:

    + +
    +Input: mat = [[1,2,3],[2,3,4],[2,3,5]]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • 1 <= mat[i][j] <= 104
    • +
    • mat[i] is sorted in strictly increasing order.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def smallestCommonElement(self, mat: List[List[int]]) -> int: + counter = collections.Counter() + for row in mat: + for num in row: + counter[num] += 1 + if counter[num] == len(mat): + return num + return -1 +``` + +### **Java** + +```java +class Solution { + public int smallestCommonElement(int[][] mat) { + int[] counter = new int[10001]; + for (int[] row : mat) { + for (int num : row) { + ++counter[num]; + if (counter[num] == mat.length) { + return num; + } + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md b/assets/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md new file mode 100644 index 00000000..19e8de7e --- /dev/null +++ b/assets/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md @@ -0,0 +1,76 @@ +# [1199. Minimum Time to Build Blocks](https://leetcode.com/problems/minimum-time-to-build-blocks) + + + +## Description + +

    You are given a list of blocks, where blocks[i] = t means that the i-th block needs t units of time to be built. A block can only be built by exactly one worker.

    + +

    A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.

    + +

    The time cost of spliting one worker into two workers is given as an integer split. Note that if two workers split at the same time, they split in parallel so the cost would be split.

    + +

    Output the minimum time needed to build all blocks.

    + +

    Initially, there is only one worker.

    + +

     

    +

    Example 1:

    + +
    +Input: blocks = [1], split = 1
    +Output: 1
    +Explanation: We use 1 worker to build 1 block in 1 time unit.
    +
    + +

    Example 2:

    + +
    +Input: blocks = [1,2], split = 5
    +Output: 7
    +Explanation: We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7.
    +
    + +

    Example 3:

    + +
    +Input: blocks = [1,2,3], split = 1
    +Output: 4
    +Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
    +Then, use the two unassigned workers to build the first two blocks.
    +The cost is 1 + max(3, 1 + max(1, 2)) = 4.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= blocks.length <= 1000
    • +
    • 1 <= blocks[i] <= 10^5
    • +
    • 1 <= split <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1200.Minimum Absolute Difference/README_EN.md b/assets/1200-1299/1200.Minimum Absolute Difference/README_EN.md new file mode 100644 index 00000000..60c039ae --- /dev/null +++ b/assets/1200-1299/1200.Minimum Absolute Difference/README_EN.md @@ -0,0 +1,70 @@ +# [1200. Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference) + + + +## Description + +

    Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. 

    + +

    Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

    + +
      +
    • a, b are from arr
    • +
    • a < b
    • +
    • b - a equals to the minimum absolute difference of any two elements in arr
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: arr = [4,2,1,3]
    +Output: [[1,2],[2,3],[3,4]]
    +Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
    + +

    Example 2:

    + +
    +Input: arr = [1,3,6,10,15]
    +Output: [[1,3]]
    +
    + +

    Example 3:

    + +
    +Input: arr = [3,8,-10,23,19,-4,-14,27]
    +Output: [[-14,-10],[19,23],[23,27]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr.length <= 10^5
    • +
    • -10^6 <= arr[i] <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1201.Ugly Number III/README_EN.md b/assets/1200-1299/1201.Ugly Number III/README_EN.md new file mode 100644 index 00000000..acabb9d6 --- /dev/null +++ b/assets/1200-1299/1201.Ugly Number III/README_EN.md @@ -0,0 +1,75 @@ +# [1201. Ugly Number III](https://leetcode.com/problems/ugly-number-iii) + + + +## Description + +

    An ugly number is a positive integer that is divisible by a, b, or c.

    + +

    Given four integers n, a, b, and c, return the nth ugly number.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, a = 2, b = 3, c = 5
    +Output: 4
    +Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
    +
    + +

    Example 2:

    + +
    +Input: n = 4, a = 2, b = 3, c = 4
    +Output: 6
    +Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.
    +
    + +

    Example 3:

    + +
    +Input: n = 5, a = 2, b = 11, c = 13
    +Output: 10
    +Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.
    +
    + +

    Example 4:

    + +
    +Input: n = 1000000000, a = 2, b = 217983653, c = 336916467
    +Output: 1999999984
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n, a, b, c <= 109
    • +
    • 1 <= a * b * c <= 1018
    • +
    • It is guaranteed that the result will be in range [1, 2 * 109].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1202.Smallest String With Swaps/README_EN.md b/assets/1200-1299/1202.Smallest String With Swaps/README_EN.md new file mode 100644 index 00000000..0d9102d0 --- /dev/null +++ b/assets/1200-1299/1202.Smallest String With Swaps/README_EN.md @@ -0,0 +1,78 @@ +# [1202. Smallest String With Swaps](https://leetcode.com/problems/smallest-string-with-swaps) + + + +## Description + +

    You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

    + +

    You can swap the characters at any pair of indices in the given pairs any number of times.

    + +

    Return the lexicographically smallest string that s can be changed to after using the swaps.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "dcab", pairs = [[0,3],[1,2]]
    +Output: "bacd"
    +Explaination: 
    +Swap s[0] and s[3], s = "bcad"
    +Swap s[1] and s[2], s = "bacd"
    +
    + +

    Example 2:

    + +
    +Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
    +Output: "abcd"
    +Explaination: 
    +Swap s[0] and s[3], s = "bcad"
    +Swap s[0] and s[2], s = "acbd"
    +Swap s[1] and s[2], s = "abcd"
    + +

    Example 3:

    + +
    +Input: s = "cba", pairs = [[0,1],[1,2]]
    +Output: "abc"
    +Explaination: 
    +Swap s[0] and s[1], s = "bca"
    +Swap s[1] and s[2], s = "bac"
    +Swap s[0] and s[1], s = "abc"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • 0 <= pairs.length <= 10^5
    • +
    • 0 <= pairs[i][0], pairs[i][1] < s.length
    • +
    • s only contains lower case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md b/assets/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md new file mode 100644 index 00000000..443f15f3 --- /dev/null +++ b/assets/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md @@ -0,0 +1,72 @@ +# [1203. Sort Items by Groups Respecting Dependencies](https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies) + + + +## Description + +

    There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.

    + +

    Return a sorted list of the items such that:

    + +
      +
    • The items that belong to the same group are next to each other in the sorted list.
    • +
    • There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).
    • +
    + +

    Return any solution if there is more than one solution and return an empty list if there is no solution.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
    +Output: [6,3,4,1,5,2,0,7]
    +
    + +

    Example 2:

    + +
    +Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
    +Output: []
    +Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= m <= n <= 3 * 104
    • +
    • group.length == beforeItems.length == n
    • +
    • -1 <= group[i] <= m - 1
    • +
    • 0 <= beforeItems[i].length <= n - 1
    • +
    • 0 <= beforeItems[i][j] <= n - 1
    • +
    • i != beforeItems[i][j]
    • +
    • beforeItems[i] does not contain duplicates elements.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1203.Sort Items by Groups Respecting Dependencies/images/1359_ex1.png b/assets/1200-1299/1203.Sort Items by Groups Respecting Dependencies/images/1359_ex1.png new file mode 100644 index 00000000..60ec6fec Binary files /dev/null and b/assets/1200-1299/1203.Sort Items by Groups Respecting Dependencies/images/1359_ex1.png differ diff --git a/assets/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md b/assets/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md new file mode 100644 index 00000000..b189b397 --- /dev/null +++ b/assets/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md @@ -0,0 +1,137 @@ +# [1204. Last Person to Fit in the Bus](https://leetcode.com/problems/last-person-to-fit-in-the-bus) + + + +## Description + +

    Table: Queue

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| person_id   | int     |
    +
    +| person_name | varchar |
    +
    +| weight      | int     |
    +
    +| turn        | int     |
    +
    ++-------------+---------+
    +
    +person_id is the primary key column for this table.
    +
    +This table has the information about all people waiting for a bus.
    +
    +The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
    +
    +turn determines the order of which the people will board the bus, where turn=1 denotes the first person to board and turn=n denotes the last person to board.
    +
    +weight is the weight of the person in kilograms.
    +
    +
    + + + +

     

    + + + +

    There is a queue of people waiting to board a bus. However, the bus has a weight limit of 1000 kilograms, so there may be some people who cannot board.

    + + + +

    Write an SQL query to find the person_name of the last person that can fit on the bus without exceeding the weight limit. The testcases are generated such that the first person does not exceed the weight limit.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Queue table:
    +
    ++-----------+-------------+--------+------+
    +
    +| person_id | person_name | weight | turn |
    +
    ++-----------+-------------+--------+------+
    +
    +| 5         | Alice       | 250    | 1    |
    +
    +| 4         | Bob         | 175    | 5    |
    +
    +| 3         | Alex        | 350    | 2    |
    +
    +| 6         | John Cena   | 400    | 3    |
    +
    +| 1         | Winston     | 500    | 6    |
    +
    +| 2         | Marie       | 200    | 4    |
    +
    ++-----------+-------------+--------+------+
    +
    +
    +
    +Result table
    +
    ++-------------+
    +
    +| person_name |
    +
    ++-------------+
    +
    +| John Cena   |
    +
    ++-------------+
    +
    +
    +
    +The table is ordered by the turn for simplicity.
    +
    ++------+----+-----------+--------+--------------+
    +
    +| Turn | ID | Name      | Weight | Total Weight |
    +
    ++------+----+-----------+--------+--------------+
    +
    +| 1    | 5  | Alice     | 250    | 250          |
    +
    +| 2    | 3  | Alex      | 350    | 600          |
    +
    +| 3    | 6  | John Cena | 400    | 1000         | (last person to board)
    +
    +| 4    | 2  | Marie     | 200    | 1200         | (cannot board)
    +
    +| 5    | 4  | Bob       | 175    | ___          |
    +
    +| 6    | 1  | Winston   | 500    | ___          |
    +
    ++------+----+-----------+--------+--------------+
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1200-1299/1204.Last Person to Fit in the Elevator/README_EN.md b/assets/1200-1299/1204.Last Person to Fit in the Elevator/README_EN.md new file mode 100644 index 00000000..cbf12ab0 --- /dev/null +++ b/assets/1200-1299/1204.Last Person to Fit in the Elevator/README_EN.md @@ -0,0 +1,115 @@ +# [1204. Last Person to Fit in the Elevator](https://leetcode.com/problems/last-person-to-fit-in-the-elevator) + + + +## Description + +

    Table: Queue

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| person_id   | int     |
    +
    +| person_name | varchar |
    +
    +| weight      | int     |
    +
    +| turn        | int     |
    +
    ++-------------+---------+
    +
    +person_id is the primary key column for this table.
    +
    +This table has the information about all people waiting for an elevator.
    +
    +The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
    +
    +
    + + + +

     

    + + + +

    The maximum weight the elevator can hold is 1000.

    + + + +

    Write an SQL query to find the person_name of the last person who will fit in the elevator without exceeding the weight limit. It is guaranteed that the person who is first in the queue can fit in the elevator.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Queue table
    +
    ++-----------+-------------------+--------+------+
    +
    +| person_id | person_name       | weight | turn |
    +
    ++-----------+-------------------+--------+------+
    +
    +| 5         | George Washington | 250    | 1    |
    +
    +| 3         | John Adams        | 350    | 2    |
    +
    +| 6         | Thomas Jefferson  | 400    | 3    |
    +
    +| 2         | Will Johnliams    | 200    | 4    |
    +
    +| 4         | Thomas Jefferson  | 175    | 5    |
    +
    +| 1         | James Elephant    | 500    | 6    |
    +
    ++-----------+-------------------+--------+------+
    +
    +
    +
    +Result table
    +
    ++-------------------+
    +
    +| person_name       |
    +
    ++-------------------+
    +
    +| Thomas Jefferson  |
    +
    ++-------------------+
    +
    +
    +
    +Queue table is ordered by turn in the example for simplicity.
    +
    +In the example George Washington(id 5), John Adams(id 3) and Thomas Jefferson(id 6) will enter the elevator as their weight sum is 250 + 350 + 400 = 1000.
    +
    +Thomas Jefferson(id 6) is the last person to fit in the elevator because he has the last turn in these three people.
    +
    +
    + + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1205.Monthly Transactions II/README_EN.md b/assets/1200-1299/1205.Monthly Transactions II/README_EN.md new file mode 100644 index 00000000..b681315c --- /dev/null +++ b/assets/1200-1299/1205.Monthly Transactions II/README_EN.md @@ -0,0 +1,87 @@ +# [1205. Monthly Transactions II](https://leetcode.com/problems/monthly-transactions-ii) + + + +## Description + +

    Table: Transactions

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| id             | int     |
    +| country        | varchar |
    +| state          | enum    |
    +| amount         | int     |
    +| trans_date     | date    |
    ++----------------+---------+
    +id is the primary key of this table.
    +The table has information about incoming transactions.
    +The state column is an enum of type ["approved", "declined"].
    +
    + +

    Table: Chargebacks

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| trans_id       | int     |
    +| charge_date    | date    |
    ++----------------+---------+
    +Chargebacks contains basic information regarding incoming chargebacks from some transactions placed in Transactions table.
    +trans_id is a foreign key to the id column of Transactions table.
    +Each chargeback corresponds to a transaction made previously even if they were not approved.
    + +

     

    + +

    Write an SQL query to find for each month and country, the number of approved transactions and their total amount, the number of chargebacks and their total amount.

    + +

    Note: In your query, given the month and country, ignore rows with all zeros.

    + +

    The query result format is in the following example:

    + +
    +Transactions table:
    ++------+---------+----------+--------+------------+
    +| id   | country | state    | amount | trans_date |
    ++------+---------+----------+--------+------------+
    +| 101  | US      | approved | 1000   | 2019-05-18 |
    +| 102  | US      | declined | 2000   | 2019-05-19 |
    +| 103  | US      | approved | 3000   | 2019-06-10 |
    +| 104  | US      | approved | 4000   | 2019-06-13 |
    +| 105  | US      | approved | 5000   | 2019-06-15 |
    ++------+---------+----------+--------+------------+
    +
    +Chargebacks table:
    ++------------+------------+
    +| trans_id   | trans_date |
    ++------------+------------+
    +| 102        | 2019-05-29 |
    +| 101        | 2019-06-30 |
    +| 105        | 2019-09-18 |
    ++------------+------------+
    +
    +Result table:
    ++----------+---------+----------------+-----------------+-------------------+--------------------+
    +| month    | country | approved_count | approved_amount | chargeback_count  | chargeback_amount  |
    ++----------+---------+----------------+-----------------+-------------------+--------------------+
    +| 2019-05  | US      | 1              | 1000            | 1                 | 2000               |
    +| 2019-06  | US      | 3              | 12000           | 1                 | 1000               |
    +| 2019-09  | US      | 0              | 0               | 1                 | 5000               |
    ++----------+---------+----------------+-----------------+-------------------+--------------------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1206.Design Skiplist/README_EN.md b/assets/1200-1299/1206.Design Skiplist/README_EN.md new file mode 100644 index 00000000..ff31539c --- /dev/null +++ b/assets/1200-1299/1206.Design Skiplist/README_EN.md @@ -0,0 +1,116 @@ +# [1206. Design Skiplist](https://leetcode.com/problems/design-skiplist) + + + +## Description + +

    Design a Skiplist without using any built-in libraries.

    + + + +

    A Skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just simple linked lists.

    + + + +

    For example: we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:

    + + + +


    + +Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons

    + + + +

    You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add , erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).

    + + + +

    To be specific, your design should include these functions:

    + + + +
      +
    • bool search(int target) : Return whether the target exists in the Skiplist or not.
    • +
    • void add(int num): Insert a value into the SkipList. 
    • +
    • bool erase(int num): Remove a value in the Skiplist. If num does not exist in the Skiplist, do nothing and return false. If there exists multiple num values, removing any one of them is fine.
    • +
    + + + +

    See more about Skiplist : https://en.wikipedia.org/wiki/Skip_list

    + + + +

    Note that duplicates may exist in the Skiplist, your code needs to handle this situation.

    + + + +

     

    + + + +

    Example:

    + + + +
    +
    +Skiplist skiplist = new Skiplist();
    +
    +
    +
    +skiplist.add(1);
    +
    +skiplist.add(2);
    +
    +skiplist.add(3);
    +
    +skiplist.search(0);   // return false.
    +
    +skiplist.add(4);
    +
    +skiplist.search(1);   // return true.
    +
    +skiplist.erase(0);    // return false, 0 is not in skiplist.
    +
    +skiplist.erase(1);    // return true.
    +
    +skiplist.search(1);   // return false, 1 has already been erased.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= num, target <= 20000
    • +
    • At most 50000 calls will be made to search, add, and erase.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1206.Design Skiplist/images/1506_skiplist.gif b/assets/1200-1299/1206.Design Skiplist/images/1506_skiplist.gif new file mode 100644 index 00000000..d21bd523 Binary files /dev/null and b/assets/1200-1299/1206.Design Skiplist/images/1506_skiplist.gif differ diff --git a/assets/1200-1299/1207.Unique Number of Occurrences/README_EN.md b/assets/1200-1299/1207.Unique Number of Occurrences/README_EN.md new file mode 100644 index 00000000..baae7648 --- /dev/null +++ b/assets/1200-1299/1207.Unique Number of Occurrences/README_EN.md @@ -0,0 +1,62 @@ +# [1207. Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences) + + + +## Description + +

    Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,2,1,1,3]
    +Output: true
    +Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
    + +

    Example 2:

    + +
    +Input: arr = [1,2]
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • -1000 <= arr[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md b/assets/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md new file mode 100644 index 00000000..a59493d9 --- /dev/null +++ b/assets/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md @@ -0,0 +1,71 @@ +# [1208. Get Equal Substrings Within Budget](https://leetcode.com/problems/get-equal-substrings-within-budget) + + + +## Description + +

    You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters.

    + +

    You are also given an integer maxCost.

    + +

    Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of twith a cost less than or equal to maxCost.

    + +

    If there is no substring from s that can be changed to its corresponding substring from t, return 0.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcd", t = "bcdf", maxCost = 3
    +Output: 3
    +Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3.
    + +

    Example 2:

    + +
    +Input: s = "abcd", t = "cdef", maxCost = 3
    +Output: 1
    +Explanation: Each character in s costs 2 to change to charactor in t, so the maximum length is 1.
    +
    + +

    Example 3:

    + +
    +Input: s = "abcd", t = "acde", maxCost = 0
    +Output: 1
    +Explanation: You can't make any change, so the maximum length is 1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length, t.length <= 10^5
    • +
    • 0 <= maxCost <= 10^6
    • +
    • s and t only contain lower case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md b/assets/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md new file mode 100644 index 00000000..e7754769 --- /dev/null +++ b/assets/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md @@ -0,0 +1,70 @@ +# [1209. Remove All Adjacent Duplicates in String II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii) + + + +## Description + +

    You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

    + +

    We repeatedly make k duplicate removals on s until we no longer can.

    + +

    Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcd", k = 2
    +Output: "abcd"
    +Explanation: There's nothing to delete.
    + +

    Example 2:

    + +
    +Input: s = "deeedbbcccbdaa", k = 3
    +Output: "aa"
    +Explanation: 
    +First delete "eee" and "ccc", get "ddbbbdaa"
    +Then delete "bbb", get "dddaa"
    +Finally delete "ddd", get "aa"
    + +

    Example 3:

    + +
    +Input: s = "pbbcggttciiippooaais", k = 2
    +Output: "ps"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • 2 <= k <= 104
    • +
    • s only contains lower case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md new file mode 100644 index 00000000..352d1b78 --- /dev/null +++ b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md @@ -0,0 +1,85 @@ +# [1210. Minimum Moves to Reach Target with Rotations](https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations) + + + +## Description + +

    In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).

    + +

    In one move the snake can:

    + +
      +
    • Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
    • +
    • Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.
    • +
    • Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).
      +
    • +
    • Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).
      +
    • +
    + +

    Return the minimum number of moves to reach the target.

    + +

    If there is no way to reach the target, return -1.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [[0,0,0,0,0,1],
    +               [1,1,0,0,1,0],
    +               [0,0,0,0,1,1],
    +               [0,0,1,0,1,0],
    +               [0,1,1,0,0,0],
    +               [0,1,1,0,0,0]]
    +Output: 11
    +Explanation:
    +One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].
    +
    + +

    Example 2:

    + +
    +Input: grid = [[0,0,1,1,1,1],
    +               [0,0,0,0,1,1],
    +               [1,1,0,0,0,1],
    +               [1,1,1,0,0,1],
    +               [1,1,1,0,0,1],
    +               [1,1,1,0,0,0]]
    +Output: 9
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • 0 <= grid[i][j] <= 1
    • +
    • It is guaranteed that the snake starts at empty cells.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image-1.png b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image-1.png new file mode 100644 index 00000000..c0761b72 Binary files /dev/null and b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image-1.png differ diff --git a/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image-2.png b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image-2.png new file mode 100644 index 00000000..271b06be Binary files /dev/null and b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image-2.png differ diff --git a/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image.png b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image.png new file mode 100644 index 00000000..004f6924 Binary files /dev/null and b/assets/1200-1299/1210.Minimum Moves to Reach Target with Rotations/images/image.png differ diff --git a/assets/1200-1299/1211.Queries Quality and Percentage/README_EN.md b/assets/1200-1299/1211.Queries Quality and Percentage/README_EN.md new file mode 100644 index 00000000..e072ef62 --- /dev/null +++ b/assets/1200-1299/1211.Queries Quality and Percentage/README_EN.md @@ -0,0 +1,83 @@ +# [1211. Queries Quality and Percentage](https://leetcode.com/problems/queries-quality-and-percentage) + + + +## Description + +

    Table: Queries

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| query_name  | varchar |
    +| result      | varchar |
    +| position    | int     |
    +| rating      | int     |
    ++-------------+---------+
    +There is no primary key for this table, it may have duplicate rows.
    +This table contains information collected from some queries on a database.
    +The position column has a value from 1 to 500.
    +The rating column has a value from 1 to 5. Query with rating less than 3 is a poor query.
    +
    + +

     

    + +

    We define query quality as:

    + +
    +

    The average of the ratio between query rating and its position.

    +
    + +

    We also define poor query percentage as:

    + +
    +

    The percentage of all queries with rating less than 3.

    +
    + +

    Write an SQL query to find each query_name, the quality and poor_query_percentage.

    + +

    Both quality and poor_query_percentage should be rounded to 2 decimal places.

    + +

    The query result format is in the following example:

    + +
    +Queries table:
    ++------------+-------------------+----------+--------+
    +| query_name | result            | position | rating |
    ++------------+-------------------+----------+--------+
    +| Dog        | Golden Retriever  | 1        | 5      |
    +| Dog        | German Shepherd   | 2        | 5      |
    +| Dog        | Mule              | 200      | 1      |
    +| Cat        | Shirazi           | 5        | 2      |
    +| Cat        | Siamese           | 3        | 3      |
    +| Cat        | Sphynx            | 7        | 4      |
    ++------------+-------------------+----------+--------+
    +
    +Result table:
    ++------------+---------+-----------------------+
    +| query_name | quality | poor_query_percentage |
    ++------------+---------+-----------------------+
    +| Dog        | 2.50    | 33.33                 |
    +| Cat        | 0.66    | 33.33                 |
    ++------------+---------+-----------------------+
    +
    +Dog queries quality is ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50
    +Dog queries poor_ query_percentage is (1 / 3) * 100 = 33.33
    +
    +Cat queries quality equals ((2 / 5) + (3 / 3) + (4 / 7)) / 3 = 0.66
    +Cat queries poor_ query_percentage is (1 / 3) * 100 = 33.33
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1212.Team Scores in Football Tournament/README_EN.md b/assets/1200-1299/1212.Team Scores in Football Tournament/README_EN.md new file mode 100644 index 00000000..026f82c1 --- /dev/null +++ b/assets/1200-1299/1212.Team Scores in Football Tournament/README_EN.md @@ -0,0 +1,96 @@ +# [1212. Team Scores in Football Tournament](https://leetcode.com/problems/team-scores-in-football-tournament) + + + +## Description + +

    Table: Teams

    + +
    ++---------------+----------+
    +| Column Name   | Type     |
    ++---------------+----------+
    +| team_id       | int      |
    +| team_name     | varchar  |
    ++---------------+----------+
    +team_id is the primary key of this table.
    +Each row of this table represents a single football team.
    +
    + +

    Table: Matches

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| match_id      | int     |
    +| host_team     | int     |
    +| guest_team    | int     | 
    +| host_goals    | int     |
    +| guest_goals   | int     |
    ++---------------+---------+
    +match_id is the primary key of this table.
    +Each row is a record of a finished match between two different teams. 
    +Teams host_team and guest_team are represented by their IDs in the teams table (team_id) and they scored host_goals and guest_goals goals respectively.
    +
    + +

     

    +You would like to compute the scores of all teams after all matches. Points are awarded as follows: + +
      +
    • A team receives three points if they win a match (Score strictly more goals than the opponent team).
    • +
    • A team receives one point if they draw a match (Same number of goals as the opponent team).
    • +
    • A team receives no points if they lose a match (Score less goals than the opponent team).
    • +
    + +

    Write an SQL query that selects the team_id, team_name and num_points of each team in the tournament after all described matches. Result table should be ordered by num_points (decreasing order). In case of a tie, order the records by team_id (increasing order).

    + +

    The query result format is in the following example:

    + +
    +Teams table:
    ++-----------+--------------+
    +| team_id   | team_name    |
    ++-----------+--------------+
    +| 10        | Leetcode FC  |
    +| 20        | NewYork FC   |
    +| 30        | Atlanta FC   |
    +| 40        | Chicago FC   |
    +| 50        | Toronto FC   |
    ++-----------+--------------+
    +
    +Matches table:
    ++------------+--------------+---------------+-------------+--------------+
    +| match_id   | host_team    | guest_team    | host_goals  | guest_goals  |
    ++------------+--------------+---------------+-------------+--------------+
    +| 1          | 10           | 20            | 3           | 0            |
    +| 2          | 30           | 10            | 2           | 2            |
    +| 3          | 10           | 50            | 5           | 1            |
    +| 4          | 20           | 30            | 1           | 0            |
    +| 5          | 50           | 30            | 1           | 0            |
    ++------------+--------------+---------------+-------------+--------------+
    +
    +Result table:
    ++------------+--------------+---------------+
    +| team_id    | team_name    | num_points    |
    ++------------+--------------+---------------+
    +| 10         | Leetcode FC  | 7             |
    +| 20         | NewYork FC   | 3             |
    +| 50         | Toronto FC   | 3             |
    +| 30         | Atlanta FC   | 1             |
    +| 40         | Chicago FC   | 0             |
    ++------------+--------------+---------------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md b/assets/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md new file mode 100644 index 00000000..0bdb647e --- /dev/null +++ b/assets/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md @@ -0,0 +1,155 @@ +# [1213. Intersection of Three Sorted Arrays](https://leetcode.com/problems/intersection-of-three-sorted-arrays) + + + +## Description + +

    Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.

    + +

     

    +

    Example 1:

    + +
    +Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
    +Output: [1,5]
    +Explanation: Only 1 and 5 appeared in the three arrays.
    +
    + +

    Example 2:

    + +
    +Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]
    +Output: []
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr1.length, arr2.length, arr3.length <= 1000
    • +
    • 1 <= arr1[i], arr2[i], arr3[i] <= 2000
    • +
    + + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: + def find(arr, val): + left, right = 0, len(arr) - 1 + while left < right: + mid = (left + right) >> 1 + if arr[mid] >= val: + right = mid + else: + left = mid + 1 + return arr[left] == val + + res = [] + for num in arr1: + if find(arr2, num) and find(arr3, num): + res.append(num) + return res +``` + +### **Java** + +```java +class Solution { + public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { + List res = new ArrayList<>(); + for (int num : arr1) { + if (find(arr2, num) && find(arr3, num)) { + res.add(num); + } + } + return res; + } + + private boolean find(int[] arr, int val) { + int left = 0, right = arr.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] >= val) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == val; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + vector res; + for (int num : arr1) { + if (find(arr2, num) && find(arr3, num)) { + res.push_back(num); + } + } + return res; + } + +private: + bool find(vector& arr, int val) { + int left = 0, right = arr.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (arr[mid] >= val) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == val; + } +}; +``` + +### **Go** + +```go +func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) []int { + var res []int + for _, num := range arr1 { + if find(arr2, num) && find(arr3, num) { + res = append(res, num) + } + } + return res +} + +func find(arr []int, val int) bool { + left, right := 0, len(arr)-1 + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= val { + right = mid + } else { + left = mid + 1 + } + } + return arr[left] == val +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1214.Two Sum BSTs/README_EN.md b/assets/1200-1299/1214.Two Sum BSTs/README_EN.md new file mode 100644 index 00000000..212255a2 --- /dev/null +++ b/assets/1200-1299/1214.Two Sum BSTs/README_EN.md @@ -0,0 +1,56 @@ +# [1214. Two Sum BSTs](https://leetcode.com/problems/two-sum-bsts) + + + +## Description + +

    Given the roots of two binary search trees, root1 and root2, return true if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target.

    + +

     

    +

    Example 1:

    + +
    +Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
    +Output: true
    +Explanation: 2 and 3 sum up to 5.
    +
    + +

    Example 2:

    + +
    +Input: root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in each tree is in the range [1, 5000].
    • +
    • -109 <= Node.val, target <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1214.Two Sum BSTs/images/1368_1_a2.png b/assets/1200-1299/1214.Two Sum BSTs/images/1368_1_a2.png new file mode 100644 index 00000000..7c4e414b Binary files /dev/null and b/assets/1200-1299/1214.Two Sum BSTs/images/1368_1_a2.png differ diff --git a/assets/1200-1299/1214.Two Sum BSTs/images/1368_1_b.png b/assets/1200-1299/1214.Two Sum BSTs/images/1368_1_b.png new file mode 100644 index 00000000..faab05c5 Binary files /dev/null and b/assets/1200-1299/1214.Two Sum BSTs/images/1368_1_b.png differ diff --git a/assets/1200-1299/1214.Two Sum BSTs/images/1368_2_a.png b/assets/1200-1299/1214.Two Sum BSTs/images/1368_2_a.png new file mode 100644 index 00000000..dcd1983d Binary files /dev/null and b/assets/1200-1299/1214.Two Sum BSTs/images/1368_2_a.png differ diff --git a/assets/1200-1299/1214.Two Sum BSTs/images/1368_2_b.png b/assets/1200-1299/1214.Two Sum BSTs/images/1368_2_b.png new file mode 100644 index 00000000..921a920f Binary files /dev/null and b/assets/1200-1299/1214.Two Sum BSTs/images/1368_2_b.png differ diff --git a/assets/1200-1299/1215.Stepping Numbers/README_EN.md b/assets/1200-1299/1215.Stepping Numbers/README_EN.md new file mode 100644 index 00000000..796b8789 --- /dev/null +++ b/assets/1200-1299/1215.Stepping Numbers/README_EN.md @@ -0,0 +1,46 @@ +# [1215. Stepping Numbers](https://leetcode.com/problems/stepping-numbers) + + + +## Description + +

    A Stepping Number is an integer such that all of its adjacent digits have an absolute difference of exactly 1. For example, 321 is a Stepping Number while 421 is not.

    + +

    Given two integers low and high, find and return a sorted list of all the Stepping Numbers in the range [low, high] inclusive.

    + +

     

    +

    Example 1:

    +
    Input: low = 0, high = 21
    +Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 0 <= low <= high <= 2 * 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1216.Valid Palindrome III/README_EN.md b/assets/1200-1299/1216.Valid Palindrome III/README_EN.md new file mode 100644 index 00000000..a5c9081c --- /dev/null +++ b/assets/1200-1299/1216.Valid Palindrome III/README_EN.md @@ -0,0 +1,59 @@ +# [1216. Valid Palindrome III](https://leetcode.com/problems/valid-palindrome-iii) + + + +## Description + +

    Given a string s and an integer k, return true if s is a k-palindrome.

    + +

    A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcdeca", k = 2
    +Output: true
    +Explanation: Remove 'b' and 'e' characters.
    +
    + +

    Example 2:

    + +
    +Input: s = "abbababa", k = 1
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s consists of only lowercase English letters.
    • +
    • 1 <= k <= s.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md b/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md new file mode 100644 index 00000000..fae60f47 --- /dev/null +++ b/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md @@ -0,0 +1,75 @@ +# [1217. Minimum Cost to Move Chips to The Same Position](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position) + + + +## Description + +

    We have n chips, where the position of the ith chip is position[i].

    + +

    We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:

    + +
      +
    • position[i] + 2 or position[i] - 2 with cost = 0.
    • +
    • position[i] + 1 or position[i] - 1 with cost = 1.
    • +
    + +

    Return the minimum cost needed to move all the chips to the same position.

    + +

     

    +

    Example 1:

    + +
    +Input: position = [1,2,3]
    +Output: 1
    +Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.
    +Second step: Move the chip at position 2 to position 1 with cost = 1.
    +Total cost is 1.
    +
    + +

    Example 2:

    + +
    +Input: position = [2,2,2,3,3]
    +Output: 2
    +Explanation: We can move the two chips at position  3 to position 2. Each move has cost = 1. The total cost = 2.
    +
    + +

    Example 3:

    + +
    +Input: position = [1,1000000000]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= position.length <= 100
    • +
    • 1 <= position[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/images/chip_e2.jpg b/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/images/chip_e2.jpg new file mode 100644 index 00000000..c239d17c Binary files /dev/null and b/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/images/chip_e2.jpg differ diff --git a/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/images/chips_e1.jpg b/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/images/chips_e1.jpg new file mode 100644 index 00000000..e7ff478a Binary files /dev/null and b/assets/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/images/chips_e1.jpg differ diff --git a/assets/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md b/assets/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md new file mode 100644 index 00000000..7758f351 --- /dev/null +++ b/assets/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md @@ -0,0 +1,96 @@ +# [1218. Longest Arithmetic Subsequence of Given Difference](https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference) + + + +## Description + +

    Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

    + + + +

    A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [1,2,3,4], difference = 1
    +
    +Output: 4
    +
    +Explanation: The longest arithmetic subsequence is [1,2,3,4].
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [1,3,5,7], difference = 1
    +
    +Output: 1
    +
    +Explanation: The longest arithmetic subsequence is any single element.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
    +
    +Output: 4
    +
    +Explanation: The longest arithmetic subsequence is [7,5,3,1].
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 105
    • +
    • -104 <= arr[i], difference <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1219.Path with Maximum Gold/README_EN.md b/assets/1200-1299/1219.Path with Maximum Gold/README_EN.md new file mode 100644 index 00000000..78205b0a --- /dev/null +++ b/assets/1200-1299/1219.Path with Maximum Gold/README_EN.md @@ -0,0 +1,80 @@ +# [1219. Path with Maximum Gold](https://leetcode.com/problems/path-with-maximum-gold) + + + +## Description + +

    In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.

    + +

    Return the maximum amount of gold you can collect under the conditions:

    + +
      +
    • Every time you are located in a cell you will collect all the gold in that cell.
    • +
    • From your position, you can walk one step to the left, right, up, or down.
    • +
    • You can't visit the same cell more than once.
    • +
    • Never visit a cell with 0 gold.
    • +
    • You can start and stop collecting gold from any position in the grid that has some gold.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
    +Output: 24
    +Explanation:
    +[[0,6,0],
    + [5,8,7],
    + [0,9,0]]
    +Path to get the maximum gold, 9 -> 8 -> 7.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
    +Output: 28
    +Explanation:
    +[[1,0,7],
    + [2,0,6],
    + [3,4,5],
    + [0,3,0],
    + [9,0,20]]
    +Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 15
    • +
    • 0 <= grid[i][j] <= 100
    • +
    • There are at most 25 cells containing gold.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1220.Count Vowels Permutation/README_EN.md b/assets/1200-1299/1220.Count Vowels Permutation/README_EN.md new file mode 100644 index 00000000..272863f5 --- /dev/null +++ b/assets/1200-1299/1220.Count Vowels Permutation/README_EN.md @@ -0,0 +1,73 @@ +# [1220. Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation) + + + +## Description + +

    Given an integer n, your task is to count how many strings of length n can be formed under the following rules:

    + +
      +
    • Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
    • +
    • Each vowel 'a' may only be followed by an 'e'.
    • +
    • Each vowel 'e' may only be followed by an 'a' or an 'i'.
    • +
    • Each vowel 'i' may not be followed by another 'i'.
    • +
    • Each vowel 'o' may only be followed by an 'i' or a 'u'.
    • +
    • Each vowel 'u' may only be followed by an 'a'.
    • +
    + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 5
    +Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 10
    +Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
    +
    + +

    Example 3: 

    + +
    +Input: n = 5
    +Output: 68
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 2 * 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1221.Split a String in Balanced Strings/README_EN.md b/assets/1200-1299/1221.Split a String in Balanced Strings/README_EN.md new file mode 100644 index 00000000..f03e2c81 --- /dev/null +++ b/assets/1200-1299/1221.Split a String in Balanced Strings/README_EN.md @@ -0,0 +1,78 @@ +# [1221. Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings) + + + +## Description + +

    Balanced strings are those that have an equal quantity of 'L' and 'R' characters.

    + +

    Given a balanced string s, split it in the maximum amount of balanced strings.

    + +

    Return the maximum amount of split balanced strings.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "RLRRLLRLRL"
    +Output: 4
    +Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
    +
    + +

    Example 2:

    + +
    +Input: s = "RLLLLRRRLR"
    +Output: 3
    +Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
    +
    + +

    Example 3:

    + +
    +Input: s = "LLLLRRRR"
    +Output: 1
    +Explanation: s can be split into "LLLLRRRR".
    +
    + +

    Example 4:

    + +
    +Input: s = "RLRRRLLRLL"
    +Output: 2
    +Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] is either 'L' or 'R'.
    • +
    • s is a balanced string.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1222.Queens That Can Attack the King/README_EN.md b/assets/1200-1299/1222.Queens That Can Attack the King/README_EN.md new file mode 100644 index 00000000..dd68c11d --- /dev/null +++ b/assets/1200-1299/1222.Queens That Can Attack the King/README_EN.md @@ -0,0 +1,113 @@ +# [1222. Queens That Can Attack the King](https://leetcode.com/problems/queens-that-can-attack-the-king) + + + +## Description + +

    On an 8x8 chessboard, there can be multiple Black Queens and one White King.

    + + + +

    Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.

    +

     

    +

    Example 1:

    + + + +

    + + + +
    +
    +Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
    +
    +Output: [[0,1],[1,0],[3,3]]
    +
    +Explanation:  
    +
    +The queen at [0,1] can attack the king cause they're in the same row. 
    +
    +The queen at [1,0] can attack the king cause they're in the same column. 
    +
    +The queen at [3,3] can attack the king cause they're in the same diagnal. 
    +
    +The queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. 
    +
    +The queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. 
    +
    +The queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
    +
    +Output: [[2,2],[3,4],[4,4]]
    +
    +
    + + + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]
    +
    +Output: [[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]
    +
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= queens.length <= 63
    • +
    • queens[i].length == 2
    • +
    • 0 <= queens[i][j] < 8
    • +
    • king.length == 2
    • +
    • 0 <= king[0], king[1] < 8
    • +
    • At most one piece is allowed in a cell.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram-1.jpg b/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram-1.jpg new file mode 100644 index 00000000..1876063f Binary files /dev/null and b/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram-1.jpg differ diff --git a/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram-2.jpg b/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram-2.jpg new file mode 100644 index 00000000..4ce0cf88 Binary files /dev/null and b/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram-2.jpg differ diff --git a/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram.jpg b/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram.jpg new file mode 100644 index 00000000..95fd221e Binary files /dev/null and b/assets/1200-1299/1222.Queens That Can Attack the King/images/untitled-diagram.jpg differ diff --git a/assets/1200-1299/1223.Dice Roll Simulation/README_EN.md b/assets/1200-1299/1223.Dice Roll Simulation/README_EN.md new file mode 100644 index 00000000..39738b6d --- /dev/null +++ b/assets/1200-1299/1223.Dice Roll Simulation/README_EN.md @@ -0,0 +1,68 @@ +# [1223. Dice Roll Simulation](https://leetcode.com/problems/dice-roll-simulation) + + + +## Description + +

    A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. 

    + +

    Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls.

    + +

    Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 2, rollMax = [1,1,2,2,2,3]
    +Output: 34
    +Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
    +
    + +

    Example 2:

    + +
    +Input: n = 2, rollMax = [1,1,1,1,1,1]
    +Output: 30
    +
    + +

    Example 3:

    + +
    +Input: n = 3, rollMax = [1,1,1,2,2,3]
    +Output: 181
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 5000
    • +
    • rollMax.length == 6
    • +
    • 1 <= rollMax[i] <= 15
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1224.Maximum Equal Frequency/README_EN.md b/assets/1200-1299/1224.Maximum Equal Frequency/README_EN.md new file mode 100644 index 00000000..b75dfbab --- /dev/null +++ b/assets/1200-1299/1224.Maximum Equal Frequency/README_EN.md @@ -0,0 +1,72 @@ +# [1224. Maximum Equal Frequency](https://leetcode.com/problems/maximum-equal-frequency) + + + +## Description + +

    Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.

    + +

    If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,2,1,1,5,3,3,5]
    +Output: 7
    +Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
    +Output: 13
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,1,1,2,2,2]
    +Output: 5
    +
    + +

    Example 4:

    + +
    +Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]
    +Output: 8
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1225.Report Contiguous Dates/README_EN.md b/assets/1200-1299/1225.Report Contiguous Dates/README_EN.md new file mode 100644 index 00000000..8ff235a6 --- /dev/null +++ b/assets/1200-1299/1225.Report Contiguous Dates/README_EN.md @@ -0,0 +1,93 @@ +# [1225. Report Contiguous Dates](https://leetcode.com/problems/report-contiguous-dates) + + + +## Description + +

    Table: Failed

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| fail_date    | date    |
    ++--------------+---------+
    +Primary key for this table is fail_date.
    +Failed table contains the days of failed tasks.
    +
    + +

    Table: Succeeded

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| success_date | date    |
    ++--------------+---------+
    +Primary key for this table is success_date.
    +Succeeded table contains the days of succeeded tasks.
    +
    + +

     

    + +

    A system is running one task every day. Every task is independent of the previous tasks. The tasks can fail or succeed.

    + +

    Write an SQL query to generate a report of period_state for each continuous interval of days in the period from 2019-01-01 to 2019-12-31.

    + +

    period_state is 'failed' if tasks in this interval failed or 'succeeded' if tasks in this interval succeeded. Interval of days are retrieved as start_date and end_date.

    + +

    Order result by start_date.

    + +

    The query result format is in the following example:

    + +
    +Failed table:
    ++-------------------+
    +| fail_date         |
    ++-------------------+
    +| 2018-12-28        |
    +| 2018-12-29        |
    +| 2019-01-04        |
    +| 2019-01-05        |
    ++-------------------+
    +
    +Succeeded table:
    ++-------------------+
    +| success_date      |
    ++-------------------+
    +| 2018-12-30        |
    +| 2018-12-31        |
    +| 2019-01-01        |
    +| 2019-01-02        |
    +| 2019-01-03        |
    +| 2019-01-06        |
    ++-------------------+
    +
    +
    +Result table:
    ++--------------+--------------+--------------+
    +| period_state | start_date   | end_date     |
    ++--------------+--------------+--------------+
    +| succeeded    | 2019-01-01   | 2019-01-03   |
    +| failed       | 2019-01-04   | 2019-01-05   |
    +| succeeded    | 2019-01-06   | 2019-01-06   |
    ++--------------+--------------+--------------+
    +
    +The report ignored the system state in 2018 as we care about the system in the period 2019-01-01 to 2019-12-31.
    +From 2019-01-01 to 2019-01-03 all tasks succeeded and the system state was "succeeded".
    +From 2019-01-04 to 2019-01-05 all tasks failed and system state was "failed".
    +From 2019-01-06 to 2019-01-06 all tasks succeeded and system state was "succeeded".
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1226.The Dining Philosophers/README_EN.md b/assets/1200-1299/1226.The Dining Philosophers/README_EN.md new file mode 100644 index 00000000..db0ec26c --- /dev/null +++ b/assets/1200-1299/1226.The Dining Philosophers/README_EN.md @@ -0,0 +1,77 @@ +# [1226. The Dining Philosophers](https://leetcode.com/problems/the-dining-philosophers) + + + +## Description + +

    Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.

    + +

    Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.

    + +

    Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.

    + +

    Design a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.

    + +

    + +

    The problem statement and the image above are taken from wikipedia.org

    + +

     

    + +

    The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where:

    + +
      +
    • philosopher is the id of the philosopher who wants to eat.
    • +
    • pickLeftFork and pickRightFork are functions you can call to pick the corresponding forks of that philosopher.
    • +
    • eat is a function you can call to let the philosopher eat once he has picked both forks.
    • +
    • putLeftFork and putRightFork are functions you can call to put down the corresponding forks of that philosopher.
    • +
    • The philosophers are assumed to be thinking as long as they are not asking to eat (the function is not being called with their number).
    • +
    + +

    Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: [[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]
    +Explanation:
    +n is the number of times each philosopher will call the function.
    +The output array describes the calls you made to the functions controlling the forks and the eat function, its format is:
    +output[i] = [a, b, c] (three integers)
    +- a is the id of a philosopher.
    +- b specifies the fork: {1 : left, 2 : right}.
    +- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 60
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1226.The Dining Philosophers/images/an_illustration_of_the_dining_philosophers_problem.png b/assets/1200-1299/1226.The Dining Philosophers/images/an_illustration_of_the_dining_philosophers_problem.png new file mode 100644 index 00000000..61548cac Binary files /dev/null and b/assets/1200-1299/1226.The Dining Philosophers/images/an_illustration_of_the_dining_philosophers_problem.png differ diff --git a/assets/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md b/assets/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md new file mode 100644 index 00000000..1acc2abe --- /dev/null +++ b/assets/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md @@ -0,0 +1,86 @@ +# [1227. Airplane Seat Assignment Probability](https://leetcode.com/problems/airplane-seat-assignment-probability) + + + +## Description + +

    n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:

    + + + +
      +
    • Take their own seat if it is still available, 
    • +
    • Pick other seats randomly when they find their seat occupied 
    • +
    + + + +

    What is the probability that the n-th person can get his own seat?

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 1
    +
    +Output: 1.00000
    +
    +Explanation: The first person can only get the first seat.
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 2
    +
    +Output: 0.50000
    +
    +Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^5
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md b/assets/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md new file mode 100644 index 00000000..94ed0b3e --- /dev/null +++ b/assets/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md @@ -0,0 +1,60 @@ +# [1228. Missing Number In Arithmetic Progression](https://leetcode.com/problems/missing-number-in-arithmetic-progression) + + + +## Description + +

    In some array arr, the values were in arithmetic progression: the values arr[i+1] - arr[i] are all equal for every 0 <= i < arr.length - 1.

    + +

    Then, a value from arr was removed that was not the first or last value in the array.

    + +

    Return the removed value.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [5,7,11,13]
    +Output: 9
    +Explanation: The previous array was [5,7,9,11,13].
    +
    + +

    Example 2:

    + +
    +Input: arr = [15,13,12]
    +Output: 14
    +Explanation: The previous array was [15,14,13,12].
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 1000
    • +
    • 0 <= arr[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1229.Meeting Scheduler/README_EN.md b/assets/1200-1299/1229.Meeting Scheduler/README_EN.md new file mode 100644 index 00000000..4188938a --- /dev/null +++ b/assets/1200-1299/1229.Meeting Scheduler/README_EN.md @@ -0,0 +1,65 @@ +# [1229. Meeting Scheduler](https://leetcode.com/problems/meeting-scheduler) + + + +## Description + +

    Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, return the earliest time slot that works for both of them and is of duration duration.

    + +

    If there is no common time slot that satisfies the requirements, return an empty array.

    + +

    The format of a time slot is an array of two elements [start, end] representing an inclusive time range from start to end.

    + +

    It is guaranteed that no two availability slots of the same person intersect with each other. That is, for any two time slots [start1, end1] and [start2, end2] of the same person, either start1 > end2 or start2 > end1.

    + +

     

    +

    Example 1:

    + +
    +Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8
    +Output: [60,68]
    +
    + +

    Example 2:

    + +
    +Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12
    +Output: []
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= slots1.length, slots2.length <= 104
    • +
    • slots1[i].length, slots2[i].length == 2
    • +
    • slots1[i][0] < slots1[i][1]
    • +
    • slots2[i][0] < slots2[i][1]
    • +
    • 0 <= slots1[i][j], slots2[i][j] <= 109
    • +
    • 1 <= duration <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1230.Toss Strange Coins/README_EN.md b/assets/1200-1299/1230.Toss Strange Coins/README_EN.md new file mode 100644 index 00000000..1763d4f1 --- /dev/null +++ b/assets/1200-1299/1230.Toss Strange Coins/README_EN.md @@ -0,0 +1,52 @@ +# [1230. Toss Strange Coins](https://leetcode.com/problems/toss-strange-coins) + + + +## Description + +

    You have some coins.  The i-th coin has a probability prob[i] of facing heads when tossed.

    + +

    Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.

    + +

     

    +

    Example 1:

    +
    Input: prob = [0.4], target = 1
    +Output: 0.40000
    +

    Example 2:

    +
    Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
    +Output: 0.03125
    +
    +

     

    +

    Constraints:

    + +
      +
    • 1 <= prob.length <= 1000
    • +
    • 0 <= prob[i] <= 1
    • +
    • 0 <= target <= prob.length
    • +
    • Answers will be accepted as correct if they are within 10^-5 of the correct answer.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1231.Divide Chocolate/README_EN.md b/assets/1200-1299/1231.Divide Chocolate/README_EN.md new file mode 100644 index 00000000..41c89ba0 --- /dev/null +++ b/assets/1200-1299/1231.Divide Chocolate/README_EN.md @@ -0,0 +1,71 @@ +# [1231. Divide Chocolate](https://leetcode.com/problems/divide-chocolate) + + + +## Description + +

    You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.

    + +

    You want to share the chocolate with your K friends so you start cutting the chocolate bar into K+1 pieces using K cuts, each piece consists of some consecutive chunks.

    + +

    Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.

    + +

    Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.

    + +

     

    +

    Example 1:

    + +
    +Input: sweetness = [1,2,3,4,5,6,7,8,9], K = 5
    +Output: 6
    +Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]
    +
    + +

    Example 2:

    + +
    +Input: sweetness = [5,6,7,8,9,1,2,3,4], K = 8
    +Output: 1
    +Explanation: There is only one way to cut the bar into 9 pieces.
    +
    + +

    Example 3:

    + +
    +Input: sweetness = [1,2,2,1,2,2,1,2,2], K = 2
    +Output: 5
    +Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= K < sweetness.length <= 10^4
    • +
    • 1 <= sweetness[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1232.Check If It Is a Straight Line/README_EN.md b/assets/1200-1299/1232.Check If It Is a Straight Line/README_EN.md new file mode 100644 index 00000000..e3f054a1 --- /dev/null +++ b/assets/1200-1299/1232.Check If It Is a Straight Line/README_EN.md @@ -0,0 +1,88 @@ +# [1232. Check If It Is a Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line) + + + +## Description + +

    You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

    + + + +

     

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
    +
    +Output: true
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
    +
    +Output: false
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= coordinates.length <= 1000
    • +
    • coordinates[i].length == 2
    • +
    • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
    • +
    • coordinates contains no duplicate point.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1232.Check If It Is a Straight Line/images/untitled-diagram-1.jpg b/assets/1200-1299/1232.Check If It Is a Straight Line/images/untitled-diagram-1.jpg new file mode 100644 index 00000000..b274c41e Binary files /dev/null and b/assets/1200-1299/1232.Check If It Is a Straight Line/images/untitled-diagram-1.jpg differ diff --git a/assets/1200-1299/1232.Check If It Is a Straight Line/images/untitled-diagram-2.jpg b/assets/1200-1299/1232.Check If It Is a Straight Line/images/untitled-diagram-2.jpg new file mode 100644 index 00000000..4739bec9 Binary files /dev/null and b/assets/1200-1299/1232.Check If It Is a Straight Line/images/untitled-diagram-2.jpg differ diff --git a/assets/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md b/assets/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md new file mode 100644 index 00000000..a57d6833 --- /dev/null +++ b/assets/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md @@ -0,0 +1,71 @@ +# [1233. Remove Sub-Folders from the Filesystem](https://leetcode.com/problems/remove-sub-folders-from-the-filesystem) + + + +## Description + +

    Given a list of folders, remove all sub-folders in those folders and return in any order the folders after removing.

    + +

    If a folder[i] is located within another folder[j], it is called a sub-folder of it.

    + +

    The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, /leetcode and /leetcode/problems are valid paths while an empty string and / are not.

    + +

     

    +

    Example 1:

    + +
    +Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
    +Output: ["/a","/c/d","/c/f"]
    +Explanation: Folders "/a/b/" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.
    +
    + +

    Example 2:

    + +
    +Input: folder = ["/a","/a/b/c","/a/b/d"]
    +Output: ["/a"]
    +Explanation: Folders "/a/b/c" and "/a/b/d/" will be removed because they are subfolders of "/a".
    +
    + +

    Example 3:

    + +
    +Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
    +Output: ["/a/b/c","/a/b/ca","/a/b/d"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= folder.length <= 4 * 10^4
    • +
    • 2 <= folder[i].length <= 100
    • +
    • folder[i] contains only lowercase letters and '/'
    • +
    • folder[i] always starts with character '/'
    • +
    • Each folder name is unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md b/assets/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md new file mode 100644 index 00000000..e7d19d6b --- /dev/null +++ b/assets/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md @@ -0,0 +1,79 @@ +# [1234. Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string) + + + +## Description + +

    You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.

    + +

    A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.

    + +

    Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.

    + +

    Return 0 if the string is already balanced.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "QWER"
    +Output: 0
    +Explanation: s is already balanced.
    + +

    Example 2:

    + +
    +Input: s = "QQWE"
    +Output: 1
    +Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
    +
    + +

    Example 3:

    + +
    +Input: s = "QQQW"
    +Output: 2
    +Explanation: We can replace the first "QQ" to "ER". 
    +
    + +

    Example 4:

    + +
    +Input: s = "QQQQ"
    +Output: 3
    +Explanation: We can replace the last 3 'Q' to make s = "QWER".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s.length is a multiple of 4
    • +
    • contains only 'Q', 'W', 'E' and 'R'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md new file mode 100644 index 00000000..23beac99 --- /dev/null +++ b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md @@ -0,0 +1,77 @@ +# [1235. Maximum Profit in Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling) + + + +## Description + +

    We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

    + +

    You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.

    + +

    If you choose a job that ends at time X you will be able to start another job that starts at time X.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
    +Output: 120
    +Explanation: The subset chosen is the first and fourth job. 
    +Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
    +
    + +

    Example 2:

    + +

    + +
    +Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
    +Output: 150
    +Explanation: The subset chosen is the first, fourth and fifth job. 
    +Profit obtained 150 = 20 + 70 + 60.
    +
    + +

    Example 3:

    + +

    + +
    +Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
    +Output: 6
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= startTime.length == endTime.length == profit.length <= 5 * 104
    • +
    • 1 <= startTime[i] < endTime[i] <= 109
    • +
    • 1 <= profit[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample1_1584.png b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample1_1584.png new file mode 100644 index 00000000..c7264d02 Binary files /dev/null and b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample1_1584.png differ diff --git a/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample22_1584.png b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample22_1584.png new file mode 100644 index 00000000..e5fd50f9 Binary files /dev/null and b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample22_1584.png differ diff --git a/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample3_1584.png b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample3_1584.png new file mode 100644 index 00000000..af835f74 Binary files /dev/null and b/assets/1200-1299/1235.Maximum Profit in Job Scheduling/images/sample3_1584.png differ diff --git a/assets/1200-1299/1236.Web Crawler/README_EN.md b/assets/1200-1299/1236.Web Crawler/README_EN.md new file mode 100644 index 00000000..39fae671 --- /dev/null +++ b/assets/1200-1299/1236.Web Crawler/README_EN.md @@ -0,0 +1,111 @@ +# [1236. Web Crawler](https://leetcode.com/problems/web-crawler) + + + +## Description + +

    Given a url startUrl and an interface HtmlParser, implement a web crawler to crawl all links that are under the same hostname as startUrl

    + +

    Return all urls obtained by your web crawler in any order.

    + +

    Your crawler should:

    + +
      +
    • Start from the page: startUrl
    • +
    • Call HtmlParser.getUrls(url) to get all urls from a webpage of given url.
    • +
    • Do not crawl the same link twice.
    • +
    • Explore only the links that are under the same hostname as startUrl.
    • +
    + +

    + +

    As shown in the example url above, the hostname is example.org. For simplicity sake, you may assume all urls use http protocol without any port specified. For example, the urls http://leetcode.com/problems and http://leetcode.com/contest are under the same hostname, while urls http://example.org/test and http://example.com/abc are not under the same hostname.

    + +

    The HtmlParser interface is defined as such: 

    + +
    +interface HtmlParser {
    +  // Return a list of all urls from a webpage of given url.
    +  public List<String> getUrls(String url);
    +}
    + +

    Below are two examples explaining the functionality of the problem, for custom testing purposes you'll have three variables urlsedges and startUrl. Notice that you will only have access to startUrl in your code, while urls and edges are not directly accessible to you in code.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input:
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com",
    +  "http://news.yahoo.com/us"
    +]
    +edges = [[2,0],[2,1],[3,2],[3,1],[0,4]]
    +startUrl = "http://news.yahoo.com/news/topics/"
    +Output: [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.yahoo.com/us"
    +]
    +
    + +

    Example 2:

    + +

    + +
    +Input: 
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com"
    +]
    +edges = [[0,2],[2,1],[3,2],[3,1],[3,0]]
    +startUrl = "http://news.google.com"
    +Output: ["http://news.google.com"]
    +Explanation: The startUrl links to all other pages that do not share the same hostname.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= urls.length <= 1000
    • +
    • 1 <= urls[i].length <= 300
    • +
    • startUrl is one of the urls.
    • +
    • Hostname label must be from 1 to 63 characters long, including the dots, may contain only the ASCII letters from 'a' to 'z', digits  from '0' to '9' and the hyphen-minus character ('-').
    • +
    • The hostname may not start or end with the hyphen-minus character ('-'). 
    • +
    • See:  https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
    • +
    • You may assume there're no duplicates in url library.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1236.Web Crawler/images/sample_2_1497.png b/assets/1200-1299/1236.Web Crawler/images/sample_2_1497.png new file mode 100644 index 00000000..3d1e1ac2 Binary files /dev/null and b/assets/1200-1299/1236.Web Crawler/images/sample_2_1497.png differ diff --git a/assets/1200-1299/1236.Web Crawler/images/sample_3_1497.png b/assets/1200-1299/1236.Web Crawler/images/sample_3_1497.png new file mode 100644 index 00000000..5355703a Binary files /dev/null and b/assets/1200-1299/1236.Web Crawler/images/sample_3_1497.png differ diff --git a/assets/1200-1299/1236.Web Crawler/images/urlhostname.png b/assets/1200-1299/1236.Web Crawler/images/urlhostname.png new file mode 100644 index 00000000..138365a5 Binary files /dev/null and b/assets/1200-1299/1236.Web Crawler/images/urlhostname.png differ diff --git a/assets/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md b/assets/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md new file mode 100644 index 00000000..df1d7bf1 --- /dev/null +++ b/assets/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md @@ -0,0 +1,219 @@ +# [1237. Find Positive Integer Solution for a Given Equation](https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation) + + + +## Description + +

    Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.

    + +

    While the exact formula is hidden, the function is monotonically increasing, i.e.:

    + +
      +
    • f(x, y) < f(x + 1, y)
    • +
    • f(x, y) < f(x, y + 1)
    • +
    + +

    The function interface is defined like this:

    + +
    +interface CustomFunction {
    +public:
    +  // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
    +  int f(int x, int y);
    +};
    +
    + +

    We will judge your solution as follows:

    + +
      +
    • The judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z.
    • +
    • The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.
    • +
    • The judge will call your findSolution and compare your results with the answer key.
    • +
    • If your results match the answer key, your solution will be Accepted.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: function_id = 1, z = 5
    +Output: [[1,4],[2,3],[3,2],[4,1]]
    +Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y.
    +The following positive integer values of x and y make f(x, y) equal to 5:
    +x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
    +x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
    +x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
    +x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
    +
    + +

    Example 2:

    + +
    +Input: function_id = 2, z = 5
    +Output: [[1,5],[5,1]]
    +Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y.
    +The following positive integer values of x and y make f(x, y) equal to 5:
    +x=1, y=5 -> f(1, 5) = 1 * 5 = 5.
    +x=5, y=1 -> f(5, 1) = 5 * 1 = 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= function_id <= 9
    • +
    • 1 <= z <= 100
    • +
    • It is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000.
    • +
    • It is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000.
    • +
    + + +## Solutions + +Binary search. + + + +### **Python3** + +```python +""" + This is the custom function interface. + You should not implement it, or speculate about its implementation + class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): + +""" + +class Solution: + def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: + res = [] + for x in range(1, 1001): + left, right = 1, 1000 + while left < right: + mid = (left + right) >> 1 + if customfunction.f(x, mid) >= z: + right = mid + else: + left = mid + 1 + if customfunction.f(x, left) == z: + res.append([x, left]) + return res +``` + +### **Java** + +```java +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * public int f(int x, int y); + * }; + */ + +class Solution { + public List> findSolution(CustomFunction customfunction, int z) { + List> res = new ArrayList<>(); + for (int i = 1; i <= 1000; ++i) { + int left = 1, right = 1000; + while (left < right) { + int mid = (left + right) >> 1; + if (customfunction.f(i, mid) >= z) { + right = mid; + } else { + left = mid + 1; + } + } + if (customfunction.f(i, left) == z) { + res.add(Arrays.asList(i, left)); + } + } + return res; + } +} +``` + +### **C++** + +```cpp +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * public: + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * int f(int x, int y); + * }; + */ + +class Solution { +public: + vector> findSolution(CustomFunction& customfunction, int z) { + vector> res; + for (int i = 1; i <= 1000; ++i) { + int left = 1, right = 1000; + while (left < right) { + int mid = left + right >> 1; + if (customfunction.f(i, mid) >= z) { + right = mid; + } else { + left = mid + 1; + } + } + if (customfunction.f(i, left) == z) { + res.push_back({i, left}); + } + } + return res; + } +}; +``` + +### **Go** + +```go +/** + * This is the declaration of customFunction API. + * @param x int + * @param x int + * @return Returns f(x, y) for any given positive integers x and y. + * Note that f(x, y) is increasing with respect to both x and y. + * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + */ + +func findSolution(customFunction func(int, int) int, z int) [][]int { + res := [][]int{} + for i := 1; i <= 1000; i++ { + left, right := 1, 1000 + for left < right { + mid := (left + right) >> 1 + if customFunction(i, mid) >= z { + right = mid + } else { + left = mid + 1 + } + } + if customFunction(i, left) == z { + res = append(res, []int{i, left}) + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md b/assets/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md new file mode 100644 index 00000000..7f2cd04f --- /dev/null +++ b/assets/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md @@ -0,0 +1,88 @@ +# [1238. Circular Permutation in Binary Representation](https://leetcode.com/problems/circular-permutation-in-binary-representation) + + + +## Description + +

    Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :

    + + + +
      +
    • p[0] = start
    • +
    • p[i] and p[i+1] differ by only one bit in their binary representation.
    • +
    • p[0] and p[2^n -1] must also differ by only one bit in their binary representation.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 2, start = 3
    +
    +Output: [3,2,0,1]
    +
    +Explanation: The binary representation of the permutation is (11,10,00,01). 
    +
    +All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 3, start = 2
    +
    +Output: [2,6,7,5,4,0,1,3]
    +
    +Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 16
    • +
    • 0 <= start < 2 ^ n
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md b/assets/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md new file mode 100644 index 00000000..57c276c1 --- /dev/null +++ b/assets/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md @@ -0,0 +1,161 @@ +# [1239. Maximum Length of a Concatenated String with Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters) + + + +## Description + +

    Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.

    + +

    Return the maximum possible length of s.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = ["un","iq","ue"]
    +Output: 4
    +Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
    +Maximum length is 4.
    +
    + +

    Example 2:

    + +
    +Input: arr = ["cha","r","act","ers"]
    +Output: 6
    +Explanation: Possible solutions are "chaers" and "acters".
    +
    + +

    Example 3:

    + +
    +Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
    +Output: 26
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 16
    • +
    • 1 <= arr[i].length <= 26
    • +
    • arr[i] contains only lower case English letters.
    • +
    + + +## Solutions + +State compression uses a 32-bit number to record the appearance of letters, and `masks` stores the previously enumerated strings. + + + +### **Python3** + +```python +class Solution: + def maxLength(self, arr: List[str]) -> int: + def ones_count(x): + c = 0 + while x: + x &= x - 1 + c += 1 + return c + + ans = 0 + masks = [0] + for s in arr: + mask = 0 + for ch in s: + ch = ord(ch) - ord('a') + if (mask >> ch) & 1 == 1: + mask = 0 + break + mask |= 1 << ch + if mask == 0: + continue + for m in masks: + if m & mask == 0: + masks.append(m | mask) + ans = max(ans, ones_count(m | mask)) + + return ans +``` + +### **Java** + +```java +class Solution { + public int maxLength(List arr) { + int ans = 0; + List masks = new ArrayList<>(); + masks.add(0); + + loop: + for (String s : arr) { + int mask = 0; + for (char ch : s.toCharArray()) { + ch -= 'a'; + if (((mask >> ch) & 1) == 1) { + continue loop; + } + mask |= 1 << ch; + } + int n = masks.size(); + for (int i = 0; i < n; i++) { + int m = masks.get(i); + if ((m & mask) == 0) { + masks.add(m | mask); + ans = Math.max(ans, Integer.bitCount(m | mask)); + } + } + } + + return ans; + } +} +``` + +### **Go** + +```go +func maxLength(arr []string) int { + + max := func(x, y int) int { + if x > y { + return x + } + return y + } + + ans := 0 + masks := []int{0} + +loop: + for _, s := range arr { + mask := 0 + for _, ch := range s { + ch -= 'a' + if (mask>>ch)&1 == 1 { + continue loop + } + mask |= 1 << ch + } + for _, m := range masks { + if m&mask == 0 { + masks = append(masks, m|mask) + ans = max(ans, bits.OnesCount(uint(m|mask))) + } + } + } + + return ans +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md new file mode 100644 index 00000000..d6302719 --- /dev/null +++ b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md @@ -0,0 +1,70 @@ +# [1240. Tiling a Rectangle with the Fewest Squares](https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares) + + + +## Description + +

    Given a rectangle of size n x m, find the minimum number of integer-sided squares that tile the rectangle.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 2, m = 3
    +Output: 3
    +Explanation: 3 squares are necessary to cover the rectangle.
    +2 (squares of 1x1)
    +1 (square of 2x2)
    + +

    Example 2:

    + +

    + +
    +Input: n = 5, m = 8
    +Output: 5
    +
    + +

    Example 3:

    + +

    + +
    +Input: n = 11, m = 13
    +Output: 6
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 13
    • +
    • 1 <= m <= 13
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_11_1592.png b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_11_1592.png new file mode 100644 index 00000000..34316c91 Binary files /dev/null and b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_11_1592.png differ diff --git a/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_22_1592.png b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_22_1592.png new file mode 100644 index 00000000..c8983a84 Binary files /dev/null and b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_22_1592.png differ diff --git a/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_33_1592.png b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_33_1592.png new file mode 100644 index 00000000..fb8661cd Binary files /dev/null and b/assets/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/images/sample_33_1592.png differ diff --git a/assets/1200-1299/1241.Number of Comments per Post/README_EN.md b/assets/1200-1299/1241.Number of Comments per Post/README_EN.md new file mode 100644 index 00000000..ae7570b4 --- /dev/null +++ b/assets/1200-1299/1241.Number of Comments per Post/README_EN.md @@ -0,0 +1,78 @@ +# [1241. Number of Comments per Post](https://leetcode.com/problems/number-of-comments-per-post) + + + +## Description + +

    Table: Submissions

    + +
    ++---------------+----------+
    +| Column Name   | Type     |
    ++---------------+----------+
    +| sub_id        | int      |
    +| parent_id     | int      |
    ++---------------+----------+
    +There is no primary key for this table, it may have duplicate rows.
    +Each row can be a post or comment on the post.
    +parent_id is null for posts.
    +parent_id for comments is sub_id for another post in the table.
    +
    + +

     

    + +

    Write an SQL query to find number of comments per each post.

    + +

    Result table should contain post_id and its corresponding number_of_comments, and must be sorted by post_id in ascending order.

    + +

    Submissions may contain duplicate comments. You should count the number of unique comments per post.

    + +

    Submissions may contain duplicate posts. You should treat them as one post.

    + +

    The query result format is in the following example:

    + +
    +Submissions table:
    ++---------+------------+
    +| sub_id  | parent_id  |
    ++---------+------------+
    +| 1       | Null       |
    +| 2       | Null       |
    +| 1       | Null       |
    +| 12      | Null       |
    +| 3       | 1          |
    +| 5       | 2          |
    +| 3       | 1          |
    +| 4       | 1          |
    +| 9       | 1          |
    +| 10      | 2          |
    +| 6       | 7          |
    ++---------+------------+
    +
    +Result table:
    ++---------+--------------------+
    +| post_id | number_of_comments |
    ++---------+--------------------+
    +| 1       | 3                  |
    +| 2       | 2                  |
    +| 12      | 0                  |
    ++---------+--------------------+
    +
    +The post with id 1 has three comments in the table with id 3, 4 and 9. The comment with id 3 is repeated in the table, we counted it only once.
    +The post with id 2 has two comments in the table with id 5 and 10.
    +The post with id 12 has no comments in the table.
    +The comment with id 6 is a comment on a deleted post with id 7 so we ignored it.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1242.Web Crawler Multithreaded/README_EN.md b/assets/1200-1299/1242.Web Crawler Multithreaded/README_EN.md new file mode 100644 index 00000000..ded832e6 --- /dev/null +++ b/assets/1200-1299/1242.Web Crawler Multithreaded/README_EN.md @@ -0,0 +1,124 @@ +# [1242. Web Crawler Multithreaded](https://leetcode.com/problems/web-crawler-multithreaded) + + + +## Description + +

    Given a url startUrl and an interface HtmlParser, implement a Multi-threaded web crawler to crawl all links that are under the same hostname as startUrl

    + +

    Return all urls obtained by your web crawler in any order.

    + +

    Your crawler should:

    + +
      +
    • Start from the page: startUrl
    • +
    • Call HtmlParser.getUrls(url) to get all urls from a webpage of given url.
    • +
    • Do not crawl the same link twice.
    • +
    • Explore only the links that are under the same hostname as startUrl.
    • +
    + +

    + +

    As shown in the example url above, the hostname is example.org. For simplicity sake, you may assume all urls use http protocol without any port specified. For example, the urls http://leetcode.com/problems and http://leetcode.com/contest are under the same hostname, while urls http://example.org/test and http://example.com/abc are not under the same hostname.

    + +

    The HtmlParser interface is defined as such: 

    + +
    +interface HtmlParser {
    +  // Return a list of all urls from a webpage of given url.
    +  // This is a blocking call, that means it will do HTTP request and return when this request is finished.
    +  public List<String> getUrls(String url);
    +}
    + +

    Note that getUrls(String url) simulates performing a HTTP request. You can treat it as a blocking function call which waits for a HTTP request to finish. It is guaranteed that getUrls(String url) will return the urls within 15ms.  Single-threaded solutions will exceed the time limit so, can your multi-threaded web crawler do better?

    + +

    Below are two examples explaining the functionality of the problem, for custom testing purposes you'll have three variables urlsedges and startUrl. Notice that you will only have access to startUrl in your code, while urls and edges are not directly accessible to you in code.

    + +

     

    + +

    Follow up:

    + +
      +
    1. Assume we have 10,000 nodes and 1 billion URLs to crawl. We will deploy the same software onto each node. The software can know about all the nodes. We have to minimize communication between machines and make sure each node does equal amount of work. How would your web crawler design change?
    2. +
    3. What if one node fails or does not work?
    4. +
    5. How do you know when the crawler is done?
    6. +
    + +

     

    +

    Example 1:

    + +

    + +
    +Input:
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com",
    +  "http://news.yahoo.com/us"
    +]
    +edges = [[2,0],[2,1],[3,2],[3,1],[0,4]]
    +startUrl = "http://news.yahoo.com/news/topics/"
    +Output: [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.yahoo.com/us"
    +]
    +
    + +

    Example 2:

    + +

    + +
    +Input: 
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com"
    +]
    +edges = [[0,2],[2,1],[3,2],[3,1],[3,0]]
    +startUrl = "http://news.google.com"
    +Output: ["http://news.google.com"]
    +Explanation: The startUrl links to all other pages that do not share the same hostname.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= urls.length <= 1000
    • +
    • 1 <= urls[i].length <= 300
    • +
    • startUrl is one of the urls.
    • +
    • Hostname label must be from 1 to 63 characters long, including the dots, may contain only the ASCII letters from 'a' to 'z', digits from '0' to '9' and the hyphen-minus character ('-').
    • +
    • The hostname may not start or end with the hyphen-minus character ('-'). 
    • +
    • See:  https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
    • +
    • You may assume there're no duplicates in url library.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1242.Web Crawler Multithreaded/images/sample_2_1497.png b/assets/1200-1299/1242.Web Crawler Multithreaded/images/sample_2_1497.png new file mode 100644 index 00000000..3d1e1ac2 Binary files /dev/null and b/assets/1200-1299/1242.Web Crawler Multithreaded/images/sample_2_1497.png differ diff --git a/assets/1200-1299/1242.Web Crawler Multithreaded/images/sample_3_1497.png b/assets/1200-1299/1242.Web Crawler Multithreaded/images/sample_3_1497.png new file mode 100644 index 00000000..5355703a Binary files /dev/null and b/assets/1200-1299/1242.Web Crawler Multithreaded/images/sample_3_1497.png differ diff --git a/assets/1200-1299/1242.Web Crawler Multithreaded/images/urlhostname.png b/assets/1200-1299/1242.Web Crawler Multithreaded/images/urlhostname.png new file mode 100644 index 00000000..138365a5 Binary files /dev/null and b/assets/1200-1299/1242.Web Crawler Multithreaded/images/urlhostname.png differ diff --git a/assets/1200-1299/1243.Array Transformation/README_EN.md b/assets/1200-1299/1243.Array Transformation/README_EN.md new file mode 100644 index 00000000..cb2a61ba --- /dev/null +++ b/assets/1200-1299/1243.Array Transformation/README_EN.md @@ -0,0 +1,110 @@ +# [1243. Array Transformation](https://leetcode.com/problems/array-transformation) + + + +## Description + +

    Given an initial array arr, every day you produce a new array using the array of the previous day.

    + +

    On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i:

    + +
      +
    1. If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
    2. +
    3. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented.
    4. +
    5. The first and last elements never change.
    6. +
    + +

    After some days, the array does not change. Return that final array.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [6,2,3,4]
    +Output: [6,3,3,4]
    +Explanation: 
    +On the first day, the array is changed from [6,2,3,4] to [6,3,3,4].
    +No more operations can be done to this array.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,6,3,4,3,5]
    +Output: [1,4,4,4,4,5]
    +Explanation: 
    +On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5].
    +On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5].
    +No more operations can be done to this array.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def transformArray(self, arr: List[int]) -> List[int]: + copy = [e for e in arr] + has_change, n = True, len(arr) + while has_change: + has_change = False + for i in range(1, n - 1): + if arr[i] < copy[i - 1] and arr[i] < copy[i + 1]: + arr[i] += 1 + has_change = True + elif arr[i] > copy[i - 1] and arr[i] > copy[i + 1]: + arr[i] -= 1 + has_change = True + copy = [e for e in arr] + return arr +``` + +### **Java** + +```java +class Solution { + public List transformArray(int[] arr) { + int n = arr.length; + int[] copy = Arrays.copyOf(arr, n); + boolean hasChange = true; + while (hasChange) { + hasChange = false; + for (int i = 1; i < n - 1; ++i) { + if (arr[i] < copy[i - 1] && arr[i] < copy[i + 1]) { + ++arr[i]; + hasChange = true; + } else if (arr[i] > copy[i - 1] && arr[i] > copy[i + 1]) { + --arr[i]; + hasChange = true; + } + } + System.arraycopy(arr, 0, copy, 0, n); + } + List res = new ArrayList<>(); + for (int e : arr) { + res.add(e); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1244.Design A Leaderboard/README_EN.md b/assets/1200-1299/1244.Design A Leaderboard/README_EN.md new file mode 100644 index 00000000..45b2f1c0 --- /dev/null +++ b/assets/1200-1299/1244.Design A Leaderboard/README_EN.md @@ -0,0 +1,125 @@ +# [1244. Design A Leaderboard](https://leetcode.com/problems/design-a-leaderboard) + + + +## Description + +

    Design a Leaderboard class, which has 3 functions:

    + +
      +
    1. addScore(playerId, score): Update the leaderboard by adding score to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the given score.
    2. +
    3. top(K): Return the score sum of the top K players.
    4. +
    5. reset(playerId): Reset the score of the player with the given id to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function.
    6. +
    + +

    Initially, the leaderboard is empty.

    + +

     

    +

    Example 1:

    + +
    +Input: 
    +["Leaderboard","addScore","addScore","addScore","addScore","addScore","top","reset","reset","addScore","top"]
    +[[],[1,73],[2,56],[3,39],[4,51],[5,4],[1],[1],[2],[2,51],[3]]
    +Output: 
    +[null,null,null,null,null,null,73,null,null,null,141]
    +
    +Explanation: 
    +Leaderboard leaderboard = new Leaderboard ();
    +leaderboard.addScore(1,73);   // leaderboard = [[1,73]];
    +leaderboard.addScore(2,56);   // leaderboard = [[1,73],[2,56]];
    +leaderboard.addScore(3,39);   // leaderboard = [[1,73],[2,56],[3,39]];
    +leaderboard.addScore(4,51);   // leaderboard = [[1,73],[2,56],[3,39],[4,51]];
    +leaderboard.addScore(5,4);    // leaderboard = [[1,73],[2,56],[3,39],[4,51],[5,4]];
    +leaderboard.top(1);           // returns 73;
    +leaderboard.reset(1);         // leaderboard = [[2,56],[3,39],[4,51],[5,4]];
    +leaderboard.reset(2);         // leaderboard = [[3,39],[4,51],[5,4]];
    +leaderboard.addScore(2,51);   // leaderboard = [[2,51],[3,39],[4,51],[5,4]];
    +leaderboard.top(3);           // returns 141 = 51 + 51 + 39;
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= playerId, K <= 10000
    • +
    • It's guaranteed that K is less than or equal to the current number of players.
    • +
    • 1 <= score <= 100
    • +
    • There will be at most 1000 function calls.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Leaderboard: + + def __init__(self): + self.player_scores = {} + + def addScore(self, playerId: int, score: int) -> None: + self.player_scores[playerId] = self.player_scores.get(playerId, 0) + score + + def top(self, K: int) -> int: + scores = sorted(list(self.player_scores.values()), reverse=True) + return sum(scores[:K]) + + def reset(self, playerId: int) -> None: + self.player_scores[playerId] = 0 + + +# Your Leaderboard object will be instantiated and called as such: +# obj = Leaderboard() +# obj.addScore(playerId,score) +# param_2 = obj.top(K) +# obj.reset(playerId) +``` + +### **Java** + +```java +class Leaderboard { + private Map playerScores; + + public Leaderboard() { + playerScores = new HashMap<>(); + } + + public void addScore(int playerId, int score) { + playerScores.put(playerId, playerScores.getOrDefault(playerId, 0) + score); + } + + public int top(int K) { + List scores = new ArrayList<>(playerScores.values()); + Collections.sort(scores, Collections.reverseOrder()); + int res = 0; + for (int i = 0; i < K; ++i) { + res += scores.get(i); + } + return res; + } + + public void reset(int playerId) { + playerScores.put(playerId, 0); + } +} + +/** + * Your Leaderboard object will be instantiated and called as such: + * Leaderboard obj = new Leaderboard(); + * obj.addScore(playerId,score); + * int param_2 = obj.top(K); + * obj.reset(playerId); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1245.Tree Diameter/README_EN.md b/assets/1200-1299/1245.Tree Diameter/README_EN.md new file mode 100644 index 00000000..8c1ee358 --- /dev/null +++ b/assets/1200-1299/1245.Tree Diameter/README_EN.md @@ -0,0 +1,67 @@ +# [1245. Tree Diameter](https://leetcode.com/problems/tree-diameter) + + + +## Description + +

    Given an undirected tree, return its diameter: the number of edges in a longest path in that tree.

    + +

    The tree is given as an array of edges where edges[i] = [u, v] is a bidirectional edge between nodes u and v.  Each node has labels in the set {0, 1, ..., edges.length}.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: edges = [[0,1],[0,2]]
    +Output: 2
    +Explanation: 
    +A longest path of the tree is the path 1 - 0 - 2.
    +
    + +

    Example 2:

    + +

    + +
    +Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
    +Output: 4
    +Explanation: 
    +A longest path of the tree is the path 3 - 2 - 1 - 4 - 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= edges.length < 10^4
    • +
    • edges[i][0] != edges[i][1]
    • +
    • 0 <= edges[i][j] <= edges.length
    • +
    • The given edges form an undirected tree.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1245.Tree Diameter/images/1397_example_1.png b/assets/1200-1299/1245.Tree Diameter/images/1397_example_1.png new file mode 100644 index 00000000..52970604 Binary files /dev/null and b/assets/1200-1299/1245.Tree Diameter/images/1397_example_1.png differ diff --git a/assets/1200-1299/1245.Tree Diameter/images/1397_example_2.png b/assets/1200-1299/1245.Tree Diameter/images/1397_example_2.png new file mode 100644 index 00000000..bf8be91e Binary files /dev/null and b/assets/1200-1299/1245.Tree Diameter/images/1397_example_2.png differ diff --git a/assets/1200-1299/1246.Palindrome Removal/README_EN.md b/assets/1200-1299/1246.Palindrome Removal/README_EN.md new file mode 100644 index 00000000..96e3b4b9 --- /dev/null +++ b/assets/1200-1299/1246.Palindrome Removal/README_EN.md @@ -0,0 +1,58 @@ +# [1246. Palindrome Removal](https://leetcode.com/problems/palindrome-removal) + + + +## Description + +

    Given an integer array arr, in one move you can select a palindromic subarray arr[i], arr[i+1], ..., arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal.

    + +

    Return the minimum number of moves needed to remove all numbers from the array.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2]
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,3,4,1,5]
    +Output: 3
    +Explanation: Remove [4] then remove [1,3,1] then remove [5].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 20
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md b/assets/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md new file mode 100644 index 00000000..3d215175 --- /dev/null +++ b/assets/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md @@ -0,0 +1,114 @@ +# [1247. Minimum Swaps to Make Strings Equal](https://leetcode.com/problems/minimum-swaps-to-make-strings-equal) + + + +## Description + +

    You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].

    + + + +

    Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s1 = "xx", s2 = "yy"
    +
    +Output: 1
    +
    +Explanation: 
    +
    +Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
    + + + +

    Example 2: 

    + + + +
    +
    +Input: s1 = "xy", s2 = "yx"
    +
    +Output: 2
    +
    +Explanation: 
    +
    +Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
    +
    +Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
    +
    +Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
    + + + +

    Example 3:

    + + + +
    +
    +Input: s1 = "xx", s2 = "xy"
    +
    +Output: -1
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
    +
    +Output: 4
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s1.length, s2.length <= 1000
    • +
    • s1, s2 only contain 'x' or 'y'.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md b/assets/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md new file mode 100644 index 00000000..d5b52634 --- /dev/null +++ b/assets/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md @@ -0,0 +1,67 @@ +# [1248. Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays) + + + +## Description + +

    Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.

    + +

    Return the number of nice sub-arrays.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,1,2,1,1], k = 3
    +Output: 2
    +Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,4,6], k = 1
    +Output: 0
    +Explanation: There is no odd numbers in the array.
    +
    + +

    Example 3:

    + +
    +Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
    +Output: 16
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 50000
    • +
    • 1 <= nums[i] <= 10^5
    • +
    • 1 <= k <= nums.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md b/assets/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md new file mode 100644 index 00000000..616899eb --- /dev/null +++ b/assets/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md @@ -0,0 +1,122 @@ +# [1249. Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses) + + + +## Description + +

    Given a string s of '(' , ')' and lowercase English characters. 

    + + + +

    Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

    + + + +

    Formally, a parentheses string is valid if and only if:

    + + + +
      +
    • It is the empty string, contains only lowercase characters, or
    • +
    • It can be written as AB (A concatenated with B), where A and B are valid strings, or
    • +
    • It can be written as (A), where A is a valid string.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "lee(t(c)o)de)"
    +
    +Output: "lee(t(c)o)de"
    +
    +Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "a)b(c)d"
    +
    +Output: "ab(c)d"
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "))(("
    +
    +Output: ""
    +
    +Explanation: An empty string is also valid.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "(a(b(c)d)"
    +
    +Output: "a(b(c)d)"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s[i] is one of  '(' , ')' and lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1250.Check If It Is a Good Array/README_EN.md b/assets/1200-1299/1250.Check If It Is a Good Array/README_EN.md new file mode 100644 index 00000000..b84cb92b --- /dev/null +++ b/assets/1200-1299/1250.Check If It Is a Good Array/README_EN.md @@ -0,0 +1,68 @@ +# [1250. Check If It Is a Good Array](https://leetcode.com/problems/check-if-it-is-a-good-array) + + + +## Description + +

    Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.

    + +

    Return True if the array is good otherwise return False.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [12,5,7,23]
    +Output: true
    +Explanation: Pick numbers 5 and 7.
    +5*3 + 7*(-2) = 1
    +
    + +

    Example 2:

    + +
    +Input: nums = [29,6,10]
    +Output: true
    +Explanation: Pick numbers 29, 6 and 10.
    +29*1 + 6*(-3) + 10*(-1) = 1
    +
    + +

    Example 3:

    + +
    +Input: nums = [3,6]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1251.Average Selling Price/README_EN.md b/assets/1200-1299/1251.Average Selling Price/README_EN.md new file mode 100644 index 00000000..3840abd5 --- /dev/null +++ b/assets/1200-1299/1251.Average Selling Price/README_EN.md @@ -0,0 +1,161 @@ +# [1251. Average Selling Price](https://leetcode.com/problems/average-selling-price) + + + +## Description + +

    Table: Prices

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| product_id    | int     |
    +
    +| start_date    | date    |
    +
    +| end_date      | date    |
    +
    +| price         | int     |
    +
    ++---------------+---------+
    +
    +(product_id, start_date, end_date) is the primary key for this table.
    +
    +Each row of this table indicates the price of the product_id in the period from start_date to end_date.
    +
    +For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.
    +
    +
    + + + +

     

    + + + +

    Table: UnitsSold

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| product_id    | int     |
    +
    +| purchase_date | date    |
    +
    +| units         | int     |
    +
    ++---------------+---------+
    +
    +There is no primary key for this table, it may contain duplicates.
    +
    +Each row of this table indicates the date, units and product_id of each product sold. 
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to find the average selling price for each product.

    + + + +

    average_price should be rounded to 2 decimal places.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Prices table:
    +
    ++------------+------------+------------+--------+
    +
    +| product_id | start_date | end_date   | price  |
    +
    ++------------+------------+------------+--------+
    +
    +| 1          | 2019-02-17 | 2019-02-28 | 5      |
    +
    +| 1          | 2019-03-01 | 2019-03-22 | 20     |
    +
    +| 2          | 2019-02-01 | 2019-02-20 | 15     |
    +
    +| 2          | 2019-02-21 | 2019-03-31 | 30     |
    +
    ++------------+------------+------------+--------+
    +
    + 
    +
    +UnitsSold table:
    +
    ++------------+---------------+-------+
    +
    +| product_id | purchase_date | units |
    +
    ++------------+---------------+-------+
    +
    +| 1          | 2019-02-25    | 100   |
    +
    +| 1          | 2019-03-01    | 15    |
    +
    +| 2          | 2019-02-10    | 200   |
    +
    +| 2          | 2019-03-22    | 30    |
    +
    ++------------+---------------+-------+
    +
    +
    +
    +Result table:
    +
    ++------------+---------------+
    +
    +| product_id | average_price |
    +
    ++------------+---------------+
    +
    +| 1          | 6.96          |
    +
    +| 2          | 16.96         |
    +
    ++------------+---------------+
    +
    +Average selling price = Total Price of Product / Number of products sold.
    +
    +Average selling price for product 1 = ((100 * 5) + (15 * 20)) / 115 = 6.96
    +
    +Average selling price for product 2 = ((200 * 15) + (30 * 30)) / 230 = 16.96
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md b/assets/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md new file mode 100644 index 00000000..51f73488 --- /dev/null +++ b/assets/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md @@ -0,0 +1,73 @@ +# [1252. Cells with Odd Values in a Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix) + + + +## Description + +

    There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.

    + +

    For each location indices[i], do both of the following:

    + +
      +
    1. Increment all the cells on row ri.
    2. +
    3. Increment all the cells on column ci.
    4. +
    + +

    Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.

    + +

     

    +

    Example 1:

    + +
    +Input: m = 2, n = 3, indices = [[0,1],[1,1]]
    +Output: 6
    +Explanation: Initial matrix = [[0,0,0],[0,0,0]].
    +After applying first increment it becomes [[1,2,1],[0,1,0]].
    +The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.
    +
    + +

    Example 2:

    + +
    +Input: m = 2, n = 2, indices = [[1,1],[0,0]]
    +Output: 0
    +Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= m, n <= 50
    • +
    • 1 <= indices.length <= 100
    • +
    • 0 <= ri < m
    • +
    • 0 <= ci < n
    • +
    + +

     

    +

    Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?

    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1252.Cells with Odd Values in a Matrix/images/e1.png b/assets/1200-1299/1252.Cells with Odd Values in a Matrix/images/e1.png new file mode 100644 index 00000000..18704fa7 Binary files /dev/null and b/assets/1200-1299/1252.Cells with Odd Values in a Matrix/images/e1.png differ diff --git a/assets/1200-1299/1252.Cells with Odd Values in a Matrix/images/e2.png b/assets/1200-1299/1252.Cells with Odd Values in a Matrix/images/e2.png new file mode 100644 index 00000000..5001fdde Binary files /dev/null and b/assets/1200-1299/1252.Cells with Odd Values in a Matrix/images/e2.png differ diff --git a/assets/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md b/assets/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md new file mode 100644 index 00000000..b781713d --- /dev/null +++ b/assets/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md @@ -0,0 +1,79 @@ +# [1253. Reconstruct a 2-Row Binary Matrix](https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix) + + + +## Description + +

    Given the following details of a matrix with n columns and 2 rows :

    + +
      +
    • The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.
    • +
    • The sum of elements of the 0-th(upper) row is given as upper.
    • +
    • The sum of elements of the 1-st(lower) row is given as lower.
    • +
    • The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.
    • +
    + +

    Your task is to reconstruct the matrix with upper, lower and colsum.

    + +

    Return it as a 2-D integer array.

    + +

    If there are more than one valid solution, any of them will be accepted.

    + +

    If no valid solution exists, return an empty 2-D array.

    + +

     

    +

    Example 1:

    + +
    +Input: upper = 2, lower = 1, colsum = [1,1,1]
    +Output: [[1,1,0],[0,0,1]]
    +Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.
    +
    + +

    Example 2:

    + +
    +Input: upper = 2, lower = 3, colsum = [2,2,1,1]
    +Output: []
    +
    + +

    Example 3:

    + +
    +Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
    +Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= colsum.length <= 10^5
    • +
    • 0 <= upper, lower <= colsum.length
    • +
    • 0 <= colsum[i] <= 2
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1254.Number of Closed Islands/README_EN.md b/assets/1200-1299/1254.Number of Closed Islands/README_EN.md new file mode 100644 index 00000000..88a81c47 --- /dev/null +++ b/assets/1200-1299/1254.Number of Closed Islands/README_EN.md @@ -0,0 +1,75 @@ +# [1254. Number of Closed Islands](https://leetcode.com/problems/number-of-closed-islands) + + + +## Description + +

    Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

    + +

    Return the number of closed islands.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
    +Output: 2
    +Explanation: 
    +Islands in gray are closed because they are completely surrounded by water (group of 1s).
    + +

    Example 2:

    + +

    + +
    +Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
    +Output: 1
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,1,1,1,1,1,1],
    +               [1,0,0,0,0,0,1],
    +               [1,0,1,1,1,0,1],
    +               [1,0,1,0,1,0,1],
    +               [1,0,1,1,1,0,1],
    +               [1,0,0,0,0,0,1],
    +               [1,1,1,1,1,1,1]]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= grid.length, grid[0].length <= 100
    • +
    • 0 <= grid[i][j] <=1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1254.Number of Closed Islands/images/sample_3_1610.png b/assets/1200-1299/1254.Number of Closed Islands/images/sample_3_1610.png new file mode 100644 index 00000000..3199dc06 Binary files /dev/null and b/assets/1200-1299/1254.Number of Closed Islands/images/sample_3_1610.png differ diff --git a/assets/1200-1299/1254.Number of Closed Islands/images/sample_4_1610.png b/assets/1200-1299/1254.Number of Closed Islands/images/sample_4_1610.png new file mode 100644 index 00000000..fd1a0040 Binary files /dev/null and b/assets/1200-1299/1254.Number of Closed Islands/images/sample_4_1610.png differ diff --git a/assets/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md b/assets/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md new file mode 100644 index 00000000..dff467db --- /dev/null +++ b/assets/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md @@ -0,0 +1,78 @@ +# [1255. Maximum Score Words Formed by Letters](https://leetcode.com/problems/maximum-score-words-formed-by-letters) + + + +## Description + +

    Given a list of words, list of  single letters (might be repeating) and score of every character.

    + +

    Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).

    + +

    It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
    +Output: 23
    +Explanation:
    +Score  a=1, c=9, d=5, g=3, o=2
    +Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
    +Words "dad" and "dog" only get a score of 21.
    + +

    Example 2:

    + +
    +Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
    +Output: 27
    +Explanation:
    +Score  a=4, b=4, c=4, x=5, z=10
    +Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
    +Word "xxxz" only get a score of 25.
    + +

    Example 3:

    + +
    +Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
    +Output: 0
    +Explanation:
    +Letter "e" can only be used once.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 14
    • +
    • 1 <= words[i].length <= 15
    • +
    • 1 <= letters.length <= 100
    • +
    • letters[i].length == 1
    • +
    • score.length == 26
    • +
    • 0 <= score[i] <= 10
    • +
    • words[i], letters[i] contains only lower case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1256.Encode Number/README_EN.md b/assets/1200-1299/1256.Encode Number/README_EN.md new file mode 100644 index 00000000..f7e7c4b0 --- /dev/null +++ b/assets/1200-1299/1256.Encode Number/README_EN.md @@ -0,0 +1,81 @@ +# [1256. Encode Number](https://leetcode.com/problems/encode-number) + + + +## Description + +

    Given a non-negative integer num, Return its encoding string.

    + + + +

    The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:

    + + + +

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: num = 23
    +
    +Output: "1000"
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: num = 107
    +
    +Output: "101100"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= num <= 10^9
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1256.Encode Number/images/encode_number.png b/assets/1200-1299/1256.Encode Number/images/encode_number.png new file mode 100644 index 00000000..61232add Binary files /dev/null and b/assets/1200-1299/1256.Encode Number/images/encode_number.png differ diff --git a/assets/1200-1299/1257.Smallest Common Region/README_EN.md b/assets/1200-1299/1257.Smallest Common Region/README_EN.md new file mode 100644 index 00000000..2e3d9dbe --- /dev/null +++ b/assets/1200-1299/1257.Smallest Common Region/README_EN.md @@ -0,0 +1,64 @@ +# [1257. Smallest Common Region](https://leetcode.com/problems/smallest-common-region) + + + +## Description + +

    You are given some lists of regions where the first region of each list includes all other regions in that list.

    + +

    Naturally, if a region X contains another region Y then X is bigger than Y. Also by definition a region X contains itself.

    + +

    Given two regions region1, region2, find out the smallest region that contains both of them.

    + +

    If you are given regions r1, r2 and r3 such that r1 includes r3, it is guaranteed there is no r2 such that r2 includes r3.
    +
    +It's guaranteed the smallest region exists.

    + +

     

    +

    Example 1:

    + +
    +Input:
    +regions = [["Earth","North America","South America"],
    +["North America","United States","Canada"],
    +["United States","New York","Boston"],
    +["Canada","Ontario","Quebec"],
    +["South America","Brazil"]],
    +region1 = "Quebec",
    +region2 = "New York"
    +Output: "North America"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= regions.length <= 10^4
    • +
    • region1 != region2
    • +
    • All strings consist of English letters and spaces with at most 20 letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1258.Synonymous Sentences/README_EN.md b/assets/1200-1299/1258.Synonymous Sentences/README_EN.md new file mode 100644 index 00000000..5e31e0fe --- /dev/null +++ b/assets/1200-1299/1258.Synonymous Sentences/README_EN.md @@ -0,0 +1,79 @@ +# [1258. Synonymous Sentences](https://leetcode.com/problems/synonymous-sentences) + + + +## Description + +Given a list of pairs of equivalent words synonyms and a sentence text, Return all possible synonymous sentences sorted lexicographically. +

     

    +

    Example 1:

    + +
    +Input:
    +synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],
    +text = "I am happy today but was sad yesterday"
    +Output:
    +["I am cheerful today but was sad yesterday",
    +"I am cheerful today but was sorrow yesterday",
    +"I am happy today but was sad yesterday",
    +"I am happy today but was sorrow yesterday",
    +"I am joy today but was sad yesterday",
    +"I am joy today but was sorrow yesterday"]
    +
    + +

    Example 2:

    + +
    +Input: synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday"
    +Output: ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"]
    +
    + +

    Example 3:

    + +
    +Input: synonyms = [["a","b"],["c","d"],["e","f"]], text = "a c e"
    +Output: ["a c e","a c f","a d e","a d f","b c e","b c f","b d e","b d f"]
    +
    + +

    Example 4:

    + +
    +Input: synonyms = [["a","QrbCl"]], text = "d QrbCl ya ya NjZQ"
    +Output: ["d QrbCl ya ya NjZQ","d a ya ya NjZQ"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= synonyms.length <= 10
    • +
    • synonyms[i].length == 2
    • +
    • synonyms[i][0] != synonyms[i][1]
    • +
    • All words consist of at most 10 English letters only.
    • +
    • text is a single space separated sentence of at most 10 words.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1259.Handshakes That Don't Cross/README_EN.md b/assets/1200-1299/1259.Handshakes That Don't Cross/README_EN.md new file mode 100644 index 00000000..386700b8 --- /dev/null +++ b/assets/1200-1299/1259.Handshakes That Don't Cross/README_EN.md @@ -0,0 +1,78 @@ +# [1259. Handshakes That Don't Cross](https://leetcode.com/problems/handshakes-that-dont-cross) + + + +## Description + +

    You are given an even number of people num_people that stand around a circle and each person shakes hands with someone else, so that there are num_people / 2 handshakes total.

    + +

    Return the number of ways these handshakes could occur such that none of the handshakes cross.

    + +

    Since this number could be very big, return the answer mod 10^9 + 7

    + +

     

    +

    Example 1:

    + +
    +Input: num_people = 2
    +Output: 1
    +
    + +

    Example 2:

    + +

    + +
    +Input: num_people = 4
    +Output: 2
    +Explanation: There are two ways to do it, the first way is [(1,2),(3,4)] and the second one is [(2,3),(4,1)].
    +
    + +

    Example 3:

    + +

    + +
    +Input: num_people = 6
    +Output: 5
    +
    + +

    Example 4:

    + +
    +Input: num_people = 8
    +Output: 14
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= num_people <= 1000
    • +
    • num_people % 2 == 0
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1259.Handshakes That Don't Cross/images/5125_example_2.png b/assets/1200-1299/1259.Handshakes That Don't Cross/images/5125_example_2.png new file mode 100644 index 00000000..d3bbc2ab Binary files /dev/null and b/assets/1200-1299/1259.Handshakes That Don't Cross/images/5125_example_2.png differ diff --git a/assets/1200-1299/1259.Handshakes That Don't Cross/images/5125_example_3.png b/assets/1200-1299/1259.Handshakes That Don't Cross/images/5125_example_3.png new file mode 100644 index 00000000..37897e2d Binary files /dev/null and b/assets/1200-1299/1259.Handshakes That Don't Cross/images/5125_example_3.png differ diff --git a/assets/1200-1299/1260.Shift 2D Grid/README_EN.md b/assets/1200-1299/1260.Shift 2D Grid/README_EN.md new file mode 100644 index 00000000..47bb7203 --- /dev/null +++ b/assets/1200-1299/1260.Shift 2D Grid/README_EN.md @@ -0,0 +1,76 @@ +# [1260. Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid) + + + +## Description + +

    Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

    + +

    In one shift operation:

    + +
      +
    • Element at grid[i][j] moves to grid[i][j + 1].
    • +
    • Element at grid[i][n - 1] moves to grid[i + 1][0].
    • +
    • Element at grid[m - 1][n - 1] moves to grid[0][0].
    • +
    + +

    Return the 2D grid after applying shift operation k times.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
    +Output: [[9,1,2],[3,4,5],[6,7,8]]
    +
    + +

    Example 2:

    + +
    +Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
    +Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
    +Output: [[1,2,3],[4,5,6],[7,8,9]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 50
    • +
    • 1 <= n <= 50
    • +
    • -1000 <= grid[i][j] <= 1000
    • +
    • 0 <= k <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1260.Shift 2D Grid/images/e1-1.png b/assets/1200-1299/1260.Shift 2D Grid/images/e1-1.png new file mode 100644 index 00000000..76107009 Binary files /dev/null and b/assets/1200-1299/1260.Shift 2D Grid/images/e1-1.png differ diff --git a/assets/1200-1299/1260.Shift 2D Grid/images/e2-1.png b/assets/1200-1299/1260.Shift 2D Grid/images/e2-1.png new file mode 100644 index 00000000..b9783883 Binary files /dev/null and b/assets/1200-1299/1260.Shift 2D Grid/images/e2-1.png differ diff --git a/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md new file mode 100644 index 00000000..1ef71f59 --- /dev/null +++ b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md @@ -0,0 +1,108 @@ +# [1261. Find Elements in a Contaminated Binary Tree](https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree) + + + +## Description + +

    Given a binary tree with the following rules:

    + +
      +
    1. root.val == 0
    2. +
    3. If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1
    4. +
    5. If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2
    6. +
    + +

    Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.

    + +

    You need to first recover the binary tree and then implement the FindElements class:

    + +
      +
    • FindElements(TreeNode* root) Initializes the object with a contamined binary tree, you need to recover it first.
    • +
    • bool find(int target) Return if the target value exists in the recovered binary tree.
    • +
    + +

     

    +

    Example 1:

    + +

    + +
    +Input
    +["FindElements","find","find"]
    +[[[-1,null,-1]],[1],[2]]
    +Output
    +[null,false,true]
    +Explanation
    +FindElements findElements = new FindElements([-1,null,-1]); 
    +findElements.find(1); // return False 
    +findElements.find(2); // return True 
    + +

    Example 2:

    + +

    + +
    +Input
    +["FindElements","find","find","find"]
    +[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
    +Output
    +[null,true,true,false]
    +Explanation
    +FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
    +findElements.find(1); // return True
    +findElements.find(3); // return True
    +findElements.find(5); // return False
    + +

    Example 3:

    + +

    + +
    +Input
    +["FindElements","find","find","find","find"]
    +[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
    +Output
    +[null,true,false,false,true]
    +Explanation
    +FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
    +findElements.find(2); // return True
    +findElements.find(3); // return False
    +findElements.find(4); // return False
    +findElements.find(5); // return True
    +
    + +

     

    +

    Constraints:

    + +
      +
    • TreeNode.val == -1
    • +
    • The height of the binary tree is less than or equal to 20
    • +
    • The total number of nodes is between [1, 10^4]
    • +
    • Total calls of find() is between [1, 10^4]
    • +
    • 0 <= target <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/1261_example_1_v2.png b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/1261_example_1_v2.png new file mode 100644 index 00000000..bb521386 Binary files /dev/null and b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/1261_example_1_v2.png differ diff --git a/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/1261_example_2_v2.png b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/1261_example_2_v2.png new file mode 100644 index 00000000..c275a91b Binary files /dev/null and b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/1261_example_2_v2.png differ diff --git a/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4-1-1.jpg b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4-1-1.jpg new file mode 100644 index 00000000..bcf95e5c Binary files /dev/null and b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4-1-1.jpg differ diff --git a/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4-1.jpg b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4-1.jpg new file mode 100644 index 00000000..7f5eef8c Binary files /dev/null and b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4-1.jpg differ diff --git a/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4.jpg b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4.jpg new file mode 100644 index 00000000..29249311 Binary files /dev/null and b/assets/1200-1299/1261.Find Elements in a Contaminated Binary Tree/images/untitled-diagram-4.jpg differ diff --git a/assets/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md b/assets/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md new file mode 100644 index 00000000..4a43b2ac --- /dev/null +++ b/assets/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md @@ -0,0 +1,67 @@ +# [1262. Greatest Sum Divisible by Three](https://leetcode.com/problems/greatest-sum-divisible-by-three) + + + +## Description + +

    Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.

    + +
      +
    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,6,5,1,8]
    +Output: 18
    +Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
    + +

    Example 2:

    + +
    +Input: nums = [4]
    +Output: 0
    +Explanation: Since 4 is not divisible by 3, do not pick any number.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3,4,4]
    +Output: 12
    +Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 4 * 10^4
    • +
    • 1 <= nums[i] <= 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md b/assets/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md new file mode 100644 index 00000000..a3c8c76a --- /dev/null +++ b/assets/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md @@ -0,0 +1,108 @@ +# [1263. Minimum Moves to Move a Box to Their Target Location](https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location) + + + +## Description + +

    Storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.

    + +

    The game is represented by a grid of size m x n, where each element is a wall, floor, or a box.

    + +

    Your task is move the box 'B' to the target position 'T' under the following rules:

    + +
      +
    • Player is represented by character 'S' and can move up, down, left, right in the grid if it is a floor (empy cell).
    • +
    • Floor is represented by character '.' that means free cell to walk.
    • +
    • Wall is represented by character '#' that means obstacle  (impossible to walk there). 
    • +
    • There is only one box 'B' and one target cell 'T' in the grid.
    • +
    • The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.
    • +
    • The player cannot walk through the box.
    • +
    + +

    Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [["#","#","#","#","#","#"],
    +               ["#","T","#","#","#","#"],
    +               ["#",".",".","B",".","#"],
    +               ["#",".","#","#",".","#"],
    +               ["#",".",".",".","S","#"],
    +               ["#","#","#","#","#","#"]]
    +Output: 3
    +Explanation: We return only the number of times the box is pushed.
    + +

    Example 2:

    + +
    +Input: grid = [["#","#","#","#","#","#"],
    +               ["#","T","#","#","#","#"],
    +               ["#",".",".","B",".","#"],
    +               ["#","#","#","#",".","#"],
    +               ["#",".",".",".","S","#"],
    +               ["#","#","#","#","#","#"]]
    +Output: -1
    +
    + +

    Example 3:

    + +
    +Input: grid = [["#","#","#","#","#","#"],
    +               ["#","T",".",".","#","#"],
    +               ["#",".","#","B",".","#"],
    +               ["#",".",".",".",".","#"],
    +               ["#",".",".",".","S","#"],
    +               ["#","#","#","#","#","#"]]
    +Output: 5
    +Explanation:  push the box down, left, left, up and up.
    +
    + +

    Example 4:

    + +
    +Input: grid = [["#","#","#","#","#","#","#"],
    +               ["#","S","#",".","B","T","#"],
    +               ["#","#","#","#","#","#","#"]]
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 20
    • +
    • 1 <= n <= 20
    • +
    • grid contains only characters '.', '#''S' , 'T', or 'B'.
    • +
    • There is only one character 'S', 'B' and 'T' in the grid.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/images/sample_1_1620.png b/assets/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/images/sample_1_1620.png new file mode 100644 index 00000000..a43b5b1f Binary files /dev/null and b/assets/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/images/sample_1_1620.png differ diff --git a/assets/1200-1299/1264.Page Recommendations/README_EN.md b/assets/1200-1299/1264.Page Recommendations/README_EN.md new file mode 100644 index 00000000..be747b70 --- /dev/null +++ b/assets/1200-1299/1264.Page Recommendations/README_EN.md @@ -0,0 +1,177 @@ +# [1264. Page Recommendations](https://leetcode.com/problems/page-recommendations) + + + +## Description + +

    Table: Friendship

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| user1_id      | int     |
    +
    +| user2_id      | int     |
    +
    ++---------------+---------+
    +
    +(user1_id, user2_id) is the primary key for this table.
    +
    +Each row of this table indicates that there is a friendship relation between user1_id and user2_id.
    +
    +
    + + + +

     

    + + + +

    Table: Likes

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| user_id     | int     |
    +
    +| page_id     | int     |
    +
    ++-------------+---------+
    +
    +(user_id, page_id) is the primary key for this table.
    +
    +Each row of this table indicates that user_id likes page_id.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to recommend pages to the user with user_id = 1 using the pages that your friends liked. It should not recommend pages you already liked.

    + + + +

    Return result table in any order without duplicates.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Friendship table:
    +
    ++----------+----------+
    +
    +| user1_id | user2_id |
    +
    ++----------+----------+
    +
    +| 1        | 2        |
    +
    +| 1        | 3        |
    +
    +| 1        | 4        |
    +
    +| 2        | 3        |
    +
    +| 2        | 4        |
    +
    +| 2        | 5        |
    +
    +| 6        | 1        |
    +
    ++----------+----------+
    +
    + 
    +
    +Likes table:
    +
    ++---------+---------+
    +
    +| user_id | page_id |
    +
    ++---------+---------+
    +
    +| 1       | 88      |
    +
    +| 2       | 23      |
    +
    +| 3       | 24      |
    +
    +| 4       | 56      |
    +
    +| 5       | 11      |
    +
    +| 6       | 33      |
    +
    +| 2       | 77      |
    +
    +| 3       | 77      |
    +
    +| 6       | 88      |
    +
    ++---------+---------+
    +
    +
    +
    +Result table:
    +
    ++------------------+
    +
    +| recommended_page |
    +
    ++------------------+
    +
    +| 23               |
    +
    +| 24               |
    +
    +| 56               |
    +
    +| 33               |
    +
    +| 77               |
    +
    ++------------------+
    +
    +User one is friend with users 2, 3, 4 and 6.
    +
    +Suggested pages are 23 from user 2, 24 from user 3, 56 from user 3 and 33 from user 6.
    +
    +Page 77 is suggested from both user 2 and user 3.
    +
    +Page 88 is not suggested because user 1 already likes it.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md b/assets/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md new file mode 100644 index 00000000..53c988e5 --- /dev/null +++ b/assets/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md @@ -0,0 +1,167 @@ +# [1265. Print Immutable Linked List in Reverse](https://leetcode.com/problems/print-immutable-linked-list-in-reverse) + + + +## Description + +

    You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface:

    + +
      +
    • ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
    • +
    + +

    You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly):

    + +
      +
    • ImmutableListNode.printValue(): Print value of the current node.
    • +
    • ImmutableListNode.getNext(): Return the next node.
    • +
    + +

    The input is only given to initialize the linked list internally. You must solve this problem without modifying the linked list. In other words, you must operate the linked list using only the mentioned APIs.

    + +

     

    +

    Example 1:

    + +
    +Input: head = [1,2,3,4]
    +Output: [4,3,2,1]
    +
    + +

    Example 2:

    + +
    +Input: head = [0,-4,-1,3,-5]
    +Output: [-5,3,-1,-4,0]
    +
    + +

    Example 3:

    + +
    +Input: head = [-2,0,6,4,4,-6]
    +Output: [-6,4,4,6,0,-2]
    +
    + +
      +
    + +

     

    +

    Constraints:

    + +
      +
    • The length of the linked list is between [1, 1000].
    • +
    • The value of each node in the linked list is between [-1000, 1000].
    • +
    + +

     

    + +

    Follow up:

    + +

    Could you solve this problem in:

    + +
      +
    • Constant space complexity?
    • +
    • Linear time complexity and less than linear space complexity?
    • +
    + + +## Solutions + + + +### **Python3** + +```python +# """ +# This is the ImmutableListNode's API interface. +# You should not implement it, or speculate about its implementation. +# """ +# class ImmutableListNode: +# def printValue(self) -> None: # print the value of this node. +# def getNext(self) -> 'ImmutableListNode': # return the next node. + +class Solution: + def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None: + if head: + self.printLinkedListInReverse(head.getNext()) + head.printValue() +``` + +### **Java** + +```java +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * interface ImmutableListNode { + * public void printValue(); // print the value of this node. + * public ImmutableListNode getNext(); // return the next node. + * }; + */ + +class Solution { + public void printLinkedListInReverse(ImmutableListNode head) { + if (head != null) { + printLinkedListInReverse(head.getNext()); + head.printValue(); + } + } +} +``` + +### **C++** + +```cpp +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * class ImmutableListNode { + * public: + * void printValue(); // print the value of the node. + * ImmutableListNode* getNext(); // return the next node. + * }; + */ + +class Solution { +public: + void printLinkedListInReverse(ImmutableListNode* head) { + if (head) { + printLinkedListInReverse(head->getNext()); + head->printValue(); + } + } +}; +``` + +### **Go** + +```go +/* Below is the interface for ImmutableListNode, which is already defined for you. + * + * type ImmutableListNode struct { + * + * } + * + * func (this *ImmutableListNode) getNext() ImmutableListNode { + * // return the next node. + * } + * + * func (this *ImmutableListNode) printValue() { + * // print the value of this node. + * } + */ + +func printLinkedListInReverse(head ImmutableListNode) { + if head != nil { + printLinkedListInReverse(head.getNext()) + head.printValue() + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md b/assets/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md new file mode 100644 index 00000000..24cd8c4d --- /dev/null +++ b/assets/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md @@ -0,0 +1,75 @@ +# [1266. Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points) + + + +## Description + +

    On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.

    + +

    You can move according to these rules:

    + +
      +
    • In 1 second, you can either: + +
        +
      • move vertically by one unit,
      • +
      • move horizontally by one unit, or
      • +
      • move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).
      • +
      +
    • +
    • You have to visit the points in the same order as they appear in the array.
    • +
    • You are allowed to pass through points that appear later in the order, but these do not count as visits.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: points = [[1,1],[3,4],[-1,0]]
    +Output: 7
    +Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]   
    +Time from [1,1] to [3,4] = 3 seconds 
    +Time from [3,4] to [-1,0] = 4 seconds
    +Total time = 7 seconds
    + +

    Example 2:

    + +
    +Input: points = [[3,2],[-2,2]]
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • points.length == n
    • +
    • 1 <= n <= 100
    • +
    • points[i].length == 2
    • +
    • -1000 <= points[i][0], points[i][1] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1266.Minimum Time Visiting All Points/images/1626_example_1.png b/assets/1200-1299/1266.Minimum Time Visiting All Points/images/1626_example_1.png new file mode 100644 index 00000000..431f3af5 Binary files /dev/null and b/assets/1200-1299/1266.Minimum Time Visiting All Points/images/1626_example_1.png differ diff --git a/assets/1200-1299/1267.Count Servers that Communicate/README_EN.md b/assets/1200-1299/1267.Count Servers that Communicate/README_EN.md new file mode 100644 index 00000000..efc043a8 --- /dev/null +++ b/assets/1200-1299/1267.Count Servers that Communicate/README_EN.md @@ -0,0 +1,75 @@ +# [1267. Count Servers that Communicate](https://leetcode.com/problems/count-servers-that-communicate) + + + +## Description + +

    You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
    +
    +Return the number of servers that communicate with any other server.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [[1,0],[0,1]]
    +Output: 0
    +Explanation: No servers can communicate with others.
    + +

    Example 2:

    + +

    + +
    +Input: grid = [[1,0],[1,1]]
    +Output: 3
    +Explanation: All three servers can communicate with at least one other server.
    +
    + +

    Example 3:

    + +

    + +
    +Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
    +Output: 4
    +Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 250
    • +
    • 1 <= n <= 250
    • +
    • grid[i][j] == 0 or 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-1-3.jpg b/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-1-3.jpg new file mode 100644 index 00000000..60cb6dab Binary files /dev/null and b/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-1-3.jpg differ diff --git a/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-4-1.jpg b/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-4-1.jpg new file mode 100644 index 00000000..a1ac4100 Binary files /dev/null and b/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-4-1.jpg differ diff --git a/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-6.jpg b/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-6.jpg new file mode 100644 index 00000000..c1403ec4 Binary files /dev/null and b/assets/1200-1299/1267.Count Servers that Communicate/images/untitled-diagram-6.jpg differ diff --git a/assets/1200-1299/1268.Search Suggestions System/README_EN.md b/assets/1200-1299/1268.Search Suggestions System/README_EN.md new file mode 100644 index 00000000..b4cfad89 --- /dev/null +++ b/assets/1200-1299/1268.Search Suggestions System/README_EN.md @@ -0,0 +1,84 @@ +# [1268. Search Suggestions System](https://leetcode.com/problems/search-suggestions-system) + + + +## Description + +

    Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

    + +

    Return list of lists of the suggested products after each character of searchWord is typed. 

    + +

     

    +

    Example 1:

    + +
    +Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
    +Output: [
    +["mobile","moneypot","monitor"],
    +["mobile","moneypot","monitor"],
    +["mouse","mousepad"],
    +["mouse","mousepad"],
    +["mouse","mousepad"]
    +]
    +Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
    +After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
    +After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
    +
    + +

    Example 2:

    + +
    +Input: products = ["havana"], searchWord = "havana"
    +Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
    +
    + +

    Example 3:

    + +
    +Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
    +Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
    +
    + +

    Example 4:

    + +
    +Input: products = ["havana"], searchWord = "tatiana"
    +Output: [[],[],[],[],[],[],[]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= products.length <= 1000
    • +
    • There are no repeated elements in products.
    • +
    • 1 <= Σ products[i].length <= 2 * 10^4
    • +
    • All characters of products[i] are lower-case English letters.
    • +
    • 1 <= searchWord.length <= 1000
    • +
    • All characters of searchWord are lower-case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md b/assets/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md new file mode 100644 index 00000000..882c3dfe --- /dev/null +++ b/assets/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md @@ -0,0 +1,74 @@ +# [1269. Number of Ways to Stay in the Same Place After Some Steps](https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps) + + + +## Description + +

    You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place  (The pointer should not be placed outside the array at any time).

    + +

    Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps.

    + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: steps = 3, arrLen = 2
    +Output: 4
    +Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
    +Right, Left, Stay
    +Stay, Right, Left
    +Right, Stay, Left
    +Stay, Stay, Stay
    +
    + +

    Example 2:

    + +
    +Input: steps = 2, arrLen = 4
    +Output: 2
    +Explanation: There are 2 differents ways to stay at index 0 after 2 steps
    +Right, Left
    +Stay, Stay
    +
    + +

    Example 3:

    + +
    +Input: steps = 4, arrLen = 2
    +Output: 8
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= steps <= 500
    • +
    • 1 <= arrLen <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1270.All People Report to the Given Manager/README_EN.md b/assets/1200-1299/1270.All People Report to the Given Manager/README_EN.md new file mode 100644 index 00000000..5596f2c8 --- /dev/null +++ b/assets/1200-1299/1270.All People Report to the Given Manager/README_EN.md @@ -0,0 +1,129 @@ +# [1270. All People Report to the Given Manager](https://leetcode.com/problems/all-people-report-to-the-given-manager) + + + +## Description + +

    Table: Employees

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| employee_id   | int     |
    +
    +| employee_name | varchar |
    +
    +| manager_id    | int     |
    +
    ++---------------+---------+
    +
    +employee_id is the primary key for this table.
    +
    +Each row of this table indicates that the employee with ID employee_id and name employee_name reports his work to his/her direct manager with manager_id
    +
    +The head of the company is the employee with employee_id = 1.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to find employee_id of all employees that directly or indirectly report their work to the head of the company.

    + + + +

    The indirect relation between managers will not exceed 3 managers as the company is small.

    + + + +

    Return result table in any order without duplicates.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Employees table:
    +
    ++-------------+---------------+------------+
    +
    +| employee_id | employee_name | manager_id |
    +
    ++-------------+---------------+------------+
    +
    +| 1           | Boss          | 1          |
    +
    +| 3           | Alice         | 3          |
    +
    +| 2           | Bob           | 1          |
    +
    +| 4           | Daniel        | 2          |
    +
    +| 7           | Luis          | 4          |
    +
    +| 8           | Jhon          | 3          |
    +
    +| 9           | Angela        | 8          |
    +
    +| 77          | Robert        | 1          |
    +
    ++-------------+---------------+------------+
    +
    +
    +
    +Result table:
    +
    ++-------------+
    +
    +| employee_id |
    +
    ++-------------+
    +
    +| 2           |
    +
    +| 77          |
    +
    +| 4           |
    +
    +| 7           |
    +
    ++-------------+
    +
    +
    +
    +The head of the company is the employee with employee_id 1.
    +
    +The employees with employee_id 2 and 77 report their work directly to the head of the company.
    +
    +The employee with employee_id 4 report his work indirectly to the head of the company 4 --> 2 --> 1. 
    +
    +The employee with employee_id 7 report his work indirectly to the head of the company 7 --> 4 --> 2 --> 1.
    +
    +The employees with employee_id 3, 8 and 9 don't report their work to head of company directly or indirectly. 
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1271.Hexspeak/README_EN.md b/assets/1200-1299/1271.Hexspeak/README_EN.md new file mode 100644 index 00000000..45093881 --- /dev/null +++ b/assets/1200-1299/1271.Hexspeak/README_EN.md @@ -0,0 +1,59 @@ +# [1271. Hexspeak](https://leetcode.com/problems/hexspeak) + + + +## Description + +

    A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit 0 with the letter O, and the digit 1 with the letter I.  Such a representation is valid if and only if it consists only of the letters in the set {"A", "B", "C", "D", "E", "F", "I", "O"}.

    + +

    Given a string num representing a decimal integer N, return the Hexspeak representation of N if it is valid, otherwise return "ERROR".

    + +

     

    +

    Example 1:

    + +
    +Input: num = "257"
    +Output: "IOI"
    +Explanation:  257 is 101 in hexadecimal.
    +
    + +

    Example 2:

    + +
    +Input: num = "3"
    +Output: "ERROR"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= N <= 10^12
    • +
    • There are no leading zeros in the given string.
    • +
    • All answers must be in uppercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1272.Remove Interval/README_EN.md b/assets/1200-1299/1272.Remove Interval/README_EN.md new file mode 100644 index 00000000..9ac824a6 --- /dev/null +++ b/assets/1200-1299/1272.Remove Interval/README_EN.md @@ -0,0 +1,66 @@ +# [1272. Remove Interval](https://leetcode.com/problems/remove-interval) + + + +## Description + +

    A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b).

    + +

    You are given a sorted list of disjoint intervals intervals representing a set of real numbers as described above, where intervals[i] = [ai, bi] represents the interval [ai, bi). You are also given another interval toBeRemoved.

    + +

    Return the set of real numbers with the interval toBeRemoved removed from intervals. In other words, return the set of real numbers such that every x in the set is in intervals but not in toBeRemoved. Your answer should be a sorted list of disjoint intervals as described above.

    + +

     

    +

    Example 1:

    + +
    +Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
    +Output: [[0,1],[6,7]]
    +
    + +

    Example 2:

    + +
    +Input: intervals = [[0,5]], toBeRemoved = [2,3]
    +Output: [[0,2],[3,5]]
    +
    + +

    Example 3:

    + +
    +Input: intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
    +Output: [[-5,-4],[-3,-2],[4,5],[8,9]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= intervals.length <= 104
    • +
    • -109 <= ai < bi <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1272.Remove Interval/images/removeintervalex1.png b/assets/1200-1299/1272.Remove Interval/images/removeintervalex1.png new file mode 100644 index 00000000..92db19ac Binary files /dev/null and b/assets/1200-1299/1272.Remove Interval/images/removeintervalex1.png differ diff --git a/assets/1200-1299/1272.Remove Interval/images/removeintervalex2.png b/assets/1200-1299/1272.Remove Interval/images/removeintervalex2.png new file mode 100644 index 00000000..22df93ab Binary files /dev/null and b/assets/1200-1299/1272.Remove Interval/images/removeintervalex2.png differ diff --git a/assets/1200-1299/1273.Delete Tree Nodes/README_EN.md b/assets/1200-1299/1273.Delete Tree Nodes/README_EN.md new file mode 100644 index 00000000..1dea46ec --- /dev/null +++ b/assets/1200-1299/1273.Delete Tree Nodes/README_EN.md @@ -0,0 +1,84 @@ +# [1273. Delete Tree Nodes](https://leetcode.com/problems/delete-tree-nodes) + + + +## Description + +

    A tree rooted at node 0 is given as follows:

    + +
      +
    • The number of nodes is nodes;
    • +
    • The value of the i-th node is value[i];
    • +
    • The parent of the i-th node is parent[i].
    • +
    + +

    Remove every subtree whose sum of values of nodes is zero.

    + +

    After doing so, return the number of nodes remaining in the tree.

    + +

     

    +

    Example 1:

    + +
    +Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
    +Output: 2
    +
    + +

    Example 2:

    + +
    +Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2]
    +Output: 6
    +
    + +

    Example 3:

    + +
    +Input: nodes = 5, parent = [-1,0,1,0,0], value = [-672,441,18,728,378]
    +Output: 5
    +
    + +

    Example 4:

    + +
    +Input: nodes = 5, parent = [-1,0,0,1,1], value = [-686,-842,616,-739,-746]
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nodes <= 10^4
    • +
    • parent.length == nodes
    • +
    • 0 <= parent[i] <= nodes - 1
    • +
    • parent[0] == -1 which indicates that 0 is the root.
    • +
    • value.length == nodes
    • +
    • -10^5 <= value[i] <= 10^5
    • +
    • The given input is guaranteed to represent a valid tree.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1273.Delete Tree Nodes/images/1421_sample_1.png b/assets/1200-1299/1273.Delete Tree Nodes/images/1421_sample_1.png new file mode 100644 index 00000000..549a5732 Binary files /dev/null and b/assets/1200-1299/1273.Delete Tree Nodes/images/1421_sample_1.png differ diff --git a/assets/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md b/assets/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md new file mode 100644 index 00000000..c184f768 --- /dev/null +++ b/assets/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md @@ -0,0 +1,62 @@ +# [1274. Number of Ships in a Rectangle](https://leetcode.com/problems/number-of-ships-in-a-rectangle) + + + +## Description + +

    (This problem is an interactive problem.)

    + +

    Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship.

    + +

    You have a function Sea.hasShips(topRight, bottomLeft) which takes two points as arguments and returns true If there is at least one ship in the rectangle represented by the two points, including on the boundary.

    + +

    Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are at most 10 ships in that rectangle.

    + +

    Submissions making more than 400 calls to hasShips will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

    + +

     

    +

    Example :

    + +

    + +
    +Input: 
    +ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0]
    +Output: 3
    +Explanation: From [0,0] to [4,4] we can count 3 ships within the range.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • On the input ships is only given to initialize the map internally. You must solve this problem "blindfolded". In other words, you must find the answer using the given hasShips API, without knowing the ships position.
    • +
    • 0 <= bottomLeft[0] <= topRight[0] <= 1000
    • +
    • 0 <= bottomLeft[1] <= topRight[1] <= 1000
    • +
    • topRight != bottomLeft
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1274.Number of Ships in a Rectangle/images/1445_example_1.png b/assets/1200-1299/1274.Number of Ships in a Rectangle/images/1445_example_1.png new file mode 100644 index 00000000..2b110148 Binary files /dev/null and b/assets/1200-1299/1274.Number of Ships in a Rectangle/images/1445_example_1.png differ diff --git a/assets/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md b/assets/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md new file mode 100644 index 00000000..e14d5b56 --- /dev/null +++ b/assets/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md @@ -0,0 +1,187 @@ +# [1275. Find Winner on a Tic Tac Toe Game](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game) + + + +## Description + +

    Tic-tac-toe is played by two players A and B on a 3 x 3 grid.

    + +

    Here are the rules of Tic-Tac-Toe:

    + +
      +
    • Players take turns placing characters into empty squares (" ").
    • +
    • The first player A always places "X" characters, while the second player B always places "O" characters.
    • +
    • "X" and "O" characters are always placed into empty squares, never on filled ones.
    • +
    • The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
    • +
    • The game also ends if all squares are non-empty.
    • +
    • No more moves can be played if the game is over.
    • +
    + +

    Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play.

    + +

    Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".

    + +

    You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
    +
    +Output: "A"
    +
    +Explanation: "A" wins, he always plays first.
    +
    +"X  "    "X  "    "X  "    "X  "    "X  "
    +
    +"   " -> "   " -> " X " -> " X " -> " X "
    +
    +"   "    "O  "    "O  "    "OO "    "OOX"
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
    +
    +Output: "B"
    +
    +Explanation: "B" wins.
    +
    +"X  "    "X  "    "XX "    "XXO"    "XXO"    "XXO"
    +
    +"   " -> " O " -> " O " -> " O " -> "XO " -> "XO " 
    +
    +"   "    "   "    "   "    "   "    "   "    "O  "
    +
    +
    + +

    Example 3:

    + +
    +
    +Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
    +
    +Output: "Draw"
    +
    +Explanation: The game ends in a draw since there are no moves to make.
    +
    +"XXO"
    +
    +"OOX"
    +
    +"XOX"
    +
    +
    + +

    Example 4:

    + +
    +
    +Input: moves = [[0,0],[1,1]]
    +
    +Output: "Pending"
    +
    +Explanation: The game has not finished yet.
    +
    +"X  "
    +
    +" O "
    +
    +"   "
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 1 <= moves.length <= 9
    • +
    • moves[i].length == 2
    • +
    • 0 <= moves[i][j] <= 2
    • +
    • There are no repeated elements on moves.
    • +
    • moves follow the rules of tic tac toe.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def tictactoe(self, moves: List[List[int]]) -> str: + n = len(moves) + counter = [0] * 8 + for i in range(n - 1, -1, -2): + row, col = moves[i][0], moves[i][1] + counter[row] += 1 + counter[col + 3] += 1 + if row == col: + counter[6] += 1 + if row + col == 2: + counter[7] += 1 + if counter[row] == 3 or counter[col + 3] == 3 or counter[6] == 3 or counter[7] == 3: + return "A" if (i % 2) == 0 else "B" + return "Draw" if n == 9 else "Pending" +``` + +### **Java** + +```java +class Solution { + public String tictactoe(int[][] moves) { + int n = moves.length; + int[] counter = new int[8]; + for (int i = n - 1; i >= 0; i -= 2) { + int row = moves[i][0], col = moves[i][1]; + ++counter[row]; + ++counter[col + 3]; + if (row == col) ++counter[6]; + if (row + col == 2) ++counter[7]; + if (counter[row] == 3 || counter[col + 3] == 3 || counter[6] == 3 || counter[7] == 3) { + return (i % 2) == 0 ? "A" : "B"; + } + } + return n == 9 ? "Draw" : "Pending"; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string tictactoe(vector>& moves) { + int n = moves.size(); + vector counter(8, 0); + for (int i = n - 1; i >= 0; i -= 2) { + int row = moves[i][0], col = moves[i][1]; + ++counter[row]; + ++counter[col + 3]; + if (row == col) ++counter[6]; + if (row + col == 2) ++counter[7]; + if (counter[row] == 3 || counter[col + 3] == 3 || counter[6] == 3 || counter[7] == 3) { + return (i % 2 == 0) ? "A" : "B"; + } + } + return n == 9 ? "Draw" : "Pending"; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md b/assets/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md new file mode 100644 index 00000000..038621de --- /dev/null +++ b/assets/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md @@ -0,0 +1,133 @@ +# [1276. Number of Burgers with No Waste of Ingredients](https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients) + + + +## Description + +

    Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:

    + + + +
      +
    • Jumbo Burger: 4 tomato slices and 1 cheese slice.
    • +
    • Small Burger: 2 Tomato slices and 1 cheese slice.
    • +
    + + + +

    Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: tomatoSlices = 16, cheeseSlices = 7
    +
    +Output: [1,6]
    +
    +Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese. There will be no remaining ingredients.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: tomatoSlices = 17, cheeseSlices = 4
    +
    +Output: []
    +
    +Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: tomatoSlices = 4, cheeseSlices = 17
    +
    +Output: []
    +
    +Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: tomatoSlices = 0, cheeseSlices = 0
    +
    +Output: [0,0]
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: tomatoSlices = 2, cheeseSlices = 1
    +
    +Output: [0,1]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= tomatoSlices <= 10^7
    • +
    • 0 <= cheeseSlices <= 10^7
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md b/assets/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md new file mode 100644 index 00000000..6737565f --- /dev/null +++ b/assets/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md @@ -0,0 +1,75 @@ +# [1277. Count Square Submatrices with All Ones](https://leetcode.com/problems/count-square-submatrices-with-all-ones) + + + +## Description + +

    Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix =
    +[
    +  [0,1,1,1],
    +  [1,1,1,1],
    +  [0,1,1,1]
    +]
    +Output: 15
    +Explanation: 
    +There are 10 squares of side 1.
    +There are 4 squares of side 2.
    +There is  1 square of side 3.
    +Total number of squares = 10 + 4 + 1 = 15.
    +
    + +

    Example 2:

    + +
    +Input: matrix = 
    +[
    +  [1,0,1],
    +  [1,1,0],
    +  [1,1,0]
    +]
    +Output: 7
    +Explanation: 
    +There are 6 squares of side 1.  
    +There is 1 square of side 2. 
    +Total number of squares = 6 + 1 = 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 300
    • +
    • 1 <= arr[0].length <= 300
    • +
    • 0 <= arr[i][j] <= 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1278.Palindrome Partitioning III/README_EN.md b/assets/1200-1299/1278.Palindrome Partitioning III/README_EN.md new file mode 100644 index 00000000..68f6e793 --- /dev/null +++ b/assets/1200-1299/1278.Palindrome Partitioning III/README_EN.md @@ -0,0 +1,101 @@ +# [1278. Palindrome Partitioning III](https://leetcode.com/problems/palindrome-partitioning-iii) + + + +## Description + +

    You are given a string s containing lowercase letters and an integer k. You need to :

    + + + +
      +
    • First, change some characters of s to other lowercase English letters.
    • +
    • Then divide s into k non-empty disjoint substrings such that each substring is palindrome.
    • +
    + + + +

    Return the minimal number of characters that you need to change to divide the string.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "abc", k = 2
    +
    +Output: 1
    +
    +Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "aabbc", k = 3
    +
    +Output: 0
    +
    +Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "leetcode", k = 8
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= k <= s.length <= 100.
    • +
    • s only contains lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md b/assets/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md new file mode 100644 index 00000000..79e068e5 --- /dev/null +++ b/assets/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md @@ -0,0 +1,91 @@ +# [1279. Traffic Light Controlled Intersection](https://leetcode.com/problems/traffic-light-controlled-intersection) + + + +## Description + +

    There is an intersection of two roads. First road is road A where cars travel from North to South in direction 1 and from South to North in direction 2. Second road is road B where cars travel from West to East in direction 3 and from East to West in direction 4.

    + +

    + +

    There is a traffic light located on each road before the intersection. A traffic light can either be green or red.

    + +
      +
    1. Green means cars can cross the intersection in both directions of the road.
    2. +
    3. Red means cars in both directions cannot cross the intersection and must wait until the light turns green.
    4. +
    + +

    The traffic lights cannot be green on both roads at the same time. That means when the light is green on road A, it is red on road B and when the light is green on road B, it is red on road A.

    + +

    Initially, the traffic light is green on road A and red on road B. When the light is green on one road, all cars can cross the intersection in both directions until the light becomes green on the other road. No two cars traveling on different roads should cross at the same time.

    + +

    Design a deadlock-free traffic light controlled system at this intersection.

    + +

    Implement the function void carArrived(carId, roadId, direction, turnGreen, crossCar) where:

    + +
      +
    • carId is the id of the car that arrived.
    • +
    • roadId is the id of the road that the car travels on.
    • +
    • direction is the direction of the car.
    • +
    • turnGreen is a function you can call to turn the traffic light to green on the current road.
    • +
    • crossCar is a function you can call to let the current car cross the intersection.
    • +
    + +

    Your answer is considered correct if it avoids cars deadlock in the intersection. Turning the light green on a road when it was already green is considered a wrong answer.

    + +

     

    +

    Example 1:

    + +
    +Input: cars = [1,3,5,2,4], directions = [2,1,2,4,3], arrivalTimes = [10,20,30,40,50]
    +Output: [
    +"Car 1 Has Passed Road A In Direction 2",    // Traffic light on road A is green, car 1 can cross the intersection.
    +"Car 3 Has Passed Road A In Direction 1",    // Car 3 crosses the intersection as the light is still green.
    +"Car 5 Has Passed Road A In Direction 2",    // Car 5 crosses the intersection as the light is still green.
    +"Traffic Light On Road B Is Green",          // Car 2 requests green light for road B.
    +"Car 2 Has Passed Road B In Direction 4",    // Car 2 crosses as the light is green on road B now.
    +"Car 4 Has Passed Road B In Direction 3"     // Car 4 crosses the intersection as the light is still green.
    +]
    +
    + +

    Example 2:

    + +
    +Input: cars = [1,2,3,4,5], directions = [2,4,3,3,1], arrivalTimes = [10,20,30,40,40]
    +Output: [
    +"Car 1 Has Passed Road A In Direction 2",    // Traffic light on road A is green, car 1 can cross the intersection.
    +"Traffic Light On Road B Is Green",          // Car 2 requests green light for road B.
    +"Car 2 Has Passed Road B In Direction 4",    // Car 2 crosses as the light is green on road B now.
    +"Car 3 Has Passed Road B In Direction 3",    // Car 3 crosses as the light is green on road B now.
    +"Traffic Light On Road A Is Green",          // Car 5 requests green light for road A.
    +"Car 5 Has Passed Road A In Direction 1",    // Car 5 crosses as the light is green on road A now.
    +"Traffic Light On Road B Is Green",          // Car 4 requests green light for road B. Car 4 blocked until car 5 crosses and then traffic light is green on road B.
    +"Car 4 Has Passed Road B In Direction 3"     // Car 4 crosses as the light is green on road B now.
    +]
    +Explanation: This is a dead-lock free scenario. Note that the scenario when car 4 crosses before turning light into green on road A and allowing car 5 to pass is also correct and Accepted scenario.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= cars.length <= 20
    • +
    • cars.length = directions.length
    • +
    • cars.length = arrivalTimes.length
    • +
    • All values of cars are unique
    • +
    • 1 <= directions[i] <= 4
    • +
    • arrivalTimes is non-decreasing
    • +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1279.Traffic Light Controlled Intersection/images/exp.png b/assets/1200-1299/1279.Traffic Light Controlled Intersection/images/exp.png new file mode 100644 index 00000000..f626bee1 Binary files /dev/null and b/assets/1200-1299/1279.Traffic Light Controlled Intersection/images/exp.png differ diff --git a/assets/1200-1299/1280.Students and Examinations/README_EN.md b/assets/1200-1299/1280.Students and Examinations/README_EN.md new file mode 100644 index 00000000..7c0b61f4 --- /dev/null +++ b/assets/1200-1299/1280.Students and Examinations/README_EN.md @@ -0,0 +1,127 @@ +# [1280. Students and Examinations](https://leetcode.com/problems/students-and-examinations) + + + +## Description + +

    Table: Students

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id is the primary key for this table.
    +Each row of this table contains the ID and the name of one student in the school.
    +
    + +

     

    + +

    Table: Subjects

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| subject_name | varchar |
    ++--------------+---------+
    +subject_name is the primary key for this table.
    +Each row of this table contains the name of one subject in the school.
    +
    + +

     

    + +

    Table: Examinations

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| student_id   | int     |
    +| subject_name | varchar |
    ++--------------+---------+
    +There is no primary key for this table. It may contain duplicates.
    +Each student from the Students table takes every course from Subjects table.
    +Each row of this table indicates that a student with ID student_id attended the exam of subject_name.
    +
    + +

     

    + +

    Write an SQL query to find the number of times each student attended each exam.

    + +

    Order the result table by student_id and subject_name.

    + +

    The query result format is in the following example:

    + +
    +Students table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 1          | Alice        |
    +| 2          | Bob          |
    +| 13         | John         |
    +| 6          | Alex         |
    ++------------+--------------+
    +Subjects table:
    ++--------------+
    +| subject_name |
    ++--------------+
    +| Math         |
    +| Physics      |
    +| Programming  |
    ++--------------+
    +Examinations table:
    ++------------+--------------+
    +| student_id | subject_name |
    ++------------+--------------+
    +| 1          | Math         |
    +| 1          | Physics      |
    +| 1          | Programming  |
    +| 2          | Programming  |
    +| 1          | Physics      |
    +| 1          | Math         |
    +| 13         | Math         |
    +| 13         | Programming  |
    +| 13         | Physics      |
    +| 2          | Math         |
    +| 1          | Math         |
    ++------------+--------------+
    +Result table:
    ++------------+--------------+--------------+----------------+
    +| student_id | student_name | subject_name | attended_exams |
    ++------------+--------------+--------------+----------------+
    +| 1          | Alice        | Math         | 3              |
    +| 1          | Alice        | Physics      | 2              |
    +| 1          | Alice        | Programming  | 1              |
    +| 2          | Bob          | Math         | 1              |
    +| 2          | Bob          | Physics      | 0              |
    +| 2          | Bob          | Programming  | 1              |
    +| 6          | Alex         | Math         | 0              |
    +| 6          | Alex         | Physics      | 0              |
    +| 6          | Alex         | Programming  | 0              |
    +| 13         | John         | Math         | 1              |
    +| 13         | John         | Physics      | 1              |
    +| 13         | John         | Programming  | 1              |
    ++------------+--------------+--------------+----------------+
    +The result table should contain all students and all subjects.
    +Alice attended Math exam 3 times, Physics exam 2 times and Programming exam 1 time.
    +Bob attended Math exam 1 time, Programming exam 1 time and didn't attend the Physics exam.
    +Alex didn't attend any exam.
    +John attended Math exam 1 time, Physics exam 1 time and Programming exam 1 time.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md b/assets/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md new file mode 100644 index 00000000..67cdfc08 --- /dev/null +++ b/assets/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md @@ -0,0 +1,61 @@ +# [1281. Subtract the Product and Sum of Digits of an Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer) + + + +## Description + +Given an integer number n, return the difference between the product of its digits and the sum of its digits. +

     

    +

    Example 1:

    + +
    +Input: n = 234
    +Output: 15 
    +Explanation: 
    +Product of digits = 2 * 3 * 4 = 24 
    +Sum of digits = 2 + 3 + 4 = 9 
    +Result = 24 - 9 = 15
    +
    + +

    Example 2:

    + +
    +Input: n = 4421
    +Output: 21
    +Explanation: 
    +Product of digits = 4 * 4 * 2 * 1 = 32 
    +Sum of digits = 4 + 4 + 2 + 1 = 11 
    +Result = 32 - 11 = 21
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md b/assets/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md new file mode 100644 index 00000000..335d051f --- /dev/null +++ b/assets/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md @@ -0,0 +1,67 @@ +# [1282. Group the People Given the Group Size They Belong To](https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to) + + + +## Description + +

    There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.

    + +

    You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.

    + +

    Return a list of groups such that each person i is in a group of size groupSizes[i].

    + +

    Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.

    + +

     

    +

    Example 1:

    + +
    +Input: groupSizes = [3,3,3,3,3,1,3]
    +Output: [[5],[0,1,2],[3,4,6]]
    +Explanation: 
    +The first group is [5]. The size is 1, and groupSizes[5] = 1.
    +The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
    +The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
    +Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
    +
    + +

    Example 2:

    + +
    +Input: groupSizes = [2,1,3,3,3,2]
    +Output: [[1],[0,5],[2,3,4]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • groupSizes.length == n
    • +
    • 1 <= n <= 500
    • +
    • 1 <= groupSizes[i] <= n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md b/assets/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md new file mode 100644 index 00000000..5cc46d68 --- /dev/null +++ b/assets/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md @@ -0,0 +1,150 @@ +# [1283. Find the Smallest Divisor Given a Threshold](https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold) + + + +## Description + +

    Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

    + +

    Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

    + +

    It is guaranteed that there will be an answer.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,5,9], threshold = 6
    +Output: 5
    +Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. 
    +If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). 
    +
    + +

    Example 2:

    + +
    +Input: nums = [44,22,33,11,1], threshold = 5
    +Output: 44
    +
    + +

    Example 3:

    + +
    +Input: nums = [21212,10101,12121], threshold = 1000000
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: nums = [2,3,5,7,11], threshold = 11
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 1 <= nums[i] <= 106
    • +
    • nums.length <= threshold <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + left, right = 1, 1000000 + while left < right: + mid = (left + right) >> 1 + s = 0 + for num in nums: + s += (num + mid - 1) // mid + if s <= threshold: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int smallestDivisor(int[] nums, int threshold) { + int left = 1, right = 1000000; + while (left < right) { + int mid = (left + right) >> 1; + int s = 0; + for (int num : nums) { + s += (num + mid - 1) / mid; + } + if (s <= threshold) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int smallestDivisor(vector& nums, int threshold) { + int left = 1, right = 1000000; + while (left < right) { + int mid = left + right >> 1; + int s = 0; + for (int& num : nums) { + s += (num + mid - 1) / mid; + } + if (s <= threshold) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func smallestDivisor(nums []int, threshold int) int { + left, right := 1, 1000000 + for left < right { + mid := (left + right) >> 1 + s := 0 + for _, num := range nums { + s += (num + mid - 1) / mid + } + if s <= threshold { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md b/assets/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md new file mode 100644 index 00000000..2b49d2c5 --- /dev/null +++ b/assets/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md @@ -0,0 +1,81 @@ +# [1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix](https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix) + + + +## Description + +

    Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.

    + +

    Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.

    + +

    Binary matrix is a matrix with all cells equal to 0 or 1 only.

    + +

    Zero matrix is a matrix with all cells equal to 0.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[0,0],[0,1]]
    +Output: 3
    +Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
    +
    + +

    Example 2:

    + +
    +Input: mat = [[0]]
    +Output: 0
    +Explanation: Given matrix is a zero matrix. We don't need to change it.
    +
    + +

    Example 3:

    + +
    +Input: mat = [[1,1,1],[1,0,1],[0,0,0]]
    +Output: 6
    +
    + +

    Example 4:

    + +
    +Input: mat = [[1,0,0],[1,0,0]]
    +Output: -1
    +Explanation: Given matrix can't be a zero matrix
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[0].length
    • +
    • 1 <= m <= 3
    • +
    • 1 <= n <= 3
    • +
    • mat[i][j] is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/images/matrix.png b/assets/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/images/matrix.png new file mode 100644 index 00000000..426cc3dd Binary files /dev/null and b/assets/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/images/matrix.png differ diff --git a/assets/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md b/assets/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md new file mode 100644 index 00000000..8fa065eb --- /dev/null +++ b/assets/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md @@ -0,0 +1,111 @@ +# [1285. Find the Start and End Number of Continuous Ranges](https://leetcode.com/problems/find-the-start-and-end-number-of-continuous-ranges) + + + +## Description + +

    Table: Logs

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| log_id        | int     |
    +
    ++---------------+---------+
    +
    +id is the primary key for this table.
    +
    +Each row of this table contains the ID in a log Table.
    +
    +
    +
    +
    + + + +

    Since some IDs have been removed from Logs. Write an SQL query to find the start and end number of continuous ranges in table Logs.

    + + + +

    Order the result table by start_id.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Logs table:
    +
    ++------------+
    +
    +| log_id     |
    +
    ++------------+
    +
    +| 1          |
    +
    +| 2          |
    +
    +| 3          |
    +
    +| 7          |
    +
    +| 8          |
    +
    +| 10         |
    +
    ++------------+
    +
    +
    +
    +Result table:
    +
    ++------------+--------------+
    +
    +| start_id   | end_id       |
    +
    ++------------+--------------+
    +
    +| 1          | 3            |
    +
    +| 7          | 8            |
    +
    +| 10         | 10           |
    +
    ++------------+--------------+
    +
    +The result table should contain all ranges in table Logs.
    +
    +From 1 to 3 is contained in the table.
    +
    +From 4 to 6 is missing in the table
    +
    +From 7 to 8 is contained in the table.
    +
    +Number 9 is missing in the table.
    +
    +Number 10 is contained in the table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1286.Iterator for Combination/README_EN.md b/assets/1200-1299/1286.Iterator for Combination/README_EN.md new file mode 100644 index 00000000..57d02e39 --- /dev/null +++ b/assets/1200-1299/1286.Iterator for Combination/README_EN.md @@ -0,0 +1,68 @@ +# [1286. Iterator for Combination](https://leetcode.com/problems/iterator-for-combination) + + + +## Description + +

    Design the CombinationIterator class:

    + +
      +
    • CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
    • +
    • next() Returns the next combination of length combinationLength in lexicographical order.
    • +
    • hasNext() Returns true if and only if there exists a next combination.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
    +[["abc", 2], [], [], [], [], [], []]
    +Output
    +[null, "ab", true, "ac", true, "bc", false]
    +
    +Explanation
    +CombinationIterator itr = new CombinationIterator("abc", 2);
    +itr.next();    // return "ab"
    +itr.hasNext(); // return True
    +itr.next();    // return "ac"
    +itr.hasNext(); // return True
    +itr.next();    // return "bc"
    +itr.hasNext(); // return False
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= combinationLength <= characters.length <= 15
    • +
    • All the characters of characters are unique.
    • +
    • At most 104 calls will be made to next and hasNext.
    • +
    • It's guaranteed that all calls of the function next are valid.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md b/assets/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md new file mode 100644 index 00000000..621835f3 --- /dev/null +++ b/assets/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md @@ -0,0 +1,55 @@ +# [1287. Element Appearing More Than 25% In Sorted Array](https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array) + + + +## Description + +

    Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,2,6,6,6,6,7,10]
    +Output: 6
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,1]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 0 <= arr[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1288.Remove Covered Intervals/README_EN.md b/assets/1200-1299/1288.Remove Covered Intervals/README_EN.md new file mode 100644 index 00000000..d0afcb74 --- /dev/null +++ b/assets/1200-1299/1288.Remove Covered Intervals/README_EN.md @@ -0,0 +1,128 @@ +# [1288. Remove Covered Intervals](https://leetcode.com/problems/remove-covered-intervals) + + + +## Description + +

    Given a list of intervals, remove all intervals that are covered by another interval in the list.

    + + + +

    Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.

    + + + +

    After doing so, return the number of remaining intervals.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: intervals = [[1,4],[3,6],[2,8]]
    +
    +Output: 2
    +
    +Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: intervals = [[1,4],[2,3]]
    +
    +Output: 1
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: intervals = [[0,10],[5,12]]
    +
    +Output: 2
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: intervals = [[3,10],[4,10],[5,11]]
    +
    +Output: 2
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: intervals = [[1,2],[1,4],[3,4]]
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= intervals.length <= 1000
    • +
    • intervals[i].length == 2
    • +
    • 0 <= intervals[i][0] < intervals[i][1] <= 10^5
    • +
    • All the intervals are unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md b/assets/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md new file mode 100644 index 00000000..04da0526 --- /dev/null +++ b/assets/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md @@ -0,0 +1,56 @@ +# [1289. Minimum Falling Path Sum II](https://leetcode.com/problems/minimum-falling-path-sum-ii) + + + +## Description + +

    Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column.

    + +

    Return the minimum sum of a falling path with non-zero shifts.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [[1,2,3],[4,5,6],[7,8,9]]
    +Output: 13
    +Explanation: 
    +The possible falling paths are:
    +[1,5,9], [1,5,7], [1,6,7], [1,6,8],
    +[2,4,8], [2,4,9], [2,6,7], [2,6,8],
    +[3,4,8], [3,4,9], [3,5,7], [3,5,9]
    +The falling path with the smallest sum is [1,5,7], so the answer is 13.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length == arr[i].length <= 200
    • +
    • -99 <= arr[i][j] <= 99
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md b/assets/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md new file mode 100644 index 00000000..58e42ee2 --- /dev/null +++ b/assets/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md @@ -0,0 +1,176 @@ +# [1290. Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer) + + + +## Description + +

    Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

    + +

    Return the decimal value of the number in the linked list.

    + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: head = [1,0,1]
    +
    +Output: 5
    +
    +Explanation: (101) in base 2 = (5) in base 10
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: head = [0]
    +
    +Output: 0
    +
    +
    + +

    Example 3:

    + +
    +
    +Input: head = [1]
    +
    +Output: 1
    +
    +
    + +

    Example 4:

    + +
    +
    +Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
    +
    +Output: 18880
    +
    +
    + +

    Example 5:

    + +
    +
    +Input: head = [0,0]
    +
    +Output: 0
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • The Linked List is not empty.
    • +
    • Number of nodes will not exceed 30.
    • +
    • Each node's value is either 0 or 1.
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def getDecimalValue(self, head: ListNode) -> int: + res = 0 + while head: + res = (res << 1) + head.val + head = head.next + return res +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public int getDecimalValue(ListNode head) { + int res = 0; + while (head != null) { + res = (res << 1) + head.val; + head = head.next; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number} + */ +var getDecimalValue = function(head) { + let res = 0; + while (head != null) { + res = (res << 1) + head.val; + head = head.next; + } + return res; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + int getDecimalValue(ListNode* head) { + int res = 0; + while (head != NULL) { + res = (res << 1) + head->val; + head = head->next; + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1290.Convert Binary Number in a Linked List to Integer/images/graph-1.png b/assets/1200-1299/1290.Convert Binary Number in a Linked List to Integer/images/graph-1.png new file mode 100644 index 00000000..7fd4b0c6 Binary files /dev/null and b/assets/1200-1299/1290.Convert Binary Number in a Linked List to Integer/images/graph-1.png differ diff --git a/assets/1200-1299/1291.Sequential Digits/README_EN.md b/assets/1200-1299/1291.Sequential Digits/README_EN.md new file mode 100644 index 00000000..9626d7d4 --- /dev/null +++ b/assets/1200-1299/1291.Sequential Digits/README_EN.md @@ -0,0 +1,49 @@ +# [1291. Sequential Digits](https://leetcode.com/problems/sequential-digits) + + + +## Description + +

    An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

    + +

    Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

    + +

     

    +

    Example 1:

    +
    Input: low = 100, high = 300
    +Output: [123,234]
    +

    Example 2:

    +
    Input: low = 1000, high = 13000
    +Output: [1234,2345,3456,4567,5678,6789,12345]
    +
    +

     

    +

    Constraints:

    + +
      +
    • 10 <= low <= high <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md b/assets/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md new file mode 100644 index 00000000..dea7761c --- /dev/null +++ b/assets/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md @@ -0,0 +1,73 @@ +# [1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold](https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold) + + + +## Description + +

    Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
    +Output: 2
    +Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
    +
    + +

    Example 2:

    + +
    +Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
    +Output: 0
    +
    + +

    Example 3:

    + +
    +Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
    +Output: 3
    +
    + +

    Example 4:

    + +
    +Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= m, n <= 300
    • +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 0 <= mat[i][j] <= 10000
    • +
    • 0 <= threshold <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/images/e1.png b/assets/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/images/e1.png new file mode 100644 index 00000000..e2a20c40 Binary files /dev/null and b/assets/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/images/e1.png differ diff --git a/assets/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md b/assets/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md new file mode 100644 index 00000000..6795ea3c --- /dev/null +++ b/assets/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md @@ -0,0 +1,80 @@ +# [1293. Shortest Path in a Grid with Obstacles Elimination](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination) + + + +## Description + +

    Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.

    + +

    Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: 
    +grid = 
    +[[0,0,0],
    + [1,1,0],
    + [0,0,0],
    + [0,1,1],
    + [0,0,0]], 
    +k = 1
    +Output: 6
    +Explanation: 
    +The shortest path without eliminating any obstacle is 10. 
    +The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
    +
    + +

     

    + +

    Example 2:

    + +
    +Input: 
    +grid = 
    +[[0,1,1],
    + [1,1,1],
    + [1,0,0]], 
    +k = 1
    +Output: -1
    +Explanation: 
    +We need to eliminate at least two obstacles to find such a walk.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • grid.length == m
    • +
    • grid[0].length == n
    • +
    • 1 <= m, n <= 40
    • +
    • 1 <= k <= m*n
    • +
    • grid[i][j] == 0 or 1
    • +
    • grid[0][0] == grid[m-1][n-1] == 0
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1294.Weather Type in Each Country/README_EN.md b/assets/1200-1299/1294.Weather Type in Each Country/README_EN.md new file mode 100644 index 00000000..a92c626d --- /dev/null +++ b/assets/1200-1299/1294.Weather Type in Each Country/README_EN.md @@ -0,0 +1,197 @@ +# [1294. Weather Type in Each Country](https://leetcode.com/problems/weather-type-in-each-country) + + + +## Description + +

    Table: Countries

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| country_id    | int     |
    +
    +| country_name  | varchar |
    +
    ++---------------+---------+
    +
    +country_id is the primary key for this table.
    +
    +Each row of this table contains the ID and the name of one country.
    +
    +
    + + + +

     

    + + + +

    Table: Weather

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| country_id    | int     |
    +
    +| weather_state | varchar |
    +
    +| day           | date    |
    +
    ++---------------+---------+
    +
    +(country_id, day) is the primary key for this table.
    +
    +Each row of this table indicates the weather state in a country for one day.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to find the type of weather in each country for November 2019.

    + + + +

    The type of weather is Cold if the average weather_state is less than or equal 15, Hot if the average weather_state is greater than or equal 25 and Warm otherwise.

    + + + +

    Return result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +Countries table:
    +
    ++------------+--------------+
    +
    +| country_id | country_name |
    +
    ++------------+--------------+
    +
    +| 2          | USA          |
    +
    +| 3          | Australia    |
    +
    +| 7          | Peru         |
    +
    +| 5          | China        |
    +
    +| 8          | Morocco      |
    +
    +| 9          | Spain        |
    +
    ++------------+--------------+
    +
    +Weather table:
    +
    ++------------+---------------+------------+
    +
    +| country_id | weather_state | day        |
    +
    ++------------+---------------+------------+
    +
    +| 2          | 15            | 2019-11-01 |
    +
    +| 2          | 12            | 2019-10-28 |
    +
    +| 2          | 12            | 2019-10-27 |
    +
    +| 3          | -2            | 2019-11-10 |
    +
    +| 3          | 0             | 2019-11-11 |
    +
    +| 3          | 3             | 2019-11-12 |
    +
    +| 5          | 16            | 2019-11-07 |
    +
    +| 5          | 18            | 2019-11-09 |
    +
    +| 5          | 21            | 2019-11-23 |
    +
    +| 7          | 25            | 2019-11-28 |
    +
    +| 7          | 22            | 2019-12-01 |
    +
    +| 7          | 20            | 2019-12-02 |
    +
    +| 8          | 25            | 2019-11-05 |
    +
    +| 8          | 27            | 2019-11-15 |
    +
    +| 8          | 31            | 2019-11-25 |
    +
    +| 9          | 7             | 2019-10-23 |
    +
    +| 9          | 3             | 2019-12-23 |
    +
    ++------------+---------------+------------+
    +
    +Result table:
    +
    ++--------------+--------------+
    +
    +| country_name | weather_type |
    +
    ++--------------+--------------+
    +
    +| USA          | Cold         |
    +
    +| Austraila    | Cold         |
    +
    +| Peru         | Hot          |
    +
    +| China        | Warm         |
    +
    +| Morocco      | Hot          |
    +
    ++--------------+--------------+
    +
    +Average weather_state in USA in November is (15) / 1 = 15 so weather type is Cold.
    +
    +Average weather_state in Austraila in November is (-2 + 0 + 3) / 3 = 0.333 so weather type is Cold.
    +
    +Average weather_state in Peru in November is (25) / 1 = 25 so weather type is Hot.
    +
    +Average weather_state in China in November is (16 + 18 + 21) / 3 = 18.333 so weather type is Warm.
    +
    +Average weather_state in Morocco in November is (25 + 27 + 31) / 3 = 27.667 so weather type is Hot.
    +
    +We know nothing about average weather_state in Spain in November so we don't include it in the result table. 
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md b/assets/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md new file mode 100644 index 00000000..26848b87 --- /dev/null +++ b/assets/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md @@ -0,0 +1,76 @@ +# [1295. Find Numbers with Even Number of Digits](https://leetcode.com/problems/find-numbers-with-even-number-of-digits) + + + +## Description + +Given an array nums of integers, return how many of them contain an even number of digits. +

     

    +

    Example 1:

    + +
    +Input: nums = [12,345,2,6,7896]
    +Output: 2
    +Explanation: 
    +12 contains 2 digits (even number of digits). 
    +345 contains 3 digits (odd number of digits). 
    +2 contains 1 digit (odd number of digits). 
    +6 contains 1 digit (odd number of digits). 
    +7896 contains 4 digits (even number of digits). 
    +Therefore only 12 and 7896 contain an even number of digits.
    +
    + +

    Example 2:

    + +
    +Input: nums = [555,901,482,1771]
    +Output: 1 
    +Explanation: 
    +Only 1771 contains an even number of digits.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 500
    • +
    • 1 <= nums[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findNumbers(self, nums: List[int]) -> int: + res = 0 + for num in nums: + res += (len(str(num)) & 1) == 0 + return res +``` + +### **Java** + +```java +class Solution { + public int findNumbers(int[] nums) { + int res = 0; + for (int num : nums) { + res += (String.valueOf(num).length() & 1) == 0 ? 1 : 0; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md b/assets/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md new file mode 100644 index 00000000..c7cd6d7d --- /dev/null +++ b/assets/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md @@ -0,0 +1,75 @@ +# [1296. Divide Array in Sets of K Consecutive Numbers](https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers) + + + +## Description + +

    Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers
    +Return True if it is possible. Otherwise, return False.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,3,4,4,5,6], k = 4
    +Output: true
    +Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
    +Output: true
    +Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
    +
    + +

    Example 3:

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

    Example 4:

    + +
    +Input: nums = [1,2,3,4], k = 3
    +Output: false
    +Explanation: Each array should be divided in subarrays of size 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    + +

     

    +Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/ + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md b/assets/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md new file mode 100644 index 00000000..5d5fc206 --- /dev/null +++ b/assets/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md @@ -0,0 +1,117 @@ +# [1297. Maximum Number of Occurrences of a Substring](https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring) + + + +## Description + +

    Given a string s, return the maximum number of ocurrences of any substring under the following rules:

    + + + +
      +
    • The number of unique characters in the substring must be less than or equal to maxLetters.
    • +
    • The substring size must be between minSize and maxSize inclusive.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
    +
    +Output: 2
    +
    +Explanation: Substring "aab" has 2 ocurrences in the original string.
    +
    +It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
    +
    +Output: 2
    +
    +Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3
    +
    +Output: 3
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 10^5
    • +
    • 1 <= maxLetters <= 26
    • +
    • 1 <= minSize <= maxSize <= min(26, s.length)
    • +
    • s only contains lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md b/assets/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md new file mode 100644 index 00000000..5e27f9e9 --- /dev/null +++ b/assets/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md @@ -0,0 +1,152 @@ +# [1298. Maximum Candies You Can Get from Boxes](https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes) + + + +## Description + +

    Given n boxes, each box is given in the format [status, candies, keys, containedBoxes] where:

    + + + +
      +
    • status[i]: an integer which is 1 if box[i] is open and 0 if box[i] is closed.
    • +
    • candies[i]: an integer representing the number of candies in box[i].
    • +
    • keys[i]: an array contains the indices of the boxes you can open with the key in box[i].
    • +
    • containedBoxes[i]: an array contains the indices of the boxes found in box[i].
    • +
    + + + +

    You will start with some boxes given in initialBoxes array. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.

    + + + +

    Return the maximum number of candies you can get following the rules above.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
    +
    +Output: 16
    +
    +Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you don't have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
    +
    +In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
    +
    +Total number of candies collected = 7 + 4 + 5 = 16 candy.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
    +
    +Output: 6
    +
    +Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]
    +
    +Output: 1
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []
    +
    +Output: 0
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]
    +
    +Output: 7
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= status.length <= 1000
    • +
    • status.length == candies.length == keys.length == containedBoxes.length == n
    • +
    • status[i] is 0 or 1.
    • +
    • 1 <= candies[i] <= 1000
    • +
    • 0 <= keys[i].length <= status.length
    • +
    • 0 <= keys[i][j] < status.length
    • +
    • All values in keys[i] are unique.
    • +
    • 0 <= containedBoxes[i].length <= status.length
    • +
    • 0 <= containedBoxes[i][j] < status.length
    • +
    • All values in containedBoxes[i] are unique.
    • +
    • Each box is contained in one box at most.
    • +
    • 0 <= initialBoxes.length <= status.length
    • +
    • 0 <= initialBoxes[i] < status.length
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md b/assets/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md new file mode 100644 index 00000000..da77bbce --- /dev/null +++ b/assets/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md @@ -0,0 +1,81 @@ +# [1299. Replace Elements with Greatest Element on Right Side](https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side) + + + +## Description + +

    Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

    + +

    After doing so, return the array.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [17,18,5,4,6,1]
    +Output: [18,6,6,6,1,-1]
    +Explanation: 
    +- index 0 --> the greatest element to the right of index 0 is index 1 (18).
    +- index 1 --> the greatest element to the right of index 1 is index 4 (6).
    +- index 2 --> the greatest element to the right of index 2 is index 4 (6).
    +- index 3 --> the greatest element to the right of index 3 is index 4 (6).
    +- index 4 --> the greatest element to the right of index 4 is index 5 (1).
    +- index 5 --> there are no elements to the right of index 5, so we put -1.
    +
    + +

    Example 2:

    + +
    +Input: arr = [400]
    +Output: [-1]
    +Explanation: There are no elements to the right of index 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 1 <= arr[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def replaceElements(self, arr: List[int]) -> List[int]: + m = -1 + for i in range(len(arr) - 1, -1, -1): + t = arr[i] + arr[i] = m + m = max(m, t) + return arr +``` + +### **Java** + +```java +class Solution { + public int[] replaceElements(int[] arr) { + for (int i = arr.length - 1, max = -1; i >= 0; --i) { + int t = arr[i]; + arr[i] = max; + max = Math.max(max, t); + } + return arr; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md b/assets/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md new file mode 100644 index 00000000..ff6868ef --- /dev/null +++ b/assets/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md @@ -0,0 +1,67 @@ +# [1300. Sum of Mutated Array Closest to Target](https://leetcode.com/problems/sum-of-mutated-array-closest-to-target) + + + +## Description + +

    Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.

    + +

    In case of a tie, return the minimum such integer.

    + +

    Notice that the answer is not neccesarilly a number from arr.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [4,9,3], target = 10
    +Output: 3
    +Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.
    +
    + +

    Example 2:

    + +
    +Input: arr = [2,3,5], target = 10
    +Output: 5
    +
    + +

    Example 3:

    + +
    +Input: arr = [60864,25176,27249,21296,20204], target = 56803
    +Output: 11361
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 10^4
    • +
    • 1 <= arr[i], target <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1301.Number of Paths with Max Score/README_EN.md b/assets/1300-1399/1301.Number of Paths with Max Score/README_EN.md new file mode 100644 index 00000000..77c6b345 --- /dev/null +++ b/assets/1300-1399/1301.Number of Paths with Max Score/README_EN.md @@ -0,0 +1,77 @@ +# [1301. Number of Paths with Max Score](https://leetcode.com/problems/number-of-paths-with-max-score) + + + +## Description + +

    You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.

    + + + +

    You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.

    + + + +

    Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.

    + + + +

    In case there is no path, return [0, 0].

    + + + +

     

    + +

    Example 1:

    + +
    Input: board = ["E23","2X2","12S"]
    +
    +Output: [7,1]
    +
    +

    Example 2:

    + +
    Input: board = ["E12","1X1","21S"]
    +
    +Output: [4,2]
    +
    +

    Example 3:

    + +
    Input: board = ["E11","XXX","11S"]
    +
    +Output: [0,0]
    +
    +
    + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= board.length == board[i].length <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1302.Deepest Leaves Sum/README_EN.md b/assets/1300-1399/1302.Deepest Leaves Sum/README_EN.md new file mode 100644 index 00000000..74a4e05f --- /dev/null +++ b/assets/1300-1399/1302.Deepest Leaves Sum/README_EN.md @@ -0,0 +1,54 @@ +# [1302. Deepest Leaves Sum](https://leetcode.com/problems/deepest-leaves-sum) + + + +## Description + +Given the root of a binary tree, return the sum of values of its deepest leaves. +

     

    +

    Example 1:

    + +
    +Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
    +Output: 15
    +
    + +

    Example 2:

    + +
    +Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
    +Output: 19
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 104].
    • +
    • 1 <= Node.val <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1302.Deepest Leaves Sum/images/1483_ex1.png b/assets/1300-1399/1302.Deepest Leaves Sum/images/1483_ex1.png new file mode 100644 index 00000000..a9096173 Binary files /dev/null and b/assets/1300-1399/1302.Deepest Leaves Sum/images/1483_ex1.png differ diff --git a/assets/1300-1399/1303.Find the Team Size/README_EN.md b/assets/1300-1399/1303.Find the Team Size/README_EN.md new file mode 100644 index 00000000..4925d8c0 --- /dev/null +++ b/assets/1300-1399/1303.Find the Team Size/README_EN.md @@ -0,0 +1,97 @@ +# [1303. Find the Team Size](https://leetcode.com/problems/find-the-team-size) + + + +## Description + +

    Table: Employee

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| employee_id   | int     |
    +| team_id       | int     |
    ++---------------+---------+
    +employee_id is the primary key for this table.
    +Each row of this table contains the ID of each employee and their respective team.
    +
    + +

    Write an SQL query to find the team size of each of the employees.

    + +

    Return result table in any order.

    + +

    The query result format is in the following example:

    + +
    +Employee Table:
    ++-------------+------------+
    +| employee_id | team_id    |
    ++-------------+------------+
    +|     1       |     8      |
    +|     2       |     8      |
    +|     3       |     8      |
    +|     4       |     7      |
    +|     5       |     9      |
    +|     6       |     9      |
    ++-------------+------------+
    +Result table:
    ++-------------+------------+
    +| employee_id | team_size  |
    ++-------------+------------+
    +|     1       |     3      |
    +|     2       |     3      |
    +|     3       |     3      |
    +|     4       |     1      |
    +|     5       |     2      |
    +|     6       |     2      |
    ++-------------+------------+
    +Employees with Id 1,2,3 are part of a team with team_id = 8.
    +Employees with Id 4 is part of a team with team_id = 7.
    +Employees with Id 5,6 are part of a team with team_id = 9.
    +
    +
    + +## Solutions + + + +### **SQL** + +Solution 1: + +```sql +# Write your MySQL query statement below +SELECT + e.employee_id, t.team_size +FROM + Employee e +LEFT JOIN + (SELECT + team_id, count(1) as team_size + FROM + Employee + GROUP BY + team_id + ) t +ON + e.team_id = t.team_id; +``` + +Solution 2: + +```sql +# Write your MySQL query statement below +SELECT + e1.employee_id, count(*) as team_size +FROM + Employee e1 +LEFT JOIN + Employee e2 +ON + e1.team_id = e2.team_id +GROUP BY + e1.employee_id; +``` + + diff --git a/assets/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md b/assets/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md new file mode 100644 index 00000000..400cde7b --- /dev/null +++ b/assets/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md @@ -0,0 +1,62 @@ +# [1304. Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero) + + + +## Description + +

    Given an integer n, return any array containing n unique integers such that they add up to 0.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5
    +Output: [-7,-1,1,3,4]
    +Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
    +
    + +

    Example 2:

    + +
    +Input: n = 3
    +Output: [-1,0,1]
    +
    + +

    Example 3:

    + +
    +Input: n = 1
    +Output: [0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md b/assets/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md new file mode 100644 index 00000000..e481bf89 --- /dev/null +++ b/assets/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md @@ -0,0 +1,78 @@ +# [1305. All Elements in Two Binary Search Trees](https://leetcode.com/problems/all-elements-in-two-binary-search-trees) + + + +## Description + +

    Given two binary search trees root1 and root2.

    + +

    Return a list containing all the integers from both trees sorted in ascending order.

    + +

     

    +

    Example 1:

    + +
    +Input: root1 = [2,1,4], root2 = [1,0,3]
    +Output: [0,1,1,2,3,4]
    +
    + +

    Example 2:

    + +
    +Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
    +Output: [-10,0,0,1,2,5,7,10]
    +
    + +

    Example 3:

    + +
    +Input: root1 = [], root2 = [5,1,7,0,2]
    +Output: [0,1,2,5,7]
    +
    + +

    Example 4:

    + +
    +Input: root1 = [0,-10,10], root2 = []
    +Output: [-10,0,10]
    +
    + +

    Example 5:

    + +
    +Input: root1 = [1,null,8], root2 = [8,1]
    +Output: [1,1,8,8]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • Each tree has at most 5000 nodes.
    • +
    • Each node's value is between [-10^5, 10^5].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1305.All Elements in Two Binary Search Trees/images/q2-e1.png b/assets/1300-1399/1305.All Elements in Two Binary Search Trees/images/q2-e1.png new file mode 100644 index 00000000..8a17ec1d Binary files /dev/null and b/assets/1300-1399/1305.All Elements in Two Binary Search Trees/images/q2-e1.png differ diff --git a/assets/1300-1399/1305.All Elements in Two Binary Search Trees/images/q2-e5-.png b/assets/1300-1399/1305.All Elements in Two Binary Search Trees/images/q2-e5-.png new file mode 100644 index 00000000..89c6c0d6 Binary files /dev/null and b/assets/1300-1399/1305.All Elements in Two Binary Search Trees/images/q2-e5-.png differ diff --git a/assets/1300-1399/1306.Jump Game III/README_EN.md b/assets/1300-1399/1306.Jump Game III/README_EN.md new file mode 100644 index 00000000..e328b33c --- /dev/null +++ b/assets/1300-1399/1306.Jump Game III/README_EN.md @@ -0,0 +1,73 @@ +# [1306. Jump Game III](https://leetcode.com/problems/jump-game-iii) + + + +## Description + +

    Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.

    + +

    Notice that you can not jump outside of the array at any time.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [4,2,3,0,3,1,2], start = 5
    +Output: true
    +Explanation: 
    +All possible ways to reach at index 3 with value 0 are: 
    +index 5 -> index 4 -> index 1 -> index 3 
    +index 5 -> index 6 -> index 4 -> index 1 -> index 3 
    +
    + +

    Example 2:

    + +
    +Input: arr = [4,2,3,0,3,1,2], start = 0
    +Output: true 
    +Explanation: 
    +One possible way to reach at index 3 with value 0 is: 
    +index 0 -> index 4 -> index 1 -> index 3
    +
    + +

    Example 3:

    + +
    +Input: arr = [3,0,2,1,2], start = 2
    +Output: false
    +Explanation: There is no way to reach at index 1 with value 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 5 * 104
    • +
    • 0 <= arr[i] < arr.length
    • +
    • 0 <= start < arr.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md b/assets/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md new file mode 100644 index 00000000..5cd912c3 --- /dev/null +++ b/assets/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md @@ -0,0 +1,84 @@ +# [1307. Verbal Arithmetic Puzzle](https://leetcode.com/problems/verbal-arithmetic-puzzle) + + + +## Description + +

    Given an equation, represented by words on left side and the result on right side.

    + +

    You need to check if the equation is solvable under the following rules:

    + +
      +
    • Each character is decoded as one digit (0 - 9).
    • +
    • Every pair of different characters they must map to different digits.
    • +
    • Each words[i] and result are decoded as one number without leading zeros.
    • +
    • Sum of numbers on left side (words) will equal to the number on right side (result). 
    • +
    + +

    Return True if the equation is solvable otherwise return False.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["SEND","MORE"], result = "MONEY"
    +Output: true
    +Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
    +Such that: "SEND" + "MORE" = "MONEY" ,  9567 + 1085 = 10652
    + +

    Example 2:

    + +
    +Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
    +Output: true
    +Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
    +Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" ,  650 + 68782 + 68782 = 138214
    + +

    Example 3:

    + +
    +Input: words = ["THIS","IS","TOO"], result = "FUNNY"
    +Output: true
    +
    + +

    Example 4:

    + +
    +Input: words = ["LEET","CODE"], result = "POINT"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= words.length <= 5
    • +
    • 1 <= words[i].length, result.length <= 7
    • +
    • words[i], result contain only uppercase English letters.
    • +
    • The number of different characters used in the expression is at most 10.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1308.Running Total for Different Genders/README_EN.md b/assets/1300-1399/1308.Running Total for Different Genders/README_EN.md new file mode 100644 index 00000000..d8b19ccf --- /dev/null +++ b/assets/1300-1399/1308.Running Total for Different Genders/README_EN.md @@ -0,0 +1,85 @@ +# [1308. Running Total for Different Genders](https://leetcode.com/problems/running-total-for-different-genders) + + + +## Description + +

    Table: Scores

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| player_name   | varchar |
    +| gender        | varchar |
    +| day           | date    |
    +| score_points  | int     |
    ++---------------+---------+
    +(gender, day) is the primary key for this table.
    +A competition is held between females team and males team.
    +Each row of this table indicates that a player_name and with gender has scored score_point in someday.
    +Gender is 'F' if the player is in females team and 'M' if the player is in males team.
    +
    + +

     

    + +

    Write an SQL query to find the total score for each gender at each day.

    + +

    Order the result table by gender and day

    + +

    The query result format is in the following example:

    + +
    +Scores table:
    ++-------------+--------+------------+--------------+
    +| player_name | gender | day        | score_points |
    ++-------------+--------+------------+--------------+
    +| Aron        | F      | 2020-01-01 | 17           |
    +| Alice       | F      | 2020-01-07 | 23           |
    +| Bajrang     | M      | 2020-01-07 | 7            |
    +| Khali       | M      | 2019-12-25 | 11           |
    +| Slaman      | M      | 2019-12-30 | 13           |
    +| Joe         | M      | 2019-12-31 | 3            |
    +| Jose        | M      | 2019-12-18 | 2            |
    +| Priya       | F      | 2019-12-31 | 23           |
    +| Priyanka    | F      | 2019-12-30 | 17           |
    ++-------------+--------+------------+--------------+
    +Result table:
    ++--------+------------+-------+
    +| gender | day        | total |
    ++--------+------------+-------+
    +| F      | 2019-12-30 | 17    |
    +| F      | 2019-12-31 | 40    |
    +| F      | 2020-01-01 | 57    |
    +| F      | 2020-01-07 | 80    |
    +| M      | 2019-12-18 | 2     |
    +| M      | 2019-12-25 | 13    |
    +| M      | 2019-12-30 | 26    |
    +| M      | 2019-12-31 | 29    |
    +| M      | 2020-01-07 | 36    |
    ++--------+------------+-------+
    +For females team:
    +First day is 2019-12-30, Priyanka scored 17 points and the total score for the team is 17.
    +Second day is 2019-12-31, Priya scored 23 points and the total score for the team is 40.
    +Third day is 2020-01-01, Aron scored 17 points and the total score for the team is 57.
    +Fourth day is 2020-01-07, Alice scored 23 points and the total score for the team is 80.
    +For males team:
    +First day is 2019-12-18, Jose scored 2 points and the total score for the team is 2.
    +Second day is 2019-12-25, Khali scored 11 points and the total score for the team is 13.
    +Third day is 2019-12-30, Slaman scored 13 points and the total score for the team is 26.
    +Fourth day is 2019-12-31, Joe scored 3 points and the total score for the team is 29.
    +Fifth day is 2020-01-07, Bajrang scored 7 points and the total score for the team is 36.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md b/assets/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md new file mode 100644 index 00000000..d6ca0af4 --- /dev/null +++ b/assets/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md @@ -0,0 +1,80 @@ +# [1309. Decrypt String from Alphabet to Integer Mapping](https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping) + + + +## Description + +

    Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:

    + +
      +
    • Characters ('a' to 'i') are represented by ('1' to '9') respectively.
    • +
    • Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. 
    • +
    + +

    Return the string formed after mapping.

    + +

    It's guaranteed that a unique mapping will always exist.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "10#11#12"
    +Output: "jkab"
    +Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
    +
    + +

    Example 2:

    + +
    +Input: s = "1326#"
    +Output: "acz"
    +
    + +

    Example 3:

    + +
    +Input: s = "25#"
    +Output: "y"
    +
    + +

    Example 4:

    + +
    +Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
    +Output: "abcdefghijklmnopqrstuvwxyz"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] only contains digits letters ('0'-'9') and '#' letter.
    • +
    • s will be valid string such that mapping is always possible.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1310.XOR Queries of a Subarray/README_EN.md b/assets/1300-1399/1310.XOR Queries of a Subarray/README_EN.md new file mode 100644 index 00000000..f87fb0a2 --- /dev/null +++ b/assets/1300-1399/1310.XOR Queries of a Subarray/README_EN.md @@ -0,0 +1,138 @@ +# [1310. XOR Queries of a Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray) + + + +## Description + +Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries. + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
    +
    +Output: [2,7,14,8] 
    +
    +Explanation: 
    +
    +The binary representation of the elements in the array are:
    +
    +1 = 0001 
    +
    +3 = 0011 
    +
    +4 = 0100 
    +
    +8 = 1000 
    +
    +The XOR values for queries are:
    +
    +[0,1] = 1 xor 3 = 2 
    +
    +[1,2] = 3 xor 4 = 7 
    +
    +[0,3] = 1 xor 3 xor 4 xor 8 = 14 
    +
    +[3,3] = 8
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
    +
    +Output: [8,0,4,4]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 3 * 10^4
    • +
    • 1 <= arr[i] <= 10^9
    • +
    • 1 <= queries.length <= 3 * 10^4
    • +
    • queries[i].length == 2
    • +
    • 0 <= queries[i][0] <= queries[i][1] < arr.length
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + pre_xor = [0] * (len(arr) + 1) + for i in range(1, len(arr) + 1): + pre_xor[i] = pre_xor[i - 1] ^ arr[i - 1] + return [pre_xor[l] ^ pre_xor[r + 1] for l, r in queries] +``` + +### **Java** + +```java +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + int[] preXor = new int[arr.length + 1]; + for (int i = 1; i <= arr.length; ++i) { + preXor[i] = preXor[i - 1] ^ arr[i - 1]; + } + int[] res = new int[queries.length]; + for (int i = 0; i < queries.length; ++i) { + int l = queries[i][0], r = queries[i][1]; + res[i] = preXor[l] ^ preXor[r + 1]; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @param {number[][]} queries + * @return {number[]} + */ +var xorQueries = function(arr, queries) { + let n = arr.length; + let xors = new Array(n + 1).fill(0); + for (let i = 0; i < n; i++) { + xors[i + 1] = xors[i] ^ arr[i]; + } + let res = []; + for (let query of queries) { + let [start, end] = query; + res.push(xors[start] ^ xors[end + 1]); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md b/assets/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md new file mode 100644 index 00000000..065569fd --- /dev/null +++ b/assets/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md @@ -0,0 +1,77 @@ +# [1311. Get Watched Videos by Your Friends](https://leetcode.com/problems/get-watched-videos-by-your-friends) + + + +## Description + +

    There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.

    + +

    Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. 

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
    +Output: ["B","C"] 
    +Explanation: 
    +You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
    +Person with id = 1 -> watchedVideos = ["C"] 
    +Person with id = 2 -> watchedVideos = ["B","C"] 
    +The frequencies of watchedVideos by your friends are: 
    +B -> 1 
    +C -> 2
    +
    + +

    Example 2:

    + +

    + +
    +Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
    +Output: ["D"]
    +Explanation: 
    +You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == watchedVideos.length == friends.length
    • +
    • 2 <= n <= 100
    • +
    • 1 <= watchedVideos[i].length <= 100
    • +
    • 1 <= watchedVideos[i][j].length <= 8
    • +
    • 0 <= friends[i].length < n
    • +
    • 0 <= friends[i][j] < n
    • +
    • 0 <= id < n
    • +
    • 1 <= level < n
    • +
    • if friends[i] contains j, then friends[j] contains i
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1311.Get Watched Videos by Your Friends/images/leetcode_friends_1.png b/assets/1300-1399/1311.Get Watched Videos by Your Friends/images/leetcode_friends_1.png new file mode 100644 index 00000000..c9c7c97b Binary files /dev/null and b/assets/1300-1399/1311.Get Watched Videos by Your Friends/images/leetcode_friends_1.png differ diff --git a/assets/1300-1399/1311.Get Watched Videos by Your Friends/images/leetcode_friends_2.png b/assets/1300-1399/1311.Get Watched Videos by Your Friends/images/leetcode_friends_2.png new file mode 100644 index 00000000..6d5d6cab Binary files /dev/null and b/assets/1300-1399/1311.Get Watched Videos by Your Friends/images/leetcode_friends_2.png differ diff --git a/assets/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md b/assets/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md new file mode 100644 index 00000000..0ec7e5b2 --- /dev/null +++ b/assets/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md @@ -0,0 +1,83 @@ +# [1312. Minimum Insertion Steps to Make a String Palindrome](https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome) + + + +## Description + +

    Given a string s. In one step you can insert any character at any index of the string.

    + +

    Return the minimum number of steps to make s palindrome.

    + +

    Palindrome String is one that reads the same backward as well as forward.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "zzazz"
    +Output: 0
    +Explanation: The string "zzazz" is already palindrome we don't need any insertions.
    +
    + +

    Example 2:

    + +
    +Input: s = "mbadm"
    +Output: 2
    +Explanation: String can be "mbdadbm" or "mdbabdm".
    +
    + +

    Example 3:

    + +
    +Input: s = "leetcode"
    +Output: 5
    +Explanation: Inserting 5 characters the string becomes "leetcodocteel".
    +
    + +

    Example 4:

    + +
    +Input: s = "g"
    +Output: 0
    +
    + +

    Example 5:

    + +
    +Input: s = "no"
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • All characters of s are lower case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md b/assets/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md new file mode 100644 index 00000000..383e8fe9 --- /dev/null +++ b/assets/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md @@ -0,0 +1,63 @@ +# [1313. Decompress Run-Length Encoded List](https://leetcode.com/problems/decompress-run-length-encoded-list) + + + +## Description + +

    We are given a list nums of integers representing a list compressed with run-length encoding.

    + +

    Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.

    + +

    Return the decompressed list.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4]
    +Output: [2,4,4,4]
    +Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
    +The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
    +At the end the concatenation [2] + [4,4,4] is [2,4,4,4].
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,1,2,3]
    +Output: [1,3,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 100
    • +
    • nums.length % 2 == 0
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1314.Matrix Block Sum/README_EN.md b/assets/1300-1399/1314.Matrix Block Sum/README_EN.md new file mode 100644 index 00000000..94ba72e4 --- /dev/null +++ b/assets/1300-1399/1314.Matrix Block Sum/README_EN.md @@ -0,0 +1,187 @@ +# [1314. Matrix Block Sum](https://leetcode.com/problems/matrix-block-sum) + + + +## Description + +

    Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:

    + +
      +
    • i - k <= r <= i + k,
    • +
    • j - k <= c <= j + k, and
    • +
    • (r, c) is a valid position in the matrix.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
    +Output: [[12,21,16],[27,45,33],[24,39,28]]
    +
    + +

    Example 2:

    + +
    +Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
    +Output: [[45,45,45],[45,45,45],[45,45,45]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n, k <= 100
    • +
    • 1 <= mat[i][j] <= 100
    • +
    + + +## Solutions + +Dynamic programming - 2D preSum. + + + +### **Python3** + +```python +class Solution: + def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: + m, n = len(mat), len(mat[0]) + pre = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + mat[i - 1][j - 1] + + def get(i, j): + i = max(min(m, i), 0) + j = max(min(n, j), 0) + return pre[i][j] + + ans = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + ans[i][j] = get(i + k + 1, j + k + 1) - get(i + k + 1, j - k) - get(i - k, j + k + 1) + get(i - k, j - k) + return ans +``` + +### **Java** + +```java +class Solution { + private int[][] pre; + private int m; + private int n; + public int[][] matrixBlockSum(int[][] mat, int k) { + int m = mat.length, n = mat[0].length; + int[][] pre = new int[m + 1][n + 1]; + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] + - pre[i - 1][j - 1] + mat[i - 1][j - 1]; + } + } + this.pre = pre; + this.m = m; + this.n = n; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = get(i + k + 1, j + k + 1) - get(i + k + 1, j - k) - get(i - k, j + k + 1) + get(i - k, j - k); + } + } + return ans; + } + + private int get(int i, int j) { + i = Math.max(Math.min(m, i), 0); + j = Math.max(Math.min(n, j), 0); + return pre[i][j]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> matrixBlockSum(vector>& mat, int k) { + int m = mat.size(), n = mat[0].size(); + vector> pre(m + 1, vector(n + 1)); + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] + - pre[i - 1][j - 1] + mat[i - 1][j - 1]; + } + } + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = get(i + k + 1, j + k + 1, m, n, pre) - get(i + k + 1, j - k, m, n, pre) - get(i - k, j + k + 1, m, n, pre) + get(i - k, j - k, m, n, pre); + } + } + return ans; + } + + int get(int i, int j, int m, int n, vector>& pre) { + i = max(min(m, i), 0); + j = max(min(n, j), 0); + return pre[i][j]; + } +}; +``` + +### **Go** + +```go +func matrixBlockSum(mat [][]int, k int) [][]int { + m, n := len(mat), len(mat[0]) + pre := make([][]int, m+1) + for i := 0; i < m+1; i++ { + pre[i] = make([]int, n+1) + } + for i := 1; i < m+1; i++ { + for j := 1; j < n+1; j++ { + pre[i][j] = pre[i-1][j] + pre[i][j-1] + -pre[i-1][j-1] + mat[i-1][j-1] + } + } + + get := func(i, j int) int { + i = max(min(m, i), 0) + j = max(min(n, j), 0) + return pre[i][j] + } + + ans := make([][]int, m) + for i := 0; i < m; i++ { + ans[i] = make([]int, n) + for j := 0; j < n; j++ { + ans[i][j] = get(i+k+1, j+k+1) - get(i+k+1, j-k) - get(i-k, j+k+1) + get(i-k, j-k) + } + } + return ans +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md b/assets/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md new file mode 100644 index 00000000..a457af3a --- /dev/null +++ b/assets/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md @@ -0,0 +1,70 @@ +# [1315. Sum of Nodes with Even-Valued Grandparent](https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent) + + + +## Description + +

    Given a binary tree, return the sum of values of nodes with even-valued grandparent.  (A grandparent of a node is the parent of its parent, if it exists.)

    + + + +

    If there are no nodes with an even-valued grandparent, return 0.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
    +
    +Output: 18
    +
    +Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is between 1 and 10^4.
    • +
    • The value of nodes is between 1 and 100.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/images/1473_ex1.png b/assets/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/images/1473_ex1.png new file mode 100644 index 00000000..65e10ec6 Binary files /dev/null and b/assets/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/images/1473_ex1.png differ diff --git a/assets/1300-1399/1316.Distinct Echo Substrings/README_EN.md b/assets/1300-1399/1316.Distinct Echo Substrings/README_EN.md new file mode 100644 index 00000000..710036aa --- /dev/null +++ b/assets/1300-1399/1316.Distinct Echo Substrings/README_EN.md @@ -0,0 +1,57 @@ +# [1316. Distinct Echo Substrings](https://leetcode.com/problems/distinct-echo-substrings) + + + +## Description + +

    Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).

    + +

     

    +

    Example 1:

    + +
    +Input: text = "abcabcabc"
    +Output: 3
    +Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
    +
    + +

    Example 2:

    + +
    +Input: text = "leetcodeleetcode"
    +Output: 2
    +Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 2000
    • +
    • text has only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md b/assets/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md new file mode 100644 index 00000000..03853705 --- /dev/null +++ b/assets/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md @@ -0,0 +1,132 @@ +# [1317. Convert Integer to the Sum of Two No-Zero Integers](https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers) + + + +## Description + +

    Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation.

    + + + +

    Return a list of two integers [A, B] where:

    + + + +
      +
    • A and B are No-Zero integers.
    • +
    • A + B = n
    • +
    + + + +

    It's guarateed that there is at least one valid solution. If there are many valid solutions you can return any of them.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 2
    +
    +Output: [1,1]
    +
    +Explanation: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 11
    +
    +Output: [2,9]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 10000
    +
    +Output: [1,9999]
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 69
    +
    +Output: [1,68]
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 1010
    +
    +Output: [11,999]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= n <= 10^4
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md b/assets/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md new file mode 100644 index 00000000..c3ac8434 --- /dev/null +++ b/assets/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md @@ -0,0 +1,95 @@ +# [1318. Minimum Flips to Make a OR b Equal to c](https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c) + + + +## Description + +

    Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
    + +Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: a = 2, b = 6, c = 5
    +
    +Output: 3
    +
    +Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
    + + + +

    Example 2:

    + + + +
    +
    +Input: a = 4, b = 2, c = 7
    +
    +Output: 1
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: a = 1, b = 2, c = 3
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= a <= 10^9
    • +
    • 1 <= b <= 10^9
    • +
    • 1 <= c <= 10^9
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/images/sample_3_1676.png b/assets/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/images/sample_3_1676.png new file mode 100644 index 00000000..17ff7184 Binary files /dev/null and b/assets/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/images/sample_3_1676.png differ diff --git a/assets/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md b/assets/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md new file mode 100644 index 00000000..a9804187 --- /dev/null +++ b/assets/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md @@ -0,0 +1,82 @@ +# [1319. Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected) + + + +## Description + +

    There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network.

    + +

    Given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it's not possible, return -1. 

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 4, connections = [[0,1],[0,2],[1,2]]
    +Output: 1
    +Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
    +Output: -1
    +Explanation: There are not enough cables.
    +
    + +

    Example 4:

    + +
    +Input: n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • 1 <= connections.length <= min(n*(n-1)/2, 10^5)
    • +
    • connections[i].length == 2
    • +
    • 0 <= connections[i][0], connections[i][1] < n
    • +
    • connections[i][0] != connections[i][1]
    • +
    • There are no repeated connections.
    • +
    • No two computers are connected by more than one cable.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1319.Number of Operations to Make Network Connected/images/sample_1_1677.png b/assets/1300-1399/1319.Number of Operations to Make Network Connected/images/sample_1_1677.png new file mode 100644 index 00000000..0276987a Binary files /dev/null and b/assets/1300-1399/1319.Number of Operations to Make Network Connected/images/sample_1_1677.png differ diff --git a/assets/1300-1399/1319.Number of Operations to Make Network Connected/images/sample_2_1677.png b/assets/1300-1399/1319.Number of Operations to Make Network Connected/images/sample_2_1677.png new file mode 100644 index 00000000..78543297 Binary files /dev/null and b/assets/1300-1399/1319.Number of Operations to Make Network Connected/images/sample_2_1677.png differ diff --git a/assets/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md b/assets/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md new file mode 100644 index 00000000..a2671867 --- /dev/null +++ b/assets/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md @@ -0,0 +1,144 @@ +# [1320. Minimum Distance to Type a Word Using Two Fingers](https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers) + + + +## Description + +

    + + + +

    You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).

    + + + +

    Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|

    + + + +

    Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: word = "CAKE"
    +
    +Output: 3
    +
    +Explanation: 
    +
    +Using two fingers, one optimal way to type "CAKE" is: 
    +
    +Finger 1 on letter 'C' -> cost = 0 
    +
    +Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 
    +
    +Finger 2 on letter 'K' -> cost = 0 
    +
    +Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 
    +
    +Total distance = 3
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: word = "HAPPY"
    +
    +Output: 6
    +
    +Explanation: 
    +
    +Using two fingers, one optimal way to type "HAPPY" is:
    +
    +Finger 1 on letter 'H' -> cost = 0
    +
    +Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
    +
    +Finger 2 on letter 'P' -> cost = 0
    +
    +Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
    +
    +Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
    +
    +Total distance = 6
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: word = "NEW"
    +
    +Output: 3
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: word = "YEAR"
    +
    +Output: 7
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= word.length <= 300
    • +
    • Each word[i] is an English uppercase letter.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/images/leetcode_keyboard.png b/assets/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/images/leetcode_keyboard.png new file mode 100644 index 00000000..0b0dfac1 Binary files /dev/null and b/assets/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/images/leetcode_keyboard.png differ diff --git a/assets/1300-1399/1321.Restaurant Growth/README_EN.md b/assets/1300-1399/1321.Restaurant Growth/README_EN.md new file mode 100644 index 00000000..56c7032a --- /dev/null +++ b/assets/1300-1399/1321.Restaurant Growth/README_EN.md @@ -0,0 +1,145 @@ +# [1321. Restaurant Growth](https://leetcode.com/problems/restaurant-growth) + + + +## Description + +

    Table: Customer

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| customer_id   | int     |
    +
    +| name          | varchar |
    +
    +| visited_on    | date    |
    +
    +| amount        | int     |
    +
    ++---------------+---------+
    +
    +(customer_id, visited_on) is the primary key for this table.
    +
    +This table contains data about customer transactions in a restaurant.
    +
    +visited_on is the date on which the customer with ID (customer_id) have visited the restaurant.
    +
    +amount is the total paid by a customer.
    +
    +
    + + + +

     

    + + + +

    You are the restaurant owner and you want to analyze a possible expansion (there will be at least one customer every day).

    + + + +

    Write an SQL query to compute moving average of how much customer paid in a 7 days window (current day + 6 days before) .

    + + + +

    The query result format is in the following example:

    + + + +

    Return result table ordered by visited_on.

    + + + +

    average_amount should be rounded to 2 decimal places, all dates are in the format ('YYYY-MM-DD').

    + + + +

     

    + + + +
    +
    +Customer table:
    +
    ++-------------+--------------+--------------+-------------+
    +
    +| customer_id | name         | visited_on   | amount      |
    +
    ++-------------+--------------+--------------+-------------+
    +
    +| 1           | Jhon         | 2019-01-01   | 100         |
    +
    +| 2           | Daniel       | 2019-01-02   | 110         |
    +
    +| 3           | Jade         | 2019-01-03   | 120         |
    +
    +| 4           | Khaled       | 2019-01-04   | 130         |
    +
    +| 5           | Winston      | 2019-01-05   | 110         | 
    +
    +| 6           | Elvis        | 2019-01-06   | 140         | 
    +
    +| 7           | Anna         | 2019-01-07   | 150         |
    +
    +| 8           | Maria        | 2019-01-08   | 80          |
    +
    +| 9           | Jaze         | 2019-01-09   | 110         | 
    +
    +| 1           | Jhon         | 2019-01-10   | 130         | 
    +
    +| 3           | Jade         | 2019-01-10   | 150         | 
    +
    ++-------------+--------------+--------------+-------------+
    +
    +
    +
    +Result table:
    +
    ++--------------+--------------+----------------+
    +
    +| visited_on   | amount       | average_amount |
    +
    ++--------------+--------------+----------------+
    +
    +| 2019-01-07   | 860          | 122.86         |
    +
    +| 2019-01-08   | 840          | 120            |
    +
    +| 2019-01-09   | 840          | 120            |
    +
    +| 2019-01-10   | 1000         | 142.86         |
    +
    ++--------------+--------------+----------------+
    +
    +
    +
    +1st moving average from 2019-01-01 to 2019-01-07 has an average_amount of (100 + 110 + 120 + 130 + 110 + 140 + 150)/7 = 122.86
    +
    +2nd moving average from 2019-01-02 to 2019-01-08 has an average_amount of (110 + 120 + 130 + 110 + 140 + 150 + 80)/7 = 120
    +
    +3rd moving average from 2019-01-03 to 2019-01-09 has an average_amount of (120 + 130 + 110 + 140 + 150 + 80 + 110)/7 = 120
    +
    +4th moving average from 2019-01-04 to 2019-01-10 has an average_amount of (130 + 110 + 140 + 150 + 80 + 110 + 130 + 150)/7 = 142.86
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1322.Ads Performance/README_EN.md b/assets/1300-1399/1322.Ads Performance/README_EN.md new file mode 100644 index 00000000..ccccc860 --- /dev/null +++ b/assets/1300-1399/1322.Ads Performance/README_EN.md @@ -0,0 +1,80 @@ +# [1322. Ads Performance](https://leetcode.com/problems/ads-performance) + + + +## Description + +

    Table: Ads

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ad_id         | int     |
    +| user_id       | int     |
    +| action        | enum    |
    ++---------------+---------+
    +(ad_id, user_id) is the primary key for this table.
    +Each row of this table contains the ID of an Ad, the ID of a user and the action taken by this user regarding this Ad.
    +The action column is an ENUM type of ('Clicked', 'Viewed', 'Ignored').
    +
    + +

     

    + +

    A company is running Ads and wants to calculate the performance of each Ad.

    + +

    Performance of the Ad is measured using Click-Through Rate (CTR) where:

    + +

    + +

    Write an SQL query to find the ctr of each Ad.

    + +

    Round ctr to 2 decimal points. Order the result table by ctr in descending order and by ad_id in ascending order in case of a tie.

    + +

    The query result format is in the following example:

    + +
    +Ads table:
    ++-------+---------+---------+
    +| ad_id | user_id | action  |
    ++-------+---------+---------+
    +| 1     | 1       | Clicked |
    +| 2     | 2       | Clicked |
    +| 3     | 3       | Viewed  |
    +| 5     | 5       | Ignored |
    +| 1     | 7       | Ignored |
    +| 2     | 7       | Viewed  |
    +| 3     | 5       | Clicked |
    +| 1     | 4       | Viewed  |
    +| 2     | 11      | Viewed  |
    +| 1     | 2       | Clicked |
    ++-------+---------+---------+
    +Result table:
    ++-------+-------+
    +| ad_id | ctr   |
    ++-------+-------+
    +| 1     | 66.67 |
    +| 3     | 50.00 |
    +| 2     | 33.33 |
    +| 5     | 0.00  |
    ++-------+-------+
    +for ad_id = 1, ctr = (2/(2+1)) * 100 = 66.67
    +for ad_id = 2, ctr = (1/(1+2)) * 100 = 33.33
    +for ad_id = 3, ctr = (1/(1+1)) * 100 = 50.00
    +for ad_id = 5, ctr = 0.00, Note that ad_id = 5 has no clicks or views.
    +Note that we don't care about Ignored Ads.
    +Result table is ordered by the ctr. in case of a tie we order them by ad_id
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1322.Ads Performance/images/sql1.png b/assets/1300-1399/1322.Ads Performance/images/sql1.png new file mode 100644 index 00000000..5592b01c Binary files /dev/null and b/assets/1300-1399/1322.Ads Performance/images/sql1.png differ diff --git a/assets/1300-1399/1323.Maximum 69 Number/README_EN.md b/assets/1300-1399/1323.Maximum 69 Number/README_EN.md new file mode 100644 index 00000000..53bacd01 --- /dev/null +++ b/assets/1300-1399/1323.Maximum 69 Number/README_EN.md @@ -0,0 +1,105 @@ +# [1323. Maximum 69 Number](https://leetcode.com/problems/maximum-69-number) + + + +## Description + +

    Given a positive integer num consisting only of digits 6 and 9.

    + + + +

    Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: num = 9669
    +
    +Output: 9969
    +
    +Explanation: 
    +
    +Changing the first digit results in 6669.
    +
    +Changing the second digit results in 9969.
    +
    +Changing the third digit results in 9699.
    +
    +Changing the fourth digit results in 9666. 
    +
    +The maximum number is 9969.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: num = 9996
    +
    +Output: 9999
    +
    +Explanation: Changing the last digit 6 to 9 results in the maximum number.
    + + + +

    Example 3:

    + + + +
    +
    +Input: num = 9999
    +
    +Output: 9999
    +
    +Explanation: It is better not to apply any change.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= num <= 10^4
    • +
    • num's digits are 6 or 9.
    • + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1324.Print Words Vertically/README_EN.md b/assets/1300-1399/1324.Print Words Vertically/README_EN.md new file mode 100644 index 00000000..6a4a8b9a --- /dev/null +++ b/assets/1300-1399/1324.Print Words Vertically/README_EN.md @@ -0,0 +1,109 @@ +# [1324. Print Words Vertically](https://leetcode.com/problems/print-words-vertically) + + + +## Description + +

    Given a string s. Return all the words vertically in the same order in which they appear in s.
    + +Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
    + +Each word would be put on only one column and that in one column there will be only one word.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "HOW ARE YOU"
    +
    +Output: ["HAY","ORO","WEU"]
    +
    +Explanation: Each word is printed vertically. 
    +
    + "HAY"
    +
    + "ORO"
    +
    + "WEU"
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "TO BE OR NOT TO BE"
    +
    +Output: ["TBONTB","OEROOE","   T"]
    +
    +Explanation: Trailing spaces is not allowed. 
    +
    +"TBONTB"
    +
    +"OEROOE"
    +
    +"   T"
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "CONTEST IS COMING"
    +
    +Output: ["CIC","OSO","N M","T I","E N","S G","T"]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 200
    • +
    • s contains only upper case English letters.
    • +
    • It's guaranteed that there is only one space between 2 words.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md b/assets/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md new file mode 100644 index 00000000..f9849c1d --- /dev/null +++ b/assets/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md @@ -0,0 +1,88 @@ +# [1325. Delete Leaves With a Given Value](https://leetcode.com/problems/delete-leaves-with-a-given-value) + + + +## Description + +

    Given a binary tree root and an integer target, delete all the leaf nodes with value target.

    + +

    Note that once you delete a leaf node with value targetif it's parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you can't).

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [1,2,3,2,null,2,4], target = 2
    +Output: [1,null,3,null,4]
    +Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). 
    +After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [1,3,3,3,2], target = 3
    +Output: [1,3,null,null,2]
    +
    + +

    Example 3:

    + +

    + +
    +Input: root = [1,2,null,2,null,2], target = 2
    +Output: [1]
    +Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
    +
    + +

    Example 4:

    + +
    +Input: root = [1,1,1], target = 1
    +Output: []
    +
    + +

    Example 5:

    + +
    +Input: root = [1,2,3], target = 1
    +Output: [1,2,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= target <= 1000
    • +
    • The given binary tree will have between 1 and 3000 nodes.
    • +
    • Each node's value is between [1, 1000].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_1_1684.png b/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_1_1684.png new file mode 100644 index 00000000..b92cfee9 Binary files /dev/null and b/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_1_1684.png differ diff --git a/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_2_1684.png b/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_2_1684.png new file mode 100644 index 00000000..4d65bc78 Binary files /dev/null and b/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_2_1684.png differ diff --git a/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_3_1684.png b/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_3_1684.png new file mode 100644 index 00000000..8966e880 Binary files /dev/null and b/assets/1300-1399/1325.Delete Leaves With a Given Value/images/sample_3_1684.png differ diff --git a/assets/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md b/assets/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md new file mode 100644 index 00000000..c079108b --- /dev/null +++ b/assets/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md @@ -0,0 +1,91 @@ +# [1326. Minimum Number of Taps to Open to Water a Garden](https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden) + + + +## Description + +

    There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).

    + +

    There are n + 1 taps located at points [0, 1, ..., n] in the garden.

    + +

    Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.

    + +

    Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, ranges = [3,4,1,1,0,0]
    +Output: 1
    +Explanation: The tap at point 0 can cover the interval [-3,3]
    +The tap at point 1 can cover the interval [-3,5]
    +The tap at point 2 can cover the interval [1,3]
    +The tap at point 3 can cover the interval [2,4]
    +The tap at point 4 can cover the interval [4,4]
    +The tap at point 5 can cover the interval [5,5]
    +Opening Only the second tap will water the whole garden [0,5]
    +
    + +

    Example 2:

    + +
    +Input: n = 3, ranges = [0,0,0,0]
    +Output: -1
    +Explanation: Even if you activate all the four taps you cannot water the whole garden.
    +
    + +

    Example 3:

    + +
    +Input: n = 7, ranges = [1,2,1,0,2,1,0,1]
    +Output: 3
    +
    + +

    Example 4:

    + +
    +Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4]
    +Output: 2
    +
    + +

    Example 5:

    + +
    +Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^4
    • +
    • ranges.length == n + 1
    • +
    • 0 <= ranges[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/images/1685_example_1.png b/assets/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/images/1685_example_1.png new file mode 100644 index 00000000..dc9e739f Binary files /dev/null and b/assets/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/images/1685_example_1.png differ diff --git a/assets/1300-1399/1327.List the Products Ordered in a Period/README_EN.md b/assets/1300-1399/1327.List the Products Ordered in a Period/README_EN.md new file mode 100644 index 00000000..24ef01f1 --- /dev/null +++ b/assets/1300-1399/1327.List the Products Ordered in a Period/README_EN.md @@ -0,0 +1,102 @@ +# [1327. List the Products Ordered in a Period](https://leetcode.com/problems/list-the-products-ordered-in-a-period) + + + +## Description + +

    Table: Products

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| product_id       | int     |
    +| product_name     | varchar |
    +| product_category | varchar |
    ++------------------+---------+
    +product_id is the primary key for this table.
    +This table contains data about the company's products.
    +
    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| order_date    | date    |
    +| unit          | int     |
    ++---------------+---------+
    +There is no primary key for this table. It may have duplicate rows.
    +product_id is a foreign key to Products table.
    +unit is the number of products ordered in order_date.
    +
    + +

     

    + +

    Write an SQL query to get the names of products with greater than or equal to 100 units ordered in February 2020 and their amount.

    + +

    Return result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Products table:
    ++-------------+-----------------------+------------------+
    +| product_id  | product_name          | product_category |
    ++-------------+-----------------------+------------------+
    +| 1           | Leetcode Solutions    | Book             |
    +| 2           | Jewels of Stringology | Book             |
    +| 3           | HP                    | Laptop           |
    +| 4           | Lenovo                | Laptop           |
    +| 5           | Leetcode Kit          | T-shirt          |
    ++-------------+-----------------------+------------------+
    +
    +Orders table:
    ++--------------+--------------+----------+
    +| product_id   | order_date   | unit     |
    ++--------------+--------------+----------+
    +| 1            | 2020-02-05   | 60       |
    +| 1            | 2020-02-10   | 70       |
    +| 2            | 2020-01-18   | 30       |
    +| 2            | 2020-02-11   | 80       |
    +| 3            | 2020-02-17   | 2        |
    +| 3            | 2020-02-24   | 3        |
    +| 4            | 2020-03-01   | 20       |
    +| 4            | 2020-03-04   | 30       |
    +| 4            | 2020-03-04   | 60       |
    +| 5            | 2020-02-25   | 50       |
    +| 5            | 2020-02-27   | 50       |
    +| 5            | 2020-03-01   | 50       |
    ++--------------+--------------+----------+
    +
    +Result table:
    ++--------------------+---------+
    +| product_name       | unit    |
    ++--------------------+---------+
    +| Leetcode Solutions | 130     |
    +| Leetcode Kit       | 100     |
    ++--------------------+---------+
    +
    +Products with product_id = 1 is ordered in February a total of (60 + 70) = 130.
    +Products with product_id = 2 is ordered in February a total of 80.
    +Products with product_id = 3 is ordered in February a total of (2 + 3) = 5.
    +Products with product_id = 4 was not ordered in February 2020.
    +Products with product_id = 5 is ordered in February a total of (50 + 50) = 100.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1328.Break a Palindrome/README_EN.md b/assets/1300-1399/1328.Break a Palindrome/README_EN.md new file mode 100644 index 00000000..d9de142f --- /dev/null +++ b/assets/1300-1399/1328.Break a Palindrome/README_EN.md @@ -0,0 +1,75 @@ +# [1328. Break a Palindrome](https://leetcode.com/problems/break-a-palindrome) + + + +## Description + +

    Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.

    + +

    Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.

    + +

    A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.

    + +

     

    +

    Example 1:

    + +
    +Input: palindrome = "abccba"
    +Output: "aaccba"
    +Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".
    +Of all the ways, "aaccba" is the lexicographically smallest.
    +
    + +

    Example 2:

    + +
    +Input: palindrome = "a"
    +Output: ""
    +Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.
    +
    + +

    Example 3:

    + +
    +Input: palindrome = "aa"
    +Output: "ab"
    + +

    Example 4:

    + +
    +Input: palindrome = "aba"
    +Output: "abb"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= palindrome.length <= 1000
    • +
    • palindrome consists of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md b/assets/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md new file mode 100644 index 00000000..97edf2d9 --- /dev/null +++ b/assets/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md @@ -0,0 +1,59 @@ +# [1329. Sort the Matrix Diagonally](https://leetcode.com/problems/sort-the-matrix-diagonally) + + + +## Description + +

    A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].

    + +

    Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
    +Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
    +
    + +

    Example 2:

    + +
    +Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
    +Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • 1 <= mat[i][j] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1329.Sort the Matrix Diagonally/images/1482_example_1_2.png b/assets/1300-1399/1329.Sort the Matrix Diagonally/images/1482_example_1_2.png new file mode 100644 index 00000000..3f00e8f1 Binary files /dev/null and b/assets/1300-1399/1329.Sort the Matrix Diagonally/images/1482_example_1_2.png differ diff --git a/assets/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md b/assets/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md new file mode 100644 index 00000000..25d6b7fe --- /dev/null +++ b/assets/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md @@ -0,0 +1,84 @@ +# [1330. Reverse Subarray To Maximize Array Value](https://leetcode.com/problems/reverse-subarray-to-maximize-array-value) + + + +## Description + +

    You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all 0 <= i < nums.length-1.

    + + + +

    You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.

    + + + +

    Find maximum possible value of the final array.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [2,3,1,5,4]
    +
    +Output: 10
    +
    +Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [2,4,9,24,2,1,10]
    +
    +Output: 68
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 3*10^4
    • +
    • -10^5 <= nums[i] <= 10^5
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1331.Rank Transform of an Array/README_EN.md b/assets/1300-1399/1331.Rank Transform of an Array/README_EN.md new file mode 100644 index 00000000..456f7a46 --- /dev/null +++ b/assets/1300-1399/1331.Rank Transform of an Array/README_EN.md @@ -0,0 +1,102 @@ +# [1331. Rank Transform of an Array](https://leetcode.com/problems/rank-transform-of-an-array) + + + +## Description + +

    Given an array of integers arr, replace each element with its rank.

    + + + +

    The rank represents how large the element is. The rank has the following rules:

    + + + +
      +
    • Rank is an integer starting from 1.
    • +
    • The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
    • +
    • Rank should be as small as possible.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [40,10,20,30]
    +
    +Output: [4,1,2,3]
    +
    +Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [100,100,100]
    +
    +Output: [1,1,1]
    +
    +Explanation: Same elements share the same rank.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [37,12,28,9,100,56,80,5,12]
    +
    +Output: [5,3,4,2,8,6,7,1,3]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= arr.length <= 105
    • +
    • -109 <= arr[i] <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md b/assets/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md new file mode 100644 index 00000000..1ce4e7c9 --- /dev/null +++ b/assets/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md @@ -0,0 +1,73 @@ +# [1332. Remove Palindromic Subsequences](https://leetcode.com/problems/remove-palindromic-subsequences) + + + +## Description + +

    You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.

    + +

    Return the minimum number of steps to make the given string empty.

    + +

    A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.

    + +

    A string is called palindrome if is one that reads the same backward as well as forward.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "ababa"
    +Output: 1
    +Explanation: s is already a palindrome, so its entirety can be removed in a single step.
    +
    + +

    Example 2:

    + +
    +Input: s = "abb"
    +Output: 2
    +Explanation: "abb" -> "bb" -> "". 
    +Remove palindromic subsequence "a" then "bb".
    +
    + +

    Example 3:

    + +
    +Input: s = "baabb"
    +Output: 2
    +Explanation: "baabb" -> "b" -> "". 
    +Remove palindromic subsequence "baab" then "b".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] is either 'a' or 'b'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md b/assets/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md new file mode 100644 index 00000000..24566f1e --- /dev/null +++ b/assets/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md @@ -0,0 +1,79 @@ +# [1333. Filter Restaurants by Vegan-Friendly, Price and Distance](https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance) + + + +## Description + +

    Given the array restaurants where  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.

    + +

    The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.

    + +

    Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.

    + +

     

    +

    Example 1:

    + +
    +Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
    +Output: [3,1,5] 
    +Explanation: 
    +The restaurants are:
    +Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
    +Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
    +Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
    +Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
    +Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] 
    +After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). 
    +
    + +

    Example 2:

    + +
    +Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
    +Output: [4,3,2,1,5]
    +Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.
    +
    + +

    Example 3:

    + +
    +Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
    +Output: [4,5]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= restaurants.length <= 10^4
    • +
    • restaurants[i].length == 5
    • +
    • 1 <= idi, ratingi, pricei, distancei <= 10^5
    • +
    • 1 <= maxPrice, maxDistance <= 10^5
    • +
    • veganFriendlyi and veganFriendly are 0 or 1.
    • +
    • All idi are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md b/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md new file mode 100644 index 00000000..08c0140b --- /dev/null +++ b/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md @@ -0,0 +1,78 @@ +# [1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance](https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance) + + + +## Description + +

    There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.

    + +

    Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.

    + +

    Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
    +Output: 3
    +Explanation: The figure above describes the graph. 
    +The neighboring cities at a distanceThreshold = 4 for each city are:
    +City 0 -> [City 1, City 2] 
    +City 1 -> [City 0, City 2, City 3] 
    +City 2 -> [City 0, City 1, City 3] 
    +City 3 -> [City 1, City 2] 
    +Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
    +
    + +

    Example 2:

    + +
    +Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
    +Output: 0
    +Explanation: The figure above describes the graph. 
    +The neighboring cities at a distanceThreshold = 2 for each city are:
    +City 0 -> [City 1] 
    +City 1 -> [City 0, City 4] 
    +City 2 -> [City 3, City 4] 
    +City 3 -> [City 2, City 4]
    +City 4 -> [City 1, City 2, City 3] 
    +The city 0 has 1 neighboring city at a distanceThreshold = 2.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • 1 <= edges.length <= n * (n - 1) / 2
    • +
    • edges[i].length == 3
    • +
    • 0 <= fromi < toi < n
    • +
    • 1 <= weighti, distanceThreshold <= 10^4
    • +
    • All pairs (fromi, toi) are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/images/find_the_city_01.png b/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/images/find_the_city_01.png new file mode 100644 index 00000000..1cfeea32 Binary files /dev/null and b/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/images/find_the_city_01.png differ diff --git a/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/images/find_the_city_02.png b/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/images/find_the_city_02.png new file mode 100644 index 00000000..5cc0c623 Binary files /dev/null and b/assets/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/images/find_the_city_02.png differ diff --git a/assets/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md b/assets/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md new file mode 100644 index 00000000..74b011c4 --- /dev/null +++ b/assets/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md @@ -0,0 +1,139 @@ +# [1335. Minimum Difficulty of a Job Schedule](https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule) + + + +## Description + +

    You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 <= j < i).

    + + + +

    You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done in that day.

    + + + +

    Given an array of integers jobDifficulty and an integer d. The difficulty of the i-th job is jobDifficulty[i].

    + + + +

    Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: jobDifficulty = [6,5,4,3,2,1], d = 2
    +
    +Output: 7
    +
    +Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
    +
    +Second day you can finish the last job, total difficulty = 1.
    +
    +The difficulty of the schedule = 6 + 1 = 7 
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: jobDifficulty = [9,9,9], d = 4
    +
    +Output: -1
    +
    +Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: jobDifficulty = [1,1,1], d = 3
    +
    +Output: 3
    +
    +Explanation: The schedule is one job per day. total difficulty will be 3.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: jobDifficulty = [7,1,7,1,7,1], d = 3
    +
    +Output: 15
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: jobDifficulty = [11,111,22,222,33,333,44,444], d = 6
    +
    +Output: 843
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= jobDifficulty.length <= 300
    • +
    • 0 <= jobDifficulty[i] <= 1000
    • +
    • 1 <= d <= 10
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1335.Minimum Difficulty of a Job Schedule/images/untitled.png b/assets/1300-1399/1335.Minimum Difficulty of a Job Schedule/images/untitled.png new file mode 100644 index 00000000..1c0ce25e Binary files /dev/null and b/assets/1300-1399/1335.Minimum Difficulty of a Job Schedule/images/untitled.png differ diff --git a/assets/1300-1399/1336.Number of Transactions per Visit/README_EN.md b/assets/1300-1399/1336.Number of Transactions per Visit/README_EN.md new file mode 100644 index 00000000..d5ff118d --- /dev/null +++ b/assets/1300-1399/1336.Number of Transactions per Visit/README_EN.md @@ -0,0 +1,115 @@ +# [1336. Number of Transactions per Visit](https://leetcode.com/problems/number-of-transactions-per-visit) + + + +## Description + +

    Table: Visits

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| visit_date    | date    |
    ++---------------+---------+
    +(user_id, visit_date) is the primary key for this table.
    +Each row of this table indicates that user_id has visited the bank in visit_date.
    +
    + +

     

    + +

    Table: Transactions

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| user_id          | int     |
    +| transaction_date | date    |
    +| amount           | int     |
    ++------------------+---------+
    +There is no primary key for this table, it may contain duplicates.
    +Each row of this table indicates that user_id has done a transaction of amount in transaction_date.
    +It is guaranteed that the user has visited the bank in the transaction_date.(i.e The Visits table contains (user_id, transaction_date) in one row)
    +
    + +

     

    + +

    A bank wants to draw a chart of the number of transactions bank visitors did in one visit to the bank and the corresponding number of visitors who have done this number of transaction in one visit.

    + +

    Write an SQL query to find how many users visited the bank and didn't do any transactions, how many visited the bank and did one transaction and so on.

    + +

    The result table will contain two columns:

    + +
      +
    • transactions_count which is the number of transactions done in one visit.
    • +
    • visits_count which is the corresponding number of users who did transactions_count in one visit to the bank.
    • +
    + +

    transactions_count should take all values from 0 to max(transactions_count) done by one or more users.

    + +

    Order the result table by transactions_count.

    + +

    The query result format is in the following example:

    + +
    +Visits table:
    ++---------+------------+
    +| user_id | visit_date |
    ++---------+------------+
    +| 1       | 2020-01-01 |
    +| 2       | 2020-01-02 |
    +| 12      | 2020-01-01 |
    +| 19      | 2020-01-03 |
    +| 1       | 2020-01-02 |
    +| 2       | 2020-01-03 |
    +| 1       | 2020-01-04 |
    +| 7       | 2020-01-11 |
    +| 9       | 2020-01-25 |
    +| 8       | 2020-01-28 |
    ++---------+------------+
    +Transactions table:
    ++---------+------------------+--------+
    +| user_id | transaction_date | amount |
    ++---------+------------------+--------+
    +| 1       | 2020-01-02       | 120    |
    +| 2       | 2020-01-03       | 22     |
    +| 7       | 2020-01-11       | 232    |
    +| 1       | 2020-01-04       | 7      |
    +| 9       | 2020-01-25       | 33     |
    +| 9       | 2020-01-25       | 66     |
    +| 8       | 2020-01-28       | 1      |
    +| 9       | 2020-01-25       | 99     |
    ++---------+------------------+--------+
    +Result table:
    ++--------------------+--------------+
    +| transactions_count | visits_count |
    ++--------------------+--------------+
    +| 0                  | 4            |
    +| 1                  | 5            |
    +| 2                  | 0            |
    +| 3                  | 1            |
    ++--------------------+--------------+
    +* For transactions_count = 0, The visits (1, "2020-01-01"), (2, "2020-01-02"), (12, "2020-01-01") and (19, "2020-01-03") did no transactions so visits_count = 4.
    +* For transactions_count = 1, The visits (2, "2020-01-03"), (7, "2020-01-11"), (8, "2020-01-28"), (1, "2020-01-02") and (1, "2020-01-04") did one transaction so visits_count = 5.
    +* For transactions_count = 2, No customers visited the bank and did two transactions so visits_count = 0.
    +* For transactions_count = 3, The visit (9, "2020-01-25") did three transactions so visits_count = 1.
    +* For transactions_count >= 4, No customers visited the bank and did more than three transactions so we will stop at transactions_count = 3
    +
    +The chart drawn for this example is as follows:
    +
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1336.Number of Transactions per Visit/images/chart.png b/assets/1300-1399/1336.Number of Transactions per Visit/images/chart.png new file mode 100644 index 00000000..fd39291c Binary files /dev/null and b/assets/1300-1399/1336.Number of Transactions per Visit/images/chart.png differ diff --git a/assets/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md b/assets/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md new file mode 100644 index 00000000..d169fbc9 --- /dev/null +++ b/assets/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md @@ -0,0 +1,136 @@ +# [1337. The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix) + + + +## Description + +

    You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.

    + +

    A row i is weaker than a row j if one of the following is true:

    + +
      +
    • The number of soldiers in row i is less than the number of soldiers in row j.
    • +
    • Both rows have the same number of soldiers and i < j.
    • +
    + +

    Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = 
    +[[1,1,0,0,0],
    + [1,1,1,1,0],
    + [1,0,0,0,0],
    + [1,1,0,0,0],
    + [1,1,1,1,1]], 
    +k = 3
    +Output: [2,0,3]
    +Explanation: 
    +The number of soldiers in each row is: 
    +- Row 0: 2 
    +- Row 1: 4 
    +- Row 2: 1 
    +- Row 3: 2 
    +- Row 4: 5 
    +The rows ordered from weakest to strongest are [2,0,3,1,4].
    +
    + +

    Example 2:

    + +
    +Input: mat = 
    +[[1,0,0,0],
    + [1,1,1,1],
    + [1,0,0,0],
    + [1,0,0,0]], 
    +k = 2
    +Output: [0,2]
    +Explanation: 
    +The number of soldiers in each row is: 
    +- Row 0: 1 
    +- Row 1: 4 
    +- Row 2: 1 
    +- Row 3: 1 
    +The rows ordered from weakest to strongest are [0,2,3,1].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 2 <= n, m <= 100
    • +
    • 1 <= k <= m
    • +
    • matrix[i][j] is either 0 or 1.
    • +
    + + +## Solutions + +Binary search & sort. + + + +### **Python3** + +```python +class Solution: + def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: + m, n = len(mat), len(mat[0]) + res = [] + for row in mat: + left, right = 0, n + while left < right: + mid = (left + right) >> 1 + if row[mid] == 0: + right = mid + else: + left = mid + 1 + res.append(left) + idx = list(range(m)) + idx.sort(key=lambda x: res[x]) + return idx[:k] +``` + +### **Java** + +```java +class Solution { + public int[] kWeakestRows(int[][] mat, int k) { + int m = mat.length, n = mat[0].length; + int[] res = new int[m]; + List idx = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + idx.add(i); + int[] row = mat[i]; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (row[mid] == 0) { + right = mid; + } else { + left = mid + 1; + } + } + res[i] = left; + } + idx.sort(Comparator.comparingInt(a -> res[a])); + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = idx.get(i); + } + return ans; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1338.Reduce Array Size to The Half/README_EN.md b/assets/1300-1399/1338.Reduce Array Size to The Half/README_EN.md new file mode 100644 index 00000000..5024fc66 --- /dev/null +++ b/assets/1300-1399/1338.Reduce Array Size to The Half/README_EN.md @@ -0,0 +1,129 @@ +# [1338. Reduce Array Size to The Half](https://leetcode.com/problems/reduce-array-size-to-the-half) + + + +## Description + +

    Given an array arr.  You can choose a set of integers and remove all the occurrences of these integers in the array.

    + + + +

    Return the minimum size of the set so that at least half of the integers of the array are removed.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [3,3,3,3,5,5,5,2,2,7]
    +
    +Output: 2
    +
    +Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
    +
    +Possible sets of size 2 are {3,5},{3,2},{5,2}.
    +
    +Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [7,7,7,7,7,7]
    +
    +Output: 1
    +
    +Explanation: The only possible set you can choose is {7}. This will make the new array empty.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [1,9]
    +
    +Output: 1
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [1000,1000,3,7]
    +
    +Output: 1
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: arr = [1,2,3,4,5,6,7,8,9,10]
    +
    +Output: 5
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • arr.length is even.
    • +
    • 1 <= arr[i] <= 10^5
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md b/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md new file mode 100644 index 00000000..9ff4771b --- /dev/null +++ b/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md @@ -0,0 +1,118 @@ +# [1339. Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree) + + + +## Description + +

    Given a binary tree root. Split the binary tree into two subtrees by removing 1 edge such that the product of the sums of the subtrees are maximized.

    + + + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: root = [1,2,3,4,5,6]
    +
    +Output: 110
    +
    +Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: root = [1,null,2,3,4,null,null,5,6]
    +
    +Output: 90
    +
    +Explanation:  Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: root = [2,3,9,10,7,8,6,5,4,11,1]
    +
    +Output: 1025
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: root = [1,1]
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • Each tree has at most 50000 nodes and at least 2 nodes.
    • +
    • Each node's value is between [1, 10000].
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/images/sample_1_1699.png b/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/images/sample_1_1699.png new file mode 100644 index 00000000..ebe99e87 Binary files /dev/null and b/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/images/sample_1_1699.png differ diff --git a/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/images/sample_2_1699.png b/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/images/sample_2_1699.png new file mode 100644 index 00000000..1d330f61 Binary files /dev/null and b/assets/1300-1399/1339.Maximum Product of Splitted Binary Tree/images/sample_2_1699.png differ diff --git a/assets/1300-1399/1340.Jump Game V/README_EN.md b/assets/1300-1399/1340.Jump Game V/README_EN.md new file mode 100644 index 00000000..9409867d --- /dev/null +++ b/assets/1300-1399/1340.Jump Game V/README_EN.md @@ -0,0 +1,146 @@ +# [1340. Jump Game V](https://leetcode.com/problems/jump-game-v) + + + +## Description + +

    Given an array of integers arr and an integer d. In one step you can jump from index i to index:

    + + + +
      +
    • i + x where: i + x < arr.length and 0 < x <= d.
    • +
    • i - x where: i - x >= 0 and 0 < x <= d.
    • +
    + + + +

    In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).

    + + + +

    You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.

    + + + +

    Notice that you can not jump outside of the array at any time.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
    +
    +Output: 4
    +
    +Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
    +
    +Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
    +
    +Similarly You cannot jump from index 3 to index 2 or index 1.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [3,3,3,3,3], d = 3
    +
    +Output: 1
    +
    +Explanation: You can start at any index. You always cannot jump to any index.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [7,6,5,4,3,2,1], d = 1
    +
    +Output: 7
    +
    +Explanation: Start at index 0. You can visit all the indicies. 
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [7,1,7,1,7,1], d = 2
    +
    +Output: 2
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: arr = [66], d = 1
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 10^5
    • +
    • 1 <= d <= arr.length
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1340.Jump Game V/images/meta-chart.jpeg b/assets/1300-1399/1340.Jump Game V/images/meta-chart.jpeg new file mode 100644 index 00000000..176f9f16 Binary files /dev/null and b/assets/1300-1399/1340.Jump Game V/images/meta-chart.jpeg differ diff --git a/assets/1300-1399/1341.Movie Rating/README_EN.md b/assets/1300-1399/1341.Movie Rating/README_EN.md new file mode 100644 index 00000000..37de09fb --- /dev/null +++ b/assets/1300-1399/1341.Movie Rating/README_EN.md @@ -0,0 +1,121 @@ +# [1341. Movie Rating](https://leetcode.com/problems/movie-rating) + + + +## Description + +

    Table: Movies

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| movie_id      | int     |
    +| title         | varchar |
    ++---------------+---------+
    +movie_id is the primary key for this table.
    +title is the name of the movie.
    +
    + +

    Table: Users

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| name          | varchar |
    ++---------------+---------+
    +user_id is the primary key for this table.
    +
    + +

    Table: Movie_Rating

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| movie_id      | int     |
    +| user_id       | int     |
    +| rating        | int     |
    +| created_at    | date    |
    ++---------------+---------+
    +(movie_id, user_id) is the primary key for this table.
    +This table contains the rating of a movie by a user in their review.
    +created_at is the user's review date. 
    +
    + +

     

    + +

    Write the following SQL query:

    + +
      +
    • Find the name of the user who has rated the greatest number of movies. +

      In case of a tie, return lexicographically smaller user name.

      +
    • +
    • Find the movie name with the highest average rating in February 2020. +

      In case of a tie, return lexicographically smaller movie name.

      +
    • +
    + +

    The query is returned in 2 rows, the query result format is in the following example:

    + +
    +Movies table:
    ++-------------+--------------+
    +| movie_id    |  title       |
    ++-------------+--------------+
    +| 1           | Avengers     |
    +| 2           | Frozen 2     |
    +| 3           | Joker        |
    ++-------------+--------------+
    +
    +Users table:
    ++-------------+--------------+
    +| user_id     |  name        |
    ++-------------+--------------+
    +| 1           | Daniel       |
    +| 2           | Monica       |
    +| 3           | Maria        |
    +| 4           | James        |
    ++-------------+--------------+
    +
    +Movie_Rating table:
    ++-------------+--------------+--------------+-------------+
    +| movie_id    | user_id      | rating       | created_at  |
    ++-------------+--------------+--------------+-------------+
    +| 1           | 1            | 3            | 2020-01-12  |
    +| 1           | 2            | 4            | 2020-02-11  |
    +| 1           | 3            | 2            | 2020-02-12  |
    +| 1           | 4            | 1            | 2020-01-01  |
    +| 2           | 1            | 5            | 2020-02-17  | 
    +| 2           | 2            | 2            | 2020-02-01  | 
    +| 2           | 3            | 2            | 2020-03-01  |
    +| 3           | 1            | 3            | 2020-02-22  | 
    +| 3           | 2            | 4            | 2020-02-25  | 
    ++-------------+--------------+--------------+-------------+
    +
    +Result table:
    ++--------------+
    +| results      |
    ++--------------+
    +| Daniel       |
    +| Frozen 2     |
    ++--------------+
    +
    +Daniel and Monica have rated 3 movies ("Avengers", "Frozen 2" and "Joker") but Daniel is smaller lexicographically.
    +Frozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is smaller lexicographically.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md b/assets/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md new file mode 100644 index 00000000..ca765819 --- /dev/null +++ b/assets/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md @@ -0,0 +1,73 @@ +# [1342. Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero) + + + +## Description + +

    Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

    + +

     

    +

    Example 1:

    + +
    +Input: num = 14
    +Output: 6
    +Explanation: 
    +Step 1) 14 is even; divide by 2 and obtain 7. 
    +Step 2) 7 is odd; subtract 1 and obtain 6.
    +Step 3) 6 is even; divide by 2 and obtain 3. 
    +Step 4) 3 is odd; subtract 1 and obtain 2. 
    +Step 5) 2 is even; divide by 2 and obtain 1. 
    +Step 6) 1 is odd; subtract 1 and obtain 0.
    +
    + +

    Example 2:

    + +
    +Input: num = 8
    +Output: 4
    +Explanation: 
    +Step 1) 8 is even; divide by 2 and obtain 4. 
    +Step 2) 4 is even; divide by 2 and obtain 2. 
    +Step 3) 2 is even; divide by 2 and obtain 1. 
    +Step 4) 1 is odd; subtract 1 and obtain 0.
    +
    + +

    Example 3:

    + +
    +Input: num = 123
    +Output: 12
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= num <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md b/assets/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md new file mode 100644 index 00000000..d7733c46 --- /dev/null +++ b/assets/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md @@ -0,0 +1,82 @@ +# [1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold](https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold) + + + +## Description + +

    Given an array of integers arr and two integers k and threshold.

    + +

    Return the number of sub-arrays of size k and average greater than or equal to threshold.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
    +Output: 3
    +Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,1,1,1,1], k = 1, threshold = 0
    +Output: 5
    +
    + +

    Example 3:

    + +
    +Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
    +Output: 6
    +Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
    +
    + +

    Example 4:

    + +
    +Input: arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
    +Output: 1
    +
    + +

    Example 5:

    + +
    +Input: arr = [4,4,4,4], k = 4, threshold = 1
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^4
    • +
    • 1 <= k <= arr.length
    • +
    • 0 <= threshold <= 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md b/assets/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md new file mode 100644 index 00000000..fd0b3dd4 --- /dev/null +++ b/assets/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md @@ -0,0 +1,83 @@ +# [1344. Angle Between Hands of a Clock](https://leetcode.com/problems/angle-between-hands-of-a-clock) + + + +## Description + +

    Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: hour = 12, minutes = 30
    +Output: 165
    +
    + +

    Example 2:

    + +

    + +
    +Input: hour = 3, minutes = 30
    +Output: 75
    +
    + +

    Example 3:

    + +

    + +
    +Input: hour = 3, minutes = 15
    +Output: 7.5
    +
    + +

    Example 4:

    + +
    +Input: hour = 4, minutes = 50
    +Output: 155
    +
    + +

    Example 5:

    + +
    +Input: hour = 12, minutes = 0
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= hour <= 12
    • +
    • 0 <= minutes <= 59
    • +
    • Answers within 10^-5 of the actual value will be accepted as correct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_1_1673.png b/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_1_1673.png new file mode 100644 index 00000000..b871df59 Binary files /dev/null and b/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_1_1673.png differ diff --git a/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_2_1673.png b/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_2_1673.png new file mode 100644 index 00000000..4655f088 Binary files /dev/null and b/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_2_1673.png differ diff --git a/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_3_1673.png b/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_3_1673.png new file mode 100644 index 00000000..21eab596 Binary files /dev/null and b/assets/1300-1399/1344.Angle Between Hands of a Clock/images/sample_3_1673.png differ diff --git a/assets/1300-1399/1345.Jump Game IV/README_EN.md b/assets/1300-1399/1345.Jump Game IV/README_EN.md new file mode 100644 index 00000000..443276c1 --- /dev/null +++ b/assets/1300-1399/1345.Jump Game IV/README_EN.md @@ -0,0 +1,91 @@ +# [1345. Jump Game IV](https://leetcode.com/problems/jump-game-iv) + + + +## Description + +

    Given an array of integers arr, you are initially positioned at the first index of the array.

    + +

    In one step you can jump from index i to index:

    + +
      +
    • i + 1 where: i + 1 < arr.length.
    • +
    • i - 1 where: i - 1 >= 0.
    • +
    • j where: arr[i] == arr[j] and i != j.
    • +
    + +

    Return the minimum number of steps to reach the last index of the array.

    + +

    Notice that you can not jump outside of the array at any time.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
    +Output: 3
    +Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
    +
    + +

    Example 2:

    + +
    +Input: arr = [7]
    +Output: 0
    +Explanation: Start index is the last index. You don't need to jump.
    +
    + +

    Example 3:

    + +
    +Input: arr = [7,6,9,6,9,6,9,7]
    +Output: 1
    +Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
    +
    + +

    Example 4:

    + +
    +Input: arr = [6,1,9]
    +Output: 2
    +
    + +

    Example 5:

    + +
    +Input: arr = [11,22,7,7,7,7,7,7,7,22,13]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 5 * 104
    • +
    • -108 <= arr[i] <= 108
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1346.Check If N and Its Double Exist/README_EN.md b/assets/1300-1399/1346.Check If N and Its Double Exist/README_EN.md new file mode 100644 index 00000000..b0e0e5fc --- /dev/null +++ b/assets/1300-1399/1346.Check If N and Its Double Exist/README_EN.md @@ -0,0 +1,73 @@ +# [1346. Check If N and Its Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist) + + + +## Description + +

    Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).

    + +

    More formally check if there exists two indices i and j such that :

    + +
      +
    • i != j
    • +
    • 0 <= i, j < arr.length
    • +
    • arr[i] == 2 * arr[j]
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: arr = [10,2,5,3]
    +Output: true
    +Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.
    +
    + +

    Example 2:

    + +
    +Input: arr = [7,1,14,11]
    +Output: true
    +Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.
    +
    + +

    Example 3:

    + +
    +Input: arr = [3,1,7,11]
    +Output: false
    +Explanation: In this case does not exist N and M, such that N = 2 * M.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr.length <= 500
    • +
    • -10^3 <= arr[i] <= 10^3
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md b/assets/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md new file mode 100644 index 00000000..323e9598 --- /dev/null +++ b/assets/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md @@ -0,0 +1,84 @@ +# [1347. Minimum Number of Steps to Make Two Strings Anagram](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram) + + + +## Description + +

    Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.

    + +

    Return the minimum number of steps to make t an anagram of s.

    + +

    An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "bab", t = "aba"
    +Output: 1
    +Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
    +
    + +

    Example 2:

    + +
    +Input: s = "leetcode", t = "practice"
    +Output: 5
    +Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
    +
    + +

    Example 3:

    + +
    +Input: s = "anagram", t = "mangaar"
    +Output: 0
    +Explanation: "anagram" and "mangaar" are anagrams. 
    +
    + +

    Example 4:

    + +
    +Input: s = "xxyyzz", t = "xxyyzz"
    +Output: 0
    +
    + +

    Example 5:

    + +
    +Input: s = "friend", t = "family"
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 50000
    • +
    • s.length == t.length
    • +
    • s and t contain lower-case English letters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md b/assets/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md new file mode 100644 index 00000000..d618546c --- /dev/null +++ b/assets/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md @@ -0,0 +1,87 @@ +# [1348. Tweet Counts Per Frequency](https://leetcode.com/problems/tweet-counts-per-frequency) + + + +## Description + +

    A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).

    + +

    For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:

    + +
      +
    • Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]
    • +
    • Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]
    • +
    • Every day (86400-second chunks): [10,10000]
    • +
    + +

    Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).

    + +

    Design and implement an API to help the company with their analysis.

    + +

    Implement the TweetCounts class:

    + +
      +
    • TweetCounts() Initializes the TweetCounts object.
    • +
    • void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).
    • +
    • List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq. +
        +
      • freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively.
      • +
      +
    • +
    + +

     

    +

    Example:

    + +
    +Input
    +["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
    +[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
    +
    +Output
    +[null,null,null,null,[2],[2,1],null,[4]]
    +
    +Explanation
    +TweetCounts tweetCounts = new TweetCounts();
    +tweetCounts.recordTweet("tweet3", 0);                              // New tweet "tweet3" at time 0
    +tweetCounts.recordTweet("tweet3", 60);                             // New tweet "tweet3" at time 60
    +tweetCounts.recordTweet("tweet3", 10);                             // New tweet "tweet3" at time 10
    +tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets
    +tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet
    +tweetCounts.recordTweet("tweet3", 120);                            // New tweet "tweet3" at time 120
    +tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210);  // return [4]; chunk [0,210] had 4 tweets
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= time, startTime, endTime <= 109
    • +
    • 0 <= endTime - startTime <= 104
    • +
    • There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1349.Maximum Students Taking Exam/README_EN.md b/assets/1300-1399/1349.Maximum Students Taking Exam/README_EN.md new file mode 100644 index 00000000..9d55ad3b --- /dev/null +++ b/assets/1300-1399/1349.Maximum Students Taking Exam/README_EN.md @@ -0,0 +1,83 @@ +# [1349. Maximum Students Taking Exam](https://leetcode.com/problems/maximum-students-taking-exam) + + + +## Description + +

    Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.

    + +

    Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..

    + +

    Students must be placed in seats in good condition.

    + +

     

    +

    Example 1:

    + +
    +Input: seats = [["#",".","#","#",".","#"],
    +                [".","#","#","#","#","."],
    +                ["#",".","#","#",".","#"]]
    +Output: 4
    +Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. 
    +
    + +

    Example 2:

    + +
    +Input: seats = [[".","#"],
    +                ["#","#"],
    +                ["#","."],
    +                ["#","#"],
    +                [".","#"]]
    +Output: 3
    +Explanation: Place all students in available seats. 
    +
    +
    + +

    Example 3:

    + +
    +Input: seats = [["#",".",".",".","#"],
    +                [".","#",".","#","."],
    +                [".",".","#",".","."],
    +                [".","#",".","#","."],
    +                ["#",".",".",".","#"]]
    +Output: 10
    +Explanation: Place students in available seats in column 1, 3 and 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • seats contains only characters '.' and'#'.
    • +
    • m == seats.length
    • +
    • n == seats[i].length
    • +
    • 1 <= m <= 8
    • +
    • 1 <= n <= 8
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1349.Maximum Students Taking Exam/images/image.png b/assets/1300-1399/1349.Maximum Students Taking Exam/images/image.png new file mode 100644 index 00000000..546e9622 Binary files /dev/null and b/assets/1300-1399/1349.Maximum Students Taking Exam/images/image.png differ diff --git a/assets/1300-1399/1350.Students With Invalid Departments/README_EN.md b/assets/1300-1399/1350.Students With Invalid Departments/README_EN.md new file mode 100644 index 00000000..28f9b7d3 --- /dev/null +++ b/assets/1300-1399/1350.Students With Invalid Departments/README_EN.md @@ -0,0 +1,104 @@ +# [1350. Students With Invalid Departments](https://leetcode.com/problems/students-with-invalid-departments) + + + +## Description + +

    Table: Departments

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id is the primary key of this table.
    +The table has information about the id of each department of a university.
    +
    + +

     

    + +

    Table: Students

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    +| department_id | int     |
    ++---------------+---------+
    +id is the primary key of this table.
    +The table has information about the id of each student at a university and the id of the department he/she studies at.
    +
    + +

     

    + +

    Write an SQL query to find the id and the name of all students who are enrolled in departments that no longer exists.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +
    +Departments table:
    ++------+--------------------------+
    +| id   | name                     |
    ++------+--------------------------+
    +| 1    | Electrical Engineering   |
    +| 7    | Computer Engineering     |
    +| 13   | Bussiness Administration |
    ++------+--------------------------+
    +
    +Students table:
    ++------+----------+---------------+
    +| id   | name     | department_id |
    ++------+----------+---------------+
    +| 23   | Alice    | 1             |
    +| 1    | Bob      | 7             |
    +| 5    | Jennifer | 13            |
    +| 2    | John     | 14            |
    +| 4    | Jasmine  | 77            |
    +| 3    | Steve    | 74            |
    +| 6    | Luis     | 1             |
    +| 8    | Jonathan | 7             |
    +| 7    | Daiana   | 33            |
    +| 11   | Madelynn | 1             |
    ++------+----------+---------------+
    +
    +Result table:
    ++------+----------+
    +| id   | name     |
    ++------+----------+
    +| 2    | John     |
    +| 7    | Daiana   |
    +| 4    | Jasmine  |
    +| 3    | Steve    |
    ++------+----------+
    +
    +John, Daiana, Steve and Jasmine are enrolled in departments 14, 33, 74 and 77 respectively. department 14, 33, 74 and 77 doesn't exist in the Departments table.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + s.id, s.name +FROM + Students s +LEFT JOIN + Departments d +ON + s.department_id = d.id +WHERE + d.id IS NULL; +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md b/assets/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md new file mode 100644 index 00000000..e2f842ab --- /dev/null +++ b/assets/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md @@ -0,0 +1,157 @@ +# [1351. Count Negative Numbers in a Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix) + + + +## Description + +

    Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
    +Output: 8
    +Explanation: There are 8 negatives number in the matrix.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[3,2],[1,0]]
    +Output: 0
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,-1],[-1,-1]]
    +Output: 3
    +
    + +

    Example 4:

    + +
    +Input: grid = [[-1]]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • -100 <= grid[i][j] <= 100
    • +
    + +

     

    +Follow up: Could you find an O(n + m) solution? + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + m, n, cnt = len(grid), len(grid[0]), 0 + i, j = 0, n - 1 + while i < m and j >= 0: + if grid[i][j] < 0: + cnt += (m - i) + j -= 1 + else: + i += 1 + return cnt +``` + +### **Java** + +```java +class Solution { + public int countNegatives(int[][] grid) { + int m = grid.length, n = grid[0].length; + int cnt = 0; + for (int i = 0, j = n - 1; j >= 0 && i < m;) { + if (grid[i][j] < 0) { + cnt += (m - i); + --j; + } else { + ++i; + } + } + return cnt; + } +} +``` + +### **TypeScript** + +```ts +function countNegatives(grid: number[][]): number { + let m = grid.length, n = grid[0].length; + let i = 0, j = n - 1; + let ans = 0; + while (i < m && j > -1) { + let cur = grid[i][j]; + if (cur < 0) { + j--; + ans += (m - i); + } else { + i++; + } + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int countNegatives(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int i = 0, j = n - 1, cnt = 0; + while (i < m && j >= 0) { + if (grid[i][j] < 0) { + cnt += (m - i); + --j; + } else { + ++i; + } + } + return cnt; + } +}; +``` + +### **Go** + +```go +func countNegatives(grid [][]int) int { + m, n := len(grid), len(grid[0]) + i, j, cnt := 0, n-1, 0 + for i < m && j >= 0 { + if grid[i][j] < 0 { + cnt += (m - i) + j-- + } else { + i++ + } + } + return cnt +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1352.Product of the Last K Numbers/README_EN.md b/assets/1300-1399/1352.Product of the Last K Numbers/README_EN.md new file mode 100644 index 00000000..91bc5a11 --- /dev/null +++ b/assets/1300-1399/1352.Product of the Last K Numbers/README_EN.md @@ -0,0 +1,129 @@ +# [1352. Product of the Last K Numbers](https://leetcode.com/problems/product-of-the-last-k-numbers) + + + +## Description + +

    Implement the class ProductOfNumbers that supports two methods:

    + +

    1. add(int num)

    + +
      +
    • Adds the number num to the back of the current list of numbers.
    • +
    + +

    2. getProduct(int k)

    + +
      +
    • Returns the product of the last k numbers in the current list.
    • +
    • You can assume that always the current list has at least k numbers.
    • +
    + +

    At any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.

    + +

     

    +

    Example:

    + +
    +Input
    +["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
    +[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
    +
    +Output
    +[null,null,null,null,null,null,20,40,0,null,32]
    +
    +Explanation
    +ProductOfNumbers productOfNumbers = new ProductOfNumbers();
    +productOfNumbers.add(3);        // [3]
    +productOfNumbers.add(0);        // [3,0]
    +productOfNumbers.add(2);        // [3,0,2]
    +productOfNumbers.add(5);        // [3,0,2,5]
    +productOfNumbers.add(4);        // [3,0,2,5,4]
    +productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
    +productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
    +productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
    +productOfNumbers.add(8);        // [3,0,2,5,4,8]
    +productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 
    +
    + +

     

    +

    Constraints:

    + +
      +
    • There will be at most 40000 operations considering both add and getProduct.
    • +
    • 0 <= num <= 100
    • +
    • 1 <= k <= 40000
    • +
    + +## Solutions + + + +### **Python3** + +```python +class ProductOfNumbers: + + def __init__(self): + self.pre_product = [] + + def add(self, num: int) -> None: + if num == 0: + self.pre_product = [] + return + if not self.pre_product: + self.pre_product.append(1) + self.pre_product.append(num * self.pre_product[-1]) + + def getProduct(self, k: int) -> int: + n = len(self.pre_product) + return 0 if n <= k else self.pre_product[n - 1] // self.pre_product[n - k - 1] + + +# Your ProductOfNumbers object will be instantiated and called as such: +# obj = ProductOfNumbers() +# obj.add(num) +# param_2 = obj.getProduct(k) +``` + +### **Java** + +```java +class ProductOfNumbers { + private List preProduct; + + public ProductOfNumbers() { + preProduct = new ArrayList<>(); + } + + public void add(int num) { + if (num == 0) { + preProduct.clear(); + return; + } + if (preProduct.isEmpty()) { + preProduct.add(1); + } + preProduct.add(num * preProduct.get(preProduct.size() - 1)); + } + + public int getProduct(int k) { + return preProduct.size() <= k ? 0 : preProduct.get(preProduct.size() - 1) / preProduct.get(preProduct.size() - 1 - k); + } +} + +/** + * Your ProductOfNumbers object will be instantiated and called as such: + * ProductOfNumbers obj = new ProductOfNumbers(); + * obj.add(num); + * int param_2 = obj.getProduct(k); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md b/assets/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md new file mode 100644 index 00000000..a1763cc6 --- /dev/null +++ b/assets/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md @@ -0,0 +1,86 @@ +# [1353. Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended) + + + +## Description + +

    Given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

    + +

    You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only attend one event at any time d.

    + +

    Return the maximum number of events you can attend.

    + +

     

    +

    Example 1:

    + +
    +Input: events = [[1,2],[2,3],[3,4]]
    +Output: 3
    +Explanation: You can attend all the three events.
    +One way to attend them all is as shown.
    +Attend the first event on day 1.
    +Attend the second event on day 2.
    +Attend the third event on day 3.
    +
    + +

    Example 2:

    + +
    +Input: events= [[1,2],[2,3],[3,4],[1,2]]
    +Output: 4
    +
    + +

    Example 3:

    + +
    +Input: events = [[1,4],[4,4],[2,2],[3,4],[1,1]]
    +Output: 4
    +
    + +

    Example 4:

    + +
    +Input: events = [[1,100000]]
    +Output: 1
    +
    + +

    Example 5:

    + +
    +Input: events = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7]]
    +Output: 7
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= events.length <= 105
    • +
    • events[i].length == 2
    • +
    • 1 <= startDayi <= endDayi <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1353.Maximum Number of Events That Can Be Attended/images/e1.png b/assets/1300-1399/1353.Maximum Number of Events That Can Be Attended/images/e1.png new file mode 100644 index 00000000..bfe20fe9 Binary files /dev/null and b/assets/1300-1399/1353.Maximum Number of Events That Can Be Attended/images/e1.png differ diff --git a/assets/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md b/assets/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md new file mode 100644 index 00000000..8cdb2bff --- /dev/null +++ b/assets/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md @@ -0,0 +1,77 @@ +# [1354. Construct Target Array With Multiple Sums](https://leetcode.com/problems/construct-target-array-with-multiple-sums) + + + +## Description + +

    Given an array of integers target. From a starting array, A consisting of all 1's, you may perform the following procedure :

    + +
      +
    • let x be the sum of all elements currently in your array.
    • +
    • choose index i, such that 0 <= i < target.size and set the value of A at index i to x.
    • +
    • You may repeat this procedure as many times as needed.
    • +
    + +

    Return True if it is possible to construct the target array from A otherwise return False.

    + +

     

    +

    Example 1:

    + +
    +Input: target = [9,3,5]
    +Output: true
    +Explanation: Start with [1, 1, 1] 
    +[1, 1, 1], sum = 3 choose index 1
    +[1, 3, 1], sum = 5 choose index 2
    +[1, 3, 5], sum = 9 choose index 0
    +[9, 3, 5] Done
    +
    + +

    Example 2:

    + +
    +Input: target = [1,1,1,2]
    +Output: false
    +Explanation: Impossible to create target array from [1,1,1,1].
    +
    + +

    Example 3:

    + +
    +Input: target = [8,5]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • N == target.length
    • +
    • 1 <= target.length <= 5 * 10^4
    • +
    • 1 <= target[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1355.Activity Participants/README_EN.md b/assets/1300-1399/1355.Activity Participants/README_EN.md new file mode 100644 index 00000000..9fafbfbe --- /dev/null +++ b/assets/1300-1399/1355.Activity Participants/README_EN.md @@ -0,0 +1,88 @@ +# [1355. Activity Participants](https://leetcode.com/problems/activity-participants) + + + +## Description + +

    Table: Friends

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    +| activity      | varchar |
    ++---------------+---------+
    +id is the id of the friend and primary key for this table.
    +name is the name of the friend.
    +activity is the name of the activity which the friend takes part in.
    +
    + +

    Table: Activities

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id is the primary key for this table.
    +name is the name of the activity.
    +
    + +

     

    + +

    Write an SQL query to find the names of all the activities with neither maximum, nor minimum number of participants.

    + +

    Return the result table in any order. Each activity in table Activities is performed by any person in the table Friends.

    + +

    The query result format is in the following example:

    + +
    +Friends table:
    ++------+--------------+---------------+
    +| id   | name         | activity      |
    ++------+--------------+---------------+
    +| 1    | Jonathan D.  | Eating        |
    +| 2    | Jade W.      | Singing       |
    +| 3    | Victor J.    | Singing       |
    +| 4    | Elvis Q.     | Eating        |
    +| 5    | Daniel A.    | Eating        |
    +| 6    | Bob B.       | Horse Riding  |
    ++------+--------------+---------------+
    +
    +Activities table:
    ++------+--------------+
    +| id   | name         |
    ++------+--------------+
    +| 1    | Eating       |
    +| 2    | Singing      |
    +| 3    | Horse Riding |
    ++------+--------------+
    +
    +Result table:
    ++--------------+
    +| activity     |
    ++--------------+
    +| Singing      |
    ++--------------+
    +
    +Eating activity is performed by 3 friends, maximum number of participants, (Jonathan D. , Elvis Q. and Daniel A.)
    +Horse Riding activity is performed by 1 friend, minimum number of participants, (Bob B.)
    +Singing is performed by 2 friends (Victor J. and Jade W.)
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md b/assets/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md new file mode 100644 index 00000000..369420a6 --- /dev/null +++ b/assets/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md @@ -0,0 +1,84 @@ +# [1356. Sort Integers by The Number of 1 Bits](https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits) + + + +## Description + +

    Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.

    + +

    Return the sorted array.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [0,1,2,3,4,5,6,7,8]
    +Output: [0,1,2,4,8,3,5,6,7]
    +Explantion: [0] is the only integer with 0 bits.
    +[1,2,4,8] all have 1 bit.
    +[3,5,6] have 2 bits.
    +[7] has 3 bits.
    +The sorted array by bits is [0,1,2,4,8,3,5,6,7]
    +
    + +

    Example 2:

    + +
    +Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
    +Output: [1,2,4,8,16,32,64,128,256,512,1024]
    +Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
    +
    + +

    Example 3:

    + +
    +Input: arr = [10000,10000]
    +Output: [10000,10000]
    +
    + +

    Example 4:

    + +
    +Input: arr = [2,3,5,7,11,13,17,19]
    +Output: [2,3,5,17,7,11,13,19]
    +
    + +

    Example 5:

    + +
    +Input: arr = [10,100,1000,10000]
    +Output: [10,100,10000,1000]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 500
    • +
    • 0 <= arr[i] <= 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1357.Apply Discount Every n Orders/README_EN.md b/assets/1300-1399/1357.Apply Discount Every n Orders/README_EN.md new file mode 100644 index 00000000..60d11cab --- /dev/null +++ b/assets/1300-1399/1357.Apply Discount Every n Orders/README_EN.md @@ -0,0 +1,112 @@ +# [1357. Apply Discount Every n Orders](https://leetcode.com/problems/apply-discount-every-n-orders) + + + +## Description + +

    There is a sale in a supermarket, there will be a discount every n customer.
    + +There are some products in the supermarket where the id of the i-th product is products[i] and the price per unit of this product is prices[i].
    + +The system will count the number of customers and when the n-th customer arrive he/she will have a discount on the bill. (i.e if the cost is x the new cost is x - (discount * x) / 100). Then the system will start counting customers again.
    + +The customer orders a certain amount of each product where product[i] is the id of the i-th product the customer ordered and amount[i] is the number of units the customer ordered of that product.

    + + + +

    Implement the Cashier class:

    + + + +
      +
    • Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, the products and their prices.
    • +
    • double getBill(int[] product, int[] amount) returns the value of the bill and apply the discount if needed. Answers within 10^-5 of the actual value will be accepted as correct.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input
    +
    +["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
    +
    +[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
    +
    +Output
    +
    +[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
    +
    +Explanation
    +
    +Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);
    +
    +cashier.getBill([1,2],[1,2]);                        // return 500.0, bill = 1 * 100 + 2 * 200 = 500.
    +
    +cashier.getBill([3,7],[10,10]);                      // return 4000.0
    +
    +cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]);    // return 800.0, The bill was 1600.0 but as this is the third customer, he has a discount of 50% which means his bill is only 1600 - 1600 * (50 / 100) = 800.
    +
    +cashier.getBill([4],[10]);                           // return 4000.0
    +
    +cashier.getBill([7,3],[10,10]);                      // return 4000.0
    +
    +cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0, Bill was 14700.0 but as the system counted three more customers, he will have a 50% discount and the bill becomes 7350.0
    +
    +cashier.getBill([2,3,5],[5,3,2]);                    // return 2500.0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^4
    • +
    • 0 <= discount <= 100
    • +
    • 1 <= products.length <= 200
    • +
    • 1 <= products[i] <= 200
    • +
    • There are not repeated elements in the array products.
    • +
    • prices.length == products.length
    • +
    • 1 <= prices[i] <= 1000
    • +
    • 1 <= product.length <= products.length
    • +
    • product[i] exists in products.
    • +
    • amount.length == product.length
    • +
    • 1 <= amount[i] <= 1000
    • +
    • At most 1000 calls will be made to getBill.
    • +
    • Answers within 10^-5 of the actual value will be accepted as correct.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md b/assets/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md new file mode 100644 index 00000000..bbe4667f --- /dev/null +++ b/assets/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md @@ -0,0 +1,66 @@ +# [1358. Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters) + + + +## Description + +

    Given a string s consisting only of characters a, b and c.

    + +

    Return the number of substrings containing at least one occurrence of all these characters a, b and c.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcabc"
    +Output: 10
    +Explanation: The substrings containing at least one occurrence of the characters ab and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). 
    +
    + +

    Example 2:

    + +
    +Input: s = "aaacb"
    +Output: 3
    +Explanation: The substrings containing at least one occurrence of the characters ab and c are "aaacb", "aacb" and "acb". 
    +
    + +

    Example 3:

    + +
    +Input: s = "abc"
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= s.length <= 5 x 10^4
    • +
    • s only consists of a, b or characters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md b/assets/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md new file mode 100644 index 00000000..534eca62 --- /dev/null +++ b/assets/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md @@ -0,0 +1,69 @@ +# [1359. Count All Valid Pickup and Delivery Options](https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options) + + + +## Description + +

    Given n orders, each order consist in pickup and delivery services. 

    + +

    Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). 

    + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 1
    +Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 6
    +Explanation: All possible orders: 
    +(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
    +This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
    +
    + +

    Example 3:

    + +
    +Input: n = 3
    +Output: 90
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 500
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1360.Number of Days Between Two Dates/README_EN.md b/assets/1300-1399/1360.Number of Days Between Two Dates/README_EN.md new file mode 100644 index 00000000..892f9c14 --- /dev/null +++ b/assets/1300-1399/1360.Number of Days Between Two Dates/README_EN.md @@ -0,0 +1,49 @@ +# [1360. Number of Days Between Two Dates](https://leetcode.com/problems/number-of-days-between-two-dates) + + + +## Description + +

    Write a program to count the number of days between two dates.

    + +

    The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

    + +

     

    +

    Example 1:

    +
    Input: date1 = "2019-06-29", date2 = "2019-06-30"
    +Output: 1
    +

    Example 2:

    +
    Input: date1 = "2020-01-15", date2 = "2019-12-31"
    +Output: 15
    +
    +

     

    +

    Constraints:

    + +
      +
    • The given dates are valid dates between the years 1971 and 2100.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md b/assets/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md new file mode 100644 index 00000000..98b92a04 --- /dev/null +++ b/assets/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md @@ -0,0 +1,74 @@ +# [1361. Validate Binary Tree Nodes](https://leetcode.com/problems/validate-binary-tree-nodes) + + + +## Description + +

    You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.

    + +

    If node i has no left child then leftChild[i] will equal -1, similarly for the right child.

    + +

    Note that the nodes have no values and that we only use the node numbers in this problem.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
    +Output: true
    +
    + +

    Example 2:

    + +
    +Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 104
    • +
    • leftChild.length == rightChild.length == n
    • +
    • -1 <= leftChild[i], rightChild[i] <= n - 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex1.png b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex1.png new file mode 100644 index 00000000..e68b5ba4 Binary files /dev/null and b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex1.png differ diff --git a/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex2.png b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex2.png new file mode 100644 index 00000000..34a1c5ed Binary files /dev/null and b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex2.png differ diff --git a/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex3.png b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex3.png new file mode 100644 index 00000000..347ce155 Binary files /dev/null and b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex3.png differ diff --git a/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex4.png b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex4.png new file mode 100644 index 00000000..c8fee1dd Binary files /dev/null and b/assets/1300-1399/1361.Validate Binary Tree Nodes/images/1503_ex4.png differ diff --git a/assets/1300-1399/1362.Closest Divisors/README_EN.md b/assets/1300-1399/1362.Closest Divisors/README_EN.md new file mode 100644 index 00000000..aa6d0d5b --- /dev/null +++ b/assets/1300-1399/1362.Closest Divisors/README_EN.md @@ -0,0 +1,64 @@ +# [1362. Closest Divisors](https://leetcode.com/problems/closest-divisors) + + + +## Description + +

    Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.

    + +

    Return the two integers in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: num = 8
    +Output: [3,3]
    +Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
    +
    + +

    Example 2:

    + +
    +Input: num = 123
    +Output: [5,25]
    +
    + +

    Example 3:

    + +
    +Input: num = 999
    +Output: [40,25]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= num <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1363.Largest Multiple of Three/README_EN.md b/assets/1300-1399/1363.Largest Multiple of Three/README_EN.md new file mode 100644 index 00000000..b71f09a3 --- /dev/null +++ b/assets/1300-1399/1363.Largest Multiple of Three/README_EN.md @@ -0,0 +1,74 @@ +# [1363. Largest Multiple of Three](https://leetcode.com/problems/largest-multiple-of-three) + + + +## Description + +

    Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.

    + +

    Since the answer may not fit in an integer data type, return the answer as a string.

    + +

    If there is no answer return an empty string.

    + +

     

    +

    Example 1:

    + +
    +Input: digits = [8,1,9]
    +Output: "981"
    +
    + +

    Example 2:

    + +
    +Input: digits = [8,6,7,1,0]
    +Output: "8760"
    +
    + +

    Example 3:

    + +
    +Input: digits = [1]
    +Output: ""
    +
    + +

    Example 4:

    + +
    +Input: digits = [0,0,0,0,0,0]
    +Output: "0"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= digits.length <= 10^4
    • +
    • 0 <= digits[i] <= 9
    • +
    • The returning answer must not contain unnecessary leading zeros.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md b/assets/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md new file mode 100644 index 00000000..ab1f9994 --- /dev/null +++ b/assets/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md @@ -0,0 +1,130 @@ +# [1364. Number of Trusted Contacts of a Customer](https://leetcode.com/problems/number-of-trusted-contacts-of-a-customer) + + + +## Description + +

    Table: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| customer_name | varchar |
    +| email         | varchar |
    ++---------------+---------+
    +customer_id is the primary key for this table.
    +Each row of this table contains the name and the email of a customer of an online shop.
    +
    + +

     

    + +

    Table: Contacts

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | id      |
    +| contact_name  | varchar |
    +| contact_email | varchar |
    ++---------------+---------+
    +(user_id, contact_email) is the primary key for this table.
    +Each row of this table contains the name and email of one contact of customer with user_id.
    +This table contains information about people each customer trust. The contact may or may not exist in the Customers table.
    +
    +
    + +

     

    + +

    Table: Invoices

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| invoice_id   | int     |
    +| price        | int     |
    +| user_id      | int     |
    ++--------------+---------+
    +invoice_id is the primary key for this table.
    +Each row of this table indicates that user_id has an invoice with invoice_id and a price.
    +
    + +

     

    + +

    Write an SQL query to find the following for each invoice_id:

    + +
      +
    • customer_name: The name of the customer the invoice is related to.
    • +
    • price: The price of the invoice.
    • +
    • contacts_cnt: The number of contacts related to the customer.
    • +
    • trusted_contacts_cnt: The number of contacts related to the customer and at the same time they are customers to the shop. (i.e His/Her email exists in the Customers table.)
    • +
    + +

    Order the result table by invoice_id.

    + +

    The query result format is in the following example:

    + +
    +Customers table:
    ++-------------+---------------+--------------------+
    +| customer_id | customer_name | email              |
    ++-------------+---------------+--------------------+
    +| 1           | Alice         | alice@leetcode.com |
    +| 2           | Bob           | bob@leetcode.com   |
    +| 13          | John          | john@leetcode.com  |
    +| 6           | Alex          | alex@leetcode.com  |
    ++-------------+---------------+--------------------+
    +Contacts table:
    ++-------------+--------------+--------------------+
    +| user_id     | contact_name | contact_email      |
    ++-------------+--------------+--------------------+
    +| 1           | Bob          | bob@leetcode.com   |
    +| 1           | John         | john@leetcode.com  |
    +| 1           | Jal          | jal@leetcode.com   |
    +| 2           | Omar         | omar@leetcode.com  |
    +| 2           | Meir         | meir@leetcode.com  |
    +| 6           | Alice        | alice@leetcode.com |
    ++-------------+--------------+--------------------+
    +Invoices table:
    ++------------+-------+---------+
    +| invoice_id | price | user_id |
    ++------------+-------+---------+
    +| 77         | 100   | 1       |
    +| 88         | 200   | 1       |
    +| 99         | 300   | 2       |
    +| 66         | 400   | 2       |
    +| 55         | 500   | 13      |
    +| 44         | 60    | 6       |
    ++------------+-------+---------+
    +Result table:
    ++------------+---------------+-------+--------------+----------------------+
    +| invoice_id | customer_name | price | contacts_cnt | trusted_contacts_cnt |
    ++------------+---------------+-------+--------------+----------------------+
    +| 44         | Alex          | 60    | 1            | 1                    |
    +| 55         | John          | 500   | 0            | 0                    |
    +| 66         | Bob           | 400   | 2            | 0                    |
    +| 77         | Alice         | 100   | 3            | 2                    |
    +| 88         | Alice         | 200   | 3            | 2                    |
    +| 99         | Bob           | 300   | 2            | 0                    |
    ++------------+---------------+-------+--------------+----------------------+
    +Alice has three contacts, two of them are trusted contacts (Bob and John).
    +Bob has two contacts, none of them is a trusted contact.
    +Alex has one contact and it is a trusted contact (Alice).
    +John doesn't have any contacts.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md b/assets/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md new file mode 100644 index 00000000..93b2a641 --- /dev/null +++ b/assets/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md @@ -0,0 +1,95 @@ +# [1365. How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number) + + + +## Description + +

    Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

    + +

    Return the answer in an array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [8,1,2,2,3]
    +Output: [4,0,1,1,3]
    +Explanation: 
    +For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
    +For nums[1]=1 does not exist any smaller number than it.
    +For nums[2]=2 there exist one smaller number than it (1). 
    +For nums[3]=2 there exist one smaller number than it (1). 
    +For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
    +
    + +

    Example 2:

    + +
    +Input: nums = [6,5,4,8]
    +Output: [2,1,0,3]
    +
    + +

    Example 3:

    + +
    +Input: nums = [7,7,7,7]
    +Output: [0,0,0,0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 500
    • +
    • 0 <= nums[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + cnt = [0] * 101 + for num in nums: + cnt[num] += 1 + for i in range(1, 101): + cnt[i] += cnt[i - 1] + res = [] + for num in nums: + res.append(0 if num == 0 else cnt[num - 1]) + return res +``` + +### **Java** + +```java +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] cnt = new int[101]; + for (int e : nums) { + ++cnt[e]; + } + for (int i = 1; i < 101; ++i) { + cnt[i] += cnt[i - 1]; + } + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) { + res[i] = nums[i] == 0 ? 0 : cnt[nums[i] - 1]; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1366.Rank Teams by Votes/README_EN.md b/assets/1300-1399/1366.Rank Teams by Votes/README_EN.md new file mode 100644 index 00000000..352351d9 --- /dev/null +++ b/assets/1300-1399/1366.Rank Teams by Votes/README_EN.md @@ -0,0 +1,98 @@ +# [1366. Rank Teams by Votes](https://leetcode.com/problems/rank-teams-by-votes) + + + +## Description + +

    In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.

    + +

    The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.

    + +

    Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.

    + +

    Return a string of all teams sorted by the ranking system.

    + +

     

    +

    Example 1:

    + +
    +Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
    +Output: "ACB"
    +Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
    +Team B was ranked second by 2 voters and was ranked third by 3 voters.
    +Team C was ranked second by 3 voters and was ranked third by 2 voters.
    +As most of the voters ranked C second, team C is the second team and team B is the third.
    +
    + +

    Example 2:

    + +
    +Input: votes = ["WXYZ","XYZW"]
    +Output: "XWYZ"
    +Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. 
    +
    + +

    Example 3:

    + +
    +Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
    +Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
    +Explanation: Only one voter so his votes are used for the ranking.
    +
    + +

    Example 4:

    + +
    +Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
    +Output: "ABC"
    +Explanation: 
    +Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters.
    +Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters.
    +Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters.
    +There is a tie and we rank teams ascending by their IDs.
    +
    + +

    Example 5:

    + +
    +Input: votes = ["M","M","M","M"]
    +Output: "M"
    +Explanation: Only team M in the competition so it has the first rank.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= votes.length <= 1000
    • +
    • 1 <= votes[i].length <= 26
    • +
    • votes[i].length == votes[j].length for 0 <= i, j < votes.length.
    • +
    • votes[i][j] is an English upper-case letter.
    • +
    • All characters of votes[i] are unique.
    • +
    • All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1367.Linked List in Binary Tree/README_EN.md b/assets/1300-1399/1367.Linked List in Binary Tree/README_EN.md new file mode 100644 index 00000000..23364251 --- /dev/null +++ b/assets/1300-1399/1367.Linked List in Binary Tree/README_EN.md @@ -0,0 +1,141 @@ +# [1367. Linked List in Binary Tree](https://leetcode.com/problems/linked-list-in-binary-tree) + + + +## Description + +

    Given a binary tree root and a linked list with head as the first node. 

    + +

    Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.

    + +

    In this context downward path means a path that starts at some node and goes downwards.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
    +Output: true
    +Explanation: Nodes in blue form a subpath in the binary Tree.  
    +
    + +

    Example 2:

    + +

    + +
    +Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
    +Output: false
    +Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree will be in the range [1, 2500].
    • +
    • The number of nodes in the list will be in the range [1, 100].
    • +
    • 1 <= Node.val <= 100 for each node in the linked list and binary tree.
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSubPath(self, head: ListNode, root: TreeNode) -> bool: + def dfs(head, root): + if head is None: + return True + if root is None: + return False + if root.val != head.val: + return False + return dfs(head.next, root.left) or dfs(head.next, root.right) + + if root is None: + return False + return dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSubPath(ListNode head, TreeNode root) { + if (root == null) { + return false; + } + return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right); + } + + private boolean dfs(ListNode head, TreeNode root) { + if (head == null) { + return true; + } + if (root == null) { + return false; + } + if (root.val != head.val) { + return false; + } + return dfs(head.next, root.left) || dfs(head.next, root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1367.Linked List in Binary Tree/images/sample_1_1720.png b/assets/1300-1399/1367.Linked List in Binary Tree/images/sample_1_1720.png new file mode 100644 index 00000000..c0bcb064 Binary files /dev/null and b/assets/1300-1399/1367.Linked List in Binary Tree/images/sample_1_1720.png differ diff --git a/assets/1300-1399/1367.Linked List in Binary Tree/images/sample_2_1720.png b/assets/1300-1399/1367.Linked List in Binary Tree/images/sample_2_1720.png new file mode 100644 index 00000000..a8478abb Binary files /dev/null and b/assets/1300-1399/1367.Linked List in Binary Tree/images/sample_2_1720.png differ diff --git a/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md new file mode 100644 index 00000000..3e8eae92 --- /dev/null +++ b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md @@ -0,0 +1,95 @@ +# [1368. Minimum Cost to Make at Least One Valid Path in a Grid](https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid) + + + +## Description + +Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: +
      +
    • 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
    • +
    • 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
    • +
    • 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
    • +
    • 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])
    • +
    + +

    Notice that there could be some invalid signs on the cells of the grid which points outside the grid.

    + +

    You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest.

    + +

    You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.

    + +

    Return the minimum cost to make the grid have at least one valid path.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
    +Output: 3
    +Explanation: You will start at point (0, 0).
    +The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
    +The total cost = 3.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
    +Output: 0
    +Explanation: You can follow the path from (0, 0) to (2, 2).
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,2],[4,3]]
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: grid = [[2,2,2],[2,2,2]]
    +Output: 3
    +
    + +

    Example 5:

    + +
    +Input: grid = [[4]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid1.png b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid1.png new file mode 100644 index 00000000..9225b4f9 Binary files /dev/null and b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid1.png differ diff --git a/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid2.png b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid2.png new file mode 100644 index 00000000..9c6a731c Binary files /dev/null and b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid2.png differ diff --git a/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid3.png b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid3.png new file mode 100644 index 00000000..5547d35b Binary files /dev/null and b/assets/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/images/grid3.png differ diff --git a/assets/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md b/assets/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md new file mode 100644 index 00000000..4b13fdd9 --- /dev/null +++ b/assets/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md @@ -0,0 +1,111 @@ +# [1369. Get the Second Most Recent Activity](https://leetcode.com/problems/get-the-second-most-recent-activity) + + + +## Description + +

    Table: UserActivity

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| username      | varchar |
    +
    +| activity      | varchar |
    +
    +| startDate     | Date    |
    +
    +| endDate       | Date    |
    +
    ++---------------+---------+
    +
    +This table does not contain primary key.
    +
    +This table contain information about the activity performed of each user in a period of time.
    +
    +A person with username performed a activity from startDate to endDate.
    +
    +
    +
    +
    + + + +

    Write an SQL query to show the second most recent activity of each user.

    + + + +

    If the user only has one activity, return that one. 

    + + + +

    A user can't perform more than one activity at the same time. Return the result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +UserActivity table:
    +
    ++------------+--------------+-------------+-------------+
    +
    +| username   | activity     | startDate   | endDate     |
    +
    ++------------+--------------+-------------+-------------+
    +
    +| Alice      | Travel       | 2020-02-12  | 2020-02-20  |
    +
    +| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
    +
    +| Alice      | Travel       | 2020-02-24  | 2020-02-28  |
    +
    +| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
    +
    ++------------+--------------+-------------+-------------+
    +
    +
    +
    +Result table:
    +
    ++------------+--------------+-------------+-------------+
    +
    +| username   | activity     | startDate   | endDate     |
    +
    ++------------+--------------+-------------+-------------+
    +
    +| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
    +
    +| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
    +
    ++------------+--------------+-------------+-------------+
    +
    +
    +
    +The most recent activity of Alice is Travel from 2020-02-24 to 2020-02-28, before that she was dancing from 2020-02-21 to 2020-02-23.
    +
    +Bob only has one record, we just take that one.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1370.Increasing Decreasing String/README_EN.md b/assets/1300-1399/1370.Increasing Decreasing String/README_EN.md new file mode 100644 index 00000000..ba5a2c05 --- /dev/null +++ b/assets/1300-1399/1370.Increasing Decreasing String/README_EN.md @@ -0,0 +1,96 @@ +# [1370. Increasing Decreasing String](https://leetcode.com/problems/increasing-decreasing-string) + + + +## Description + +

    Given a string s. You should re-order the string using the following algorithm:

    + +
      +
    1. Pick the smallest character from s and append it to the result.
    2. +
    3. Pick the smallest character from s which is greater than the last appended character to the result and append it.
    4. +
    5. Repeat step 2 until you cannot pick more characters.
    6. +
    7. Pick the largest character from s and append it to the result.
    8. +
    9. Pick the largest character from s which is smaller than the last appended character to the result and append it.
    10. +
    11. Repeat step 5 until you cannot pick more characters.
    12. +
    13. Repeat the steps from 1 to 6 until you pick all characters from s.
    14. +
    + +

    In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.

    + +

    Return the result string after sorting s with this algorithm.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aaaabbbbcccc"
    +Output: "abccbaabccba"
    +Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
    +After steps 4, 5 and 6 of the first iteration, result = "abccba"
    +First iteration is done. Now s = "aabbcc" and we go back to step 1
    +After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
    +After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
    +
    + +

    Example 2:

    + +
    +Input: s = "rat"
    +Output: "art"
    +Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
    +
    + +

    Example 3:

    + +
    +Input: s = "leetcode"
    +Output: "cdelotee"
    +
    + +

    Example 4:

    + +
    +Input: s = "ggggggg"
    +Output: "ggggggg"
    +
    + +

    Example 5:

    + +
    +Input: s = "spo"
    +Output: "ops"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s contains only lower-case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md b/assets/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md new file mode 100644 index 00000000..d11bd96c --- /dev/null +++ b/assets/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md @@ -0,0 +1,65 @@ +# [1371. Find the Longest Substring Containing Vowels in Even Counts](https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts) + + + +## Description + +

    Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "eleetminicoworoep"
    +Output: 13
    +Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.
    +
    + +

    Example 2:

    + +
    +Input: s = "leetcodeisgreat"
    +Output: 5
    +Explanation: The longest substring is "leetc" which contains two e's.
    +
    + +

    Example 3:

    + +
    +Input: s = "bcbcbc"
    +Output: 6
    +Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 5 x 10^5
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md b/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md new file mode 100644 index 00000000..9af9841d --- /dev/null +++ b/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md @@ -0,0 +1,77 @@ +# [1372. Longest ZigZag Path in a Binary Tree](https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree) + + + +## Description + +

    You are given the root of a binary tree.

    + +

    A ZigZag path for a binary tree is defined as follow:

    + +
      +
    • Choose any node in the binary tree and a direction (right or left).
    • +
    • If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
    • +
    • Change the direction from right to left or from left to right.
    • +
    • Repeat the second and third steps until you can't move in the tree.
    • +
    + +

    Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).

    + +

    Return the longest ZigZag path contained in that tree.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
    +Output: 3
    +Explanation: Longest ZigZag path in blue nodes (right -> left -> right).
    +
    + +

    Example 2:

    + +
    +Input: root = [1,1,1,null,1,null,null,1,1,null,1]
    +Output: 4
    +Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).
    +
    + +

    Example 3:

    + +
    +Input: root = [1]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 5 * 104].
    • +
    • 1 <= Node.val <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/images/sample_1_1702.png b/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/images/sample_1_1702.png new file mode 100644 index 00000000..035facfc Binary files /dev/null and b/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/images/sample_1_1702.png differ diff --git a/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/images/sample_2_1702.png b/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/images/sample_2_1702.png new file mode 100644 index 00000000..d3e756f7 Binary files /dev/null and b/assets/1300-1399/1372.Longest ZigZag Path in a Binary Tree/images/sample_2_1702.png differ diff --git a/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md b/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md new file mode 100644 index 00000000..febeee61 --- /dev/null +++ b/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md @@ -0,0 +1,91 @@ +# [1373. Maximum Sum BST in Binary Tree](https://leetcode.com/problems/maximum-sum-bst-in-binary-tree) + + + +## Description + +

    Given a binary tree root, the task is to return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).

    + +

    Assume a BST is defined as follows:

    + +
      +
    • The left subtree of a node contains only nodes with keys less than the node's key.
    • +
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • +
    • Both the left and right subtrees must also be binary search trees.
    • +
    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
    +Output: 20
    +Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [4,3,null,1,2]
    +Output: 2
    +Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.
    +
    + +

    Example 3:

    + +
    +Input: root = [-4,-2,-5]
    +Output: 0
    +Explanation: All values are negatives. Return an empty BST.
    +
    + +

    Example 4:

    + +
    +Input: root = [2,1,3]
    +Output: 6
    +
    + +

    Example 5:

    + +
    +Input: root = [5,4,8,3,null,6,3]
    +Output: 7
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The given binary tree will have between 1 and 40000 nodes.
    • +
    • Each node's value is between [-4 * 10^4 , 4 * 10^4].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/images/sample_1_1709.png b/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/images/sample_1_1709.png new file mode 100644 index 00000000..b0e6a9f1 Binary files /dev/null and b/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/images/sample_1_1709.png differ diff --git a/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/images/sample_2_1709.png b/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/images/sample_2_1709.png new file mode 100644 index 00000000..dbbfb49a Binary files /dev/null and b/assets/1300-1399/1373.Maximum Sum BST in Binary Tree/images/sample_2_1709.png differ diff --git a/assets/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md b/assets/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md new file mode 100644 index 00000000..b564f207 --- /dev/null +++ b/assets/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md @@ -0,0 +1,65 @@ +# [1374. Generate a String With Characters That Have Odd Counts](https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts) + + + +## Description + +

    Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.

    + +

    The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.  

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4
    +Output: "pppz"
    +Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: "xy"
    +Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".
    +
    + +

    Example 3:

    + +
    +Input: n = 7
    +Output: "holasss"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 500
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1375.Bulb Switcher III/README_EN.md b/assets/1300-1399/1375.Bulb Switcher III/README_EN.md new file mode 100644 index 00000000..fd25882d --- /dev/null +++ b/assets/1300-1399/1375.Bulb Switcher III/README_EN.md @@ -0,0 +1,87 @@ +# [1375. Bulb Switcher III](https://leetcode.com/problems/bulb-switcher-iii) + + + +## Description + +

    There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. Initially, all the bulbs are turned off.

    + +

    At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only if it is on and all the previous bulbs (to the left) are turned on too.

    + +

    Return the number of moments in which all turned on bulbs are blue.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: light = [2,1,3,5,4]
    +Output: 3
    +Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4.
    +
    + +

    Example 2:

    + +
    +Input: light = [3,2,4,1,5]
    +Output: 2
    +Explanation: All bulbs turned on, are blue at the moment 3, and 4 (index-0).
    +
    + +

    Example 3:

    + +
    +Input: light = [4,1,2,3]
    +Output: 1
    +Explanation: All bulbs turned on, are blue at the moment 3 (index-0).
    +Bulb 4th changes to blue at the moment 3.
    +
    + +

    Example 4:

    + +
    +Input: light = [2,1,4,3,6,5]
    +Output: 3
    +
    + +

    Example 5:

    + +
    +Input: light = [1,2,3,4,5,6]
    +Output: 6
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == light.length
    • +
    • 1 <= n <= 5 * 10^4
    • +
    • light is a permutation of  [1, 2, ..., n]
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1375.Bulb Switcher III/images/sample_2_1725.png b/assets/1300-1399/1375.Bulb Switcher III/images/sample_2_1725.png new file mode 100644 index 00000000..c296e38b Binary files /dev/null and b/assets/1300-1399/1375.Bulb Switcher III/images/sample_2_1725.png differ diff --git a/assets/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md b/assets/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md new file mode 100644 index 00000000..ceac3105 --- /dev/null +++ b/assets/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md @@ -0,0 +1,104 @@ +# [1376. Time Needed to Inform All Employees](https://leetcode.com/problems/time-needed-to-inform-all-employees) + + + +## Description + +

    A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.

    + +

    Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.

    + +

    The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.

    + +

    The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).

    + +

    Return the number of minutes needed to inform all the employees about the urgent news.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1, headID = 0, manager = [-1], informTime = [0]
    +Output: 0
    +Explanation: The head of the company is the only employee in the company.
    +
    + +

    Example 2:

    + +
    +Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
    +Output: 1
    +Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
    +The tree structure of the employees in the company is shown.
    +
    + +

    Example 3:

    + +
    +Input: n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = [0,6,5,4,3,2,1]
    +Output: 21
    +Explanation: The head has id = 6. He will inform employee with id = 5 in 1 minute.
    +The employee with id = 5 will inform the employee with id = 4 in 2 minutes.
    +The employee with id = 4 will inform the employee with id = 3 in 3 minutes.
    +The employee with id = 3 will inform the employee with id = 2 in 4 minutes.
    +The employee with id = 2 will inform the employee with id = 1 in 5 minutes.
    +The employee with id = 1 will inform the employee with id = 0 in 6 minutes.
    +Needed time = 1 + 2 + 3 + 4 + 5 + 6 = 21.
    +
    + +

    Example 4:

    + +
    +Input: n = 15, headID = 0, manager = [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], informTime = [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0]
    +Output: 3
    +Explanation: The first minute the head will inform employees 1 and 2.
    +The second minute they will inform employees 3, 4, 5 and 6.
    +The third minute they will inform the rest of employees.
    +
    + +

    Example 5:

    + +
    +Input: n = 4, headID = 2, manager = [3,3,-1,2], informTime = [0,0,162,914]
    +Output: 1076
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 105
    • +
    • 0 <= headID < n
    • +
    • manager.length == n
    • +
    • 0 <= manager[i] < n
    • +
    • manager[headID] == -1
    • +
    • informTime.length == n
    • +
    • 0 <= informTime[i] <= 1000
    • +
    • informTime[i] == 0 if employee i has no subordinates.
    • +
    • It is guaranteed that all the employees can be informed.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1376.Time Needed to Inform All Employees/images/1730_example_3_5.png b/assets/1300-1399/1376.Time Needed to Inform All Employees/images/1730_example_3_5.png new file mode 100644 index 00000000..b66709a4 Binary files /dev/null and b/assets/1300-1399/1376.Time Needed to Inform All Employees/images/1730_example_3_5.png differ diff --git a/assets/1300-1399/1376.Time Needed to Inform All Employees/images/graph.png b/assets/1300-1399/1376.Time Needed to Inform All Employees/images/graph.png new file mode 100644 index 00000000..51d0d306 Binary files /dev/null and b/assets/1300-1399/1376.Time Needed to Inform All Employees/images/graph.png differ diff --git a/assets/1300-1399/1377.Frog Position After T Seconds/README_EN.md b/assets/1300-1399/1377.Frog Position After T Seconds/README_EN.md new file mode 100644 index 00000000..d68791ed --- /dev/null +++ b/assets/1300-1399/1377.Frog Position After T Seconds/README_EN.md @@ -0,0 +1,77 @@ +# [1377. Frog Position After T Seconds](https://leetcode.com/problems/frog-position-after-t-seconds) + + + +## Description + +

    Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.

    + +

    The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.

    + +

    Return the probability that after t seconds the frog is on the vertex target.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
    +Output: 0.16666666666666666 
    +Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. 
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
    +Output: 0.3333333333333333
    +Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. 
    +
    + +

    Example 3:

    + +
    +Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
    +Output: 0.16666666666666666
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 100
    • +
    • edges.length == n - 1
    • +
    • edges[i].length == 2
    • +
    • 1 <= ai, bi <= n
    • +
    • 1 <= t <= 50
    • +
    • 1 <= target <= n
    • +
    • Answers within 10-5 of the actual value will be accepted as correct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1377.Frog Position After T Seconds/images/frog_2.png b/assets/1300-1399/1377.Frog Position After T Seconds/images/frog_2.png new file mode 100644 index 00000000..04880625 Binary files /dev/null and b/assets/1300-1399/1377.Frog Position After T Seconds/images/frog_2.png differ diff --git a/assets/1300-1399/1377.Frog Position After T Seconds/images/frog_3.png b/assets/1300-1399/1377.Frog Position After T Seconds/images/frog_3.png new file mode 100644 index 00000000..9f923134 Binary files /dev/null and b/assets/1300-1399/1377.Frog Position After T Seconds/images/frog_3.png differ diff --git a/assets/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md b/assets/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md new file mode 100644 index 00000000..0756362c --- /dev/null +++ b/assets/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md @@ -0,0 +1,101 @@ +# [1378. Replace Employee ID With The Unique Identifier](https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier) + + + +## Description + +

    Table: Employees

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id is the primary key for this table.
    +Each row of this table contains the id and the name of an employee in a company.
    +
    + +

     

    + +

    Table: EmployeeUNI

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| unique_id     | int     |
    ++---------------+---------+
    +(id, unique_id) is the primary key for this table.
    +Each row of this table contains the id and the corresponding unique id of an employee in the company.
    +
    + +

     

    + +

    Write an SQL query to show the unique ID of each user, If a user doesn't have a unique ID replace just show null.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +
    +Employees table:
    ++----+----------+
    +| id | name     |
    ++----+----------+
    +| 1  | Alice    |
    +| 7  | Bob      |
    +| 11 | Meir     |
    +| 90 | Winston  |
    +| 3  | Jonathan |
    ++----+----------+
    +
    +EmployeeUNI table:
    ++----+-----------+
    +| id | unique_id |
    ++----+-----------+
    +| 3  | 1         |
    +| 11 | 2         |
    +| 90 | 3         |
    ++----+-----------+
    +
    +Result table:
    ++-----------+----------+
    +| unique_id | name     |
    ++-----------+----------+
    +| null      | Alice    |
    +| null      | Bob      |
    +| 2         | Meir     |
    +| 3         | Winston  |
    +| 1         | Jonathan |
    ++-----------+----------+
    +
    +Alice and Bob don't have a unique ID, We will show null instead.
    +The unique ID of Meir is 2.
    +The unique ID of Winston is 3.
    +The unique ID of Jonathan is 1.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + b.unique_id AS unique_id, + a.name AS name +FROM + Employees a +LEFT JOIN + EmployeeUNI b +ON + a.id = b.id; +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md new file mode 100644 index 00000000..dda8611c --- /dev/null +++ b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md @@ -0,0 +1,135 @@ +# [1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree](https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree) + + + +## Description + +

    Given two binary trees original and cloned and given a reference to a node target in the original tree.

    + + + +

    The cloned tree is a copy of the original tree.

    + + + +

    Return a reference to the same node in the cloned tree.

    + + + +

    Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.

    + + + +

    Follow up: Solve the problem if repeated values on the tree are allowed.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: tree = [7,4,3,null,null,6,19], target = 3
    +
    +Output: 3
    +
    +Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: tree = [7], target =  7
    +
    +Output: 7
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
    +
    +Output: 4
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: tree = [1,2,3,4,5,6,7,8,9,10], target = 5
    +
    +Output: 5
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: tree = [1,2,null,3], target = 2
    +
    +Output: 2
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is in the range [1, 10^4].
    • +
    • The values of the nodes of the tree are unique.
    • +
    • target node is a node from the original tree and is not null.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e1.png b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e1.png new file mode 100644 index 00000000..5173e5c5 Binary files /dev/null and b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e1.png differ diff --git a/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e2.png b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e2.png new file mode 100644 index 00000000..f6a805bc Binary files /dev/null and b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e2.png differ diff --git a/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e3.png b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e3.png new file mode 100644 index 00000000..553015cf Binary files /dev/null and b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e3.png differ diff --git a/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e4.png b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e4.png new file mode 100644 index 00000000..375a2a71 Binary files /dev/null and b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e4.png differ diff --git a/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e5.png b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e5.png new file mode 100644 index 00000000..ea1ab16a Binary files /dev/null and b/assets/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/images/e5.png differ diff --git a/assets/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md b/assets/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md new file mode 100644 index 00000000..17b52988 --- /dev/null +++ b/assets/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md @@ -0,0 +1,98 @@ +# [1380. Lucky Numbers in a Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix) + + + +## Description + +

    Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

    + +

    A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
    +Output: [15]
    +Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
    +Output: [12]
    +Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
    +
    + +

    Example 3:

    + +
    +Input: matrix = [[7,8],[1,2]]
    +Output: [7]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= n, m <= 50
    • +
    • 1 <= matrix[i][j] <= 10^5.
    • +
    • All elements in the matrix are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: + row_min = {min(rows) for rows in matrix} + col_max = {max(cols) for cols in zip(*matrix)} + return [e for e in row_min if e in col_max] +``` + +### **Java** + +```java +class Solution { + public List luckyNumbers (int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + Set rowMin = new HashSet<>(); + List res = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + int min = Integer.MAX_VALUE; + for (int j = 0; j < n; ++j) { + min = Math.min(min, matrix[i][j]); + } + rowMin.add(min); + } + + for (int j = 0; j < n; ++j) { + int max = Integer.MIN_VALUE; + for (int i = 0; i < m; ++i) { + max = Math.max(max, matrix[i][j]); + } + if (rowMin.contains(max)) { + res.add(max); + } + + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md b/assets/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md new file mode 100644 index 00000000..a1362627 --- /dev/null +++ b/assets/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md @@ -0,0 +1,167 @@ +# [1381. Design a Stack With Increment Operation](https://leetcode.com/problems/design-a-stack-with-increment-operation) + + + +## Description + +

    Design a stack which supports the following operations.

    + + + +

    Implement the CustomStack class:

    + + + +
      +
    • CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.
    • +
    • void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.
    • +
    • int pop() Pops and returns the top of stack or -1 if the stack is empty.
    • +
    • void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input
    +
    +["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]
    +
    +[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
    +
    +Output
    +
    +[null,null,null,2,null,null,null,null,null,103,202,201,-1]
    +
    +Explanation
    +
    +CustomStack customStack = new CustomStack(3); // Stack is Empty []
    +
    +customStack.push(1);                          // stack becomes [1]
    +
    +customStack.push(2);                          // stack becomes [1, 2]
    +
    +customStack.pop();                            // return 2 --> Return top of the stack 2, stack becomes [1]
    +
    +customStack.push(2);                          // stack becomes [1, 2]
    +
    +customStack.push(3);                          // stack becomes [1, 2, 3]
    +
    +customStack.push(4);                          // stack still [1, 2, 3], Don't add another elements as size is 4
    +
    +customStack.increment(5, 100);                // stack becomes [101, 102, 103]
    +
    +customStack.increment(2, 100);                // stack becomes [201, 202, 103]
    +
    +customStack.pop();                            // return 103 --> Return top of the stack 103, stack becomes [201, 202]
    +
    +customStack.pop();                            // return 202 --> Return top of the stack 102, stack becomes [201]
    +
    +customStack.pop();                            // return 201 --> Return top of the stack 101, stack becomes []
    +
    +customStack.pop();                            // return -1 --> Stack is empty return -1.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= maxSize <= 1000
    • +
    • 1 <= x <= 1000
    • +
    • 1 <= k <= 1000
    • +
    • 0 <= val <= 100
    • +
    • At most 1000 calls will be made to each method of increment, push and pop each separately.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class CustomStack: + + def __init__(self, maxSize: int): + self.s = [0] * maxSize + self.tail = 0 + + def push(self, x: int) -> None: + if self.tail < len(self.s): + self.s[self.tail] = x + self.tail += 1 + + def pop(self) -> int: + if self.tail == 0: + return -1 + self.tail -= 1 + return self.s[self.tail] + + def increment(self, k: int, val: int) -> None: + for i in range(min(k, self.tail)): + self.s[i] += val + + +# Your CustomStack object will be instantiated and called as such: +# obj = CustomStack(maxSize) +# obj.push(x) +# param_2 = obj.pop() +# obj.increment(k,val) +``` + +### **Java** + +```java +class CustomStack { + private int[] s; + private int tail; + + public CustomStack(int maxSize) { + s = new int[maxSize]; + } + + public void push(int x) { + if (tail < s.length) { + s[tail++] = x; + } + } + + public int pop() { + return tail == 0 ? -1 : s[--tail]; + } + + public void increment(int k, int val) { + for (int i = 0; i < Math.min(k, tail); ++i) { + s[i] += val; + } + } +} + +/** + * Your CustomStack object will be instantiated and called as such: + * CustomStack obj = new CustomStack(maxSize); + * obj.push(x); + * int param_2 = obj.pop(); + * obj.increment(k,val); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1382.Balance a Binary Search Tree/README_EN.md b/assets/1300-1399/1382.Balance a Binary Search Tree/README_EN.md new file mode 100644 index 00000000..7dc9bd65 --- /dev/null +++ b/assets/1300-1399/1382.Balance a Binary Search Tree/README_EN.md @@ -0,0 +1,74 @@ +# [1382. Balance a Binary Search Tree](https://leetcode.com/problems/balance-a-binary-search-tree) + + + +## Description + +

    Given a binary search tree, return a balanced binary search tree with the same node values.

    + + + +

    A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.

    + + + +

    If there is more than one answer, return any of them.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: root = [1,null,2,null,3,null,4,null,null]
    +
    +Output: [2,1,3,null,null,null,4]
    +
    +Explanation: This is not the only correct answer, [3,1,4,null,2,null,null] is also correct.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is between 1 and 10^4.
    • +
    • The tree nodes will have distinct values between 1 and 10^5.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1382.Balance a Binary Search Tree/images/1515_ex1.png b/assets/1300-1399/1382.Balance a Binary Search Tree/images/1515_ex1.png new file mode 100644 index 00000000..87ed014c Binary files /dev/null and b/assets/1300-1399/1382.Balance a Binary Search Tree/images/1515_ex1.png differ diff --git a/assets/1300-1399/1382.Balance a Binary Search Tree/images/1515_ex1_out.png b/assets/1300-1399/1382.Balance a Binary Search Tree/images/1515_ex1_out.png new file mode 100644 index 00000000..17757097 Binary files /dev/null and b/assets/1300-1399/1382.Balance a Binary Search Tree/images/1515_ex1_out.png differ diff --git a/assets/1300-1399/1383.Maximum Performance of a Team/README_EN.md b/assets/1300-1399/1383.Maximum Performance of a Team/README_EN.md new file mode 100644 index 00000000..1ad228d5 --- /dev/null +++ b/assets/1300-1399/1383.Maximum Performance of a Team/README_EN.md @@ -0,0 +1,104 @@ +# [1383. Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team) + + + +## Description + +

    There are n engineers numbered from 1 to n and two arrays: speed and efficiency, where speed[i] and efficiency[i] represent the speed and efficiency for the i-th engineer respectively. Return the maximum performance of a team composed of at most k engineers, since the answer can be a huge number, return this modulo 10^9 + 7.

    + + + +

    The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers. 

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
    +
    +Output: 60
    +
    +Explanation: 
    +
    +We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
    +
    +Output: 68
    +
    +Explanation:
    +
    +This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4
    +
    +Output: 72
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^5
    • +
    • speed.length == n
    • +
    • efficiency.length == n
    • +
    • 1 <= speed[i] <= 10^5
    • +
    • 1 <= efficiency[i] <= 10^8
    • +
    • 1 <= k <= n
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1384.Total Sales Amount by Year/README_EN.md b/assets/1300-1399/1384.Total Sales Amount by Year/README_EN.md new file mode 100644 index 00000000..7bc61354 --- /dev/null +++ b/assets/1300-1399/1384.Total Sales Amount by Year/README_EN.md @@ -0,0 +1,91 @@ +# [1384. Total Sales Amount by Year](https://leetcode.com/problems/total-sales-amount-by-year) + + + +## Description + +

    Table: Product

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    ++---------------+---------+
    +product_id is the primary key for this table.
    +product_name is the name of the product.
    +
    + +

     

    + +

    Table: Sales

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| product_id          | int     |
    +| period_start        | date    |
    +| period_end          | date    |
    +| average_daily_sales | int     |
    ++---------------------+---------+
    +product_id is the primary key for this table. 
    +period_start and period_end indicates the start and end date for sales period, both dates are inclusive.
    +The average_daily_sales column holds the average daily sales amount of the items for the period.
    +
    +
    + +

    Write an SQL query to report the Total sales amount of each item for each year, with corresponding product name, product_id, product_name and report_year.

    + +

    Dates of the sales years are between 2018 to 2020. Return the result table ordered by product_id and report_year.

    + +

    The query result format is in the following example:

    + +
    +Product table:
    ++------------+--------------+
    +| product_id | product_name |
    ++------------+--------------+
    +| 1          | LC Phone     |
    +| 2          | LC T-Shirt   |
    +| 3          | LC Keychain  |
    ++------------+--------------+
    +
    +Sales table:
    ++------------+--------------+-------------+---------------------+
    +| product_id | period_start | period_end  | average_daily_sales |
    ++------------+--------------+-------------+---------------------+
    +| 1          | 2019-01-25   | 2019-02-28  | 100                 |
    +| 2          | 2018-12-01   | 2020-01-01  | 10                  |
    +| 3          | 2019-12-01   | 2020-01-31  | 1                   |
    ++------------+--------------+-------------+---------------------+
    +
    +Result table:
    ++------------+--------------+-------------+--------------+
    +| product_id | product_name | report_year | total_amount |
    ++------------+--------------+-------------+--------------+
    +| 1          | LC Phone     |    2019     | 3500         |
    +| 2          | LC T-Shirt   |    2018     | 310          |
    +| 2          | LC T-Shirt   |    2019     | 3650         |
    +| 2          | LC T-Shirt   |    2020     | 10           |
    +| 3          | LC Keychain  |    2019     | 31           |
    +| 3          | LC Keychain  |    2020     | 31           |
    ++------------+--------------+-------------+--------------+
    +LC Phone was sold for the period of 2019-01-25 to 2019-02-28, and there are 35 days for this period. Total amount 35*100 = 3500. 
    +LC T-shirt was sold for the period of 2018-12-01 to 2020-01-01, and there are 31, 365, 1 days for years 2018, 2019 and 2020 respectively.
    +LC Keychain was sold for the period of 2019-12-01 to 2020-01-31, and there are 31, 31 days for years 2019 and 2020 respectively.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md b/assets/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md new file mode 100644 index 00000000..8805949c --- /dev/null +++ b/assets/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md @@ -0,0 +1,153 @@ +# [1385. Find the Distance Value Between Two Arrays](https://leetcode.com/problems/find-the-distance-value-between-two-arrays) + + + +## Description + +

    Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.

    + +

    The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.

    + +

     

    +

    Example 1:

    + +
    +Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
    +Output: 2
    +Explanation: 
    +For arr1[0]=4 we have: 
    +|4-10|=6 > d=2 
    +|4-9|=5 > d=2 
    +|4-1|=3 > d=2 
    +|4-8|=4 > d=2 
    +For arr1[1]=5 we have: 
    +|5-10|=5 > d=2 
    +|5-9|=4 > d=2 
    +|5-1|=4 > d=2 
    +|5-8|=3 > d=2
    +For arr1[2]=8 we have:
    +|8-10|=2 <= d=2
    +|8-9|=1 <= d=2
    +|8-1|=7 > d=2
    +|8-8|=0 <= d=2
    +
    + +

    Example 2:

    + +
    +Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 500
    • +
    • -10^3 <= arr1[i], arr2[j] <= 10^3
    • +
    • 0 <= d <= 100
    • +
    + +## Solutions + +Brute-force. + + + +### **Python3** + +```python +class Solution: + def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: + res = 0 + for a in arr1: + exist = False + for b in arr2: + if abs(a - b) <= d: + exist = True + break + if not exist: + res += 1 + return res +``` + +### **Java** + +```java +class Solution { + public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { + int res = 0; + for (int a : arr1) { + boolean exist = false; + for (int b : arr2) { + if (Math.abs(a - b) <= d) { + exist = true; + break; + } + } + if (!exist) { + ++res; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + int res = 0; + for (auto& a : arr1) { + bool exist = false; + for (auto& b : arr2) { + if (abs(a - b) <= d) { + exist = true; + break; + } + } + if (!exist) ++res; + } + return res; + } +}; +``` + +### **Go** + +```go +func findTheDistanceValue(arr1 []int, arr2 []int, d int) int { + res := 0 + for _, a := range arr1 { + exist := false + for _, b := range arr2 { + if math.Abs(float64(a-b)) <= float64(d) { + exist = true + break + } + } + if !exist { + res++ + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1386.Cinema Seat Allocation/README_EN.md b/assets/1300-1399/1386.Cinema Seat Allocation/README_EN.md new file mode 100644 index 00000000..35d675a1 --- /dev/null +++ b/assets/1300-1399/1386.Cinema Seat Allocation/README_EN.md @@ -0,0 +1,75 @@ +# [1386. Cinema Seat Allocation](https://leetcode.com/problems/cinema-seat-allocation) + + + +## Description + +

    + +

    A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.

    + +

    Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.

    + +

    Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
    +Output: 4
    +Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
    +
    + +

    Example 2:

    + +
    +Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^9
    • +
    • 1 <= reservedSeats.length <= min(10*n, 10^4)
    • +
    • reservedSeats[i].length == 2
    • +
    • 1 <= reservedSeats[i][0] <= n
    • +
    • 1 <= reservedSeats[i][1] <= 10
    • +
    • All reservedSeats[i] are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1386.Cinema Seat Allocation/images/cinema_seats_1.png b/assets/1300-1399/1386.Cinema Seat Allocation/images/cinema_seats_1.png new file mode 100644 index 00000000..5a36023c Binary files /dev/null and b/assets/1300-1399/1386.Cinema Seat Allocation/images/cinema_seats_1.png differ diff --git a/assets/1300-1399/1386.Cinema Seat Allocation/images/cinema_seats_3.png b/assets/1300-1399/1386.Cinema Seat Allocation/images/cinema_seats_3.png new file mode 100644 index 00000000..35ac1338 Binary files /dev/null and b/assets/1300-1399/1386.Cinema Seat Allocation/images/cinema_seats_3.png differ diff --git a/assets/1300-1399/1387.Sort Integers by The Power Value/README_EN.md b/assets/1300-1399/1387.Sort Integers by The Power Value/README_EN.md new file mode 100644 index 00000000..7f71e337 --- /dev/null +++ b/assets/1300-1399/1387.Sort Integers by The Power Value/README_EN.md @@ -0,0 +1,157 @@ +# [1387. Sort Integers by The Power Value](https://leetcode.com/problems/sort-integers-by-the-power-value) + + + +## Description + +

    The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:

    + + + +
      +
    • if x is even then x = x / 2
    • +
    • if x is odd then x = 3 * x + 1
    • +
    + + + +

    For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).

    + + + +

    Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.

    + + + +

    Return the k-th integer in the range [lo, hi] sorted by the power value.

    + + + +

    Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: lo = 12, hi = 15, k = 2
    +
    +Output: 13
    +
    +Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
    +
    +The power of 13 is 9
    +
    +The power of 14 is 17
    +
    +The power of 15 is 17
    +
    +The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.
    +
    +Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: lo = 1, hi = 1, k = 1
    +
    +Output: 1
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: lo = 7, hi = 11, k = 4
    +
    +Output: 7
    +
    +Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].
    +
    +The interval sorted by power is [8, 10, 11, 7, 9].
    +
    +The fourth number in the sorted array is 7.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: lo = 10, hi = 20, k = 5
    +
    +Output: 13
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: lo = 1, hi = 1000, k = 777
    +
    +Output: 570
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= lo <= hi <= 1000
    • +
    • 1 <= k <= hi - lo + 1
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1388.Pizza With 3n Slices/README_EN.md b/assets/1300-1399/1388.Pizza With 3n Slices/README_EN.md new file mode 100644 index 00000000..5d1ca44a --- /dev/null +++ b/assets/1300-1399/1388.Pizza With 3n Slices/README_EN.md @@ -0,0 +1,87 @@ +# [1388. Pizza With 3n Slices](https://leetcode.com/problems/pizza-with-3n-slices) + + + +## Description + +

    There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:

    + +
      +
    • You will pick any pizza slice.
    • +
    • Your friend Alice will pick next slice in anti clockwise direction of your pick. 
    • +
    • Your friend Bob will pick next slice in clockwise direction of your pick.
    • +
    • Repeat until there are no more slices of pizzas.
    • +
    + +

    Sizes of Pizza slices is represented by circular array slices in clockwise direction.

    + +

    Return the maximum possible sum of slice sizes which you can have.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: slices = [1,2,3,4,5,6]
    +Output: 10
    +Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
    +
    + +

    Example 2:

    + +

    + +
    +Input: slices = [8,9,8,6,1,1]
    +Output: 16
    +Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
    +
    + +

    Example 3:

    + +
    +Input: slices = [4,1,2,5,8,3,1,9,7]
    +Output: 21
    +
    + +

    Example 4:

    + +
    +Input: slices = [3,1,2]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= slices.length <= 500
    • +
    • slices.length % 3 == 0
    • +
    • 1 <= slices[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1388.Pizza With 3n Slices/images/sample_3_1723.png b/assets/1300-1399/1388.Pizza With 3n Slices/images/sample_3_1723.png new file mode 100644 index 00000000..f620b00b Binary files /dev/null and b/assets/1300-1399/1388.Pizza With 3n Slices/images/sample_3_1723.png differ diff --git a/assets/1300-1399/1388.Pizza With 3n Slices/images/sample_4_1723.png b/assets/1300-1399/1388.Pizza With 3n Slices/images/sample_4_1723.png new file mode 100644 index 00000000..8a6a5b80 Binary files /dev/null and b/assets/1300-1399/1388.Pizza With 3n Slices/images/sample_4_1723.png differ diff --git a/assets/1300-1399/1389.Create Target Array in the Given Order/README_EN.md b/assets/1300-1399/1389.Create Target Array in the Given Order/README_EN.md new file mode 100644 index 00000000..4bd7fea9 --- /dev/null +++ b/assets/1300-1399/1389.Create Target Array in the Given Order/README_EN.md @@ -0,0 +1,88 @@ +# [1389. Create Target Array in the Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order) + + + +## Description + +

    Given two arrays of integers nums and index. Your task is to create target array under the following rules:

    + +
      +
    • Initially target array is empty.
    • +
    • From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
    • +
    • Repeat the previous step until there are no elements to read in nums and index.
    • +
    + +

    Return the target array.

    + +

    It is guaranteed that the insertion operations will be valid.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
    +Output: [0,4,1,3,2]
    +Explanation:
    +nums       index     target
    +0            0        [0]
    +1            1        [0,1]
    +2            2        [0,1,2]
    +3            2        [0,1,3,2]
    +4            1        [0,4,1,3,2]
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
    +Output: [0,1,2,3,4]
    +Explanation:
    +nums       index     target
    +1            0        [1]
    +2            1        [1,2]
    +3            2        [1,2,3]
    +4            3        [1,2,3,4]
    +0            0        [0,1,2,3,4]
    +
    + +

    Example 3:

    + +
    +Input: nums = [1], index = [0]
    +Output: [1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length, index.length <= 100
    • +
    • nums.length == index.length
    • +
    • 0 <= nums[i] <= 100
    • +
    • 0 <= index[i] <= i
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1390.Four Divisors/README_EN.md b/assets/1300-1399/1390.Four Divisors/README_EN.md new file mode 100644 index 00000000..570a39fd --- /dev/null +++ b/assets/1300-1399/1390.Four Divisors/README_EN.md @@ -0,0 +1,55 @@ +# [1390. Four Divisors](https://leetcode.com/problems/four-divisors) + + + +## Description + +

    Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors.

    + +

    If there is no such integer in the array, return 0.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [21,4,7]
    +Output: 32
    +Explanation:
    +21 has 4 divisors: 1, 3, 7, 21
    +4 has 3 divisors: 1, 2, 4
    +7 has 2 divisors: 1, 7
    +The answer is the sum of divisors of 21 only.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^4
    • +
    • 1 <= nums[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md new file mode 100644 index 00000000..ec7312f7 --- /dev/null +++ b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md @@ -0,0 +1,97 @@ +# [1391. Check if There is a Valid Path in a Grid](https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid) + + + +## Description + +Given a m x n grid. Each cell of the grid represents a street. The street of grid[i][j] can be: +
      +
    • 1 which means a street connecting the left cell and the right cell.
    • +
    • 2 which means a street connecting the upper cell and the lower cell.
    • +
    • 3 which means a street connecting the left cell and the lower cell.
    • +
    • 4 which means a street connecting the right cell and the lower cell.
    • +
    • 5 which means a street connecting the left cell and the upper cell.
    • +
    • 6 which means a street connecting the right cell and the upper cell.
    • +
    + +

    + +

    You will initially start at the street of the upper-left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.

    + +

    Notice that you are not allowed to change any street.

    + +

    Return true if there is a valid path in the grid or false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[2,4,3],[6,5,2]]
    +Output: true
    +Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,2,1],[1,2,1]]
    +Output: false
    +Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,1,2]]
    +Output: false
    +Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
    +
    + +

    Example 4:

    + +
    +Input: grid = [[1,1,1,1,1,1,3]]
    +Output: true
    +
    + +

    Example 5:

    + +
    +Input: grid = [[2],[2],[2],[2],[2],[2],[6]]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 300
    • +
    • 1 <= grid[i][j] <= 6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/e1.png b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/e1.png new file mode 100644 index 00000000..ffab0fb9 Binary files /dev/null and b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/e1.png differ diff --git a/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/e2.png b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/e2.png new file mode 100644 index 00000000..2e9af982 Binary files /dev/null and b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/e2.png differ diff --git a/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/main.png b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/main.png new file mode 100644 index 00000000..0dcb6c09 Binary files /dev/null and b/assets/1300-1399/1391.Check if There is a Valid Path in a Grid/images/main.png differ diff --git a/assets/1300-1399/1392.Longest Happy Prefix/README_EN.md b/assets/1300-1399/1392.Longest Happy Prefix/README_EN.md new file mode 100644 index 00000000..4d366c23 --- /dev/null +++ b/assets/1300-1399/1392.Longest Happy Prefix/README_EN.md @@ -0,0 +1,75 @@ +# [1392. Longest Happy Prefix](https://leetcode.com/problems/longest-happy-prefix) + + + +## Description + +

    A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).

    + +

    Given a string s. Return the longest happy prefix of s .

    + +

    Return an empty string if no such prefix exists.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "level"
    +Output: "l"
    +Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
    +
    + +

    Example 2:

    + +
    +Input: s = "ababab"
    +Output: "abab"
    +Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
    +
    + +

    Example 3:

    + +
    +Input: s = "leetcodeleet"
    +Output: "leet"
    +
    + +

    Example 4:

    + +
    +Input: s = "a"
    +Output: ""
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1393.Capital GainLoss/README_EN.md b/assets/1300-1399/1393.Capital GainLoss/README_EN.md new file mode 100644 index 00000000..38c1aea8 --- /dev/null +++ b/assets/1300-1399/1393.Capital GainLoss/README_EN.md @@ -0,0 +1,87 @@ +# [1393. Capital GainLoss](https://leetcode.com/problems/capital-gainloss) + + + +## Description + +

    Table: Stocks

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| stock_name    | varchar |
    +| operation     | enum    |
    +| operation_day | int     |
    +| price         | int     |
    ++---------------+---------+
    +(stock_name, operation_day) is the primary key for this table.
    +The operation column is an ENUM of type ('Sell', 'Buy')
    +Each row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price.
    +It is guaranteed that each 'Sell' operation for a stock has a corresponding 'Buy' operation in a previous day.
    +
    + +

     

    + +

    Write an SQL query to report the Capital gain/loss for each stock.

    + +

    The capital gain/loss of a stock is total gain or loss after buying and selling the stock one or many times.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Stocks table:
    ++---------------+-----------+---------------+--------+
    +| stock_name    | operation | operation_day | price  |
    ++---------------+-----------+---------------+--------+
    +| Leetcode      | Buy       | 1             | 1000   |
    +| Corona Masks  | Buy       | 2             | 10     |
    +| Leetcode      | Sell      | 5             | 9000   |
    +| Handbags      | Buy       | 17            | 30000  |
    +| Corona Masks  | Sell      | 3             | 1010   |
    +| Corona Masks  | Buy       | 4             | 1000   |
    +| Corona Masks  | Sell      | 5             | 500    |
    +| Corona Masks  | Buy       | 6             | 1000   |
    +| Handbags      | Sell      | 29            | 7000   |
    +| Corona Masks  | Sell      | 10            | 10000  |
    ++---------------+-----------+---------------+--------+
    +
    +Result table:
    ++---------------+-------------------+
    +| stock_name    | capital_gain_loss |
    ++---------------+-------------------+
    +| Corona Masks  | 9500              |
    +| Leetcode      | 8000              |
    +| Handbags      | -23000            |
    ++---------------+-------------------+
    +Leetcode stock was bought at day 1 for 1000$ and was sold at day 5 for 9000$. Capital gain = 9000 - 1000 = 8000$.
    +Handbags stock was bought at day 17 for 30000$ and was sold at day 29 for 7000$. Capital loss = 7000 - 30000 = -23000$.
    +Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$. It was bought again at day 4 for 1000$ and was sold at day 5 for 500$. At last, it was bought at day 6 for 1000$ and was sold at day 10 for 10000$. Capital gain/loss is the sum of capital gains/losses for each ('Buy' --> 'Sell') operation = (1010 - 10) + (500 - 1000) + (10000 - 1000) = 1000 - 500 + 9000 = 9500$.
    +
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + stock_name, + sum( + CASE WHEN operation = 'Buy' THEN -price ELSE price END + ) AS capital_gain_loss +FROM + Stocks +GROUP BY + stock_name; +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md b/assets/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md new file mode 100644 index 00000000..7a13d7f6 --- /dev/null +++ b/assets/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md @@ -0,0 +1,126 @@ +# [1394. Find Lucky Integer in an Array](https://leetcode.com/problems/find-lucky-integer-in-an-array) + + + +## Description + +

    Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.

    + + + +

    Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [2,2,3,4]
    +
    +Output: 2
    +
    +Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [1,2,2,3,3,3]
    +
    +Output: 3
    +
    +Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [2,2,2,3,3]
    +
    +Output: -1
    +
    +Explanation: There are no lucky numbers in the array.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [5]
    +
    +Output: -1
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: arr = [7,7,7,7,7,7,7]
    +
    +Output: 7
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 500
    • +
    • 1 <= arr[i] <= 500
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1395.Count Number of Teams/README_EN.md b/assets/1300-1399/1395.Count Number of Teams/README_EN.md new file mode 100644 index 00000000..544e3781 --- /dev/null +++ b/assets/1300-1399/1395.Count Number of Teams/README_EN.md @@ -0,0 +1,75 @@ +# [1395. Count Number of Teams](https://leetcode.com/problems/count-number-of-teams) + + + +## Description + +

    There are n soldiers standing in a line. Each soldier is assigned a unique rating value.

    + +

    You have to form a team of 3 soldiers amongst them under the following rules:

    + +
      +
    • Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
    • +
    • A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
    • +
    + +

    Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).

    + +

     

    +

    Example 1:

    + +
    +Input: rating = [2,5,3,4,1]
    +Output: 3
    +Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). 
    +
    + +

    Example 2:

    + +
    +Input: rating = [2,1,3]
    +Output: 0
    +Explanation: We can't form any team given the conditions.
    +
    + +

    Example 3:

    + +
    +Input: rating = [1,2,3,4]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == rating.length
    • +
    • 3 <= n <= 1000
    • +
    • 1 <= rating[i] <= 105
    • +
    • All the integers in rating are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1396.Design Underground System/README_EN.md b/assets/1300-1399/1396.Design Underground System/README_EN.md new file mode 100644 index 00000000..db228e65 --- /dev/null +++ b/assets/1300-1399/1396.Design Underground System/README_EN.md @@ -0,0 +1,188 @@ +# [1396. Design Underground System](https://leetcode.com/problems/design-underground-system) + + + +## Description + +

    An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

    + +

    Implement the UndergroundSystem class:

    + +
      +
    • void checkIn(int id, string stationName, int t) +
        +
      • A customer with a card ID equal to id, checks in at the station stationName at time t.
      • +
      • A customer can only be checked into one place at a time.
      • +
      +
    • +
    • void checkOut(int id, string stationName, int t) +
        +
      • A customer with a card ID equal to id, checks out from the station stationName at time t.
      • +
      +
    • +
    • double getAverageTime(string startStation, string endStation) +
        +
      • Returns the average time it takes to travel from startStation to endStation.
      • +
      • The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
      • +
      • The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
      • +
      • There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.
      • +
      +
    • +
    + +

    You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

    + +

     

    +

    Example 1:

    + +
    +Input
    +["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
    +[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
    +
    +Output
    +[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
    +
    +Explanation
    +UndergroundSystem undergroundSystem = new UndergroundSystem();
    +undergroundSystem.checkIn(45, "Leyton", 3);
    +undergroundSystem.checkIn(32, "Paradise", 8);
    +undergroundSystem.checkIn(27, "Leyton", 10);
    +undergroundSystem.checkOut(45, "Waterloo", 15);  // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
    +undergroundSystem.checkOut(27, "Waterloo", 20);  // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
    +undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
    +undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
    +undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
    +undergroundSystem.checkIn(10, "Leyton", 24);
    +undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000
    +undergroundSystem.checkOut(10, "Waterloo", 38);  // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
    +undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12
    +
    + +

    Example 2:

    + +
    +Input
    +["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
    +[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]
    +
    +Output
    +[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]
    +
    +Explanation
    +UndergroundSystem undergroundSystem = new UndergroundSystem();
    +undergroundSystem.checkIn(10, "Leyton", 3);
    +undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
    +undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
    +undergroundSystem.checkIn(5, "Leyton", 10);
    +undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
    +undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
    +undergroundSystem.checkIn(2, "Leyton", 21);
    +undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
    +undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= id, t <= 106
    • +
    • 1 <= stationName.length, startStation.length, endStation.length <= 10
    • +
    • All strings consist of uppercase and lowercase English letters and digits.
    • +
    • There will be at most 2 * 104 calls in total to checkIn, checkOut, and getAverageTime.
    • +
    • Answers within 10-5 of the actual value will be accepted.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class UndergroundSystem: + + def __init__(self): + self.check_in_station = {} + self.check_in_time = {} + self.total_time = {} + + def checkIn(self, id: int, stationName: str, t: int) -> None: + self.check_in_station[id] = stationName + self.check_in_time[id] = t + + def checkOut(self, id: int, stationName: str, t: int) -> None: + cost = t - self.check_in_time.pop(id) + start_station = self.check_in_station.pop(id) + stations = start_station + '.' + stationName + times = self.total_time.get(stations, [0, 0]) + times[0] += cost + times[1] += 1 + self.total_time[stations] = times + + def getAverageTime(self, startStation: str, endStation: str) -> float: + stations = startStation + '.' + endStation + times = self.total_time[stations] + return times[0] / times[1] + + +# Your UndergroundSystem object will be instantiated and called as such: +# obj = UndergroundSystem() +# obj.checkIn(id,stationName,t) +# obj.checkOut(id,stationName,t) +# param_3 = obj.getAverageTime(startStation,endStation) +``` + +### **Java** + +```java +class UndergroundSystem { + private Map checkInStation; + private Map checkInTime; + private Map totalTime; + + public UndergroundSystem() { + checkInStation = new HashMap<>(); + checkInTime = new HashMap<>(); + totalTime = new HashMap<>(); + } + + public void checkIn(int id, String stationName, int t) { + checkInStation.put(id, stationName); + checkInTime.put(id, t); + } + + public void checkOut(int id, String stationName, int t) { + int cost = t - checkInTime.remove(id); + String startStation = checkInStation.remove(id); + String stations = startStation + "." + stationName; + int[] times = totalTime.getOrDefault(stations, new int[2]); + times[0] += cost; + ++times[1]; + totalTime.put(stations, times); + } + + public double getAverageTime(String startStation, String endStation) { + String stations = startStation + "." + endStation; + int[] times = totalTime.get(stations); + return times[0] * 1.0 / times[1]; + } +} + +/** + * Your UndergroundSystem object will be instantiated and called as such: + * UndergroundSystem obj = new UndergroundSystem(); + * obj.checkIn(id,stationName,t); + * obj.checkOut(id,stationName,t); + * double param_3 = obj.getAverageTime(startStation,endStation); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1397.Find All Good Strings/README_EN.md b/assets/1300-1399/1397.Find All Good Strings/README_EN.md new file mode 100644 index 00000000..d31bdcae --- /dev/null +++ b/assets/1300-1399/1397.Find All Good Strings/README_EN.md @@ -0,0 +1,70 @@ +# [1397. Find All Good Strings](https://leetcode.com/problems/find-all-good-strings) + + + +## Description + +

    Given the strings s1 and s2 of size n and the string evil, return the number of good strings.

    + +

    A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 2, s1 = "aa", s2 = "da", evil = "b"
    +Output: 51 
    +Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da". 
    +
    + +

    Example 2:

    + +
    +Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
    +Output: 0 
    +Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string.
    +
    + +

    Example 3:

    + +
    +Input: n = 2, s1 = "gx", s2 = "gz", evil = "x"
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • s1.length == n
    • +
    • s2.length == n
    • +
    • s1 <= s2
    • +
    • 1 <= n <= 500
    • +
    • 1 <= evil.length <= 50
    • +
    • All strings consist of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md b/assets/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md new file mode 100644 index 00000000..36f7b6ea --- /dev/null +++ b/assets/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md @@ -0,0 +1,90 @@ +# [1398. Customers Who Bought Products A and B but Not C](https://leetcode.com/problems/customers-who-bought-products-a-and-b-but-not-c) + + + +## Description + +

    Table: Customers

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| customer_id         | int     |
    +| customer_name       | varchar |
    ++---------------------+---------+
    +customer_id is the primary key for this table.
    +customer_name is the name of the customer.
    + +

     

    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| customer_id   | int     |
    +| product_name  | varchar |
    ++---------------+---------+
    +order_id is the primary key for this table.
    +customer_id is the id of the customer who bought the product "product_name".
    +
    + +

     

    + +

    Write an SQL query to report the customer_id and customer_name of customers who bought products "A", "B" but did not buy the product "C" since we want to recommend them buy this product.

    + +

    Return the result table ordered by customer_id.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Customers table:
    ++-------------+---------------+
    +| customer_id | customer_name |
    ++-------------+---------------+
    +| 1           | Daniel        |
    +| 2           | Diana         |
    +| 3           | Elizabeth     |
    +| 4           | Jhon          |
    ++-------------+---------------+
    +
    +Orders table:
    ++------------+--------------+---------------+
    +| order_id   | customer_id  | product_name  |
    ++------------+--------------+---------------+
    +| 10         |     1        |     A         |
    +| 20         |     1        |     B         |
    +| 30         |     1        |     D         |
    +| 40         |     1        |     C         |
    +| 50         |     2        |     A         |
    +| 60         |     3        |     A         |
    +| 70         |     3        |     B         |
    +| 80         |     3        |     D         |
    +| 90         |     4        |     C         |
    ++------------+--------------+---------------+
    +
    +Result table:
    ++-------------+---------------+
    +| customer_id | customer_name |
    ++-------------+---------------+
    +| 3           | Elizabeth     |
    ++-------------+---------------+
    +Only the customer_id with id 3 bought the product A and B but not the product C.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1300-1399/1399.Count Largest Group/README_EN.md b/assets/1300-1399/1399.Count Largest Group/README_EN.md new file mode 100644 index 00000000..0230f09c --- /dev/null +++ b/assets/1300-1399/1399.Count Largest Group/README_EN.md @@ -0,0 +1,73 @@ +# [1399. Count Largest Group](https://leetcode.com/problems/count-largest-group) + + + +## Description + +

    Given an integer n. Each number from 1 to n is grouped according to the sum of its digits. 

    + +

    Return how many groups have the largest size.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 13
    +Output: 4
    +Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
    +[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size.
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 2
    +Explanation: There are 2 groups [1], [2] of size 1.
    +
    + +

    Example 3:

    + +
    +Input: n = 15
    +Output: 6
    +
    + +

    Example 4:

    + +
    +Input: n = 24
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1400.Construct K Palindrome Strings/README_EN.md b/assets/1400-1499/1400.Construct K Palindrome Strings/README_EN.md new file mode 100644 index 00000000..d40e7cbd --- /dev/null +++ b/assets/1400-1499/1400.Construct K Palindrome Strings/README_EN.md @@ -0,0 +1,133 @@ +# [1400. Construct K Palindrome Strings](https://leetcode.com/problems/construct-k-palindrome-strings) + + + +## Description + +

    Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s.

    + + + +

    Return True if you can use all the characters in s to construct k palindrome strings or False otherwise.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "annabelle", k = 2
    +
    +Output: true
    +
    +Explanation: You can construct two palindromes using all characters in s.
    +
    +Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "leetcode", k = 3
    +
    +Output: false
    +
    +Explanation: It is impossible to construct 3 palindromes using all the characters of s.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "true", k = 4
    +
    +Output: true
    +
    +Explanation: The only possible solution is to put each character in a separate string.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "yzyzyzyzyzyzyzy", k = 2
    +
    +Output: true
    +
    +Explanation: Simply you can put all z's in one string and all y's in the other string. Both strings will be palindrome.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: s = "cr", k = 7
    +
    +Output: false
    +
    +Explanation: We don't have enough characters in s to construct 7 palindromes.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 10^5
    • +
    • All characters in s are lower-case English letters.
    • +
    • 1 <= k <= 10^5
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md b/assets/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md new file mode 100644 index 00000000..06ad8ffd --- /dev/null +++ b/assets/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md @@ -0,0 +1,82 @@ +# [1401. Circle and Rectangle Overlapping](https://leetcode.com/problems/circle-and-rectangle-overlapping) + + + +## Description + +

    Given a circle represented as (radius, x_center, y_center) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.

    + +

    Return True if the circle and rectangle are overlapped otherwise return False.

    + +

    In other words, check if there are any point (xi, yi) such that belongs to the circle and the rectangle at the same time.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
    +Output: true
    +Explanation: Circle and rectangle share the point (1,0) 
    +
    + +

    Example 2:

    + +

    + +
    +Input: radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
    +Output: true
    +
    + +

    Example 3:

    + +

    + +
    +Input: radius = 1, x_center = 1, y_center = 1, x1 = -3, y1 = -3, x2 = 3, y2 = 3
    +Output: true
    +
    + +

    Example 4:

    + +
    +Input: radius = 1, x_center = 1, y_center = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= radius <= 2000
    • +
    • -10^4 <= x_center, y_center, x1, y1, x2, y2 <= 10^4
    • +
    • x1 < x2
    • +
    • y1 < y2
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_2_1728.png b/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_2_1728.png new file mode 100644 index 00000000..bf1596a4 Binary files /dev/null and b/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_2_1728.png differ diff --git a/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_4_1728.png b/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_4_1728.png new file mode 100644 index 00000000..dfec092f Binary files /dev/null and b/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_4_1728.png differ diff --git a/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_6_1728.png b/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_6_1728.png new file mode 100644 index 00000000..2826adf7 Binary files /dev/null and b/assets/1400-1499/1401.Circle and Rectangle Overlapping/images/sample_6_1728.png differ diff --git a/assets/1400-1499/1402.Reducing Dishes/README_EN.md b/assets/1400-1499/1402.Reducing Dishes/README_EN.md new file mode 100644 index 00000000..0b6664ab --- /dev/null +++ b/assets/1400-1499/1402.Reducing Dishes/README_EN.md @@ -0,0 +1,119 @@ +# [1402. Reducing Dishes](https://leetcode.com/problems/reducing-dishes) + + + +## Description + +

    A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.

    + + + +

    Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level  i.e.  time[i]*satisfaction[i]

    + + + +

    Return the maximum sum of Like-time coefficient that the chef can obtain after dishes preparation.

    + + + +

    Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: satisfaction = [-1,-8,0,5,-9]
    +
    +Output: 14
    +
    +Explanation: After Removing the second and last dish, the maximum total Like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14). Each dish is prepared in one unit of time.
    + + + +

    Example 2:

    + + + +
    +
    +Input: satisfaction = [4,3,2]
    +
    +Output: 20
    +
    +Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: satisfaction = [-1,-4,-5]
    +
    +Output: 0
    +
    +Explanation: People don't like the dishes. No dish is prepared.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: satisfaction = [-2,5,-1,0,3,-3]
    +
    +Output: 35
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == satisfaction.length
    • +
    • 1 <= n <= 500
    • +
    • -10^3 <= satisfaction[i] <= 10^3
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md b/assets/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md new file mode 100644 index 00000000..cce9d07e --- /dev/null +++ b/assets/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md @@ -0,0 +1,100 @@ +# [1403. Minimum Subsequence in Non-Increasing Order](https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order) + + + +## Description + +

    Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. 

    + + + +

    If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. 

    + + + +

    Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [4,3,10,9,8]
    +
    +Output: [10,9] 
    +
    +Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements. 
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [4,4,7,6,7]
    +
    +Output: [7,7,6] 
    +
    +Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to returned in non-decreasing order.  
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [6]
    +
    +Output: [6]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 500
    • +
    • 1 <= nums[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md b/assets/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md new file mode 100644 index 00000000..9144c982 --- /dev/null +++ b/assets/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md @@ -0,0 +1,83 @@ +# [1404. Number of Steps to Reduce a Number in Binary Representation to One](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one) + + + +## Description + +

    Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules:

    + +
      +
    • +

      If the current number is even, you have to divide it by 2.

      +
    • +
    • +

      If the current number is odd, you have to add 1 to it.

      +
    • +
    + +

    It's guaranteed that you can always reach to one for all testcases.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "1101"
    +Output: 6
    +Explanation: "1101" corressponds to number 13 in their decimal representation.
    +Step 1) 13 is odd, add 1 and obtain 14. 
    +Step 2) 14 is even, divide by 2 and obtain 7.
    +Step 3) 7 is odd, add 1 and obtain 8.
    +Step 4) 8 is even, divide by 2 and obtain 4.  
    +Step 5) 4 is even, divide by 2 and obtain 2. 
    +Step 6) 2 is even, divide by 2 and obtain 1.  
    +
    + +

    Example 2:

    + +
    +Input: s = "10"
    +Output: 1
    +Explanation: "10" corressponds to number 2 in their decimal representation.
    +Step 1) 2 is even, divide by 2 and obtain 1.  
    +
    + +

    Example 3:

    + +
    +Input: s = "1"
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s consists of characters '0' or '1'
    • +
    • s[0] == '1'
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1405.Longest Happy String/README_EN.md b/assets/1400-1499/1405.Longest Happy String/README_EN.md new file mode 100644 index 00000000..61bc72d8 --- /dev/null +++ b/assets/1400-1499/1405.Longest Happy String/README_EN.md @@ -0,0 +1,74 @@ +# [1405. Longest Happy String](https://leetcode.com/problems/longest-happy-string) + + + +## Description + +

    A string is called happy if it does not have any of the strings 'aaa', 'bbb' or 'ccc' as a substring.

    + +

    Given three integers a, b and c, return any string s, which satisfies following conditions:

    + +
      +
    • s is happy and longest possible.
    • +
    • s contains at most a occurrences of the letter 'a', at most b occurrences of the letter 'b' and at most c occurrences of the letter 'c'.
    • +
    • will only contain 'a', 'b' and 'c' letters.
    • +
    + +

    If there is no such string s return the empty string "".

    + +

     

    +

    Example 1:

    + +
    +Input: a = 1, b = 1, c = 7
    +Output: "ccaccbcc"
    +Explanation: "ccbccacc" would also be a correct answer.
    +
    + +

    Example 2:

    + +
    +Input: a = 2, b = 2, c = 1
    +Output: "aabbc"
    +
    + +

    Example 3:

    + +
    +Input: a = 7, b = 1, c = 0
    +Output: "aabaa"
    +Explanation: It's the only correct answer in this case.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= a, b, c <= 100
    • +
    • a + b + c > 0
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1406.Stone Game III/README_EN.md b/assets/1400-1499/1406.Stone Game III/README_EN.md new file mode 100644 index 00000000..8cd58088 --- /dev/null +++ b/assets/1400-1499/1406.Stone Game III/README_EN.md @@ -0,0 +1,148 @@ +# [1406. Stone Game III](https://leetcode.com/problems/stone-game-iii) + + + +## Description + +

    Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

    + + + +

    Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row.

    + + + +

    The score of each player is the sum of values of the stones taken. The score of each player is 0 initially.

    + + + +

    The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.

    + + + +

    Assume Alice and Bob play optimally.

    + + + +

    Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: values = [1,2,3,7]
    +
    +Output: "Bob"
    +
    +Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: values = [1,2,3,-9]
    +
    +Output: "Alice"
    +
    +Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.
    +
    +If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose.
    +
    +If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose.
    +
    +Remember that both play optimally so here Alice will choose the scenario that makes her win.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: values = [1,2,3,6]
    +
    +Output: "Tie"
    +
    +Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: values = [1,2,3,-1,-2,-3,7]
    +
    +Output: "Alice"
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: values = [-1,-2,-3]
    +
    +Output: "Tie"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= values.length <= 50000
    • +
    • -1000 <= values[i] <= 1000
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1407.Top Travellers/README_EN.md b/assets/1400-1499/1407.Top Travellers/README_EN.md new file mode 100644 index 00000000..a164ed64 --- /dev/null +++ b/assets/1400-1499/1407.Top Travellers/README_EN.md @@ -0,0 +1,103 @@ +# [1407. Top Travellers](https://leetcode.com/problems/top-travellers) + + + +## Description + +

    Table: Users

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id is the primary key for this table.
    +name is the name of the user.
    +
    + +

     

    + +

    Table: Rides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| user_id       | int     |
    +| distance      | int     |
    ++---------------+---------+
    +id is the primary key for this table.
    +user_id is the id of the user who travelled the distance "distance".
    +
    + +

     

    + +

    Write an SQL query to report the distance travelled by each user.

    + +

    Return the result table ordered by travelled_distance in descending order, if two or more users travelled the same distance, order them by their name in ascending order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Users table:
    ++------+-----------+
    +| id   | name      |
    ++------+-----------+
    +| 1    | Alice     |
    +| 2    | Bob       |
    +| 3    | Alex      |
    +| 4    | Donald    |
    +| 7    | Lee       |
    +| 13   | Jonathan  |
    +| 19   | Elvis     |
    ++------+-----------+
    +
    +Rides table:
    ++------+----------+----------+
    +| id   | user_id  | distance |
    ++------+----------+----------+
    +| 1    | 1        | 120      |
    +| 2    | 2        | 317      |
    +| 3    | 3        | 222      |
    +| 4    | 7        | 100      |
    +| 5    | 13       | 312      |
    +| 6    | 19       | 50       |
    +| 7    | 7        | 120      |
    +| 8    | 19       | 400      |
    +| 9    | 7        | 230      |
    ++------+----------+----------+
    +
    +Result table:
    ++----------+--------------------+
    +| name     | travelled_distance |
    ++----------+--------------------+
    +| Elvis    | 450                |
    +| Lee      | 450                |
    +| Bob      | 317                |
    +| Jonathan | 312                |
    +| Alex     | 222                |
    +| Alice    | 120                |
    +| Donald   | 0                  |
    ++----------+--------------------+
    +Elvis and Lee travelled 450 miles, Elvis is the top traveller as his name is alphabetically smaller than Lee.
    +Bob, Jonathan, Alex and Alice have only one ride and we just order them by the total distances of the ride.
    +Donald didn't have any rides, the distance travelled by him is 0.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1408.String Matching in an Array/README_EN.md b/assets/1400-1499/1408.String Matching in an Array/README_EN.md new file mode 100644 index 00000000..818595e7 --- /dev/null +++ b/assets/1400-1499/1408.String Matching in an Array/README_EN.md @@ -0,0 +1,100 @@ +# [1408. String Matching in an Array](https://leetcode.com/problems/string-matching-in-an-array) + + + +## Description + +

    Given an array of string words. Return all strings in words which is substring of another word in any order. 

    + + + +

    String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: words = ["mass","as","hero","superhero"]
    +
    +Output: ["as","hero"]
    +
    +Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
    +
    +["hero","as"] is also a valid answer.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: words = ["leetcode","et","code"]
    +
    +Output: ["et","code"]
    +
    +Explanation: "et", "code" are substring of "leetcode".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: words = ["blue","green","bu"]
    +
    +Output: []
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= words.length <= 100
    • +
    • 1 <= words[i].length <= 30
    • +
    • words[i] contains only lowercase English letters.
    • +
    • It's guaranteed that words[i] will be unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1409.Queries on a Permutation With Key/README_EN.md b/assets/1400-1499/1409.Queries on a Permutation With Key/README_EN.md new file mode 100644 index 00000000..4435e04a --- /dev/null +++ b/assets/1400-1499/1409.Queries on a Permutation With Key/README_EN.md @@ -0,0 +1,112 @@ +# [1409. Queries on a Permutation With Key](https://leetcode.com/problems/queries-on-a-permutation-with-key) + + + +## Description + +

    Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:

    + + + +
      +
    • In the beginning, you have the permutation P=[1,2,3,...,m].
    • +
    • For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].
    • +
    + + + +

    Return an array containing the result for the given queries.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: queries = [3,1,2,1], m = 5
    +
    +Output: [2,1,2,1] 
    +
    +Explanation: The queries are processed as follow: 
    +
    +For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. 
    +
    +For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. 
    +
    +For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. 
    +
    +For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. 
    +
    +Therefore, the array containing the result is [2,1,2,1].  
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: queries = [4,1,2,2], m = 4
    +
    +Output: [3,1,2,0]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: queries = [7,5,5,8,3], m = 8
    +
    +Output: [6,5,0,7,5]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= m <= 10^3
    • +
    • 1 <= queries.length <= m
    • +
    • 1 <= queries[i] <= m
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1410.HTML Entity Parser/README_EN.md b/assets/1400-1499/1410.HTML Entity Parser/README_EN.md new file mode 100644 index 00000000..ca9b98e3 --- /dev/null +++ b/assets/1400-1499/1410.HTML Entity Parser/README_EN.md @@ -0,0 +1,92 @@ +# [1410. HTML Entity Parser](https://leetcode.com/problems/html-entity-parser) + + + +## Description + +

    HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.

    + +

    The special characters and their entities for HTML are:

    + +
      +
    • Quotation Mark: the entity is &quot; and symbol character is ".
    • +
    • Single Quote Mark: the entity is &apos; and symbol character is '.
    • +
    • Ampersand: the entity is &amp; and symbol character is &.
    • +
    • Greater Than Sign: the entity is &gt; and symbol character is >.
    • +
    • Less Than Sign: the entity is &lt; and symbol character is <.
    • +
    • Slash: the entity is &frasl; and symbol character is /.
    • +
    + +

    Given the input text string to the HTML parser, you have to implement the entity parser.

    + +

    Return the text after replacing the entities by the special characters.

    + +

     

    +

    Example 1:

    + +
    +Input: text = "&amp; is an HTML entity but &ambassador; is not."
    +Output: "& is an HTML entity but &ambassador; is not."
    +Explanation: The parser will replace the &amp; entity by &
    +
    + +

    Example 2:

    + +
    +Input: text = "and I quote: &quot;...&quot;"
    +Output: "and I quote: \"...\""
    +
    + +

    Example 3:

    + +
    +Input: text = "Stay home! Practice on Leetcode :)"
    +Output: "Stay home! Practice on Leetcode :)"
    +
    + +

    Example 4:

    + +
    +Input: text = "x &gt; y &amp;&amp; x &lt; y is always false"
    +Output: "x > y && x < y is always false"
    +
    + +

    Example 5:

    + +
    +Input: text = "leetcode.com&frasl;problemset&frasl;all"
    +Output: "leetcode.com/problemset/all"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 10^5
    • +
    • The string may contain any possible characters out of all the 256 ASCII characters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/assets/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" "b/assets/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" new file mode 100644 index 00000000..16081bce --- /dev/null +++ "b/assets/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" @@ -0,0 +1,80 @@ +# [1411. Number of Ways to Paint N × 3 Grid](https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid) + + + +## Description + +

    You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).

    + +

    Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 12
    +Explanation: There are 12 possible way to paint the grid as shown.
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 54
    +
    + +

    Example 3:

    + +
    +Input: n = 3
    +Output: 246
    +
    + +

    Example 4:

    + +
    +Input: n = 7
    +Output: 106494
    +
    + +

    Example 5:

    + +
    +Input: n = 5000
    +Output: 30228214
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • grid[i].length == 3
    • +
    • 1 <= n <= 5000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/assets/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/images/e1.png" "b/assets/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/images/e1.png" new file mode 100644 index 00000000..d80a3d9b Binary files /dev/null and "b/assets/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/images/e1.png" differ diff --git a/assets/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md b/assets/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md new file mode 100644 index 00000000..6d758a68 --- /dev/null +++ b/assets/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md @@ -0,0 +1,100 @@ +# [1412. Find the Quiet Students in All Exams](https://leetcode.com/problems/find-the-quiet-students-in-all-exams) + + + +## Description + +

    Table: Student

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| student_id          | int     |
    +| student_name        | varchar |
    ++---------------------+---------+
    +student_id is the primary key for this table.
    +student_name is the name of the student.
    + +

     

    + +

    Table: Exam

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| exam_id       | int     |
    +| student_id    | int     |
    +| score         | int     |
    ++---------------+---------+
    +(exam_id, student_id) is the primary key for this table.
    +Student with student_id got score points in exam with id exam_id.
    +
    + +

     

    + +

    A "quite" student is the one who took at least one exam and didn't score neither the high score nor the low score.

    + +

    Write an SQL query to report the students (student_id, student_name) being "quiet" in ALL exams.

    + +

    Don't return the student who has never taken any exam. Return the result table ordered by student_id.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Student table:
    ++-------------+---------------+
    +| student_id  | student_name  |
    ++-------------+---------------+
    +| 1           | Daniel        |
    +| 2           | Jade          |
    +| 3           | Stella        |
    +| 4           | Jonathan      |
    +| 5           | Will          |
    ++-------------+---------------+
    +
    +Exam table:
    ++------------+--------------+-----------+
    +| exam_id    | student_id   | score     |
    ++------------+--------------+-----------+
    +| 10         |     1        |    70     |
    +| 10         |     2        |    80     |
    +| 10         |     3        |    90     |
    +| 20         |     1        |    80     |
    +| 30         |     1        |    70     |
    +| 30         |     3        |    80     |
    +| 30         |     4        |    90     |
    +| 40         |     1        |    60     |
    +| 40         |     2        |    70     |
    +| 40         |     4        |    80     |
    ++------------+--------------+-----------+
    +
    +Result table:
    ++-------------+---------------+
    +| student_id  | student_name  |
    ++-------------+---------------+
    +| 2           | Jade          |
    ++-------------+---------------+
    +
    +For exam 1: Student 1 and 3 hold the lowest and high score respectively.
    +For exam 2: Student 1 hold both highest and lowest score.
    +For exam 3 and 4: Studnet 1 and 4 hold the lowest and high score respectively.
    +Student 2 and 5 have never got the highest or lowest in any of the exam.
    +Since student 5 is not taking any exam, he is excluded from the result.
    +So, we only return the information of Student 2.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md b/assets/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md new file mode 100644 index 00000000..5eb0d3eb --- /dev/null +++ b/assets/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md @@ -0,0 +1,114 @@ +# [1413. Minimum Value to Get Positive Step by Step Sum](https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum) + + + +## Description + +

    Given an array of integers nums, you start with an initial positive value startValue.

    + + + +

    In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).

    + + + +

    Return the minimum positive value of startValue such that the step by step sum is never less than 1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [-3,2,-3,4,2]
    +
    +Output: 5
    +
    +Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
    +
    +                step by step sum
    +
    +                startValue = 4 | startValue = 5 | nums
    +
    +                  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3
    +
    +                  (1 +2 ) = 3  | (2 +2 ) = 4    |   2
    +
    +                  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3
    +
    +                  (0 +4 ) = 4  | (1 +4 ) = 5    |   4
    +
    +                  (4 +2 ) = 6  | (5 +2 ) = 7    |   2
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,2]
    +
    +Output: 1
    +
    +Explanation: Minimum start value should be positive. 
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [1,-2,-3]
    +
    +Output: 5
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 100
    • +
    • -100 <= nums[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md b/assets/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md new file mode 100644 index 00000000..15b408c9 --- /dev/null +++ b/assets/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md @@ -0,0 +1,72 @@ +# [1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K](https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k) + + + +## Description + +

    Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.

    + +

    The Fibonacci numbers are defined as:

    + +
      +
    • F1 = 1
    • +
    • F2 = 1
    • +
    • Fn = Fn-1 + Fn-2 for n > 2.
    • +
    +It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k. +

     

    +

    Example 1:

    + +
    +Input: k = 7
    +Output: 2 
    +Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... 
    +For k = 7 we can use 2 + 5 = 7.
    + +

    Example 2:

    + +
    +Input: k = 10
    +Output: 2 
    +Explanation: For k = 10 we can use 2 + 8 = 10.
    +
    + +

    Example 3:

    + +
    +Input: k = 19
    +Output: 3 
    +Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md b/assets/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md new file mode 100644 index 00000000..e2768118 --- /dev/null +++ b/assets/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md @@ -0,0 +1,145 @@ +# [1415. The k-th Lexicographical String of All Happy Strings of Length n](https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n) + + + +## Description + +

    A happy string is a string that:

    + + + +
      +
    • consists only of letters of the set ['a', 'b', 'c'].
    • +
    • s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
    • +
    + + + +

    For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.

    + + + +

    Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.

    + + + +

    Return the kth string of this list or return an empty string if there are less than k happy strings of length n.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 1, k = 3
    +
    +Output: "c"
    +
    +Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 1, k = 4
    +
    +Output: ""
    +
    +Explanation: There are only 3 happy strings of length 1.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 3, k = 9
    +
    +Output: "cab"
    +
    +Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 2, k = 7
    +
    +Output: ""
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 10, k = 100
    +
    +Output: "abacbabacb"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10
    • +
    • 1 <= k <= 100
    • +
    + + + +
     
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1416.Restore The Array/README_EN.md b/assets/1400-1499/1416.Restore The Array/README_EN.md new file mode 100644 index 00000000..5f372d13 --- /dev/null +++ b/assets/1400-1499/1416.Restore The Array/README_EN.md @@ -0,0 +1,137 @@ +# [1416. Restore The Array](https://leetcode.com/problems/restore-the-array) + + + +## Description + +

    A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.

    + + + +

    Given the string s and the integer k. There can be multiple ways to restore the array.

    + + + +

    Return the number of possible array that can be printed as a string s using the mentioned program.

    + + + +

    The number of ways could be very large so return it modulo 10^9 + 7

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "1000", k = 10000
    +
    +Output: 1
    +
    +Explanation: The only possible array is [1000]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "1000", k = 10
    +
    +Output: 0
    +
    +Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "1317", k = 2000
    +
    +Output: 8
    +
    +Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "2020", k = 30
    +
    +Output: 1
    +
    +Explanation: The only possible array is [20,20]. [2020] is invalid because 2020 > 30. [2,020] is ivalid because 020 contains leading zeros.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: s = "1234567890", k = 90
    +
    +Output: 34
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 10^5.
    • +
    • s consists of only digits and doesn't contain leading zeros.
    • +
    • 1 <= k <= 10^9.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1417.Reformat The String/README_EN.md b/assets/1400-1499/1417.Reformat The String/README_EN.md new file mode 100644 index 00000000..fd2b8d93 --- /dev/null +++ b/assets/1400-1499/1417.Reformat The String/README_EN.md @@ -0,0 +1,83 @@ +# [1417. Reformat The String](https://leetcode.com/problems/reformat-the-string) + + + +## Description + +

    Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).

    + +

    You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.

    + +

    Return the reformatted string or return an empty string if it is impossible to reformat the string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "a0b1c2"
    +Output: "0a1b2c"
    +Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
    +
    + +

    Example 2:

    + +
    +Input: s = "leetcode"
    +Output: ""
    +Explanation: "leetcode" has only characters so we cannot separate them by digits.
    +
    + +

    Example 3:

    + +
    +Input: s = "1229857369"
    +Output: ""
    +Explanation: "1229857369" has only digits so we cannot separate them by characters.
    +
    + +

    Example 4:

    + +
    +Input: s = "covid2019"
    +Output: "c2o0v1i9d"
    +
    + +

    Example 5:

    + +
    +Input: s = "ab123"
    +Output: "1a2b3"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s consists of only lowercase English letters and/or digits.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md b/assets/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md new file mode 100644 index 00000000..e14e6df6 --- /dev/null +++ b/assets/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md @@ -0,0 +1,119 @@ +# [1418. Display Table of Food Orders in a Restaurant](https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant) + + + +## Description + +

    Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.

    + + + +

    Return the restaurant's “display table. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
    +
    +Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] 
    +
    +Explanation:
    +
    +The displaying table looks like:
    +
    +Table,Beef Burrito,Ceviche,Fried Chicken,Water
    +
    +3    ,0           ,2      ,1            ,0
    +
    +5    ,0           ,1      ,0            ,1
    +
    +10   ,1           ,0      ,0            ,0
    +
    +For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
    +
    +For the table 5: Carla orders "Water" and "Ceviche".
    +
    +For the table 10: Corina orders "Beef Burrito". 
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
    +
    +Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] 
    +
    +Explanation: 
    +
    +For the table 1: Adam and Brianna order "Canadian Waffles".
    +
    +For the table 12: James, Ratesh and Amadeus order "Fried Chicken".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
    +
    +Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= orders.length <= 5 * 10^4
    • +
    • orders[i].length == 3
    • +
    • 1 <= customerNamei.length, foodItemi.length <= 20
    • +
    • customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.
    • +
    • tableNumberi is a valid integer between 1 and 500.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md b/assets/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md new file mode 100644 index 00000000..759c7a11 --- /dev/null +++ b/assets/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md @@ -0,0 +1,76 @@ +# [1419. Minimum Number of Frogs Croaking](https://leetcode.com/problems/minimum-number-of-frogs-croaking) + + + +## Description + +

    Given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple “croak” are mixed. Return the minimum number of different frogs to finish all the croak in the given string.

    + +

    A valid "croak" means a frog is printing 5 letters ‘c’, ’r’, ’o’, ’a’, ’k’ sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of valid "croak" return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: croakOfFrogs = "croakcroak"
    +Output: 1 
    +Explanation: One frog yelling "croak" twice.
    +
    + +

    Example 2:

    + +
    +Input: croakOfFrogs = "crcoakroak"
    +Output: 2 
    +Explanation: The minimum number of frogs is two. 
    +The first frog could yell "crcoakroak".
    +The second frog could yell later "crcoakroak".
    +
    + +

    Example 3:

    + +
    +Input: croakOfFrogs = "croakcrook"
    +Output: -1
    +Explanation: The given string is an invalid combination of "croak" from different frogs.
    +
    + +

    Example 4:

    + +
    +Input: croakOfFrogs = "croakcroa"
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= croakOfFrogs.length <= 10^5
    • +
    • All characters in the string are: 'c', 'r', 'o', 'a' or 'k'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md b/assets/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md new file mode 100644 index 00000000..d6ab3b76 --- /dev/null +++ b/assets/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md @@ -0,0 +1,141 @@ +# [1420. Build Array Where You Can Find The Maximum Exactly K Comparisons](https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons) + + + +## Description + +

    Given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:

    + + + +

    You should build the array arr which has the following properties:

    + + + +
      +
    • arr has exactly n integers.
    • +
    • 1 <= arr[i] <= m where (0 <= i < n).
    • +
    • After applying the mentioned algorithm to arr, the value search_cost is equal to k.
    • +
    + + + +

    Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 10^9 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 2, m = 3, k = 1
    +
    +Output: 6
    +
    +Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 5, m = 2, k = 3
    +
    +Output: 0
    +
    +Explanation: There are no possible arrays that satisify the mentioned conditions.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 9, m = 1, k = 1
    +
    +Output: 1
    +
    +Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 50, m = 100, k = 25
    +
    +Output: 34549172
    +
    +Explanation: Don't forget to compute the answer modulo 1000000007
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 37, m = 17, k = 7
    +
    +Output: 418930126
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 50
    • +
    • 1 <= m <= 100
    • +
    • 0 <= k <= n
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/images/e.png b/assets/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/images/e.png new file mode 100644 index 00000000..1900e784 Binary files /dev/null and b/assets/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/images/e.png differ diff --git a/assets/1400-1499/1421.NPV Queries/README_EN.md b/assets/1400-1499/1421.NPV Queries/README_EN.md new file mode 100644 index 00000000..bb551def --- /dev/null +++ b/assets/1400-1499/1421.NPV Queries/README_EN.md @@ -0,0 +1,179 @@ +# [1421. NPV Queries](https://leetcode.com/problems/npv-queries) + + + +## Description + +

    Table: NPV

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| id            | int     |
    +
    +| year          | int     |
    +
    +| npv           | int     |
    +
    ++---------------+---------+
    +
    +(id, year) is the primary key of this table.
    +
    +The table has information about the id and the year of each inventory and the corresponding net present value.
    +
    +
    + + + +

     

    + + + +

    Table: Queries

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| id            | int     |
    +
    +| year          | int     |
    +
    ++---------------+---------+
    +
    +(id, year) is the primary key of this table.
    +
    +The table has information about the id and the year of each inventory query.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to find the npv of all each query of queries table.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +
    +
    +NPV table:
    +
    ++------+--------+--------+
    +
    +| id   | year   | npv    |
    +
    ++------+--------+--------+
    +
    +| 1    | 2018   | 100    |
    +
    +| 7    | 2020   | 30     |
    +
    +| 13   | 2019   | 40     |
    +
    +| 1    | 2019   | 113    |
    +
    +| 2    | 2008   | 121    |
    +
    +| 3    | 2009   | 12     |
    +
    +| 11   | 2020   | 99     |
    +
    +| 7    | 2019   | 0      |
    +
    ++------+--------+--------+
    +
    +
    +
    +Queries table:
    +
    ++------+--------+
    +
    +| id   | year   |
    +
    ++------+--------+
    +
    +| 1    | 2019   |
    +
    +| 2    | 2008   |
    +
    +| 3    | 2009   |
    +
    +| 7    | 2018   |
    +
    +| 7    | 2019   |
    +
    +| 7    | 2020   |
    +
    +| 13   | 2019   |
    +
    ++------+--------+
    +
    +
    +
    +Result table:
    +
    ++------+--------+--------+
    +
    +| id   | year   | npv    |
    +
    ++------+--------+--------+
    +
    +| 1    | 2019   | 113    |
    +
    +| 2    | 2008   | 121    |
    +
    +| 3    | 2009   | 12     |
    +
    +| 7    | 2018   | 0      |
    +
    +| 7    | 2019   | 0      |
    +
    +| 7    | 2020   | 30     |
    +
    +| 13   | 2019   | 40     |
    +
    ++------+--------+--------+
    +
    +
    +
    +The npv value of (7, 2018) is not present in the NPV table, we consider it 0.
    +
    +The npv values of all other queries can be found in the NPV table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md b/assets/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md new file mode 100644 index 00000000..b56dd73d --- /dev/null +++ b/assets/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md @@ -0,0 +1,72 @@ +# [1422. Maximum Score After Splitting a String](https://leetcode.com/problems/maximum-score-after-splitting-a-string) + + + +## Description + +

    Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).

    + +

    The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "011101"
    +Output: 5 
    +Explanation: 
    +All possible ways of splitting s into two non-empty substrings are:
    +left = "0" and right = "11101", score = 1 + 4 = 5 
    +left = "01" and right = "1101", score = 1 + 3 = 4 
    +left = "011" and right = "101", score = 1 + 2 = 3 
    +left = "0111" and right = "01", score = 1 + 1 = 2 
    +left = "01110" and right = "1", score = 2 + 1 = 3
    +
    + +

    Example 2:

    + +
    +Input: s = "00111"
    +Output: 5
    +Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
    +
    + +

    Example 3:

    + +
    +Input: s = "1111"
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= s.length <= 500
    • +
    • The string s consists of characters '0' and '1' only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md b/assets/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md new file mode 100644 index 00000000..cbfecaff --- /dev/null +++ b/assets/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md @@ -0,0 +1,87 @@ +# [1423. Maximum Points You Can Obtain from Cards](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards) + + + +## Description + +

    There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints.

    + +

    In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

    + +

    Your score is the sum of the points of the cards you have taken.

    + +

    Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

    + +

     

    +

    Example 1:

    + +
    +Input: cardPoints = [1,2,3,4,5,6,1], k = 3
    +Output: 12
    +Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
    +
    + +

    Example 2:

    + +
    +Input: cardPoints = [2,2,2], k = 2
    +Output: 4
    +Explanation: Regardless of which two cards you take, your score will always be 4.
    +
    + +

    Example 3:

    + +
    +Input: cardPoints = [9,7,7,9,7,7,9], k = 7
    +Output: 55
    +Explanation: You have to take all the cards. Your score is the sum of points of all cards.
    +
    + +

    Example 4:

    + +
    +Input: cardPoints = [1,1000,1], k = 1
    +Output: 1
    +Explanation: You cannot take the card in the middle. Your best score is 1. 
    +
    + +

    Example 5:

    + +
    +Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3
    +Output: 202
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= cardPoints.length <= 10^5
    • +
    • 1 <= cardPoints[i] <= 10^4
    • +
    • 1 <= k <= cardPoints.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1424.Diagonal Traverse II/README_EN.md b/assets/1400-1499/1424.Diagonal Traverse II/README_EN.md new file mode 100644 index 00000000..9293645c --- /dev/null +++ b/assets/1400-1499/1424.Diagonal Traverse II/README_EN.md @@ -0,0 +1,74 @@ +# [1424. Diagonal Traverse II](https://leetcode.com/problems/diagonal-traverse-ii) + + + +## Description + +Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images. +

     

    +

    Example 1:

    + +

    + +
    +Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
    +Output: [1,4,2,7,5,3,8,6,9]
    +
    + +

    Example 2:

    + +

    + +
    +Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
    +Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
    +
    + +

    Example 3:

    + +
    +Input: nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]]
    +Output: [1,4,2,5,3,8,6,9,7,10,11]
    +
    + +

    Example 4:

    + +
    +Input: nums = [[1,2,3,4,5,6]]
    +Output: [1,2,3,4,5,6]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i].length <= 10^5
    • +
    • 1 <= nums[i][j] <= 10^9
    • +
    • There at most 10^5 elements in nums.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1424.Diagonal Traverse II/images/sample_1_1784.png b/assets/1400-1499/1424.Diagonal Traverse II/images/sample_1_1784.png new file mode 100644 index 00000000..d365dcce Binary files /dev/null and b/assets/1400-1499/1424.Diagonal Traverse II/images/sample_1_1784.png differ diff --git a/assets/1400-1499/1424.Diagonal Traverse II/images/sample_2_1784.png b/assets/1400-1499/1424.Diagonal Traverse II/images/sample_2_1784.png new file mode 100644 index 00000000..49fac9d9 Binary files /dev/null and b/assets/1400-1499/1424.Diagonal Traverse II/images/sample_2_1784.png differ diff --git a/assets/1400-1499/1425.Constrained Subsequence Sum/README_EN.md b/assets/1400-1499/1425.Constrained Subsequence Sum/README_EN.md new file mode 100644 index 00000000..a7d1f7ee --- /dev/null +++ b/assets/1400-1499/1425.Constrained Subsequence Sum/README_EN.md @@ -0,0 +1,67 @@ +# [1425. Constrained Subsequence Sum](https://leetcode.com/problems/constrained-subsequence-sum) + + + +## Description + +

    Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.

    + +

    A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [10,2,-10,5,20], k = 2
    +Output: 37
    +Explanation: The subsequence is [10, 2, 5, 20].
    +
    + +

    Example 2:

    + +
    +Input: nums = [-1,-2,-3], k = 1
    +Output: -1
    +Explanation: The subsequence must be non-empty, so we choose the largest number.
    +
    + +

    Example 3:

    + +
    +Input: nums = [10,-2,-10,-5,20], k = 2
    +Output: 23
    +Explanation: The subsequence is [10, -2, -5, 20].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1426.Counting Elements/README_EN.md b/assets/1400-1499/1426.Counting Elements/README_EN.md new file mode 100644 index 00000000..0f2067d7 --- /dev/null +++ b/assets/1400-1499/1426.Counting Elements/README_EN.md @@ -0,0 +1,80 @@ +# [1426. Counting Elements](https://leetcode.com/problems/counting-elements) + + + +## Description + +

    Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr, count them separately.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,3]
    +Output: 2
    +Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
    + +

    Example 2:

    + +
    +Input: arr = [1,1,3,3,5,5,7,7]
    +Output: 0
    +Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,3,2,3,5,0]
    +Output: 3
    +Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
    +
    + +

    Example 4:

    + +
    +Input: arr = [1,1,2,2]
    +Output: 2
    +Explanation: Two 1s are counted cause 2 is in arr.
    +
    + +

    Example 5:

    + +
    +Input: arr = [1,1,2]
    +Output: 2
    +Explanation: Both 1s are counted because 2 is in the array.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 0 <= arr[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1427.Perform String Shifts/README_EN.md b/assets/1400-1499/1427.Perform String Shifts/README_EN.md new file mode 100644 index 00000000..6b17a9d9 --- /dev/null +++ b/assets/1400-1499/1427.Perform String Shifts/README_EN.md @@ -0,0 +1,74 @@ +# [1427. Perform String Shifts](https://leetcode.com/problems/perform-string-shifts) + + + +## Description + +

    You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [directioni, amounti]:

    + +
      +
    • directioni can be 0 (for left shift) or 1 (for right shift).
    • +
    • amounti is the amount by which string s is to be shifted.
    • +
    • A left shift by 1 means remove the first character of s and append it to the end.
    • +
    • Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.
    • +
    + +

    Return the final string after all operations.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abc", shift = [[0,1],[1,2]]
    +Output: "cab"
    +Explanation: 
    +[0,1] means shift to left by 1. "abc" -> "bca"
    +[1,2] means shift to right by 2. "bca" -> "cab"
    + +

    Example 2:

    + +
    +Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
    +Output: "efgabcd"
    +Explanation:  
    +[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
    +[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
    +[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
    +[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s only contains lower case English letters.
    • +
    • 1 <= shift.length <= 100
    • +
    • shift[i].length == 2
    • +
    • directioni is either 0 or 1.
    • +
    • 0 <= amounti <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md b/assets/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md new file mode 100644 index 00000000..e4186c1c --- /dev/null +++ b/assets/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md @@ -0,0 +1,242 @@ +# [1428. Leftmost Column with at Least a One](https://leetcode.com/problems/leftmost-column-with-at-least-a-one) + + + +## Description + +

    (This problem is an interactive problem.)

    + +

    A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.

    + +

    Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.

    + +

    You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:

    + +
      +
    • BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).
    • +
    • BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.
    • +
    + +

    Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

    + +

    For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: mat = [[0,0],[1,1]]
    +Output: 0
    +
    + +

    Example 2:

    + +

    + +
    +Input: mat = [[0,0],[0,1]]
    +Output: 1
    +
    + +

    Example 3:

    + +

    + +
    +Input: mat = [[0,0],[0,0]]
    +Output: -1
    + +

    Example 4:

    + +

    + +
    +Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • rows == mat.length
    • +
    • cols == mat[i].length
    • +
    • 1 <= rows, cols <= 100
    • +
    • mat[i][j] is either 0 or 1.
    • +
    • mat[i] is sorted in non-decreasing order.
    • +
    + + +## Solutions + +Binary search. + + + +### **Python3** + +```python +# """ +# This is BinaryMatrix's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class BinaryMatrix(object): +# def get(self, row: int, col: int) -> int: +# def dimensions(self) -> list[]: + +class Solution: + def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: + rows, cols = binaryMatrix.dimensions() + res = -1 + for row in range(rows): + left, right = 0, cols - 1 + while left < right: + mid = (left + right) >> 1 + if binaryMatrix.get(row, mid) == 1: + right = mid + else: + left = mid + 1 + if binaryMatrix.get(row, left) == 1: + if res == -1: + res = left + else: + res = min(res, left) + return res +``` + +### **Java** + +```java +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * interface BinaryMatrix { + * public int get(int row, int col) {} + * public List dimensions {} + * }; + */ + +class Solution { + public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { + List scale = binaryMatrix.dimensions(); + int rows = scale.get(0), cols = scale.get(1); + int res = -1; + for (int row = 0; row < rows; ++row) { + int left = 0, right = cols - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (binaryMatrix.get(row, mid) == 1) { + right = mid; + } else { + left = mid + 1; + } + } + if (binaryMatrix.get(row, left) == 1) { + if (res == -1) { + res = left; + } else { + res = Math.min(res, left); + } + } + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * class BinaryMatrix { + * public: + * int get(int row, int col); + * vector dimensions(); + * }; + */ + +class Solution { +public: + int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { + vector scale = binaryMatrix.dimensions(); + int rows = scale[0], cols = scale[1]; + int res = -1; + for (int row = 0; row < rows; ++row) { + int left = 0, right = cols - 1; + while (left < right) { + int mid = left + right >> 1; + if (binaryMatrix.get(row, mid) == 1) { + right = mid; + } else { + left = mid + 1; + } + } + if (binaryMatrix.get(row, left) == 1) { + if (res == -1) { + res = left; + } else { + res = min(res, left); + } + } + } + return res; + } +}; +``` + +### **Go** + +```go +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * type BinaryMatrix struct { + * Get func(int, int) int + * Dimensions func() []int + * } + */ + +func leftMostColumnWithOne(binaryMatrix BinaryMatrix) int { + scale := binaryMatrix.Dimensions() + rows, cols := scale[0], scale[1] + res := -1 + for row := 0; row < rows; row++ { + left, right := 0, cols-1 + for left < right { + mid := (left + right) >> 1 + if binaryMatrix.Get(row, mid) == 1 { + right = mid + } else { + left = mid + 1 + } + } + if binaryMatrix.Get(row, left) == 1 { + if res == -1 { + res = left + } else { + res = min(res, left) + } + } + } + return res +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-3.jpg b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-3.jpg new file mode 100644 index 00000000..5de8b6cc Binary files /dev/null and b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-3.jpg differ diff --git a/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-4.jpg b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-4.jpg new file mode 100644 index 00000000..b896f233 Binary files /dev/null and b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-4.jpg differ diff --git a/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-5.jpg b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-5.jpg new file mode 100644 index 00000000..a7bde80b Binary files /dev/null and b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-5.jpg differ diff --git a/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-6.jpg b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-6.jpg new file mode 100644 index 00000000..1a2f9325 Binary files /dev/null and b/assets/1400-1499/1428.Leftmost Column with at Least a One/images/untitled-diagram-6.jpg differ diff --git a/assets/1400-1499/1429.First Unique Number/README_EN.md b/assets/1400-1499/1429.First Unique Number/README_EN.md new file mode 100644 index 00000000..a3288458 --- /dev/null +++ b/assets/1400-1499/1429.First Unique Number/README_EN.md @@ -0,0 +1,169 @@ +# [1429. First Unique Number](https://leetcode.com/problems/first-unique-number) + + + +## Description + +

    You have a queue of integers, you need to retrieve the first unique integer in the queue.

    + +

    Implement the FirstUnique class:

    + +
      +
    • FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
    • +
    • int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer.
    • +
    • void add(int value) insert value to the queue.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: 
    +["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"]
    +[[[2,3,5]],[],[5],[],[2],[],[3],[]]
    +Output: 
    +[null,2,null,2,null,3,null,-1]
    +Explanation: 
    +FirstUnique firstUnique = new FirstUnique([2,3,5]);
    +firstUnique.showFirstUnique(); // return 2
    +firstUnique.add(5);            // the queue is now [2,3,5,5]
    +firstUnique.showFirstUnique(); // return 2
    +firstUnique.add(2);            // the queue is now [2,3,5,5,2]
    +firstUnique.showFirstUnique(); // return 3
    +firstUnique.add(3);            // the queue is now [2,3,5,5,2,3]
    +firstUnique.showFirstUnique(); // return -1
    +
    + +

    Example 2:

    + +
    +Input: 
    +["FirstUnique","showFirstUnique","add","add","add","add","add","showFirstUnique"]
    +[[[7,7,7,7,7,7]],[],[7],[3],[3],[7],[17],[]]
    +Output: 
    +[null,-1,null,null,null,null,null,17]
    +Explanation: 
    +FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]);
    +firstUnique.showFirstUnique(); // return -1
    +firstUnique.add(7);            // the queue is now [7,7,7,7,7,7,7]
    +firstUnique.add(3);            // the queue is now [7,7,7,7,7,7,7,3]
    +firstUnique.add(3);            // the queue is now [7,7,7,7,7,7,7,3,3]
    +firstUnique.add(7);            // the queue is now [7,7,7,7,7,7,7,3,3,7]
    +firstUnique.add(17);           // the queue is now [7,7,7,7,7,7,7,3,3,7,17]
    +firstUnique.showFirstUnique(); // return 17
    +
    + +

    Example 3:

    + +
    +Input: 
    +["FirstUnique","showFirstUnique","add","showFirstUnique"]
    +[[[809]],[],[809],[]]
    +Output: 
    +[null,809,null,-1]
    +Explanation: 
    +FirstUnique firstUnique = new FirstUnique([809]);
    +firstUnique.showFirstUnique(); // return 809
    +firstUnique.add(809);          // the queue is now [809,809]
    +firstUnique.showFirstUnique(); // return -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^8
    • +
    • 1 <= value <= 10^8
    • +
    • At most 50000 calls will be made to showFirstUnique and add.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class FirstUnique: + + def __init__(self, nums: List[int]): + self.counter = collections.OrderedDict() + self.unique_nums = collections.OrderedDict() + for num in nums: + self.counter[num] = self.counter.get(num, 0) + 1 + for k, v in self.counter.items(): + if v == 1: + self.unique_nums[k] = 1 + + def showFirstUnique(self) -> int: + if len(self.unique_nums) == 0: + return -1 + for k in self.unique_nums.keys(): + return k + + def add(self, value: int) -> None: + if value not in self.counter: + self.counter[value] = 1 + self.unique_nums[value] = 1 + else: + self.counter[value] += 1 + if value in self.unique_nums: + self.unique_nums.pop(value) + +# Your FirstUnique object will be instantiated and called as such: +# obj = FirstUnique(nums) +# param_1 = obj.showFirstUnique() +# obj.add(value) +``` + +### **Java** + +```java +class FirstUnique { + private Map counter; + private Set uniqueNums; + + public FirstUnique(int[] nums) { + counter = new LinkedHashMap<>(); + uniqueNums = new LinkedHashSet<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + for (Map.Entry entry : counter.entrySet()) { + if (entry.getValue() == 1) { + uniqueNums.add(entry.getKey()); + } + } + } + + public int showFirstUnique() { + return uniqueNums.isEmpty() ? -1 : uniqueNums.iterator().next(); + } + + public void add(int value) { + if (!counter.containsKey(value)) { + counter.put(value, 1); + uniqueNums.add(value); + } else { + counter.put(value, counter.get(value) + 1); + uniqueNums.remove(value); + } + } +} + +/** + * Your FirstUnique object will be instantiated and called as such: + * FirstUnique obj = new FirstUnique(nums); + * int param_1 = obj.showFirstUnique(); + * obj.add(value); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md new file mode 100644 index 00000000..2b823c7f --- /dev/null +++ b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md @@ -0,0 +1,78 @@ +# [1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree](https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree) + + + +## Description + +

    Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 

    + +

    We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
    +Output: true
    +Explanation: 
    +The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 
    +Other valid sequences are: 
    +0 -> 1 -> 1 -> 0 
    +0 -> 0 -> 0
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
    +Output: false 
    +Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.
    +
    + +

    Example 3:

    + +

    + +
    +Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
    +Output: false
    +Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 5000
    • +
    • 0 <= arr[i] <= 9
    • +
    • Each node's value is between [0 - 9].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_1.png b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_1.png new file mode 100644 index 00000000..abd661ab Binary files /dev/null and b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_1.png differ diff --git a/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_2.png b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_2.png new file mode 100644 index 00000000..c415e80b Binary files /dev/null and b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_2.png differ diff --git a/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_3.png b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_3.png new file mode 100644 index 00000000..3870572d Binary files /dev/null and b/assets/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/images/leetcode_testcase_3.png differ diff --git a/assets/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md b/assets/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md new file mode 100644 index 00000000..4921b6b6 --- /dev/null +++ b/assets/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md @@ -0,0 +1,107 @@ +# [1431. Kids With the Greatest Number of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies) + + + +## Description + +

    Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.

    + + + +

    For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: candies = [2,3,5,1,3], extraCandies = 3
    +
    +Output: [true,true,true,false,true] 
    +
    +Explanation: 
    +
    +Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. 
    +
    +Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 
    +
    +Kid 3 has 5 candies and this is already the greatest number of candies among the kids. 
    +
    +Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. 
    +
    +Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: candies = [4,2,1,1,2], extraCandies = 1
    +
    +Output: [true,false,false,false,false] 
    +
    +Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: candies = [12,1,12], extraCandies = 10
    +
    +Output: [true,false,true]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= candies.length <= 100
    • +
    • 1 <= candies[i] <= 100
    • +
    • 1 <= extraCandies <= 50
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md b/assets/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md new file mode 100644 index 00000000..f3114cfa --- /dev/null +++ b/assets/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md @@ -0,0 +1,92 @@ +# [1432. Max Difference You Can Get From Changing an Integer](https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer) + + + +## Description + +

    You are given an integer num. You will apply the following steps exactly two times:

    + +
      +
    • Pick a digit x (0 <= x <= 9).
    • +
    • Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
    • +
    • Replace all the occurrences of x in the decimal representation of num by y.
    • +
    • The new integer cannot have any leading zeros, also the new integer cannot be 0.
    • +
    + +

    Let a and b be the results of applying the operations to num the first and second times, respectively.

    + +

    Return the max difference between a and b.

    + +

     

    +

    Example 1:

    + +
    +Input: num = 555
    +Output: 888
    +Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
    +The second time pick x = 5 and y = 1 and store the new integer in b.
    +We have now a = 999 and b = 111 and max difference = 888
    +
    + +

    Example 2:

    + +
    +Input: num = 9
    +Output: 8
    +Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
    +The second time pick x = 9 and y = 1 and store the new integer in b.
    +We have now a = 9 and b = 1 and max difference = 8
    +
    + +

    Example 3:

    + +
    +Input: num = 123456
    +Output: 820000
    +
    + +

    Example 4:

    + +
    +Input: num = 10000
    +Output: 80000
    +
    + +

    Example 5:

    + +
    +Input: num = 9288
    +Output: 8700
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= num <= 10^8
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1433.Check If a String Can Break Another String/README_EN.md b/assets/1400-1499/1433.Check If a String Can Break Another String/README_EN.md new file mode 100644 index 00000000..6982a376 --- /dev/null +++ b/assets/1400-1499/1433.Check If a String Can Break Another String/README_EN.md @@ -0,0 +1,68 @@ +# [1433. Check If a String Can Break Another String](https://leetcode.com/problems/check-if-a-string-can-break-another-string) + + + +## Description + +

    Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.

    + +

    A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.

    + +

     

    +

    Example 1:

    + +
    +Input: s1 = "abc", s2 = "xya"
    +Output: true
    +Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".
    +
    + +

    Example 2:

    + +
    +Input: s1 = "abe", s2 = "acd"
    +Output: false 
    +Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
    +
    + +

    Example 3:

    + +
    +Input: s1 = "leetcodee", s2 = "interview"
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • s1.length == n
    • +
    • s2.length == n
    • +
    • 1 <= n <= 10^5
    • +
    • All strings consist of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md b/assets/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md new file mode 100644 index 00000000..3e0e2992 --- /dev/null +++ b/assets/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md @@ -0,0 +1,127 @@ +# [1434. Number of Ways to Wear Different Hats to Each Other](https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other) + + + +## Description + +

    There are n people and 40 types of hats labeled from 1 to 40.

    + + + +

    Given a list of list of integers hats, where hats[i] is a list of all hats preferred by the i-th person.

    + + + +

    Return the number of ways that the n people wear different hats to each other.

    + + + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: hats = [[3,4],[4,5],[5]]
    +
    +Output: 1
    +
    +Explanation: There is only one way to choose hats given the conditions. 
    +
    +First person choose hat 3, Second person choose hat 4 and last one hat 5.
    + + + +

    Example 2:

    + + + +
    +
    +Input: hats = [[3,5,1],[3,5]]
    +
    +Output: 4
    +
    +Explanation: There are 4 ways to choose hats
    +
    +(3,5), (5,3), (1,3) and (1,5)
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
    +
    +Output: 24
    +
    +Explanation: Each person can choose hats labeled from 1 to 4.
    +
    +Number of Permutations of (1,2,3,4) = 24.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: hats = [[1,2,3],[2,3,5,6],[1,3,7,9],[1,8,9],[2,5,7]]
    +
    +Output: 111
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == hats.length
    • +
    • 1 <= n <= 10
    • +
    • 1 <= hats[i].length <= 40
    • +
    • 1 <= hats[i][j] <= 40
    • +
    • hats[i] contains a list of unique integers.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1435.Create a Session Bar Chart/README_EN.md b/assets/1400-1499/1435.Create a Session Bar Chart/README_EN.md new file mode 100644 index 00000000..f3541800 --- /dev/null +++ b/assets/1400-1499/1435.Create a Session Bar Chart/README_EN.md @@ -0,0 +1,67 @@ +# [1435. Create a Session Bar Chart](https://leetcode.com/problems/create-a-session-bar-chart) + + + +## Description + +

    Table: Sessions

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| session_id          | int     |
    +| duration            | int     |
    ++---------------------+---------+
    +session_id is the primary key for this table.
    +duration is the time in seconds that a user has visited the application.
    +
    + +

     

    + +

    You want to know how long a user visits your application. You decided to create bins of "[0-5>", "[5-10>", "[10-15>" and "15 minutes or more" and count the number of sessions on it.

    + +

    Write an SQL query to report the (bin, total) in any order.

    + +

    The query result format is in the following example.

    + +
    +Sessions table:
    ++-------------+---------------+
    +| session_id  | duration      |
    ++-------------+---------------+
    +| 1           | 30            |
    +| 2           | 199           |
    +| 3           | 299           |
    +| 4           | 580           |
    +| 5           | 1000          |
    ++-------------+---------------+
    +
    +Result table:
    ++--------------+--------------+
    +| bin          | total        |
    ++--------------+--------------+
    +| [0-5>        | 3            |
    +| [5-10>       | 1            |
    +| [10-15>      | 0            |
    +| 15 or more   | 1            |
    ++--------------+--------------+
    +
    +For session_id 1, 2 and 3 have a duration greater or equal than 0 minutes and less than 5 minutes.
    +For session_id 4 has a duration greater or equal than 5 minutes and less than 10 minutes.
    +There are no session with a duration greater or equial than 10 minutes and less than 15 minutes.
    +For session_id 5 has a duration greater or equal than 15 minutes.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1436.Destination City/README_EN.md b/assets/1400-1499/1436.Destination City/README_EN.md new file mode 100644 index 00000000..e66def1b --- /dev/null +++ b/assets/1400-1499/1436.Destination City/README_EN.md @@ -0,0 +1,74 @@ +# [1436. Destination City](https://leetcode.com/problems/destination-city) + + + +## Description + +

    You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.

    + +

    It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

    + +

     

    +

    Example 1:

    + +
    +Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
    +Output: "Sao Paulo" 
    +Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".
    +
    + +

    Example 2:

    + +
    +Input: paths = [["B","C"],["D","B"],["C","A"]]
    +Output: "A"
    +Explanation: All possible trips are: 
    +"D" -> "B" -> "C" -> "A". 
    +"B" -> "C" -> "A". 
    +"C" -> "A". 
    +"A". 
    +Clearly the destination city is "A".
    +
    + +

    Example 3:

    + +
    +Input: paths = [["A","Z"]]
    +Output: "Z"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= paths.length <= 100
    • +
    • paths[i].length == 2
    • +
    • 1 <= cityAi.length, cityBi.length <= 10
    • +
    • cityAi != cityBi
    • +
    • All strings consist of lowercase and uppercase English letters and the space character.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md b/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md new file mode 100644 index 00000000..3bfd4749 --- /dev/null +++ b/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md @@ -0,0 +1,75 @@ +# [1437. Check If All 1's Are at Least Length K Places Away](https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away) + + + +## Description + +

    Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: nums = [1,0,0,0,1,0,0,1], k = 2
    +Output: true
    +Explanation: Each of the 1s are at least 2 places away from each other.
    +
    + +

    Example 2:

    + +

    + +
    +Input: nums = [1,0,0,1,0,1], k = 2
    +Output: false
    +Explanation: The second 1 and third 1 are only one apart from each other.
    + +

    Example 3:

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

    Example 4:

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

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 0 <= k <= nums.length
    • +
    • nums[i] is 0 or 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/images/sample_1_1791.png b/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/images/sample_1_1791.png new file mode 100644 index 00000000..cd260f72 Binary files /dev/null and b/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/images/sample_1_1791.png differ diff --git a/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/images/sample_2_1791.png b/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/images/sample_2_1791.png new file mode 100644 index 00000000..df31cee4 Binary files /dev/null and b/assets/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/images/sample_2_1791.png differ diff --git a/assets/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md b/assets/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md new file mode 100644 index 00000000..a5a2bdbc --- /dev/null +++ b/assets/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md @@ -0,0 +1,76 @@ +# [1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit) + + + +## Description + +

    Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [8,2,4,7], limit = 4
    +Output: 2 
    +Explanation: All subarrays are: 
    +[8] with maximum absolute diff |8-8| = 0 <= 4.
    +[8,2] with maximum absolute diff |8-2| = 6 > 4. 
    +[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
    +[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
    +[2] with maximum absolute diff |2-2| = 0 <= 4.
    +[2,4] with maximum absolute diff |2-4| = 2 <= 4.
    +[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
    +[4] with maximum absolute diff |4-4| = 0 <= 4.
    +[4,7] with maximum absolute diff |4-7| = 3 <= 4.
    +[7] with maximum absolute diff |7-7| = 0 <= 4. 
    +Therefore, the size of the longest subarray is 2.
    +
    + +

    Example 2:

    + +
    +Input: nums = [10,1,2,4,7,2], limit = 5
    +Output: 4 
    +Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
    +
    + +

    Example 3:

    + +
    +Input: nums = [4,2,2,2,4,4,2,2], limit = 0
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • 0 <= limit <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md b/assets/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md new file mode 100644 index 00000000..1743f5ef --- /dev/null +++ b/assets/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md @@ -0,0 +1,78 @@ +# [1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows](https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows) + + + +## Description + +

    You are given an m * n matrix, mat, and an integer k, which has its rows sorted in non-decreasing order.

    + +

    You are allowed to choose exactly 1 element from each row to form an array. Return the Kth smallest array sum among all possible arrays.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[1,3,11],[2,4,6]], k = 5
    +Output: 7
    +Explanation: Choosing one element from each row, the first k smallest sum are:
    +[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.  
    + +

    Example 2:

    + +
    +Input: mat = [[1,3,11],[2,4,6]], k = 9
    +Output: 17
    +
    + +

    Example 3:

    + +
    +Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
    +Output: 9
    +Explanation: Choosing one element from each row, the first k smallest sum are:
    +[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.  
    +
    + +

    Example 4:

    + +
    +Input: mat = [[1,1,10],[2,2,9]], k = 7
    +Output: 12
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat.length[i]
    • +
    • 1 <= m, n <= 40
    • +
    • 1 <= k <= min(200, n ^ m)
    • +
    • 1 <= mat[i][j] <= 5000
    • +
    • mat[i] is a non decreasing array.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1440.Evaluate Boolean Expression/README_EN.md b/assets/1400-1499/1440.Evaluate Boolean Expression/README_EN.md new file mode 100644 index 00000000..7395da3c --- /dev/null +++ b/assets/1400-1499/1440.Evaluate Boolean Expression/README_EN.md @@ -0,0 +1,163 @@ +# [1440. Evaluate Boolean Expression](https://leetcode.com/problems/evaluate-boolean-expression) + + + +## Description + +

    Table Variables:

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| name          | varchar |
    +
    +| value         | int     |
    +
    ++---------------+---------+
    +
    +name is the primary key for this table.
    +
    +This table contains the stored variables and their values.
    +
    +
    + + + +

     

    + + + +

    Table Expressions:

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| left_operand  | varchar |
    +
    +| operator      | enum    |
    +
    +| right_operand | varchar |
    +
    ++---------------+---------+
    +
    +(left_operand, operator, right_operand) is the primary key for this table.
    +
    +This table contains a boolean expression that should be evaluated.
    +
    +operator is an enum that takes one of the values ('<', '>', '=')
    +
    +The values of left_operand and right_operand are guaranteed to be in the Variables table.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to evaluate the boolean expressions in Expressions table.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example.

    + + + +
    +
    +Variables table:
    +
    ++------+-------+
    +
    +| name | value |
    +
    ++------+-------+
    +
    +| x    | 66    |
    +
    +| y    | 77    |
    +
    ++------+-------+
    +
    +
    +
    +Expressions table:
    +
    ++--------------+----------+---------------+
    +
    +| left_operand | operator | right_operand |
    +
    ++--------------+----------+---------------+
    +
    +| x            | >        | y             |
    +
    +| x            | <        | y             |
    +
    +| x            | =        | y             |
    +
    +| y            | >        | x             |
    +
    +| y            | <        | x             |
    +
    +| x            | =        | x             |
    +
    ++--------------+----------+---------------+
    +
    +
    +
    +Result table:
    +
    ++--------------+----------+---------------+-------+
    +
    +| left_operand | operator | right_operand | value |
    +
    ++--------------+----------+---------------+-------+
    +
    +| x            | >        | y             | false |
    +
    +| x            | <        | y             | true  |
    +
    +| x            | =        | y             | false |
    +
    +| y            | >        | x             | true  |
    +
    +| y            | <        | x             | false |
    +
    +| x            | =        | x             | true  |
    +
    ++--------------+----------+---------------+-------+
    +
    +As shown, you need find the value of each boolean exprssion in the table using the variables table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1441.Build an Array With Stack Operations/README_EN.md b/assets/1400-1499/1441.Build an Array With Stack Operations/README_EN.md new file mode 100644 index 00000000..e558c968 --- /dev/null +++ b/assets/1400-1499/1441.Build an Array With Stack Operations/README_EN.md @@ -0,0 +1,86 @@ +# [1441. Build an Array With Stack Operations](https://leetcode.com/problems/build-an-array-with-stack-operations) + + + +## Description + +

    Given an array target and an integer n. In each iteration, you will read a number from  list = {1,2,3..., n}.

    + +

    Build the target array using the following operations:

    + +
      +
    • Push: Read a new element from the beginning list, and push it in the array.
    • +
    • Pop: delete the last element of the array.
    • +
    • If the target array is already built, stop reading more elements.
    • +
    + +

    Return the operations to build the target array. You are guaranteed that the answer is unique.

    + +

     

    +

    Example 1:

    + +
    +Input: target = [1,3], n = 3
    +Output: ["Push","Push","Pop","Push"]
    +Explanation: 
    +Read number 1 and automatically push in the array -> [1]
    +Read number 2 and automatically push in the array then Pop it -> [1]
    +Read number 3 and automatically push in the array -> [1,3]
    +
    + +

    Example 2:

    + +
    +Input: target = [1,2,3], n = 3
    +Output: ["Push","Push","Push"]
    +
    + +

    Example 3:

    + +
    +Input: target = [1,2], n = 4
    +Output: ["Push","Push"]
    +Explanation: You only need to read the first 2 numbers and stop.
    +
    + +

    Example 4:

    + +
    +Input: target = [2,3,4], n = 4
    +Output: ["Push","Pop","Push","Push","Push"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= target.length <= 100
    • +
    • 1 <= target[i] <= n
    • +
    • 1 <= n <= 100
    • +
    • target is strictly increasing.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md b/assets/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md new file mode 100644 index 00000000..336cb955 --- /dev/null +++ b/assets/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md @@ -0,0 +1,141 @@ +# [1442. Count Triplets That Can Form Two Arrays of Equal XOR](https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor) + + + +## Description + +

    Given an array of integers arr.

    + + + +

    We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).

    + + + +

    Let's define a and b as follows:

    + + + +
      +
    • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
    • +
    • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
    • +
    + + + +

    Note that ^ denotes the bitwise-xor operation.

    + + + +

    Return the number of triplets (i, j and k) Where a == b.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [2,3,1,6,7]
    +
    +Output: 4
    +
    +Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [1,1,1,1,1]
    +
    +Output: 10
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [2,3]
    +
    +Output: 0
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [1,3,5,7,9]
    +
    +Output: 3
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: arr = [7,11,12,9,5,2,7,17,22]
    +
    +Output: 8
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 300
    • +
    • 1 <= arr[i] <= 10^8
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md b/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md new file mode 100644 index 00000000..515ab8a7 --- /dev/null +++ b/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md @@ -0,0 +1,74 @@ +# [1443. Minimum Time to Collect All Apples in a Tree](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree) + + + +## Description + +

    Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.

    + +

    The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
    +Output: 8 
    +Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
    +Output: 6
    +Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  
    +
    + +

    Example 3:

    + +
    +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • edges.length == n - 1
    • +
    • edges[i].length == 2
    • +
    • 0 <= ai < bi <= n - 1
    • +
    • fromi < toi
    • +
    • hasApple.length == n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/images/min_time_collect_apple_1.png b/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/images/min_time_collect_apple_1.png new file mode 100644 index 00000000..479423b2 Binary files /dev/null and b/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/images/min_time_collect_apple_1.png differ diff --git a/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/images/min_time_collect_apple_2.png b/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/images/min_time_collect_apple_2.png new file mode 100644 index 00000000..a18be698 Binary files /dev/null and b/assets/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/images/min_time_collect_apple_2.png differ diff --git a/assets/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md b/assets/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md new file mode 100644 index 00000000..4c386df2 --- /dev/null +++ b/assets/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md @@ -0,0 +1,105 @@ +# [1444. Number of Ways of Cutting a Pizza](https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza) + + + +## Description + +

    Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts. 

    + + + +

    For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.

    + + + +

    Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: pizza = ["A..","AAA","..."], k = 3
    +
    +Output: 3 
    +
    +Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: pizza = ["A..","AA.","..."], k = 3
    +
    +Output: 1
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: pizza = ["A..","A..","..."], k = 1
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= rows, cols <= 50
    • +
    • rows == pizza.length
    • +
    • cols == pizza[i].length
    • +
    • 1 <= k <= 10
    • +
    • pizza consists of characters 'A' and '.' only.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1444.Number of Ways of Cutting a Pizza/images/ways_to_cut_apple_1.png b/assets/1400-1499/1444.Number of Ways of Cutting a Pizza/images/ways_to_cut_apple_1.png new file mode 100644 index 00000000..36c073d3 Binary files /dev/null and b/assets/1400-1499/1444.Number of Ways of Cutting a Pizza/images/ways_to_cut_apple_1.png differ diff --git a/assets/1400-1499/1445.Apples & Oranges/README_EN.md b/assets/1400-1499/1445.Apples & Oranges/README_EN.md new file mode 100644 index 00000000..0520744c --- /dev/null +++ b/assets/1400-1499/1445.Apples & Oranges/README_EN.md @@ -0,0 +1,82 @@ +# [1445. Apples & Oranges](https://leetcode.com/problems/apples-oranges) + + + +## Description + +

    Table: Sales

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| sale_date     | date    |
    +| fruit         | enum    | 
    +| sold_num      | int     | 
    ++---------------+---------+
    +(sale_date,fruit) is the primary key for this table.
    +This table contains the sales of "apples" and "oranges" sold each day.
    +
    + +

     

    + +

    Write an SQL query to report the difference between number of apples and oranges sold each day.

    + +

    Return the result table ordered by sale_date in format ('YYYY-MM-DD').

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Sales table:
    ++------------+------------+-------------+
    +| sale_date  | fruit      | sold_num    |
    ++------------+------------+-------------+
    +| 2020-05-01 | apples     | 10          |
    +| 2020-05-01 | oranges    | 8           |
    +| 2020-05-02 | apples     | 15          |
    +| 2020-05-02 | oranges    | 15          |
    +| 2020-05-03 | apples     | 20          |
    +| 2020-05-03 | oranges    | 0           |
    +| 2020-05-04 | apples     | 15          |
    +| 2020-05-04 | oranges    | 16          |
    ++------------+------------+-------------+
    +
    +Result table:
    ++------------+--------------+
    +| sale_date  | diff         |
    ++------------+--------------+
    +| 2020-05-01 | 2            |
    +| 2020-05-02 | 0            |
    +| 2020-05-03 | 20           |
    +| 2020-05-04 | -1           |
    ++------------+--------------+
    +
    +Day 2020-05-01, 10 apples and 8 oranges were sold (Difference  10 - 8 = 2).
    +Day 2020-05-02, 15 apples and 15 oranges were sold (Difference 15 - 15 = 0).
    +Day 2020-05-03, 20 apples and 0 oranges were sold (Difference 20 - 0 = 20).
    +Day 2020-05-04, 15 apples and 16 oranges were sold (Difference 15 - 16 = -1).
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + sale_date AS SALE_DATE, + sum( + CASE WHEN fruit = 'oranges' THEN -sold_num ELSE sold_num END + ) AS DIFF +FROM + Sales +GROUP BY sale_date +ORDER BY sale_date; +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1446.Consecutive Characters/README_EN.md b/assets/1400-1499/1446.Consecutive Characters/README_EN.md new file mode 100644 index 00000000..64125230 --- /dev/null +++ b/assets/1400-1499/1446.Consecutive Characters/README_EN.md @@ -0,0 +1,124 @@ +# [1446. Consecutive Characters](https://leetcode.com/problems/consecutive-characters) + + + +## Description + +

    Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.

    + + + +

    Return the power of the string.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "leetcode"
    +
    +Output: 2
    +
    +Explanation: The substring "ee" is of length 2 with the character 'e' only.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "abbcccddddeeeeedcba"
    +
    +Output: 5
    +
    +Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "triplepillooooow"
    +
    +Output: 5
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "hooraaaaaaaaaaay"
    +
    +Output: 11
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: s = "tourist"
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 500
    • +
    • s contains only lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1447.Simplified Fractions/README_EN.md b/assets/1400-1499/1447.Simplified Fractions/README_EN.md new file mode 100644 index 00000000..f75e34a2 --- /dev/null +++ b/assets/1400-1499/1447.Simplified Fractions/README_EN.md @@ -0,0 +1,101 @@ +# [1447. Simplified Fractions](https://leetcode.com/problems/simplified-fractions) + + + +## Description + +

    Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. The fractions can be in any order.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 2
    +
    +Output: ["1/2"]
    +
    +Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 3
    +
    +Output: ["1/2","1/3","2/3"]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 4
    +
    +Output: ["1/2","1/3","1/4","2/3","3/4"]
    +
    +Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2".
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 1
    +
    +Output: []
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md b/assets/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md new file mode 100644 index 00000000..ec79865c --- /dev/null +++ b/assets/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md @@ -0,0 +1,108 @@ +# [1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree) + + + +## Description + +

    Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

    + + + +

    Return the number of good nodes in the binary tree.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: root = [3,1,4,3,null,1,5]
    +
    +Output: 4
    +
    +Explanation: Nodes in blue are good.
    +
    +Root Node (3) is always a good node.
    +
    +Node 4 -> (3,4) is the maximum value in the path starting from the root.
    +
    +Node 5 -> (3,4,5) is the maximum value in the path
    +
    +Node 3 -> (3,1,3) is the maximum value in the path.
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: root = [3,3,null,4,2]
    +
    +Output: 3
    +
    +Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
    + + + +

    Example 3:

    + + + +
    +
    +Input: root = [1]
    +
    +Output: 1
    +
    +Explanation: Root is considered as good.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the binary tree is in the range [1, 10^5].
    • +
    • Each node's value is between [-10^4, 10^4].
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1448.Count Good Nodes in Binary Tree/images/test_sample_1.png b/assets/1400-1499/1448.Count Good Nodes in Binary Tree/images/test_sample_1.png new file mode 100644 index 00000000..f33cb92a Binary files /dev/null and b/assets/1400-1499/1448.Count Good Nodes in Binary Tree/images/test_sample_1.png differ diff --git a/assets/1400-1499/1448.Count Good Nodes in Binary Tree/images/test_sample_2.png b/assets/1400-1499/1448.Count Good Nodes in Binary Tree/images/test_sample_2.png new file mode 100644 index 00000000..e6d5b83b Binary files /dev/null and b/assets/1400-1499/1448.Count Good Nodes in Binary Tree/images/test_sample_2.png differ diff --git a/assets/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md b/assets/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md new file mode 100644 index 00000000..c1e5be3e --- /dev/null +++ b/assets/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md @@ -0,0 +1,93 @@ +# [1449. Form Largest Integer With Digits That Add up to Target](https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target) + + + +## Description + +

    Given an array of integers cost and an integer target. Return the maximum integer you can paint under the following rules:

    + +
      +
    • The cost of painting a digit (i+1) is given by cost[i] (0 indexed).
    • +
    • The total cost used must be equal to target.
    • +
    • Integer does not have digits 0.
    • +
    + +

    Since the answer may be too large, return it as string.

    + +

    If there is no way to paint any integer given the condition, return "0".

    + +

     

    +

    Example 1:

    + +
    +Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
    +Output: "7772"
    +Explanation:  The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
    +Digit    cost
    +  1  ->   4
    +  2  ->   3
    +  3  ->   2
    +  4  ->   5
    +  5  ->   6
    +  6  ->   7
    +  7  ->   2
    +  8  ->   5
    +  9  ->   5
    +
    + +

    Example 2:

    + +
    +Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
    +Output: "85"
    +Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.
    +
    + +

    Example 3:

    + +
    +Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
    +Output: "0"
    +Explanation: It's not possible to paint any integer with total cost equal to target.
    +
    + +

    Example 4:

    + +
    +Input: cost = [6,10,15,40,40,40,40,40,40], target = 47
    +Output: "32211"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • cost.length == 9
    • +
    • 1 <= cost[i] <= 5000
    • +
    • 1 <= target <= 5000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md b/assets/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md new file mode 100644 index 00000000..2cc22fe0 --- /dev/null +++ b/assets/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md @@ -0,0 +1,87 @@ +# [1450. Number of Students Doing Homework at a Given Time](https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time) + + + +## Description + +

    Given two integer arrays startTime and endTime and given an integer queryTime.

    + +

    The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].

    + +

    Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.

    + +

     

    +

    Example 1:

    + +
    +Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
    +Output: 1
    +Explanation: We have 3 students where:
    +The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
    +The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
    +The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
    +
    + +

    Example 2:

    + +
    +Input: startTime = [4], endTime = [4], queryTime = 4
    +Output: 1
    +Explanation: The only student was doing their homework at the queryTime.
    +
    + +

    Example 3:

    + +
    +Input: startTime = [4], endTime = [4], queryTime = 5
    +Output: 0
    +
    + +

    Example 4:

    + +
    +Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
    +Output: 0
    +
    + +

    Example 5:

    + +
    +Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • startTime.length == endTime.length
    • +
    • 1 <= startTime.length <= 100
    • +
    • 1 <= startTime[i] <= endTime[i] <= 1000
    • +
    • 1 <= queryTime <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md b/assets/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md new file mode 100644 index 00000000..f97975cb --- /dev/null +++ b/assets/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md @@ -0,0 +1,79 @@ +# [1451. Rearrange Words in a Sentence](https://leetcode.com/problems/rearrange-words-in-a-sentence) + + + +## Description + +

    Given a sentence text (A sentence is a string of space-separated words) in the following format:

    + +
      +
    • First letter is in upper case.
    • +
    • Each word in text are separated by a single space.
    • +
    + +

    Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

    + +

    Return the new text following the format shown above.

    + +

     

    +

    Example 1:

    + +
    +Input: text = "Leetcode is cool"
    +Output: "Is cool leetcode"
    +Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
    +Output is ordered by length and the new first word starts with capital letter.
    +
    + +

    Example 2:

    + +
    +Input: text = "Keep calm and code on"
    +Output: "On and keep calm code"
    +Explanation: Output is ordered as follows:
    +"On" 2 letters.
    +"and" 3 letters.
    +"keep" 4 letters in case of tie order by position in original text.
    +"calm" 4 letters.
    +"code" 4 letters.
    +
    + +

    Example 3:

    + +
    +Input: text = "To be or not to be"
    +Output: "To be or to be not"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • text begins with a capital letter and then contains lowercase letters and single space between words.
    • +
    • 1 <= text.length <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md b/assets/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md new file mode 100644 index 00000000..a97af819 --- /dev/null +++ b/assets/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md @@ -0,0 +1,73 @@ +# [1452. People Whose List of Favorite Companies Is Not a Subset of Another List](https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list) + + + +## Description + +

    Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).

    + +

    Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.

    + +

     

    +

    Example 1:

    + +
    +Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
    +Output: [0,1,4] 
    +Explanation: 
    +Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0. 
    +Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"]. 
    +Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
    +
    + +

    Example 2:

    + +
    +Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
    +Output: [0,1] 
    +Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
    +
    + +

    Example 3:

    + +
    +Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
    +Output: [0,1,2,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= favoriteCompanies.length <= 100
    • +
    • 1 <= favoriteCompanies[i].length <= 500
    • +
    • 1 <= favoriteCompanies[i][j].length <= 20
    • +
    • All strings in favoriteCompanies[i] are distinct.
    • +
    • All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
    • +
    • All strings consist of lowercase English letters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md b/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md new file mode 100644 index 00000000..e78e8184 --- /dev/null +++ b/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md @@ -0,0 +1,120 @@ +# [1453. Maximum Number of Darts Inside of a Circular Dartboard](https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard) + + + +## Description + +

    You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of points on a 2D plane. 

    + + + +

    Return the maximum number of points that are within or lie on any circular dartboard of radius r.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
    +
    +Output: 4
    +
    +Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
    +
    +Output: 5
    +
    +Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1
    +
    +Output: 1
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2
    +
    +Output: 4
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= points.length <= 100
    • +
    • points[i].length == 2
    • +
    • -10^4 <= points[i][0], points[i][1] <= 10^4
    • +
    • 1 <= r <= 5000
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/images/sample_1_1806.png b/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/images/sample_1_1806.png new file mode 100644 index 00000000..de0893ea Binary files /dev/null and b/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/images/sample_1_1806.png differ diff --git a/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/images/sample_2_1806.png b/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/images/sample_2_1806.png new file mode 100644 index 00000000..bc1e678e Binary files /dev/null and b/assets/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/images/sample_2_1806.png differ diff --git a/assets/1400-1499/1454.Active Users/README_EN.md b/assets/1400-1499/1454.Active Users/README_EN.md new file mode 100644 index 00000000..fee76ea6 --- /dev/null +++ b/assets/1400-1499/1454.Active Users/README_EN.md @@ -0,0 +1,93 @@ +# [1454. Active Users](https://leetcode.com/problems/active-users) + + + +## Description + +

    Table Accounts:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +the id is the primary key for this table.
    +This table contains the account id and the user name of each account.
    +
    + +

     

    + +

    Table Logins:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| login_date    | date    |
    ++---------------+---------+
    +There is no primary key for this table, it may contain duplicates.
    +This table contains the account id of the user who logged in and the login date. A user may log in multiple times in the day.
    +
    + +

     

    + +

    Write an SQL query to find the id and the name of active users.

    + +

    Active users are those who logged in to their accounts for 5 or more consecutive days.

    + +

    Return the result table ordered by the id.

    + +

    The query result format is in the following example:

    + +
    +Accounts table:
    ++----+----------+
    +| id | name     |
    ++----+----------+
    +| 1  | Winston  |
    +| 7  | Jonathan |
    ++----+----------+
    +
    +Logins table:
    ++----+------------+
    +| id | login_date |
    ++----+------------+
    +| 7  | 2020-05-30 |
    +| 1  | 2020-05-30 |
    +| 7  | 2020-05-31 |
    +| 7  | 2020-06-01 |
    +| 7  | 2020-06-02 |
    +| 7  | 2020-06-02 |
    +| 7  | 2020-06-03 |
    +| 1  | 2020-06-07 |
    +| 7  | 2020-06-10 |
    ++----+------------+
    +
    +Result table:
    ++----+----------+
    +| id | name     |
    ++----+----------+
    +| 7  | Jonathan |
    ++----+----------+
    +User Winston with id = 1 logged in 2 times only in 2 different days, so, Winston is not an active user.
    +User Jonathan with id = 7 logged in 7 times in 6 different days, five of them were consecutive days, so, Jonathan is an active user.
    +
    + +

    Follow up question:
    +Can you write a general solution if the active users are those who logged in to their accounts for n or more consecutive days?

    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md b/assets/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md new file mode 100644 index 00000000..dc7cc376 --- /dev/null +++ b/assets/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md @@ -0,0 +1,109 @@ +# [1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) + + + +## Description + +

    Given a sentence that consists of some words separated by a single space, and a searchWord.

    + +

    You have to check if searchWord is a prefix of any word in sentence.

    + +

    Return the index of the word in sentence where searchWord is a prefix of this word (1-indexed).

    + +

    If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.

    + +

    A prefix of a string S is any leading contiguous substring of S.

    + +

     

    +

    Example 1:

    + +
    +Input: sentence = "i love eating burger", searchWord = "burg"
    +Output: 4
    +Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
    +
    + +

    Example 2:

    + +
    +Input: sentence = "this problem is an easy problem", searchWord = "pro"
    +Output: 2
    +Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
    +
    + +

    Example 3:

    + +
    +Input: sentence = "i am tired", searchWord = "you"
    +Output: -1
    +Explanation: "you" is not a prefix of any word in the sentence.
    +
    + +

    Example 4:

    + +
    +Input: sentence = "i use triple pillow", searchWord = "pill"
    +Output: 4
    +
    + +

    Example 5:

    + +
    +Input: sentence = "hello from the other side", searchWord = "they"
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= sentence.length <= 100
    • +
    • 1 <= searchWord.length <= 10
    • +
    • sentence consists of lowercase English letters and spaces.
    • +
    • searchWord consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: + words = sentence.split(' ') + i, n = 0, len(words) + while i < n: + word = words[i] + if word[: len(searchWord)] == searchWord: + return i + 1 + i += 1 + return -1 +``` + +### **Java** + +```java +class Solution { + public int isPrefixOfWord(String sentence, String searchWord) { + String[] words = sentence.split(" "); + int i = 0, n = words.length; + for (; i < n; ++i) { + if (words[i].indexOf(searchWord) == 0) { + return i + 1; + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md b/assets/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md new file mode 100644 index 00000000..0b8b497d --- /dev/null +++ b/assets/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md @@ -0,0 +1,133 @@ +# [1456. Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length) + + + +## Description + +

    Given a string s and an integer k.

    + + + +

    Return the maximum number of vowel letters in any substring of s with length k.

    + + + +

    Vowel letters in English are (a, e, i, o, u).

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "abciiidef", k = 3
    +
    +Output: 3
    +
    +Explanation: The substring "iii" contains 3 vowel letters.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "aeiou", k = 2
    +
    +Output: 2
    +
    +Explanation: Any substring of length 2 contains 2 vowels.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "leetcode", k = 3
    +
    +Output: 2
    +
    +Explanation: "lee", "eet" and "ode" contain 2 vowels.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "rhythms", k = 4
    +
    +Output: 0
    +
    +Explanation: We can see that s doesn't have any vowel letters.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: s = "tryhard", k = 4
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s consists of lowercase English letters.
    • +
    • 1 <= k <= s.length
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md new file mode 100644 index 00000000..aa4060a8 --- /dev/null +++ b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md @@ -0,0 +1,70 @@ +# [1457. Pseudo-Palindromic Paths in a Binary Tree](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree) + + + +## Description + +

    Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.

    + +

    Return the number of pseudo-palindromic paths going from the root node to leaf nodes.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [2,3,1,3,1,null,1]
    +Output: 2 
    +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [2,1,1,1,3,null,null,null,null,null,1]
    +Output: 1 
    +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
    +
    + +

    Example 3:

    + +
    +Input: root = [9]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 105].
    • +
    • 1 <= Node.val <= 9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/graph-1.png b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/graph-1.png new file mode 100644 index 00000000..139ad8f9 Binary files /dev/null and b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/graph-1.png differ diff --git a/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/graph.png b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/graph.png new file mode 100644 index 00000000..2cfb0ea2 Binary files /dev/null and b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/graph.png differ diff --git a/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/palindromic_paths_1.png b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/palindromic_paths_1.png new file mode 100644 index 00000000..04ace778 Binary files /dev/null and b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/palindromic_paths_1.png differ diff --git a/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/palindromic_paths_2.png b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/palindromic_paths_2.png new file mode 100644 index 00000000..920102d6 Binary files /dev/null and b/assets/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/images/palindromic_paths_2.png differ diff --git a/assets/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md b/assets/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md new file mode 100644 index 00000000..d2299d79 --- /dev/null +++ b/assets/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md @@ -0,0 +1,69 @@ +# [1458. Max Dot Product of Two Subsequences](https://leetcode.com/problems/max-dot-product-of-two-subsequences) + + + +## Description + +

    Given two arrays nums1 and nums2.

    + +

    Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.

    + +

    A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
    +Output: 18
    +Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
    +Their dot product is (2*3 + (-2)*(-6)) = 18.
    + +

    Example 2:

    + +
    +Input: nums1 = [3,-2], nums2 = [2,-6,7]
    +Output: 21
    +Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
    +Their dot product is (3*7) = 21.
    + +

    Example 3:

    + +
    +Input: nums1 = [-1,-1], nums2 = [1,1]
    +Output: -1
    +Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
    +Their dot product is -1.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 500
    • +
    • -1000 <= nums1[i], nums2[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1458.Max Dot Product of Two Subsequences/images/c329bf86e747d74f55ed2e17c36fd83f.png b/assets/1400-1499/1458.Max Dot Product of Two Subsequences/images/c329bf86e747d74f55ed2e17c36fd83f.png new file mode 100644 index 00000000..f58471e7 Binary files /dev/null and b/assets/1400-1499/1458.Max Dot Product of Two Subsequences/images/c329bf86e747d74f55ed2e17c36fd83f.png differ diff --git a/assets/1400-1499/1459.Rectangles Area/README_EN.md b/assets/1400-1499/1459.Rectangles Area/README_EN.md new file mode 100644 index 00000000..b557fe07 --- /dev/null +++ b/assets/1400-1499/1459.Rectangles Area/README_EN.md @@ -0,0 +1,72 @@ +# [1459. Rectangles Area](https://leetcode.com/problems/rectangles-area) + + + +## Description + +

    Table: Points

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| x_value       | int     |
    +| y_value       | int     |
    ++---------------+---------+
    +id is the primary key for this table.
    +Each point is represented as a 2D coordinate (x_value, y_value).
    + +

     

    + +

    Write an SQL query to report all possible axis-aligned rectangles with non-zero area that can be formed by any two points in the Points table.

    + +

    Each row in the result should contain three columns (p1, p2, area) where:

    + +
      +
    • p1 and p2 are the id's of the two points that determine the opposite corners of a rectangle.
    • +
    • area is the area of the rectangle and must be non-zero.
    • +
    + +

    Report the query in descending order by area first, then in ascending order by p1's id if there is a tie, then in ascending order by p2's id if there is another tie.

    + +

    The query result format is in the following table:

    + +

     

    + +
    +Points table:
    ++----------+-------------+-------------+
    +| id       | x_value     | y_value     |
    ++----------+-------------+-------------+
    +| 1        | 2           | 7           |
    +| 2        | 4           | 8           |
    +| 3        | 2           | 10          |
    ++----------+-------------+-------------+
    +
    +Result table:
    ++----------+-------------+-------------+
    +| p1       | p2          | area        |
    ++----------+-------------+-------------+
    +| 2        | 3           | 4           |
    +| 1        | 2           | 2           |
    ++----------+-------------+-------------+
    +
    +
    +The rectangle formed by p1 = 2 and p2 = 3 has an area equal to |4-2| * |8-10| = 4.
    +The rectangle formed by p1 = 1 and p2 = 2 has an area equal to |2-4| * |7-8| = 2.
    +Note that the rectangle formed by p1 = 1 and p2 = 3 is invalid because the area is 0.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1459.Rectangles Area/images/rect.png b/assets/1400-1499/1459.Rectangles Area/images/rect.png new file mode 100644 index 00000000..a009e766 Binary files /dev/null and b/assets/1400-1499/1459.Rectangles Area/images/rect.png differ diff --git a/assets/1400-1499/1460.Make Two Arrays Equal by Reversing Sub-arrays/README_EN.md b/assets/1400-1499/1460.Make Two Arrays Equal by Reversing Sub-arrays/README_EN.md new file mode 100644 index 00000000..056b0c50 --- /dev/null +++ b/assets/1400-1499/1460.Make Two Arrays Equal by Reversing Sub-arrays/README_EN.md @@ -0,0 +1,97 @@ +# [1460. Make Two Arrays Equal by Reversing Sub-arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays) + + + +## Description + +

    Given two integer arrays of equal length target and arr.

    + +

    In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps.

    + +

    Return True if you can make arr equal to target, or False otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: target = [1,2,3,4], arr = [2,4,1,3]
    +Output: true
    +Explanation: You can follow the next steps to convert arr to target:
    +1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
    +2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
    +3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
    +There are multiple ways to convert arr to target, this is not the only way to do so.
    +
    + +

    Example 2:

    + +
    +Input: target = [7], arr = [7]
    +Output: true
    +Explanation: arr is equal to target without any reverses.
    +
    + +

    Example 3:

    + +
    +Input: target = [1,12], arr = [12,1]
    +Output: true
    +
    + +

    Example 4:

    + +
    +Input: target = [3,7,9], arr = [3,7,11]
    +Output: false
    +Explanation: arr doesn't have value 9 and it can never be converted to target.
    +
    + +

    Example 5:

    + +
    +Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • target.length == arr.length
    • +
    • 1 <= target.length <= 1000
    • +
    • 1 <= target[i] <= 1000
    • +
    • 1 <= arr[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return sorted(target) == sorted(arr) +``` + +### **Java** + +```java +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + Arrays.sort(target); + Arrays.sort(arr); + return Arrays.equals(target, arr); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md b/assets/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md new file mode 100644 index 00000000..d2d19ba7 --- /dev/null +++ b/assets/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md @@ -0,0 +1,108 @@ +# [1461. Check If a String Contains All Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k) + + + +## Description + +

    Given a binary string s and an integer k.

    + +

    Return true if every binary code of length k is a substring of s. Otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "00110110", k = 2
    +Output: true
    +Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and 2 respectively.
    +
    + +

    Example 2:

    + +
    +Input: s = "00110", k = 2
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: s = "0110", k = 1
    +Output: true
    +Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. 
    +
    + +

    Example 4:

    + +
    +Input: s = "0110", k = 2
    +Output: false
    +Explanation: The binary code "00" is of length 2 and doesn't exist in the array.
    +
    + +

    Example 5:

    + +
    +Input: s = "0000000001011100", k = 4
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 5 * 105
    • +
    • s[i] is either '0' or '1'.
    • +
    • 1 <= k <= 20
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def hasAllCodes(self, s: str, k: int) -> bool: + counter = 1 << k + exists = set() + for i in range(k, len(s) + 1): + if s[i - k: i] not in exists: + exists.add(s[i - k: i]) + counter -= 1 + if counter == 0: + return True + return False +``` + +### **Java** + +```java +class Solution { + public boolean hasAllCodes(String s, int k) { + int counter = 1 << k; + Set exists = new HashSet<>(); + for (int i = k; i <= s.length(); ++i) { + String t = s.substring(i - k, i); + if (!exists.contains(t)) { + exists.add(t); + --counter; + } + if (counter == 0) { + return true; + } + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1462.Course Schedule IV/README_EN.md b/assets/1400-1499/1462.Course Schedule IV/README_EN.md new file mode 100644 index 00000000..fc0dda16 --- /dev/null +++ b/assets/1400-1499/1462.Course Schedule IV/README_EN.md @@ -0,0 +1,94 @@ +# [1462. Course Schedule IV](https://leetcode.com/problems/course-schedule-iv) + + + +## Description + +

    There are a total of n courses you have to take, labeled from 0 to n-1.

    + +

    Some courses may have direct prerequisites, for example, to take course 0 you have first to take course 1, which is expressed as a pair: [1,0]

    + +

    Given the total number of courses n, a list of direct prerequisite pairs and a list of queries pairs.

    + +

    You should answer for each queries[i] whether the course queries[i][0] is a prerequisite of the course queries[i][1] or not.

    + +

    Return a list of boolean, the answers to the given queries.

    + +

    Please note that if course a is a prerequisite of course b and course b is a prerequisite of course c, then, course a is a prerequisite of course c.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
    +Output: [false,true]
    +Explanation: course 0 is not a prerequisite of course 1 but the opposite is true.
    +
    + +

    Example 2:

    + +
    +Input: n = 2, prerequisites = [], queries = [[1,0],[0,1]]
    +Output: [false,false]
    +Explanation: There are no prerequisites and each course is independent.
    +
    + +

    Example 3:

    + +
    +Input: n = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
    +Output: [true,true]
    +
    + +

    Example 4:

    + +
    +Input: n = 3, prerequisites = [[1,0],[2,0]], queries = [[0,1],[2,0]]
    +Output: [false,true]
    +
    + +

    Example 5:

    + +
    +Input: n = 5, prerequisites = [[0,1],[1,2],[2,3],[3,4]], queries = [[0,4],[4,0],[1,3],[3,0]]
    +Output: [true,false,true,false]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • 0 <= prerequisite.length <= (n * (n - 1) / 2)
    • +
    • 0 <= prerequisite[i][0], prerequisite[i][1] < n
    • +
    • prerequisite[i][0] != prerequisite[i][1]
    • +
    • The prerequisites graph has no cycles.
    • +
    • The prerequisites graph has no repeated edges.
    • +
    • 1 <= queries.length <= 10^4
    • +
    • queries[i][0] != queries[i][1]
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1462.Course Schedule IV/images/graph-1.png b/assets/1400-1499/1462.Course Schedule IV/images/graph-1.png new file mode 100644 index 00000000..79e9694f Binary files /dev/null and b/assets/1400-1499/1462.Course Schedule IV/images/graph-1.png differ diff --git a/assets/1400-1499/1462.Course Schedule IV/images/graph.png b/assets/1400-1499/1462.Course Schedule IV/images/graph.png new file mode 100644 index 00000000..89ce3719 Binary files /dev/null and b/assets/1400-1499/1462.Course Schedule IV/images/graph.png differ diff --git a/assets/1400-1499/1463.Cherry Pickup II/README_EN.md b/assets/1400-1499/1463.Cherry Pickup II/README_EN.md new file mode 100644 index 00000000..160db528 --- /dev/null +++ b/assets/1400-1499/1463.Cherry Pickup II/README_EN.md @@ -0,0 +1,95 @@ +# [1463. Cherry Pickup II](https://leetcode.com/problems/cherry-pickup-ii) + + + +## Description + +

    Given a rows x cols matrix grid representing a field of cherries. Each cell in grid represents the number of cherries that you can collect.

    + +

    You have two robots that can collect cherries for you, Robot #1 is located at the top-left corner (0,0) , and Robot #2 is located at the top-right corner (0, cols-1) of the grid.

    + +

    Return the maximum number of cherries collection using both robots  by following the rules below:

    + +
      +
    • From a cell (i,j), robots can move to cell (i+1, j-1) , (i+1, j) or (i+1, j+1).
    • +
    • When any robot is passing through a cell, It picks it up all cherries, and the cell becomes an empty cell (0).
    • +
    • When both robots stay on the same cell, only one of them takes the cherries.
    • +
    • Both robots cannot move outside of the grid at any moment.
    • +
    • Both robots should reach the bottom row in the grid.
    • +
    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
    +Output: 24
    +Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
    +Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
    +Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
    +Total of cherries: 12 + 12 = 24.
    +
    + +

    Example 2:

    + +

    + +
    +Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
    +Output: 28
    +Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
    +Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
    +Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
    +Total of cherries: 17 + 11 = 28.
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0,0,3],[0,0,0,3],[0,0,3,3],[9,0,3,3]]
    +Output: 22
    +
    + +

    Example 4:

    + +
    +Input: grid = [[1,1],[1,1]]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • rows == grid.length
    • +
    • cols == grid[i].length
    • +
    • 2 <= rows, cols <= 70
    • +
    • 0 <= grid[i][j] <= 100 
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1463.Cherry Pickup II/images/sample_1_1802.png b/assets/1400-1499/1463.Cherry Pickup II/images/sample_1_1802.png new file mode 100644 index 00000000..1ecc81b4 Binary files /dev/null and b/assets/1400-1499/1463.Cherry Pickup II/images/sample_1_1802.png differ diff --git a/assets/1400-1499/1463.Cherry Pickup II/images/sample_2_1802.png b/assets/1400-1499/1463.Cherry Pickup II/images/sample_2_1802.png new file mode 100644 index 00000000..fe1c80dd Binary files /dev/null and b/assets/1400-1499/1463.Cherry Pickup II/images/sample_2_1802.png differ diff --git a/assets/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md b/assets/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md new file mode 100644 index 00000000..4de348cf --- /dev/null +++ b/assets/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md @@ -0,0 +1,89 @@ +# [1464. Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array) + + + +## Description + +Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). +

     

    +

    Example 1:

    + +
    +Input: nums = [3,4,5,2]
    +Output: 12 
    +Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,5,4,5]
    +Output: 16
    +Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
    +
    + +

    Example 3:

    + +
    +Input: nums = [3,7]
    +Output: 12
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 500
    • +
    • 1 <= nums[i] <= 10^3
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + i = 0 if nums[0] > nums[1] else 1 + j = 1 - i + for k in range(2, len(nums)): + if nums[k] > nums[i]: + j = k + i, j = j, i + elif nums[k] > nums[j]: + j = k + return (nums[i] - 1) * (nums[j] - 1) +``` + +### **Java** + +```java +class Solution { + public int maxProduct(int[] nums) { + int i = nums[0] > nums[1] ? 0 : 1; + int j = 1 - i; + for (int k = 2; k < nums.length; ++k) { + if (nums[k] > nums[i]) { + j = k; + int t = i; + i = j; + j = t; + } else if (nums[k] > nums[j]) { + j = k; + } + } + return (nums[i] - 1) * (nums[j] - 1); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md b/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md new file mode 100644 index 00000000..a41b5fc9 --- /dev/null +++ b/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md @@ -0,0 +1,75 @@ +# [1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts](https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts) + + + +## Description + +

    Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.

    + +

    Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCutsSince the answer can be a huge number, return this modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
    +Output: 4 
    +Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
    +
    + +

    Example 2:

    + +

    + +
    +Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
    +Output: 6
    +Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
    +
    + +

    Example 3:

    + +
    +Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
    +Output: 9
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= h, w <= 10^9
    • +
    • 1 <= horizontalCuts.length < min(h, 10^5)
    • +
    • 1 <= verticalCuts.length < min(w, 10^5)
    • +
    • 1 <= horizontalCuts[i] < h
    • +
    • 1 <= verticalCuts[i] < w
    • +
    • It is guaranteed that all elements in horizontalCuts are distinct.
    • +
    • It is guaranteed that all elements in verticalCuts are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/images/leetcode_max_area_2.png b/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/images/leetcode_max_area_2.png new file mode 100644 index 00000000..b82d2ac0 Binary files /dev/null and b/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/images/leetcode_max_area_2.png differ diff --git a/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/images/leetcode_max_area_3.png b/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/images/leetcode_max_area_3.png new file mode 100644 index 00000000..0f968335 Binary files /dev/null and b/assets/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/images/leetcode_max_area_3.png differ diff --git a/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md b/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md new file mode 100644 index 00000000..9b464306 --- /dev/null +++ b/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md @@ -0,0 +1,77 @@ +# [1466. Reorder Routes to Make All Paths Lead to the City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero) + + + +## Description + +

    There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.

    + +

    Roads are represented by connections where connections[i] = [a, b] represents a road from city a to b.

    + +

    This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

    + +

    Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.

    + +

    It's guaranteed that each city can reach the city 0 after reorder.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
    +Output: 3
    +Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
    + +

    Example 2:

    + +

    + +
    +Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
    +Output: 2
    +Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
    + +

    Example 3:

    + +
    +Input: n = 3, connections = [[1,0],[2,0]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 5 * 10^4
    • +
    • connections.length == n-1
    • +
    • connections[i].length == 2
    • +
    • 0 <= connections[i][0], connections[i][1] <= n-1
    • +
    • connections[i][0] != connections[i][1]
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/images/sample_1_1819.png b/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/images/sample_1_1819.png new file mode 100644 index 00000000..90835e61 Binary files /dev/null and b/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/images/sample_1_1819.png differ diff --git a/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/images/sample_2_1819.png b/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/images/sample_2_1819.png new file mode 100644 index 00000000..4f5d262d Binary files /dev/null and b/assets/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/images/sample_2_1819.png differ diff --git a/assets/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md b/assets/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md new file mode 100644 index 00000000..543363e7 --- /dev/null +++ b/assets/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md @@ -0,0 +1,98 @@ +# [1467. Probability of a Two Boxes Having The Same Number of Distinct Balls](https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls) + + + +## Description + +

    Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i

    + +

    All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).

    + +

    Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).

    + +

    We want to calculate the probability that the two boxes have the same number of distinct balls.

    + +

     

    +

    Example 1:

    + +
    +Input: balls = [1,1]
    +Output: 1.00000
    +Explanation: Only 2 ways to divide the balls equally:
    +- A ball of color 1 to box 1 and a ball of color 2 to box 2
    +- A ball of color 2 to box 1 and a ball of color 1 to box 2
    +In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
    +
    + +

    Example 2:

    + +
    +Input: balls = [2,1,1]
    +Output: 0.66667
    +Explanation: We have the set of balls [1, 1, 2, 3]
    +This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 1/12):
    +[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
    +After that we add the first two balls to the first box and the second two balls to the second box.
    +We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
    +Probability is 8/12 = 0.66667
    +
    + +

    Example 3:

    + +
    +Input: balls = [1,2,1,2]
    +Output: 0.60000
    +Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
    +Probability = 108 / 180 = 0.6
    +
    + +

    Example 4:

    + +
    +Input: balls = [3,2,1]
    +Output: 0.30000
    +Explanation: The set of balls is [1, 1, 1, 2, 2, 3]. It is hard to display all the 60 possible random shuffles of this set but it is easy to check that 18 of them will have the same number of distinct colors in each box.
    +Probability = 18 / 60 = 0.3
    +
    + +

    Example 5:

    + +
    +Input: balls = [6,6,6,6,6,6]
    +Output: 0.90327
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= balls.length <= 8
    • +
    • 1 <= balls[i] <= 6
    • +
    • sum(balls) is even.
    • +
    • Answers within 10^-5 of the actual value will be accepted as correct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1468.Calculate Salaries/README_EN.md b/assets/1400-1499/1468.Calculate Salaries/README_EN.md new file mode 100644 index 00000000..4d0735c0 --- /dev/null +++ b/assets/1400-1499/1468.Calculate Salaries/README_EN.md @@ -0,0 +1,88 @@ +# [1468. Calculate Salaries](https://leetcode.com/problems/calculate-salaries) + + + +## Description + +

    Table Salaries:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| company_id    | int     |
    +| employee_id   | int     |
    +| employee_name | varchar |
    +| salary        | int     |
    ++---------------+---------+
    +(company_id, employee_id) is the primary key for this table.
    +This table contains the company id, the id, the name and the salary for an employee.
    +
    + +

     

    + +

    Write an SQL query to find the salaries of the employees after applying taxes.

    + +

    The tax rate is calculated for each company based on the following criteria:

    + +
      +
    • 0% If the max salary of any employee in the company is less than 1000$.
    • +
    • 24% If the max salary of any employee in the company is in the range [1000, 10000] inclusive.
    • +
    • 49% If the max salary of any employee in the company is greater than 10000$.
    • +
    + +

    Return the result table in any order. Round the salary to the nearest integer.

    + +

    The query result format is in the following example:

    + +
    +Salaries table:
    ++------------+-------------+---------------+--------+
    +| company_id | employee_id | employee_name | salary |
    ++------------+-------------+---------------+--------+
    +| 1          | 1           | Tony          | 2000   |
    +| 1          | 2           | Pronub        | 21300  |
    +| 1          | 3           | Tyrrox        | 10800  |
    +| 2          | 1           | Pam           | 300    |
    +| 2          | 7           | Bassem        | 450    |
    +| 2          | 9           | Hermione      | 700    |
    +| 3          | 7           | Bocaben       | 100    |
    +| 3          | 2           | Ognjen        | 2200   |
    +| 3          | 13          | Nyancat       | 3300   |
    +| 3          | 15          | Morninngcat   | 7777   |
    ++------------+-------------+---------------+--------+
    +
    +Result table:
    ++------------+-------------+---------------+--------+
    +| company_id | employee_id | employee_name | salary |
    ++------------+-------------+---------------+--------+
    +| 1          | 1           | Tony          | 1020   |
    +| 1          | 2           | Pronub        | 10863  |
    +| 1          | 3           | Tyrrox        | 5508   |
    +| 2          | 1           | Pam           | 300    |
    +| 2          | 7           | Bassem        | 450    |
    +| 2          | 9           | Hermione      | 700    |
    +| 3          | 7           | Bocaben       | 76     |
    +| 3          | 2           | Ognjen        | 1672   |
    +| 3          | 13          | Nyancat       | 2508   |
    +| 3          | 15          | Morninngcat   | 5911   |
    ++------------+-------------+---------------+--------+
    +For company 1, Max salary is 21300. Employees in company 1 have taxes = 49%
    +For company 2, Max salary is 700. Employees in company 2 have taxes = 0%
    +For company 3, Max salary is 7777. Employees in company 3 have taxes = 24%
    +The salary after taxes = salary - (taxes percentage / 100) * salary
    +For example, Salary for Morninngcat (3, 15) after taxes = 7777 - 7777 * (24 / 100) = 7777 - 1866.48 = 5910.52, which is rounded to 5911.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1469.Find All The Lonely Nodes/README_EN.md b/assets/1400-1499/1469.Find All The Lonely Nodes/README_EN.md new file mode 100644 index 00000000..1fa1154b --- /dev/null +++ b/assets/1400-1499/1469.Find All The Lonely Nodes/README_EN.md @@ -0,0 +1,143 @@ +# [1469. Find All The Lonely Nodes](https://leetcode.com/problems/find-all-the-lonely-nodes) + + + +## Description + +

    In a binary tree, a lonely node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.

    + +

    Given the root of a binary tree, return an array containing the values of all lonely nodes in the tree. Return the list in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,2,3,null,4]
    +Output: [4]
    +Explanation: Light blue node is the only lonely node.
    +Node 1 is the root and is not lonely.
    +Nodes 2 and 3 have the same parent and are not lonely.
    +
    + +

    Example 2:

    + +
    +Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2]
    +Output: [6,2]
    +Explanation: Light blue nodes are lonely nodes.
    +Please remember that order doesn't matter, [2,6] is also an acceptable answer.
    +
    + +

    Example 3:

    + + +
    +
    +Input: root = [11,99,88,77,null,null,66,55,null,null,44,33,null,null,22]
    +Output: [77,55,33,66,44,22]
    +Explanation: Nodes 99 and 88 share the same parent. Node 11 is the root.
    +All other nodes are lonely.
    +
    + +

    Example 4:

    + +
    +Input: root = [197]
    +Output: []
    +
    + +

    Example 5:

    + +
    +Input: root = [31,null,78,null,28]
    +Output: [78,28]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 1000].
    • +
    • Each node's value is between [1, 10^6].
    • +
    + + +## Solutions + + + +### **Python3** + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def getLonelyNodes(self, root: TreeNode) -> List[int]: + def traverse(root): + if root is None: + return + if root.left is None and root.right is not None: + self.res.append(root.right.val) + if root.left is not None and root.right is None: + self.res.append(root.left.val) + traverse(root.left) + traverse(root.right) + self.res = [] + traverse(root) + return self.res +``` + +### **Java** + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List res; + + public List getLonelyNodes(TreeNode root) { + res = new ArrayList<>(); + traverse(root); + return res; + } + + private void traverse(TreeNode root) { + if (root == null) { + return; + } + if (root.left == null && root.right != null) { + res.add(root.right.val); + } + if (root.left != null && root.right == null) { + res.add(root.left.val); + } + traverse(root.left); + traverse(root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1469.Find All The Lonely Nodes/images/e1.png b/assets/1400-1499/1469.Find All The Lonely Nodes/images/e1.png new file mode 100644 index 00000000..ae29a2d6 Binary files /dev/null and b/assets/1400-1499/1469.Find All The Lonely Nodes/images/e1.png differ diff --git a/assets/1400-1499/1469.Find All The Lonely Nodes/images/e2.png b/assets/1400-1499/1469.Find All The Lonely Nodes/images/e2.png new file mode 100644 index 00000000..08f51a6e Binary files /dev/null and b/assets/1400-1499/1469.Find All The Lonely Nodes/images/e2.png differ diff --git a/assets/1400-1499/1469.Find All The Lonely Nodes/images/tree.png b/assets/1400-1499/1469.Find All The Lonely Nodes/images/tree.png new file mode 100644 index 00000000..0b26685c Binary files /dev/null and b/assets/1400-1499/1469.Find All The Lonely Nodes/images/tree.png differ diff --git a/assets/1400-1499/1470.Shuffle the Array/README_EN.md b/assets/1400-1499/1470.Shuffle the Array/README_EN.md new file mode 100644 index 00000000..1669436c --- /dev/null +++ b/assets/1400-1499/1470.Shuffle the Array/README_EN.md @@ -0,0 +1,95 @@ +# [1470. Shuffle the Array](https://leetcode.com/problems/shuffle-the-array) + + + +## Description + +

    Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].

    + + + +

    Return the array in the form [x1,y1,x2,y2,...,xn,yn].

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [2,5,1,3,4,7], n = 3
    +
    +Output: [2,3,5,4,1,7] 
    +
    +Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,2,3,4,4,3,2,1], n = 4
    +
    +Output: [1,4,2,3,3,2,4,1]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [1,1,2,2], n = 2
    +
    +Output: [1,2,1,2]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 500
    • +
    • nums.length == 2n
    • +
    • 1 <= nums[i] <= 10^3
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1471.The k Strongest Values in an Array/README_EN.md b/assets/1400-1499/1471.The k Strongest Values in an Array/README_EN.md new file mode 100644 index 00000000..d2238b91 --- /dev/null +++ b/assets/1400-1499/1471.The k Strongest Values in an Array/README_EN.md @@ -0,0 +1,148 @@ +# [1471. The k Strongest Values in an Array](https://leetcode.com/problems/the-k-strongest-values-in-an-array) + + + +## Description + +

    Given an array of integers arr and an integer k.

    + + + +

    A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
    + +If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].

    + + + +

    Return a list of the strongest k values in the array. return the answer in any arbitrary order.

    + + + +

    Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).

    + + + +
      +
    • For arr = [6, -3, 7, 2, 11]n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.
    • +
    • For arr = [-7, 22, 17, 3]n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [1,2,3,4,5], k = 2
    +
    +Output: [5,1]
    +
    +Explanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.
    +
    +Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [1,1,3,5,5], k = 2
    +
    +Output: [5,5]
    +
    +Explanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [6,7,11,7,6,8], k = 5
    +
    +Output: [11,8,6,6,7]
    +
    +Explanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].
    +
    +Any permutation of [11,8,6,6,7] is accepted.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [6,-3,7,2,11], k = 3
    +
    +Output: [-3,11,2]
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: arr = [-7,22,17,3], k = 2
    +
    +Output: [22,17]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • -10^5 <= arr[i] <= 10^5
    • +
    • 1 <= k <= arr.length
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1472.Design Browser History/README_EN.md b/assets/1400-1499/1472.Design Browser History/README_EN.md new file mode 100644 index 00000000..8e42cc02 --- /dev/null +++ b/assets/1400-1499/1472.Design Browser History/README_EN.md @@ -0,0 +1,228 @@ +# [1472. Design Browser History](https://leetcode.com/problems/design-browser-history) + + + +## Description + +

    You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.

    + +

    Implement the BrowserHistory class:

    + +
      +
    • BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
    • +
    • void visit(string url) Visits url from the current page. It clears up all the forward history.
    • +
    • string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.
    • +
    • string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.
    • +
    + +

     

    +

    Example:

    + +
    +Input:
    +["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
    +[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
    +Output:
    +[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
    +
    +Explanation:
    +BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
    +browserHistory.visit("google.com");       // You are in "leetcode.com". Visit "google.com"
    +browserHistory.visit("facebook.com");     // You are in "google.com". Visit "facebook.com"
    +browserHistory.visit("youtube.com");      // You are in "facebook.com". Visit "youtube.com"
    +browserHistory.back(1);                   // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
    +browserHistory.back(1);                   // You are in "facebook.com", move back to "google.com" return "google.com"
    +browserHistory.forward(1);                // You are in "google.com", move forward to "facebook.com" return "facebook.com"
    +browserHistory.visit("linkedin.com");     // You are in "facebook.com". Visit "linkedin.com"
    +browserHistory.forward(2);                // You are in "linkedin.com", you cannot move forward any steps.
    +browserHistory.back(2);                   // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
    +browserHistory.back(7);                   // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= homepage.length <= 20
    • +
    • 1 <= url.length <= 20
    • +
    • 1 <= steps <= 100
    • +
    • homepage and url consist of  '.' or lower case English letters.
    • +
    • At most 5000 calls will be made to visit, back, and forward.
    • +
    + +## Solutions + + + +### **Python3** + +Using list. + +```python +class BrowserHistory: + + def __init__(self, homepage: str): + self.urls = [] + self.cur = -1 + self.tail = -1 + self.visit(homepage) + + def visit(self, url: str) -> None: + self.cur += 1 + if self.cur < len(self.urls): + self.urls[self.cur] = url + else: + self.urls.append(url) + self.tail = self.cur + + def back(self, steps: int) -> str: + self.cur = max(0, self.cur -steps) + return self.urls[self.cur] + + def forward(self, steps: int) -> str: + self.cur = min(self.tail, self.cur + steps) + return self.urls[self.cur] + +# Your BrowserHistory object will be instantiated and called as such: +# obj = BrowserHistory(homepage) +# obj.visit(url) +# param_2 = obj.back(steps) +# param_3 = obj.forward(steps) +``` + +Using stacks. + +```python +class BrowserHistory: + + def __init__(self, homepage: str): + self.s1 = [] + self.s2 = [] + self.cur = homepage + + def visit(self, url: str) -> None: + self.s2.clear() + self.s1.append(self.cur) + self.cur = url + + def back(self, steps: int) -> str: + while steps > 0 and self.s1: + self.s2.append(self.cur) + self.cur = self.s1.pop() + steps -= 1 + return self.cur + + def forward(self, steps: int) -> str: + while steps > 0 and self.s2: + self.s1.append(self.cur) + self.cur = self.s2.pop() + steps -= 1 + return self.cur + + +# Your BrowserHistory object will be instantiated and called as such: +# obj = BrowserHistory(homepage) +# obj.visit(url) +# param_2 = obj.back(steps) +``` + +### **Java** + +Using list. + +```java +class BrowserHistory { + private List urls; + private int cur = -1; + private int tail = -1; + + public BrowserHistory(String homepage) { + urls = new ArrayList<>(); + visit(homepage); + } + + public void visit(String url) { + ++cur; + if (cur < urls.size()) { + urls.set(cur, url); + } else { + urls.add(url); + } + tail = cur; + } + + public String back(int steps) { + cur = Math.max(0, cur - steps); + return urls.get(cur); + } + + public String forward(int steps) { + cur = Math.min(tail, cur + steps); + return urls.get(cur); + } +} + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory obj = new BrowserHistory(homepage); + * obj.visit(url); + * String param_2 = obj.back(steps); + * String param_3 = obj.forward(steps); + */ +``` + +Using stacks. + +```java +class BrowserHistory { + private Deque s1; + private Deque s2; + private String cur; + + public BrowserHistory(String homepage) { + s1 = new ArrayDeque<>(); + s2 = new ArrayDeque<>(); + cur = homepage; + } + + public void visit(String url) { + s2.clear(); + s1.push(cur); + cur = url; + } + + public String back(int steps) { + while (steps > 0 && !s1.isEmpty()) { + s2.push(cur); + cur = s1.pop(); + --steps; + } + return cur; + } + + public String forward(int steps) { + while (steps > 0 && !s2.isEmpty()) { + s1.push(cur); + cur = s2.pop(); + --steps; + } + return cur; + } +} + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory obj = new BrowserHistory(homepage); + * obj.visit(url); + * String param_2 = obj.back(steps); + * String param_3 = obj.forward(steps); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1473.Paint House III/README_EN.md b/assets/1400-1499/1473.Paint House III/README_EN.md new file mode 100644 index 00000000..dc2cf420 --- /dev/null +++ b/assets/1400-1499/1473.Paint House III/README_EN.md @@ -0,0 +1,96 @@ +# [1473. Paint House III](https://leetcode.com/problems/paint-house-iii) + + + +## Description + +

    There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.

    + +

    A neighborhood is a maximal group of continuous houses that are painted with the same color.

    + +
      +
    • For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].
    • +
    + +

    Given an array houses, an m x n matrix cost and an integer target where:

    + +
      +
    • houses[i]: is the color of the house i, and 0 if the house is not painted yet.
    • +
    • cost[i][j]: is the cost of paint the house i with the color j + 1.
    • +
    + +

    Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
    +Output: 9
    +Explanation: Paint houses of this way [1,2,2,1,1]
    +This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].
    +Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.
    +
    + +

    Example 2:

    + +
    +Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
    +Output: 11
    +Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]
    +This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. 
    +Cost of paint the first and last house (10 + 1) = 11.
    +
    + +

    Example 3:

    + +
    +Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[1,10],[10,1],[1,10]], m = 5, n = 2, target = 5
    +Output: 5
    +
    + +

    Example 4:

    + +
    +Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
    +Output: -1
    +Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == houses.length == cost.length
    • +
    • n == cost[i].length
    • +
    • 1 <= m <= 100
    • +
    • 1 <= n <= 20
    • +
    • 1 <= target <= m
    • +
    • 0 <= houses[i] <= n
    • +
    • 1 <= cost[i][j] <= 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md b/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md new file mode 100644 index 00000000..fe60cb90 --- /dev/null +++ b/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md @@ -0,0 +1,153 @@ +# [1474. Delete N Nodes After M Nodes of a Linked List](https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list) + + + +## Description + +

    Given the head of a linked list and two integers m and n. Traverse the linked list and remove some nodes in the following way:

    + +
      +
    • Start with the head as the current node.
    • +
    • Keep the first m nodes starting with the current node.
    • +
    • Remove the next n nodes
    • +
    • Keep repeating steps 2 and 3 until you reach the end of the list.
    • +
    + +

    Return the head of the modified list after removing the mentioned nodes.

    + +

    Follow up question: How can you solve this problem by modifying the list in-place?

    + +

     

    + +

    Example 1:

    + +

    + +
    +
    +Input: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3
    +
    +Output: [1,2,6,7,11,12]
    +
    +Explanation: Keep the first (m = 2) nodes starting from the head of the linked List  (1 ->2) show in black nodes.
    +
    +Delete the next (n = 3) nodes (3 -> 4 -> 5) show in read nodes.
    +
    +Continue with the same procedure until reaching the tail of the Linked List.
    +
    +Head of linked list after removing nodes is returned.
    + +

    Example 2:

    + +

    + +
    +
    +Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 1, n = 3
    +
    +Output: [1,5,9]
    +
    +Explanation: Head of linked list after removing nodes is returned.
    + +

    Example 3:

    + +
    +
    +Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 3, n = 1
    +
    +Output: [1,2,3,5,6,7,9,10,11]
    +
    +
    + +

    Example 4:

    + +
    +
    +Input: head = [9,3,7,7,9,10,8,2], m = 1, n = 2
    +
    +Output: [9,7,8]
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • The given linked list will contain between 1 and 10^4 nodes.
    • +
    • The value of each node in the linked list will be in the range [1, 10^6].
    • +
    • 1 <= m,n <= 1000
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode: + pre = head + while pre: + for i in range(m - 1): + if pre: + pre = pre.next + if pre is None: + return head + cur = pre + for i in range(n): + if cur: + cur = cur.next + pre.next = None if cur is None else cur.next + pre = pre.next + return head +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteNodes(ListNode head, int m, int n) { + ListNode pre = head; + while (pre != null) { + for (int i = 0; i < m - 1 && pre != null; ++i) { + pre = pre.next; + } + if (pre == null) { + return head; + } + ListNode cur = pre; + for (int i = 0; i < n && cur != null; ++i) { + cur = cur.next; + } + pre.next = cur == null ? null : cur.next; + pre = pre.next; + } + return head; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/images/sample_1_1848.png b/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/images/sample_1_1848.png new file mode 100644 index 00000000..72a12702 Binary files /dev/null and b/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/images/sample_1_1848.png differ diff --git a/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/images/sample_2_1848.png b/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/images/sample_2_1848.png new file mode 100644 index 00000000..852cc688 Binary files /dev/null and b/assets/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/images/sample_2_1848.png differ diff --git a/assets/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md b/assets/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md new file mode 100644 index 00000000..c6b4ec88 --- /dev/null +++ b/assets/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md @@ -0,0 +1,70 @@ +# [1475. Final Prices With a Special Discount in a Shop](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop) + + + +## Description + +

    Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.

    + +

    Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.

    + +

     

    +

    Example 1:

    + +
    +Input: prices = [8,4,6,2,3]
    +Output: [4,2,4,2,3]
    +Explanation: 
    +For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. 
    +For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. 
    +For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. 
    +For items 3 and 4 you will not receive any discount at all.
    +
    + +

    Example 2:

    + +
    +Input: prices = [1,2,3,4,5]
    +Output: [1,2,3,4,5]
    +Explanation: In this case, for all items, you will not receive any discount at all.
    +
    + +

    Example 3:

    + +
    +Input: prices = [10,1,1,6]
    +Output: [9,0,1,6]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= prices.length <= 500
    • +
    • 1 <= prices[i] <= 10^3
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1476.Subrectangle Queries/README_EN.md b/assets/1400-1499/1476.Subrectangle Queries/README_EN.md new file mode 100644 index 00000000..9ed31018 --- /dev/null +++ b/assets/1400-1499/1476.Subrectangle Queries/README_EN.md @@ -0,0 +1,261 @@ +# [1476. Subrectangle Queries](https://leetcode.com/problems/subrectangle-queries) + + + +## Description + +

    Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:

    + + + +

    1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

    + + + +
      +
    • Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
    • +
    + + + +

    2. getValue(int row, int col)

    + + + +
      +
    • Returns the current value of the coordinate (row,col) from the rectangle.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input
    +
    +["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]
    +
    +[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
    +
    +Output
    +
    +[null,1,null,5,5,null,10,5]
    +
    +Explanation
    +
    +SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);  
    +
    +// The initial rectangle (4x3) looks like:
    +
    +// 1 2 1
    +
    +// 4 3 4
    +
    +// 3 2 1
    +
    +// 1 1 1
    +
    +subrectangleQueries.getValue(0, 2); // return 1
    +
    +subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
    +
    +// After this update the rectangle looks like:
    +
    +// 5 5 5
    +
    +// 5 5 5
    +
    +// 5 5 5
    +
    +// 5 5 5 
    +
    +subrectangleQueries.getValue(0, 2); // return 5
    +
    +subrectangleQueries.getValue(3, 1); // return 5
    +
    +subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
    +
    +// After this update the rectangle looks like:
    +
    +// 5   5   5
    +
    +// 5   5   5
    +
    +// 5   5   5
    +
    +// 10  10  10 
    +
    +subrectangleQueries.getValue(3, 1); // return 10
    +
    +subrectangleQueries.getValue(0, 2); // return 5
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input
    +
    +["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"]
    +
    +[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]
    +
    +Output
    +
    +[null,1,null,100,100,null,20]
    +
    +Explanation
    +
    +SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);
    +
    +subrectangleQueries.getValue(0, 0); // return 1
    +
    +subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);
    +
    +subrectangleQueries.getValue(0, 0); // return 100
    +
    +subrectangleQueries.getValue(2, 2); // return 100
    +
    +subrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);
    +
    +subrectangleQueries.getValue(2, 2); // return 20
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • There will be at most 500 operations considering both methods: updateSubrectangle and getValue.
    • +
    • 1 <= rows, cols <= 100
    • +
    • rows == rectangle.length
    • +
    • cols == rectangle[i].length
    • +
    • 0 <= row1 <= row2 < rows
    • +
    • 0 <= col1 <= col2 < cols
    • +
    • 1 <= newValue, rectangle[i][j] <= 10^9
    • +
    • 0 <= row < rows
    • +
    • 0 <= col < cols
    • +
    + +## Solutions + +Use history list to save the updated record. + + + +### **Python3** + +```python +class SubrectangleQueries: + + def __init__(self, rectangle: List[List[int]]): + self.rec = rectangle + self.history = [] + + def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: + self.history.append((row1, col1, row2, col2, newValue)) + + def getValue(self, row: int, col: int) -> int: + for row1, col1, row2, col2, newValue in self.history[::-1]: + if row >= row1 and row <= row2 and col >= col1 and col <= col2: + return newValue + return self.rec[row][col] + + +# Your SubrectangleQueries object will be instantiated and called as such: +# obj = SubrectangleQueries(rectangle) +# obj.updateSubrectangle(row1,col1,row2,col2,newValue) +# param_2 = obj.getValue(row,col) +``` + +### **Java** + +```java +class SubrectangleQueries { + private int[][] rec; + private List history; + + public SubrectangleQueries(int[][] rectangle) { + rec = rectangle; + history = new ArrayList<>(); + } + + public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { + history.add(new int[]{row1, col1, row2, col2, newValue}); + } + + public int getValue(int row, int col) { + for (int i = history.size() - 1; i >= 0; --i) { + int[] record = history.get(i); + if (row >= record[0] && row <= record[2] && col >= record[1] && col <= record[3]) { + return record[4]; + } + } + return rec[row][col]; + } +} + +/** + * Your SubrectangleQueries object will be instantiated and called as such: + * SubrectangleQueries obj = new SubrectangleQueries(rectangle); + * obj.updateSubrectangle(row1,col1,row2,col2,newValue); + * int param_2 = obj.getValue(row,col); + */ +``` + +### **TypeScript** + +```ts +class SubrectangleQueries { + grid: number[][]; + history: number[][]; + constructor(rectangle: number[][]) { + this.grid = rectangle; + this.history = []; + } + + updateSubrectangle(row1: number, col1: number, row2: number, col2: number, newValue: number): void { + this.history.push([row1, col1, row2, col2, newValue]); + } + + getValue(row: number, col: number): number { + for (let i = this.history.length - 1; i >= 0; --i) { + let [row1, col1, row2, col2, newValue] = this.history[i]; + if (row >= row1 && row <= row2 && col >= col1 && col <= col2) { + return newValue; + } + } + return this.grid[row][col]; + } +} + +/** + * Your SubrectangleQueries object will be instantiated and called as such: + * var obj = new SubrectangleQueries(rectangle) + * obj.updateSubrectangle(row1,col1,row2,col2,newValue) + * var param_2 = obj.getValue(row,col) + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md b/assets/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md new file mode 100644 index 00000000..7b4d3484 --- /dev/null +++ b/assets/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md @@ -0,0 +1,86 @@ +# [1477. Find Two Non-overlapping Sub-arrays Each With Target Sum](https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum) + + + +## Description + +

    Given an array of integers arr and an integer target.

    + +

    You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.

    + +

    Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,2,2,4,3], target = 3
    +Output: 2
    +Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
    +
    + +

    Example 2:

    + +
    +Input: arr = [7,3,4,7], target = 7
    +Output: 2
    +Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
    +
    + +

    Example 3:

    + +
    +Input: arr = [4,3,2,6,2,3,4], target = 6
    +Output: -1
    +Explanation: We have only one sub-array of sum = 6.
    +
    + +

    Example 4:

    + +
    +Input: arr = [5,5,4,4,5], target = 3
    +Output: -1
    +Explanation: We cannot find a sub-array of sum = 3.
    +
    + +

    Example 5:

    + +
    +Input: arr = [3,1,1,1,5,1,2,1], target = 3
    +Output: 3
    +Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • 1 <= arr[i] <= 1000
    • +
    • 1 <= target <= 108
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1478.Allocate Mailboxes/README_EN.md b/assets/1400-1499/1478.Allocate Mailboxes/README_EN.md new file mode 100644 index 00000000..7754fda0 --- /dev/null +++ b/assets/1400-1499/1478.Allocate Mailboxes/README_EN.md @@ -0,0 +1,129 @@ +# [1478. Allocate Mailboxes](https://leetcode.com/problems/allocate-mailboxes) + + + +## Description + +

    Given the array houses and an integer k. where houses[i] is the location of the ith house along a street, your task is to allocate k mailboxes in the street.

    + + + +

    Return the minimum total distance between each house and its nearest mailbox.

    + + + +

    The answer is guaranteed to fit in a 32-bit signed integer.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: houses = [1,4,8,10,20], k = 3
    +
    +Output: 5
    +
    +Explanation: Allocate mailboxes in position 3, 9 and 20.
    +
    +Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: houses = [2,3,5,12,18], k = 2
    +
    +Output: 9
    +
    +Explanation: Allocate mailboxes in position 3 and 14.
    +
    +Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: houses = [7,4,6,1], k = 1
    +
    +Output: 8
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: houses = [3,6,14,10], k = 4
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == houses.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= houses[i] <= 10^4
    • +
    • 1 <= k <= n
    • +
    • Array houses contain unique integers.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1478.Allocate Mailboxes/images/sample_11_1816.png b/assets/1400-1499/1478.Allocate Mailboxes/images/sample_11_1816.png new file mode 100644 index 00000000..6ebd3b18 Binary files /dev/null and b/assets/1400-1499/1478.Allocate Mailboxes/images/sample_11_1816.png differ diff --git a/assets/1400-1499/1478.Allocate Mailboxes/images/sample_2_1816.png b/assets/1400-1499/1478.Allocate Mailboxes/images/sample_2_1816.png new file mode 100644 index 00000000..1edc2c48 Binary files /dev/null and b/assets/1400-1499/1478.Allocate Mailboxes/images/sample_2_1816.png differ diff --git a/assets/1400-1499/1479.Sales by Day of the Week/README_EN.md b/assets/1400-1499/1479.Sales by Day of the Week/README_EN.md new file mode 100644 index 00000000..36a37b50 --- /dev/null +++ b/assets/1400-1499/1479.Sales by Day of the Week/README_EN.md @@ -0,0 +1,201 @@ +# [1479. Sales by Day of the Week](https://leetcode.com/problems/sales-by-day-of-the-week) + + + +## Description + +

    Table: Orders

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| order_id      | int     |
    +
    +| customer_id   | int     |
    +
    +| order_date    | date    | 
    +
    +| item_id       | varchar |
    +
    +| quantity      | int     |
    +
    ++---------------+---------+
    +
    +(ordered_id, item_id) is the primary key for this table.
    +
    +This table contains information of the orders placed.
    +
    +order_date is the date when item_id was ordered by the customer with id customer_id.
    +
    +
    + + + +

     

    + + + +

    Table: Items

    + + + +
    +
    ++---------------------+---------+
    +
    +| Column Name         | Type    |
    +
    ++---------------------+---------+
    +
    +| item_id             | varchar |
    +
    +| item_name           | varchar |
    +
    +| item_category       | varchar |
    +
    ++---------------------+---------+
    +
    +item_id is the primary key for this table.
    +
    +item_name is the name of the item.
    +
    +item_category is the category of the item.
    +
    +
    + + + +

     

    + + + +

    You are the business owner and would like to obtain a sales report for category items and day of the week.

    + + + +

    Write an SQL query to report how many units in each category have been ordered on each day of the week.

    + + + +

    Return the result table ordered by category.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Orders table:
    +
    ++------------+--------------+-------------+--------------+-------------+
    +
    +| order_id   | customer_id  | order_date  | item_id      | quantity    |
    +
    ++------------+--------------+-------------+--------------+-------------+
    +
    +| 1          | 1            | 2020-06-01  | 1            | 10          |
    +
    +| 2          | 1            | 2020-06-08  | 2            | 10          |
    +
    +| 3          | 2            | 2020-06-02  | 1            | 5           |
    +
    +| 4          | 3            | 2020-06-03  | 3            | 5           |
    +
    +| 5          | 4            | 2020-06-04  | 4            | 1           |
    +
    +| 6          | 4            | 2020-06-05  | 5            | 5           |
    +
    +| 7          | 5            | 2020-06-05  | 1            | 10          |
    +
    +| 8          | 5            | 2020-06-14  | 4            | 5           |
    +
    +| 9          | 5            | 2020-06-21  | 3            | 5           |
    +
    ++------------+--------------+-------------+--------------+-------------+
    +
    +
    +
    +Items table:
    +
    ++------------+----------------+---------------+
    +
    +| item_id    | item_name      | item_category |
    +
    ++------------+----------------+---------------+
    +
    +| 1          | LC Alg. Book   | Book          |
    +
    +| 2          | LC DB. Book    | Book          |
    +
    +| 3          | LC SmarthPhone | Phone         |
    +
    +| 4          | LC Phone 2020  | Phone         |
    +
    +| 5          | LC SmartGlass  | Glasses       |
    +
    +| 6          | LC T-Shirt XL  | T-Shirt       |
    +
    ++------------+----------------+---------------+
    +
    +
    +
    +Result table:
    +
    ++------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
    +
    +| Category   | Monday    | Tuesday   | Wednesday | Thursday  | Friday    | Saturday  | Sunday    |
    +
    ++------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
    +
    +| Book       | 20        | 5         | 0         | 0         | 10        | 0         | 0         |
    +
    +| Glasses    | 0         | 0         | 0         | 0         | 5         | 0         | 0         |
    +
    +| Phone      | 0         | 0         | 5         | 1         | 0         | 0         | 10        |
    +
    +| T-Shirt    | 0         | 0         | 0         | 0         | 0         | 0         | 0         |
    +
    ++------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
    +
    +On Monday (2020-06-01, 2020-06-08) were sold a total of 20 units (10 + 10) in the category Book (ids: 1, 2).
    +
    +On Tuesday (2020-06-02) were sold a total of 5 units  in the category Book (ids: 1, 2).
    +
    +On Wednesday (2020-06-03) were sold a total of 5 units in the category Phone (ids: 3, 4).
    +
    +On Thursday (2020-06-04) were sold a total of 1 unit in the category Phone (ids: 3, 4).
    +
    +On Friday (2020-06-05) were sold 10 units in the category Book (ids: 1, 2) and 5 units in Glasses (ids: 5).
    +
    +On Saturday there are no items sold.
    +
    +On Sunday (2020-06-14, 2020-06-21) were sold a total of 10 units (5 +5) in the category Phone (ids: 3, 4).
    +
    +There are no sales of T-Shirt.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1480.Running Sum of 1d Array/README_EN.md b/assets/1400-1499/1480.Running Sum of 1d Array/README_EN.md new file mode 100644 index 00000000..182f35db --- /dev/null +++ b/assets/1400-1499/1480.Running Sum of 1d Array/README_EN.md @@ -0,0 +1,128 @@ +# [1480. Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array) + + + +## Description + +

    Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

    + + + +

    Return the running sum of nums.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [1,2,3,4]
    +
    +Output: [1,3,6,10]
    +
    +Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,1,1,1,1]
    +
    +Output: [1,2,3,4,5]
    +
    +Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [3,1,2,10,1]
    +
    +Output: [3,4,6,16,17]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 1000
    • +
    • -10^6 <= nums[i] <= 10^6
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + for i in range(1, len(nums)): + nums[i] += nums[i - 1] + return nums +``` + +### **Java** + +```java +class Solution { + public int[] runningSum(int[] nums) { + for (int i = 1; i < nums.length; ++i) { + nums[i] += nums[i - 1]; + } + return nums; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector runningSum(vector& nums) { + for (int i = 1; i < nums.size(); ++i) { + nums[i] += nums[i - 1]; + } + return nums; + } +}; +``` + +### **Go** + +```go +func runningSum(nums []int) []int { + for i := 1; i < len(nums); i++ { + nums[i] += nums[i-1] + } + return nums +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md b/assets/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md new file mode 100644 index 00000000..26ee08b1 --- /dev/null +++ b/assets/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md @@ -0,0 +1,81 @@ +# [1481. Least Number of Unique Integers after K Removals](https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals) + + + +## Description + +

    Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.

    + + + +
      + +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [5,5,4], k = 1
    +
    +Output: 1
    +
    +Explanation: Remove the single 4, only 5 is left.
    +
    +
    + +Example 2: + + + +
    +
    +Input: arr = [4,3,1,1,3,3,2], k = 3
    +
    +Output: 2
    +
    +Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^9
    • +
    • 0 <= k <= arr.length
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md b/assets/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md new file mode 100644 index 00000000..774c49fa --- /dev/null +++ b/assets/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md @@ -0,0 +1,308 @@ +# [1482. Minimum Number of Days to Make m Bouquets](https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets) + + + +## Description + +

    Given an integer array bloomDay, an integer m and an integer k.

    + + + +

    We need to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.

    + + + +

    The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.

    + + + +

    Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
    +
    +Output: 3
    +
    +Explanation: Let's see what happened in the first three days. x means flower bloomed and _ means flower didn't bloom in the garden.
    +
    +We need 3 bouquets each should contain 1 flower.
    +
    +After day 1: [x, _, _, _, _]   // we can only make one bouquet.
    +
    +After day 2: [x, _, _, _, x]   // we can only make two bouquets.
    +
    +After day 3: [x, _, x, _, x]   // we can make 3 bouquets. The answer is 3.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
    +
    +Output: -1
    +
    +Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
    +
    +Output: 12
    +
    +Explanation: We need 2 bouquets each should have 3 flowers.
    +
    +Here's the garden after the 7 and 12 days:
    +
    +After day 7: [x, x, x, x, _, x, x]
    +
    +We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
    +
    +After day 12: [x, x, x, x, x, x, x]
    +
    +It is obvious that we can make two bouquets in different ways.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: bloomDay = [1000000000,1000000000], m = 1, k = 1
    +
    +Output: 1000000000
    +
    +Explanation: You need to wait 1000000000 days to have a flower ready for a bouquet.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
    +
    +Output: 9
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • bloomDay.length == n
    • +
    • 1 <= n <= 10^5
    • +
    • 1 <= bloomDay[i] <= 10^9
    • +
    • 1 <= m <= 10^6
    • +
    • 1 <= k <= n
    • +
    + +## Solutions + +Quickly locate using binary search. + + + +### **Python3** + +```python +class Solution: + def minDays(self, bloomDay: List[int], m: int, k: int) -> int: + if m * k > len(bloomDay): + return -1 + + def check(day: int) -> bool: + cnt = cur = 0 + for bd in bloomDay: + cur = cur + 1 if bd <= day else 0 + if cur == k: + cnt += 1 + cur = 0 + return cnt >= m + + left, right = min(bloomDay), max(bloomDay) + while left < right: + mid = (left + right) >> 1 + if check(mid): + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int minDays(int[] bloomDay, int m, int k) { + if (m * k > bloomDay.length) { + return -1; + } + int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; + for (int bd : bloomDay) { + min = Math.min(min, bd); + max = Math.max(max, bd); + } + int left = min, right = max; + while (left < right) { + int mid = (left + right) >>> 1; + if (check(bloomDay, m, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean check(int[] bloomDay, int m, int k, int day) { + int cnt = 0, cur = 0; + for (int bd : bloomDay) { + cur = bd <= day ? cur + 1 : 0; + if (cur == k) { + cnt++; + cur = 0; + } + } + return cnt >= m; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minDays(vector& bloomDay, int m, int k) { + if (m * k > bloomDay.size()) { + return -1; + } + int mi = INT_MIN, mx = INT_MAX; + for (int& bd : bloomDay) { + mi = min(mi, bd); + mx = max(mx, bd); + } + int left = mi, right = mx; + while (left < right) { + int mid = left + right >> 1; + if (check(bloomDay, m, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + bool check(vector& bloomDay, int m, int k, int day) { + int cnt = 0, cur = 0; + for (int& bd : bloomDay) { + cur = bd <= day ? cur + 1 : 0; + if (cur == k) { + ++cnt; + cur = 0; + } + } + return cnt >= m; + } +}; +``` + +### **Go** + +```go +func minDays(bloomDay []int, m int, k int) int { + if m*k > len(bloomDay) { + return -1 + } + mi, mx := 0, 1000000000 + for _, bd := range bloomDay { + mi = min(mi, bd) + mx = max(mx, bd) + } + left, right := mi, mx + for left < right { + mid := (left + right) >> 1 + if check(bloomDay, m, k, mid) { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func check(bloomDay []int, m, k, day int) bool { + cnt, cur := 0, 0 + for _, bd := range bloomDay { + if bd <= day { + cur++ + } else { + cur = 0 + } + if cur == k { + cnt++ + cur = 0 + } + } + return cnt >= m +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md b/assets/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md new file mode 100644 index 00000000..94a74644 --- /dev/null +++ b/assets/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md @@ -0,0 +1,99 @@ +# [1483. Kth Ancestor of a Tree Node](https://leetcode.com/problems/kth-ancestor-of-a-tree-node) + + + +## Description + +

    You are given a tree with n nodes numbered from 0 to n-1 in the form of a parent array where parent[i] is the parent of node i. The root of the tree is node 0.

    + + + +

    Implement the function getKthAncestor(int node, int k) to return the k-th ancestor of the given node. If there is no such ancestor, return -1.

    + + + +

    The k-th ancestor of a tree node is the k-th node in the path from that node to the root.

    + + + +

     

    + + + +

    Example:

    + + + +

    + + + +
    +
    +Input:
    +
    +["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"]
    +
    +[[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]
    +
    +
    +
    +Output:
    +
    +[null,1,0,-1]
    +
    +
    +
    +Explanation:
    +
    +TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
    +
    +
    +
    +treeAncestor.getKthAncestor(3, 1);  // returns 1 which is the parent of 3
    +
    +treeAncestor.getKthAncestor(5, 2);  // returns 0 which is the grandparent of 5
    +
    +treeAncestor.getKthAncestor(6, 3);  // returns -1 because there is no such ancestor
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= k <= n <= 5*10^4
    • +
    • parent[0] == -1 indicating that 0 is the root node.
    • +
    • 0 <= parent[i] < n for all 0 < i < n
    • +
    • 0 <= node < n
    • +
    • There will be at most 5*10^4 queries.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1483.Kth Ancestor of a Tree Node/images/1528_ex1.png b/assets/1400-1499/1483.Kth Ancestor of a Tree Node/images/1528_ex1.png new file mode 100644 index 00000000..1e7c772e Binary files /dev/null and b/assets/1400-1499/1483.Kth Ancestor of a Tree Node/images/1528_ex1.png differ diff --git a/assets/1400-1499/1484.Group Sold Products By The Date/README_EN.md b/assets/1400-1499/1484.Group Sold Products By The Date/README_EN.md new file mode 100644 index 00000000..25402b7f --- /dev/null +++ b/assets/1400-1499/1484.Group Sold Products By The Date/README_EN.md @@ -0,0 +1,115 @@ +# [1484. Group Sold Products By The Date](https://leetcode.com/problems/group-sold-products-by-the-date) + + + +## Description + +

    Table Activities:

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| sell_date   | date    |
    +
    +| product     | varchar |
    +
    ++-------------+---------+
    +
    +There is no primary key for this table, it may contains duplicates.
    +
    +Each row of this table contains the product name and the date it was sold in a market.
    + + + +

     

    + + + +

    Write an SQL query to find for each date, the number of distinct products sold and their names.

    + + + +

    The sold-products names for each date should be sorted lexicographically. 

    + + + +

    Return the result table ordered by sell_date.

    + + + +

    The query result format is in the following example.

    + + + +
    +
    +Activities table:
    +
    ++------------+-------------+
    +
    +| sell_date  | product     |
    +
    ++------------+-------------+
    +
    +| 2020-05-30 | Headphone   |
    +
    +| 2020-06-01 | Pencil      |
    +
    +| 2020-06-02 | Mask        |
    +
    +| 2020-05-30 | Basketball  |
    +
    +| 2020-06-01 | Bible       |
    +
    +| 2020-06-02 | Mask        |
    +
    +| 2020-05-30 | T-Shirt     |
    +
    ++------------+-------------+
    +
    +
    +
    +Result table:
    +
    ++------------+----------+------------------------------+
    +
    +| sell_date  | num_sold | products                     |
    +
    ++------------+----------+------------------------------+
    +
    +| 2020-05-30 | 3        | Basketball,Headphone,T-shirt |
    +
    +| 2020-06-01 | 2        | Bible,Pencil                 |
    +
    +| 2020-06-02 | 1        | Mask                         |
    +
    ++------------+----------+------------------------------+
    +
    +For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by comma.
    +
    +For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by comma.
    +
    +For 2020-06-02, Sold item is (Masks), we just return it.
    +
    +
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md new file mode 100644 index 00000000..566d1fcb --- /dev/null +++ b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md @@ -0,0 +1,92 @@ +# [1485. Clone Binary Tree With Random Pointer](https://leetcode.com/problems/clone-binary-tree-with-random-pointer) + + + +## Description + +

    A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null.

    + +

    Return a deep copy of the tree.

    + +

    The tree is represented in the same input/output way as normal binary trees where each node is represented as a pair of [val, random_index] where:

    + +
      +
    • val: an integer representing Node.val
    • +
    • random_index: the index of the node (in the input) where the random pointer points to, or null if it does not point to any node.
    • +
    + +

    You will be given the tree in class Node and you should return the cloned tree in class NodeCopy.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [[1,null],null,[4,3],[7,0]]
    +Output: [[1,null],null,[4,3],[7,0]]
    +Explanation: The original binary tree is [1,null,4,7].
    +The random pointer of node one is null, so it is represented as [1, null].
    +The random pointer of node 4 is node 7, so it is represented as [4, 3] where 3 is the index of node 7 in the tree array.
    +The random pointer of node 7 is node 1, so it is represented as [7, 0] where 0 is the index of node 1 in the tree array
    +
    + +

    Example 2:

    + +
    +Input: root = [[1,4],null,[1,0],null,[1,5],[1,5]]
    +Output: [[1,4],null,[1,0],null,[1,5],[1,5]]
    +Explanation: The random pointer of a node can be the node itself.
    +
    + +

    Example 3:

    + +
    +Input: root = [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
    +Output: [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
    +
    + +

    Example 4:

    + +
    +Input: root = []
    +Output: []
    +
    + +

    Example 5:

    + +
    +Input: root = [[1,null],null,[2,null],null,[1,null]]
    +Output: [[1,null],null,[2,null],null,[1,null]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [0, 1000].
    • +
    • Each node's value is between [1, 10^6].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e1.png b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e1.png new file mode 100644 index 00000000..b95e6cd7 Binary files /dev/null and b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e1.png differ diff --git a/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e2.png b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e2.png new file mode 100644 index 00000000..c8f819d3 Binary files /dev/null and b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e2.png differ diff --git a/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e3.png b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e3.png new file mode 100644 index 00000000..1a7ae7fd Binary files /dev/null and b/assets/1400-1499/1485.Clone Binary Tree With Random Pointer/images/e3.png differ diff --git a/assets/1400-1499/1486.XOR Operation in an Array/README_EN.md b/assets/1400-1499/1486.XOR Operation in an Array/README_EN.md new file mode 100644 index 00000000..248ddacf --- /dev/null +++ b/assets/1400-1499/1486.XOR Operation in an Array/README_EN.md @@ -0,0 +1,120 @@ +# [1486. XOR Operation in an Array](https://leetcode.com/problems/xor-operation-in-an-array) + + + +## Description + +

    Given an integer n and an integer start.

    + + + +

    Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length.

    + + + +

    Return the bitwise XOR of all elements of nums.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 5, start = 0
    +
    +Output: 8
    +
    +Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
    +
    +Where "^" corresponds to bitwise XOR operator.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 4, start = 3
    +
    +Output: 8
    +
    +Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 1, start = 7
    +
    +Output: 7
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 10, start = 5
    +
    +Output: 2
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 1000
    • +
    • 0 <= start <= 1000
    • +
    • n == nums.length
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def xorOperation(self, n: int, start: int) -> int: + res = 0 + for i in range(n): + res ^= (start + (i << 1)) + return res +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1487.Making File Names Unique/README_EN.md b/assets/1400-1499/1487.Making File Names Unique/README_EN.md new file mode 100644 index 00000000..655ca06d --- /dev/null +++ b/assets/1400-1499/1487.Making File Names Unique/README_EN.md @@ -0,0 +1,151 @@ +# [1487. Making File Names Unique](https://leetcode.com/problems/making-file-names-unique) + + + +## Description + +

    Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].

    + + + +

    Since two files cannot have the same name, if you enter a folder name which is previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.

    + + + +

    Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: names = ["pes","fifa","gta","pes(2019)"]
    +
    +Output: ["pes","fifa","gta","pes(2019)"]
    +
    +Explanation: Let's see how the file system creates folder names:
    +
    +"pes" --> not assigned before, remains "pes"
    +
    +"fifa" --> not assigned before, remains "fifa"
    +
    +"gta" --> not assigned before, remains "gta"
    +
    +"pes(2019)" --> not assigned before, remains "pes(2019)"
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: names = ["gta","gta(1)","gta","avalon"]
    +
    +Output: ["gta","gta(1)","gta(2)","avalon"]
    +
    +Explanation: Let's see how the file system creates folder names:
    +
    +"gta" --> not assigned before, remains "gta"
    +
    +"gta(1)" --> not assigned before, remains "gta(1)"
    +
    +"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"
    +
    +"avalon" --> not assigned before, remains "avalon"
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]
    +
    +Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]
    +
    +Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)".
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: names = ["wano","wano","wano","wano"]
    +
    +Output: ["wano","wano(1)","wano(2)","wano(3)"]
    +
    +Explanation: Just increase the value of k each time you create folder "wano".
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: names = ["kaido","kaido(1)","kaido","kaido(1)"]
    +
    +Output: ["kaido","kaido(1)","kaido(2)","kaido(1)(1)"]
    +
    +Explanation: Please note that system adds the suffix (k) to current name even it contained the same suffix before.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= names.length <= 5 * 10^4
    • +
    • 1 <= names[i].length <= 20
    • +
    • names[i] consists of lower case English letters, digits and/or round brackets.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1488.Avoid Flood in The City/README_EN.md b/assets/1400-1499/1488.Avoid Flood in The City/README_EN.md new file mode 100644 index 00000000..0af148cc --- /dev/null +++ b/assets/1400-1499/1488.Avoid Flood in The City/README_EN.md @@ -0,0 +1,111 @@ +# [1488. Avoid Flood in The City](https://leetcode.com/problems/avoid-flood-in-the-city) + + + +## Description + +

    Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.

    + +

    Given an integer array rains where:

    + +
      +
    • rains[i] > 0 means there will be rains over the rains[i] lake.
    • +
    • rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
    • +
    + +

    Return an array ans where:

    + +
      +
    • ans.length == rains.length
    • +
    • ans[i] == -1 if rains[i] > 0.
    • +
    • ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
    • +
    + +

    If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.

    + +

    Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)

    + +

     

    +

    Example 1:

    + +
    +Input: rains = [1,2,3,4]
    +Output: [-1,-1,-1,-1]
    +Explanation: After the first day full lakes are [1]
    +After the second day full lakes are [1,2]
    +After the third day full lakes are [1,2,3]
    +After the fourth day full lakes are [1,2,3,4]
    +There's no day to dry any lake and there is no flood in any lake.
    +
    + +

    Example 2:

    + +
    +Input: rains = [1,2,0,0,2,1]
    +Output: [-1,-1,2,1,-1,-1]
    +Explanation: After the first day full lakes are [1]
    +After the second day full lakes are [1,2]
    +After the third day, we dry lake 2. Full lakes are [1]
    +After the fourth day, we dry lake 1. There is no full lakes.
    +After the fifth day, full lakes are [2].
    +After the sixth day, full lakes are [1,2].
    +It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
    +
    + +

    Example 3:

    + +
    +Input: rains = [1,2,0,1,2]
    +Output: []
    +Explanation: After the second day, full lakes are  [1,2]. We have to dry one lake in the third day.
    +After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
    +
    + +

    Example 4:

    + +
    +Input: rains = [69,0,0,0,69]
    +Output: [-1,69,1,1,-1]
    +Explanation: Any solution on one of the forms [-1,69,x,y,-1], [-1,x,69,y,-1] or [-1,x,y,69,-1] is acceptable where 1 <= x,y <= 10^9
    +
    + +

    Example 5:

    + +
    +Input: rains = [10,20,20]
    +Output: []
    +Explanation: It will rain over lake 20 two consecutive days. There is no chance to dry any lake.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= rains.length <= 105
    • +
    • 0 <= rains[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md new file mode 100644 index 00000000..4554f100 --- /dev/null +++ b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md @@ -0,0 +1,73 @@ +# [1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree](https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree) + + + +## Description + +

    Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.

    + +

    Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.

    + +

    Note that you can return the indices of the edges in any order.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]
    +Output: [[0,1],[2,3,4,5]]
    +Explanation: The figure above describes the graph.
    +The following figure shows all the possible MSTs:
    +
    +Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
    +The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]
    +Output: [[],[0,1,2,3]]
    +Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • 1 <= edges.length <= min(200, n * (n - 1) / 2)
    • +
    • edges[i].length == 3
    • +
    • 0 <= ai < bi < n
    • +
    • 1 <= weighti <= 1000
    • +
    • All pairs (ai, bi) are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/ex1.png b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/ex1.png new file mode 100644 index 00000000..2f6afd34 Binary files /dev/null and b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/ex1.png differ diff --git a/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/ex2.png b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/ex2.png new file mode 100644 index 00000000..b18a66dd Binary files /dev/null and b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/ex2.png differ diff --git a/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/msts.png b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/msts.png new file mode 100644 index 00000000..6b3d7d83 Binary files /dev/null and b/assets/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/images/msts.png differ diff --git a/assets/1400-1499/1490.Clone N-ary Tree/README_EN.md b/assets/1400-1499/1490.Clone N-ary Tree/README_EN.md new file mode 100644 index 00000000..47e1aeb8 --- /dev/null +++ b/assets/1400-1499/1490.Clone N-ary Tree/README_EN.md @@ -0,0 +1,72 @@ +# [1490. Clone N-ary Tree](https://leetcode.com/problems/clone-n-ary-tree) + + + +## Description + +

    Given a root of an N-ary tree, return a deep copy (clone) of the tree.

    + +

    Each node in the n-ary tree contains a val (int) and a list (List[Node]) of its children.

    + +
    +class Node {
    +    public int val;
    +    public List<Node> children;
    +}
    +
    + +

    Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

    + +

    Follow up: Can your solution work for the graph problem?

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [1,null,3,2,4,null,5,6]
    +Output: [1,null,3,2,4,null,5,6]
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The depth of the n-ary tree is less than or equal to 1000.
    • +
    • The total number of nodes is between [0, 10^4].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1490.Clone N-ary Tree/images/narytreeexample.png b/assets/1400-1499/1490.Clone N-ary Tree/images/narytreeexample.png new file mode 100644 index 00000000..c8d6a81f Binary files /dev/null and b/assets/1400-1499/1490.Clone N-ary Tree/images/narytreeexample.png differ diff --git a/assets/1400-1499/1490.Clone N-ary Tree/images/sample_4_964.png b/assets/1400-1499/1490.Clone N-ary Tree/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/1400-1499/1490.Clone N-ary Tree/images/sample_4_964.png differ diff --git a/assets/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md b/assets/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md new file mode 100644 index 00000000..d66d0d39 --- /dev/null +++ b/assets/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md @@ -0,0 +1,116 @@ +# [1491. Average Salary Excluding the Minimum and Maximum Salary](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary) + + + +## Description + +

    Given an array of unique integers salary where salary[i] is the salary of the employee i.

    + + + +

    Return the average salary of employees excluding the minimum and maximum salary.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: salary = [4000,3000,1000,2000]
    +
    +Output: 2500.00000
    +
    +Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
    +
    +Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: salary = [1000,2000,3000]
    +
    +Output: 2000.00000
    +
    +Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
    +
    +Average salary excluding minimum and maximum salary is (2000)/1= 2000
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: salary = [6000,5000,4000,3000,2000,1000]
    +
    +Output: 3500.00000
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: salary = [8000,9000,2000,3000,6000,1000]
    +
    +Output: 4750.00000
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 3 <= salary.length <= 100
    • +
    • 10^3 <= salary[i] <= 10^6
    • +
    • salary[i] is unique.
    • +
    • Answers within 10^-5 of the actual value will be accepted as correct.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1492.The kth Factor of n/README_EN.md b/assets/1400-1499/1492.The kth Factor of n/README_EN.md new file mode 100644 index 00000000..076c533d --- /dev/null +++ b/assets/1400-1499/1492.The kth Factor of n/README_EN.md @@ -0,0 +1,133 @@ +# [1492. The kth Factor of n](https://leetcode.com/problems/the-kth-factor-of-n) + + + +## Description + +

    Given two positive integers n and k.

    + + + +

    A factor of an integer n is defined as an integer i where n % i == 0.

    + + + +

    Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 12, k = 3
    +
    +Output: 3
    +
    +Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 7, k = 2
    +
    +Output: 7
    +
    +Explanation: Factors list is [1, 7], the 2nd factor is 7.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 4, k = 4
    +
    +Output: -1
    +
    +Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 1, k = 1
    +
    +Output: 1
    +
    +Explanation: Factors list is [1], the 1st factor is 1.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 1000, k = 3
    +
    +Output: 4
    +
    +Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000].
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= k <= n <= 1000
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md b/assets/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md new file mode 100644 index 00000000..d18f13a8 --- /dev/null +++ b/assets/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md @@ -0,0 +1,80 @@ +# [1493. Longest Subarray of 1's After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element) + + + +## Description + +

    Given a binary array nums, you should delete one element from it.

    + +

    Return the size of the longest non-empty subarray containing only 1's in the resulting array.

    + +

    Return 0 if there is no such subarray.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,1,0,1]
    +Output: 3
    +Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
    + +

    Example 2:

    + +
    +Input: nums = [0,1,1,1,0,1,1,0,1]
    +Output: 5
    +Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
    + +

    Example 3:

    + +
    +Input: nums = [1,1,1]
    +Output: 2
    +Explanation: You must delete one element.
    + +

    Example 4:

    + +
    +Input: nums = [1,1,0,0,1,1,1,0,1]
    +Output: 4
    +
    + +

    Example 5:

    + +
    +Input: nums = [0,0,0]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • nums[i] is either 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1494.Parallel Courses II/README_EN.md b/assets/1400-1499/1494.Parallel Courses II/README_EN.md new file mode 100644 index 00000000..62bac0ff --- /dev/null +++ b/assets/1400-1499/1494.Parallel Courses II/README_EN.md @@ -0,0 +1,78 @@ +# [1494. Parallel Courses II](https://leetcode.com/problems/parallel-courses-ii) + + + +## Description + +

    Given the integer n representing the number of courses at some university labeled from 1 to n, and the array dependencies where dependencies[i] = [xi, yi] represents a prerequisite relationship, that is, the course xi must be taken before the course yi. Also, you are given the integer k.

    + +

    In one semester you can take at most k courses as long as you have taken all the prerequisites for the courses you are taking.

    + +

    Return the minimum number of semesters to take all courses. It is guaranteed that you can take all courses in some way.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2
    +Output: 3 
    +Explanation: The figure above represents the given graph. In this case we can take courses 2 and 3 in the first semester, then take course 1 in the second semester and finally take course 4 in the third semester.
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2
    +Output: 4 
    +Explanation: The figure above represents the given graph. In this case one optimal way to take all courses is: take courses 2 and 3 in the first semester and take course 4 in the second semester, then take course 1 in the third semester and finally take course 5 in the fourth semester.
    +
    + +

    Example 3:

    + +
    +Input: n = 11, dependencies = [], k = 2
    +Output: 6
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 15
    • +
    • 1 <= k <= n
    • +
    • 0 <= dependencies.length <= n * (n-1) / 2
    • +
    • dependencies[i].length == 2
    • +
    • 1 <= xi, yi <= n
    • +
    • xi != yi
    • +
    • All prerequisite relationships are distinct, that is, dependencies[i] != dependencies[j].
    • +
    • The given graph is a directed acyclic graph.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1494.Parallel Courses II/images/leetcode_parallel_courses_1.png b/assets/1400-1499/1494.Parallel Courses II/images/leetcode_parallel_courses_1.png new file mode 100644 index 00000000..c5235e06 Binary files /dev/null and b/assets/1400-1499/1494.Parallel Courses II/images/leetcode_parallel_courses_1.png differ diff --git a/assets/1400-1499/1494.Parallel Courses II/images/leetcode_parallel_courses_2.png b/assets/1400-1499/1494.Parallel Courses II/images/leetcode_parallel_courses_2.png new file mode 100644 index 00000000..05b1ba20 Binary files /dev/null and b/assets/1400-1499/1494.Parallel Courses II/images/leetcode_parallel_courses_2.png differ diff --git a/assets/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md b/assets/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md new file mode 100644 index 00000000..c7db73bf --- /dev/null +++ b/assets/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md @@ -0,0 +1,187 @@ +# [1495. Friendly Movies Streamed Last Month](https://leetcode.com/problems/friendly-movies-streamed-last-month) + + + +## Description + +

    Table: TVProgram

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| program_date  | date    |
    +
    +| content_id    | int     |
    +
    +| channel       | varchar |
    +
    ++---------------+---------+
    +
    +(program_date, content_id) is the primary key for this table.
    +
    +This table contains information of the programs on the TV.
    +
    +content_id is the id of the program in some channel on the TV.
    + + + +

     

    + + + +

    Table: Content

    + + + +
    +
    ++------------------+---------+
    +
    +| Column Name      | Type    |
    +
    ++------------------+---------+
    +
    +| content_id       | varchar |
    +
    +| title            | varchar |
    +
    +| Kids_content     | enum    |
    +
    +| content_type     | varchar |
    +
    ++------------------+---------+
    +
    +content_id is the primary key for this table.
    +
    +Kids_content is an enum that takes one of the values ('Y', 'N') where: 
    +
    +'Y' means is content for kids otherwise 'N' is not content for kids.
    +
    +content_type is the category of the content as movies, series, etc.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the distinct titles of the kid-friendly movies streamed in June 2020.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example.

    + + + +

     

    + + + +
    +
    +TVProgram table:
    +
    ++--------------------+--------------+-------------+
    +
    +| program_date       | content_id   | channel     |
    +
    ++--------------------+--------------+-------------+
    +
    +| 2020-06-10 08:00   | 1            | LC-Channel  |
    +
    +| 2020-05-11 12:00   | 2            | LC-Channel  |
    +
    +| 2020-05-12 12:00   | 3            | LC-Channel  |
    +
    +| 2020-05-13 14:00   | 4            | Disney Ch   |
    +
    +| 2020-06-18 14:00   | 4            | Disney Ch   |
    +
    +| 2020-07-15 16:00   | 5            | Disney Ch   |
    +
    ++--------------------+--------------+-------------+
    +
    +
    +
    +Content table:
    +
    ++------------+----------------+---------------+---------------+
    +
    +| content_id | title          | Kids_content  | content_type  |
    +
    ++------------+----------------+---------------+---------------+
    +
    +| 1          | Leetcode Movie | N             | Movies        |
    +
    +| 2          | Alg. for Kids  | Y             | Series        |
    +
    +| 3          | Database Sols  | N             | Series        |
    +
    +| 4          | Aladdin        | Y             | Movies        |
    +
    +| 5          | Cinderella     | Y             | Movies        |
    +
    ++------------+----------------+---------------+---------------+
    +
    +
    +
    +Result table:
    +
    ++--------------+
    +
    +| title        |
    +
    ++--------------+
    +
    +| Aladdin      |
    +
    ++--------------+
    +
    +"Leetcode Movie" is not a content for kids.
    +
    +"Alg. for Kids" is not a movie.
    +
    +"Database Sols" is not a movie
    +
    +"Alladin" is a movie, content for kids and was streamed in June 2020.
    +
    +"Cinderella" was not streamed in June 2020.
    +
    +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1496.Path Crossing/README_EN.md b/assets/1400-1499/1496.Path Crossing/README_EN.md new file mode 100644 index 00000000..cdb0be9b --- /dev/null +++ b/assets/1400-1499/1496.Path Crossing/README_EN.md @@ -0,0 +1,62 @@ +# [1496. Path Crossing](https://leetcode.com/problems/path-crossing) + + + +## Description + +

    Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.

    + +

    Return True if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False otherwise.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: path = "NES"
    +Output: false 
    +Explanation: Notice that the path doesn't cross any point more than once.
    +
    + +

    Example 2:

    + +

    + +
    +Input: path = "NESWW"
    +Output: true
    +Explanation: Notice that the path visits the origin twice.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= path.length <= 10^4
    • +
    • path will only consist of characters in {'N', 'S', 'E', 'W}
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1496.Path Crossing/images/screen-shot-2020-06-10-at-123843-pm.png b/assets/1400-1499/1496.Path Crossing/images/screen-shot-2020-06-10-at-123843-pm.png new file mode 100644 index 00000000..d9c64818 Binary files /dev/null and b/assets/1400-1499/1496.Path Crossing/images/screen-shot-2020-06-10-at-123843-pm.png differ diff --git a/assets/1400-1499/1496.Path Crossing/images/screen-shot-2020-06-10-at-123929-pm.png b/assets/1400-1499/1496.Path Crossing/images/screen-shot-2020-06-10-at-123929-pm.png new file mode 100644 index 00000000..fc4046d6 Binary files /dev/null and b/assets/1400-1499/1496.Path Crossing/images/screen-shot-2020-06-10-at-123929-pm.png differ diff --git a/assets/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md b/assets/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md new file mode 100644 index 00000000..5f8e180c --- /dev/null +++ b/assets/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md @@ -0,0 +1,128 @@ +# [1497. Check If Array Pairs Are Divisible by k](https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k) + + + +## Description + +

    Given an array of integers arr of even length n and an integer k.

    + +

    We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.

    + +

    Return True If you can find a way to do that or False otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
    +Output: true
    +Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,2,3,4,5,6], k = 7
    +Output: true
    +Explanation: Pairs are (1,6),(2,5) and(3,4).
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,2,3,4,5,6], k = 10
    +Output: false
    +Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
    +
    + +

    Example 4:

    + +
    +Input: arr = [-10,10], k = 2
    +Output: true
    +
    + +

    Example 5:

    + +
    +Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • arr.length == n
    • +
    • 1 <= n <= 105
    • +
    • n is even.
    • +
    • -109 <= arr[i] <= 109
    • +
    • 1 <= k <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isPathCrossing(self, path: str) -> bool: + x = y = 0 + visited = set() + visited.add('0.0') + for c in path: + if c == 'N': + y += 1 + elif c == 'S': + y -= 1 + elif c == 'E': + x += 1 + else: + x -= 1 + pos = f'{x}.{y}' + if pos in visited: + return True + visited.add(pos) + return False +``` + +### **Java** + +```java +class Solution { + public boolean isPathCrossing(String path) { + Set visited = new HashSet<>(); + visited.add("0.0"); + int x = 0, y = 0; + for (int i = 0; i < path.length(); ++i) { + char c = path.charAt(i); + if (c == 'N') { + ++y; + } else if (c == 'S') { + --y; + } else if (c == 'E') { + ++x; + } else { + --x; + } + String pos = x + "." + y; + if (visited.contains(pos)) { + return true; + } + visited.add(pos); + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md b/assets/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md new file mode 100644 index 00000000..7e38960a --- /dev/null +++ b/assets/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md @@ -0,0 +1,80 @@ +# [1498. Number of Subsequences That Satisfy the Given Sum Condition](https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition) + + + +## Description + +

    Given an array of integers nums and an integer target.

    + +

    Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,5,6,7], target = 9
    +Output: 4
    +Explanation: There are 4 subsequences that satisfy the condition.
    +[3] -> Min value + max value <= target (3 + 3 <= 9)
    +[3,5] -> (3 + 5 <= 9)
    +[3,5,6] -> (3 + 6 <= 9)
    +[3,6] -> (3 + 6 <= 9)
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,3,6,8], target = 10
    +Output: 6
    +Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
    +[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
    + +

    Example 3:

    + +
    +Input: nums = [2,3,3,4,6,7], target = 12
    +Output: 61
    +Explanation: There are 63 non-empty subsequences, two of them don't satisfy the condition ([6,7], [7]).
    +Number of valid subsequences (63 - 2 = 61).
    +
    + +

    Example 4:

    + +
    +Input: nums = [5,2,4,1,7,6,8], target = 16
    +Output: 127
    +Explanation: All non-empty subset satisfy the condition (2^7 - 1) = 127
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 106
    • +
    • 1 <= target <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1400-1499/1499.Max Value of Equation/README_EN.md b/assets/1400-1499/1499.Max Value of Equation/README_EN.md new file mode 100644 index 00000000..10074f6d --- /dev/null +++ b/assets/1400-1499/1499.Max Value of Equation/README_EN.md @@ -0,0 +1,63 @@ +# [1499. Max Value of Equation](https://leetcode.com/problems/max-value-of-equation) + + + +## Description + +

    Given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k.

    + +

    Find the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.

    + +

     

    +

    Example 1:

    + +
    +Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
    +Output: 4
    +Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
    +No other pairs satisfy the condition, so we return the max of 4 and 1.
    + +

    Example 2:

    + +
    +Input: points = [[0,0],[3,0],[9,2]], k = 3
    +Output: 3
    +Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= points.length <= 10^5
    • +
    • points[i].length == 2
    • +
    • -10^8 <= points[i][0], points[i][1] <= 10^8
    • +
    • 0 <= k <= 2 * 10^8
    • +
    • points[i][0] < points[j][0] for all 1 <= i < j <= points.length
    • +
    • xi form a strictly increasing sequence.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1500.Design a File Sharing System/README_EN.md b/assets/1500-1599/1500.Design a File Sharing System/README_EN.md new file mode 100644 index 00000000..2569d77a --- /dev/null +++ b/assets/1500-1599/1500.Design a File Sharing System/README_EN.md @@ -0,0 +1,244 @@ +# [1500. Design a File Sharing System](https://leetcode.com/problems/design-a-file-sharing-system) + + + +## Description + +

    We will use a file-sharing system to share a very large file which consists of m small chunks with IDs from 1 to m.

    + + + +

    When users join the system, the system should assign a unique ID to them. The unique ID should be used once for each user, but when a user leaves the system, the ID can be reused again.

    + + + +

    Users can request a certain chunk of the file, the system should return a list of IDs of all the users who own this chunk. If the user receive a non-empty list of IDs, they receive the requested chunk successfully.

    + + + +


    + +Implement the FileSharing class:

    + + + +
      +
    • FileSharing(int m) Initializes the object with a file of m chunks.
    • +
    • int join(int[] ownedChunks): A new user joined the system owning some chunks of the file, the system should assign an id to the user which is the smallest positive integer not taken by any other user. Return the assigned id.
    • +
    • void leave(int userID): The user with userID will leave the system, you cannot take file chunks from them anymore.
    • +
    • int[] request(int userID, int chunkID): The user userID requested the file chunk with chunkID. Return a list of the IDs of all users that own this chunk sorted in ascending order.
    • +
    + + + +

     

    + + + +

    Follow-ups:

    + + + +
      +
    • What happens if the system identifies the user by their IP address instead of their unique ID and users disconnect and connect from the system with the same IP?
    • +
    • If the users in the system join and leave the system frequently without requesting any chunks, will your solution still be efficient?
    • +
    • If all each user join the system one time, request all files and then leave, will your solution still be efficient?
    • +
    • If the system will be used to share n files where the ith file consists of m[i], what are the changes you have to do?
    • +
    + + + +

     

    + +

    Example:

    + + + +
    +
    +Input:
    +
    +["FileSharing","join","join","join","request","request","leave","request","leave","join"]
    +
    +[[4],[[1,2]],[[2,3]],[[4]],[1,3],[2,2],[1],[2,1],[2],[[]]]
    +
    +Output:
    +
    +[null,1,2,3,[2],[1,2],null,[],null,1]
    +
    +Explanation:
    +
    +FileSharing fileSharing = new FileSharing(4); // We use the system to share a file of 4 chunks.
    +
    +
    +
    +fileSharing.join([1, 2]);    // A user who has chunks [1,2] joined the system, assign id = 1 to them and return 1.
    +
    +
    +
    +fileSharing.join([2, 3]);    // A user who has chunks [2,3] joined the system, assign id = 2 to them and return 2.
    +
    +
    +
    +fileSharing.join([4]);       // A user who has chunk [4] joined the system, assign id = 3 to them and return 3.
    +
    +
    +
    +fileSharing.request(1, 3);   // The user with id = 1 requested the third file chunk, as only the user with id = 2 has the file, return [2] . Notice that user 1 now has chunks [1,2,3].
    +
    +
    +
    +fileSharing.request(2, 2);   // The user with id = 2 requested the second file chunk, users with ids [1,2] have this chunk, thus we return [1,2].
    +
    +
    +
    +fileSharing.leave(1);        // The user with id = 1 left the system, all the file chunks with them are no longer available for other users.
    +
    +
    +
    +fileSharing.request(2, 1);   // The user with id = 2 requested the first file chunk, no one in the system has this chunk, we return empty list [].
    +
    +
    +
    +fileSharing.leave(2);        // The user with id = 2 left the system.
    +
    +
    +
    +fileSharing.join([]);        // A user who doesn't have any chunks joined the system, assign id = 1 to them and return 1. Notice that ids 1 and 2 are free and we can reuse them.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= m <= 10^5
    • +
    • 0 <= ownedChunks.length <= min(100, m)
    • +
    • 1 <= ownedChunks[i] <= m
    • +
    • Values of ownedChunks are unique.
    • +
    • 1 <= chunkID <= m
    • +
    • userID is guaranteed to be a user in the system if you assign the IDs correctly
    • +
    • At most 10^4 calls will be made to joinleave and request.
    • +
    • Each call to leave will have a matching call for join.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class FileSharing: + + def __init__(self, m: int): + self.cur = 0 + self.chunks = m + self.reused = [] + self.user_chunks = collections.defaultdict(set) + + def join(self, ownedChunks: List[int]) -> int: + if self.reused: + userID = heapq.heappop(self.reused) + else: + self.cur += 1 + userID = self.cur + self.user_chunks[userID] = set(ownedChunks) + return userID + + def leave(self, userID: int) -> None: + heapq.heappush(self.reused, userID) + self.user_chunks.pop(userID) + + def request(self, userID: int, chunkID: int) -> List[int]: + if chunkID < 1 or chunkID > self.chunks: + return [] + res = [] + for k, v in self.user_chunks.items(): + if chunkID in v: + res.append(k) + if res: + self.user_chunks[userID].add(chunkID) + return sorted(res) + +# Your FileSharing object will be instantiated and called as such: +# obj = FileSharing(m) +# param_1 = obj.join(ownedChunks) +# obj.leave(userID) +# param_3 = obj.request(userID,chunkID) +``` + +### **Java** + +```java +class FileSharing { + private int chunks; + private int cur; + private TreeSet reused; + private TreeMap> userChunks; + + public FileSharing(int m) { + cur = 0; + chunks = m; + reused = new TreeSet<>(); + userChunks = new TreeMap<>(); + } + + public int join(List ownedChunks) { + int userID; + if (reused.isEmpty()) { + ++cur; + userID = cur; + } else { + userID = reused.pollFirst(); + } + userChunks.put(userID, new HashSet<>(ownedChunks)); + return userID; + } + + public void leave(int userID) { + reused.add(userID); + userChunks.remove(userID); + } + + public List request(int userID, int chunkID) { + if (chunkID < 1 || chunkID > chunks) { + return Collections.emptyList(); + } + List res = new ArrayList<>(); + for (Map.Entry> entry : userChunks.entrySet()) { + if (entry.getValue().contains(chunkID)) { + res.add(entry.getKey()); + } + } + if (!userChunks.containsKey(userID)) { + userChunks.put(userID, new HashSet<>()); + } + if (!res.isEmpty()) { + userChunks.get(userID).add(chunkID); + } + return res; + } +} + +/** + * Your FileSharing object will be instantiated and called as such: + * FileSharing obj = new FileSharing(m); + * int param_1 = obj.join(ownedChunks); + * obj.leave(userID); + * List param_3 = obj.request(userID,chunkID); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md b/assets/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md new file mode 100644 index 00000000..36fb001f --- /dev/null +++ b/assets/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md @@ -0,0 +1,129 @@ +# [1501. Countries You Can Safely Invest In](https://leetcode.com/problems/countries-you-can-safely-invest-in) + + + +## Description + +

    Table Person:

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| id             | int     |
    +| name           | varchar |
    +| phone_number   | varchar |
    ++----------------+---------+
    +id is the primary key for this table.
    +Each row of this table contains the name of a person and their phone number.
    +Phone number will be in the form 'xxx-yyyyyyy' where xxx is the country code (3 characters) and yyyyyyy is the phone number (7 characters) where x and y are digits. Both can contain leading zeros.
    +
    + +

     

    + +

    Table Country:

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| name           | varchar |
    +| country_code   | varchar |
    ++----------------+---------+
    +country_code is the primary key for this table.
    +Each row of this table contains the country name and its code. country_code will be in the form 'xxx' where x is digits.
    +
    + +

     

    + +

    Table Calls:

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| caller_id   | int  |
    +| callee_id   | int  |
    +| duration    | int  |
    ++-------------+------+
    +There is no primary key for this table, it may contain duplicates.
    +Each row of this table contains the caller id, callee id and the duration of the call in minutes. caller_id != callee_id
    +
    + +

     

    + +

    A telecommunications company wants to invest in new countries. The company intends to invest in the countries where the average call duration of the calls in this country is strictly greater than the global average call duration.

    + +

    Write an SQL query to find the countries where this company can invest.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Person table:
    ++----+----------+--------------+
    +| id | name     | phone_number |
    ++----+----------+--------------+
    +| 3  | Jonathan | 051-1234567  |
    +| 12 | Elvis    | 051-7654321  |
    +| 1  | Moncef   | 212-1234567  |
    +| 2  | Maroua   | 212-6523651  |
    +| 7  | Meir     | 972-1234567  |
    +| 9  | Rachel   | 972-0011100  |
    ++----+----------+--------------+
    +
    +Country table:
    ++----------+--------------+
    +| name     | country_code |
    ++----------+--------------+
    +| Peru     | 051          |
    +| Israel   | 972          |
    +| Morocco  | 212          |
    +| Germany  | 049          |
    +| Ethiopia | 251          |
    ++----------+--------------+
    +
    +Calls table:
    ++-----------+-----------+----------+
    +| caller_id | callee_id | duration |
    ++-----------+-----------+----------+
    +| 1         | 9         | 33       |
    +| 2         | 9         | 4        |
    +| 1         | 2         | 59       |
    +| 3         | 12        | 102      |
    +| 3         | 12        | 330      |
    +| 12        | 3         | 5        |
    +| 7         | 9         | 13       |
    +| 7         | 1         | 3        |
    +| 9         | 7         | 1        |
    +| 1         | 7         | 7        |
    ++-----------+-----------+----------+
    +
    +Result table:
    ++----------+
    +| country  |
    ++----------+
    +| Peru     |
    ++----------+
    +The average call duration for Peru is (102 + 102 + 330 + 330 + 5 + 5) / 6 = 145.666667
    +The average call duration for Israel is (33 + 4 + 13 + 13 + 3 + 1 + 1 + 7) / 8 = 9.37500
    +The average call duration for Morocco is (33 + 4 + 59 + 59 + 3 + 7) / 6 = 27.5000 
    +Global call duration average = (2 * (33 + 4 + 59 + 102 + 330 + 5 + 13 + 3 + 1 + 7)) / 20 = 55.70000
    +Since Peru is the only country where average call duration is greater than the global average, it's the only recommended country.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md b/assets/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md new file mode 100644 index 00000000..228e87e0 --- /dev/null +++ b/assets/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md @@ -0,0 +1,91 @@ +# [1502. Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence) + + + +## Description + +

    Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

    + +

    Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,5,1]
    +Output: true
    +Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,2,4]
    +Output: false
    +Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr.length <= 1000
    • +
    • -10^6 <= arr[i] <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + arr.sort() + for i in range(1, len(arr) - 1): + if (arr[i] << 1) != arr[i - 1] + arr[i + 1]: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + Arrays.sort(arr); + for (int i = 1; i < arr.length - 1; ++i) { + if ((arr[i] << 1) != arr[i - 1] + arr[i + 1]) { + return false; + } + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function(arr) { + arr.sort((a, b) => a - b); + for (let i = 1; i < arr.length - 1; i++) { + if ((arr[i] << 1) != (arr[i - 1] + arr[i + 1])) return false; + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md new file mode 100644 index 00000000..ba0fc1bf --- /dev/null +++ b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md @@ -0,0 +1,151 @@ +# [1503. Last Moment Before All Ants Fall Out of a Plank](https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank) + + + +## Description + +

    We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with speed 1 unit per second. Some of the ants move to the left, the other move to the right.

    + + + +

    When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions doesn't take any additional time.

    + + + +

    When an ant reaches one end of the plank at a time t, it falls out of the plank imediately.

    + + + +

    Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right. Return the moment when the last ant(s) fall out of the plank.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 4, left = [4,3], right = [0,1]
    +
    +Output: 4
    +
    +Explanation: In the image above:
    +
    +-The ant at index 0 is named A and going to the right.
    +
    +-The ant at index 1 is named B and going to the right.
    +
    +-The ant at index 3 is named C and going to the left.
    +
    +-The ant at index 4 is named D and going to the left.
    +
    +Note that the last moment when an ant was on the plank is t = 4 second, after that it falls imediately out of the plank. (i.e. We can say that at t = 4.0000000001, there is no ants on the plank).
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
    +
    +Output: 7
    +
    +Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 7, left = [0,1,2,3,4,5,6,7], right = []
    +
    +Output: 7
    +
    +Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 9, left = [5], right = [4]
    +
    +Output: 5
    +
    +Explanation: At t = 1 second, both ants will be at the same intial position but with different direction.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 6, left = [6], right = [0]
    +
    +Output: 6
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^4
    • +
    • 0 <= left.length <= n + 1
    • +
    • 0 <= left[i] <= n
    • +
    • 0 <= right.length <= n + 1
    • +
    • 0 <= right[i] <= n
    • +
    • 1 <= left.length + right.length <= n + 1
    • +
    • All values of left and right are unique, and each value can appear only in one of the two arrays.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants.jpg b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants.jpg new file mode 100644 index 00000000..88c4ead5 Binary files /dev/null and b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants.jpg differ diff --git a/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants2.jpg b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants2.jpg new file mode 100644 index 00000000..3a7aa260 Binary files /dev/null and b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants2.jpg differ diff --git a/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants3.jpg b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants3.jpg new file mode 100644 index 00000000..673c3b85 Binary files /dev/null and b/assets/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/images/images/ants3.jpg differ diff --git a/assets/1500-1599/1504.Count Submatrices With All Ones/README_EN.md b/assets/1500-1599/1504.Count Submatrices With All Ones/README_EN.md new file mode 100644 index 00000000..f80d5f6f --- /dev/null +++ b/assets/1500-1599/1504.Count Submatrices With All Ones/README_EN.md @@ -0,0 +1,143 @@ +# [1504. Count Submatrices With All Ones](https://leetcode.com/problems/count-submatrices-with-all-ones) + + + +## Description + +

    Given a rows * columns matrix mat of ones and zeros, return how many submatrices have all ones.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: mat = [[1,0,1],
    +
    +              [1,1,0],
    +
    +              [1,1,0]]
    +
    +Output: 13
    +
    +Explanation:
    +
    +There are 6 rectangles of side 1x1.
    +
    +There are 2 rectangles of side 1x2.
    +
    +There are 3 rectangles of side 2x1.
    +
    +There is 1 rectangle of side 2x2. 
    +
    +There is 1 rectangle of side 3x1.
    +
    +Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: mat = [[0,1,1,0],
    +
    +              [0,1,1,1],
    +
    +              [1,1,1,0]]
    +
    +Output: 24
    +
    +Explanation:
    +
    +There are 8 rectangles of side 1x1.
    +
    +There are 5 rectangles of side 1x2.
    +
    +There are 2 rectangles of side 1x3. 
    +
    +There are 4 rectangles of side 2x1.
    +
    +There are 2 rectangles of side 2x2. 
    +
    +There are 2 rectangles of side 3x1. 
    +
    +There is 1 rectangle of side 3x2. 
    +
    +Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: mat = [[1,1,1,1,1,1]]
    +
    +Output: 21
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: mat = [[1,0,1],[0,1,0],[1,0,1]]
    +
    +Output: 5
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= rows <= 150
    • +
    • 1 <= columns <= 150
    • +
    • 0 <= mat[i][j] <= 1
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md b/assets/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md new file mode 100644 index 00000000..4ea08bb6 --- /dev/null +++ b/assets/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md @@ -0,0 +1,84 @@ +# [1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits](https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits) + + + +## Description + +

    Given a string num representing the digits of a very large integer and an integer k.

    + +

    You are allowed to swap any two adjacent digits of the integer at most k times.

    + +

    Return the minimum integer you can obtain also as a string.

    + +

     

    +

    Example 1:

    + +
    +Input: num = "4321", k = 4
    +Output: "1342"
    +Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
    +
    + +

    Example 2:

    + +
    +Input: num = "100", k = 1
    +Output: "010"
    +Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
    +
    + +

    Example 3:

    + +
    +Input: num = "36789", k = 1000
    +Output: "36789"
    +Explanation: We can keep the number without any swaps.
    +
    + +

    Example 4:

    + +
    +Input: num = "22", k = 22
    +Output: "22"
    +
    + +

    Example 5:

    + +
    +Input: num = "9438957234785635408", k = 23
    +Output: "0345989723478563548"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= num.length <= 30000
    • +
    • num contains digits only and doesn't have leading zeros.
    • +
    • 1 <= k <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/images/q4_1.jpg b/assets/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/images/q4_1.jpg new file mode 100644 index 00000000..45476274 Binary files /dev/null and b/assets/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/images/q4_1.jpg differ diff --git a/assets/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md b/assets/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md new file mode 100644 index 00000000..cb8e389a --- /dev/null +++ b/assets/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md @@ -0,0 +1,90 @@ +# [1506. Find Root of N-Ary Tree](https://leetcode.com/problems/find-root-of-n-ary-tree) + + + +## Description + +

    You are given all the nodes of an N-ary tree as an array of Node objects, where each node has a unique value.

    + +

    Return the root of the N-ary tree.

    + +

    Custom testing:

    + +

    An N-ary tree can be serialized as represented in its level order traversal where each group of children is separated by the null value (see examples).

    + +

    + +

    For example, the above tree is serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

    + +

    The testing will be done in the following way:

    + +
      +
    1. The input data should be provided as a serialization of the tree.
    2. +
    3. The driver code will construct the tree from the serialized input data and put each Node object into an array in an arbitrary order.
    4. +
    5. The driver code will pass the array to findRoot, and your function should find and return the root Node object in the array.
    6. +
    7. The driver code will take the returned Node object and serialize it. If the serialized value and the input data are the same, the test passes.
    8. +
    + +

     

    +

    Example 1:

    + +

    + +
    +Input: tree = [1,null,3,2,4,null,5,6]
    +Output: [1,null,3,2,4,null,5,6]
    +Explanation: The tree from the input data is shown above.
    +The driver code creates the tree and gives findRoot the Node objects in an arbitrary order.
    +For example, the passed array could be [Node(5),Node(4),Node(3),Node(6),Node(2),Node(1)] or [Node(2),Node(6),Node(1),Node(3),Node(5),Node(4)].
    +The findRoot function should return the root Node(1), and the driver code will serialize it and compare with the input data.
    +The input data and serialized Node(1) are the same, so the test passes.
    +
    + +

    Example 2:

    + +

    + +
    +Input: tree = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The total number of nodes is between [1, 5 * 104].
    • +
    • Each node has a unique value.
    • +
    + +

     

    +

    Follow up:

    + +
      +
    • Could you solve this problem in constant space complexity with a linear time algorithm?
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1506.Find Root of N-Ary Tree/images/narytreeexample.png b/assets/1500-1599/1506.Find Root of N-Ary Tree/images/narytreeexample.png new file mode 100644 index 00000000..c8d6a81f Binary files /dev/null and b/assets/1500-1599/1506.Find Root of N-Ary Tree/images/narytreeexample.png differ diff --git a/assets/1500-1599/1506.Find Root of N-Ary Tree/images/sample_4_964.png b/assets/1500-1599/1506.Find Root of N-Ary Tree/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/1500-1599/1506.Find Root of N-Ary Tree/images/sample_4_964.png differ diff --git a/assets/1500-1599/1507.Reformat Date/README_EN.md b/assets/1500-1599/1507.Reformat Date/README_EN.md new file mode 100644 index 00000000..f32b35f7 --- /dev/null +++ b/assets/1500-1599/1507.Reformat Date/README_EN.md @@ -0,0 +1,96 @@ +# [1507. Reformat Date](https://leetcode.com/problems/reformat-date) + + + +## Description + +

    Given a date string in the form Day Month Year, where:

    + +
      +
    • Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
    • +
    • Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
    • +
    • Year is in the range [1900, 2100].
    • +
    + +

    Convert the date string to the format YYYY-MM-DD, where:

    + +
      +
    • YYYY denotes the 4 digit year.
    • +
    • MM denotes the 2 digit month.
    • +
    • DD denotes the 2 digit day.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: date = "20th Oct 2052"
    +Output: "2052-10-20"
    +
    + +

    Example 2:

    + +
    +Input: date = "6th Jun 1933"
    +Output: "1933-06-06"
    +
    + +

    Example 3:

    + +
    +Input: date = "26th May 1960"
    +Output: "1960-05-26"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The given dates are guaranteed to be valid, so no error handling is necessary.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def reformatDate(self, date: str) -> str: + months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + mapper = {v: str(k + 1) for k, v in enumerate(months)} + split = date.split(' ') + year = split[2] + month = mapper.get(split[1]) + day = split[0][:len(split[0]) - 2] + return year + '-' + month.zfill(2) + '-' + day.zfill(2) +``` + +### **Java** + +```java +class Solution { + public String reformatDate(String date) { + Map mapper = new HashMap<>(); + String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + for (int i = 0; i < months.length; ++i) { + mapper.put(months[i], i + 1); + } + String[] split = date.split(" "); + int year = Integer.parseInt(split[2]); + int month = mapper.get(split[1]); + int day = Integer.parseInt(split[0].substring(0, split[0].length() -2)); + return String.format("%d-%02d-%02d", year, month, day); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md b/assets/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md new file mode 100644 index 00000000..31d0e5de --- /dev/null +++ b/assets/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md @@ -0,0 +1,68 @@ +# [1508. Range Sum of Sorted Subarray Sums](https://leetcode.com/problems/range-sum-of-sorted-subarray-sums) + + + +## Description + +

    Given the array nums consisting of n positive integers. You computed the sum of all non-empty continous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.

    + +

    Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4], n = 4, left = 1, right = 5
    +Output: 13 
    +Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. 
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
    +Output: 6
    +Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
    +Output: 50
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^3
    • +
    • nums.length == n
    • +
    • 1 <= nums[i] <= 100
    • +
    • 1 <= left <= right <= n * (n + 1) / 2
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md b/assets/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md new file mode 100644 index 00000000..8035a9f3 --- /dev/null +++ b/assets/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md @@ -0,0 +1,113 @@ +# [1509. Minimum Difference Between Largest and Smallest Value in Three Moves](https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves) + + + +## Description + +

    Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.

    + + + +

    Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [5,3,2,4]
    +
    +Output: 0
    +
    +Explanation: Change the array [5,3,2,4] to [2,2,2,2].
    +
    +The difference between the maximum and minimum is 2-2 = 0.
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,5,0,10,14]
    +
    +Output: 1
    +
    +Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. 
    +
    +The difference between the maximum and minimum is 1-0 = 1.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [6,6,0,1,1,4,6]
    +
    +Output: 2
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: nums = [1,5,6,14,15]
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • -10^9 <= nums[i] <= 10^9
    • + +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1510.Stone Game IV/README_EN.md b/assets/1500-1599/1510.Stone Game IV/README_EN.md new file mode 100644 index 00000000..d3b66c8c --- /dev/null +++ b/assets/1500-1599/1510.Stone Game IV/README_EN.md @@ -0,0 +1,85 @@ +# [1510. Stone Game IV](https://leetcode.com/problems/stone-game-iv) + + + +## Description + +

    Alice and Bob take turns playing a game, with Alice starting first.

    + +

    Initially, there are n stones in a pile.  On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.

    + +

    Also, if a player cannot make a move, he/she loses the game.

    + +

    Given a positive integer n. Return True if and only if Alice wins the game otherwise return False, assuming both players play optimally.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: true
    +Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: false
    +Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
    + +

    Example 3:

    + +
    +Input: n = 4
    +Output: true
    +Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
    +
    + +

    Example 4:

    + +
    +Input: n = 7
    +Output: false
    +Explanation: Alice can't win the game if Bob plays optimally.
    +If Alice starts removing 4 stones, Bob will remove 1 stone then Alice should remove only 1 stone and finally Bob removes the last one (7 -> 3 -> 2 -> 1 -> 0). 
    +If Alice starts removing 1 stone, Bob will remove 4 stones then Alice only can remove 1 stone and finally Bob removes the last one (7 -> 6 -> 2 -> 1 -> 0).
    + +

    Example 5:

    + +
    +Input: n = 17
    +Output: false
    +Explanation: Alice can't win the game if Bob plays optimally.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1511.Customer Order Frequency/README_EN.md b/assets/1500-1599/1511.Customer Order Frequency/README_EN.md new file mode 100644 index 00000000..22929673 --- /dev/null +++ b/assets/1500-1599/1511.Customer Order Frequency/README_EN.md @@ -0,0 +1,234 @@ +# [1511. Customer Order Frequency](https://leetcode.com/problems/customer-order-frequency) + + + +## Description + +

    Table: Customers

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| customer_id   | int     |
    +
    +| name          | varchar |
    +
    +| country       | varchar |
    +
    ++---------------+---------+
    +
    +customer_id is the primary key for this table.
    +
    +This table contains information of the customers in the company.
    +
    +
    + + + +

     

    + + + +

    Table: Product

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| product_id    | int     |
    +
    +| description   | varchar |
    +
    +| price         | int     |
    +
    ++---------------+---------+
    +
    +product_id is the primary key for this table.
    +
    +This table contains information of the products in the company.
    +
    +price is the product cost.
    + + + +

     

    + + + +

    Table: Orders

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| order_id      | int     |
    +
    +| customer_id   | int     |
    +
    +| product_id    | int     |
    +
    +| order_date    | date    |
    +
    +| quantity      | int     |
    +
    ++---------------+---------+
    +
    +order_id is the primary key for this table.
    +
    +This table contains information on customer orders.
    +
    +customer_id is the id of the customer who bought "quantity" products with id "product_id".
    +
    +Order_date is the date in format ('YYYY-MM-DD') when the order was shipped.
    + + + +

     

    + + + +

    Write an SQL query to report the customer_id and customer_name of customers who have spent at least $100 in each month of June and July 2020.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example.

    + + + +

     

    + + + +
    +
    +Customers
    +
    ++--------------+-----------+-------------+
    +
    +| customer_id  | name      | country     |
    +
    ++--------------+-----------+-------------+
    +
    +| 1            | Winston   | USA         |
    +
    +| 2            | Jonathan  | Peru        |
    +
    +| 3            | Moustafa  | Egypt       |
    +
    ++--------------+-----------+-------------+
    +
    +
    +
    +Product
    +
    ++--------------+-------------+-------------+
    +
    +| product_id   | description | price       |
    +
    ++--------------+-------------+-------------+
    +
    +| 10           | LC Phone    | 300         |
    +
    +| 20           | LC T-Shirt  | 10          |
    +
    +| 30           | LC Book     | 45          |
    +
    +| 40           | LC Keychain | 2           |
    +
    ++--------------+-------------+-------------+
    +
    +
    +
    +Orders
    +
    ++--------------+-------------+-------------+-------------+-----------+
    +
    +| order_id     | customer_id | product_id  | order_date  | quantity  |
    +
    ++--------------+-------------+-------------+-------------+-----------+
    +
    +| 1            | 1           | 10          | 2020-06-10  | 1         |
    +
    +| 2            | 1           | 20          | 2020-07-01  | 1         |
    +
    +| 3            | 1           | 30          | 2020-07-08  | 2         |
    +
    +| 4            | 2           | 10          | 2020-06-15  | 2         |
    +
    +| 5            | 2           | 40          | 2020-07-01  | 10        |
    +
    +| 6            | 3           | 20          | 2020-06-24  | 2         |
    +
    +| 7            | 3           | 30          | 2020-06-25  | 2         |
    +
    +| 9            | 3           | 30          | 2020-05-08  | 3         |
    +
    ++--------------+-------------+-------------+-------------+-----------+
    +
    +
    +
    +Result table:
    +
    ++--------------+------------+
    +
    +| customer_id  | name       |  
    +
    ++--------------+------------+
    +
    +| 1            | Winston    |
    +
    ++--------------+------------+ 
    +
    +Winston spent $300 (300 * 1) in June and $100 ( 10 * 1 + 45 * 2) in July 2020.
    +
    +Jonathan spent $600 (300 * 2) in June and $20 ( 2 * 10) in July 2020.
    +
    +Moustafa spent $110 (10 * 2 + 45 * 2) in June and $0 in July 2020.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + c.customer_id AS CUSTOMER_ID, + c.name AS NAME +FROM + Customers c, Product p, Orders o +WHERE + c.customer_id = o.customer_id +AND p.product_id = o.product_id +GROUP BY c.customer_id +HAVING sum(if(month(o.order_date)=6, price*quantity, 0)) >= 100 +AND sum(if(month(o.order_date)=7, price*quantity, 0)) >= 100; +``` + + \ No newline at end of file diff --git a/assets/1500-1599/1512.Number of Good Pairs/README_EN.md b/assets/1500-1599/1512.Number of Good Pairs/README_EN.md new file mode 100644 index 00000000..1bbedf9f --- /dev/null +++ b/assets/1500-1599/1512.Number of Good Pairs/README_EN.md @@ -0,0 +1,150 @@ +# [1512. Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs) + + + +## Description + +

    Given an array of integers nums.

    + + + +

    A pair (i,j) is called good if nums[i] == nums[j] and i < j.

    + + + +

    Return the number of good pairs.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [1,2,3,1,1,3]
    +
    +Output: 4
    +
    +Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,1,1,1]
    +
    +Output: 6
    +
    +Explanation: Each pair in the array are good.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [1,2,3]
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + counter = collections.Counter(nums) + return sum([x * (x - 1) for x in counter.values()]) >> 1 +``` + +### **Java** + +```java +class Solution { + public int numIdenticalPairs(int[] nums) { + Map counter = new HashMap<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + int res = 0; + for (int n : counter.values()) { + res += n * (n - 1); + } + return res >> 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numIdenticalPairs(vector& nums) { + unordered_map counter; + for (int num : nums) { + ++counter[num]; + } + int res = 0; + for (auto &[num, n] : counter) { + res += n * (n - 1); + } + return res >> 1; + } +}; +``` + +### **Go** + +```go +func numIdenticalPairs(nums []int) int { + counter := make(map[int]int) + for _, num := range nums { + counter[num]++ + } + res := 0 + for _, n := range counter { + res += n * (n - 1) + } + return res >> 1 +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md b/assets/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md new file mode 100644 index 00000000..53e5a2e0 --- /dev/null +++ b/assets/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md @@ -0,0 +1,120 @@ +# [1513. Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s) + + + +## Description + +

    Given a binary string s (a string consisting only of '0' and '1's).

    + + + +

    Return the number of substrings with all characters 1's.

    + + + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "0110111"
    +
    +Output: 9
    +
    +Explanation: There are 9 substring in total with only 1's characters.
    +
    +"1" -> 5 times.
    +
    +"11" -> 3 times.
    +
    +"111" -> 1 time.
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "101"
    +
    +Output: 2
    +
    +Explanation: Substring "1" is shown 2 times in s.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "111111"
    +
    +Output: 21
    +
    +Explanation: Each substring contains only 1's characters.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "000"
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • s[i] == '0' or s[i] == '1'
    • +
    • 1 <= s.length <= 10^5
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1514.Path with Maximum Probability/README_EN.md b/assets/1500-1599/1514.Path with Maximum Probability/README_EN.md new file mode 100644 index 00000000..b009f044 --- /dev/null +++ b/assets/1500-1599/1514.Path with Maximum Probability/README_EN.md @@ -0,0 +1,118 @@ +# [1514. Path with Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability) + + + +## Description + +

    You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].

    + + + +

    Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.

    + + + +

    If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
    +
    +Output: 0.25000
    +
    +Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
    +
    +Output: 0.30000
    +
    +
    + + + +

    Example 3:

    + + + +

    + + + +
    +
    +Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
    +
    +Output: 0.00000
    +
    +Explanation: There is no path between 0 and 2.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= n <= 10^4
    • +
    • 0 <= start, end < n
    • +
    • start != end
    • +
    • 0 <= a, b < n
    • +
    • a != b
    • +
    • 0 <= succProb.length == edges.length <= 2*10^4
    • +
    • 0 <= succProb[i] <= 1
    • +
    • There is at most one edge between every two nodes.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex1.png b/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex1.png new file mode 100644 index 00000000..0391c0d3 Binary files /dev/null and b/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex1.png differ diff --git a/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex2.png b/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex2.png new file mode 100644 index 00000000..cc256ab6 Binary files /dev/null and b/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex2.png differ diff --git a/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex3.png b/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex3.png new file mode 100644 index 00000000..31f86834 Binary files /dev/null and b/assets/1500-1599/1514.Path with Maximum Probability/images/1558_ex3.png differ diff --git a/assets/1500-1599/1515.Best Position for a Service Centre/README_EN.md b/assets/1500-1599/1515.Best Position for a Service Centre/README_EN.md new file mode 100644 index 00000000..3b1e1533 --- /dev/null +++ b/assets/1500-1599/1515.Best Position for a Service Centre/README_EN.md @@ -0,0 +1,89 @@ +# [1515. Best Position for a Service Centre](https://leetcode.com/problems/best-position-for-a-service-centre) + + + +## Description + +

    A delivery company wants to build a new service centre in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new centre in a position such that the sum of the euclidean distances to all customers is minimum.

    + +

    Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.

    + +

    In other words, you need to choose the position of the service centre [xcentre, ycentre] such that the following formula is minimized:

    + +

    Answers within 10^-5 of the actual value will be accepted.

    + +

     

    +

    Example 1:

    + +
    +Input: positions = [[0,1],[1,0],[1,2],[2,1]]
    +Output: 4.00000
    +Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.
    +
    + +

    Example 2:

    + +
    +Input: positions = [[1,1],[3,3]]
    +Output: 2.82843
    +Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843
    +
    + +

    Example 3:

    + +
    +Input: positions = [[1,1]]
    +Output: 0.00000
    +
    + +

    Example 4:

    + +
    +Input: positions = [[1,1],[0,0],[2,0]]
    +Output: 2.73205
    +Explanation: At the first glance, you may think that locating the centre at [1, 0] will achieve the minimum sum, but locating it at [1, 0] will make the sum of distances = 3.
    +Try to locate the centre at [1.0, 0.5773502711] you will see that the sum of distances is 2.73205.
    +Be careful with the precision!
    +
    + +

    Example 5:

    + +
    +Input: positions = [[0,1],[3,2],[4,5],[7,6],[8,9],[11,1],[2,12]]
    +Output: 32.94036
    +Explanation: You can use [4.3460852395, 4.9813795505] as the position of the centre.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= positions.length <= 50
    • +
    • positions[i].length == 2
    • +
    • 0 <= positions[i][0], positions[i][1] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_e1.jpg b/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_e1.jpg new file mode 100644 index 00000000..352b01d7 Binary files /dev/null and b/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_e1.jpg differ diff --git a/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_e3.jpg b/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_e3.jpg new file mode 100644 index 00000000..6d263775 Binary files /dev/null and b/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_e3.jpg differ diff --git a/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_edited.jpg b/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_edited.jpg new file mode 100644 index 00000000..29a723c6 Binary files /dev/null and b/assets/1500-1599/1515.Best Position for a Service Centre/images/q4_edited.jpg differ diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md new file mode 100644 index 00000000..f7f9d498 --- /dev/null +++ b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md @@ -0,0 +1,112 @@ +# [1516. Move Sub-Tree of N-Ary Tree](https://leetcode.com/problems/move-sub-tree-of-n-ary-tree) + + + +## Description + +

    Given the root of an N-ary tree of unique values, and two nodes of the tree p and q.

    + +

    You should move the subtree of the node p to become a direct child of node q. If p is already a direct child of q, don't change anything. Node p must be the last child in the children list of node q.

    + +

    Return the root of the tree after adjusting it.

    + +

     

    + +

    There are 3 cases for nodes p and q:

    + +
      +
    1. Node q is in the sub-tree of node p.
    2. +
    3. Node p is in the sub-tree of node q.
    4. +
    5. Neither node p is in the sub-tree of node q nor node q is in the sub-tree of node p.
    6. +
    + +

    In cases 2 and 3, you just need to move p (with its sub-tree) to be a child of q, but in case 1 the tree may be disconnected, thus you need to reconnect the tree again. Please read the examples carefully before solving this problem.

    + +

     

    + +

    Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

    + +

    + +

    For example, the above tree is serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

    + +

     

    +

    Example 1:

    + +
    +Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 4, q = 1
    +Output: [1,null,2,3,4,null,5,null,6,null,7,8]
    +Explanation: This example follows the second case as node p is in the sub-tree of node q. We move node p with its sub-tree to be a direct child of node q.
    +Notice that node 4 is the last child of node 1.
    + +

    Example 2:

    + +
    +Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 7, q = 4
    +Output: [1,null,2,3,null,4,5,null,6,null,7,8]
    +Explanation: Node 7 is already a direct child of node 4. We don't change anything.
    +
    + +

    Example 3:

    + +
    +Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 3, q = 8
    +Output: [1,null,2,null,4,5,null,7,8,null,null,null,3,null,6]
    +Explanation: This example follows case 3 because node p is not in the sub-tree of node q and vice-versa. We can move node 3 with its sub-tree and make it as node 8's child.
    +
    + +

    Example 4:

    + +
    +Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 2, q = 7
    +Output: [1,null,7,3,null,2,null,6,null,4,5,null,null,8]
    +Explanation: Node q is in the sub-tree of node p, so this is case 1.
    +The first step, we move node p (with all of its sub-tree except for node q) and add it as a child to node q.
    +Then we will see that the tree is disconnected, you need to reconnect node q to replace node p as shown.
    +
    + +

    Example 5:

    + +
    +Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 1, q = 2
    +Output: [2,null,4,5,1,null,7,8,null,null,3,null,null,null,6]
    +Explanation: Node q is in the sub-tree of node p, so this is case 1.
    +The first step, we move node p (with all of its sub-tree except for node q) and add it as a child to node q.
    +As node p was the root of the tree, node q replaces it and becomes the root of the tree.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The total number of nodes is between [2, 1000].
    • +
    • Each node has a unique value.
    • +
    • p != null
    • +
    • q != null
    • +
    • p and q are two different nodes (i.e. p != q).
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e1.jpg b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e1.jpg new file mode 100644 index 00000000..a9bfa783 Binary files /dev/null and b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e1.jpg differ diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e2.jpg b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e2.jpg new file mode 100644 index 00000000..a3a6534e Binary files /dev/null and b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e2.jpg differ diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e3.jpg b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e3.jpg new file mode 100644 index 00000000..f0714307 Binary files /dev/null and b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e3.jpg differ diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e4.jpg b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e4.jpg new file mode 100644 index 00000000..f96272b2 Binary files /dev/null and b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e4.jpg differ diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e5.jpg b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e5.jpg new file mode 100644 index 00000000..c3fd5349 Binary files /dev/null and b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/move_e5.jpg differ diff --git a/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/sample_4_964.png b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/sample_4_964.png new file mode 100644 index 00000000..ad2c3cfa Binary files /dev/null and b/assets/1500-1599/1516.Move Sub-Tree of N-Ary Tree/images/sample_4_964.png differ diff --git a/assets/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md b/assets/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md new file mode 100644 index 00000000..9b685040 --- /dev/null +++ b/assets/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md @@ -0,0 +1,77 @@ +# [1517. Find Users With Valid E-Mails](https://leetcode.com/problems/find-users-with-valid-e-mails) + + + +## Description + +

    Table: Users

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| name          | varchar |
    +| mail          | varchar |
    ++---------------+---------+
    +user_id is the primary key for this table.
    +This table contains information of the users signed up in a website. Some e-mails are invalid.
    +
    + +

     

    + +

    Write an SQL query to find the users who have valid emails.

    + +

    A valid e-mail has a prefix name and a domain where: 

    + +
      +
    • The prefix name is a string that may contain letters (upper or lower case), digits, underscore '_', period '.' and/or dash '-'. The prefix name must start with a letter.
    • +
    • The domain is '@leetcode.com'.
    • +
    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Users
    ++---------+-----------+-------------------------+
    +| user_id | name      | mail                    |
    ++---------+-----------+-------------------------+
    +| 1       | Winston   | winston@leetcode.com    |
    +| 2       | Jonathan  | jonathanisgreat         |
    +| 3       | Annabelle | bella-@leetcode.com     |
    +| 4       | Sally     | sally.come@leetcode.com |
    +| 5       | Marwan    | quarz#2020@leetcode.com |
    +| 6       | David     | david69@gmail.com       |
    +| 7       | Shapiro   | .shapo@leetcode.com     |
    ++---------+-----------+-------------------------+
    +
    +Result table:
    ++---------+-----------+-------------------------+
    +| user_id | name      | mail                    |
    ++---------+-----------+-------------------------+
    +| 1       | Winston   | winston@leetcode.com    |
    +| 3       | Annabelle | bella-@leetcode.com     |
    +| 4       | Sally     | sally.come@leetcode.com |
    ++---------+-----------+-------------------------+
    +The mail of user 2 doesn't have a domain.
    +The mail of user 5 has # sign which is not allowed.
    +The mail of user 6 doesn't have leetcode domain.
    +The mail of user 7 starts with a period.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1500-1599/1518.Water Bottles/README_EN.md b/assets/1500-1599/1518.Water Bottles/README_EN.md new file mode 100644 index 00000000..5c292abd --- /dev/null +++ b/assets/1500-1599/1518.Water Bottles/README_EN.md @@ -0,0 +1,126 @@ +# [1518. Water Bottles](https://leetcode.com/problems/water-bottles) + + + +## Description + +

    Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.

    + + + +

    The operation of drinking a full water bottle turns it into an empty bottle.

    + + + +

    Return the maximum number of water bottles you can drink.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: numBottles = 9, numExchange = 3
    +
    +Output: 13
    +
    +Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
    +
    +Number of water bottles you can drink: 9 + 3 + 1 = 13.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: numBottles = 15, numExchange = 4
    +
    +Output: 19
    +
    +Explanation: You can exchange 4 empty bottles to get 1 full water bottle. 
    +
    +Number of water bottles you can drink: 15 + 3 + 1 = 19.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: numBottles = 5, numExchange = 5
    +
    +Output: 6
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: numBottles = 2, numExchange = 3
    +
    +Output: 2
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= numBottles <= 100
    • +
    • 2 <= numExchange <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1518.Water Bottles/images/sample_1_1875.png b/assets/1500-1599/1518.Water Bottles/images/sample_1_1875.png new file mode 100644 index 00000000..825896a2 Binary files /dev/null and b/assets/1500-1599/1518.Water Bottles/images/sample_1_1875.png differ diff --git a/assets/1500-1599/1518.Water Bottles/images/sample_2_1875.png b/assets/1500-1599/1518.Water Bottles/images/sample_2_1875.png new file mode 100644 index 00000000..012e439f Binary files /dev/null and b/assets/1500-1599/1518.Water Bottles/images/sample_2_1875.png differ diff --git a/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md new file mode 100644 index 00000000..407c19d8 --- /dev/null +++ b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md @@ -0,0 +1,145 @@ +# [1519. Number of Nodes in the Sub-Tree With the Same Label](https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label) + + + +## Description + +

    Given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).

    + + + +

    The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.

    + + + +

    Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.

    + + + +

    A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
    +
    +Output: [2,1,1,1,1,1,1]
    +
    +Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
    +
    +Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
    +
    +Output: [4,2,1,1]
    +
    +Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.
    +
    +The sub-tree of node 3 contains only node 3, so the answer is 1.
    +
    +The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
    +
    +The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
    +
    +Output: [3,2,1,1,1]
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 6, edges = [[0,1],[0,2],[1,3],[3,4],[4,5]], labels = "cbabaa"
    +
    +Output: [1,2,1,1,2,1]
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], labels = "aaabaaa"
    +
    +Output: [6,5,4,1,3,2,1]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^5
    • +
    • edges.length == n - 1
    • +
    • edges[i].length == 2
    • +
    • 0 <= ai, bi < n
    • +
    • ai != bi
    • +
    • labels.length == n
    • +
    • labels is consisting of only of lower-case English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e1.jpg b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e1.jpg new file mode 100644 index 00000000..c97e0776 Binary files /dev/null and b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e1.jpg differ diff --git a/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e2.jpg b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e2.jpg new file mode 100644 index 00000000..6c4daa50 Binary files /dev/null and b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e2.jpg differ diff --git a/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e3.jpg b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e3.jpg new file mode 100644 index 00000000..564fd56d Binary files /dev/null and b/assets/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/images/q3e3.jpg differ diff --git a/assets/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md b/assets/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md new file mode 100644 index 00000000..63bdb904 --- /dev/null +++ b/assets/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md @@ -0,0 +1,75 @@ +# [1520. Maximum Number of Non-Overlapping Substrings](https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings) + + + +## Description + +

    Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:

    + +
      +
    1. The substrings do not overlap, that is for any two substrings s[i..j] and s[k..l], either j < k or i > l is true.
    2. +
    3. A substring that contains a certain character c must also contain all occurrences of c.
    4. +
    + +

    Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.

    + +

    Notice that you can return the substrings in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "adefaddaccc"
    +Output: ["e","f","ccc"]
    +Explanation: The following are all the possible substrings that meet the conditions:
    +[
    +  "adefaddaccc"
    +  "adefadda",
    +  "ef",
    +  "e",
    +  "f",
    +  "ccc",
    +]
    +If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.
    +
    + +

    Example 2:

    + +
    +Input: s = "abbaccd"
    +Output: ["d","bb","cc"]
    +Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md b/assets/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md new file mode 100644 index 00000000..c26d3fd7 --- /dev/null +++ b/assets/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md @@ -0,0 +1,71 @@ +# [1521. Find a Value of a Mysterious Function Closest to Target](https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target) + + + +## Description + +

    + +

    Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.

    + +

    Return the minimum possible value of |func(arr, l, r) - target|.

    + +

    Notice that func should be called with the values l and r where 0 <= l, r < arr.length.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [9,12,3,7,15], target = 5
    +Output: 2
    +Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1000000,1000000,1000000], target = 1
    +Output: 999999
    +Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,2,4,8,16], target = 0
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • 1 <= arr[i] <= 106
    • +
    • 0 <= target <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/images/change.png b/assets/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/images/change.png new file mode 100644 index 00000000..298f1f8f Binary files /dev/null and b/assets/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/images/change.png differ diff --git a/assets/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md b/assets/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md new file mode 100644 index 00000000..c8413d1b --- /dev/null +++ b/assets/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md @@ -0,0 +1,72 @@ +# [1522. Diameter of N-Ary Tree](https://leetcode.com/problems/diameter-of-n-ary-tree) + + + +## Description + +

    Given a root of an N-ary tree, you need to compute the length of the diameter of the tree.

    + +

    The diameter of an N-ary tree is the length of the longest path between any two nodes in the tree. This path may or may not pass through the root.

    + +

    (Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value.)

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [1,null,3,2,4,null,5,6]
    +Output: 3
    +Explanation: Diameter is shown in red color.
    + +

    Example 2:

    + +

    + +
    +Input: root = [1,null,2,null,3,4,null,5,null,6]
    +Output: 4
    +
    + +

    Example 3:

    + +

    + +
    +Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +Output: 7
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The depth of the n-ary tree is less than or equal to 1000.
    • +
    • The total number of nodes is between [1, 104].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_1_1897.png b/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_1_1897.png new file mode 100644 index 00000000..0e5b1f02 Binary files /dev/null and b/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_1_1897.png differ diff --git a/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_2_1897.png b/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_2_1897.png new file mode 100644 index 00000000..efc0fcb1 Binary files /dev/null and b/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_2_1897.png differ diff --git a/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_3_1897.png b/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_3_1897.png new file mode 100644 index 00000000..ebb7279a Binary files /dev/null and b/assets/1500-1599/1522.Diameter of N-Ary Tree/images/sample_3_1897.png differ diff --git a/assets/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md b/assets/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md new file mode 100644 index 00000000..ef01f46d --- /dev/null +++ b/assets/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md @@ -0,0 +1,73 @@ +# [1523. Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range) + + + +## Description + +

    Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: low = 3, high = 7
    +
    +Output: 3
    +
    +Explanation: The odd numbers between 3 and 7 are [3,5,7].
    + + + +

    Example 2:

    + + + +
    +
    +Input: low = 8, high = 10
    +
    +Output: 1
    +
    +Explanation: The odd numbers between 8 and 10 are [9].
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 0 <= low <= high <= 10^9
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md b/assets/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md new file mode 100644 index 00000000..2cba74dc --- /dev/null +++ b/assets/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md @@ -0,0 +1,132 @@ +# [1524. Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum) + + + +## Description + +

    Given an array of integers arr. Return the number of sub-arrays with odd sum.

    + + + +

    As the answer may grow large, the answer must be computed modulo 10^9 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [1,3,5]
    +
    +Output: 4
    +
    +Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
    +
    +All sub-arrays sum are [1,4,9,3,8,5].
    +
    +Odd sums are [1,9,3,5] so the answer is 4.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [2,4,6]
    +
    +Output: 0
    +
    +Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
    +
    +All sub-arrays sum are [2,6,12,4,10,6].
    +
    +All sub-arrays have even sum and the answer is 0.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [1,2,3,4,5,6,7]
    +
    +Output: 16
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [100,100,99,99]
    +
    +Output: 4
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: arr = [7]
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md b/assets/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md new file mode 100644 index 00000000..5d8bb82f --- /dev/null +++ b/assets/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md @@ -0,0 +1,120 @@ +# [1525. Number of Good Ways to Split a String](https://leetcode.com/problems/number-of-good-ways-to-split-a-string) + + + +## Description + +

    You are given a string s, a split is called good if you can split s into 2 non-empty strings p and q where its concatenation is equal to s and the number of distinct letters in p and q are the same.

    + + + +

    Return the number of good splits you can make in s.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "aacaba"
    +
    +Output: 2
    +
    +Explanation: There are 5 ways to split "aacaba" and 2 of them are good. 
    +
    +("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
    +
    +("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
    +
    +("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
    +
    +("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
    +
    +("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "abcd"
    +
    +Output: 1
    +
    +Explanation: Split the string as follows ("ab", "cd").
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "aaaaa"
    +
    +Output: 4
    +
    +Explanation: All possible splits are good.
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "acbadbaada"
    +
    +Output: 2
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • s contains only lowercase English letters.
    • +
    • 1 <= s.length <= 10^5
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md b/assets/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md new file mode 100644 index 00000000..3300a55d --- /dev/null +++ b/assets/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md @@ -0,0 +1,83 @@ +# [1526. Minimum Number of Increments on Subarrays to Form a Target Array](https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array) + + + +## Description + +

    Given an array of positive integers target and an array initial of same size with all zeros.

    + +

    Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation:

    + +
      +
    • Choose any subarray from initial and increment each value by one.
    • +
    +The answer is guaranteed to fit within the range of a 32-bit signed integer. +

     

    +

    Example 1:

    + +
    +Input: target = [1,2,3,2,1]
    +Output: 3
    +Explanation: We need at least 3 operations to form the target array from the initial array.
    +[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
    +[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
    +[1,2,2,2,1] increment 1 at index 2.
    +[1,2,3,2,1] target array is formed.
    +
    + +

    Example 2:

    + +
    +Input: target = [3,1,1,2]
    +Output: 4
    +Explanation: (initial)[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] (target).
    +
    + +

    Example 3:

    + +
    +Input: target = [3,1,5,4,2]
    +Output: 7
    +Explanation: (initial)[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] 
    +                                  -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2] (target).
    +
    + +

    Example 4:

    + +
    +Input: target = [1,1,1,1]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= target.length <= 10^5
    • +
    • 1 <= target[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1527.Patients With a Condition/README_EN.md b/assets/1500-1599/1527.Patients With a Condition/README_EN.md new file mode 100644 index 00000000..80d05a11 --- /dev/null +++ b/assets/1500-1599/1527.Patients With a Condition/README_EN.md @@ -0,0 +1,65 @@ +# [1527. Patients With a Condition](https://leetcode.com/problems/patients-with-a-condition) + + + +## Description + +

    Table: Patients

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| patient_id   | int     |
    +| patient_name | varchar |
    +| conditions   | varchar |
    ++--------------+---------+
    +patient_id is the primary key for this table.
    +'conditions' contains 0 or more code separated by spaces. 
    +This table contains information of the patients in the hospital.
    +
    + +

     

    + +

    Write an SQL query to report the patient_id, patient_name all conditions of patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1 prefix

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Patients
    ++------------+--------------+--------------+
    +| patient_id | patient_name | conditions   |
    ++------------+--------------+--------------+
    +| 1          | Daniel       | YFEV COUGH   |
    +| 2          | Alice        |              |
    +| 3          | Bob          | DIAB100 MYOP |
    +| 4          | George       | ACNE DIAB100 |
    +| 5          | Alain        | DIAB201      |
    ++------------+--------------+--------------+
    +
    +Result table:
    ++------------+--------------+--------------+
    +| patient_id | patient_name | conditions   |
    ++------------+--------------+--------------+
    +| 3          | Bob          | DIAB100 MYOP |
    +| 4          | George       | ACNE DIAB100 | 
    ++------------+--------------+--------------+
    +Bob and George both have a condition that starts with DIAB1.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1500-1599/1528.Shuffle String/README_EN.md b/assets/1500-1599/1528.Shuffle String/README_EN.md new file mode 100644 index 00000000..ba825f22 --- /dev/null +++ b/assets/1500-1599/1528.Shuffle String/README_EN.md @@ -0,0 +1,131 @@ +# [1528. Shuffle String](https://leetcode.com/problems/shuffle-string) + + + +## Description + +

    Given a string s and an integer array indices of the same length.

    + + + +

    The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.

    + + + +

    Return the shuffled string.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
    +
    +Output: "leetcode"
    +
    +Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "abc", indices = [0,1,2]
    +
    +Output: "abc"
    +
    +Explanation: After shuffling, each character remains in its position.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "aiohn", indices = [3,1,4,2,0]
    +
    +Output: "nihao"
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "aaiougrt", indices = [4,0,2,6,7,3,1,5]
    +
    +Output: "arigatou"
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: s = "art", indices = [1,0,2]
    +
    +Output: "rat"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • s.length == indices.length == n
    • +
    • 1 <= n <= 100
    • +
    • s contains only lower-case English letters.
    • +
    • 0 <= indices[i] < n
    • +
    • All values of indices are unique (i.e. indices is a permutation of the integers from 0 to n - 1).
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1528.Shuffle String/images/q1.jpg b/assets/1500-1599/1528.Shuffle String/images/q1.jpg new file mode 100644 index 00000000..a8374567 Binary files /dev/null and b/assets/1500-1599/1528.Shuffle String/images/q1.jpg differ diff --git a/assets/1500-1599/1529.Bulb Switcher IV/README_EN.md b/assets/1500-1599/1529.Bulb Switcher IV/README_EN.md new file mode 100644 index 00000000..4a6e6bd0 --- /dev/null +++ b/assets/1500-1599/1529.Bulb Switcher IV/README_EN.md @@ -0,0 +1,87 @@ +# [1529. Bulb Switcher IV](https://leetcode.com/problems/bulb-switcher-iv) + + + +## Description + +

    There is a room with n bulbs, numbered from 0 to n-1, arranged in a row from left to right. Initially all the bulbs are turned off.

    + +

    Your task is to obtain the configuration represented by target where target[i] is '1' if the i-th bulb is turned on and is '0' if it is turned off.

    + +

    You have a switch to flip the state of the bulb, a flip operation is defined as follows:

    + +
      +
    • Choose any bulb (index i) of your current configuration.
    • +
    • Flip each bulb from index i to n-1.
    • +
    + +

    When any bulb is flipped it means that if it is 0 it changes to 1 and if it is 1 it changes to 0.

    + +

    Return the minimum number of flips required to form target.

    + +

     

    +

    Example 1:

    + +
    +Input: target = "10111"
    +Output: 3
    +Explanation: Initial configuration "00000".
    +flip from the third bulb:  "00000" -> "00111"
    +flip from the first bulb:  "00111" -> "11000"
    +flip from the second bulb:  "11000" -> "10111"
    +We need at least 3 flip operations to form target.
    + +

    Example 2:

    + +
    +Input: target = "101"
    +Output: 3
    +Explanation: "000" -> "111" -> "100" -> "101".
    +
    + +

    Example 3:

    + +
    +Input: target = "00000"
    +Output: 0
    +
    + +

    Example 4:

    + +
    +Input: target = "001011101"
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= target.length <= 10^5
    • +
    • target[i] == '0' or target[i] == '1'
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md b/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md new file mode 100644 index 00000000..a36dd9dd --- /dev/null +++ b/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md @@ -0,0 +1,127 @@ +# [1530. Number of Good Leaf Nodes Pairs](https://leetcode.com/problems/number-of-good-leaf-nodes-pairs) + + + +## Description + +

    Given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.

    + + + +

    Return the number of good leaf node pairs in the tree.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: root = [1,2,3,null,4], distance = 3
    +
    +Output: 1
    +
    +Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: root = [1,2,3,4,5,6,7], distance = 3
    +
    +Output: 2
    +
    +Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
    +
    +Output: 1
    +
    +Explanation: The only good pair is [2,5].
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: root = [100], distance = 1
    +
    +Output: 0
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: root = [1,1,1], distance = 2
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is in the range [1, 2^10].
    • +
    • Each node's value is between [1, 100].
    • +
    • 1 <= distance <= 10
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/images/e1.jpg b/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/images/e1.jpg new file mode 100644 index 00000000..fd7b10e3 Binary files /dev/null and b/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/images/e1.jpg differ diff --git a/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/images/e2.jpg b/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/images/e2.jpg new file mode 100644 index 00000000..5826d6e7 Binary files /dev/null and b/assets/1500-1599/1530.Number of Good Leaf Nodes Pairs/images/e2.jpg differ diff --git a/assets/1500-1599/1531.String Compression II/README_EN.md b/assets/1500-1599/1531.String Compression II/README_EN.md new file mode 100644 index 00000000..63a4a1c9 --- /dev/null +++ b/assets/1500-1599/1531.String Compression II/README_EN.md @@ -0,0 +1,71 @@ +# [1531. String Compression II](https://leetcode.com/problems/string-compression-ii) + + + +## Description + +

    Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".

    + +

    Notice that in this problem, we are not adding '1' after single characters.

    + +

    Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.

    + +

    Find the minimum length of the run-length encoded version of s after deleting at most k characters.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aaabcccd", k = 2
    +Output: 4
    +Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
    + +

    Example 2:

    + +
    +Input: s = "aabbaa", k = 2
    +Output: 2
    +Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.
    +
    + +

    Example 3:

    + +
    +Input: s = "aaaaaaaaaaa", k = 0
    +Output: 3
    +Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • 0 <= k <= s.length
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1532.The Most Recent Three Orders/README_EN.md b/assets/1500-1599/1532.The Most Recent Three Orders/README_EN.md new file mode 100644 index 00000000..01b09fae --- /dev/null +++ b/assets/1500-1599/1532.The Most Recent Three Orders/README_EN.md @@ -0,0 +1,109 @@ +# [1532. The Most Recent Three Orders](https://leetcode.com/problems/the-most-recent-three-orders) + + + +## Description + +

    Table: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    ++---------------+---------+
    +customer_id is the primary key for this table.
    +This table contains information about customers.
    +
    + +

     

    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| cost          | int     |
    ++---------------+---------+
    +order_id is the primary key for this table.
    +This table contains information about the orders made by customer_id.
    +Each customer has one order per day.
    +
    + +

     

    + +

    Write an SQL query to find the most recent 3 orders of each user. If a user ordered less than 3 orders return all of their orders.

    + +

    Return the result table sorted by customer_name in ascending order and in case of a tie by the customer_id in ascending order. If there still a tie, order them by the order_date in descending order.

    + +

    The query result format is in the following example:

    + +
    +Customers
    ++-------------+-----------+
    +| customer_id | name      |
    ++-------------+-----------+
    +| 1           | Winston   |
    +| 2           | Jonathan  |
    +| 3           | Annabelle |
    +| 4           | Marwan    |
    +| 5           | Khaled    |
    ++-------------+-----------+
    +
    +Orders
    ++----------+------------+-------------+------+
    +| order_id | order_date | customer_id | cost |
    ++----------+------------+-------------+------+
    +| 1        | 2020-07-31 | 1           | 30   |
    +| 2        | 2020-07-30 | 2           | 40   |
    +| 3        | 2020-07-31 | 3           | 70   |
    +| 4        | 2020-07-29 | 4           | 100  |
    +| 5        | 2020-06-10 | 1           | 1010 |
    +| 6        | 2020-08-01 | 2           | 102  |
    +| 7        | 2020-08-01 | 3           | 111  |
    +| 8        | 2020-08-03 | 1           | 99   |
    +| 9        | 2020-08-07 | 2           | 32   |
    +| 10       | 2020-07-15 | 1           | 2    |
    ++----------+------------+-------------+------+
    +
    +Result table:
    ++---------------+-------------+----------+------------+
    +| customer_name | customer_id | order_id | order_date |
    ++---------------+-------------+----------+------------+
    +| Annabelle     | 3           | 7        | 2020-08-01 |
    +| Annabelle     | 3           | 3        | 2020-07-31 |
    +| Jonathan      | 2           | 9        | 2020-08-07 |
    +| Jonathan      | 2           | 6        | 2020-08-01 |
    +| Jonathan      | 2           | 2        | 2020-07-30 |
    +| Marwan        | 4           | 4        | 2020-07-29 |
    +| Winston       | 1           | 8        | 2020-08-03 |
    +| Winston       | 1           | 1        | 2020-07-31 |
    +| Winston       | 1           | 10       | 2020-07-15 |
    ++---------------+-------------+----------+------------+
    +Winston has 4 orders, we discard the order of "2020-06-10" because it is the oldest order.
    +Annabelle has only 2 orders, we return them.
    +Jonathan has exactly 3 orders.
    +Marwan ordered only one time.
    +We sort the result table by customer_name in ascending order, by customer_id in ascending order and by order_date in descending order in case of a tie.
    +
    + +

    Follow-up:
    +Can you write a general solution for the most recent n orders?

    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1500-1599/1533.Find the Index of the Large Integer/README_EN.md b/assets/1500-1599/1533.Find the Index of the Large Integer/README_EN.md new file mode 100644 index 00000000..5cd935e7 --- /dev/null +++ b/assets/1500-1599/1533.Find the Index of the Large Integer/README_EN.md @@ -0,0 +1,219 @@ +# [1533. Find the Index of the Large Integer](https://leetcode.com/problems/find-the-index-of-the-large-integer) + + + +## Description + +

    We have an integer array arr, where all the integers in arr are equal except for one integer which is larger than the rest of the integers. You will not be given direct access to the array, instead, you will have an API ArrayReader which have the following functions:

    + +
      +
    • int compareSub(int l, int r, int x, int y): where 0 <= l, r, x, y < ArrayReader.length(), l <= r and x <= y. The function compares the sum of sub-array arr[l..r] with the sum of the sub-array arr[x..y] and returns: +
        +
      • 1 if arr[l]+arr[l+1]+...+arr[r] > arr[x]+arr[x+1]+...+arr[y].
      • +
      • 0 if arr[l]+arr[l+1]+...+arr[r] == arr[x]+arr[x+1]+...+arr[y].
      • +
      • -1 if arr[l]+arr[l+1]+...+arr[r] < arr[x]+arr[x+1]+...+arr[y].
      • +
      +
    • +
    • int length(): Returns the size of the array.
    • +
    + +

    You are allowed to call compareSub() 20 times at most. You can assume both functions work in O(1) time.

    + +

    Return the index of the array arr which has the largest integer.

    + +

    Follow-up:

    + +
      +
    • What if there are two numbers in arr that are bigger than all other numbers?
    • +
    • What if there is one number that is bigger than other numbers and one number that is smaller than other numbers?
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: arr = [7,7,7,7,10,7,7,7]
    +Output: 4
    +Explanation: The following calls to the API
    +reader.compareSub(0, 0, 1, 1) // returns 0 this is a query comparing the sub-array (0, 0) with the sub array (1, 1), (i.e. compares arr[0] with arr[1]).
    +Thus we know that arr[0] and arr[1] doesn't contain the largest element.
    +reader.compareSub(2, 2, 3, 3) // returns 0, we can exclude arr[2] and arr[3].
    +reader.compareSub(4, 4, 5, 5) // returns 1, thus for sure arr[4] is the largest element in the array.
    +Notice that we made only 3 calls, so the answer is valid.
    +
    + +

    Example 2:

    + +
    +Input: nums = [6,6,12]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr.length <= 5 * 10^5
    • +
    • 1 <= arr[i] <= 100
    • +
    • All elements of arr are equal except for one element which is larger than all other elements.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class ArrayReader(object): +# # Compares the sum of arr[l..r] with the sum of arr[x..y] +# # return 1 if sum(arr[l..r]) > sum(arr[x..y]) +# # return 0 if sum(arr[l..r]) == sum(arr[x..y]) +# # return -1 if sum(arr[l..r]) < sum(arr[x..y]) +# def compareSub(self, l: int, r: int, x: int, y: int) -> int: +# +# # Returns the length of the array +# def length(self) -> int: +# + + +class Solution: + def getIndex(self, reader: 'ArrayReader') -> int: + left, right = 0, reader.length() - 1 + while left < right: + t1, t2, t3 = left, left + (right - left) // 3, left + ((right - left) // 3) * 2 + 1 + cmp = reader.compareSub(t1, t2, t2 + 1, t3) + if cmp == 0: + left = t3 + 1 + elif cmp == 1: + right = t2 + else: + left, right = t2 + 1, t3 + return left +``` + +### **Java** + +```java +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * public int compareSub(int l, int r, int x, int y) {} + * + * // Returns the length of the array + * public int length() {} + * } + */ + +class Solution { + public int getIndex(ArrayReader reader) { + int left = 0, right = reader.length() - 1; + while (left < right) { + int t1 = left, t2 = left + (right - left) / 3, t3 = left + (right - left) / 3 * 2 + 1; + int cmp = reader.compareSub(t1, t2, t2 + 1, t3); + if (cmp == 0) { + left = t3 + 1; + } else if (cmp == 1) { + right = t2; + } else { + left = t2 + 1; + right = t3; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * int compareSub(int l, int r, int x, int y); + * + * // Returns the length of the array + * int length(); + * }; + */ + +class Solution { +public: + int getIndex(ArrayReader &reader) { + int left = 0, right = reader.length() - 1; + while (left < right) { + int t1 = left, t2 = left + (right - left) / 3, t3 = left + (right - left) / 3 * 2 + 1; + int cmp = reader.compareSub(t1, t2, t2 + 1, t3); + if (cmp == 0) { + left = t3 + 1; + } else if (cmp == 1) { + right = t2; + } else { + left = t2 + 1; + right = t3; + } + } + return left; + } +}; +``` + +### **Go** + +```go +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * type ArrayReader struct { + * } + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * func (this *ArrayReader) compareSub(l, r, x, y int) int {} + * + * // Returns the length of the array + * func (this *ArrayReader) length() int {} + */ + +func getIndex(reader *ArrayReader) int { + left, right := 0, reader.length()-1 + for left < right { + t1, t2, t3 := left, left+(right-left)/3, left+(right-left)/3*2+1 + cmp := reader.compareSub(t1, t2, t2+1, t3) + if cmp == 0 { + left = t3 + 1 + } else if cmp == 1 { + right = t2 + } else { + left, right = t2+1, t3 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1534.Count Good Triplets/README_EN.md b/assets/1500-1599/1534.Count Good Triplets/README_EN.md new file mode 100644 index 00000000..e6bc6ca2 --- /dev/null +++ b/assets/1500-1599/1534.Count Good Triplets/README_EN.md @@ -0,0 +1,100 @@ +# [1534. Count Good Triplets](https://leetcode.com/problems/count-good-triplets) + + + +## Description + +

    Given an array of integers arr, and three integers ab and c. You need to find the number of good triplets.

    + + + +

    A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

    + + + +
      +
    • 0 <= i < j < k < arr.length
    • +
    • |arr[i] - arr[j]| <= a
    • +
    • |arr[j] - arr[k]| <= b
    • +
    • |arr[i] - arr[k]| <= c
    • +
    + + + +

    Where |x| denotes the absolute value of x.

    + + + +

    Return the number of good triplets.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
    +
    +Output: 4
    +
    +Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
    +
    +Output: 0
    +
    +Explanation: No triplet satisfies all conditions.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 3 <= arr.length <= 100
    • +
    • 0 <= arr[i] <= 1000
    • +
    • 0 <= a, b, c <= 1000
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1535.Find the Winner of an Array Game/README_EN.md b/assets/1500-1599/1535.Find the Winner of an Array Game/README_EN.md new file mode 100644 index 00000000..092a74c9 --- /dev/null +++ b/assets/1500-1599/1535.Find the Winner of an Array Game/README_EN.md @@ -0,0 +1,132 @@ +# [1535. Find the Winner of an Array Game](https://leetcode.com/problems/find-the-winner-of-an-array-game) + + + +## Description + +

    Given an integer array arr of distinct integers and an integer k.

    + + + +

    A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0 and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.

    + + + +

    Return the integer which will win the game.

    + + + +

    It is guaranteed that there will be a winner of the game.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: arr = [2,1,3,5,4,6,7], k = 2
    +
    +Output: 5
    +
    +Explanation: Let's see the rounds of the game:
    +
    +Round |       arr       | winner | win_count
    +
    +  1   | [2,1,3,5,4,6,7] | 2      | 1
    +
    +  2   | [2,3,5,4,6,7,1] | 3      | 1
    +
    +  3   | [3,5,4,6,7,1,2] | 5      | 1
    +
    +  4   | [5,4,6,7,1,2,3] | 5      | 2
    +
    +So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: arr = [3,2,1], k = 10
    +
    +Output: 3
    +
    +Explanation: 3 will win the first 10 rounds consecutively.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: arr = [1,9,8,2,3,7,6,4,5], k = 7
    +
    +Output: 9
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: arr = [1,11,22,33,44,55,66,77,88,99], k = 1000000000
    +
    +Output: 99
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^6
    • +
    • arr contains distinct integers.
    • +
    • 1 <= k <= 10^9
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1535.Find the Winner of an Array Game/images/q-example.png b/assets/1500-1599/1535.Find the Winner of an Array Game/images/q-example.png new file mode 100644 index 00000000..5c3edce6 Binary files /dev/null and b/assets/1500-1599/1535.Find the Winner of an Array Game/images/q-example.png differ diff --git a/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md new file mode 100644 index 00000000..192773ed --- /dev/null +++ b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md @@ -0,0 +1,71 @@ +# [1536. Minimum Swaps to Arrange a Binary Grid](https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid) + + + +## Description + +

    Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.

    + +

    A grid is said to be valid if all the cells above the main diagonal are zeros.

    + +

    Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.

    + +

    The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[0,0,1],[1,1,0],[1,0,0]]
    +Output: 3
    +
    + +

    Example 2:

    + +
    +Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
    +Output: -1
    +Explanation: All rows are similar, swaps have no effect on the grid.
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0,0],[1,1,0],[1,1,1]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 200
    • +
    • grid[i][j] is 0 or 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/e2.jpg b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/e2.jpg new file mode 100644 index 00000000..92cbcce4 Binary files /dev/null and b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/e2.jpg differ diff --git a/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/e3.jpg b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/e3.jpg new file mode 100644 index 00000000..2aafe510 Binary files /dev/null and b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/e3.jpg differ diff --git a/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/fw.jpg b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/fw.jpg new file mode 100644 index 00000000..1450b8b8 Binary files /dev/null and b/assets/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/images/fw.jpg differ diff --git a/assets/1500-1599/1537.Get the Maximum Score/README_EN.md b/assets/1500-1599/1537.Get the Maximum Score/README_EN.md new file mode 100644 index 00000000..c24797cc --- /dev/null +++ b/assets/1500-1599/1537.Get the Maximum Score/README_EN.md @@ -0,0 +1,94 @@ +# [1537. Get the Maximum Score](https://leetcode.com/problems/get-the-maximum-score) + + + +## Description + +

    You are given two sorted arrays of distinct integers nums1 and nums2.

    + +

    A valid path is defined as follows:

    + +
      +
    • Choose array nums1 or nums2 to traverse (from index-0).
    • +
    • Traverse the current array from left to right.
    • +
    • If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).
    • +
    + +

    Score is defined as the sum of uniques values in a valid path.

    + +

    Return the maximum score you can obtain of all possible valid paths.

    + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
    +Output: 30
    +Explanation: Valid paths:
    +[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],  (starting from nums1)
    +[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10]    (starting from nums2)
    +The maximum is obtained with the path in green [2,4,6,8,10].
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]
    +Output: 109
    +Explanation: Maximum sum is obtained with the path [1,3,5,100].
    +
    + +

    Example 3:

    + +
    +Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
    +Output: 40
    +Explanation: There are no common elements between nums1 and nums2.
    +Maximum sum is obtained with the path [6,7,8,9,10].
    +
    + +

    Example 4:

    + +
    +Input: nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]
    +Output: 61
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length <= 10^5
    • +
    • 1 <= nums2.length <= 10^5
    • +
    • 1 <= nums1[i], nums2[i] <= 10^7
    • +
    • nums1 and nums2 are strictly increasing.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1537.Get the Maximum Score/images/sample_1_1893.png b/assets/1500-1599/1537.Get the Maximum Score/images/sample_1_1893.png new file mode 100644 index 00000000..ea59d514 Binary files /dev/null and b/assets/1500-1599/1537.Get the Maximum Score/images/sample_1_1893.png differ diff --git a/assets/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md b/assets/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md new file mode 100644 index 00000000..b456d914 --- /dev/null +++ b/assets/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md @@ -0,0 +1,87 @@ +# [1538. Guess the Majority in a Hidden Array](https://leetcode.com/problems/guess-the-majority-in-a-hidden-array) + + + +## Description + +

    We have an integer array nums, where all the integers in nums are 0 or 1. You will not be given direct access to the array, instead, you will have an API ArrayReader which have the following functions:

    + +
      +
    • int query(int a, int b, int c, int d): where 0 <= a < b < c < d < ArrayReader.length(). The function returns the distribution of the value of the 4 elements and returns: + +
        +
      • 4 : if the values of the 4 elements are the same (0 or 1).
      • +
      • 2 : if three elements have a value equal to 0 and one element has value equal to 1 or vice versa.
      • +
      • : if two element have a value equal to 0 and two elements have a value equal to 1.
      • +
      +
    • +
    • int length(): Returns the size of the array.
    • +
    + +

    You are allowed to call query() 2 * n times at most where n is equal to ArrayReader.length().

    + +

    Return any index of the most frequent value in nums, in case of tie, return -1.

    + +

    Follow up: What is the minimum number of calls needed to find the majority element?

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [0,0,1,0,1,1,1,1]
    +Output: 5
    +Explanation: The following calls to the API
    +reader.length() // returns 8 because there are 8 elements in the hidden array.
    +reader.query(0,1,2,3) // returns 2 this is a query that compares the elements nums[0], nums[1], nums[2], nums[3]
    +// Three elements have a value equal to 0 and one element has value equal to 1 or viceversa.
    +reader.query(4,5,6,7) // returns 4 because nums[4], nums[5], nums[6], nums[7] have the same value.
    +we can infer that the most frequent value is found in the last 4 elements.
    +Index 2, 4, 6, 7 is also a correct answer.
    +
    + +

    Example 2:

    + +
    +Input: nums = [0,0,1,1,0]
    +Output: 0
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,0,1,0,1,0,1,0]
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 5 <= nums.length <= 10^5
    • +
    • 0 <= nums[i] <= 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1539.Kth Missing Positive Number/README_EN.md b/assets/1500-1599/1539.Kth Missing Positive Number/README_EN.md new file mode 100644 index 00000000..39933467 --- /dev/null +++ b/assets/1500-1599/1539.Kth Missing Positive Number/README_EN.md @@ -0,0 +1,61 @@ +# [1539. Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number) + + + +## Description + +

    Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.

    + +

    Find the kth positive integer that is missing from this array.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [2,3,4,7,11], k = 5
    +Output: 9
    +Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,2,3,4], k = 2
    +Output: 6
    +Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 1000
    • +
    • 1 <= k <= 1000
    • +
    • arr[i] < arr[j] for 1 <= i < j <= arr.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1540.Can Convert String in K Moves/README_EN.md b/assets/1500-1599/1540.Can Convert String in K Moves/README_EN.md new file mode 100644 index 00000000..012ddec6 --- /dev/null +++ b/assets/1500-1599/1540.Can Convert String in K Moves/README_EN.md @@ -0,0 +1,79 @@ +# [1540. Can Convert String in K Moves](https://leetcode.com/problems/can-convert-string-in-k-moves) + + + +## Description + +

    Given two strings s and t, your goal is to convert s into t in k moves or less.

    + +

    During the ith (1 <= i <= kmove you can:

    + +
      +
    • Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
    • +
    • Do nothing.
    • +
    + +

    Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.

    + +

    Remember that any index j can be picked at most once.

    + +

    Return true if it's possible to convert s into t in no more than k moves, otherwise return false.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "input", t = "ouput", k = 9
    +Output: true
    +Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
    +
    + +

    Example 2:

    + +
    +Input: s = "abc", t = "bcd", k = 10
    +Output: false
    +Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
    +
    + +

    Example 3:

    + +
    +Input: s = "aab", t = "bbb", k = 27
    +Output: true
    +Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length, t.length <= 10^5
    • +
    • 0 <= k <= 10^9
    • +
    • s, t contain only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md b/assets/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md new file mode 100644 index 00000000..358c17f0 --- /dev/null +++ b/assets/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md @@ -0,0 +1,94 @@ +# [1541. Minimum Insertions to Balance a Parentheses String](https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string) + + + +## Description + +

    Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:

    + +
      +
    • Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.
    • +
    • Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
    • +
    + +

    In other words, we treat '(' as openning parenthesis and '))' as closing parenthesis.

    + +

    For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not balanced.

    + +

    You can insert the characters '(' and ')' at any position of the string to balance it if needed.

    + +

    Return the minimum number of insertions needed to make s balanced.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "(()))"
    +Output: 1
    +Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to to add one more ')' at the end of the string to be "(())))" which is balanced.
    +
    + +

    Example 2:

    + +
    +Input: s = "())"
    +Output: 0
    +Explanation: The string is already balanced.
    +
    + +

    Example 3:

    + +
    +Input: s = "))())("
    +Output: 3
    +Explanation: Add '(' to match the first '))', Add '))' to match the last '('.
    +
    + +

    Example 4:

    + +
    +Input: s = "(((((("
    +Output: 12
    +Explanation: Add 12 ')' to balance the string.
    +
    + +

    Example 5:

    + +
    +Input: s = ")))))))"
    +Output: 5
    +Explanation: Add 4 '(' at the beginning of the string and one ')' at the end. The string becomes "(((())))))))".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s consists of '(' and ')' only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1542.Find Longest Awesome Substring/README_EN.md b/assets/1500-1599/1542.Find Longest Awesome Substring/README_EN.md new file mode 100644 index 00000000..bf8785ec --- /dev/null +++ b/assets/1500-1599/1542.Find Longest Awesome Substring/README_EN.md @@ -0,0 +1,73 @@ +# [1542. Find Longest Awesome Substring](https://leetcode.com/problems/find-longest-awesome-substring) + + + +## Description + +

    Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome.

    + +

    Return the length of the maximum length awesome substring of s.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "3242415"
    +Output: 5
    +Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
    +
    + +

    Example 2:

    + +
    +Input: s = "12345678"
    +Output: 1
    +
    + +

    Example 3:

    + +
    +Input: s = "213123"
    +Output: 6
    +Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
    +
    + +

    Example 4:

    + +
    +Input: s = "00"
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s consists only of digits.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1543.Fix Product Name Format/README_EN.md b/assets/1500-1599/1543.Fix Product Name Format/README_EN.md new file mode 100644 index 00000000..12b2e3bf --- /dev/null +++ b/assets/1500-1599/1543.Fix Product Name Format/README_EN.md @@ -0,0 +1,77 @@ +# [1543. Fix Product Name Format](https://leetcode.com/problems/fix-product-name-format) + + + +## Description + +

    Table: Sales

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| sale_id      | int     |
    +| product_name | varchar |
    +| sale_date    | date    |
    ++--------------+---------+
    +sale_id is the primary key for this table.
    +Each row of this table contains the product name and the date it was sold.
    +
    + +

     

    + +

    Since table Sales was filled manually in the year 2000, product_name may contain leading and/or trailing white spaces, also they are case-insensitive.

    + +

    Write an SQL query to report

    + +
      +
    • product_name in lowercase without leading or trailing white spaces.
    • +
    • sale_date in the format ('YYYY-MM').
    • +
    • total the number of times the product was sold in this month.
    • +
    + +

    Return the result table ordered by product_name in ascending order. In case of a tie, order it by sale_date in ascending order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Sales
    ++---------+--------------+------------+
    +| sale_id | product_name | sale_date  |
    ++---------+--------------+------------+
    +| 1       | LCPHONE      | 2000-01-16 |
    +| 2       | LCPhone      | 2000-01-17 |
    +| 3       | LcPhOnE      | 2000-02-18 |
    +| 4       | LCKeyCHAiN   | 2000-02-19 |
    +| 5       | LCKeyChain   | 2000-02-28 |
    +| 6       | Matryoshka   | 2000-03-31 |
    ++---------+--------------+------------+
    +
    +Result table:
    ++--------------+-----------+-------+
    +| product_name | sale_date | total |
    ++--------------+-----------+-------+
    +| lckeychain   | 2000-02   | 2     |
    +| lcphone      | 2000-01   | 2     |
    +| lcphone      | 2000-02   | 1     |
    +| matryoshka   | 2000-03   | 1     |
    ++--------------+-----------+-------+
    +In January, 2 LcPhones were sold, please note that the product names are not case sensitive and may contain spaces.
    +In Februery, 2 LCKeychains and 1 LCPhone were sold.
    +In March, 1 matryoshka was sold.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1500-1599/1544.Make The String Great/README_EN.md b/assets/1500-1599/1544.Make The String Great/README_EN.md new file mode 100644 index 00000000..14bbc99e --- /dev/null +++ b/assets/1500-1599/1544.Make The String Great/README_EN.md @@ -0,0 +1,120 @@ +# [1544. Make The String Great](https://leetcode.com/problems/make-the-string-great) + + + +## Description + +

    Given a string s of lower and upper case English letters.

    + + + +

    A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

    + + + +
      +
    • 0 <= i <= s.length - 2
    • +
    • s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
    • + +
    + + + +

    To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.

    + + + +

    Return the string after making it good. The answer is guaranteed to be unique under the given constraints.

    + + + +

    Notice that an empty string is also good.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "leEeetcode"
    +
    +Output: "leetcode"
    +
    +Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "abBAcC"
    +
    +Output: ""
    +
    +Explanation: We have many possible scenarios, and all lead to the same answer. For example:
    +
    +"abBAcC" --> "aAcC" --> "cC" --> ""
    +
    +"abBAcC" --> "abBA" --> "aA" --> ""
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "s"
    +
    +Output: "s"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 100
    • +
    • s contains only lower and upper case English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md b/assets/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md new file mode 100644 index 00000000..cc4e5694 --- /dev/null +++ b/assets/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md @@ -0,0 +1,134 @@ +# [1545. Find Kth Bit in Nth Binary String](https://leetcode.com/problems/find-kth-bit-in-nth-binary-string) + + + +## Description + +

    Given two positive integers n and k, the binary string  Sn is formed as follows:

    + + + +
      +
    • S1 = "0"
    • +
    • Si = Si-1 + "1" + reverse(invert(Si-1)) for i > 1
    • +
    + + + +

    Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).

    + + + +

    For example, the first 4 strings in the above sequence are:

    + + + +
      +
    • S= "0"
    • +
    • S= "011"
    • +
    • S= "0111001"
    • +
    • S4 = "011100110110001"
    • +
    + + + +

    Return the kth bit in Sn. It is guaranteed that k is valid for the given n.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 3, k = 1
    +
    +Output: "0"
    +
    +Explanation: S3 is "0111001". The first bit is "0".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 4, k = 11
    +
    +Output: "1"
    +
    +Explanation: S4 is "011100110110001". The 11th bit is "1".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 1, k = 1
    +
    +Output: "0"
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 2, k = 3
    +
    +Output: "1"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 20
    • +
    • 1 <= k <= 2n - 1
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md b/assets/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md new file mode 100644 index 00000000..b42aca66 --- /dev/null +++ b/assets/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md @@ -0,0 +1,74 @@ +# [1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target](https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target) + + + +## Description + +

    Given an array nums and an integer target.

    + +

    Return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,1,1,1,1], target = 2
    +Output: 2
    +Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).
    +
    + +

    Example 2:

    + +
    +Input: nums = [-1,3,5,1,4,2,-9], target = 6
    +Output: 2
    +Explanation: There are 3 subarrays with sum equal to 6.
    +([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
    + +

    Example 3:

    + +
    +Input: nums = [-2,6,6,3,5,4,1,2,8], target = 10
    +Output: 3
    +
    + +

    Example 4:

    + +
    +Input: nums = [0,0,0], target = 0
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • -10^4 <= nums[i] <= 10^4
    • +
    • 0 <= target <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md new file mode 100644 index 00000000..2459f5d5 --- /dev/null +++ b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md @@ -0,0 +1,102 @@ +# [1547. Minimum Cost to Cut a Stick](https://leetcode.com/problems/minimum-cost-to-cut-a-stick) + + + +## Description + +

    Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:

    + + + +

    Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.

    + + + +

    You should perform the cuts in order, you can change the order of the cuts as you wish.

    + + + +

    The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.

    + + + +

    Return the minimum total cost of the cuts.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 7, cuts = [1,3,4,5]
    +
    +Output: 16
    +
    +Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:
    +
    +
    +
    +The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
    +
    +Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 9, cuts = [5,6,1,4,2]
    +
    +Output: 22
    +
    +Explanation: If you try the given cuts ordering the cost will be 25.
    +
    +There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= n <= 10^6
    • +
    • 1 <= cuts.length <= min(n - 1, 100)
    • +
    • 1 <= cuts[i] <= n - 1
    • +
    • All the integers in cuts array are distinct.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/e1.jpg b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/e1.jpg new file mode 100644 index 00000000..cd78010c Binary files /dev/null and b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/e1.jpg differ diff --git a/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/e11.jpg b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/e11.jpg new file mode 100644 index 00000000..246ceb52 Binary files /dev/null and b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/e11.jpg differ diff --git a/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/statement.jpg b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/statement.jpg new file mode 100644 index 00000000..5d48a255 Binary files /dev/null and b/assets/1500-1599/1547.Minimum Cost to Cut a Stick/images/statement.jpg differ diff --git a/assets/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md b/assets/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md new file mode 100644 index 00000000..8d6599af --- /dev/null +++ b/assets/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md @@ -0,0 +1,92 @@ +# [1548. The Most Similar Path in a Graph](https://leetcode.com/problems/the-most-similar-path-in-a-graph) + + + +## Description + +

    We have n cities and m bi-directional roads where roads[i] = [ai, bi] connects city ai with city bi. Each city has a name consisting of exactly 3 upper-case English letters given in the string array names. Starting at any city x, you can reach any city y where y != x (i.e. the cities and the roads are forming an undirected connected graph).

    + +

    You will be given a string array targetPath. You should find a path in the graph of the same length and with the minimum edit distance to targetPath.

    + +

    You need to return the order of the nodes in the path with the minimum edit distance, The path should be of the same length of targetPath and should be valid (i.e. there should be a direct road between ans[i] and ans[i + 1]). If there are multiple answers return any one of them.

    + +

    The edit distance is defined as follows:

    + +

    + +

    Follow-up: If each node can be visited only once in the path, What should you change in your solution?

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, roads = [[0,2],[0,3],[1,2],[1,3],[1,4],[2,4]], names = ["ATL","PEK","LAX","DXB","HND"], targetPath = ["ATL","DXB","HND","LAX"]
    +Output: [0,2,4,2]
    +Explanation: [0,2,4,2], [0,3,0,2] and [0,3,1,2] are accepted answers.
    +[0,2,4,2] is equivalent to ["ATL","LAX","HND","LAX"] which has edit distance = 1 with targetPath.
    +[0,3,0,2] is equivalent to ["ATL","DXB","ATL","LAX"] which has edit distance = 1 with targetPath.
    +[0,3,1,2] is equivalent to ["ATL","DXB","PEK","LAX"] which has edit distance = 1 with targetPath.
    +
    + +

    Example 2:

    + +
    +Input: n = 4, roads = [[1,0],[2,0],[3,0],[2,1],[3,1],[3,2]], names = ["ATL","PEK","LAX","DXB"], targetPath = ["ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX"]
    +Output: [0,1,0,1,0,1,0,1]
    +Explanation: Any path in this graph has edit distance = 8 with targetPath.
    +
    + +

    Example 3:

    + +

    + +
    +Input: n = 6, roads = [[0,1],[1,2],[2,3],[3,4],[4,5]], names = ["ATL","PEK","LAX","ATL","DXB","HND"], targetPath = ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
    +Output: [3,4,5,4,3,2,1]
    +Explanation: [3,4,5,4,3,2,1] is the only path with edit distance = 0 with targetPath.
    +It's equivalent to ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • m == roads.length
    • +
    • n - 1 <= m <= (n * (n - 1) / 2)
    • +
    • 0 <= ai, bi <= n - 1
    • +
    • ai != bi 
    • +
    • The graph is guaranteed to be connected and each pair of nodes may have at most one direct road.
    • +
    • names.length == n
    • +
    • names[i].length == 3
    • +
    • names[i] consists of upper-case English letters.
    • +
    • There can be two cities with the same name.
    • +
    • 1 <= targetPath.length <= 100
    • +
    • targetPath[i].length == 3
    • +
    • targetPath[i] consists of upper-case English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e1.jpg b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e1.jpg new file mode 100644 index 00000000..2178dcd8 Binary files /dev/null and b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e1.jpg differ diff --git a/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e2.jpg b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e2.jpg new file mode 100644 index 00000000..3c9b571d Binary files /dev/null and b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e2.jpg differ diff --git a/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e3.jpg b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e3.jpg new file mode 100644 index 00000000..835d59dd Binary files /dev/null and b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/e3.jpg differ diff --git a/assets/1500-1599/1548.The Most Similar Path in a Graph/images/edit.jpg b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/edit.jpg new file mode 100644 index 00000000..53bf5f91 Binary files /dev/null and b/assets/1500-1599/1548.The Most Similar Path in a Graph/images/edit.jpg differ diff --git a/assets/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md b/assets/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md new file mode 100644 index 00000000..d5389592 --- /dev/null +++ b/assets/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md @@ -0,0 +1,125 @@ +# [1549. The Most Recent Orders for Each Product](https://leetcode.com/problems/the-most-recent-orders-for-each-product) + + + +## Description + +

    Table: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    ++---------------+---------+
    +customer_id is the primary key for this table.
    +This table contains information about the customers.
    +
    + +

     

    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| product_id    | int     |
    ++---------------+---------+
    +order_id is the primary key for this table.
    +This table contains information about the orders made by customer_id.
    +There will be no product ordered by the same user more than once in one day.
    + +

     

    + +

    Table: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    +| price         | int     |
    ++---------------+---------+
    +product_id is the primary key for this table.
    +This table contains information about the Products.
    +
    + +

     

    + +

    Write an SQL query to find the most recent order(s) of each product.

    + +

    Return the result table sorted by product_name in ascending order and in case of a tie by the product_id in ascending order. If there still a tie, order them by the order_id in ascending order.

    + +

    The query result format is in the following example:

    + +
    +Customers
    ++-------------+-----------+
    +| customer_id | name      |
    ++-------------+-----------+
    +| 1           | Winston   |
    +| 2           | Jonathan  |
    +| 3           | Annabelle |
    +| 4           | Marwan    |
    +| 5           | Khaled    |
    ++-------------+-----------+
    +
    +Orders
    ++----------+------------+-------------+------------+
    +| order_id | order_date | customer_id | product_id |
    ++----------+------------+-------------+------------+
    +| 1        | 2020-07-31 | 1           | 1          |
    +| 2        | 2020-07-30 | 2           | 2          |
    +| 3        | 2020-08-29 | 3           | 3          |
    +| 4        | 2020-07-29 | 4           | 1          |
    +| 5        | 2020-06-10 | 1           | 2          |
    +| 6        | 2020-08-01 | 2           | 1          |
    +| 7        | 2020-08-01 | 3           | 1          |
    +| 8        | 2020-08-03 | 1           | 2          |
    +| 9        | 2020-08-07 | 2           | 3          |
    +| 10       | 2020-07-15 | 1           | 2          |
    ++----------+------------+-------------+------------+
    +
    +Products
    ++------------+--------------+-------+
    +| product_id | product_name | price |
    ++------------+--------------+-------+
    +| 1          | keyboard     | 120   |
    +| 2          | mouse        | 80    |
    +| 3          | screen       | 600   |
    +| 4          | hard disk    | 450   |
    ++------------+--------------+-------+
    +
    +Result table:
    ++--------------+------------+----------+------------+
    +| product_name | product_id | order_id | order_date |
    ++--------------+------------+----------+------------+
    +| keyboard     | 1          | 6        | 2020-08-01 |
    +| keyboard     | 1          | 7        | 2020-08-01 |
    +| mouse        | 2          | 8        | 2020-08-03 |
    +| screen       | 3          | 3        | 2020-08-29 |
    ++--------------+------------+----------+------------+
    +keyboard's most recent order is in 2020-08-01, it was ordered two times this day.
    +mouse's most recent order is in 2020-08-03, it was ordered only once this day.
    +screen's most recent order is in 2020-08-29, it was ordered only once this day.
    +The hard disk was never ordered and we don't include it in the result table.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1500-1599/1550.Three Consecutive Odds/README_EN.md b/assets/1500-1599/1550.Three Consecutive Odds/README_EN.md new file mode 100644 index 00000000..9a93d37b --- /dev/null +++ b/assets/1500-1599/1550.Three Consecutive Odds/README_EN.md @@ -0,0 +1,56 @@ +# [1550. Three Consecutive Odds](https://leetcode.com/problems/three-consecutive-odds) + + + +## Description + +Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. +

     

    +

    Example 1:

    + +
    +Input: arr = [2,6,4,1]
    +Output: false
    +Explanation: There are no three consecutive odds.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,2,34,3,4,5,7,23,12]
    +Output: true
    +Explanation: [5,7,23] are three consecutive odds.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md b/assets/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md new file mode 100644 index 00000000..ebaecf1e --- /dev/null +++ b/assets/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md @@ -0,0 +1,87 @@ +# [1551. Minimum Operations to Make Array Equal](https://leetcode.com/problems/minimum-operations-to-make-array-equal) + + + +## Description + +

    You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).

    + + + +

    In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.

    + + + +

    Given an integer n, the length of the array. Return the minimum number of operations needed to make all the elements of arr equal.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 3
    +
    +Output: 2
    +
    +Explanation: arr = [1, 3, 5]
    +
    +First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
    +
    +In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 6
    +
    +Output: 9
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 10^4
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md b/assets/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md new file mode 100644 index 00000000..c11b569d --- /dev/null +++ b/assets/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md @@ -0,0 +1,64 @@ +# [1552. Magnetic Force Between Two Balls](https://leetcode.com/problems/magnetic-force-between-two-balls) + + + +## Description + +

    In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.

    + +

    Rick stated that magnetic force between two different balls at positions x and y is |x - y|.

    + +

    Given the integer array position and the integer m. Return the required force.

    + +

     

    +

    Example 1:

    + +
    +Input: position = [1,2,3,4,7], m = 3
    +Output: 3
    +Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
    +
    + +

    Example 2:

    + +
    +Input: position = [5,4,3,2,1,1000000000], m = 2
    +Output: 999999999
    +Explanation: We can use baskets 1 and 1000000000.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == position.length
    • +
    • 2 <= n <= 10^5
    • +
    • 1 <= position[i] <= 10^9
    • +
    • All integers in position are distinct.
    • +
    • 2 <= m <= position.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1552.Magnetic Force Between Two Balls/images/q3v1.jpg b/assets/1500-1599/1552.Magnetic Force Between Two Balls/images/q3v1.jpg new file mode 100644 index 00000000..64406986 Binary files /dev/null and b/assets/1500-1599/1552.Magnetic Force Between Two Balls/images/q3v1.jpg differ diff --git a/assets/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md b/assets/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md new file mode 100644 index 00000000..270eb2b5 --- /dev/null +++ b/assets/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md @@ -0,0 +1,139 @@ +# [1553. Minimum Number of Days to Eat N Oranges](https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges) + + + +## Description + +

    There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:

    + + + +
      +
    • Eat one orange.
    • +
    • If the number of remaining oranges (n) is divisible by 2 then you can eat  n/2 oranges.
    • +
    • If the number of remaining oranges (n) is divisible by 3 then you can eat  2*(n/3) oranges.
    • +
    + + + +

    You can only choose one of the actions per day.

    + + + +

    Return the minimum number of days to eat n oranges.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 10
    +
    +Output: 4
    +
    +Explanation: You have 10 oranges.
    +
    +Day 1: Eat 1 orange,  10 - 1 = 9.  
    +
    +Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
    +
    +Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. 
    +
    +Day 4: Eat the last orange  1 - 1  = 0.
    +
    +You need at least 4 days to eat the 10 oranges.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 6
    +
    +Output: 3
    +
    +Explanation: You have 6 oranges.
    +
    +Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
    +
    +Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
    +
    +Day 3: Eat the last orange  1 - 1  = 0.
    +
    +You need at least 3 days to eat the 6 oranges.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 1
    +
    +Output: 1
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 56
    +
    +Output: 6
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 2*10^9
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1554.Strings Differ by One Character/README_EN.md b/assets/1500-1599/1554.Strings Differ by One Character/README_EN.md new file mode 100644 index 00000000..c21d92a7 --- /dev/null +++ b/assets/1500-1599/1554.Strings Differ by One Character/README_EN.md @@ -0,0 +1,69 @@ +# [1554. Strings Differ by One Character](https://leetcode.com/problems/strings-differ-by-one-character) + + + +## Description + +

    Given a list of strings dict where all the strings are of the same length.

    + +

    Return True if there are 2 strings that only differ by 1 character in the same index, otherwise return False.

    + +

    Follow up: Could you solve this problem in O(n*m) where n is the length of dict and m is the length of each string.

    + +

     

    +

    Example 1:

    + +
    +Input: dict = ["abcd","acbd", "aacd"]
    +Output: true
    +Explanation: Strings "abcd" and "aacd" differ only by one character in the index 1.
    +
    + +

    Example 2:

    + +
    +Input: dict = ["ab","cd","yz"]
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: dict = ["abcd","cccc","abyd","abab"]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • Number of characters in dict <= 10^5
    • +
    • dict[i].length == dict[j].length
    • +
    • dict[i] should be unique.
    • +
    • dict[i] contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1555.Bank Account Summary/README_EN.md b/assets/1500-1599/1555.Bank Account Summary/README_EN.md new file mode 100644 index 00000000..3f8799a9 --- /dev/null +++ b/assets/1500-1599/1555.Bank Account Summary/README_EN.md @@ -0,0 +1,116 @@ +# [1555. Bank Account Summary](https://leetcode.com/problems/bank-account-summary) + + + +## Description + +

    Table: Users

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| user_id      | int     |
    +| user_name    | varchar |
    +| credit       | int     |
    ++--------------+---------+
    +user_id is the primary key for this table.
    +Each row of this table contains the current credit information for each user.
    +
    + +

     

    + +

    Table: Transactions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| trans_id      | int     |
    +| paid_by       | int     |
    +| paid_to       | int     |
    +| amount        | int     |
    +| transacted_on | date    |
    ++---------------+---------+
    +trans_id is the primary key for this table.
    +Each row of this table contains the information about the transaction in the bank.
    +User with id (paid_by) transfer money to user with id (paid_to).
    +
    + +

     

    + +

    Leetcode Bank (LCB) helps its coders in making virtual payments. Our bank records all transactions in the table Transaction, we want to find out the current balance of all users and check wheter they have breached their credit limit (If their current credit is less than 0).

    + +

    Write an SQL query to report.

    + +
      +
    • user_id
    • +
    • user_name
    • +
    • credit, current balance after performing transactions.  
    • +
    • credit_limit_breached, check credit_limit ("Yes" or "No")
    • +
    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Users table:
    ++------------+--------------+-------------+
    +| user_id    | user_name    | credit      |
    ++------------+--------------+-------------+
    +| 1          | Moustafa     | 100         |
    +| 2          | Jonathan     | 200         |
    +| 3          | Winston      | 10000       |
    +| 4          | Luis         | 800         | 
    ++------------+--------------+-------------+
    +
    +Transactions table:
    ++------------+------------+------------+----------+---------------+
    +| trans_id   | paid_by    | paid_to    | amount   | transacted_on |
    ++------------+------------+------------+----------+---------------+
    +| 1          | 1          | 3          | 400      | 2020-08-01    |
    +| 2          | 3          | 2          | 500      | 2020-08-02    |
    +| 3          | 2          | 1          | 200      | 2020-08-03    |
    ++------------+------------+------------+----------+---------------+
    +
    +Result table:
    ++------------+------------+------------+-----------------------+
    +| user_id    | user_name  | credit     | credit_limit_breached |
    ++------------+------------+------------+-----------------------+
    +| 1          | Moustafa   | -100       | Yes                   | 
    +| 2          | Jonathan   | 500        | No                    |
    +| 3          | Winston    | 9900       | No                    |
    +| 4          | Luis       | 800        | No                    |
    ++------------+------------+------------+-----------------------+
    +Moustafa paid $400 on "2020-08-01" and received $200 on "2020-08-03", credit (100 -400 +200) = -$100
    +Jonathan received $500 on "2020-08-02" and paid $200 on "2020-08-08", credit (200 +500 -200) = $500
    +Winston received $400 on "2020-08-01" and paid $500 on "2020-08-03", credit (10000 +400 -500) = $9990
    +Luis didn't received any transfer, credit = $800
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1556.Thousand Separator/README_EN.md b/assets/1500-1599/1556.Thousand Separator/README_EN.md new file mode 100644 index 00000000..edf6b951 --- /dev/null +++ b/assets/1500-1599/1556.Thousand Separator/README_EN.md @@ -0,0 +1,68 @@ +# [1556. Thousand Separator](https://leetcode.com/problems/thousand-separator) + + + +## Description + +

    Given an integer n, add a dot (".") as the thousands separator and return it in string format.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 987
    +Output: "987"
    +
    + +

    Example 2:

    + +
    +Input: n = 1234
    +Output: "1.234"
    +
    + +

    Example 3:

    + +
    +Input: n = 123456789
    +Output: "123.456.789"
    +
    + +

    Example 4:

    + +
    +Input: n = 0
    +Output: "0"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= n < 2^31
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md new file mode 100644 index 00000000..5d855178 --- /dev/null +++ b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md @@ -0,0 +1,95 @@ +# [1557. Minimum Number of Vertices to Reach All Nodes](https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes) + + + +## Description + +

    Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.

    + + + +

    Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.

    + + + +

    Notice that you can return the vertices in any order.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
    +
    +Output: [0,3]
    +
    +Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
    +
    +Output: [0,2,3]
    +
    +Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= n <= 10^5
    • +
    • 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
    • +
    • edges[i].length == 2
    • +
    • 0 <= fromi, toi < n
    • +
    • All pairs (fromi, toi) are distinct.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/5480e1.png b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/5480e1.png new file mode 100644 index 00000000..5942878f Binary files /dev/null and b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/5480e1.png differ diff --git a/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/5480e2.png b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/5480e2.png new file mode 100644 index 00000000..d60431a8 Binary files /dev/null and b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/5480e2.png differ diff --git a/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/untitled.png b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/untitled.png new file mode 100644 index 00000000..d60431a8 Binary files /dev/null and b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/untitled.png differ diff --git a/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/untitled22.png b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/untitled22.png new file mode 100644 index 00000000..3b718fe3 Binary files /dev/null and b/assets/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/images/untitled22.png differ diff --git a/assets/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md b/assets/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md new file mode 100644 index 00000000..b312fa6e --- /dev/null +++ b/assets/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md @@ -0,0 +1,90 @@ +# [1558. Minimum Numbers of Function Calls to Make Target Array](https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array) + + + +## Description + +

    + +

    Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums.

    + +

    Return the minimum number of function calls to make nums from arr.

    + +

    The answer is guaranteed to fit in a 32-bit signed integer.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,5]
    +Output: 5
    +Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
    +Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
    +Increment by 1 (both elements)  [0, 4] -> [1, 4] -> [1, 5] (2 operations).
    +Total of operations: 1 + 2 + 2 = 5.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,2]
    +Output: 3
    +Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
    +Double all the elements: [1, 1] -> [2, 2] (1 operation).
    +Total of operations: 2 + 1 = 3.
    +
    + +

    Example 3:

    + +
    +Input: nums = [4,2,5]
    +Output: 6
    +Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
    +
    + +

    Example 4:

    + +
    +Input: nums = [3,2,2,4]
    +Output: 7
    +
    + +

    Example 5:

    + +
    +Input: nums = [2,4,8,16]
    +Output: 8
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 0 <= nums[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/images/sample_2_1887.png b/assets/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/images/sample_2_1887.png new file mode 100644 index 00000000..9fc99a7b Binary files /dev/null and b/assets/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/images/sample_2_1887.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md b/assets/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md new file mode 100644 index 00000000..4b0fdc89 --- /dev/null +++ b/assets/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md @@ -0,0 +1,81 @@ +# [1559. Detect Cycles in 2D Grid](https://leetcode.com/problems/detect-cycles-in-2d-grid) + + + +## Description + +

    Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.

    + +

    A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.

    + +

    Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.

    + +

    Return true if any cycle of the same value exists in grid, otherwise, return false.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
    +Output: true
    +Explanation: There are two valid cycles shown in different colors in the image below:
    +
    +
    + +

    Example 2:

    + +

    + +
    +Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
    +Output: true
    +Explanation: There is only one valid cycle highlighted in the image below:
    +
    +
    + +

    Example 3:

    + +

    + +
    +Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 500
    • +
    • 1 <= n <= 500
    • +
    • grid consists only of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/1.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/1.png new file mode 100644 index 00000000..26804706 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/1.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/11.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/11.png new file mode 100644 index 00000000..ac8b1e2f Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/11.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/2.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/2.png new file mode 100644 index 00000000..bc468c79 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/2.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/22.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/22.png new file mode 100644 index 00000000..84aa39bf Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/22.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/3.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/3.png new file mode 100644 index 00000000..fb268776 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/3.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e1.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e1.png new file mode 100644 index 00000000..92aa92d4 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e1.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e11.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e11.png new file mode 100644 index 00000000..ac8b1e2f Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e11.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e2.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e2.png new file mode 100644 index 00000000..a770ed41 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e2.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e22.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e22.png new file mode 100644 index 00000000..bc468c79 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e22.png differ diff --git a/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e3.png b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e3.png new file mode 100644 index 00000000..4668bcb7 Binary files /dev/null and b/assets/1500-1599/1559.Detect Cycles in 2D Grid/images/5482e3.png differ diff --git a/assets/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md b/assets/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md new file mode 100644 index 00000000..b33da25a --- /dev/null +++ b/assets/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md @@ -0,0 +1,71 @@ +# [1560. Most Visited Sector in a Circular Track](https://leetcode.com/problems/most-visited-sector-in-a-circular-track) + + + +## Description + +

    Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]

    + +

    Return an array of the most visited sectors sorted in ascending order.

    + +

    Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, rounds = [1,3,1,2]
    +Output: [1,2]
    +Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
    +1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
    +We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
    + +

    Example 2:

    + +
    +Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
    +Output: [2]
    +
    + +

    Example 3:

    + +
    +Input: n = 7, rounds = [1,3,5,7]
    +Output: [1,2,3,4,5,6,7]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • 1 <= m <= 100
    • +
    • rounds.length == m + 1
    • +
    • 1 <= rounds[i] <= n
    • +
    • rounds[i] != rounds[i + 1] for 0 <= i < m
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1560.Most Visited Sector in a Circular Track/images/3rd45e.jpg b/assets/1500-1599/1560.Most Visited Sector in a Circular Track/images/3rd45e.jpg new file mode 100644 index 00000000..abb21fef Binary files /dev/null and b/assets/1500-1599/1560.Most Visited Sector in a Circular Track/images/3rd45e.jpg differ diff --git a/assets/1500-1599/1560.Most Visited Sector in a Circular Track/images/tmp.jpg b/assets/1500-1599/1560.Most Visited Sector in a Circular Track/images/tmp.jpg new file mode 100644 index 00000000..abb21fef Binary files /dev/null and b/assets/1500-1599/1560.Most Visited Sector in a Circular Track/images/tmp.jpg differ diff --git a/assets/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md b/assets/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md new file mode 100644 index 00000000..223ea98f --- /dev/null +++ b/assets/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md @@ -0,0 +1,79 @@ +# [1561. Maximum Number of Coins You Can Get](https://leetcode.com/problems/maximum-number-of-coins-you-can-get) + + + +## Description + +

    There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:

    + +
      +
    • In each step, you will choose any 3 piles of coins (not necessarily consecutive).
    • +
    • Of your choice, Alice will pick the pile with the maximum number of coins.
    • +
    • You will pick the next pile with maximum number of coins.
    • +
    • Your friend Bob will pick the last pile.
    • +
    • Repeat until there are no more piles of coins.
    • +
    + +

    Given an array of integers piles where piles[i] is the number of coins in the ith pile.

    + +

    Return the maximum number of coins which you can have.

    + +

     

    +

    Example 1:

    + +
    +Input: piles = [2,4,1,2,7,8]
    +Output: 9
    +Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.
    +Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.
    +The maximum number of coins which you can have are: 7 + 2 = 9.
    +On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.
    +
    + +

    Example 2:

    + +
    +Input: piles = [2,4,5]
    +Output: 4
    +
    + +

    Example 3:

    + +
    +Input: piles = [9,8,7,6,5,1,2,3,4]
    +Output: 18
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= piles.length <= 10^5
    • +
    • piles.length % 3 == 0
    • +
    • 1 <= piles[i] <= 10^4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1562.Find Latest Group of Size M/README_EN.md b/assets/1500-1599/1562.Find Latest Group of Size M/README_EN.md new file mode 100644 index 00000000..b0152b5d --- /dev/null +++ b/assets/1500-1599/1562.Find Latest Group of Size M/README_EN.md @@ -0,0 +1,89 @@ +# [1562. Find Latest Group of Size M](https://leetcode.com/problems/find-latest-group-of-size-m) + + + +## Description + +

    Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero.

    + +

    At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are given an integer m and you need to find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1s such that it cannot be extended in either direction.

    + +

    Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [3,5,1,2,4], m = 1
    +Output: 4
    +Explanation:
    +Step 1: "00100", groups: ["1"]
    +Step 2: "00101", groups: ["1", "1"]
    +Step 3: "10101", groups: ["1", "1", "1"]
    +Step 4: "11101", groups: ["111", "1"]
    +Step 5: "11111", groups: ["11111"]
    +The latest step at which there exists a group of size 1 is step 4.
    + +

    Example 2:

    + +
    +Input: arr = [3,1,5,4,2], m = 2
    +Output: -1
    +Explanation:
    +Step 1: "00100", groups: ["1"]
    +Step 2: "10100", groups: ["1", "1"]
    +Step 3: "10101", groups: ["1", "1", "1"]
    +Step 4: "10111", groups: ["1", "111"]
    +Step 5: "11111", groups: ["11111"]
    +No group of size 2 exists during any step.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1], m = 1
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: arr = [2,1], m = 2
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == arr.length
    • +
    • 1 <= n <= 10^5
    • +
    • 1 <= arr[i] <= n
    • +
    • All integers in arr are distinct.
    • +
    • 1 <= m <= arr.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1563.Stone Game V/README_EN.md b/assets/1500-1599/1563.Stone Game V/README_EN.md new file mode 100644 index 00000000..bf6477b3 --- /dev/null +++ b/assets/1500-1599/1563.Stone Game V/README_EN.md @@ -0,0 +1,71 @@ +# [1563. Stone Game V](https://leetcode.com/problems/stone-game-v) + + + +## Description + +

    There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

    + +

    In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.

    + +

    The game ends when there is only one stone remaining. Alice's is initially zero.

    + +

    Return the maximum score that Alice can obtain.

    + +

     

    +

    Example 1:

    + +
    +Input: stoneValue = [6,2,3,4,5,5]
    +Output: 18
    +Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.
    +In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).
    +The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.
    +
    + +

    Example 2:

    + +
    +Input: stoneValue = [7,7,7,7,7,7,7]
    +Output: 28
    +
    + +

    Example 3:

    + +
    +Input: stoneValue = [4]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= stoneValue.length <= 500
    • +
    • 1 <= stoneValue[i] <= 10^6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md new file mode 100644 index 00000000..f6646bbe --- /dev/null +++ b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md @@ -0,0 +1,90 @@ +# [1564. Put Boxes Into the Warehouse I](https://leetcode.com/problems/put-boxes-into-the-warehouse-i) + + + +## Description + +

    You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labelled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room.

    + +

    Boxes are put into the warehouse by the following rules:

    + +
      +
    • Boxes cannot be stacked.
    • +
    • You can rearrange the insertion order of the boxes.
    • +
    • Boxes can only be pushed into the warehouse from left to right only.
    • +
    • If the height of some room in the warehouse is less than the height of a box, then that box and all other boxes behind it will be stopped before that room.
    • +
    + +

    Return the maximum number of boxes you can put into the warehouse.

    + +

     

    +

    Example 1:

    + +
    +Input: boxes = [4,3,4,1], warehouse = [5,3,3,4,1]
    +Output: 3
    +Explanation: 
    +
    +We can first put the box of height 1 in room 4. Then we can put the box of height 3 in either of the 3 rooms 1, 2, or 3. Lastly, we can put one box of height 4 in room 0.
    +There is no way we can fit all 4 boxes in the warehouse.
    + +

    Example 2:

    + +
    +Input: boxes = [1,2,2,3,4], warehouse = [3,4,1,2]
    +Output: 3
    +Explanation: 
    +
    +Notice that it's not possible to put the box of height 4 into the warehouse since it cannot pass the first room of height 3.
    +Also, for the last two rooms, 2 and 3, only boxes of height 1 can fit.
    +We can fit 3 boxes maximum as shown above. The yellow box can also be put in room 2 instead.
    +Swapping the orange and green boxes is also valid, or swapping one of them with the red box.
    + +

    Example 3:

    + +
    +Input: boxes = [1,2,3], warehouse = [1,2,3,4]
    +Output: 1
    +Explanation: Since the first room in the warehouse is of height 1, we can only put boxes of height 1.
    +
    + +

    Example 4:

    + +
    +Input: boxes = [4,5,6], warehouse = [3,3,3,3,3]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == warehouse.length
    • +
    • 1 <= boxes.length, warehouse.length <= 10^5
    • +
    • 1 <= boxes[i], warehouse[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/11.png b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/11.png new file mode 100644 index 00000000..16b0ee6b Binary files /dev/null and b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/11.png differ diff --git a/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/12.png b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/12.png new file mode 100644 index 00000000..903be366 Binary files /dev/null and b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/12.png differ diff --git a/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/21.png b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/21.png new file mode 100644 index 00000000..9caa25cd Binary files /dev/null and b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/21.png differ diff --git a/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/22.png b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/22.png new file mode 100644 index 00000000..f147bea6 Binary files /dev/null and b/assets/1500-1599/1564.Put Boxes Into the Warehouse I/images/22.png differ diff --git a/assets/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md b/assets/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md new file mode 100644 index 00000000..9c7ff229 --- /dev/null +++ b/assets/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md @@ -0,0 +1,86 @@ +# [1565. Unique Orders and Customers Per Month](https://leetcode.com/problems/unique-orders-and-customers-per-month) + + + +## Description + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| invoice       | int     |
    ++---------------+---------+
    +order_id is the primary key for this table.
    +This table contains information about the orders made by customer_id.
    +
    + +

     

    + +

    Write an SQL query to find the number of unique orders and the number of unique customers with invoices > $20 for each different month.

    + +

    Return the result table sorted in any order.

    + +

    The query result format is in the following example:

    + +
    +Orders
    ++----------+------------+-------------+------------+
    +| order_id | order_date | customer_id | invoice    |
    ++----------+------------+-------------+------------+
    +| 1        | 2020-09-15 | 1           | 30         |
    +| 2        | 2020-09-17 | 2           | 90         |
    +| 3        | 2020-10-06 | 3           | 20         |
    +| 4        | 2020-10-20 | 3           | 21         |
    +| 5        | 2020-11-10 | 1           | 10         |
    +| 6        | 2020-11-21 | 2           | 15         |
    +| 7        | 2020-12-01 | 4           | 55         |
    +| 8        | 2020-12-03 | 4           | 77         |
    +| 9        | 2021-01-07 | 3           | 31         |
    +| 10       | 2021-01-15 | 2           | 20         |
    ++----------+------------+-------------+------------+
    +
    +Result table:
    ++---------+-------------+----------------+
    +| month   | order_count | customer_count |
    ++---------+-------------+----------------+
    +| 2020-09 | 2           | 2              |
    +| 2020-10 | 1           | 1              |
    +| 2020-12 | 2           | 1              |
    +| 2021-01 | 1           | 1              |
    ++---------+-------------+----------------+
    +In September 2020 we have two orders from 2 different customers with invoices > $20.
    +In October 2020 we have two orders from 1 customer, and only one of the two orders has invoice > $20.
    +In November 2020 we have two orders from 2 different customers but invoices < $20, so we don't include that month.
    +In December 2020 we have two orders from 1 customer both with invoices > $20.
    +In January 2021 we have two orders from 2 different customers, but only one of them with invoice > $20.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md b/assets/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md new file mode 100644 index 00000000..be14a3ce --- /dev/null +++ b/assets/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md @@ -0,0 +1,87 @@ +# [1566. Detect Pattern of Length M Repeated K or More Times](https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times) + + + +## Description + +

    Given an array of positive integers arr,  find a pattern of length m that is repeated k or more times.

    + +

    A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.

    + +

    Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,4,4,4,4], m = 1, k = 3
    +Output: true
    +Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
    +
    + +

    Example 2:

    + +
    +Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
    +Output: true
    +Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,2,1,2,1,3], m = 2, k = 3
    +Output: false
    +Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
    +
    + +

    Example 4:

    + +
    +Input: arr = [1,2,3,1,2], m = 2, k = 2
    +Output: false
    +Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.
    +
    + +

    Example 5:

    + +
    +Input: arr = [2,2,2,2], m = 2, k = 3
    +Output: false
    +Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 100
    • +
    • 1 <= m <= 100
    • +
    • 2 <= k <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md b/assets/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md new file mode 100644 index 00000000..0aa5dd88 --- /dev/null +++ b/assets/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md @@ -0,0 +1,225 @@ +# [1567. Maximum Length of Subarray With Positive Product](https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product) + + + +## Description + +

    Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

    + +

    A subarray of an array is a consecutive sequence of zero or more values taken out of that array.

    + +

    Return the maximum length of a subarray with positive product.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,-2,-3,4]
    +Output: 4
    +Explanation: The array nums already has a positive product of 24.
    +
    + +

    Example 2:

    + +
    +Input: nums = [0,1,-2,-3,-4]
    +Output: 3
    +Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
    +Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
    + +

    Example 3:

    + +
    +Input: nums = [-1,-2,-3,0,1]
    +Output: 2
    +Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
    +
    + +

    Example 4:

    + +
    +Input: nums = [-1,2]
    +Output: 1
    +
    + +

    Example 5:

    + +
    +Input: nums = [1,2,3,5,-6,4,0,10]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • -10^9 <= nums[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def getMaxLen(self, nums: List[int]) -> int: + f1 = 1 if nums[0] > 0 else 0 + f2 = 1 if nums[0] < 0 else 0 + res = f1 + for num in nums[1:]: + pf1, pf2 = f1, f2 + if num > 0: + f1 += 1 + if f2 > 0: + f2 += 1 + else: + f2 = 0 + elif num < 0: + pf1, pf2 = f1, f2 + f2 = pf1 + 1 + if pf2 > 0: + f1 = pf2 + 1 + else: + f1 = 0 + else: + f1 = 0 + f2 = 0 + res = max(res, f1) + return res +``` + +### **Java** + +```java +class Solution { + public int getMaxLen(int[] nums) { + int f1 = nums[0] > 0 ? 1 : 0; + int f2 = nums[0] < 0 ? 1 : 0; + int res = f1; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] > 0) { + ++f1; + f2 = f2 > 0 ? f2 + 1 : 0; + } else if (nums[i] < 0) { + int pf1 = f1, pf2 = f2; + f2 = pf1 + 1; + f1 = pf2 > 0 ? pf2 + 1 : 0; + } else { + f1 = 0; + f2 = 0; + } + res = Math.max(res, f1); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function getMaxLen(nums: number[]): number { + // 连续正数计数n1, 连续负数计数n2 + let n1 = nums[0] > 0 ? 1 : 0, n2 = nums[0] < 0 ? 1 : 0; + let ans = n1; + for (let i = 1; i < nums.length; ++i) { + let cur = nums[i]; + if (cur == 0) { + n1 = 0, n2 = 0; + } else if (cur > 0) { + ++n1; + n2 = n2 > 0 ? n2 + 1 : 0; + } else { + let t1 = n1, t2 = n2; + n1 = t2 > 0 ? t2 + 1 : 0; + n2 = t1 + 1; + } + ans = Math.max(ans, n1); + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int getMaxLen(vector& nums) { + int f1 = nums[0] > 0 ? 1 : 0; + int f2 = nums[0] < 0 ? 1 : 0; + int res = f1; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > 0) { + ++f1; + f2 = f2 > 0 ? f2 + 1 : 0; + } else if (nums[i] < 0) { + int pf1 = f1, pf2 = f2; + f2 = pf1 + 1; + f1 = pf2 > 0 ? pf2 + 1 : 0; + } else { + f1 = 0; + f2 = 0; + } + res = max(res, f1); + } + return res; + } +}; +``` + +### **Go** + +```go +func getMaxLen(nums []int) int { + f1, f2 := 0, 0 + if nums[0] > 0 { + f1 = 1 + } + if nums[0] < 0 { + f2 = 1 + } + res := f1 + for i := 1; i < len(nums); i++ { + if nums[i] > 0 { + f1++ + if f2 > 0 { + f2++ + } else { + f2 = 0 + } + } else if nums[i] < 0 { + pf1, pf2 := f1, f2 + f2 = pf1 + 1 + if pf2 > 0 { + f1 = pf2 + 1 + } else { + f1 = 0 + } + } else { + f1, f2 = 0, 0 + } + res = max(res, f1) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md b/assets/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md new file mode 100644 index 00000000..3e5ffbab --- /dev/null +++ b/assets/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md @@ -0,0 +1,93 @@ +# [1568. Minimum Number of Days to Disconnect Island](https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island) + + + +## Description + +

    Given a 2D grid consisting of 1s (land) and 0s (water).  An island is a maximal 4-directionally (horizontal or vertical) connected group of 1s.

    + +

    The grid is said to be connected if we have exactly one island, otherwise is said disconnected.

    + +

    In one day, we are allowed to change any single land cell (1) into a water cell (0).

    + +

    Return the minimum number of days to disconnect the grid.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
    +Output: 2
    +Explanation: We need at least 2 days to get a disconnected grid.
    +Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,1]]
    +Output: 2
    +Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0,1,0]]
    +Output: 0
    +
    + +

    Example 4:

    + +
    +Input: grid = [[1,1,0,1,1],
    +               [1,1,1,1,1],
    +               [1,1,0,1,1],
    +               [1,1,0,1,1]]
    +Output: 1
    +
    + +

    Example 5:

    + +
    +Input: grid = [[1,1,0,1,1],
    +               [1,1,1,1,1],
    +               [1,1,0,1,1],
    +               [1,1,1,1,1]]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= grid.length, grid[i].length <= 30
    • +
    • grid[i][j] is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1568.Minimum Number of Days to Disconnect Island/images/1926_island.png b/assets/1500-1599/1568.Minimum Number of Days to Disconnect Island/images/1926_island.png new file mode 100644 index 00000000..fb4912d3 Binary files /dev/null and b/assets/1500-1599/1568.Minimum Number of Days to Disconnect Island/images/1926_island.png differ diff --git a/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md new file mode 100644 index 00000000..10dbf27e --- /dev/null +++ b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md @@ -0,0 +1,100 @@ +# [1569. Number of Ways to Reorder Array to Get Same BST](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst) + + + +## Description + +

    Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.

    + +

    For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.

    + +

    Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.

    + +

    Since the answer may be very large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: nums = [2,1,3]
    +Output: 1
    +Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
    +
    + +

    Example 2:

    + +

    + +
    +Input: nums = [3,4,5,1,2]
    +Output: 5
    +Explanation: The following 5 arrays will yield the same BST: 
    +[3,1,2,4,5]
    +[3,1,4,2,5]
    +[3,1,4,5,2]
    +[3,4,1,2,5]
    +[3,4,1,5,2]
    +
    + +

    Example 3:

    + +

    + +
    +Input: nums = [1,2,3]
    +Output: 0
    +Explanation: There are no other orderings of nums that will yield the same BST.
    +
    + +

    Example 4:

    + +

    + +
    +Input: nums = [3,1,2,5,4,6]
    +Output: 19
    +
    + +

    Example 5:

    + +
    +Input: nums = [9,4,2,1,3,6,5,7,8,14,11,10,12,13,16,15,17,18]
    +Output: 216212978
    +Explanation: The number of ways to reorder nums to get the same BST is 3216212999. Taking this number modulo 10^9 + 7 gives 216212978.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= nums.length
    • +
    • All integers in nums are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/abc.png b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/abc.png new file mode 100644 index 00000000..a46b9c71 Binary files /dev/null and b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/abc.png differ diff --git a/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/bb.png b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/bb.png new file mode 100644 index 00000000..2a9022a5 Binary files /dev/null and b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/bb.png differ diff --git a/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/ex1.png b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/ex1.png new file mode 100644 index 00000000..c171f0e8 Binary files /dev/null and b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/ex1.png differ diff --git a/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/ex4.png b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/ex4.png new file mode 100644 index 00000000..5a85be7f Binary files /dev/null and b/assets/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/images/ex4.png differ diff --git a/assets/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md b/assets/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md new file mode 100644 index 00000000..ab7fbf34 --- /dev/null +++ b/assets/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md @@ -0,0 +1,131 @@ +# [1570. Dot Product of Two Sparse Vectors](https://leetcode.com/problems/dot-product-of-two-sparse-vectors) + + + +## Description + +

    Given two sparse vectors, compute their dot product.

    + +

    Implement class SparseVector:

    + +
      +
    • SparseVector(nums) Initializes the object with the vector nums
    • +
    • dotProduct(vec) Compute the dot product between the instance of SparseVector and vec
    • +
    + +

    A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector.

    + +

    Follow up: What if only one of the vectors is sparse?

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
    +Output: 8
    +Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
    +v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
    +Output: 0
    +Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
    +v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0
    +
    + +

    Example 3:

    + +
    +Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4]
    +Output: 6
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums1.length == nums2.length
    • +
    • 1 <= n <= 10^5
    • +
    • 0 <= nums1[i], nums2[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +class SparseVector: + def __init__(self, nums: List[int]): + self.v = {} + for i, num in enumerate(nums): + if num != 0: + self.v[i] = num + + # Return the dotProduct of two sparse vectors + def dotProduct(self, vec: 'SparseVector') -> int: + res = 0 + if len(self.v) > len(vec.v): + self.v, vec.v = vec.v, self.v + for i, num in self.v.items(): + if i not in vec.v: + continue + res += num * vec.v[i] + return res + + +# Your SparseVector object will be instantiated and called as such: +# v1 = SparseVector(nums1) +# v2 = SparseVector(nums2) +# ans = v1.dotProduct(v2) +``` + +### **Java** + +```java +class SparseVector { + + private Map v; + + SparseVector(int[] nums) { + v = new HashMap<>(); + for (int i = 0; i < nums.length; ++i) { + if (nums[i] != 0) { + v.put(i, nums[i]); + } + } + } + + // Return the dotProduct of two sparse vectors + public int dotProduct(SparseVector vec) { + int res = 0; + if (v.size() > vec.v.size()) { + Map t = v; + v = vec.v; + vec.v = t; + } + for (Map.Entry entry : v.entrySet()) { + int i = entry.getKey(), num = entry.getValue(); + res += num * vec.v.getOrDefault(i, 0); + } + return res; + } +} + +// Your SparseVector object will be instantiated and called as such: +// SparseVector v1 = new SparseVector(nums1); +// SparseVector v2 = new SparseVector(nums2); +// int ans = v1.dotProduct(v2); +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1571.Warehouse Manager/README_EN.md b/assets/1500-1599/1571.Warehouse Manager/README_EN.md new file mode 100644 index 00000000..eb559bac --- /dev/null +++ b/assets/1500-1599/1571.Warehouse Manager/README_EN.md @@ -0,0 +1,120 @@ +# [1571. Warehouse Manager](https://leetcode.com/problems/warehouse-manager) + + + +## Description + +

    Table: Warehouse

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| name         | varchar |
    +| product_id   | int     |
    +| units        | int     |
    ++--------------+---------+
    +(name, product_id) is the primary key for this table.
    +Each row of this table contains the information of the products in each warehouse.
    +
    + +

     

    + +

    Table: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    +| Width         | int     |
    +| Length        | int     |
    +| Height        | int     |
    ++---------------+---------+
    +product_id is the primary key for this table.
    +Each row of this table contains the information about the product dimensions (Width, Lenght and Height) in feets of each product.
    +
    + +

     

    + +

    Write an SQL query to report, How much cubic feet of volume does the inventory occupy in each warehouse.

    + +
      +
    • warehouse_name
    • +
    • volume
    • +
    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Warehouse table:
    ++------------+--------------+-------------+
    +| name       | product_id   | units       |
    ++------------+--------------+-------------+
    +| LCHouse1   | 1            | 1           |
    +| LCHouse1   | 2            | 10          |
    +| LCHouse1   | 3            | 5           |
    +| LCHouse2   | 1            | 2           |
    +| LCHouse2   | 2            | 2           |
    +| LCHouse3   | 4            | 1           |
    ++------------+--------------+-------------+
    +
    +Products table:
    ++------------+--------------+------------+----------+-----------+
    +| product_id | product_name | Width      | Length   | Height    |
    ++------------+--------------+------------+----------+-----------+
    +| 1          | LC-TV        | 5          | 50       | 40        |
    +| 2          | LC-KeyChain  | 5          | 5        | 5         |
    +| 3          | LC-Phone     | 2          | 10       | 10        |
    +| 4          | LC-T-Shirt   | 4          | 10       | 20        |
    ++------------+--------------+------------+----------+-----------+
    +
    +Result table:
    ++----------------+------------+
    +| warehouse_name | volume     | 
    ++----------------+------------+
    +| LCHouse1       | 12250      | 
    +| LCHouse2       | 20250      |
    +| LCHouse3       | 800        |
    ++----------------+------------+
    +Volume of product_id = 1 (LC-TV), 5x50x40 = 10000
    +Volume of product_id = 2 (LC-KeyChain), 5x5x5 = 125 
    +Volume of product_id = 3 (LC-Phone), 2x10x10 = 200
    +Volume of product_id = 4 (LC-T-Shirt), 4x10x20 = 800
    +LCHouse1: 1 unit of LC-TV + 10 units of LC-KeyChain + 5 units of LC-Phone.
    +          Total volume: 1*10000 + 10*125  + 5*200 = 12250 cubic feet
    +LCHouse2: 2 units of LC-TV + 2 units of LC-KeyChain.
    +          Total volume: 2*10000 + 2*125 = 20250 cubic feet
    +LCHouse3: 1 unit of LC-T-Shirt.
    +          Total volume: 1*800 = 800 cubic feet.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1572.Matrix Diagonal Sum/README_EN.md b/assets/1500-1599/1572.Matrix Diagonal Sum/README_EN.md new file mode 100644 index 00000000..c3ab2ce5 --- /dev/null +++ b/assets/1500-1599/1572.Matrix Diagonal Sum/README_EN.md @@ -0,0 +1,72 @@ +# [1572. Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum) + + + +## Description + +

    Given a square matrix mat, return the sum of the matrix diagonals.

    + +

    Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[1,2,3],
    +              [4,5,6],
    +              [7,8,9]]
    +Output: 25
    +Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
    +Notice that element mat[1][1] = 5 is counted only once.
    +
    + +

    Example 2:

    + +
    +Input: mat = [[1,1,1,1],
    +              [1,1,1,1],
    +              [1,1,1,1],
    +              [1,1,1,1]]
    +Output: 8
    +
    + +

    Example 3:

    + +
    +Input: mat = [[5]]
    +Output: 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == mat.length == mat[i].length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= mat[i][j] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1572.Matrix Diagonal Sum/images/sample_1911.png b/assets/1500-1599/1572.Matrix Diagonal Sum/images/sample_1911.png new file mode 100644 index 00000000..498d98db Binary files /dev/null and b/assets/1500-1599/1572.Matrix Diagonal Sum/images/sample_1911.png differ diff --git a/assets/1500-1599/1573.Number of Ways to Split a String/README_EN.md b/assets/1500-1599/1573.Number of Ways to Split a String/README_EN.md new file mode 100644 index 00000000..aadfcb35 --- /dev/null +++ b/assets/1500-1599/1573.Number of Ways to Split a String/README_EN.md @@ -0,0 +1,82 @@ +# [1573. Number of Ways to Split a String](https://leetcode.com/problems/number-of-ways-to-split-a-string) + + + +## Description + +

    Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).

    + +

    Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.

    + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "10101"
    +Output: 4
    +Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
    +"1|010|1"
    +"1|01|01"
    +"10|10|1"
    +"10|1|01"
    +
    + +

    Example 2:

    + +
    +Input: s = "1001"
    +Output: 0
    +
    + +

    Example 3:

    + +
    +Input: s = "0000"
    +Output: 3
    +Explanation: There are three ways to split s in 3 parts.
    +"0|0|00"
    +"0|00|0"
    +"00|0|0"
    +
    + +

    Example 4:

    + +
    +Input: s = "100100010100110"
    +Output: 12
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= s.length <= 10^5
    • +
    • s[i] is '0' or '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md b/assets/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md new file mode 100644 index 00000000..bda1aa21 --- /dev/null +++ b/assets/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md @@ -0,0 +1,76 @@ +# [1574. Shortest Subarray to be Removed to Make Array Sorted](https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted) + + + +## Description + +

    Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.

    + +

    A subarray is a contiguous subsequence of the array.

    + +

    Return the length of the shortest subarray to remove.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,3,10,4,2,3,5]
    +Output: 3
    +Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
    +Another correct solution is to remove the subarray [3,10,4].
    + +

    Example 2:

    + +
    +Input: arr = [5,4,3,2,1]
    +Output: 4
    +Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,2,3]
    +Output: 0
    +Explanation: The array is already non-decreasing. We do not need to remove any elements.
    +
    + +

    Example 4:

    + +
    +Input: arr = [1]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 0 <= arr[i] <= 10^9
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1575.Count All Possible Routes/README_EN.md b/assets/1500-1599/1575.Count All Possible Routes/README_EN.md new file mode 100644 index 00000000..49cc1f7b --- /dev/null +++ b/assets/1500-1599/1575.Count All Possible Routes/README_EN.md @@ -0,0 +1,99 @@ +# [1575. Count All Possible Routes](https://leetcode.com/problems/count-all-possible-routes) + + + +## Description + +

    You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers startfinish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.

    + +

    At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.

    + +

    Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).

    + +

    Return the count of all possible routes from start to finish.

    + +

    Since the answer may be too large, return it modulo 10^9 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
    +Output: 4
    +Explanation: The following are all possible routes, each uses 5 units of fuel:
    +1 -> 3
    +1 -> 2 -> 3
    +1 -> 4 -> 3
    +1 -> 4 -> 2 -> 3
    +
    + +

    Example 2:

    + +
    +Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
    +Output: 5
    +Explanation: The following are all possible routes:
    +1 -> 0, used fuel = 1
    +1 -> 2 -> 0, used fuel = 5
    +1 -> 2 -> 1 -> 0, used fuel = 5
    +1 -> 0 -> 1 -> 0, used fuel = 3
    +1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5
    +
    + +

    Example 3:

    + +
    +Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
    +Output: 0
    +Explanation: It's impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
    + +

    Example 4:

    + +
    +Input: locations = [2,1,5], start = 0, finish = 0, fuel = 3
    +Output: 2
    +Explanation: There are two possible routes, 0 and 0 -> 1 -> 0.
    + +

    Example 5:

    + +
    +Input: locations = [1,2,3], start = 0, finish = 2, fuel = 40
    +Output: 615088286
    +Explanation: The total number of possible routes is 2615088300. Taking this number modulo 10^9 + 7 gives us 615088286.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= locations.length <= 100
    • +
    • 1 <= locations[i] <= 10^9
    • +
    • All integers in locations are distinct.
    • +
    • 0 <= start, finish < locations.length
    • +
    • 1 <= fuel <= 200
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md b/assets/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md new file mode 100644 index 00000000..214491f0 --- /dev/null +++ b/assets/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md @@ -0,0 +1,116 @@ +# [1576. Replace All 's to Avoid Consecutive Repeating Characters](https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters) + + + +## Description + +

    Given a string s containing only lower case English letters and the '?' character, convert all the '?' characters into lower case letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.

    + +

    It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.

    + +

    Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "?zs"
    +Output: "azs"
    +Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
    + +

    Example 2:

    + +
    +Input: s = "ubv?w"
    +Output: "ubvaw"
    +Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".
    +
    + +

    Example 3:

    + +
    +Input: s = "j?qg??b"
    +Output: "jaqgacb"
    +
    + +

    Example 4:

    + +
    +Input: s = "??yw?ipkj?"
    +Output: "acywaipkja"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s contains only lower case English letters and '?'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def modifyString(self, s: str) -> str: + s = list(s) + for i in range(len(s)): + if s[i] == '?': + ahead = ' ' if i == 0 else s[i - 1] + behind = ' ' if i == len(s) - 1 else s[i + 1] + for c in string.ascii_lowercase: + if c != ahead and c != behind: + s[i] = c + break + return "".join(s) +``` + +### **Java** + +```java +class Solution { + public String modifyString(String s) { + char[] chars = s.toCharArray(); + for (int i = 0; i < chars.length; i++) { + if (chars[i] == '?') { + // 前面的字符 + char ahead = i == 0 ? ' ' : chars[i - 1]; + // 后面的字符 + char behind = i == chars.length - 1 ? ' ' : chars[i + 1]; + char temp = 'a'; + while (temp == ahead || temp == behind) { + temp++; + } + chars[i] = temp; + } + } + return new String(chars); + } +} +``` + +### **Go** + +```go +func modifyString(s string) string { + data := []byte(" " + s + " ") + for i, c := range data { + if c == byte('?') { + ahead, behind := data[i-1], data[i+1] + for t := byte('a'); t <= byte('z'); t++ { + if t != ahead && t != behind { + data[i] = t + } + } + } + } + return string(data[1 : len(data)-1]) +} +``` + + diff --git a/assets/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md b/assets/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md new file mode 100644 index 00000000..dec3636c --- /dev/null +++ b/assets/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md @@ -0,0 +1,82 @@ +# [1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers](https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers) + + + +## Description + +

    Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:

    + +
      +
    • Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
    • +
    • Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [7,4], nums2 = [5,2,8,9]
    +Output: 1
    +Explanation: Type 1: (1,1,2), nums1[1]^2 = nums2[1] * nums2[2]. (4^2 = 2 * 8). 
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [1,1], nums2 = [1,1,1]
    +Output: 9
    +Explanation: All Triplets are valid, because 1^2 = 1 * 1.
    +Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2).  nums1[i]^2 = nums2[j] * nums2[k].
    +Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]^2 = nums1[j] * nums1[k].
    +
    + +

    Example 3:

    + +
    +Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
    +Output: 2
    +Explanation: There are 2 valid triplets.
    +Type 1: (3,0,2).  nums1[3]^2 = nums2[0] * nums2[2].
    +Type 2: (3,0,1).  nums2[3]^2 = nums1[0] * nums1[1].
    +
    + +

    Example 4:

    + +
    +Input: nums1 = [4,7,9,11,23], nums2 = [3,5,1024,12,18]
    +Output: 0
    +Explanation: There are no valid triplets.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 1000
    • +
    • 1 <= nums1[i], nums2[i] <= 10^5
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1578.Minimum Deletion Cost to Avoid Repeating Letters/README_EN.md b/assets/1500-1599/1578.Minimum Deletion Cost to Avoid Repeating Letters/README_EN.md new file mode 100644 index 00000000..0b12dd7a --- /dev/null +++ b/assets/1500-1599/1578.Minimum Deletion Cost to Avoid Repeating Letters/README_EN.md @@ -0,0 +1,71 @@ +# [1578. Minimum Deletion Cost to Avoid Repeating Letters](https://leetcode.com/problems/minimum-deletion-cost-to-avoid-repeating-letters) + + + +## Description + +

    Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s.

    + +

    Return the minimum cost of deletions such that there are no two identical letters next to each other.

    + +

    Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abaac", cost = [1,2,3,4,5]
    +Output: 3
    +Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other).
    +
    + +

    Example 2:

    + +
    +Input: s = "abc", cost = [1,2,3]
    +Output: 0
    +Explanation: You don't need to delete any character because there are no identical letters next to each other.
    +
    + +

    Example 3:

    + +
    +Input: s = "aabaa", cost = [1,2,3,4,1]
    +Output: 2
    +Explanation: Delete the first and the last character, getting the string ("aba").
    +
    + +

     

    +

    Constraints:

    + +
      +
    • s.length == cost.length
    • +
    • 1 <= s.length, cost.length <= 10^5
    • +
    • 1 <= cost[i] <= 10^4
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md new file mode 100644 index 00000000..bf00f9bb --- /dev/null +++ b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md @@ -0,0 +1,86 @@ +# [1579. Remove Max Number of Edges to Keep Graph Fully Traversable](https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable) + + + +## Description + +

    Alice and Bob have an undirected graph of n nodes and 3 types of edges:

    + +
      +
    • Type 1: Can be traversed by Alice only.
    • +
    • Type 2: Can be traversed by Bob only.
    • +
    • Type 3: Can by traversed by both Alice and Bob.
    • +
    + +

    Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.

    + +

    Return the maximum number of edges you can remove, or return -1 if it's impossible for the graph to be fully traversed by Alice and Bob.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
    +Output: 2
    +Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
    +Output: 0
    +Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
    +
    + +

    Example 3:

    + +

    + +
    +Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
    +Output: -1
    +Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
    + +

     

    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • 1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2)
    • +
    • edges[i].length == 3
    • +
    • 1 <= edges[i][0] <= 3
    • +
    • 1 <= edges[i][1] < edges[i][2] <= n
    • +
    • All tuples (typei, ui, vi) are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex1.png b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex1.png new file mode 100644 index 00000000..717ef9ea Binary files /dev/null and b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex1.png differ diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex2.png b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex2.png new file mode 100644 index 00000000..d0b17f16 Binary files /dev/null and b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex2.png differ diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex3.png b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex3.png new file mode 100644 index 00000000..09fdf5cd Binary files /dev/null and b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/5510ex3.png differ diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex1.png b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex1.png new file mode 100644 index 00000000..717ef9ea Binary files /dev/null and b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex1.png differ diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex2.png b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex2.png new file mode 100644 index 00000000..d0b17f16 Binary files /dev/null and b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex2.png differ diff --git a/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex3.png b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex3.png new file mode 100644 index 00000000..09fdf5cd Binary files /dev/null and b/assets/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/images/ex3.png differ diff --git a/assets/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md new file mode 100644 index 00000000..afd1c9be --- /dev/null +++ b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md @@ -0,0 +1,144 @@ +# [1580. Put Boxes Into the Warehouse II](https://leetcode.com/problems/put-boxes-into-the-warehouse-ii) + + + +## Description + +

    You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively. The warehouse's rooms are labeled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room.

    + + + +

    Boxes are put into the warehouse by the following rules:

    + + + +
      +
    • Boxes cannot be stacked.
    • +
    • You can rearrange the insertion order of the boxes.
    • +
    • Boxes can be pushed into the warehouse from either side (left or right)
    • +
    • If the height of some room in the warehouse is less than the height of a box, then that box and all other boxes behind it will be stopped before that room.
    • +
    + + + +

    Return the maximum number of boxes you can put into the warehouse.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: boxes = [1,2,2,3,4], warehouse = [3,4,1,2]
    +
    +Output: 4
    +
    +Explanation:
    +
    +
    +
    +We can store the boxes in the following order:
    +
    +1- Put the yellow box in room 2 from either the left or right side.
    +
    +2- Put the orange box in room 3 from the right side.
    +
    +3- Put the green box in room 1 from the left side.
    +
    +4- Put the red box in room 0 from the left side.
    +
    +Notice that there are other valid ways to put 4 boxes such as swapping the red and green boxes or the red and orange boxes.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: boxes = [3,5,5,2], warehouse = [2,1,3,4,5]
    +
    +Output: 3
    +
    +Explanation:
    +
    +
    +
    +It's not possible to put the two boxes of height 5 in the warehouse since there's only 1 room of height >= 5.
    +
    +Other valid solutions are to put the green box in room 2 or to put the orange box first in room 2 before putting the green and red boxes.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: boxes = [1,2,3], warehouse = [1,2,3,4]
    +
    +Output: 3
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: boxes = [4,5,6], warehouse = [3,3,3,3,3]
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == warehouse.length
    • +
    • 1 <= boxes.length, warehouse.length <= 105
    • +
    • 1 <= boxes[i], warehouse[i] <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-1.png b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-1.png new file mode 100644 index 00000000..fb405603 Binary files /dev/null and b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-1.png differ diff --git a/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-2.png b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-2.png new file mode 100644 index 00000000..5955dd5e Binary files /dev/null and b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-2.png differ diff --git a/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-3.png b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-3.png new file mode 100644 index 00000000..b158f2c8 Binary files /dev/null and b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22-3.png differ diff --git a/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22.png b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22.png new file mode 100644 index 00000000..8773f427 Binary files /dev/null and b/assets/1500-1599/1580.Put Boxes Into the Warehouse II/images/22.png differ diff --git a/assets/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md b/assets/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md new file mode 100644 index 00000000..1d257988 --- /dev/null +++ b/assets/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md @@ -0,0 +1,108 @@ +# [1581. Customer Who Visited but Did Not Make Any Transactions](https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions) + + + +## Description + +

    Table: Visits

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| visit_id    | int     |
    +| customer_id | int     |
    ++-------------+---------+
    +visit_id is the primary key for this table.
    +This table contains information about the customers who visited the mall.
    +
    + +

     

    + +

    Table: Transactions

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| transaction_id | int     |
    +| visit_id       | int     |
    +| amount         | int     |
    ++----------------+---------+
    +transaction_id is the primary key for this table.
    +This table contains information about the transactions made during the visit_id.
    +
    + +

     

    + +

    Write an SQL query to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits.

    + +

    Return the result table sorted in any order.

    + +

    The query result format is in the following example:

    + +
    +Visits
    ++----------+-------------+
    +| visit_id | customer_id |
    ++----------+-------------+
    +| 1        | 23          |
    +| 2        | 9           |
    +| 4        | 30          |
    +| 5        | 54          |
    +| 6        | 96          |
    +| 7        | 54          |
    +| 8        | 54          |
    ++----------+-------------+
    +
    +Transactions
    ++----------------+----------+--------+
    +| transaction_id | visit_id | amount |
    ++----------------+----------+--------+
    +| 2              | 5        | 310    |
    +| 3              | 5        | 300    |
    +| 9              | 5        | 200    |
    +| 12             | 1        | 910    |
    +| 13             | 2        | 970    |
    ++----------------+----------+--------+
    +
    +Result table:
    ++-------------+----------------+
    +| customer_id | count_no_trans |
    ++-------------+----------------+
    +| 54          | 2              |
    +| 30          | 1              |
    +| 96          | 1              |
    ++-------------+----------------+
    +Customer with id = 23 visited the mall once and made one transaction during the visit with id = 12.
    +Customer with id = 9 visited the mall once and made one transaction during the visit with id = 13.
    +Customer with id = 30 visited the mall once and did not make any transactions.
    +Customer with id = 54 visited the mall three times. During 2 visits they did not make any transactions, and during one visit they made 3 transactions.
    +Customer with id = 96 visited the mall once and did not make any transactions.
    +As we can see, users with IDs 30 and 96 visited the mall one time without making any transactions. Also user 54 visited the mall twice and did not make any transactions.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md b/assets/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md new file mode 100644 index 00000000..16de48c4 --- /dev/null +++ b/assets/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md @@ -0,0 +1,86 @@ +# [1582. Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix) + + + +## Description + +

    Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat.

    + +

    A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[1,0,0],
    +              [0,0,1],
    +              [1,0,0]]
    +Output: 1
    +Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
    +
    + +

    Example 2:

    + +
    +Input: mat = [[1,0,0],
    +              [0,1,0],
    +              [0,0,1]]
    +Output: 3
    +Explanation: (0,0), (1,1) and (2,2) are special positions. 
    +
    + +

    Example 3:

    + +
    +Input: mat = [[0,0,0,1],
    +              [1,0,0,0],
    +              [0,1,1,0],
    +              [0,0,0,0]]
    +Output: 2
    +
    + +

    Example 4:

    + +
    +Input: mat = [[0,0,0,0,0],
    +              [1,0,0,0,0],
    +              [0,1,0,0,0],
    +              [0,0,1,0,0],
    +              [0,0,0,1,1]]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • rows == mat.length
    • +
    • cols == mat[i].length
    • +
    • 1 <= rows, cols <= 100
    • +
    • mat[i][j] is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1583.Count Unhappy Friends/README_EN.md b/assets/1500-1599/1583.Count Unhappy Friends/README_EN.md new file mode 100644 index 00000000..dc11343c --- /dev/null +++ b/assets/1500-1599/1583.Count Unhappy Friends/README_EN.md @@ -0,0 +1,94 @@ +# [1583. Count Unhappy Friends](https://leetcode.com/problems/count-unhappy-friends) + + + +## Description + +

    You are given a list of preferences for n friends, where n is always even.

    + +

    For each person ipreferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.

    + +

    All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.

    + +

    However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:

    + +
      +
    • x prefers u over y, and
    • +
    • u prefers x over v.
    • +
    + +

    Return the number of unhappy friends.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
    +Output: 2
    +Explanation:
    +Friend 1 is unhappy because:
    +- 1 is paired with 0 but prefers 3 over 0, and
    +- 3 prefers 1 over 2.
    +Friend 3 is unhappy because:
    +- 3 is paired with 2 but prefers 1 over 2, and
    +- 1 prefers 3 over 0.
    +Friends 0 and 2 are happy.
    +
    + +

    Example 2:

    + +
    +Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
    +Output: 0
    +Explanation: Both friends 0 and 1 are happy.
    +
    + +

    Example 3:

    + +
    +Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 500
    • +
    • n is even.
    • +
    • preferences.length == n
    • +
    • preferences[i].length == n - 1
    • +
    • 0 <= preferences[i][j] <= n - 1
    • +
    • preferences[i] does not contain i.
    • +
    • All values in preferences[i] are unique.
    • +
    • pairs.length == n/2
    • +
    • pairs[i].length == 2
    • +
    • xi != yi
    • +
    • 0 <= xi, yi <= n - 1
    • +
    • Each person is contained in exactly one pair.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1584.Min Cost to Connect All Points/README_EN.md b/assets/1500-1599/1584.Min Cost to Connect All Points/README_EN.md new file mode 100644 index 00000000..9a0885c0 --- /dev/null +++ b/assets/1500-1599/1584.Min Cost to Connect All Points/README_EN.md @@ -0,0 +1,87 @@ +# [1584. Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points) + + + +## Description + +

    You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].

    + +

    The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.

    + +

    Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
    +Output: 20
    +Explanation:
    +
    +We can connect the points as shown above to get the minimum cost of 20.
    +Notice that there is a unique path between every pair of points.
    +
    + +

    Example 2:

    + +
    +Input: points = [[3,12],[-2,5],[-4,1]]
    +Output: 18
    +
    + +

    Example 3:

    + +
    +Input: points = [[0,0],[1,1],[1,0],[-1,1]]
    +Output: 4
    +
    + +

    Example 4:

    + +
    +Input: points = [[-1000000,-1000000],[1000000,1000000]]
    +Output: 4000000
    +
    + +

    Example 5:

    + +
    +Input: points = [[0,0]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= points.length <= 1000
    • +
    • -106 <= xi, yi <= 106
    • +
    • All pairs (xi, yi) are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1584.Min Cost to Connect All Points/images/c.png b/assets/1500-1599/1584.Min Cost to Connect All Points/images/c.png new file mode 100644 index 00000000..acef7869 Binary files /dev/null and b/assets/1500-1599/1584.Min Cost to Connect All Points/images/c.png differ diff --git a/assets/1500-1599/1584.Min Cost to Connect All Points/images/d.png b/assets/1500-1599/1584.Min Cost to Connect All Points/images/d.png new file mode 100644 index 00000000..5c26da66 Binary files /dev/null and b/assets/1500-1599/1584.Min Cost to Connect All Points/images/d.png differ diff --git a/assets/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md b/assets/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md new file mode 100644 index 00000000..457efe9e --- /dev/null +++ b/assets/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md @@ -0,0 +1,86 @@ +# [1585. Check If String Is Transformable With Substring Sort Operations](https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations) + + + +## Description + +

    Given two strings s and t, you want to transform string s into string t using the following operation any number of times:

    + +
      +
    • Choose a non-empty substring in s and sort it in-place so the characters are in ascending order.
    • +
    + +

    For example, applying the operation on the underlined substring in "14234" results in "12344".

    + +

    Return true if it is possible to transform string s into string t. Otherwise, return false.

    + +

    A substring is a contiguous sequence of characters within a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "84532", t = "34852"
    +Output: true
    +Explanation: You can transform s into t using the following sort operations:
    +"84532" (from index 2 to 3) -> "84352"
    +"84352" (from index 0 to 2) -> "34852"
    +
    + +

    Example 2:

    + +
    +Input: s = "34521", t = "23415"
    +Output: true
    +Explanation: You can transform s into t using the following sort operations:
    +"34521" -> "23451"
    +"23451" -> "23415"
    +
    + +

    Example 3:

    + +
    +Input: s = "12345", t = "12435"
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: s = "1", t = "2"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • s.length == t.length
    • +
    • 1 <= s.length <= 105
    • +
    • s and t only contain digits from '0' to '9'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md b/assets/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md new file mode 100644 index 00000000..5bbc4f3b --- /dev/null +++ b/assets/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md @@ -0,0 +1,84 @@ +# [1586. Binary Search Tree Iterator II](https://leetcode.com/problems/binary-search-tree-iterator-ii) + + + +## Description + +

    Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):

    + +
      +
    • BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
    • +
    • boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
    • +
    • int next() Moves the pointer to the right, then returns the number at the pointer.
    • +
    • boolean hasPrev() Returns true if there exists a number in the traversal to the left of the pointer, otherwise returns false.
    • +
    • int prev() Moves the pointer to the left, then returns the number at the pointer.
    • +
    + +

    Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.

    + +

    You may assume that next() and prev() calls will always be valid. That is, there will be at least a next/previous number in the in-order traversal when next()/prev() is called.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input
    +["BSTIterator", "next", "next", "prev", "next", "hasNext", "next", "next", "next", "hasNext", "hasPrev", "prev", "prev"]
    +[[[7, 3, 15, null, null, 9, 20]], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null]]
    +Output
    +[null, 3, 7, 3, 7, true, 9, 15, 20, false, true, 15, 9]
    +
    +Explanation
    +// The underlined element is where the pointer currently is.
    +BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); // state is   [3, 7, 9, 15, 20]
    +bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 3
    +bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 7
    +bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 3
    +bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 7
    +bSTIterator.hasNext(); // return true
    +bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 9
    +bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 15
    +bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 20
    +bSTIterator.hasNext(); // return false
    +bSTIterator.hasPrev(); // return true
    +bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 15
    +bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 9
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 105].
    • +
    • 0 <= Node.val <= 106
    • +
    • At most 105 calls will be made to hasNext, next, hasPrev, and prev.
    • +
    + +

     

    +Follow up: Could you solve the problem without precalculating the values of the tree? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1586.Binary Search Tree Iterator II/images/untitled-diagram-1.png b/assets/1500-1599/1586.Binary Search Tree Iterator II/images/untitled-diagram-1.png new file mode 100644 index 00000000..27458a3e Binary files /dev/null and b/assets/1500-1599/1586.Binary Search Tree Iterator II/images/untitled-diagram-1.png differ diff --git a/assets/1500-1599/1587.Bank Account Summary II/README_EN.md b/assets/1500-1599/1587.Bank Account Summary II/README_EN.md new file mode 100644 index 00000000..1da66ea7 --- /dev/null +++ b/assets/1500-1599/1587.Bank Account Summary II/README_EN.md @@ -0,0 +1,106 @@ +# [1587. Bank Account Summary II](https://leetcode.com/problems/bank-account-summary-ii) + + + +## Description + +

    Table: Users

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| account      | int     |
    +| name         | varchar |
    ++--------------+---------+
    +account is the primary key for this table.
    +Each row of this table contains the account number of each user in the bank.
    +
    + +

     

    + +

    Table: Transactions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| trans_id      | int     |
    +| account       | int     |
    +| amount        | int     |
    +| transacted_on | date    |
    ++---------------+---------+
    +trans_id is the primary key for this table.
    +Each row of this table contains all changes made to all accounts.
    +amount is positive if the user received money and negative if they transferred money.
    +All accounts start with a balance 0.
    +
    + +

     

    + +

    Write an SQL query to report the name and balance of users with a balance higher than 10000. The balance of an account is equal to the sum of the amounts of all transactions involving that account.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Users table:
    ++------------+--------------+
    +| account    | name         |
    ++------------+--------------+
    +| 900001     | Alice        |
    +| 900002     | Bob          |
    +| 900003     | Charlie      |
    ++------------+--------------+
    +
    +Transactions table:
    ++------------+------------+------------+---------------+
    +| trans_id   | account    | amount     | transacted_on |
    ++------------+------------+------------+---------------+
    +| 1          | 900001     | 7000       |  2020-08-01   |
    +| 2          | 900001     | 7000       |  2020-09-01   |
    +| 3          | 900001     | -3000      |  2020-09-02   |
    +| 4          | 900002     | 1000       |  2020-09-12   |
    +| 5          | 900003     | 6000       |  2020-08-07   |
    +| 6          | 900003     | 6000       |  2020-09-07   |
    +| 7          | 900003     | -4000      |  2020-09-11   |
    ++------------+------------+------------+---------------+
    +
    +Result table:
    ++------------+------------+
    +| name       | balance    |
    ++------------+------------+
    +| Alice      | 11000      |
    ++------------+------------+
    +Alice's balance is (7000 + 7000 - 3000) = 11000.
    +Bob's balance is 1000.
    +Charlie's balance is (6000 + 6000 - 4000) = 8000.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md b/assets/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md new file mode 100644 index 00000000..c6360137 --- /dev/null +++ b/assets/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md @@ -0,0 +1,76 @@ +# [1588. Sum of All Odd Length Subarrays](https://leetcode.com/problems/sum-of-all-odd-length-subarrays) + + + +## Description + +

    Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.

    + +

    A subarray is a contiguous subsequence of the array.

    + +

    Return the sum of all odd-length subarrays of arr.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,4,2,5,3]
    +Output: 58
    +Explanation: The odd-length subarrays of arr and their sums are:
    +[1] = 1
    +[4] = 4
    +[2] = 2
    +[5] = 5
    +[3] = 3
    +[1,4,2] = 7
    +[4,2,5] = 11
    +[2,5,3] = 10
    +[1,4,2,5,3] = 15
    +If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
    + +

    Example 2:

    + +
    +Input: arr = [1,2]
    +Output: 3
    +Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
    + +

    Example 3:

    + +
    +Input: arr = [10,11,12]
    +Output: 66
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md b/assets/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md new file mode 100644 index 00000000..1f0155bb --- /dev/null +++ b/assets/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md @@ -0,0 +1,78 @@ +# [1589. Maximum Sum Obtained of Any Permutation](https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation) + + + +## Description + +

    We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.

    + +

    Return the maximum total sum of all requests among all permutations of nums.

    + +

    Since the answer may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
    +Output: 19
    +Explanation: One permutation of nums is [2,1,3,4,5] with the following result: 
    +requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
    +requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
    +Total sum: 8 + 3 = 11.
    +A permutation with a higher total sum is [3,5,4,2,1] with the following result:
    +requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
    +requests[1] -> nums[0] + nums[1] = 3 + 5  = 8
    +Total sum: 11 + 8 = 19, which is the best that you can do.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
    +Output: 11
    +Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
    +Output: 47
    +Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 105
    • +
    • 0 <= nums[i] <= 105
    • +
    • 1 <= requests.length <= 105
    • +
    • requests[i].length == 2
    • +
    • 0 <= starti <= endi < n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1590.Make Sum Divisible by P/README_EN.md b/assets/1500-1599/1590.Make Sum Divisible by P/README_EN.md new file mode 100644 index 00000000..5b322b03 --- /dev/null +++ b/assets/1500-1599/1590.Make Sum Divisible by P/README_EN.md @@ -0,0 +1,133 @@ +# [1590. Make Sum Divisible by P](https://leetcode.com/problems/make-sum-divisible-by-p) + + + +## Description + +

    Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.

    + + + +

    Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.

    + + + +

    A subarray is defined as a contiguous block of elements in the array.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [3,1,4,2], p = 6
    +
    +Output: 1
    +
    +Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [6,3,5,2], p = 9
    +
    +Output: 2
    +
    +Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [1,2,3], p = 3
    +
    +Output: 0
    +
    +Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: nums = [1,2,3], p = 7
    +
    +Output: -1
    +
    +Explanation: There is no way to remove a subarray in order to get a sum divisible by 7.
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: nums = [1000000000,1000000000,1000000000], p = 3
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • 1 <= p <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1591.Strange Printer II/README_EN.md b/assets/1500-1599/1591.Strange Printer II/README_EN.md new file mode 100644 index 00000000..3c9f4ad0 --- /dev/null +++ b/assets/1500-1599/1591.Strange Printer II/README_EN.md @@ -0,0 +1,84 @@ +# [1591. Strange Printer II](https://leetcode.com/problems/strange-printer-ii) + + + +## Description + +

    There is a strange printer with the following two special requirements:

    + +
      +
    • On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
    • +
    • Once the printer has used a color for the above operation, the same color cannot be used again.
    • +
    + +

    You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.

    + +

    Return true if it is possible to print the matrix targetGrid, otherwise, return false.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]
    +Output: true
    +
    + +

    Example 2:

    + +

    + +
    +Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]
    +Output: false
    +Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.
    + +

    Example 4:

    + +
    +Input: targetGrid = [[1,1,1],[3,1,3]]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == targetGrid.length
    • +
    • n == targetGrid[i].length
    • +
    • 1 <= m, n <= 60
    • +
    • 1 <= targetGrid[row][col] <= 60
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1591.Strange Printer II/images/sample_1_1929.png b/assets/1500-1599/1591.Strange Printer II/images/sample_1_1929.png new file mode 100644 index 00000000..0e53462f Binary files /dev/null and b/assets/1500-1599/1591.Strange Printer II/images/sample_1_1929.png differ diff --git a/assets/1500-1599/1591.Strange Printer II/images/sample_2_1929.png b/assets/1500-1599/1591.Strange Printer II/images/sample_2_1929.png new file mode 100644 index 00000000..81721eb0 Binary files /dev/null and b/assets/1500-1599/1591.Strange Printer II/images/sample_2_1929.png differ diff --git a/assets/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md b/assets/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md new file mode 100644 index 00000000..693167ad --- /dev/null +++ b/assets/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md @@ -0,0 +1,83 @@ +# [1592. Rearrange Spaces Between Words](https://leetcode.com/problems/rearrange-spaces-between-words) + + + +## Description + +

    You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.

    + +

    Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.

    + +

    Return the string after rearranging the spaces.

    + +

     

    +

    Example 1:

    + +
    +Input: text = "  this   is  a sentence "
    +Output: "this   is   a   sentence"
    +Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.
    +
    + +

    Example 2:

    + +
    +Input: text = " practice   makes   perfect"
    +Output: "practice   makes   perfect "
    +Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.
    +
    + +

    Example 3:

    + +
    +Input: text = "hello   world"
    +Output: "hello   world"
    +
    + +

    Example 4:

    + +
    +Input: text = "  walks  udp package   into  bar a"
    +Output: "walks  udp  package  into  bar  a "
    +
    + +

    Example 5:

    + +
    +Input: text = "a"
    +Output: "a"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 100
    • +
    • text consists of lowercase English letters and ' '.
    • +
    • text contains at least one word.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md b/assets/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md new file mode 100644 index 00000000..5332e6b7 --- /dev/null +++ b/assets/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md @@ -0,0 +1,73 @@ +# [1593. Split a String Into the Max Number of Unique Substrings](https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings) + + + +## Description + +

    Given a string s, return the maximum number of unique substrings that the given string can be split into.

    + +

    You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.

    + +

    A substring is a contiguous sequence of characters within a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "ababccc"
    +Output: 5
    +Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
    +
    + +

    Example 2:

    + +
    +Input: s = "aba"
    +Output: 2
    +Explanation: One way to split maximally is ['a', 'ba'].
    +
    + +

    Example 3:

    + +
    +Input: s = "aa"
    +Output: 1
    +Explanation: It is impossible to split the string any further.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • +

      1 <= s.length <= 16

      +
    • +
    • +

      s contains only lower case English letters.

      +
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md b/assets/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md new file mode 100644 index 00000000..4417e934 --- /dev/null +++ b/assets/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md @@ -0,0 +1,86 @@ +# [1594. Maximum Non Negative Product in a Matrix](https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix) + + + +## Description + +

    You are given a rows x cols matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.

    + +

    Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (rows - 1, cols - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.

    + +

    Return the maximum non-negative product modulo 109 + 7If the maximum product is negative return -1.

    + +

    Notice that the modulo is performed after getting the maximum product.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[-1,-2,-3],
    +               [-2,-3,-3],
    +               [-3,-3,-2]]
    +Output: -1
    +Explanation: It's not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,-2,1],
    +               [1,-2,1],
    +               [3,-4,1]]
    +Output: 8
    +Explanation: Maximum non-negative product is in bold (1 * 1 * -2 * -4 * 1 = 8).
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1, 3],
    +               [0,-4]]
    +Output: 0
    +Explanation: Maximum non-negative product is in bold (1 * 0 * -4 = 0).
    +
    + +

    Example 4:

    + +
    +Input: grid = [[ 1, 4,4,0],
    +               [-2, 0,0,1],
    +               [ 1,-1,1,1]]
    +Output: 2
    +Explanation: Maximum non-negative product is in bold (1 * -2 * 1 * -1 * 1 * 1 = 2).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= rows, cols <= 15
    • +
    • -4 <= grid[i][j] <= 4
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md b/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md new file mode 100644 index 00000000..678fdf20 --- /dev/null +++ b/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md @@ -0,0 +1,80 @@ +# [1595. Minimum Cost to Connect Two Groups of Points](https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points) + + + +## Description + +

    You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.

    + +

    The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.

    + +

    Return the minimum cost it takes to connect the two groups.

    + +

     

    +

    Example 1:

    + +
    +Input: cost = [[15, 96], [36, 2]]
    +Output: 17
    +Explanation: The optimal way of connecting the groups is:
    +1--A
    +2--B
    +This results in a total cost of 17.
    +
    + +

    Example 2:

    + +
    +Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]
    +Output: 4
    +Explanation: The optimal way of connecting the groups is:
    +1--A
    +2--B
    +2--C
    +3--A
    +This results in a total cost of 4.
    +Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.
    +
    + +

    Example 3:

    + +
    +Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]
    +Output: 10
    +
    + +

     

    +

    Constraints:

    + +
      +
    • size1 == cost.length
    • +
    • size2 == cost[i].length
    • +
    • 1 <= size1, size2 <= 12
    • +
    • size1 >= size2
    • +
    • 0 <= cost[i][j] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/images/ex1.jpg b/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/images/ex1.jpg new file mode 100644 index 00000000..a85c4eed Binary files /dev/null and b/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/images/ex1.jpg differ diff --git a/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/images/ex2.jpg b/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/images/ex2.jpg new file mode 100644 index 00000000..3abe8fd3 Binary files /dev/null and b/assets/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/images/ex2.jpg differ diff --git a/assets/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md b/assets/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md new file mode 100644 index 00000000..7242a6d3 --- /dev/null +++ b/assets/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md @@ -0,0 +1,140 @@ +# [1596. The Most Frequently Ordered Products for Each Customer](https://leetcode.com/problems/the-most-frequently-ordered-products-for-each-customer) + + + +## Description + +

    Table: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    ++---------------+---------+
    +customer_id is the primary key for this table.
    +This table contains information about the customers.
    +
    + +

     

    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| product_id    | int     |
    ++---------------+---------+
    +order_id is the primary key for this table.
    +This table contains information about the orders made by customer_id.
    +No customer will order the same product more than once in a single day.
    + +

     

    + +

    Table: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    +| price         | int     |
    ++---------------+---------+
    +product_id is the primary key for this table.
    +This table contains information about the products.
    +
    + +

     

    + +

    Write an SQL query to find the most frequently ordered product(s) for each customer.

    + +

    The result table should have the product_id and product_name for each customer_id who ordered at least one order. Return the result table in any order.

    + +

    The query result format is in the following example:

    + +
    +Customers
    ++-------------+-------+
    +| customer_id | name  |
    ++-------------+-------+
    +| 1           | Alice |
    +| 2           | Bob   |
    +| 3           | Tom   |
    +| 4           | Jerry |
    +| 5           | John  |
    ++-------------+-------+
    +
    +Orders
    ++----------+------------+-------------+------------+
    +| order_id | order_date | customer_id | product_id |
    ++----------+------------+-------------+------------+
    +| 1        | 2020-07-31 | 1           | 1          |
    +| 2        | 2020-07-30 | 2           | 2          |
    +| 3        | 2020-08-29 | 3           | 3          |
    +| 4        | 2020-07-29 | 4           | 1          |
    +| 5        | 2020-06-10 | 1           | 2          |
    +| 6        | 2020-08-01 | 2           | 1          |
    +| 7        | 2020-08-01 | 3           | 3          |
    +| 8        | 2020-08-03 | 1           | 2          |
    +| 9        | 2020-08-07 | 2           | 3          |
    +| 10       | 2020-07-15 | 1           | 2          |
    ++----------+------------+-------------+------------+
    +
    +Products
    ++------------+--------------+-------+
    +| product_id | product_name | price |
    ++------------+--------------+-------+
    +| 1          | keyboard     | 120   |
    +| 2          | mouse        | 80    |
    +| 3          | screen       | 600   |
    +| 4          | hard disk    | 450   |
    ++------------+--------------+-------+
    +Result table:
    ++-------------+------------+--------------+
    +| customer_id | product_id | product_name |
    ++-------------+------------+--------------+
    +| 1           | 2          | mouse        |
    +| 2           | 1          | keyboard     |
    +| 2           | 2          | mouse        |
    +| 2           | 3          | screen       |
    +| 3           | 3          | screen       |
    +| 4           | 1          | keyboard     |
    ++-------------+------------+--------------+
    +
    +Alice (customer 1) ordered the mouse three times and the keyboard one time, so the mouse is the most frquently ordered product for them.
    +Bob (customer 2) ordered the keyboard, the mouse, and the screen one time, so those are the most frquently ordered products for them.
    +Tom (customer 3) only ordered the screen (two times), so that is the most frquently ordered product for them.
    +Jerry (customer 4) only ordered the keyboard (one time), so that is the most frquently ordered product for them.
    +John (customer 5) did not order anything, so we do not include them in the result table.
    +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md new file mode 100644 index 00000000..c0fe8be0 --- /dev/null +++ b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md @@ -0,0 +1,81 @@ +# [1597. Build Binary Expression Tree From Infix Expression](https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression) + + + +## Description + +

    A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with 2 children) correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and '/' (division).

    + +

    For each internal node with operator o, the infix expression that it represents is (A o B), where A is the expression the left subtree represents and B is the expression the right subtree represents.

    + +

    You are given a string s, an infix expression containing operands, the operators described above, and parentheses '(' and ')'.

    + +

    Return any valid binary expression tree, which its in-order traversal reproduces s after omitting the parenthesis from it (see examples below).

    + +

    Please note that order of operations applies in s. That is, expressions in parentheses are evaluated first, and multiplication and division happen before addition and subtraction.

    + +

    Operands must also appear in the same order in both s and the in-order traversal of the tree.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "3*4-2*5"
    +Output: [-,*,*,3,4,2,5]
    +Explanation: The tree above is the only valid tree whose inorder traversal produces s.
    +
    + +

    Example 2:

    + +
    +Input: s = "2-3/(5*2)+1"
    +Output: [+,-,1,2,/,null,null,null,null,3,*,null,null,5,2]
    +Explanation: The inorder traversal of the tree above is 2-3/5*2+1 which is the same as s without the parenthesis. The tree also produces the correct result and its operands are in the same order as they appear in s.
    +The tree below is also a valid binary expression tree with the same inorder traversal as s, but it not a valid answer because it does not evaluate to the same value.
    +
    +The third tree below is also not valid. Although it produces the same result and is equivalent to the above trees, its inorder traversal does not produce s and its operands are not in the same order as s.
    +
    +
    + +

    Example 3:

    + +
    +Input: s = "1+2+3+4+5"
    +Output: [+,+,5,+,4,null,null,+,3,null,null,1,2]
    +Explanation: The tree [+,+,5,+,+,null,null,1,2,3,4] is also one of many other valid trees.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s consists of digits and the characters '+', '-', '*', and '/'.
    • +
    • Operands in s are exactly 1 digit.
    • +
    • It is guaranteed that s is a valid expression.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-1.png b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-1.png new file mode 100644 index 00000000..d733d220 Binary files /dev/null and b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-1.png differ diff --git a/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-2.png b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-2.png new file mode 100644 index 00000000..8f4d173a Binary files /dev/null and b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-2.png differ diff --git a/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-3.png b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-3.png new file mode 100644 index 00000000..a41c08bb Binary files /dev/null and b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-3.png differ diff --git a/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-4.png b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-4.png new file mode 100644 index 00000000..f0d41696 Binary files /dev/null and b/assets/1500-1599/1597.Build Binary Expression Tree From Infix Expression/images/ex1-4.png differ diff --git a/assets/1500-1599/1598.Crawler Log Folder/README_EN.md b/assets/1500-1599/1598.Crawler Log Folder/README_EN.md new file mode 100644 index 00000000..6aa83245 --- /dev/null +++ b/assets/1500-1599/1598.Crawler Log Folder/README_EN.md @@ -0,0 +1,84 @@ +# [1598. Crawler Log Folder](https://leetcode.com/problems/crawler-log-folder) + + + +## Description + +

    The Leetcode file system keeps a log each time some user performs a change folder operation.

    + +

    The operations are described below:

    + +
      +
    • "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).
    • +
    • "./" : Remain in the same folder.
    • +
    • "x/" : Move to the child folder named x (This folder is guaranteed to always exist).
    • +
    + +

    You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.

    + +

    The file system starts in the main folder, then the operations in logs are performed.

    + +

    Return the minimum number of operations needed to go back to the main folder after the change folder operations.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: logs = ["d1/","d2/","../","d21/","./"]
    +Output: 2
    +Explanation: Use this change folder operation "../" 2 times and go back to the main folder.
    +
    + +

    Example 2:

    + +

    + +
    +Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
    +Output: 3
    +
    + +

    Example 3:

    + +
    +Input: logs = ["d1/","../","../","../"]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= logs.length <= 103
    • +
    • 2 <= logs[i].length <= 10
    • +
    • logs[i] contains lowercase English letters, digits, '.', and '/'.
    • +
    • logs[i] follows the format described in the statement.
    • +
    • Folder names consist of lowercase English letters and digits.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1598.Crawler Log Folder/images/sample_11_1957.png b/assets/1500-1599/1598.Crawler Log Folder/images/sample_11_1957.png new file mode 100644 index 00000000..5535bc03 Binary files /dev/null and b/assets/1500-1599/1598.Crawler Log Folder/images/sample_11_1957.png differ diff --git a/assets/1500-1599/1598.Crawler Log Folder/images/sample_22_1957.png b/assets/1500-1599/1598.Crawler Log Folder/images/sample_22_1957.png new file mode 100644 index 00000000..b3c836a7 Binary files /dev/null and b/assets/1500-1599/1598.Crawler Log Folder/images/sample_22_1957.png differ diff --git a/assets/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md b/assets/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md new file mode 100644 index 00000000..86879b15 --- /dev/null +++ b/assets/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md @@ -0,0 +1,110 @@ +# [1599. Maximum Profit of Operating a Centennial Wheel](https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel) + + + +## Description + +

    You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.

    + +

    You are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.

    + +

    You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.

    + +

    Return the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: customers = [8,3], boardingCost = 5, runningCost = 6
    +Output: 3
    +Explanation: The numbers written on the gondolas are the number of people currently there.
    +1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.
    +2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.
    +3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.
    +The highest profit was $37 after rotating the wheel 3 times.
    + +

    Example 2:

    + +
    +Input: customers = [10,9,6], boardingCost = 6, runningCost = 4
    +Output: 7
    +Explanation:
    +1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.
    +2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.
    +3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.
    +4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.
    +5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.
    +6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.
    +7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.
    +The highest profit was $122 after rotating the wheel 7 times.
    +
    +
    + +

    Example 3:

    + +
    +Input: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92
    +Output: -1
    +Explanation:
    +1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.
    +2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.
    +3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.
    +4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.
    +5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.
    +The profit was never positive, so return -1.
    +
    + +

    Example 4:

    + +
    +Input: customers = [10,10,6,4,7], boardingCost = 3, runningCost = 8
    +Output: 9
    +Explanation:
    +1. 10 customers arrive, 4 board and 6 wait, the wheel rotates. Current profit is 4 * $3 - 1 * $8 = $4.
    +2. 10 customers arrive, 4 board and 12 wait, the wheel rotates. Current profit is 8 * $3 - 2 * $8 = $8.
    +3. 6 customers arrive, 4 board and 14 wait, the wheel rotates. Current profit is 12 * $3 - 3 * $8 = $12.
    +4. 4 customers arrive, 4 board and 14 wait, the wheel rotates. Current profit is 16 * $3 - 4 * $8 = $16.
    +5. 7 customers arrive, 4 board and 17 wait, the wheel rotates. Current profit is 20 * $3 - 5 * $8 = $20.
    +6. 4 board and 13 wait, the wheel rotates. Current profit is 24 * $3 - 6 * $8 = $24.
    +7. 4 board and 9 wait, the wheel rotates. Current profit is 28 * $3 - 7 * $8 = $28.
    +8. 4 board and 5 wait, the wheel rotates. Current profit is 32 * $3 - 8 * $8 = $32.
    +9. 4 board and 1 waits, the wheel rotates. Current profit is 36 * $3 - 9 * $8 = $36.
    +10. 1 board and 0 wait, the wheel rotates. Current profit is 37 * $3 - 10 * $8 = $31.
    +The highest profit was $36 after rotating the wheel 9 times.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == customers.length
    • +
    • 1 <= n <= 105
    • +
    • 0 <= customers[i] <= 50
    • +
    • 1 <= boardingCost, runningCost <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/images/wheeldiagram12.png b/assets/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/images/wheeldiagram12.png new file mode 100644 index 00000000..7d97cd5f Binary files /dev/null and b/assets/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/images/wheeldiagram12.png differ diff --git a/assets/1600-1699/1600.Throne Inheritance/README_EN.md b/assets/1600-1699/1600.Throne Inheritance/README_EN.md new file mode 100644 index 00000000..39cb934e --- /dev/null +++ b/assets/1600-1699/1600.Throne Inheritance/README_EN.md @@ -0,0 +1,99 @@ +# [1600. Throne Inheritance](https://leetcode.com/problems/throne-inheritance) + + + +## Description + +

    A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.

    + +

    The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.

    + +
    +Successor(x, curOrder):
    +    if x has no children or all of x's children are in curOrder:
    +        if x is the king return null
    +        else return Successor(x's parent, curOrder)
    +    else return x's oldest child who's not in curOrder
    +
    + +

    For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.

    + +
      +
    1. In the beginning, curOrder will be ["king"].
    2. +
    3. Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].
    4. +
    5. Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].
    6. +
    7. Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].
    8. +
    9. Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"].
    10. +
    + +

    Using the above function, we can always obtain a unique order of inheritance.

    + +

    Implement the ThroneInheritance class:

    + +
      +
    • ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.
    • +
    • void birth(string parentName, string childName) Indicates that parentName gave birth to childName.
    • +
    • void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.
    • +
    • string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
    +[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
    +Output
    +[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
    +
    +Explanation
    +ThroneInheritance t= new ThroneInheritance("king"); // order: king
    +t.birth("king", "andy"); // order: king > andy
    +t.birth("king", "bob"); // order: king > andy > bob
    +t.birth("king", "catherine"); // order: king > andy > bob > catherine
    +t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine
    +t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine
    +t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine
    +t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
    +t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine
    +t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= kingName.length, parentName.length, childName.length, name.length <= 15
    • +
    • kingName, parentName, childName, and name consist of lowercase English letters only.
    • +
    • All arguments childName and kingName are distinct.
    • +
    • All name arguments of death will be passed to either the constructor or as childName to birth first.
    • +
    • For each call to birth(parentName, childName), it is guaranteed that parentName is alive.
    • +
    • At most 105 calls will be made to birth and death.
    • +
    • At most 10 calls will be made to getInheritanceOrder.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md b/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md new file mode 100644 index 00000000..2a58571d --- /dev/null +++ b/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md @@ -0,0 +1,82 @@ +# [1601. Maximum Number of Achievable Transfer Requests](https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests) + + + +## Description + +

    We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.

    + +

    You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.

    + +

    All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.

    + +

    Return the maximum number of achievable requests.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
    +Output: 5
    +Explantion: Let's see the requests:
    +From building 0 we have employees x and y and both want to move to building 1.
    +From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
    +From building 2 we have employee z and they want to move to building 0.
    +From building 3 we have employee c and they want to move to building 4.
    +From building 4 we don't have any requests.
    +We can achieve the requests of users x and b by swapping their places.
    +We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
    +
    + +

    Example 2:

    + +
    +Input: n = 3, requests = [[0,0],[1,2],[2,1]]
    +Output: 3
    +Explantion: Let's see the requests:
    +From building 0 we have employee x and they want to stay in the same building 0.
    +From building 1 we have employee y and they want to move to building 2.
    +From building 2 we have employee z and they want to move to building 1.
    +We can achieve all the requests. 
    + +

    Example 3:

    + +
    +Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 20
    • +
    • 1 <= requests.length <= 16
    • +
    • requests[i].length == 2
    • +
    • 0 <= fromi, toi < n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/images/move1.jpg b/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/images/move1.jpg new file mode 100644 index 00000000..742b20ec Binary files /dev/null and b/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/images/move1.jpg differ diff --git a/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/images/move2.jpg b/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/images/move2.jpg new file mode 100644 index 00000000..7f652a38 Binary files /dev/null and b/assets/1600-1699/1601.Maximum Number of Achievable Transfer Requests/images/move2.jpg differ diff --git a/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md b/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md new file mode 100644 index 00000000..64804472 --- /dev/null +++ b/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md @@ -0,0 +1,77 @@ +# [1602. Find Nearest Right Node in Binary Tree](https://leetcode.com/problems/find-nearest-right-node-in-binary-tree) + + + +## Description + +

    Given the root of a binary tree and a node u in the tree, return the nearest node on the same level that is to the right of u, or return null if u is the rightmost node in its level.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [1,2,3,null,4,5,6], u = 4
    +Output: 5
    +Explanation: The nearest node on the same level to the right of node 4 is node 5.
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [3,null,4,2], u = 2
    +Output: null
    +Explanation: There are no nodes to the right of 2.
    +
    + +

    Example 3:

    + +
    +Input: root = [1], u = 1
    +Output: null
    +
    + +

    Example 4:

    + +
    +Input: root = [3,4,2,null,null,null,1], u = 4
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 105].
    • +
    • 1 <= Node.val <= 105
    • +
    • All values in the tree are distinct.
    • +
    • u is a node in the binary tree rooted at root.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/images/p2.png b/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/images/p2.png new file mode 100644 index 00000000..e77ecfa6 Binary files /dev/null and b/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/images/p2.png differ diff --git a/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/images/p3.png b/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/images/p3.png new file mode 100644 index 00000000..5119b675 Binary files /dev/null and b/assets/1600-1699/1602.Find Nearest Right Node in Binary Tree/images/p3.png differ diff --git a/assets/1600-1699/1603.Design Parking System/README_EN.md b/assets/1600-1699/1603.Design Parking System/README_EN.md new file mode 100644 index 00000000..a2e76509 --- /dev/null +++ b/assets/1600-1699/1603.Design Parking System/README_EN.md @@ -0,0 +1,104 @@ +# [1603. Design Parking System](https://leetcode.com/problems/design-parking-system) + + + +## Description + +

    Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.

    + +

    Implement the ParkingSystem class:

    + +
      +
    • ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.
    • +
    • bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
    +[[1, 1, 0], [1], [2], [3], [1]]
    +Output
    +[null, true, true, false, false]
    +
    +Explanation
    +ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
    +parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
    +parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
    +parkingSystem.addCar(3); // return false because there is no available slot for a small car
    +parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= big, medium, small <= 1000
    • +
    • carType is 1, 2, or 3
    • +
    • At most 1000 calls will be made to addCar
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class ParkingSystem: + + def __init__(self, big: int, medium: int, small: int): + self.spaces = [big, medium, small] + + + def addCar(self, carType: int) -> bool: + if self.spaces[carType - 1] <= 0: + return False + self.spaces[carType - 1] -= 1 + return True + + +# Your ParkingSystem object will be instantiated and called as such: +# obj = ParkingSystem(big, medium, small) +# param_1 = obj.addCar(carType) +``` + +### **Java** + +```java +class ParkingSystem { + + private int[] spaces = new int[3]; + + public ParkingSystem(int big, int medium, int small) { + spaces[0] = big; + spaces[1] = medium; + spaces[2] = small; + } + + public boolean addCar(int carType) { + if (spaces[carType - 1] <= 0) { + return false; + } + --spaces[carType - 1]; + return true; + } +} + +/** + * Your ParkingSystem object will be instantiated and called as such: + * ParkingSystem obj = new ParkingSystem(big, medium, small); + * boolean param_1 = obj.addCar(carType); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md b/assets/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md new file mode 100644 index 00000000..885639be --- /dev/null +++ b/assets/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md @@ -0,0 +1,83 @@ +# [1604. Alert Using Same Key-Card Three or More Times in a One Hour Period](https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period) + + + +## Description + +

    LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.

    + +

    You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.

    + +

    Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49".

    + +

    Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.

    + +

    Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not considered to be within a one-hour period.

    + +

     

    +

    Example 1:

    + +
    +Input: keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
    +Output: ["daniel"]
    +Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").
    +
    + +

    Example 2:

    + +
    +Input: keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]
    +Output: ["bob"]
    +Explanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30").
    +
    + +

    Example 3:

    + +
    +Input: keyName = ["john","john","john"], keyTime = ["23:58","23:59","00:01"]
    +Output: []
    +
    + +

    Example 4:

    + +
    +Input: keyName = ["leslie","leslie","leslie","clare","clare","clare","clare"], keyTime = ["13:00","13:20","14:00","18:00","18:51","19:30","19:49"]
    +Output: ["clare","leslie"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= keyName.length, keyTime.length <= 105
    • +
    • keyName.length == keyTime.length
    • +
    • keyTime[i] is in the format "HH:MM".
    • +
    • [keyName[i], keyTime[i]] is unique.
    • +
    • 1 <= keyName[i].length <= 10
    • +
    • keyName[i] contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md b/assets/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md new file mode 100644 index 00000000..0da3afdd --- /dev/null +++ b/assets/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md @@ -0,0 +1,94 @@ +# [1605. Find Valid Matrix Given Row and Column Sums](https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums) + + + +## Description + +

    You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.

    + +

    Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.

    + +

    Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.

    + +

     

    +

    Example 1:

    + +
    +Input: rowSum = [3,8], colSum = [4,7]
    +Output: [[3,0],
    +         [1,7]]
    +Explanation:
    +0th row: 3 + 0 = 3 == rowSum[0]
    +1st row: 1 + 7 = 8 == rowSum[1]
    +0th column: 3 + 1 = 4 == colSum[0]
    +1st column: 0 + 7 = 7 == colSum[1]
    +The row and column sums match, and all matrix elements are non-negative.
    +Another possible matrix is: [[1,2],
    +                             [3,5]]
    +
    + +

    Example 2:

    + +
    +Input: rowSum = [5,7,10], colSum = [8,6,8]
    +Output: [[0,5,0],
    +         [6,1,0],
    +         [2,0,8]]
    +
    + +

    Example 3:

    + +
    +Input: rowSum = [14,9], colSum = [6,9,8]
    +Output: [[0,9,5],
    +         [6,0,3]]
    +
    + +

    Example 4:

    + +
    +Input: rowSum = [1,0], colSum = [1]
    +Output: [[1],
    +         [0]]
    +
    + +

    Example 5:

    + +
    +Input: rowSum = [0], colSum = [0]
    +Output: [[0]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= rowSum.length, colSum.length <= 500
    • +
    • 0 <= rowSum[i], colSum[i] <= 108
    • +
    • sum(rows) == sum(columns)
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md b/assets/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md new file mode 100644 index 00000000..4b2e4417 --- /dev/null +++ b/assets/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md @@ -0,0 +1,101 @@ +# [1606. Find Servers That Handled Most Number of Requests](https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests) + + + +## Description + +

    You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:

    + +
      +
    • The ith (0-indexed) request arrives.
    • +
    • If all servers are busy, the request is dropped (not handled at all).
    • +
    • If the (i % k)th server is available, assign the request to that server.
    • +
    • Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on.
    • +
    + +

    You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.

    + +

    Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] 
    +Output: [1] 
    +Explanation:
    +All of the servers start out available.
    +The first 3 requests are handled by the first 3 servers in order.
    +Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.
    +Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.
    +Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.
    +
    + +

    Example 2:

    + +
    +Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]
    +Output: [0]
    +Explanation:
    +The first 3 requests are handled by first 3 servers.
    +Request 3 comes in. It is handled by server 0 since the server is available.
    +Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.
    +
    + +

    Example 3:

    + +
    +Input: k = 3, arrival = [1,2,3], load = [10,12,11]
    +Output: [0,1,2]
    +Explanation: Each server handles a single request, so they are all considered the busiest.
    +
    + +

    Example 4:

    + +
    +Input: k = 3, arrival = [1,2,3,4,8,9,10], load = [5,2,10,3,1,2,2]
    +Output: [1]
    +
    + +

    Example 5:

    + +
    +Input: k = 1, arrival = [1], load = [1]
    +Output: [0]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= 105
    • +
    • 1 <= arrival.length, load.length <= 105
    • +
    • arrival.length == load.length
    • +
    • 1 <= arrival[i], load[i] <= 109
    • +
    • arrival is strictly increasing.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1606.Find Servers That Handled Most Number of Requests/images/load-1.png b/assets/1600-1699/1606.Find Servers That Handled Most Number of Requests/images/load-1.png new file mode 100644 index 00000000..44f7515f Binary files /dev/null and b/assets/1600-1699/1606.Find Servers That Handled Most Number of Requests/images/load-1.png differ diff --git a/assets/1600-1699/1607.Sellers With No Sales/README_EN.md b/assets/1600-1699/1607.Sellers With No Sales/README_EN.md new file mode 100644 index 00000000..0eabb495 --- /dev/null +++ b/assets/1600-1699/1607.Sellers With No Sales/README_EN.md @@ -0,0 +1,114 @@ +# [1607. Sellers With No Sales](https://leetcode.com/problems/sellers-with-no-sales) + + + +## Description + +

    Table: Customer

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| customer_name | varchar |
    ++---------------+---------+
    +customer_id is the primary key for this table.
    +Each row of this table contains the information of each customer in the WebStore.
    +
    + +

     

    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| sale_date     | date    |
    +| order_cost    | int     |
    +| customer_id   | int     |
    +| seller_id     | int     |
    ++---------------+---------+
    +order_id is the primary key for this table.
    +Each row of this table contains all orders made in the webstore.
    +sale_date is the date when the transaction was made between the customer (customer_id) and the seller (seller_id).
    +
    + +

     

    + +

    Table: Seller

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| seller_id     | int     |
    +| seller_name   | varchar |
    ++---------------+---------+
    +seller_id is the primary key for this table.
    +Each row of this table contains the information of each seller.
    +
    + +

     

    + +

    Write an SQL query to report the names of all sellers who did not make any sales in 2020.

    + +

    Return the result table ordered by seller_name in ascending order.

    + +

    The query result format is in the following example.

    + +
    +Customer table:
    ++--------------+---------------+
    +| customer_id  | customer_name |
    ++--------------+---------------+
    +| 101          | Alice         |
    +| 102          | Bob           |
    +| 103          | Charlie       |
    ++--------------+---------------+
    +
    +Orders table:
    ++-------------+------------+--------------+-------------+-------------+
    +| order_id    | sale_date  | order_cost   | customer_id | seller_id   |
    ++-------------+------------+--------------+-------------+-------------+
    +| 1           | 2020-03-01 | 1500         | 101         | 1           |
    +| 2           | 2020-05-25 | 2400         | 102         | 2           |
    +| 3           | 2019-05-25 | 800          | 101         | 3           |
    +| 4           | 2020-09-13 | 1000         | 103         | 2           |
    +| 5           | 2019-02-11 | 700          | 101         | 2           |
    ++-------------+------------+--------------+-------------+-------------+
    +
    +Seller table:
    ++-------------+-------------+
    +| seller_id   | seller_name |
    ++-------------+-------------+
    +| 1           | Daniel      |
    +| 2           | Elizabeth   |
    +| 3           | Frank       |
    ++-------------+-------------+
    +
    +Result table:
    ++-------------+
    +| seller_name |
    ++-------------+
    +| Frank       |
    ++-------------+
    +Daniel made 1 sale in March 2020.
    +Elizabeth made 2 sales in 2020 and 1 sale in 2019.
    +Frank made 1 sale in 2019 but no sales in 2020.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md b/assets/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md new file mode 100644 index 00000000..c3b23451 --- /dev/null +++ b/assets/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md @@ -0,0 +1,80 @@ +# [1608. Special Array With X Elements Greater Than or Equal X](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x) + + + +## Description + +

    You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.

    + +

    Notice that x does not have to be an element in nums.

    + +

    Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,5]
    +Output: 2
    +Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.
    +
    + +

    Example 2:

    + +
    +Input: nums = [0,0]
    +Output: -1
    +Explanation: No numbers fit the criteria for x.
    +If x = 0, there should be 0 numbers >= x, but there are 2.
    +If x = 1, there should be 1 number >= x, but there are 0.
    +If x = 2, there should be 2 numbers >= x, but there are 0.
    +x cannot be greater since there are only 2 numbers in nums.
    +
    + +

    Example 3:

    + +
    +Input: nums = [0,4,3,0,4]
    +Output: 3
    +Explanation: There are 3 values that are greater than or equal to 3.
    +
    + +

    Example 4:

    + +
    +Input: nums = [3,6,7,7,0]
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1609.Even Odd Tree/README_EN.md b/assets/1600-1699/1609.Even Odd Tree/README_EN.md new file mode 100644 index 00000000..455bbdfd --- /dev/null +++ b/assets/1600-1699/1609.Even Odd Tree/README_EN.md @@ -0,0 +1,102 @@ +# [1609. Even Odd Tree](https://leetcode.com/problems/even-odd-tree) + + + +## Description + +

    A binary tree is named Even-Odd if it meets the following conditions:

    + +
      +
    • The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
    • +
    • For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
    • +
    • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
    • +
    + +

    Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
    +Output: true
    +Explanation: The node values on each level are:
    +Level 0: [1]
    +Level 1: [10,4]
    +Level 2: [3,7,9]
    +Level 3: [12,8,6,2]
    +Since levels 0 and 2 are all odd and increasing, and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
    +
    + +

    Example 2:

    + +

    + +
    +Input: root = [5,4,2,3,3,7]
    +Output: false
    +Explanation: The node values on each level are:
    +Level 0: [5]
    +Level 1: [4,2]
    +Level 2: [3,3,7]
    +Node values in the level 2 must be in strictly increasing order, so the tree is not Even-Odd.
    +
    + +

    Example 3:

    + +

    + +
    +Input: root = [5,9,1,3,5,7]
    +Output: false
    +Explanation: Node values in the level 1 should be even integers.
    +
    + +

    Example 4:

    + +
    +Input: root = [1]
    +Output: true
    +
    + +

    Example 5:

    + +
    +Input: root = [11,8,6,1,3,9,11,30,20,18,16,12,10,4,2,17]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 105].
    • +
    • 1 <= Node.val <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1609.Even Odd Tree/images/sample_1_1966.png b/assets/1600-1699/1609.Even Odd Tree/images/sample_1_1966.png new file mode 100644 index 00000000..84991f6f Binary files /dev/null and b/assets/1600-1699/1609.Even Odd Tree/images/sample_1_1966.png differ diff --git a/assets/1600-1699/1609.Even Odd Tree/images/sample_1_333_1966.png b/assets/1600-1699/1609.Even Odd Tree/images/sample_1_333_1966.png new file mode 100644 index 00000000..2970ee8d Binary files /dev/null and b/assets/1600-1699/1609.Even Odd Tree/images/sample_1_333_1966.png differ diff --git a/assets/1600-1699/1609.Even Odd Tree/images/sample_2_1966.png b/assets/1600-1699/1609.Even Odd Tree/images/sample_2_1966.png new file mode 100644 index 00000000..2230cf5c Binary files /dev/null and b/assets/1600-1699/1609.Even Odd Tree/images/sample_2_1966.png differ diff --git a/assets/1600-1699/1610.Maximum Number of Visible Points/README_EN.md b/assets/1600-1699/1610.Maximum Number of Visible Points/README_EN.md new file mode 100644 index 00000000..f0393809 --- /dev/null +++ b/assets/1600-1699/1610.Maximum Number of Visible Points/README_EN.md @@ -0,0 +1,80 @@ +# [1610. Maximum Number of Visible Points](https://leetcode.com/problems/maximum-number-of-visible-points) + + + +## Description + +

    You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.

    + +

    Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].

    + +

    + +

    + +

    You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.

    + +

    There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.

    + +

    Return the maximum number of points you can see.

    + +

     

    +

    Example 1:

    + +
    +Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]
    +Output: 3
    +Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.
    +
    + +

    Example 2:

    + +
    +Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]
    +Output: 4
    +Explanation: All points can be made visible in your field of view, including the one at your location.
    +
    + +

    Example 3:

    + +
    +Input: points = [[1,0],[2,1]], angle = 13, location = [1,1]
    +Output: 1
    +Explanation: You can only see one of the two points, as shown above.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= points.length <= 105
    • +
    • points[i].length == 2
    • +
    • location.length == 2
    • +
    • 0 <= angle < 360
    • +
    • 0 <= posx, posy, xi, yi <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1610.Maximum Number of Visible Points/images/5010bfd3-86e6-465f-ac64-e9df941d2e49.png b/assets/1600-1699/1610.Maximum Number of Visible Points/images/5010bfd3-86e6-465f-ac64-e9df941d2e49.png new file mode 100644 index 00000000..1c9d76f0 Binary files /dev/null and b/assets/1600-1699/1610.Maximum Number of Visible Points/images/5010bfd3-86e6-465f-ac64-e9df941d2e49.png differ diff --git a/assets/1600-1699/1610.Maximum Number of Visible Points/images/89a07e9b-00ab-4967-976a-c723b2aa8656.png b/assets/1600-1699/1610.Maximum Number of Visible Points/images/89a07e9b-00ab-4967-976a-c723b2aa8656.png new file mode 100644 index 00000000..0d10e4df Binary files /dev/null and b/assets/1600-1699/1610.Maximum Number of Visible Points/images/89a07e9b-00ab-4967-976a-c723b2aa8656.png differ diff --git a/assets/1600-1699/1610.Maximum Number of Visible Points/images/angle.mp4 b/assets/1600-1699/1610.Maximum Number of Visible Points/images/angle.mp4 new file mode 100644 index 00000000..5fdfe8ea Binary files /dev/null and b/assets/1600-1699/1610.Maximum Number of Visible Points/images/angle.mp4 differ diff --git a/assets/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md b/assets/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md new file mode 100644 index 00000000..f71dbf7b --- /dev/null +++ b/assets/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md @@ -0,0 +1,90 @@ +# [1611. Minimum One Bit Operations to Make Integers Zero](https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero) + + + +## Description + +

    Given an integer n, you must transform it into 0 using the following operations any number of times:

    + +
      +
    • Change the rightmost (0th) bit in the binary representation of n.
    • +
    • Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
    • +
    + +

    Return the minimum number of operations to transform n into 0.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 0
    +Output: 0
    +
    + +

    Example 2:

    + +
    +Input: n = 3
    +Output: 2
    +Explanation: The binary representation of 3 is "11".
    +"11" -> "01" with the 2nd operation since the 0th bit is 1.
    +"01" -> "00" with the 1st operation.
    +
    + +

    Example 3:

    + +
    +Input: n = 6
    +Output: 4
    +Explanation: The binary representation of 6 is "110".
    +"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
    +"010" -> "011" with the 1st operation.
    +"011" -> "001" with the 2nd operation since the 0th bit is 1.
    +"001" -> "000" with the 1st operation.
    +
    + +

    Example 4:

    + +
    +Input: n = 9
    +Output: 14
    +
    + +

    Example 5:

    + +
    +Input: n = 333
    +Output: 393
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= n <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md b/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md new file mode 100644 index 00000000..e5c9fc79 --- /dev/null +++ b/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md @@ -0,0 +1,74 @@ +# [1612. Check If Two Expression Trees are Equivalent](https://leetcode.com/problems/check-if-two-expression-trees-are-equivalent) + + + +## Description + +

    A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators. In this problem, we only consider the '+' operator (i.e. addition).

    + +

    You are given the roots of two binary expression trees, root1 and root2. Return true if the two binary expression trees are equivalent. Otherwise, return false.

    + +

    Two binary expression trees are equivalent if they evaluate to the same value regardless of what the variables are set to.

    + +

    Follow up: What will you change in your solution if the tree also supports the '-' operator (i.e. subtraction)?

    + +

     

    +

    Example 1:

    + +
    +Input: root1 = [x], root2 = [x]
    +Output: true
    +
    + +

    Example 2:

    + +

    + +
    +Input: root1 = [+,a,+,null,null,b,c], root2 = [+,+,a,b,c]
    +Output: true
    +Explaination: a + (b + c) == (b + c) + a
    + +

    Example 3:

    + +

    + +
    +Input: root1 = [+,a,+,null,null,b,c], root2 = [+,+,a,b,d]
    +Output: false
    +Explaination: a + (b + c) != (b + d) + a
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in both trees are equal, odd and, in the range [1, 4999].
    • +
    • Node.val is '+' or a lower-case English letter.
    • +
    • It's guaranteed that the tree given is a valid binary expression tree.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/images/tree1.png b/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/images/tree1.png new file mode 100644 index 00000000..796a55a0 Binary files /dev/null and b/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/images/tree1.png differ diff --git a/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/images/tree2.png b/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/images/tree2.png new file mode 100644 index 00000000..9ee1afa9 Binary files /dev/null and b/assets/1600-1699/1612.Check If Two Expression Trees are Equivalent/images/tree2.png differ diff --git a/assets/1600-1699/1613.Find the Missing IDs/README_EN.md b/assets/1600-1699/1613.Find the Missing IDs/README_EN.md new file mode 100644 index 00000000..b077c2ee --- /dev/null +++ b/assets/1600-1699/1613.Find the Missing IDs/README_EN.md @@ -0,0 +1,62 @@ +# [1613. Find the Missing IDs](https://leetcode.com/problems/find-the-missing-ids) + + + +## Description + +

    Table: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| customer_name | varchar |
    ++---------------+---------+
    +customer_id is the primary key for this table.
    +Each row of this table contains the name and the id customer.
    +
    + +

     

    + +

    Write an SQL query to find the missing customer IDs. The missing IDs are ones that are not in the Customers table but are in the range between 1 and the maximum customer_id present in the table.

    + +

    Notice that the maximum customer_id will not exceed 100.

    + +

    Return the result table ordered by ids in ascending order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Customers table:
    ++-------------+---------------+
    +| customer_id | customer_name |
    ++-------------+---------------+
    +| 1           | Alice         |
    +| 4           | Bob           |
    +| 5           | Charlie       |
    ++-------------+---------------+
    +
    +Result table:
    ++-----+
    +| ids |
    ++-----+
    +| 2   |
    +| 3   |
    ++-----+
    +The maximum customer_id present in the table is 5, so in the range [1,5], IDs 2 and 3 are missing from the table.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md b/assets/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md new file mode 100644 index 00000000..bedf32cf --- /dev/null +++ b/assets/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md @@ -0,0 +1,90 @@ +# [1614. Maximum Nesting Depth of the Parentheses](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses) + + + +## Description + +

    A string is a valid parentheses string (denoted VPS) if it meets one of the following:

    + +
      +
    • It is an empty string "", or a single character not equal to "(" or ")",
    • +
    • It can be written as AB (A concatenated with B), where A and B are VPS's, or
    • +
    • It can be written as (A), where A is a VPS.
    • +
    + +

    We can similarly define the nesting depth depth(S) of any VPS S as follows:

    + +
      +
    • depth("") = 0
    • +
    • depth(C) = 0, where C is a string with a single character not equal to "(" or ")".
    • +
    • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.
    • +
    • depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
    • +
    + +

    For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.

    + +

    Given a VPS represented as string s, return the nesting depth of s.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "(1+(2*3)+((8)/4))+1"
    +Output: 3
    +Explanation: Digit 8 is inside of 3 nested parentheses in the string.
    +
    + +

    Example 2:

    + +
    +Input: s = "(1)+((2))+(((3)))"
    +Output: 3
    +
    + +

    Example 3:

    + +
    +Input: s = "1+(2*3)/(2-1)"
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: s = "1"
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.
    • +
    • It is guaranteed that parentheses expression s is a VPS.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1615.Maximal Network Rank/README_EN.md b/assets/1600-1699/1615.Maximal Network Rank/README_EN.md new file mode 100644 index 00000000..88dd9466 --- /dev/null +++ b/assets/1600-1699/1615.Maximal Network Rank/README_EN.md @@ -0,0 +1,79 @@ +# [1615. Maximal Network Rank](https://leetcode.com/problems/maximal-network-rank) + + + +## Description + +

    There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.

    + +

    The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.

    + +

    The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.

    + +

    Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
    +Output: 4
    +Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
    +Output: 5
    +Explanation: There are 5 roads that are connected to cities 1 or 2.
    +
    + +

    Example 3:

    + +
    +Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
    +Output: 5
    +Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 100
    • +
    • 0 <= roads.length <= n * (n - 1) / 2
    • +
    • roads[i].length == 2
    • +
    • 0 <= ai, bi <= n-1
    • +
    • ai != bi
    • +
    • Each pair of cities has at most one road connecting them.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1615.Maximal Network Rank/images/ex1.png b/assets/1600-1699/1615.Maximal Network Rank/images/ex1.png new file mode 100644 index 00000000..bcbdc3fc Binary files /dev/null and b/assets/1600-1699/1615.Maximal Network Rank/images/ex1.png differ diff --git a/assets/1600-1699/1615.Maximal Network Rank/images/ex2.png b/assets/1600-1699/1615.Maximal Network Rank/images/ex2.png new file mode 100644 index 00000000..ee33f97d Binary files /dev/null and b/assets/1600-1699/1615.Maximal Network Rank/images/ex2.png differ diff --git a/assets/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md b/assets/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md new file mode 100644 index 00000000..509d0be5 --- /dev/null +++ b/assets/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md @@ -0,0 +1,84 @@ +# [1616. Split Two Strings to Make Palindrome](https://leetcode.com/problems/split-two-strings-to-make-palindrome) + + + +## Description + +

    You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.

    + +

    When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.

    + +

    Return true if it is possible to form a palindrome string, otherwise return false.

    + +

    Notice that x + y denotes the concatenation of strings x and y.

    + +

     

    +

    Example 1:

    + +
    +Input: a = "x", b = "y"
    +Output: true
    +Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
    +aprefix = "", asuffix = "x"
    +bprefix = "", bsuffix = "y"
    +Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
    +
    + +

    Example 2:

    + +
    +Input: a = "abdef", b = "fecab"
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: a = "ulacfd", b = "jizalu"
    +Output: true
    +Explaination: Split them at index 3:
    +aprefix = "ula", asuffix = "cfd"
    +bprefix = "jiz", bsuffix = "alu"
    +Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
    +
    + +

    Example 4:

    + +
    +Input: a = "xbdef", b = "xecab"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= a.length, b.length <= 105
    • +
    • a.length == b.length
    • +
    • a and b consist of lowercase English letters
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md b/assets/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md new file mode 100644 index 00000000..a35c6d0f --- /dev/null +++ b/assets/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md @@ -0,0 +1,119 @@ +# [1617. Count Subtrees With Max Distance Between Cities](https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities) + + + +## Description + +

    There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree.

    + + + +

    A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.

    + + + +

    For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.

    + + + +

    Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.

    + + + +

    Notice that the distance between the two cities is the number of edges in the path between them.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: n = 4, edges = [[1,2],[2,3],[2,4]]
    +
    +Output: [3,4,0]
    +
    +Explanation:
    +
    +The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.
    +
    +The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.
    +
    +No subtree has two nodes where the max distance between them is 3.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 2, edges = [[1,2]]
    +
    +Output: [1]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 3, edges = [[1,2],[2,3]]
    +
    +Output: [2,1]
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= n <= 15
    • +
    • edges.length == n-1
    • +
    • edges[i].length == 2
    • +
    • 1 <= ui, vi <= n
    • +
    • All pairs (ui, vi) are distinct.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1617.Count Subtrees With Max Distance Between Cities/images/p1.png b/assets/1600-1699/1617.Count Subtrees With Max Distance Between Cities/images/p1.png new file mode 100644 index 00000000..035bfb45 Binary files /dev/null and b/assets/1600-1699/1617.Count Subtrees With Max Distance Between Cities/images/p1.png differ diff --git a/assets/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md b/assets/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md new file mode 100644 index 00000000..dcb21b11 --- /dev/null +++ b/assets/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md @@ -0,0 +1,271 @@ +# [1618. Maximum Font to Fit a Sentence in a Screen](https://leetcode.com/problems/maximum-font-to-fit-a-sentence-in-a-screen) + + + +## Description + +

    You are given a string text. We want to display text on a screen of width w and height h. You can choose any font size from array fonts, which contains the available font sizes in ascending order.

    + + + +

    You can use the FontInfo interface to get the width and height of any character at any available font size.

    + + + +

    The FontInfo interface is defined as such:

    + + + +
    +
    +interface FontInfo {
    +
    +  // Returns the width of character ch on the screen using font size fontSize.
    +
    +  // O(1) per call
    +
    +  public int getWidth(int fontSize, char ch);
    +
    +
    +
    +  // Returns the height of any character on the screen using font size fontSize.
    +
    +  // O(1) per call
    +
    +  public int getHeight(int fontSize);
    +
    +}
    + + + +

    The calculated width of text for some fontSize is the sum of every getWidth(fontSize, text[i]) call for each 0 <= i < text.length (0-indexed). The calculated height of text for some fontSize is getHeight(fontSize). Note that text is displayed on a single line.

    + + + +

    It is guaranteed that FontInfo will return the same value if you call getHeight or getWidth with the same parameters.

    + + + +

    It is also guaranteed that for any font size fontSize and any character ch:

    + + + +
      +
    • getHeight(fontSize) <= getHeight(fontSize+1)
    • +
    • getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
    • +
    + + + +

    Return the maximum font size you can use to display text on the screen. If text cannot fit on the display with any font size, return -1.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: text = "helloworld", w = 80, h = 20, fonts = [6,8,10,12,14,16,18,24,36]
    +
    +Output: 6
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: text = "leetcode", w = 1000, h = 50, fonts = [1,2,4]
    +
    +Output: 4
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: text = "easyquestion", w = 100, h = 100, fonts = [10,15,20,25]
    +
    +Output: -1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= text.length <= 50000
    • +
    • text contains only lowercase English letters.
    • +
    • 1 <= w <= 107
    • +
    • 1 <= h <= 104
    • +
    • 1 <= fonts.length <= 105
    • +
    • 1 <= fonts[i] <= 105
    • +
    • fonts is sorted in ascending order and does not contain duplicates.
    • +
    + +## Solutions + + + +### **Python3** + +```python +# """ +# This is FontInfo's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class FontInfo(object): +# Return the width of char ch when fontSize is used. +# def getWidth(self, fontSize, ch): +# """ +# :type fontSize: int +# :type ch: char +# :rtype int +# """ +# +# def getHeight(self, fontSize): +# """ +# :type fontSize: int +# :rtype int +# """ +class Solution: + def maxFont(self, text: str, w: int, h: int, fonts: List[int], fontInfo : 'FontInfo') -> int: + def check(text, fontSize, w, h, fontInfo) -> bool: + if fontInfo.getHeight(fontSize) > h: + return False + width = 0 + for ch in text: + width += fontInfo.getWidth(fontSize, ch) + if width > w: + return False + return True + + left, right = 0, len(fonts) - 1 + while left < right: + mid = (left + right + 1) >> 1 + fontSize = fonts[mid] + if check(text, fontSize, w, h, fontInfo): + left = mid + else: + right = mid - 1 + return fonts[left] if check(text, fonts[left], w, h, fontInfo) else -1 +``` + +### **Java** + +```java +/** + * // This is the FontInfo's API interface. + * // You should not implement it, or speculate about its implementation + * interface FontInfo { + * // Return the width of char ch when fontSize is used. + * public int getWidth(int fontSize, char ch) {} + * // Return Height of any char when fontSize is used. + * public int getHeight(int fontSize) + * } + */ +class Solution { + public int maxFont(String text, int w, int h, int[] fonts, FontInfo fontInfo) { + int left = 0, right = fonts.length - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + int fontSize = fonts[mid]; + if (check(text, fontSize, w, h, fontInfo)) { + left = mid; + } else { + right = mid - 1; + } + } + return check(text, fonts[left], w, h, fontInfo) ? fonts[left] : -1; + } + + private boolean check(String s, int fontSize, int w, int h, FontInfo fontInfo) { + if (fontInfo.getHeight(fontSize) > h) { + return false; + } + int width = 0; + for (int i = 0; i < s.length(); ++i) { + char ch = s.charAt(i); + width += fontInfo.getWidth(fontSize, ch); + if (width > w) { + return false; + } + } + return true; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the FontInfo's API interface. + * // You should not implement it, or speculate about its implementation + * class FontInfo { + * public: + * // Return the width of char ch when fontSize is used. + * int getWidth(int fontSize, char ch); + * + * // Return Height of any char when fontSize is used. + * int getHeight(int fontSize) + * }; + */ +class Solution { +public: + int maxFont(string text, int w, int h, vector& fonts, FontInfo fontInfo) { + int left = 0, right = fonts.size() - 1; + while (left < right) { + int mid = left + right + 1 >> 1; + int fontSize = fonts[mid]; + if (check(text, fontSize, w, h, fontInfo)) { + left = mid; + } else { + right = mid - 1; + } + } + return check(text, fonts[left], w, h, fontInfo) ? fonts[left] : -1; + } + +private: + bool check(string s, int fontSize, int w, int h, FontInfo fontInfo) { + if (fontInfo.getHeight(fontSize) > h) { + return false; + } + int width = 0; + for (auto ch : s) { + width += fontInfo.getWidth(fontSize, ch); + if (width > w) { + return false; + } + } + return true; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md b/assets/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md new file mode 100644 index 00000000..94b24ce3 --- /dev/null +++ b/assets/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md @@ -0,0 +1,80 @@ +# [1619. Mean of Array After Removing Some Elements](https://leetcode.com/problems/mean-of-array-after-removing-some-elements) + + + +## Description + +

    Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.

    + +

    Answers within 10-5 of the actual answer will be considered accepted.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
    +Output: 2.00000
    +Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
    +
    + +

    Example 2:

    + +
    +Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
    +Output: 4.00000
    +
    + +

    Example 3:

    + +
    +Input: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
    +Output: 4.77778
    +
    + +

    Example 4:

    + +
    +Input: arr = [9,7,8,7,7,8,4,4,6,8,8,7,6,8,8,9,2,6,0,0,1,10,8,6,3,3,5,1,10,9,0,7,10,0,10,4,1,10,6,9,3,6,0,0,2,7,0,6,7,2,9,7,7,3,0,1,6,1,10,3]
    +Output: 5.27778
    +
    + +

    Example 5:

    + +
    +Input: arr = [4,8,4,10,0,7,1,3,7,8,8,3,4,1,6,2,1,1,8,0,9,8,0,3,9,10,3,10,1,10,7,3,2,1,4,9,10,7,6,4,0,8,5,1,2,1,6,2,5,0,7,10,9,10,3,7,10,5,8,5,7,6,7,6,10,9,5,10,5,5,7,2,10,7,7,8,2,0,1,1]
    +Output: 5.29167
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 20 <= arr.length <= 1000
    • +
    • arr.length is a multiple of 20.
    • +
    • 0 <= arr[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md b/assets/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md new file mode 100644 index 00000000..c7cf30da --- /dev/null +++ b/assets/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md @@ -0,0 +1,90 @@ +# [1620. Coordinate With Maximum Network Quality](https://leetcode.com/problems/coordinate-with-maximum-network-quality) + + + +## Description + +

    You are given an array of network towers towers and an integer radius, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between two coordinates is the Euclidean distance.

    + +

    The integer radius denotes the maximum distance in which the tower is reachable. The tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.

    + +

    The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.

    + +

    Return the integral coordinate where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum coordinate.

    + +

    Note:

    + +
      +
    • A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either x1 < x2 or x1 == x2 and y1 < y2.
    • +
    • ⌊val⌋ is the greatest integer less than or equal to val (the floor function).
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2
    +Output: [2,1]
    +Explanation: 
    +At coordinate (2, 1) the total quality is 13
    +- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
    +- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
    +- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
    +No other coordinate has higher quality.
    + +

    Example 2:

    + +
    +Input: towers = [[23,11,21]], radius = 9
    +Output: [23,11]
    +
    + +

    Example 3:

    + +
    +Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2
    +Output: [1,2]
    +
    + +

    Example 4:

    + +
    +Input: towers = [[2,1,9],[0,1,9]], radius = 2
    +Output: [0,1]
    +Explanation: Both (0, 1) and (2, 1) are optimal in terms of quality but (0, 1) is lexicograpically minimal.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= towers.length <= 50
    • +
    • towers[i].length == 3
    • +
    • 0 <= xi, yi, qi <= 50
    • +
    • 1 <= radius <= 50
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1620.Coordinate With Maximum Network Quality/images/untitled-diagram.png b/assets/1600-1699/1620.Coordinate With Maximum Network Quality/images/untitled-diagram.png new file mode 100644 index 00000000..cafe556f Binary files /dev/null and b/assets/1600-1699/1620.Coordinate With Maximum Network Quality/images/untitled-diagram.png differ diff --git a/assets/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md b/assets/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md new file mode 100644 index 00000000..48fd50c8 --- /dev/null +++ b/assets/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md @@ -0,0 +1,126 @@ +# [1621. Number of Sets of K Non-Overlapping Line Segments](https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments) + + + +## Description + +

    Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.

    + + + +

    Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 4, k = 2
    +
    +Output: 5
    +
    +Explanation: 
    +
    +The two line segments are shown in red and blue.
    +
    +The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 3, k = 1
    +
    +Output: 3
    +
    +Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: n = 30, k = 7
    +
    +Output: 796297179
    +
    +Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: n = 5, k = 3
    +
    +Output: 7
    +
    +
    + + + +

    Example 5:

    + + + +
    +
    +Input: n = 3, k = 2
    +
    +Output: 1
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= n <= 1000
    • +
    • 1 <= k <= n-1
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/images/ex1.png b/assets/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/images/ex1.png new file mode 100644 index 00000000..b2228565 Binary files /dev/null and b/assets/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/images/ex1.png differ diff --git a/assets/1600-1699/1622.Fancy Sequence/README_EN.md b/assets/1600-1699/1622.Fancy Sequence/README_EN.md new file mode 100644 index 00000000..f64709d2 --- /dev/null +++ b/assets/1600-1699/1622.Fancy Sequence/README_EN.md @@ -0,0 +1,76 @@ +# [1622. Fancy Sequence](https://leetcode.com/problems/fancy-sequence) + + + +## Description + +

    Write an API that generates fancy sequences using the append, addAll, and multAll operations.

    + +

    Implement the Fancy class:

    + +
      +
    • Fancy() Initializes the object with an empty sequence.
    • +
    • void append(val) Appends an integer val to the end of the sequence.
    • +
    • void addAll(inc) Increments all existing values in the sequence by an integer inc.
    • +
    • void multAll(m) Multiplies all existing values in the sequence by an integer m.
    • +
    • int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"]
    +[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]
    +Output
    +[null, null, null, null, null, 10, null, null, null, 26, 34, 20]
    +
    +Explanation
    +Fancy fancy = new Fancy();
    +fancy.append(2);   // fancy sequence: [2]
    +fancy.addAll(3);   // fancy sequence: [2+3] -> [5]
    +fancy.append(7);   // fancy sequence: [5, 7]
    +fancy.multAll(2);  // fancy sequence: [5*2, 7*2] -> [10, 14]
    +fancy.getIndex(0); // return 10
    +fancy.addAll(3);   // fancy sequence: [10+3, 14+3] -> [13, 17]
    +fancy.append(10);  // fancy sequence: [13, 17, 10]
    +fancy.multAll(2);  // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]
    +fancy.getIndex(0); // return 26
    +fancy.getIndex(1); // return 34
    +fancy.getIndex(2); // return 20
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= val, inc, m <= 100
    • +
    • 0 <= idx <= 105
    • +
    • At most 105 calls total will be made to append, addAll, multAll, and getIndex.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md b/assets/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md new file mode 100644 index 00000000..5e4ae6be --- /dev/null +++ b/assets/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md @@ -0,0 +1,124 @@ +# [1623. All Valid Triplets That Can Represent a Country](https://leetcode.com/problems/all-valid-triplets-that-can-represent-a-country) + + + +## Description + +

    Table: SchoolA

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id is the primary key for this table.
    +Each row of this table contains the name and the id of a student in school A.
    +All student_name are distinct.
    +
    + +

     

    + +

    Table: SchoolB

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id is the primary key for this table.
    +Each row of this table contains the name and the id of a student in school B.
    +All student_name are distinct.
    +
    + +

     

    + +

    Table: SchoolC

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id is the primary key for this table.
    +Each row of this table contains the name and the id of a student in school C.
    +All student_name are distinct.
    +
    + +

     

    + +

    There is a country with three schools, where each student is enrolled in exactly one school. The country is joining a competition and wants to select one student from each school to represent the country such that:

    + +
      +
    • member_A is selected from SchoolA,
    • +
    • member_B is selected from SchoolB,
    • +
    • member_C is selected from SchoolC, and
    • +
    • The selected students' names and IDs are pairwise distinct (i.e. no two students share the same name, and no two students share the same ID).
    • +
    + +

    Write an SQL query to find all the possible triplets representing the country under the given constraints.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +SchoolA table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 1          | Alice        |
    +| 2          | Bob          |
    ++------------+--------------+
    +
    +SchoolB table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 3          | Tom          |
    ++------------+--------------+
    +
    +SchoolC table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 3          | Tom          |
    +| 2          | Jerry        |
    +| 10         | Alice        |
    ++------------+--------------+
    +
    +Result table:
    ++----------+----------+----------+
    +| member_A | member_B | member_C |
    ++----------+----------+----------+
    +| Alice    | Tom      | Jerry    |
    +| Bob      | Tom      | Alice    |
    ++----------+----------+----------+
    +Let us see all the possible triplets.
    +- (Alice, Tom, Tom) --> Rejected because member_B and member_C have the same name and the same ID.
    +- (Alice, Tom, Jerry) --> Valid triplet.
    +- (Alice, Tom, Alice) --> Rejected because member_A and member_C have the same name.
    +- (Bob, Tom, Tom) --> Rejected because member_B and member_C have the same name and the same ID.
    +- (Bob, Tom, Jerry) --> Rejected because member_A and member_C have the same ID.
    +- (Bob, Tom, Alice) --> Valid triplet.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md b/assets/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md new file mode 100644 index 00000000..6269fc4b --- /dev/null +++ b/assets/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md @@ -0,0 +1,74 @@ +# [1624. Largest Substring Between Two Equal Characters](https://leetcode.com/problems/largest-substring-between-two-equal-characters) + + + +## Description + +

    Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.

    + +

    A substring is a contiguous sequence of characters within a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aa"
    +Output: 0
    +Explanation: The optimal substring here is an empty substring between the two 'a's.
    + +

    Example 2:

    + +
    +Input: s = "abca"
    +Output: 2
    +Explanation: The optimal substring here is "bc".
    +
    + +

    Example 3:

    + +
    +Input: s = "cbzxy"
    +Output: -1
    +Explanation: There are no characters that appear twice in s.
    +
    + +

    Example 4:

    + +
    +Input: s = "cabbac"
    +Output: 4
    +Explanation: The optimal substring here is "abba". Other non-optimal substrings include "bb" and "".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 300
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md b/assets/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md new file mode 100644 index 00000000..dad6eb3f --- /dev/null +++ b/assets/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md @@ -0,0 +1,160 @@ +# [1625. Lexicographically Smallest String After Applying Operations](https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations) + + + +## Description + +

    You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.

    + + + +

    You can apply either of the following two operations any number of times and in any order on s:

    + + + +
      +
    • Add a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = "3456" and a = 5, s becomes "3951".
    • +
    • Rotate s to the right by b positions. For example, if s = "3456" and b = 1, s becomes "6345".
    • +
    + + + +

    Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s.

    + + + +

    A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" because the first position they differ is at the third letter, and '5' comes before '9'.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "5525", a = 9, b = 2
    +
    +Output: "2050"
    +
    +Explanation: We can apply the following operations:
    +
    +Start:  "5525"
    +
    +Rotate: "2555"
    +
    +Add:    "2454"
    +
    +Add:    "2353"
    +
    +Rotate: "5323"
    +
    +Add:    "5222"
    +
    +​​​​​​​Add:    "5121"
    +
    +​​​​​​​Rotate: "2151"
    +
    +​​​​​​​Add:    "2050"​​​​​​​​​​​​
    +
    +There is no way to obtain a string that is lexicographically smaller then "2050".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "74", a = 5, b = 1
    +
    +Output: "24"
    +
    +Explanation: We can apply the following operations:
    +
    +Start:  "74"
    +
    +Rotate: "47"
    +
    +​​​​​​​Add:    "42"
    +
    +​​​​​​​Rotate: "24"​​​​​​​​​​​​
    +
    +There is no way to obtain a string that is lexicographically smaller then "24".
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "0011", a = 4, b = 2
    +
    +Output: "0011"
    +
    +Explanation: There are no sequence of operations that will give us a lexicographically smaller string than "0011".
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = "43987654", a = 7, b = 3
    +
    +Output: "00553311"
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= s.length <= 100
    • +
    • s.length is even.
    • +
    • s consists of digits from 0 to 9 only.
    • +
    • 1 <= a <= 9
    • +
    • 1 <= b <= s.length - 1
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1626.Best Team With No Conflicts/README_EN.md b/assets/1600-1699/1626.Best Team With No Conflicts/README_EN.md new file mode 100644 index 00000000..049ff6e3 --- /dev/null +++ b/assets/1600-1699/1626.Best Team With No Conflicts/README_EN.md @@ -0,0 +1,71 @@ +# [1626. Best Team With No Conflicts](https://leetcode.com/problems/best-team-with-no-conflicts) + + + +## Description + +

    You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.

    + +

    However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.

    + +

    Given two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.

    + +

     

    +

    Example 1:

    + +
    +Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
    +Output: 34
    +Explanation: You can choose all the players.
    +
    + +

    Example 2:

    + +
    +Input: scores = [4,5,6,5], ages = [2,1,2,1]
    +Output: 16
    +Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
    +
    + +

    Example 3:

    + +
    +Input: scores = [1,2,3,5], ages = [8,9,10,1]
    +Output: 6
    +Explanation: It is best to choose the first 3 players. 
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= scores.length, ages.length <= 1000
    • +
    • scores.length == ages.length
    • +
    • 1 <= scores[i] <= 106
    • +
    • 1 <= ages[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md b/assets/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md new file mode 100644 index 00000000..e1dfcd7e --- /dev/null +++ b/assets/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md @@ -0,0 +1,92 @@ +# [1627. Graph Connectivity With Threshold](https://leetcode.com/problems/graph-connectivity-with-threshold) + + + +## Description + +

    We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true:

    + +
      +
    • x % z == 0,
    • +
    • y % z == 0, and
    • +
    • z > threshold.
    • +
    + +

    Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them).

    + +

    Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]
    +Output: [false,false,true]
    +Explanation: The divisors for each number:
    +1:   1
    +2:   1, 2
    +3:   1, 3
    +4:   1, 2, 4
    +5:   1, 5
    +6:   1, 2, 3, 6
    +Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the
    +only ones directly connected. The result of each query:
    +[1,4]   1 is not connected to 4
    +[2,5]   2 is not connected to 5
    +[3,6]   3 is connected to 6 through path 3--6
    +
    + +

    Example 2:

    + +
    +Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]
    +Output: [true,true,true,true,true]
    +Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,
    +all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.
    +
    + +

    Example 3:

    + +
    +Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]
    +Output: [false,false,false,false,false]
    +Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.
    +Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 104
    • +
    • 0 <= threshold <= n
    • +
    • 1 <= queries.length <= 105
    • +
    • queries[i].length == 2
    • +
    • 1 <= ai, bi <= cities
    • +
    • ai != bi
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1627.Graph Connectivity With Threshold/images/ex1.jpg b/assets/1600-1699/1627.Graph Connectivity With Threshold/images/ex1.jpg new file mode 100644 index 00000000..66987053 Binary files /dev/null and b/assets/1600-1699/1627.Graph Connectivity With Threshold/images/ex1.jpg differ diff --git a/assets/1600-1699/1627.Graph Connectivity With Threshold/images/ex3.jpg b/assets/1600-1699/1627.Graph Connectivity With Threshold/images/ex3.jpg new file mode 100644 index 00000000..7e1ab35c Binary files /dev/null and b/assets/1600-1699/1627.Graph Connectivity With Threshold/images/ex3.jpg differ diff --git a/assets/1600-1699/1627.Graph Connectivity With Threshold/images/tmp.jpg b/assets/1600-1699/1627.Graph Connectivity With Threshold/images/tmp.jpg new file mode 100644 index 00000000..af9cbac1 Binary files /dev/null and b/assets/1600-1699/1627.Graph Connectivity With Threshold/images/tmp.jpg differ diff --git a/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md b/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md new file mode 100644 index 00000000..100e12c7 --- /dev/null +++ b/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md @@ -0,0 +1,139 @@ +# [1628. Design an Expression Tree With Evaluate Function](https://leetcode.com/problems/design-an-expression-tree-with-evaluate-function) + + + +## Description + +

    Given the postfix tokens of an arithmetic expression, build and return the binary expression tree that represents this expression.

    + + + +

    Postfix notation is a notation for writing arithmetic expressions in which the operands (numbers) appear before their operators. For example, the postfix tokens of the expression 4*(5-(7+2)) are represented in the array postfix = ["4","5","7","2","+","-","*"].

    + + + +

    The class Node is an interface you should use to implement the binary expression tree. The returned tree will be tested using the evaluate function, which is supposed to evaluate the tree's value. You should not remove the Node class; however, you can modify it as you wish, and you can define other classes to implement it if needed.

    + + + +

    A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with two children) correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and '/' (division).

    + + + +

    It's guaranteed that no subtree will yield a value that exceeds 109 in absolute value, and all the operations are valid (i.e., no division by zero).

    + + + +

    Follow up: Could you design the expression tree such that it is more modular? For example, is your design able to support additional operators without making changes to your existing evaluate implementation?

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: s = ["3","4","+","2","*","7","/"]
    +
    +Output: 2
    +
    +Explanation: this expression evaluates to the above binary tree with expression ((3+4)*2)/7) = 14/7 = 2.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: s = ["4","5","7","2","+","-","*"]
    +
    +Output: -16
    +
    +Explanation: this expression evaluates to the above binary tree with expression 4*(5-(2+7)) = 4*(-4) = -16.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = ["4","2","+","3","5","1","-","*","+"]
    +
    +Output: 18
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: s = ["100","200","+","2","/","5","*","7","+"]
    +
    +Output: 757
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length < 100
    • +
    • s.length is odd.
    • +
    • s consists of numbers and the characters '+', '-', '*', and '/'.
    • +
    • If s[i] is a number, its integer representation is no more than 105.
    • +
    • It is guaranteed that s is a valid expression.
    • +
    • The absolute value of the result and intermediate values will not exceed 109.
    • +
    • It is guaranteed that no expression will include division by zero.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/images/untitled-diagram.png b/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/images/untitled-diagram.png new file mode 100644 index 00000000..03ecc218 Binary files /dev/null and b/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/images/untitled-diagram.png differ diff --git a/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/images/untitled-diagram2.png b/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/images/untitled-diagram2.png new file mode 100644 index 00000000..e29d4865 Binary files /dev/null and b/assets/1600-1699/1628.Design an Expression Tree With Evaluate Function/images/untitled-diagram2.png differ diff --git a/assets/1600-1699/1629.Slowest Key/README_EN.md b/assets/1600-1699/1629.Slowest Key/README_EN.md new file mode 100644 index 00000000..9b64efef --- /dev/null +++ b/assets/1600-1699/1629.Slowest Key/README_EN.md @@ -0,0 +1,80 @@ +# [1629. Slowest Key](https://leetcode.com/problems/slowest-key) + + + +## Description + +

    A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.

    + +

    You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.

    + +

    The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].

    + +

    Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.

    + +

    Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.

    + +

     

    +

    Example 1:

    + +
    +Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
    +Output: "c"
    +Explanation: The keypresses were as follows:
    +Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
    +Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
    +Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
    +Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
    +The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
    +'c' is lexicographically larger than 'b', so the answer is 'c'.
    +
    + +

    Example 2:

    + +
    +Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
    +Output: "a"
    +Explanation: The keypresses were as follows:
    +Keypress for 's' had a duration of 12.
    +Keypress for 'p' had a duration of 23 - 12 = 11.
    +Keypress for 'u' had a duration of 36 - 23 = 13.
    +Keypress for 'd' had a duration of 46 - 36 = 10.
    +Keypress for 'a' had a duration of 62 - 46 = 16.
    +The longest of these was the keypress for 'a' with duration 16.
    + +

     

    +

    Constraints:

    + +
      +
    • releaseTimes.length == n
    • +
    • keysPressed.length == n
    • +
    • 2 <= n <= 1000
    • +
    • 1 <= releaseTimes[i] <= 109
    • +
    • releaseTimes[i] < releaseTimes[i+1]
    • +
    • keysPressed contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1630.Arithmetic Subarrays/README_EN.md b/assets/1600-1699/1630.Arithmetic Subarrays/README_EN.md new file mode 100644 index 00000000..3b4d3bd4 --- /dev/null +++ b/assets/1600-1699/1630.Arithmetic Subarrays/README_EN.md @@ -0,0 +1,79 @@ +# [1630. Arithmetic Subarrays](https://leetcode.com/problems/arithmetic-subarrays) + + + +## Description + +

    A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.

    + +

    For example, these are arithmetic sequences:

    + +
    +1, 3, 5, 7, 9
    +7, 7, 7, 7
    +3, -1, -5, -9
    + +

    The following sequence is not arithmetic:

    + +
    +1, 1, 2, 5, 7
    + +

    You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.

    + +

    Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
    +Output: [true,false,true]
    +Explanation:
    +In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.
    +In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.
    +In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.
    + +

    Example 2:

    + +
    +Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
    +Output: [false,true,false,false,true,true]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • m == l.length
    • +
    • m == r.length
    • +
    • 2 <= n <= 500
    • +
    • 1 <= m <= 500
    • +
    • 0 <= l[i] < r[i] < n
    • +
    • -105 <= nums[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1631.Path With Minimum Effort/README_EN.md b/assets/1600-1699/1631.Path With Minimum Effort/README_EN.md new file mode 100644 index 00000000..18bcc0ad --- /dev/null +++ b/assets/1600-1699/1631.Path With Minimum Effort/README_EN.md @@ -0,0 +1,76 @@ +# [1631. Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort) + + + +## Description + +

    You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

    + +

    A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

    + +

    Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
    +Output: 2
    +Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
    +This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
    +
    + +

    Example 2:

    + +

    + +
    +Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
    +Output: 1
    +Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
    +
    + +

    Example 3:

    + +
    +Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
    +Output: 0
    +Explanation: This route does not require any effort.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • rows == heights.length
    • +
    • columns == heights[i].length
    • +
    • 1 <= rows, columns <= 100
    • +
    • 1 <= heights[i][j] <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1631.Path With Minimum Effort/images/ex1.png b/assets/1600-1699/1631.Path With Minimum Effort/images/ex1.png new file mode 100644 index 00000000..d425710b Binary files /dev/null and b/assets/1600-1699/1631.Path With Minimum Effort/images/ex1.png differ diff --git a/assets/1600-1699/1631.Path With Minimum Effort/images/ex2.png b/assets/1600-1699/1631.Path With Minimum Effort/images/ex2.png new file mode 100644 index 00000000..d24bbca4 Binary files /dev/null and b/assets/1600-1699/1631.Path With Minimum Effort/images/ex2.png differ diff --git a/assets/1600-1699/1631.Path With Minimum Effort/images/ex3.png b/assets/1600-1699/1631.Path With Minimum Effort/images/ex3.png new file mode 100644 index 00000000..d0b474bb Binary files /dev/null and b/assets/1600-1699/1631.Path With Minimum Effort/images/ex3.png differ diff --git a/assets/1600-1699/1632.Rank Transform of a Matrix/README_EN.md b/assets/1600-1699/1632.Rank Transform of a Matrix/README_EN.md new file mode 100644 index 00000000..39e0be6a --- /dev/null +++ b/assets/1600-1699/1632.Rank Transform of a Matrix/README_EN.md @@ -0,0 +1,92 @@ +# [1632. Rank Transform of a Matrix](https://leetcode.com/problems/rank-transform-of-a-matrix) + + + +## Description + +

    Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].

    + +

    The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:

    + +
      +
    • The rank is an integer starting from 1.
    • +
    • If two elements p and q are in the same row or column, then: +
        +
      • If p < q then rank(p) < rank(q)
      • +
      • If p == q then rank(p) == rank(q)
      • +
      • If p > q then rank(p) > rank(q)
      • +
      +
    • +
    • The rank should be as small as possible.
    • +
    + +

    It is guaranteed that answer is unique under the given rules.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[1,2],[3,4]]
    +Output: [[1,2],[2,3]]
    +Explanation:
    +The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
    +The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.
    +The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.
    +The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.
    +
    + +

    Example 2:

    + +
    +Input: matrix = [[7,7],[7,7]]
    +Output: [[1,1],[1,1]]
    +
    + +

    Example 3:

    + +
    +Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
    +Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
    +
    + +

    Example 4:

    + +
    +Input: matrix = [[7,3,6],[1,4,5],[9,8,2]]
    +Output: [[5,1,4],[1,2,3],[6,3,1]]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • -109 <= matrix[row][col] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank1.jpg b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank1.jpg new file mode 100644 index 00000000..ff23affd Binary files /dev/null and b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank1.jpg differ diff --git a/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank2.jpg b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank2.jpg new file mode 100644 index 00000000..6539452a Binary files /dev/null and b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank2.jpg differ diff --git a/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank3.jpg b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank3.jpg new file mode 100644 index 00000000..60b6aca3 Binary files /dev/null and b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank3.jpg differ diff --git a/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank4.jpg b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank4.jpg new file mode 100644 index 00000000..442006a1 Binary files /dev/null and b/assets/1600-1699/1632.Rank Transform of a Matrix/images/rank4.jpg differ diff --git a/assets/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md b/assets/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md new file mode 100644 index 00000000..a95337ce --- /dev/null +++ b/assets/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md @@ -0,0 +1,99 @@ +# [1633. Percentage of Users Attended a Contest](https://leetcode.com/problems/percentage-of-users-attended-a-contest) + + + +## Description + +

    Table: Users

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| user_name   | varchar |
    ++-------------+---------+
    +user_id is the primary key for this table.
    +Each row of this table contains the name and the id of a user.
    +
    + +

     

    + +

    Table: Register

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| contest_id  | int     |
    +| user_id     | int     |
    ++-------------+---------+
    +(contest_id, user_id) is the primary key for this table.
    +Each row of this table contains the id of a user and the contest they registered into.
    +
    + +

     

    + +

    Write an SQL query to find the percentage of the users registered in each contest rounded to two decimals.

    + +

    Return the result table ordered by percentage in descending order. In case of a tie, order it by contest_id in ascending order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Users table:
    ++---------+-----------+
    +| user_id | user_name |
    ++---------+-----------+
    +| 6       | Alice     |
    +| 2       | Bob       |
    +| 7       | Alex      |
    ++---------+-----------+
    +
    +Register table:
    ++------------+---------+
    +| contest_id | user_id |
    ++------------+---------+
    +| 215        | 6       |
    +| 209        | 2       |
    +| 208        | 2       |
    +| 210        | 6       |
    +| 208        | 6       |
    +| 209        | 7       |
    +| 209        | 6       |
    +| 215        | 7       |
    +| 208        | 7       |
    +| 210        | 2       |
    +| 207        | 2       |
    +| 210        | 7       |
    ++------------+---------+
    +
    +Result table:
    ++------------+------------+
    +| contest_id | percentage |
    ++------------+------------+
    +| 208        | 100.0      |
    +| 209        | 100.0      |
    +| 210        | 100.0      |
    +| 215        | 66.67      |
    +| 207        | 33.33      |
    ++------------+------------+
    +All the users registered in contests 208, 209, and 210. The percentage is 100% and we sort them in the answer table by contest_id in ascending order.
    +Alice and Alex registered in contest 215 and the percentage is ((2/3) * 100) = 66.67%
    +Bob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33%
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md b/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md new file mode 100644 index 00000000..9596d7d9 --- /dev/null +++ b/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md @@ -0,0 +1,169 @@ +# [1634. Add Two Polynomials Represented as Linked Lists](https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists) + + + +## Description + +

    A polynomial linked list is a special type of linked list where every node represents a term in a polynomial expression.

    + +

    Each node has three attributes:

    + +
      +
    • coefficient: an integer representing the number multiplier of the term. The coefficient of the term 9x4 is 9.
    • +
    • power: an integer representing the exponent. The power of the term 9x4 is 4.
    • +
    • next: a pointer to the next node in the list, or null if it is the last node of the list.
    • +
    + +

    For example, the polynomial 5x3 + 4x - 7 is represented by the polynomial linked list illustrated below:

    + +

    + +

    The polynomial linked list must be in its standard form: the polynomial must be in strictly descending order by its power value. Also, terms with a coefficient of 0 are omitted.

    + +

    Given two polynomial linked list heads, poly1 and poly2, add the polynomials together and return the head of the sum of the polynomials.

    + +

    PolyNode format:

    + +

    The input/output format is as a list of n nodes, where each node is represented as its [coefficient, power]. For example, the polynomial 5x3 + 4x - 7 would be represented as: [[5,3],[4,1],[-7,0]].

    + +

     

    + +

    Example 1:

    + +

    + +
    +
    +Input: poly1 = [[1,1]], poly2 = [[1,0]]
    +
    +Output: [[1,1],[1,0]]
    +
    +Explanation: poly1 = x. poly2 = 1. The sum is x + 1.
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: poly1 = [[2,2],[4,1],[3,0]], poly2 = [[3,2],[-4,1],[-1,0]]
    +
    +Output: [[5,2],[2,0]]
    +
    +Explanation: poly1 = 2x2 + 4x + 3. poly2 = 3x2 - 4x - 1. The sum is 5x2 + 2. Notice that we omit the "0x" term.
    +
    +
    + +

    Example 3:

    + +
    +
    +Input: poly1 = [[1,2]], poly2 = [[-1,2]]
    +
    +Output: []
    +
    +Explanation: The sum is 0. We return an empty list.
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 0 <= n <= 104
    • +
    • -109 <= PolyNode.coefficient <= 109
    • +
    • PolyNode.coefficient != 0
    • +
    • 0 <= PolyNode.power <= 109
    • +
    • PolyNode.power > PolyNode.next.power
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for polynomial singly-linked list. +# class PolyNode: +# def __init__(self, x=0, y=0, next=None): +# self.coefficient = x +# self.power = y +# self.next = next + +class Solution: + def addPoly(self, poly1: 'PolyNode', poly2: 'PolyNode') -> 'PolyNode': + dummy = PolyNode() + cur = dummy + while poly1 or poly2: + if poly1 is None or (poly2 and poly2.power > poly1.power): + cur.next = poly2 + cur = cur.next + poly2 = poly2.next + elif poly2 is None or (poly1 and poly1.power > poly2.power): + cur.next = poly1 + cur = cur.next + poly1 = poly1.next + else: + val = poly1.coefficient + poly2.coefficient + if val != 0: + cur.next = PolyNode(x=val, y=poly1.power) + cur = cur.next + poly1 = poly1.next + poly2 = poly2.next + cur.next = None + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for polynomial singly-linked list. + * class PolyNode { + * int coefficient, power; + * PolyNode next = null; + + * PolyNode() {} + * PolyNode(int x, int y) { this.coefficient = x; this.power = y; } + * PolyNode(int x, int y, PolyNode next) { this.coefficient = x; this.power = y; this.next = next; } + * } + */ + +class Solution { + public PolyNode addPoly(PolyNode poly1, PolyNode poly2) { + PolyNode dummy = new PolyNode(); + PolyNode cur = dummy; + while (poly1 != null || poly2 != null) { + if (poly1 == null || (poly2 != null && poly2.power > poly1.power)) { + cur.next = poly2; + cur = cur.next; + poly2 = poly2.next; + } else if (poly2 == null || (poly1 != null && poly1.power > poly2.power)) { + cur.next = poly1; + cur = cur.next; + poly1 = poly1.next; + } else { + int val = poly1.coefficient + poly2.coefficient; + if (val != 0) { + cur.next = new PolyNode(val, poly1.power); + cur = cur.next; + } + poly1 = poly1.next; + poly2 = poly2.next; + } + } + cur.next = null; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/images/ex1.png b/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/images/ex1.png new file mode 100644 index 00000000..6d64ae59 Binary files /dev/null and b/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/images/ex1.png differ diff --git a/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/images/polynomial2.png b/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/images/polynomial2.png new file mode 100644 index 00000000..b047eb90 Binary files /dev/null and b/assets/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/images/polynomial2.png differ diff --git a/assets/1600-1699/1635.Hopper Company Queries I/README_EN.md b/assets/1600-1699/1635.Hopper Company Queries I/README_EN.md new file mode 100644 index 00000000..385e6d36 --- /dev/null +++ b/assets/1600-1699/1635.Hopper Company Queries I/README_EN.md @@ -0,0 +1,165 @@ +# [1635. Hopper Company Queries I](https://leetcode.com/problems/hopper-company-queries-i) + + + +## Description + +

    Table: Drivers

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| driver_id   | int     |
    +| join_date   | date    |
    ++-------------+---------+
    +driver_id is the primary key for this table.
    +Each row of this table contains the driver's ID and the date they joined the Hopper company.
    +
    + +

     

    + +

    Table: Rides

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| ride_id      | int     |
    +| user_id      | int     |
    +| requested_at | date    |
    ++--------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
    +There may be some ride requests in this table that were not accepted.
    +
    + +

     

    + +

    Table: AcceptedRides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ride_id       | int     |
    +| driver_id     | int     |
    +| ride_distance | int     |
    +| ride_duration | int     |
    ++---------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains some information about an accepted ride.
    +It is guaranteed that each accepted ride exists in the Rides table.
    +
    + +

     

    + +

    Write an SQL query to report the following statistics for each month of 2020:

    + +
      +
    • The number of drivers currently with the Hopper company by the end of the month (active_drivers).
    • +
    • The number of accepted rides in that month (accepted_rides).
    • +
    + +

    Return the result table ordered by month in ascending order, where month is the month's number (January is 1, February is 2, etc.).

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Drivers table:
    ++-----------+------------+
    +| driver_id | join_date  |
    ++-----------+------------+
    +| 10        | 2019-12-10 |
    +| 8         | 2020-1-13  |
    +| 5         | 2020-2-16  |
    +| 7         | 2020-3-8   |
    +| 4         | 2020-5-17  |
    +| 1         | 2020-10-24 |
    +| 6         | 2021-1-5   |
    ++-----------+------------+
    +
    +Rides table:
    ++---------+---------+--------------+
    +| ride_id | user_id | requested_at |
    ++---------+---------+--------------+
    +| 6       | 75      | 2019-12-9    |
    +| 1       | 54      | 2020-2-9     |
    +| 10      | 63      | 2020-3-4     |
    +| 19      | 39      | 2020-4-6     |
    +| 3       | 41      | 2020-6-3     |
    +| 13      | 52      | 2020-6-22    |
    +| 7       | 69      | 2020-7-16    |
    +| 17      | 70      | 2020-8-25    |
    +| 20      | 81      | 2020-11-2    |
    +| 5       | 57      | 2020-11-9    |
    +| 2       | 42      | 2020-12-9    |
    +| 11      | 68      | 2021-1-11    |
    +| 15      | 32      | 2021-1-17    |
    +| 12      | 11      | 2021-1-19    |
    +| 14      | 18      | 2021-1-27    |
    ++---------+---------+--------------+
    +
    +AcceptedRides table:
    ++---------+-----------+---------------+---------------+
    +| ride_id | driver_id | ride_distance | ride_duration |
    ++---------+-----------+---------------+---------------+
    +| 10      | 10        | 63            | 38            |
    +| 13      | 10        | 73            | 96            |
    +| 7       | 8         | 100           | 28            |
    +| 17      | 7         | 119           | 68            |
    +| 20      | 1         | 121           | 92            |
    +| 5       | 7         | 42            | 101           |
    +| 2       | 4         | 6             | 38            |
    +| 11      | 8         | 37            | 43            |
    +| 15      | 8         | 108           | 82            |
    +| 12      | 8         | 38            | 34            |
    +| 14      | 1         | 90            | 74            |
    ++---------+-----------+---------------+---------------+
    +
    +Result table:
    ++-------+----------------+----------------+
    +| month | active_drivers | accepted_rides |
    ++-------+----------------+----------------+
    +| 1     | 2              | 0              |
    +| 2     | 3              | 0              |
    +| 3     | 4              | 1              |
    +| 4     | 4              | 0              |
    +| 5     | 5              | 0              |
    +| 6     | 5              | 1              |
    +| 7     | 5              | 1              |
    +| 8     | 5              | 1              |
    +| 9     | 5              | 0              |
    +| 10    | 6              | 0              |
    +| 11    | 6              | 2              |
    +| 12    | 6              | 1              |
    ++-------+----------------+----------------+
    +
    +By the end of January --> two active drivers (10, 8) and no accepted rides.
    +By the end of February --> three active drivers (10, 8, 5) and no accepted rides.
    +By the end of March --> four active drivers (10, 8, 5, 7) and one accepted ride (10).
    +By the end of April --> four active drivers (10, 8, 5, 7) and no accepted rides.
    +By the end of May --> five active drivers (10, 8, 5, 7, 4) and no accepted rides.
    +By the end of June --> five active drivers (10, 8, 5, 7, 4) and one accepted ride (13).
    +By the end of July --> five active drivers (10, 8, 5, 7, 4) and one accepted ride (7).
    +By the end of August --> five active drivers (10, 8, 5, 7, 4) and one accepted ride (17).
    +By the end of Septemeber --> five active drivers (10, 8, 5, 7, 4) and no accepted rides.
    +By the end of October --> six active drivers (10, 8, 5, 7, 4, 1) and no accepted rides.
    +By the end of November --> six active drivers (10, 8, 5, 7, 4, 1) and two accepted rides (20, 5).
    +By the end of December --> six active drivers (10, 8, 5, 7, 4, 1) and one accepted ride (2).
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md b/assets/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md new file mode 100644 index 00000000..facabc60 --- /dev/null +++ b/assets/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md @@ -0,0 +1,65 @@ +# [1636. Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency) + + + +## Description + +

    Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.

    + +

    Return the sorted array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,1,2,2,2,3]
    +Output: [3,1,1,2,2,2]
    +Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,3,1,3,2]
    +Output: [1,3,3,2,2]
    +Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
    +
    + +

    Example 3:

    + +
    +Input: nums = [-1,1,-6,4,5,-6,1,4,1]
    +Output: [5,-1,4,4,-6,-6,1,1,1]
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • -100 <= nums[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md b/assets/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md new file mode 100644 index 00000000..c4d63c65 --- /dev/null +++ b/assets/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md @@ -0,0 +1,62 @@ +# [1637. Widest Vertical Area Between Two Points Containing No Points](https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points) + + + +## Description + +

    Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.

    + +

    A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.

    + +

    Note that points on the edge of a vertical area are not considered included in the area.

    + +

     

    +

    Example 1:

    +​ +
    +Input: points = [[8,7],[9,9],[7,4],[9,7]]
    +Output: 1
    +Explanation: Both the red and the blue area are optimal.
    +
    + +

    Example 2:

    + +
    +Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == points.length
    • +
    • 2 <= n <= 105
    • +
    • points[i].length == 2
    • +
    • 0 <= xi, yi <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/images/points3.png b/assets/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/images/points3.png new file mode 100644 index 00000000..f70d7895 Binary files /dev/null and b/assets/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/images/points3.png differ diff --git a/assets/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md b/assets/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md new file mode 100644 index 00000000..66c747b8 --- /dev/null +++ b/assets/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md @@ -0,0 +1,86 @@ +# [1638. Count Substrings That Differ by One Character](https://leetcode.com/problems/count-substrings-that-differ-by-one-character) + + + +## Description + +

    Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.

    + +

    For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way.

    + +

    Return the number of substrings that satisfy the condition above.

    + +

    A substring is a contiguous sequence of characters within a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aba", t = "baba"
    +Output: 6
    +Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +The underlined portions are the substrings that are chosen from s and t.
    +
    +​​Example 2: + +
    +Input: s = "ab", t = "bb"
    +Output: 3
    +Explanation: The following are the pairs of substrings from s and t that differ by 1 character:
    +("ab", "bb")
    +("ab", "bb")
    +("ab", "bb")
    +​​​​The underlined portions are the substrings that are chosen from s and t.
    +
    +Example 3: + +
    +Input: s = "a", t = "a"
    +Output: 0
    +
    + +

    Example 4:

    + +
    +Input: s = "abe", t = "bbc"
    +Output: 10
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length, t.length <= 100
    • +
    • s and t consist of lowercase English letters only.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md b/assets/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md new file mode 100644 index 00000000..04ca299c --- /dev/null +++ b/assets/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md @@ -0,0 +1,97 @@ +# [1639. Number of Ways to Form a Target String Given a Dictionary](https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary) + + + +## Description + +

    You are given a list of strings of the same length words and a string target.

    + +

    Your task is to form target using the given words under the following rules:

    + +
      +
    • target should be formed from left to right.
    • +
    • To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].
    • +
    • Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string.
    • +
    • Repeat the process until you form the string target.
    • +
    + +

    Notice that you can use multiple characters from the same string in words provided the conditions above are met.

    + +

    Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["acca","bbbb","caca"], target = "aba"
    +Output: 6
    +Explanation: There are 6 ways to form target.
    +"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")
    +"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")
    +"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")
    +"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")
    +"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")
    +"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")
    +
    + +

    Example 2:

    + +
    +Input: words = ["abba","baab"], target = "bab"
    +Output: 4
    +Explanation: There are 4 ways to form target.
    +"bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba")
    +"bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab")
    +"bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab")
    +"bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab")
    +
    + +

    Example 3:

    + +
    +Input: words = ["abcd"], target = "abcd"
    +Output: 1
    +
    + +

    Example 4:

    + +
    +Input: words = ["abab","baba","abba","baab"], target = "abba"
    +Output: 16
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 1000
    • +
    • 1 <= words[i].length <= 1000
    • +
    • All strings in words have the same length.
    • +
    • 1 <= target.length <= 1000
    • +
    • words[i] and target contain only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md b/assets/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md new file mode 100644 index 00000000..c1a56a53 --- /dev/null +++ b/assets/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md @@ -0,0 +1,143 @@ +# [1640. Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation) + + + +## Description + +

    You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].

    + +

    Return true if it is possible to form the array arr from pieces. Otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [85], pieces = [[85]]
    +Output: true
    +
    + +

    Example 2:

    + +
    +Input: arr = [15,88], pieces = [[88],[15]]
    +Output: true
    +Explanation: Concatenate [15] then [88]
    +
    + +

    Example 3:

    + +
    +Input: arr = [49,18,16], pieces = [[16,18,49]]
    +Output: false
    +Explanation: Even though the numbers match, we cannot reorder pieces[0].
    +
    + +

    Example 4:

    + +
    +Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
    +Output: true
    +Explanation: Concatenate [91] then [4,64] then [78]
    + +

    Example 5:

    + +
    +Input: arr = [1,3,5,7], pieces = [[2,4,6,8]]
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= pieces.length <= arr.length <= 100
    • +
    • sum(pieces[i].length) == arr.length
    • +
    • 1 <= pieces[i].length <= arr.length
    • +
    • 1 <= arr[i], pieces[i][j] <= 100
    • +
    • The integers in arr are distinct.
    • +
    • The integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: + mapper = {piece[0]: piece for piece in pieces} + i, n = 0, len(arr) + while i < n: + if arr[i] not in mapper: + return False + vals = mapper[arr[i]] + for val in vals: + if arr[i] != val: + return False + i += 1 + return True +``` + +### **Java** + +```java +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + Map map = new HashMap<>(); + for (int[] piece : pieces) { + map.put(piece[0], piece); + } + for (int i = 0; i < arr.length;) { + int[] vals = map.get(arr[i]); + if (vals == null) { + return false; + } + for (int val : vals) { + if (arr[i] != val) { + return false; + } + ++i; + } + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @param {number[][]} pieces + * @return {boolean} + */ +var canFormArray = function(arr, pieces) { + let mapper = new Map(); + for (let i = 0; i < pieces.length; i++) { + mapper.set(pieces[i][0], pieces[i]); + } + let i = 0, n = arr.length; + while (i < n) { + let cur = arr[i]; + let nums = mapper.get(cur); + if (nums == undefined) return false; + for (let num of nums) { + if (arr[i] != num) return false; + i++; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md b/assets/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md new file mode 100644 index 00000000..99911510 --- /dev/null +++ b/assets/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md @@ -0,0 +1,67 @@ +# [1641. Count Sorted Vowel Strings](https://leetcode.com/problems/count-sorted-vowel-strings) + + + +## Description + +

    Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.

    + +

    A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 5
    +Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 15
    +Explanation: The 15 sorted strings that consist of vowels only are
    +["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
    +Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
    +
    + +

    Example 3:

    + +
    +Input: n = 33
    +Output: 66045
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 50 
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1642.Furthest Building You Can Reach/README_EN.md b/assets/1600-1699/1642.Furthest Building You Can Reach/README_EN.md new file mode 100644 index 00000000..4604ab58 --- /dev/null +++ b/assets/1600-1699/1642.Furthest Building You Can Reach/README_EN.md @@ -0,0 +1,81 @@ +# [1642. Furthest Building You Can Reach](https://leetcode.com/problems/furthest-building-you-can-reach) + + + +## Description + +

    You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.

    + +

    You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

    + +

    While moving from building i to building i+1 (0-indexed),

    + +
      +
    • If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
    • +
    • If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
    • +
    + +

    Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

    + +

     

    +

    Example 1:

    + +
    +Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
    +Output: 4
    +Explanation: Starting at building 0, you can follow these steps:
    +- Go to building 1 without using ladders nor bricks since 4 >= 2.
    +- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
    +- Go to building 3 without using ladders nor bricks since 7 >= 6.
    +- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
    +It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
    +
    + +

    Example 2:

    + +
    +Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
    +Output: 7
    +
    + +

    Example 3:

    + +
    +Input: heights = [14,3,19,3], bricks = 17, ladders = 0
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= heights.length <= 105
    • +
    • 1 <= heights[i] <= 106
    • +
    • 0 <= bricks <= 109
    • +
    • 0 <= ladders <= heights.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1642.Furthest Building You Can Reach/images/q4.gif b/assets/1600-1699/1642.Furthest Building You Can Reach/images/q4.gif new file mode 100644 index 00000000..b9118152 Binary files /dev/null and b/assets/1600-1699/1642.Furthest Building You Can Reach/images/q4.gif differ diff --git a/assets/1600-1699/1643.Kth Smallest Instructions/README_EN.md b/assets/1600-1699/1643.Kth Smallest Instructions/README_EN.md new file mode 100644 index 00000000..71d018ac --- /dev/null +++ b/assets/1600-1699/1643.Kth Smallest Instructions/README_EN.md @@ -0,0 +1,84 @@ +# [1643. Kth Smallest Instructions](https://leetcode.com/problems/kth-smallest-instructions) + + + +## Description + +

    Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.

    + +

    The instructions are represented as a string, where each character is either:

    + +
      +
    • 'H', meaning move horizontally (go right), or
    • +
    • 'V', meaning move vertically (go down).
    • +
    + +

    Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.

    + +

    However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.

    + +

    Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: destination = [2,3], k = 1
    +Output: "HHHVV"
    +Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:
    +["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
    +
    + +

    Example 2:

    + +

    + +
    +Input: destination = [2,3], k = 2
    +Output: "HHVHV"
    +
    + +

    Example 3:

    + +

    + +
    +Input: destination = [2,3], k = 3
    +Output: "HHVVH"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • destination.length == 2
    • +
    • 1 <= row, column <= 15
    • +
    • 1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b​​​​​.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1643.Kth Smallest Instructions/images/ex1.png b/assets/1600-1699/1643.Kth Smallest Instructions/images/ex1.png new file mode 100644 index 00000000..f0b1eb67 Binary files /dev/null and b/assets/1600-1699/1643.Kth Smallest Instructions/images/ex1.png differ diff --git a/assets/1600-1699/1643.Kth Smallest Instructions/images/ex2.png b/assets/1600-1699/1643.Kth Smallest Instructions/images/ex2.png new file mode 100644 index 00000000..a2542937 Binary files /dev/null and b/assets/1600-1699/1643.Kth Smallest Instructions/images/ex2.png differ diff --git a/assets/1600-1699/1643.Kth Smallest Instructions/images/ex3.png b/assets/1600-1699/1643.Kth Smallest Instructions/images/ex3.png new file mode 100644 index 00000000..2098d431 Binary files /dev/null and b/assets/1600-1699/1643.Kth Smallest Instructions/images/ex3.png differ diff --git a/assets/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md b/assets/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md new file mode 100644 index 00000000..911f6d1b --- /dev/null +++ b/assets/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md @@ -0,0 +1,73 @@ +# [1644. Lowest Common Ancestor of a Binary Tree II](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii) + + + +## Description + +

    Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique.

    + +

    According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)". A descendant of a node x is a node y that is on the path from node x to some leaf node.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    +Output: 3
    +Explanation: The LCA of nodes 5 and 1 is 3.
    + +

    Example 2:

    + +

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    +Output: 5
    +Explanation: The LCA of nodes 5 and 4 is 5. A node can be a descendant of itself according to the definition of LCA.
    + +

    Example 3:

    + +

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10
    +Output: null
    +Explanation: Node 10 does not exist in the tree, so return null.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 104].
    • +
    • -109 <= Node.val <= 109
    • +
    • All Node.val are unique.
    • +
    • p != q
    • +
    + +

     

    +Follow up: Can you find the LCA traversing the tree, without checking nodes existence? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/images/binarytree.png b/assets/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/images/binarytree.png new file mode 100644 index 00000000..2ad942c3 Binary files /dev/null and b/assets/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/images/binarytree.png differ diff --git a/assets/1600-1699/1645.Hopper Company Queries II/README_EN.md b/assets/1600-1699/1645.Hopper Company Queries II/README_EN.md new file mode 100644 index 00000000..35066673 --- /dev/null +++ b/assets/1600-1699/1645.Hopper Company Queries II/README_EN.md @@ -0,0 +1,162 @@ +# [1645. Hopper Company Queries II](https://leetcode.com/problems/hopper-company-queries-ii) + + + +## Description + +

    Table: Drivers

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| driver_id   | int     |
    +| join_date   | date    |
    ++-------------+---------+
    +driver_id is the primary key for this table.
    +Each row of this table contains the driver's ID and the date they joined the Hopper company.
    +
    + +

     

    + +

    Table: Rides

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| ride_id      | int     |
    +| user_id      | int     |
    +| requested_at | date    |
    ++--------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
    +There may be some ride requests in this table that were not accepted.
    +
    + +

     

    + +

    Table: AcceptedRides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ride_id       | int     |
    +| driver_id     | int     |
    +| ride_distance | int     |
    +| ride_duration | int     |
    ++---------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains some information about an accepted ride.
    +It is guaranteed that each accepted ride exists in the Rides table.
    +
    + +

     

    + +

    Write an SQL query to report the percentage of working drivers (working_percentage) for each month of 2020 where:

    + +

    Note that if the number of available drivers during a month is zero, we consider the working_percentage to be 0.

    + +

    Return the result table ordered by month in ascending order, where month is the month's number (January is 1, February is 2, etc.). Round working_percentage to the nearest 2 decimal places.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Drivers table:
    ++-----------+------------+
    +| driver_id | join_date  |
    ++-----------+------------+
    +| 10        | 2019-12-10 |
    +| 8         | 2020-1-13  |
    +| 5         | 2020-2-16  |
    +| 7         | 2020-3-8   |
    +| 4         | 2020-5-17  |
    +| 1         | 2020-10-24 |
    +| 6         | 2021-1-5   |
    ++-----------+------------+
    +
    +Rides table:
    ++---------+---------+--------------+
    +| ride_id | user_id | requested_at |
    ++---------+---------+--------------+
    +| 6       | 75      | 2019-12-9    |
    +| 1       | 54      | 2020-2-9     |
    +| 10      | 63      | 2020-3-4     |
    +| 19      | 39      | 2020-4-6     |
    +| 3       | 41      | 2020-6-3     |
    +| 13      | 52      | 2020-6-22    |
    +| 7       | 69      | 2020-7-16    |
    +| 17      | 70      | 2020-8-25    |
    +| 20      | 81      | 2020-11-2    |
    +| 5       | 57      | 2020-11-9    |
    +| 2       | 42      | 2020-12-9    |
    +| 11      | 68      | 2021-1-11    |
    +| 15      | 32      | 2021-1-17    |
    +| 12      | 11      | 2021-1-19    |
    +| 14      | 18      | 2021-1-27    |
    ++---------+---------+--------------+
    +
    +AcceptedRides table:
    ++---------+-----------+---------------+---------------+
    +| ride_id | driver_id | ride_distance | ride_duration |
    ++---------+-----------+---------------+---------------+
    +| 10      | 10        | 63            | 38            |
    +| 13      | 10        | 73            | 96            |
    +| 7       | 8         | 100           | 28            |
    +| 17      | 7         | 119           | 68            |
    +| 20      | 1         | 121           | 92            |
    +| 5       | 7         | 42            | 101           |
    +| 2       | 4         | 6             | 38            |
    +| 11      | 8         | 37            | 43            |
    +| 15      | 8         | 108           | 82            |
    +| 12      | 8         | 38            | 34            |
    +| 14      | 1         | 90            | 74            |
    ++---------+-----------+---------------+---------------+
    +
    +Result table:
    ++-------+--------------------+
    +| month | working_percentage |
    ++-------+--------------------+
    +| 1     | 0.00               |
    +| 2     | 0.00               |
    +| 3     | 25.00              |
    +| 4     | 0.00               |
    +| 5     | 0.00               |
    +| 6     | 20.00              |
    +| 7     | 20.00              |
    +| 8     | 20.00              |
    +| 9     | 0.00               |
    +| 10    | 0.00               |
    +| 11    | 33.33              |
    +| 12    | 16.67              |
    ++-------+--------------------+
    +
    +By the end of January --> two active drivers (10, 8) and no accepted rides. The percentage is 0%.
    +By the end of February --> three active drivers (10, 8, 5) and no accepted rides. The percentage is 0%.
    +By the end of March --> four active drivers (10, 8, 5, 7) and one accepted ride by driver (10). The percentage is (1 / 4) * 100 = 25%.
    +By the end of April --> four active drivers (10, 8, 5, 7) and no accepted rides. The percentage is 0%.
    +By the end of May --> five active drivers (10, 8, 5, 7, 4) and no accepted rides. The percentage is 0%.
    +By the end of June --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (10). The percentage is (1 / 5) * 100 = 20%.
    +By the end of July --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (8). The percentage is (1 / 5) * 100 = 20%.
    +By the end of August --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (7). The percentage is (1 / 5) * 100 = 20%.
    +By the end of Septemeber --> five active drivers (10, 8, 5, 7, 4) and no accepted rides. The percentage is 0%.
    +By the end of October --> six active drivers (10, 8, 5, 7, 4, 1) and no accepted rides. The percentage is 0%.
    +By the end of November --> six active drivers (10, 8, 5, 7, 4, 1) and two accepted rides by two different drivers (1, 7). The percentage is (2 / 6) * 100 = 33.33%.
    +By the end of December --> six active drivers (10, 8, 5, 7, 4, 1) and one accepted ride by driver (4). The percentage is (1 / 6) * 100 = 16.67%.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1645.Hopper Company Queries II/images/codecogseqn.png b/assets/1600-1699/1645.Hopper Company Queries II/images/codecogseqn.png new file mode 100644 index 00000000..e732ce7d Binary files /dev/null and b/assets/1600-1699/1645.Hopper Company Queries II/images/codecogseqn.png differ diff --git a/assets/1600-1699/1646.Get Maximum in Generated Array/README_EN.md b/assets/1600-1699/1646.Get Maximum in Generated Array/README_EN.md new file mode 100644 index 00000000..ad1ea2a2 --- /dev/null +++ b/assets/1600-1699/1646.Get Maximum in Generated Array/README_EN.md @@ -0,0 +1,82 @@ +# [1646. Get Maximum in Generated Array](https://leetcode.com/problems/get-maximum-in-generated-array) + + + +## Description + +

    You are given an integer n. An array nums of length n + 1 is generated in the following way:

    + +
      +
    • nums[0] = 0
    • +
    • nums[1] = 1
    • +
    • nums[2 * i] = nums[i] when 2 <= 2 * i <= n
    • +
    • nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n
    • +
    + +

    Return the maximum integer in the array nums​​​.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 7
    +Output: 3
    +Explanation: According to the given rules:
    +  nums[0] = 0
    +  nums[1] = 1
    +  nums[(1 * 2) = 2] = nums[1] = 1
    +  nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
    +  nums[(2 * 2) = 4] = nums[2] = 1
    +  nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
    +  nums[(3 * 2) = 6] = nums[3] = 2
    +  nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
    +Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is 3.
    +
    + +

    Example 2:

    + +
    +Input: n = 2
    +Output: 1
    +Explanation: According to the given rules, the maximum between nums[0], nums[1], and nums[2] is 1.
    +
    + +

    Example 3:

    + +
    +Input: n = 3
    +Output: 2
    +Explanation: According to the given rules, the maximum between nums[0], nums[1], nums[2], and nums[3] is 2.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= n <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md b/assets/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md new file mode 100644 index 00000000..03a71479 --- /dev/null +++ b/assets/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md @@ -0,0 +1,117 @@ +# [1647. Minimum Deletions to Make Character Frequencies Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique) + + + +## Description + +

    A string s is called good if there are no two different characters in s that have the same frequency.

    + +

    Given a string s, return the minimum number of characters you need to delete to make s good.

    + +

    The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aab"
    +Output: 0
    +Explanation: s is already good.
    +
    + +

    Example 2:

    + +
    +Input: s = "aaabbbcc"
    +Output: 2
    +Explanation: You can delete two 'b's resulting in the good string "aaabcc".
    +Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".
    + +

    Example 3:

    + +
    +Input: s = "ceabaacb"
    +Output: 2
    +Explanation: You can delete both 'c's resulting in the good string "eabaab".
    +Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minDeletions(self, s: str) -> int: + counter = collections.Counter(s) + vals = [v for v in counter.values()] + vals.sort(reverse=True) + ans = 0 + for i in range(1, len(vals)): + while vals[i] >= vals[i - 1] and vals[i] > 0: + vals[i] -= 1 + ans += 1 + return ans +``` + +### **Java** + +```java +class Solution { + public int minDeletions(String s) { + int[] counter = new int[26]; + for (char c : s.toCharArray()) { + ++counter[c - 'a']; + } + Arrays.sort(counter); + int ans = 0; + for (int i = 24; i >= 0; --i) { + while (counter[i] >= counter[i + 1] && counter[i] > 0) { + --counter[i]; + ++ans; + } + } + return ans; + } +} +``` + +### **TypeScript** + +```ts +function minDeletions(s: string): number { + let map = {}; + for (let c of s) { + map[c] = (map[c] || 0) + 1; + } + let ans = 0; + let vals: number[] = Object.values(map); + vals.sort((a, b) => a - b); + for (let i = 1; i < vals.length; ++i) { + while(vals[i] > 0 && i != vals.indexOf(vals[i])) { + --vals[i]; + ++ans; + } + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md b/assets/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md new file mode 100644 index 00000000..8f3f6df4 --- /dev/null +++ b/assets/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md @@ -0,0 +1,81 @@ +# [1648. Sell Diminishing-Valued Colored Balls](https://leetcode.com/problems/sell-diminishing-valued-colored-balls) + + + +## Description + +

    You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.

    + +

    The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).

    + +

    You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.

    + +

    Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: inventory = [2,5], orders = 4
    +Output: 14
    +Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
    +The maximum total value is 2 + 5 + 4 + 3 = 14.
    +
    + +

    Example 2:

    + +
    +Input: inventory = [3,5], orders = 6
    +Output: 19
    +Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
    +The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
    +
    + +

    Example 3:

    + +
    +Input: inventory = [2,8,4,10,6], orders = 20
    +Output: 110
    +
    + +

    Example 4:

    + +
    +Input: inventory = [1000000000], orders = 1000000000
    +Output: 21
    +Explanation: Sell the 1st color 1000000000 times for a total value of 500000000500000000. 500000000500000000 modulo 109 + 7 = 21.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= inventory.length <= 105
    • +
    • 1 <= inventory[i] <= 109
    • +
    • 1 <= orders <= min(sum(inventory[i]), 109)
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1648.Sell Diminishing-Valued Colored Balls/images/jj.gif b/assets/1600-1699/1648.Sell Diminishing-Valued Colored Balls/images/jj.gif new file mode 100644 index 00000000..2d36fd37 Binary files /dev/null and b/assets/1600-1699/1648.Sell Diminishing-Valued Colored Balls/images/jj.gif differ diff --git a/assets/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md b/assets/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md new file mode 100644 index 00000000..c6f9abc0 --- /dev/null +++ b/assets/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md @@ -0,0 +1,151 @@ +# [1649. Create Sorted Array through Instructions](https://leetcode.com/problems/create-sorted-array-through-instructions) + + + +## Description + +

    Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:

    + + + +
      +
    • The number of elements currently in nums that are strictly less than instructions[i].
    • +
    • The number of elements currently in nums that are strictly greater than instructions[i].
    • +
    + + + +

    For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].

    + + + +

    Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: instructions = [1,5,6,2]
    +
    +Output: 1
    +
    +Explanation: Begin with nums = [].
    +
    +Insert 1 with cost min(0, 0) = 0, now nums = [1].
    +
    +Insert 5 with cost min(1, 0) = 0, now nums = [1,5].
    +
    +Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].
    +
    +Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].
    +
    +The total cost is 0 + 0 + 0 + 1 = 1.
    + + + +

    Example 2:

    + + + +
    +
    +Input: instructions = [1,2,3,6,5,4]
    +
    +Output: 3
    +
    +Explanation: Begin with nums = [].
    +
    +Insert 1 with cost min(0, 0) = 0, now nums = [1].
    +
    +Insert 2 with cost min(1, 0) = 0, now nums = [1,2].
    +
    +Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].
    +
    +Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].
    +
    +Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].
    +
    +Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].
    +
    +The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: instructions = [1,3,3,3,2,4,2,1,2]
    +
    +Output: 4
    +
    +Explanation: Begin with nums = [].
    +
    +Insert 1 with cost min(0, 0) = 0, now nums = [1].
    +
    +Insert 3 with cost min(1, 0) = 0, now nums = [1,3].
    +
    +Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].
    +
    +Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].
    +
    +Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].
    +
    +Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].
    +
    +​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].
    +
    +​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].
    +
    +​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].
    +
    +The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= instructions.length <= 105
    • +
    • 1 <= instructions[i] <= 105
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md b/assets/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md new file mode 100644 index 00000000..3817c600 --- /dev/null +++ b/assets/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md @@ -0,0 +1,80 @@ +# [1650. Lowest Common Ancestor of a Binary Tree III](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iii) + + + +## Description + +

    Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA).

    + +

    Each node will have a reference to its parent node. The definition for Node is below:

    + +
    +class Node {
    +    public int val;
    +    public Node left;
    +    public Node right;
    +    public Node parent;
    +}
    +
    + +

    According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    +Output: 3
    +Explanation: The LCA of nodes 5 and 1 is 3.
    +
    + +

    Example 2:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    +Output: 5
    +Explanation: The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.
    +
    + +

    Example 3:

    + +
    +Input: root = [1,2], p = 1, q = 2
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [2, 105].
    • +
    • -109 <= Node.val <= 109
    • +
    • All Node.val are unique.
    • +
    • p != q
    • +
    • p and q exist in the tree.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/images/binarytree.png b/assets/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/images/binarytree.png new file mode 100644 index 00000000..2ad942c3 Binary files /dev/null and b/assets/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/images/binarytree.png differ diff --git a/assets/1600-1699/1651.Hopper Company Queries III/README_EN.md b/assets/1600-1699/1651.Hopper Company Queries III/README_EN.md new file mode 100644 index 00000000..d79ad443 --- /dev/null +++ b/assets/1600-1699/1651.Hopper Company Queries III/README_EN.md @@ -0,0 +1,158 @@ +# [1651. Hopper Company Queries III](https://leetcode.com/problems/hopper-company-queries-iii) + + + +## Description + +

    Table: Drivers

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| driver_id   | int     |
    +| join_date   | date    |
    ++-------------+---------+
    +driver_id is the primary key for this table.
    +Each row of this table contains the driver's ID and the date they joined the Hopper company.
    +
    + +

     

    + +

    Table: Rides

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| ride_id      | int     |
    +| user_id      | int     |
    +| requested_at | date    |
    ++--------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
    +There may be some ride requests in this table that were not accepted.
    +
    + +

     

    + +

    Table: AcceptedRides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ride_id       | int     |
    +| driver_id     | int     |
    +| ride_distance | int     |
    +| ride_duration | int     |
    ++---------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains some information about an accepted ride.
    +It is guaranteed that each accepted ride exists in the Rides table.
    +
    + +

     

    + +

    Write an SQL query to compute the average_ride_distance and average_ride_duration of every 3-month window starting from January - March 2020 to October - December 2020. Round average_ride_distance and average_ride_duration to the nearest two decimal places.

    + +

    The average_ride_distance is calculated by summing up the total ride_distance values from the three months and dividing it by 3. The average_ride_duration is calculated in a similar way.

    + +

    Return the result table ordered by month in ascending order, where month is the starting month's number (January is 1, February is 2, etc.).

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Drivers table:
    ++-----------+------------+
    +| driver_id | join_date  |
    ++-----------+------------+
    +| 10        | 2019-12-10 |
    +| 8         | 2020-1-13  |
    +| 5         | 2020-2-16  |
    +| 7         | 2020-3-8   |
    +| 4         | 2020-5-17  |
    +| 1         | 2020-10-24 |
    +| 6         | 2021-1-5   |
    ++-----------+------------+
    +
    +Rides table:
    ++---------+---------+--------------+
    +| ride_id | user_id | requested_at |
    ++---------+---------+--------------+
    +| 6       | 75      | 2019-12-9    |
    +| 1       | 54      | 2020-2-9     |
    +| 10      | 63      | 2020-3-4     |
    +| 19      | 39      | 2020-4-6     |
    +| 3       | 41      | 2020-6-3     |
    +| 13      | 52      | 2020-6-22    |
    +| 7       | 69      | 2020-7-16    |
    +| 17      | 70      | 2020-8-25    |
    +| 20      | 81      | 2020-11-2    |
    +| 5       | 57      | 2020-11-9    |
    +| 2       | 42      | 2020-12-9    |
    +| 11      | 68      | 2021-1-11    |
    +| 15      | 32      | 2021-1-17    |
    +| 12      | 11      | 2021-1-19    |
    +| 14      | 18      | 2021-1-27    |
    ++---------+---------+--------------+
    +
    +AcceptedRides table:
    ++---------+-----------+---------------+---------------+
    +| ride_id | driver_id | ride_distance | ride_duration |
    ++---------+-----------+---------------+---------------+
    +| 10      | 10        | 63            | 38            |
    +| 13      | 10        | 73            | 96            |
    +| 7       | 8         | 100           | 28            |
    +| 17      | 7         | 119           | 68            |
    +| 20      | 1         | 121           | 92            |
    +| 5       | 7         | 42            | 101           |
    +| 2       | 4         | 6             | 38            |
    +| 11      | 8         | 37            | 43            |
    +| 15      | 8         | 108           | 82            |
    +| 12      | 8         | 38            | 34            |
    +| 14      | 1         | 90            | 74            |
    ++---------+-----------+---------------+---------------+
    +
    +Result table:
    ++-------+-----------------------+-----------------------+
    +| month | average_ride_distance | average_ride_duration |
    ++-------+-----------------------+-----------------------+
    +| 1     | 21.00                 | 12.67                 |
    +| 2     | 21.00                 | 12.67                 |
    +| 3     | 21.00                 | 12.67                 |
    +| 4     | 24.33                 | 32.00                 |
    +| 5     | 57.67                 | 41.33                 |
    +| 6     | 97.33                 | 64.00                 |
    +| 7     | 73.00                 | 32.00                 |
    +| 8     | 39.67                 | 22.67                 |
    +| 9     | 54.33                 | 64.33                 |
    +| 10    | 56.33                 | 77.00                 |
    ++-------+-----------------------+-----------------------+
    +
    +By the end of January --> average_ride_distance = (0+0+63)/3=21, average_ride_duration = (0+0+38)/3=12.67
    +By the end of February --> average_ride_distance = (0+63+0)/3=21, average_ride_duration = (0+38+0)/3=12.67
    +By the end of March --> average_ride_distance = (63+0+0)/3=21, average_ride_duration = (38+0+0)/3=12.67
    +By the end of April --> average_ride_distance = (0+0+73)/3=24.33, average_ride_duration = (0+0+96)/3=32.00
    +By the end of May --> average_ride_distance = (0+73+100)/3=57.67, average_ride_duration = (0+96+28)/3=41.33
    +By the end of June --> average_ride_distance = (73+100+119)/3=97.33, average_ride_duration = (96+28+68)/3=64.00
    +By the end of July --> average_ride_distance = (100+119+0)/3=73.00, average_ride_duration = (28+68+0)/3=32.00
    +By the end of August --> average_ride_distance = (119+0+0)/3=39.67, average_ride_duration = (68+0+0)/3=22.67
    +By the end of Septemeber --> average_ride_distance = (0+0+163)/3=54.33, average_ride_duration = (0+0+193)/3=64.33
    +By the end of October --> average_ride_distance = (0+163+6)/3=56.33, average_ride_duration = (0+193+38)/3=77.00
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1652.Defuse the Bomb/README_EN.md b/assets/1600-1699/1652.Defuse the Bomb/README_EN.md new file mode 100644 index 00000000..72f040d0 --- /dev/null +++ b/assets/1600-1699/1652.Defuse the Bomb/README_EN.md @@ -0,0 +1,110 @@ +# [1652. Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb) + + + +## Description + +

    You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.

    + +

    To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.

    + +
      +
    • If k > 0, replace the ith number with the sum of the next k numbers.
    • +
    • If k < 0, replace the ith number with the sum of the previous k numbers.
    • +
    • If k == 0, replace the ith number with 0.
    • +
    + +

    As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].

    + +

    Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!

    + +

     

    +

    Example 1:

    + +
    +Input: code = [5,7,1,4], k = 3
    +Output: [12,10,16,13]
    +Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.
    +
    + +

    Example 2:

    + +
    +Input: code = [1,2,3,4], k = 0
    +Output: [0,0,0,0]
    +Explanation: When k is zero, the numbers are replaced by 0. 
    +
    + +

    Example 3:

    + +
    +Input: code = [2,4,9,3], k = -2
    +Output: [12,5,6,13]
    +Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == code.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= code[i] <= 100
    • +
    • -(n - 1) <= k <= n - 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + res = [0] * n + if k == 0: + return res + for i in range(n): + if k > 0: + for j in range(i + 1, i + k + 1): + res[i] += code[j % n] + else: + for j in range(i + k, i): + res[i] += code[(j + n) % n] + return res +``` + +### **Java** + +```java +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] res = new int[n]; + if (k == 0) return res; + for (int i = 0; i < n; ++i) { + if (k > 0) { + for (int j = i + 1; j <= i + k; ++j) { + res[i] += code[j % n]; + } + } else { + for (int j = i + k; j <= i - 1; ++j) { + res[i] += code[(j + n) % n]; + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md b/assets/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md new file mode 100644 index 00000000..f2e6a073 --- /dev/null +++ b/assets/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md @@ -0,0 +1,63 @@ +# [1653. Minimum Deletions to Make String Balanced](https://leetcode.com/problems/minimum-deletions-to-make-string-balanced) + + + +## Description + +

    You are given a string s consisting only of characters 'a' and 'b'​​​​.

    + +

    You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.

    + +

    Return the minimum number of deletions needed to make s balanced.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aababbab"
    +Output: 2
    +Explanation: You can either:
    +Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or
    +Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").
    +
    + +

    Example 2:

    + +
    +Input: s = "bbaaaaabb"
    +Output: 2
    +Explanation: The only solution is to delete the first two characters.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s[i] is 'a' or 'b'​​.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md b/assets/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md new file mode 100644 index 00000000..7868946e --- /dev/null +++ b/assets/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md @@ -0,0 +1,80 @@ +# [1654. Minimum Jumps to Reach Home](https://leetcode.com/problems/minimum-jumps-to-reach-home) + + + +## Description + +

    A certain bug's home is on the x-axis at position x. Help them get there from position 0.

    + +

    The bug jumps according to the following rules:

    + +
      +
    • It can jump exactly a positions forward (to the right).
    • +
    • It can jump exactly b positions backward (to the left).
    • +
    • It cannot jump backward twice in a row.
    • +
    • It cannot jump to any forbidden positions.
    • +
    + +

    The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.

    + +

    Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
    +Output: 3
    +Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.
    +
    + +

    Example 2:

    + +
    +Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
    +Output: -1
    +
    + +

    Example 3:

    + +
    +Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
    +Output: 2
    +Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= forbidden.length <= 1000
    • +
    • 1 <= a, b, forbidden[i] <= 2000
    • +
    • 0 <= x <= 2000
    • +
    • All the elements in forbidden are distinct.
    • +
    • Position x is not forbidden.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1655.Distribute Repeating Integers/README_EN.md b/assets/1600-1699/1655.Distribute Repeating Integers/README_EN.md new file mode 100644 index 00000000..e01fad47 --- /dev/null +++ b/assets/1600-1699/1655.Distribute Repeating Integers/README_EN.md @@ -0,0 +1,93 @@ +# [1655. Distribute Repeating Integers](https://leetcode.com/problems/distribute-repeating-integers) + + + +## Description + +

    You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:

    + +
      +
    • The ith customer gets exactly quantity[i] integers,
    • +
    • The integers the ith customer gets are all equal, and
    • +
    • Every customer is satisfied.
    • +
    + +

    Return true if it is possible to distribute nums according to the above conditions.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4], quantity = [2]
    +Output: false
    +Explanation: The 0th customer cannot be given two different integers.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,3,3], quantity = [2]
    +Output: true
    +Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,1,2,2], quantity = [2,2]
    +Output: true
    +Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].
    +
    + +

    Example 4:

    + +
    +Input: nums = [1,1,2,3], quantity = [2,2]
    +Output: false
    +Explanation: Although the 0th customer could be given [1,1], the 1st customer cannot be satisfied.
    + +

    Example 5:

    + +
    +Input: nums = [1,1,1,1,1], quantity = [2,3]
    +Output: true
    +Explanation: The 0th customer is given [1,1], and the 1st customer is given [1,1,1].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums[i] <= 1000
    • +
    • m == quantity.length
    • +
    • 1 <= m <= 10
    • +
    • 1 <= quantity[i] <= 105
    • +
    • There are at most 50 unique values in nums.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1656.Design an Ordered Stream/README_EN.md b/assets/1600-1699/1656.Design an Ordered Stream/README_EN.md new file mode 100644 index 00000000..471552cc --- /dev/null +++ b/assets/1600-1699/1656.Design an Ordered Stream/README_EN.md @@ -0,0 +1,78 @@ +# [1656. Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream) + + + +## Description + +

    There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.

    + +

    Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.

    + +

    Implement the OrderedStream class:

    + +
      +
    • OrderedStream(int n) Constructs the stream to take n values.
    • +
    • String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.
    • +
    + +

     

    +

    Example:

    + +

    + +
    +Input
    +["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
    +[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
    +Output
    +[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
    +
    +Explanation
    +// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].
    +OrderedStream os = new OrderedStream(5);
    +os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].
    +os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].
    +os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
    +os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].
    +os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].
    +// Concatentating all the chunks returned:
    +// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]
    +// The resulting order is the same as the order above.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1000
    • +
    • 1 <= id <= n
    • +
    • value.length == 5
    • +
    • value consists only of lowercase letters.
    • +
    • Each call to insert will have a unique id.
    • +
    • Exactly n calls will be made to insert.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1656.Design an Ordered Stream/images/q1.gif b/assets/1600-1699/1656.Design an Ordered Stream/images/q1.gif new file mode 100644 index 00000000..ea04d86f Binary files /dev/null and b/assets/1600-1699/1656.Design an Ordered Stream/images/q1.gif differ diff --git a/assets/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md b/assets/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md new file mode 100644 index 00000000..ab3c6717 --- /dev/null +++ b/assets/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md @@ -0,0 +1,96 @@ +# [1657. Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close) + + + +## Description + +

    Two strings are considered close if you can attain one from the other using the following operations:

    + +
      +
    • Operation 1: Swap any two existing characters. + +
        +
      • For example, abcde -> aecdb
      • +
      +
    • +
    • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. +
        +
      • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
      • +
      +
    • +
    + +

    You can use the operations on either string as many times as necessary.

    + +

    Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: word1 = "abc", word2 = "bca"
    +Output: true
    +Explanation: You can attain word2 from word1 in 2 operations.
    +Apply Operation 1: "abc" -> "acb"
    +Apply Operation 1: "acb" -> "bca"
    +
    + +

    Example 2:

    + +
    +Input: word1 = "a", word2 = "aa"
    +Output: false
    +Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
    +
    + +

    Example 3:

    + +
    +Input: word1 = "cabbba", word2 = "abbccc"
    +Output: true
    +Explanation: You can attain word2 from word1 in 3 operations.
    +Apply Operation 1: "cabbba" -> "caabbb"
    +Apply Operation 2: "caabbb" -> "baaccc"
    +Apply Operation 2: "baaccc" -> "abbccc"
    +
    + +

    Example 4:

    + +
    +Input: word1 = "cabbba", word2 = "aabbss"
    +Output: false
    +Explanation: It is impossible to attain word2 from word1, or vice versa, in any amount of operations.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word1.length, word2.length <= 105
    • +
    • word1 and word2 contain only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md b/assets/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md new file mode 100644 index 00000000..8aec9bdb --- /dev/null +++ b/assets/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md @@ -0,0 +1,67 @@ +# [1658. Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero) + + + +## Description + +

    You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.

    + +

    Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,1,4,2,3], x = 5
    +Output: 2
    +Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,6,7,8,9], x = 4
    +Output: -1
    +
    + +

    Example 3:

    + +
    +Input: nums = [3,2,20,1,1,3], x = 10
    +Output: 5
    +Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 104
    • +
    • 1 <= x <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1659.Maximize Grid Happiness/README_EN.md b/assets/1600-1699/1659.Maximize Grid Happiness/README_EN.md new file mode 100644 index 00000000..eb361e8b --- /dev/null +++ b/assets/1600-1699/1659.Maximize Grid Happiness/README_EN.md @@ -0,0 +1,87 @@ +# [1659. Maximize Grid Happiness](https://leetcode.com/problems/maximize-grid-happiness) + + + +## Description + +

    You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts.

    + +

    You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.

    + +

    The happiness of each person is calculated as follows:

    + +
      +
    • Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).
    • +
    • Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).
    • +
    + +

    Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.

    + +

    The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.

    + +

     

    +

    Example 1:

    + +
    +Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
    +Output: 240
    +Explanation: Assume the grid is 1-indexed with coordinates (row, column).
    +We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).
    +- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120
    +- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
    +- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
    +The grid happiness is 120 + 60 + 60 = 240.
    +The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.
    +
    + +

    Example 2:

    + +
    +Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
    +Output: 260
    +Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).
    +- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
    +- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80
    +- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
    +The grid happiness is 90 + 80 + 90 = 260.
    +
    + +

    Example 3:

    + +
    +Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
    +Output: 240
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= m, n <= 5
    • +
    • 0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1659.Maximize Grid Happiness/images/grid_happiness.png b/assets/1600-1699/1659.Maximize Grid Happiness/images/grid_happiness.png new file mode 100644 index 00000000..6084df0a Binary files /dev/null and b/assets/1600-1699/1659.Maximize Grid Happiness/images/grid_happiness.png differ diff --git a/assets/1600-1699/1660.Correct a Binary Tree/README_EN.md b/assets/1600-1699/1660.Correct a Binary Tree/README_EN.md new file mode 100644 index 00000000..2ccb47b9 --- /dev/null +++ b/assets/1600-1699/1660.Correct a Binary Tree/README_EN.md @@ -0,0 +1,115 @@ +# [1660. Correct a Binary Tree](https://leetcode.com/problems/correct-a-binary-tree) + + + +## Description + +

    You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node's right.

    + + + +

    Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this invalid node and every node underneath it (minus the node it incorrectly points to).

    + + + +

    Custom testing:

    + + + +

    The test input is read as 3 lines:

    + + + +
      +
    • TreeNode root
    • +
    • int fromNode (not available to correctBinaryTree)
    • +
    • int toNode (not available to correctBinaryTree)
    • +
    + + + +

    After the binary tree rooted at root is parsed, the TreeNode with value of fromNode will have its right child pointer pointing to the TreeNode with a value of toNode. Then, root is passed to correctBinaryTree.

    + + + +

     

    + +

    Example 1:

    + + + +

    + + + +
    +
    +Input: root = [1,2,3], fromNode = 2, toNode = 3
    +
    +Output: [1,null,3]
    +
    +Explanation: The node with value 2 is invalid, so remove it.
    +
    +
    + + + +

    Example 2:

    + + + +

    + + + +
    +
    +Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4
    +
    +Output: [8,3,1,null,null,9,4,null,null,5,6]
    +
    +Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the tree is in the range [3, 104].
    • +
    • -109 <= Node.val <= 109
    • +
    • All Node.val are unique.
    • +
    • fromNode != toNode
    • +
    • fromNode and toNode will exist in the tree and will be on the same depth.
    • +
    • toNode is to the right of fromNode.
    • +
    • fromNode.right is null in the initial tree from the test data.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1660.Correct a Binary Tree/images/ex1v2.png b/assets/1600-1699/1660.Correct a Binary Tree/images/ex1v2.png new file mode 100644 index 00000000..c0ff183e Binary files /dev/null and b/assets/1600-1699/1660.Correct a Binary Tree/images/ex1v2.png differ diff --git a/assets/1600-1699/1660.Correct a Binary Tree/images/ex2v3.png b/assets/1600-1699/1660.Correct a Binary Tree/images/ex2v3.png new file mode 100644 index 00000000..644b7de0 Binary files /dev/null and b/assets/1600-1699/1660.Correct a Binary Tree/images/ex2v3.png differ diff --git a/assets/1600-1699/1661.Average Time of Process per Machine/README_EN.md b/assets/1600-1699/1661.Average Time of Process per Machine/README_EN.md new file mode 100644 index 00000000..025f5d90 --- /dev/null +++ b/assets/1600-1699/1661.Average Time of Process per Machine/README_EN.md @@ -0,0 +1,84 @@ +# [1661. Average Time of Process per Machine](https://leetcode.com/problems/average-time-of-process-per-machine) + + + +## Description + +

    Table: Activity

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| machine_id     | int     |
    +| process_id     | int     |
    +| activity_type  | enum    |
    +| timestamp      | float   |
    ++----------------+---------+
    +The table shows the user activities for a factory website.
    +(machine_id, process_id, activity_type) is the primary key of this table.
    +machine_id is the ID of a machine.
    +process_id is the ID of a process running on the machine with ID machine_id.
    +activity_type is an ENUM of type ('start', 'end').
    +timestamp is a float representing the current time in seconds.
    +'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp.
    +The 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair.
    + +

     

    + +

    There is a factory website that has several machines each running the same number of processes. Write an SQL query to find the average time each machine takes to complete a process.

    + +

    The time to complete a process is the 'end' timestamp minus the 'start' timestamp. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run.

    + +

    The resulting table should have the machine_id along with the average time as processing_time, which should be rounded to 3 decimal places.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Activity table:
    ++------------+------------+---------------+-----------+
    +| machine_id | process_id | activity_type | timestamp |
    ++------------+------------+---------------+-----------+
    +| 0          | 0          | start         | 0.712     |
    +| 0          | 0          | end           | 1.520     |
    +| 0          | 1          | start         | 3.140     |
    +| 0          | 1          | end           | 4.120     |
    +| 1          | 0          | start         | 0.550     |
    +| 1          | 0          | end           | 1.550     |
    +| 1          | 1          | start         | 0.430     |
    +| 1          | 1          | end           | 1.420     |
    +| 2          | 0          | start         | 4.100     |
    +| 2          | 0          | end           | 4.512     |
    +| 2          | 1          | start         | 2.500     |
    +| 2          | 1          | end           | 5.000     |
    ++------------+------------+---------------+-----------+
    +
    +Result table:
    ++------------+-----------------+
    +| machine_id | processing_time |
    ++------------+-----------------+
    +| 0          | 0.894           |
    +| 1          | 0.995           |
    +| 2          | 1.456           |
    ++------------+-----------------+
    +
    +There are 3 machines running 2 processes each.
    +Machine 0's average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894
    +Machine 1's average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995
    +Machine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md b/assets/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md new file mode 100644 index 00000000..5fdf16c0 --- /dev/null +++ b/assets/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md @@ -0,0 +1,69 @@ +# [1662. Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent) + + + +## Description + +

    Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

    + +

    A string is represented by an array if the array elements concatenated in order forms the string.

    + +

     

    +

    Example 1:

    + +
    +Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
    +Output: true
    +Explanation:
    +word1 represents string "ab" + "c" -> "abc"
    +word2 represents string "a" + "bc" -> "abc"
    +The strings are the same, so return true.
    + +

    Example 2:

    + +
    +Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
    +Output: false
    +
    + +

    Example 3:

    + +
    +Input: word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word1.length, word2.length <= 103
    • +
    • 1 <= word1[i].length, word2[i].length <= 103
    • +
    • 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
    • +
    • word1[i] and word2[i] consist of lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md b/assets/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md new file mode 100644 index 00000000..70a9dc3c --- /dev/null +++ b/assets/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md @@ -0,0 +1,62 @@ +# [1663. Smallest String With A Given Numeric Value](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value) + + + +## Description + +

    The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.

    + +

    The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.

    + +

    You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.

    + +

    Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, k = 27
    +Output: "aay"
    +Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
    +
    + +

    Example 2:

    + +
    +Input: n = 5, k = 73
    +Output: "aaszz"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 105
    • +
    • n <= k <= 26 * n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1664.Ways to Make a Fair Array/README_EN.md b/assets/1600-1699/1664.Ways to Make a Fair Array/README_EN.md new file mode 100644 index 00000000..3cae9309 --- /dev/null +++ b/assets/1600-1699/1664.Ways to Make a Fair Array/README_EN.md @@ -0,0 +1,82 @@ +# [1664. Ways to Make a Fair Array](https://leetcode.com/problems/ways-to-make-a-fair-array) + + + +## Description + +

    You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.

    + +

    For example, if nums = [6,1,7,4,1]:

    + +
      +
    • Choosing to remove index 1 results in nums = [6,7,4,1].
    • +
    • Choosing to remove index 2 results in nums = [6,1,4,1].
    • +
    • Choosing to remove index 4 results in nums = [6,1,7,4].
    • +
    + +

    An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.

    + +

    Return the number of indices that you could choose such that after the removal, nums is fair.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,1,6,4]
    +Output: 1
    +Explanation:
    +Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
    +Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
    +Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
    +Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
    +There is 1 index that you can remove to make nums fair.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,1,1]
    +Output: 3
    +Explanation: You can remove any index and the remaining array is fair.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3]
    +Output: 0
    +Explanation: You cannot make a fair array after removing any index.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md b/assets/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md new file mode 100644 index 00000000..51ed570a --- /dev/null +++ b/assets/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md @@ -0,0 +1,92 @@ +# [1665. Minimum Initial Energy to Finish Tasks](https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks) + + + +## Description + +

    You are given an array tasks where tasks[i] = [actuali, minimumi]:

    + +
      +
    • actuali is the actual amount of energy you spend to finish the ith task.
    • +
    • minimumi is the minimum amount of energy you require to begin the ith task.
    • +
    + +

    For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.

    + +

    You can finish the tasks in any order you like.

    + +

    Return the minimum initial amount of energy you will need to finish all the tasks.

    + +

     

    +

    Example 1:

    + +
    +Input: tasks = [[1,2],[2,4],[4,8]]
    +Output: 8
    +Explanation:
    +Starting with 8 energy, we finish the tasks in the following order:
    +    - 3rd task. Now energy = 8 - 4 = 4.
    +    - 2nd task. Now energy = 4 - 2 = 2.
    +    - 1st task. Now energy = 2 - 1 = 1.
    +Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.
    + +

    Example 2:

    + +
    +Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]
    +Output: 32
    +Explanation:
    +Starting with 32 energy, we finish the tasks in the following order:
    +    - 1st task. Now energy = 32 - 1 = 31.
    +    - 2nd task. Now energy = 31 - 2 = 29.
    +    - 3rd task. Now energy = 29 - 10 = 19.
    +    - 4th task. Now energy = 19 - 10 = 9.
    +    - 5th task. Now energy = 9 - 8 = 1.
    + +

    Example 3:

    + +
    +Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]
    +Output: 27
    +Explanation:
    +Starting with 27 energy, we finish the tasks in the following order:
    +    - 5th task. Now energy = 27 - 5 = 22.
    +    - 2nd task. Now energy = 22 - 2 = 20.
    +    - 3rd task. Now energy = 20 - 3 = 17.
    +    - 1st task. Now energy = 17 - 1 = 16.
    +    - 4th task. Now energy = 16 - 4 = 12.
    +    - 6th task. Now energy = 12 - 6 = 6.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= tasks.length <= 105
    • +
    • 1 <= actual​i <= minimumi <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md b/assets/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md new file mode 100644 index 00000000..46cea8b4 --- /dev/null +++ b/assets/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md @@ -0,0 +1,68 @@ +# [1666. Change the Root of a Binary Tree](https://leetcode.com/problems/change-the-root-of-a-binary-tree) + + + +## Description + +

    Given the root of a binary tree and a leaf node, reroot the tree so that the leaf is the new root.

    + +

    You can reroot the tree with the following steps for each node cur on the path starting from the leaf up to the root​​​ excluding the root:

    + +
      +
    1. If cur has a left child, then that child becomes cur's right child.
    2. +
    3. cur's original parent becomes cur's left child. Note that in this process the original parent's pointer to cur becomes null, making it have at most one child.
    4. +
    + +

    Return the new root of the rerooted tree.

    + +

    Note: Ensure that your solution sets the Node.parent pointers correctly after rerooting or you will receive "Wrong Answer".

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 7
    +Output: [7,2,null,5,4,3,6,null,null,null,1,null,null,0,8]
    +
    + +

    Example 2:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 0
    +Output: [0,1,null,3,8,5,null,null,null,6,2,null,null,7,4]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [2, 100].
    • +
    • -109 <= Node.val <= 109
    • +
    • All Node.val are unique.
    • +
    • leaf exist in the tree.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1666.Change the Root of a Binary Tree/images/fliptree.png b/assets/1600-1699/1666.Change the Root of a Binary Tree/images/fliptree.png new file mode 100644 index 00000000..4c9ea468 Binary files /dev/null and b/assets/1600-1699/1666.Change the Root of a Binary Tree/images/fliptree.png differ diff --git a/assets/1600-1699/1667.Fix Names in a Table/README_EN.md b/assets/1600-1699/1667.Fix Names in a Table/README_EN.md new file mode 100644 index 00000000..65f596ea --- /dev/null +++ b/assets/1600-1699/1667.Fix Names in a Table/README_EN.md @@ -0,0 +1,59 @@ +# [1667. Fix Names in a Table](https://leetcode.com/problems/fix-names-in-a-table) + + + +## Description + +

    Table: Users

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| user_id        | int     |
    +| name           | varchar |
    ++----------------+---------+
    +user_id is the primary key for this table.
    +This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters.
    +
    + +

     

    + +

    Write an SQL query to fix the names so that only the first character is uppercase and the rest are lowercase.

    + +

    Return the result table ordered by user_id.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Users table:
    ++---------+-------+
    +| user_id | name  |
    ++---------+-------+
    +| 1       | aLice |
    +| 2       | bOB   |
    ++---------+-------+
    +
    +Result table:
    ++---------+-------+
    +| user_id | name  |
    ++---------+-------+
    +| 1       | Alice |
    +| 2       | Bob   |
    ++---------+-------+
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1668.Maximum Repeating Substring/README_EN.md b/assets/1600-1699/1668.Maximum Repeating Substring/README_EN.md new file mode 100644 index 00000000..3b74be7c --- /dev/null +++ b/assets/1600-1699/1668.Maximum Repeating Substring/README_EN.md @@ -0,0 +1,68 @@ +# [1668. Maximum Repeating Substring](https://leetcode.com/problems/maximum-repeating-substring) + + + +## Description + +

    For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.

    + +

    Given strings sequence and word, return the maximum k-repeating value of word in sequence.

    + +

     

    +

    Example 1:

    + +
    +Input: sequence = "ababc", word = "ab"
    +Output: 2
    +Explanation: "abab" is a substring in "ababc".
    +
    + +

    Example 2:

    + +
    +Input: sequence = "ababc", word = "ba"
    +Output: 1
    +Explanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".
    +
    + +

    Example 3:

    + +
    +Input: sequence = "ababc", word = "ac"
    +Output: 0
    +Explanation: "ac" is not a substring in "ababc". 
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= sequence.length <= 100
    • +
    • 1 <= word.length <= 100
    • +
    • sequence and word contains only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1669.Merge In Between Linked Lists/README_EN.md b/assets/1600-1699/1669.Merge In Between Linked Lists/README_EN.md new file mode 100644 index 00000000..22e24921 --- /dev/null +++ b/assets/1600-1699/1669.Merge In Between Linked Lists/README_EN.md @@ -0,0 +1,106 @@ +# [1669. Merge In Between Linked Lists](https://leetcode.com/problems/merge-in-between-linked-lists) + + + +## Description + +

    You are given two linked lists: list1 and list2 of sizes n and m respectively.

    + +

    Remove list1's nodes from the ath node to the bth node, and put list2 in their place.

    + +

    The blue edges and nodes in the following figure incidate the result:

    + +

    Build the result list and return its head.

    + +

     

    +

    Example 1:

    + +
    +Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
    +Output: [0,1,2,1000000,1000001,1000002,5]
    +Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
    +
    + +

    Example 2:

    + +
    +Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
    +Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
    +Explanation: The blue edges and nodes in the above figure indicate the result.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= list1.length <= 104
    • +
    • 1 <= a <= b < list1.length - 1
    • +
    • 1 <= list2.length <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: + p = q = list1 + for _ in range(a - 1): + p = p.next + for _ in range(b + 1): + q = q.next + p.next = list2 + while list2.next: + list2 = list2.next + list2.next = q + return list1 +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode p = list1; + for (int i = 0; i < a - 1; ++i) { + p = p.next; + } + ListNode q = list1; + for (int i = 0; i < b + 1; ++i) { + q = q.next; + } + p.next = list2; + while (list2.next != null) { + list2 = list2.next; + } + list2.next = q; + return list1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1669.Merge In Between Linked Lists/images/fig1.png b/assets/1600-1699/1669.Merge In Between Linked Lists/images/fig1.png new file mode 100644 index 00000000..5d982306 Binary files /dev/null and b/assets/1600-1699/1669.Merge In Between Linked Lists/images/fig1.png differ diff --git a/assets/1600-1699/1669.Merge In Between Linked Lists/images/merge_linked_list_ex1.png b/assets/1600-1699/1669.Merge In Between Linked Lists/images/merge_linked_list_ex1.png new file mode 100644 index 00000000..ed5ccfd9 Binary files /dev/null and b/assets/1600-1699/1669.Merge In Between Linked Lists/images/merge_linked_list_ex1.png differ diff --git a/assets/1600-1699/1669.Merge In Between Linked Lists/images/merge_linked_list_ex2.png b/assets/1600-1699/1669.Merge In Between Linked Lists/images/merge_linked_list_ex2.png new file mode 100644 index 00000000..bc0f7abb Binary files /dev/null and b/assets/1600-1699/1669.Merge In Between Linked Lists/images/merge_linked_list_ex2.png differ diff --git a/assets/1600-1699/1670.Design Front Middle Back Queue/README_EN.md b/assets/1600-1699/1670.Design Front Middle Back Queue/README_EN.md new file mode 100644 index 00000000..dc24a352 --- /dev/null +++ b/assets/1600-1699/1670.Design Front Middle Back Queue/README_EN.md @@ -0,0 +1,307 @@ +# [1670. Design Front Middle Back Queue](https://leetcode.com/problems/design-front-middle-back-queue) + + + +## Description + +

    Design a queue that supports push and pop operations in the front, middle, and back.

    + +

    Implement the FrontMiddleBack class:

    + +
      +
    • FrontMiddleBack() Initializes the queue.
    • +
    • void pushFront(int val) Adds val to the front of the queue.
    • +
    • void pushMiddle(int val) Adds val to the middle of the queue.
    • +
    • void pushBack(int val) Adds val to the back of the queue.
    • +
    • int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1.
    • +
    • int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1.
    • +
    • int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1.
    • +
    + +

    Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:

    + +
      +
    • Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5].
    • +
    • Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].
    • +
    + +

     

    +

    Example 1:

    + +
    +Input:
    +["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
    +[[], [1], [2], [3], [4], [], [], [], [], []]
    +Output:
    +[null, null, null, null, null, 1, 3, 4, 2, -1]
    +
    +Explanation:
    +FrontMiddleBackQueue q = new FrontMiddleBackQueue();
    +q.pushFront(1);   // [1]
    +q.pushBack(2);    // [1, 2]
    +q.pushMiddle(3);  // [1, 3, 2]
    +q.pushMiddle(4);  // [1, 4, 3, 2]
    +q.popFront();     // return 1 -> [4, 3, 2]
    +q.popMiddle();    // return 3 -> [4, 2]
    +q.popMiddle();    // return 4 -> [2]
    +q.popBack();      // return 2 -> []
    +q.popFront();     // return -1 -> [] (The queue is empty)
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= val <= 109
    • +
    • At most 1000 calls will be made to pushFrontpushMiddlepushBack, popFront, popMiddle, and popBack.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class FrontMiddleBackQueue: + + def __init__(self): + self.left = collections.deque() + self.right = collections.deque() + + def pushFront(self, val: int) -> None: + self.left.appendleft(val) + self.rebalance() + + def pushMiddle(self, val: int) -> None: + self.left.append(val) + self.rebalance() + + def pushBack(self, val: int) -> None: + self.right.append(val) + self.rebalance() + + def popFront(self) -> int: + if self.empty(): + return -1 + if self.left: + val = self.left.popleft() + else: + val = self.right.popleft() + self.rebalance() + return val + + def popMiddle(self) -> int: + if self.empty(): + return -1 + if len(self.left) >= len(self.right): + val = self.left.pop() + else: + val = self.right.popleft() + self.rebalance() + return val + + def popBack(self) -> int: + if self.empty(): + return -1 + val = self.right.pop() + self.rebalance() + return val + + def empty(self) -> bool: + return not self.left and not self.right + + def rebalance(self) -> None: + while len(self.left) > len(self.right): + self.right.appendleft(self.left.pop()) + while len(self.right) - len(self.left) > 1: + self.left.append(self.right.popleft()) + + +# Your FrontMiddleBackQueue object will be instantiated and called as such: +# obj = FrontMiddleBackQueue() +# obj.pushFront(val) +# obj.pushMiddle(val) +# obj.pushBack(val) +# param_4 = obj.popFront() +# param_5 = obj.popMiddle() +# param_6 = obj.popBack() +``` + +### **Java** + +```java +class FrontMiddleBackQueue { + private Deque left; + private Deque right; + + public FrontMiddleBackQueue() { + left = new LinkedList<>(); + right = new LinkedList<>(); + } + + public void pushFront(int val) { + left.offerFirst(val); + rebalance(); + } + + public void pushMiddle(int val) { + left.offerLast(val); + rebalance(); + } + + public void pushBack(int val) { + right.offerLast(val); + rebalance(); + } + + public int popFront() { + if (empty()) { + return -1; + } + int val = left.isEmpty() ? right.pollFirst() : left.pollFirst(); + rebalance(); + return val; + } + + public int popMiddle() { + if (empty()) { + return -1; + } + int val = left.size() >= right.size() ? left.pollLast() : right.pollFirst(); + rebalance(); + return val; + } + + public int popBack() { + if (empty()) { + return -1; + } + int val = right.pollLast(); + rebalance(); + return val; + } + + private boolean empty() { + return left.isEmpty() && right.isEmpty(); + } + + private void rebalance() { + while (left.size() > right.size()) { + right.offerFirst(left.pollLast()); + } + while (right.size() - left.size() > 1) { + left.offerLast(right.pollFirst()); + } + } +} + +/** + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * FrontMiddleBackQueue obj = new FrontMiddleBackQueue(); + * obj.pushFront(val); + * obj.pushMiddle(val); + * obj.pushBack(val); + * int param_4 = obj.popFront(); + * int param_5 = obj.popMiddle(); + * int param_6 = obj.popBack(); + */ +``` + +### **JavaScript** + +```js +var FrontMiddleBackQueue = function() { + this.left = []; + this.right = []; +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushFront = function(val) { + this.left.unshift(val); + this.rebalance(); +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushMiddle = function(val) { + this.left.push(val); + this.rebalance(); +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushBack = function(val) { + this.right.push(val); + this.rebalance(); +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popFront = function() { + if (this.isEmpty()) return -1; + let num = this.left.length == 0 ? this.right.shift() : this.left.shift(); + this.rebalance(); + return num; +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popMiddle = function() { + if (this.isEmpty()) return -1; + let num = this.left.length == this.right.length ? this.left.pop() : this.right.shift(); + this.rebalance(); + return num; +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popBack = function() { + if (this.isEmpty()) return -1; + let num = this.right.pop(); + this.rebalance(); + return num; +}; + +FrontMiddleBackQueue.prototype.rebalance = function () { + while (this.left.length > this.right.length) { + this.right.unshift(this.left.pop()); + } + while (this.right.length > this.left.length + 1) { + this.left.push(this.right.shift()); + } +} + +FrontMiddleBackQueue.prototype.isEmpty = function () { + return this.left.length == 0 && this.right.length == 0; +} + +/** + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * var obj = new FrontMiddleBackQueue() + * obj.pushFront(val) + * obj.pushMiddle(val) + * obj.pushBack(val) + * var param_4 = obj.popFront() + * var param_5 = obj.popMiddle() + * var param_6 = obj.popBack() + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md b/assets/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md new file mode 100644 index 00000000..25d5a652 --- /dev/null +++ b/assets/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md @@ -0,0 +1,84 @@ +# [1671. Minimum Number of Removals to Make Mountain Array](https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array) + + + +## Description + +

    You may recall that an array arr is a mountain array if and only if:

    + +
      +
    • arr.length >= 3
    • +
    • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: +
        +
      • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
      • +
      • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

    Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,3,1]
    +Output: 0
    +Explanation: The array itself is a mountain array so we do not need to remove any elements.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,1,1,5,6,2,3,1]
    +Output: 3
    +Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].
    +
    + +

    Example 3:

    + +
    +Input: nums = [4,3,2,1,1,2,3,1]
    +Output: 4
    +
    + +

    Example 4:

    + +
    +Input: nums = [1,2,3,4,4,3,2,1]
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 109
    • +
    • It is guaranteed that you can make a mountain array out of nums.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1672.Richest Customer Wealth/README_EN.md b/assets/1600-1699/1672.Richest Customer Wealth/README_EN.md new file mode 100644 index 00000000..89c81234 --- /dev/null +++ b/assets/1600-1699/1672.Richest Customer Wealth/README_EN.md @@ -0,0 +1,128 @@ +# [1672. Richest Customer Wealth](https://leetcode.com/problems/richest-customer-wealth) + + + +## Description + +

    You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.

    + +

    A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

    + +

     

    +

    Example 1:

    + +
    +Input: accounts = [[1,2,3],[3,2,1]]
    +Output: 6
    +Explanation:
    +1st customer has wealth = 1 + 2 + 3 = 6
    +2nd customer has wealth = 3 + 2 + 1 = 6
    +Both customers are considered the richest with a wealth of 6 each, so return 6.
    +
    + +

    Example 2:

    + +
    +Input: accounts = [[1,5],[7,3],[3,5]]
    +Output: 10
    +Explanation: 
    +1st customer has wealth = 6
    +2nd customer has wealth = 10 
    +3rd customer has wealth = 8
    +The 2nd customer is the richest with a wealth of 10.
    + +

    Example 3:

    + +
    +Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]
    +Output: 17
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == accounts.length
    • +
    • n == accounts[i].length
    • +
    • 1 <= m, n <= 50
    • +
    • 1 <= accounts[i][j] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maximumWealth(self, accounts: List[List[int]]) -> int: + res = 0 + for account in accounts: + res = max(res, sum(account)) + return res +``` + +### **Java** + +```java +class Solution { + public int maximumWealth(int[][] accounts) { + int res = 0; + for (int[] account : accounts) { + int t = 0; + for (int money : account) { + t += money; + } + res = Math.max(res, t); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maximumWealth(vector>& accounts) { + int res = 0; + for (auto& account : accounts) { + int t = 0; + for (auto& money : account) { + t += money; + } + res = max(res, t); + } + return res; + } +}; +``` + +### **Go** + +```go +func maximumWealth(accounts [][]int) int { + res := 0 + for _, account := range accounts { + t := 0 + for _, money := range account { + t += money + } + if t > res { + res = t + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md b/assets/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md new file mode 100644 index 00000000..d1383449 --- /dev/null +++ b/assets/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md @@ -0,0 +1,61 @@ +# [1673. Find the Most Competitive Subsequence](https://leetcode.com/problems/find-the-most-competitive-subsequence) + + + +## Description + +

    Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.

    + +

    An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.

    + +

    We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,5,2,6], k = 2
    +Output: [2,6]
    +Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,4,3,3,5,4,9,6], k = 4
    +Output: [2,3,3,4]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 0 <= nums[i] <= 109
    • +
    • 1 <= k <= nums.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md b/assets/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md new file mode 100644 index 00000000..bf53fdbe --- /dev/null +++ b/assets/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md @@ -0,0 +1,76 @@ +# [1674. Minimum Moves to Make Array Complementary](https://leetcode.com/problems/minimum-moves-to-make-array-complementary) + + + +## Description + +

    You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.

    + +

    The array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5.

    + +

    Return the minimum number of moves required to make nums complementary.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,4,3], limit = 4
    +Output: 1
    +Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).
    +nums[0] + nums[3] = 1 + 3 = 4.
    +nums[1] + nums[2] = 2 + 2 = 4.
    +nums[2] + nums[1] = 2 + 2 = 4.
    +nums[3] + nums[0] = 3 + 1 = 4.
    +Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,2,2,1], limit = 2
    +Output: 2
    +Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,1,2], limit = 2
    +Output: 0
    +Explanation: nums is already complementary.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 2 <= n <= 105
    • +
    • 1 <= nums[i] <= limit <= 105
    • +
    • n is even.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1675.Minimize Deviation in Array/README_EN.md b/assets/1600-1699/1675.Minimize Deviation in Array/README_EN.md new file mode 100644 index 00000000..87ca90b3 --- /dev/null +++ b/assets/1600-1699/1675.Minimize Deviation in Array/README_EN.md @@ -0,0 +1,85 @@ +# [1675. Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array) + + + +## Description + +

    You are given an array nums of n positive integers.

    + +

    You can perform two types of operations on any element of the array any number of times:

    + +
      +
    • If the element is even, divide it by 2. + +
        +
      • For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
      • +
      +
    • +
    • If the element is odd, multiply it by 2. +
        +
      • For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
      • +
      +
    • +
    + +

    The deviation of the array is the maximum difference between any two elements in the array.

    + +

    Return the minimum deviation the array can have after performing some number of operations.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4]
    +Output: 1
    +Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
    +
    + +

    Example 2:

    + +
    +Input: nums = [4,1,5,20,3]
    +Output: 3
    +Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
    +
    + +

    Example 3:

    + +
    +Input: nums = [2,10,8]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 2 <= n <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md b/assets/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md new file mode 100644 index 00000000..825ec7d2 --- /dev/null +++ b/assets/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md @@ -0,0 +1,79 @@ +# [1676. Lowest Common Ancestor of a Binary Tree IV](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv) + + + +## Description + +

    Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree's nodes are unique.

    + +

    Extending the definition of LCA on Wikipedia: "The lowest common ancestor of n nodes p1, p2, ..., pn in a binary tree T is the lowest node that has every pi as a descendant (where we allow a node to be a descendant of itself) for every valid i". A descendant of a node x is a node y that is on the path from node x to some leaf node.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
    +Output: 2
    +Explanation: The lowest common ancestor of nodes 4 and 7 is node 2.
    +
    + +

    Example 2:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1]
    +Output: 1
    +Explanation: The lowest common ancestor of a single node is the node itself.
    +
    +
    + +

    Example 3:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [7,6,2,4]
    +Output: 5
    +Explanation: The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5.
    +
    + +

    Example 4:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [0,1,2,3,4,5,6,7,8]
    +Output: 3
    +Explanation: The lowest common ancestor of all the nodes is the root node.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 104].
    • +
    • -109 <= Node.val <= 109
    • +
    • All Node.val are unique.
    • +
    • All nodes[i] will exist in the tree.
    • +
    • All nodes[i] are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/images/binarytree.png b/assets/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/images/binarytree.png new file mode 100644 index 00000000..2ad942c3 Binary files /dev/null and b/assets/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/images/binarytree.png differ diff --git a/assets/1600-1699/1677.Product's Worth Over Invoices/README_EN.md b/assets/1600-1699/1677.Product's Worth Over Invoices/README_EN.md new file mode 100644 index 00000000..8fa59684 --- /dev/null +++ b/assets/1600-1699/1677.Product's Worth Over Invoices/README_EN.md @@ -0,0 +1,100 @@ +# [1677. Product's Worth Over Invoices](https://leetcode.com/problems/products-worth-over-invoices) + + + +## Description + +

    Table: Product

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_id  | int     |
    +| name        | varchar |
    ++-------------+---------+
    +product_id is the primary key for this table.
    +This table contains the ID and the name of the product. The name consists of only lowercase English letters. No two products have the same name.
    +
    + +

     

    + +

    Table: Invoice

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| invoice_id  | int  |
    +| product_id  | int  |
    +| rest        | int  |
    +| paid        | int  |
    +| canceled    | int  |
    +| refunded    | int  |
    ++-------------+------+
    +invoice_id is the primary key for this table and the id of this invoice.
    +product_id is the id of the product for this invoice.
    +rest is the amount left to pay for this invoice.
    +paid is the amount paid for this invoice.
    +canceled is the amount canceled for this invoice.
    +refunded is the amount refunded for this invoice.
    +
    + +

     

    + +

    Write an SQL query that will, for all products, return each product name with total amount due, paid, canceled, and refunded across all invoices.

    + +

    Return the result table ordered by product_name.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Product table:
    ++------------+-------+
    +| product_id | name  |
    ++------------+-------+
    +| 0          | ham   |
    +| 1          | bacon |
    ++------------+-------+
    +Invoice table:
    ++------------+------------+------+------+----------+----------+
    +| invoice_id | product_id | rest | paid | canceled | refunded |
    ++------------+------------+------+------+----------+----------+
    +| 23         | 0          | 2    | 0    | 5        | 0        |
    +| 12         | 0          | 0    | 4    | 0        | 3        |
    +| 1          | 1          | 1    | 1    | 0        | 1        |
    +| 2          | 1          | 1    | 0    | 1        | 1        |
    +| 3          | 1          | 0    | 1    | 1        | 1        |
    +| 4          | 1          | 1    | 1    | 1        | 0        |
    ++------------+------------+------+------+----------+----------+
    +Result table:
    ++-------+------+------+----------+----------+
    +| name  | rest | paid | canceled | refunded |
    ++-------+------+------+----------+----------+
    +| bacon | 3    | 3    | 3        | 3        |
    +| ham   | 2    | 4    | 5        | 3        |
    ++-------+------+------+----------+----------+
    +- The amount of money left to pay for bacon is 1 + 1 + 0 + 1 = 3
    +- The amount of money paid for bacon is 1 + 0 + 1 + 1 = 3
    +- The amount of money canceled for bacon is 0 + 1 + 1 + 1 = 3
    +- The amount of money refunded for bacon is 1 + 1 + 1 + 0 = 3
    +- The amount of money left to pay for ham is 2 + 0 = 2
    +- The amount of money paid for ham is 0 + 4 = 4
    +- The amount of money canceled for ham is 5 + 0 = 5
    +- The amount of money refunded for ham is 0 + 3 = 3
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1678.Goal Parser Interpretation/README_EN.md b/assets/1600-1699/1678.Goal Parser Interpretation/README_EN.md new file mode 100644 index 00000000..ea0f67c8 --- /dev/null +++ b/assets/1600-1699/1678.Goal Parser Interpretation/README_EN.md @@ -0,0 +1,69 @@ +# [1678. Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation) + + + +## Description + +

    You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order.

    + +

    Given the string command, return the Goal Parser's interpretation of command.

    + +

     

    +

    Example 1:

    + +
    +Input: command = "G()(al)"
    +Output: "Goal"
    +Explanation: The Goal Parser interprets the command as follows:
    +G -> G
    +() -> o
    +(al) -> al
    +The final concatenated result is "Goal".
    +
    + +

    Example 2:

    + +
    +Input: command = "G()()()()(al)"
    +Output: "Gooooal"
    +
    + +

    Example 3:

    + +
    +Input: command = "(al)G(al)()()G"
    +Output: "alGalooG"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= command.length <= 100
    • +
    • command consists of "G", "()", and/or "(al)" in some order.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md b/assets/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md new file mode 100644 index 00000000..1ee14db7 --- /dev/null +++ b/assets/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md @@ -0,0 +1,65 @@ +# [1679. Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs) + + + +## Description + +

    You are given an integer array nums and an integer k.

    + +

    In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

    + +

    Return the maximum number of operations you can perform on the array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4], k = 5
    +Output: 2
    +Explanation: Starting with nums = [1,2,3,4]:
    +- Remove numbers 1 and 4, then nums = [2,3]
    +- Remove numbers 2 and 3, then nums = []
    +There are no more pairs that sum up to 5, hence a total of 2 operations.
    + +

    Example 2:

    + +
    +Input: nums = [3,1,3,4,3], k = 6
    +Output: 1
    +Explanation: Starting with nums = [3,1,3,4,3]:
    +- Remove the first two 3's, then nums = [1,4,3]
    +There are no more pairs that sum up to 6, hence a total of 1 operation.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • 1 <= k <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md b/assets/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md new file mode 100644 index 00000000..cf29793f --- /dev/null +++ b/assets/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md @@ -0,0 +1,67 @@ +# [1680. Concatenation of Consecutive Binary Numbers](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers) + + + +## Description + +

    Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 1
    +Explanation: "1" in binary corresponds to the decimal value 1. 
    +
    + +

    Example 2:

    + +
    +Input: n = 3
    +Output: 27
    +Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
    +After concatenating them, we have "11011", which corresponds to the decimal value 27.
    +
    + +

    Example 3:

    + +
    +Input: n = 12
    +Output: 505379714
    +Explanation: The concatenation results in "1101110010111011110001001101010111100".
    +The decimal value of that is 118505380540.
    +After modulo 109 + 7, the result is 505379714.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1681.Minimum Incompatibility/README_EN.md b/assets/1600-1699/1681.Minimum Incompatibility/README_EN.md new file mode 100644 index 00000000..e26f9dee --- /dev/null +++ b/assets/1600-1699/1681.Minimum Incompatibility/README_EN.md @@ -0,0 +1,74 @@ +# [1681. Minimum Incompatibility](https://leetcode.com/problems/minimum-incompatibility) + + + +## Description + +

    You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.

    + +

    A subset's incompatibility is the difference between the maximum and minimum elements in that array.

    + +

    Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.

    + +

    A subset is a group integers that appear in the array with no particular order.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,1,4], k = 2
    +Output: 4
    +Explanation: The optimal distribution of subsets is [1,2] and [1,4].
    +The incompatibility is (2-1) + (4-1) = 4.
    +Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
    + +

    Example 2:

    + +
    +Input: nums = [6,3,8,1,3,1,2,2], k = 4
    +Output: 6
    +Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].
    +The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
    +
    + +

    Example 3:

    + +
    +Input: nums = [5,3,3,6,3,3], k = 3
    +Output: -1
    +Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= nums.length <= 16
    • +
    • nums.length is divisible by k
    • +
    • 1 <= nums[i] <= nums.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md b/assets/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md new file mode 100644 index 00000000..f90ce47d --- /dev/null +++ b/assets/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md @@ -0,0 +1,95 @@ +# [1682. Longest Palindromic Subsequence II](https://leetcode.com/problems/longest-palindromic-subsequence-ii) + + + +## Description + +

    A subsequence of a string s is considered a good palindromic subsequence if:

    + + + +
      +
    • It is a subsequence of s.
    • +
    • It is a palindrome (has the same value if reversed).
    • +
    • It has an even length.
    • +
    • No two consecutive characters are equal, except the two middle ones.
    • +
    + + + +

    For example, if s = "abcabcabb", then "abba" is considered a good palindromic subsequence, while "bcb" (not even length) and "bbbb" (has equal consecutive characters) are not.

    + + + +

    Given a string s, return the length of the longest good palindromic subsequence in s.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "bbabab"
    +
    +Output: 4
    +
    +Explanation: The longest good palindromic subsequence of s is "baab".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "dcbccacdb"
    +
    +Output: 4
    +
    +Explanation: The longest good palindromic subsequence of s is "dccd".
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 250
    • +
    • s consists of lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1683.Invalid Tweets/README_EN.md b/assets/1600-1699/1683.Invalid Tweets/README_EN.md new file mode 100644 index 00000000..7a581587 --- /dev/null +++ b/assets/1600-1699/1683.Invalid Tweets/README_EN.md @@ -0,0 +1,66 @@ +# [1683. Invalid Tweets](https://leetcode.com/problems/invalid-tweets) + + + +## Description + +

    Table: Tweets

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| tweet_id       | int     |
    +| content        | varchar |
    ++----------------+---------+
    +tweet_id is the primary key for this table.
    +This table contains all the tweets in a social media app.
    +
    + +

     

    + +

    Write an SQL query to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Tweets table:
    ++----------+----------------------------------+
    +| tweet_id | content                          |
    ++----------+----------------------------------+
    +| 1        | Vote for Biden                   |
    +| 2        | Let us make America great again! |
    ++----------+----------------------------------+
    +
    +Result table:
    ++----------+
    +| tweet_id |
    ++----------+
    +| 2        |
    ++----------+
    +Tweet 1 has length = 14. It is a valid tweet.
    +Tweet 2 has length = 32. It is an invalid tweet.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + tweet_id +FROM + Tweets +WHERE + CHAR_LENGTH(content) > 15; +``` + + diff --git a/assets/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md b/assets/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md new file mode 100644 index 00000000..aafef3c1 --- /dev/null +++ b/assets/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md @@ -0,0 +1,70 @@ +# [1684. Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings) + + + +## Description + +

    You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.

    + +

    Return the number of consistent strings in the array words.

    + +

     

    +

    Example 1:

    + +
    +Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
    +Output: 2
    +Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
    +
    + +

    Example 2:

    + +
    +Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
    +Output: 7
    +Explanation: All strings are consistent.
    +
    + +

    Example 3:

    + +
    +Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
    +Output: 4
    +Explanation: Strings "cc", "acd", "ac", and "d" are consistent.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 104
    • +
    • 1 <= allowed.length <= 26
    • +
    • 1 <= words[i].length <= 10
    • +
    • The characters in allowed are distinct.
    • +
    • words[i] and allowed contain only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md b/assets/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md new file mode 100644 index 00000000..7176033b --- /dev/null +++ b/assets/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md @@ -0,0 +1,63 @@ +# [1685. Sum of Absolute Differences in a Sorted Array](https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array) + + + +## Description + +

    You are given an integer array nums sorted in non-decreasing order.

    + +

    Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.

    + +

    In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,3,5]
    +Output: [4,3,5]
    +Explanation: Assuming the arrays are 0-indexed, then
    +result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
    +result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
    +result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,4,6,8,10]
    +Output: [24,15,13,15,21]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= nums[i + 1] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1686.Stone Game VI/README_EN.md b/assets/1600-1699/1686.Stone Game VI/README_EN.md new file mode 100644 index 00000000..96e84994 --- /dev/null +++ b/assets/1600-1699/1686.Stone Game VI/README_EN.md @@ -0,0 +1,88 @@ +# [1686. Stone Game VI](https://leetcode.com/problems/stone-game-vi) + + + +## Description + +

    Alice and Bob take turns playing a game, with Alice starting first.

    + +

    There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.

    + +

    You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.

    + +

    The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.

    + +

    Determine the result of the game, and:

    + +
      +
    • If Alice wins, return 1.
    • +
    • If Bob wins, return -1.
    • +
    • If the game results in a draw, return 0.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: aliceValues = [1,3], bobValues = [2,1]
    +Output: 1
    +Explanation:
    +If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.
    +Bob can only choose stone 0, and will only receive 2 points.
    +Alice wins.
    +
    + +

    Example 2:

    + +
    +Input: aliceValues = [1,2], bobValues = [3,1]
    +Output: 0
    +Explanation:
    +If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.
    +Draw.
    +
    + +

    Example 3:

    + +
    +Input: aliceValues = [2,4,3], bobValues = [1,6,7]
    +Output: -1
    +Explanation:
    +Regardless of how Alice plays, Bob will be able to have more points than Alice.
    +For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.
    +Bob wins.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == aliceValues.length == bobValues.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= aliceValues[i], bobValues[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md b/assets/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md new file mode 100644 index 00000000..741ce123 --- /dev/null +++ b/assets/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md @@ -0,0 +1,113 @@ +# [1687. Delivering Boxes from Storage to Ports](https://leetcode.com/problems/delivering-boxes-from-storage-to-ports) + + + +## Description + +

    You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.

    + +

    You are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight.

    + +
      +
    • ports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box.
    • +
    • portsCount is the number of ports.
    • +
    • maxBoxes and maxWeight are the respective box and weight limits of the ship.
    • +
    + +

    The boxes need to be delivered in the order they are given. The ship will follow these steps:

    + +
      +
    • The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.
    • +
    • For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.
    • +
    • The ship then makes a return trip to storage to take more boxes from the queue.
    • +
    + +

    The ship must end at storage after all the boxes have been delivered.

    + +

    Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.

    + +

     

    +

    Example 1:

    + +
    +Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
    +Output: 4
    +Explanation: The optimal strategy is as follows: 
    +- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
    +So the total number of trips is 4.
    +Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).
    +
    + +

    Example 2:

    + +
    +Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
    +Output: 6
    +Explanation: The optimal strategy is as follows: 
    +- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.
    +- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.
    +- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.
    +So the total number of trips is 2 + 2 + 2 = 6.
    +
    + +

    Example 3:

    + +
    +Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7
    +Output: 6
    +Explanation: The optimal strategy is as follows:
    +- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
    +- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
    +- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
    +So the total number of trips is 2 + 2 + 2 = 6.
    +
    + +

    Example 4:

    + +
    +Input: boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], portsCount = 5, maxBoxes = 5, maxWeight = 7
    +Output: 14
    +Explanation: The optimal strategy is as follows:
    +- The ship takes the first box, goes to port 2, then storage. 2 trips.
    +- The ship takes the second box, goes to port 2, then storage. 2 trips.
    +- The ship takes the third and fourth boxes, goes to port 3, then storage. 2 trips.
    +- The ship takes the fifth box, goes to port 3, then storage. 2 trips.
    +- The ship takes the sixth and seventh boxes, goes to port 3, then port 4, then storage. 3 trips. 
    +- The ship takes the eighth and ninth boxes, goes to port 1, then port 5, then storage. 3 trips.
    +So the total number of trips is 2 + 2 + 2 + 2 + 3 + 3 = 14.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= boxes.length <= 105
    • +
    • 1 <= portsCount, maxBoxes, maxWeight <= 105
    • +
    • 1 <= ports​​i <= portsCount
    • +
    • 1 <= weightsi <= maxWeight
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1688.Count of Matches in Tournament/README_EN.md b/assets/1600-1699/1688.Count of Matches in Tournament/README_EN.md new file mode 100644 index 00000000..5b8363ea --- /dev/null +++ b/assets/1600-1699/1688.Count of Matches in Tournament/README_EN.md @@ -0,0 +1,72 @@ +# [1688. Count of Matches in Tournament](https://leetcode.com/problems/count-of-matches-in-tournament) + + + +## Description + +

    You are given an integer n, the number of teams in a tournament that has strange rules:

    + +
      +
    • If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
    • +
    • If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.
    • +
    + +

    Return the number of matches played in the tournament until a winner is decided.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 7
    +Output: 6
    +Explanation: Details of the tournament: 
    +- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
    +- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
    +- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
    +Total number of matches = 3 + 2 + 1 = 6.
    +
    + +

    Example 2:

    + +
    +Input: n = 14
    +Output: 13
    +Explanation: Details of the tournament:
    +- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
    +- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
    +- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
    +- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
    +Total number of matches = 7 + 3 + 2 + 1 = 13.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 200
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md b/assets/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md new file mode 100644 index 00000000..cfcac4ee --- /dev/null +++ b/assets/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md @@ -0,0 +1,127 @@ +# [1689. Partitioning Into Minimum Number Of Deci-Binary Numbers](https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers) + + + +## Description + +

    A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.

    + +

    Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: n = "32"
    +
    +Output: 3
    +
    +Explanation: 10 + 11 + 11 = 32
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: n = "82734"
    +
    +Output: 8
    +
    +
    + +

    Example 3:

    + +
    +
    +Input: n = "27346209830709182346"
    +
    +Output: 9
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 1 <= n.length <= 105
    • +
    • n consists of only digits.
    • +
    • n does not contain any leading zeros and represents a positive integer.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minPartitions(self, n: str) -> int: + return int(max(n)) +``` + +### **Java** + +```java +class Solution { + public int minPartitions(String n) { + int res = 0; + for (char c : n.toCharArray()) { + res = Math.max(res, c - '0'); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function minPartitions(n: string): number { + let nums = n.split('').map(d => parseInt(d)); + let ans = Math.max(...nums); + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int minPartitions(string n) { + int res = 0; + for (auto& c : n) { + res = max(res, c - '0'); + } + return res; + } +}; +``` + +### **Go** + +```go +func minPartitions(n string) int { + res := 0 + for _, c := range n { + t := int(c - '0') + if t > res { + res = t + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1690.Stone Game VII/README_EN.md b/assets/1600-1699/1690.Stone Game VII/README_EN.md new file mode 100644 index 00000000..dbb16960 --- /dev/null +++ b/assets/1600-1699/1690.Stone Game VII/README_EN.md @@ -0,0 +1,68 @@ +# [1690. Stone Game VII](https://leetcode.com/problems/stone-game-vii) + + + +## Description + +

    Alice and Bob take turns playing a game, with Alice starting first.

    + +

    There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.

    + +

    Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.

    + +

    Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.

    + +

     

    +

    Example 1:

    + +
    +Input: stones = [5,3,1,4,2]
    +Output: 6
    +Explanation: 
    +- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].
    +- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].
    +- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].
    +- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].
    +- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].
    +The score difference is 18 - 12 = 6.
    +
    + +

    Example 2:

    + +
    +Input: stones = [7,90,5,1,100,10,10,2]
    +Output: 122
    + +

     

    +

    Constraints:

    + +
      +
    • n == stones.length
    • +
    • 2 <= n <= 1000
    • +
    • 1 <= stones[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md b/assets/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md new file mode 100644 index 00000000..643e0114 --- /dev/null +++ b/assets/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md @@ -0,0 +1,81 @@ +# [1691. Maximum Height by Stacking Cuboids](https://leetcode.com/problems/maximum-height-by-stacking-cuboids) + + + +## Description + +

    Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other.

    + +

    You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.

    + +

    Return the maximum height of the stacked cuboids.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]
    +Output: 190
    +Explanation:
    +Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.
    +Cuboid 0 is placed next with the 45x20 side facing down with height 50.
    +Cuboid 2 is placed next with the 23x12 side facing down with height 45.
    +The total height is 95 + 50 + 45 = 190.
    +
    + +

    Example 2:

    + +
    +Input: cuboids = [[38,25,45],[76,35,3]]
    +Output: 76
    +Explanation:
    +You can't place any of the cuboids on the other.
    +We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.
    +
    + +

    Example 3:

    + +
    +Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
    +Output: 102
    +Explanation:
    +After rearranging the cuboids, you can see that all cuboids have the same dimension.
    +You can place the 11x7 side down on all cuboids so their heights are 17.
    +The maximum height of stacked cuboids is 6 * 17 = 102.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == cuboids.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= widthi, lengthi, heighti <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1691.Maximum Height by Stacking Cuboids/images/image.jpg b/assets/1600-1699/1691.Maximum Height by Stacking Cuboids/images/image.jpg new file mode 100644 index 00000000..31f8bf9c Binary files /dev/null and b/assets/1600-1699/1691.Maximum Height by Stacking Cuboids/images/image.jpg differ diff --git a/assets/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md b/assets/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md new file mode 100644 index 00000000..027e1666 --- /dev/null +++ b/assets/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md @@ -0,0 +1,82 @@ +# [1692. Count Ways to Distribute Candies](https://leetcode.com/problems/count-ways-to-distribute-candies) + + + +## Description + +

    There are n unique candies (labeled 1 through n) and k bags. You are asked to distribute all the candies into the bags such that every bag has at least one candy.

    + +

    There can be multiple ways to distribute the candies. Two ways are considered different if the candies in one bag in the first way are not all in the same bag in the second way. The order of the bags and the order of the candies within each bag do not matter.

    + +

    For example, (1), (2,3) and (2), (1,3) are considered different because candies 2 and 3 in the bag (2,3) in the first way are not in the same bag in the second way (they are split between the bags (2) and (1,3)). However, (1), (2,3) and (3,2), (1) are considered the same because the candies in each bag are all in the same bags in both ways.

    + +

    Given two integers, n and k, return the number of different ways to distribute the candies. As the answer may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 3, k = 2
    +Output: 3
    +Explanation: You can distribute 3 candies into 2 bags in 3 ways:
    +(1), (2,3)
    +(1,2), (3)
    +(1,3), (2)
    +
    + +

    Example 2:

    + +
    +Input: n = 4, k = 2
    +Output: 7
    +Explanation: You can distribute 4 candies into 2 bags in 7 ways:
    +(1), (2,3,4)
    +(1,2), (3,4)
    +(1,3), (2,4)
    +(1,4), (2,3)
    +(1,2,3), (4)
    +(1,2,4), (3)
    +(1,3,4), (2)
    +
    + +

    Example 3:

    + +
    +Input: n = 20, k = 5
    +Output: 206085257
    +Explanation: You can distribute 20 candies into 5 bags in 1881780996 ways. 1881780996 modulo 109 + 7 = 206085257.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= n <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1692.Count Ways to Distribute Candies/images/candies-1.png b/assets/1600-1699/1692.Count Ways to Distribute Candies/images/candies-1.png new file mode 100644 index 00000000..0f0d320f Binary files /dev/null and b/assets/1600-1699/1692.Count Ways to Distribute Candies/images/candies-1.png differ diff --git a/assets/1600-1699/1693.Daily Leads and Partners/README_EN.md b/assets/1600-1699/1693.Daily Leads and Partners/README_EN.md new file mode 100644 index 00000000..66bde771 --- /dev/null +++ b/assets/1600-1699/1693.Daily Leads and Partners/README_EN.md @@ -0,0 +1,73 @@ +# [1693. Daily Leads and Partners](https://leetcode.com/problems/daily-leads-and-partners) + + + +## Description + +

    Table: DailySales

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| date_id     | date    |
    +| make_name   | varchar |
    +| lead_id     | int     |
    +| partner_id  | int     |
    ++-------------+---------+
    +This table does not have a primary key.
    +This table contains the date and the name of the product sold and the IDs of the lead and partner it was sold to.
    +The name consists of only lowercase English letters.
    +
    + +

     

    + +

    Write an SQL query that will, for each date_id and make_name, return the number of distinct lead_id's and distinct partner_id's.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +DailySales table:
    ++-----------+-----------+---------+------------+
    +| date_id   | make_name | lead_id | partner_id |
    ++-----------+-----------+---------+------------+
    +| 2020-12-8 | toyota    | 0       | 1          |
    +| 2020-12-8 | toyota    | 1       | 0          |
    +| 2020-12-8 | toyota    | 1       | 2          |
    +| 2020-12-7 | toyota    | 0       | 2          |
    +| 2020-12-7 | toyota    | 0       | 1          |
    +| 2020-12-8 | honda     | 1       | 2          |
    +| 2020-12-8 | honda     | 2       | 1          |
    +| 2020-12-7 | honda     | 0       | 1          |
    +| 2020-12-7 | honda     | 1       | 2          |
    +| 2020-12-7 | honda     | 2       | 1          |
    ++-----------+-----------+---------+------------+
    +Result table:
    ++-----------+-----------+--------------+-----------------+
    +| date_id   | make_name | unique_leads | unique_partners |
    ++-----------+-----------+--------------+-----------------+
    +| 2020-12-8 | toyota    | 2            | 3               |
    +| 2020-12-7 | toyota    | 1            | 2               |
    +| 2020-12-8 | honda     | 2            | 2               |
    +| 2020-12-7 | honda     | 3            | 2               |
    ++-----------+-----------+--------------+-----------------+
    +For 2020-12-8, toyota gets leads = [0, 1] and partners = [0, 1, 2] while honda gets leads = [1, 2] and partners = [1, 2].
    +For 2020-12-7, toyota gets leads = [0] and partners = [1, 2] while honda gets leads = [0, 1, 2] and partners = [1, 2].
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1600-1699/1694.Reformat Phone Number/README_EN.md b/assets/1600-1699/1694.Reformat Phone Number/README_EN.md new file mode 100644 index 00000000..262a3e65 --- /dev/null +++ b/assets/1600-1699/1694.Reformat Phone Number/README_EN.md @@ -0,0 +1,102 @@ +# [1694. Reformat Phone Number](https://leetcode.com/problems/reformat-phone-number) + + + +## Description + +

    You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.

    + +

    You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:

    + +
      +
    • 2 digits: A single block of length 2.
    • +
    • 3 digits: A single block of length 3.
    • +
    • 4 digits: Two blocks of length 2 each.
    • +
    + +

    The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.

    + +

    Return the phone number after formatting.

    + +

     

    +

    Example 1:

    + +
    +Input: number = "1-23-45 6"
    +Output: "123-456"
    +Explanation: The digits are "123456".
    +Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
    +Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456".
    +Joining the blocks gives "123-456".
    +
    + +

    Example 2:

    + +
    +Input: number = "123 4-567"
    +Output: "123-45-67"
    +Explanation: The digits are "1234567".
    +Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".
    +Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67".
    +Joining the blocks gives "123-45-67".
    +
    + +

    Example 3:

    + +
    +Input: number = "123 4-5678"
    +Output: "123-456-78"
    +Explanation: The digits are "12345678".
    +Step 1: The 1st block is "123".
    +Step 2: The 2nd block is "456".
    +Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78".
    +Joining the blocks gives "123-456-78".
    +
    + +

    Example 4:

    + +
    +Input: number = "12"
    +Output: "12"
    +
    + +

    Example 5:

    + +
    +Input: number = "--17-5 229 35-39475 "
    +Output: "175-229-353-94-75"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= number.length <= 100
    • +
    • number consists of digits and the characters '-' and ' '.
    • +
    • There are at least two digits in number.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1695.Maximum Erasure Value/README_EN.md b/assets/1600-1699/1695.Maximum Erasure Value/README_EN.md new file mode 100644 index 00000000..f7109b57 --- /dev/null +++ b/assets/1600-1699/1695.Maximum Erasure Value/README_EN.md @@ -0,0 +1,61 @@ +# [1695. Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value) + + + +## Description + +

    You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.

    + +

    Return the maximum score you can get by erasing exactly one subarray.

    + +

    An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [4,2,4,5,6]
    +Output: 17
    +Explanation: The optimal subarray here is [2,4,5,6].
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,2,1,2,5,2,1,2,5]
    +Output: 8
    +Explanation: The optimal subarray here is [5,2,1] or [1,2,5].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1696.Jump Game VI/README_EN.md b/assets/1600-1699/1696.Jump Game VI/README_EN.md new file mode 100644 index 00000000..45415c36 --- /dev/null +++ b/assets/1600-1699/1696.Jump Game VI/README_EN.md @@ -0,0 +1,70 @@ +# [1696. Jump Game VI](https://leetcode.com/problems/jump-game-vi) + + + +## Description + +

    You are given a 0-indexed integer array nums and an integer k.

    + +

    You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.

    + +

    You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.

    + +

    Return the maximum score you can get.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,-1,-2,4,-7,3], k = 2
    +Output: 7
    +Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
    +
    + +

    Example 2:

    + +
    +Input: nums = [10,-5,-2,4,0,3], k = 3
    +Output: 17
    +Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    •  1 <= nums.length, k <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md b/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md new file mode 100644 index 00000000..eef6594f --- /dev/null +++ b/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md @@ -0,0 +1,70 @@ +# [1697. Checking Existence of Edge Length Limited Paths](https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths) + + + +## Description + +

    An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes.

    + +

    Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj .

    + +

    Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]
    +Output: [false,true]
    +Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
    +For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
    +For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
    +
    + +

    Example 2:

    + +
    +Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]
    +Output: [true,false]
    +Exaplanation: The above figure shows the given graph.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 105
    • +
    • 1 <= edgeList.length, queries.length <= 105
    • +
    • edgeList[i].length == 3
    • +
    • queries[j].length == 3
    • +
    • 0 <= ui, vi, pj, qj <= n - 1
    • +
    • ui != vi
    • +
    • pj != qj
    • +
    • 1 <= disi, limitj <= 109
    • +
    • There may be multiple edges between two nodes.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/images/h.png b/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/images/h.png new file mode 100644 index 00000000..d6aafa8a Binary files /dev/null and b/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/images/h.png differ diff --git a/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/images/q.png b/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/images/q.png new file mode 100644 index 00000000..c3aa8a9f Binary files /dev/null and b/assets/1600-1699/1697.Checking Existence of Edge Length Limited Paths/images/q.png differ diff --git a/assets/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md b/assets/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md new file mode 100644 index 00000000..99795982 --- /dev/null +++ b/assets/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md @@ -0,0 +1,60 @@ +# [1698. Number of Distinct Substrings in a String](https://leetcode.com/problems/number-of-distinct-substrings-in-a-string) + + + +## Description + +

    Given a string s, return the number of distinct substrings of s.

    + +

    A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aabbaba"
    +Output: 21
    +Explanation: The set of distinct strings is ["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"]
    +
    + +

    Example 2:

    + +
    +Input: s = "abcdefg"
    +Output: 28
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s consists of lowercase English letters.
    • +
    + +

     

    +Follow up: Can you solve this problem in O(n) time complexity? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md b/assets/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md new file mode 100644 index 00000000..4ea2dba1 --- /dev/null +++ b/assets/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md @@ -0,0 +1,70 @@ +# [1699. Number of Calls Between Two Persons](https://leetcode.com/problems/number-of-calls-between-two-persons) + + + +## Description + +

    Table: Calls

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| from_id     | int     |
    +| to_id       | int     |
    +| duration    | int     |
    ++-------------+---------+
    +This table does not have a primary key, it may contain duplicates.
    +This table contains the duration of a phone call between from_id and to_id.
    +from_id != to_id
    +
    + +

     

    + +

    Write an SQL query to report the number of calls and the total call duration between each pair of distinct persons (person1, person2) where person1 < person2.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Calls table:
    ++---------+-------+----------+
    +| from_id | to_id | duration |
    ++---------+-------+----------+
    +| 1       | 2     | 59       |
    +| 2       | 1     | 11       |
    +| 1       | 3     | 20       |
    +| 3       | 4     | 100      |
    +| 3       | 4     | 200      |
    +| 3       | 4     | 200      |
    +| 4       | 3     | 499      |
    ++---------+-------+----------+
    +
    +Result table:
    ++---------+---------+------------+----------------+
    +| person1 | person2 | call_count | total_duration |
    ++---------+---------+------------+----------------+
    +| 1       | 2       | 2          | 70             |
    +| 1       | 3       | 1          | 20             |
    +| 3       | 4       | 4          | 999            |
    ++---------+---------+------------+----------------+
    +Users 1 and 2 had 2 calls and the total duration is 70 (59 + 11).
    +Users 1 and 3 had 1 call and the total duration is 20.
    +Users 3 and 4 had 4 calls and the total duration is 999 (100 + 200 + 200 + 499).
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md b/assets/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md new file mode 100644 index 00000000..46dec0fa --- /dev/null +++ b/assets/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md @@ -0,0 +1,98 @@ +# [1700. Number of Students Unable to Eat Lunch](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch) + + + +## Description + +

    The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.

    + +

    The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:

    + +
      +
    • If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.
    • +
    • Otherwise, they will leave it and go to the queue's end.
    • +
    + +

    This continues until none of the queue students want to take the top sandwich and are thus unable to eat.

    + +

    You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.

    + +

     

    +

    Example 1:

    + +
    +Input: students = [1,1,0,0], sandwiches = [0,1,0,1]
    +Output: 0 
    +Explanation:
    +- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
    +- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
    +- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
    +- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
    +- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
    +- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
    +- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
    +- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
    +Hence all students are able to eat.
    +
    + +

    Example 2:

    + +
    +Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= students.length, sandwiches.length <= 100
    • +
    • students.length == sandwiches.length
    • +
    • sandwiches[i] is 0 or 1.
    • +
    • students[i] is 0 or 1.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countStudents(self, students: List[int], sandwiches: List[int]) -> int: + counter = collections.Counter(students) + for i, sandwich in enumerate(sandwiches): + if counter[sandwich] == 0: + return len(students) - i + counter[sandwich] -= 1 + return 0 +``` + +### **Java** + +```java +class Solution { + public int countStudents(int[] students, int[] sandwiches) { + int[] counter = new int[2]; + for (int i : students) { + counter[i] += 1; + } + for (int i = 0; i < sandwiches.length; ++i) { + if (counter[sandwiches[i]] == 0) { + return sandwiches.length - i; + } + counter[sandwiches[i]] -= 1; + } + return 0; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1701.Average Waiting Time/README_EN.md b/assets/1700-1799/1701.Average Waiting Time/README_EN.md new file mode 100644 index 00000000..0b70ae23 --- /dev/null +++ b/assets/1700-1799/1701.Average Waiting Time/README_EN.md @@ -0,0 +1,91 @@ +# [1701. Average Waiting Time](https://leetcode.com/problems/average-waiting-time) + + + +## Description + +

    There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:

    + +
      +
    • arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order.
    • +
    • timei is the time needed to prepare the order of the ith customer.
    • +
    + +

    When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.

    + +

    Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.

    + +

     

    +

    Example 1:

    + +
    +Input: customers = [[1,2],[2,5],[4,3]]
    +Output: 5.00000
    +Explanation:
    +1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.
    +2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.
    +3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.
    +So the average waiting time = (2 + 6 + 7) / 3 = 5.
    +
    + +

    Example 2:

    + +
    +Input: customers = [[5,2],[5,4],[10,3],[20,1]]
    +Output: 3.25000
    +Explanation:
    +1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.
    +2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.
    +3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.
    +4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.
    +So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= customers.length <= 105
    • +
    • 1 <= arrivali, timei <= 104
    • +
    • arrival<= arrivali+1
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def averageWaitingTime(self, customers: List[List[int]]) -> float: + f = total_waiting_time = 0 + for arrival, time in customers: + f = max(arrival, f) + time + total_waiting_time += (f - arrival) + return total_waiting_time / len(customers) +``` + +### **Java** + +```java +class Solution { + public double averageWaitingTime(int[][] customers) { + int f = 0; + double totalWaitingTime = 0; + for (int[] customer : customers) { + f = Math.max(f, customer[0]) + customer[1]; + totalWaitingTime += (f - customer[0]); + } + return totalWaitingTime / customers.length; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1702.Maximum Binary String After Change/README_EN.md b/assets/1700-1799/1702.Maximum Binary String After Change/README_EN.md new file mode 100644 index 00000000..ebbf6c69 --- /dev/null +++ b/assets/1700-1799/1702.Maximum Binary String After Change/README_EN.md @@ -0,0 +1,78 @@ +# [1702. Maximum Binary String After Change](https://leetcode.com/problems/maximum-binary-string-after-change) + + + +## Description + +

    You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:

    + +
      +
    • Operation 1: If the number contains the substring "00", you can replace it with "10". + +
        +
      • For example, "00010" -> "10010"
      • +
      +
    • +
    • Operation 2: If the number contains the substring "10", you can replace it with "01". +
        +
      • For example, "00010" -> "00001"
      • +
      +
    • +
    + +

    Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.

    + +

     

    +

    Example 1:

    + +
    +Input: binary = "000110"
    +Output: "111011"
    +Explanation: A valid transformation sequence can be:
    +"000110" -> "000101" 
    +"000101" -> "100101" 
    +"100101" -> "110101" 
    +"110101" -> "110011" 
    +"110011" -> "111011"
    +
    + +

    Example 2:

    + +
    +Input: binary = "01"
    +Output: "01"
    +Explanation: "01" cannot be transformed any further.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= binary.length <= 105
    • +
    • binary consist of '0' and '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md b/assets/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md new file mode 100644 index 00000000..6f7b4050 --- /dev/null +++ b/assets/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md @@ -0,0 +1,68 @@ +# [1703. Minimum Adjacent Swaps for K Consecutive Ones](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones) + + + +## Description + +

    You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values.

    + +

    Return the minimum number of moves required so that nums has k consecutive 1's.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,0,0,1,0,1], k = 2
    +Output: 1
    +Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,0,0,0,0,0,1,1], k = 3
    +Output: 5
    +Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,1,0,1], k = 2
    +Output: 0
    +Explanation: nums already has 2 consecutive 1's.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • nums[i] is 0 or 1.
    • +
    • 1 <= k <= sum(nums)
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md b/assets/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md new file mode 100644 index 00000000..902ba114 --- /dev/null +++ b/assets/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md @@ -0,0 +1,98 @@ +# [1704. Determine if String Halves Are Alike](https://leetcode.com/problems/determine-if-string-halves-are-alike) + + + +## Description + +

    You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

    + +

    Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

    + +

    Return true if a and b are alike. Otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "book"
    +Output: true
    +Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
    +
    + +

    Example 2:

    + +
    +Input: s = "textbook"
    +Output: false
    +Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
    +Notice that the vowel o is counted twice.
    +
    + +

    Example 3:

    + +
    +Input: s = "MerryChristmas"
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: s = "AbCdEfGh"
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= s.length <= 1000
    • +
    • s.length is even.
    • +
    • s consists of uppercase and lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def halvesAreAlike(self, s: str) -> bool: + half = len(s) >> 1 + vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} + s1 = sum(1 for c in s[:half] if c in vowels) + s2 = sum(1 for c in s[half:] if c in vowels) + return s1 == s2 +``` + +### **Java** + +```java +class Solution { + public boolean halvesAreAlike(String s) { + int half = s.length() >> 1; + Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); + int s1 = 0, s2 = 0; + for (int i = 0; i < half; ++i) { + if (vowels.contains(s.charAt(i))) { + ++s1; + } + if (vowels.contains(s.charAt(half + i))) { + ++s2; + } + } + return s1 == s2; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md b/assets/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md new file mode 100644 index 00000000..48dad7a5 --- /dev/null +++ b/assets/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md @@ -0,0 +1,71 @@ +# [1705. Maximum Number of Eaten Apples](https://leetcode.com/problems/maximum-number-of-eaten-apples) + + + +## Description + +

    There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.

    + +

    You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.

    + +

    Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.

    + +

     

    +

    Example 1:

    + +
    +Input: apples = [1,2,3,5,2], days = [3,2,1,4,2]
    +Output: 7
    +Explanation: You can eat 7 apples:
    +- On the first day, you eat an apple that grew on the first day.
    +- On the second day, you eat an apple that grew on the second day.
    +- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
    +- On the fourth to the seventh days, you eat apples that grew on the fourth day.
    +
    + +

    Example 2:

    + +
    +Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
    +Output: 5
    +Explanation: You can eat 5 apples:
    +- On the first to the third day you eat apples that grew on the first day.
    +- Do nothing on the fouth and fifth days.
    +- On the sixth and seventh days you eat apples that grew on the sixth day.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • apples.length == n
    • +
    • days.length == n
    • +
    • 1 <= n <= 2 * 104
    • +
    • 0 <= apples[i], days[i] <= 2 * 104
    • +
    • days[i] = 0 if and only if apples[i] = 0.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1706.Where Will the Ball Fall/README_EN.md b/assets/1700-1799/1706.Where Will the Ball Fall/README_EN.md new file mode 100644 index 00000000..0c63552a --- /dev/null +++ b/assets/1700-1799/1706.Where Will the Ball Fall/README_EN.md @@ -0,0 +1,84 @@ +# [1706. Where Will the Ball Fall](https://leetcode.com/problems/where-will-the-ball-fall) + + + +## Description + +

    You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.

    + +

    Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.

    + +
      +
    • A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.
    • +
    • A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.
    • +
    + +

    We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box.

    + +

    Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
    +Output: [1,-1,-1,-1,-1]
    +Explanation: This example is shown in the photo.
    +Ball b0 is dropped at column 0 and falls out of the box at column 1.
    +Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
    +Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
    +Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
    +Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[-1]]
    +Output: [-1]
    +Explanation: The ball gets stuck against the left wall.
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]
    +Output: [0,1,2,3,4,-1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • grid[i][j] is 1 or -1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1706.Where Will the Ball Fall/images/ball.jpg b/assets/1700-1799/1706.Where Will the Ball Fall/images/ball.jpg new file mode 100644 index 00000000..85257c12 Binary files /dev/null and b/assets/1700-1799/1706.Where Will the Ball Fall/images/ball.jpg differ diff --git a/assets/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md b/assets/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md new file mode 100644 index 00000000..a8a6aaeb --- /dev/null +++ b/assets/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md @@ -0,0 +1,64 @@ +# [1707. Maximum XOR With an Element From Array](https://leetcode.com/problems/maximum-xor-with-an-element-from-array) + + + +## Description + +

    You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].

    + +

    The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.

    + +

    Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
    +Output: [3,3,7]
    +Explanation:
    +1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
    +2) 1 XOR 2 = 3.
    +3) 5 XOR 2 = 7.
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]
    +Output: [15,-1,5]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length, queries.length <= 105
    • +
    • queries[i].length == 2
    • +
    • 0 <= nums[j], xi, mi <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1708.Largest Subarray Length K/README_EN.md b/assets/1700-1799/1708.Largest Subarray Length K/README_EN.md new file mode 100644 index 00000000..a306cfdf --- /dev/null +++ b/assets/1700-1799/1708.Largest Subarray Length K/README_EN.md @@ -0,0 +1,78 @@ +# [1708. Largest Subarray Length K](https://leetcode.com/problems/largest-subarray-length-k) + + + +## Description + +

    An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i].

    + +

    For example, consider 0-indexing:

    + +
      +
    • [1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2.
    • +
    • [1,4,4,4] < [2,1,1,1], since at index 0, 1 < 2.
    • +
    + +

    A subarray is a contiguous subsequence of the array.

    + +

    Given an integer array nums of distinct integers, return the largest subarray of nums of length k.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,4,5,2,3], k = 3
    +Output: [5,2,3]
    +Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3].
    +Of these, [5,2,3] is the largest.
    + +

    Example 2:

    + +
    +Input: nums = [1,4,5,2,3], k = 4
    +Output: [4,5,2,3]
    +Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3].
    +Of these, [4,5,2,3] is the largest.
    + +

    Example 3:

    + +
    +Input: nums = [1,4,5,2,3], k = 1
    +Output: [5]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • All the integers of nums are unique.
    • +
    + +

     

    +Follow up: What if the integers in nums are not distinct? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1709.Biggest Window Between Visits/README_EN.md b/assets/1700-1799/1709.Biggest Window Between Visits/README_EN.md new file mode 100644 index 00000000..cf07df5b --- /dev/null +++ b/assets/1700-1799/1709.Biggest Window Between Visits/README_EN.md @@ -0,0 +1,74 @@ +# [1709. Biggest Window Between Visits](https://leetcode.com/problems/biggest-window-between-visits) + + + +## Description + +

    Table: UserVisits

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| user_id     | int  |
    +| visit_date  | date |
    ++-------------+------+
    +This table does not have a primary key.
    +This table contains logs of the dates that users vistied a certain retailer.
    +
    + +

     

    + +

    Assume today's date is '2021-1-1'.

    + +

    Write an SQL query that will, for each user_id, find out the largest window of days between each visit and the one right after it (or today if you are considering the last visit).

    + +

    Return the result table ordered by user_id.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +UserVisits table:
    ++---------+------------+
    +| user_id | visit_date |
    ++---------+------------+
    +| 1       | 2020-11-28 |
    +| 1       | 2020-10-20 |
    +| 1       | 2020-12-3  |
    +| 2       | 2020-10-5  |
    +| 2       | 2020-12-9  |
    +| 3       | 2020-11-11 |
    ++---------+------------+
    +Result table:
    ++---------+---------------+
    +| user_id | biggest_window|
    ++---------+---------------+
    +| 1       | 39            |
    +| 2       | 65            |
    +| 3       | 51            |
    ++---------+---------------+
    +For the first user, the windows in question are between dates:
    +    - 2020-10-20 and 2020-11-28 with a total of 39 days. 
    +    - 2020-11-28 and 2020-12-3 with a total of 5 days. 
    +    - 2020-12-3 and 2021-1-1 with a total of 29 days.
    +Making the biggest window the one with 39 days.
    +For the second user, the windows in question are between dates:
    +    - 2020-10-5 and 2020-12-9 with a total of 65 days.
    +    - 2020-12-9 and 2021-1-1 with a total of 23 days.
    +Making the biggest window the one with 65 days.
    +For the third user, the only window in question is between dates 2020-11-11 and 2021-1-1 with a total of 51 days.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1700-1799/1710.Maximum Units on a Truck/README_EN.md b/assets/1700-1799/1710.Maximum Units on a Truck/README_EN.md new file mode 100644 index 00000000..09a5d901 --- /dev/null +++ b/assets/1700-1799/1710.Maximum Units on a Truck/README_EN.md @@ -0,0 +1,71 @@ +# [1710. Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck) + + + +## Description + +

    You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:

    + +
      +
    • numberOfBoxesi is the number of boxes of type i.
    • +
    • numberOfUnitsPerBoxi is the number of units in each box of the type i.
    • +
    + +

    You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

    + +

    Return the maximum total number of units that can be put on the truck.

    + +

     

    +

    Example 1:

    + +
    +Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
    +Output: 8
    +Explanation: There are:
    +- 1 box of the first type that contains 3 units.
    +- 2 boxes of the second type that contain 2 units each.
    +- 3 boxes of the third type that contain 1 unit each.
    +You can take all the boxes of the first and second types, and one box of the third type.
    +The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.
    +
    + +

    Example 2:

    + +
    +Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
    +Output: 91
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= boxTypes.length <= 1000
    • +
    • 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
    • +
    • 1 <= truckSize <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1711.Count Good Meals/README_EN.md b/assets/1700-1799/1711.Count Good Meals/README_EN.md new file mode 100644 index 00000000..a64eefe4 --- /dev/null +++ b/assets/1700-1799/1711.Count Good Meals/README_EN.md @@ -0,0 +1,122 @@ +# [1711. Count Good Meals](https://leetcode.com/problems/count-good-meals) + + + +## Description + +

    A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.

    + +

    You can pick any two different foods to make a good meal.

    + +

    Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7.

    + +

    Note that items with different indices are considered different even if they have the same deliciousness value.

    + +

     

    +

    Example 1:

    + +
    +Input: deliciousness = [1,3,5,7,9]
    +Output: 4
    +Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).
    +Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.
    +
    + +

    Example 2:

    + +
    +Input: deliciousness = [1,1,1,3,3,3,7]
    +Output: 15
    +Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= deliciousness.length <= 105
    • +
    • 0 <= deliciousness[i] <= 220
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + mod = 1000000007 + limit = max(deliciousness) * 2 + pairs = 0 + freq = collections.defaultdict(int) + for d in deliciousness: + target = 1 + while target <= limit: + pairs = (pairs + freq[target - d]) % mod + target = target << 1 + freq[d] += 1 + return pairs +``` + +### **Java** + +```java +class Solution { + + private static final int MOD = 1000000007; + + public int countPairs(int[] deliciousness) { + int limit = Arrays.stream(deliciousness).max().getAsInt() * 2; + int pairs = 0; + Map freq = new HashMap<>(); + for (int d : deliciousness) { + for (int sum = 1; sum <= limit; sum <<= 1) { + int count = freq.getOrDefault(sum - d, 0); + pairs = (pairs + count) % MOD; + } + freq.merge(d, 1, Integer::sum); + } + return pairs; + } +} +``` + +### **Go** + +```go +const mod int = 1e9 + 7 + +func countPairs(deliciousness []int) int { + limit := 0 + for _, d := range deliciousness { + limit = max(limit, d) + } + limit *= 2 + pairs := 0 + freq := make(map[int]int) + for _, d := range deliciousness { + for sum := 1; sum <= limit; sum <<= 1 { + pairs = (pairs + freq[sum-d]) % mod + } + freq[d]++ + } + return pairs +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md b/assets/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md new file mode 100644 index 00000000..a29f18a7 --- /dev/null +++ b/assets/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md @@ -0,0 +1,107 @@ +# [1712. Ways to Split Array Into Three Subarrays](https://leetcode.com/problems/ways-to-split-array-into-three-subarrays) + + + +## Description + +

    A split of an integer array is good if:

    + + + +
      +
    • The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.
    • +
    • The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.
    • +
    + + + +

    Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [1,1,1]
    +
    +Output: 1
    +
    +Explanation: The only good way to split nums is [1] [1] [1].
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,2,2,2,5,0]
    +
    +Output: 3
    +
    +Explanation: There are three good ways of splitting nums:
    +
    +[1] [2] [2,2,5,0]
    +
    +[1] [2,2] [2,5,0]
    +
    +[1,2] [2,2] [5,0]
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [3,2,1]
    +
    +Output: 0
    +
    +Explanation: There is no good way to split nums.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 3 <= nums.length <= 105
    • +
    • 0 <= nums[i] <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md b/assets/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md new file mode 100644 index 00000000..ec317453 --- /dev/null +++ b/assets/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md @@ -0,0 +1,63 @@ +# [1713. Minimum Operations to Make a Subsequence](https://leetcode.com/problems/minimum-operations-to-make-a-subsequence) + + + +## Description + +

    You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.

    + +

    In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.

    + +

    Return the minimum number of operations needed to make target a subsequence of arr.

    + +

    A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.

    + +

     

    +

    Example 1:

    + +
    +Input: target = [5,1,3], arr = [9,4,2,3,4]
    +Output: 2
    +Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.
    +
    + +

    Example 2:

    + +
    +Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= target.length, arr.length <= 105
    • +
    • 1 <= target[i], arr[i] <= 109
    • +
    • target contains no duplicates.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md b/assets/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md new file mode 100644 index 00000000..9cf87b82 --- /dev/null +++ b/assets/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md @@ -0,0 +1,67 @@ +# [1714. Sum Of Special Evenly-Spaced Elements In Array](https://leetcode.com/problems/sum-of-special-evenly-spaced-elements-in-array) + + + +## Description + +

    You are given a 0-indexed integer array nums consisting of n non-negative integers.

    + +

    You are also given an array queries, where queries[i] = [xi, yi]. The answer to the ith query is the sum of all nums[j] where xi <= j < n and (j - xi) is divisible by yi.

    + +

    Return an array answer where answer.length == queries.length and answer[i] is the answer to the ith query modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [0,1,2,3,4,5,6,7], queries = [[0,3],[5,1],[4,2]]
    +Output: [9,18,10]
    +Explanation: The answers of the queries are as follows:
    +1) The j indices that satisfy this query are 0, 3, and 6. nums[0] + nums[3] + nums[6] = 9
    +2) The j indices that satisfy this query are 5, 6, and 7. nums[5] + nums[6] + nums[7] = 18
    +3) The j indices that satisfy this query are 4 and 6. nums[4] + nums[6] = 10
    +
    + +

    Example 2:

    + +
    +Input: nums = [100,200,101,201,102,202,103,203], queries = [[0,7]]
    +Output: [303]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 5 * 104
    • +
    • 0 <= nums[i] <= 109
    • +
    • 1 <= queries.length <= 1.5 * 105
    • +
    • 0 <= xi < n
    • +
    • 1 <= yi <= 5 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1715.Count Apples and Oranges/README_EN.md b/assets/1700-1799/1715.Count Apples and Oranges/README_EN.md new file mode 100644 index 00000000..cd2f3808 --- /dev/null +++ b/assets/1700-1799/1715.Count Apples and Oranges/README_EN.md @@ -0,0 +1,113 @@ +# [1715. Count Apples and Oranges](https://leetcode.com/problems/count-apples-and-oranges) + + + +## Description + +

    Table: Boxes

    + +
    ++--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| box_id       | int  |
    +| chest_id     | int  |
    +| apple_count  | int  |
    +| orange_count | int  |
    ++--------------+------+
    +box_id is the primary key for this table.
    +chest_id is a foreign key of the chests table.
    +This table contains information about the boxes and the number of oranges and apples they contain. Each box may contain a chest, which also can contain oranges and apples.
    +
    + +

     

    + +

    Table: Chests

    + +
    ++--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| chest_id     | int  |
    +| apple_count  | int  |
    +| orange_count | int  |
    ++--------------+------+
    +chest_id is the primary key for this table.
    +This table contains information about the chests we have, and the corresponding number if oranges and apples they contain.
    +
    + +

     

    + +

    Write an SQL query to count the number of apples and oranges in all the boxes. If a box contains a chest, you should also include the number of apples and oranges it has.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Boxes table:
    ++--------+----------+-------------+--------------+
    +| box_id | chest_id | apple_count | orange_count |
    ++--------+----------+-------------+--------------+
    +| 2      | null     | 6           | 15           |
    +| 18     | 14       | 4           | 15           |
    +| 19     | 3        | 8           | 4            |
    +| 12     | 2        | 19          | 20           |
    +| 20     | 6        | 12          | 9            |
    +| 8      | 6        | 9           | 9            |
    +| 3      | 14       | 16          | 7            |
    ++--------+----------+-------------+--------------+
    +
    +Chests table:
    ++----------+-------------+--------------+
    +| chest_id | apple_count | orange_count |
    ++----------+-------------+--------------+
    +| 6        | 5           | 6            |
    +| 14       | 20          | 10           |
    +| 2        | 8           | 8            |
    +| 3        | 19          | 4            |
    +| 16       | 19          | 19           |
    ++----------+-------------+--------------+
    +
    +Result table:
    ++-------------+--------------+
    +| apple_count | orange_count |
    ++-------------+--------------+
    +| 151         | 123          |
    ++-------------+--------------+
    +box 2 has 6 apples and 15 oranges.
    +box 18 has 4 + 20 (from the chest) = 24 apples and 15 + 10 (from the chest) = 25 oranges.
    +box 19 has 8 + 19 (from the chest) = 27 apples and 4 + 4 (from the chest) = 8 oranges.
    +box 12 has 19 + 8 (from the chest) = 27 apples and 20 + 8 (from the chest) = 28 oranges.
    +box 20 has 12 + 5 (from the chest) = 17 apples and 9 + 6 (from the chest) = 15 oranges.
    +box 8 has 9 + 5 (from the chest) = 14 apples and 9 + 6 (from the chest) = 15 oranges.
    +box 3 has 16 + 20 (from the chest) = 36 apples and 7 + 10 (from the chest) = 17 oranges.
    +Total number of apples = 6 + 24 + 27 + 27 + 17 + 14 + 36 = 151
    +Total number of oranges = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123
    +
    + + +## Solutions + + + +`LEFT JOIN` and `IFNULL`. + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + SUM(IFNULL(b.apple_count, 0) + IFNULL(c.apple_count, 0)) AS apple_count, + SUM(IFNULL(b.orange_count, 0) + IFNULL(c.orange_count, 0)) AS orange_count +FROM + Boxes b +LEFT JOIN + Chests c +ON + b.chest_id = c.chest_id; +``` + + \ No newline at end of file diff --git a/assets/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md b/assets/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md new file mode 100644 index 00000000..05e4e9a7 --- /dev/null +++ b/assets/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md @@ -0,0 +1,68 @@ +# [1716. Calculate Money in Leetcode Bank](https://leetcode.com/problems/calculate-money-in-leetcode-bank) + + + +## Description + +

    Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.

    + +

    He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.

    + +

    Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4
    +Output: 10
    +Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
    +
    + +

    Example 2:

    + +
    +Input: n = 10
    +Output: 37
    +Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
    +
    + +

    Example 3:

    + +
    +Input: n = 20
    +Output: 96
    +Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md b/assets/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md new file mode 100644 index 00000000..2a27d8c6 --- /dev/null +++ b/assets/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md @@ -0,0 +1,77 @@ +# [1717. Maximum Score From Removing Substrings](https://leetcode.com/problems/maximum-score-from-removing-substrings) + + + +## Description + +

    You are given a string s and two integers x and y. You can perform two types of operations any number of times.

    + +
      +
    • Remove substring "ab" and gain x points. + +
        +
      • For example, when removing "ab" from "cabxbae" it becomes "cxbae".
      • +
      +
    • +
    • Remove substring "ba" and gain y points. +
        +
      • For example, when removing "ba" from "cabxbae" it becomes "cabxe".
      • +
      +
    • +
    + +

    Return the maximum points you can gain after applying the above operations on s.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "cdbcbbaaabab", x = 4, y = 5
    +Output: 19
    +Explanation:
    +- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
    +- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
    +- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
    +- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.
    +Total score = 5 + 4 + 5 + 5 = 19.
    + +

    Example 2:

    + +
    +Input: s = "aabbaaxybbaabb", x = 5, y = 4
    +Output: 20
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • 1 <= x, y <= 104
    • +
    • s consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md b/assets/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md new file mode 100644 index 00000000..3b4d0a88 --- /dev/null +++ b/assets/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md @@ -0,0 +1,67 @@ +# [1718. Construct the Lexicographically Largest Valid Sequence](https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence) + + + +## Description + +

    Given an integer n, find a sequence that satisfies all of the following:

    + +
      +
    • The integer 1 occurs once in the sequence.
    • +
    • Each integer between 2 and n occurs twice in the sequence.
    • +
    • For every integer i between 2 and n, the distance between the two occurrences of i is exactly i.
    • +
    + +

    The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|.

    + +

    Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.

    + +

    A sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3
    +Output: [3,1,2,3,2]
    +Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.
    +
    + +

    Example 2:

    + +
    +Input: n = 5
    +Output: [5,3,1,4,3,5,2,4,2]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 20
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md b/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md new file mode 100644 index 00000000..d1452dc7 --- /dev/null +++ b/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md @@ -0,0 +1,92 @@ +# [1719. Number Of Ways To Reconstruct A Tree](https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree) + + + +## Description + +

    You are given an array pairs, where pairs[i] = [xi, yi], and:

    + +
      +
    • There are no duplicates.
    • +
    • xi < yi
    • +
    + +

    Let ways be the number of rooted trees that satisfy the following conditions:

    + +
      +
    • The tree consists of nodes whose values appeared in pairs.
    • +
    • A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi.
    • +
    • Note: the tree does not have to be a binary tree.
    • +
    + +

    Two ways are considered to be different if there is at least one node that has different parents in both ways.

    + +

    Return:

    + +
      +
    • 0 if ways == 0
    • +
    • 1 if ways == 1
    • +
    • 2 if ways > 1
    • +
    + +

    A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.

    + +

    An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.

    + +

     

    +

    Example 1:

    + +
    +Input: pairs = [[1,2],[2,3]]
    +Output: 1
    +Explanation: There is exactly one valid rooted tree, which is shown in the above figure.
    +
    + +

    Example 2:

    + +
    +Input: pairs = [[1,2],[2,3],[1,3]]
    +Output: 2
    +Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures.
    +
    + +

    Example 3:

    + +
    +Input: pairs = [[1,2],[2,3],[2,4],[1,5]]
    +Output: 0
    +Explanation: There are no valid rooted trees.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= pairs.length <= 105
    • +
    • 1 <= xi < yi <= 500
    • +
    • The elements in pairs are unique.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/images/tree.png b/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/images/tree.png new file mode 100644 index 00000000..c70ffb01 Binary files /dev/null and b/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/images/tree.png differ diff --git a/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/images/trees2.png b/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/images/trees2.png new file mode 100644 index 00000000..eb847230 Binary files /dev/null and b/assets/1700-1799/1719.Number Of Ways To Reconstruct A Tree/images/trees2.png differ diff --git a/assets/1700-1799/1720.Decode XORed Array/README_EN.md b/assets/1700-1799/1720.Decode XORed Array/README_EN.md new file mode 100644 index 00000000..e6eeb255 --- /dev/null +++ b/assets/1700-1799/1720.Decode XORed Array/README_EN.md @@ -0,0 +1,82 @@ +# [1720. Decode XORed Array](https://leetcode.com/problems/decode-xored-array) + + + +## Description + +

    There is a hidden integer array arr that consists of n non-negative integers.

    + +

    It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].

    + +

    You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].

    + +

    Return the original array arr. It can be proved that the answer exists and is unique.

    + +

     

    +

    Example 1:

    + +
    +Input: encoded = [1,2,3], first = 1
    +Output: [1,0,2,1]
    +Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
    +
    + +

    Example 2:

    + +
    +Input: encoded = [6,2,7,3], first = 4
    +Output: [4,2,0,7,4]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 104
    • +
    • encoded.length == n - 1
    • +
    • 0 <= encoded[i] <= 105
    • +
    • 0 <= first <= 105
    • +
    + +## Solutions + +XOR. + +`a = b ^ c` => `a ^ b = b ^ c ^ b` => `c = a ^ b`. + + + +### **Python3** + +```python +class Solution: + def decode(self, encoded: List[int], first: int) -> List[int]: + res = [first] + for e in encoded: + first ^= e + res.append(first) + return res +``` + +### **Java** + +```java +class Solution { + public int[] decode(int[] encoded, int first) { + int[] res = new int[encoded.length + 1]; + res[0] = first; + for (int i = 0; i < encoded.length; ++i) { + res[i + 1] = res[i] ^ encoded[i]; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md b/assets/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md new file mode 100644 index 00000000..ac9e1bdd --- /dev/null +++ b/assets/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md @@ -0,0 +1,122 @@ +# [1721. Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list) + + + +## Description + +

    You are given the head of a linked list, and an integer k.

    + +

    Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

    + +

     

    +

    Example 1:

    + +
    +Input: head = [1,2,3,4,5], k = 2
    +Output: [1,4,3,2,5]
    +
    + +

    Example 2:

    + +
    +Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
    +Output: [7,9,6,6,8,7,3,0,9,5]
    +
    + +

    Example 3:

    + +
    +Input: head = [1], k = 1
    +Output: [1]
    +
    + +

    Example 4:

    + +
    +Input: head = [1,2], k = 1
    +Output: [2,1]
    +
    + +

    Example 5:

    + +
    +Input: head = [1,2,3], k = 2
    +Output: [1,2,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the list is n.
    • +
    • 1 <= k <= n <= 105
    • +
    • 0 <= Node.val <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapNodes(self, head: ListNode, k: int) -> ListNode: + fast = head + for _ in range(k - 1): + fast = fast.next + p = fast + slow = head + while fast.next: + slow, fast = slow.next, fast.next + q = slow + p.val, q.val = q.val, p.val + return head +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapNodes(ListNode head, int k) { + ListNode fast = head; + while (--k > 0) { + fast = fast.next; + } + ListNode p = fast; + ListNode slow = head; + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + ListNode q = slow; + int t = p.val; + p.val = q.val; + q.val = t; + return head; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1721.Swapping Nodes in a Linked List/images/linked1.jpg b/assets/1700-1799/1721.Swapping Nodes in a Linked List/images/linked1.jpg new file mode 100644 index 00000000..3970e3be Binary files /dev/null and b/assets/1700-1799/1721.Swapping Nodes in a Linked List/images/linked1.jpg differ diff --git a/assets/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md b/assets/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md new file mode 100644 index 00000000..9b986e44 --- /dev/null +++ b/assets/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md @@ -0,0 +1,77 @@ +# [1722. Minimize Hamming Distance After Swap Operations](https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations) + + + +## Description + +

    You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.

    + +

    The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed).

    + +

    Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.

    + +

     

    +

    Example 1:

    + +
    +Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
    +Output: 1
    +Explanation: source can be transformed the following way:
    +- Swap indices 0 and 1: source = [2,1,3,4]
    +- Swap indices 2 and 3: source = [2,1,4,3]
    +The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
    +
    + +

    Example 2:

    + +
    +Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
    +Output: 2
    +Explanation: There are no allowed swaps.
    +The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
    +
    + +

    Example 3:

    + +
    +Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
    +Output: 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == source.length == target.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= source[i], target[i] <= 105
    • +
    • 0 <= allowedSwaps.length <= 105
    • +
    • allowedSwaps[i].length == 2
    • +
    • 0 <= ai, bi <= n - 1
    • +
    • ai != bi
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md b/assets/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md new file mode 100644 index 00000000..2f56629f --- /dev/null +++ b/assets/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md @@ -0,0 +1,63 @@ +# [1723. Find Minimum Time to Finish All Jobs](https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs) + + + +## Description + +

    You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job.

    + +

    There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.

    + +

    Return the minimum possible maximum working time of any assignment.

    + +

     

    +

    Example 1:

    + +
    +Input: jobs = [3,2,3], k = 3
    +Output: 3
    +Explanation: By assigning each person one job, the maximum time is 3.
    +
    + +

    Example 2:

    + +
    +Input: jobs = [1,2,4,7,8], k = 2
    +Output: 11
    +Explanation: Assign the jobs the following way:
    +Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
    +Worker 2: 4, 7 (working time = 4 + 7 = 11)
    +The maximum working time is 11.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= jobs.length <= 12
    • +
    • 1 <= jobs[i] <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md b/assets/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md new file mode 100644 index 00000000..bed1cf83 --- /dev/null +++ b/assets/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md @@ -0,0 +1,73 @@ +# [1724. Checking Existence of Edge Length Limited Paths II](https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths-ii) + + + +## Description + +

    An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes, and the graph may not be connected.

    + +

    Implement the DistanceLimitedPathsExist class:

    + +
      +
    • DistanceLimitedPathsExist(int n, int[][] edgeList) Initializes the class with an undirected graph.
    • +
    • boolean query(int p, int q, int limit) Returns true if there exists a path from p to q such that each edge on the path has a distance strictly less than limit, and otherwise false.
    • +
    + +

     

    +

    Example 1:

    + +

    + +
    +Input
    +["DistanceLimitedPathsExist", "query", "query", "query", "query"]
    +[[6, [[0, 2, 4], [0, 3, 2], [1, 2, 3], [2, 3, 1], [4, 5, 5]]], [2, 3, 2], [1, 3, 3], [2, 0, 3], [0, 5, 6]]
    +Output
    +[null, true, false, true, false]
    +
    +Explanation
    +DistanceLimitedPathsExist distanceLimitedPathsExist = new DistanceLimitedPathsExist(6, [[0, 2, 4], [0, 3, 2], [1, 2, 3], [2, 3, 1], [4, 5, 5]]);
    +distanceLimitedPathsExist.query(2, 3, 2); // return true. There is an edge from 2 to 3 of distance 1, which is less than 2.
    +distanceLimitedPathsExist.query(1, 3, 3); // return false. There is no way to go from 1 to 3 with distances strictly less than 3.
    +distanceLimitedPathsExist.query(2, 0, 3); // return true. There is a way to go from 2 to 0 with distance < 3: travel from 2 to 3 to 0.
    +distanceLimitedPathsExist.query(0, 5, 6); // return false. There are no paths from 0 to 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 104
    • +
    • 0 <= edgeList.length <= 104
    • +
    • edgeList[i].length == 3
    • +
    • 0 <= ui, vi, p, q <= n-1
    • +
    • ui != vi
    • +
    • p != q
    • +
    • 1 <= disi, limit <= 109
    • +
    • At most 104 calls will be made to query.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/images/messed.png b/assets/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/images/messed.png new file mode 100644 index 00000000..2fba44c4 Binary files /dev/null and b/assets/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/images/messed.png differ diff --git a/assets/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md b/assets/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md new file mode 100644 index 00000000..71247f5a --- /dev/null +++ b/assets/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md @@ -0,0 +1,92 @@ +# [1725. Number Of Rectangles That Can Form The Largest Square](https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square) + + + +## Description + +

    You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.

    + + + +

    You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.

    + + + +

    Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.

    + + + +

    Return the number of rectangles that can make a square with a side length of maxLen.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]
    +
    +Output: 3
    +
    +Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].
    +
    +The largest possible square is of length 5, and you can get it out of 3 rectangles.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]
    +
    +Output: 3
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= rectangles.length <= 1000
    • +
    • rectangles[i].length == 2
    • +
    • 1 <= li, wi <= 109
    • +
    • li != wi
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1726.Tuple with Same Product/README_EN.md b/assets/1700-1799/1726.Tuple with Same Product/README_EN.md new file mode 100644 index 00000000..f407b126 --- /dev/null +++ b/assets/1700-1799/1726.Tuple with Same Product/README_EN.md @@ -0,0 +1,119 @@ +# [1726. Tuple with Same Product](https://leetcode.com/problems/tuple-with-same-product) + + + +## Description + +

    Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [2,3,4,6]
    +
    +Output: 8
    +
    +Explanation: There are 8 valid tuples:
    +
    +(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
    +
    +(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,2,4,5,10]
    +
    +Output: 16
    +
    +Explanation: There are 16 valids tuples:
    +
    +(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
    +
    +(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
    +
    +(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)
    +
    +(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: nums = [2,3,4,6,8,12]
    +
    +Output: 40
    +
    +
    + + + +

    Example 4:

    + + + +
    +
    +Input: nums = [2,3,5,7]
    +
    +Output: 0
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 104
    • +
    • All elements in nums are distinct.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md b/assets/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md new file mode 100644 index 00000000..452a0461 --- /dev/null +++ b/assets/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md @@ -0,0 +1,81 @@ +# [1727. Largest Submatrix With Rearrangements](https://leetcode.com/problems/largest-submatrix-with-rearrangements) + + + +## Description + +

    You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.

    + +

    Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]
    +Output: 4
    +Explanation: You can rearrange the columns as shown above.
    +The largest submatrix of 1s, in bold, has an area of 4.
    +
    + +

    Example 2:

    + +

    + +
    +Input: matrix = [[1,0,1,0,1]]
    +Output: 3
    +Explanation: You can rearrange the columns as shown above.
    +The largest submatrix of 1s, in bold, has an area of 3.
    +
    + +

    Example 3:

    + +
    +Input: matrix = [[1,1,0],[1,0,1]]
    +Output: 2
    +Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
    + +

    Example 4:

    + +
    +Input: matrix = [[0,0],[0,0]]
    +Output: 0
    +Explanation: As there are no 1s, no submatrix of 1s can be formed and the area is 0.
    + +

     

    +

    Constraints:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m * n <= 105
    • +
    • matrix[i][j] is 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1727.Largest Submatrix With Rearrangements/images/screenshot-2020-12-30-at-40536-pm.png b/assets/1700-1799/1727.Largest Submatrix With Rearrangements/images/screenshot-2020-12-30-at-40536-pm.png new file mode 100644 index 00000000..060fead8 Binary files /dev/null and b/assets/1700-1799/1727.Largest Submatrix With Rearrangements/images/screenshot-2020-12-30-at-40536-pm.png differ diff --git a/assets/1700-1799/1727.Largest Submatrix With Rearrangements/images/screenshot-2020-12-30-at-40852-pm.png b/assets/1700-1799/1727.Largest Submatrix With Rearrangements/images/screenshot-2020-12-30-at-40852-pm.png new file mode 100644 index 00000000..73688048 Binary files /dev/null and b/assets/1700-1799/1727.Largest Submatrix With Rearrangements/images/screenshot-2020-12-30-at-40852-pm.png differ diff --git a/assets/1700-1799/1728.Cat and Mouse II/README_EN.md b/assets/1700-1799/1728.Cat and Mouse II/README_EN.md new file mode 100644 index 00000000..4c825160 --- /dev/null +++ b/assets/1700-1799/1728.Cat and Mouse II/README_EN.md @@ -0,0 +1,116 @@ +# [1728. Cat and Mouse II](https://leetcode.com/problems/cat-and-mouse-ii) + + + +## Description + +

    A game is played by a cat and a mouse named Cat and Mouse.

    + +

    The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food.

    + +
      +
    • Players are represented by the characters 'C'(Cat),'M'(Mouse).
    • +
    • Floors are represented by the character '.' and can be walked on.
    • +
    • Walls are represented by the character '#' and cannot be walked on.
    • +
    • Food is represented by the character 'F' and can be walked on.
    • +
    • There is only one of each character 'C', 'M', and 'F' in grid.
    • +
    + +

    Mouse and Cat play according to the following rules:

    + +
      +
    • Mouse moves first, then they take turns to move.
    • +
    • During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid.
    • +
    • catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
    • +
    • Staying in the same position is allowed.
    • +
    • Mouse can jump over Cat.
    • +
    + +

    The game can end in 4 ways:

    + +
      +
    • If Cat occupies the same position as Mouse, Cat wins.
    • +
    • If Cat reaches the food first, Cat wins.
    • +
    • If Mouse reaches the food first, Mouse wins.
    • +
    • If Mouse cannot get to the food within 1000 turns, Cat wins.
    • +
    + +

    Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2
    +Output: true
    +Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
    +
    + +

    Example 2:

    + +

    + +
    +Input: grid = ["M.C...F"], catJump = 1, mouseJump = 4
    +Output: true
    +
    + +

    Example 3:

    + +
    +Input: grid = ["M.C...F"], catJump = 1, mouseJump = 3
    +Output: false
    +
    + +

    Example 4:

    + +
    +Input: grid = ["C...#","...#F","....#","M...."], catJump = 2, mouseJump = 5
    +Output: false
    +
    + +

    Example 5:

    + +
    +Input: grid = [".M...","..#..","#..#.","C#.#.","...#F"], catJump = 3, mouseJump = 1
    +Output: true
    +
    + +

     

    +

    Constraints:

    + +
      +
    • rows == grid.length
    • +
    • cols = grid[i].length
    • +
    • 1 <= rows, cols <= 8
    • +
    • grid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'.
    • +
    • There is only one of each character 'C', 'M', and 'F' in grid.
    • +
    • 1 <= catJump, mouseJump <= 8
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1728.Cat and Mouse II/images/sample_111_1955.png b/assets/1700-1799/1728.Cat and Mouse II/images/sample_111_1955.png new file mode 100644 index 00000000..1b47cfde Binary files /dev/null and b/assets/1700-1799/1728.Cat and Mouse II/images/sample_111_1955.png differ diff --git a/assets/1700-1799/1728.Cat and Mouse II/images/sample_2_1955.png b/assets/1700-1799/1728.Cat and Mouse II/images/sample_2_1955.png new file mode 100644 index 00000000..0bfeea41 Binary files /dev/null and b/assets/1700-1799/1728.Cat and Mouse II/images/sample_2_1955.png differ diff --git a/assets/1700-1799/1729.Find Followers Count/README_EN.md b/assets/1700-1799/1729.Find Followers Count/README_EN.md new file mode 100644 index 00000000..73b58caa --- /dev/null +++ b/assets/1700-1799/1729.Find Followers Count/README_EN.md @@ -0,0 +1,70 @@ +# [1729. Find Followers Count](https://leetcode.com/problems/find-followers-count) + + + +## Description + +

    Table: Followers

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| user_id     | int  |
    +| follower_id | int  |
    ++-------------+------+
    +(user_id, follower_id) is the primary key for this table.
    +This table contains the IDs of a user and a follower in a social media app where the follower follows the user.
    + +

    Write an SQL query that will, for each user, return the number of followers.

    + +

    Return the result table ordered by user_id.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Followers table:
    ++---------+-------------+
    +| user_id | follower_id |
    ++---------+-------------+
    +| 0       | 1           |
    +| 1       | 0           |
    +| 2       | 0           |
    +| 2       | 1           |
    ++---------+-------------+
    +Result table:
    ++---------+----------------+
    +| user_id | followers_count|
    ++---------+----------------+
    +| 0       | 1              |
    +| 1       | 1              |
    +| 2       | 2              |
    ++---------+----------------+
    +The followers of 0 are {1}
    +The followers of 1 are {0}
    +The followers of 2 are {0,1}
    +
    + +

     

    + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + user_id, count(1) AS followers_count +FROM + Followers +GROUP BY + user_id +ORDER BY + user_id +``` + + diff --git a/assets/1700-1799/1730.Shortest Path to Get Food/README_EN.md b/assets/1700-1799/1730.Shortest Path to Get Food/README_EN.md new file mode 100644 index 00000000..7c463317 --- /dev/null +++ b/assets/1700-1799/1730.Shortest Path to Get Food/README_EN.md @@ -0,0 +1,94 @@ +# [1730. Shortest Path to Get Food](https://leetcode.com/problems/shortest-path-to-get-food) + + + +## Description + +

    You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.

    + +

    You are given an m x n character matrix, grid, of these different types of cells:

    + +
      +
    • '*' is your location. There is exactly one '*' cell.
    • +
    • '#' is a food cell. There may be multiple food cells.
    • +
    • 'O' is free space, and you can travel through these cells.
    • +
    • 'X' is an obstacle, and you cannot travel through these cells.
    • +
    + +

    You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.

    + +

    Return the length of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]]
    +Output: 3
    +Explanation: It takes 3 steps to reach the food.
    +
    + +

    Example 2:

    + +
    +Input: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]]
    +Output: -1
    +Explanation: It is not possible to reach the food.
    +
    + +

    Example 3:

    + +
    +Input: grid = [["X","X","X","X","X","X","X","X"],["X","*","O","X","O","#","O","X"],["X","O","O","X","O","O","X","X"],["X","O","O","O","O","#","O","X"],["X","X","X","X","X","X","X","X"]]
    +Output: 6
    +Explanation: There can be multiple food cells. It only takes 6 steps to reach the bottom food.
    + +

    Example 4:

    + +
    +Input: grid = [["O","*"],["#","O"]]
    +Output: 2
    +
    + +

    Example 5:

    + +
    +Input: grid = [["X","*"],["#","X"]]
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • grid[row][col] is '*', 'X', 'O', or '#'.
    • +
    • The grid contains exactly one '*'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1730.Shortest Path to Get Food/images/img1.jpg b/assets/1700-1799/1730.Shortest Path to Get Food/images/img1.jpg new file mode 100644 index 00000000..5dcc34da Binary files /dev/null and b/assets/1700-1799/1730.Shortest Path to Get Food/images/img1.jpg differ diff --git a/assets/1700-1799/1730.Shortest Path to Get Food/images/img2.jpg b/assets/1700-1799/1730.Shortest Path to Get Food/images/img2.jpg new file mode 100644 index 00000000..0eacc857 Binary files /dev/null and b/assets/1700-1799/1730.Shortest Path to Get Food/images/img2.jpg differ diff --git a/assets/1700-1799/1730.Shortest Path to Get Food/images/img3.jpg b/assets/1700-1799/1730.Shortest Path to Get Food/images/img3.jpg new file mode 100644 index 00000000..17fd963a Binary files /dev/null and b/assets/1700-1799/1730.Shortest Path to Get Food/images/img3.jpg differ diff --git a/assets/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md b/assets/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md new file mode 100644 index 00000000..8bddd48d --- /dev/null +++ b/assets/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md @@ -0,0 +1,65 @@ +# [1731. The Number of Employees Which Report to Each Employee](https://leetcode.com/problems/the-number-of-employees-which-report-to-each-employee) + + + +## Description + +

    Table: Employees

    + +
    ++-------------+----------+
    +| Column Name | Type     |
    ++-------------+----------+
    +| employee_id | int      |
    +| name        | varchar  |
    +| reports_to  | int      |
    +| age         | int      |
    ++-------------+----------+
    +employee_id is the primary key for this table.
    +This table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports_to is null). 
    +
    + +

     

    + +

    For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.

    + +

    Write an SQL query to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer.

    + +

    Return the result table ordered by employee_id.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Employees table:
    ++-------------+---------+------------+-----+
    +| employee_id | name    | reports_to | age |
    ++-------------+---------+------------+-----+
    +| 9           | Hercy   | null       | 43  |
    +| 6           | Alice   | 9          | 41  |
    +| 4           | Bob     | 9          | 36  |
    +| 2           | Winston | null       | 37  |
    ++-------------+---------+------------+-----+
    +
    +Result table:
    ++-------------+-------+---------------+-------------+
    +| employee_id | name  | reports_count | average_age |
    ++-------------+-------+---------------+-------------+
    +| 9           | Hercy | 2             | 39          |
    ++-------------+-------+---------------+-------------+
    +Hercy has 2 people report directly to him, Alice and Bob. Their average age is (41+36)/2 = 38.5, which is 39 after rounding it to the nearest integer.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1700-1799/1732.Find the Highest Altitude/README_EN.md b/assets/1700-1799/1732.Find the Highest Altitude/README_EN.md new file mode 100644 index 00000000..48510ba3 --- /dev/null +++ b/assets/1700-1799/1732.Find the Highest Altitude/README_EN.md @@ -0,0 +1,60 @@ +# [1732. Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude) + + + +## Description + +

    There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.

    + +

    You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point.

    + +

     

    +

    Example 1:

    + +
    +Input: gain = [-5,1,5,0,-7]
    +Output: 1
    +Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
    +
    + +

    Example 2:

    + +
    +Input: gain = [-4,-3,-2,-1,4,3,2]
    +Output: 0
    +Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == gain.length
    • +
    • 1 <= n <= 100
    • +
    • -100 <= gain[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1733.Minimum Number of People to Teach/README_EN.md b/assets/1700-1799/1733.Minimum Number of People to Teach/README_EN.md new file mode 100644 index 00000000..4465a510 --- /dev/null +++ b/assets/1700-1799/1733.Minimum Number of People to Teach/README_EN.md @@ -0,0 +1,74 @@ +# [1733. Minimum Number of People to Teach](https://leetcode.com/problems/minimum-number-of-people-to-teach) + + + +## Description + +

    On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language.

    + +

    You are given an integer n, an array languages, and an array friendships where:

    + +
      +
    • There are n languages numbered 1 through n,
    • +
    • languages[i] is the set of languages the i​​​​​​th​​​​ user knows, and
    • +
    • friendships[i] = [u​​​​​​i​​​, v​​​​​​i] denotes a friendship between the users u​​​​​​​​​​​i​​​​​ and vi.
    • +
    + +

    You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.

    +Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn't guarantee that x is a friend of z. +

     

    +

    Example 1:

    + +
    +Input: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]
    +Output: 1
    +Explanation: You can either teach user 1 the second language or user 2 the first language.
    +
    + +

    Example 2:

    + +
    +Input: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]
    +Output: 2
    +Explanation: Teach the third language to users 1 and 3, yielding two users to teach.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 500
    • +
    • languages.length == m
    • +
    • 1 <= m <= 500
    • +
    • 1 <= languages[i].length <= n
    • +
    • 1 <= languages[i][j] <= n
    • +
    • 1 <= u​​​​​​i < v​​​​​​i <= languages.length
    • +
    • 1 <= friendships.length <= 500
    • +
    • All tuples (u​​​​​i, v​​​​​​i) are unique
    • +
    • languages[i] contains only unique values
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1734.Decode XORed Permutation/README_EN.md b/assets/1700-1799/1734.Decode XORed Permutation/README_EN.md new file mode 100644 index 00000000..4cbc637d --- /dev/null +++ b/assets/1700-1799/1734.Decode XORed Permutation/README_EN.md @@ -0,0 +1,61 @@ +# [1734. Decode XORed Permutation](https://leetcode.com/problems/decode-xored-permutation) + + + +## Description + +

    There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.

    + +

    It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].

    + +

    Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.

    + +

     

    +

    Example 1:

    + +
    +Input: encoded = [3,1]
    +Output: [1,2,3]
    +Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]
    +
    + +

    Example 2:

    + +
    +Input: encoded = [6,5,4,6]
    +Output: [2,4,1,5,3]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= n < 105
    • +
    • n is odd.
    • +
    • encoded.length == n - 1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md b/assets/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md new file mode 100644 index 00000000..fb53329b --- /dev/null +++ b/assets/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md @@ -0,0 +1,61 @@ +# [1735. Count Ways to Make Array With Product](https://leetcode.com/problems/count-ways-to-make-array-with-product) + + + +## Description + +

    You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7.

    + +

    Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.

    + +

     

    +

    Example 1:

    + +
    +Input: queries = [[2,6],[5,1],[73,660]]
    +Output: [4,1,50734910]
    +Explanation: Each query is independent.
    +[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].
    +[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].
    +[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.
    +
    + +

    Example 2:

    + +
    +Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]
    +Output: [1,2,3,10,5]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= queries.length <= 104
    • +
    • 1 <= ni, ki <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md b/assets/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md new file mode 100644 index 00000000..fb32601d --- /dev/null +++ b/assets/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md @@ -0,0 +1,67 @@ +# [1736. Latest Time by Replacing Hidden Digits](https://leetcode.com/problems/latest-time-by-replacing-hidden-digits) + + + +## Description + +

    You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).

    + +

    The valid times are those inclusively between 00:00 and 23:59.

    + +

    Return the latest valid time you can get from time by replacing the hidden digits.

    + +

     

    +

    Example 1:

    + +
    +Input: time = "2?:?0"
    +Output: "23:50"
    +Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.
    +
    + +

    Example 2:

    + +
    +Input: time = "0?:3?"
    +Output: "09:39"
    +
    + +

    Example 3:

    + +
    +Input: time = "1?:22"
    +Output: "19:22"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • time is in the format hh:mm.
    • +
    • It is guaranteed that you can produce a valid time from the given string.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md b/assets/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md new file mode 100644 index 00000000..5eb2cc08 --- /dev/null +++ b/assets/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md @@ -0,0 +1,71 @@ +# [1737. Change Minimum Characters to Satisfy One of Three Conditions](https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions) + + + +## Description + +

    You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.

    + +

    Your goal is to satisfy one of the following three conditions:

    + +
      +
    • Every letter in a is strictly less than every letter in b in the alphabet.
    • +
    • Every letter in b is strictly less than every letter in a in the alphabet.
    • +
    • Both a and b consist of only one distinct letter.
    • +
    + +

    Return the minimum number of operations needed to achieve your goal.

    + +

     

    +

    Example 1:

    + +
    +Input: a = "aba", b = "caa"
    +Output: 2
    +Explanation: Consider the best way to make each condition true:
    +1) Change b to "ccc" in 2 operations, then every letter in a is less than every letter in b.
    +2) Change a to "bbb" and b to "aaa" in 3 operations, then every letter in b is less than every letter in a.
    +3) Change a to "aaa" and b to "aaa" in 2 operations, then a and b consist of one distinct letter.
    +The best way was done in 2 operations (either condition 1 or condition 3).
    +
    + +

    Example 2:

    + +
    +Input: a = "dabadd", b = "cda"
    +Output: 3
    +Explanation: The best way is to make condition 1 true by changing b to "eee".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= a.length, b.length <= 105
    • +
    • a and b consist only of lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md b/assets/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md new file mode 100644 index 00000000..f62b906c --- /dev/null +++ b/assets/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md @@ -0,0 +1,76 @@ +# [1738. Find Kth Largest XOR Coordinate Value](https://leetcode.com/problems/find-kth-largest-xor-coordinate-value) + + + +## Description + +

    You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.

    + +

    The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed).

    + +

    Find the kth largest value (1-indexed) of all the coordinates of matrix.

    + +

     

    +

    Example 1:

    + +
    +Input: matrix = [[5,2],[1,6]], k = 1
    +Output: 7
    +Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.
    + +

    Example 2:

    + +
    +Input: matrix = [[5,2],[1,6]], k = 2
    +Output: 5
    +Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.
    + +

    Example 3:

    + +
    +Input: matrix = [[5,2],[1,6]], k = 3
    +Output: 4
    +Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.
    + +

    Example 4:

    + +
    +Input: matrix = [[5,2],[1,6]], k = 4
    +Output: 0
    +Explanation: The value of coordinate (1,1) is 5 XOR 2 XOR 1 XOR 6 = 0, which is the 4th largest value.
    + +

     

    +

    Constraints:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 1000
    • +
    • 0 <= matrix[i][j] <= 106
    • +
    • 1 <= k <= m * n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1739.Building Boxes/README_EN.md b/assets/1700-1799/1739.Building Boxes/README_EN.md new file mode 100644 index 00000000..3138c047 --- /dev/null +++ b/assets/1700-1799/1739.Building Boxes/README_EN.md @@ -0,0 +1,79 @@ +# [1739. Building Boxes](https://leetcode.com/problems/building-boxes) + + + +## Description + +

    You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:

    + +
      +
    • You can place the boxes anywhere on the floor.
    • +
    • If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall.
    • +
    + +

    Given an integer n, return the minimum possible number of boxes touching the floor.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: n = 3
    +Output: 3
    +Explanation: The figure above is for the placement of the three boxes.
    +These boxes are placed in the corner of the room, where the corner is on the left side.
    +
    + +

    Example 2:

    + +

    + +
    +Input: n = 4
    +Output: 3
    +Explanation: The figure above is for the placement of the four boxes.
    +These boxes are placed in the corner of the room, where the corner is on the left side.
    +
    + +

    Example 3:

    + +

    + +
    +Input: n = 10
    +Output: 6
    +Explanation: The figure above is for the placement of the ten boxes.
    +These boxes are placed in the corner of the room, where the corner is on the back side.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1739.Building Boxes/images/10-boxes.png b/assets/1700-1799/1739.Building Boxes/images/10-boxes.png new file mode 100644 index 00000000..2ceb751c Binary files /dev/null and b/assets/1700-1799/1739.Building Boxes/images/10-boxes.png differ diff --git a/assets/1700-1799/1739.Building Boxes/images/3-boxes.png b/assets/1700-1799/1739.Building Boxes/images/3-boxes.png new file mode 100644 index 00000000..40425ce9 Binary files /dev/null and b/assets/1700-1799/1739.Building Boxes/images/3-boxes.png differ diff --git a/assets/1700-1799/1739.Building Boxes/images/4-boxes.png b/assets/1700-1799/1739.Building Boxes/images/4-boxes.png new file mode 100644 index 00000000..979e3428 Binary files /dev/null and b/assets/1700-1799/1739.Building Boxes/images/4-boxes.png differ diff --git a/assets/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md b/assets/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md new file mode 100644 index 00000000..323971cc --- /dev/null +++ b/assets/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md @@ -0,0 +1,66 @@ +# [1740. Find Distance in a Binary Tree](https://leetcode.com/problems/find-distance-in-a-binary-tree) + + + +## Description + +

    Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.

    + +

    The distance between two nodes is the number of edges on the path from one to the other.

    + +

     

    +

    Example 1:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
    +Output: 3
    +Explanation: There are 3 edges between 5 and 0: 5-3-1-0.
    + +

    Example 2:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
    +Output: 2
    +Explanation: There are 2 edges between 5 and 7: 5-2-7.
    + +

    Example 3:

    + +
    +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
    +Output: 0
    +Explanation: The distance between a node and itself is 0.
    + +

     

    +

    Constraints:

    + +
      +
    • The number of nodes in the tree is in the range [1, 104].
    • +
    • 0 <= Node.val <= 109
    • +
    • All Node.val are unique.
    • +
    • p and q are values in the tree.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1740.Find Distance in a Binary Tree/images/binarytree.png b/assets/1700-1799/1740.Find Distance in a Binary Tree/images/binarytree.png new file mode 100644 index 00000000..2ad942c3 Binary files /dev/null and b/assets/1700-1799/1740.Find Distance in a Binary Tree/images/binarytree.png differ diff --git a/assets/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md b/assets/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md new file mode 100644 index 00000000..45e71547 --- /dev/null +++ b/assets/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md @@ -0,0 +1,76 @@ +# [1741. Find Total Time Spent by Each Employee](https://leetcode.com/problems/find-total-time-spent-by-each-employee) + + + +## Description + +

    Table: Employees

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| emp_id      | int  |
    +| event_day   | date |
    +| in_time     | int  |
    +| out_time    | int  |
    ++-------------+------+
    +(emp_id, event_day, in_time) is the primary key of this table.
    +The table shows the employees' entries and exits in an office.
    +event_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute at which they left the office.
    +in_time and out_time are between 1 and 1440.
    +It is guaranteed that no two events on the same day intersect in time, and in_time < out_time.
    +
    + +

     

    + +

    Write an SQL query to calculate the total time in minutes spent by each employee on each day at the office. Note that within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is out_time - in_time.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +
    +Employees table:
    ++--------+------------+---------+----------+
    +| emp_id | event_day  | in_time | out_time |
    ++--------+------------+---------+----------+
    +| 1      | 2020-11-28 | 4       | 32       |
    +| 1      | 2020-11-28 | 55      | 200      |
    +| 1      | 2020-12-03 | 1       | 42       |
    +| 2      | 2020-11-28 | 3       | 33       |
    +| 2      | 2020-12-09 | 47      | 74       |
    ++--------+------------+---------+----------+
    +Result table:
    ++------------+--------+------------+
    +| day        | emp_id | total_time |
    ++------------+--------+------------+
    +| 2020-11-28 | 1      | 173        |
    +| 2020-11-28 | 2      | 30         |
    +| 2020-12-03 | 1      | 41         |
    +| 2020-12-09 | 2      | 27         |
    ++------------+--------+------------+
    +Employee 1 has three events: two on day 2020-11-28 with a total of (32 - 4) + (200 - 55) = 173, and one on day 2020-12-03 with a total of (42 - 1) = 41.
    +Employee 2 has two events: one on day 2020-11-28 with a total of (33 - 3) = 30, and one on day 2020-12-09 with a total of (74 - 47) = 27.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + event_day AS day, + emp_id, + SUM(out_time - in_time) AS total_time +FROM + Employees +GROUP BY + emp_id, event_day; +``` + + diff --git a/assets/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md b/assets/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md new file mode 100644 index 00000000..a40aabdd --- /dev/null +++ b/assets/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md @@ -0,0 +1,76 @@ +# [1742. Maximum Number of Balls in a Box](https://leetcode.com/problems/maximum-number-of-balls-in-a-box) + + + +## Description + +

    You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.

    + +

    Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.

    + +

    Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.

    + +

     

    +

    Example 1:

    + +
    +Input: lowLimit = 1, highLimit = 10
    +Output: 2
    +Explanation:
    +Box Number:  1 2 3 4 5 6 7 8 9 10 11 ...
    +Ball Count:  2 1 1 1 1 1 1 1 1 0  0  ...
    +Box 1 has the most number of balls with 2 balls.
    + +

    Example 2:

    + +
    +Input: lowLimit = 5, highLimit = 15
    +Output: 2
    +Explanation:
    +Box Number:  1 2 3 4 5 6 7 8 9 10 11 ...
    +Ball Count:  1 1 1 1 2 2 1 1 1 0  0  ...
    +Boxes 5 and 6 have the most number of balls with 2 balls in each.
    +
    + +

    Example 3:

    + +
    +Input: lowLimit = 19, highLimit = 28
    +Output: 2
    +Explanation:
    +Box Number:  1 2 3 4 5 6 7 8 9 10 11 12 ...
    +Ball Count:  0 1 1 1 1 1 1 1 1 2  0  0  ...
    +Box 10 has the most number of balls with 2 balls.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= lowLimit <= highLimit <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md b/assets/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md new file mode 100644 index 00000000..d529d614 --- /dev/null +++ b/assets/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md @@ -0,0 +1,76 @@ +# [1743. Restore the Array From Adjacent Pairs](https://leetcode.com/problems/restore-the-array-from-adjacent-pairs) + + + +## Description + +

    There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.

    + +

    You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.

    + +

    It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.

    + +

    Return the original array nums. If there are multiple solutions, return any of them.

    + +

     

    +

    Example 1:

    + +
    +Input: adjacentPairs = [[2,1],[3,4],[3,2]]
    +Output: [1,2,3,4]
    +Explanation: This array has all its adjacent pairs in adjacentPairs.
    +Notice that adjacentPairs[i] may not be in left-to-right order.
    +
    + +

    Example 2:

    + +
    +Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]
    +Output: [-2,4,1,-3]
    +Explanation: There can be negative numbers.
    +Another solution is [-3,1,4,-2], which would also be accepted.
    +
    + +

    Example 3:

    + +
    +Input: adjacentPairs = [[100000,-100000]]
    +Output: [100000,-100000]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • nums.length == n
    • +
    • adjacentPairs.length == n - 1
    • +
    • adjacentPairs[i].length == 2
    • +
    • 2 <= n <= 105
    • +
    • -105 <= nums[i], ui, vi <= 105
    • +
    • There exists some nums that has adjacentPairs as its pairs.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md b/assets/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md new file mode 100644 index 00000000..6e235cd3 --- /dev/null +++ b/assets/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md @@ -0,0 +1,78 @@ +# [1744. Can You Eat Your Favorite Candy on Your Favorite Day](https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day) + + + +## Description + +

    You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].

    + +

    You play a game with the following rules:

    + +
      +
    • You start eating candies on day 0.
    • +
    • You cannot eat any candy of type i unless you have eaten all candies of type i - 1.
    • +
    • You must eat at least one candy per day until you have eaten all the candies.
    • +
    + +

    Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.

    + +

    Return the constructed array answer.

    + +

     

    +

    Example 1:

    + +
    +Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
    +Output: [true,false,true]
    +Explanation:
    +1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.
    +2- You can eat at most 4 candies each day.
    +   If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.
    +   On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.
    +3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.
    +
    + +

    Example 2:

    + +
    +Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
    +Output: [false,true,true,false,false]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= candiesCount.length <= 105
    • +
    • 1 <= candiesCount[i] <= 105
    • +
    • 1 <= queries.length <= 105
    • +
    • queries[i].length == 3
    • +
    • 0 <= favoriteTypei < candiesCount.length
    • +
    • 0 <= favoriteDayi <= 109
    • +
    • 1 <= dailyCapi <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1745.Palindrome Partitioning IV/README_EN.md b/assets/1700-1799/1745.Palindrome Partitioning IV/README_EN.md new file mode 100644 index 00000000..1a768f6c --- /dev/null +++ b/assets/1700-1799/1745.Palindrome Partitioning IV/README_EN.md @@ -0,0 +1,59 @@ +# [1745. Palindrome Partitioning IV](https://leetcode.com/problems/palindrome-partitioning-iv) + + + +## Description + +

    Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​

    + +

    A string is said to be palindrome if it the same string when reversed.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcbdd"
    +Output: true
    +Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.
    +
    + +

    Example 2:

    + +
    +Input: s = "bcbddxy"
    +Output: false
    +Explanation: s cannot be split into 3 palindromes.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= s.length <= 2000
    • +
    • s​​​​​​ consists only of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md b/assets/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md new file mode 100644 index 00000000..398bf384 --- /dev/null +++ b/assets/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md @@ -0,0 +1,78 @@ +# [1746. Maximum Subarray Sum After One Operation](https://leetcode.com/problems/maximum-subarray-sum-after-one-operation) + + + +## Description + +

    You are given an integer array nums. You must perform exactly one operation where you can replace one element nums[i] with nums[i] * nums[i]

    + + + +

    Return the maximum possible subarray sum after exactly one operation. The subarray must be non-empty.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [2,-1,-4,-3]
    +
    +Output: 17
    +
    +Explanation: You can perform the operation on index 2 (0-indexed) to make nums = [2,-1,16,-3]. Now, the maximum subarray sum is 2 + -1 + 16 = 17.
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,-1,1,1,-1,-1,1]
    +
    +Output: 4
    +
    +Explanation: You can perform the operation on index 1 (0-indexed) to make nums = [1,1,1,1,-1,-1,1]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1747.Leetflex Banned Accounts/README_EN.md b/assets/1700-1799/1747.Leetflex Banned Accounts/README_EN.md new file mode 100644 index 00000000..fc3b7fef --- /dev/null +++ b/assets/1700-1799/1747.Leetflex Banned Accounts/README_EN.md @@ -0,0 +1,123 @@ +# [1747. Leetflex Banned Accounts](https://leetcode.com/problems/leetflex-banned-accounts) + + + +## Description + +

    Table: LogInfo

    + + + +
    +
    ++-------------+----------+
    +
    +| Column Name | Type     |
    +
    ++-------------+----------+
    +
    +| account_id  | int      |
    +
    +| ip_address  | int      |
    +
    +| login       | datetime |
    +
    +| logout      | datetime |
    +
    ++-------------+----------+
    +
    +There is no primary key for this table, and it may contain duplicates.
    +
    +The table contains information about the login and logout dates of Leetflex accounts. It also contains the IP address from which the account logged in and out.
    +
    +It is guaranteed that the logout time is after the login time.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to find the account_id of the accounts that should be banned from Leetflex. An account should be banned if it was logged in at some moment from two different IP addresses.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +LogInfo table:
    +
    ++------------+------------+---------------------+---------------------+
    +
    +| account_id | ip_address | login               | logout              |
    +
    ++------------+------------+---------------------+---------------------+
    +
    +| 1          | 1          | 2021-02-01 09:00:00 | 2021-02-01 09:30:00 |
    +
    +| 1          | 2          | 2021-02-01 08:00:00 | 2021-02-01 11:30:00 |
    +
    +| 2          | 6          | 2021-02-01 20:30:00 | 2021-02-01 22:00:00 |
    +
    +| 2          | 7          | 2021-02-02 20:30:00 | 2021-02-02 22:00:00 |
    +
    +| 3          | 9          | 2021-02-01 16:00:00 | 2021-02-01 16:59:59 |
    +
    +| 3          | 13         | 2021-02-01 17:00:00 | 2021-02-01 17:59:59 |
    +
    +| 4          | 10         | 2021-02-01 16:00:00 | 2021-02-01 17:00:00 |
    +
    +| 4          | 11         | 2021-02-01 17:00:00 | 2021-02-01 17:59:59 |
    +
    ++------------+------------+---------------------+---------------------+
    +
    +
    +
    +Result table:
    +
    ++------------+
    +
    +| account_id |
    +
    ++------------+
    +
    +| 1          |
    +
    +| 4          |
    +
    ++------------+
    +
    +Account ID 1 --> The account was active from "2021-02-01 09:00:00" to "2021-02-01 09:30:00" with two different IP addresses (1 and 2). It should be banned.
    +
    +Account ID 2 --> The account was active from two different addresses (6, 7) but in two different times.
    +
    +Account ID 3 --> The account was active from two different addresses (9, 13) on the same day but they do not intersect at any moment.
    +
    +Account ID 4 --> The account was active from "2021-02-01 17:00:00" to "2021-02-01 17:00:00" with two different IP addresses (10 and 11). It should be banned.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1700-1799/1748.Sum of Unique Elements/README_EN.md b/assets/1700-1799/1748.Sum of Unique Elements/README_EN.md new file mode 100644 index 00000000..4b0ce707 --- /dev/null +++ b/assets/1700-1799/1748.Sum of Unique Elements/README_EN.md @@ -0,0 +1,85 @@ +# [1748. Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements) + + + +## Description + +

    You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.

    + +

    Return the sum of all the unique elements of nums.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,2]
    +Output: 4
    +Explanation: The unique elements are [1,3], and the sum is 4.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,1,1,1,1]
    +Output: 0
    +Explanation: There are no unique elements, and the sum is 0.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3,4,5]
    +Output: 15
    +Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sumOfUnique(self, nums: List[int]) -> int: + counter = [0] * 101 + for num in nums: + counter[num] += 1 + return sum([i for i in range(1, 101) if counter[i] == 1]) +``` + +### **Java** + +```java +class Solution { + public int sumOfUnique(int[] nums) { + int[] counter = new int[101]; + for (int num : nums) { + ++counter[num]; + } + int res = 0; + for (int i = 1; i < 101; ++i) { + if (counter[i] == 1) { + res += i; + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md b/assets/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md new file mode 100644 index 00000000..a0af2f93 --- /dev/null +++ b/assets/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md @@ -0,0 +1,66 @@ +# [1749. Maximum Absolute Sum of Any Subarray](https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray) + + + +## Description + +

    You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr).

    + +

    Return the maximum absolute sum of any (possibly empty) subarray of nums.

    + +

    Note that abs(x) is defined as follows:

    + +
      +
    • If x is a negative integer, then abs(x) = -x.
    • +
    • If x is a non-negative integer, then abs(x) = x.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,-3,2,3,-4]
    +Output: 5
    +Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,-5,1,-4,3,-2]
    +Output: 8
    +Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md b/assets/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md new file mode 100644 index 00000000..2db3eda9 --- /dev/null +++ b/assets/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md @@ -0,0 +1,80 @@ +# [1750. Minimum Length of String After Deleting Similar Ends](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends) + + + +## Description + +

    Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:

    + +
      +
    1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
    2. +
    3. Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
    4. +
    5. The prefix and the suffix should not intersect at any index.
    6. +
    7. The characters from the prefix and suffix must be the same.
    8. +
    9. Delete both the prefix and the suffix.
    10. +
    + +

    Return the minimum length of s after performing the above operation any number of times (possibly zero times).

    + +

     

    +

    Example 1:

    + +
    +Input: s = "ca"
    +Output: 2
    +Explanation: You can't remove any characters, so the string stays as is.
    +
    + +

    Example 2:

    + +
    +Input: s = "cabaabac"
    +Output: 0
    +Explanation: An optimal sequence of operations is:
    +- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
    +- Take prefix = "a" and suffix = "a" and remove them, s = "baab".
    +- Take prefix = "b" and suffix = "b" and remove them, s = "aa".
    +- Take prefix = "a" and suffix = "a" and remove them, s = "".
    + +

    Example 3:

    + +
    +Input: s = "aabccabba"
    +Output: 3
    +Explanation: An optimal sequence of operations is:
    +- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
    +- Take prefix = "b" and suffix = "bb" and remove them, s = "cca".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s only consists of characters 'a', 'b', and 'c'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md new file mode 100644 index 00000000..ef3bdc63 --- /dev/null +++ b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md @@ -0,0 +1,75 @@ +# [1751. Maximum Number of Events That Can Be Attended II](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii) + + + +## Description + +

    You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.

    + +

    You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.

    + +

    Return the maximum sum of values that you can receive by attending events.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
    +Output: 7
    +Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
    + +

    Example 2:

    + +

    + +
    +Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
    +Output: 10
    +Explanation: Choose event 2 for a total value of 10.
    +Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.
    + +

    Example 3:

    + +

    + +
    +Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
    +Output: 9
    +Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= events.length
    • +
    • 1 <= k * events.length <= 106
    • +
    • 1 <= startDayi <= endDayi <= 109
    • +
    • 1 <= valuei <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60048-pm.png b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60048-pm.png new file mode 100644 index 00000000..98bc460a Binary files /dev/null and b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60048-pm.png differ diff --git a/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60150-pm.png b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60150-pm.png new file mode 100644 index 00000000..2fa4b4a6 Binary files /dev/null and b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60150-pm.png differ diff --git a/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60703-pm.png b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60703-pm.png new file mode 100644 index 00000000..c2343c48 Binary files /dev/null and b/assets/1700-1799/1751.Maximum Number of Events That Can Be Attended II/images/screenshot-2021-01-11-at-60703-pm.png differ diff --git a/assets/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md b/assets/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md new file mode 100644 index 00000000..d56f84ec --- /dev/null +++ b/assets/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md @@ -0,0 +1,89 @@ +# [1752. Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated) + + + +## Description + +

    Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.

    + +

    There may be duplicates in the original array.

    + +

    Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [3,4,5,1,2]
    +Output: true
    +Explanation: [1,2,3,4,5] is the original sorted array.
    +You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,1,3,4]
    +Output: false
    +Explanation: There is no sorted array once rotated that can make nums.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3]
    +Output: true
    +Explanation: [1,2,3] is the original sorted array.
    +You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
    +
    + +

    Example 4:

    + +
    +Input: nums = [1,1,1]
    +Output: true
    +Explanation: [1,1,1] is the original sorted array.
    +You can rotate any number of positions to make nums.
    +
    + +

    Example 5:

    + +
    +Input: nums = [2,1]
    +Output: true
    +Explanation: [1,2] is the original sorted array.
    +You can rotate the array by x = 5 positions to begin on the element of value 2: [2,1].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md b/assets/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md new file mode 100644 index 00000000..ffe9aec0 --- /dev/null +++ b/assets/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md @@ -0,0 +1,82 @@ +# [1753. Maximum Score From Removing Stones](https://leetcode.com/problems/maximum-score-from-removing-stones) + + + +## Description + +

    You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).

    + +

    Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.

    + +

     

    +

    Example 1:

    + +
    +Input: a = 2, b = 4, c = 6
    +Output: 6
    +Explanation: The starting state is (2, 4, 6). One optimal set of moves is:
    +- Take from 1st and 3rd piles, state is now (1, 4, 5)
    +- Take from 1st and 3rd piles, state is now (0, 4, 4)
    +- Take from 2nd and 3rd piles, state is now (0, 3, 3)
    +- Take from 2nd and 3rd piles, state is now (0, 2, 2)
    +- Take from 2nd and 3rd piles, state is now (0, 1, 1)
    +- Take from 2nd and 3rd piles, state is now (0, 0, 0)
    +There are fewer than two non-empty piles, so the game ends. Total: 6 points.
    +
    + +

    Example 2:

    + +
    +Input: a = 4, b = 4, c = 6
    +Output: 7
    +Explanation: The starting state is (4, 4, 6). One optimal set of moves is:
    +- Take from 1st and 2nd piles, state is now (3, 3, 6)
    +- Take from 1st and 3rd piles, state is now (2, 3, 5)
    +- Take from 1st and 3rd piles, state is now (1, 3, 4)
    +- Take from 1st and 3rd piles, state is now (0, 3, 3)
    +- Take from 2nd and 3rd piles, state is now (0, 2, 2)
    +- Take from 2nd and 3rd piles, state is now (0, 1, 1)
    +- Take from 2nd and 3rd piles, state is now (0, 0, 0)
    +There are fewer than two non-empty piles, so the game ends. Total: 7 points.
    +
    + +

    Example 3:

    + +
    +Input: a = 1, b = 8, c = 8
    +Output: 8
    +Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.
    +After that, there are fewer than two non-empty piles, so the game ends.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= a, b, c <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md b/assets/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md new file mode 100644 index 00000000..65cf2c10 --- /dev/null +++ b/assets/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md @@ -0,0 +1,80 @@ +# [1754. Largest Merge Of Two Strings](https://leetcode.com/problems/largest-merge-of-two-strings) + + + +## Description + +

    You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options:

    + +
      +
    • If word1 is non-empty, append the first character in word1 to merge and delete it from word1. + +
        +
      • For example, if word1 = "abc" and merge = "dv", then after choosing this operation, word1 = "bc" and merge = "dva".
      • +
      +
    • +
    • If word2 is non-empty, append the first character in word2 to merge and delete it from word2. +
        +
      • For example, if word2 = "abc" and merge = "", then after choosing this operation, word2 = "bc" and merge = "a".
      • +
      +
    • +
    + +

    Return the lexicographically largest merge you can construct.

    + +

    A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.

    + +

     

    +

    Example 1:

    + +
    +Input: word1 = "cabaa", word2 = "bcaaa"
    +Output: "cbcabaaaaa"
    +Explanation: One way to get the lexicographically largest merge is:
    +- Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa"
    +- Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa"
    +- Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa"
    +- Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa"
    +- Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa"
    +- Append the remaining 5 a's from word1 and word2 at the end of merge.
    +
    + +

    Example 2:

    + +
    +Input: word1 = "abcabc", word2 = "abdcaba"
    +Output: "abdcabcabcaba"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word1.length, word2.length <= 3000
    • +
    • word1 and word2 consist only of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1755.Closest Subsequence Sum/README_EN.md b/assets/1700-1799/1755.Closest Subsequence Sum/README_EN.md new file mode 100644 index 00000000..f4d991b0 --- /dev/null +++ b/assets/1700-1799/1755.Closest Subsequence Sum/README_EN.md @@ -0,0 +1,73 @@ +# [1755. Closest Subsequence Sum](https://leetcode.com/problems/closest-subsequence-sum) + + + +## Description + +

    You are given an integer array nums and an integer goal.

    + +

    You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).

    + +

    Return the minimum possible value of abs(sum - goal).

    + +

    Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [5,-7,3,5], goal = 6
    +Output: 0
    +Explanation: Choose the whole array as a subsequence, with a sum of 6.
    +This is equal to the goal, so the absolute difference is 0.
    +
    + +

    Example 2:

    + +
    +Input: nums = [7,-9,15,-2], goal = -5
    +Output: 1
    +Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.
    +The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3], goal = -7
    +Output: 7
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 40
    • +
    • -107 <= nums[i] <= 107
    • +
    • -109 <= goal <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1756.Design Most Recently Used Queue/README_EN.md b/assets/1700-1799/1756.Design Most Recently Used Queue/README_EN.md new file mode 100644 index 00000000..631aefb8 --- /dev/null +++ b/assets/1700-1799/1756.Design Most Recently Used Queue/README_EN.md @@ -0,0 +1,98 @@ +# [1756. Design Most Recently Used Queue](https://leetcode.com/problems/design-most-recently-used-queue) + + + +## Description + +

    Design a queue-like data structure that moves the most recently used element to the end of the queue.

    + + + +

    Implement the MRUQueue class:

    + + + +
      +
    • MRUQueue(int n) constructs the MRUQueue with n elements: [1,2,3,...,n].
    • +
    • fetch(int k) moves the kth element (1-indexed) to the end of the queue and returns it.
    • +
    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input:
    +
    +["MRUQueue", "fetch", "fetch", "fetch", "fetch"]
    +
    +[[8], [3], [5], [2], [8]]
    +
    +Output:
    +
    +[null, 3, 6, 2, 2]
    +
    +
    +
    +Explanation:
    +
    +MRUQueue mRUQueue = new MRUQueue(8); // Initializes the queue to [1,2,3,4,5,6,7,8].
    +
    +mRUQueue.fetch(3); // Moves the 3rd element (3) to the end of the queue to become [1,2,4,5,6,7,8,3] and returns it.
    +
    +mRUQueue.fetch(5); // Moves the 5th element (6) to the end of the queue to become [1,2,4,5,7,8,3,6] and returns it.
    +
    +mRUQueue.fetch(2); // Moves the 2nd element (2) to the end of the queue to become [1,4,5,7,8,3,6,2] and returns it.
    +
    +mRUQueue.fetch(8); // The 8th element (2) is already at the end of the queue so just return it.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= n <= 2000
    • +
    • 1 <= k <= n
    • +
    • At most 2000 calls will be made to fetch.
    • +
    + + + +

     

    + +Follow up: Finding an O(n) algorithm per fetch is a bit easy. Can you find an algorithm with a better complexity for each fetch call? + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md b/assets/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md new file mode 100644 index 00000000..2fc35260 --- /dev/null +++ b/assets/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md @@ -0,0 +1,70 @@ +# [1757. Recyclable and Low Fat Products](https://leetcode.com/problems/recyclable-and-low-fat-products) + + + +## Description + +

    Table: Products

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_id  | int     |
    +| low_fats    | enum    |
    +| recyclable  | enum    |
    ++-------------+---------+
    +product_id is the primary key for this table.
    +low_fats is an ENUM of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
    +recyclable is an ENUM of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.
    + +

     

    + +

    Write an SQL query to find the ids of products that are both low fat and recyclable.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Products table:
    ++-------------+----------+------------+
    +| product_id  | low_fats | recyclable |
    ++-------------+----------+------------+
    +| 0           | Y        | N          |
    +| 1           | Y        | Y          |
    +| 2           | N        | Y          |
    +| 3           | Y        | Y          |
    +| 4           | N        | N          |
    ++-------------+----------+------------+
    +Result table:
    ++-------------+
    +| product_id  |
    ++-------------+
    +| 1           |
    +| 3           |
    ++-------------+
    +Only products 1 and 3 are both low fat and recyclable.
    +
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + product_id +FROM + Products +WHERE + low_fats = 'Y' +AND recyclable = 'Y'; +``` + + diff --git a/assets/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md b/assets/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md new file mode 100644 index 00000000..cd5d84b3 --- /dev/null +++ b/assets/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md @@ -0,0 +1,97 @@ +# [1758. Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string) + + + +## Description + +

    You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.

    + +

    The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.

    + +

    Return the minimum number of operations needed to make s alternating.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "0100"
    +Output: 1
    +Explanation: If you change the last character to '1', s will be "0101", which is alternating.
    +
    + +

    Example 2:

    + +
    +Input: s = "10"
    +Output: 0
    +Explanation: s is already alternating.
    +
    + +

    Example 3:

    + +
    +Input: s = "1111"
    +Output: 2
    +Explanation: You need two operations to reach "0101" or "1010".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s[i] is either '0' or '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minOperations(self, s: str) -> int: + cnt = 0 + for i, c in enumerate(s): + cnt += c == '01'[i & 1] + return min(cnt, len(s) - cnt) +``` + +### **Java** + +```java +class Solution { + public int minOperations(String s) { + int cnt = 0, n = s.length(); + for (int i = 0; i < n; ++i) { + cnt += (s.charAt(i) == "01".charAt(i & 1) ? 1 : 0); + } + return Math.min(cnt, n - cnt); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minOperations(string s) { + int cnt = 0, n = s.size(); + for (int i = 0; i < n; ++i) { + cnt += s[i] == "01"[i & 1]; + } + return min(cnt, n - cnt); + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md b/assets/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md new file mode 100644 index 00000000..e0605843 --- /dev/null +++ b/assets/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md @@ -0,0 +1,112 @@ +# [1759. Count Number of Homogenous Substrings](https://leetcode.com/problems/count-number-of-homogenous-substrings) + + + +## Description + +

    Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.

    + + + +

    A string is homogenous if all the characters of the string are the same.

    + + + +

    A substring is a contiguous sequence of characters within a string.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: s = "abbcccaa"
    +
    +Output: 13
    +
    +Explanation: The homogenous substrings are listed as below:
    +
    +"a"   appears 3 times.
    +
    +"aa"  appears 1 time.
    +
    +"b"   appears 2 times.
    +
    +"bb"  appears 1 time.
    +
    +"c"   appears 3 times.
    +
    +"cc"  appears 2 times.
    +
    +"ccc" appears 1 time.
    +
    +3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
    + + + +

    Example 2:

    + + + +
    +
    +Input: s = "xy"
    +
    +Output: 2
    +
    +Explanation: The homogenous substrings are "x" and "y".
    + + + +

    Example 3:

    + + + +
    +
    +Input: s = "zzzzz"
    +
    +Output: 15
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= s.length <= 105
    • +
    • s consists of lowercase letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md b/assets/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md new file mode 100644 index 00000000..0b30fecb --- /dev/null +++ b/assets/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md @@ -0,0 +1,171 @@ +# [1760. Minimum Limit of Balls in a Bag](https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag) + + + +## Description + +

    You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.

    + +

    You can perform the following operation at most maxOperations times:

    + +
      +
    • Take any bag of balls and divide it into two new bags with a positive number of balls. + +
        +
      • For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.
      • +
      +
    • + +
    + +

    Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.

    + +

    Return the minimum possible penalty after performing the operations.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [9], maxOperations = 2
    +Output: 3
    +Explanation: 
    +- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].
    +- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].
    +The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,4,8,2], maxOperations = 4
    +Output: 2
    +Explanation:
    +- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
    +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
    +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
    +- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
    +The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.
    +
    + +

    Example 3:

    + +
    +Input: nums = [7,17], maxOperations = 2
    +Output: 7
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= maxOperations, nums[i] <= 109
    • +
    + +## Solutions + +Binary search. + + + +### **Python3** + +```python +class Solution: + def minimumSize(self, nums: List[int], maxOperations: int) -> int: + left, right = 1, max(nums) + while left < right: + mid = (left + right) >> 1 + ops = sum([(num - 1) // mid for num in nums]) + if ops <= maxOperations: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int minimumSize(int[] nums, int maxOperations) { + int left = 1, right = 1000000000; + while (left < right) { + int mid = (left + right) >>> 1; + long ops = 0; + for (int num : nums) { + ops += (num - 1) / mid; + } + if (ops <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minimumSize(vector& nums, int maxOperations) { + int left = 1, right = *max_element(nums.begin(), nums.end()); + while (left < right) { + int mid = left + (right - left >> 1); + long long ops = 0; + for (int num : nums) { + ops += (num - 1) / mid; + } + if (ops <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func minimumSize(nums []int, maxOperations int) int { + left, right := 1, max(nums) + for left < right { + mid := (left + right) >> 1 + var ops int + for _, num := range nums { + ops += (num - 1) / mid + } + if ops <= maxOperations { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func max(nums []int) int { + res := 0 + for _, num := range nums { + if res < num { + res = num + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md b/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md new file mode 100644 index 00000000..12cd08bf --- /dev/null +++ b/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md @@ -0,0 +1,70 @@ +# [1761. Minimum Degree of a Connected Trio in a Graph](https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph) + + + +## Description + +

    You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi.

    + +

    A connected trio is a set of three nodes where there is an edge between every pair of them.

    + +

    The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.

    + +

    Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]
    +Output: 3
    +Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.
    +
    + +

    Example 2:

    + +
    +Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]
    +Output: 0
    +Explanation: There are exactly three trios:
    +1) [1,4,3] with degree 0.
    +2) [2,5,6] with degree 2.
    +3) [5,6,7] with degree 2.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 400
    • +
    • edges[i].length == 2
    • +
    • 1 <= edges.length <= n * (n-1) / 2
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • There are no repeated edges.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/images/trios1.png b/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/images/trios1.png new file mode 100644 index 00000000..94dbb455 Binary files /dev/null and b/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/images/trios1.png differ diff --git a/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/images/trios2.png b/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/images/trios2.png new file mode 100644 index 00000000..afa084af Binary files /dev/null and b/assets/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/images/trios2.png differ diff --git a/assets/1700-1799/1762.Buildings With an Ocean View/README_EN.md b/assets/1700-1799/1762.Buildings With an Ocean View/README_EN.md new file mode 100644 index 00000000..9bcc681a --- /dev/null +++ b/assets/1700-1799/1762.Buildings With an Ocean View/README_EN.md @@ -0,0 +1,112 @@ +# [1762. Buildings With an Ocean View](https://leetcode.com/problems/buildings-with-an-ocean-view) + + + +## Description + +

    There are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line.

    + + + +

    The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.

    + + + +

    Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: heights = [4,2,3,1]
    +
    +Output: [0,2,3]
    +
    +Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: heights = [4,3,2,1]
    +
    +Output: [0,1,2,3]
    +
    +Explanation: All the buildings have an ocean view.
    + + + +

    Example 3:

    + + + +
    +
    +Input: heights = [1,3,2,4]
    +
    +Output: [3]
    +
    +Explanation: Only building 3 has an ocean view.
    + + + +

    Example 4:

    + + + +
    +
    +Input: heights = [2,2,2,2]
    +
    +Output: [3]
    +
    +Explanation: Buildings cannot see the ocean if there are buildings of the same height to its right.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= heights.length <= 105
    • +
    • 1 <= heights[i] <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1763.Longest Nice Substring/README_EN.md b/assets/1700-1799/1763.Longest Nice Substring/README_EN.md new file mode 100644 index 00000000..9be055ff --- /dev/null +++ b/assets/1700-1799/1763.Longest Nice Substring/README_EN.md @@ -0,0 +1,74 @@ +# [1763. Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring) + + + +## Description + +

    A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not.

    + +

    Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "YazaAay"
    +Output: "aAa"
    +Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.
    +"aAa" is the longest nice substring.
    +
    + +

    Example 2:

    + +
    +Input: s = "Bb"
    +Output: "Bb"
    +Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.
    + +

    Example 3:

    + +
    +Input: s = "c"
    +Output: ""
    +Explanation: There are no nice substrings.
    + +

    Example 4:

    + +
    +Input: s = "dDzeE"
    +Output: "dD"
    +Explanation: Both "dD" and "eE" are the longest nice substrings.
    +As there are multiple longest nice substrings, return "dD" since it occurs earlier.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s consists of uppercase and lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md b/assets/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md new file mode 100644 index 00000000..a6622c15 --- /dev/null +++ b/assets/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md @@ -0,0 +1,77 @@ +# [1764. Form Array by Concatenating Subarrays of Another Array](https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array) + + + +## Description + +

    You are given a 2D integer array groups of length n. You are also given an integer array nums.

    + +

    You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).

    + +

    Return true if you can do this task, and false otherwise.

    + +

    Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.

    + +

     

    +

    Example 1:

    + +
    +Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
    +Output: true
    +Explanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].
    +These subarrays are disjoint as they share no common nums[k] element.
    +
    + +

    Example 2:

    + +
    +Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]
    +Output: false
    +Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.
    +[10,-2] must come before [1,2,3,4].
    +
    + +

    Example 3:

    + +
    +Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]
    +Output: false
    +Explanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.
    +They share a common elements nums[4] (0-indexed).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • groups.length == n
    • +
    • 1 <= n <= 103
    • +
    • 1 <= groups[i].length, sum(groups[i].length) <= 103
    • +
    • 1 <= nums.length <= 103
    • +
    • -107 <= groups[i][j], nums[k] <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1765.Map of Highest Peak/README_EN.md b/assets/1700-1799/1765.Map of Highest Peak/README_EN.md new file mode 100644 index 00000000..b2762a24 --- /dev/null +++ b/assets/1700-1799/1765.Map of Highest Peak/README_EN.md @@ -0,0 +1,83 @@ +# [1765. Map of Highest Peak](https://leetcode.com/problems/map-of-highest-peak) + + + +## Description + +

    You are given an integer matrix isWater of size m x n that represents a map of land and water cells.

    + +
      +
    • If isWater[i][j] == 0, cell (i, j) is a land cell.
    • +
    • If isWater[i][j] == 1, cell (i, j) is a water cell.
    • +
    + +

    You must assign each cell a height in a way that follows these rules:

    + +
      +
    • The height of each cell must be non-negative.
    • +
    • If the cell is a water cell, its height must be 0.
    • +
    • Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
    • +
    + +

    Find an assignment of heights such that the maximum height in the matrix is maximized.

    + +

    Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: isWater = [[0,1],[0,0]]
    +Output: [[1,0],[2,1]]
    +Explanation: The image shows the assigned heights of each cell.
    +The blue cell is the water cell, and the green cells are the land cells.
    +
    + +

    Example 2:

    + +

    + +
    +Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]
    +Output: [[1,1,0],[0,1,1],[1,2,2]]
    +Explanation: A height of 2 is the maximum possible height of any assignment.
    +Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == isWater.length
    • +
    • n == isWater[i].length
    • +
    • 1 <= m, n <= 1000
    • +
    • isWater[i][j] is 0 or 1.
    • +
    • There is at least one water cell.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1765.Map of Highest Peak/images/screenshot-2021-01-11-at-82045-am.png b/assets/1700-1799/1765.Map of Highest Peak/images/screenshot-2021-01-11-at-82045-am.png new file mode 100644 index 00000000..c8de5c1f Binary files /dev/null and b/assets/1700-1799/1765.Map of Highest Peak/images/screenshot-2021-01-11-at-82045-am.png differ diff --git a/assets/1700-1799/1765.Map of Highest Peak/images/screenshot-2021-01-11-at-82050-am.png b/assets/1700-1799/1765.Map of Highest Peak/images/screenshot-2021-01-11-at-82050-am.png new file mode 100644 index 00000000..6d1cadaf Binary files /dev/null and b/assets/1700-1799/1765.Map of Highest Peak/images/screenshot-2021-01-11-at-82050-am.png differ diff --git a/assets/1700-1799/1766.Tree of Coprimes/README_EN.md b/assets/1700-1799/1766.Tree of Coprimes/README_EN.md new file mode 100644 index 00000000..63c27b28 --- /dev/null +++ b/assets/1700-1799/1766.Tree of Coprimes/README_EN.md @@ -0,0 +1,79 @@ +# [1766. Tree of Coprimes](https://leetcode.com/problems/tree-of-coprimes) + + + +## Description + +

    There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.

    + +

    To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.

    + +

    Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.

    + +

    An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.

    + +

    Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
    +Output: [-1,0,0,1]
    +Explanation: In the above figure, each node's value is in parentheses.
    +- Node 0 has no coprime ancestors.
    +- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).
    +- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's
    +  value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.
    +- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its
    +  closest valid ancestor.
    +
    + +

    Example 2:

    + +

    + +
    +Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
    +Output: [-1,0,-1,0,0,0,-1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • nums.length == n
    • +
    • 1 <= nums[i] <= 50
    • +
    • 1 <= n <= 105
    • +
    • edges.length == n - 1
    • +
    • edges[j].length == 2
    • +
    • 0 <= uj, vj < n
    • +
    • uj != vj
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1766.Tree of Coprimes/images/untitled-diagram.png b/assets/1700-1799/1766.Tree of Coprimes/images/untitled-diagram.png new file mode 100644 index 00000000..4bbebf9f Binary files /dev/null and b/assets/1700-1799/1766.Tree of Coprimes/images/untitled-diagram.png differ diff --git a/assets/1700-1799/1766.Tree of Coprimes/images/untitled-diagram1.png b/assets/1700-1799/1766.Tree of Coprimes/images/untitled-diagram1.png new file mode 100644 index 00000000..611ed44c Binary files /dev/null and b/assets/1700-1799/1766.Tree of Coprimes/images/untitled-diagram1.png differ diff --git a/assets/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md b/assets/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md new file mode 100644 index 00000000..4518f046 --- /dev/null +++ b/assets/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md @@ -0,0 +1,92 @@ +# [1767. Find the Subtasks That Did Not Execute](https://leetcode.com/problems/find-the-subtasks-that-did-not-execute) + + + +## Description + +

    Table: Tasks

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| task_id        | int     |
    +| subtasks_count | int     |
    ++----------------+---------+
    +task_id is the primary key for this table.
    +Each row in this table indicates that task_id was divided into subtasks_count subtasks labelled from 1 to subtasks_count.
    +It is guaranteed that 2 <= subtasks_count <= 20.
    +
    + +

     

    + +

    Table: Executed

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| task_id       | int     |
    +| subtask_id    | int     |
    ++---------------+---------+
    +(task_id, subtask_id) is the primary key for this table.
    +Each row in this table indicates that for the task task_id, the subtask with ID subtask_id was executed successfully.
    +It is guaranteed that subtask_id <= subtasks_count for each task_id.
    + +

     

    + +

    Write an SQL query to report the IDs of the missing subtasks for each task_id.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Tasks table:
    ++---------+----------------+
    +| task_id | subtasks_count |
    ++---------+----------------+
    +| 1       | 3              |
    +| 2       | 2              |
    +| 3       | 4              |
    ++---------+----------------+
    +
    +Executed table:
    ++---------+------------+
    +| task_id | subtask_id |
    ++---------+------------+
    +| 1       | 2          |
    +| 3       | 1          |
    +| 3       | 2          |
    +| 3       | 3          |
    +| 3       | 4          |
    ++---------+------------+
    +
    +Result table:
    ++---------+------------+
    +| task_id | subtask_id |
    ++---------+------------+
    +| 1       | 1          |
    +| 1       | 3          |
    +| 2       | 1          |
    +| 2       | 2          |
    ++---------+------------+
    +Task 1 was divided into 3 subtasks (1, 2, 3). Only subtask 2 was executed successfully, so we include (1, 1) and (1, 3) in the answer.
    +Task 2 was divided into 2 subtasks (1, 2). No subtask was executed successfully, so we include (2, 1) and (2, 2) in the answer.
    +Task 3 was divided into 4 subtasks (1, 2, 3, 4). All of the subtasks were executed successfully.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1700-1799/1768.Merge Strings Alternately/README_EN.md b/assets/1700-1799/1768.Merge Strings Alternately/README_EN.md new file mode 100644 index 00000000..26f659ac --- /dev/null +++ b/assets/1700-1799/1768.Merge Strings Alternately/README_EN.md @@ -0,0 +1,161 @@ +# [1768. Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately) + + + +## Description + +

    You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

    + + + +

    Return the merged string.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: word1 = "abc", word2 = "pqr"
    +
    +Output: "apbqcr"
    +
    +Explanation: The merged string will be merged as so:
    +
    +word1:  a   b   c
    +
    +word2:    p   q   r
    +
    +merged: a p b q c r
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: word1 = "ab", word2 = "pqrs"
    +
    +Output: "apbqrs"
    +
    +Explanation: Notice that as word2 is longer, "rs" is appended to the end.
    +
    +word1:  a   b 
    +
    +word2:    p   q   r   s
    +
    +merged: a p b q   r   s
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: word1 = "abcd", word2 = "pq"
    +
    +Output: "apbqcd"
    +
    +Explanation: Notice that as word1 is longer, "cd" is appended to the end.
    +
    +word1:  a   b   c   d
    +
    +word2:    p   q 
    +
    +merged: a p b q c   d
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= word1.length, word2.length <= 100
    • +
    • word1 and word2 consist of lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + i, m, n = 0, len(word1), len(word2) + res = [] + while i < m or i < n: + if i < m: + res.append(word1[i]) + if i < n: + res.append(word2[i]) + i += 1 + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String mergeAlternately(String word1, String word2) { + int m = word1.length(), n = word2.length(); + StringBuilder res = new StringBuilder(); + for (int i = 0; i < m || i < n; ++i) { + if (i < m) { + res.append(word1.charAt(i)); + } + if (i < n) { + res.append(word2.charAt(i)); + } + } + return res.toString(); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string mergeAlternately(string word1, string word2) { + int m = word1.size(), n = word2.size(); + string res; + for (int i = 0; i < m || i < n; ++i) { + if (i < m) { + res.push_back(word1[i]); + } + if (i < n) { + res.push_back(word2[i]); + } + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md b/assets/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md new file mode 100644 index 00000000..c325b812 --- /dev/null +++ b/assets/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md @@ -0,0 +1,65 @@ +# [1769. Minimum Number of Operations to Move All Balls to Each Box](https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box) + + + +## Description + +

    You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.

    + +

    In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.

    + +

    Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.

    + +

    Each answer[i] is calculated considering the initial state of the boxes.

    + +

     

    +

    Example 1:

    + +
    +Input: boxes = "110"
    +Output: [1,1,3]
    +Explanation: The answer for each box is as follows:
    +1) First box: you will have to move one ball from the second box to the first box in one operation.
    +2) Second box: you will have to move one ball from the first box to the second box in one operation.
    +3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
    +
    + +

    Example 2:

    + +
    +Input: boxes = "001011"
    +Output: [11,8,5,4,3,4]
    + +

     

    +

    Constraints:

    + +
      +
    • n == boxes.length
    • +
    • 1 <= n <= 2000
    • +
    • boxes[i] is either '0' or '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md b/assets/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md new file mode 100644 index 00000000..2ffb5794 --- /dev/null +++ b/assets/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md @@ -0,0 +1,79 @@ +# [1770. Maximum Score from Performing Multiplication Operations](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations) + + + +## Description + +

    You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed.

    + +

    You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will:

    + +
      +
    • Choose one integer x from either the start or the end of the array nums.
    • +
    • Add multipliers[i] * x to your score.
    • +
    • Remove x from the array nums.
    • +
    + +

    Return the maximum score after performing m operations.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3], multipliers = [3,2,1]
    +Output: 14
    +Explanation: An optimal solution is as follows:
    +- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
    +- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
    +- Choose from the end, [1], adding 1 * 1 = 1 to the score.
    +The total score is 9 + 4 + 1 = 14.
    + +

    Example 2:

    + +
    +Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
    +Output: 102
    +Explanation: An optimal solution is as follows:
    +- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.
    +- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.
    +- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.
    +- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.
    +- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. 
    +The total score is 50 + 15 - 9 + 4 + 42 = 102.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • m == multipliers.length
    • +
    • 1 <= m <= 103
    • +
    • m <= n <= 105
    • +
    • -1000 <= nums[i], multipliers[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md b/assets/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md new file mode 100644 index 00000000..34bb342e --- /dev/null +++ b/assets/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md @@ -0,0 +1,74 @@ +# [1771. Maximize Palindrome Length From Subsequences](https://leetcode.com/problems/maximize-palindrome-length-from-subsequences) + + + +## Description + +

    You are given two strings, word1 and word2. You want to construct a string in the following manner:

    + +
      +
    • Choose some non-empty subsequence subsequence1 from word1.
    • +
    • Choose some non-empty subsequence subsequence2 from word2.
    • +
    • Concatenate the subsequences: subsequence1 + subsequence2, to make the string.
    • +
    + +

    Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0.

    + +

    A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.

    + +

    A palindrome is a string that reads the same forward as well as backward.

    + +

     

    +

    Example 1:

    + +
    +Input: word1 = "cacb", word2 = "cbba"
    +Output: 5
    +Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome.
    + +

    Example 2:

    + +
    +Input: word1 = "ab", word2 = "ab"
    +Output: 3
    +Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome.
    + +

    Example 3:

    + +
    +Input: word1 = "aa", word2 = "bb"
    +Output: 0
    +Explanation: You cannot construct a palindrome from the described method, so return 0.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word1.length, word2.length <= 1000
    • +
    • word1 and word2 consist of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1772.Sort Features by Popularity/README_EN.md b/assets/1700-1799/1772.Sort Features by Popularity/README_EN.md new file mode 100644 index 00000000..a2d431b6 --- /dev/null +++ b/assets/1700-1799/1772.Sort Features by Popularity/README_EN.md @@ -0,0 +1,104 @@ +# [1772. Sort Features by Popularity](https://leetcode.com/problems/sort-features-by-popularity) + + + +## Description + +

    You are given a string array features where features[i] is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array responses, where each responses[i] is a string containing space-separated words.

    + +

    The popularity of a feature is the number of responses[i] that contain the feature. You want to sort the features in non-increasing order by their popularity. If two features have the same popularity, order them by their original index in features. Notice that one response could contain the same feature multiple times; this feature is only counted once in its popularity.

    + +

    Return the features in sorted order.

    + +

     

    +

    Example 1:

    + +
    +Input: features = ["cooler","lock","touch"], responses = ["i like cooler cooler","lock touch cool","locker like touch"]
    +Output: ["touch","cooler","lock"]
    +Explanation: appearances("cooler") = 1, appearances("lock") = 1, appearances("touch") = 2. Since "cooler" and "lock" both had 1 appearance, "cooler" comes first because "cooler" came first in the features array.
    +
    + +

    Example 2:

    + +
    +Input: features = ["a","aa","b","c"], responses = ["a","a aa","a a a a a","b a"]
    +Output: ["a","aa","b","c"]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= features.length <= 104
    • +
    • 1 <= features[i].length <= 10
    • +
    • features contains no duplicates.
    • +
    • features[i] consists of lowercase letters.
    • +
    • 1 <= responses.length <= 102
    • +
    • 1 <= responses[i].length <= 103
    • +
    • responses[i] consists of lowercase letters and spaces.
    • +
    • responses[i] contains no two consecutive spaces.
    • +
    • responses[i] has no leading or trailing spaces.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: + feature_set = set(features) + counter = collections.Counter() + for resp in responses: + for feat in set(resp.split(' ')): + if feat in feature_set: + counter[feat] += 1 + order = {feat: i for i, feat in enumerate(features)} + return sorted(features, key=lambda feat: (-counter[feat], order[feat])) +``` + +### **Java** + +```java +class Solution { + public String[] sortFeatures(String[] features, String[] responses) { + Set featureSet = new HashSet<>(); + Map order = new HashMap<>(); + for (int i = 0; i < features.length; ++i) { + featureSet.add(features[i]); + order.put(features[i], i); + } + + Map counter = new HashMap<>(); + for (String resp : responses) { + Set s = new HashSet<>(); + String[] words = resp.split(" "); + for (String word : words) { + s.add(word); + } + for (String word : s) { + if (featureSet.contains(word)) { + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + } + } + String[] copyFeatures = Arrays.copyOf(features, features.length); + Arrays.sort(copyFeatures, (a, b) -> { + int diff = counter.getOrDefault(b, 0) - counter.getOrDefault(a, 0); + return diff == 0 ? order.get(a) - order.get(b) : diff; + }); + return copyFeatures; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1773.Count Items Matching a Rule/README_EN.md b/assets/1700-1799/1773.Count Items Matching a Rule/README_EN.md new file mode 100644 index 00000000..839ed138 --- /dev/null +++ b/assets/1700-1799/1773.Count Items Matching a Rule/README_EN.md @@ -0,0 +1,68 @@ +# [1773. Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule) + + + +## Description + +

    You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.

    + +

    The ith item is said to match the rule if one of the following is true:

    + +
      +
    • ruleKey == "type" and ruleValue == typei.
    • +
    • ruleKey == "color" and ruleValue == colori.
    • +
    • ruleKey == "name" and ruleValue == namei.
    • +
    + +

    Return the number of items that match the given rule.

    + +

     

    +

    Example 1:

    + +
    +Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
    +Output: 1
    +Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].
    +
    + +

    Example 2:

    + +
    +Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
    +Output: 2
    +Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= items.length <= 104
    • +
    • 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
    • +
    • ruleKey is equal to either "type", "color", or "name".
    • +
    • All strings consist only of lowercase letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1774.Closest Dessert Cost/README_EN.md b/assets/1700-1799/1774.Closest Dessert Cost/README_EN.md new file mode 100644 index 00000000..288add74 --- /dev/null +++ b/assets/1700-1799/1774.Closest Dessert Cost/README_EN.md @@ -0,0 +1,102 @@ +# [1774. Closest Dessert Cost](https://leetcode.com/problems/closest-dessert-cost) + + + +## Description + +

    You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:

    + +
      +
    • There must be exactly one ice cream base.
    • +
    • You can add one or more types of topping or have no toppings at all.
    • +
    • There are at most two of each type of topping.
    • +
    + +

    You are given three inputs:

    + +
      +
    • baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.
    • +
    • toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.
    • +
    • target, an integer representing your target price for dessert.
    • +
    + +

    You want to make a dessert with a total cost as close to target as possible.

    + +

    Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.

    + +

     

    +

    Example 1:

    + +
    +Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10
    +Output: 10
    +Explanation: Consider the following combination (all 0-indexed):
    +- Choose base 1: cost 7
    +- Take 1 of topping 0: cost 1 x 3 = 3
    +- Take 0 of topping 1: cost 0 x 4 = 0
    +Total: 7 + 3 + 0 = 10.
    +
    + +

    Example 2:

    + +
    +Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
    +Output: 17
    +Explanation: Consider the following combination (all 0-indexed):
    +- Choose base 1: cost 3
    +- Take 1 of topping 0: cost 1 x 4 = 4
    +- Take 2 of topping 1: cost 2 x 5 = 10
    +- Take 0 of topping 2: cost 0 x 100 = 0
    +Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
    +
    + +

    Example 3:

    + +
    +Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9
    +Output: 8
    +Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
    +
    + +

    Example 4:

    + +
    +Input: baseCosts = [10], toppingCosts = [1], target = 1
    +Output: 10
    +Explanation: Notice that you don't have to have any toppings, but you must have exactly one base.
    + +

     

    +

    Constraints:

    + +
      +
    • n == baseCosts.length
    • +
    • m == toppingCosts.length
    • +
    • 1 <= n, m <= 10
    • +
    • 1 <= baseCosts[i], toppingCosts[i] <= 104
    • +
    • 1 <= target <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md b/assets/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md new file mode 100644 index 00000000..05fc5ee1 --- /dev/null +++ b/assets/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md @@ -0,0 +1,75 @@ +# [1775. Equal Sum Arrays With Minimum Number of Operations](https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations) + + + +## Description + +

    You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.

    + +

    In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.

    + +

    Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
    +Output: 3
    +Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
    +- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
    +- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
    +- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
    +Output: -1
    +Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
    +
    + +

    Example 3:

    + +
    +Input: nums1 = [6,6], nums2 = [1]
    +Output: 3
    +Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. 
    +- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
    +- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
    +- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 6
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1776.Car Fleet II/README_EN.md b/assets/1700-1799/1776.Car Fleet II/README_EN.md new file mode 100644 index 00000000..1c6e6d89 --- /dev/null +++ b/assets/1700-1799/1776.Car Fleet II/README_EN.md @@ -0,0 +1,66 @@ +# [1776. Car Fleet II](https://leetcode.com/problems/car-fleet-ii) + + + +## Description + +

    There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:

    + +
      +
    • positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.
    • +
    • speedi is the initial speed of the ith car in meters per second.
    • +
    + +

    For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.

    + +

    Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.

    + +

     

    +

    Example 1:

    + +
    +Input: cars = [[1,2],[2,1],[4,3],[7,2]]
    +Output: [1.00000,-1.00000,3.00000,-1.00000]
    +Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
    +
    + +

    Example 2:

    + +
    +Input: cars = [[3,4],[5,4],[6,3],[9,1]]
    +Output: [2.00000,1.00000,1.50000,-1.00000]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= cars.length <= 105
    • +
    • 1 <= positioni, speedi <= 106
    • +
    • positioni < positioni+1
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1777.Product's Price for Each Store/README_EN.md b/assets/1700-1799/1777.Product's Price for Each Store/README_EN.md new file mode 100644 index 00000000..65dc1178 --- /dev/null +++ b/assets/1700-1799/1777.Product's Price for Each Store/README_EN.md @@ -0,0 +1,107 @@ +# [1777. Product's Price for Each Store](https://leetcode.com/problems/products-price-for-each-store) + + + +## Description + +

    Table: Products

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| product_id  | int     |
    +
    +| store       | enum    |
    +
    +| price       | int     |
    +
    ++-------------+---------+
    +
    +(product_id,store) is the primary key for this table.
    +
    +store is an ENUM of type ('store1', 'store2', 'store3') where each represents the store this product is available at.
    +
    +price is the price of the product at this store.
    + + + +

     

    + + + +

    Write an SQL query to find the price of each product in each store.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Products table:
    +
    ++-------------+--------+-------+
    +
    +| product_id  | store  | price |
    +
    ++-------------+--------+-------+
    +
    +| 0           | store1 | 95    |
    +
    +| 0           | store3 | 105   |
    +
    +| 0           | store2 | 100   |
    +
    +| 1           | store1 | 70    |
    +
    +| 1           | store3 | 80    |
    +
    ++-------------+--------+-------+
    +
    +Result table:
    +
    ++-------------+--------+--------+--------+
    +
    +| product_id  | store1 | store2 | store3 |
    +
    ++-------------+--------+--------+--------+
    +
    +| 0           | 95     | 100    | 105    |
    +
    +| 1           | 70     | null   | 80     |
    +
    ++-------------+--------+--------+--------+
    +
    +Product 0 price's are 95 for store1, 100 for store2 and, 105 for store3.
    +
    +Product 1 price's are 70 for store1, 80 for store3 and, it's not sold in store2.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md b/assets/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md new file mode 100644 index 00000000..da28d832 --- /dev/null +++ b/assets/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md @@ -0,0 +1,110 @@ +# [1778. Shortest Path in a Hidden Grid](https://leetcode.com/problems/shortest-path-in-a-hidden-grid) + + + +## Description + +

    This is an interactive problem.

    + +

    There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.

    + +

    You want to find the minimum distance to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.

    + +

    Thr GridMaster class has the following functions:

    + +
      +
    • boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
    • +
    • void move(char direction) Moves the robot in that direction. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, and the robot will remain in the same position.
    • +
    • boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.
    • +
    + +

    Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.

    + +

    Return the minimum distance between the robot's initial starting cell and the target cell. If there is no valid path between the cells, return -1.

    + +

    Custom testing:

    + +

    The test input is read as a 2D matrix grid of size m x n where:

    + +
      +
    • grid[i][j] == -1 indicates that the robot is in cell (i, j) (the starting cell).
    • +
    • grid[i][j] == 0 indicates that the cell (i, j) is blocked.
    • +
    • grid[i][j] == 1 indicates that the cell (i, j) is empty.
    • +
    • grid[i][j] == 2 indicates that the cell (i, j) is the target cell.
    • +
    + +

    There is exactly one -1 and 2 in grid. Remember that you will not have this information in your code.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,2],[-1,0]]
    +Output: 2
    +Explanation: One possible interaction is described below:
    +The robot is initially standing on cell (1, 0), denoted by the -1.
    +- master.canMove('U') returns true.
    +- master.canMove('D') returns false.
    +- master.canMove('L') returns false.
    +- master.canMove('R') returns false.
    +- master.move('U') moves the robot to the cell (0, 0).
    +- master.isTarget() returns false.
    +- master.canMove('U') returns false.
    +- master.canMove('D') returns true.
    +- master.canMove('L') returns false.
    +- master.canMove('R') returns true.
    +- master.move('R') moves the robot to the cell (0, 1).
    +- master.isTarget() returns true. 
    +We now know that the target is the cell (0, 1), and the shortest path to the target cell is 2.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[0,0,-1],[1,1,1],[2,0,0]]
    +Output: 4
    +Explanation: The minimum distance between the robot and the target cell is 4.
    + +

    Example 3:

    + +
    +Input: grid = [[-1,0],[0,2]]
    +Output: -1
    +Explanation: There is no path from the robot to the target cell.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n, m <= 500
    • +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • grid[i][j] is either -1, 0, 1, or 2.
    • +
    • There is exactly one -1 in grid.
    • +
    • There is exactly one 2 in grid.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md b/assets/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md new file mode 100644 index 00000000..ab1ddc88 --- /dev/null +++ b/assets/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md @@ -0,0 +1,67 @@ +# [1779. Find Nearest Point That Has the Same X or Y Coordinate](https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate) + + + +## Description + +

    You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.

    + +

    Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.

    + +

    The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).

    + +

     

    +

    Example 1:

    + +
    +Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
    +Output: 2
    +Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.
    + +

    Example 2:

    + +
    +Input: x = 3, y = 4, points = [[3,4]]
    +Output: 0
    +Explanation: The answer is allowed to be on the same location as your current location.
    + +

    Example 3:

    + +
    +Input: x = 3, y = 4, points = [[2,3]]
    +Output: -1
    +Explanation: There are no valid points.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= points.length <= 104
    • +
    • points[i].length == 2
    • +
    • 1 <= x, y, ai, bi <= 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md b/assets/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md new file mode 100644 index 00000000..52b89750 --- /dev/null +++ b/assets/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md @@ -0,0 +1,65 @@ +# [1780. Check if Number is a Sum of Powers of Three](https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three) + + + +## Description + +

    Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.

    + +

    An integer y is a power of three if there exists an integer x such that y == 3x.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 12
    +Output: true
    +Explanation: 12 = 31 + 32
    +
    + +

    Example 2:

    + +
    +Input: n = 91
    +Output: true
    +Explanation: 91 = 30 + 32 + 34
    +
    + +

    Example 3:

    + +
    +Input: n = 21
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md b/assets/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md new file mode 100644 index 00000000..c9661af9 --- /dev/null +++ b/assets/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md @@ -0,0 +1,61 @@ +# [1781. Sum of Beauty of All Substrings](https://leetcode.com/problems/sum-of-beauty-of-all-substrings) + + + +## Description + +

    The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.

    + +
      +
    • For example, the beauty of "abaacc" is 3 - 1 = 2.
    • +
    + +

    Given a string s, return the sum of beauty of all of its substrings.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "aabcb"
    +Output: 5
    +Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.
    + +

    Example 2:

    + +
    +Input: s = "aabcbaa"
    +Output: 17
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s consists of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1782.Count Pairs Of Nodes/README_EN.md b/assets/1700-1799/1782.Count Pairs Of Nodes/README_EN.md new file mode 100644 index 00000000..61d24f2a --- /dev/null +++ b/assets/1700-1799/1782.Count Pairs Of Nodes/README_EN.md @@ -0,0 +1,71 @@ +# [1782. Count Pairs Of Nodes](https://leetcode.com/problems/count-pairs-of-nodes) + + + +## Description + +

    You are given an undirected graph represented by an integer n, which is the number of nodes, and edges, where edges[i] = [ui, vi] which indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.

    + +

    The answer to the jth query is the number of pairs of nodes (a, b) that satisfy the following conditions:

    + +
      +
    • a < b
    • +
    • cnt is strictly greater than queries[j], where cnt is the number of edges incident to a or b.
    • +
    + +

    Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.

    + +

    Note that there can be repeated edges.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]
    +Output: [6,5]
    +Explanation: The number of edges incident to at least one of each pair is shown above.
    +
    + +

    Example 2:

    + +
    +Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]
    +Output: [10,10,9,8,6]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 2 * 104
    • +
    • 1 <= edges.length <= 105
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 1 <= queries.length <= 20
    • +
    • 0 <= queries[j] < edges.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1782.Count Pairs Of Nodes/images/screenshot-from-2021-02-11-23-07-35.png b/assets/1700-1799/1782.Count Pairs Of Nodes/images/screenshot-from-2021-02-11-23-07-35.png new file mode 100644 index 00000000..ca5530eb Binary files /dev/null and b/assets/1700-1799/1782.Count Pairs Of Nodes/images/screenshot-from-2021-02-11-23-07-35.png differ diff --git a/assets/1700-1799/1783.Grand Slam Titles/README_EN.md b/assets/1700-1799/1783.Grand Slam Titles/README_EN.md new file mode 100644 index 00000000..52cd72d5 --- /dev/null +++ b/assets/1700-1799/1783.Grand Slam Titles/README_EN.md @@ -0,0 +1,161 @@ +# [1783. Grand Slam Titles](https://leetcode.com/problems/grand-slam-titles) + + + +## Description + +

    Table: Players

    + + + +
    +
    ++----------------+---------+
    +
    +| Column Name    | Type    |
    +
    ++----------------+---------+
    +
    +| player_id      | int     |
    +
    +| player_name    | varchar |
    +
    ++----------------+---------+
    +
    +player_id is the primary key for this table.
    +
    +Each row in this table contains the name and the ID of a tennis player.
    +
    +
    + + + +

     

    + + + +

    Table: Championships

    + + + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| year          | int     |
    +
    +| Wimbledon     | int     |
    +
    +| Fr_open       | int     |
    +
    +| US_open       | int     |
    +
    +| Au_open       | int     |
    +
    ++---------------+---------+
    +
    +year is the primary key for this table.
    +
    +Each row of this table containts the IDs of the players who won one each tennis tournament of the grand slam.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the number of grand slam tournaments won by each player. Do not include the players who did not win any tournament.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Players table:
    +
    ++-----------+-------------+
    +
    +| player_id | player_name |
    +
    ++-----------+-------------+
    +
    +| 1         | Nadal       |
    +
    +| 2         | Federer     |
    +
    +| 3         | Novak       |
    +
    ++-----------+-------------+
    +
    +
    +
    +Championships table:
    +
    ++------+-----------+---------+---------+---------+
    +
    +| year | Wimbledon | Fr_open | US_open | Au_open |
    +
    ++------+-----------+---------+---------+---------+
    +
    +| 2018 | 1         | 1       | 1       | 1       |
    +
    +| 2019 | 1         | 1       | 2       | 2       |
    +
    +| 2020 | 2         | 1       | 2       | 2       |
    +
    ++------+-----------+---------+---------+---------+
    +
    +
    +
    +Result table:
    +
    ++-----------+-------------+-------------------+
    +
    +| player_id | player_name | grand_slams_count |
    +
    ++-----------+-------------+-------------------+
    +
    +| 2         | Federer     | 5                 |
    +
    +| 1         | Nadal       | 7                 |
    +
    ++-----------+-------------+-------------------+
    +
    +
    +
    +Player 1 (Nadal) won 7 titles: Wimbledon (2018, 2019), Fr_open (2018, 2019, 2020), US_open (2018), and Au_open (2018).
    +
    +Player 2 (Federer) won 5 titles: Wimbledon (2020), US_open (2019, 2020), and Au_open (2019, 2020).
    +
    +Player 3 (Novak) did not win anything, we did not include them in the result table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git a/assets/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md b/assets/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md new file mode 100644 index 00000000..85c2eb31 --- /dev/null +++ b/assets/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md @@ -0,0 +1,56 @@ +# [1784. Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones) + + + +## Description + +

    Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "1001"
    +Output: false
    +Explanation: The ones do not form a contiguous segment.
    +
    + +

    Example 2:

    + +
    +Input: s = "110"
    +Output: true
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s[i]​​​​ is either '0' or '1'.
    • +
    • s[0] is '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md b/assets/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md new file mode 100644 index 00000000..516a9a52 --- /dev/null +++ b/assets/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md @@ -0,0 +1,62 @@ +# [1785. Minimum Elements to Add to Form a Given Sum](https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum) + + + +## Description + +

    You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.

    + +

    Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.

    + +

    Note that abs(x) equals x if x >= 0, and -x otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,-1,1], limit = 3, goal = -4
    +Output: 2
    +Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,-10,9,1], limit = 100, goal = 0
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= limit <= 106
    • +
    • -limit <= nums[i] <= limit
    • +
    • -109 <= goal <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md b/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md new file mode 100644 index 00000000..16564172 --- /dev/null +++ b/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md @@ -0,0 +1,72 @@ +# [1786. Number of Restricted Paths From First to Last Node](https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node) + + + +## Description + +

    There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.

    + +

    A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.

    + +

    The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.

    + +

    Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
    +Output: 3
    +Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
    +1) 1 --> 2 --> 5
    +2) 1 --> 2 --> 3 --> 5
    +3) 1 --> 3 --> 5
    +
    + +

    Example 2:

    + +
    +Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
    +Output: 1
    +Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 2 * 104
    • +
    • n - 1 <= edges.length <= 4 * 104
    • +
    • edges[i].length == 3
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 1 <= weighti <= 105
    • +
    • There is at most one edge between any two nodes.
    • +
    • There is at least one path between any two nodes.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/images/restricted_paths_ex1.png b/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/images/restricted_paths_ex1.png new file mode 100644 index 00000000..1bb9c8b5 Binary files /dev/null and b/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/images/restricted_paths_ex1.png differ diff --git a/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/images/restricted_paths_ex22.png b/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/images/restricted_paths_ex22.png new file mode 100644 index 00000000..a43681fd Binary files /dev/null and b/assets/1700-1799/1786.Number of Restricted Paths From First to Last Node/images/restricted_paths_ex22.png differ diff --git a/assets/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md b/assets/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md new file mode 100644 index 00000000..4721edf3 --- /dev/null +++ b/assets/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md @@ -0,0 +1,66 @@ +# [1787. Make the XOR of All Segments Equal to Zero](https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero) + + + +## Description + +

    You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].

    + +

    Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,0,3,0], k = 1
    +Output: 3
    +Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,4,5,2,1,7,3,4,7], k = 3
    +Output: 3
    +Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,4,1,2,5,1,2,6], k = 3
    +Output: 3
    +Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= k <= nums.length <= 2000
    • +
    • ​​​​​​0 <= nums[i] < 210
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md b/assets/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md new file mode 100644 index 00000000..219ebd34 --- /dev/null +++ b/assets/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md @@ -0,0 +1,112 @@ +# [1788. Maximize the Beauty of the Garden](https://leetcode.com/problems/maximize-the-beauty-of-the-garden) + + + +## Description + +

    There is a garden of n flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array flowers of size n and each flowers[i] represents the beauty of the ith flower.

    + + + +

    A garden is valid if it meets these conditions:

    + + + +
      +
    • The garden has at least two flowers.
    • +
    • The first and the last flower of the garden have the same beauty value.
    • +
    + + + +

    As the appointed gardener, you have the ability to remove any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden valid. The beauty of the garden is the sum of the beauty of all the remaining flowers.

    + + + +

    Return the maximum possible beauty of some valid garden after you have removed any (possibly none) flowers.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: flowers = [1,2,3,1,2]
    +
    +Output: 8
    +
    +Explanation: You can produce the valid garden [2,3,1,2] to have a total beauty of 2 + 3 + 1 + 2 = 8.
    + + + +

    Example 2:

    + + + +
    +
    +Input: flowers = [100,1,1,-3,1]
    +
    +Output: 3
    +
    +Explanation: You can produce the valid garden [1,1,1] to have a total beauty of 1 + 1 + 1 = 3.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: flowers = [-1,-2,0,-1]
    +
    +Output: -2
    +
    +Explanation: You can produce the valid garden [-1,-1] to have a total beauty of -1 + -1 = -2.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 2 <= flowers.length <= 105
    • +
    • -104 <= flowers[i] <= 104
    • +
    • It is possible to create a valid garden by removing some (possibly none) flowers.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1789.Primary Department for Each Employee/README_EN.md b/assets/1700-1799/1789.Primary Department for Each Employee/README_EN.md new file mode 100644 index 00000000..a9df3041 --- /dev/null +++ b/assets/1700-1799/1789.Primary Department for Each Employee/README_EN.md @@ -0,0 +1,76 @@ +# [1789. Primary Department for Each Employee](https://leetcode.com/problems/primary-department-for-each-employee) + + + +## Description + +

    Table: Employee

    + +
    ++---------------+---------+
    +| Column Name   |  Type   |
    ++---------------+---------+
    +| employee_id   | int     |
    +| department_id | int     |
    +| primary_flag  | varchar |
    ++---------------+---------+
    +(employee_id, department_id) is the primary key for this table.
    +employee_id is the id of the employee.
    +department_id is the id of the department to which the employee belongs.
    +primary_flag is an ENUM of type ('Y', 'N'). If the flag is 'Y', the department is the primary department for the employee. If the flag is 'N', the department is not the primary.
    +
    + +

     

    + +

    Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is 'N'.

    + +

    Write an SQL query to report all the employees with their primary department. For employees who belong to one department, report their only department.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Employee table:
    ++-------------+---------------+--------------+
    +| employee_id | department_id | primary_flag |
    ++-------------+---------------+--------------+
    +| 1           | 1             | N            |
    +| 2           | 1             | Y            |
    +| 2           | 2             | N            |
    +| 3           | 3             | N            |
    +| 4           | 2             | N            |
    +| 4           | 3             | Y            |
    +| 4           | 4             | N            |
    ++-------------+---------------+--------------+
    +
    +Result table:
    ++-------------+---------------+
    +| employee_id | department_id |
    ++-------------+---------------+
    +| 1           | 1             |
    +| 2           | 1             |
    +| 3           | 3             |
    +| 4           | 3             |
    ++-------------+---------------+
    +- The Primary department for employee 1 is 1.
    +- The Primary department for employee 2 is 1.
    +- The Primary department for employee 3 is 3.
    +- The Primary department for employee 4 is 3.
    + +

     

    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md b/assets/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md new file mode 100644 index 00000000..1702c724 --- /dev/null +++ b/assets/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md @@ -0,0 +1,75 @@ +# [1790. Check if One String Swap Can Make Strings Equal](https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal) + + + +## Description + +

    You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

    + +

    Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: s1 = "bank", s2 = "kanb"
    +Output: true
    +Explanation: For example, swap the first character with the last character of s2 to make "bank".
    +
    + +

    Example 2:

    + +
    +Input: s1 = "attack", s2 = "defend"
    +Output: false
    +Explanation: It is impossible to make them equal with one string swap.
    +
    + +

    Example 3:

    + +
    +Input: s1 = "kelb", s2 = "kelb"
    +Output: true
    +Explanation: The two strings are already equal, so no string swap operation is required.
    +
    + +

    Example 4:

    + +
    +Input: s1 = "abcd", s2 = "dcba"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s1.length, s2.length <= 100
    • +
    • s1.length == s2.length
    • +
    • s1 and s2 consist of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1791.Find Center of Star Graph/README_EN.md b/assets/1700-1799/1791.Find Center of Star Graph/README_EN.md new file mode 100644 index 00000000..29faa1f6 --- /dev/null +++ b/assets/1700-1799/1791.Find Center of Star Graph/README_EN.md @@ -0,0 +1,86 @@ +# [1791. Find Center of Star Graph](https://leetcode.com/problems/find-center-of-star-graph) + + + +## Description + +

    There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.

    + + + +

    You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: edges = [[1,2],[2,3],[4,2]]
    +
    +Output: 2
    +
    +Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: edges = [[1,2],[5,1],[1,3],[1,4]]
    +
    +Output: 1
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 3 <= n <= 105
    • +
    • edges.length == n - 1
    • +
    • edges[i].length == 2
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • The given edges represent a valid star graph.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findCenter(self, edges: List[List[int]]) -> int: + return edges[0][0] if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1] else edges[0][1] +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1791.Find Center of Star Graph/images/star_graph.png b/assets/1700-1799/1791.Find Center of Star Graph/images/star_graph.png new file mode 100644 index 00000000..bbbdd146 Binary files /dev/null and b/assets/1700-1799/1791.Find Center of Star Graph/images/star_graph.png differ diff --git a/assets/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md b/assets/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md new file mode 100644 index 00000000..d87c290f --- /dev/null +++ b/assets/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md @@ -0,0 +1,64 @@ +# [1792. Maximum Average Pass Ratio](https://leetcode.com/problems/maximum-average-pass-ratio) + + + +## Description + +

    There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.

    + +

    You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.

    + +

    The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.

    + +

    Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.

    + +

     

    +

    Example 1:

    + +
    +Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2
    +Output: 0.78333
    +Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
    +
    + +

    Example 2:

    + +
    +Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
    +Output: 0.53485
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= classes.length <= 105
    • +
    • classes[i].length == 2
    • +
    • 1 <= passi <= totali <= 105
    • +
    • 1 <= extraStudents <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md b/assets/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md new file mode 100644 index 00000000..4bb177e1 --- /dev/null +++ b/assets/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md @@ -0,0 +1,62 @@ +# [1793. Maximum Score of a Good Subarray](https://leetcode.com/problems/maximum-score-of-a-good-subarray) + + + +## Description + +

    You are given an array of integers nums (0-indexed) and an integer k.

    + +

    The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.

    + +

    Return the maximum possible score of a good subarray.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,4,3,7,4,5], k = 3
    +Output: 15
    +Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. 
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,5,4,5,4,1,1,1], k = 0
    +Output: 20
    +Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 2 * 104
    • +
    • 0 <= k < nums.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md b/assets/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md new file mode 100644 index 00000000..724b9c94 --- /dev/null +++ b/assets/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md @@ -0,0 +1,91 @@ +# [1794. Count Pairs of Equal Substrings With Minimum Difference](https://leetcode.com/problems/count-pairs-of-equal-substrings-with-minimum-difference) + + + +## Description + +

    You are given two strings firstString and secondString that are 0-indexed and consist only of lowercase English letters. Count the number of index quadruples (i,j,a,b) that satisfy the following conditions:

    + + + +
      +
    • 0 <= i <= j < firstString.length
    • +
    • 0 <= a <= b < secondString.length
    • +
    • The substring of firstString that starts at the ith character and ends at the jth character (inclusive) is equal to the substring of secondString that starts at the ath character and ends at the bth character (inclusive).
    • +
    • j - a is the minimum possible value among all quadruples that satisfy the previous conditions.
    • +
    + + + +

    Return the number of such quadruples.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: firstString = "abcd", secondString = "bccda"
    +
    +Output: 1
    +
    +Explanation: The quadruple (0,0,4,4) is the only one that satisfies all the conditions and minimizes j - a.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: firstString = "ab", secondString = "cd"
    +
    +Output: 0
    +
    +Explanation: There are no quadruples satisfying all the conditions.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= firstString.length, secondString.length <= 2 * 105
    • +
    • Both strings consist only of lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1795.Rearrange Products Table/README_EN.md b/assets/1700-1799/1795.Rearrange Products Table/README_EN.md new file mode 100644 index 00000000..92b61835 --- /dev/null +++ b/assets/1700-1799/1795.Rearrange Products Table/README_EN.md @@ -0,0 +1,115 @@ +# [1795. Rearrange Products Table](https://leetcode.com/problems/rearrange-products-table) + + + +## Description + +

    Table: Products

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| product_id  | int     |
    +
    +| store1      | int     |
    +
    +| store2      | int     |
    +
    +| store3      | int     |
    +
    ++-------------+---------+
    +
    +product_id is the primary key for this table.
    +
    +Each row in this table indicates the product's price in 3 different stores: store1, store2, and store3.
    +
    +If the product is not available in a store, the price will be null in that store's column.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table.

    + + + +

    Return the result table in any order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Products table:
    +
    ++------------+--------+--------+--------+
    +
    +| product_id | store1 | store2 | store3 |
    +
    ++------------+--------+--------+--------+
    +
    +| 0          | 95     | 100    | 105    |
    +
    +| 1          | 70     | null   | 80     |
    +
    ++------------+--------+--------+--------+
    +
    +
    +
    +Result table:
    +
    ++------------+--------+-------+
    +
    +| product_id | store  | price |
    +
    ++------------+--------+-------+
    +
    +| 0          | store1 | 95    |
    +
    +| 0          | store2 | 100   |
    +
    +| 0          | store3 | 105   |
    +
    +| 1          | store1 | 70    |
    +
    +| 1          | store3 | 80    |
    +
    ++------------+--------+-------+
    +
    +
    +
    +Product 0 is available in all three stores with prices 95, 100, and 105 respectively.
    +
    +Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1700-1799/1796.Second Largest Digit in a String/README_EN.md b/assets/1700-1799/1796.Second Largest Digit in a String/README_EN.md new file mode 100644 index 00000000..d15511cf --- /dev/null +++ b/assets/1700-1799/1796.Second Largest Digit in a String/README_EN.md @@ -0,0 +1,85 @@ +# [1796. Second Largest Digit in a String](https://leetcode.com/problems/second-largest-digit-in-a-string) + + + +## Description + +

    Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.

    + +

    An alphanumeric string is a string consisting of lowercase English letters and digits.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "dfa12321afd"
    +Output: 2
    +Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
    +
    + +

    Example 2:

    + +
    +Input: s = "abc1111"
    +Output: -1
    +Explanation: The digits that appear in s are [1]. There is no second largest digit. 
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s consists of only lowercase English letters and/or digits.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def secondHighest(self, s: str) -> int: + largest_digit = second_largest_digit = -1 + for c in s: + if c.isdigit(): + num = int(c) + if num > largest_digit: + second_largest_digit, largest_digit = largest_digit, num + elif num > second_largest_digit and num < largest_digit: + second_largest_digit = num + return second_largest_digit +``` + +### **Java** + +```java +class Solution { + public int secondHighest(String s) { + int largestDigit = -1, secondLargestDigit = -1; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c >= '0' && c <= '9') { + int num = c - '0'; + if (num > largestDigit) { + secondLargestDigit = largestDigit; + largestDigit = num; + } else if (num > secondLargestDigit && num < largestDigit) { + secondLargestDigit = num; + } + } + } + return secondLargestDigit; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1797.Design Authentication Manager/README_EN.md b/assets/1700-1799/1797.Design Authentication Manager/README_EN.md new file mode 100644 index 00000000..4711e495 --- /dev/null +++ b/assets/1700-1799/1797.Design Authentication Manager/README_EN.md @@ -0,0 +1,142 @@ +# [1797. Design Authentication Manager](https://leetcode.com/problems/design-authentication-manager) + + + +## Description + +

    There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.

    + +

    Implement the AuthenticationManager class:

    + +
      +
    • AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive.
    • +
    • generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.
    • +
    • renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens.
    • +
    • countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime.
    • +
    + +

    Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.

    + +

     

    +

    Example 1:

    + +
    +Input
    +["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"]
    +[[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]]
    +Output
    +[null, null, null, 1, null, null, null, 0]
    +
    +Explanation
    +AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.
    +authenticationManager.renew("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens.
    +authenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2.
    +authenticationManager.countUnexpiredTokens(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1.
    +authenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7.
    +authenticationManager.renew("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens.
    +authenticationManager.renew("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15.
    +authenticationManager.countUnexpiredTokens(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0.
    +
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= timeToLive <= 108
    • +
    • 1 <= currentTime <= 108
    • +
    • 1 <= tokenId.length <= 5
    • +
    • tokenId consists only of lowercase letters.
    • +
    • All calls to generate will contain unique values of tokenId.
    • +
    • The values of currentTime across all the function calls will be strictly increasing.
    • +
    • At most 2000 calls will be made to all functions combined.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class AuthenticationManager: + + def __init__(self, timeToLive: int): + self.timeToLive = timeToLive + self.tokens = {} + + def generate(self, tokenId: str, currentTime: int) -> None: + self.tokens[tokenId] = currentTime + self.timeToLive + + def renew(self, tokenId: str, currentTime: int) -> None: + expire_time = self.tokens.get(tokenId) + if expire_time is None or expire_time <= currentTime: + return + self.tokens[tokenId] = currentTime + self.timeToLive + + def countUnexpiredTokens(self, currentTime: int) -> int: + unexpiredCount = 0 + for val in self.tokens.values(): + if val > currentTime: + unexpiredCount += 1 + return unexpiredCount + + +# Your AuthenticationManager object will be instantiated and called as such: +# obj = AuthenticationManager(timeToLive) +# obj.generate(tokenId,currentTime) +# obj.renew(tokenId,currentTime) +# param_3 = obj.countUnexpiredTokens(currentTime) +``` + +### **Java** + +```java +class AuthenticationManager { + private int timeToLive; + private Map tokens; + + public AuthenticationManager(int timeToLive) { + this.timeToLive = timeToLive; + tokens = new HashMap<>(); + } + + public void generate(String tokenId, int currentTime) { + tokens.put(tokenId, currentTime + timeToLive); + } + + public void renew(String tokenId, int currentTime) { + Integer expireTime = tokens.get(tokenId); + if (expireTime == null || expireTime <= currentTime) { + return; + } + tokens.put(tokenId, currentTime + timeToLive); + } + + public int countUnexpiredTokens(int currentTime) { + int unexpiredCount = 0; + for (Integer val : tokens.values()) { + if (val > currentTime) { + ++unexpiredCount; + } + } + return unexpiredCount; + } +} + +/** + * Your AuthenticationManager object will be instantiated and called as such: + * AuthenticationManager obj = new AuthenticationManager(timeToLive); + * obj.generate(tokenId,currentTime); + * obj.renew(tokenId,currentTime); + * int param_3 = obj.countUnexpiredTokens(currentTime); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1797.Design Authentication Manager/images/copy-of-pc68_q2.png b/assets/1700-1799/1797.Design Authentication Manager/images/copy-of-pc68_q2.png new file mode 100644 index 00000000..112d6e01 Binary files /dev/null and b/assets/1700-1799/1797.Design Authentication Manager/images/copy-of-pc68_q2.png differ diff --git a/assets/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md b/assets/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md new file mode 100644 index 00000000..4eb3871b --- /dev/null +++ b/assets/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md @@ -0,0 +1,96 @@ +# [1798. Maximum Number of Consecutive Values You Can Make](https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make) + + + +## Description + +

    You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.

    + +

    Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.

    + +

    Note that you may have multiple coins of the same value.

    + +

     

    +

    Example 1:

    + +
    +Input: coins = [1,3]
    +Output: 2
    +Explanation: You can make the following values:
    +- 0: take []
    +- 1: take [1]
    +You can make 2 consecutive integer values starting from 0.
    + +

    Example 2:

    + +
    +Input: coins = [1,1,1,4]
    +Output: 8
    +Explanation: You can make the following values:
    +- 0: take []
    +- 1: take [1]
    +- 2: take [1,1]
    +- 3: take [1,1,1]
    +- 4: take [4]
    +- 5: take [4,1]
    +- 6: take [4,1,1]
    +- 7: take [4,1,1,1]
    +You can make 8 consecutive integer values starting from 0.
    + +

    Example 3:

    + +
    +Input: nums = [1,4,10,3,1]
    +Output: 20
    + +

     

    +

    Constraints:

    + +
      +
    • coins.length == n
    • +
    • 1 <= n <= 4 * 104
    • +
    • 1 <= coins[i] <= 4 * 104
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def getMaximumConsecutive(self, coins: List[int]) -> int: + res = 1 + for coin in sorted(coins): + if coin > res: + break + res += coin + return res +``` + +### **Java** + +```java +class Solution { + public int getMaximumConsecutive(int[] coins) { + int res = 1; + Arrays.sort(coins); + for (int coin : coins) { + if (coin > res) { + break; + } + res += coin; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1700-1799/1799.Maximize Score After N Operations/README_EN.md b/assets/1700-1799/1799.Maximize Score After N Operations/README_EN.md new file mode 100644 index 00000000..e780540b --- /dev/null +++ b/assets/1700-1799/1799.Maximize Score After N Operations/README_EN.md @@ -0,0 +1,81 @@ +# [1799. Maximize Score After N Operations](https://leetcode.com/problems/maximize-score-after-n-operations) + + + +## Description + +

    You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.

    + +

    In the ith operation (1-indexed), you will:

    + +
      +
    • Choose two elements, x and y.
    • +
    • Receive a score of i * gcd(x, y).
    • +
    • Remove x and y from nums.
    • +
    + +

    Return the maximum score you can receive after performing n operations.

    + +

    The function gcd(x, y) is the greatest common divisor of x and y.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2]
    +Output: 1
    +Explanation: The optimal choice of operations is:
    +(1 * gcd(1, 2)) = 1
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,4,6,8]
    +Output: 11
    +Explanation: The optimal choice of operations is:
    +(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,2,3,4,5,6]
    +Output: 14
    +Explanation: The optimal choice of operations is:
    +(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 7
    • +
    • nums.length == 2 * n
    • +
    • 1 <= nums[i] <= 106
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md b/assets/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md new file mode 100644 index 00000000..80ef967c --- /dev/null +++ b/assets/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md @@ -0,0 +1,161 @@ +# [1800. Maximum Ascending Subarray Sum](https://leetcode.com/problems/maximum-ascending-subarray-sum) + + + +## Description + +

    Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.

    + +

    A subarray is defined as a contiguous sequence of numbers in an array.

    + +

    A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [10,20,30,5,10,50]
    +Output: 65
    +Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
    +
    + +

    Example 2:

    + +
    +Input: nums = [10,20,30,40,50]
    +Output: 150
    +Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
    +
    + +

    Example 3:

    + +
    +Input: nums = [12,17,15,13,10,11,12]
    +Output: 33
    +Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.
    +
    + +

    Example 4:

    + +
    +Input: nums = [100,10,1]
    +Output: 100
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxAscendingSum(self, nums: List[int]) -> int: + res, cur = 0, nums[0] + for i in range(1, len(nums)): + if nums[i] > nums[i - 1]: + cur += nums[i] + else: + res = max(res, cur) + cur = nums[i] + res = max(res, cur) + return res +``` + +### **Java** + +```java +class Solution { + public int maxAscendingSum(int[] nums) { + int cur = nums[0]; + int res = 0; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] > nums[i - 1]) { + cur += nums[i]; + } else { + res = Math.max(res, cur); + cur = nums[i]; + } + } + res = Math.max(res, cur); + return res; + } +} +``` + +### **TypeScript** + +```ts +function maxAscendingSum(nums: number[]): number { + let res = 0, sum = nums[0]; + for (let i = 1; i < nums.length; ++i) { + if (nums[i] > nums[i - 1]) { + sum += nums[i]; + } else { + res = Math.max(res, sum); + sum = nums[i]; + } + } + res = Math.max(res, sum); + return res; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int maxAscendingSum(vector& nums) { + int res = 0, cur = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > nums[i - 1]) { + cur += nums[i]; + } else { + res = max(res, cur); + cur = nums[i]; + } + } + res = max(res, cur); + return res; + } +}; +``` + +### **Go** + +```go +func maxAscendingSum(nums []int) int { + res, cur := 0, nums[0] + for i := 1; i < len(nums); i++ { + if nums[i] > nums[i-1] { + cur += nums[i] + } else { + if res < cur { + res = cur + } + cur = nums[i] + } + } + if res < cur { + res = cur + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1801.Number of Orders in the Backlog/README_EN.md b/assets/1800-1899/1801.Number of Orders in the Backlog/README_EN.md new file mode 100644 index 00000000..9344b0ba --- /dev/null +++ b/assets/1800-1899/1801.Number of Orders in the Backlog/README_EN.md @@ -0,0 +1,126 @@ +# [1801. Number of Orders in the Backlog](https://leetcode.com/problems/number-of-orders-in-the-backlog) + + + +## Description + +

    You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:

    + + + +
      +
    • 0 if it is a batch of buy orders, or
    • +
    • 1 if it is a batch of sell orders.
    • +
    + + + +

    Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.

    + + + +

    There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:

    + + + +
      +
    • If the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.
    • +
    • Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.
    • +
    + + + +

    Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
    +
    +Output: 6
    +
    +Explanation: Here is what happens with the orders:
    +
    +- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.
    +
    +- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.
    +
    +- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.
    +
    +- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.
    +
    +Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
    +
    +Output: 999999984
    +
    +Explanation: Here is what happens with the orders:
    +
    +- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.
    +
    +- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.
    +
    +- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.
    +
    +- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.
    +
    +Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= orders.length <= 105
    • +
    • orders[i].length == 3
    • +
    • 1 <= pricei, amounti <= 109
    • +
    • orderTypei is either 0 or 1.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1801.Number of Orders in the Backlog/images/ex1.png b/assets/1800-1899/1801.Number of Orders in the Backlog/images/ex1.png new file mode 100644 index 00000000..19e9e413 Binary files /dev/null and b/assets/1800-1899/1801.Number of Orders in the Backlog/images/ex1.png differ diff --git a/assets/1800-1899/1801.Number of Orders in the Backlog/images/ex2.png b/assets/1800-1899/1801.Number of Orders in the Backlog/images/ex2.png new file mode 100644 index 00000000..4f7255c9 Binary files /dev/null and b/assets/1800-1899/1801.Number of Orders in the Backlog/images/ex2.png differ diff --git a/assets/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md b/assets/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md new file mode 100644 index 00000000..7ed2c686 --- /dev/null +++ b/assets/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md @@ -0,0 +1,69 @@ +# [1802. Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array) + + + +## Description + +

    You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:

    + +
      +
    • nums.length == n
    • +
    • nums[i] is a positive integer where 0 <= i < n.
    • +
    • abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.
    • +
    • The sum of all the elements of nums does not exceed maxSum.
    • +
    • nums[index] is maximized.
    • +
    + +

    Return nums[index] of the constructed array.

    + +

    Note that abs(x) equals x if x >= 0, and -x otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 4, index = 2,  maxSum = 6
    +Output: 2
    +Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions.
    +There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].
    +
    + +

    Example 2:

    + +
    +Input: n = 6, index = 1,  maxSum = 10
    +Output: 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= maxSum <= 109
    • +
    • 0 <= index < n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md b/assets/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md new file mode 100644 index 00000000..3b88cbc9 --- /dev/null +++ b/assets/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md @@ -0,0 +1,73 @@ +# [1803. Count Pairs With XOR in a Range](https://leetcode.com/problems/count-pairs-with-xor-in-a-range) + + + +## Description + +

    Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.

    + +

    A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,4,2,7], low = 2, high = 6
    +Output: 6
    +Explanation: All nice pairs (i, j) are as follows:
    +    - (0, 1): nums[0] XOR nums[1] = 5 
    +    - (0, 2): nums[0] XOR nums[2] = 3
    +    - (0, 3): nums[0] XOR nums[3] = 6
    +    - (1, 2): nums[1] XOR nums[2] = 6
    +    - (1, 3): nums[1] XOR nums[3] = 3
    +    - (2, 3): nums[2] XOR nums[3] = 5
    +
    + +

    Example 2:

    + +
    +Input: nums = [9,8,4,2,1], low = 5, high = 14
    +Output: 8
    +Explanation: All nice pairs (i, j) are as follows:
    +​​​​​    - (0, 2): nums[0] XOR nums[2] = 13
    +    - (0, 3): nums[0] XOR nums[3] = 11
    +    - (0, 4): nums[0] XOR nums[4] = 8
    +    - (1, 2): nums[1] XOR nums[2] = 12
    +    - (1, 3): nums[1] XOR nums[3] = 10
    +    - (1, 4): nums[1] XOR nums[4] = 9
    +    - (2, 3): nums[2] XOR nums[3] = 6
    +    - (2, 4): nums[2] XOR nums[4] = 5
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 2 * 104
    • +
    • 1 <= nums[i] <= 2 * 104
    • +
    • 1 <= low <= high <= 2 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md b/assets/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md new file mode 100644 index 00000000..4e10d211 --- /dev/null +++ b/assets/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md @@ -0,0 +1,185 @@ +# [1804. Implement Trie II (Prefix Tree)](https://leetcode.com/problems/implement-trie-ii-prefix-tree) + + + +## Description + +

    A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

    + +

    Implement the Trie class:

    + +
      +
    • Trie() Initializes the trie object.
    • +
    • void insert(String word) Inserts the string word into the trie.
    • +
    • int countWordsEqualTo(String word) Returns the number of instances of the string word in the trie.
    • +
    • int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have the string prefix as a prefix.
    • +
    • void erase(String word) Erases the string word from the trie.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["Trie", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsStartingWith"]
    +[[], ["apple"], ["apple"], ["apple"], ["app"], ["apple"], ["apple"], ["app"], ["apple"], ["app"]]
    +Output
    +[null, null, null, 2, 2, null, 1, 1, null, 0]
    +
    +Explanation
    +Trie trie = new Trie();
    +trie.insert("apple");               // Inserts "apple".
    +trie.insert("apple");               // Inserts another "apple".
    +trie.countWordsEqualTo("apple");    // There are two instances of "apple" so return 2.
    +trie.countWordsStartingWith("app"); // "app" is a prefix of "apple" so return 2.
    +trie.erase("apple");                // Erases one "apple".
    +trie.countWordsEqualTo("apple");    // Now there is only one instance of "apple" so return 1.
    +trie.countWordsStartingWith("app"); // return 1
    +trie.erase("apple");                // Erases "apple". Now the trie is empty.
    +trie.countWordsStartingWith("app"); // return 0
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word.length, prefix.length <= 2000
    • +
    • word and prefix consist only of lowercase English letters.
    • +
    • At most 3 * 104 calls in total will be made to insert, countWordsEqualTo, countWordsStartingWith, and erase.
    • +
    • It is guaranteed that for any function call to erase, the string word will exist in the trie.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Trie: + + def __init__(self): + self.children = [None] * 26 + self.count = 0 + self.pre_count = 0 + + def insert(self, word: str) -> None: + node = self + for c in word: + index = ord(c) - ord('a') + if node.children[index] is None: + node.children[index] = Trie() + node = node.children[index] + node.pre_count += 1 + node.count += 1 + + def countWordsEqualTo(self, word: str) -> int: + node = self._search_prefix(word) + return 0 if node is None else node.count + + def countWordsStartingWith(self, prefix: str) -> int: + node = self._search_prefix(prefix) + return 0 if node is None else node.pre_count + + def erase(self, word: str) -> None: + node = self + for c in word: + index = ord(c) - ord('a') + node = node.children[index] + node.pre_count -= 1 + node.count -= 1 + + def _search_prefix(self, prefix: str): + node = self + for c in prefix: + index = ord(c) - ord('a') + if node.children[index] is None: + return None + node = node.children[index] + return node + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.countWordsEqualTo(word) +# param_3 = obj.countWordsStartingWith(prefix) +# obj.erase(word) +``` + +### **Java** + +```java +class Trie { + private Trie[] children; + private int count; + private int preCount; + + public Trie() { + children = new Trie[26]; + count = 0; + preCount = 0; + } + + public void insert(String word) { + Trie node = this; + for (int i = 0; i < word.length(); ++i) { + int index = word.charAt(i) - 'a'; + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + node = node.children[index]; + node.preCount += 1; + } + node.count += 1; + } + + public int countWordsEqualTo(String word) { + Trie node = searchPrefix(word); + return node == null ? 0 : node.count; + } + + public int countWordsStartingWith(String prefix) { + Trie node = searchPrefix(prefix); + return node == null ? 0 : node.preCount; + } + + public void erase(String word) { + Trie node = this; + for (int i = 0; i < word.length(); ++i) { + int index = word.charAt(i) - 'a'; + node = node.children[index]; + node.preCount -= 1; + } + node.count -= 1; + } + + private Trie searchPrefix(String prefix) { + Trie node = this; + for (int i = 0; i < prefix.length(); ++i) { + int index = prefix.charAt(i) - 'a'; + if (node.children[index] == null) { + return null; + } + node = node.children[index]; + } + return node; + } +} + +/** + * Your Trie object will be instantiated and called as such: + * Trie obj = new Trie(); + * obj.insert(word); + * int param_2 = obj.countWordsEqualTo(word); + * int param_3 = obj.countWordsStartingWith(prefix); + * obj.erase(word); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1805.Number of Different Integers in a String/README_EN.md b/assets/1800-1899/1805.Number of Different Integers in a String/README_EN.md new file mode 100644 index 00000000..2a90fe0c --- /dev/null +++ b/assets/1800-1899/1805.Number of Different Integers in a String/README_EN.md @@ -0,0 +1,91 @@ +# [1805. Number of Different Integers in a String](https://leetcode.com/problems/number-of-different-integers-in-a-string) + + + +## Description + +

    You are given a string word that consists of digits and lowercase English letters.

    + +

    You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123  34 8  34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".

    + +

    Return the number of different integers after performing the replacement operations on word.

    + +

    Two integers are considered different if their decimal representations without any leading zeros are different.

    + +

     

    +

    Example 1:

    + +
    +Input: word = "a123bc34d8ef34"
    +Output: 3
    +Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.
    +
    + +

    Example 2:

    + +
    +Input: word = "leet1234code234"
    +Output: 2
    +
    + +

    Example 3:

    + +
    +Input: word = "a1b01c001"
    +Output: 1
    +Explanation: The three integers "1", "01", and "001" all represent the same integer because
    +the leading zeros are ignored when comparing their decimal values.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word.length <= 1000
    • +
    • word consists of digits and lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python +import re + +class Solution: + def numDifferentIntegers(self, word: str) -> int: + nums = re.split(r'[a-z]+', word) + return len({int(num) for num in nums if num != ''}) +``` + +### **Java** + +```java +class Solution { + public int numDifferentIntegers(String word) { + String[] nums = word.split("[a-z]+"); + Set numSet = new HashSet<>(); + for (String num : nums) { + if ("".equals(num)) { + continue; + } + int j = 0; + while (j < num.length() - 1 && num.charAt(j) == '0') { + ++j; + } + numSet.add(num.substring(j)); + } + return numSet.size(); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md b/assets/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md new file mode 100644 index 00000000..0a1d535d --- /dev/null +++ b/assets/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md @@ -0,0 +1,80 @@ +# [1806. Minimum Number of Operations to Reinitialize a Permutation](https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation) + + + +## Description + +

    You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i(0-indexed)​​​​.

    + +

    In one operation, you will create a new array arr, and for each i:

    + +
      +
    • If i % 2 == 0, then arr[i] = perm[i / 2].
    • +
    • If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].
    • +
    + +

    You will then assign arr​​​​ to perm.

    + +

    Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 2
    +Output: 1
    +Explanation: perm = [0,1] initially.
    +After the 1st operation, perm = [0,1]
    +So it takes only 1 operation.
    +
    + +

    Example 2:

    + +
    +Input: n = 4
    +Output: 2
    +Explanation: perm = [0,1,2,3] initially.
    +After the 1st operation, perm = [0,2,1,3]
    +After the 2nd operation, perm = [0,1,2,3]
    +So it takes only 2 operations.
    +
    + +

    Example 3:

    + +
    +Input: n = 6
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 1000
    • +
    • n​​​​​​ is even.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md b/assets/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md new file mode 100644 index 00000000..965c4516 --- /dev/null +++ b/assets/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md @@ -0,0 +1,147 @@ +# [1807. Evaluate the Bracket Pairs of a String](https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string) + + + +## Description + +

    You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.

    + +
      +
    • For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".
    • +
    + +

    You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.

    + +

    You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:

    + +
      +
    • Replace keyi and the bracket pair with the key's corresponding valuei.
    • +
    • If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks).
    • +
    + +

    Each key will appear at most once in your knowledge. There will not be any nested brackets in s.

    + +

    Return the resulting string after evaluating all of the bracket pairs.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]]
    +Output: "bobistwoyearsold"
    +Explanation:
    +The key "name" has a value of "bob", so replace "(name)" with "bob".
    +The key "age" has a value of "two", so replace "(age)" with "two".
    +
    + +

    Example 2:

    + +
    +Input: s = "hi(name)", knowledge = [["a","b"]]
    +Output: "hi?"
    +Explanation: As you do not know the value of the key "name", replace "(name)" with "?".
    +
    + +

    Example 3:

    + +
    +Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]]
    +Output: "yesyesyesaaa"
    +Explanation: The same key can appear multiple times.
    +The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes".
    +Notice that the "a"s not in a bracket pair are not evaluated.
    +
    + +

    Example 4:

    + +
    +Input: s = "(a)(b)", knowledge = [["a","b"],["b","a"]]
    +Output: "ba"
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • 0 <= knowledge.length <= 105
    • +
    • knowledge[i].length == 2
    • +
    • 1 <= keyi.length, valuei.length <= 10
    • +
    • s consists of lowercase English letters and round brackets '(' and ')'.
    • +
    • Every open bracket '(' in s will have a corresponding close bracket ')'.
    • +
    • The key in each bracket pair of s will be non-empty.
    • +
    • There will not be any nested bracket pairs in s.
    • +
    • keyi and valuei consist of lowercase English letters.
    • +
    • Each keyi in knowledge is unique.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def evaluate(self, s: str, knowledge: List[List[str]]) -> str: + def find_right_bracket(s, start, end): + for i in range(start, end): + if s[i] == ')': + return i + knowledge_dict = {item[0]: item[1] for item in knowledge} + res, n = [], len(s) + i = 0 + while i < n: + if s[i] == '(': + right_bracket_pos = find_right_bracket(s, i + 1, n) + key = s[i + 1: right_bracket_pos] + res.append(knowledge_dict.get(key, '?')) + i = right_bracket_pos + 1 + else: + res.append(s[i]) + i += 1 + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String evaluate(String s, List> knowledge) { + Map knowledgeDict = new HashMap<>(); + for (List item : knowledge) { + knowledgeDict.put(item.get(0), item.get(1)); + } + StringBuilder res = new StringBuilder(); + int i = 0, n = s.length(); + while (i < n) { + if (s.charAt(i) == '(') { + int rightBracketPos = findRightBracket(s, i + 1, n); + String key = s.substring(i + 1, rightBracketPos); + res.append(knowledgeDict.getOrDefault(key, "?")); + i = rightBracketPos + 1; + } else { + res.append(s.charAt(i)); + i += 1; + } + } + return res.toString(); + } + + private int findRightBracket(String s, int start, int end) { + for (int i = start; i < end; ++i) { + if (s.charAt(i) == ')') { + return i; + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md b/assets/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md new file mode 100644 index 00000000..8bf15d82 --- /dev/null +++ b/assets/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md @@ -0,0 +1,94 @@ +# [1808. Maximize Number of Nice Divisors](https://leetcode.com/problems/maximize-number-of-nice-divisors) + + + +## Description + +

    You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:

    + + + +
      +
    • The number of prime factors of n (not necessarily distinct) is at most primeFactors.
    • +
    • The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.
    • +
    + + + +

    Return the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7.

    + + + +

    Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: primeFactors = 5
    +
    +Output: 6
    +
    +Explanation: 200 is a valid value of n.
    +
    +It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].
    +
    +There is not other value of n that has at most 5 prime factors and more nice divisors.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: primeFactors = 8
    +
    +Output: 18
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= primeFactors <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1809.Ad-Free Sessions/README_EN.md b/assets/1800-1899/1809.Ad-Free Sessions/README_EN.md new file mode 100644 index 00000000..a8728977 --- /dev/null +++ b/assets/1800-1899/1809.Ad-Free Sessions/README_EN.md @@ -0,0 +1,95 @@ +# [1809. Ad-Free Sessions](https://leetcode.com/problems/ad-free-sessions) + + + +## Description + +

    Table: Playback

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| session_id  | int  |
    +| customer_id | int  |
    +| start_time  | int  |
    +| end_time    | int  |
    ++-------------+------+
    +session_id is the primary key for this table.
    +customer_id is the ID of the customer watching this session.
    +The session runs during the inclusive interval between start_time and end_time.
    +It is guaranteed that start_time <= end_time and that two sessions for the same customer do not intersect.
    + +

     

    + +

    Table: Ads

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| ad_id       | int  |
    +| customer_id | int  |
    +| timestamp   | int  |
    ++-------------+------+
    +ad_id is the primary key for this table.
    +customer_id is the ID of the customer viewing this ad.
    +timestamp is the moment of time at which the ad was shown.
    +
    + +

     

    + +

    Write an SQL query to report all the sessions that did not get shown any ads.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Playback table:
    ++------------+-------------+------------+----------+
    +| session_id | customer_id | start_time | end_time |
    ++------------+-------------+------------+----------+
    +| 1          | 1           | 1          | 5        |
    +| 2          | 1           | 15         | 23       |
    +| 3          | 2           | 10         | 12       |
    +| 4          | 2           | 17         | 28       |
    +| 5          | 2           | 2          | 8        |
    ++------------+-------------+------------+----------+
    +
    +Ads table:
    ++-------+-------------+-----------+
    +| ad_id | customer_id | timestamp |
    ++-------+-------------+-----------+
    +| 1     | 1           | 5         |
    +| 2     | 2           | 17        |
    +| 3     | 2           | 20        |
    ++-------+-------------+-----------+
    +
    +Result table:
    ++------------+
    +| session_id |
    ++------------+
    +| 2          |
    +| 3          |
    +| 5          |
    ++------------+
    +The ad with ID 1 was shown to user 1 at time 5 while they were in session 1.
    +The ad with ID 2 was shown to user 2 at time 17 while they were in session 4.
    +The ad with ID 3 was shown to user 2 at time 20 while they were in session 4.
    +We can see that sessions 1 and 4 had at least one ad. Sessions 2, 3, and 5 did not have any ads, so we return them.
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md b/assets/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md new file mode 100644 index 00000000..70851727 --- /dev/null +++ b/assets/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md @@ -0,0 +1,113 @@ +# [1810. Minimum Path Cost in a Hidden Grid](https://leetcode.com/problems/minimum-path-cost-in-a-hidden-grid) + + + +## Description + +

    This is an interactive problem.

    + +

    There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.

    + +

    Each cell has a cost that you need to pay each time you move to the cell. The starting cell's cost is not applied before the robot moves.

    + +

    You want to find the minimum total cost to move the robot to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.

    + +

    The GridMaster class has the following functions:

    + +
      +
    • boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
    • +
    • int move(char direction) Moves the robot in that direction and returns the cost of moving to that cell. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, the robot will remain in the same position, and the function will return -1.
    • +
    • boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.
    • +
    + +

    Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.

    + +

    Return the minimum total cost to get the robot from its initial starting cell to the target cell. If there is no valid path between the cells, return -1.

    + +

    Custom testing:

    + +

    The test input is read as a 2D matrix grid of size m x n and four integers r1, c1, r2, and c2 where:

    + +
      +
    • grid[i][j] == 0 indicates that the cell (i, j) is blocked.
    • +
    • grid[i][j] >= 1 indicates that the cell (i, j) is empty and grid[i][j] is the cost to move to that cell.
    • +
    • (r1, c1) is the starting cell of the robot.
    • +
    • (r2, c2) is the target cell of the robot.
    • +
    + +

    Remember that you will not have this information in your code.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[2,3],[1,1]], r1 = 0, c1 = 1, r2 = 1, c2 = 0
    +Output: 2
    +Explanation: One possible interaction is described below:
    +The robot is initially standing on cell (0, 1), denoted by the 3.
    +- master.canMove('U') returns false.
    +- master.canMove('D') returns true.
    +- master.canMove('L') returns true.
    +- master.canMove('R') returns false.
    +- master.move('L') moves the robot to the cell (0, 0) and returns 2.
    +- master.isTarget() returns false.
    +- master.canMove('U') returns false.
    +- master.canMove('D') returns true.
    +- master.canMove('L') returns false.
    +- master.canMove('R') returns true.
    +- master.move('D') moves the robot to the cell (1, 0) and returns 1.
    +- master.isTarget() returns true.
    +- master.move('L') doesn't move the robot and returns -1.
    +- master.move('R') moves the robot to the cell (1, 1) and returns 1.
    +We now know that the target is the cell (0, 1), and the minimum total cost to reach it is 2. 
    + +

    Example 2:

    + +
    +Input: grid = [[0,3,1],[3,4,2],[1,2,0]], r1 = 2, c1 = 0, r2 = 0, c2 = 2
    +Output: 9
    +Explanation: The minimum cost path is (2,0) -> (2,1) -> (1,1) -> (1,2) -> (0,2).
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0],[0,1]], r1 = 0, c1 = 0, r2 = 1, c2 = 1
    +Output: -1
    +Explanation: There is no path from the robot to the target cell.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n, m <= 100
    • +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 0 <= grid[i][j] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1811.Find Interview Candidates/README_EN.md b/assets/1800-1899/1811.Find Interview Candidates/README_EN.md new file mode 100644 index 00000000..53457ce4 --- /dev/null +++ b/assets/1800-1899/1811.Find Interview Candidates/README_EN.md @@ -0,0 +1,114 @@ +# [1811. Find Interview Candidates](https://leetcode.com/problems/find-interview-candidates) + + + +## Description + +

    Table: Contests

    + +
    ++--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| contest_id   | int  |
    +| gold_medal   | int  |
    +| silver_medal | int  |
    +| bronze_medal | int  |
    ++--------------+------+
    +contest_id is the primary key for this table.
    +This table contains the LeetCode contest ID and the user IDs of the gold, silver, and bronze medalists.
    +It is guaranteed that any consecutive contests have consecutive IDs and that no ID is skipped.
    + +

     

    + +

    Table: Users

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| mail        | varchar |
    +| name        | varchar |
    ++-------------+---------+
    +user_id is the primary key for this table.
    +This table contains information about the users.
    +
    + +

     

    + +

    Write an SQL query to report the name and the mail of all interview candidates. A user is an interview candidate if at least one of these two conditions is true:

    + +
      +
    • The user won any medal in three or more consecutive contests.
    • +
    • The user won the gold medal in three or more different contests (not necessarily consecutive).
    • +
    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Contests table:
    ++------------+------------+--------------+--------------+
    +| contest_id | gold_medal | silver_medal | bronze_medal |
    ++------------+------------+--------------+--------------+
    +| 190        | 1          | 5            | 2            |
    +| 191        | 2          | 3            | 5            |
    +| 192        | 5          | 2            | 3            |
    +| 193        | 1          | 3            | 5            |
    +| 194        | 4          | 5            | 2            |
    +| 195        | 4          | 2            | 1            |
    +| 196        | 1          | 5            | 2            |
    ++------------+------------+--------------+--------------+
    +
    +Users table:
    ++---------+--------------------+-------+
    +| user_id | mail               | name  |
    ++---------+--------------------+-------+
    +| 1       | sarah@leetcode.com | Sarah |
    +| 2       | bob@leetcode.com   | Bob   |
    +| 3       | alice@leetcode.com | Alice |
    +| 4       | hercy@leetcode.com | Hercy |
    +| 5       | quarz@leetcode.com | Quarz |
    ++---------+--------------------+-------+
    +
    +Result table:
    ++-------+--------------------+
    +| name  | mail               |
    ++-------+--------------------+
    +| Sarah | sarah@leetcode.com |
    +| Bob   | bob@leetcode.com   |
    +| Alice | alice@leetcode.com |
    +| Quarz | quarz@leetcode.com |
    ++-------+--------------------+
    +
    +Sarah won 3 gold medals (190, 193, and 196), so we include her in the result table.
    +Bob won a medal in 3 consecutive contests (190, 191, and 192), so we include him in the result table.
    +    - Note that he also won a medal in 3 other consecutive contests (194, 195, and 196).
    +Alice won a medal in 3 consecutive contests (191, 192, and 193), so we include her in the result table.
    +Quarz won a medal in 5 consecutive contests (190, 191, 192, 193, and 194), so we include them in the result table.
    +
    + +

     

    +

    Follow up:

    + +
      +
    • What if the first condition changed to be "any medal in n or more consecutive contests"? How would you change your solution to get the interview candidates? Imagine that n is the parameter of a stored procedure.
    • +
    • Some users may not participate in every contest but still perform well in the ones they do. How would you change your solution to only consider contests where the user was a participant? Suppose the registered users for each contest are given in another table.
    • +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md b/assets/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md new file mode 100644 index 00000000..50db2716 --- /dev/null +++ b/assets/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md @@ -0,0 +1,95 @@ +# [1812. Determine Color of a Chessboard Square](https://leetcode.com/problems/determine-color-of-a-chessboard-square) + + + +## Description + +

    You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.

    + +

    + +

    Return true if the square is white, and false if the square is black.

    + +

    The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.

    + +

     

    +

    Example 1:

    + +
    +Input: coordinates = "a1"
    +Output: false
    +Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false.
    +
    + +

    Example 2:

    + +
    +Input: coordinates = "h3"
    +Output: true
    +Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true.
    +
    + +

    Example 3:

    + +
    +Input: coordinates = "c7"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • coordinates.length == 2
    • +
    • 'a' <= coordinates[0] <= 'h'
    • +
    • '1' <= coordinates[1] <= '8'
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def squareIsWhite(self, coordinates: str) -> bool: + x = ord(coordinates[0]) - ord('a') + 1 + y = int(coordinates[1]) + return ((x + y) & 1) == 1 +``` + +### **Java** + +```java +class Solution { + public boolean squareIsWhite(String coordinates) { + int x = coordinates.charAt(0) - 'a' + 1; + int y = coordinates.charAt(1) - '0'; + return ((x + y) & 1) == 1; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} coordinates + * @return {boolean} + */ + var squareIsWhite = function(coordinates) { + let x = coordinates.charAt(0).charCodeAt() - 'a'.charCodeAt() + 1; + let y = Number(coordinates.charAt(1)); + return ((x + y) & 1) == 1; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1812.Determine Color of a Chessboard Square/images/screenshot-2021-02-20-at-22159-pm.png b/assets/1800-1899/1812.Determine Color of a Chessboard Square/images/screenshot-2021-02-20-at-22159-pm.png new file mode 100644 index 00000000..30b33a34 Binary files /dev/null and b/assets/1800-1899/1812.Determine Color of a Chessboard Square/images/screenshot-2021-02-20-at-22159-pm.png differ diff --git a/assets/1800-1899/1813.Sentence Similarity III/README_EN.md b/assets/1800-1899/1813.Sentence Similarity III/README_EN.md new file mode 100644 index 00000000..b12d0b9c --- /dev/null +++ b/assets/1800-1899/1813.Sentence Similarity III/README_EN.md @@ -0,0 +1,127 @@ +# [1813. Sentence Similarity III](https://leetcode.com/problems/sentence-similarity-iii) + + + +## Description + +

    A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters.

    + +

    Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = "Hello my name is Jane" and sentence2 = "Hello Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in sentence2.

    + +

    Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.

    + +

     

    +

    Example 1:

    + +
    +Input: sentence1 = "My name is Haley", sentence2 = "My Haley"
    +Output: true
    +Explanation: sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley".
    +
    + +

    Example 2:

    + +
    +Input: sentence1 = "of", sentence2 = "A lot of words"
    +Output: false
    +Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other.
    +
    + +

    Example 3:

    + +
    +Input: sentence1 = "Eating right now", sentence2 = "Eating"
    +Output: true
    +Explanation: sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.
    +
    + +

    Example 4:

    + +
    +Input: sentence1 = "Luky", sentence2 = "Lucccky"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= sentence1.length, sentence2.length <= 100
    • +
    • sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.
    • +
    • The words in sentence1 and sentence2 are separated by a single space.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: + if sentence1 == sentence2: + return True + n1, n2 = len(sentence1), len(sentence2) + if n1 == n2: + return False + if n1 < n2: + sentence1, sentence2 = sentence2, sentence1 + words1, words2 = sentence1.split(), sentence2.split() + i = j = 0 + while i < len(words2) and words1[i] == words2[i]: + i += 1 + if i == len(words2): + return True + while j < len(words2) and words1[len(words1) - 1 - j] == words2[len(words2) - 1 - j]: + j += 1 + if j == len(words2): + return True + return i + j == len(words2) +``` + +### **Java** + +```java +class Solution { + public boolean areSentencesSimilar(String sentence1, String sentence2) { + if (Objects.equals(sentence1, sentence2)) { + return true; + } + int n1 = sentence1.length(), n2 = sentence2.length(); + if (n1 == n2) { + return false; + } + if (n1 < n2) { + String t = sentence1; + sentence1 = sentence2; + sentence2 = t; + } + String[] words1 = sentence1.split(" "); + String[] words2 = sentence2.split(" "); + int i = 0, j = 0; + while (i < words2.length && Objects.equals(words1[i], words2[i])) { + ++i; + } + if (i == words2.length) { + return true; + } + while (j < words2.length && Objects.equals(words1[words1.length - 1 - j], words2[words2.length - 1 - j])) { + ++j; + } + if (j == words2.length) { + return true; + } + return i + j == words2.length; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md b/assets/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md new file mode 100644 index 00000000..7495e988 --- /dev/null +++ b/assets/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md @@ -0,0 +1,65 @@ +# [1814. Count Nice Pairs in an Array](https://leetcode.com/problems/count-nice-pairs-in-an-array) + + + +## Description + +

    You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:

    + +
      +
    • 0 <= i < j < nums.length
    • +
    • nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
    • +
    + +

    Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [42,11,1,97]
    +Output: 2
    +Explanation: The two pairs are:
    + - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
    + - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
    +
    + +

    Example 2:

    + +
    +Input: nums = [13,10,35,24,76]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 0 <= nums[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md b/assets/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md new file mode 100644 index 00000000..f0194723 --- /dev/null +++ b/assets/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md @@ -0,0 +1,61 @@ +# [1815. Maximum Number of Groups Getting Fresh Donuts](https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts) + + + +## Description + +

    There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.

    + +

    When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.

    + +

    You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.

    + +

     

    +

    Example 1:

    + +
    +Input: batchSize = 3, groups = [1,2,3,4,5,6]
    +Output: 4
    +Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.
    +
    + +

    Example 2:

    + +
    +Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]
    +Output: 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= batchSize <= 9
    • +
    • 1 <= groups.length <= 30
    • +
    • 1 <= groups[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1816.Truncate Sentence/README_EN.md b/assets/1800-1899/1816.Truncate Sentence/README_EN.md new file mode 100644 index 00000000..ef30674c --- /dev/null +++ b/assets/1800-1899/1816.Truncate Sentence/README_EN.md @@ -0,0 +1,128 @@ +# [1816. Truncate Sentence](https://leetcode.com/problems/truncate-sentence) + + + +## Description + +

    A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).

    + +
      +
    • For example, "Hello World", "HELLO", and "hello world hello world" are all sentences.
    • +
    + +

    You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "Hello how are you Contestant", k = 4
    +Output: "Hello how are you"
    +Explanation:
    +The words in s are ["Hello", "how" "are", "you", "Contestant"].
    +The first 4 words are ["Hello", "how", "are", "you"].
    +Hence, you should return "Hello how are you".
    +
    + +

    Example 2:

    + +
    +Input: s = "What is the solution to this problem", k = 4
    +Output: "What is the solution"
    +Explanation:
    +The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].
    +The first 4 words are ["What", "is", "the", "solution"].
    +Hence, you should return "What is the solution".
    + +

    Example 3:

    + +
    +Input: s = "chopper is not a tanuki", k = 5
    +Output: "chopper is not a tanuki"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • k is in the range [1, the number of words in s].
    • +
    • s consist of only lowercase and uppercase English letters and spaces.
    • +
    • The words in s are separated by a single space.
    • +
    • There are no leading or trailing spaces.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + for i, c in enumerate(s): + if c == ' ': + k -= 1 + if k == 0: + return s[:i] + return s +``` + +### **Java** + +```java +class Solution { + public String truncateSentence(String s, int k) { + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == ' ' && (--k) == 0) { + return s.substring(0, i); + } + } + return s; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string truncateSentence(string s, int k) { + for (int i = 0; i < s.size(); ++i) { + if (s[i] == ' ' && (--k) == 0) { + return s.substr(0, i); + } + } + return s; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var truncateSentence = function (s, k) { + for (let i = 0; i < s.length; ++i) { + if (s[i] == " " && --k == 0) { + return s.substring(0, i); + } + } + return s; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1817.Finding the Users Active Minutes/README_EN.md b/assets/1800-1899/1817.Finding the Users Active Minutes/README_EN.md new file mode 100644 index 00000000..c36a37e6 --- /dev/null +++ b/assets/1800-1899/1817.Finding the Users Active Minutes/README_EN.md @@ -0,0 +1,74 @@ +# [1817. Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes) + + + +## Description + +

    You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.

    + +

    Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.

    + +

    The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.

    + +

    You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.

    + +

    Return the array answer as described above.

    + +

     

    +

    Example 1:

    + +
    +Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5
    +Output: [0,2,0,0,0]
    +Explanation:
    +The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).
    +The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
    +Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.
    +
    + +

    Example 2:

    + +
    +Input: logs = [[1,1],[2,2],[2,3]], k = 4
    +Output: [1,1,0,0]
    +Explanation:
    +The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.
    +The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
    +There is one user with a UAM of 1 and one with a UAM of 2.
    +Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= logs.length <= 104
    • +
    • 0 <= IDi <= 109
    • +
    • 1 <= timei <= 105
    • +
    • k is in the range [The maximum UAM for a user, 105].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md b/assets/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md new file mode 100644 index 00000000..15f10ff2 --- /dev/null +++ b/assets/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md @@ -0,0 +1,85 @@ +# [1818. Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference) + + + +## Description + +

    You are given two positive integer arrays nums1 and nums2, both of length n.

    + +

    The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).

    + +

    You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.

    + +

    Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.

    + +

    |x| is defined as:

    + +
      +
    • x if x >= 0, or
    • +
    • -x if x < 0.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [1,7,5], nums2 = [2,3,5]
    +Output: 3
    +Explanation: There are two possible optimal solutions:
    +- Replace the second element with the first: [1,7,5] => [1,1,5], or
    +- Replace the second element with the third: [1,7,5] => [1,5,5].
    +Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
    +Output: 0
    +Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an 
    +absolute sum difference of 0.
    +
    + +

    Example 3:

    + +
    +Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
    +Output: 20
    +Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
    +This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums1.length
    • +
    • n == nums2.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md b/assets/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md new file mode 100644 index 00000000..dbdffe91 --- /dev/null +++ b/assets/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md @@ -0,0 +1,71 @@ +# [1819. Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds) + + + +## Description + +

    You are given an array nums that consists of positive integers.

    + +

    The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.

    + +
      +
    • For example, the GCD of the sequence [4,6,16] is 2.
    • +
    + +

    A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

    + +
      +
    • For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
    • +
    + +

    Return the number of different GCDs among all non-empty subsequences of nums.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [6,10,3]
    +Output: 5
    +Explanation: The figure shows all the non-empty subsequences and their GCDs.
    +The different GCDs are 6, 10, 3, 2, and 1.
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,15,40,5,6]
    +Output: 7
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 2 * 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1819.Number of Different Subsequences GCDs/images/image-1.png b/assets/1800-1899/1819.Number of Different Subsequences GCDs/images/image-1.png new file mode 100644 index 00000000..fcafe649 Binary files /dev/null and b/assets/1800-1899/1819.Number of Different Subsequences GCDs/images/image-1.png differ diff --git a/assets/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md b/assets/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md new file mode 100644 index 00000000..2a96dbd3 --- /dev/null +++ b/assets/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md @@ -0,0 +1,73 @@ +# [1820. Maximum Number of Accepted Invitations](https://leetcode.com/problems/maximum-number-of-accepted-invitations) + + + +## Description + +

    There are m boys and n girls in a class attending an upcoming party.

    + +

    You are given an m x n integer matrix grid, where grid[i][j] equals 0 or 1. If grid[i][j] == 1, then that means the ith boy can invite the jth girl to the party. A boy can invite at most one girl, and a girl can accept at most one invitation from a boy.

    + +

    Return the maximum possible number of accepted invitations.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,1,1],
    +               [1,0,1],
    +               [0,0,1]]
    +Output: 3
    +Explanation: The invitations are sent as follows:
    +- The 1st boy invites the 2nd girl.
    +- The 2nd boy invites the 1st girl.
    +- The 3rd boy invites the 3rd girl.
    + +

    Example 2:

    + +
    +Input: grid = [[1,0,1,0],
    +               [1,0,0,0],
    +               [0,0,1,0],
    +               [1,1,1,0]]
    +Output: 3
    +Explanation: The invitations are sent as follows:
    +-The 1st boy invites the 3rd girl.
    +-The 2nd boy invites the 1st girl.
    +-The 3rd boy invites no one.
    +-The 4th boy invites the 2nd girl.
    + +

     

    +

    Constraints:

    + +
      +
    • grid.length == m
    • +
    • grid[i].length == n
    • +
    • 1 <= m, n <= 200
    • +
    • grid[i][j] is either 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md b/assets/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md new file mode 100644 index 00000000..abade9de --- /dev/null +++ b/assets/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md @@ -0,0 +1,78 @@ +# [1821. Find Customers With Positive Revenue this Year](https://leetcode.com/problems/find-customers-with-positive-revenue-this-year) + + + +## Description + +

    Table: Customers

    + +
    ++--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| customer_id  | int  |
    +| year         | int  |
    +| revenue      | int  |
    ++--------------+------+
    +(customer_id, year) is the primary key for this table.
    +This table contains the customer ID and the revenue of customers in different years.
    +Note that this revenue can be negative.
    +
    + +

     

    + +

    Write an SQL query to report the customers with postive revenue in the year 2021.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Customers
    ++-------------+------+---------+
    +| customer_id | year | revenue |
    ++-------------+------+---------+
    +| 1           | 2018 | 50      |
    +| 1           | 2021 | 30      |
    +| 1           | 2020 | 70      |
    +| 2           | 2021 | -50     |
    +| 3           | 2018 | 10      |
    +| 3           | 2016 | 50      |
    +| 4           | 2021 | 20      |
    ++-------------+------+---------+
    +
    +Result table:
    ++-------------+
    +| customer_id |
    ++-------------+
    +| 1           |
    +| 4           |
    ++-------------+
    +
    +Customer 1 has revenue equal to 30 in year 2021.
    +Customer 2 has revenue equal to -50 in year 2021.
    +Customer 3 has no revenue in year 2021.
    +Customer 4 has revenue equal to 20 in year 2021.
    +Thus only customers 1 and 4 have postive revenue in year 2021.
    + + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + customer_id +FROM + Customers +WHERE + year = '2021' +AND revenue > 0; +``` + + diff --git a/assets/1800-1899/1822.Sign of the Product of an Array/README_EN.md b/assets/1800-1899/1822.Sign of the Product of an Array/README_EN.md new file mode 100644 index 00000000..766ad819 --- /dev/null +++ b/assets/1800-1899/1822.Sign of the Product of an Array/README_EN.md @@ -0,0 +1,145 @@ +# [1822. Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array) + + + +## Description + +

    There is a function signFunc(x) that returns:

    + +
      +
    • 1 if x is positive.
    • +
    • -1 if x is negative.
    • +
    • 0 if x is equal to 0.
    • +
    + +

    You are given an integer array nums. Let product be the product of all values in the array nums.

    + +

    Return signFunc(product).

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [-1,-2,-3,-4,3,2,1]
    +Output: 1
    +Explanation: The product of all values in the array is 144, and signFunc(144) = 1
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,5,0,2,-3]
    +Output: 0
    +Explanation: The product of all values in the array is 0, and signFunc(0) = 0
    +
    + +

    Example 3:

    + +
    +Input: nums = [-1,1,-1,1,-1]
    +Output: -1
    +Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • -100 <= nums[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def arraySign(self, nums: List[int]) -> int: + res = 1 + for num in nums: + if num == 0: + return 0 + if num < 0: + res *= -1 + return res +``` + +### **Java** + +```java +class Solution { + public int arraySign(int[] nums) { + int res = 1; + for (int num : nums) { + if (num == 0) return 0; + if (num < 0) res *= -1; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var arraySign = function (nums) { + let res = 1; + for (let num of nums) { + if (num == 0) return 0; + if (num < 0) res *= -1; + } + return res; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int arraySign(vector& nums) { + int res = 1; + for (auto &num : nums) { + if (num == 0) { + return 0; + } + if (num < 0) { + res *= -1; + } + } + return res; + } +}; +``` + +### **Go** + +```go +func arraySign(nums []int) int { + res := 1 + for _, num := range nums { + if num == 0 { + return 0 + } + if num < 0 { + res *= -1 + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md b/assets/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md new file mode 100644 index 00000000..9772c5ef --- /dev/null +++ b/assets/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md @@ -0,0 +1,111 @@ +# [1823. Find the Winner of the Circular Game](https://leetcode.com/problems/find-the-winner-of-the-circular-game) + + + +## Description + +

    There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.

    + + + +

    The rules of the game are as follows:

    + + + +
      +
    1. Start at the 1st friend.
    2. +
    3. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.
    4. +
    5. The last friend you counted leaves the circle and loses the game.
    6. +
    7. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.
    8. +
    9. Else, the last friend in the circle wins the game.
    10. +
    + + + +

    Given the number of friends, n, and an integer k, return the winner of the game.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: n = 5, k = 2
    +
    +Output: 3
    +
    +Explanation: Here are the steps of the game:
    +
    +1) Start at friend 1.
    +
    +2) Count 2 friends clockwise, which are friends 1 and 2.
    +
    +3) Friend 2 leaves the circle. Next start is friend 3.
    +
    +4) Count 2 friends clockwise, which are friends 3 and 4.
    +
    +5) Friend 4 leaves the circle. Next start is friend 5.
    +
    +6) Count 2 friends clockwise, which are friends 5 and 1.
    +
    +7) Friend 1 leaves the circle. Next start is friend 3.
    +
    +8) Count 2 friends clockwise, which are friends 3 and 5.
    +
    +9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
    + + + +

    Example 2:

    + + + +
    +
    +Input: n = 6, k = 5
    +
    +Output: 1
    +
    +Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= k <= n <= 500
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1823.Find the Winner of the Circular Game/images/ic234-q2-ex11.png b/assets/1800-1899/1823.Find the Winner of the Circular Game/images/ic234-q2-ex11.png new file mode 100644 index 00000000..41a9248a Binary files /dev/null and b/assets/1800-1899/1823.Find the Winner of the Circular Game/images/ic234-q2-ex11.png differ diff --git a/assets/1800-1899/1824.Minimum Sideway Jumps/README_EN.md b/assets/1800-1899/1824.Minimum Sideway Jumps/README_EN.md new file mode 100644 index 00000000..3ee15b20 --- /dev/null +++ b/assets/1800-1899/1824.Minimum Sideway Jumps/README_EN.md @@ -0,0 +1,84 @@ +# [1824. Minimum Sideway Jumps](https://leetcode.com/problems/minimum-sideway-jumps) + + + +## Description + +

    There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.

    + +

    You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.

    + +
      +
    • For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.
    • +
    + +

    The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.

    + +
      +
    • For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.
    • +
    + +

    Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.

    + +

    Note: There will be no obstacles on points 0 and n.

    + +

     

    +

    Example 1:

    + +
    +Input: obstacles = [0,1,2,3,0]
    +Output: 2 
    +Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).
    +Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).
    +
    + +

    Example 2:

    + +
    +Input: obstacles = [0,1,1,3,3,0]
    +Output: 0
    +Explanation: There are no obstacles on lane 2. No side jumps are required.
    +
    + +

    Example 3:

    + +
    +Input: obstacles = [0,2,1,0,3,0]
    +Output: 2
    +Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • obstacles.length == n + 1
    • +
    • 1 <= n <= 5 * 105
    • +
    • 0 <= obstacles[i] <= 3
    • +
    • obstacles[0] == obstacles[n] == 0
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex1.png b/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex1.png new file mode 100644 index 00000000..2643c4e1 Binary files /dev/null and b/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex1.png differ diff --git a/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex2.png b/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex2.png new file mode 100644 index 00000000..25180b03 Binary files /dev/null and b/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex2.png differ diff --git a/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex3.png b/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex3.png new file mode 100644 index 00000000..6287bbe9 Binary files /dev/null and b/assets/1800-1899/1824.Minimum Sideway Jumps/images/ic234-q3-ex3.png differ diff --git a/assets/1800-1899/1825.Finding MK Average/README_EN.md b/assets/1800-1899/1825.Finding MK Average/README_EN.md new file mode 100644 index 00000000..73088ad1 --- /dev/null +++ b/assets/1800-1899/1825.Finding MK Average/README_EN.md @@ -0,0 +1,85 @@ +# [1825. Finding MK Average](https://leetcode.com/problems/finding-mk-average) + + + +## Description + +

    You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.

    + +

    The MKAverage can be calculated using these steps:

    + +
      +
    1. If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.
    2. +
    3. Remove the smallest k elements and the largest k elements from the container.
    4. +
    5. Calculate the average value for the rest of the elements rounded down to the nearest integer.
    6. +
    + +

    Implement the MKAverage class:

    + +
      +
    • MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k.
    • +
    • void addElement(int num) Inserts a new element num into the stream.
    • +
    • int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
    +[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]
    +Output
    +[null, null, null, -1, null, 3, null, null, null, 5]
    +
    +Explanation
    +MKAverage obj = new MKAverage(3, 1); 
    +obj.addElement(3);        // current elements are [3]
    +obj.addElement(1);        // current elements are [3,1]
    +obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.
    +obj.addElement(10);       // current elements are [3,1,10]
    +obj.calculateMKAverage(); // The last 3 elements are [3,1,10].
    +                          // After removing smallest and largest 1 element the container will be [3].
    +                          // The average of [3] equals 3/1 = 3, return 3
    +obj.addElement(5);        // current elements are [3,1,10,5]
    +obj.addElement(5);        // current elements are [3,1,10,5,5]
    +obj.addElement(5);        // current elements are [3,1,10,5,5,5]
    +obj.calculateMKAverage(); // The last 3 elements are [5,5,5].
    +                          // After removing smallest and largest 1 element the container will be [5].
    +                          // The average of [5] equals 5/1 = 5, return 5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= m <= 105
    • +
    • 1 <= k*2 < m
    • +
    • 1 <= num <= 105
    • +
    • At most 105 calls will be made to addElement and calculateMKAverage.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1826.Faulty Sensor/README_EN.md b/assets/1800-1899/1826.Faulty Sensor/README_EN.md new file mode 100644 index 00000000..49214c04 --- /dev/null +++ b/assets/1800-1899/1826.Faulty Sensor/README_EN.md @@ -0,0 +1,77 @@ +# [1826. Faulty Sensor](https://leetcode.com/problems/faulty-sensor) + + + +## Description + +

    An experiment is being conducted in a lab. To ensure accuracy, there are two sensors collecting data simultaneously. You are given two arrays sensor1 and sensor2, where sensor1[i] and sensor2[i] are the ith data points collected by the two sensors.

    + +

    However, this type of sensor has a chance of being defective, which causes exactly one data point to be dropped. After the data is dropped, all the data points to the right of the dropped data are shifted one place to the left, and the last data point is replaced with some random value. It is guaranteed that this random value will not be equal to the dropped value.

    + +
      +
    • For example, if the correct data is [1,2,3,4,5] and 3 is dropped, the sensor could return [1,2,4,5,7] (the last position can be any value, not just 7).
    • +
    + +

    We know that there is a defect in at most one of the sensors. Return the sensor number (1 or 2) with the defect. If there is no defect in either sensor or if it is impossible to determine the defective sensor, return -1.

    + +

     

    +

    Example 1:

    + +
    +Input: sensor1 = [2,3,4,5], sensor2 = [2,1,3,4]
    +Output: 1
    +Explanation: Sensor 2 has the correct values.
    +The second data point from sensor 2 is dropped, and the last value of sensor 1 is replaced by a 5.
    +
    + +

    Example 2:

    + +
    +Input: sensor1 = [2,2,2,2,2], sensor2 = [2,2,2,2,5]
    +Output: -1
    +Explanation: It is impossible to determine which sensor has a defect.
    +Dropping the last value for either sensor could produce the output for the other sensor.
    +
    + +

    Example 3:

    + +
    +Input: sensor1 = [2,3,2,2,3,2], sensor2 = [2,3,2,3,2,7]
    +Output: 2
    +Explanation: Sensor 1 has the correct values.
    +The fourth data point from sensor 1 is dropped, and the last value of sensor 1 is replaced by a 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • sensor1.length == sensor2.length
    • +
    • 1 <= sensor1.length <= 100
    • +
    • 1 <= sensor1[i], sensor2[i] <= 100
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md b/assets/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md new file mode 100644 index 00000000..51de19d0 --- /dev/null +++ b/assets/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md @@ -0,0 +1,116 @@ +# [1827. Minimum Operations to Make the Array Increasing](https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing) + + + +## Description + +

    You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.

    + +
      +
    • For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].
    • +
    + +

    Return the minimum number of operations needed to make nums strictly increasing.

    + +

    An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: nums = [1,1,1]
    +
    +Output: 3
    +
    +Explanation: You can do the following operations:
    +
    +1) Increment nums[2], so nums becomes [1,1,2].
    +
    +2) Increment nums[1], so nums becomes [1,2,2].
    +
    +3) Increment nums[2], so nums becomes [1,2,3].
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: nums = [1,5,2,4,1]
    +
    +Output: 14
    +
    +
    + +

    Example 3:

    + +
    +
    +Input: nums = [8]
    +
    +Output: 0
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 5000
    • +
    • 1 <= nums[i] <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + pre_max = nums[0] + times = 0 + for i in range(1, n): + if nums[i] <= pre_max: + steps = pre_max - nums[i] + 1 + times += steps + pre_max = nums[i] + steps + else: + pre_max = nums[i] + return times +``` + +### **Java** + +```java +class Solution { + public int minOperations(int[] nums) { + int n = nums.length; + int preMax = nums[0]; + int times = 0; + for (int i = 1; i < n; ++i) { + if (nums[i] <= preMax) { + int steps = preMax - nums[i] + 1; + times += steps; + preMax = nums[i] + steps; + } else { + preMax = nums[i]; + } + } + return times; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md b/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md new file mode 100644 index 00000000..69ca4eed --- /dev/null +++ b/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md @@ -0,0 +1,162 @@ +# [1828. Queries on Number of Points Inside a Circle](https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle) + + + +## Description + +

    You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.

    + +

    You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.

    + +

    For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.

    + +

    Return an array answer, where answer[j] is the answer to the jth query.

    + +

     

    +

    Example 1:

    + +
    +Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]
    +Output: [3,2,2]
    +Explanation: The points and circles are shown above.
    +queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.
    +
    + +

    Example 2:

    + +
    +Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]
    +Output: [2,3,2,4]
    +Explanation: The points and circles are shown above.
    +queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= points.length <= 500
    • +
    • points[i].length == 2
    • +
    • 0 <= x​​​​​​i, y​​​​​​i <= 500
    • +
    • 1 <= queries.length <= 500
    • +
    • queries[j].length == 3
    • +
    • 0 <= xj, yj <= 500
    • +
    • 1 <= rj <= 500
    • +
    • All coordinates are integers.
    • +
    + +

     

    +

    Follow up: Could you find the answer for each query in better complexity than O(n)?

    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]: + ans = [] + for x0, y0, r in queries: + count = 0 + for x, y in points: + dx, dy = x - x0, y - y0 + if dx * dx + dy * dy <= r * r: + count += 1 + ans.append(count) + return ans +``` + +### **Java** + +```java +class Solution { + public int[] countPoints(int[][] points, int[][] queries) { + int[] ans = new int[queries.length]; + int i = 0; + for (int[] query : queries) { + int x0 = query[0], y0 = query[1], r = query[2]; + for (int[] point : points) { + int x = point[0], y = point[1]; + int dx = x - x0, dy = y - y0; + if (dx * dx + dy * dy <= r * r) { + ++ans[i]; + } + } + ++i; + } + return ans; + } +} +``` + +### **TypeScript** + +```ts +function countPoints(points: number[][], queries: number[][]): number[] { + let ans = []; + for (let [cx, cy, r] of queries) { + let square = r ** 2; + let count = 0; + for (let [px, py] of points) { + if ((px - cx) ** 2 + (py - cy) ** 2 <= square) { + ++count; + } + } + ans.push(count); + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector countPoints(vector>& points, vector>& queries) { + vector ans; + for (auto& query : queries) { + int x0 = query[0], y0 = query[1], r = query[2]; + int count = 0; + for (auto& point : points) { + int x = point[0], y = point[1]; + int dx = x - x0, dy = y - y0; + if (dx * dx + dy * dy <= r * r) { + ++count; + } + } + ans.push_back(count); + } + return ans; + } +}; +``` + +### **Go** + +```go +func countPoints(points [][]int, queries [][]int) []int { + ans := make([]int, len(queries)) + for i, query := range queries { + x0, y0, r := query[0], query[1], query[2] + for _, point := range points { + x, y := point[0], point[1] + dx, dy := x-x0, y-y0 + if dx*dx+dy*dy <= r*r { + ans[i]++ + } + } + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/images/chrome_2021-03-25_22-34-16.png b/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/images/chrome_2021-03-25_22-34-16.png new file mode 100644 index 00000000..4cd843c8 Binary files /dev/null and b/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/images/chrome_2021-03-25_22-34-16.png differ diff --git a/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/images/chrome_2021-03-25_22-42-07.png b/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/images/chrome_2021-03-25_22-42-07.png new file mode 100644 index 00000000..96d6b177 Binary files /dev/null and b/assets/1800-1899/1828.Queries on Number of Points Inside a Circle/images/chrome_2021-03-25_22-42-07.png differ diff --git a/assets/1800-1899/1829.Maximum XOR for Each Query/README_EN.md b/assets/1800-1899/1829.Maximum XOR for Each Query/README_EN.md new file mode 100644 index 00000000..aae95262 --- /dev/null +++ b/assets/1800-1899/1829.Maximum XOR for Each Query/README_EN.md @@ -0,0 +1,82 @@ +# [1829. Maximum XOR for Each Query](https://leetcode.com/problems/maximum-xor-for-each-query) + + + +## Description + +

    You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times:

    + +
      +
    1. Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query.
    2. +
    3. Remove the last element from the current array nums.
    4. +
    + +

    Return an array answer, where answer[i] is the answer to the ith query.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [0,1,1,3], maximumBit = 2
    +Output: [0,3,2,3]
    +Explanation: The queries are answered as follows:
    +1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.
    +2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.
    +3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.
    +4th query: nums = [0], k = 3 since 0 XOR 3 = 3.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,3,4,7], maximumBit = 3
    +Output: [5,2,6,5]
    +Explanation: The queries are answered as follows:
    +1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.
    +2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.
    +3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.
    +4th query: nums = [2], k = 5 since 2 XOR 5 = 7.
    +
    + +

    Example 3:

    + +
    +Input: nums = [0,1,2,2,5,7], maximumBit = 3
    +Output: [4,3,6,4,6,7]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • nums.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= maximumBit <= 20
    • +
    • 0 <= nums[i] < 2maximumBit
    • +
    • nums​​​ is sorted in ascending order.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md b/assets/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md new file mode 100644 index 00000000..87f256f3 --- /dev/null +++ b/assets/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md @@ -0,0 +1,86 @@ +# [1830. Minimum Number of Operations to Make String Sorted](https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted) + + + +## Description + +

    You are given a string s (0-indexed)​​​​​​. You are asked to perform the following operation on s​​​​​​ until you get a sorted string:

    + +
      +
    1. Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].
    2. +
    3. Find the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.
    4. +
    5. Swap the two characters at indices i - 1​​​​ and j​​​​​.
    6. +
    7. Reverse the suffix starting at index i​​​​​​.
    8. +
    + +

    Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "cba"
    +Output: 5
    +Explanation: The simulation goes as follows:
    +Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
    +Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
    +Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
    +Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
    +Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
    +
    + +

    Example 2:

    + +
    +Input: s = "aabaa"
    +Output: 2
    +Explanation: The simulation goes as follows:
    +Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
    +Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
    +
    + +

    Example 3:

    + +
    +Input: s = "cdbea"
    +Output: 63
    + +

    Example 4:

    + +
    +Input: s = "leetcodeleetcodeleetcode"
    +Output: 982157772
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 3000
    • +
    • s​​​​​​ consists only of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1831.Maximum Transaction Each Day/README_EN.md b/assets/1800-1899/1831.Maximum Transaction Each Day/README_EN.md new file mode 100644 index 00000000..f9d69201 --- /dev/null +++ b/assets/1800-1899/1831.Maximum Transaction Each Day/README_EN.md @@ -0,0 +1,121 @@ +# [1831. Maximum Transaction Each Day](https://leetcode.com/problems/maximum-transaction-each-day) + + + +## Description + +

    Table: Transactions

    + + + +
    +
    ++----------------+----------+
    +
    +| Column Name    | Type     |
    +
    ++----------------+----------+
    +
    +| transaction_id | int      |
    +
    +| day            | datetime |
    +
    +| amount         | int      |
    +
    ++----------------+----------+
    +
    +transaction_id is the primary key for this table.
    +
    +Each row contains information about one transaction.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the IDs of the transactions with the maximum amount on their respective day. If in one day there are multiple such transactions, return all of them.

    + + + +

    Return the result table in ascending order by transaction_id.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Transactions table:
    +
    ++----------------+--------------------+--------+
    +
    +| transaction_id | day                | amount |
    +
    ++----------------+--------------------+--------+
    +
    +| 8              | 2021-4-3 15:57:28  | 57     |
    +
    +| 9              | 2021-4-28 08:47:25 | 21     |
    +
    +| 1              | 2021-4-29 13:28:30 | 58     |
    +
    +| 5              | 2021-4-28 16:39:59 | 40     |
    +
    +| 6              | 2021-4-29 23:39:28 | 58     |
    +
    ++----------------+--------------------+--------+
    +
    +
    +
    +Result table:
    +
    ++----------------+
    +
    +| transaction_id |
    +
    ++----------------+
    +
    +| 1              |
    +
    +| 5              |
    +
    +| 6              |
    +
    +| 8              |
    +
    ++----------------+
    +
    +"2021-4-3"  --> We have one transaction with ID 8, so we add 8 to the result table.
    +
    +"2021-4-28" --> We have two transactions with IDs 5 and 9. The transaction with ID 5 has an amount of 40, while the transaction with ID 9 has an amount of 21. We only include the transaction with ID 5 as it has the maximum amount this day.
    +
    +"2021-4-29" --> We have two transactions with IDs 1 and 6. Both transactions have the same amount of 58, so we include both in the result table.
    +
    +We order the result table by transaction_id after collecting these IDs.
    + + + +

     

    + +

    Follow up: Could you solve it without using the MAX() function?

    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md b/assets/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md new file mode 100644 index 00000000..8e5c56c2 --- /dev/null +++ b/assets/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md @@ -0,0 +1,103 @@ +# [1832. Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram) + + + +## Description + +

    A pangram is a sentence where every letter of the English alphabet appears at least once.

    + +

    Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
    +Output: true
    +Explanation: sentence contains at least one of every letter of the English alphabet.
    +
    + +

    Example 2:

    + +
    +Input: sentence = "leetcode"
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= sentence.length <= 1000
    • +
    • sentence consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +Set: + +```python +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + return len(set(sentence)) == 26 +``` + +Bit Manipulation: + +```python +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + res = 0 + for c in sentence: + diff = ord(c) - ord('a') + res |= (1 << diff) + if res == 0x3ffffff: + return True + return False +``` + +### **Java** + +HashSet: + +```java +class Solution { + public boolean checkIfPangram(String sentence) { + Set s = new HashSet<>(); + for (int i = 0; i < sentence.length(); ++i) { + s.add(sentence.charAt(i)); + if (s.size() == 26) return true; + } + return false; + } +} +``` + +Bit Manipulation: + +```java +class Solution { + public boolean checkIfPangram(String sentence) { + int res = 0; + for (int i = 0; i < sentence.length(); ++i) { + int diff = sentence.charAt(i) - 'a'; + res |= (1 << diff); + if (res == 0x3ffffff) return true; + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md b/assets/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md new file mode 100644 index 00000000..3752e37d --- /dev/null +++ b/assets/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md @@ -0,0 +1,110 @@ +# [1833. Maximum Ice Cream Bars](https://leetcode.com/problems/maximum-ice-cream-bars) + + + +## Description + +

    It is a sweltering summer day, and a boy wants to buy some ice cream bars.

    + +

    At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. 

    + +

    Return the maximum number of ice cream bars the boy can buy with coins coins.

    + +

    Note: The boy can buy the ice cream bars in any order.

    + +

     

    +

    Example 1:

    + +
    +Input: costs = [1,3,2,4,1], coins = 7
    +Output: 4
    +Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
    +
    + +

    Example 2:

    + +
    +Input: costs = [10,6,8,7,7,8], coins = 5
    +Output: 0
    +Explanation: The boy cannot afford any of the ice cream bars.
    +
    + +

    Example 3:

    + +
    +Input: costs = [1,6,3,1,2,5], coins = 20
    +Output: 6
    +Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • costs.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= costs[i] <= 105
    • +
    • 1 <= coins <= 108
    • +
    + + +## Solutions + +Pay attention to the data range. The question can easily mislead us to use the 01 backpack (it will overtime). In fact, this question is a simple "greedy problem" (choose low-priced ice cream first) + + + +### **Python3** + +```python +class Solution: + def maxIceCream(self, costs: List[int], coins: int) -> int: + costs.sort() + ans, n = 0, len(costs) + for i in range(n): + if coins < costs[i]: + break + else: + ans += 1 + coins -= costs[i] + return ans +``` + +### **Java** + +```java +class Solution { + public int maxIceCream(int[] costs, int coins) { + Arrays.sort(costs); + int ans = 0, n = costs.length; + for (int i = 0; i < n && coins >= costs[i]; i++) { + ans++; + coins -= costs[i]; + } + return ans; + } +} +``` + +### **Go** + +```go +func maxIceCream(costs []int, coins int) int { + sort.Ints(costs) + n := len(costs) + ans := 0 + for i := 0; i < n && coins >= costs[i]; i++ { + ans++ + coins -= costs[i] + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1834.Single-Threaded CPU/README_EN.md b/assets/1800-1899/1834.Single-Threaded CPU/README_EN.md new file mode 100644 index 00000000..ef0d72b4 --- /dev/null +++ b/assets/1800-1899/1834.Single-Threaded CPU/README_EN.md @@ -0,0 +1,85 @@ +# [1834. Single-Threaded CPU](https://leetcode.com/problems/single-threaded-cpu) + + + +## Description + +

    You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.

    + +

    You have a single-threaded CPU that can process at most one task at a time and will act in the following way:

    + +
      +
    • If the CPU is idle and there are no available tasks to process, the CPU remains idle.
    • +
    • If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
    • +
    • Once a task is started, the CPU will process the entire task without stopping.
    • +
    • The CPU can finish a task then start a new one instantly.
    • +
    + +

    Return the order in which the CPU will process the tasks.

    + +

     

    +

    Example 1:

    + +
    +Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
    +Output: [0,2,3,1]
    +Explanation: The events go as follows: 
    +- At time = 1, task 0 is available to process. Available tasks = {0}.
    +- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
    +- At time = 2, task 1 is available to process. Available tasks = {1}.
    +- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
    +- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
    +- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
    +- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
    +- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
    +- At time = 10, the CPU finishes task 1 and becomes idle.
    +
    + +

    Example 2:

    + +
    +Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
    +Output: [4,3,2,0,1]
    +Explanation: The events go as follows:
    +- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
    +- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
    +- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
    +- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
    +- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
    +- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
    +- At time = 40, the CPU finishes task 1 and becomes idle.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • tasks.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= enqueueTimei, processingTimei <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md b/assets/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md new file mode 100644 index 00000000..bc4d9e61 --- /dev/null +++ b/assets/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md @@ -0,0 +1,68 @@ +# [1835. Find XOR Sum of All Pairs Bitwise AND](https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and) + + + +## Description + +

    The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.

    + +
      +
    • For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
    • +
    + +

    You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.

    + +

    Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.

    + +

    Return the XOR sum of the aforementioned list.

    + +

     

    +

    Example 1:

    + +
    +Input: arr1 = [1,2,3], arr2 = [6,5]
    +Output: 0
    +Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
    +The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
    +
    + +

    Example 2:

    + +
    +Input: arr1 = [12], arr2 = [4]
    +Output: 4
    +Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 105
    • +
    • 0 <= arr1[i], arr2[j] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md new file mode 100644 index 00000000..0770c8cc --- /dev/null +++ b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md @@ -0,0 +1,168 @@ +# [1836. Remove Duplicates From an Unsorted Linked List](https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list) + + + +## Description + +

    Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.

    + +

    Return the linked list after the deletions.

    + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: head = [1,2,3,2]
    +
    +Output: [1,3]
    +
    +Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3].
    +
    +
    + +

    Example 2:

    + + + +
    +
    +Input: head = [2,1,1,2]
    +
    +Output: []
    +
    +Explanation: 2 and 1 both appear twice. All the elements should be deleted.
    +
    +
    + +

    Example 3:

    + + + +
    +
    +Input: head = [3,2,2,1,3,2,4]
    +
    +Output: [1,4]
    +
    +Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4].
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • The number of nodes in the list is in the range [1, 105]
    • +
    • 1 <= Node.val <= 105
    • +
    + +## Solutions + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode: + cur = head + counter = collections.Counter() + while cur: + counter[cur.val] += 1 + cur = cur.next + + dummy = ListNode(0, head) + pre, cur = dummy, head + while cur: + if counter[cur.val] > 1: + pre.next = cur.next + else: + pre = cur + cur = cur.next + return dummy.next +``` + +### **Java** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicatesUnsorted(ListNode head) { + Map counter = new HashMap<>(); + for (ListNode cur = head; cur != null; cur = cur.next) { + counter.put(cur.val, counter.getOrDefault(cur.val, 0) + 1); + } + + ListNode dummy = new ListNode(0, head); + for (ListNode pre = dummy, cur = head; cur != null; cur = cur.next) { + if (counter.get(cur.val) > 1) { + pre.next = cur.next; + } else { + pre = cur; + } + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicatesUnsorted(ListNode* head) { + unordered_map counter; + for (ListNode* cur = head; cur != nullptr; cur = cur->next) { + ++counter[cur->val]; + } + + ListNode* dummy = new ListNode(0, head); + for (ListNode* pre = dummy, *cur = head; cur != nullptr; cur = cur->next) { + if (counter[cur->val] > 1) { + pre->next = cur->next; + } else { + pre = cur; + } + } + return dummy->next; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list-1.jpg b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list-1.jpg new file mode 100644 index 00000000..c7b58c13 Binary files /dev/null and b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list-1.jpg differ diff --git a/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list-2.jpg b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list-2.jpg new file mode 100644 index 00000000..b62ec46e Binary files /dev/null and b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list-2.jpg differ diff --git a/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list.jpg b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list.jpg new file mode 100644 index 00000000..e6c23cdc Binary files /dev/null and b/assets/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/images/tmp-linked-list.jpg differ diff --git a/assets/1800-1899/1837.Sum of Digits in Base K/README_EN.md b/assets/1800-1899/1837.Sum of Digits in Base K/README_EN.md new file mode 100644 index 00000000..c878b8f6 --- /dev/null +++ b/assets/1800-1899/1837.Sum of Digits in Base K/README_EN.md @@ -0,0 +1,73 @@ +# [1837. Sum of Digits in Base K](https://leetcode.com/problems/sum-of-digits-in-base-k) + + + +## Description + +

    Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.

    + +

    After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 34, k = 6
    +Output: 9
    +Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
    +
    + +

    Example 2:

    + +
    +Input: n = 10, k = 10
    +Output: 1
    +Explanation: n is already in base 10. 1 + 0 = 1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 100
    • +
    • 2 <= k <= 10
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sumBase(self, n: int, k: int) -> int: + res = 0 + while n != 0: + n, t = divmod(n, k) + res += t + return res +``` + +### **Java** + +```java +class Solution { + public int sumBase(int n, int k) { + int res = 0; + while (n != 0) { + res += (n % k); + n /= k; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md b/assets/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md new file mode 100644 index 00000000..46bb4af9 --- /dev/null +++ b/assets/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md @@ -0,0 +1,129 @@ +# [1838. Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element) + + + +## Description + +

    The frequency of an element is the number of times it occurs in an array.

    + +

    You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.

    + +

    Return the maximum possible frequency of an element after performing at most k operations.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,4], k = 5
    +Output: 3
    +Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
    +4 has a frequency of 3.
    + +

    Example 2:

    + +
    +Input: nums = [1,4,8,13], k = 5
    +Output: 2
    +Explanation: There are multiple optimal solutions:
    +- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
    +- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
    +- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
    +
    + +

    Example 3:

    + +
    +Input: nums = [3,9,6], k = 2
    +Output: 1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    • 1 <= k <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxFrequency(self, nums: List[int], k: int) -> int: + nums.sort() + ans = 1 + window = 0 + l, r, n = 0, 1, len(nums) + while r < n: + window += (nums[r] - nums[r - 1]) * (r - l) + r += 1 + while window > k: + window -= nums[r - 1] - nums[l] + l += 1 + ans = max(ans, r - l) + return ans +``` + +### **Java** + +```java +class Solution { + public int maxFrequency(int[] nums, int k) { + Arrays.sort(nums); + int ans = 1; + int window = 0; + int l = 0, r = 1, n = nums.length; + while (r < n) { + window += (nums[r] - nums[r - 1]) * (r++ - l); + while (window > k) { + window -= nums[r - 1] - nums[l]; + l++; + } + ans = Math.max(ans, r - l); + } + return ans; + } +} +``` + +### **Go** + +```go +func maxFrequency(nums []int, k int) int { + sort.Ints(nums) + ans := 1 + window := 0 + l, r, n := 0, 1, len(nums) + for r < n { + window += (nums[r] - nums[r-1]) * (r - l) + r++ + for window > k { + window -= nums[r-1] - nums[l] + l++ + } + ans = max(ans, r-l) + } + return ans +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md b/assets/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md new file mode 100644 index 00000000..87c78d66 --- /dev/null +++ b/assets/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md @@ -0,0 +1,74 @@ +# [1839. Longest Substring Of All Vowels in Order](https://leetcode.com/problems/longest-substring-of-all-vowels-in-order) + + + +## Description + +

    A string is considered beautiful if it satisfies the following conditions:

    + +
      +
    • Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.
    • +
    • The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).
    • +
    + +

    For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful.

    + +

    Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.

    + +

    A substring is a contiguous sequence of characters in a string.

    + +

     

    +

    Example 1:

    + +
    +Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"
    +Output: 13
    +Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.
    + +

    Example 2:

    + +
    +Input: word = "aeeeiiiioooauuuaeiou"
    +Output: 5
    +Explanation: The longest beautiful substring in word is "aeiou" of length 5.
    +
    + +

    Example 3:

    + +
    +Input: word = "a"
    +Output: 0
    +Explanation: There is no beautiful substring, so return 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word.length <= 5 * 105
    • +
    • word consists of characters 'a', 'e', 'i', 'o', and 'u'.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1840.Maximum Building Height/README_EN.md b/assets/1800-1899/1840.Maximum Building Height/README_EN.md new file mode 100644 index 00000000..7883293a --- /dev/null +++ b/assets/1800-1899/1840.Maximum Building Height/README_EN.md @@ -0,0 +1,83 @@ +# [1840. Maximum Building Height](https://leetcode.com/problems/maximum-building-height) + + + +## Description + +

    You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.

    + +

    However, there are city restrictions on the heights of the new buildings:

    + +
      +
    • The height of each building must be a non-negative integer.
    • +
    • The height of the first building must be 0.
    • +
    • The height difference between any two adjacent buildings cannot exceed 1.
    • +
    + +

    Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.

    + +

    It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.

    + +

    Return the maximum possible height of the tallest building.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, restrictions = [[2,1],[4,1]]
    +Output: 2
    +Explanation: The green area in the image indicates the maximum allowed height for each building.
    +We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.
    + +

    Example 2:

    + +
    +Input: n = 6, restrictions = []
    +Output: 5
    +Explanation: The green area in the image indicates the maximum allowed height for each building.
    +We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.
    +
    + +

    Example 3:

    + +
    +Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]
    +Output: 5
    +Explanation: The green area in the image indicates the maximum allowed height for each building.
    +We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= n <= 109
    • +
    • 0 <= restrictions.length <= min(n - 1, 105)
    • +
    • 2 <= idi <= n
    • +
    • idi is unique.
    • +
    • 0 <= maxHeighti <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex1-1.png b/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex1-1.png new file mode 100644 index 00000000..f6c2222c Binary files /dev/null and b/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex1-1.png differ diff --git a/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex2.png b/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex2.png new file mode 100644 index 00000000..31d66268 Binary files /dev/null and b/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex2.png differ diff --git a/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex3.png b/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex3.png new file mode 100644 index 00000000..08d21ae6 Binary files /dev/null and b/assets/1800-1899/1840.Maximum Building Height/images/ic236-q4-ex3.png differ diff --git a/assets/1800-1899/1841.League Statistics/README_EN.md b/assets/1800-1899/1841.League Statistics/README_EN.md new file mode 100644 index 00000000..f96d5e51 --- /dev/null +++ b/assets/1800-1899/1841.League Statistics/README_EN.md @@ -0,0 +1,188 @@ +# [1841. League Statistics](https://leetcode.com/problems/league-statistics) + + + +## Description + +

    Table: Teams

    + + + +
    +
    ++----------------+---------+
    +
    +| Column Name    | Type    |
    +
    ++----------------+---------+
    +
    +| team_id        | int     |
    +
    +| team_name      | varchar |
    +
    ++----------------+---------+
    +
    +team_id is the primary key for this table.
    +
    +Each row contains information about one team in the league.
    +
    +
    + + + +

     

    + + + +

    Table: Matches

    + + + +
    +
    ++-----------------+---------+
    +
    +| Column Name     | Type    |
    +
    ++-----------------+---------+
    +
    +| home_team_id    | int     |
    +
    +| away_team_id    | int     |
    +
    +| home_team_goals | int     |
    +
    +| away_team_goals | int     |
    +
    ++-----------------+---------+
    +
    +(home_team_id, away_team_id) is the primary key for this table.
    +
    +Each row contains information about one match.
    +
    +home_team_goals is the number of goals scored by the home team.
    +
    +away_team_goals is the number of goals scored by the away team.
    +
    +The winner of the match is the team with the higher number of goals.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the statistics of the league. The statistics should be built using the played matches where the winning team gets three points and the losing team gets no points. If a match ends with a draw, both teams get one point.

    + + + +

    Each row of the result table should contain:

    + + + +
      +
    • team_name - The name of the team in the Teams table.
    • +
    • matches_played - The number of matches played as either a home or away team.
    • +
    • points - The total points the team has so far.
    • +
    • goal_for - The total number of goals scored by the team across all matches.
    • +
    • goal_against - The total number of goals scored by opponent teams against this team across all matches.
    • +
    • goal_diff - The result of goal_for - goal_against.
    • +
    + + + +

    Return the result table in descending order by points. If two or more teams have the same points, order them in descending order by goal_diff. If there is still a tie, order them by team_name in lexicographical order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Teams table:
    +
    ++---------+-----------+
    +
    +| team_id | team_name |
    +
    ++---------+-----------+
    +
    +| 1       | Ajax      |
    +
    +| 4       | Dortmund  |
    +
    +| 6       | Arsenal   |
    +
    ++---------+-----------+
    +
    +
    +
    +Matches table:
    +
    ++--------------+--------------+-----------------+-----------------+
    +
    +| home_team_id | away_team_id | home_team_goals | away_team_goals |
    +
    ++--------------+--------------+-----------------+-----------------+
    +
    +| 1            | 4            | 0               | 1               |
    +
    +| 1            | 6            | 3               | 3               |
    +
    +| 4            | 1            | 5               | 2               |
    +
    +| 6            | 1            | 0               | 0               |
    +
    ++--------------+--------------+-----------------+-----------------+
    +
    +
    +
    +
    +
    +Result table:
    +
    ++-----------+----------------+--------+----------+--------------+-----------+
    +
    +| team_name | matches_played | points | goal_for | goal_against | goal_diff |
    +
    ++-----------+----------------+--------+----------+--------------+-----------+
    +
    +| Dortmund  | 2              | 6      | 6        | 2            | 4         |
    +
    +| Arsenal   | 2              | 2      | 3        | 3            | 0         |
    +
    +| Ajax      | 4              | 2      | 5        | 9            | -4        |
    +
    ++-----------+----------------+--------+----------+--------------+-----------+
    +
    +
    +
    +Ajax (team_id=1) played 4 matches: 2 losses and 2 draws. Total points = 0 + 0 + 1 + 1 = 2.
    +
    +Dortmund (team_id=4) played 2 matches: 2 wins. Total points = 3 + 3 = 6.
    +
    +Arsenal (team_id=6) played 2 matches: 2 draws. Total points = 1 + 1 = 2.
    +
    +Dortmund is the first team in the table. Ajax and Arsenal have the same points, but since Arsenal has a higher goal_diff than Ajax, Arsenal comes before Ajax in the table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md b/assets/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md new file mode 100644 index 00000000..8465803a --- /dev/null +++ b/assets/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md @@ -0,0 +1,102 @@ +# [1842. Next Palindrome Using Same Digits](https://leetcode.com/problems/next-palindrome-using-same-digits) + + + +## Description + +

    You are given a numeric string num, representing a very large palindrome.

    + + + +

    Return the smallest palindrome larger than num that can be created by rearranging its digits. If no such palindrome exists, return an empty string "".

    + + + +

    A palindrome is a number that reads the same backward as forward.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: num = "1221"
    +
    +Output: "2112"
    +
    +Explanation: The next palindrome larger than "1221" is "2112".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: num = "32123"
    +
    +Output: ""
    +
    +Explanation: No palindromes larger than "32123" can be made by rearranging the digits.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: num = "45544554"
    +
    +Output: "54455445"
    +
    +Explanation: The next palindrome larger than "45544554" is "54455445".
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= num.length <= 105
    • +
    • num is a palindrome.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1843.Suspicious Bank Accounts/README_EN.md b/assets/1800-1899/1843.Suspicious Bank Accounts/README_EN.md new file mode 100644 index 00000000..39691dff --- /dev/null +++ b/assets/1800-1899/1843.Suspicious Bank Accounts/README_EN.md @@ -0,0 +1,194 @@ +# [1843. Suspicious Bank Accounts](https://leetcode.com/problems/suspicious-bank-accounts) + + + +## Description + +

    Table: Accounts

    + + + +
    +
    ++----------------+------+
    +
    +| Column Name    | Type |
    +
    ++----------------+------+
    +
    +| account_id     | int  |
    +
    +| max_income     | int  |
    +
    ++----------------+------+
    +
    +account_id is the primary key for this table.
    +
    +Each row contains information about the maximum monthly income for one bank account.
    +
    +
    + + + +

     

    + + + +

    Table: Transactions

    + + + +
    +
    ++----------------+----------+
    +
    +| Column Name    | Type     |
    +
    ++----------------+----------+
    +
    +| transaction_id | int      |
    +
    +| account_id     | int      |
    +
    +| type           | ENUM     |
    +
    +| amount         | int      |
    +
    +| day            | datetime |
    +
    ++----------------+----------+
    +
    +transaction_id is the primary key for this table.
    +
    +Each row contains information about one transaction.
    +
    +type is ENUM ('Creditor','Debtor') where 'Creditor' means the user deposited money into their account and 'Debtor' means the user withdrew money from their account.
    +
    +amount is the amount of money depositied/withdrawn during the transaction.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the IDs of all suspicious bank accounts.

    + + + +

    A bank account is suspicious if the total income exceeds the max_income for this account for two or more consecutive months. The total income of an account in some month is the sum of all its deposits in that month (i.e., transactions of the type 'Creditor').

    + + + +

    Return the result table in ascending order by transaction_id.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Accounts table:
    +
    ++------------+------------+
    +
    +| account_id | max_income |
    +
    ++------------+------------+
    +
    +| 3          | 21000      |
    +
    +| 4          | 10400      |
    +
    ++------------+------------+
    +
    +
    +
    +Transactions table:
    +
    ++----------------+------------+----------+--------+---------------------+
    +
    +| transaction_id | account_id | type     | amount | day                 |
    +
    ++----------------+------------+----------+--------+---------------------+
    +
    +| 2              | 3          | Creditor | 107100 | 2021-06-02 11:38:14 |
    +
    +| 4              | 4          | Creditor | 10400  | 2021-06-20 12:39:18 |
    +
    +| 11             | 4          | Debtor   | 58800  | 2021-07-23 12:41:55 |
    +
    +| 1              | 4          | Creditor | 49300  | 2021-05-03 16:11:04 |
    +
    +| 15             | 3          | Debtor   | 75500  | 2021-05-23 14:40:20 |
    +
    +| 10             | 3          | Creditor | 102100 | 2021-06-15 10:37:16 |
    +
    +| 14             | 4          | Creditor | 56300  | 2021-07-21 12:12:25 |
    +
    +| 19             | 4          | Debtor   | 101100 | 2021-05-09 15:21:49 |
    +
    +| 8              | 3          | Creditor | 64900  | 2021-07-26 15:09:56 |
    +
    +| 7              | 3          | Creditor | 90900  | 2021-06-14 11:23:07 |
    +
    ++----------------+------------+----------+--------+---------------------+
    +
    +
    +
    +Result table:
    +
    ++------------+
    +
    +| account_id |
    +
    ++------------+
    +
    +| 3          |
    +
    ++------------+
    +
    +
    +
    +For account 3:
    +
    +- In 6-2021, the user had an income of 107100 + 102100 + 90900 = 300100.
    +
    +- In 7-2021, the user had an income of 64900.
    +
    +We can see that the income exceeded the max income of 21000 for two consecutive months, so we include 3 in the result table.
    +
    +
    +
    +For account 4:
    +
    +- In 5-2021, the user had an income of 49300.
    +
    +- In 6-2021, the user had an income of 10400.
    +
    +- In 7-2021, the user had an income of 56300.
    +
    +We can see that the income exceeded the max income in May and July, but not in June. Since the account did not exceed the max income for two consecutive months, we do not include it in the result table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + + diff --git a/assets/1800-1899/1844.Replace All Digits with Characters/README_EN.md b/assets/1800-1899/1844.Replace All Digits with Characters/README_EN.md new file mode 100644 index 00000000..018f65db --- /dev/null +++ b/assets/1800-1899/1844.Replace All Digits with Characters/README_EN.md @@ -0,0 +1,85 @@ +# [1844. Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters) + + + +## Description + +

    You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.

    + +

    There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.

    + +
      +
    • For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.
    • +
    + +

    For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).

    + +

    Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "a1c1e1"
    +Output: "abcdef"
    +Explanation: The digits are replaced as follows:
    +- s[1] -> shift('a',1) = 'b'
    +- s[3] -> shift('c',1) = 'd'
    +- s[5] -> shift('e',1) = 'f'
    + +

    Example 2:

    + +
    +Input: s = "a1b2c3d4e"
    +Output: "abbdcfdhe"
    +Explanation: The digits are replaced as follows:
    +- s[1] -> shift('a',1) = 'b'
    +- s[3] -> shift('b',2) = 'd'
    +- s[5] -> shift('c',3) = 'f'
    +- s[7] -> shift('d',4) = 'h'
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s consists only of lowercase English letters and digits.
    • +
    • shift(s[i-1], s[i]) <= 'z' for all odd indices i.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def replaceDigits(self, s: str) -> str: + s = list(s) + for i in range(1, len(s), 2): + s[i] = chr(ord(s[i - 1]) + int(s[i])) + return ''.join(s) +``` + +### **Java** + +```java +class Solution { + public String replaceDigits(String s) { + char[] chars = s.toCharArray(); + for (int i = 1; i < chars.length; i += 2) { + chars[i] = (char) (chars[i - 1] + (chars[i] - '0')); + } + return new String(chars); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1845.Seat Reservation Manager/README_EN.md b/assets/1800-1899/1845.Seat Reservation Manager/README_EN.md new file mode 100644 index 00000000..6f0ed744 --- /dev/null +++ b/assets/1800-1899/1845.Seat Reservation Manager/README_EN.md @@ -0,0 +1,112 @@ +# [1845. Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager) + + + +## Description + +

    Design a system that manages the reservation state of n seats that are numbered from 1 to n.

    + +

    Implement the SeatManager class:

    + +
      +
    • SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
    • +
    • int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
    • +
    • void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]
    +[[5], [], [], [2], [], [], [], [], [5]]
    +Output
    +[null, 1, 2, null, 2, 3, 4, 5, null]
    +
    +Explanation
    +SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
    +seatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is 1.
    +seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
    +seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].
    +seatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.
    +seatManager.reserve();    // The available seats are [3,4,5], so return the lowest of them, which is 3.
    +seatManager.reserve();    // The available seats are [4,5], so return the lowest of them, which is 4.
    +seatManager.reserve();    // The only available seat is seat 5, so return 5.
    +seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 105
    • +
    • 1 <= seatNumber <= n
    • +
    • For each call to reserve, it is guaranteed that there will be at least one unreserved seat.
    • +
    • For each call to unreserve, it is guaranteed that seatNumber will be reserved.
    • +
    • At most 105 calls in total will be made to reserve and unreserve.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class SeatManager: + + def __init__(self, n: int): + self.q = [i for i in range(1, n + 1)] + + def reserve(self) -> int: + return heapq.heappop(self.q) + + def unreserve(self, seatNumber: int) -> None: + heapq.heappush(self.q, seatNumber) + + +# Your SeatManager object will be instantiated and called as such: +# obj = SeatManager(n) +# param_1 = obj.reserve() +# obj.unreserve(seatNumber) +``` + +### **Java** + +```java +class SeatManager { + private PriorityQueue q; + + public SeatManager(int n) { + q = new PriorityQueue<>(n); + for (int i = 1; i <= n; ++i) { + q.offer(i); + } + } + + public int reserve() { + return q.poll(); + } + + public void unreserve(int seatNumber) { + q.offer(seatNumber); + } +} + +/** + * Your SeatManager object will be instantiated and called as such: + * SeatManager obj = new SeatManager(n); + * int param_1 = obj.reserve(); + * obj.unreserve(seatNumber); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md b/assets/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md new file mode 100644 index 00000000..1aa45b51 --- /dev/null +++ b/assets/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md @@ -0,0 +1,87 @@ +# [1846. Maximum Element After Decreasing and Rearranging](https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging) + + + +## Description + +

    You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:

    + +
      +
    • The value of the first element in arr must be 1.
    • +
    • The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.
    • +
    + +

    There are 2 types of operations that you can perform any number of times:

    + +
      +
    • Decrease the value of any element of arr to a smaller positive integer.
    • +
    • Rearrange the elements of arr to be in any order.
    • +
    + +

    Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.

    + +

     

    +

    Example 1:

    + +
    +Input: arr = [2,2,1,2,1]
    +Output: 2
    +Explanation: 
    +We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].
    +The largest element in arr is 2.
    +
    + +

    Example 2:

    + +
    +Input: arr = [100,1,1000]
    +Output: 3
    +Explanation: 
    +One possible way to satisfy the conditions is by doing the following:
    +1. Rearrange arr so it becomes [1,100,1000].
    +2. Decrease the value of the second element to 2.
    +3. Decrease the value of the third element to 3.
    +Now arr = [1,2,3], which satisfies the conditions.
    +The largest element in arr is 3.
    +
    + +

    Example 3:

    + +
    +Input: arr = [1,2,3,4,5]
    +Output: 5
    +Explanation: The array already satisfies the conditions, and the largest element is 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • 1 <= arr[i] <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1847.Closest Room/README_EN.md b/assets/1800-1899/1847.Closest Room/README_EN.md new file mode 100644 index 00000000..c40e8088 --- /dev/null +++ b/assets/1800-1899/1847.Closest Room/README_EN.md @@ -0,0 +1,77 @@ +# [1847. Closest Room](https://leetcode.com/problems/closest-room) + + + +## Description + +

    There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique.

    + +

    You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that:

    + +
      +
    • The room has a size of at least minSizej, and
    • +
    • abs(id - preferredj) is minimized, where abs(x) is the absolute value of x.
    • +
    + +

    If there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1.

    + +

    Return an array answer of length k where answer[j] contains the answer to the jth query.

    + +

     

    +

    Example 1:

    + +
    +Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]
    +Output: [3,-1,3]
    +Explanation: The answers to the queries are as follows:
    +Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
    +Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.
    +Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.
    + +

    Example 2:

    + +
    +Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]
    +Output: [2,1,3]
    +Explanation: The answers to the queries are as follows:
    +Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
    +Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
    +Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.
    + +

     

    +

    Constraints:

    + +
      +
    • n == rooms.length
    • +
    • 1 <= n <= 105
    • +
    • k == queries.length
    • +
    • 1 <= k <= 104
    • +
    • 1 <= roomIdi, preferredj <= 107
    • +
    • 1 <= sizei, minSizej <= 107
    • +
    •  
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md b/assets/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md new file mode 100644 index 00000000..2263035d --- /dev/null +++ b/assets/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md @@ -0,0 +1,103 @@ +# [1848. Minimum Distance to the Target Element](https://leetcode.com/problems/minimum-distance-to-the-target-element) + + + +## Description + +

    Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.

    + +

    Return abs(i - start).

    + +

    It is guaranteed that target exists in nums.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,4,5], target = 5, start = 3
    +Output: 1
    +Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
    +
    + +

    Example 2:

    + +
    +Input: nums = [1], target = 1, start = 0
    +Output: 0
    +Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 1.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
    +Output: 0
    +Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 104
    • +
    • 0 <= start < nums.length
    • +
    • target is in nums.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def getMinDistance(self, nums: List[int], target: int, start: int) -> int: + res = float('inf') + for i, num in enumerate(nums): + if num == target: + res = min(res, abs(i - start)) + return res +``` + +### **Java** + +```java +class Solution { + public int getMinDistance(int[] nums, int target, int start) { + int res = Integer.MAX_VALUE; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == target) { + res = Math.min(res, Math.abs(i - start)); + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int getMinDistance(vector& nums, int target, int start) { + int res = nums.size(); + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == target) { + res = min(res, abs(i - start)); + } + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md b/assets/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md new file mode 100644 index 00000000..c3df9b55 --- /dev/null +++ b/assets/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md @@ -0,0 +1,86 @@ +# [1849. Splitting a String Into Descending Consecutive Values](https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values) + + + +## Description + +

    You are given a string s that consists of only digits.

    + +

    Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.

    + +
      +
    • For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
    • +
    • Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.
    • +
    + +

    Return true if it is possible to split s​​​​​​ as described above, or false otherwise.

    + +

    A substring is a contiguous sequence of characters in a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "1234"
    +Output: false
    +Explanation: There is no valid way to split s.
    +
    + +

    Example 2:

    + +
    +Input: s = "050043"
    +Output: true
    +Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].
    +The values are in descending order with adjacent values differing by 1.
    +
    + +

    Example 3:

    + +
    +Input: s = "9080701"
    +Output: false
    +Explanation: There is no valid way to split s.
    +
    + +

    Example 4:

    + +
    +Input: s = "10009998"
    +Output: true
    +Explanation: s can be split into ["100", "099", "98"] with numerical values [100,99,98].
    +The values are in descending order with adjacent values differing by 1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 20
    • +
    • s only consists of digits.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md b/assets/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md new file mode 100644 index 00000000..6e469984 --- /dev/null +++ b/assets/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md @@ -0,0 +1,90 @@ +# [1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number](https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number) + + + +## Description + +

    You are given a string num, representing a large integer, and an integer k.

    + +

    We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.

    + +
      +
    • For example, when num = "5489355142": +
        +
      • The 1st smallest wonderful integer is "5489355214".
      • +
      • The 2nd smallest wonderful integer is "5489355241".
      • +
      • The 3rd smallest wonderful integer is "5489355412".
      • +
      • The 4th smallest wonderful integer is "5489355421".
      • +
      +
    • +
    + +

    Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.

    + +

    The tests are generated in such a way that kth smallest wonderful integer exists.

    + +

     

    +

    Example 1:

    + +
    +Input: num = "5489355142", k = 4
    +Output: 2
    +Explanation: The 4th smallest wonderful number is "5489355421". To get this number:
    +- Swap index 7 with index 8: "5489355142" -> "5489355412"
    +- Swap index 8 with index 9: "5489355412" -> "5489355421"
    +
    + +

    Example 2:

    + +
    +Input: num = "11112", k = 4
    +Output: 4
    +Explanation: The 4th smallest wonderful number is "21111". To get this number:
    +- Swap index 3 with index 4: "11112" -> "11121"
    +- Swap index 2 with index 3: "11121" -> "11211"
    +- Swap index 1 with index 2: "11211" -> "12111"
    +- Swap index 0 with index 1: "12111" -> "21111"
    +
    + +

    Example 3:

    + +
    +Input: num = "00123", k = 1
    +Output: 1
    +Explanation: The 1st smallest wonderful number is "00132". To get this number:
    +- Swap index 3 with index 4: "00123" -> "00132"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= num.length <= 1000
    • +
    • 1 <= k <= 1000
    • +
    • num only consists of digits.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md b/assets/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md new file mode 100644 index 00000000..8462b968 --- /dev/null +++ b/assets/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md @@ -0,0 +1,72 @@ +# [1851. Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query) + + + +## Description + +

    You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.

    + +

    You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.

    + +

    Return an array containing the answers to the queries.

    + +

     

    +

    Example 1:

    + +
    +Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
    +Output: [3,3,1,4]
    +Explanation: The queries are processed as follows:
    +- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
    +- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
    +- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
    +- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
    +
    + +

    Example 2:

    + +
    +Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
    +Output: [2,-1,4,6]
    +Explanation: The queries are processed as follows:
    +- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
    +- Query = 19: None of the intervals contain 19. The answer is -1.
    +- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
    +- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= intervals.length <= 105
    • +
    • 1 <= queries.length <= 105
    • +
    • queries[i].length == 2
    • +
    • 1 <= lefti <= righti <= 107
    • +
    • 1 <= queries[j] <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md b/assets/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md new file mode 100644 index 00000000..a3f8658b --- /dev/null +++ b/assets/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md @@ -0,0 +1,100 @@ +# [1852. Distinct Numbers in Each Subarray](https://leetcode.com/problems/distinct-numbers-in-each-subarray) + + + +## Description + +

    Given an integer array nums and an integer k, you are asked to construct the array ans of size n-k+1 where ans[i] is the number of distinct numbers in the subarray nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]].

    + + + +

    Return the array ans.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [1,2,3,2,2,1,3], k = 3
    +
    +Output: [3,2,2,2,3]
    +
    +Explanation: The number of distinct elements in each subarray goes as follows:
    +
    +- nums[0:2] = [1,2,3] so ans[0] = 3
    +
    +- nums[1:3] = [2,3,2] so ans[1] = 2
    +
    +- nums[2:4] = [3,2,2] so ans[2] = 2
    +
    +- nums[3:5] = [2,2,1] so ans[3] = 2
    +
    +- nums[4:6] = [2,1,3] so ans[4] = 3
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,1,1,1,2,3,4], k = 4
    +
    +Output: [1,2,3,4]
    +
    +Explanation: The number of distinct elements in each subarray goes as follows:
    +
    +- nums[0:3] = [1,1,1,1] so ans[0] = 1
    +
    +- nums[1:4] = [1,1,1,2] so ans[1] = 2
    +
    +- nums[2:5] = [1,1,2,3] so ans[2] = 3
    +
    +- nums[3:6] = [1,2,3,4] so ans[3] = 4
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= k <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1853.Convert Date Format/README_EN.md b/assets/1800-1899/1853.Convert Date Format/README_EN.md new file mode 100644 index 00000000..58cfe3a4 --- /dev/null +++ b/assets/1800-1899/1853.Convert Date Format/README_EN.md @@ -0,0 +1,60 @@ +# [1853. Convert Date Format](https://leetcode.com/problems/convert-date-format) + + + +## Description + +

    Table: Days

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| day         | date |
    ++-------------+------+
    +day is the primary key for this table.
    +
    + +

     

    + +

    Write an SQL query to convert each date in Days into a string formatted as "day_name, month_name day, year".

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Days table:
    ++------------+
    +| day        |
    ++------------+
    +| 2022-04-12 |
    +| 2021-08-09 |
    +| 2020-06-26 |
    ++------------+
    +
    +Result table:
    ++-------------------------+
    +| day                     |
    ++-------------------------+
    +| Tuesday, April 12, 2022 |
    +| Monday, August 9, 2021  |
    +| Friday, June 26, 2020   |
    ++-------------------------+
    +Please note that the output is case-sensitive.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1854.Maximum Population Year/README_EN.md b/assets/1800-1899/1854.Maximum Population Year/README_EN.md new file mode 100644 index 00000000..d8151fbe --- /dev/null +++ b/assets/1800-1899/1854.Maximum Population Year/README_EN.md @@ -0,0 +1,122 @@ +# [1854. Maximum Population Year](https://leetcode.com/problems/maximum-population-year) + + + +## Description + +

    You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.

    + +

    The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.

    + +

    Return the earliest year with the maximum population.

    + +

     

    +

    Example 1:

    + +
    +Input: logs = [[1993,1999],[2000,2010]]
    +Output: 1993
    +Explanation: The maximum population is 1, and 1993 is the earliest year with this population.
    +
    + +

    Example 2:

    + +
    +Input: logs = [[1950,1961],[1960,1971],[1970,1981]]
    +Output: 1960
    +Explanation: 
    +The maximum population is 2, and it had happened in years 1960 and 1970.
    +The earlier year between them is 1960.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= logs.length <= 100
    • +
    • 1950 <= birthi < deathi <= 2050
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maximumPopulation(self, logs: List[List[int]]) -> int: + offset = 1950 + delta = [0] * 101 + for birth, death in logs: + delta[birth - offset] += 1 + delta[death - offset] -= 1 + mx = cur = res = 0 + for i in range(101): + cur += delta[i] + if mx < cur: + mx = cur + res = i + return res + offset +``` + +### **Java** + +```java +class Solution { + public int maximumPopulation(int[][] logs) { + int offset = 1950; + int[] delta = new int[101]; + for (int[] log : logs) { + ++delta[log[0] - offset]; + --delta[log[1] - offset]; + } + int mx = 0, cur = 0, res = 0; + for (int i = 0; i < 101; ++i) { + cur += delta[i]; + if (mx < cur) { + mx = cur; + res = i; + } + } + return res + offset; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} logs + * @return {number} + */ +var maximumPopulation = function(logs) { + const offset = 1950; + const len = 2050 - 1950 + 1; + let delta = new Array(len).fill(0); + for (let log of logs) { + delta[log[0] - offset] += 1; + delta[log[1] - offset] -= 1; + } + let max = 0; + let total = 0; + let index = 0; + for (let i = 0; i < len; i++) { + total += delta[i]; + if (total > max) { + max = total; + index = i; + } + } + return index + offset; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md b/assets/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md new file mode 100644 index 00000000..db2b28e9 --- /dev/null +++ b/assets/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md @@ -0,0 +1,190 @@ +# [1855. Maximum Distance Between a Pair of Values](https://leetcode.com/problems/maximum-distance-between-a-pair-of-values) + + + +## Description + +

    You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​.

    + +

    A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​.

    + +

    Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.

    + +

    An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
    +Output: 2
    +Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
    +The maximum distance is 2 with pair (2,4).
    +
    + +

    Example 2:

    + +
    +Input: nums1 = [2,2,2], nums2 = [10,10,1]
    +Output: 1
    +Explanation: The valid pairs are (0,0), (0,1), and (1,1).
    +The maximum distance is 1 with pair (0,1).
    +
    + +

    Example 3:

    + +
    +Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
    +Output: 2
    +Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
    +The maximum distance is 2 with pair (2,4).
    +
    + +

    Example 4:

    + +
    +Input: nums1 = [5,4], nums2 = [3,2]
    +Output: 0
    +Explanation: There are no valid pairs, so return 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length <= 105
    • +
    • 1 <= nums2.length <= 105
    • +
    • 1 <= nums1[i], nums2[j] <= 105
    • +
    • Both nums1 and nums2 are non-increasing.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + res, n = 0, len(nums2) + for i, num in enumerate(nums1): + left, right = i, n - 1 + while left < right: + mid = (left + right + 1) >> 1 + if nums2[mid] >= num: + left = mid + else: + right = mid - 1 + res = max(res, left - i) + return res +``` + +### **Java** + +```java +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int res = 0; + int m = nums1.length, n = nums2.length; + for (int i = 0; i < m; ++i) { + int left = i, right = n - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + res = Math.max(res, left - i); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int res = 0; + int m = nums1.size(), n = nums2.size(); + for (int i = 0; i < m; ++i) { + int left = i, right = n - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + res = max(res, left - i); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxDistance(nums1 []int, nums2 []int) int { + res, n := 0, len(nums2) + for i, num := range nums1 { + left, right := i, n-1 + for left < right { + mid := (left + right + 1) >> 1 + if nums2[mid] >= num { + left = mid + } else { + right = mid - 1 + } + } + if res < left-i { + res = left - i + } + } + return res +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDistance = function(nums1, nums2) { + let res = 0; + let m = nums1.length; + let n = nums2.length; + for (let i = 0; i < m; ++i) { + let left = i; + let right = n - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + res = Math.max(res, left - i); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md b/assets/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md new file mode 100644 index 00000000..8f728488 --- /dev/null +++ b/assets/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md @@ -0,0 +1,137 @@ +# [1856. Maximum Subarray Min-Product](https://leetcode.com/problems/maximum-subarray-min-product) + + + +## Description + +

    The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.

    + +
      +
    • For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.
    • +
    + +

    Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7.

    + +

    Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.

    + +

    A subarray is a contiguous part of an array.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,3,2]
    +Output: 14
    +Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).
    +2 * (2+3+2) = 2 * 7 = 14.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,3,3,1,2]
    +Output: 18
    +Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).
    +3 * (3+3) = 3 * 6 = 18.
    +
    + +

    Example 3:

    + +
    +Input: nums = [3,1,5,6,4,2]
    +Output: 60
    +Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).
    +4 * (5+6+4) = 4 * 15 = 60.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 107
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxSumMinProduct(self, nums: List[int]) -> int: + n = len(nums) + pre_sum = [0] * (n + 1) + for i in range(1, n + 1): + pre_sum[i] = pre_sum[i - 1] + nums[i - 1] + + stack = [] + next_lesser = [n] * n + for i in range(n): + while stack and nums[stack[-1]] > nums[i]: + next_lesser[stack.pop()] = i + stack.append(i) + + stack = [] + prev_lesser = [-1] * n + for i in range(n - 1, -1, -1): + while stack and nums[stack[-1]] > nums[i]: + prev_lesser[stack.pop()] = i + stack.append(i) + + res = 0 + for i in range(n): + start, end = prev_lesser[i], next_lesser[i] + t = nums[i] * (pre_sum[end] - pre_sum[start + 1]) + res = max(res, t) + return res % (10 ** 9 + 7) +``` + +### **Java** + +```java +class Solution { + public int maxSumMinProduct(int[] nums) { + int n = nums.length; + long[] preSum = new long[n + 1]; + for (int i = 1; i < n + 1; ++i) { + preSum[i] = preSum[i - 1] + nums[i - 1]; + } + Deque stack = new ArrayDeque<>(); + int[] nextLesser = new int[n]; + Arrays.fill(nextLesser, n); + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + nextLesser[stack.pop()] = i; + } + stack.push(i); + } + + stack = new ArrayDeque<>(); + int[] prevLesser = new int[n]; + Arrays.fill(prevLesser, -1); + for (int i = n - 1; i >= 0; --i) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + prevLesser[stack.pop()] = i; + } + stack.push(i); + } + long res = 0; + for (int i = 0; i < n; ++i) { + int start = prevLesser[i], end = nextLesser[i]; + long t = nums[i] * (preSum[end] - preSum[start + 1]); + res = Math.max(res, t); + } + return (int) (res % 1000000007); + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md b/assets/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md new file mode 100644 index 00000000..382c2b57 --- /dev/null +++ b/assets/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md @@ -0,0 +1,71 @@ +# [1857. Largest Color Value in a Directed Graph](https://leetcode.com/problems/largest-color-value-in-a-directed-graph) + + + +## Description + +

    There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.

    + +

    You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.

    + +

    A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.

    + +

    Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
    +Output: 3
    +Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).
    +
    + +

    Example 2:

    + +

    + +
    +Input: colors = "a", edges = [[0,0]]
    +Output: -1
    +Explanation: There is a cycle from 0 to 0.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == colors.length
    • +
    • m == edges.length
    • +
    • 1 <= n <= 105
    • +
    • 0 <= m <= 105
    • +
    • colors consists of lowercase English letters.
    • +
    • 0 <= aj, bj < n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1857.Largest Color Value in a Directed Graph/images/leet1.png b/assets/1800-1899/1857.Largest Color Value in a Directed Graph/images/leet1.png new file mode 100644 index 00000000..3889603a Binary files /dev/null and b/assets/1800-1899/1857.Largest Color Value in a Directed Graph/images/leet1.png differ diff --git a/assets/1800-1899/1857.Largest Color Value in a Directed Graph/images/leet2.png b/assets/1800-1899/1857.Largest Color Value in a Directed Graph/images/leet2.png new file mode 100644 index 00000000..69ef9123 Binary files /dev/null and b/assets/1800-1899/1857.Largest Color Value in a Directed Graph/images/leet2.png differ diff --git a/assets/1800-1899/1858.Longest Word With All Prefixes/README_EN.md b/assets/1800-1899/1858.Longest Word With All Prefixes/README_EN.md new file mode 100644 index 00000000..81a1989e --- /dev/null +++ b/assets/1800-1899/1858.Longest Word With All Prefixes/README_EN.md @@ -0,0 +1,105 @@ +# [1858. Longest Word With All Prefixes](https://leetcode.com/problems/longest-word-with-all-prefixes) + + + +## Description + +

    Given an array of strings words, find the longest string in words such that every prefix of it is also in words.

    + + + +
      +
    • For example, let words = ["a", "app", "ap"]. The string "app" has prefixes "ap" and "a", all of which are in words.
    • +
    + + + +

    Return the string described above. If there is more than one string with the same length, return the lexicographically smallest one, and if no string exists, return "".

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: words = ["k","ki","kir","kira", "kiran"]
    +
    +Output: "kiran"
    +
    +Explanation: "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
    +
    +Output: "apple"
    +
    +Explanation: Both "apple" and "apply" have all their prefixes in words.
    +
    +However, "apple" is lexicographically smaller, so we return that.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: words = ["abc", "bc", "ab", "qwe"]
    +
    +Output: ""
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= words.length <= 105
    • +
    • 1 <= words[i].length <= 105
    • +
    • 1 <= sum(words[i].length) <= 105
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1859.Sorting the Sentence/README_EN.md b/assets/1800-1899/1859.Sorting the Sentence/README_EN.md new file mode 100644 index 00000000..62a0474a --- /dev/null +++ b/assets/1800-1899/1859.Sorting the Sentence/README_EN.md @@ -0,0 +1,114 @@ +# [1859. Sorting the Sentence](https://leetcode.com/problems/sorting-the-sentence) + + + +## Description + +

    A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.

    + +

    A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.

    + +
      +
    • For example, the sentence "This is a sentence" can be shuffled as "sentence4 a3 is2 This1" or "is2 sentence4 This1 a3".
    • +
    + +

    Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: s = "is2 sentence4 This1 a3"
    +
    +Output: "This is a sentence"
    +
    +Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: s = "Myself2 Me1 I4 and3"
    +
    +Output: "Me Myself and I"
    +
    +Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 2 <= s.length <= 200
    • +
    • s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
    • +
    • The number of words in s is between 1 and 9.
    • +
    • The words in s are separated by a single space.
    • +
    • s contains no leading or trailing spaces.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def sortSentence(self, s: str) -> str: + words = s.split(' ') + arr = [None] * len(words) + for word in words: + idx = int(word[-1]) - 1 + arr[idx] = word[:-1] + return ' '.join(arr) +``` + +### **Java** + +```java +class Solution { + public String sortSentence(String s) { + String[] words = s.split(" "); + String[] arr = new String[words.length]; + for (String word : words) { + int idx = word.charAt(word.length() - 1) - '0' - 1; + arr[idx] = word.substring(0, word.length() - 1); + } + return String.join(" ", arr); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {string} + */ +var sortSentence = function(s) { + let words = s.split(' '); + let n = words.length; + let res = new Array(n); + for (let word of words) { + let key = word.slice(-1); + let val = word.slice(0, -1); + res[parseInt(key) - 1] = val; + } + return res.join(' '); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1860.Incremental Memory Leak/README_EN.md b/assets/1800-1899/1860.Incremental Memory Leak/README_EN.md new file mode 100644 index 00000000..f5622768 --- /dev/null +++ b/assets/1800-1899/1860.Incremental Memory Leak/README_EN.md @@ -0,0 +1,132 @@ +# [1860. Incremental Memory Leak](https://leetcode.com/problems/incremental-memory-leak) + + + +## Description + +

    You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.

    + +

    At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.

    + +

    Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.

    + +

     

    +

    Example 1:

    + +
    +Input: memory1 = 2, memory2 = 2
    +Output: [3,1,0]
    +Explanation: The memory is allocated as follows:
    +- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.
    +- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.
    +- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.
    +
    + +

    Example 2:

    + +
    +Input: memory1 = 8, memory2 = 11
    +Output: [6,0,4]
    +Explanation: The memory is allocated as follows:
    +- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.
    +- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.
    +- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.
    +- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.
    +- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.
    +- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 0 <= memory1, memory2 <= 231 - 1
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def memLeak(self, memory1: int, memory2: int) -> List[int]: + i = 1 + while memory1 >= i or memory2 >= i: + if memory1 >= memory2: + memory1 -= i + else: + memory2 -= i + i += 1 + return [i, memory1, memory2] +``` + +### **Java** + +```java +class Solution { + public int[] memLeak(int memory1, int memory2) { + int i = 1; + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + ++i; + } + return new int[]{i, memory1, memory2}; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} memory1 + * @param {number} memory2 + * @return {number[]} + */ +var memLeak = function(memory1, memory2) { + let i = 1; + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + i++; + } + return [i, memory1, memory2]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector memLeak(int memory1, int memory2) { + int i = 1; + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + ++i; + } + return {i, memory1, memory2}; + } +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1861.Rotating the Box/README_EN.md b/assets/1800-1899/1861.Rotating the Box/README_EN.md new file mode 100644 index 00000000..a2ba55f2 --- /dev/null +++ b/assets/1800-1899/1861.Rotating the Box/README_EN.md @@ -0,0 +1,169 @@ +# [1861. Rotating the Box](https://leetcode.com/problems/rotating-the-box) + + + +## Description + +

    You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:

    + +
      +
    • A stone '#'
    • +
    • A stationary obstacle '*'
    • +
    • Empty '.'
    • +
    + +

    The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.

    + +

    It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.

    + +

    Return an n x m matrix representing the box after the rotation described above.

    + +

     

    + +

    Example 1:

    + +

    + +
    +
    +Input: box = [["#",".","#"]]
    +
    +Output: [["."],
    +
    +         ["#"],
    +
    +         ["#"]]
    +
    +
    + +

    Example 2:

    + +

    + +
    +
    +Input: box = [["#",".","*","."],
    +
    +              ["#","#","*","."]]
    +
    +Output: [["#","."],
    +
    +         ["#","#"],
    +
    +         ["*","*"],
    +
    +         [".","."]]
    +
    +
    + +

    Example 3:

    + +

    + +
    +
    +Input: box = [["#","#","*",".","*","."],
    +
    +              ["#","#","#","*",".","."],
    +
    +              ["#","#","#",".","#","."]]
    +
    +Output: [[".","#","#"],
    +
    +         [".","#","#"],
    +
    +         ["#","#","*"],
    +
    +         ["#","*","."],
    +
    +         ["#",".","*"],
    +
    +         ["#",".","."]]
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • m == box.length
    • +
    • n == box[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • box[i][j] is either '#', '*', or '.'.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: + m, n = len(box), len(box[0]) + res = [[None] * m for _ in range(n)] + for i in range(m): + for j in range(n): + res[j][m - i - 1] = box[i][j] + for j in range(m): + q = collections.deque() + for i in range(n - 1, -1, -1): + if res[i][j] == '*': + q.clear() + continue + if res[i][j] == '.': + q.append(i) + else: + if not q: + continue + res[q.popleft()][j] = '#' + res[i][j] = '.' + q.append(i) + return res +``` + +### **Java** + +```java +class Solution { + public char[][] rotateTheBox(char[][] box) { + int m = box.length, n = box[0].length; + char[][] res = new char[n][m]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + res[j][m - i - 1] = box[i][j]; + } + } + for (int j = 0; j < m; ++j) { + Deque q = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + if (res[i][j] == '*') { + q.clear(); + continue; + } + if (res[i][j] == '.') { + q.offer(i); + } else { + if (q.isEmpty()) { + continue; + } + res[q.poll()][j] = '#'; + res[i][j] = '.'; + q.offer(i); + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcode2withstones.png b/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcode2withstones.png new file mode 100644 index 00000000..4e26b875 Binary files /dev/null and b/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcode2withstones.png differ diff --git a/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcode3withstone.png b/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcode3withstone.png new file mode 100644 index 00000000..7de38258 Binary files /dev/null and b/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcode3withstone.png differ diff --git a/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcodewithstones.png b/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcodewithstones.png new file mode 100644 index 00000000..6135c797 Binary files /dev/null and b/assets/1800-1899/1861.Rotating the Box/images/rotatingtheboxleetcodewithstones.png differ diff --git a/assets/1800-1899/1862.Sum of Floored Pairs/README_EN.md b/assets/1800-1899/1862.Sum of Floored Pairs/README_EN.md new file mode 100644 index 00000000..ecc4886e --- /dev/null +++ b/assets/1800-1899/1862.Sum of Floored Pairs/README_EN.md @@ -0,0 +1,64 @@ +# [1862. Sum of Floored Pairs](https://leetcode.com/problems/sum-of-floored-pairs) + + + +## Description + +

    Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.

    + +

    The floor() function returns the integer part of the division.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,5,9]
    +Output: 10
    +Explanation:
    +floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
    +floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
    +floor(5 / 2) = 2
    +floor(9 / 2) = 4
    +floor(9 / 5) = 1
    +We calculate the floor of the division for every pair of indices in the array then sum them up.
    +
    + +

    Example 2:

    + +
    +Input: nums = [7,7,7,7,7,7,7]
    +Output: 49
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md b/assets/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md new file mode 100644 index 00000000..e0b29cb4 --- /dev/null +++ b/assets/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md @@ -0,0 +1,143 @@ +# [1863. Sum of All Subset XOR Totals](https://leetcode.com/problems/sum-of-all-subset-xor-totals) + + + +## Description + +

    The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.

    + +
      +
    • For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
    • +
    + +

    Given an array nums, return the sum of all XOR totals for every subset of nums

    + +

    Note: Subsets with the same elements should be counted multiple times.

    + +

    An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,3]
    +Output: 6
    +Explanation: The 4 subsets of [1,3] are:
    +- The empty subset has an XOR total of 0.
    +- [1] has an XOR total of 1.
    +- [3] has an XOR total of 3.
    +- [1,3] has an XOR total of 1 XOR 3 = 2.
    +0 + 1 + 3 + 2 = 6
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,1,6]
    +Output: 28
    +Explanation: The 8 subsets of [5,1,6] are:
    +- The empty subset has an XOR total of 0.
    +- [5] has an XOR total of 5.
    +- [1] has an XOR total of 1.
    +- [6] has an XOR total of 6.
    +- [5,1] has an XOR total of 5 XOR 1 = 4.
    +- [5,6] has an XOR total of 5 XOR 6 = 3.
    +- [1,6] has an XOR total of 1 XOR 6 = 7.
    +- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
    +0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
    +
    + +

    Example 3:

    + +
    +Input: nums = [3,4,5,6,7,8]
    +Output: 480
    +Explanation: The sum of all XOR totals for every subset is 480.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 12
    • +
    • 1 <= nums[i] <= 20
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(nums, depth, prev): + self.res += prev + for num in nums[depth:]: + prev ^= num + depth += 1 + dfs(nums, depth, prev) + prev ^= num + + self.res = 0 + dfs(nums, 0, 0) + return self.res +``` + +### **Java** + +```java +class Solution { + private int res; + + public int subsetXORSum(int[] nums) { + dfs(nums, 0, 0); + return res; + } + + private void dfs(int[] nums, int depth, int prev) { + res += prev; + for (int i = depth; i < nums.length; ++i) { + prev ^= nums[i]; + dfs(nums, ++depth, prev); + prev ^= nums[i]; + } + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ + var subsetXORSum = function(nums) { + let res = []; + let prev = 0; + dfs(nums, 0, prev, res); + return res.reduce((a, c) => a + c, 0) +}; + +function dfs(nums, depth, prev, res) { + res.push(prev); + for (let i = depth; i < nums.length; i++) { + prev ^= nums[i]; + depth++; + dfs(nums, depth, prev, res); + // bracktrack + prev ^= nums[i]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md b/assets/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md new file mode 100644 index 00000000..1d8a70ed --- /dev/null +++ b/assets/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md @@ -0,0 +1,152 @@ +# [1864. Minimum Number of Swaps to Make the Binary String Alternating](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating) + + + +## Description + +

    Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.

    + +

    The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.

    + +

    Any two characters may be swapped, even if they are not adjacent.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "111000"
    +Output: 1
    +Explanation: Swap positions 1 and 4: "111000" -> "101010"
    +The string is now alternating.
    +
    + +

    Example 2:

    + +
    +Input: s = "010"
    +Output: 0
    +Explanation: The string is already alternating, no swaps are needed.
    +
    + +

    Example 3:

    + +
    +Input: s = "1110"
    +Output: -1
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] is either '0' or '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minSwaps(self, s: str) -> int: + s0n0 = s0n1 = s1n0 = s1n1 = 0 + for i in range(len(s)): + if (i & 1) == 0: + if s[i] != '0': + s0n0 += 1 + else: + s1n1 += 1 + else: + if s[i] != '0': + s1n0 += 1 + else: + s0n1 += 1 + if s0n0 != s0n1 and s1n0 != s1n1: + return -1 + if s0n0 != s0n1: + return s1n0 + if s1n0 != s1n1: + return s0n0 + return min(s0n0, s1n0) +``` + +### **Java** + +```java +class Solution { + public int minSwaps(String s) { + int s0n0 = 0, s0n1 = 0; + int s1n0 = 0, s1n1 = 0; + for (int i = 0; i < s.length(); ++i) { + if ((i & 1) == 0) { + if (s.charAt(i) != '0') { + s0n0 += 1; + } else { + s1n1 += 1; + } + } else { + if (s.charAt(i) != '0') { + s1n0 += 1; + } else { + s0n1 += 1; + } + } + } + if (s0n0 != s0n1 && s1n0 != s1n1) { + return -1; + } + if (s0n0 != s0n1) { + return s1n0; + } + if (s1n0 != s1n1) { + return s0n0; + } + return Math.min(s0n0, s1n0); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {number} + */ + var minSwaps = function(s) { + let n = s.length; + let n1 = [...s].reduce((a, c) => parseInt(c) + a, 0); + let n0 = n - n1; + let count = Infinity; + let half = n / 2; + // 101、1010 + if (n1 == Math.ceil(half) && n0 == Math.floor(half)) { + let cur = 0; + for (let i = 0; i < n; i++) { + if (i % 2 == 0 && s.charAt(i) != '1') cur++; + } + count = Math.min(count, cur); + } + // 010、0101 + if (n0 == Math.ceil(half) && n1 == Math.floor(half)) { + let cur = 0; + for (let i = 0; i < n; i++) { + if (i % 2 == 0 && s.charAt(i) != '0') cur++; + } + count = Math.min(count, cur); + } + return count == Infinity ? -1 : count; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md b/assets/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md new file mode 100644 index 00000000..87ef2d64 --- /dev/null +++ b/assets/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md @@ -0,0 +1,133 @@ +# [1865. Finding Pairs With a Certain Sum](https://leetcode.com/problems/finding-pairs-with-a-certain-sum) + + + +## Description + +

    You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types:

    + +
      +
    1. Add a positive integer to an element of a given index in the array nums2.
    2. +
    3. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length).
    4. +
    + +

    Implement the FindSumPairs class:

    + +
      +
    • FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2.
    • +
    • void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val.
    • +
    • int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input
    +["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"]
    +[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]
    +Output
    +[null, 8, null, 2, 1, null, null, 11]
    +
    +Explanation
    +FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);
    +findSumPairs.count(7);  // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4
    +findSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]
    +findSumPairs.count(8);  // return 2; pairs (5,2), (5,4) make 3 + 5
    +findSumPairs.count(4);  // return 1; pair (5,0) makes 3 + 1
    +findSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]
    +findSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]
    +findSumPairs.count(7);  // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums1.length <= 1000
    • +
    • 1 <= nums2.length <= 105
    • +
    • 1 <= nums1[i] <= 109
    • +
    • 1 <= nums2[i] <= 105
    • +
    • 0 <= index < nums2.length
    • +
    • 1 <= val <= 105
    • +
    • 1 <= tot <= 109
    • +
    • At most 1000 calls are made to add and count each.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class FindSumPairs: + + def __init__(self, nums1: List[int], nums2: List[int]): + self.nums1 = nums1 + self.nums2 = nums2 + self.counter = collections.Counter(nums2) + + def add(self, index: int, val: int) -> None: + old_val = self.nums2[index] + self.counter[old_val] -= 1 + self.nums2[index] += val + self.counter[old_val + val] += 1 + + def count(self, tot: int) -> int: + return sum([self.counter[tot - num] for num in self.nums1]) + +# Your FindSumPairs object will be instantiated and called as such: +# obj = FindSumPairs(nums1, nums2) +# obj.add(index,val) +# param_2 = obj.count(tot) +``` + +### **Java** + +```java +class FindSumPairs { + private int[] nums1; + private int[] nums2; + private Map counter; + + public FindSumPairs(int[] nums1, int[] nums2) { + this.nums1 = nums1; + this.nums2 = nums2; + counter = new HashMap<>(); + for (int num : nums2) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + } + + public void add(int index, int val) { + int oldVal = nums2[index]; + counter.put(oldVal, counter.get(oldVal) - 1); + nums2[index] += val; + counter.put(oldVal + val, counter.getOrDefault(oldVal + val, 0) + 1); + } + + public int count(int tot) { + int res = 0; + for (int num : nums1) { + res += counter.getOrDefault(tot - num, 0); + } + return res; + } +} + +/** + * Your FindSumPairs object will be instantiated and called as such: + * FindSumPairs obj = new FindSumPairs(nums1, nums2); + * obj.add(index,val); + * int param_2 = obj.count(tot); + */ +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md b/assets/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md new file mode 100644 index 00000000..857db740 --- /dev/null +++ b/assets/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md @@ -0,0 +1,73 @@ +# [1866. Number of Ways to Rearrange Sticks With K Sticks Visible](https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible) + + + +## Description + +

    There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.

    + +
      +
    • For example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.
    • +
    + +

    Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 3, k = 2
    +Output: 3
    +Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.
    +The visible sticks are underlined.
    +
    + +

    Example 2:

    + +
    +Input: n = 5, k = 5
    +Output: 1
    +Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.
    +The visible sticks are underlined.
    +
    + +

    Example 3:

    + +
    +Input: n = 20, k = 11
    +Output: 647427950
    +Explanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1000
    • +
    • 1 <= k <= n
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md b/assets/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md new file mode 100644 index 00000000..8ef75af2 --- /dev/null +++ b/assets/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md @@ -0,0 +1,93 @@ +# [1867. Orders With Maximum Quantity Above Average](https://leetcode.com/problems/orders-with-maximum-quantity-above-average) + + + +## Description + +

    Table: OrdersDetails

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| order_id    | int  |
    +| product_id  | int  |
    +| quantity    | int  |
    ++-------------+------+
    +(order_id, product_id) is the primary key for this table.
    +A single order is represented as multiple rows, one row for each product in the order.
    +Each row of this table contains the quantity ordered of the product product_id in the order order_id.
    +
    + +

     

    + +

    You are running an ecommerce site that is looking for imbalanced orders. An imbalanced order is one whose maximum quantity is strictly greater than the average quantity of every order (including itself).

    + +

    The average quantity of an order is calculated as (total quantity of all products in the order) / (number of different products in the order). The maximum quantity of an order is the highest quantity of any single product in the order.

    + +

    Write an SQL query to find the order_id of all imbalanced orders.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +OrdersDetails table:
    ++----------+------------+----------+
    +| order_id | product_id | quantity |
    ++----------+------------+----------+
    +| 1        | 1          | 12       |
    +| 1        | 2          | 10       |
    +| 1        | 3          | 15       |
    +| 2        | 1          | 8        |
    +| 2        | 4          | 4        |
    +| 2        | 5          | 6        |
    +| 3        | 3          | 5        |
    +| 3        | 4          | 18       |
    +| 4        | 5          | 2        |
    +| 4        | 6          | 8        |
    +| 5        | 7          | 9        |
    +| 5        | 8          | 9        |
    +| 3        | 9          | 20       |
    +| 2        | 9          | 4        |
    ++----------+------------+----------+
    +
    +Result table:
    ++----------+
    +| order_id |
    ++----------+
    +| 1        |
    +| 3        |
    ++----------+
    +
    +The average quantity of each order is:
    +- order_id=1: (12+10+15)/3 = 12.3333333
    +- order_id=2: (8+4+6+4)/4 = 5.5
    +- order_id=3: (5+18+20)/3 = 14.333333
    +- order_id=4: (2+8)/2 = 5
    +- order_id=5: (9+9)/2 = 9
    +
    +The maximum quantity of each order is:
    +- order_id=1: max(12, 10, 15) = 15
    +- order_id=2: max(8, 4, 6, 4) = 8
    +- order_id=3: max(5, 18, 20) = 20
    +- order_id=4: max(2, 8) = 8
    +- order_id=5: max(9, 9) = 9
    +
    +Orders 1 and 3 are imbalanced because they have a maximum quantity that exceeds the average quantity of every order.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md b/assets/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md new file mode 100644 index 00000000..0aa81a62 --- /dev/null +++ b/assets/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md @@ -0,0 +1,81 @@ +# [1868. Product of Two Run-Length Encoded Arrays](https://leetcode.com/problems/product-of-two-run-length-encoded-arrays) + + + +## Description + +

    Run-length encoding is a compression algorithm that allows for an integer array nums with many segments of consecutive repeated numbers to be represented by a (generally smaller) 2D array encoded. Each encoded[i] = [vali, freqi] describes the ith segment of repeated numbers in nums where vali is the value that is repeated freqi times.

    + +
      +
    • For example, nums = [1,1,1,2,2,2,2,2] is represented by the run-length encoded array encoded = [[1,3],[2,5]]. Another way to read this is "three 1's followed by five 2's".
    • +
    + +

    The product of two run-length encoded arrays encoded1 and encoded2 can be calculated using the following steps:

    + +
      +
    1. Expand both encoded1 and encoded2 into the full arrays nums1 and nums2 respectively.
    2. +
    3. Create a new array prodNums of length nums1.length and set prodNums[i] = nums1[i] * nums2[i].
    4. +
    5. Compress prodNums into a run-length encoded array and return it.
    6. +
    + +

    You are given two run-length encoded arrays encoded1 and encoded2 representing full arrays nums1 and nums2 respectively. Both nums1 and nums2 have the same length. Each encoded1[i] = [vali, freqi] describes the ith segment of nums1, and each encoded2[j] = [valj, freqj] describes the jth segment of nums2.

    + +

    Return the product of encoded1 and encoded2.

    + +

    Note: Compression should be done such that the run-length encoded array has the minimum possible length.

    + +

     

    +

    Example 1:

    + +
    +Input: encoded1 = [[1,3],[2,3]], encoded2 = [[6,3],[3,3]]
    +Output: [[6,6]]
    +Explanation: encoded1 expands to [1,1,1,2,2,2] and encoded2 expands to [6,6,6,3,3,3].
    +prodNums = [6,6,6,6,6,6], which is compressed into the run-length encoded array [[6,6]].
    +
    + +

    Example 2:

    + +
    +Input: encoded1 = [[1,3],[2,1],[3,2]], encoded2 = [[2,3],[3,3]]
    +Output: [[2,3],[6,1],[9,2]]
    +Explanation: encoded1 expands to [1,1,1,2,3,3] and encoded2 expands to [2,2,2,3,3,3].
    +prodNums = [2,2,2,6,9,9], which is compressed into the run-length encoded array [[2,3],[6,1],[9,2]].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= encoded1.length, encoded2.length <= 105
    • +
    • encoded1[i].length == 2
    • +
    • encoded2[j].length == 2
    • +
    • 1 <= vali, freqi <= 104 for each encoded1[i].
    • +
    • 1 <= valj, freqj <= 104 for each encoded2[j].
    • +
    • The full arrays that encoded1 and encoded2 represent are the same length.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md b/assets/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md new file mode 100644 index 00000000..0b677d64 --- /dev/null +++ b/assets/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md @@ -0,0 +1,134 @@ +# [1869. Longer Contiguous Segments of Ones than Zeros](https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros) + + + +## Description + +

    Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.

    + +
      +
    • For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.
    • +
    + +

    Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "1101"
    +Output: true
    +Explanation:
    +The longest contiguous segment of 1s has length 2: "1101"
    +The longest contiguous segment of 0s has length 1: "1101"
    +The segment of 1s is longer, so return true.
    +
    + +

    Example 2:

    + +
    +Input: s = "111000"
    +Output: false
    +Explanation:
    +The longest contiguous segment of 1s has length 3: "111000"
    +The longest contiguous segment of 0s has length 3: "111000"
    +The segment of 1s is not longer, so return false.
    +
    + +

    Example 3:

    + +
    +Input: s = "110100010"
    +Output: false
    +Explanation:
    +The longest contiguous segment of 1s has length 2: "110100010"
    +The longest contiguous segment of 0s has length 3: "110100010"
    +The segment of 1s is not longer, so return false.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s[i] is either '0' or '1'.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def checkZeroOnes(self, s: str) -> bool: + len0 = len1 = 0 + t0 = t1 = 0 + for c in s: + if c == '0': + t0 += 1 + t1 = 0 + else: + t0 = 0 + t1 += 1 + len0 = max(len0, t0) + len1 = max(len1, t1) + return len1 > len0 +``` + +### **Java** + +```java +class Solution { + public boolean checkZeroOnes(String s) { + int len0 = 0, len1 = 0; + int t0 = 0, t1 = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == '0') { + t0 += 1; + t1 = 0; + } else { + t0 = 0; + t1 += 1; + } + len0 = Math.max(len0, t0); + len1 = Math.max(len1, t1); + } + return len1 > len0; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {boolean} + */ + var checkZeroOnes = function(s) { + let max0 = 0, max1 = 0; + let t0 = 0, t1 = 0; + for (let char of s) { + if (char == '0') { + t0++; + t1 = 0; + } else { + t1++; + t0 = 0; + } + max0 = Math.max(max0, t0); + max1 = Math.max(max1, t1); + } + return max1 > max0; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md b/assets/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md new file mode 100644 index 00000000..328148a2 --- /dev/null +++ b/assets/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md @@ -0,0 +1,217 @@ +# [1870. Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time) + + + +## Description + +

    You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.

    + +

    Each train can only depart at an integer hour, so you may need to wait in between each train ride.

    + +
      +
    • For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.
    • +
    + +

    Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.

    + +

    Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.

    + +

     

    +

    Example 1:

    + +
    +Input: dist = [1,3,2], hour = 6
    +Output: 1
    +Explanation: At speed 1:
    +- The first train ride takes 1/1 = 1 hour.
    +- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
    +- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
    +- You will arrive at exactly the 6 hour mark.
    +
    + +

    Example 2:

    + +
    +Input: dist = [1,3,2], hour = 2.7
    +Output: 3
    +Explanation: At speed 3:
    +- The first train ride takes 1/3 = 0.33333 hours.
    +- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
    +- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
    +- You will arrive at the 2.66667 hour mark.
    +
    + +

    Example 3:

    + +
    +Input: dist = [1,3,2], hour = 1.9
    +Output: -1
    +Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == dist.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= dist[i] <= 105
    • +
    • 1 <= hour <= 109
    • +
    • There will be at most two digits after the decimal point in hour.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minSpeedOnTime(self, dist: List[int], hour: float) -> int: + def arrive_on_time(speed): + res = 0 + for i, d in enumerate(dist): + res += (d / speed) if i == len(dist) - 1 else math.ceil(d / speed) + return res <= hour + + left, right = 1, 10 ** 7 + while left < right: + mid = (left + right) >> 1 + if arrive_on_time(mid): + right = mid + else: + left = mid + 1 + return left if arrive_on_time(left) else -1 +``` + +### **Java** + +```java +class Solution { + public int minSpeedOnTime(int[] dist, double hour) { + int left = 1, right = (int) 1e7; + while (left < right) { + int mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return arriveOnTime(dist, left, hour) ? left : -1; + } + + private boolean arriveOnTime(int[] dist, int speed, double hour) { + double res = 0; + for (int i = 0; i < dist.length; ++i) { + double cost = dist[i] * 1.0 / speed; + res += (i == dist.length - 1 ? cost : Math.ceil(cost)); + } + return res <= hour; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minSpeedOnTime(vector& dist, double hour) { + int left = 1, right = 1e7; + while (left < right) { + int mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return arriveOnTime(dist, left, hour) ? left : -1; + } + + bool arriveOnTime(vector& dist, int speed, double hour) { + double res = 0; + for (int i = 0; i < dist.size(); ++i) { + double cost = dist[i] * 1.0 / speed; + res += (i == dist.size() - 1 ? cost : ceil(cost)); + } + return res <= hour; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} dist + * @param {number} hour + * @return {number} + */ + var minSpeedOnTime = function(dist, hour) { + if (dist.length > Math.ceil(hour)) return -1; + let left = 1, right = 10 ** 7; + while (left < right) { + let mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + + function arriveOnTime (dist, speed, hour) { + let res = 0.0; + let n = dist.length; + for (let i = 0; i < n; i++) { + let cost = parseFloat(dist[i]) / speed; + if (i != n - 1) { + cost = Math.ceil(cost); + } + res += cost; + } + return res <= hour; + } +``` + +### **Go** + +```go +func minSpeedOnTime(dist []int, hour float64) int { + n := len(dist) + left, right := 1, int(1e7) + for left < right { + mid := (left + right) >> 1 + if arriveOnTime(dist, n, float64(mid), hour) { + right = mid + } else { + left = mid + 1 + } + } + if arriveOnTime(dist, n, float64(left), hour) { + return left + } + return -1 +} + +func arriveOnTime(dist []int, n int, speed, hour float64) bool { + var cost float64 + for _, v := range dist[:n-1] { + cost += math.Ceil(float64(v) / speed) + } + cost += float64(dist[n-1]) / speed + return cost <= hour +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1871.Jump Game VII/README_EN.md b/assets/1800-1899/1871.Jump Game VII/README_EN.md new file mode 100644 index 00000000..09e5f8eb --- /dev/null +++ b/assets/1800-1899/1871.Jump Game VII/README_EN.md @@ -0,0 +1,128 @@ +# [1871. Jump Game VII](https://leetcode.com/problems/jump-game-vii) + + + +## Description + +

    You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:

    + +
      +
    • i + minJump <= j <= min(i + maxJump, s.length - 1), and
    • +
    • s[j] == '0'.
    • +
    + +

    Return true if you can reach index s.length - 1 in s, or false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "011010", minJump = 2, maxJump = 3
    +Output: true
    +Explanation:
    +In the first step, move from index 0 to index 3. 
    +In the second step, move from index 3 to index 5.
    +
    + +

    Example 2:

    + +
    +Input: s = "01101110", minJump = 2, maxJump = 3
    +Output: false
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= s.length <= 105
    • +
    • s[i] is either '0' or '1'.
    • +
    • s[0] == '0'
    • +
    • 1 <= minJump <= maxJump < s.length
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def canReach(self, s: str, minJump: int, maxJump: int) -> bool: + n = len(s) + dp = [False] * n + dp[0] = True + pre_sum = [0] * (n + 1) + pre_sum[1] = 1 + for i in range(1, n): + if s[i] == '0': + l = max(0, i - maxJump) + r = i - minJump + if r >= l and pre_sum[r + 1] - pre_sum[l] > 0: + dp[i] = True + pre_sum[i + 1] = pre_sum[i] + dp[i] + return dp[n - 1] +``` + +### **Java** + +```java +class Solution { + public boolean canReach(String s, int minJump, int maxJump) { + int n = s.length(); + boolean[] dp = new boolean[n]; + dp[0] = true; + int[] preSum = new int[n + 1]; + preSum[1] = 1; + for (int i = 1; i < n; ++i) { + if (s.charAt(i) == '0') { + int l = Math.max(0, i - maxJump); + int r = i - minJump; + if (r >= l && preSum[r + 1] - preSum[l] > 0) { + dp[i] = true; + } + } + preSum[i + 1] = preSum[i] + (dp[i] ? 1 : 0); + } + return dp[n - 1]; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @param {number} minJump + * @param {number} maxJump + * @return {boolean} + */ +var canReach = function(s, minJump, maxJump) { + let n = s.length; + let dp = new Array(n).fill(0); + let sum = new Array(n + 1).fill(0); + dp[0] = 1; + sum[1] = 1; + for (let i = 1; i < n; i++) { + if (s.charAt(i) == '0') { + let left = Math.max(0, i - maxJump); + let right = i - minJump; + if (left <= right && sum[right + 1] - sum[left] > 0) { + dp[i] = 1; + } + } + sum[i + 1] = sum[i] + dp[i]; + } + return dp.pop(); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1872.Stone Game VIII/README_EN.md b/assets/1800-1899/1872.Stone Game VIII/README_EN.md new file mode 100644 index 00000000..382fb09a --- /dev/null +++ b/assets/1800-1899/1872.Stone Game VIII/README_EN.md @@ -0,0 +1,110 @@ +# [1872. Stone Game VIII](https://leetcode.com/problems/stone-game-viii) + + + +## Description + +

    Alice and Bob take turns playing a game, with Alice starting first.

    + +

    There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:

    + +
      +
    1. Choose an integer x > 1, and remove the leftmost x stones from the row.
    2. +
    3. Add the sum of the removed stones' values to the player's score.
    4. +
    5. Place a new stone, whose value is equal to that sum, on the left side of the row.
    6. +
    + +

    The game stops when only one stone is left in the row.

    + +

    The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.

    + +

    Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.

    + +

     

    +

    Example 1:

    + +
    +Input: stones = [-1,2,-3,4,-5]
    +Output: 5
    +Explanation:
    +- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
    +  value 2 on the left. stones = [2,-5].
    +- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on
    +  the left. stones = [-3].
    +The difference between their scores is 2 - (-3) = 5.
    +
    + +

    Example 2:

    + +
    +Input: stones = [7,-6,5,10,5,-2,-6]
    +Output: 13
    +Explanation:
    +- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a
    +  stone of value 13 on the left. stones = [13].
    +The difference between their scores is 13 - 0 = 13.
    +
    + +

    Example 3:

    + +
    +Input: stones = [-10,-12]
    +Output: -22
    +Explanation:
    +- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her
    +  score and places a stone of value -22 on the left. stones = [-22].
    +The difference between their scores is (-22) - 0 = -22.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == stones.length
    • +
    • 2 <= n <= 105
    • +
    • -104 <= stones[i] <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + pre_sum = list(accumulate(stones)) + f = pre_sum[len(stones) - 1] + for i in range(len(stones) - 2, 0, -1): + f = max(f, pre_sum[i] - f) + return f +``` + +### **Java** + +```java +class Solution { + public int stoneGameVIII(int[] stones) { + int n = stones.length; + int[] preSum = new int[n]; + preSum[0] = stones[0]; + for (int i = 1; i < n; ++i) { + preSum[i] = preSum[i - 1] + stones[i]; + } + int f = preSum[n - 1]; + for (int i = n - 2; i > 0; --i) { + f = Math.max(f, preSum[i] - f); + } + return f; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1873.Calculate Special Bonus/README_EN.md b/assets/1800-1899/1873.Calculate Special Bonus/README_EN.md new file mode 100644 index 00000000..e41d3d84 --- /dev/null +++ b/assets/1800-1899/1873.Calculate Special Bonus/README_EN.md @@ -0,0 +1,119 @@ +# [1873. Calculate Special Bonus](https://leetcode.com/problems/calculate-special-bonus) + + + +## Description + +

    Table: Employees

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| employee_id | int     |
    +
    +| name        | varchar |
    +
    +| salary      | int     |
    +
    ++-------------+---------+
    +
    +employee_id is the primary key for this table.
    +
    +Each row of this table indicates the employee ID, employee name, and salary.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to calculate the bonus of each employee. The bonus of an employee is 100% of their salary if the ID of the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an employee is 0 otherwise.

    + + + +

    Return the result table ordered by employee_id.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Employees table:
    +
    ++-------------+---------+--------+
    +
    +| employee_id | name    | salary |
    +
    ++-------------+---------+--------+
    +
    +| 2           | Meir    | 3000   |
    +
    +| 3           | Michael | 3800   |
    +
    +| 7           | Addilyn | 7400   |
    +
    +| 8           | Juan    | 6100   |
    +
    +| 9           | Kannon  | 7700   |
    +
    ++-------------+---------+--------+
    +
    +
    +
    +Result table:
    +
    ++-------------+-------+
    +
    +| employee_id | bonus |
    +
    ++-------------+-------+
    +
    +| 2           | 0     |
    +
    +| 3           | 0     |
    +
    +| 7           | 7400  |
    +
    +| 8           | 0     |
    +
    +| 9           | 7700  |
    +
    ++-------------+-------+
    +
    +
    +
    +The employees with IDs 2 and 8 get 0 bonus because they have an even employee_id.
    +
    +The employee with ID 3 gets 0 bonus because their name starts with 'M'.
    +
    +The rest of the employees get a 100% bonus.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md b/assets/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md new file mode 100644 index 00000000..81bd976b --- /dev/null +++ b/assets/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md @@ -0,0 +1,89 @@ +# [1874. Minimize Product Sum of Two Arrays](https://leetcode.com/problems/minimize-product-sum-of-two-arrays) + + + +## Description + +

    The product sum of two equal-length arrays a and b is equal to the sum of a[i] * b[i] for all 0 <= i < a.length (0-indexed).

    + + + +
      +
    • For example, if a = [1,2,3,4] and b = [5,2,3,1], the product sum would be 1*5 + 2*2 + 3*3 + 4*1 = 22.
    • +
    + + + +

    Given two arrays nums1 and nums2 of length n, return the minimum product sum if you are allowed to rearrange the order of the elements in nums1

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums1 = [5,3,4,2], nums2 = [4,2,2,5]
    +
    +Output: 40
    +
    +Explanation: We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums1 = [2,1,4,5,7], nums2 = [3,2,4,8,6]
    +
    +Output: 65
    +
    +Explanation: We can rearrange nums1 to become [5,7,4,1,2]. The product sum of [5,7,4,1,2] and [3,2,4,8,6] is 5*3 + 7*2 + 4*4 + 1*8 + 2*6 = 65.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == nums1.length == nums2.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 100
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1875.Group Employees of the Same Salary/README_EN.md b/assets/1800-1899/1875.Group Employees of the Same Salary/README_EN.md new file mode 100644 index 00000000..e733bed3 --- /dev/null +++ b/assets/1800-1899/1875.Group Employees of the Same Salary/README_EN.md @@ -0,0 +1,137 @@ +# [1875. Group Employees of the Same Salary](https://leetcode.com/problems/group-employees-of-the-same-salary) + + + +## Description + +

    Table: Employees

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| employee_id | int     |
    +
    +| name        | varchar |
    +
    +| salary      | int     |
    +
    ++-------------+---------+
    +
    +employee_id is the primary key for this table.
    +
    +Each row of this table indicates the employee ID, employee name, and salary.
    +
    +
    + + + +

     

    + + + +

    A company wants to divide the employees into teams such that all the members on each team have the same salary. The teams should follow these criteria:

    + + + +
      +
    • Each team should consist of at least two employees.
    • +
    • All the employees on a team should have the same salary.
    • +
    • All the employees of the same salary should be assigned to the same team.
    • +
    • If the salary of an employee is unique, we do not assign this employee to any team.
    • +
    • A team's ID is assigned based on the rank of the team's salary relative to the other teams' salaries, where the team with the lowest salary has team_id = 1. Note that the salaries for employees not on a team are not included in this ranking.
    • +
    + + + +

    Write an SQL query to get the team_id of each employee that is in a team.

    + + + +

    Return the result table ordered by team_id in ascending order. In case of a tie, order it by employee_id in ascending order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Employees table:
    +
    ++-------------+---------+--------+
    +
    +| employee_id | name    | salary |
    +
    ++-------------+---------+--------+
    +
    +| 2           | Meir    | 3000   |
    +
    +| 3           | Michael | 3000   |
    +
    +| 7           | Addilyn | 7400   |
    +
    +| 8           | Juan    | 6100   |
    +
    +| 9           | Kannon  | 7400   |
    +
    ++-------------+---------+--------+
    +
    +
    +
    +Result table:
    +
    ++-------------+---------+--------+---------+
    +
    +| employee_id | name    | salary | team_id |
    +
    ++-------------+---------+--------+---------+
    +
    +| 2           | Meir    | 3000   | 1       |
    +
    +| 3           | Michael | 3000   | 1       |
    +
    +| 7           | Addilyn | 7400   | 2       |
    +
    +| 9           | Kannon  | 7400   | 2       |
    +
    ++-------------+---------+--------+---------+
    +
    +
    +
    +Meir (employee_id=2) and Michael (employee_id=3) are in the same team because they have the same salary of 3000.
    +
    +Addilyn (employee_id=7) and Kannon (employee_id=9) are in the same team because they have the same salary of 7400.
    +
    +Juan (employee_id=8) is not included in any team because their salary of 6100 is unique (i.e. no other employee has the same salary).
    +
    +The team IDs are assigned as follows (based on salary ranking, lowest first):
    +
    +- team_id=1: Meir and Michael, salary of 3000
    +
    +- team_id=2: Addilyn and Kannon, salary of 7400
    +
    +Juan's salary of 6100 is not included in the ranking because they are not on a team.
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md b/assets/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md new file mode 100644 index 00000000..457c9d60 --- /dev/null +++ b/assets/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md @@ -0,0 +1,96 @@ +# [1876. Substrings of Size Three with Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters) + + + +## Description + +

    A string is good if there are no repeated characters.

    + +

    Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​.

    + +

    Note that if there are multiple occurrences of the same substring, every occurrence should be counted.

    + +

    A substring is a contiguous sequence of characters in a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "xyzzaz"
    +Output: 1
    +Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". 
    +The only good substring of length 3 is "xyz".
    +
    + +

    Example 2:

    + +
    +Input: s = "aababcabc"
    +Output: 4
    +Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".
    +The good substrings are "abc", "bca", "cab", and "abc".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s​​​​​​ consists of lowercase English letters.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countGoodSubstrings(self, s: str) -> int: + count, n = 0, len(s) + for i in range(n - 2): + count += (s[i] != s[i + 1] and s[i] != s[i + 2] and s[i + 1] != s[i + 2]) + return count +``` + +### **Java** + +```java +class Solution { + public int countGoodSubstrings(String s) { + int count = 0, n = s.length(); + for (int i = 0; i < n - 2; ++i) { + char a = s.charAt(i), b = s.charAt(i + 1), c = s.charAt(i + 2); + if (a != b && a != c && b != c) { + ++count; + } + } + return count; + } +} +``` + +### **TypeScript** + +```ts +function countGoodSubstrings(s: string): number { + const n: number = s.length; + let count: number = 0; + for (let i: number = 0; i < n - 2; ++i) { + let a: string = s.charAt(i), b: string = s.charAt(i + 1), c: string = s.charAt(i + 2); + if (a != b && a != c && b != c) { + ++count; + } + } + return count; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md b/assets/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md new file mode 100644 index 00000000..4eb58102 --- /dev/null +++ b/assets/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md @@ -0,0 +1,85 @@ +# [1877. Minimize Maximum Pair Sum in Array](https://leetcode.com/problems/minimize-maximum-pair-sum-in-array) + + + +## Description + +

    The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.

    + +
      +
    • For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.
    • +
    + +

    Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:

    + +
      +
    • Each element of nums is in exactly one pair, and
    • +
    • The maximum pair sum is minimized.
    • +
    + +

    Return the minimized maximum pair sum after optimally pairing up the elements.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: nums = [3,5,2,3]
    +
    +Output: 7
    +
    +Explanation: The elements can be paired up into pairs (3,3) and (5,2).
    +
    +The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: nums = [3,5,4,2,4,6]
    +
    +Output: 8
    +
    +Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).
    +
    +The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 2 <= n <= 105
    • +
    • n is even.
    • +
    • 1 <= nums[i] <= 105
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md new file mode 100644 index 00000000..2bc1af7f --- /dev/null +++ b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md @@ -0,0 +1,77 @@ +# [1878. Get Biggest Three Rhombus Sums in a Grid](https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid) + + + +## Description + +

    You are given an m x n integer matrix grid​​​.

    +

    A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:

    + +

    Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.

    + +

    Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
    +Output: [228,216,211]
    +Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
    +- Blue: 20 + 3 + 200 + 5 = 228
    +- Red: 200 + 2 + 10 + 4 = 216
    +- Green: 5 + 200 + 4 + 2 = 211
    +
    + +

    Example 2:

    + +
    +Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
    +Output: [20,9,8]
    +Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
    +- Blue: 4 + 2 + 6 + 8 = 20
    +- Red: 9 (area 0 rhombus in the bottom right corner)
    +- Green: 8 (area 0 rhombus in the bottom middle)
    +
    + +

    Example 3:

    + +
    +Input: grid = [[7,7,7]]
    +Output: [7]
    +Explanation: All three possible rhombus sums are the same, so return [7].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • 1 <= grid[i][j] <= 105
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-desc-2.png b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-desc-2.png new file mode 100644 index 00000000..2c5483a1 Binary files /dev/null and b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-desc-2.png differ diff --git a/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-ex1.png b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-ex1.png new file mode 100644 index 00000000..74d5902a Binary files /dev/null and b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-ex1.png differ diff --git a/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-ex2.png b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-ex2.png new file mode 100644 index 00000000..15892295 Binary files /dev/null and b/assets/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/images/pc73-q4-ex2.png differ diff --git a/assets/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md b/assets/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md new file mode 100644 index 00000000..b6db5b84 --- /dev/null +++ b/assets/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md @@ -0,0 +1,70 @@ +# [1879. Minimum XOR Sum of Two Arrays](https://leetcode.com/problems/minimum-xor-sum-of-two-arrays) + + + +## Description + +

    You are given two integer arrays nums1 and nums2 of length n.

    + +

    The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).

    + +
      +
    • For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4.
    • +
    + +

    Rearrange the elements of nums2 such that the resulting XOR sum is minimized.

    + +

    Return the XOR sum after the rearrangement.

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [1,2], nums2 = [2,3]
    +Output: 2
    +Explanation: Rearrange nums2 so that it becomes [3,2].
    +The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
    + +

    Example 2:

    + +
    +Input: nums1 = [1,0,3], nums2 = [5,3,4]
    +Output: 8
    +Explanation: Rearrange nums2 so that it becomes [5,4,3]. 
    +The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums1.length
    • +
    • n == nums2.length
    • +
    • 1 <= n <= 14
    • +
    • 0 <= nums1[i], nums2[i] <= 107
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md b/assets/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md new file mode 100644 index 00000000..be56f491 --- /dev/null +++ b/assets/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md @@ -0,0 +1,182 @@ +# [1880. Check if Word Equals Summation of Two Words](https://leetcode.com/problems/check-if-word-equals-summation-of-two-words) + + + +## Description + +

    The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).

    + +

    The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.

    + +
      +
    • For example, if s = "acb", we concatenate each letter's letter value, resulting in "021". After converting it, we get 21.
    • +
    + +

    You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.

    + +

    Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
    +
    +Output: true
    +
    +Explanation:
    +
    +The numerical value of firstWord is "acb" -> "021" -> 21.
    +
    +The numerical value of secondWord is "cba" -> "210" -> 210.
    +
    +The numerical value of targetWord is "cdb" -> "231" -> 231.
    +
    +We return true because 21 + 210 == 231.
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
    +
    +Output: false
    +
    +Explanation: 
    +
    +The numerical value of firstWord is "aaa" -> "000" -> 0.
    +
    +The numerical value of secondWord is "a" -> "0" -> 0.
    +
    +The numerical value of targetWord is "aab" -> "001" -> 1.
    +
    +We return false because 0 + 0 != 1.
    +
    +
    + +

    Example 3:

    + +
    +
    +Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
    +
    +Output: true
    +
    +Explanation: 
    +
    +The numerical value of firstWord is "aaa" -> "000" -> 0.
    +
    +The numerical value of secondWord is "a" -> "0" -> 0.
    +
    +The numerical value of targetWord is "aaaa" -> "0000" -> 0.
    +
    +We return true because 0 + 0 == 0.
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
    • +
    • firstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: + def convert(word): + res = 0 + for c in word: + res *= 10 + res += (ord(c) - ord('a')) + return res + return convert(firstWord) + convert(secondWord) == convert(targetWord) +``` + +### **Java** + +```java +class Solution { + public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { + return convert(firstWord) + convert(secondWord) == convert(targetWord); + } + + private int convert(String word) { + int res = 0; + for (char c : word.toCharArray()) { + res *= 10; + res += (c - 'a'); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isSumEqual(string firstWord, string secondWord, string targetWord) { + return convert(firstWord) + convert(secondWord) == convert(targetWord); + } +private: + int convert(string word) { + int res = 0; + for (char c : word) { + res *= 10; + res += (c - 'a'); + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {string} firstWord + * @param {string} secondWord + * @param {string} targetWord + * @return {boolean} + */ + var isSumEqual = function(firstWord, secondWord, targetWord) { + let carry = 0; + let n1 = firstWord.length, n2 = secondWord.length; + let n3 = targetWord.length; + for (let i = 0; i < n3; i++) { + let num1 = getNum(firstWord.charAt(n1 - 1 - i)); + let num2 = getNum(secondWord.charAt(n2 - 1 - i)); + let sum = carry + num1 + num2; + if (getNum(targetWord.charAt(n3 - 1 - i)) != (sum % 10)) return false; + carry = parseInt(sum / 10); + } + return true; +}; + +function getNum (char) { + if (!char) return 0; + return char.charCodeAt() - 'a'.charCodeAt(); +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1881.Maximum Value after Insertion/README_EN.md b/assets/1800-1899/1881.Maximum Value after Insertion/README_EN.md new file mode 100644 index 00000000..da2c86ba --- /dev/null +++ b/assets/1800-1899/1881.Maximum Value after Insertion/README_EN.md @@ -0,0 +1,130 @@ +# [1881. Maximum Value after Insertion](https://leetcode.com/problems/maximum-value-after-insertion) + + + +## Description + +

    You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.

    + +

    You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign.

    + +
      +
    • For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.
    • +
    • If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.
    • +
    + +

    Return a string representing the maximum value of n​​​​​​ after the insertion.

    + +

     

    +

    Example 1:

    + +
    +Input: n = "99", x = 9
    +Output: "999"
    +Explanation: The result is the same regardless of where you insert 9.
    +
    + +

    Example 2:

    + +
    +Input: n = "-13", x = 2
    +Output: "-123"
    +Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n.length <= 105
    • +
    • 1 <= x <= 9
    • +
    • The digits in n​​​ are in the range [1, 9].
    • +
    • n is a valid representation of an integer.
    • +
    • In the case of a negative n,​​​​​​ it will begin with '-'.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxValue(self, n: str, x: int) -> str: + negative = n[0] == '-' + i, res = 0, [] + if negative: + i += 1 + res.append('-') + find = False + while i < len(n): + num = int(n[i]) + if (negative and x < num) or (not negative and x > num): + res.append(str(x)) + find = True + break + res.append(n[i]) + i += 1 + res.append(n[i:] if find else str(x)) + return ''.join(res) +``` + +### **Java** + +```java +class Solution { + public String maxValue(String n, int x) { + boolean negative = n.charAt(0) == '-'; + StringBuilder res = new StringBuilder(); + int i = 0; + if (negative) { + ++i; + res.append("-"); + } + boolean find = false; + for (; i < n.length(); ++i) { + int num = n.charAt(i) - '0'; + if ((negative && x < num) || (!negative && x > num)) { + res.append(x); + find = true; + break; + } + res.append(n.charAt(i)); + } + res.append(find ? n.substring(i) : x); + return res.toString(); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} n + * @param {number} x + * @return {string} + */ + var maxValue = function(n, x) { + let nums = [...n]; + let sign = 1, i = 0; + if (nums[0] == '-') { + sign = -1; + i++; + } + while (i < n.length && (nums[i] - x) * sign >= 0) { + i++; + } + nums.splice(i, 0, x); + return nums.join(''); +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1882.Process Tasks Using Servers/README_EN.md b/assets/1800-1899/1882.Process Tasks Using Servers/README_EN.md new file mode 100644 index 00000000..8a49ce72 --- /dev/null +++ b/assets/1800-1899/1882.Process Tasks Using Servers/README_EN.md @@ -0,0 +1,131 @@ +# [1882. Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers) + + + +## Description + +

    You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds.

    + +

    You are running a simulation system that will shut down after all tasks are processed. Each server can only process one task at a time. You will be able to process the jth task starting from the jth second beginning with the 0th task at second 0. To process task j, you assign it to the server with the smallest weight that is free, and in case of a tie, choose the server with the smallest index. If a free server gets assigned task j at second t,​​​​​​ it will be free again at the second t + tasks[j].

    + +

    If there are no free servers, you must wait until one is free and execute the free tasks as soon as possible. If multiple tasks need to be assigned, assign them in order of increasing index.

    + +

    You may assign multiple tasks at the same second if there are multiple free servers.

    + +

    Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to.

    + +

    Return the array ans​​​​.

    + +

     

    +

    Example 1:

    + +
    +Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]
    +Output: [2,2,0,2,1,2]
    +Explanation: Events in chronological order go as follows:
    +- At second 0, task 0 is added and processed using server 2 until second 1.
    +- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.
    +- At second 2, task 2 is added and processed using server 0 until second 5.
    +- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.
    +- At second 4, task 4 is added and processed using server 1 until second 5.
    +- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.
    + +

    Example 2:

    + +
    +Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
    +Output: [1,4,1,4,1,3,2]
    +Explanation: Events in chronological order go as follows: 
    +- At second 0, task 0 is added and processed using server 1 until second 2.
    +- At second 1, task 1 is added and processed using server 4 until second 2.
    +- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. 
    +- At second 3, task 3 is added and processed using server 4 until second 7.
    +- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. 
    +- At second 5, task 5 is added and processed using server 3 until second 7.
    +- At second 6, task 6 is added and processed using server 2 until second 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • servers.length == n
    • +
    • tasks.length == m
    • +
    • 1 <= n, m <= 2 * 105
    • +
    • 1 <= servers[i], tasks[j] <= 2 * 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: + idle, busy = [], [] + for i, weight in enumerate(servers): + heapq.heappush(idle, (weight, i)) + res = [] + for start, cost in enumerate(tasks): + while busy and busy[0][0] <= start: + _, s, i = heapq.heappop(busy) + heapq.heappush(idle, (s, i)) + if idle: + s, i = heapq.heappop(idle) + heapq.heappush(busy, (start + cost, s, i)) + else: + t, s, i = heapq.heappop(busy) + heapq.heappush(busy, (t + cost, s, i)) + res.append(i) + return res +``` + +### **Java** + +```java +class Solution { + public int[] assignTasks(int[] servers, int[] tasks) { + int m = tasks.length, n = servers.length; + PriorityQueue idle = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + PriorityQueue busy = new PriorityQueue<>((a, b) -> { + if (a[0] == b[0]) { + return a[1] == b[1] ? a[2] - b[2] : a[1] - b[1]; + } + return a[0] - b[0]; + }); + for (int i = 0; i < n; ++i) { + idle.offer(new int[]{servers[i], i}); + } + int[] res = new int[m]; + int j = 0; + for (int start = 0; start < m; ++start) { + int cost = tasks[start]; + while (!busy.isEmpty() && busy.peek()[0] <= start) { + int[] item = busy.poll(); + idle.offer(new int[]{item[1], item[2]}); + } + if (!idle.isEmpty()) { + int[] item = idle.poll(); + res[j++] = item[1]; + busy.offer(new int[]{start + cost, item[0], item[1]}); + } else { + int[] item = busy.poll(); + res[j++] = item[2]; + busy.offer(new int[]{item[0] + cost, item[1], item[2]}); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md b/assets/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md new file mode 100644 index 00000000..bcbc4326 --- /dev/null +++ b/assets/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md @@ -0,0 +1,129 @@ +# [1883. Minimum Skips to Arrive at Meeting On Time](https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time) + + + +## Description + +

    You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.

    + +

    After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.

    + +
      +
    • For example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.
    • +
    + +

    However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.

    + +
      +
    • For example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.
    • +
    + +

    Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.

    + +

     

    +

    Example 1:

    + +
    +Input: dist = [1,3,2], speed = 4, hoursBefore = 2
    +Output: 1
    +Explanation:
    +Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
    +You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.
    +Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.
    +
    + +

    Example 2:

    + +
    +Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10
    +Output: 2
    +Explanation:
    +Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.
    +You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.
    +
    + +

    Example 3:

    + +
    +Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10
    +Output: -1
    +Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == dist.length
    • +
    • 1 <= n <= 1000
    • +
    • 1 <= dist[i] <= 105
    • +
    • 1 <= speed <= 106
    • +
    • 1 <= hoursBefore <= 107
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + n = len(dist) + dp = [[float('inf')] * (n + 1) for _ in range(n + 1)] + dp[0][0] = 0 + for i in range(1, n + 1): + for j in range(i + 1): + if i != j: + dp[i][j] = min(dp[i][j], ((dp[i - 1][j] + dist[i - 1] - 1) // speed + 1) * speed) + if j > 0: + dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + dist[i - 1]) + for i in range(n + 1): + if dp[n][i] <= hoursBefore * speed: + return i + return -1 +``` + +### **Java** + +```java +class Solution { + public int minSkips(int[] dist, int speed, int hoursBefore) { + int n = dist.length; + int[][] dp = new int[n + 1][n + 1]; + for (int i = 0; i <= n; ++i) { + for (int j = 0; j <= n; ++j) { + dp[i][j] = Integer.MAX_VALUE; + } + } + dp[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= i; ++j) { + if (i != j) { + // 没有跳过 + dp[i][j] = Math.min(dp[i][j], ((dp[i - 1][j] + dist[i - 1] - 1) / speed + 1) * speed); + } + if (j > 0) { + // 跳过 + dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + dist[i - 1]); + } + } + } + for (int i = 0; i <= n; ++i) { + if (dp[n][i] <= hoursBefore * speed) { + return i; + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md b/assets/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md new file mode 100644 index 00000000..142766a2 --- /dev/null +++ b/assets/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md @@ -0,0 +1,73 @@ +# [1884. Egg Drop With 2 Eggs and N Floors](https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors) + + + +## Description + +

    You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.

    + +

    You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.

    + +

    In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.

    + +

    Return the minimum number of moves that you need to determine with certainty what the value of f is.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 2
    +Output: 2
    +Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.
    +If the first egg breaks, we know that f = 0.
    +If the second egg breaks but the first egg didn't, we know that f = 1.
    +Otherwise, if both eggs survive, we know that f = 2.
    +
    + +

    Example 2:

    + +
    +Input: n = 100
    +Output: 14
    +Explanation: One optimal strategy is:
    +- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting
    +  from floor 1 and going up one at a time to find f within 7 more drops. Total drops is 1 + 7 = 8.
    +- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9
    +  and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more
    +  drops. Total drops is 2 + 12 = 14.
    +- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45,
    +  55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
    +Regardless of the outcome, it takes at most 14 drops to determine f.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md b/assets/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md new file mode 100644 index 00000000..ab71acab --- /dev/null +++ b/assets/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md @@ -0,0 +1,65 @@ +# [1885. Count Pairs in Two Arrays](https://leetcode.com/problems/count-pairs-in-two-arrays) + + + +## Description + +

    Given two integer arrays nums1 and nums2 of length n, count the pairs of indices (i, j) such that i < j and nums1[i] + nums1[j] > nums2[i] + nums2[j].

    + +

    Return the number of pairs satisfying the condition.

    + +

     

    +

    Example 1:

    + +
    +Input: nums1 = [2,1,2,1], nums2 = [1,2,1,2]
    +Output: 1
    +Explanation: The pairs satisfying the condition are:
    +- (0, 2) where 2 + 2 > 1 + 1.
    + +

    Example 2:

    + +
    +Input: nums1 = [1,10,6,2], nums2 = [1,4,1,5]
    +Output: 5
    +Explanation: The pairs satisfying the condition are:
    +- (0, 1) where 1 + 10 > 1 + 4.
    +- (0, 2) where 1 + 6 > 1 + 1.
    +- (1, 2) where 10 + 6 > 4 + 1.
    +- (1, 3) where 10 + 2 > 4 + 5.
    +- (2, 3) where 6 + 2 > 1 + 5.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums1.length == nums2.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md new file mode 100644 index 00000000..9bee7646 --- /dev/null +++ b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md @@ -0,0 +1,118 @@ +# [1886. Determine Whether Matrix Can Be Obtained By Rotation](https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation) + + + +## Description + +

    Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
    +Output: true
    +Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.
    +
    + +

    Example 2:

    + +
    +Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
    +Output: false
    +Explanation: It is impossible to make mat equal to target by rotating mat.
    +
    + +

    Example 3:

    + +
    +Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
    +Output: true
    +Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == mat.length == target.length
    • +
    • n == mat[i].length == target[i].length
    • +
    • 1 <= n <= 10
    • +
    • mat[i][j] and target[i][j] are either 0 or 1.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + def rotate(matrix): + n = len(matrix) + for i in range(n // 2): + for j in range(i, n - 1 - i): + t = matrix[i][j] + matrix[i][j] = matrix[n - j - 1][i] + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] + matrix[j][n - i - 1] = t + for _ in range(4): + if mat == target: + return True + rotate(mat) + return False +``` + +### **Java** + +```java +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + int times = 4; + while (times-- > 0) { + if (equals(mat, target)) { + return true; + } + rotate(mat); + } + return false; + } + + private void rotate(int[][] matrix) { + int n = matrix.length; + for (int i = 0; i < n / 2; ++i) { + for (int j = i; j < n - 1 - i; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[n - j - 1][i]; + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; + matrix[j][n - i - 1] = t; + } + } + } + + private boolean equals(int[][] nums1, int[][] nums2) { + int n = nums1.length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (nums1[i][j] != nums2[i][j]) { + return false; + } + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid3.png b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid3.png new file mode 100644 index 00000000..74065587 Binary files /dev/null and b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid3.png differ diff --git a/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid4-1.png b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid4-1.png new file mode 100644 index 00000000..1e6eccbc Binary files /dev/null and b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid4-1.png differ diff --git a/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid4.png b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid4.png new file mode 100644 index 00000000..469e5ed8 Binary files /dev/null and b/assets/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/images/grid4.png differ diff --git a/assets/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md b/assets/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md new file mode 100644 index 00000000..70106994 --- /dev/null +++ b/assets/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md @@ -0,0 +1,102 @@ +# [1887. Reduction Operations to Make the Array Elements Equal](https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal) + + + +## Description + +

    Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:

    + +
      +
    1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
    2. +
    3. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
    4. +
    5. Reduce nums[i] to nextLargest.
    6. +
    + +

    Return the number of operations to make all elements in nums equal.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [5,1,3]
    +Output: 3
    +Explanation: It takes 3 operations to make all elements in nums equal:
    +1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].
    +2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].
    +3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
    +
    + +

    Example 2:

    + +
    +Input: nums = [1,1,1]
    +Output: 0
    +Explanation: All elements in nums are already equal.
    +
    + +

    Example 3:

    + +
    +Input: nums = [1,1,2,2,3]
    +Output: 4
    +Explanation: It takes 4 operations to make all elements in nums equal:
    +1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].
    +2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].
    +3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].
    +4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 1 <= nums[i] <= 5 * 104
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def reductionOperations(self, nums: List[int]) -> int: + counter = collections.Counter(nums) + f = res = 0 + n = len(nums) + for _, v in sorted(counter.items(), key=lambda x: x[0]): + f += v + res += (n - f) + return res +``` + +### **Java** + +```java +class Solution { + public int reductionOperations(int[] nums) { + TreeMap counter = new TreeMap<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + int n = nums.length; + int f = 0, res = 0; + while (counter.size() != 0) { + f += counter.pollFirstEntry().getValue(); + res += (n - f); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md b/assets/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md new file mode 100644 index 00000000..08a4ab67 --- /dev/null +++ b/assets/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md @@ -0,0 +1,127 @@ +# [1888. Minimum Number of Flips to Make the Binary String Alternating](https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating) + + + +## Description + +

    You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:

    + +
      +
    • Type-1: Remove the character at the start of the string s and append it to the end of the string.
    • +
    • Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
    • +
    + +

    Return the minimum number of type-2 operations you need to perform such that s becomes alternating.

    + +

    The string is called alternating if no two adjacent characters are equal.

    + +
      +
    • For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: s = "111000"
    +Output: 2
    +Explanation: Use the first operation two times to make s = "100011".
    +Then, use the second operation on the third and sixth elements to make s = "101010".
    +
    + +

    Example 2:

    + +
    +Input: s = "010"
    +Output: 0
    +Explanation: The string is already alternating.
    +
    + +

    Example 3:

    + +
    +Input: s = "1110"
    +Output: 1
    +Explanation: Use the second operation on the second element to make s = "1010".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s[i] is either '0' or '1'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minFlips(self, s: str) -> int: + n = len(s) + target = '01' + cnt = 0 + for i, c in enumerate(s): + cnt += c != target[i & 1] + res = min(cnt, n - cnt) + for i in range(n): + cnt -= s[i] != target[i & 1] + cnt += s[i] != target[(i + n) & 1] + res = min(res, cnt, n - cnt) + return res +``` + +### **Java** + +```java +class Solution { + public int minFlips(String s) { + int n = s.length(); + String target = "01"; + int cnt = 0; + for (int i = 0; i < n; ++i) { + cnt += (s.charAt(i) == target.charAt(i & 1) ? 0 : 1); + } + int res = Math.min(cnt, n - cnt); + for (int i = 0; i < n; ++i) { + cnt -= (s.charAt(i) == target.charAt(i & 1) ? 0 : 1); + cnt += (s.charAt(i) == target.charAt((i + n) & 1) ? 0 : 1); + res = Math.min(res, Math.min(cnt, n - cnt)); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function minFlips(s: string): number { + const n: number = s.length; + const target: string[] = ['0', '1']; + let count: number = 0; + for (let i: number = 0; i < n; ++i) { + count += (s.charAt(i) == target[i & 1] ? 0 : 1); + } + let res = Math.min(count, n - count); + for (let i: number = 0; i < n; ++i) { + count -= (s.charAt(i) == target[i & 1] ? 0 : 1); + count += (s.charAt(i) == target[(i + n) & 1] ? 0 : 1); + res = Math.min(res, count, n - count); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md b/assets/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md new file mode 100644 index 00000000..50ea4d6e --- /dev/null +++ b/assets/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md @@ -0,0 +1,174 @@ +# [1889. Minimum Space Wasted From Packaging](https://leetcode.com/problems/minimum-space-wasted-from-packaging) + + + +## Description + +

    You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.

    + +

    The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.

    + +

    You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.

    + +
      +
    • For example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6.
    • +
    + +

    Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: packages = [2,3,5], boxes = [[4,8],[2,8]]
    +Output: 6
    +Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
    +The total waste is (4-2) + (4-3) + (8-5) = 6.
    +
    + +

    Example 2:

    + +
    +Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]
    +Output: -1
    +Explanation: There is no box that the package of size 5 can fit in.
    +
    + +

    Example 3:

    + +
    +Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]
    +Output: 9
    +Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
    +The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == packages.length
    • +
    • m == boxes.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= m <= 105
    • +
    • 1 <= packages[i] <= 105
    • +
    • 1 <= boxes[j].length <= 105
    • +
    • 1 <= boxes[j][k] <= 105
    • +
    • sum(boxes[j].length) <= 105
    • +
    • The elements in boxes[j] are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: + packages.sort() + res = float('inf') + for box in boxes: + box.sort() + if packages[-1] > box[-1]: + continue + t = last = 0 + for b in box: + idx = bisect.bisect_right(packages, b, lo=last) + t += (idx - last) * b + last = idx + res = min(res, t) + return -1 if res == float('inf') else (res - sum(packages)) % (10 ** 9 + 7) +``` + +### **Java** + +```java +class Solution { + public int minWastedSpace(int[] packages, int[][] boxes) { + int n = packages.length; + Arrays.sort(packages); + long[] preSum = new long[n + 1]; + for (int i = 0; i < n; ++i) { + preSum[i + 1] = preSum[i] + packages[i]; + } + + long res = Long.MAX_VALUE; + for (int[] box : boxes) { + Arrays.sort(box); + if (packages[n - 1] > box[box.length - 1]) { + continue; + } + long t = 0; + int low = 0; + for (int b : box) { + int idx = searchRight(packages, b, low); + t += ((idx - low) * (long) b - (preSum[idx] - preSum[low])); + low = idx; + } + res = Math.min(res, t); + } + return res == Long.MAX_VALUE ? -1 : (int) (res % 1000000007); + } + + private int searchRight(int[] packages, int target, int low) { + int high = packages.length; + while (low < high) { + int mid = (low + high) >> 1; + if (packages[mid] <= target) { + low = mid + 1; + } else { + high = mid; + } + } + return low; + } +} +``` + +### **TypeScript** + +```ts +function minWastedSpace(packages: number[], boxes: number[][]): number { + const MOD = 10 ** 9 + 7; + packages.sort((a, b) => a - b); + const max_package = packages[packages.length - 1]; + const total = packages.reduce((a, c) => a + c, 0); + let res = Infinity; + for (let box of boxes) { + box.sort((a, b) => a - b); + if (max_package > box[box.length - 1]) continue; + let left = 0, sum = 0; + for (let capacity of box) { + let right = searchRight(packages, capacity, left); + sum += (right - left) * capacity; + left = right; + } + res = Math.min(res, sum); + } + return res == Infinity ? -1 : (res - total) % MOD; +}; + +function searchRight(packages: number[], target: number, left: number): number { + let right = packages.length; + while (left < right) { + let mid = (left + right) >> 1; + if (packages[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1890.The Latest Login in 2020/README_EN.md b/assets/1800-1899/1890.The Latest Login in 2020/README_EN.md new file mode 100644 index 00000000..7714cc71 --- /dev/null +++ b/assets/1800-1899/1890.The Latest Login in 2020/README_EN.md @@ -0,0 +1,116 @@ +# [1890. The Latest Login in 2020](https://leetcode.com/problems/the-latest-login-in-2020) + + + +## Description + +

    Table: Logins

    + +
    +
    ++----------------+----------+
    +
    +| Column Name    | Type     |
    +
    ++----------------+----------+
    +
    +| user_id        | int      |
    +
    +| time_stamp     | datetime |
    +
    ++----------------+----------+
    +
    +(user_id, time_stamp) is the primary key for this table.
    +
    +Each row contains information about the login time for the user with ID user_id.
    +
    +
    + +

     

    + +

    Write an SQL query to report the latest login for all users in the year 2020. Do not include the users who did not login in 2020.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +
    +Logins table:
    +
    ++---------+---------------------+
    +
    +| user_id | time_stamp          |
    +
    ++---------+---------------------+
    +
    +| 6       | 2020-06-30 15:06:07 |
    +
    +| 6       | 2021-04-21 14:06:06 |
    +
    +| 6       | 2019-03-07 00:18:15 |
    +
    +| 8       | 2020-02-01 05:10:53 |
    +
    +| 8       | 2020-12-30 00:46:50 |
    +
    +| 2       | 2020-01-16 02:49:50 |
    +
    +| 2       | 2019-08-25 07:59:08 |
    +
    +| 14      | 2019-07-14 09:00:00 |
    +
    +| 14      | 2021-01-06 11:59:59 |
    +
    ++---------+---------------------+
    +
    +
    +
    +Result table:
    +
    ++---------+---------------------+
    +
    +| user_id | last_stamp          |
    +
    ++---------+---------------------+
    +
    +| 6       | 2020-06-30 15:06:07 |
    +
    +| 8       | 2020-12-30 00:46:50 |
    +
    +| 2       | 2020-01-16 02:49:50 |
    +
    ++---------+---------------------+
    +
    +
    +
    +User 6 logged into their account 3 times but only once in 2020, so we include this login in the result table.
    +
    +User 8 logged into their account 2 times in 2020, once in February and once in December. We include only the latest one (December) in the result table.
    +
    +User 2 logged into their account 2 times but only once in 2020, so we include this login in the result table.
    +
    +User 14 did not login in 2020, so we do not include them in the result table.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + user_id, + max(time_stamp) AS last_stamp +FROM + Logins +WHERE YEAR(time_stamp) = 2020 +GROUP BY user_id; +``` + + diff --git a/assets/1800-1899/1891.Cutting Ribbons/README_EN.md b/assets/1800-1899/1891.Cutting Ribbons/README_EN.md new file mode 100644 index 00000000..9c57e31c --- /dev/null +++ b/assets/1800-1899/1891.Cutting Ribbons/README_EN.md @@ -0,0 +1,189 @@ +# [1891. Cutting Ribbons](https://leetcode.com/problems/cutting-ribbons) + + + +## Description + +

    You are given an integer array ribbons, where ribbons[i] represents the length of the ith ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.

    + +
      +
    • For example, if you have a ribbon of length 4, you can: +
        +
      • Keep the ribbon of length 4,
      • +
      • Cut it into one ribbon of length 3 and one ribbon of length 1,
      • +
      • Cut it into two ribbons of length 2,
      • +
      • Cut it into one ribbon of length 2 and two ribbons of length 1, or
      • +
      • Cut it into four ribbons of length 1.
      • +
      +
    • +
    + +

    Your goal is to obtain k ribbons of all the same positive integer length. You are allowed to throw away any excess ribbon as a result of cutting.

    + +

    Return the maximum possible positive integer length that you can obtain k ribbons of, or 0 if you cannot obtain k ribbons of the same length.

    + +

     

    +

    Example 1:

    + +
    +Input: ribbons = [9,7,5], k = 3
    +Output: 5
    +Explanation:
    +- Cut the first ribbon to two ribbons, one of length 5 and one of length 4.
    +- Cut the second ribbon to two ribbons, one of length 5 and one of length 2.
    +- Keep the third ribbon as it is.
    +Now you have 3 ribbons of length 5.
    + +

    Example 2:

    + +
    +Input: ribbons = [7,5,9], k = 4
    +Output: 4
    +Explanation:
    +- Cut the first ribbon to two ribbons, one of length 4 and one of length 3.
    +- Cut the second ribbon to two ribbons, one of length 4 and one of length 1.
    +- Cut the third ribbon to three ribbons, two of length 4 and one of length 1.
    +Now you have 4 ribbons of length 4.
    +
    + +

    Example 3:

    + +
    +Input: ribbons = [5,7,9], k = 22
    +Output: 0
    +Explanation: You cannot obtain k ribbons of the same positive integer length.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= ribbons.length <= 105
    • +
    • 1 <= ribbons[i] <= 105
    • +
    • 1 <= k <= 109
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxLength(self, ribbons: List[int], k: int) -> int: + low, high = 0, 100000 + while low < high: + mid = (low + high + 1) >> 1 + cnt = 0 + for ribbon in ribbons: + cnt += ribbon // mid + if cnt < k: + high = mid - 1 + else: + low = mid + return low +``` + +### **Java** + +```java +class Solution { + public int maxLength(int[] ribbons, int k) { + int low = 0, high = 100000; + while (low < high) { + int mid = (low + high + 1) >> 1; + int cnt = 0; + for (int ribbon : ribbons) { + cnt += ribbon / mid; + } + if (cnt < k) { + high = mid - 1; + } else { + low = mid; + } + } + return low; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxLength(vector& ribbons, int k) { + int low = 0, high = 100000; + while (low < high) { + int mid = (low + high + 1) / 2; + int cnt = 0; + for (auto ribbon : ribbons) { + cnt += ribbon / mid; + } + if (cnt < k) { + high = mid - 1; + } else { + low = mid; + } + } + return low; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} ribbons + * @param {number} k + * @return {number} + */ +var maxLength = function(ribbons, k) { + let low = 0; + let high = 100000; + while (low < high) { + const mid = (low + high + 1) >> 1; + let cnt = 0; + for (let ribbon of ribbons) { + cnt += Math.floor(ribbon / mid); + } + if (cnt < k) { + high = mid - 1; + } else { + low = mid; + } + } + return low; +}; +``` + +### **Go** + +```go +func maxLength(ribbons []int, k int) int { + low, high := 0, 100000 + for low < high { + mid := (low + high + 1) >> 1 + cnt := 0 + for _, ribbon := range ribbons { + cnt += ribbon / mid + } + if cnt < k { + high = mid - 1 + } else { + low = mid + } + } + return low +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1892.Page Recommendations II/README_EN.md b/assets/1800-1899/1892.Page Recommendations II/README_EN.md new file mode 100644 index 00000000..73628902 --- /dev/null +++ b/assets/1800-1899/1892.Page Recommendations II/README_EN.md @@ -0,0 +1,203 @@ +# [1892. Page Recommendations II](https://leetcode.com/problems/page-recommendations-ii) + + + +## Description + +

    Table: Friendship

    + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| user1_id      | int     |
    +
    +| user2_id      | int     |
    +
    ++---------------+---------+
    +
    +(user1_id, user2_id) is the primary key for this table.
    +
    +Each row of this table indicates that the users user1_id and user2_id are friends.
    +
    +
    + +

     

    + +

    Table: Likes

    + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| user_id     | int     |
    +
    +| page_id     | int     |
    +
    ++-------------+---------+
    +
    +(user_id, page_id) is the primary key for this table.
    +
    +Each row of this table indicates that user_id likes page_id.
    +
    +
    + +

     

    + +

    You are implementing a page recommendation system for a social media website. Your system will recommended a page to user_id if the page is liked by at least one friend of user_id and is not liked by user_id.

    + +

    Write an SQL query to find all the possible page recommendations for every user. Each recommendation should appear as a row in the result table with these columns:

    + +
      +
    • user_id: The ID of the user that your system is making the recommendation to.
    • +
    • page_id: The ID of the page that will be recommended to user_id.
    • +
    • friends_likes: The number of the friends of user_id that like page_id.
    • +
    + +

    Return result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +
    +Friendship table:
    +
    ++----------+----------+
    +
    +| user1_id | user2_id |
    +
    ++----------+----------+
    +
    +| 1        | 2        |
    +
    +| 1        | 3        |
    +
    +| 1        | 4        |
    +
    +| 2        | 3        |
    +
    +| 2        | 4        |
    +
    +| 2        | 5        |
    +
    +| 6        | 1        |
    +
    ++----------+----------+
    +
    + 
    +
    +Likes table:
    +
    ++---------+---------+
    +
    +| user_id | page_id |
    +
    ++---------+---------+
    +
    +| 1       | 88      |
    +
    +| 2       | 23      |
    +
    +| 3       | 24      |
    +
    +| 4       | 56      |
    +
    +| 5       | 11      |
    +
    +| 6       | 33      |
    +
    +| 2       | 77      |
    +
    +| 3       | 77      |
    +
    +| 6       | 88      |
    +
    ++---------+---------+
    +
    +
    +
    +Result table:
    +
    ++---------+---------+---------------+
    +
    +| user_id | page_id | friends_likes |
    +
    ++---------+---------+---------------+
    +
    +| 1       | 77      | 2             |
    +
    +| 1       | 23      | 1             |
    +
    +| 1       | 24      | 1             |
    +
    +| 1       | 56      | 1             |
    +
    +| 1       | 33      | 1             |
    +
    +| 2       | 24      | 1             |
    +
    +| 2       | 56      | 1             |
    +
    +| 2       | 11      | 1             |
    +
    +| 2       | 88      | 1             |
    +
    +| 3       | 88      | 1             |
    +
    +| 3       | 23      | 1             |
    +
    +| 4       | 88      | 1             |
    +
    +| 4       | 77      | 1             |
    +
    +| 4       | 23      | 1             |
    +
    +| 5       | 77      | 1             |
    +
    +| 5       | 23      | 1             |
    +
    ++---------+---------+---------------+
    +
    +Take user 1 as an example:
    +
    +  - User 1 is friends with users 2, 3, 4, and 6.
    +
    +  - Recommended pages are 23 (user 2 liked it), 24 (user 3 liked it), 56 (user 3 liked it), 33 (user 6 liked it), and 77 (user 2 and user 3 liked it).
    +
    +  - Note that page 88 is not recommended because user 1 already liked it.
    +
    +
    +
    +Another example is user 6:
    +
    +  - User 6 is friends with user 1.
    +
    +  - User 1 only liked page 88, but user 6 already liked it. Hence, user 6 has no recommendations.
    +
    +
    +
    +You can recommend pages for users 2, 3, 4, and 5 using a similar process.
    +
    +
    + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md b/assets/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md new file mode 100644 index 00000000..ce3444ef --- /dev/null +++ b/assets/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md @@ -0,0 +1,65 @@ +# [1893. Check if All the Integers in a Range Are Covered](https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered) + + + +## Description + +

    You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.

    + +

    Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.

    + +

    An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.

    + +

     

    +

    Example 1:

    + +
    +Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5
    +Output: true
    +Explanation: Every integer between 2 and 5 is covered:
    +- 2 is covered by the first range.
    +- 3 and 4 are covered by the second range.
    +- 5 is covered by the third range.
    +
    + +

    Example 2:

    + +
    +Input: ranges = [[1,10],[10,20]], left = 21, right = 21
    +Output: false
    +Explanation: 21 is not covered by any range.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= ranges.length <= 50
    • +
    • 1 <= starti <= endi <= 50
    • +
    • 1 <= left <= right <= 50
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md b/assets/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md new file mode 100644 index 00000000..cbcc86bc --- /dev/null +++ b/assets/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md @@ -0,0 +1,201 @@ +# [1894. Find the Student that Will Replace the Chalk](https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk) + + + +## Description + +

    There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.

    + + + +

    You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.

    + + + +

    Return the index of the student that will replace the chalk.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: chalk = [5,1,5], k = 22
    +
    +Output: 0
    +
    +Explanation: The students go in turns as follows:
    +
    +- Student number 0 uses 5 chalk, so k = 17.
    +
    +- Student number 1 uses 1 chalk, so k = 16.
    +
    +- Student number 2 uses 5 chalk, so k = 11.
    +
    +- Student number 0 uses 5 chalk, so k = 6.
    +
    +- Student number 1 uses 1 chalk, so k = 5.
    +
    +- Student number 2 uses 5 chalk, so k = 0.
    +
    +Student number 0 does not have enough chalk, so they will have to replace it.
    + + + +

    Example 2:

    + + + +
    +
    +Input: chalk = [3,4,1,2], k = 25
    +
    +Output: 1
    +
    +Explanation: The students go in turns as follows:
    +
    +- Student number 0 uses 3 chalk so k = 22.
    +
    +- Student number 1 uses 4 chalk so k = 18.
    +
    +- Student number 2 uses 1 chalk so k = 17.
    +
    +- Student number 3 uses 2 chalk so k = 15.
    +
    +- Student number 0 uses 3 chalk so k = 12.
    +
    +- Student number 1 uses 4 chalk so k = 8.
    +
    +- Student number 2 uses 1 chalk so k = 7.
    +
    +- Student number 3 uses 2 chalk so k = 5.
    +
    +- Student number 0 uses 3 chalk so k = 2.
    +
    +Student number 1 does not have enough chalk, so they will have to replace it.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • chalk.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= chalk[i] <= 105
    • +
    • 1 <= k <= 109
    • +
    + +## Solutions + +PreSum and Binary search. + + + +### **Python3** + +```python +class Solution: + def chalkReplacer(self, chalk: List[int], k: int) -> int: + pre_sum = list(itertools.accumulate(chalk)) + k %= pre_sum[-1] + left, right = 0, len(chalk) - 1 + while left < right: + mid = (left + right) >> 1 + if pre_sum[mid] > k: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + +```java +class Solution { + public int chalkReplacer(int[] chalk, int k) { + int n = chalk.length; + long[] preSum = new long[n + 1]; + for (int i = 0; i < n; ++i) { + preSum[i + 1] = preSum[i] + chalk[i]; + } + k %= preSum[n]; + int left = 0, right = n - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (preSum[mid + 1] > k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int chalkReplacer(vector& chalk, int k) { + int n = chalk.size(); + vector preSum(n + 1); + for (int i = 0; i < n; ++i) { + preSum[i + 1] = preSum[i] + chalk[i]; + } + k %= preSum[n]; + int left = 0, right = n - 1; + while (left < right) { + int mid = left + (right - left >> 1); + if (preSum[mid + 1] > k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func chalkReplacer(chalk []int, k int) int { + n := len(chalk) + preSum := make([]int, n+1) + for i := 0; i < n; i++ { + preSum[i+1] = preSum[i] + chalk[i] + } + k %= preSum[n] + left, right := 0, n-1 + for left < right { + mid := left + ((right - left) >> 1) + if preSum[mid+1] > k { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1895.Largest Magic Square/README_EN.md b/assets/1800-1899/1895.Largest Magic Square/README_EN.md new file mode 100644 index 00000000..aeea41d1 --- /dev/null +++ b/assets/1800-1899/1895.Largest Magic Square/README_EN.md @@ -0,0 +1,63 @@ +# [1895. Largest Magic Square](https://leetcode.com/problems/largest-magic-square) + + + +## Description + +

    A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.

    + +

    Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
    +Output: 3
    +Explanation: The largest magic square has a size of 3.
    +Every row sum, column sum, and diagonal sum of this magic square is equal to 12.
    +- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12
    +- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12
    +- Diagonal sums: 5+4+3 = 6+4+2 = 12
    +
    + +

    Example 2:

    + +
    +Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
    +Output: 2
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 50
    • +
    • 1 <= grid[i][j] <= 106
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1895.Largest Magic Square/images/magicsquare-grid.jpg b/assets/1800-1899/1895.Largest Magic Square/images/magicsquare-grid.jpg new file mode 100644 index 00000000..5a8def69 Binary files /dev/null and b/assets/1800-1899/1895.Largest Magic Square/images/magicsquare-grid.jpg differ diff --git a/assets/1800-1899/1895.Largest Magic Square/images/magicsquare2-grid.jpg b/assets/1800-1899/1895.Largest Magic Square/images/magicsquare2-grid.jpg new file mode 100644 index 00000000..dd25baa8 Binary files /dev/null and b/assets/1800-1899/1895.Largest Magic Square/images/magicsquare2-grid.jpg differ diff --git a/assets/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md b/assets/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md new file mode 100644 index 00000000..1acd89be --- /dev/null +++ b/assets/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md @@ -0,0 +1,89 @@ +# [1896. Minimum Cost to Change the Final Value of Expression](https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression) + + + +## Description + +

    You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.

    + +
      +
    • For example, "()1|1" and "(1)&()" are not valid while "1", "(((1))|(0))", and "1|(0&(1))" are valid expressions.
    • +
    + +

    Return the minimum cost to change the final value of the expression.

    + +
      +
    • For example, if expression = "1|1|(0&0)&1", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.
    • +
    + +

    The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:

    + +
      +
    • Turn a '1' into a '0'.
    • +
    • Turn a '0' into a '1'.
    • +
    • Turn a '&' into a '|'.
    • +
    • Turn a '|' into a '&'.
    • +
    + +

    Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.

    + +

     

    +

    Example 1:

    + +
    +Input: expression = "1&(0|1)"
    +Output: 1
    +Explanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation.
    +The new expression evaluates to 0. 
    +
    + +

    Example 2:

    + +
    +Input: expression = "(0&0)&(0&0&0)"
    +Output: 3
    +Explanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations.
    +The new expression evaluates to 1.
    +
    + +

    Example 3:

    + +
    +Input: expression = "(0|(1|0&1))"
    +Output: 1
    +Explanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation.
    +The new expression evaluates to 0.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= expression.length <= 105
    • +
    • expression only contains '1','0','&','|','(', and ')'
    • +
    • All parentheses are properly matched.
    • +
    • There will be no empty parentheses (i.e: "()" is not a substring of expression).
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md b/assets/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md new file mode 100644 index 00000000..91a0eaf5 --- /dev/null +++ b/assets/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md @@ -0,0 +1,111 @@ +# [1897. Redistribute Characters to Make All Strings Equal](https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal) + + + +## Description + +

    You are given an array of strings words (0-indexed).

    + +

    In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].

    + +

    Return true if you can make every string in words equal using any number of operations, and false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: words = ["abc","aabc","bc"]
    +Output: true
    +Explanation: Move the first 'a' in words[1] to the front of words[2],
    +to make words[1] = "abc" and words[2] = "abc".
    +All the strings are now equal to "abc", so return true.
    +
    + +

    Example 2:

    + +
    +Input: words = ["ab","a"]
    +Output: false
    +Explanation: It is impossible to make all the strings equal using the operation.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= words.length <= 100
    • +
    • 1 <= words[i].length <= 100
    • +
    • words[i] consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def makeEqual(self, words: List[str]) -> bool: + counter = collections.Counter() + for word in words: + for c in word: + counter[c] += 1 + n = len(words) + for count in counter.values(): + if count % n != 0: + return False + return True +``` + +### **Java** + +```java +class Solution { + public boolean makeEqual(String[] words) { + int[] counter = new int[26]; + for (String word : words) { + for (char c : word.toCharArray()) { + ++counter[c - 'a']; + } + } + int n = words.length; + for (int i = 0; i < 26; ++i) { + if (counter[i] % n != 0) { + return false; + } + } + return true; + } +} +``` + +### **TypeScript** + +```ts +function makeEqual(words: string[]): boolean { + let n = words.length; + let letters = new Array(26).fill(0); + for (let word of words) { + for (let i = 0; i < word.length; ++i) { + ++letters[word.charCodeAt(i) - 97]; + } + } + + for (let i = 0; i < letters.length; ++i) { + if (letters[i] % n != 0) { + return false; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md b/assets/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md new file mode 100644 index 00000000..611996af --- /dev/null +++ b/assets/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md @@ -0,0 +1,220 @@ +# [1898. Maximum Number of Removable Characters](https://leetcode.com/problems/maximum-number-of-removable-characters) + + + +## Description + +

    You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).

    + +

    You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.

    + +

    Return the maximum k you can choose such that p is still a subsequence of s after the removals.

    + +

    A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "abcacb", p = "ab", removable = [3,1,0]
    +Output: 2
    +Explanation: After removing the characters at indices 3 and 1, "abcacb" becomes "accb".
    +"ab" is a subsequence of "accb".
    +If we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.
    +Hence, the maximum k is 2.
    +
    + +

    Example 2:

    + +
    +Input: s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]
    +Output: 1
    +Explanation: After removing the character at index 3, "abcbddddd" becomes "abcddddd".
    +"abcd" is a subsequence of "abcddddd".
    +
    + +

    Example 3:

    + +
    +Input: s = "abcab", p = "abc", removable = [0,1,2,3,4]
    +Output: 0
    +Explanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= p.length <= s.length <= 105
    • +
    • 0 <= removable.length < s.length
    • +
    • 0 <= removable[i] < s.length
    • +
    • p is a subsequence of s.
    • +
    • s and p both consist of lowercase English letters.
    • +
    • The elements in removable are distinct.
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int: + def check(mid): + m, n, i, j = len(s), len(p), 0, 0 + ids = set(removable[:mid]) + while i < m and j < n: + if i not in ids and s[i] == p[j]: + j += 1 + i += 1 + return j == n + + left, right = 0, len(removable) + while left < right: + mid = (left + right + 1) >> 1 + if check(mid): + left = mid + else: + right = mid - 1 + return left +``` + +### **Java** + +```java +class Solution { + public int maximumRemovals(String s, String p, int[] removable) { + int left = 0, right = removable.length; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(s, p, removable, mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(String s, String p, int[] removable, int mid) { + int m = s.length(), n = p.length(), i = 0, j = 0; + Set ids = new HashSet<>(); + for (int k = 0; k < mid; ++k) { + ids.add(removable[k]); + } + while (i < m && j < n) { + if (!ids.contains(i) && s.charAt(i) == p.charAt(j)) { + ++j; + } + ++i; + } + return j == n; + } +} +``` + +### **TypeScript** + +```ts +function maximumRemovals(s: string, p: string, removable: number[]): number { + let left = 0, right = removable.length; + while (left < right) { + let mid = (left + right + 1) >> 1; + if (isSub(s, p, new Set(removable.slice(0, mid)))) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; + +function isSub(str: string, sub: string, idxes: Set): boolean { + let m = str.length, n = sub.length; + let i = 0, j = 0; + while (i < m && j < n) { + if (!idxes.has(i) && str.charAt(i) == sub.charAt(j)) { + ++j; + } + ++i; + } + return j == n; +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maximumRemovals(string s, string p, vector& removable) { + int left = 0, right = removable.size(); + while (left < right) { + int mid = left + right + 1 >> 1; + if (check(s, p, removable, mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + bool check(string s, string p, vector& removable, int mid) { + int m = s.size(), n = p.size(), i = 0, j = 0; + unordered_set ids; + for (int k = 0; k < mid; ++k) { + ids.insert(removable[k]); + } + while (i < m && j < n) { + if (ids.count(i) == 0 && s[i] == p[j]) { + ++j; + } + ++i; + } + return j == n; + } +}; +``` + +### **Go** + +```go +func maximumRemovals(s string, p string, removable []int) int { + left, right := 0, len(removable) + for left < right { + mid := (left + right + 1) >> 1 + if check(s, p, removable, mid) { + left = mid + } else { + right = mid - 1 + } + } + return left +} + +func check(s string, p string, removable []int, mid int) bool { + m, n, i, j := len(s), len(p), 0, 0 + ids := make(map[int]bool) + for k := 0; k < mid; k++ { + ids[removable[k]] = true + } + for i < m && j < n { + if !ids[i] && s[i] == p[j] { + j++ + } + i++ + } + return j == n +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md b/assets/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md new file mode 100644 index 00000000..4c27d98c --- /dev/null +++ b/assets/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md @@ -0,0 +1,130 @@ +# [1899. Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet) + + + +## Description + +

    A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.

    + +

    To obtain target, you may apply the following operation on triplets any number of times (possibly zero):

    + +
      +
    • Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. +
        +
      • For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].
      • +
      +
    • +
    + +

    Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.

    + +

     

    +

    Example 1:

    + +
    +Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
    +Output: true
    +Explanation: Perform the following operations:
    +- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]
    +The target triplet [2,7,5] is now an element of triplets.
    +
    + +

    Example 2:

    + +
    +Input: triplets = [[1,3,4],[2,5,8]], target = [2,5,8]
    +Output: true
    +Explanation: The target triplet [2,5,8] is already an element of triplets.
    +
    + +

    Example 3:

    + +
    +Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]
    +Output: true
    +Explanation: Perform the following operations:
    +- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].
    +- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].
    +The target triplet [5,5,5] is now an element of triplets.
    +
    + +

    Example 4:

    + +
    +Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]
    +Output: false
    +Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= triplets.length <= 105
    • +
    • triplets[i].length == target.length == 3
    • +
    • 1 <= ai, bi, ci, x, y, z <= 1000
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: + maxA = maxB = maxC = 0 + tA, tB, tC = target + for a, b, c in triplets: + if a <= tA and b <= tB and c <= tC: + maxA = max(maxA, a) + maxB = max(maxB, b) + maxC = max(maxC, c) + return (maxA, maxB, maxC) == (tA, tB, tC) +``` + +### **Java** + +```java +class Solution { + public boolean mergeTriplets(int[][] triplets, int[] target) { + int maxA = 0, maxB = 0, maxC = 0; + for (int[] triplet : triplets) { + int a = triplet[0], b = triplet[1], c = triplet[2]; + if (a <= target[0] && b <= target[1] && c <= target[2]) { + maxA = Math.max(maxA, a); + maxB = Math.max(maxB, b); + maxC = Math.max(maxC, c); + } + } + return maxA == target[0] && maxB == target[1] && maxC == target[2]; + } +} +``` + +### **TypeScript** + +```ts +function mergeTriplets(triplets: number[][], target: number[]): boolean { + let [x, y, z] = target; // 目标值 + let [i, j, k] = [0, 0, 0]; // 最大值 + for (let triplet of triplets) { + let [a, b, c] = triplet; // 当前值 + if (a <= x && b <= y && c <= z) { + i = Math.max(i, a); + j = Math.max(j, b); + k = Math.max(k, c); + } + } + return i == x && j == y && k == z; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md b/assets/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md new file mode 100644 index 00000000..86097634 --- /dev/null +++ b/assets/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md @@ -0,0 +1,104 @@ +# [1900. The Earliest and Latest Rounds Where Players Compete](https://leetcode.com/problems/the-earliest-and-latest-rounds-where-players-compete) + + + +## Description + +

    There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.).

    + +

    The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.

    + +
      +
    • For example, if the row consists of players 1, 2, 4, 6, 7 +
        +
      • Player 1 competes against player 7.
      • +
      • Player 2 competes against player 6.
      • +
      • Player 4 automatically advances to the next round.
      • +
      +
    • +
    + +

    After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order).

    + +

    The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round.

    + +

    Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.

    + +

     

    + +

    Example 1:

    + +
    +
    +Input: n = 11, firstPlayer = 2, secondPlayer = 4
    +
    +Output: [3,4]
    +
    +Explanation:
    +
    +One possible scenario which leads to the earliest round number:
    +
    +First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
    +
    +Second round: 2, 3, 4, 5, 6, 11
    +
    +Third round: 2, 3, 4
    +
    +One possible scenario which leads to the latest round number:
    +
    +First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
    +
    +Second round: 1, 2, 3, 4, 5, 6
    +
    +Third round: 1, 2, 4
    +
    +Fourth round: 2, 4
    +
    +
    + +

    Example 2:

    + +
    +
    +Input: n = 5, firstPlayer = 1, secondPlayer = 5
    +
    +Output: [1,1]
    +
    +Explanation: The players numbered 1 and 5 compete in the first round.
    +
    +There is no way to make them compete in any other round.
    +
    +
    + +

     

    + +

    Constraints:

    + +
      +
    • 2 <= n <= 28
    • +
    • 1 <= firstPlayer < secondPlayer <= n
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1901.Find a Peak Element II/README_EN.md b/assets/1900-1999/1901.Find a Peak Element II/README_EN.md new file mode 100644 index 00000000..7c8cb62b --- /dev/null +++ b/assets/1900-1999/1901.Find a Peak Element II/README_EN.md @@ -0,0 +1,70 @@ +# [1901. Find a Peak Element II](https://leetcode.com/problems/find-a-peak-element-ii) + + + +## Description + +

    A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.

    + +

    Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].

    + +

    You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.

    + +

    You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: mat = [[1,4],[3,2]]
    +Output: [0,1]
    +Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
    +
    + +

    Example 2:

    + +

    + +
    +Input: mat = [[10,20,15],[21,30,14],[7,16,32]]
    +Output: [1,1]
    +Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • 1 <= mat[i][j] <= 105
    • +
    • No two adjacent cells are equal.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1901.Find a Peak Element II/images/1.png b/assets/1900-1999/1901.Find a Peak Element II/images/1.png new file mode 100644 index 00000000..a116feba Binary files /dev/null and b/assets/1900-1999/1901.Find a Peak Element II/images/1.png differ diff --git a/assets/1900-1999/1901.Find a Peak Element II/images/3.png b/assets/1900-1999/1901.Find a Peak Element II/images/3.png new file mode 100644 index 00000000..6572b908 Binary files /dev/null and b/assets/1900-1999/1901.Find a Peak Element II/images/3.png differ diff --git a/assets/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md b/assets/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md new file mode 100644 index 00000000..6526195d --- /dev/null +++ b/assets/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md @@ -0,0 +1,126 @@ +# [1902. Depth of BST Given Insertion Order](https://leetcode.com/problems/depth-of-bst-given-insertion-order) + + + +## Description + +

    You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree.

    + + + +

    A binary search tree is defined as follows:

    + + + +
      +
    • The left subtree of a node contains only nodes with keys less than the node's key.
    • +
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • +
    • Both the left and right subtrees must also be binary search trees.
    • +
    + + + +

    The binary search tree is constructed as follows:

    + + + +
      +
    • order[0] will be the root of the binary search tree.
    • +
    • All subsequent elements are inserted as the child of any existing node such that the binary search tree properties hold.
    • +
    + + + +

    Return the depth of the binary search tree.

    + + + +

    A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: order = [2,1,4,3]
    +
    +Output: 3
    +
    +Explanation: The binary search tree has a depth of 3 with path 2->3->4.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: order = [2,1,3,4]
    +
    +Output: 3
    +
    +Explanation: The binary search tree has a depth of 3 with path 2->3->4.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: order = [1,2,3,4]
    +
    +Output: 4
    +
    +Explanation: The binary search tree has a depth of 4 with path 1->2->3->4.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == order.length
    • +
    • 1 <= n <= 105
    • +
    • order is a permutation of integers between 1 and n.
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/1.png b/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/1.png new file mode 100644 index 00000000..b7f46456 Binary files /dev/null and b/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/1.png differ diff --git a/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/2.png b/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/2.png new file mode 100644 index 00000000..39822ab5 Binary files /dev/null and b/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/2.png differ diff --git a/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/3.png b/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/3.png new file mode 100644 index 00000000..bcf9e85c Binary files /dev/null and b/assets/1900-1999/1902.Depth of BST Given Insertion Order/images/3.png differ diff --git a/assets/1900-1999/1903.Largest Odd Number in String/README_EN.md b/assets/1900-1999/1903.Largest Odd Number in String/README_EN.md new file mode 100644 index 00000000..38b02e54 --- /dev/null +++ b/assets/1900-1999/1903.Largest Odd Number in String/README_EN.md @@ -0,0 +1,131 @@ +# [1903. Largest Odd Number in String](https://leetcode.com/problems/largest-odd-number-in-string) + + + +## Description + +

    You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.

    + +

    A substring is a contiguous sequence of characters within a string.

    + +

     

    +

    Example 1:

    + +
    +Input: num = "52"
    +Output: "5"
    +Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
    +
    + +

    Example 2:

    + +
    +Input: num = "4206"
    +Output: ""
    +Explanation: There are no odd numbers in "4206".
    +
    + +

    Example 3:

    + +
    +Input: num = "35427"
    +Output: "35427"
    +Explanation: "35427" is already an odd number.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= num.length <= 105
    • +
    • num only consists of digits and does not contain any leading zeros.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def largestOddNumber(self, num: str) -> str: + for i in range(len(num) - 1, -1, -1): + if (int(num[i]) & 1) == 1: + return num[:i + 1] + return '' +``` + +### **Java** + +```java +class Solution { + public String largestOddNumber(String num) { + for (int i = num.length() - 1; i >= 0; --i) { + int c = num.charAt(i) - '0'; + if ((c & 1) == 1) { + return num.substring(0, i + 1); + } + } + return ""; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} num + * @return {string} + */ + var largestOddNumber = function(num) { + let n = num.length; + for (let j = n - 1; j >= 0; j--) { + if (num.charAt(j) & 1 == 1) { + return num.slice(0, j+1); + } + } + return ''; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + string largestOddNumber(string num) { + for (int i = num.size() - 1; i >= 0; --i) { + int c = num[i] - '0'; + if ((c & 1) == 1) { + return num.substr(0, i + 1); + } + } + return ""; + } +}; +``` + +### **Go** + +```go +func largestOddNumber(num string) string { + for i := len(num) - 1; i >= 0; i-- { + c := num[i] - '0' + if (c & 1) == 1 { + return num[:i+1] + } + } + return "" +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md b/assets/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md new file mode 100644 index 00000000..9f8eecda --- /dev/null +++ b/assets/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md @@ -0,0 +1,176 @@ +# [1904. The Number of Full Rounds You Have Played](https://leetcode.com/problems/the-number-of-full-rounds-you-have-played) + + + +## Description + +

    A new online video game has been released, and in this video game, there are 15-minute rounds scheduled every quarter-hour period. This means that at HH:00, HH:15, HH:30 and HH:45, a new round starts, where HH represents an integer number from 00 to 23. A 24-hour clock is used, so the earliest time in the day is 00:00 and the latest is 23:59.

    + +

    Given two strings startTime and finishTime in the format "HH:MM" representing the exact time you started and finished playing the game, respectively, calculate the number of full rounds that you played during your game session.

    + +
      +
    • For example, if startTime = "05:20" and finishTime = "05:59" this means you played only one full round from 05:30 to 05:45. You did not play the full round from 05:15 to 05:30 because you started after the round began, and you did not play the full round from 05:45 to 06:00 because you stopped before the round ended.
    • +
    + +

    If finishTime is earlier than startTime, this means you have played overnight (from startTime to the midnight and from midnight to finishTime).

    + +

    Return the number of full rounds that you have played if you had started playing at startTime and finished at finishTime.

    + +

     

    +

    Example 1:

    + +
    +Input: startTime = "12:01", finishTime = "12:44"
    +Output: 1
    +Explanation: You played one full round from 12:15 to 12:30.
    +You did not play the full round from 12:00 to 12:15 because you started playing at 12:01 after it began.
    +You did not play the full round from 12:30 to 12:45 because you stopped playing at 12:44 before it ended.
    +
    + +

    Example 2:

    + +
    +Input: startTime = "20:00", finishTime = "06:00"
    +Output: 40
    +Explanation: You played 16 full rounds from 20:00 to 00:00 and 24 full rounds from 00:00 to 06:00.
    +16 + 24 = 40.
    +
    + +

    Example 3:

    + +
    +Input: startTime = "00:00", finishTime = "23:59"
    +Output: 95
    +Explanation: You played 4 full rounds each hour except for the last hour where you played 3 full rounds.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • startTime and finishTime are in the format HH:MM.
    • +
    • 00 <= HH <= 23
    • +
    • 00 <= MM <= 59
    • +
    • startTime and finishTime are not equal.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def numberOfRounds(self, startTime: str, finishTime: str) -> int: + def get(s: str) -> int: + return int(s[:2]) * 60 + int(s[3:]) + + start, finish = get(startTime), get(finishTime) + if start > finish: + finish += 24 * 60 + start, finish = (start + 14) // 15, finish // 15 + return max(0, finish - start) +``` + +### **Java** + +```java +class Solution { + public int numberOfRounds(String startTime, String finishTime) { + int start = get(startTime), finish = get(finishTime); + if (start > finish) { + finish += 24 * 60; + } + start = (start + 14) / 15; + finish /= 15; + return Math.max(0, finish - start); + } + + private int get(String s) { + return Integer.parseInt(s.substring(0, 2)) * 60 + Integer.parseInt(s.substring(3)); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} startTime + * @param {string} finishTime + * @return {number} + */ + var numberOfRounds = function(startTime, finishTime) { + let m1 = toMinutes(startTime), m2 = toMinutes(finishTime); + + if (m1 > m2) { + m2 += 24 * 60; + } + + let ans = Math.floor(m2 / 15) - Math.ceil(m1 / 15); + return ans < 0 ? 0 : ans; +}; + +function toMinutes(time) { + let [h, m] = time.split(':'); + return Number(h) * 60 + Number(m); +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numberOfRounds(string startTime, string finishTime) { + int start = get(startTime), finish = get(finishTime); + if (start > finish) { + finish += 24 * 60; + } + start = (start + 14) / 15; + finish /= 15; + return max(0, finish - start); + } + +private: + int get(string s) { + int a, b; + sscanf(s.c_str(), "%d:%d", &a, &b); + return a * 60 + b; + } +}; +``` + +### **Go** + +```go +func numberOfRounds(startTime string, finishTime string) int { + start, finish := get(startTime), get(finishTime) + if start > finish { + finish += 24 * 60 + } + start = (start + 14) / 15 + finish /= 15 + if start > finish { + return 0 + } + return finish - start + +} + +func get(s string) int { + var a, b int + fmt.Sscanf(s, "%d:%d", &a, &b) + return a*60 + b +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1905.Count Sub Islands/README_EN.md b/assets/1900-1999/1905.Count Sub Islands/README_EN.md new file mode 100644 index 00000000..b2ce8c89 --- /dev/null +++ b/assets/1900-1999/1905.Count Sub Islands/README_EN.md @@ -0,0 +1,221 @@ +# [1905. Count Sub Islands](https://leetcode.com/problems/count-sub-islands) + + + +## Description + +

    You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

    + +

    An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

    + +

    Return the number of islands in grid2 that are considered sub-islands.

    + +

     

    +

    Example 1:

    + + +
    +Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
    +Output: 3
    +Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
    +The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
    +
    + +

    Example 2:

    + +
    +Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
    +Output: 2 
    +Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
    +The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid1.length == grid2.length
    • +
    • n == grid1[i].length == grid2[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • grid1[i][j] and grid2[i][j] are either 0 or 1.
    • +
    + + +## Solutions + +DFS. + + + +### **Python3** + +```python +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + def dfs(grid1, grid2, i, j, m, n) -> bool: + res = grid1[i][j] == 1 + grid2[i][j] = 0 + for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + a, b = i + x, j + y + if a >= 0 and a < m and b >= 0 and b < n and grid2[a][b] == 1: + if not dfs(grid1, grid2, a, b, m, n): + res = False + return res + + m, n = len(grid1), len(grid1[0]) + count = 0 + for i in range(m): + for j in range(n): + if grid2[i][j] == 1 and dfs(grid1, grid2, i, j, m, n): + count += 1 + return count +``` + +### **Java** + +```java +class Solution { + private int[][] directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + + public int countSubIslands(int[][] grid1, int[][] grid2) { + int m = grid1.length, n = grid1[0].length; + int count = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid2[i][j] == 1 && dfs(grid1, grid2, i, j, m, n)) { + ++count; + } + } + } + return count; + } + + private boolean dfs(int[][] grid1, int[][] grid2, int i, int j, int m, int n) { + boolean res = grid1[i][j] == 1; + grid2[i][j] = 0; + + for (int[] direction : directions) { + int a = i + direction[0], b = j + direction[1]; + if (a >= 0 && a < m && b >= 0 && b < n && grid2[a][b] == 1) { + if (!dfs(grid1, grid2, a, b, m, n)) { + res = false; + } + } + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function countSubIslands(grid1: number[][], grid2: number[][]): number { + let m = grid1.length, n = grid1[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid2[i][j] == 1 && dfs(grid1, grid2, i, j)) { + ++ans; + } + } + } + return ans; +}; + +function dfs(grid1: number[][], grid2: number[][], i: number, j: number): boolean { + let m = grid1.length, n = grid1[0].length; + let ans = true; + if (grid1[i][j] == 0) { + ans = false; + } + grid2[i][j] = 0; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + if (x < 0 || x > m - 1 || y < 0 || y > n - 1 || grid2[x][y] == 0) { + continue; + } + if (!dfs(grid1, grid2, x, y)) { + ans = false; + } + } + return ans; +} +``` + +### **C++** + +```cpp +class Solution { +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + int m = grid1.size(), n = grid1[0].size(); + int count = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid2[i][j] == 1 && dfs(grid1, grid2, i, j, m, n)) { + ++count; + } + } + } + return count; + } + +private: + vector> directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + bool dfs(vector>& grid1, vector>& grid2, int i, int j, int m, int n) { + bool res = grid1[i][j] == 1; + grid2[i][j] = 0; + + for (auto direction : directions) { + int a = i + direction[0], b = j + direction[1]; + if (a >= 0 && a < m && b >= 0 && b < n && grid2[a][b] == 1) { + if (!dfs(grid1, grid2, a, b, m, n)) { + res = false; + } + } + } + return res; + } +}; +``` + +### **Go** + +```go +func countSubIslands(grid1 [][]int, grid2 [][]int) int { + m, n := len(grid1), len(grid1[0]) + count := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid2[i][j] == 1 && dfs(grid1, grid2, i, j, m, n) { + count++ + } + } + } + return count +} + +func dfs(grid1 [][]int, grid2 [][]int, i, j, m, n int) bool { + res := grid1[i][j] == 1 + grid2[i][j] = 0 + directions := [4][2]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} + for _, direction := range directions { + a, b := i+direction[0], j+direction[1] + if a >= 0 && a < m && b >= 0 && b < n && grid2[a][b] == 1 { + if !dfs(grid1, grid2, a, b, m, n) { + res = false + } + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1905.Count Sub Islands/images/test1.png b/assets/1900-1999/1905.Count Sub Islands/images/test1.png new file mode 100644 index 00000000..f613d111 Binary files /dev/null and b/assets/1900-1999/1905.Count Sub Islands/images/test1.png differ diff --git a/assets/1900-1999/1905.Count Sub Islands/images/testcasex2.png b/assets/1900-1999/1905.Count Sub Islands/images/testcasex2.png new file mode 100644 index 00000000..6d3c01c2 Binary files /dev/null and b/assets/1900-1999/1905.Count Sub Islands/images/testcasex2.png differ diff --git a/assets/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md b/assets/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md new file mode 100644 index 00000000..53279a7c --- /dev/null +++ b/assets/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md @@ -0,0 +1,248 @@ +# [1906. Minimum Absolute Difference Queries](https://leetcode.com/problems/minimum-absolute-difference-queries) + + + +## Description + +

    The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.

    + +
      +
    • For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.
    • +
    + +

    You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).

    + +

    Return an array ans where ans[i] is the answer to the ith query.

    + +

    A subarray is a contiguous sequence of elements in an array.

    + +

    The value of |x| is defined as:

    + +
      +
    • x if x >= 0.
    • +
    • -x if x < 0.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
    +Output: [2,1,4,1]
    +Explanation: The queries are processed as follows:
    +- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.
    +- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.
    +- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.
    +- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.
    +
    + +

    Example 2:

    + +
    +Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
    +Output: [-1,1,1,3]
    +Explanation: The queries are processed as follows:
    +- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the
    +  elements are the same.
    +- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.
    +- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.
    +- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 100
    • +
    • 1 <= queries.length <= 2 * 104
    • +
    • 0 <= li < ri < nums.length
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: + m, n = len(nums), len(queries) + pre_sum = [[0] * 101 for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, 101): + t = 1 if nums[i - 1] == j else 0 + pre_sum[i][j] = pre_sum[i - 1][j] + t + + ans = [] + for i in range(n): + left, right = queries[i][0], queries[i][1] + 1 + t = float('inf') + last = -1 + for j in range(1, 101): + if pre_sum[right][j] - pre_sum[left][j] > 0: + if last != -1: + t = min(t, j - last) + last = j + if t == float('inf'): + t = -1 + ans.append(t) + return ans +``` + +### **Java** + +```java +class Solution { + public int[] minDifference(int[] nums, int[][] queries) { + int m = nums.length, n = queries.length; + int[][] preSum = new int[m + 1][101]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= 100; ++j) { + int t = nums[i - 1] == j ? 1 : 0; + preSum[i][j] = preSum[i - 1][j] + t; + } + } + + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int left = queries[i][0], right = queries[i][1] + 1; + int t = Integer.MAX_VALUE; + int last = -1; + for (int j = 1; j <= 100; ++j) { + if (preSum[right][j] > preSum[left][j]) { + if (last != -1) { + t = Math.min(t, j - last); + } + last = j; + } + } + if (t == Integer.MAX_VALUE) { + t = -1; + } + ans[i] = t; + } + return ans; + } +} +``` + +### **TypeScript** + +```ts +function minDifference(nums: number[], queries: number[][]): number[] { + let m = nums.length, n = queries.length; + let max = 100; + // let max = Math.max(...nums); + let pre: number[][] = []; + pre.push(new Array(max + 1).fill(0)); + for (let i = 0; i < m; ++i) { + let num = nums[i]; + pre.push(pre[i].slice()); + pre[i + 1][num] += 1; + } + + let ans = []; + for (let [left, right] of queries) { + let last = -1; + let min = Infinity; + for (let j = 1; j < max + 1; ++j) { + if (pre[left][j] < pre[right + 1][j]) { + if (last != -1) { + min = Math.min(min, j - last); + } + last = j; + } + } + ans.push(min == Infinity ? -1 : min); + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector minDifference(vector& nums, vector>& queries) { + int m = nums.size(), n = queries.size(); + int preSum[m + 1][101]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= 100; ++j) { + int t = nums[i - 1] == j ? 1 : 0; + preSum[i][j] = preSum[i - 1][j] + t; + } + } + + vector ans(n); + for (int i = 0; i < n; ++i) { + int left = queries[i][0], right = queries[i][1] + 1; + int t = 101; + int last = -1; + for (int j = 1; j <= 100; ++j) { + if (preSum[right][j] > preSum[left][j]) { + if (last != -1) { + t = min(t, j - last); + } + last = j; + } + } + if (t == 101) { + t = -1; + } + ans[i] = t; + } + return ans; + } +}; +``` + +### **Go** + +```go +func minDifference(nums []int, queries [][]int) []int { + m, n := len(nums), len(queries) + preSum := make([][101]int, m+1) + for i := 1; i <= m; i++ { + for j := 1; j <= 100; j++ { + t := 0 + if nums[i-1] == j { + t = 1 + } + preSum[i][j] = preSum[i-1][j] + t + } + } + + ans := make([]int, n) + for i := 0; i < n; i++ { + left, right := queries[i][0], queries[i][1]+1 + t, last := 101, -1 + for j := 1; j <= 100; j++ { + if preSum[right][j]-preSum[left][j] > 0 { + if last != -1 { + if t > j-last { + t = j - last + } + } + last = j + } + } + if t == 101 { + t = -1 + } + ans[i] = t + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1907.Count Salary Categories/README_EN.md b/assets/1900-1999/1907.Count Salary Categories/README_EN.md new file mode 100644 index 00000000..211da63d --- /dev/null +++ b/assets/1900-1999/1907.Count Salary Categories/README_EN.md @@ -0,0 +1,72 @@ +# [1907. Count Salary Categories](https://leetcode.com/problems/count-salary-categories) + + + +## Description + +

    Table: Accounts

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| account_id  | int  |
    +| income      | int  |
    ++-------------+------+
    +account_id is the primary key for this table.
    +Each row contains information about the monthly income for one bank account.
    +
    + +

     

    + +

    Write an SQL query to report the number of bank accounts of each salary category. The salary categories are:

    + +
      +
    • "Low Salary": All the salaries strictly less than $20000.
    • +
    • "Average Salary": All the salaries in the inclusive range [$20000, $50000].
    • +
    • "High Salary": All the salaries strictly greater than $50000.
    • +
    + +

    The result table must contain all three categories. If there are no accounts in a category, then report 0. Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Accounts table:
    ++------------+--------+
    +| account_id | income |
    ++------------+--------+
    +| 3          | 108939 |
    +| 2          | 12747  |
    +| 8          | 87709  |
    +| 6          | 91796  |
    ++------------+--------+
    +
    +Result table:
    ++----------------+----------------+
    +| category       | accounts_count |
    ++----------------+----------------+
    +| Low Salary     | 1              |
    +| Average Salary | 0              |
    +| High Salary    | 3              |
    ++----------------+----------------+
    +
    +Low Salary: Account 2.
    +Average Salary: No accounts.
    +High Salary: Accounts 3, 6, and 8.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1900-1999/1908.Game of Nim/README_EN.md b/assets/1900-1999/1908.Game of Nim/README_EN.md new file mode 100644 index 00000000..1e5fe384 --- /dev/null +++ b/assets/1900-1999/1908.Game of Nim/README_EN.md @@ -0,0 +1,125 @@ +# [1908. Game of Nim](https://leetcode.com/problems/game-of-nim) + + + +## Description + +

    Alice and Bob take turns playing a game with Alice starting first.

    + + + +

    In this game, there are n piles of stones. On each player's turn, the player should remove any positive number of stones from a non-empty pile of his or her choice. The first player who cannot make a move loses, and the other player wins.

    + + + +

    Given an integer array piles, where piles[i] is the number of stones in the ith pile, return true if Alice wins, or false if Bob wins.

    + + + +

    Both Alice and Bob play optimally.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: piles = [1]
    +
    +Output: true
    +
    +Explanation: There is only one possible scenario:
    +
    +- On the first turn, Alice removes one stone from the first pile. piles = [0].
    +
    +- On the second turn, there are no stones left for Bob to remove. Alice wins.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: piles = [1,1]
    +
    +Output: false
    +
    +Explanation: It can be proven that Bob will always win. One possible scenario is:
    +
    +- On the first turn, Alice removes one stone from the first pile. piles = [0,1].
    +
    +- On the second turn, Bob removes one stone from the second pile. piles = [0,0].
    +
    +- On the third turn, there are no stones left for Alice to remove. Bob wins.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: piles = [1,2,3]
    +
    +Output: false
    +
    +Explanation: It can be proven that Bob will always win. One possible scenario is:
    +
    +- On the first turn, Alice removes three stones from the third pile. piles = [1,2,0].
    +
    +- On the second turn, Bob removes one stone from the second pile. piles = [1,1,0].
    +
    +- On the third turn, Alice removes one stone from the first pile. piles = [0,1,0].
    +
    +- On the fourth turn, Bob removes one stone from the second pile. piles = [0,0,0].
    +
    +- On the fifth turn, there are no stones left for Alice to remove. Bob wins.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == piles.length
    • +
    • 1 <= n <= 7
    • +
    • 1 <= piles[i] <= 7
    • +
    + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md b/assets/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md new file mode 100644 index 00000000..8e4b744d --- /dev/null +++ b/assets/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md @@ -0,0 +1,81 @@ +# [1909. Remove One Element to Make the Array Strictly Increasing](https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing) + + + +## Description + +

    Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.

    + +

    The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,10,5,7]
    +Output: true
    +Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].
    +[1,2,5,7] is strictly increasing, so return true.
    +
    + +

    Example 2:

    + +
    +Input: nums = [2,3,1,2]
    +Output: false
    +Explanation:
    +[3,1,2] is the result of removing the element at index 0.
    +[2,1,2] is the result of removing the element at index 1.
    +[2,3,2] is the result of removing the element at index 2.
    +[2,3,1] is the result of removing the element at index 3.
    +No resulting array is strictly increasing, so return false.
    + +

    Example 3:

    + +
    +Input: nums = [1,1,1]
    +Output: false
    +Explanation: The result of removing any element is [1,1].
    +[1,1] is not strictly increasing, so return false.
    +
    + +

    Example 4:

    + +
    +Input: nums = [1,2,3]
    +Output: true
    +Explanation: [1,2,3] is already strictly increasing, so return true.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md b/assets/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md new file mode 100644 index 00000000..4430e31b --- /dev/null +++ b/assets/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md @@ -0,0 +1,75 @@ +# [1910. Remove All Occurrences of a Substring](https://leetcode.com/problems/remove-all-occurrences-of-a-substring) + + + +## Description + +

    Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:

    + +
      +
    • Find the leftmost occurrence of the substring part and remove it from s.
    • +
    + +

    Return s after removing all occurrences of part.

    + +

    A substring is a contiguous sequence of characters in a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "daabcbaabcbc", part = "abc"
    +Output: "dab"
    +Explanation: The following operations are done:
    +- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
    +- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
    +- s = "dababc", remove "abc" starting at index 3, so s = "dab".
    +Now s has no occurrences of "abc".
    +
    + +

    Example 2:

    + +
    +Input: s = "axxxxyyyyb", part = "xy"
    +Output: "ab"
    +Explanation: The following operations are done:
    +- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
    +- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".
    +- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".
    +- s = "axyb", remove "xy" starting at index 1 so s = "ab".
    +Now s has no occurrences of "xy".
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • 1 <= part.length <= 1000
    • +
    • s​​​​​​ and part consists of lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md b/assets/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md new file mode 100644 index 00000000..5e42f884 --- /dev/null +++ b/assets/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md @@ -0,0 +1,76 @@ +# [1911. Maximum Alternating Subsequence Sum](https://leetcode.com/problems/maximum-alternating-subsequence-sum) + + + +## Description + +

    The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.

    + +
      +
    • For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.
    • +
    + +

    Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).

    + +
      +
    + +

    A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [4,2,5,3]
    +Output: 7
    +Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.
    +
    + +

    Example 2:

    + +
    +Input: nums = [5,6,7,8]
    +Output: 8
    +Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.
    +
    + +

    Example 3:

    + +
    +Input: nums = [6,2,1,2,4,5]
    +Output: 10
    +Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1912.Design Movie Rental System/README_EN.md b/assets/1900-1999/1912.Design Movie Rental System/README_EN.md new file mode 100644 index 00000000..cbd168c1 --- /dev/null +++ b/assets/1900-1999/1912.Design Movie Rental System/README_EN.md @@ -0,0 +1,87 @@ +# [1912. Design Movie Rental System](https://leetcode.com/problems/design-movie-rental-system) + + + +## Description + +

    You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.

    + +

    Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei.

    + +

    The system should support the following functions:

    + +
      +
    • Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
    • +
    • Rent: Rents an unrented copy of a given movie from a given shop.
    • +
    • Drop: Drops off a previously rented copy of a given movie at a given shop.
    • +
    • Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj should appear first, and if there is still tie, the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
    • +
    + +

    Implement the MovieRentingSystem class:

    + +
      +
    • MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n shops and the movies in entries.
    • +
    • List<Integer> search(int movie) Returns a list of shops that have an unrented copy of the given movie as described above.
    • +
    • void rent(int shop, int movie) Rents the given movie from the given shop.
    • +
    • void drop(int shop, int movie) Drops off a previously rented movie at the given shop.
    • +
    • List<List<Integer>> report() Returns a list of cheapest rented movies as described above.
    • +
    + +

    Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.

    + +

     

    +

    Example 1:

    + +
    +Input
    +["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"]
    +[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]
    +Output
    +[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]
    +
    +Explanation
    +MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);
    +movieRentingSystem.search(1);  // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
    +movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].
    +movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].
    +movieRentingSystem.report();   // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
    +movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].
    +movieRentingSystem.search(2);  // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 3 * 105
    • +
    • 1 <= entries.length <= 105
    • +
    • 0 <= shopi < n
    • +
    • 1 <= moviei, pricei <= 104
    • +
    • Each shop carries at most one copy of a movie moviei.
    • +
    • At most 105 calls in total will be made to search, rent, drop and report.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md b/assets/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md new file mode 100644 index 00000000..c6dfebd5 --- /dev/null +++ b/assets/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md @@ -0,0 +1,120 @@ +# [1913. Maximum Product Difference Between Two Pairs](https://leetcode.com/problems/maximum-product-difference-between-two-pairs) + + + +## Description + +

    The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).

    + + + +
      +
    • For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
    • +
    + + + +

    Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

    + + + +

    Return the maximum such product difference.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [5,6,2,7,4]
    +
    +Output: 34
    +
    +Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
    +
    +The product difference is (6 * 7) - (2 * 4) = 34.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [4,2,5,9,7,4,8]
    +
    +Output: 64
    +
    +Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
    +
    +The product difference is (9 * 8) - (2 * 4) = 64.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 4 <= nums.length <= 104
    • +
    • 1 <= nums[i] <= 104
    • +
    + +## Solutions + + + +### **Python3** + +```python +class Solution: + def maxProductDifference(self, nums: List[int]) -> int: + nums.sort() + return nums[-1] * nums[-2] - nums[0] * nums[1] +``` + +### **Java** + +```java +class Solution { + public int maxProductDifference(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxProductDifference = function(nums) { + nums.sort((a, b) => a - b); + let n = nums.length; + let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md b/assets/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md new file mode 100644 index 00000000..e9eeff0a --- /dev/null +++ b/assets/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md @@ -0,0 +1,155 @@ +# [1914. Cyclically Rotating a Grid](https://leetcode.com/problems/cyclically-rotating-a-grid) + + + +## Description + +

    You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k.

    + +

    The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:

    + +

    + +

    A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:

    + +

    Return the matrix after applying k cyclic rotations to it.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[40,10],[30,20]], k = 1
    +Output: [[10,20],[40,30]]
    +Explanation: The figures above represent the grid at every state.
    +
    + +

    Example 2:

    + + +
    +Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
    +Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
    +Explanation: The figures above represent the grid at every state.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 2 <= m, n <= 50
    • +
    • Both m and n are even integers.
    • +
    • 1 <= grid[i][j] <= 5000
    • +
    • 1 <= k <= 109
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + def rotate(grid, s1, e1, s2, e2, k): + t = [] + for j in range(e2, e1, -1): + t.append(grid[s1][j]) + for i in range(s1, s2): + t.append(grid[i][e1]) + for j in range(e1, e2): + t.append(grid[s2][j]) + for i in range(s2, s1, -1): + t.append(grid[i][e2]) + k %= len(t) + t = t[-k:] +t[:-k] + k = 0 + for j in range(e2, e1, -1): + grid[s1][j] = t[k] + k += 1 + for i in range(s1, s2): + grid[i][e1] = t[k] + k += 1 + for j in range(e1, e2): + grid[s2][j] = t[k] + k += 1 + for i in range(s2, s1, -1): + grid[i][e2] = t[k] + k += 1 + + m, n = len(grid), len(grid[0]) + s1 = e1 = 0 + s2, e2 = m - 1, n - 1 + while s1 <= s2 and e1 <= e2: + rotate(grid, s1, e1, s2, e2, k) + s1 += 1 + e1 += 1 + s2 -= 1 + e2 -= 1 + return grid +``` + +### **Java** + +```java +class Solution { + public int[][] rotateGrid(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + int s1 = 0, e1 = 0; + int s2 = m - 1, e2 = n - 1; + while (s1 <= s2 && e1 <= e2) { + rotate(grid, s1++, e1++, s2--, e2--, k); + } + return grid; + } + + private void rotate(int[][] grid, int s1, int e1, int s2, int e2, int k) { + List t = new ArrayList<>(); + for (int j = e2; j > e1; --j) { + t.add(grid[s1][j]); + } + for (int i = s1; i < s2; ++i) { + t.add(grid[i][e1]); + } + for (int j = e1; j < e2; ++j) { + t.add(grid[s2][j]); + } + for (int i = s2; i > s1; --i) { + t.add(grid[i][e2]); + } + int n = t.size(); + k %= n; + if (k == 0) { + return; + } + k = n - k; + for (int j = e2; j > e1; --j) { + grid[s1][j] = t.get(k); + k = (k + 1) % n; + } + for (int i = s1; i < s2; ++i) { + grid[i][e1] = t.get(k); + k = (k + 1) % n; + } + for (int j = e1; j < e2; ++j) { + grid[s2][j] = t.get(k); + k = (k + 1) % n; + } + for (int i = s2; i > s1; --i) { + grid[i][e2] = t.get(k); + k = (k + 1) % n; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/images/explanation_grid.jpg b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/explanation_grid.jpg new file mode 100644 index 00000000..bf0b6ce8 Binary files /dev/null and b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/explanation_grid.jpg differ diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid.png b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid.png new file mode 100644 index 00000000..fb4d3cc9 Binary files /dev/null and b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid.png differ diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid5.png b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid5.png new file mode 100644 index 00000000..5abdea74 Binary files /dev/null and b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid5.png differ diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid6.png b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid6.png new file mode 100644 index 00000000..62ea839c Binary files /dev/null and b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid6.png differ diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid7.png b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid7.png new file mode 100644 index 00000000..0f4a2ae6 Binary files /dev/null and b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/ringofgrid7.png differ diff --git a/assets/1900-1999/1914.Cyclically Rotating a Grid/images/rod2.png b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/rod2.png new file mode 100644 index 00000000..29887940 Binary files /dev/null and b/assets/1900-1999/1914.Cyclically Rotating a Grid/images/rod2.png differ diff --git a/assets/1900-1999/1915.Number of Wonderful Substrings/README_EN.md b/assets/1900-1999/1915.Number of Wonderful Substrings/README_EN.md new file mode 100644 index 00000000..714494cd --- /dev/null +++ b/assets/1900-1999/1915.Number of Wonderful Substrings/README_EN.md @@ -0,0 +1,114 @@ +# [1915. Number of Wonderful Substrings](https://leetcode.com/problems/number-of-wonderful-substrings) + + + +## Description + +

    A wonderful string is a string where at most one letter appears an odd number of times.

    + +
      +
    • For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
    • +
    + +

    Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.

    + +

    A substring is a contiguous sequence of characters in a string.

    + +

     

    +

    Example 1:

    + +
    +Input: word = "aba"
    +Output: 4
    +Explanation: The four wonderful substrings are underlined below:
    +- "aba" -> "a"
    +- "aba" -> "b"
    +- "aba" -> "a"
    +- "aba" -> "aba"
    +
    + +

    Example 2:

    + +
    +Input: word = "aabb"
    +Output: 9
    +Explanation: The nine wonderful substrings are underlined below:
    +- "aabb" -> "a"
    +- "aabb" -> "aa"
    +- "aabb" -> "aab"
    +- "aabb" -> "aabb"
    +- "aabb" -> "a"
    +- "aabb" -> "abb"
    +- "aabb" -> "b"
    +- "aabb" -> "bb"
    +- "aabb" -> "b"
    +
    + +

    Example 3:

    + +
    +Input: word = "he"
    +Output: 2
    +Explanation: The two wonderful substrings are underlined below:
    +- "he" -> "h"
    +- "he" -> "e"
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= word.length <= 105
    • +
    • word consists of lowercase English letters from 'a' to 'j'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **JavaScript** + +```js +/** + * @param {string} word + * @return {number} + */ +var wonderfulSubstrings = function(word) { + let n = 1 << 10; + let counts = new Array(n).fill(0); + counts[0] = 1; + let pre = 0; + let ans = 0; + for (let c of word) { + let cur = c.charCodeAt(0) - 'a'.charCodeAt(0); + pre ^= (1 << cur); + ans += counts[pre]; + for (let i = 1; i < n; i <<= 1) { + ans += counts[pre ^ i]; + } + ++counts[pre]; + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md b/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md new file mode 100644 index 00000000..708a1d2c --- /dev/null +++ b/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md @@ -0,0 +1,72 @@ +# [1916. Count Ways to Build Rooms in an Ant Colony](https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony) + + + +## Description + +

    You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0.

    + +

    You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built.

    + +

    Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: prevRoom = [-1,0,1]
    +Output: 1
    +Explanation: There is only one way to build the additional rooms: 0 → 1 → 2
    +
    + +

    Example 2:

    + + +
    +Input: prevRoom = [-1,0,0,1,2]
    +Output: 6
    +Explanation:
    +The 6 ways are:
    +0 → 1 → 3 → 2 → 4
    +0 → 2 → 4 → 1 → 3
    +0 → 1 → 2 → 3 → 4
    +0 → 1 → 2 → 4 → 3
    +0 → 2 → 1 → 3 → 4
    +0 → 2 → 1 → 4 → 3
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == prevRoom.length
    • +
    • 2 <= n <= 105
    • +
    • prevRoom[0] == -1
    • +
    • 0 <= prevRoom[i] < n for all 1 <= i < n
    • +
    • Every room is reachable from room 0 once all the rooms are built.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/images/d1.jpg b/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/images/d1.jpg new file mode 100644 index 00000000..739f5afd Binary files /dev/null and b/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/images/d1.jpg differ diff --git a/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/images/d2.jpg b/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/images/d2.jpg new file mode 100644 index 00000000..d5328564 Binary files /dev/null and b/assets/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/images/d2.jpg differ diff --git a/assets/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md b/assets/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md new file mode 100644 index 00000000..62076cd6 --- /dev/null +++ b/assets/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md @@ -0,0 +1,111 @@ +# [1917. Leetcodify Friends Recommendations](https://leetcode.com/problems/leetcodify-friends-recommendations) + + + +## Description + +

    Table: Listens

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| song_id     | int     |
    +| day         | date    |
    ++-------------+---------+
    +There is no primary key for this table. It may contain duplicates.
    +Each row of this table indicates that the user user_id listened to the song song_id on the day day.
    +
    + +

     

    + +

    Table: Friendship

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user1_id      | int     |
    +| user2_id      | int     |
    ++---------------+---------+
    +(user1_id, user2_id) is the primary key for this table.
    +Each row of this table indicates that the users user1_id and user2_id are friends.
    +Note that user1_id < user2_id.
    +
    + +

     

    + +

    Write an SQL query to recommend friends to Leetcodify users. We recommend user x to user y if:

    + +
      +
    • Users x and y are not friends, and
    • +
    • Users x and y listened to the same three or more different songs on the same day.
    • +
    + +

    Note that friend recommendations are unidirectional, meaning if user x and user y should be recommended to each other, the result table should have both user x recommended to user y and user y recommended to user x.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Listens table:
    ++---------+---------+------------+
    +| user_id | song_id | day        |
    ++---------+---------+------------+
    +| 1       | 10      | 2021-03-15 |
    +| 1       | 11      | 2021-03-15 |
    +| 1       | 12      | 2021-03-15 |
    +| 2       | 10      | 2021-03-15 |
    +| 2       | 11      | 2021-03-15 |
    +| 2       | 12      | 2021-03-15 |
    +| 3       | 10      | 2021-03-15 |
    +| 3       | 11      | 2021-03-15 |
    +| 3       | 12      | 2021-03-15 |
    +| 4       | 10      | 2021-03-15 |
    +| 4       | 11      | 2021-03-15 |
    +| 4       | 13      | 2021-03-15 |
    +| 5       | 10      | 2021-03-16 |
    +| 5       | 11      | 2021-03-16 |
    +| 5       | 12      | 2021-03-16 |
    ++---------+---------+------------+
    +
    +Friendship table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    ++----------+----------+
    +
    +Result table:
    ++---------+----------------+
    +| user_id | recommended_id |
    ++---------+----------------+
    +| 1       | 3              |
    +| 2       | 3              |
    +| 3       | 1              |
    +| 3       | 2              |
    ++---------+----------------+
    +Users 1 and 2 listened to songs 10, 11, and 12 on the same day, but they are already friends.
    +Users 1 and 3 listened to songs 10, 11, and 12 on the same day. Since they are not friends, we recommend them to each other.
    +Users 1 and 4 did not listen to the same three songs.
    +Users 1 and 5 listened to songs 10, 11, and 12, but on different days.
    +
    +Similarly, we can see that users 2 and 3 listened to songs 10, 11, and 12 on the same day and are not friends, so we recommend them to each other.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md b/assets/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md new file mode 100644 index 00000000..6762ae0e --- /dev/null +++ b/assets/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md @@ -0,0 +1,79 @@ +# [1918. Kth Smallest Subarray Sum](https://leetcode.com/problems/kth-smallest-subarray-sum) + + + +## Description + +

    Given an integer array nums of length n and an integer k, return the kth smallest subarray sum.

    + +

    A subarray is defined as a non-empty contiguous sequence of elements in an array. A subarray sum is the sum of all elements in the subarray.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,1,3], k = 4
    +Output: 3
    +Explanation: The subarrays of [2,1,3] are:
    +- [2] with sum 2
    +- [1] with sum 1
    +- [3] with sum 3
    +- [2,1] with sum 3
    +- [1,3] with sum 4
    +- [2,1,3] with sum 6 
    +Ordering the sums from smallest to largest gives 1, 2, 3, 3, 4, 6. The 4th smallest is 3.
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,3,5,5], k = 7
    +Output: 10
    +Explanation: The subarrays of [3,3,5,5] are:
    +- [3] with sum 3
    +- [3] with sum 3
    +- [5] with sum 5
    +- [5] with sum 5
    +- [3,3] with sum 6
    +- [3,5] with sum 8
    +- [5,5] with sum 10
    +- [3,3,5], with sum 11
    +- [3,5,5] with sum 13
    +- [3,3,5,5] with sum 16
    +Ordering the sums from smallest to largest gives 3, 3, 5, 5, 6, 8, 10, 11, 13, 16. The 7th smallest is 10.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 2 * 104
    • +
    • 1 <= nums[i] <= 5 * 104
    • +
    • 1 <= k <= n * (n + 1) / 2
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1919.Leetcodify Similar Friends/README_EN.md b/assets/1900-1999/1919.Leetcodify Similar Friends/README_EN.md new file mode 100644 index 00000000..68b2b38f --- /dev/null +++ b/assets/1900-1999/1919.Leetcodify Similar Friends/README_EN.md @@ -0,0 +1,107 @@ +# [1919. Leetcodify Similar Friends](https://leetcode.com/problems/leetcodify-similar-friends) + + + +## Description + +

    Table: Listens

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| song_id     | int     |
    +| day         | date    |
    ++-------------+---------+
    +There is no primary key for this table. It may contain duplicates.
    +Each row of this table indicates that the user user_id listened to the song song_id on the day day.
    +
    + +

     

    + +

    Table: Friendship

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user1_id      | int     |
    +| user2_id      | int     |
    ++---------------+---------+
    +(user1_id, user2_id) is the primary key for this table.
    +Each row of this table indicates that the users user1_id and user2_id are friends.
    +Note that user1_id < user2_id.
    +
    + +

     

    + +

    Write an SQL query to report the similar friends of Leetcodify users. A user x and user y are similar friends if:

    + +
      +
    • Users x and y are friends, and
    • +
    • Users x and y listened to the same three or more different songs on the same day.
    • +
    + +

    Return the result table in any order. Note that you must return the similar pairs of friends the same way they were represented in the input (i.e., always user1_id < user2_id).

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Listens table:
    ++---------+---------+------------+
    +| user_id | song_id | day        |
    ++---------+---------+------------+
    +| 1       | 10      | 2021-03-15 |
    +| 1       | 11      | 2021-03-15 |
    +| 1       | 12      | 2021-03-15 |
    +| 2       | 10      | 2021-03-15 |
    +| 2       | 11      | 2021-03-15 |
    +| 2       | 12      | 2021-03-15 |
    +| 3       | 10      | 2021-03-15 |
    +| 3       | 11      | 2021-03-15 |
    +| 3       | 12      | 2021-03-15 |
    +| 4       | 10      | 2021-03-15 |
    +| 4       | 11      | 2021-03-15 |
    +| 4       | 13      | 2021-03-15 |
    +| 5       | 10      | 2021-03-16 |
    +| 5       | 11      | 2021-03-16 |
    +| 5       | 12      | 2021-03-16 |
    ++---------+---------+------------+
    +
    +Friendship table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    +| 2        | 4        |
    +| 2        | 5        |
    ++----------+----------+
    +
    +Result table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    ++----------+----------+
    +
    +Users 1 and 2 are friends, and they listened to songs 10, 11, and 12 on the same day. They are similar friends.
    +Users 1 and 3 listened to songs 10, 11, and 12 on the same day, but they are not friends.
    +Users 2 and 4 are friends, but they did not listen to the same three different songs.
    +Users 2 and 5 are friends and listened to songs 10, 11, and 12, but they did not listen to them on the same day.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1900-1999/1920.Build Array from Permutation/README_EN.md b/assets/1900-1999/1920.Build Array from Permutation/README_EN.md new file mode 100644 index 00000000..bdbc3879 --- /dev/null +++ b/assets/1900-1999/1920.Build Array from Permutation/README_EN.md @@ -0,0 +1,117 @@ +# [1920. Build Array from Permutation](https://leetcode.com/problems/build-array-from-permutation) + + + +## Description + +

    Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.

    + +

    A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [0,2,1,5,3,4]
    +Output: [0,1,2,4,5,3]
    +Explanation: The array ans is built as follows: 
    +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    +    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
    +    = [0,1,2,4,5,3]
    + +

    Example 2:

    + +
    +Input: nums = [5,0,1,2,3,4]
    +Output: [4,5,0,1,2,3]
    +Explanation: The array ans is built as follows:
    +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    +    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
    +    = [4,5,0,1,2,3]
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 0 <= nums[i] < nums.length
    • +
    • The elements in nums are distinct.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def buildArray(self, nums: List[int]) -> List[int]: + return [nums[num] for num in nums] +``` + +### **Java** + +```java +class Solution { + public int[] buildArray(int[] nums) { + int[] ans = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) { + ans[i] = nums[nums[i]]; + } + return ans; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var buildArray = function(nums) { + let ans = []; + for (let i = 0; i < nums.length; ++i) { + ans[i] = nums[nums[i]]; + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector buildArray(vector& nums) { + vector ans; + for (int& num : nums) { + ans.push_back(nums[num]); + } + return ans; + } +}; +``` + +### **Go** + +```go +func buildArray(nums []int) []int { + ans := make([]int, len(nums)) + for i, num := range nums { + ans[i] = nums[num] + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md b/assets/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md new file mode 100644 index 00000000..761d67d6 --- /dev/null +++ b/assets/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md @@ -0,0 +1,169 @@ +# [1921. Eliminate Maximum Number of Monsters](https://leetcode.com/problems/eliminate-maximum-number-of-monsters) + + + +## Description + +

    You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in meters of the ith monster from the city.

    + +

    The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in meters per minute.

    + +

    The monsters start moving at minute 0. You have a weapon that you can choose to use at the start of every minute, including minute 0. You cannot use the weapon in the middle of a minute. The weapon can eliminate any monster that is still alive. You lose when any monster reaches your city. If a monster reaches the city exactly at the start of a minute, it counts as a loss, and the game ends before you can use your weapon in that minute.

    + +

    Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.

    + +

     

    +

    Example 1:

    + +
    +Input: dist = [1,3,4], speed = [1,1,1]
    +Output: 3
    +Explanation:
    +At the start of minute 0, the distances of the monsters are [1,3,4], you eliminate the first monster.
    +At the start of minute 1, the distances of the monsters are [X,2,3], you don't do anything.
    +At the start of minute 2, the distances of the monsters are [X,1,2], you eliminate the second monster.
    +At the start of minute 3, the distances of the monsters are [X,X,1], you eliminate the third monster.
    +All 3 monsters can be eliminated.
    + +

    Example 2:

    + +
    +Input: dist = [1,1,2,3], speed = [1,1,1,1]
    +Output: 1
    +Explanation:
    +At the start of minute 0, the distances of the monsters are [1,1,2,3], you eliminate the first monster.
    +At the start of minute 1, the distances of the monsters are [X,0,1,2], so you lose.
    +You can only eliminate 1 monster.
    +
    + +

    Example 3:

    + +
    +Input: dist = [3,2,4], speed = [5,3,2]
    +Output: 1
    +Explanation:
    +At the start of minute 0, the distances of the monsters are [3,2,4], you eliminate the first monster.
    +At the start of minute 1, the distances of the monsters are [X,0,2], so you lose.
    +You can only eliminate 1 monster.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == dist.length == speed.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= dist[i], speed[i] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: + n = len(dist) + times = [(dist[i] - 1) // speed[i] for i in range(n)] + times.sort() + for i in range(n): + if times[i] < i: + return i + return n +``` + +### **Java** + +```java +class Solution { + public int eliminateMaximum(int[] dist, int[] speed) { + int n = dist.length; + int[] times = new int[n]; + for (int i = 0; i < n; ++i) { + times[i] = (dist[i] - 1) / speed[i]; + } + Arrays.sort(times); + for (int i = 0; i < n; ++i) { + if (times[i] < i) { + return i; + } + } + return n; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} dist + * @param {number[]} speed + * @return {number} + */ + var eliminateMaximum = function(dist, speed) { + let arr = []; + for (let i = 0; i < dist.length; i++) { + arr[i] = dist[i] / speed[i]; + } + arr.sort((a, b) => a - b); + let ans = 0; + while (arr[0] > ans) { + arr.shift(); + ++ans; + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int eliminateMaximum(vector& dist, vector& speed) { + int n = dist.size(); + vector times; + for (int i = 0; i < n; ++i) { + times.push_back((dist[i] - 1) / speed[i]); + } + sort(times.begin(), times.end()); + for (int i = 0; i < n; ++i) { + if (times[i] < i) { + return i; + } + } + return n; + } +}; +``` + +### **Go** + +```go +func eliminateMaximum(dist []int, speed []int) int { + n := len(dist) + times := make([]int, n) + for i := 0; i < n; i++ { + times[i] = (dist[i] - 1) / speed[i] + } + sort.Ints(times) + for i := 0; i < n; i++ { + if times[i] < i { + return i + } + } + return n +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1922.Count Good Numbers/README_EN.md b/assets/1900-1999/1922.Count Good Numbers/README_EN.md new file mode 100644 index 00000000..99cf7c9f --- /dev/null +++ b/assets/1900-1999/1922.Count Good Numbers/README_EN.md @@ -0,0 +1,149 @@ +# [1922. Count Good Numbers](https://leetcode.com/problems/count-good-numbers) + + + +## Description + +

    A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).

    + +
      +
    • For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even.
    • +
    + +

    Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.

    + +

    A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 1
    +Output: 5
    +Explanation: The good numbers of length 1 are "0", "2", "4", "6", "8".
    +
    + +

    Example 2:

    + +
    +Input: n = 4
    +Output: 400
    +
    + +

    Example 3:

    + +
    +Input: n = 50
    +Output: 564908303
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 1015
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countGoodNumbers(self, n: int) -> int: + mod = 10 ** 9 + 7 + + def myPow(x, n): + res = 1 + while n: + if (n & 1) == 1: + res = res * x % mod + x = x * x % mod + n >>= 1 + return res + + return myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % mod +``` + +### **Java** + +```java +class Solution { + private int mod = 1000000007; + + public int countGoodNumbers(long n) { + return (int) (myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % mod); + } + + private long myPow(long x, long n) { + long res = 1; + while (n != 0) { + if ((n & 1) == 1) { + res = res * x % mod; + } + x = x * x % mod; + n >>= 1; + } + return res; + } +} +``` + +### **C++** + +```cpp +int MOD = 1000000007; + +class Solution { +public: + int countGoodNumbers(long long n) { + return (int) (myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % MOD); + } + +private: + long long myPow(long long x, long long n) { + long long res = 1; + while (n) { + if ((n & 1) == 1) { + res = res * x % MOD; + } + x = x * x % MOD; + n >>= 1; + } + return res; + } +}; +``` + +### **Go** + +```go +const mod int64 = 1e9 + 7 + +func countGoodNumbers(n int64) int { + return int(myPow(5, (n+1)>>1) * myPow(4, n>>1) % mod) +} + +func myPow(x, n int64) int64 { + var res int64 = 1 + for n != 0 { + if (n & 1) == 1 { + res = res * x % mod + } + x = x * x % mod + n >>= 1 + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1923.Longest Common Subpath/README_EN.md b/assets/1900-1999/1923.Longest Common Subpath/README_EN.md new file mode 100644 index 00000000..25aaf6b8 --- /dev/null +++ b/assets/1900-1999/1923.Longest Common Subpath/README_EN.md @@ -0,0 +1,130 @@ +# [1923. Longest Common Subpath](https://leetcode.com/problems/longest-common-subpath) + + + +## Description + +

    There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.

    + +

    There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.

    + +

    Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.

    + +

    A subpath of a path is a contiguous sequence of cities within that path.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5, paths = [[0,1,2,3,4],
    +                       [2,3,4],
    +                       [4,0,1,2,3]]
    +Output: 2
    +Explanation: The longest common subpath is [2,3].
    +
    + +

    Example 2:

    + +
    +Input: n = 3, paths = [[0],[1],[2]]
    +Output: 0
    +Explanation: There is no common subpath shared by the three paths.
    +
    + +

    Example 3:

    + +
    +Input: n = 5, paths = [[0,1,2,3,4],
    +                       [4,3,2,1,0]]
    +Output: 1
    +Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 105
    • +
    • m == paths.length
    • +
    • 2 <= m <= 105
    • +
    • sum(paths[i].length) <= 105
    • +
    • 0 <= paths[i][j] < n
    • +
    • The same city is not listed multiple times consecutively in paths[i].
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java +class Solution { + int N = 100010; + long[] h = new long[N]; + long[] p = new long[N]; + private int[][] paths; + Map cnt = new HashMap<>(); + Map inner = new HashMap<>(); + + public int longestCommonSubpath(int n, int[][] paths) { + int left = 0, right = N; + for (int[] path : paths) { + right = Math.min(right, path.length); + } + this.paths = paths; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(int mid) { + cnt.clear(); + inner.clear(); + p[0] = 1; + for (int j = 0; j < paths.length; ++j) { + int n = paths[j].length; + for (int i = 1; i <= n; ++i) { + p[i] = p[i - 1] * 133331; + h[i] = h[i - 1] * 133331 + paths[j][i - 1]; + } + for (int i = mid; i <= n; ++i) { + long val = get(i - mid + 1, i); + if (!inner.containsKey(val) || inner.get(val) != j) { + inner.put(val, j); + cnt.put(val, cnt.getOrDefault(val, 0) + 1); + } + } + } + int max = 0; + for (int val : cnt.values()) { + max = Math.max(max, val); + } + return max == paths.length; + } + + private long get(int l, int r) { + return h[r] - h[l - 1] * p[r - l + 1]; + } +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1924.Erect the Fence II/README_EN.md b/assets/1900-1999/1924.Erect the Fence II/README_EN.md new file mode 100644 index 00000000..899936ee --- /dev/null +++ b/assets/1900-1999/1924.Erect the Fence II/README_EN.md @@ -0,0 +1,68 @@ +# [1924. Erect the Fence II](https://leetcode.com/problems/erect-the-fence-ii) + + + +## Description + +

    You are given a 2D integer array trees where trees[i] = [xi, yi] represents the location of the ith tree in the garden.

    + +

    You are asked to fence the entire garden using the minimum length of rope possible. The garden is well-fenced only if all the trees are enclosed and the rope used forms a perfect circle. A tree is considered enclosed if it is inside or on the border of the circle.

    + +

    More formally, you must form a circle using the rope with a center (x, y) and radius r where all trees lie inside or on the circle and r is minimum.

    + +

    Return the center and radius of the circle as a length 3 array [x, y, r]. Answers within 10-5 of the actual answer will be accepted.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
    +Output: [2.00000,2.00000,2.00000]
    +Explanation: The fence will have center = (2, 2) and radius = 2
    +
    + +

    Example 2:

    + +

    + +
    +Input: trees = [[1,2],[2,2],[4,2]]
    +Output: [2.50000,2.00000,1.50000]
    +Explanation: The fence will have center = (2.5, 2) and radius = 1.5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= trees.length <= 3000
    • +
    • trees[i].length == 2
    • +
    • 0 <= xi, yi <= 3000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1924.Erect the Fence II/images/trees1.png b/assets/1900-1999/1924.Erect the Fence II/images/trees1.png new file mode 100644 index 00000000..bdc537ed Binary files /dev/null and b/assets/1900-1999/1924.Erect the Fence II/images/trees1.png differ diff --git a/assets/1900-1999/1924.Erect the Fence II/images/trees2.png b/assets/1900-1999/1924.Erect the Fence II/images/trees2.png new file mode 100644 index 00000000..bf7112ac Binary files /dev/null and b/assets/1900-1999/1924.Erect the Fence II/images/trees2.png differ diff --git a/assets/1900-1999/1925.Count Square Sum Triples/README_EN.md b/assets/1900-1999/1925.Count Square Sum Triples/README_EN.md new file mode 100644 index 00000000..90c08c43 --- /dev/null +++ b/assets/1900-1999/1925.Count Square Sum Triples/README_EN.md @@ -0,0 +1,120 @@ +# [1925. Count Square Sum Triples](https://leetcode.com/problems/count-square-sum-triples) + + + +## Description + +

    A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.

    + +

    Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.

    + +

     

    +

    Example 1:

    + +
    +Input: n = 5
    +Output: 2
    +Explanation: The square triples are (3,4,5) and (4,3,5).
    +
    + +

    Example 2:

    + +
    +Input: n = 10
    +Output: 4
    +Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n <= 250
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countTriples(self, n: int) -> int: + res = 0 + for a in range(1, n + 1): + for b in range(1, n + 1): + t = a ** 2 + b ** 2 + c = int(sqrt(t)) + if c <= n and c ** 2 == t: + res += 1 + return res +``` + +### **Java** + +```java +class Solution { + public int countTriples(int n) { + int res = 0; + for (int a = 1; a <= n; ++a) { + for (int b = 1; b <= n; ++b) { + int t = a * a + b * b; + int c = (int) Math.sqrt(t); + if (c <= n && c * c == t) { + ++res; + } + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int countTriples(int n) { + int res = 0; + for (int a = 1; a <= n; ++a) { + for (int b = 1; b <= n; ++b) { + int t = a * a + b * b; + int c = (int) sqrt(t); + if (c <= n && c * c == t) { + ++res; + } + } + } + return res; + } +}; +``` + +### **Go** + +```go +func countTriples(n int) int { + res := 0 + for a := 1; a <= n; a++ { + for b := 1; b <= n; b++ { + t := a*a + b*b + c := int(math.Sqrt(float64(t))) + if c <= n && c*c == t { + res++ + } + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md new file mode 100644 index 00000000..b7b99114 --- /dev/null +++ b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md @@ -0,0 +1,84 @@ +# [1926. Nearest Exit from Entrance in Maze](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze) + + + +## Description + +

    You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.

    + +

    In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.

    + +

    Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.

    + +

     

    +

    Example 1:

    + +
    +Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
    +Output: 1
    +Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].
    +Initially, you are at the entrance cell [1,2].
    +- You can reach [1,0] by moving 2 steps left.
    +- You can reach [0,2] by moving 1 step up.
    +It is impossible to reach [2,3] from the entrance.
    +Thus, the nearest exit is [0,2], which is 1 step away.
    +
    + +

    Example 2:

    + +
    +Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
    +Output: 2
    +Explanation: There is 1 exit in this maze at [1,2].
    +[1,0] does not count as an exit since it is the entrance cell.
    +Initially, you are at the entrance cell [1,0].
    +- You can reach [1,2] by moving 2 steps right.
    +Thus, the nearest exit is [1,2], which is 2 steps away.
    +
    + +

    Example 3:

    + +
    +Input: maze = [[".","+"]], entrance = [0,0]
    +Output: -1
    +Explanation: There are no exits in this maze.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • maze.length == m
    • +
    • maze[i].length == n
    • +
    • 1 <= m, n <= 100
    • +
    • maze[i][j] is either '.' or '+'.
    • +
    • entrance.length == 2
    • +
    • 0 <= entrancerow < m
    • +
    • 0 <= entrancecol < n
    • +
    • entrance will always be an empty cell.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearesr2-grid.jpg b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearesr2-grid.jpg new file mode 100644 index 00000000..1bea2eb0 Binary files /dev/null and b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearesr2-grid.jpg differ diff --git a/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearest1-grid.jpg b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearest1-grid.jpg new file mode 100644 index 00000000..5f3e5415 Binary files /dev/null and b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearest1-grid.jpg differ diff --git a/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearest3-grid.jpg b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearest3-grid.jpg new file mode 100644 index 00000000..5f18d961 Binary files /dev/null and b/assets/1900-1999/1926.Nearest Exit from Entrance in Maze/images/nearest3-grid.jpg differ diff --git a/assets/1900-1999/1927.Sum Game/README_EN.md b/assets/1900-1999/1927.Sum Game/README_EN.md new file mode 100644 index 00000000..83e67c37 --- /dev/null +++ b/assets/1900-1999/1927.Sum Game/README_EN.md @@ -0,0 +1,89 @@ +# [1927. Sum Game](https://leetcode.com/problems/sum-game) + + + +## Description + +

    Alice and Bob take turns playing a game, with Alice starting first.

    + +

    You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:

    + +
      +
    1. Choose an index i where num[i] == '?'.
    2. +
    3. Replace num[i] with any digit between '0' and '9'.
    4. +
    + +

    The game ends when there are no more '?' characters in num.

    + +

    For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.

    + +
      +
    • For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3.
    • +
    + +

    Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.

    + +

     

    +

    Example 1:

    + +
    +Input: num = "5023"
    +Output: false
    +Explanation: There are no moves to be made.
    +The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.
    +
    + +

    Example 2:

    + +
    +Input: num = "25??"
    +Output: true
    +Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.
    +
    + +

    Example 3:

    + +
    +Input: num = "?3295???"
    +Output: false
    +Explanation: It can be proven that Bob will always win. One possible outcome is:
    +- Alice replaces the first '?' with '9'. num = "93295???".
    +- Bob replaces one of the '?' in the right half with '9'. num = "932959??".
    +- Alice replaces one of the '?' in the right half with '2'. num = "9329592?".
    +- Bob replaces the last '?' in the right half with '7'. num = "93295927".
    +Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= num.length <= 105
    • +
    • num.length is even.
    • +
    • num consists of only digits and '?'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md b/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md new file mode 100644 index 00000000..0a211c2a --- /dev/null +++ b/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md @@ -0,0 +1,83 @@ +# [1928. Minimum Cost to Reach Destination in Time](https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time) + + + +## Description + +

    There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.

    + +

    Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.

    + +

    In the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).

    + +

    Given maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
    +Output: 11
    +Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
    +
    + +

    Example 2:

    + +

    + +
    +Input: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
    +Output: 48
    +Explanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
    +You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
    +
    + +

    Example 3:

    + +
    +Input: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
    +Output: -1
    +Explanation: There is no way to reach city 5 from city 0 within 25 minutes.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= maxTime <= 1000
    • +
    • n == passingFees.length
    • +
    • 2 <= n <= 1000
    • +
    • n - 1 <= edges.length <= 1000
    • +
    • 0 <= xi, yi <= n - 1
    • +
    • 1 <= timei <= 1000
    • +
    • 1 <= passingFees[j] <= 1000 
    • +
    • The graph may contain multiple edges between two nodes.
    • +
    • The graph does not contain self loops.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/images/copy-of-leetgraph1-1.png b/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/images/copy-of-leetgraph1-1.png new file mode 100644 index 00000000..e0646f99 Binary files /dev/null and b/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/images/copy-of-leetgraph1-1.png differ diff --git a/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/images/leetgraph1-1.png b/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/images/leetgraph1-1.png new file mode 100644 index 00000000..4f9f654d Binary files /dev/null and b/assets/1900-1999/1928.Minimum Cost to Reach Destination in Time/images/leetgraph1-1.png differ diff --git a/assets/1900-1999/1929.Concatenation of Array/README_EN.md b/assets/1900-1999/1929.Concatenation of Array/README_EN.md new file mode 100644 index 00000000..a8a2be4b --- /dev/null +++ b/assets/1900-1999/1929.Concatenation of Array/README_EN.md @@ -0,0 +1,112 @@ +# [1929. Concatenation of Array](https://leetcode.com/problems/concatenation-of-array) + + + +## Description + +

    Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

    + +

    Specifically, ans is the concatenation of two nums arrays.

    + +

    Return the array ans.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [1,2,1]
    +Output: [1,2,1,1,2,1]
    +Explanation: The array ans is formed as follows:
    +- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
    +- ans = [1,2,1,1,2,1]
    + +

    Example 2:

    + +
    +Input: nums = [1,3,2,1]
    +Output: [1,3,2,1,1,3,2,1]
    +Explanation: The array ans is formed as follows:
    +- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
    +- ans = [1,3,2,1,1,3,2,1]
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 1000
    • +
    • 1 <= nums[i] <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def getConcatenation(self, nums: List[int]) -> List[int]: + return nums + nums +``` + +### **Java** + +```java +class Solution { + public int[] getConcatenation(int[] nums) { + int n = nums.length; + int[] ans = new int[n << 1]; + for (int i = 0; i < n << 1; ++i) { + ans[i] = nums[i % n]; + } + return ans; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var getConcatenation = function(nums) { + let ans = nums.slice(); + ans.splice(nums.length, 0, ...nums); + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector getConcatenation(vector& nums) { + for (int i = 0, n = nums.size(); i < n; ++i) { + nums.push_back(nums[i]); + } + return nums; + } +}; +``` + +### **Go** + +```go +func getConcatenation(nums []int) []int { + return append(nums, nums...) +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md b/assets/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md new file mode 100644 index 00000000..ab870da5 --- /dev/null +++ b/assets/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md @@ -0,0 +1,141 @@ +# [1930. Unique Length-3 Palindromic Subsequences](https://leetcode.com/problems/unique-length-3-palindromic-subsequences) + + + +## Description + +

    Given a string s, return the number of unique palindromes of length three that are a subsequence of s.

    + +

    Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.

    + +

    A palindrome is a string that reads the same forwards and backwards.

    + +

    A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

    + +
      +
    • For example, "ace" is a subsequence of "abcde".
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: s = "aabca"
    +Output: 3
    +Explanation: The 3 palindromic subsequences of length 3 are:
    +- "aba" (subsequence of "aabca")
    +- "aaa" (subsequence of "aabca")
    +- "aca" (subsequence of "aabca")
    +
    + +

    Example 2:

    + +
    +Input: s = "adc"
    +Output: 0
    +Explanation: There are no palindromic subsequences of length 3 in "adc".
    +
    + +

    Example 3:

    + +
    +Input: s = "bbcbaba"
    +Output: 4
    +Explanation: The 4 palindromic subsequences of length 3 are:
    +- "bbb" (subsequence of "bbcbaba")
    +- "bcb" (subsequence of "bbcbaba")
    +- "bab" (subsequence of "bbcbaba")
    +- "aba" (subsequence of "bbcbaba")
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 3 <= s.length <= 105
    • +
    • s consists of only lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python +class Solution: + def countPalindromicSubsequence(self, s: str) -> int: + res = 0 + for i in range(26): + c = chr(ord('a') + i) + if c in s: + l, r = s.index(c), s.rindex(c) + chars = {s[j] for j in range(l + 1, r)} + res += len(chars) + return res +``` + +### **Java** + +```java +class Solution { + public int countPalindromicSubsequence(String s) { + int res = 0; + for (char c = 'a'; c <= 'z'; ++c) { + int l = s.indexOf(c), r = s.lastIndexOf(c); + Set chars = new HashSet<>(); + for (int i = l + 1; i < r; ++i) { + chars.add(s.charAt(i)); + } + res += chars.size(); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int countPalindromicSubsequence(string s) { + int res = 0; + for (char c = 'a'; c <= 'z'; ++c) { + int l = s.find_first_of(c), r = s.find_last_of(c); + unordered_set chars; + for (int i = l + 1; i < r; ++i) { + chars.insert(s[i]); + } + res += chars.size(); + } + return res; + } +}; +``` + +### **Go** + +```go +func countPalindromicSubsequence(s string) int { + res := 0 + for c := 'a'; c <= 'z'; c++ { + l, r := strings.Index(s, string(c)), strings.LastIndex(s, string(c)) + chars := make(map[byte]bool) + for i := l + 1; i < r; i++ { + chars[s[i]] = true + } + res += len(chars) + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md b/assets/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md new file mode 100644 index 00000000..dd2595a0 --- /dev/null +++ b/assets/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md @@ -0,0 +1,66 @@ +# [1931. Painting a Grid With Three Different Colors](https://leetcode.com/problems/painting-a-grid-with-three-different-colors) + + + +## Description + +

    You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.

    + +

    Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.

    + +

     

    +

    Example 1:

    + +
    +Input: m = 1, n = 1
    +Output: 3
    +Explanation: The three possible colorings are shown in the image above.
    +
    + +

    Example 2:

    + +
    +Input: m = 1, n = 2
    +Output: 6
    +Explanation: The six possible colorings are shown in the image above.
    +
    + +

    Example 3:

    + +
    +Input: m = 5, n = 5
    +Output: 580986
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= m <= 5
    • +
    • 1 <= n <= 1000
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md b/assets/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md new file mode 100644 index 00000000..4f13fc38 --- /dev/null +++ b/assets/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md @@ -0,0 +1,104 @@ +# [1932. Merge BSTs to Create Single BST](https://leetcode.com/problems/merge-bsts-to-create-single-bst) + + + +## Description + +

    You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:

    + +
      +
    • Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].
    • +
    • Replace the leaf node in trees[i] with trees[j].
    • +
    • Remove trees[j] from trees.
    • +
    + +

    Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.

    + +

    A BST (binary search tree) is a binary tree where each node satisfies the following property:

    + +
      +
    • Every node in the node's left subtree has a value strictly less than the node's value.
    • +
    • Every node in the node's right subtree has a value strictly greater than the node's value.
    • +
    + +

    A leaf is a node that has no children.

    + +

     

    +

    Example 1:

    + +
    +Input: trees = [[2,1],[3,2,5],[5,4]]
    +Output: [3,2,5,1,null,4]
    +Explanation:
    +In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].
    +Delete trees[0], so trees = [[3,2,5,1],[5,4]].
    +
    +In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].
    +Delete trees[1], so trees = [[3,2,5,1,null,4]].
    +
    +The resulting tree, shown above, is a valid BST, so return its root.
    + +

    Example 2:

    + +
    +Input: trees = [[5,3,8],[3,2,6]]
    +Output: []
    +Explanation:
    +Pick i=0 and j=1 and merge trees[1] into trees[0].
    +Delete trees[1], so trees = [[5,3,8,2,6]].
    +
    +The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.
    +
    + +

    Example 3:

    + +
    +Input: trees = [[5,4],[3]]
    +Output: []
    +Explanation: It is impossible to perform any operations.
    +
    + +

    Example 4:

    + +
    +Input: trees = [[2,1,3]]
    +Output: [2,1,3]
    +Explanation: There is only one tree, and it is already a valid BST, so return its root.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == trees.length
    • +
    • 1 <= n <= 5 * 104
    • +
    • The number of nodes in each tree is in the range [1, 3].
    • +
    • No two roots of trees have the same value.
    • +
    • All the trees in the input are valid BSTs.
    • +
    • 1 <= TreeNode.val <= 5 * 104.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md b/assets/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md new file mode 100644 index 00000000..fbb92bbe --- /dev/null +++ b/assets/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md @@ -0,0 +1,76 @@ +# [1933. Check if String Is Decomposable Into Value-Equal Substrings](https://leetcode.com/problems/check-if-string-is-decomposable-into-value-equal-substrings) + + + +## Description + +

    A value-equal string is a string where all characters are the same.

    + +
      +
    • For example, "1111" and "33" are value-equal strings.
    • +
    • In contrast, "123" is not a value-equal string.
    • +
    + +

    Given a digit string s, decompose the string into some number of consecutive value-equal substrings where exactly one substring has a length of 2 and the remaining substrings have a length of 3.

    + +

    Return true if you can decompose s according to the above rules. Otherwise, return false.

    + +

    A substring is a contiguous sequence of characters in a string.

    + +

     

    +

    Example 1:

    + +
    +Input: s = "000111000"
    +Output: false
    +Explanation: s cannot be decomposed according to the rules because ["000", "111", "000"] does not have a substring of length 2.
    +
    + +

    Example 2:

    + +
    +Input: s = "00011111222"
    +Output: true
    +Explanation: s can be decomposed into ["000", "111", "11", "222"].
    +
    + +

    Example 3:

    + +
    +Input: s = "011100022233"
    +Output: false
    +Explanation: s cannot be decomposed according to the rules because of the first '0'.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s consists of only digits '0' through '9'.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1934.Confirmation Rate/README_EN.md b/assets/1900-1999/1934.Confirmation Rate/README_EN.md new file mode 100644 index 00000000..46f19161 --- /dev/null +++ b/assets/1900-1999/1934.Confirmation Rate/README_EN.md @@ -0,0 +1,100 @@ +# [1934. Confirmation Rate](https://leetcode.com/problems/confirmation-rate) + + + +## Description + +

    Table: Signups

    + +
    ++----------------+----------+
    +| Column Name    | Type     |
    ++----------------+----------+
    +| user_id        | int      |
    +| time_stamp     | datetime |
    ++----------------+----------+
    +user_id is the primary key for this table.
    +Each row contains information about the signup time for the user with ID user_id.
    +
    + +

     

    + +

    Table: Confirmations

    + +
    ++----------------+----------+
    +| Column Name    | Type     |
    ++----------------+----------+
    +| user_id        | int      |
    +| time_stamp     | datetime |
    +| action         | ENUM     |
    ++----------------+----------+
    +(user_id, time_stamp) is the primary key for this table.
    +user_id is a foreign key with a reference to the Signups table.
    +action is an ENUM of the type ('confirmed', 'timeout')
    +Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout').
    + +

     

    + +

    The confirmation rate of a user is the number of 'confirmed' messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is 0.

    + +

    Write an SQL query to find the confirmation rate of each user.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Signups table:
    ++---------+---------------------+
    +| user_id | time_stamp          |
    ++---------+---------------------+
    +| 3       | 2020-03-21 10:16:13 |
    +| 7       | 2020-01-04 13:57:59 |
    +| 2       | 2020-07-29 23:09:44 |
    +| 6       | 2020-12-09 10:39:37 |
    ++---------+---------------------+
    +
    +Confirmations table:
    ++---------+---------------------+-----------+
    +| user_id | time_stamp          | action    |
    ++---------+---------------------+-----------+
    +| 3       | 2021-01-06 03:30:46 | timeout   |
    +| 3       | 2021-07-14 14:00:00 | timeout   |
    +| 7       | 2021-06-12 11:57:29 | confirmed |
    +| 7       | 2021-06-13 12:58:28 | confirmed |
    +| 7       | 2021-06-14 13:59:27 | confirmed |
    +| 2       | 2021-01-22 00:00:00 | confirmed |
    +| 2       | 2021-02-28 23:59:59 | timeout   |
    ++---------+---------------------+-----------+
    +
    +Result table
    ++---------+-------------------+
    +| user_id | confirmation_rate |
    ++---------+-------------------+
    +| 6       | 0.00              |
    +| 3       | 0.00              |
    +| 7       | 1.00              |
    +| 2       | 0.50              |
    ++---------+-------------------+
    +
    +User 6 did not request any confirmation messages. The confirmation rate is 0.
    +User 3 made 2 requests and both timed out. The confirmation rate is 0.
    +User 7 made 3 requests and all were confirmed. The confirmation rate is 1.
    +User 2 made 2 requests where one was confirmed and the other timed out. The confirmation rate is 1 / 2 = 0.5.
    +
    + + +## Solutions + + + +### **SQL** + +```sql + +``` + + diff --git a/assets/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md b/assets/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md new file mode 100644 index 00000000..ed292d2c --- /dev/null +++ b/assets/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md @@ -0,0 +1,70 @@ +# [1935. Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type) + + + +## Description + +

    There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.

    + +

    Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.

    + +

     

    +

    Example 1:

    + +
    +Input: text = "hello world", brokenLetters = "ad"
    +Output: 1
    +Explanation: We cannot type "world" because the 'd' key is broken.
    +
    + +

    Example 2:

    + +
    +Input: text = "leet code", brokenLetters = "lt"
    +Output: 1
    +Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.
    +
    + +

    Example 3:

    + +
    +Input: text = "leet code", brokenLetters = "e"
    +Output: 0
    +Explanation: We cannot type either word because the 'e' key is broken.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= text.length <= 104
    • +
    • 0 <= brokenLetters.length <= 26
    • +
    • text consists of words separated by a single space without any leading or trailing spaces.
    • +
    • Each word only consists of lowercase English letters.
    • +
    • brokenLetters consists of distinct lowercase English letters.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md b/assets/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md new file mode 100644 index 00000000..9c7963f5 --- /dev/null +++ b/assets/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md @@ -0,0 +1,87 @@ +# [1936. Add Minimum Number of Rungs](https://leetcode.com/problems/add-minimum-number-of-rungs) + + + +## Description + +

    You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.

    + +

    You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.

    + +

    Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.

    + +

     

    +

    Example 1:

    + +
    +Input: rungs = [1,3,5,10], dist = 2
    +Output: 2
    +Explanation:
    +You currently cannot reach the last rung.
    +Add rungs at heights 7 and 8 to climb this ladder. 
    +The ladder will now have rungs at [1,3,5,7,8,10].
    +
    + +

    Example 2:

    + +
    +Input: rungs = [3,6,8,10], dist = 3
    +Output: 0
    +Explanation:
    +This ladder can be climbed without adding additional rungs.
    +
    + +

    Example 3:

    + +
    +Input: rungs = [3,4,6,7], dist = 2
    +Output: 1
    +Explanation:
    +You currently cannot reach the first rung from the ground.
    +Add a rung at height 1 to climb this ladder.
    +The ladder will now have rungs at [1,3,4,6,7].
    +
    + +

    Example 4:

    + +
    +Input: rungs = [5], dist = 10
    +Output: 0
    +Explanation:
    +This ladder can be climbed without adding additional rungs.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= rungs.length <= 105
    • +
    • 1 <= rungs[i] <= 109
    • +
    • 1 <= dist <= 109
    • +
    • rungs is strictly increasing.
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md b/assets/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md new file mode 100644 index 00000000..72c46e10 --- /dev/null +++ b/assets/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md @@ -0,0 +1,81 @@ +# [1937. Maximum Number of Points with Cost](https://leetcode.com/problems/maximum-number-of-points-with-cost) + + + +## Description + +

    You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.

    + +

    To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.

    + +

    However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.

    + +

    Return the maximum number of points you can achieve.

    + +

    abs(x) is defined as:

    + +
      +
    • x for x >= 0.
    • +
    • -x for x < 0.
    • +
    + +

     

    +

    Example 1:

    + +
    +Input: points = [[1,2,3],[1,5,1],[3,1,1]]
    +Output: 9
    +Explanation:
    +The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
    +You add 3 + 5 + 3 = 11 to your score.
    +However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
    +Your final score is 11 - 2 = 9.
    +
    + +

    Example 2:

    + +
    +Input: points = [[1,5],[2,3],[4,2]]
    +Output: 11
    +Explanation:
    +The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
    +You add 5 + 3 + 4 = 12 to your score.
    +However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
    +Your final score is 12 - 1 = 11.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == points.length
    • +
    • n == points[r].length
    • +
    • 1 <= m, n <= 105
    • +
    • 1 <= m * n <= 105
    • +
    • 0 <= points[r][c] <= 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1937.Maximum Number of Points with Cost/images/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png b/assets/1900-1999/1937.Maximum Number of Points with Cost/images/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png new file mode 100644 index 00000000..9c39bb60 Binary files /dev/null and b/assets/1900-1999/1937.Maximum Number of Points with Cost/images/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png differ diff --git a/assets/1900-1999/1937.Maximum Number of Points with Cost/images/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png b/assets/1900-1999/1937.Maximum Number of Points with Cost/images/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png new file mode 100644 index 00000000..3c4cae3b Binary files /dev/null and b/assets/1900-1999/1937.Maximum Number of Points with Cost/images/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png differ diff --git a/assets/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md b/assets/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md new file mode 100644 index 00000000..d567516b --- /dev/null +++ b/assets/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md @@ -0,0 +1,71 @@ +# [1938. Maximum Genetic Difference Query](https://leetcode.com/problems/maximum-genetic-difference-query) + + + +## Description + +

    There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.

    + +

    You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.

    + +

    Return an array ans where ans[i] is the answer to the ith query.

    + +

     

    +

    Example 1:

    + +
    +Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]
    +Output: [2,3,7]
    +Explanation: The queries are processed as follows:
    +- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.
    +- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.
    +- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
    +
    + +

    Example 2:

    + +
    +Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]
    +Output: [6,14,7]
    +Explanation: The queries are processed as follows:
    +- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.
    +- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.
    +- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 2 <= parents.length <= 105
    • +
    • 0 <= parents[i] <= parents.length - 1 for every node i that is not the root.
    • +
    • parents[root] == -1
    • +
    • 1 <= queries.length <= 3 * 104
    • +
    • 0 <= nodei <= parents.length - 1
    • +
    • 0 <= vali <= 2 * 105
    • +
    + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **...** + +``` + +``` + + diff --git a/assets/1900-1999/1938.Maximum Genetic Difference Query/images/c1.png b/assets/1900-1999/1938.Maximum Genetic Difference Query/images/c1.png new file mode 100644 index 00000000..f251b533 Binary files /dev/null and b/assets/1900-1999/1938.Maximum Genetic Difference Query/images/c1.png differ diff --git a/assets/1900-1999/1938.Maximum Genetic Difference Query/images/c2.png b/assets/1900-1999/1938.Maximum Genetic Difference Query/images/c2.png new file mode 100644 index 00000000..5779888e Binary files /dev/null and b/assets/1900-1999/1938.Maximum Genetic Difference Query/images/c2.png differ diff --git a/assets/images/leetcode-ac-qrcode.jpg b/assets/images/leetcode-ac-qrcode.jpg new file mode 100644 index 00000000..a58a9bc9 Binary files /dev/null and b/assets/images/leetcode-ac-qrcode.jpg differ diff --git a/assets/images/leetcode-code-quick-find.gif b/assets/images/leetcode-code-quick-find.gif new file mode 100644 index 00000000..35ede067 Binary files /dev/null and b/assets/images/leetcode-code-quick-find.gif differ diff --git a/cpp-cc189_lcci/.vscode/c_cpp_properties.json b/cpp-cc189_lcci/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..7576cd08 --- /dev/null +++ b/cpp-cc189_lcci/.vscode/c_cpp_properties.json @@ -0,0 +1,21 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.19041.0", + "compilerPath": "C:/Program Files/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/g++.exe", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "gcc-x86" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/cpp-cc189_lcci/.vscode/launch.json b/cpp-cc189_lcci/.vscode/launch.json new file mode 100644 index 00000000..2af67dc7 --- /dev/null +++ b/cpp-cc189_lcci/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + "version": "0.2.0", + "configurations": [ + { + "name": "g++.exe - Build and debug active file", + "type": "cppdbg", + "request": "launch", + "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { // Display content in STL containers pretty + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ], + // VS Code debug的日志信息,能清楚gdb加载和运行的各种过程 + "logging": { + "moduleLoad": false, + "trace": true, + "engineLogging": true, + "exceptions": true + }, + "preLaunchTask": "C/C++: g++.exe build active file" + } + ] +} \ No newline at end of file diff --git a/cpp-cc189_lcci/.vscode/settings.json b/cpp-cc189_lcci/.vscode/settings.json new file mode 100644 index 00000000..2b64035b --- /dev/null +++ b/cpp-cc189_lcci/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "files.associations": { + "deque": "cpp", + "string": "cpp", + "vector": "cpp", + "iostream": "cpp" + } +} \ No newline at end of file diff --git a/cpp-cc189_lcci/.vscode/tasks.json b/cpp-cc189_lcci/.vscode/tasks.json new file mode 100644 index 00000000..1ad2a5fb --- /dev/null +++ b/cpp-cc189_lcci/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + //"type": "shell", + "label": "C/C++: g++.exe build active file", + "command": "g++", + "args": [ + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} \ No newline at end of file diff --git a/cpp-cc189_lcci/lcci01.03-string-to-url-lcci.cpp b/cpp-cc189_lcci/lcci01.03-string-to-url-lcci.cpp new file mode 100644 index 00000000..d592b0b9 --- /dev/null +++ b/cpp-cc189_lcci/lcci01.03-string-to-url-lcci.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string replaceSpaces(string S, int length) { + if(length > S.size()) return ""; + S = S.substr(0, length); + + string res; + for(int i=0; i < length; i++) + { + if(S[i] != ' ') + res.push_back(S[i]); + else { + res.append("%20"); + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "Mr John Smith "; + int k = 13; + auto res = sol.replaceSpaces(str, k); + + cout << res << endl; + + return 0; +} diff --git a/cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution1.cpp b/cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution1.cpp new file mode 100644 index 00000000..c0401bf2 --- /dev/null +++ b/cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution1.cpp @@ -0,0 +1,80 @@ +#include + +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode +{ + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution +{ +public: + ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) + { + ListNode *fakeHead = new ListNode(-1); //定义输出链表 + ListNode *p = fakeHead; + + int carry = 0; //进位数字 + int x = 0; //记录l1链表的值 + int y = 0; //记录12链表的值 + + //遍历两个链表 + while (l1 != NULL || l2 != NULL) + { + x = l1 == NULL ? 0 : l1->val; + y = l2 == NULL ? 0 : l2->val; + + int sum = x + y + carry; + if (sum < 10) + { + p->next = new ListNode(sum); + carry = 0; + } + else + { + p->next = new ListNode(sum % 10); + carry = sum / 10; + } + + if (l1 != NULL) + l1 = l1->next; + if (l2 != NULL) + l2 = l2->next; + p = p->next; + } + if (carry != 0) + p->next = new ListNode(carry); + return fakeHead->next; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + ListNode *l2; + + l1 = new ListNode(7); + l1->next = new ListNode(1); + l1->next->next = new ListNode(6); + + l2 = new ListNode(5); + l2->next = new ListNode(9); + l2->next->next = new ListNode(2); + + ListNode *resHead = sol.addTwoNumbers(l1, l2); + + while (resHead != NULL) + { + cout << resHead->val << endl; + resHead = resHead -> next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution2.cpp b/cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution2.cpp new file mode 100644 index 00000000..b7291ffc --- /dev/null +++ b/cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution2.cpp @@ -0,0 +1,63 @@ +#include + +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode +{ + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* fakeNode = new ListNode(-1); + ListNode* p = fakeNode; + + int carrry = 0; + while(l1 || l2) + { + int val1 = (l1 != NULL) ? l1 -> val : 0; + int val2 = (l2 != NULL) ? l2 -> val : 0; + int sum = val1 + val2 + carrry; + carrry = sum / 10; // 拿掉这个sum(二位数)的末尾数字, 得到当前位的进位值 + p -> next = new ListNode(sum % 10); + p = p -> next; + if(l1) l1 = l1 -> next; + if(l2) l2 = l2 -> next; + } + if (carrry == 1) + p -> next = new ListNode(1); + + return fakeNode -> next; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + ListNode *l2; + + l1 = new ListNode(7); + l1->next = new ListNode(1); + l1->next->next = new ListNode(6); + + l2 = new ListNode(5); + l2->next = new ListNode(9); + l2->next->next = new ListNode(2); + + ListNode *resHead = sol.addTwoNumbers(l1, l2); + + while (resHead != NULL) + { + cout << resHead->val << endl; + resHead = resHead -> next; + } + + return 0; +} \ No newline at end of file diff --git "a/cpp-cc189_lcci/\351\235\242\350\257\225\351\242\230 02.05. \351\223\276\350\241\250\346\261\202\345\222\214-solution1.cpp" "b/cpp-cc189_lcci/\351\235\242\350\257\225\351\242\230 02.05. \351\223\276\350\241\250\346\261\202\345\222\214-solution1.cpp" new file mode 100644 index 00000000..0b2cc9b2 --- /dev/null +++ "b/cpp-cc189_lcci/\351\235\242\350\257\225\351\242\230 02.05. \351\223\276\350\241\250\346\261\202\345\222\214-solution1.cpp" @@ -0,0 +1,63 @@ +#include + +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* fakeHead = new ListNode(-1); //定义输出链表 + ListNode* p = fakeHead; + + int carry = 0; //进位数字 + int x = 0; //记录l1链表的值 + int y = 0; //记录12链表的值 + + //遍历两个链表 + while(l1 != NULL || l2 != NULL) { + x = l1 == NULL ? 0 : l1->val; + y = l2 == NULL ? 0 : l2->val; + + int sum = x + y + carry; + if(sum < 10) { + p->next = new ListNode(sum); + carry = 0; + }else { + p->next = new ListNode(sum % 10); + carry = sum / 10; + } + + if(l1 != NULL) l1 = l1->next; + if(l2 != NULL) l2 = l2->next; + p = p->next; + } + if (carry != 0) p->next = new ListNode(carry); + return fakeHead->next; + } +}; + +int main() +{ + Solution sol; + ListNode *l1; + ListNode *l2; + l1 = new ListNode(7); + l1->next=new ListNode(1); + l1->next->next=new ListNode(6); + + l2 = new ListNode(5); + l2->next=new ListNode(9); + l2->next->next=new ListNode(2); + + auto res = sol.addTwoNumbers(l1, l2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git "a/cpp-cc189_lcci/\351\235\242\350\257\225\351\242\23001.03.URL\345\214\226-string-to-url-lcci.cpp" "b/cpp-cc189_lcci/\351\235\242\350\257\225\351\242\23001.03.URL\345\214\226-string-to-url-lcci.cpp" new file mode 100644 index 00000000..d592b0b9 --- /dev/null +++ "b/cpp-cc189_lcci/\351\235\242\350\257\225\351\242\23001.03.URL\345\214\226-string-to-url-lcci.cpp" @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string replaceSpaces(string S, int length) { + if(length > S.size()) return ""; + S = S.substr(0, length); + + string res; + for(int i=0; i < length; i++) + { + if(S[i] != ' ') + res.push_back(S[i]); + else { + res.append("%20"); + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "Mr John Smith "; + int k = 13; + auto res = sol.replaceSpaces(str, k); + + cout << res << endl; + + return 0; +} diff --git a/cpp-lcof/.vscode/c_cpp_properties.json b/cpp-lcof/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..7576cd08 --- /dev/null +++ b/cpp-lcof/.vscode/c_cpp_properties.json @@ -0,0 +1,21 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.19041.0", + "compilerPath": "C:/Program Files/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/g++.exe", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "gcc-x86" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/cpp-lcof/.vscode/launch.json b/cpp-lcof/.vscode/launch.json new file mode 100644 index 00000000..2af67dc7 --- /dev/null +++ b/cpp-lcof/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + "version": "0.2.0", + "configurations": [ + { + "name": "g++.exe - Build and debug active file", + "type": "cppdbg", + "request": "launch", + "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { // Display content in STL containers pretty + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ], + // VS Code debug的日志信息,能清楚gdb加载和运行的各种过程 + "logging": { + "moduleLoad": false, + "trace": true, + "engineLogging": true, + "exceptions": true + }, + "preLaunchTask": "C/C++: g++.exe build active file" + } + ] +} \ No newline at end of file diff --git a/cpp-lcof/.vscode/settings.json b/cpp-lcof/.vscode/settings.json new file mode 100644 index 00000000..4a8bdbe9 --- /dev/null +++ b/cpp-lcof/.vscode/settings.json @@ -0,0 +1,10 @@ +{ + "files.associations": { + "*.vue": "vue", + "deque": "cpp", + "string": "cpp", + "vector": "cpp", + "new": "cpp", + "unordered_map": "cpp" + } +} \ No newline at end of file diff --git a/cpp-lcof/.vscode/tasks.json b/cpp-lcof/.vscode/tasks.json new file mode 100644 index 00000000..1ad2a5fb --- /dev/null +++ b/cpp-lcof/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + //"type": "shell", + "label": "C/C++: g++.exe build active file", + "command": "g++", + "args": [ + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} \ No newline at end of file diff --git a/cpp-lcof/lcof03-offer-shu-zu-zhong-zhong-fu-de-shu-zi-lcof.cpp b/cpp-lcof/lcof03-offer-shu-zu-zhong-zhong-fu-de-shu-zi-lcof.cpp new file mode 100644 index 00000000..46a6e42c --- /dev/null +++ b/cpp-lcof/lcof03-offer-shu-zu-zhong-zhong-fu-de-shu-zi-lcof.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findRepeatNumber(vector& nums) { + unordered_map map; + + for(int i=0; i < nums.size(); i++) + { + map[nums[i]]++; + if (map[nums[i]] == 2) + return nums[i]; + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 3, 1, 0, 2, 5, 3}; + int res = sol.findRepeatNumber(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/.vscode/c_cpp_properties.json b/cpp-leetcode/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..7576cd08 --- /dev/null +++ b/cpp-leetcode/.vscode/c_cpp_properties.json @@ -0,0 +1,21 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.19041.0", + "compilerPath": "C:/Program Files/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/g++.exe", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "gcc-x86" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/cpp-leetcode/.vscode/launch.json b/cpp-leetcode/.vscode/launch.json new file mode 100644 index 00000000..2af67dc7 --- /dev/null +++ b/cpp-leetcode/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + "version": "0.2.0", + "configurations": [ + { + "name": "g++.exe - Build and debug active file", + "type": "cppdbg", + "request": "launch", + "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { // Display content in STL containers pretty + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ], + // VS Code debug的日志信息,能清楚gdb加载和运行的各种过程 + "logging": { + "moduleLoad": false, + "trace": true, + "engineLogging": true, + "exceptions": true + }, + "preLaunchTask": "C/C++: g++.exe build active file" + } + ] +} \ No newline at end of file diff --git a/cpp-leetcode/.vscode/settings.json b/cpp-leetcode/.vscode/settings.json new file mode 100644 index 00000000..9a91c8a3 --- /dev/null +++ b/cpp-leetcode/.vscode/settings.json @@ -0,0 +1,77 @@ +{ + "files.associations": { + "*.vue": "vue", + "deque": "cpp", + "string": "cpp", + "vector": "cpp", + "algorithm": "cpp", + "unordered_set": "cpp", + "queue": "cpp", + "iterator": "cpp", + "iostream": "cpp", + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "charconv": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "codecvt": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "csetjmp": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cuchar": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "forward_list": "cpp", + "list": "cpp", + "unordered_map": "cpp", + "exception": "cpp", + "functional": "cpp", + "map": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "ratio": "cpp", + "regex": "cpp", + "set": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "fstream": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "mutex": "cpp", + "new": "cpp", + "ostream": "cpp", + "scoped_allocator": "cpp", + "shared_mutex": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "thread": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "valarray": "cpp" + } +} \ No newline at end of file diff --git a/cpp-leetcode/.vscode/tasks.json b/cpp-leetcode/.vscode/tasks.json new file mode 100644 index 00000000..1ad2a5fb --- /dev/null +++ b/cpp-leetcode/.vscode/tasks.json @@ -0,0 +1,26 @@ +{ + "version": "2.0.0", + "tasks": [ + { + //"type": "shell", + "label": "C/C++: g++.exe build active file", + "command": "g++", + "args": [ + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} \ No newline at end of file diff --git a/cpp-leetcode/README.md b/cpp-leetcode/README.md new file mode 100644 index 00000000..31229169 --- /dev/null +++ b/cpp-leetcode/README.md @@ -0,0 +1,3 @@ +# Leetcode 刷题方法及AC 代码 - C++版 + +mingw32 的安装目录为: `C:\Program Files\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0`. diff --git a/cpp-leetcode/lcci17.17-multi-search-lcci_trie.cpp b/cpp-leetcode/lcci17.17-multi-search-lcci_trie.cpp new file mode 100644 index 00000000..7dfee150 --- /dev/null +++ b/cpp-leetcode/lcci17.17-multi-search-lcci_trie.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +private: + struct Node { + int idx; + vector children; + Node() : idx(-1), children(26, nullptr) {} + }; + struct Trie { + Node* root; + Trie() : root(new Node()) {} + void insert(string& word, int idx) + { + Node* p = root; + for (char& c : word) { + c -= 'a'; + if (p->children[c] == nullptr) + { + p->children[c] = new Node(); + } + p = p->children[c]; + } + p->idx = idx; + } + }; +public: + vector> multiSearch(string big, vector& smalls) { + unordered_map> cache; + const int n = big.size(); + const int m = smalls.size(); + vector> res(m); + + Trie trie = Trie(); + // 构造前缀树 + for (int i = 0; i < m; i++) + { + trie.insert(smalls[i], i); + } + for (int i = 0; i < n; i++) + { + int j = i; + Node* node = trie.root; + while (j < n && node->children[big[j] - 'a']) + { + node = node->children[big[j] - 'a']; + if (node->idx != -1) + { + res[node->idx].push_back(i); + } + j++; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string big = "mississippi"; + vector smalls = {"is", "ppi", "hi", "sis", "i", "ssippi"}; + auto res = sol.multiSearch(big, smalls); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode-playground-built-in-functions.cpp b/cpp-leetcode/leetcode-playground-built-in-functions.cpp new file mode 100644 index 00000000..6db8be5b --- /dev/null +++ b/cpp-leetcode/leetcode-playground-built-in-functions.cpp @@ -0,0 +1,326 @@ +#include +#include +#include +#include +#include +#include /* 含有stringstream类 */ +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +void trimLeftTrailingSpaces(string &input) +{ + input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) + { return !isspace(ch); })); +} + +void trimRightTrailingSpaces(string &input) +{ + input.erase(find_if(input.rbegin(), input.rend(), [](int ch) + { return !isspace(ch); }) + .base(), + input.end()); +} + +vector stringToIntegerVector(string input) +{ + vector output; + trimLeftTrailingSpaces(input); + trimRightTrailingSpaces(input); + input = input.substr(1, input.length() - 2); + stringstream ss; + ss.str(input); + string item; + char delim = ','; + while (getline(ss, item, delim)) + { + output.push_back(stoi(item)); + } + return output; +} + +int stringToInteger(string input) +{ + return stoi(input); +} + +ListNode *stringToListNode(string input) +{ + // Generate list from the input + vector list = stringToIntegerVector(input); + + // Now convert that list into linked list + ListNode *dummyRoot = new ListNode(0); + ListNode *ptr = dummyRoot; + for (int item : list) + { + ptr->next = new ListNode(item); + ptr = ptr->next; + } + ptr = dummyRoot->next; + delete dummyRoot; + return ptr; +} + +string integerVectorToString(vector list, int length = -1) +{ + if (length == -1) + { + length = list.size(); + } + + if (length == 0) + { + return "[]"; + } + + string result; + for (int index = 0; index < length; index++) + { + int number = list[index]; + result += to_string(number) + ", "; + } + return "[" + result.substr(0, result.length() - 2) + "]"; +} +string listNodeToString(ListNode *node) +{ + if (node == nullptr) + { + return "[]"; + } + + string result; + while (node) + { + result += to_string(node->val) + ", "; + node = node->next; + } + return "[" + result.substr(0, result.length() - 2) + "]"; +} +string boolToString(bool input) +{ + return input ? "True" : "False"; +} +bool stringToBool(string input) +{ + transform(input.begin(), input.end(), input.begin(), ::tolower); + return input == "true"; +} + +string treeNodeToString(TreeNode *root) +{ + if (root == nullptr) + { + return "[]"; + } + + string output = ""; + queue q; + q.push(root); + while (!q.empty()) + { + TreeNode *node = q.front(); + q.pop(); + + if (node == nullptr) + { + output += "null, "; + continue; + } + + output += to_string(node->val) + ", "; + q.push(node->left); + q.push(node->right); + } + return "[" + output.substr(0, output.length() - 2) + "]"; +} + +TreeNode *stringToTreeNode(string input) +{ + trimLeftTrailingSpaces(input); + trimRightTrailingSpaces(input); + input = input.substr(1, input.length() - 2); + if (!input.size()) + { + return nullptr; + } + + string item; + stringstream ss; + ss.str(input); + + getline(ss, item, ','); + TreeNode *root = new TreeNode(stoi(item)); + queue nodeQueue; + nodeQueue.push(root); + + while (true) + { + TreeNode *node = nodeQueue.front(); + nodeQueue.pop(); + + if (!getline(ss, item, ',')) + { + break; + } + + trimLeftTrailingSpaces(item); + if (item != "null") + { + int leftNumber = stoi(item); + node->left = new TreeNode(leftNumber); + nodeQueue.push(node->left); + } + + if (!getline(ss, item, ',')) + { + break; + } + + trimLeftTrailingSpaces(item); + if (item != "null") + { + int rightNumber = stoi(item); + node->right = new TreeNode(rightNumber); + nodeQueue.push(node->right); + } + } + return root; +} + +string stringToString(string input) +{ + assert(input.length() >= 2); + string result; + for (int i = 1; i < input.length() - 1; i++) + { + char currentChar = input[i]; + if (input[i] == '\\') + { + char nextChar = input[i + 1]; + switch (nextChar) + { + case '\"': + result.push_back('\"'); + break; + case '/': + result.push_back('/'); + break; + case '\\': + result.push_back('\\'); + break; + case 'b': + result.push_back('\b'); + break; + case 'f': + result.push_back('\f'); + break; + case 'r': + result.push_back('\r'); + break; + case 'n': + result.push_back('\n'); + break; + case 't': + result.push_back('\t'); + break; + default: + break; + } + i++; + } + else + { + result.push_back(currentChar); + } + } + return result; +} + +void prettyPrintTree(TreeNode *node, string prefix = "", bool isLeft = true) +{ + if (node == nullptr) + { + cout << "Empty tree"; + return; + } + + if (node->right) + { + prettyPrintTree(node->right, prefix + (isLeft ? "│ " : " "), false); + } + + cout << prefix + (isLeft ? "└── " : "┌── ") + to_string(node->val) + "\n"; + + if (node->left) + { + prettyPrintTree(node->left, prefix + (isLeft ? " " : "│ "), true); + } +} + +void prettyPrintLinkedList(ListNode *node) +{ + while (node && node->next) + { + cout << node->val << "->"; + node = node->next; + } + + if (node) + { + cout << node->val << endl; + } + else + { + cout << "Empty LinkedList" << endl; + } +} + +class Solution { +public: + int longestConsecutive(vector &nums) + { + + return 0; + } +}; + +// Test +int main() +{ + string line; + while (getline(cin, line)) + { + vector nums = stringToIntegerVector(line); + + int ret = Solution().longestConsecutive(nums); + + string out = to_string(ret); + cout << out << endl; + } + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1-two-sum_method1_two_pointers.cpp b/cpp-leetcode/leetcode1-two-sum_method1_two_pointers.cpp new file mode 100644 index 00000000..1910abd6 --- /dev/null +++ b/cpp-leetcode/leetcode1-two-sum_method1_two_pointers.cpp @@ -0,0 +1,35 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector twoSum(vector& nums, int target) { + vector res(2); + // 双指针, 先固定一个 + for (int i = 0; i < nums.size(); i++) + { + for (int j = i + 1; j < nums.size(); j++) + { + if (nums[i] + nums[j] == target) + { + res[0] = i; + res[1] = j; + return res; + } + } + } + return res; + } +}; + +// 下面是测试 +int main() +{ + Solution sol; + vector arr = {3, 2, 4}; + vector res = sol.twoSum(arr, 7); + for (int i : res) + printf("%d ", i); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1-two-sum_method2_hashmap.cpp b/cpp-leetcode/leetcode1-two-sum_method2_hashmap.cpp new file mode 100644 index 00000000..ef876c0f --- /dev/null +++ b/cpp-leetcode/leetcode1-two-sum_method2_hashmap.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector twoSum(vector &nums, int target) { + unordered_map dict; + vector result; + for (int i = 0; i < nums.size(); i++) + { + dict[nums[i]] = i; // 顺序的map映射: value->index + } + for (int i = 0; i < nums.size(); i++) + { + int query = target - nums[i]; + if (dict.find(query) != dict.end() && dict[query] > i) // dict[query] > i是为了防止重复计算 + { + result.push_back(i); + result.push_back(dict[query]); + break; + } + } + return result; + } +}; +// 下面是测试 +int main() +{ + Solution sol; + vector arr1 = {3, 2, 2, 2, 2, 2, 4}; + vector arr2 = {3, 2, 4}; + vector res1= sol.twoSum(arr1, 6); + vector res2= sol.twoSum(arr2, 6); + for (int i : res1) + printf("%d ", i); + printf("\n"); + for (int i : res2) + printf("%d ", i); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1-two-sum_method3_hashmap2.cpp b/cpp-leetcode/leetcode1-two-sum_method3_hashmap2.cpp new file mode 100644 index 00000000..32f3f714 --- /dev/null +++ b/cpp-leetcode/leetcode1-two-sum_method3_hashmap2.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector twoSum(vector &nums, int target) + { + unordered_map dict; + vector res(2,-1); + for (int i = 0; i < nums.size(); i++) + { + int query = target - nums[i]; + if (dict.find(query) == dict.end()) + dict[nums[i]] = i; // map映射: value->index + else + { + res[1] = i; + res[0] = dict[query]; + return res; + } + } + return {}; + } +}; +// 下面是测试 +int main() +{ + Solution sol; + vector arr = {3, 2, 4}; + vector res = sol.twoSum(arr, 7); + for (int i : res) + printf("%d ", i); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1-two-sum_method4.cpp b/cpp-leetcode/leetcode1-two-sum_method4.cpp new file mode 100644 index 00000000..5923e636 --- /dev/null +++ b/cpp-leetcode/leetcode1-two-sum_method4.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +using namespace std; + +typedef struct node +{ + int index; + int value; + node(){}; + node(int i, int v) : index(i), value(v) {} +} Node; + +bool compare(const Node& a, const Node& b){ + return a.value < b.value; +} + +class Solution { +public: + vector twoSum(vector &nums, int target) { + int len = nums.size(); + + vector ret(2, 0); // 初始化:ret包含2个值为0的元素 + vector nums2(len); + for (int i = 0; i < len; i++) + { + nums2[i] = Node(i + 1, nums[i]); + } + + sort(nums2.begin(), nums2.end(), compare); // 调用快排,T(n)=O(n*log(n)) + + int l = 0; + int r = len - 1; + while (l < r) + { + int sum = nums2[l].value + nums2[r].value; + if (sum == target) + { + ret[0] = min(nums2[l].index, nums2[r].index) - 1; // 注意,这里需要减去1 + ret[1] = max(nums2[l].index, nums2[r].index) - 1; + break; + } + else if (sum < target) + { + l++; + } + else + { + r--; + } + } + return ret; // 用两个指针来扫 + } +}; + +// 下面是测试代码 + +int main() +{ + Solution sol; + vector arr; + + arr.push_back(3); + arr.push_back(2); + arr.push_back(4); + + vector res = sol.twoSum(arr, 6); + cout << res[0] << " " << res[1] << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode10-regular-expression-matching_dp.cpp b/cpp-leetcode/leetcode10-regular-expression-matching_dp.cpp new file mode 100644 index 00000000..7efb9f25 --- /dev/null +++ b/cpp-leetcode/leetcode10-regular-expression-matching_dp.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isMatch(string s, string p) { + int n = s.size(); + int m = p.size(); + s = " " + s, p = " " + p; /* 为方便计算, 从第1个字符开始统计, 故需在开头补上空格 */ + vector> f(n + 1, vector(m + 1)); + f[0][0] = true; + for (int i = 0; i <= n; i++) + for (int j = 1; j <= m; j++) + { + if (j + 1 <= m && p[j + 1] == '*') + continue; /* 如果一个字母(比如a)的后一个字符是*, 那么a不能单独看待,应与*看成是一个整体,所以需要跳过 */ + if (i && p[j] != '*') + { + f[i][j] = f[i - 1][j - 1] && (s[i] == p[j] || p[j] == '.'); + } + else if (p[j] == '*') + { + /* 不需要判断 j >= 2, 英文如果有*出现, 那它之前必然至少还有1个字符 */ + f[i][j] = f[i][j - 2] || i && (f[i - 1][j] && (s[i] == p[j - 1] || p[j - 1] == '.')); + } + } + + return f[n][m]; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "aab", p = "c*a*b"; + auto res = sol.isMatch(s, p); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1002-find-common-characters_hashmap.cpp b/cpp-leetcode/leetcode1002-find-common-characters_hashmap.cpp new file mode 100644 index 00000000..c3cf991e --- /dev/null +++ b/cpp-leetcode/leetcode1002-find-common-characters_hashmap.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector commonChars(vector& words) { + vector res; + int minDict[26]; // 统计每个字母的最小count + fill(minDict, minDict + 26, INT_MAX); + for (int j = 0; j < words.size(); j++) // 将每一个单词进行哈希化, 然后分别算出每个字母的最小count + { + string curWord = words[j]; + vector curDict(26, 0); // 26个字母 + for (auto& ch : curWord) + curDict[ch - 'a']++; + for (int i = 0; i < 26; i++) + minDict[i] = min(minDict[i], curDict[i]); + } + for (int i = 0; i < 26; i++) + { + int curCount = minDict[i]; + if (curCount >= 1) + { + auto ch = i + 'a'; + string str; + str.push_back(ch); + for (int i = 0; i < curCount; i++) + res.push_back(str); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector words = {"cool", "lock", "cook"}; + auto res = sol.commonChars(words); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1003-check-if-word-is-valid-after-substitutions_stack.cpp b/cpp-leetcode/leetcode1003-check-if-word-is-valid-after-substitutions_stack.cpp new file mode 100644 index 00000000..5580fe4c --- /dev/null +++ b/cpp-leetcode/leetcode1003-check-if-word-is-valid-after-substitutions_stack.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isValid(string s) { + string stk; // 用string模拟栈 + for (auto& c: s) { + stk += c; + if (stk.size() >= 3 && stk.substr(stk.size() - 3) == "abc") + { + for (int i = 0; i < 3; i++) + stk.pop_back(); + } + } + return stk.empty(); + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abcabcababcc"; + auto res = sol.isValid(s); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1004-max-consecutive-ones-iii_sliding_window1.cpp b/cpp-leetcode/leetcode1004-max-consecutive-ones-iii_sliding_window1.cpp new file mode 100644 index 00000000..a77dec3c --- /dev/null +++ b/cpp-leetcode/leetcode1004-max-consecutive-ones-iii_sliding_window1.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int longestOnes(vector& nums, int k) { + const int N = nums.size(); + int i = 0; // i: 滑动窗口左边界, 固定右边界, 移动左边界 + int count = 0; // 已经使用了多少次反转次数 + int res = 0; // res: max len + for (int j = 0; j < N; j++) + { + if (nums[j] == 1) // 新加入窗口右侧的数是1, 不需要使用反转次数 + res = max(res, j - i + 1); + else { + count++; + while (count > k) // 此时使用的反转次数超了, 需要移动左边界, 直到窗口使用的反转次数减小回到k为止 + { + if (nums[i] == 0) + count--; + i++; + } + res = max(res, j - i + 1); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}; + int k = 2; + auto res = sol.longestOnes(nums, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1004-max-consecutive-ones-iii_sliding_window2.cpp b/cpp-leetcode/leetcode1004-max-consecutive-ones-iii_sliding_window2.cpp new file mode 100644 index 00000000..4972302f --- /dev/null +++ b/cpp-leetcode/leetcode1004-max-consecutive-ones-iii_sliding_window2.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int longestOnes(vector& nums, int k) { + const int N = nums.size(); + int left = 0; // left: 滑动窗口左边界, 固定右边界, 移动左边界 + int j = 0; // j: 滑动窗口右边界right + int preSum = 0; // 使用的反转次数 0 -> 1 + int res = 0; + for (int j = 0; j < N; j++) + { + preSum += (nums[j] == 0 ? 1 : 0); + if (preSum > k) // 一开始, 让反转次数达到k+1, 然后开始根据情况收缩左边界 + { + while (left < j && nums[left] == 1) /* 在左边界每遇到一个1, 就直接移动左边界, 如果遇到1个0, 翻转次数又新腾出了1, 需要先更新preSum的值 */ + left++; + + preSum -= 1; + left++; + } + res = max(res, j - left + 1); // 此时, 反转次数恰好恢复到k, 可以更新结果了 + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}; + int k = 2; + auto res = sol.longestOnes(nums, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1005-maximize-sum-of-array-after-k-negations_classification.cpp b/cpp-leetcode/leetcode1005-maximize-sum-of-array-after-k-negations_classification.cpp new file mode 100644 index 00000000..d3e60738 --- /dev/null +++ b/cpp-leetcode/leetcode1005-maximize-sum-of-array-after-k-negations_classification.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int largestSumAfterKNegations(vector& nums, int k) { + int m = 0; // 负数的个数 + for (auto& num : nums) + if (num < 0) m++; + auto sum = accumulate(nums.begin(), nums.end(), 0); + if (m == 0 && k % 2 == 0) + return sum; + else if (m == 0 && k % 2 == 1) + { + auto it = min_element(nums.begin(), nums.end()); + return sum - 2*(*it); + } + else if (m > 0 && m >= k) + { + sort(nums.begin(), nums.end()); + int sum1 = 0; + for (int i = 0; i < nums.size(); i++) + { + if (i <= k-1) /* 题意: k >= 1, k-1不会成负数 */ + sum1 += -nums[i]; + else sum1 += nums[i]; + } + return sum1; + } + else if (m > 0 && m < k) + { + if ((k - m) % 2 == 0) + { + int sum1 = 0; + for (int i = 0; i < nums.size(); i++) + { + if (nums[i] < 0) + sum1 += -nums[i]; + else sum1 += nums[i]; + } + return sum1; + } + else { + int sum1 = 0; + for (int i = 0; i < nums.size(); i++) + { + if (nums[i] < 0) + nums[i] = -nums[i]; + sum1 += nums[i]; + } + sort(nums.begin(), nums.end()); + auto it = min_element(nums.begin(), nums.end()); + return sum1 - 2*(*it); + } + } + return 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 6, 9, -3, 3}; + int k = 2; + auto res = sol.largestSumAfterKNegations(nums, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1009-complement-of-base-10-integer_bit_operation_mask.cpp b/cpp-leetcode/leetcode1009-complement-of-base-10-integer_bit_operation_mask.cpp new file mode 100644 index 00000000..6a6f49a8 --- /dev/null +++ b/cpp-leetcode/leetcode1009-complement-of-base-10-integer_bit_operation_mask.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int bitwiseComplement(int n) { + if (n == 0) return 1; + unsigned mask = INT_MAX; + // unsigned mask = ~0; /* 也能这样写 */ + + /* 由于存储 n 时, 有32个bit, 其高位有不少的0. 故此处按位取反时~n 的高位会产生很多不必要的1 */ + while (n & mask) mask <<= 1; /* 这里的目标是把mask末尾与结果相关的bit位清零, 循环结束时mask的形式是111...00 */ + return ~n & (~mask); + } +}; + +// Test +int main() +{ + Solution sol; + int num = 5; + auto res = sol.bitwiseComplement(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode102-binary-tree-level-order-traversal_deque.cpp b/cpp-leetcode/leetcode102-binary-tree-level-order-traversal_deque.cpp new file mode 100644 index 00000000..ae4a186b --- /dev/null +++ b/cpp-leetcode/leetcode102-binary-tree-level-order-traversal_deque.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> levelOrder(TreeNode* root) { + if (root == NULL) + return {}; + if (root->left == NULL && root->right == NULL) + return {{root->val}}; + + deque q { root }; + vector> res; + + while (!q.empty()) + { + vector curLevel; + for (int i = q.size(); i > 0; i--) + { + TreeNode* p = q.front(); // 取出队头的node, 后面就可以删掉它了. + q.pop_front(); /* 队列: 队尾进,队头出 */ + curLevel.push_back(p->val); + if (p->left != NULL) + q.push_back(p->left); + + if (p->right != NULL) + q.push_back(p->right); + } + res.push_back(curLevel); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector> res = sol.levelOrder(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode102-binary-tree-level-order-traversal_queue.cpp b/cpp-leetcode/leetcode102-binary-tree-level-order-traversal_queue.cpp new file mode 100644 index 00000000..5e9ceeee --- /dev/null +++ b/cpp-leetcode/leetcode102-binary-tree-level-order-traversal_queue.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> levelOrder(TreeNode* root) { + if (root == NULL) + return {}; + if (root->left == NULL && root->right == NULL) + return {{root->val}}; + + queue q; + q.push({root}); /* queue与deque相比少了一种初始化方式 */ + vector> res; + + while (!q.empty()) /* q.size()会依次变成每一层的结点个数, 在 0,1,2 之间变化 */ + { + vector curLevel; + for (int i = q.size(); i > 0; i--) + { + TreeNode* p = q.front(); // 取出队头的node, 后面就可以删掉它了. + q.pop(); /* 队列: 队尾进,队头出 */ + curLevel.push_back(p->val); + if (p->left != NULL) + q.push(p->left); + + if (p->right != NULL) + q.push(p->right); + } + res.push_back(curLevel); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector> res = sol.levelOrder(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1023-camelcase-matching_word_frequency.cpp b/cpp-leetcode/leetcode1023-camelcase-matching_word_frequency.cpp new file mode 100644 index 00000000..3315a158 --- /dev/null +++ b/cpp-leetcode/leetcode1023-camelcase-matching_word_frequency.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector camelMatch(vector& queries, string pattern) { + vector res; + vector patArr = getCamelArr(pattern); + for (auto& q : queries) + { + auto qArr = getCamelArr(q); + bool check = true; + if (patArr.size() != qArr.size()) + check = false; + else + { + for (int i = 0; i < patArr.size(); i++) + { + if (qArr[i][0] != patArr[i][0]) + { + check = false; + break; + } + + unordered_map dict1; // 小写字母的词频 + unordered_map dict2; + for (auto c : qArr[i]) + if (c >= 'a' && c <= 'z') + dict1[c]++; + for (auto c : patArr[i]) + if (c >= 'a' && c <= 'z') + dict2[c]++; + for (char c = 'a'; c <= 'z'; c++) + { + if (dict2[c] > dict1[c]) + { + check = false; + break; + } + } + } + } + res.push_back(check); + } + return res; + } + vector getCamelArr(string s) + { + vector wordList; + vector upCharIndexes; + for (int i = 0; i < s.size(); i++) + { + // 找到大写字母的index + if (s[i] >= 'A' && s[i] <= 'Z') + upCharIndexes.push_back(i); + } + for (int i = 1; i < upCharIndexes.size(); i++) + { + string str = s.substr(upCharIndexes[i-1], upCharIndexes[i] - upCharIndexes[i-1]); + wordList.push_back(str); + } + wordList.push_back(s.substr(upCharIndexes.back(), s.size() - upCharIndexes.back())); + return wordList; + } +}; + +// Test +int main() +{ + Solution sol; + // vector queries = {"uAxaqlzahfialcezsLfj", "cAqlzyahaslccezssLfj", "tAqlzahavslcezsLwzfj", "eAqlzbxahalcezelsLfj"}; + // string pattern = "AqlzahalcezsLfj"; + vector queries = {"FooBar","FootBall"}; + string pattern = "FoBa"; + auto res = sol.camelMatch(queries, pattern); + for (auto match : res) + { + cout << (match ? "True" : "False") << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode103-zigzag-traverse_deque.cpp b/cpp-leetcode/leetcode103-zigzag-traverse_deque.cpp new file mode 100644 index 00000000..a9c5aecc --- /dev/null +++ b/cpp-leetcode/leetcode103-zigzag-traverse_deque.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + if (!root) return {}; + if (root->left == nullptr && root->right == nullptr) return {{root->val}}; + + vector> res; + deque q {root}; + while (!q.empty()) + { + vector curLevel; + for (int i = q.size() ; i > 0; --i) + { + TreeNode* p = q.front(); + q.pop_front(); + curLevel.push_back(p->val); + if (p->left != nullptr) q.push_back(p->left); + if (p->right != nullptr) q.push_back(p->right); + } + res.push_back(curLevel); + } + + for (int i = 0; i < res.size(); i++) + { + vector curLevel = res[i]; + if (i % 2 == 1) + { + reverse(curLevel.begin(), curLevel.end()); + res[i] = curLevel; + } + } + + return res; + } +}; +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(9); + root->right = new TreeNode(20); + root->right->left = new TreeNode(15); + root->right->left->left = nullptr; + root->right->left->right = nullptr; + root->right->right = new TreeNode(7); + root->right->right->left = nullptr; + root->right->right->right = nullptr; + + vector> res = sol.zigzagLevelOrder(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode103-zigzag-traverse_queue.cpp b/cpp-leetcode/leetcode103-zigzag-traverse_queue.cpp new file mode 100644 index 00000000..99b4cbaf --- /dev/null +++ b/cpp-leetcode/leetcode103-zigzag-traverse_queue.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + if (!root) return {}; + if (root->left == nullptr && root->right == nullptr) return {{root->val}}; + + vector> res; + queue q; + q.push(root); + while (!q.empty()) + { + vector curLevel; + for (int i = q.size() ; i > 0; --i) + { + TreeNode* p = q.front(); + q.pop(); + curLevel.push_back(p->val); + if (p->left != nullptr) q.push(p->left); /* 不能写出 !p->left 或 !(p->left) */ + if (p->right != nullptr) q.push(p->right); + } + res.push_back(curLevel); + } + + for (int i = 0; i < res.size(); i++) + { + vector curLevel = res[i]; + if (i % 2 == 1) + { + reverse(curLevel.begin(), curLevel.end()); + res[i] = curLevel; + } + } + + return res; + } +}; +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(9); + root->right = new TreeNode(20); + root->right->left = new TreeNode(15); + root->right->left->left = nullptr; + root->right->left->right = nullptr; + root->right->right = new TreeNode(7); + root->right->right->left = nullptr; + root->right->right->right = nullptr; + + vector> res = sol.zigzagLevelOrder(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1047-remove-all-adjacent-duplicates-in-string_direct_method(TLE).cpp b/cpp-leetcode/leetcode1047-remove-all-adjacent-duplicates-in-string_direct_method(TLE).cpp new file mode 100644 index 00000000..ccfde515 --- /dev/null +++ b/cpp-leetcode/leetcode1047-remove-all-adjacent-duplicates-in-string_direct_method(TLE).cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string removeDuplicates(string s) { + string s1 = s; + while (hasDup(s1)) + { + removeRepeatsOnce(s1); + } + return s1; + } + void removeRepeatsOnce(string& s) + { + string str = s; + for (int i = 0; i < str.size(); i++) + { + if (str[i] == str[i + 1]) + { + str.erase(i, 2); + } + } + + s = str; + } + bool hasDup(string s) + { + bool hasDup = false; + for (int i = 0; i < s.size(); i++) + { + if (s[i] == s[i + 1]) + hasDup = true; + } + return hasDup; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abbaca"; + // 输出:"ca" + auto res = sol.removeDuplicates(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1047-remove-all-adjacent-duplicates-in-string_stack_using_string.cpp b/cpp-leetcode/leetcode1047-remove-all-adjacent-duplicates-in-string_stack_using_string.cpp new file mode 100644 index 00000000..51e9bef9 --- /dev/null +++ b/cpp-leetcode/leetcode1047-remove-all-adjacent-duplicates-in-string_stack_using_string.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string removeDuplicates(string S) { + string noDupStr; /* 用字符串模拟栈 */ + for (char& ch : S) + { + if (!noDupStr.empty() && noDupStr.back() == ch) + noDupStr.pop_back(); + else noDupStr.push_back(ch); + } + return noDupStr; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abbaca"; + // 输出:"ca" + auto res = sol.removeDuplicates(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode105-construct-binary-tree-from-preorder-and-inorder-traversal_recursive.cpp b/cpp-leetcode/leetcode105-construct-binary-tree-from-preorder-and-inorder-traversal_recursive.cpp new file mode 100644 index 00000000..69a0c205 --- /dev/null +++ b/cpp-leetcode/leetcode105-construct-binary-tree-from-preorder-and-inorder-traversal_recursive.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + unordered_map posDict; + vector pre, in; + TreeNode* buildTree(vector& preorder, vector& inorder) { + pre = preorder; + in = inorder; + if (pre.size() != in.size() || pre.empty() || in.empty()) + return nullptr; + for (int i = 0; i < in.size(); i++) + posDict[in[i]] = i; + + return build(0, pre.size() - 1, 0, in.size() - 1); + } + TreeNode* build(int preStart, int preEnd, int inStart, int inEnd) + { + if (preStart > preEnd) + return nullptr; + int rootVal = pre[preStart]; /* 不能写成 rootVal=pre.front();, 因为数组pre是不变的, 但实际上要处理的区间一直是缩小的, 即 preStart是递增变化的 */ + auto root = new TreeNode(rootVal); + int k = posDict[rootVal]; // 找到当前的root结点在中序遍历中的位置 + root->left = build(preStart+1, k + preStart - inStart, inStart, k - 1); + root->right = build(k+1+preStart - inStart, preEnd, k+1, inEnd); + + return root; + } +}; + +// Test +int main() +{ + Solution sol; + vector pre = {3, 9, 20, 15, 7}; + vector in = {9, 3, 15, 20, 7}; + + auto root = sol.buildTree(pre, in); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1052-grumpy-bookstore-owner_sliding_window.cpp b/cpp-leetcode/leetcode1052-grumpy-bookstore-owner_sliding_window.cpp new file mode 100644 index 00000000..0dc84d5a --- /dev/null +++ b/cpp-leetcode/leetcode1052-grumpy-bookstore-owner_sliding_window.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxSatisfied(vector& customers, vector& grumpy, int minutes) { + int sum = 0; + const int len = customers.size(); + for (int i = 0; i < len; i++) /* 先统计状态=不生气时的满意度之和(基本盘) */ + { + if (grumpy[i] == 0) + sum += customers[i]; + } + int maxScrore = 0; + for (int i = 0; i < len; i++) /* 遍历滑动窗口右端点i */ + { + if (grumpy[i] == 1) /* 新加入滑动窗口的1分钟是暴躁的, 可以用技能压制住 */ + sum += customers[i]; + if (i - minutes >= 0 && grumpy[i - minutes] == 1) /* 从滑动窗口中拿掉最前面的1分钟时, 如果是暴躁的, 技能就无法压制了, 此时会生效 */ + sum -= customers[i - minutes]; + maxScrore = max(maxScrore, sum); + } + return maxScrore; + } +}; + +// Test +int main() +{ + Solution sol; + vector customers = {4, 10, 10}; + vector grumpy = {1, 1, 0}; + int X = 2; + auto res = sol.maxSatisfied(customers, grumpy, X); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode106-construct-binary-tree-from-inorder-and-postorder-traversal_recursive.cpp b/cpp-leetcode/leetcode106-construct-binary-tree-from-inorder-and-postorder-traversal_recursive.cpp new file mode 100644 index 00000000..a49c6862 --- /dev/null +++ b/cpp-leetcode/leetcode106-construct-binary-tree-from-inorder-and-postorder-traversal_recursive.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector in; + vector post; + unordered_map posDict; + TreeNode* buildTree(vector& inorder, vector& postorder) { + in = inorder, post = postorder; + if (in.size() != post.size() || in.empty() || post.empty()) + return nullptr; + for (int i = 0; i < in.size(); i++) + posDict[in[i]] = i; + + return build(0, post.size() - 1, 0, in.size() - 1); + } + TreeNode* build(int postStart, int postEnd, int inStart, int inEnd) + { + if (postStart > postEnd) + return nullptr; + int rootVal = post[postEnd]; + auto root = new TreeNode(rootVal); + int k = posDict[rootVal]; + root->left = build(postStart, k + postStart - inStart - 1, inStart, k - 1); + root->right = build(k + postStart - inStart, postEnd - 1, k + 1, inEnd); + return root; + } +}; + +// Test +int main() +{ + Solution sol; + vector inorder = {9,3,15,20,7}; + vector postorder = {9,15,7,20,3}; + auto root = sol.buildTree(inorder, postorder); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode106-construct-binary-tree-from-postorder-and-inorder-traversal_recursive.cpp b/cpp-leetcode/leetcode106-construct-binary-tree-from-postorder-and-inorder-traversal_recursive.cpp new file mode 100644 index 00000000..a2a5e5f5 --- /dev/null +++ b/cpp-leetcode/leetcode106-construct-binary-tree-from-postorder-and-inorder-traversal_recursive.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector in; + vector post; + unordered_map posDict; + TreeNode* buildTree(vector& inorder, vector& postorder) { + in = inorder, post = postorder; + if (in.size() != post.size() || in.empty() || post.empty()) + return nullptr; + for (int i = 0; i < in.size(); i++) + posDict[in[i]] = i; + + return build(0, post.size() - 1, 0, in.size() - 1); + } + TreeNode* build(int postStart, int postEnd, int inStart, int inEnd) + { + if (postStart > postEnd || inStart > inEnd) + return nullptr; + int rootVal = post[postEnd]; + auto root = new TreeNode(rootVal); + int k = posDict[rootVal]; + root->left = build(postStart, k + postStart - inStart - 1, inStart, k - 1); + root->right = build(k + postStart - inStart, postEnd - 1, k+1, inEnd); + return root; + } +}; + +// Test +int main() +{ + Solution sol; + vector post = {9, 3, 15, 20, 7}; + vector in = {9, 15, 7, 20, 3}; + + auto root = sol.buildTree(post, in); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode107-binary-tree-level-order-traversal-ii_bfs.cpp b/cpp-leetcode/leetcode107-binary-tree-level-order-traversal-ii_bfs.cpp new file mode 100644 index 00000000..b26bdbe9 --- /dev/null +++ b/cpp-leetcode/leetcode107-binary-tree-level-order-traversal-ii_bfs.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + if (!root) return {}; + if (root->left == nullptr && root->right == nullptr) return {{root->val}}; + + vector> res; + queue q; + q.push(root); + while (!q.empty()) + { + vector curLevel; + for (int i = q.size() ; i > 0; --i) + { + TreeNode* p = q.front(); + q.pop(); + curLevel.push_back(p->val); + if (p->left != nullptr) q.push(p->left); /* 不能写出 !p->left 或 !(p->left) */ + if (p->right != nullptr) q.push(p->right); + } + res.push_back(curLevel); + } + reverse(res.begin(), res.end()); + return res; + } +}; + + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(9); + root->right = new TreeNode(20); + root->right->left = new TreeNode(15); + root->right->right = new TreeNode(7); + root->right->left->left = nullptr; + root->right->left->right = nullptr; + root->right->right->left = nullptr; + root->right->right->right = nullptr; + + vector> res = sol.levelOrderBottom(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode108-convert-sorted-array-to-binary-search-tree_dfs1.cpp b/cpp-leetcode/leetcode108-convert-sorted-array-to-binary-search-tree_dfs1.cpp new file mode 100644 index 00000000..918b39db --- /dev/null +++ b/cpp-leetcode/leetcode108-convert-sorted-array-to-binary-search-tree_dfs1.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. + */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + return dfs(nums, 0, nums.size() - 1); + } + TreeNode* dfs(vector& nums, int startPos, int endPos) + { + if (startPos > endPos) return nullptr; + if (startPos == endPos) return new TreeNode(nums[startPos]); + int mid = startPos + (endPos - startPos)/2; + auto root = new TreeNode(nums[mid]); + root->left = dfs(nums, startPos, mid - 1); + root->right = dfs(nums, mid+1, endPos); + return root; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-10, -3, 0, 5, 9}; + TreeNode* res = sol.sortedArrayToBST(nums); + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode108-convert-sorted-array-to-binary-search-tree_dfs2.cpp b/cpp-leetcode/leetcode108-convert-sorted-array-to-binary-search-tree_dfs2.cpp new file mode 100644 index 00000000..1eb4d5dc --- /dev/null +++ b/cpp-leetcode/leetcode108-convert-sorted-array-to-binary-search-tree_dfs2.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. + */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + return dfs(nums, 0, nums.size() - 1); + } + TreeNode* dfs(vector &nums, int start, int end) + { + if (start == end) + { + TreeNode* root = new TreeNode(nums[start]); + return root; + } + if (start < end) + { + int m = (end - start) / 2 + start; + auto leftChild = dfs(nums, start, m - 1); + auto rightChild = dfs(nums, m + 1, end); + TreeNode* root = new TreeNode(nums[m], leftChild, rightChild); + return root; + } + return nullptr; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-10, -3, 0, 5, 9}; + TreeNode* res = sol.sortedArrayToBST(nums); + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode11-container-with-most-water.cpp b/cpp-leetcode/leetcode11-container-with-most-water.cpp new file mode 100644 index 00000000..12e1352f --- /dev/null +++ b/cpp-leetcode/leetcode11-container-with-most-water.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxArea(vector& height) { + int len = height.size(); + int left = 0; + int right = len - 1; + + int maxArea = INT_MIN; + while(left < right) + { + int area = min(height[left], height[right]) * (right - left); + if(area > maxArea) + maxArea = area; + + if(height[left] <= height[right]) + left++; + else right--; + } + return maxArea; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,8,6,2,5,4,8,3,7}; + int res = sol.maxArea(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol1.cpp b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol1.cpp new file mode 100644 index 00000000..75841264 --- /dev/null +++ b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol1.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector pathInZigZagTree(int label) { + vector res; + while (label > 1) + { + res.push_back(label); + getParent(label); + } + res.push_back(1); + reverse(res.begin(), res.end()); + return res; + } + void getParent(int& num) + { + int levelIdx = 0; + int copy = num; + while (copy > 1) + { + copy /= 2; + levelIdx++; + } + bool isRev = levelIdx % 2 == 1; + int preLevelIdx = levelIdx - 1; + bool isPreRev = !isRev; + int preLevelMin = 1 << preLevelIdx; + vector preLevel; + for (int i = preLevelMin; i < 2*preLevelMin; i++) + preLevel.push_back(i); + if (isPreRev) reverse(preLevel.begin(), preLevel.end()); + int half = num / 2; + int halfIndex = find(preLevel.begin(), preLevel.end(), half) - preLevel.begin(); + num = preLevel[preLevelMin - 1 - halfIndex]; + } +}; + +// Test +int main() +{ + Solution sol; + auto res = sol.pathInZigZagTree(12); + for (auto x : res) + cout << x << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol2_using_bit_op.cpp b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol2_using_bit_op.cpp new file mode 100644 index 00000000..1dcb2474 --- /dev/null +++ b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol2_using_bit_op.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector pathInZigZagTree(int label) { + vector res; + int i = 2; + int level = 0; // 计算label所在层的level index + while (i <= label) + { + i *= 2; + level++; + } + res.push_back(label); + while (level > 0) + { + int level_min = 1 << level; + int level_max = (1 << (level + 1)) - 1; + label = (level_min + level_max - label) / 2; + res.push_back(label); + + level--; + } + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + auto res = sol.pathInZigZagTree(12); + for (auto x : res) + cout << x << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol2_using_pow.cpp b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol2_using_pow.cpp new file mode 100644 index 00000000..1e599822 --- /dev/null +++ b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol2_using_pow.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector pathInZigZagTree(int label) { + vector res; + int level = 0; // 计算label所在层的level index + while (pow(2, level + 1) <= label) + level++; + res.push_back(label); + while (level > 0) + { + int level_min = pow(2, level); + int level_max = pow(2, level + 1) - 1; + label = (level_min + level_max - label) / 2; + res.push_back(label); + + level--; + } + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + auto res = sol.pathInZigZagTree(12); + for (auto x : res) + cout << x << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol3_using_log2.cpp b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol3_using_log2.cpp new file mode 100644 index 00000000..905e29b7 --- /dev/null +++ b/cpp-leetcode/leetcode1104-path-in-zigzag-labelled-binary-tree_sol3_using_log2.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector pathInZigZagTree(int label) { + int levelIdx; + int start, end; // 用来记录当前层的第1个和最后1个结点的值 + vector res; + levelIdx = log2(label); + start = 1 << levelIdx; + end = (1 << (levelIdx + 1)) - 1; + int pos, dir; + dir = levelIdx & 0x01; // levelIdx是奇数时 dir = 1(从右到左), 否则是0(从左到右) + pos = dir ? label - start : end - label; + while (levelIdx) + { + start = 1 << levelIdx; + end = (1 << (levelIdx + 1)) - 1; + + if (dir) res.push_back(start + pos); + else res.push_back(end - pos); + + dir = 1 - dir; // 翻转: 0 => 1 或 1 => 0 + pos >>= 1; + levelIdx--; + } + res.push_back(1); + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + auto res = sol.pathInZigZagTree(12); + for (auto x : res) + cout << x << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1109-corporate-flight-bookings_different_array_and_prefix_sum.cpp b/cpp-leetcode/leetcode1109-corporate-flight-bookings_different_array_and_prefix_sum.cpp new file mode 100644 index 00000000..46c9e563 --- /dev/null +++ b/cpp-leetcode/leetcode1109-corporate-flight-bookings_different_array_and_prefix_sum.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector corpFlightBookings(vector> &bookings, int n) { + vector diff(n); // 差分数组 + for (vector& booking : bookings) /* 区间[L, R]上做inc操作: diff[L] += c, diff[R+1] -= c; */ + { + diff[booking[0] - 1] += booking[2]; + if (booking[1] < n) + diff[booking[1]] -= booking[2]; + } + vector preSum = diff; + // 反推出前缀和 + for (int i = 1; i < n; ++i) + preSum[i] += preSum[i - 1]; + + return preSum; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 5; + vector> updates = {{1,2,10}, {2,3,20}, {2,5,25}}; + auto res = sol.corpFlightBookings(updates, n); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode112-path-sum_tree.cpp b/cpp-leetcode/leetcode112-path-sum_tree.cpp new file mode 100644 index 00000000..218c73b4 --- /dev/null +++ b/cpp-leetcode/leetcode112-path-sum_tree.cpp @@ -0,0 +1,54 @@ +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + bool hasPathSum(TreeNode* root, int targetSum) { + // 1.明显的出口, 考虑第1层为NULL的情形 + if (root == NULL) return false; + + /* 2.具体逻辑的出口: 考虑第1层的左右孩子为NULL的情形 */ + if (root->left == NULL && root->right == NULL) + return root->val == targetSum; /* 注意这里不是直接return一个bool值, 而是return一个含变量的表达式(递归地判断叶子节点) */ + + // 3.自顶向下进行递归调用 + bool hasLeftPath = hasPathSum(root->left, targetSum - root->val); + bool hasRightPath = hasPathSum(root->right, targetSum - root->val); + return hasLeftPath || hasRightPath; + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(3); + root->left = new TreeNode(2); + root->right->left = nullptr; + root->right->right = nullptr; + root->left->left = nullptr; + root->left->right = nullptr; + int targetSum = 4; + bool res = sol.hasPathSum(root, targetSum); + cout << (res == true ? "true" : "false") << endl; + + targetSum = 5; + res = sol.hasPathSum(root, targetSum); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode113-path-sum-ii_dfs1.cpp b/cpp-leetcode/leetcode113-path-sum-ii_dfs1.cpp new file mode 100644 index 00000000..93ce50a6 --- /dev/null +++ b/cpp-leetcode/leetcode113-path-sum-ii_dfs1.cpp @@ -0,0 +1,74 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree root-> +*/ +struct TreeNode +{ + int val; + TreeNode* left; + TreeNode* right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> pathSum(TreeNode* root, int targetSum) { + vector> paths; + vector curPath; + dfs(root, targetSum, paths, curPath); + return paths; + } + /* 类似于two sum的做法, 下次调用dfs时传入dfs的新sum为sum - root->val */ + void dfs(TreeNode* root, int sum, vector>& paths, vector curPath) + { + if (root == nullptr) return; + curPath.push_back(root->val); + if (root->val == sum && root->left == nullptr && root->right == nullptr) + paths.push_back(curPath); + else + { + dfs(root->left, sum - root->val, paths, curPath); + dfs(root->right, sum - root->val, paths, curPath); + } + curPath.pop_back(); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(3); + TreeNode* n1 = new TreeNode(5); + TreeNode* n2 = new TreeNode(1); + TreeNode* n3 = new TreeNode(6); + TreeNode* n4 = new TreeNode(2); + TreeNode* n5 = new TreeNode(0); + TreeNode* n6 = new TreeNode(8); + TreeNode* n7 = new TreeNode(7); + TreeNode* n8 = new TreeNode(4); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + + int targetSum = 14; + auto res = sol.pathSum(root, targetSum); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode113-path-sum-ii_dfs2.cpp b/cpp-leetcode/leetcode113-path-sum-ii_dfs2.cpp new file mode 100644 index 00000000..4bf97efb --- /dev/null +++ b/cpp-leetcode/leetcode113-path-sum-ii_dfs2.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree root-> +*/ +struct TreeNode +{ + int val; + TreeNode* left; + TreeNode* right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector> pathSum(TreeNode* root, int targetSum) { + vector> res; + vector curPath; + dfs(root, targetSum, curPath, res); + return res; + } + void dfs(TreeNode* root, int sum, vector& curPath, vector>& res) + { + if (root == nullptr) return; + if (root->left == nullptr && root->right == nullptr) /* 走到叶子节点, 就没法继续向下走了 */ + { + if (root->val == sum) /* 特殊情况, 当前结点的值就是需要找的sum */ + { + curPath.push_back(root->val); + res.push_back(curPath); + curPath.pop_back(); /* Un-choose(回到选这个结点之前的状态), 尝试找下一个 */ + } + return; + } + curPath.push_back(root->val); + int newSum = sum - root->val; + dfs(root->left, newSum, curPath, res); + dfs(root->right, newSum, curPath, res); + curPath.pop_back(); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(3); + TreeNode* n1 = new TreeNode(5); + TreeNode* n2 = new TreeNode(1); + TreeNode* n3 = new TreeNode(6); + TreeNode* n4 = new TreeNode(2); + TreeNode* n5 = new TreeNode(0); + TreeNode* n6 = new TreeNode(8); + TreeNode* n7 = new TreeNode(7); + TreeNode* n8 = new TreeNode(4); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + + int targetSum = 14; + auto res = sol.pathSum(root, targetSum); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode113-path-sum-ii_dfs3_preorder.cpp b/cpp-leetcode/leetcode113-path-sum-ii_dfs3_preorder.cpp new file mode 100644 index 00000000..29e88236 --- /dev/null +++ b/cpp-leetcode/leetcode113-path-sum-ii_dfs3_preorder.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree root-> +*/ +struct TreeNode +{ + int val; + TreeNode* left; + TreeNode* right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} +}; + +class Solution { + vector> res; + int _targetSum; +public: + vector> pathSum(TreeNode* root, int targetSum) { + _targetSum = targetSum; + vector curPath; + int sum = 0; + preOrder(root, _targetSum, curPath, sum); + return res; + } + void preOrder(TreeNode* root, int targetSum, vector& curPath, int curSum) + { + if (root == nullptr) return; + curSum += root->val; + curPath.push_back(root->val); + + if (root->left == nullptr && root->right == nullptr) + { + if (curSum == targetSum) res.emplace_back(curPath); + curPath.pop_back(); + return; + } + + preOrder(root->left, targetSum, curPath, curSum); + preOrder(root->right, targetSum, curPath, curSum); + curPath.pop_back(); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(3); + TreeNode* n1 = new TreeNode(5); + TreeNode* n2 = new TreeNode(1); + TreeNode* n3 = new TreeNode(6); + TreeNode* n4 = new TreeNode(2); + TreeNode* n5 = new TreeNode(0); + TreeNode* n6 = new TreeNode(8); + TreeNode* n7 = new TreeNode(7); + TreeNode* n8 = new TreeNode(4); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + + int targetSum = 14; + auto res = sol.pathSum(root, targetSum); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode114-flatten-binary-tree-to-linked-list_recursive.cpp b/cpp-leetcode/leetcode114-flatten-binary-tree-to-linked-list_recursive.cpp new file mode 100644 index 00000000..9453a75b --- /dev/null +++ b/cpp-leetcode/leetcode114-flatten-binary-tree-to-linked-list_recursive.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + void flatten(TreeNode* root) { + // 题意: 按照 root(1)->左子树撸直(2, 3) -> 右子树撸直(4,5,6) 连接 + if (root == nullptr) return; + if (root->left == nullptr) { // 如果root没有left结点, 直接撸直右子树后return即可 + flatten(root->right); + return; + } + + TreeNode* pl = root->left; // 递归调用撸直函数前保留现场 root 结点的 left/right 指针 + TreeNode* pr = root->right; + flatten(root->left); + flatten(root->right); + + root->right = pl; // 先把左子树的所有left结点撸直的结果挂上去 + root->left = nullptr; + while (pl-> right != nullptr) // 先把左子树的所有right结点遍历出来后挂上去 + pl = pl->right; + + pl->right = pr; // 最后将右子树撸直的结果挂接到左子树撸直结果的后面 + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(4); + root->right = new TreeNode(5); + root->right->left = nullptr; + root->right->right = new TreeNode(6); + + sol.flatten(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1143-longest-common-subsequence_dp.cpp b/cpp-leetcode/leetcode1143-longest-common-subsequence_dp.cpp new file mode 100644 index 00000000..9325bb3a --- /dev/null +++ b/cpp-leetcode/leetcode1143-longest-common-subsequence_dp.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + const int m = text1.size(); + const int n = text2.size(); + text1 = '#' + text1; + text2 = '#' + text2; + int dp[m + 1][n + 1]; + for (auto& row : dp) + fill(row, row + n, 0); + for (int i = 1; i <= m; i++) + dp[i][0] = 0; + for (int i = 1; i <= n; i++) + dp[0][i] = 0; + + for (int i = 1; i <= m; i++) + { + for (int j = 1; j <= n; j++) + { + if (text1[i] == text2[j]) dp[i][j] = dp[i-1][j-1] + 1; + else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); + } + } + return dp[m][n]; + } +}; + +// Test +int main() +{ + Solution sol; + string str1 = "abcdecgdagkdgd"; + string str2 = "efgedsgded"; + auto res = sol.longestCommonSubsequence(str1, str2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode116-populating-next-right-pointers-in-each-node_bfs_level_order.cpp b/cpp-leetcode/leetcode116-populating-next-right-pointers-in-each-node_bfs_level_order.cpp new file mode 100644 index 00000000..b878e96d --- /dev/null +++ b/cpp-leetcode/leetcode116-populating-next-right-pointers-in-each-node_bfs_level_order.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; + +/** Definition for a Node. */ +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; + +class Solution { +public: + Node* connect(Node* root) { + if (root == nullptr) + return nullptr; + if (root->left == NULL && root->right == NULL) + return root; + + queue q; + q.push({root}); + + while (!q.empty()) + { + vector curLevel; + for (int i = q.size(); i > 0; i--) + { + Node* p = q.front(); + q.pop(); + curLevel.push_back(p); + if (p->left != NULL) + q.push(p->left); + + if (p->right != NULL) + q.push(p->right); + } + int curSize = curLevel.size(); + for (int i = 0; i < curSize - 1; i++) /* 设置每一层的node的next指针的指向 */ + curLevel[i]->next = curLevel[i+1]; + curLevel.back()->next = nullptr; /* 将当前层最后一个Node的next设为null */ + } + + return root; + } +}; + +// Test +int main() +{ + Solution sol; + Node *root = new Node(1); + root->left = NULL; + root->right = new Node(2); + root->right->left = new Node(3); + + auto res = sol.connect(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1162-as-far-from-land-as-possible_bfs1.cpp b/cpp-leetcode/leetcode1162-as-far-from-land-as-possible_bfs1.cpp new file mode 100644 index 00000000..6c61abd0 --- /dev/null +++ b/cpp-leetcode/leetcode1162-as-far-from-land-as-possible_bfs1.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + const int dx[4] = {0, 1, 0, -1}; + const int dy[4] = {1, 0, -1, 0}; +public: + int maxDistance(vector>& grid) { + int N = grid.size(); + queue> q; // queue存储坐标值, 即 pair of {x, y} + vector> d(N, vector(N, 1000)); // 二维数组d[][]: 记录每个格子grid[i][j]的距离值 + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + if (grid[i][j] == 1) + { + q.push(make_pair(i, j)); + d[i][j] = 0; + } + } + while (!q.empty()) + { + auto kvp = q.front(); + q.pop(); + for (int i = 0; i < 4; i++) + { + int newX = kvp.first + dx[i], newY = kvp.second + dy[i]; + if (newX < 0 || newX >= N || newY < 0 || newY >= N) // 越界了, 跳过 + continue; + + if (d[newX][newY] > d[kvp.first][kvp.second] + 1) /* 如果从水域(值为0的格子)走到陆地(值为1的格子)或从陆地走到水域, 且新到达的位置之前没被访问过, 此时需要将其坐标加入队列, 并更新距离值d */ + { + d[newX][newY] = d[kvp.first][kvp.second] + 1; /* 当前格子的上下左右4个方向之一走一步恰好使得曼哈顿距离增加1 */ + q.push(make_pair(newX, newY)); + } + } + } + int res = -1; + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + if (grid[i][j] == 0 && d[i][j] <= 200) /* 挑出访问过的水域位置(值为0的格子), 并维护这些格子中距离值d的最大值 */ + res = max(res, d[i][j]); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = + { + {1, 0, 1}, + {0, 0, 0}, + {1, 0, 1} + }; + auto res = sol.maxDistance(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1162-as-far-from-land-as-possible_bfs2.cpp b/cpp-leetcode/leetcode1162-as-far-from-land-as-possible_bfs2.cpp new file mode 100644 index 00000000..0ca60d51 --- /dev/null +++ b/cpp-leetcode/leetcode1162-as-far-from-land-as-possible_bfs2.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + const int dx[4] = {0, 1, 0, -1}; + const int dy[4] = {1, 0, -1, 0}; +public: + int maxDistance(vector>& grid) { + const int N = grid.size(); + deque> q; + int d[N][N]; + for (auto& row : d) + fill(row, row + N, 1000); + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + if (grid[i][j] == 1) + { + q.push_back(make_pair(i, j)); + d[i][j] = 0; + } + } + while (!q.empty()) + { + auto kvp = q.front(); + q.pop_front(); + for (int i = 0; i < 4; i++) + { + int newX = kvp.first + dx[i], newY = kvp.second + dy[i]; + if (newX < 0 || newX >= N || newY < 0 || newY >= N) + continue; + + if (d[newX][newY] > d[kvp.first][kvp.second] + 1) + { + d[newX][newY] = d[kvp.first][kvp.second] + 1; + q.push_back(make_pair(newX, newY)); + } + } + } + int res = -1; + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + if (grid[i][j] == 0 && d[i][j] <= 200) + res = max(res, d[i][j]); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = + { + {1, 0, 1}, + {0, 0, 0}, + {1, 0, 1} + }; + auto res = sol.maxDistance(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode117-populating-next-right-pointers-in-each-node-ii_level_order.cpp b/cpp-leetcode/leetcode117-populating-next-right-pointers-in-each-node-ii_level_order.cpp new file mode 100644 index 00000000..2a28239d --- /dev/null +++ b/cpp-leetcode/leetcode117-populating-next-right-pointers-in-each-node-ii_level_order.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +using namespace std; +/* Definition for a Node. */ +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; + +class Solution { +public: + Node* connect(Node* root) { + if (root == nullptr) + return nullptr; + if (root->left == nullptr && root->right == nullptr) + return root; + + queue q; + q.push({root}); + + while (!q.empty()) + { + vector curLevel; + for (int i = q.size(); i > 0; i--) + { + Node* p = q.front(); + q.pop(); + curLevel.push_back(p); + if (p->left != NULL) + q.push(p->left); + + if (p->right != NULL) + q.push(p->right); + } + int curSize = curLevel.size(); + for (int i = 0; i < curSize - 1; i++) /* 设置每一层的node的next指针的指向 */ + curLevel[i]->next = curLevel[i+1]; + curLevel.back()->next = nullptr; + } + + return root; + } +}; + +// Test +int main() +{ + Solution sol; + Node *root = new Node(1); + root->left = new Node(2); + root->right = new Node(3); + root->left->left = new Node(4); + root->left->right = new Node(5); + root->right->left = NULL; + root->right->right = new Node(7); + root->left->left->left = NULL; + root->left->left->right = NULL; + root->left->right->left = NULL; + root->left->right->right = NULL; + root->right->right->left = NULL; + root->right->right->right = NULL; + + auto res = sol.connect(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode118-Pascal-triangle.cpp b/cpp-leetcode/leetcode118-Pascal-triangle.cpp new file mode 100644 index 00000000..5fd4ce84 --- /dev/null +++ b/cpp-leetcode/leetcode118-Pascal-triangle.cpp @@ -0,0 +1,50 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector> generate(int numRows) { + vector> res(numRows); + + if (numRows > 0) + { + res[0] = {1}; + } + + for (int i = 1; i < numRows; i++) + { + vector row(i+1); // No.i row (index: i-1) havs i nums + auto preRow = res[i-1]; + auto curRow = row; + + curRow[0] = curRow[i] = 1; + + for (int j = 1; j < curRow.size() - 1; j++) // The first and last of each row no need to be added from two nums + { + curRow[j] = preRow[j-1] + preRow[j]; + } + res[i] = curRow; + } + return res; + } +}; + +// Below is testing +int main() +{ + Solution sol; + int numRows = 5; + vector> res = sol.generate(numRows); + + for (int i = 0; i < res.size(); i++) + { + for (int j = 0; j < res[i].size(); j++) + { + printf("%d ", res[i][j]); + } + printf("\n"); + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode119-pascal-triangle-ii.cpp b/cpp-leetcode/leetcode119-pascal-triangle-ii.cpp new file mode 100644 index 00000000..52c72606 --- /dev/null +++ b/cpp-leetcode/leetcode119-pascal-triangle-ii.cpp @@ -0,0 +1,41 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector getRow(int rowIndex) { + int numRows = rowIndex + 1; + vector> rows(numRows); + + if (numRows > 0) rows[0] = {1}; + for (int i = 1; i < numRows; i++) + { + vector row(i+1); // 第 i 行 (行index为i-1) 有 i 个数 + auto preRow = rows[i-1]; + auto curRow = row; + + curRow[0] = curRow[i] = 1; + + for (int j = 1; j < curRow.size() - 1; j++) // 每一行的首尾两个数不是通过相加得来的 + { + curRow[j] = preRow[j-1] + preRow[j]; + } + rows[i] = curRow; + } + return rows[rowIndex]; + } +}; + +// Below is testing +int main() +{ + Solution sol; + int numRows = 5; + auto res = sol.getRow(numRows); + + for (int i = 0; i < res.size(); i++) + printf("%d ", res[i]); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode12-integer-to-roman.cpp b/cpp-leetcode/leetcode12-integer-to-roman.cpp new file mode 100644 index 00000000..cfb311b2 --- /dev/null +++ b/cpp-leetcode/leetcode12-integer-to-roman.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string intToRoman(int num) { + string res; + vector vals = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; + /* 注意: 只有I,X,C可以在临近大小值的左侧位置, 剩下的 V,L,D,M不能 */ + vector strs = {"M", "CM","D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV","I"}; + for(int i=0; i < vals.size(); i++) + { + while(num >= vals[i]) /* 循环出口:只要够减,就继续 */ + { + num -= vals[i]; + res.append(strs[i]); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 4999; + string res = sol.intToRoman(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_array.cpp b/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_array.cpp new file mode 100644 index 00000000..389c9eb7 --- /dev/null +++ b/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_array.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +using namespace std; + +const int K = 1e5; +class Solution { +public: + int longestSubsequence(vector& arr, int diff) { + const int N = arr.size(); + int count = 0; + for (auto& num : arr) + { + if (num == arr.front()) count++; + } + if (diff == 0 && count == N) return N; + + int res = 1; + int dp[2*K+1]; + memset(dp, 0, sizeof(dp)); + for (auto& num : arr) + { + dp[num + K] = 1; + if (dp[num - diff + K] != 0) + dp[num + K] = dp[num - diff + K] + 1; + } + for (auto& num : dp) + res = max(res, num); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector arr = {1, 5, 7, 8, 5, 3, 4, 2, 1}; + int diff = -2; + auto res = sol.longestSubsequence(arr, diff); + cout << res << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_array_with_accumulate.cpp b/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_array_with_accumulate.cpp new file mode 100644 index 00000000..e6a4e799 --- /dev/null +++ b/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_array_with_accumulate.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include /* std::memset在这个头文件中 */ +#include +using namespace std; + +const int K = 1e5; +class Solution { +public: + int longestSubsequence(vector& arr, int diff) { + const int N = arr.size(); + long sum = accumulate(arr.begin(), arr.end(), (long)0); + if (diff == 0 && sum == N*arr[0]) return N; + int res = 1; + int dp[2*K+1]; + memset(dp, 0, sizeof(dp)); + for (auto& num : arr) + { + dp[num + K] = 1; + if (dp[num - diff + K] != 0) + dp[num + K] = dp[num - diff + K] + 1; + } + for (auto& num : dp) + res = max(res, num); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector arr = {1, 5, 7, 8, 5, 3, 4, 2, 1}; + int diff = -2; + auto res = sol.longestSubsequence(arr, diff); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_hashmap.cpp b/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_hashmap.cpp new file mode 100644 index 00000000..6930cead --- /dev/null +++ b/cpp-leetcode/leetcode1218-longest-arithmetic-subsequence-of-given-difference_dp_hashmap.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int longestSubsequence(vector& arr, int diff) { + const int N = arr.size(); + int count = 0; + for (auto& num : arr) + { + if (num == arr.front()) count++; + } + if (diff == 0 && count == N) return N; + + int res = 1; // 记录最大长度 + unordered_map dp; /* map: value -> length, dp[i]: 以nums[i]结尾的最长等差子序列的长度, 类似于LIS的dp数组定义 */ + for (auto& num : arr) + { + dp[num] = 1; /* 不能构成等差序列的情形, 最长的等差子序列的长度为1, 默认值可设置为 1 */ + if (dp.count(num - diff)) /* 如果num - diff 出现过, (num-diff)与num组成等差序列, 最大等差子序列的长度+1, 扩展出1个新的等差数列 */ + dp[num] = dp[num - diff] + 1; + } + for (auto& kvp : dp) + res = max(res, kvp.second); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector arr = {1, 5, 7, 8, 5, 3, 4, 2, 1}; + int diff = -2; + auto res = sol.longestSubsequence(arr, diff); + cout << res << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol1.cpp b/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol1.cpp new file mode 100644 index 00000000..d3c2200a --- /dev/null +++ b/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol1.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector circularPermutation(int n, int start) { + int len = 1 << n; /* n: 格雷码中bit位的个数 */ + vector grey(len, 0); + int startPos = 0; + for (int i = 0; i < len; i++) + { + grey[i] = i ^ (i >> 1); // 格雷码的数学公式 + if (grey[i] == start) /* 由于格雷码数组中每一个数都是不相等的, 所以这里加不加break语句都行 */ + startPos = i; + } + vector res; + res.insert(res.end(), grey.begin() + startPos, grey.end()); + res.insert(res.end(), grey.begin(), grey.begin() + startPos); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 2, start = 3; + auto res = sol.circularPermutation(n, start); + for (auto x : res) + cout << x << " "; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol2.cpp b/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol2.cpp new file mode 100644 index 00000000..0f388267 --- /dev/null +++ b/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol2.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector circularPermutation(int n, int start) { + int len = 1 << n; /* n: 格雷码中bit位的个数 */ + vector grey(len, 0); + int startPos = 0; + for (int i = 0; i < len; i++) + { + grey[i] = i ^ (i >> 1); + if (grey[i] == start) /* 由于格雷码数组中每一个数都是不相等的, 所以这里加不加break语句都行 */ + startPos = i; + } + vector res(grey.begin() + startPos, grey.end()); + res.insert(res.end(), grey.begin(), grey.begin() + startPos); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 2, start = 3; + auto res = sol.circularPermutation(n, start); + for (auto x : res) + cout << x << " "; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol3_rotate.cpp b/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol3_rotate.cpp new file mode 100644 index 00000000..9602de4a --- /dev/null +++ b/cpp-leetcode/leetcode1238-circular-permutation-in-binary-representation_sol3_rotate.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector circularPermutation(int n, int start) { + int len = 1 << n; /* n: 格雷码中bit位的个数 */ + vector grey(len, 0); + int startPos = 0; + for (int i = 0; i < len; i++) + { + grey[i] = i ^ (i >> 1); + if (grey[i] == start) + startPos = i; + } + rotate(grey.begin(), grey.begin() + startPos, grey.end()); /* 原地做rotate操作得到想要的数组part2+part1 */ + return grey; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 2, start = 3; + auto res = sol.circularPermutation(n, start); + for (auto x : res) + cout << x << " "; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode128-longest-consecutive-sequence_hashmap.cpp b/cpp-leetcode/leetcode128-longest-consecutive-sequence_hashmap.cpp new file mode 100644 index 00000000..cf359fdb --- /dev/null +++ b/cpp-leetcode/leetcode128-longest-consecutive-sequence_hashmap.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include +using namespace std; + +/* 题目要求: 时间复杂度为 O(n) */ +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_map dict; + for (int num : nums) { + if (dict.count(num)) continue; // 重复出现的数不用再考虑一次 + + auto preIt = dict.find(num - 1); + auto nextIt = dict.find(num + 1); + + int preCount = preIt != dict.end() ? preIt->second : 0; + int nextCount = nextIt != dict.end() ? nextIt->second : 0; + + if (preCount > 0 && nextCount > 0) + dict[num] = dict[num - preCount] = dict[num + nextCount] = preCount + nextCount + 1; + else if (preCount > 0) + dict[num] = dict[num - preCount] = preCount + 1; + else if (nextCount > 0) + dict[num] = dict[num + nextCount] = nextCount + 1; + else dict[num] = 1; + } + + int maxLen = 0; + for (const auto &kvp : dict) + maxLen = max(maxLen, kvp.second); + + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 100,4,200,1,3,2,4 }; + auto res = sol.longestConsecutive(nums); + cout << res << endl; + + nums = { 0,3,7,2,5,8,4,6,0,1 }; + res = sol.longestConsecutive(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode128-longest-consecutive-sequence_hashset.cpp b/cpp-leetcode/leetcode128-longest-consecutive-sequence_hashset.cpp new file mode 100644 index 00000000..fc0d1e8d --- /dev/null +++ b/cpp-leetcode/leetcode128-longest-consecutive-sequence_hashset.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include +using namespace std; + +/* 题目要求: 时间复杂度为 O(n) */ +class Solution { +public: + int longestConsecutive(vector& nums) { + if (nums.empty()) return 0; + + unordered_set st; + for (auto &num : nums) + st.insert(num); + + int maxLen = 0; + for (int num : nums) + { + if (!st.count(num - 1)) { + int curLen = 0; + while (st.count(num)) + { + curLen++; + num++; + } + maxLen = max(maxLen, curLen); + } + } + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 100,4,200,1,3,2,4 }; + auto res = sol.longestConsecutive(nums); + cout << res << endl; + + nums = { 0,3,7,2,5,8,4,6,0,1 }; + res = sol.longestConsecutive(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode129-sum-root-to-leaf-numbers_dfs1.cpp b/cpp-leetcode/leetcode129-sum-root-to-leaf-numbers_dfs1.cpp new file mode 100644 index 00000000..9aee7a1a --- /dev/null +++ b/cpp-leetcode/leetcode129-sum-root-to-leaf-numbers_dfs1.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +private: + int sum = 0; + string pathStr; + +public: + int sumNumbers(TreeNode *root) { + dfs(root); + return sum; + } + +private: + void dfs(TreeNode *root) { + if (root == nullptr) return; + + pathStr.push_back(root->val + '0'); + if (root->left == nullptr && root->right == nullptr) + sum += stoi(pathStr); + else + { + if (root->left != nullptr) + dfs(root->left); + if (root->right != nullptr) + dfs(root->right); + } + pathStr.pop_back(); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->left->left = nullptr; + root->left->right = nullptr; + root->right = new TreeNode(3); + root->right->left = nullptr; + root->right->right = nullptr; + + auto res = sol.sumNumbers(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode129-sum-root-to-leaf-numbers_dfs2.cpp b/cpp-leetcode/leetcode129-sum-root-to-leaf-numbers_dfs2.cpp new file mode 100644 index 00000000..f251dcd3 --- /dev/null +++ b/cpp-leetcode/leetcode129-sum-root-to-leaf-numbers_dfs2.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int sumNumbers(TreeNode *root) { + string pathStr = ""; + int sum = 0; + + dfs(root, pathStr, sum); + + return sum; + } + +private: + void dfs(TreeNode *root, string& pathStr, int& sum) { + if (root == nullptr) return; + + pathStr.push_back(root->val + '0'); + if (root->left == nullptr && root->right == nullptr) + sum += stoi(pathStr); + else + { + if (root->left != nullptr) + dfs(root->left, pathStr, sum); + if (root->right != nullptr) + dfs(root->right, pathStr, sum); + } + pathStr.pop_back(); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->left->left = nullptr; + root->left->right = nullptr; + root->right = new TreeNode(3); + root->right->left = nullptr; + root->right->right = nullptr; + + auto res = sol.sumNumbers(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode13-roman-to-integer.cpp b/cpp-leetcode/leetcode13-roman-to-integer.cpp new file mode 100644 index 00000000..3f334b0a --- /dev/null +++ b/cpp-leetcode/leetcode13-roman-to-integer.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int romanToInt(string s) { + int sum = 0; + unordered_map dict = { + {'I',1}, + {'V',5}, + {'X',10}, + {'L',50}, + {'C',100}, + {'D',500}, + {'M',1000} + }; + int len = s.size(); + + /* 反向遍历: 如果当前位的字母是最后一位,或者它后一位字母对应的数比它对应的数小的话, + 则加上当前位的字母对应的数;其他情况则减去当前位的字母对应的数。 */ + for(int i = len - 1; i >= 0; i--) + { + if((i == len - 1) || dict[s[i]] >= dict[s[i+1]]) + sum += dict[s[i]]; + else sum -= dict[s[i]]; + } + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "LVIII"; + auto res = sol.romanToInt(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode13-roman-to-integer_style2.cpp b/cpp-leetcode/leetcode13-roman-to-integer_style2.cpp new file mode 100644 index 00000000..5af9e5e0 --- /dev/null +++ b/cpp-leetcode/leetcode13-roman-to-integer_style2.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int romanToInt(string s) { + int sum = 0; + int dict[100] = {}; /* X的ASCII码是88, 长度给100够了 */ + dict['I'] = 1; + dict['V'] = 5; + dict['X'] = 10; + dict['L'] = 50; + dict['C'] = 100; + dict['D'] = 500; + dict['M'] = 1000; + + int len = s.size(); + for(int i = len - 1; i >= 0; i--) + { + if((i == len - 1) || dict[s[i]] >= dict[s[i+1]]) + sum += dict[s[i]]; + else sum -= dict[s[i]]; + } + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "LVIII"; + auto res = sol.romanToInt(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode130-surrounded-regions_bfs1.cpp b/cpp-leetcode/leetcode130-surrounded-regions_bfs1.cpp new file mode 100644 index 00000000..96064c78 --- /dev/null +++ b/cpp-leetcode/leetcode130-surrounded-regions_bfs1.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int dx[4] = {1, -1, 0, 0}; + int dy[4] = {0, 0, -1, 1}; +public: + void solve(vector> &M) { + if (M.size() == 0 || M[0].size() == 0) return; + const int n = M.size(); + const int m = M[0].size(); + queue> q; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if ((i == 0 || j == 0 || i == n - 1 || j == m - 1) && M[i][j] == 'O') + { + // 只要遇到4条边上的大写'o', 就改为$后放入BFS搜索队列 + M[i][j] = '$'; + q.push({i, j}); + } + } + } + while (q.size()) + { + int x = q.front().first; + int y = q.front().second; + q.pop(); + for (int i = 0; i < 4; i++) + { + int a = x + dx[i]; + int b = y + dy[i]; + if (a >= 0 && a < n && b >= 0 && b < m && M[a][b] == 'O') + { + M[a][b] = '$'; + q.push({a, b}); + } + } + } + /* 遍历完成后, 所有与边相邻的大写'o'变成了$。需要此时的$恢复成大写'o', 且将此时还不是$或X的格子修改为$ */ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if (M[i][j] == '$') M[i][j] = 'O'; + else if (M[i][j] != 'X') + M[i][j] = 'X'; + } + } + return; + } +}; + +// Test +int main() +{ + Solution sol; + vector> M { + {'X', 'X', 'X', 'X'}, + {'X', 'O', 'O', 'X'}, + {'X', 'X', 'O', 'X'}, + {'X', 'O', 'X', 'X'}}; + + sol.solve(M); + for (auto& row : M) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << "\t"; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode130-surrounded-regions_dfs1.cpp b/cpp-leetcode/leetcode130-surrounded-regions_dfs1.cpp new file mode 100644 index 00000000..0d12d1f1 --- /dev/null +++ b/cpp-leetcode/leetcode130-surrounded-regions_dfs1.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int n, m; + int dx[4] = {0, 0, -1, 1}; + int dy[4] = {-1, 1, 0, 0}; +public: + void solve(vector>& M) { + n = M.size(); + m = M[0].size(); + if (m == 0 || n == 0) return; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if (i == 0 || j == 0 || i == n - 1 || j == m - 1) /* 只对边界4条边上值是大写'o'的格子进行dfs */ + { + if (M[i][j] == 'O') dfs(M, i, j); + } + } + } + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if (M[i][j] == 'O') M[i][j] = 'X'; /* 留下来的大写'o'的格子是非边界上(内部)的大'o', 且不与边界的大'o'相连, 最终必然会变成X */ + else if (M[i][j] == '$') + M[i][j] = 'O'; + } + } + } + /* dfs: 把(边界4条边上)所有值是大写'o'的格子标记为$, 并dfs遍历其上下左右4个邻居 */ + void dfs(vector>& M, int x, int y) + { + if (M[x][y] != 'O') return; + M[x][y] = '$'; + for (int i = 0; i < 4; i++) + { + int a = x + dx[i]; + int b = y + dy[i]; + if (a < 0 || a >= n || b < 0 || b >= m || M[a][b] != 'O') continue; + dfs(M, a, b); + } + } +}; + +// Test +int main() +{ + Solution sol; + vector> M { + {'X', 'X', 'X', 'X'}, + {'X', 'O', 'O', 'X'}, + {'X', 'X', 'O', 'X'}, + {'X', 'O', 'X', 'X'}}; + + sol.solve(M); + for (auto& row : M) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << "\t"; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode133-clone-graph_hashmap.cpp b/cpp-leetcode/leetcode133-clone-graph_hashmap.cpp new file mode 100644 index 00000000..748e0f86 --- /dev/null +++ b/cpp-leetcode/leetcode133-clone-graph_hashmap.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; + +class Solution { + unordered_map dict; /* 哈希表: 记录源点(source node)和它的克隆点(cloned node) */ +public: + Node* cloneGraph(Node* node) { + if (node == nullptr) return nullptr; + dfs(node); // 复制所有node + + // 遍历原graph中所有node的所有边 + for (auto& [sNode, cNode] : dict) + { + for (auto& nextNode : sNode->neighbors) + cNode->neighbors.push_back(dict[nextNode]); + } + return dict[node]; + } + void dfs(Node* node) + { + dict[node] = new Node(node->val); + for (auto& nextNode : node->neighbors) + { + if (dict.count(nextNode) == 0) + dfs(nextNode); + } + } +}; + +// Test +int main() +{ + Solution sol; + Node n1(1), n2(2), n3(3), n4(4); + n1.neighbors.push_back(&n2); + n2.neighbors.push_back(&n3); + n3.neighbors.push_back(&n4); + n4.neighbors.push_back(&n1); + Node* newNode = sol.cloneGraph(&n1); + cout << newNode->val << endl; + cout << newNode->neighbors[0]->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1337-the-k-weakest-rows-in-a-matrix_priority_queue.cpp b/cpp-leetcode/leetcode1337-the-k-weakest-rows-in-a-matrix_priority_queue.cpp new file mode 100644 index 00000000..a25691ce --- /dev/null +++ b/cpp-leetcode/leetcode1337-the-k-weakest-rows-in-a-matrix_priority_queue.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector kWeakestRows(vector>& mat, int k) { + /* 题意: + * 强弱的规则有两条: + * 1、该row的1的数量比较少 + * 2、遇到与该row中1的数量相同的,row index越小, 该row越弱 + */ + vector res; + unordered_map dict; // map: row index -> count of 1 (or sum) + for (int i = 0; i < mat.size(); i++) + { + vector row = mat[i]; + dict[i] = count(row.begin(), row.end(), 1); + } + // k: 倒计数的计数器, 出来1个就-1 + // 越靠前, 越小, 于是直接取靠前的即可. + auto cmp = [](pair x, pair y) + { + if (x.second == y.second) + return x.first > y.first; + else return x.second > y.second; /* 小顶堆, 这里y代表顶部值 */ + }; + priority_queue, vector>, decltype(cmp)> q(cmp); + for (pair kvp : dict) + { + q.push(kvp); + } + + while (!q.empty() && k > 0) + { + res.push_back(q.top().first); + q.pop(); + k--; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> mat = {{1,1,0,0,0},{1,1,1,1,0},{1,0,0,0,0},{1,1,0,0,0},{1,1,1,1,1}}; + int k = 3; + auto res = sol.kWeakestRows(mat, k); + for (auto index : res) + cout << index << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode134-gas-station_geedy_optimization_based_on_direct_method.cpp b/cpp-leetcode/leetcode134-gas-station_geedy_optimization_based_on_direct_method.cpp new file mode 100644 index 00000000..757eb08e --- /dev/null +++ b/cpp-leetcode/leetcode134-gas-station_geedy_optimization_based_on_direct_method.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + const int N = gas.size(); + int j = 0; + for (int i = 0; i < N; ) + { + int remain = 0; // 记录当前总的油量 + for (j = 0; j < N; j++) // 向前走j个站点后到达站点k + { + int k = (i + j) % N; // 环形, 可能 i + j可能比较大 + remain += gas[k] - cost[k]; + if (remain < 0) break; + } + if (j == N) return i; // 恰好走了一圈 + i = i + j + 1; // 跳到下一个有可能的i 继续枚举 + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + vector gas = {1, 2, 3, 4, 5}; + vector cost = {3, 4, 5, 1, 2}; + auto res = sol.canCompleteCircuit(gas, cost); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode136-single-number_bit_operation.cpp b/cpp-leetcode/leetcode136-single-number_bit_operation.cpp new file mode 100644 index 00000000..ec4d733a --- /dev/null +++ b/cpp-leetcode/leetcode136-single-number_bit_operation.cpp @@ -0,0 +1,24 @@ +#include +#include +using namespace std; + +class Solution { +public: + int singleNumber(vector& nums) { + if (nums.empty()) return 0; + const int len = nums.size(); + int res = nums.front(); + for (int i = 1; i < len; i++) + res = res ^ nums[i]; /* 基于异或^运算来做成对抵消 */ + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {4, 1, 2, 1, 2}; + printf("%d ", sol.singleNumber(nums)); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution1.cpp b/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution1.cpp new file mode 100644 index 00000000..8e0cd3fb --- /dev/null +++ b/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution1.cpp @@ -0,0 +1,30 @@ +#include +#include +using namespace std; + +class Solution { +public: + int singleNumber(vector& nums) { + int res = 0; + for (int i = 0; i < 32; i++) /* nums数组中每个数nums[i] 都是int 32 */ + { + int sum = 0; + for (int num : nums) + { + sum += ((num >> i) & 1); /* 取出第i位二进制位的值, 并累加各位数字(0/1), 假如没出现落单的数, 根据题意目前拿到的数都出现了3次, 累加和必然能被3整除. 假如不能整除, 说明那个落单的数已出现, 且落单的那个数的第i位是1不是0. */ + } + if (sum % 3 == 1) + res += (1 << i); /* 既然知道了落单的数中哪些二进制为是1, 那么对数位是1的二进制位加权求和即为该数 */ + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {0, 1, 0, 1, 0, 1, 99}; + printf("%d ", sol.singleNumber(nums)); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution2.cpp b/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution2.cpp new file mode 100644 index 00000000..70a9fff0 --- /dev/null +++ b/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution2.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +class Solution { +public: + int singleNumber(vector& nums) { + vector bits(32); + + for (auto num : nums) + { + for (int i = 0; i < 32; i++) + { + bits[i] += (num >> i) & 1; // num>>i: [二进制下移位]丢掉num末尾i个bit位, + // digit & 1 用于高位清零, 检查数字的最后一位是否为偶数, 比number%2速度快 + // 于是最后的作用是将第i位转换为二进制的 0/1 + } + } + + int res = 0; + for (int i = 0; i < 32; i++) + { + res += (bits[i] % 3) << i; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {0, 1, 0, 1, 0, 1, 99}; + printf("%d ", sol.singleNumber(nums)); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution3.cpp b/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution3.cpp new file mode 100644 index 00000000..edd27cd5 --- /dev/null +++ b/cpp-leetcode/leetcode137-single-number-ii_bit_operation_solution3.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; + +class Solution { +public: + int singleNumber(vector &nums) + { + int bits1 = 0, bits2 = 0; + for (int num : nums) + { + int bits1_new = 0, bits2_new = 0; + for (int i = 0; i < 32; i++) + { + int hi = (bits1 >> i) & 1; + int low = (bits2 >> i) & 1; + int sum = (hi * 2 + low + ((num >> i) & 1)) % 3; + bits1_new += (sum / 2) << i; + bits2_new += (sum % 2) << i; + } + bits1 = bits1_new, bits2 = bits2_new; + } + + int res = 0; + for (int i = 0; i < 32; i++) + { + res += ((bits2 >> i) & 1) << i; + } + return res; + } +}; + +int main() +{ + Solution sol; + vector nums = { 0,1,0,1,0,1,99 }; + printf("%d ", sol.singleNumber(nums)); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode139-word-break_dp1.cpp b/cpp-leetcode/leetcode139-word-break_dp1.cpp new file mode 100644 index 00000000..69f0623a --- /dev/null +++ b/cpp-leetcode/leetcode139-word-break_dp1.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + /** 题意: 1 <= s.length <= 300, 故不需要判空 */ + const int len = s.size(); + bool dp[len + 1]; + dp[0] = true; + fill(dp + 1, dp + len + 1, false); + for (int i = 0; i < len; i++) /* 双指针i和j */ + { + for (int j = i + 1; j <= len; j++) + { + string subs = s.substr(i, j - i); /* 对于字符串s中[i:j]范围内的子串subs, 都去判断一下dp[i]是不是true以及subs在不在数组wordDict中。 */ + if (find(wordDict.begin(), wordDict.end(), subs) != wordDict.end() && dp[i]) + dp[j] = true; + } + } + return dp[len]; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "applepenapple"; + vector wordDict = {"apple", "pen"}; + // 预期输出: true + auto res = sol.wordBreak(s, wordDict); + cout << (res == true ? "true" : "false"); + + return 0; +} diff --git a/cpp-leetcode/leetcode139-word-break_dp2.cpp b/cpp-leetcode/leetcode139-word-break_dp2.cpp new file mode 100644 index 00000000..c831781a --- /dev/null +++ b/cpp-leetcode/leetcode139-word-break_dp2.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +// 更快的dp, 时间复杂度: O(N * M), N是字符串s的长度, M是数组wordDict的长度 +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + const int len = s.size(); + bool dp[len + 1]; + dp[0] = true; + fill(dp + 1, dp + len + 1, false); + for (int i = 1; i <= len; i++) + { + if (!dp[i - 1]) continue; /* dp[i - 1]是false时, 是无法完成拆分的, 指针i跳到下一个index */ + for (auto& word : wordDict) /* 能执行到这, 说明子串s[0:i-1]都是能拆分的。遍历数组wordDict, 尝试从s中取出新的子串(这个子串的长度和当前循环的word相等, 即s[i-1:j]), 如果这个子串恰好与当前word相同, 那么子串s[0:j]也都是能拆分的。重复以上过程~ */ + { + int j = i - 1 + word.size(); + if (j <= len && s.substr(i - 1, word.size()) == word) /* 指针j也不能越界, 即j <= len */ + dp[j] = true; + } + } + return dp[len]; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "applepenapple"; + vector wordDict = {"apple", "pen"}; + // 预期输出: true + auto res = sol.wordBreak(s, wordDict); + cout << (res == true ? "true" : "false"); + + return 0; +} diff --git a/cpp-leetcode/leetcode139-word-break_trie_and_dfs.cpp b/cpp-leetcode/leetcode139-word-break_trie_and_dfs.cpp new file mode 100644 index 00000000..56e149a6 --- /dev/null +++ b/cpp-leetcode/leetcode139-word-break_trie_and_dfs.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; + +struct TrieNode { + TrieNode* next[26]; + bool isEnd; + TrieNode() + { + for (int i = 0; i < 26; i++) + next[i] = nullptr; + isEnd = false; + } +}; +class Solution { + TrieNode* root; + int failMemo[301]; // 记录dfs中失败时对应的s中的index +public: + bool wordBreak(string s, vector& wordDict) { + root = new TrieNode(); + // 建树 + for (auto& word : wordDict) + { + TrieNode* p = root; + for (auto& ch : word) + { + if (p->next[ch - 'a'] == nullptr) + p->next[ch - 'a'] = new TrieNode(); + p = p->next[ch - 'a']; + } + p->isEnd = true; + } + return dfs(s, 0); + } + bool dfs(string& s, int startPos) + { + if (failMemo[startPos] == 1) return false; + if (startPos == s.size()) return true; + TrieNode* p = root; + for (int i = startPos; i < s.size(); i++) + { + if (p->next[s[i] - 'a'] != nullptr) + { + p = p->next[s[i] - 'a']; + if (p->isEnd == true && dfs(s, i+1)) + return true; + } + else break; + } + failMemo[startPos] = 1; + return false; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "applepenapple"; + vector wordDict = {"apple", "pen"}; + // 预期输出: true + auto res = sol.wordBreak(s, wordDict); + cout << (res == true ? "true" : "false"); + + return 0; +} diff --git a/cpp-leetcode/leetcode14-longest-common-prefix.cpp b/cpp-leetcode/leetcode14-longest-common-prefix.cpp new file mode 100644 index 00000000..d2528972 --- /dev/null +++ b/cpp-leetcode/leetcode14-longest-common-prefix.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + // 思路: 先将vector中第1个string 作为prefix初始值,然后取后面的string进行判断,更新prefix + if(strs.empty()) return ""; + string prefix = strs.front(); // strs[0] + + for (int i = 1; i < strs.size(); i++) + { + const string& curStr = strs[i]; + + int k = 0; + while (k < min(prefix.length(), curStr.length())) + { + if (prefix[k] != curStr[k]) + { + break; // 每次都找当前最新的prefix与当前str的公共前缀 + } + k++; + } + prefix = prefix.substr(0, k); + } + + return prefix; + } +}; + +// Test +int main() +{ + Solution sol; + vector input = {"flower","flow","flight"}; + string res = sol.longestCommonPrefix(input); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode140-word-break-ii_trie_and_dfs.cpp b/cpp-leetcode/leetcode140-word-break-ii_trie_and_dfs.cpp new file mode 100644 index 00000000..ee09acfb --- /dev/null +++ b/cpp-leetcode/leetcode140-word-break-ii_trie_and_dfs.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + struct TrieNode + { + TrieNode* next[26]; + bool isEnd; + TrieNode() + { + isEnd = false; + for (int i = 0; i < 26; i++) + next[i] = nullptr; + } + // ~TrieNode() + // { + // for (auto node : next) delete node; + // } + }; + TrieNode* root; + int failMemo[301]; // 记录dfs中失败时对应的s中的index + vector res; +public: + vector wordBreak(string s, vector& wordDict) { + root = new TrieNode(); + for (auto word : wordDict) + { + TrieNode* node = root; + for (auto ch : word) + { + if (node->next[ch - 'a'] == nullptr) + node->next[ch - 'a'] = new TrieNode(); + node = node->next[ch - 'a']; + } + node->isEnd = true; + } + + vector curWords; + dfs(s, 0, curWords); + return res; + } + + bool dfs(string& s, int startPos, vector& curWords) + { + if (failMemo[startPos] == 1) return false; + if (startPos == s.size()) + { + string sen; // 句子 + for (auto& word : curWords) + sen += word + " "; + sen.pop_back(); // 删掉最后一个空格 + res.push_back(sen); + return true; + } + + TrieNode* node = root; + bool flag = false; + for (int i = startPos; i < s.size(); i++) + { + if (node->next[s[i] - 'a'] != nullptr) + { + node = node->next[s[i] - 'a']; + if (node->isEnd == true) + { + curWords.push_back(s.substr(startPos, i - startPos + 1)); + if (dfs(s, i + 1, curWords)) + flag = true; + curWords.pop_back(); + } + } + else break; + } + + if (flag == false) failMemo[startPos] = 1; + return flag; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "catsanddog"; + vector wordDict = {"cat", "cats", "and", "sand", "dog"}; + auto res = sol.wordBreak(s, wordDict); /* 我安装的vs code或minGW或gdb有bug, 结果是{}. 用Dev C++运行正常 */ + for (auto& path : res) + cout << path << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode141-linked-list-cycle.cpp b/cpp-leetcode/leetcode141-linked-list-cycle.cpp new file mode 100644 index 00000000..ffbbe8e6 --- /dev/null +++ b/cpp-leetcode/leetcode141-linked-list-cycle.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode *slow = head; + ListNode *fast = head; + + while(fast != NULL && fast->next != NULL) /* 排除: 当原链表没有节点和只有一个节点时,是无法构成环的 */ + { + slow = slow->next; + fast = fast -> next -> next; // 此处也明显需要 fast->next != NULL + if(slow == fast) + return true; + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *n1 = new ListNode(3); + ListNode *n2 = new ListNode(2); + ListNode *n3 = new ListNode(0); + ListNode *n4 = new ListNode(-4); + n1->next = n2; + n2->next = n1; + n2->next = n3; + n3->next = n4; + n4->next = n2; + + bool hasCycle = sol.hasCycle(n1); + cout << (hasCycle == true ? "true" : "false") << endl; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode142-cycle-list-2_fast_slow_pointer_solution.cpp b/cpp-leetcode/leetcode142-cycle-list-2_fast_slow_pointer_solution.cpp new file mode 100644 index 00000000..ff454ef8 --- /dev/null +++ b/cpp-leetcode/leetcode142-cycle-list-2_fast_slow_pointer_solution.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + ListNode* slow = head; + ListNode* fast = head; + + while (fast != NULL && fast->next != NULL) + { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) + break; + } + /* 处理上一轮遍历结束时的临界情况 */ + if (fast == NULL || fast->next == NULL) + return NULL; + slow = head; + while (fast != slow) /* 只要还没相遇就继续循环 */ + { + slow = slow->next; + fast = fast->next; /* 此轮循环每次只走一步 */ + } + return slow; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *n1 = new ListNode(3); + ListNode *n2 = new ListNode(2); + ListNode *n3 = new ListNode(0); + ListNode *n4 = new ListNode(-4); + n1->next = n2; + n2->next = n1; + n2->next = n3; + n3->next = n4; + n4->next = n2; + + ListNode* meet = sol.detectCycle(n1); + cout << meet->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode142-cycle-list-2_set_solution.cpp b/cpp-leetcode/leetcode142-cycle-list-2_set_solution.cpp new file mode 100644 index 00000000..dfcc1a88 --- /dev/null +++ b/cpp-leetcode/leetcode142-cycle-list-2_set_solution.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + set st; + ListNode* p = head; + ListNode* res = NULL; + + while(p != NULL) + { + if(st.insert(p).second == false) /* 向set中插入node失败,说明是第2次出现了,第1个出现第2次的 */ + { + res = p; + return res; + } + p = p -> next; + } + return NULL; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *n1 = new ListNode(3); + ListNode *n2 = new ListNode(2); + ListNode *n3 = new ListNode(0); + ListNode *n4 = new ListNode(-4); + n1->next = n2; + n2->next = n1; + n2->next = n3; + n3->next = n4; + n4->next = n2; + + ListNode* meet = sol.detectCycle(n1); + cout << meet->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode142-cycle-list-2_solution3_only_for_leetcode_cpp.cpp b/cpp-leetcode/leetcode142-cycle-list-2_solution3_only_for_leetcode_cpp.cpp new file mode 100644 index 00000000..39ffba5a --- /dev/null +++ b/cpp-leetcode/leetcode142-cycle-list-2_solution3_only_for_leetcode_cpp.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + while(head) { + if(!less()(head, head->next)) { + return head->next; + } + head = head->next; + } + return NULL; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *n1 = new ListNode(3); + ListNode *n2 = new ListNode(2); + ListNode *n3 = new ListNode(0); + ListNode *n4 = new ListNode(-4); + n1->next = n2; + n2->next = n1; + n2->next = n3; + n3->next = n4; + n4->next = n2; + + ListNode* meet = sol.detectCycle(n1); + cout << meet->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode143-reorder-list_even_odd_analysis.cpp b/cpp-leetcode/leetcode143-reorder-list_even_odd_analysis.cpp new file mode 100644 index 00000000..8eab48b9 --- /dev/null +++ b/cpp-leetcode/leetcode143-reorder-list_even_odd_analysis.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + void reorderList(ListNode* head) { + auto fakeNode = new ListNode(-1); + vector arr = getNewArr(head); + fakeNode->next = arr[0]; + for (int i = 0; i < arr.size() - 1; i++) + arr[i]->next = arr[i+1]; + arr.back()->next = nullptr; + head = fakeNode->next; + } + vector getNewArr(ListNode* head) + { + vector oriArr; + vector newArr; + auto p = head; + while (p) + { + oriArr.push_back(p); + p = p->next; + } + int count = oriArr.size(); + for (int i = 0; i <= oriArr.size()/2 + 1; i++) + { + if (count >= 2) + { + newArr.push_back(oriArr[i]); + newArr.push_back(oriArr[oriArr.size() - 1 - i]); + count -= 2; + } + } + if (count == 1) + newArr.push_back(oriArr[oriArr.size()/2]); + return newArr; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(1); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(4); + head->next->next->next->next = NULL; + + sol.reorderList(head); + ListNode* p = head; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1436-destination-city_hashmap.cpp b/cpp-leetcode/leetcode1436-destination-city_hashmap.cpp new file mode 100644 index 00000000..190eb9b8 --- /dev/null +++ b/cpp-leetcode/leetcode1436-destination-city_hashmap.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string destCity(vector>& paths) { + unordered_map dict; + string res; + for (auto& path : paths) + { + dict[path[0]] += -1; + dict[path[1]] += 1; + // 记录 sum = 1的key + for (auto kvp : dict) + { + if (kvp.second == 1) res = kvp.first; /* 无论何时都只有一个key为1的城市 */ + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> paths = {{"London","New York"},{"New York","Lima"},{"Lima","Sao Paulo"}}; + auto res = sol.destCity(paths); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1436-destination-city_two_set.cpp b/cpp-leetcode/leetcode1436-destination-city_two_set.cpp new file mode 100644 index 00000000..7239753d --- /dev/null +++ b/cpp-leetcode/leetcode1436-destination-city_two_set.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string destCity(vector>& paths) { + unordered_set startSet; + unordered_set endSet; + for (auto& path : paths) + { + startSet.insert(path[0]); + endSet.insert(path[1]); + } + string res; + for (auto& city : endSet) + { + if (startSet.count(city) == 0) + res = city; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> paths = {{"London","New York"},{"New York","Lima"},{"Lima","Sao Paulo"}}; + auto res = sol.destCity(paths); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_deque_with_extra_struct.cpp b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_deque_with_extra_struct.cpp new file mode 100644 index 00000000..4a884a8b --- /dev/null +++ b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_deque_with_extra_struct.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +struct Pack { + int op; /* 0, to visit (表示还需要后续处理); 1, visited/print/save (不需要后续处理了, 就想取里面的值) */ + TreeNode* node; + Pack(int op, TreeNode* node) { + this->op = op; + this->node = node; + } +}; + +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + deque st; + st.push_front(new Pack(0, root)); + + while (!st.empty()) + { + Pack* cur = st.front(); // 先front(), 再pop + st.pop_front(); + if (cur->node == nullptr) + continue; /* 此时该 TreeNode的val/left/right都没法取到, 故不需要处理 */ + if (cur->op == 1) + res.push_back(cur->node->val); + else + { + /* 基于deque的辅助栈, 要求每一个结点及其子树的输出(遍历)顺序: 根 左 右, 于是放入顺序遍历顺序: 右 左 根 */ + st.push_front(new Pack(0, cur->node->right)); + st.push_front(new Pack(0, cur->node->left)); + st.push_front(new Pack(1, cur->node)); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.preorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_recursive1.cpp b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_recursive1.cpp new file mode 100644 index 00000000..bc52b08c --- /dev/null +++ b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_recursive1.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 前序遍历顺序: 根 左 右 */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + preOrder(root, res); + return res; + } + void preOrder(TreeNode* root, vector& res) + { + if (root == nullptr) return; + res.push_back(root->val); + preOrder(root->left, res); + preOrder(root->right, res); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.preorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_recursive2.cpp b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_recursive2.cpp new file mode 100644 index 00000000..48ec7eb0 --- /dev/null +++ b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_recursive2.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 前序遍历顺序: 根 左 右 */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + if(root == NULL) + return {}; + + vector res; + res.push_back(root->val); + vector left = preorderTraversal(root->left); + vector right = preorderTraversal(root->right); + // 合并各个数组到res数组 + res.insert(res.end(), left.begin(), left.end()); + res.insert(res.end(), right.begin(), right.end()); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.preorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_stack.cpp b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_stack.cpp new file mode 100644 index 00000000..5b92c61e --- /dev/null +++ b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_stack.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 前序遍历顺序: 根 左 右 */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + stack st; /* 基于stack的辅助栈, 输出(遍历)顺序: 根 左 右, 于是放入顺序遍历顺序: 右 左 根 */ + // 遍历 part1 - 根结点 + if (root != NULL) + st.push(root); + + while (!st.empty()) + { + TreeNode* p = st.top(); + res.push_back(p->val); // 只要栈里有node,就输出栈顶元素到res数组 + st.pop(); + + // 遍历 part2 - 右子树 + if (p -> right != NULL) + st.push(p -> right); + // 遍历 part3 - 左子树 + if (p -> left != NULL) + st.push(p -> left); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.preorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_stack_using_deque.cpp b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_stack_using_deque.cpp new file mode 100644 index 00000000..30af08b4 --- /dev/null +++ b/cpp-leetcode/leetcode144-binary-tree-preorder-traversal_stack_using_deque.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 前序遍历顺序: 根 左 右 */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + deque st; /* 基于deque的辅助栈, 输出(遍历)顺序: 根 左 右, 于是放入顺序遍历顺序: 右 左 根 */ + // 遍历 part1 - 根结点 + if (root != NULL) + st.push_front(root); + + while (!st.empty()) + { + TreeNode* p = st.front(); + res.push_back(p->val); // 只要栈里有node,就输出栈顶元素到res数组 + st.pop_front(); + + // 遍历 part2 - 右子树 + if (p -> right != NULL) + st.push_front(p -> right); + // 遍历 part3 - 左子树 + if (p -> left != NULL) + st.push_front(p -> left); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.preorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_deque_with_extra_struct.cpp b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_deque_with_extra_struct.cpp new file mode 100644 index 00000000..da1ff31a --- /dev/null +++ b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_deque_with_extra_struct.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +struct Pack { + int op; /* 0, to visit (表示还需要后续处理); 1, visited/print/save (不需要后续处理了, 就想取里面的值) */ + TreeNode* node; + Pack(int op, TreeNode* node) { + this->op = op; + this->node = node; + } +}; + +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + vector res; + deque st; + st.push_front(new Pack(0, root)); + + while (!st.empty()) + { + Pack* cur = st.front(); // 先front(), 再pop + st.pop_front(); + if (cur->node == nullptr) + continue; + if (cur->op == 1) + res.push_back(cur->node->val); + else + { + /* 基于deque的辅助栈, 要求每一个结点及其子树的输出(遍历)顺序: 左 右 根, 于是放入顺序遍历顺序: 根 右 左 */ + st.push_front(new Pack(1, cur->node)); + st.push_front(new Pack(0, cur->node->right)); + st.push_front(new Pack(0, cur->node->left)); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.postorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_recursive.cpp b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_recursive.cpp new file mode 100644 index 00000000..6966518d --- /dev/null +++ b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_recursive.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 后序遍历顺序: 左右根 */ +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + if(root == NULL) + return {}; + + vector res = postorderTraversal(root->left); + vector right = postorderTraversal(root->right); + res.insert(res.end(), right.begin(), right.end()); + res.push_back(root->val); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.postorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_recursive2.cpp b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_recursive2.cpp new file mode 100644 index 00000000..e806b3c9 --- /dev/null +++ b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_recursive2.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + if(root == NULL) return {}; + vector res; + postOrder(root, res); + return res; + } + void postOrder(TreeNode* root, vector& res) + { + if (!root) return; + postOrder(root->left, res); + postOrder(root->right, res); + res.push_back(root->val); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.postorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_stack_using_deque.cpp b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_stack_using_deque.cpp new file mode 100644 index 00000000..1558fdc2 --- /dev/null +++ b/cpp-leetcode/leetcode145-binary-tree-postorder-traversal_stack_using_deque.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode +{ + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 后序遍历顺序: 左右根 */ +class Solution +{ +public: + vector postorderTraversal(TreeNode *root) + { + if (root == NULL) + return {}; + vector res; + deque st; /* 基于deque的辅助栈, 输出(遍历)顺序: 左 右 根 */ + TreeNode* p = root; + while (p != NULL || !st.empty()) + { + while (p != NULL) + { + st.push_front(p->left); + res.push_back(p->val); + p = p->right; + } + p = st.front(); + st.pop_front(); + } + reverse(res.begin(), res.end()); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.postorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode146-implement-LRUcache.cpp b/cpp-leetcode/leetcode146-implement-LRUcache.cpp new file mode 100644 index 00000000..cb4ab457 --- /dev/null +++ b/cpp-leetcode/leetcode146-implement-LRUcache.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include +using namespace std; + +class LRUCache { +public: + LRUCache(int capacity) { + cap = capacity; + } + + int get(int key) { + const auto it = map.find(key); + if (it == map.cend()) return -1; + + // 使用splice函数将这个entry移到缓存的最前面 + caches.splice(caches.begin(), caches, it->second); + return it->second->second; + } + + void put(int key, int value) { + const auto it = map.find(key); + + if (it != map.cend()) { // 如果key已经存在于map中 + // 更新kv pair中的value + it->second->second = value; + // 使用splice函数将这个entry移到缓存的最前面 + caches.splice(caches.begin(), caches, it->second); + return; + } + + // 如果(key不存在,且)容量到上限时,则删除最早的entry + if (caches.size() == cap) { + const auto& oldestPair = caches.back(); + map.erase(oldestPair.first); // 从map中删除最早的entry的key + caches.pop_back(); + } + + // 使用list容器的emplace_front函数将entry插入到cache的第一个位置并更新mapping. + caches.emplace_front(key, value); + map[key] = caches.begin(); + } + +private: + int cap; + list> caches; + unordered_map>::iterator> map; // list>::iterator是迭代器位置,类似于"指针" +}; + +/** +* Your LRUCache object will be instantiated and called as such: +* LRUCache obj = new LRUCache(capacity); +* int paramap1 = obj.get(key); +* obj.put(key,value); +*/ + +// Test +int main() +{ + LRUCache* lRUCache = new LRUCache(2); + lRUCache->put(1, 1); // 缓存是 {1=1} + lRUCache->put(2, 2); // 缓存是 {1=1, 2=2} + int res1 = lRUCache->get(1); // 返回 1 + cout << res1 << endl; + lRUCache->put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3} + int res2 = lRUCache->get(2); // 返回 -1 (未找到) + cout << res2 << endl; + lRUCache->put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3} + int res3 = lRUCache->get(1); // 返回 -1 (未找到) + cout << res3 << endl; + int res4 = lRUCache->get(3); // 返回 3 + cout << res4 << endl; + int res5 = lRUCache->get(4); // 返回 4 + cout << res5 << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode147-insertion-sort-list.cpp b/cpp-leetcode/leetcode147-insertion-sort-list.cpp new file mode 100644 index 00000000..a3753cbc --- /dev/null +++ b/cpp-leetcode/leetcode147-insertion-sort-list.cpp @@ -0,0 +1,62 @@ +#include +#include +using namespace std; +/** Definition for singly-linked list. */ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* insertionSortList(ListNode* head) { + ListNode* fakeNode = new ListNode(INT_MIN); /* 输入的链表中有0、负数之类的,这里用 INT_MAX比较合理 */ + ListNode *p = fakeNode, *q = fakeNode; + ListNode* cur = head; + while (cur) + { + if (q->val < cur->val) + { + q->next = cur; + q = q->next; + cur = cur->next; + } + else + { + q->next = cur->next; + while (p->next != nullptr && p->next->val < cur->val) + p = p->next; /* 指针p 不断向前, 找需要插入的位置, 找到时停下 */ + cur->next = p->next; + p->next = cur; + p = fakeNode; /* 插入排序: 每来1个新数, 都需要将它与已排序的每一个数都比较一次, 所以需要拉到开头供下次使用 */ + cur = q->next; + } + } + return fakeNode->next; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(4); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(1); + head->next->next->next->next = NULL; + + auto res = sol.insertionSortList(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1470-shuffle-the-array_two_vectors.cpp b/cpp-leetcode/leetcode1470-shuffle-the-array_two_vectors.cpp new file mode 100644 index 00000000..f0f81873 --- /dev/null +++ b/cpp-leetcode/leetcode1470-shuffle-the-array_two_vectors.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector shuffle(vector& nums, int n) { + vector part1(nums.begin(), nums.begin() + n); + vector part2(nums.begin() + n, nums.end()); + for (int i = 0; i < n; i++) + { + nums[2*i] = part1[i]; + nums[2*i + 1] = part2[i]; + } + return nums; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 5, 1, 3, 4, 7}; + int k = 3; + + auto res = sol.shuffle(nums, k); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode15-3sum.cpp b/cpp-leetcode/leetcode15-3sum.cpp new file mode 100644 index 00000000..02373dd1 --- /dev/null +++ b/cpp-leetcode/leetcode15-3sum.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> threeSum(vector &nums) + { + int len = nums.size(); + vector> res; + sort(nums.begin(), nums.end()); // 先进行排序(从小到大) + if (nums.empty() || nums.front() > 0 || nums.back() < 0) /* 处理临界情况 */ + { + return {}; + } + + for (int i = 0; i < len - 2; i++) + { + if (nums[i] > 0) + { + break; + } + if (i > 0 && nums[i] == nums[i - 1]) /* 注意此处的nums[i] == nums[i-1], 需要覆盖尽量多的case。当循环没到达尾部,且相邻位置出现相等的数组元素时, 跳过 */ + { + continue; + } + + int target = 0 - nums[i]; // a+b = -c + int j = i + 1; + int k = len - 1; + + while (j < k) + { + if (nums[j] + nums[k] == target) + { + res.push_back({nums[i], nums[j], nums[k]}); + while (j < k && nums[j] == nums[j + 1]) /* 注意此处的 j input = {-1, 0, 1, 2, -1, -4}; // {0,0,0} + vector> res = sol.threeSum(input); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode151-reverse-words_solution1.cpp b/cpp-leetcode/leetcode151-reverse-words_solution1.cpp new file mode 100644 index 00000000..6b804e2a --- /dev/null +++ b/cpp-leetcode/leetcode151-reverse-words_solution1.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string reverseWords(string s) { + int len0 = s.size(); + string res = ""; + // 1.标准化/归约 + int preSpaceCount = 0; + for (int i = 0; i < len0; i++) + { + if (s[0] == ' ' && s[i] == ' ') preSpaceCount++; + else break; + } + s = s.substr(preSpaceCount, len0 - preSpaceCount); + int tailSpaceCount = 0; + for (int i = s.size() - 1; i >= 0; i--) + { + if (s.back() == ' ' && s[i] == ' ') tailSpaceCount++; + else break; + } + s = s.substr(0, s.size() - tailSpaceCount); + // 把word放进vector + vector vect; + istringstream temp(s); // 类似于cin, 以空格为分隔符将原字符串中的子字符串保存 + while(temp >> s) + vect.push_back(s); + + for (int i = vect.size() - 1; i >= 0; i--) + { + if (i > 0) res += vect[i] + " "; + if (i == 0) res += vect[i]; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "the sky is blue"; + auto res = sol.reverseWords(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1518_water-bottles_simulation.cpp b/cpp-leetcode/leetcode1518_water-bottles_simulation.cpp new file mode 100644 index 00000000..4f2508bd --- /dev/null +++ b/cpp-leetcode/leetcode1518_water-bottles_simulation.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int numWaterBottles(int bot, int exc) { /* bot: 一开始酒的瓶数, exc: 换一瓶新酒需要的空瓶数 */ + int res = bot; + while (bot >= exc) + { + res += bot/exc; // 当前次循环可以新换来的酒的瓶数 + bot = bot/exc + bot % exc; /* 更新总的酒瓶数: 新换来的酒喝完后就成了空瓶, 与当前没用完的酒瓶放在一起, 为下一轮循环做准备 */ + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int bot = 24; + int exc = 4; + auto res = sol.numWaterBottles(bot, exc); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode152-maximum-product-subarray_dp_no_array.cpp b/cpp-leetcode/leetcode152-maximum-product-subarray_dp_no_array.cpp new file mode 100644 index 00000000..01a3072a --- /dev/null +++ b/cpp-leetcode/leetcode152-maximum-product-subarray_dp_no_array.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxProduct(vector& nums) { + int res = nums[0]; /* 1 <= nums.length <= 2 * 10^4, -10 <= nums[i] <= 10 */ + int f = nums[0]; // f: 记录最大值f[i], g: 记录最小值g[i] + int g = nums[0]; + const int N = nums.size(); + for (int i = 1; i < N; i++) + { + int a_i = nums[i]; + int fa = f*a_i; + int ga = g*a_i; + f = max(a_i, max(fa, ga)); + g = min(a_i, min(fa, ga)); + res = max(res, f); // 更新最终的最大值 + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 3, -2, 4}; + auto res = sol.maxProduct(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode16-3sum-closest-optimize.cpp b/cpp-leetcode/leetcode16-3sum-closest-optimize.cpp new file mode 100644 index 00000000..f96eceac --- /dev/null +++ b/cpp-leetcode/leetcode16-3sum-closest-optimize.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + int closest = nums[0] + nums[1] + nums[2]; + int gap = abs(closest - target); + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size() - 2; i++) { /* 注意循环的上界, 需要给后两个数留位置 */ + if (nums[i] * 3 > target) + return min(closest, nums[i] + nums[i + 1] + nums[i + 2]); /* 优化 */ + int left = i + 1, right = nums.size() - 1; + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + int curGap = abs(sum - target); + if (gap > curGap) { + gap = curGap; + closest = sum; + } + if (sum < target) + left++; + else right--; + } + } + return closest; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-1,2,1,-4}; + int target = 1; + auto res = sol.threeSumClosest(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode16-3sum-closest.cpp b/cpp-leetcode/leetcode16-3sum-closest.cpp new file mode 100644 index 00000000..446ce5db --- /dev/null +++ b/cpp-leetcode/leetcode16-3sum-closest.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int threeSumClosest(vector& nums, int target) { + int closest = nums[0] + nums[1] + nums[2]; + int gap = abs(closest - target); + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size() - 2; i++) { /* 注意循环的上界, 需要给后两个数留位置 */ + int left = i + 1, right = nums.size() - 1; + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + int curGap = abs(sum - target); + if (gap > curGap) { + gap = curGap; + closest = sum; + } + if (sum < target) + left++; + else right--; + } + } + return closest; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-1,2,1,-4}; + int target = 1; + auto res = sol.threeSumClosest(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode160-intersection-of-two-linked-list.cpp b/cpp-leetcode/leetcode160-intersection-of-two-linked-list.cpp new file mode 100644 index 00000000..a713a25b --- /dev/null +++ b/cpp-leetcode/leetcode160-intersection-of-two-linked-list.cpp @@ -0,0 +1,76 @@ +#include +using namespace std; +struct ListNode +{ + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + int getLen(ListNode *head) + { + int count = 0; + ListNode *p = head; + while (p != NULL) + { + count++; + p = p->next; + } + return count; + } + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) + { + + if (headA == NULL || headB == NULL) + return NULL; + int len1 = getLen(headA); + int len2 = getLen(headB); + + if (len1 >= len2) + { + int gap = len1 - len2; + while (gap--) + headA = headA->next; + } + else + { + int gap = len2 - len1; + while (gap--) + headB = headB->next; + } + // 遍历headA 和 headB,遇到相同则直接返回 + while (headA != NULL) { + if (headA == headB) { + return headA; + } + headA = headA->next; + headB = headB->next; + } + return NULL; + } +}; + +// 以下为测试部分 +int main() +{ + ListNode *pA = new ListNode(1); + ListNode *p1 = new ListNode(2); + ListNode *p2 = new ListNode(3); + ListNode *pB = new ListNode(4); + ListNode *p3 = new ListNode(5); + ListNode *p4 = new ListNode(6); + ListNode *p5 = new ListNode(7); + pA->next = p1; + p1->next = p2; + p2->next = p4; + pB->next = p3; + p3->next = p4; + p4->next = p5; + p5->next = NULL; + Solution sol; + ListNode *pOut = sol.getIntersectionNode(pA, pB); + cout << pOut->val << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode160-knowledge.cpp b/cpp-leetcode/leetcode160-knowledge.cpp new file mode 100644 index 00000000..ac742931 --- /dev/null +++ b/cpp-leetcode/leetcode160-knowledge.cpp @@ -0,0 +1,90 @@ +// list.c, 参考: 正月点灯笼(黄浩杰)的实现 +#include +#include + +typedef struct Node +{ + int value; + struct Node *next; +} Node; + +int get_list_length(Node *list) +{ + Node *p = list; + int length = 0; + while (p != NULL) + { + ++length; + p = p->next; + } + return length; +} + +/* 先移动gapLen的距离 */ +Node* relocate_first_node(Node *list, int offset) +{ + Node *p = list; + int i; + for (i = 0; i < offset; i++) + { + p = p->next; + } + return p; +} + +Node* find_common_node(Node *list1, Node *list2) +{ + int length1 = get_list_length(list1); + int length2 = get_list_length(list2); + Node *long_list = list1; + Node *short_list = list2; + if (length2 > length1) + { + long_list = list2; + short_list = list1; + } + + int offset = abs(length1 - length2); + Node *p1 = relocate_first_node(long_list, offset); + Node *p2 = short_list; + while (p1 != NULL) + { + if (p1 == p2) + { + return p1; + } + + p1 = p1->next; + p2 = p2->next; + } + + return NULL; +} + +int main() +{ + Node n1, n2, n3, n4, n5, n6, n7; + n1.value = 1; + n2.value = 2; + n3.value = 3; + n4.value = 4; + n5.value = 5; + n6.value = 6; + n7.value = 7; + n1.next = &n2; + n2.next = &n3; + n3.next = &n4; + n4.next = &n5; + n5.next = &n6; + n6.next = NULL; + n7.next = &n4; + Node* list1 = &n1; + Node* list2 = &n7; + printf("list1 length: %d\n", get_list_length(list1)); + printf("list2 length: %d\n", get_list_length(list2)); + + Node* common = find_common_node(list1, list2); + printf("common node = %d\n", common->value); + + return 0; +} diff --git a/cpp-leetcode/leetcode1636-get-maximum-in-generated-array_solution1.cpp b/cpp-leetcode/leetcode1636-get-maximum-in-generated-array_solution1.cpp new file mode 100644 index 00000000..7d76f9d5 --- /dev/null +++ b/cpp-leetcode/leetcode1636-get-maximum-in-generated-array_solution1.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int getMaximumGenerated(int n) { + vector A(n+1); + A[0] = 0; + if(n >= 1) A[1] = 1; + for (int i = 2; i <= n; i++) + { + if (i % 2 == 0) A[i] = A[i/2]; + else A[i] = A[i/2] + A[i/2 + 1]; + } + auto it = max_element(A.begin(), A.end()); + long res = *it; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int N = 5; + auto res = sol.getMaximumGenerated(N); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode164-maximum-gap_bucket_sort1.cpp b/cpp-leetcode/leetcode164-maximum-gap_bucket_sort1.cpp new file mode 100644 index 00000000..33306339 --- /dev/null +++ b/cpp-leetcode/leetcode164-maximum-gap_bucket_sort1.cpp @@ -0,0 +1,71 @@ +// #include +// #include +// #include +#include +#include +using namespace std; + +class Solution +{ +public: + int maximumGap(vector &num) { + if (num.size() < 2) + return 0; + + int _min = num[0], _max = num[0]; + for (int i = 1; i < num.size(); i++) + { + _min = _min > num[i] ? num[i] : _min; + _max = _max < num[i] ? num[i] : _max; + } + + // 将区间 [_min, _max] 分成n个size 为 (_max -_min)/n 的桶 + int bucket_size = (_max - _min) / num.size() + 1; + + // 遍历剩下的 n-2 个数, 确定它们该放在哪个桶里. + // 当且仅当 (num[i]-_min)/m = k-1 时, num[i] 应该放到第k个桶 B[k] 中 + + vector> buckets((_max - _min) / bucket_size + 1); + // 对每一个桶 B[k], 计算其最大值、最小值, 确定它们该放在哪个桶里 + // 如果桶是空的, 把数据放进去, 不做其他操作 + // 如果桶里只有一个数, 确保这个数 num = _max = _min + for (int i = 0; i < num.size(); i++) + { + int idx = (num[i] - _min) / bucket_size; + if (buckets[idx].empty()) + { + buckets[idx].push_back(num[i]); + buckets[idx].push_back(num[i]); + } + else + { + buckets[idx][0] = buckets[idx][0] > num[i] ? num[i] : buckets[idx][0]; /* 更新当前桶的最大值 */ + buckets[idx][1] = buckets[idx][1] < num[i] ? num[i] : buckets[idx][1]; /* 更新当前桶的最小值 */ + } + } + + // 计算maxGap + int maxGap = 0; + int prev = 0; + for (int i = 1; i < buckets.size(); i++) + { + if (buckets[i].empty()) continue; + int gap = buckets[i][0] - buckets[prev][1]; + maxGap = maxGap > gap ? maxGap : gap; + prev = i; + } + return maxGap; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {3,6,9,1}; + + auto res = sol.maximumGap(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode164-maximum-gap_bucket_sort2.cpp b/cpp-leetcode/leetcode164-maximum-gap_bucket_sort2.cpp new file mode 100644 index 00000000..acc71d0a --- /dev/null +++ b/cpp-leetcode/leetcode164-maximum-gap_bucket_sort2.cpp @@ -0,0 +1,51 @@ +// #include +// #include +// #include +#include +#include +using namespace std; + +class Solution { +public: + int maximumGap(vector& nums) { + int _max = *max_element(nums.begin(), nums.end()); + int _min = *min_element(nums.begin(), nums.end()); + int n = nums.size(); + if(n < 2) return 0; + + int d = max(1, (_max - _min) / (n - 1)); /* 桶间隔 d, 有些桶不需要填 */ + int bucketSize = (_max - _min) / d + 1; + vector> bucket (bucketSize, {-1, -1}); + for(auto i : nums) { + int index = (i - _min) / d; + if (bucket[index].first == -1) { + bucket[index].first = bucket[index].second = i; + } else { + bucket[index].first = min(bucket[index].first, i); + bucket[index].second = max(bucket[index].second, i); + } + } + int res = 0; + int prev = -1; + for (int i = 0; i < bucketSize; i++) { + if (bucket[i].first == -1) continue; + if (prev != -1) { + res = max(res, bucket[i].first - bucket[prev].second); + } + prev = i; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {3,6,9,1}; + + auto res = sol.maximumGap(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode165-compare-version-numbers_split.cpp b/cpp-leetcode/leetcode165-compare-version-numbers_split.cpp new file mode 100644 index 00000000..b88296f3 --- /dev/null +++ b/cpp-leetcode/leetcode165-compare-version-numbers_split.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int compareVersion(string v1, string v2) { + if (v1 == v2) + return 0; + + auto strArr1 = split(v1, '.'); + auto strArr2 = split(v2, '.'); + + int maxLen = strArr1.size() >= strArr2.size() ? strArr1.size() : strArr2.size(); + for (int i = 0; i < maxLen; i++) + { + int digit1 = (i >= strArr1.size()) ? 0 : stoi(strArr1[i]); + int digit2 = (i >= strArr2.size()) ? 0 : stoi(strArr2[i]); + + if (digit1 == digit2) + continue; + + return (digit1 > digit2) ? 1 : -1; + } + + return 0; + } + + vector split(string s, const char sep) + { + if (find(s.begin(), s.end(), sep) == s.end()) + return {s}; + + vector res; + auto firstIt = find(s.begin(), s.end(), sep); + res.push_back(s.substr(0, firstIt - s.begin())); /* 放入字符串s开头到第1个sep字符的子串 */ + for (int i = 0; i < s.size(); i++) + { + string digitStr; + int curSepPos = 0; + int preStartPos = 0; + if (s[i] == sep) + { + curSepPos = i; + preStartPos = curSepPos + 1; + + digitStr = s.substr(preStartPos, curSepPos - preStartPos); + res.push_back(digitStr); + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string version1 = "7.5.2.4", version2 = "7.5.3"; + auto res = sol.compareVersion(version1, version2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode165-compare-version-numbers_stringstream1.cpp b/cpp-leetcode/leetcode165-compare-version-numbers_stringstream1.cpp new file mode 100644 index 00000000..92f75734 --- /dev/null +++ b/cpp-leetcode/leetcode165-compare-version-numbers_stringstream1.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int compareVersion(string v1, string v2) { + if (v1 == v2) return 0; + + istringstream iss1(v1); /* 把每一个stringstream都看作数字+点字符+数字+点字符+... */ + istringstream iss2(v2); + while (iss1 || iss2) + { + char dot; + long num1 = 0, num2 = 0; + if (iss1) iss1 >> num1 >> dot; + if (iss2) iss2 >> num2 >> dot; + if (num1 != num2) + return num1 < num2 ? -1 : 1; + } + return 0; + }; +}; + +// Test +int main() +{ + Solution sol; + string version1 = "7.5.2.4", version2 = "7.5.3"; + auto res = sol.compareVersion(version1, version2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode165-compare-version-numbers_stringstream2.cpp b/cpp-leetcode/leetcode165-compare-version-numbers_stringstream2.cpp new file mode 100644 index 00000000..83065be4 --- /dev/null +++ b/cpp-leetcode/leetcode165-compare-version-numbers_stringstream2.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int compareVersion(string v1, string v2) { + for(auto& ch : v1) + if (ch == '.') ch = ' '; + for(auto& ch : v2) + if (ch == '.') ch = ' '; + + istringstream s1(v1), s2(v2); + while (true) + { + int n1, n2; + if (!(s1 >> n1)) n1 = 0; + if (!(s2 >> n2)) n2 = 0; + if (!s1 && !s2) return 0; + if (n1 < n2) return -1; + if (n1 > n2) return 1; + } + } +}; + +// Test +int main() +{ + Solution sol; + string version1 = "7.5.2.4", version2 = "7.5.3"; + auto res = sol.compareVersion(version1, version2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode165-compare-version-numbers_two_pointers.cpp b/cpp-leetcode/leetcode165-compare-version-numbers_two_pointers.cpp new file mode 100644 index 00000000..1aee1c4e --- /dev/null +++ b/cpp-leetcode/leetcode165-compare-version-numbers_two_pointers.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int compareVersion(string v1, string v2) { + if (v1 == v2) return 0; + + const int len1 = v1.size(), len2 = v2.size(); + int i = 0, j = 0; + while (i < len1 || j < len2) + { + int num1 = 0; // 记录字符串v1中相邻两个dot字符间的数字(不包含首尾的点.字符) + int num2 = 0; // 记录字符串v2中相邻两个dot字符间的数字 + while (i < len1 && v1[i] != '.') + { + int newDigit = v1[i++] - '0'; + num1 = num1 * 10 + newDigit; + } + while (j < len2 && v2[j] != '.') + { + int newDigit = v2[j++] - '0'; + num2 = num2 * 10 + newDigit; + } + if (num1 > num2) return 1; + else if (num1 < num2) return -1; + + i++; + j++; + } + return 0; + } +}; + +// Test +int main() +{ + Solution sol; + string version1 = "7.5.2.4", version2 = "7.5.3"; + auto res = sol.compareVersion(version1, version2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode166-fraction-to-recurring-decimal_solution1.cpp b/cpp-leetcode/leetcode166-fraction-to-recurring-decimal_solution1.cpp new file mode 100644 index 00000000..3c40efa5 --- /dev/null +++ b/cpp-leetcode/leetcode166-fraction-to-recurring-decimal_solution1.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +using namespace std; +/** + * @Author: https://github.com/yanglr + * @Date: 2021-08-17 17:32:27 + * @Title: LeetCode166. 分数到小数 + * @中文题目: 166. 分数到小数 + * @EnglishTitle: 166. Fraction to Recurring Decimal + * @Alias: LC166 - 力扣166 + * @Tag: 数学 + * Created by 极客学长 on 2021-08-17. +*/ +class Solution { +public: + // 使用缩写: A: 分子numerator, D: 分母denominator + string fractionToDecimal(int A, int D) { + if (A == 0) return "0"; + string res; + + // 符号位 + int sign = 1; + if ((A > 0 && D > 0) || (A < 0 && D < 0)) + sign = 1; + else sign = -1; + A = abs(A); + D = abs(D); + long beforeDot = A/D; + if (sign == -1) res.push_back('-'); + res.append(to_string(beforeDot)); + + long rem = A%D; + if (rem == 0) return res; + else res.append("."); + unordered_map dict; // 余数 -> 余数在结果字符串中的index + // 没有除尽且暂时没发现"循环节"时一直loop + while (rem != 0 && dict.find(rem) == dict.end()) + { + dict[rem] = res.size(); // value -> index + int quo = rem*10/D; + res.push_back('0' + quo); + rem = rem*10%D; + } + if (rem == 0) return res; + // 遇到循环节, 循环终止的原因发现了第一个第2次出现的余数 + char firstRepChar = rem; + int repStartIndex = dict[rem]; + res.insert(res.begin() + repStartIndex, '('); + res += ")"; + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int A = 4, D = 333; + auto res = sol.fractionToDecimal(A, D); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode17-letter-combinations-of-a-phone-number_iterate.cpp b/cpp-leetcode/leetcode17-letter-combinations-of-a-phone-number_iterate.cpp new file mode 100644 index 00000000..e604a32b --- /dev/null +++ b/cpp-leetcode/leetcode17-letter-combinations-of-a-phone-number_iterate.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector letterCombinations(string digits) { + vector dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + if(digits == "") return {}; + vector res{""}; + + for(int i=0; i temp; // temp是本轮字符选择完成的结果 + char ch = digits[i]; + string curStr = dict[ch-'0']; + + for(int j = 0; j < curStr.size(); j++) + for(int k = 0; k < res.size(); k++) + { + temp.push_back(res[k]+curStr[j]); // res[k] 是上一轮字符选择的结果 + } + res = temp; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string n = "25"; + vector res = sol.letterCombinations(n); + + for(string s : res) + { + cout << s << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode173-binary-search-tree-iterator_deque.cpp b/cpp-leetcode/leetcode173-binary-search-tree-iterator_deque.cpp new file mode 100644 index 00000000..8cb36bbf --- /dev/null +++ b/cpp-leetcode/leetcode173-binary-search-tree-iterator_deque.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class BSTIterator { + deque st; // 用做stack, top/pop/push 都在尾部进行 +public: + BSTIterator(TreeNode* root) { /* 0 <= Node.val <= 10^6 */ + TreeNode* p = root; + while (p) + { + st.push_back(p); + p = p->left; + } + } + + // 将指针向右移动,然后返回指针处的val + int next() { + auto p = st.back(); + int res = p->val; + TreeNode* node = p->right; // 刚开始时node是栈的top处结点的right子结点 + st.pop_back(); + while (node) + { + st.push_back(node); + node = node->left; + } + return res; + } + // 如果向指针右侧遍历存在数字,则返回 true + bool hasNext() { + return !st.empty(); + } +}; + +// Test +int main() +{ + TreeNode *root = new TreeNode(6); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(8); + TreeNode *n3 = new TreeNode(0); + TreeNode *n4 = new TreeNode(4); + TreeNode *n5 = new TreeNode(7); + TreeNode *n6 = new TreeNode(9); + TreeNode *n7 = new TreeNode(3); + TreeNode *n8 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + + /** + * 你的 BSTIterator 对象会被用以下方式初始化和调用: + * */ + BSTIterator *it = new BSTIterator(root); + int val = it->next(); + cout << val << endl; + bool hasNext = it->hasNext(); + cout << (hasNext ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode173-binary-search-tree-iterator_stack.cpp b/cpp-leetcode/leetcode173-binary-search-tree-iterator_stack.cpp new file mode 100644 index 00000000..9dd849bb --- /dev/null +++ b/cpp-leetcode/leetcode173-binary-search-tree-iterator_stack.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class BSTIterator { + stack st; +public: + BSTIterator(TreeNode* root) { /* 0 <= Node.val <= 10^6 */ + TreeNode* p = root; + while (p) + { + st.push(p); + p = p->left; + } + } + + // 将指针向右移动,然后返回指针处的val + int next() { + auto p = st.top(); + int res = p->val; + TreeNode* node = p->right; // 刚开始时node是栈的top处结点的right子结点 + st.pop(); + while (node) + { + st.push(node); + node = node->left; + } + return res; + } + // 如果向指针右侧遍历存在数字,则返回 true + bool hasNext() { + return !st.empty(); + } +}; + +// Test +int main() +{ + TreeNode *root = new TreeNode(6); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(8); + TreeNode *n3 = new TreeNode(0); + TreeNode *n4 = new TreeNode(4); + TreeNode *n5 = new TreeNode(7); + TreeNode *n6 = new TreeNode(9); + TreeNode *n7 = new TreeNode(3); + TreeNode *n8 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + + /** + * 你的 BSTIterator 对象会被用以下方式初始化和调用: + * */ + BSTIterator *it = new BSTIterator(root); + int val = it->next(); + cout << val << endl; + bool hasNext = it->hasNext(); + cout << (hasNext ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1737-change-minimum-characters-to-satisfy-one-of-three-conditions_hash.cpp b/cpp-leetcode/leetcode1737-change-minimum-characters-to-satisfy-one-of-three-conditions_hash.cpp new file mode 100644 index 00000000..db4f994d --- /dev/null +++ b/cpp-leetcode/leetcode1737-change-minimum-characters-to-satisfy-one-of-three-conditions_hash.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minCharacters(string a, string b) + { + vector freqA(26); // 词频数组 + vector freqB(26); + for (auto& ch : a) freqA[ch - 'a']++; + for (auto& ch : b) freqB[ch - 'a']++; + + int res = INT_MAX; + for (int key = 0; key < 26; key++) // key: 每个字母在词频数组中对应的index + { + if (key > 0) // 注意: 分界线不可能是字母'a' + { + // case1: max(a) < min(b) + int changes = 0; + for (int i = key; i < 26; i++) + changes += freqA[i]; // 把字符串a中 > key对应的字母 的字母改小 + for (int i = 0; i < key; i++) + changes += freqB[i]; + res = min(res, changes); + + // case2: max(b) < min(a) + changes = 0; + for (int i = 0; i < key; i++) + changes += freqA[i]; // 把a中 < key对应的字母 的字母改大 + for (int i = key; i < 26; i++) + changes += freqB[i]; + res = min(res, changes); + } + // case3: b只含1种字母, a也只含这一种字母 + int changes = 0; + for (int i = 0; i < 26; i++) + if (i != key) + { + changes += freqA[i]; + changes += freqB[i]; + } + res = min(res, changes); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string A = "dabadd", B = "cda"; + auto res = sol.minCharacters(A, B); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode175-combine-two-tables_mysql.sql b/cpp-leetcode/leetcode175-combine-two-tables_mysql.sql new file mode 100644 index 00000000..82c4eade --- /dev/null +++ b/cpp-leetcode/leetcode175-combine-two-tables_mysql.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below +SELECT tb1.FirstName, tb1.LastName, tb2.City, tb2.State +FROM Person as tb1 +left join Address as tb2 +on tb1.PersonId = tb2.PersonId; \ No newline at end of file diff --git a/cpp-leetcode/leetcode177-nth-highest-salary_mysql.sql b/cpp-leetcode/leetcode177-nth-highest-salary_mysql.sql new file mode 100644 index 00000000..2ea22d1a --- /dev/null +++ b/cpp-leetcode/leetcode177-nth-highest-salary_mysql.sql @@ -0,0 +1,8 @@ +CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT +BEGIN + SET N = N - 1; + RETURN ( + # Write your MySQL query statement below. + select distinct Salary from Employee order by Salary desc limit 1 offset N + ); +END \ No newline at end of file diff --git a/cpp-leetcode/leetcode178-rank-scores_mysql.sql b/cpp-leetcode/leetcode178-rank-scores_mysql.sql new file mode 100644 index 00000000..c890e399 --- /dev/null +++ b/cpp-leetcode/leetcode178-rank-scores_mysql.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +select a.Score as Score, +(select count(distinct b.Score) from Scores b where b.Score >=a.Score) as 'Rank' +from Scores a order by Score DESC; \ No newline at end of file diff --git a/cpp-leetcode/leetcode179-largest-number_solution1.cpp b/cpp-leetcode/leetcode179-largest-number_solution1.cpp new file mode 100644 index 00000000..cfcb6e6d --- /dev/null +++ b/cpp-leetcode/leetcode179-largest-number_solution1.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string largestNumber(vector& nums) { + int _max = *max_element(nums.begin(), nums.end()); + int maxLen = to_string(_max).size(); + vector> kvVect; + for (auto num : nums) + { + int curLen = to_string(num).size(); + string str = to_string(num); + string str0 = str; + int len0 = str0.size(); + if (_max != 0 && curLen < maxLen) + { + char firstDigit = to_string(num).front(); + while (curLen < maxLen - 1) + { + str.push_back(str0[(maxLen - curLen) % len0]); + curLen++; + } + str.push_back(*max_element(str0.begin(), str0.end())); + } + int mask = stoi(str); + kvVect.push_back({num, mask}); + } + + auto cmp = [](pair p1, pair p2) + { + return p1.second > p2.second; + }; + sort(kvVect.begin(), kvVect.end(), cmp); + + string resultStr = ""; + for (auto kvp : kvVect) + resultStr += to_string(kvp.first); + if (resultStr.front() == '0') resultStr = to_string(stoll(resultStr)); + return resultStr; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {34323,3432}; + // case1: {432,43243} , case2: {111311, 1113}, case3: {34323,3432}, case4: {0,0,0} + auto res = sol.largestNumber(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode179-largest-number_sort_using_custom_mask.cpp b/cpp-leetcode/leetcode179-largest-number_sort_using_custom_mask.cpp new file mode 100644 index 00000000..037ebf41 --- /dev/null +++ b/cpp-leetcode/leetcode179-largest-number_sort_using_custom_mask.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string largestNumber(vector& nums) { + int _max = *max_element(nums.begin(), nums.end()); + int maxLen = to_string(_max).size(); + vector> kvVect; + for (auto num : nums) + { + int curLen = to_string(num).size(); + string str = to_string(num); + string str0 = str; + int len0 = str0.size(); + if (_max != 0 && curLen < maxLen) + { + char firstDigit = to_string(num).front(); + while (curLen < maxLen - 1) + { + str.push_back(str0[(maxLen - curLen) % len0]); + curLen++; + } + str.push_back(*max_element(str0.begin(), str0.end())); + } + int mask = stoi(str); + kvVect.push_back({num, mask}); + } + + auto cmp = [](pair p1, pair p2) + { + return p1.second > p2.second; + }; + sort(kvVect.begin(), kvVect.end(), cmp); + + string resultStr = ""; + for (auto kvp : kvVect) + resultStr += to_string(kvp.first); + if (resultStr.front() == '0') resultStr = to_string(stoll(resultStr)); + return resultStr; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {999999998, 999999997, 999999999}; + auto res = sol.largestNumber(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode18-4sum.cpp b/cpp-leetcode/leetcode18-4sum.cpp new file mode 100644 index 00000000..860b18b7 --- /dev/null +++ b/cpp-leetcode/leetcode18-4sum.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> fourSum(vector &nums, int target) + { + vector> res; + int n = nums.size(); + sort(nums.begin(), nums.end()); + + for (int i = 0; i < n - 3; i++) + { + if (i > 0 && nums[i] == nums[i - 1]) + continue; // 跳过重复:当前项与相邻项相等时跳过 + for (int j = i + 1; j < n - 2; j++) + { + if (j > i + 1 && nums[j] == nums[j - 1]) + continue; // 跳过重复 + int left = j + 1, right = n - 1; + while (left < right) + { + int sum = nums[i] + nums[j] + nums[left] + nums[right]; + if (sum == target) + { + vector group{nums[i], nums[j], nums[left], nums[right]}; + res.push_back(group); + + while (left < right && nums[left] == nums[left + 1]) + left++; // 左侧遇到重复,跳过 + while (left < right && nums[right] == nums[right - 1]) + right--; // 右侧遇到重复,跳过 + + // 继续找下一组满足条件的 + left++; + right--; + } + else if (sum < target) + left++; + else + right--; + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1,0,-1,0,-2,2 }; + int target = 0; + auto res = sol.fourSum(nums, target); /* debug下查看结果(二维数组) */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode180-consecutive-numbers_mysql.sql b/cpp-leetcode/leetcode180-consecutive-numbers_mysql.sql new file mode 100644 index 00000000..02d07df3 --- /dev/null +++ b/cpp-leetcode/leetcode180-consecutive-numbers_mysql.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +SELECT distinct tb1.Num as "ConsecutiveNums" +FROM Logs as tb1, Logs as tb2, Logs as tb3 +WHERE tb1.Id + 1 = tb2.Id and tb2.Id + 1 = tb3.Id and tb1.Num = tb2.Num and tb2.Num = tb3.Num; \ No newline at end of file diff --git a/cpp-leetcode/leetcode181-employees-earning-more-than-their-managers_solution1.sql b/cpp-leetcode/leetcode181-employees-earning-more-than-their-managers_solution1.sql new file mode 100644 index 00000000..214374eb --- /dev/null +++ b/cpp-leetcode/leetcode181-employees-earning-more-than-their-managers_solution1.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below +select e1.Name as Employee from Employee e1, Employee e2 +where e1.ManagerId = e2.Id and e1.Salary > e2.Salary \ No newline at end of file diff --git a/cpp-leetcode/leetcode1834-single-threaded-cpu_sort_and_priority_queue.cpp b/cpp-leetcode/leetcode1834-single-threaded-cpu_sort_and_priority_queue.cpp new file mode 100644 index 00000000..552b68d3 --- /dev/null +++ b/cpp-leetcode/leetcode1834-single-threaded-cpu_sort_and_priority_queue.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include +using namespace std; + +typedef long long LL; +typedef pair PLL; // pair: 处理时间 -> index +class Solution { +public: + vector getOrder(vector>& tasks) { + // 加入index, 题目要求在任务池中选任务时需要按下标排序, 下标小的排前面 + for (int i = 0; i < tasks.size(); i++) + tasks[i].push_back(i); + sort(tasks.begin(), tasks.end()); // 根据先来先服务的规则, 按每个任务的开始时刻排序 + priority_queue, greater<>> pq; + + LL cur = 0; // 记录当前时间点 + vector res; + for (int i = 0; i < tasks.size(); i++) + { + while (cur < tasks[i][0] && !pq.empty()) /* 先去任务池捞一下, 看有没有可以执行的任务, 如果有逐个执行 */ + { + res.push_back(pq.top().second); + cur += pq.top().first; + pq.pop(); + } + if (cur < tasks[i][0]) cur = (LL)tasks[i][0]; /* 如果循环结束时, 时间片还没到达, 那就可以将时间直接跳到最近的下一个任务开始的时刻, 反正也是空等 */ + pq.push({tasks[i][1], tasks[i][2]}); + } + while (!pq.empty()) /* 再去任务池捞一下, 看有没有可以执行的任务, 如果有逐个执行 */ + { + res.push_back(pq.top().second); + cur += pq.top().first; + pq.pop(); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> tasks = {{1,2},{2,4},{3,2},{4,1}}; + auto res = sol.getOrder(tasks); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode187-repeated-dna-sequences_bit_operation2.cpp b/cpp-leetcode/leetcode187-repeated-dna-sequences_bit_operation2.cpp new file mode 100644 index 00000000..55d33de2 --- /dev/null +++ b/cpp-leetcode/leetcode187-repeated-dna-sequences_bit_operation2.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findRepeatedDnaSequences(string s) { + if (s.size() <= 10) return {}; + + vector res; + bitset<1 << 20> bin1; /* 原字符串映射的二进制bit串第1次出现时, 在二进制数bin1中更新其标志位 */ + bitset<1 << 20> bin2; /* 原字符串映射的二进制bit串再次出现时, 在二进制数bin2中更新其标志位 */ + + unordered_map dict; + dict['A'] = 0; // 二进制数00 + dict['C'] = 1; // 二进制数01 + dict['G'] = 2; // 二进制数10 + dict['T'] = 3; // 二进制数11 + + int val = 0; + /* 从前向后的滑动窗口(由长度为0开始, 长度每次增加1, 直到长度为10), 每次读入一个新的字母(2个bit), 并将其对应的二进制数与bin1相加 */ + for (int i = 0; i < 10; i++) + { + auto temp = (val << 2); + val = temp | dict[s[i]]; + } + bin1.set(val); + + int mask = (1 << 20) - 1; /* 掩码: 20个全1, 起到按长度20截断二进制串的作用, 只保留较低位的20个bit位 */ + for (int i = 10; i < s.size(); i++) + { + /* 计算以index = i 为结束位置且长度为10的字符串(其在原串s中index区间为[i-9, i])对应的二进制数: 滑动窗口继续右移, + 去掉最高位的有效位(对应一个英文字母), 用当前新扫描进来的字母对应的二进制数替换最右边的两个bit位(00) */ + auto temp1 = val << 2; + auto temp2 = temp1 & mask; /* & mask 是为了让二进制数的长度始终保持为20个bit, 否则会出现越界(bitset index outside of range) */ + val = temp2 | dict[s[i]]; + if (bin2[val]) continue; /* bin2[val]: 用来判断数val是否在二进制数bin2中已经有标志位了(之前已出现过2次, 这次是第3次出现). + 具体步骤: 取出数val的对应的bit 标志位, 看结果是否为0x1, 为0x1表示已出现了2次, 后面不用继续统计次数了, 跳过之. + 如果bin2[val]是0, 那还需要继续处理. */ + /* bin1[val]: 用来判断数val是否在二进制数bin1中已经有标志位了, 即判断结果是否为0x1, 为0x1表示之前已出现了1次, + 此时可以加到结果集中, 并在二进制数bin2中更新其标志位 */ + if (bin1[val]) + { + res.push_back(s.substr(i - 9, 10)); + bin2.set(val); + } + else bin1.set(val); /* 第1次出现, 在二进制数bin1中更新其标志位 */ + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"; + auto res = sol.findRepeatedDnaSequences(s); + // 预期输出结果为: {"AAAAACCCCC","CCCCCAAAAA"} + for (auto& num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode187-repeated-dna-sequences_set.cpp b/cpp-leetcode/leetcode187-repeated-dna-sequences_set.cpp new file mode 100644 index 00000000..e555ff8e --- /dev/null +++ b/cpp-leetcode/leetcode187-repeated-dna-sequences_set.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findRepeatedDnaSequences(string s) { + const int len = s.size(); + if (len <= 10) return {}; + unordered_set st; + vector res; + for (int i = 0; i < len - 9; i++) + { + string subStr = s.substr(i, 10); + if (st.count(subStr) && count(res.begin(), res.end(), subStr) == 0) + res.push_back(subStr); + else st.insert(subStr); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"; + auto res = sol.findRepeatedDnaSequences(s); + // 预期输出结果为: {"AAAAACCCCC","CCCCCAAAAA"} + for (auto& num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode187-repeated-dna-sequences_set_and_bit_operation1.cpp b/cpp-leetcode/leetcode187-repeated-dna-sequences_set_and_bit_operation1.cpp new file mode 100644 index 00000000..12e3179a --- /dev/null +++ b/cpp-leetcode/leetcode187-repeated-dna-sequences_set_and_bit_operation1.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findRepeatedDnaSequences(string s) { + const int len = s.size(); + if (len <= 10) return {}; + unordered_set st; + vector res; + unordered_map dict; + unordered_set set; /* 存放出现次数≥1的原字符串映射的二进制bit 串(最后会自动被转为十进制数) */ + dict['A'] = 0; // 二进制数00 + dict['C'] = 1; // 二进制数01 + dict['G'] = 2; // 二进制数10 + dict['T'] = 3; // 二进制数11 + for (int i = 0; i < s.size() - 9; i++) + { + int bin = 0; + // 使用一个长度固定为10的滑动窗口, 对应一个字符串 + for (int j = i; j < i + 10; j++) + { + bin <<= 2; /* 删掉滑动窗口最左侧滑出的那1个字母[由于每个字母(A、C、G、T之一)对应两个bit位, 故需要左移两个bit] */ + bin |= dict[s[j]]; /* 加入滑动窗口最右侧刚滑入的那1个字母: 把一个字母的二进制表示加到二进制串bin的末尾两个bit位(00) 上 */ + } + string curStr = s.substr(i, 10); + if (set.count(bin) && count(res.begin(), res.end(), curStr) == 0) + res.push_back(curStr); + else set.insert(bin); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"; + auto res = sol.findRepeatedDnaSequences(s); + // 预期输出结果为: {"AAAAACCCCC","CCCCCAAAAA"} + for (auto& num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode189-rotate-array_reverse_solution1.cpp b/cpp-leetcode/leetcode189-rotate-array_reverse_solution1.cpp new file mode 100644 index 00000000..18c3f6c4 --- /dev/null +++ b/cpp-leetcode/leetcode189-rotate-array_reverse_solution1.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void rotate(vector& nums, int k) { + int n = nums.size(); + int shift = k % n; + + // 翻转前 n - shift 个数. + // Index i (0 <= i < n - shift) 会变成 n - shift - i. + reverse(nums.begin(), nums.begin() + n - shift); + + // 翻转末尾 shift 个数. + // Index n - shift + i (0 <= i < shift) 会变成 n - i. + reverse(nums.begin() + n - shift, nums.begin() + n); + + // 翻转所有数 + // Index i (0 <= i < n - shift) 会变成 n - (n - shift - i) = i + shift. + // Index n - shift + i (0 <= i < shift) 会变成 n - (n - i) = i. + reverse(nums.begin(), nums.begin() + n); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3,4,5,6,7}; + int k = 3; + sol.rotate(nums, k); + + for (int num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode189-rotate-array_reverse_solution2.cpp b/cpp-leetcode/leetcode189-rotate-array_reverse_solution2.cpp new file mode 100644 index 00000000..523be0e2 --- /dev/null +++ b/cpp-leetcode/leetcode189-rotate-array_reverse_solution2.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void rotate(vector& nums, int k) { + int len = nums.size(); + int shift = k % len; + + reverse(nums.begin(), nums.end()); + reverse(nums.begin(), nums.begin() + shift); + reverse(nums.begin() + shift, nums.end()); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3,4,5,6,7}; + int k = 3; + sol.rotate(nums, k); + + for (int num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode189-rotate-array_swap_solution.cpp b/cpp-leetcode/leetcode189-rotate-array_swap_solution.cpp new file mode 100644 index 00000000..723938dd --- /dev/null +++ b/cpp-leetcode/leetcode189-rotate-array_swap_solution.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +class Solution +{ +public: + void rotate(vector &nums, int k) + { + int n = nums.size(); + if (nums.empty() || (k % n) == 0) return; + + int nowIndex = 0; + int temp, cur = nums[0]; + // 双指针 + 基于临时变量的swap + for (int j = 0, i = 0; j < n; j++) + { + temp = cur; + nowIndex = (k + nowIndex) % n; + cur = nums[nowIndex]; + nums[nowIndex] = temp; + if (nowIndex == i) + { + nowIndex = ++i; + cur = nums[nowIndex]; + } + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3,4,5,6,7}; + int k = 3; + sol.rotate(nums, k); + + for (int num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode189-rotate-array_two_pointers_solution.cpp b/cpp-leetcode/leetcode189-rotate-array_two_pointers_solution.cpp new file mode 100644 index 00000000..bbdff3bb --- /dev/null +++ b/cpp-leetcode/leetcode189-rotate-array_two_pointers_solution.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +class Solution +{ +public: + void rotate(vector &nums, int k) + { + int n = nums.size(); + if (nums.empty() || (k % n) == 0) return; + + int nowIndex = 0; + int temp, cur = nums[0]; + // 双指针 + for (int j = 0, i = 0; j < n; j++) + { + temp = cur; + nowIndex = (k + nowIndex) % n; + cur = nums[nowIndex]; + nums[nowIndex] = temp; + if (nowIndex == i) + { + nowIndex = ++i; + cur = nums[nowIndex]; + } + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3,4,5,6,7}; + int k = 3; + sol.rotate(nums, k); + + for (int num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1894-find-the-student-that-will-replace-the-chalk_mod_tip.cpp b/cpp-leetcode/leetcode1894-find-the-student-that-will-replace-the-chalk_mod_tip.cpp new file mode 100644 index 00000000..464ba558 --- /dev/null +++ b/cpp-leetcode/leetcode1894-find-the-student-that-will-replace-the-chalk_mod_tip.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int chalkReplacer(vector& chalk, int k) { + long long sum = 0; + for (auto num : chalk) + sum += num; // 求和 + k = k % sum; // 小技巧: mod, 减小目标值 k 的规模 + int len = chalk.size(); + for (int i = 0; i < len; i++) + { + if (k < chalk[i]) return i; // 不够减时 + k -= chalk[i]; + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + vector chalk = {3, 1, 7}; + int k = 30004001; + int res = sol.chalkReplacer(chalk, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode19-remove-nth-node-from-end-of-list-solution1.cpp b/cpp-leetcode/leetcode19-remove-nth-node-from-end-of-list-solution1.cpp new file mode 100644 index 00000000..0fd28f59 --- /dev/null +++ b/cpp-leetcode/leetcode19-remove-nth-node-from-end-of-list-solution1.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + int len = 0; + ListNode* p = head; + + while(p != NULL) + { + p = p -> next; + len++; + } + + if (n == len) + { + ListNode* newHead = head -> next; + delete head; // 释放被删除节点占用的内存 + return newHead; + } + + p = head; + for (int i = 1; i < len - n; i++) /* 注意 for能跑的区间长度是 len - n - 1, 到要删除的节点的前一个就停下来 */ + { + p = p -> next; + } + + ListNode* toDel = p -> next; + p->next = p->next->next; + delete toDel; // 释放被删除节点占用的内存 + + return head; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + + l1 = new ListNode(1); + l1->next = new ListNode(2); + int k = 2; + + ListNode* p = sol.removeNthFromEnd(l1, k); + + while (p != NULL) + { + cout << p -> val << endl; + p = p -> next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode19-remove-nth-node-from-end-of-list-solution2.cpp b/cpp-leetcode/leetcode19-remove-nth-node-from-end-of-list-solution2.cpp new file mode 100644 index 00000000..b308de34 --- /dev/null +++ b/cpp-leetcode/leetcode19-remove-nth-node-from-end-of-list-solution2.cpp @@ -0,0 +1,71 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode *fast = head; + ListNode *slow = head; + + // 让fast指针先走n步 + for (int i = 0; i < n; i++) + { + fast = fast -> next; + + if (fast == NULL) /* 此时刚好到tail节点, 需要删掉的恰好是head节点 */ + { + ListNode *newHead = head -> next; + delete head; + return newHead; + } + } + + while (fast -> next != NULL) + { + fast = fast -> next; + slow = slow -> next; + } + + ListNode *toDel = slow -> next; + slow -> next = slow -> next -> next; + delete toDel; + + return head; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + + l1 = new ListNode(1); + l1->next = new ListNode(2); + l1->next = new ListNode(5); + l1->next = new ListNode(8); + int k = 2; + + ListNode* p = sol.removeNthFromEnd(l1, k); + + while (p != NULL) + { + cout << p -> val << endl; + p = p -> next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode1904-the-number-of-full-rounds-you-have-played_simulate.cpp b/cpp-leetcode/leetcode1904-the-number-of-full-rounds-you-have-played_simulate.cpp new file mode 100644 index 00000000..0358676e --- /dev/null +++ b/cpp-leetcode/leetcode1904-the-number-of-full-rounds-you-have-played_simulate.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int numberOfRounds(string startTime, string finishTime) { + int startMinu = getMinutes(startTime); + int endMinu = getMinutes(finishTime); + if (endMinu < startMinu) endMinu += 24 * 60; /* case: ["20:00", "06:00"], 包括了 00:00 */ + else if (endMinu - startMinu < 15) return 0; /* case: ["00:47", "00:57"] */ + int validStart = startMinu % 15 != 0 ? (startMinu / 15 + 1) * 15 : startMinu / 15 * 15; + int validEnd = endMinu / 15 * 15; + return (validEnd - validStart) / 15; /* 有效区间: 原区间的子区间, 两端均收缩, 即endTime/15向下取整 - startTime/15向上取整 */ + } + int getMinutes(string ts) + { + int hour = stoi(ts.substr(0, 2)); + int minute = stoi(ts.substr(3, 2)); + return 60*hour + minute; + } +}; + +// Test +int main() +{ + Solution sol; + string start = "20:00"; + string end = "06:00"; + auto res = sol.numberOfRounds(start, end); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode197-rising-temperature_mysql.sql b/cpp-leetcode/leetcode197-rising-temperature_mysql.sql new file mode 100644 index 00000000..27f2a780 --- /dev/null +++ b/cpp-leetcode/leetcode197-rising-temperature_mysql.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +select w2.id from Weather w1, Weather w2 +where DATEDIFF(w2.recordDate, w1.recordDate) = 1 +and w2.Temperature > w1.Temperature \ No newline at end of file diff --git a/cpp-leetcode/leetcode198-house-robber_solution1_recursive.cpp b/cpp-leetcode/leetcode198-house-robber_solution1_recursive.cpp new file mode 100644 index 00000000..c492fc19 --- /dev/null +++ b/cpp-leetcode/leetcode198-house-robber_solution1_recursive.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + vector opt(n+2, 0); + + return optSum(nums, 0, opt); + } + + // 返回 dp[start..] 能抢到的最大值 + int optSum(vector nums, int startIndex, vector& opt) + { + if (startIndex > nums.size() - 1) /* 不可能发生的情况, 直接 return 0 */ + return 0; + // 查表, 如果缓存中的值已不是初始值就return + if (opt[startIndex] != 0) + return opt[startIndex]; + int res = max(optSum(nums, startIndex + 1, opt), + nums[startIndex] + optSum(nums, startIndex + 2, opt)); + opt[startIndex] = res; + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3,1}; + auto res = sol.rob(nums); + cout << res << endl; + + nums = {2,7,9,3,1}; + res = sol.rob(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode198-house-robber_solution2_iterative.cpp b/cpp-leetcode/leetcode198-house-robber_solution2_iterative.cpp new file mode 100644 index 00000000..78ea371e --- /dev/null +++ b/cpp-leetcode/leetcode198-house-robber_solution2_iterative.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + // opt[i] = x 表示:从第 i 间房子开始抢劫,最多能抢到的钱为 x + vector opt(n+2, 0); /* base case: opt[n] = 0; 于是opt[n]和opt[n+1] 都应该初始化为0 */ + for (int i = n - 1; i >= 0; i--) + { + opt[i] = max(opt[i+1], opt[i+2] + nums[i]); + } + + return opt[0]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3,1}; + auto res = sol.rob(nums); + cout << res << endl; + + nums = {2,7,9,3,1}; + res = sol.rob(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode199-binary-tree-right-side-view_level_order_deque.cpp b/cpp-leetcode/leetcode199-binary-tree-right-side-view_level_order_deque.cpp new file mode 100644 index 00000000..af2bc57f --- /dev/null +++ b/cpp-leetcode/leetcode199-binary-tree-right-side-view_level_order_deque.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector rightSideView(TreeNode* root) { + if (root == nullptr) return {}; + vector res; + + deque q{root}; + + while (!q.empty()) + { + vector curLevel; + for (int i = q.size(); i > 0; i--) + { + TreeNode *p = q.front(); + q.pop_front(); + curLevel.push_back(p->val); + + if (p->left != nullptr) q.push_back(p->left); + if (p->right != nullptr) q.push_back(p->right); + } + res.push_back(curLevel.back()); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(3); + TreeNode *n3 = new TreeNode(5); + TreeNode *n4 = new TreeNode(4); + root->left = n1; + root->right = n2; + n1->right = n3; + n2->right = n4; + n3->left == NULL; + n3->right == NULL; + n4->left == NULL; + n4->right == NULL; + + auto res = sol.rightSideView(root); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode199-binary-tree-right-side-view_level_order_queue.cpp b/cpp-leetcode/leetcode199-binary-tree-right-side-view_level_order_queue.cpp new file mode 100644 index 00000000..34f04e29 --- /dev/null +++ b/cpp-leetcode/leetcode199-binary-tree-right-side-view_level_order_queue.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector rightSideView(TreeNode* root) { + if (root == nullptr) return {}; + vector res; + + queue q; + q.push(root); + + while (!q.empty()) + { + vector curLevel; + for (int i = q.size(); i > 0; i--) + { + TreeNode *p = q.front(); + q.pop(); + curLevel.push_back(p->val); + + if (p->left != nullptr) q.push(p->left); + if (p->right != nullptr) q.push(p->right); + } + res.push_back(curLevel.back()); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(3); + TreeNode *n3 = new TreeNode(5); + TreeNode *n4 = new TreeNode(4); + root->left = n1; + root->right = n2; + n1->right = n3; + n2->right = n4; + n3->left == NULL; + n3->right == NULL; + n4->left == NULL; + n4->right == NULL; + + auto res = sol.rightSideView(root); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode2-add-two-numbers.cpp b/cpp-leetcode/leetcode2-add-two-numbers.cpp new file mode 100644 index 00000000..d195302a --- /dev/null +++ b/cpp-leetcode/leetcode2-add-two-numbers.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* fakeNode = new ListNode(-1); + ListNode* p = fakeNode; + + int carry = 0; + while(l1 || l2) + { + int val1 = (l1 != NULL) ? l1 -> val : 0; + int val2 = (l2 != NULL) ? l2 -> val : 0; + int sum = val1 + val2 + carry; + carry = sum / 10; // 拿掉这个sum(二位数)的末尾数字, 得到当前位的进位值 + p -> next = new ListNode(sum % 10); + p = p -> next; + if(l1) l1 = l1 -> next; + if(l2) l2 = l2 -> next; + } + if (carry == 1) + p -> next = new ListNode(1); + + return fakeNode -> next; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + ListNode *l2; + + l1 = new ListNode(1); + l1->next = new ListNode(3); + l1->next->next = new ListNode(6); + l1->next->next->next = NULL; + + l2 = new ListNode(5); + l2->next = new ListNode(8); + l2->next->next = new ListNode(3); + l2->next->next->next = NULL; + ListNode *res = sol.addTwoNumbers(l1, l2); + + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode20-valid-parentheses.cpp b/cpp-leetcode/leetcode20-valid-parentheses.cpp new file mode 100644 index 00000000..7038f685 --- /dev/null +++ b/cpp-leetcode/leetcode20-valid-parentheses.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isValid(string s) { + stack st; + + for(char ch : s) + { + if(ch == '(' || ch == '[' || ch == '{') + st.push(ch); + else { + if(st.empty()) + return false; + if(ch == ')' && st.top() != '(') + return false; + if(ch == ']' && st.top() != '[') + return false; + if(ch == '}' && st.top() != '{') + return false; + + st.pop(); + } + } + return st.empty(); + } +}; + +//Test +int main() +{ + Solution sol; + string str = "()[]{}"; // "(}{)"; + bool res = sol.isValid(str); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode200-number-of-islands_flood_fill.cpp b/cpp-leetcode/leetcode200-number-of-islands_flood_fill.cpp new file mode 100644 index 00000000..0fb208a1 --- /dev/null +++ b/cpp-leetcode/leetcode200-number-of-islands_flood_fill.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +using namespace std; + +class Solution { +private: + vector> M; + int rows; + int cols; +public: + int numIslands(vector>& grid) { + M = grid; + rows = grid.size(); + cols = grid[0].size(); + + int count = 0; + for (int r = 0; r < rows; r++) + { + for (int c = 0; c < cols; c++) + count += dfs(r, c); + } + return count; + } + + int dfs(int r, int c) /* dfs: return能形成的连通岛屿的数量(上下左右四连通) */ + { + if (r < 0 || c < 0 || r == rows || c == cols) + return 0; + if (M[r][c] == '0') + return 0; + + M[r][c] = '0'; /* 将当前格子标记为: visited, 并检查当前格子的上下左右4个位置。下次遇到1(地)就继续向前, 下次遇到0(水, 表示已到尽头)就结束 */ + + dfs(r - 1, c); // 选择上方相邻位置前进 + dfs(r + 1, c); // 选择下方相邻位置前进 + dfs(r, c - 1); // 选择左侧相邻位置前进 + dfs(r, c + 1); // 选择右侧相邻位置前进 + + return 1; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = { + {'1', '1', '0', '0', '0'}, + {'1', '1', '0', '0', '0'}, + {'0', '0', '1', '0', '0'}, + {'0', '0', '0', '1', '1'}}; + auto res = sol.numIslands(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode201-bitwise-and-of-numbers-range.cpp b/cpp-leetcode/leetcode201-bitwise-and-of-numbers-range.cpp new file mode 100644 index 00000000..1af05d43 --- /dev/null +++ b/cpp-leetcode/leetcode201-bitwise-and-of-numbers-range.cpp @@ -0,0 +1,38 @@ +#include +#include +using namespace std; + +class Solution { +public: + int rangeBitwiseAnd(int m, int n) + { + /* 题中规定数据范围: m, n中较大值<= 2^31 - 1 = 2147483647 */ + int shiftCount = 0; + int common = 0; + GetCommonDigits(m, n, common, shiftCount); + auto res = common << shiftCount; // 末位补0 + return res; + } + + void GetCommonDigits(int a, int b, int& common, int& shiftCount) + { + shiftCount = 0; + while (a != b) + { + a = a >> 1; + b = b >> 1; + shiftCount++; + } + common = a; + } +}; + +// Test +int main() +{ + Solution sol; + int left = 5, right = 2147483647; + printf("%d", sol.rangeBitwiseAnd(left, right)); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode203-remove-linked-list-elements_optimize.cpp b/cpp-leetcode/leetcode203-remove-linked-list-elements_optimize.cpp new file mode 100644 index 00000000..4a107b5e --- /dev/null +++ b/cpp-leetcode/leetcode203-remove-linked-list-elements_optimize.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ + +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + // 迭代地删除开头的结点 + while (head != NULL && head->val == val) { /* 注意这里用while, 而不是if */ + ListNode* tmp = head; + head = head->next; + delete tmp; + } + + // 删除非开头的结点 + ListNode* p = head; + while (p != NULL && p->next!= NULL) { + if ((p->next)->val == val) { // 此时 p 就是pre结点 + ListNode* tmp = p->next; + p->next = p->next->next; + delete tmp; + } else { + p = p->next; + } + } + return head; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(7); + head->next = new ListNode(7); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(7); + head->next->next->next->next = NULL; + int target = 7; + + ListNode *res = sol.removeElements(head, target); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode203-remove-linked-list-elements_solution1.cpp b/cpp-leetcode/leetcode203-remove-linked-list-elements_solution1.cpp new file mode 100644 index 00000000..ddd0b9a8 --- /dev/null +++ b/cpp-leetcode/leetcode203-remove-linked-list-elements_solution1.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ + +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + ListNode *p = head; + if(head == NULL) /* 这里的条件不能是 head == NULL || head -> next == NULL */ + return p; + + // 迭代地删除开头的结点 + while(head != NULL && (head -> val) == val) /* 注意这里用while, 而不是if */ + { + head = head -> next; + } + + while(p != NULL && (p -> next) != NULL) + { + // 删除非开头的结点 + if((p -> next) -> val == val) // 此时 p 就是pre结点 + { + p -> next = p->next->next; + } + else p = p -> next; + } + return head; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(7); + head->next = new ListNode(7); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(7); + head->next->next->next->next = NULL; + int target = 7; + + ListNode *res = sol.removeElements(head, target); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode204-count-prims-sieveMethod_style1.cpp b/cpp-leetcode/leetcode204-count-prims-sieveMethod_style1.cpp new file mode 100644 index 00000000..35978f84 --- /dev/null +++ b/cpp-leetcode/leetcode204-count-prims-sieveMethod_style1.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +class Solution +{ +public: + int countPrimes(int n) + { + if (n < 2) + return 0; + + vector isDelete(n, false); + int max = (int)sqrt(n); + int count = 0; + for (int i = 2; i < n; i++) + { + if (isDelete[i]) + continue; + count++; + if (i > max) + continue; + for (int j = i * i; j < n; j += i) + isDelete[j] = true; + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + auto result = sol.countPrimes(1001561); + cout << result << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode204-count-prims-sieveMethod_style2.cpp b/cpp-leetcode/leetcode204-count-prims-sieveMethod_style2.cpp new file mode 100644 index 00000000..d71f67a4 --- /dev/null +++ b/cpp-leetcode/leetcode204-count-prims-sieveMethod_style2.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int countPrimes(int n) { + vector isPrime(n, 1); + if(n < 2) + { + return 0; + } + else { + int count = 0; + for (int i = 2; i * i < n; i++) + { + if (isPrime[i]) + { + for (int j = i; i * j < n; j++) // Use j to record times(倍数). + { + isPrime[i*j] = 0; + } + } + } + + for (int i = 2; i < n; i++) + { + if (isPrime[i] == 1) + count++; + } + + return count; + } + } +}; + +// Test +int main() +{ + Solution sol; + auto result = sol.countPrimes(100156150); + cout << result << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode205-isomorphic-strings.cpp b/cpp-leetcode/leetcode205-isomorphic-strings.cpp new file mode 100644 index 00000000..4ee3f8ca --- /dev/null +++ b/cpp-leetcode/leetcode205-isomorphic-strings.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isIsomorphic(string s, string t) { + vector sFirstIndex; + vector tFirstIndex; + for (auto ch : s) + { + int firstIndex = s.find_first_of(ch); + sFirstIndex.push_back(firstIndex); + } + for (auto ch : t) + { + int firstIndex = t.find_first_of(ch); + tFirstIndex.push_back(firstIndex); + } + return sFirstIndex == tFirstIndex; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "paper", t = "title"; + auto res = sol.isIsomorphic(s, t); + + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode206-reverse-linked-list-solution1.cpp b/cpp-leetcode/leetcode206-reverse-linked-list-solution1.cpp new file mode 100644 index 00000000..cdad1405 --- /dev/null +++ b/cpp-leetcode/leetcode206-reverse-linked-list-solution1.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *reverseList(ListNode *head) + { + if (head == NULL) + return NULL; + ListNode *cur = head; + ListNode *prev = NULL; + + while (cur != NULL) + { + ListNode *nextp = cur->next; // 用指针nextp占位,确保下一次可以取到 + cur->next = prev; + prev = cur; /* 为下一轮操作做准备,同时在cur移走之前指向过去 */ + cur = nextp; /* 移到原链表的下一个结点,为下一轮操作做准备。*/ + } + + return prev; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = NULL; + + ListNode *res = sol.reverseList(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode206-reverse-linked-list-solution2.cpp b/cpp-leetcode/leetcode206-reverse-linked-list-solution2.cpp new file mode 100644 index 00000000..cc223603 --- /dev/null +++ b/cpp-leetcode/leetcode206-reverse-linked-list-solution2.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *reverseList(ListNode *head) + { + ListNode *cur = head; + ListNode *newHead = NULL; + if (cur == NULL) + return head; + + while (cur != NULL) + { + ListNode *pre = cur; + cur = cur->next; + pre->next = newHead; + newHead = pre; /* 由于此处不是用newHead的next指针进行挂接,故直接return newHead即可。 */ + } + + return newHead; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = NULL; + + ListNode *res = sol.reverseList(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode206-reverse-linked-list-solution3-recursive.cpp b/cpp-leetcode/leetcode206-reverse-linked-list-solution3-recursive.cpp new file mode 100644 index 00000000..ab09a29f --- /dev/null +++ b/cpp-leetcode/leetcode206-reverse-linked-list-solution3-recursive.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *reverseList(ListNode *head) + { + if (head == NULL || head->next == NULL) + return head; + + ListNode *nextp = head->next; + head->next = NULL; + ListNode *newHead = reverseList(nextp); + nextp->next = head; /* 把head看作prev结点,f(n) = f(n-1) -> head -> NULL, n是结点序号,与当前指针cur一一对应 */ + return newHead; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = NULL; + + ListNode *res = sol.reverseList(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode207-course-schedule_dfs.cpp b/cpp-leetcode/leetcode207-course-schedule_dfs.cpp new file mode 100644 index 00000000..fcb8df55 --- /dev/null +++ b/cpp-leetcode/leetcode207-course-schedule_dfs.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { + vector visited; + vector> next; // 邻接矩阵, 其中next[i]是第i门课的所有先修课程 +public: + bool canFinish(int numCourses, vector>& prerequisites) { + visited.resize(numCourses, 0); + next.resize(numCourses); // 由于是二维矩阵, 如果结构有变化第一维需要resize + for (auto& p : prerequisites) + next[p[0]].push_back(p[1]); + for (int i = 0; i < numCourses; i++) + { + if (dfs(i) == false) return false; + } + return true; + } + bool dfs(int cur) + { + if (visited[cur] == 1) return true; + if (visited[cur] == 2) return false; // 当前状态之前处理过, 现在又正在处理 + + visited[cur] = 2; // 2: 将当前结点标记为"正在处理"状态 + for (int& next : next[cur]) + { + if (dfs(next) == false) return false; + } + visited[cur] = 1; // 一个node及其邻接的所有结点被处理完一次时, 将其标记为"已经访问过" + + return true; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 2; + vector> pres = {{1,0},{0,1}}; + auto res = sol.canFinish(num, pres); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode208-implement-trie-prefix-tree_hashmap.cpp b/cpp-leetcode/leetcode208-implement-trie-prefix-tree_hashmap.cpp new file mode 100644 index 00000000..27e9c5f5 --- /dev/null +++ b/cpp-leetcode/leetcode208-implement-trie-prefix-tree_hashmap.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include /* 包含智能指针std::unique_ptr */ +#include +using namespace std; + +class Trie { +public: + /** Initialize your data structure here. */ + Trie() : _root(new TrieNode()) {} + + /** Inserts a word into the trie. */ + void insert(string word) + { + TrieNode* p = _root.get(); + for (auto ch : word) + { + if (!p->children.count(ch)) + p->children[ch] = new TrieNode(); + p = p->children[ch]; + } + p->isWord = true; + } + + /** return: 单词是否在trie 中 */ + bool search(string word) + { + const TrieNode* p = find(word); + return p && p->isWord; // p != nullptr && p->isWord + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + bool startsWith(string prefix) + { + return find(prefix) != nullptr; + } + +private: + struct TrieNode + { + bool isWord; + unordered_map children; + TrieNode() : isWord(false) {} + ~TrieNode() + { + for (auto kvp : children) + if (kvp.second) delete kvp.second; + } + }; + std::unique_ptr _root; + + const TrieNode* find(const string &prefix) + { + TrieNode* p = _root.get(); + for (auto ch : prefix) + { + if (!p->children.count(ch)) return nullptr; + p = p->children[ch]; // 或 p = p->children.at(c); + } + return p; + } +}; + +// Test +int main() +{ + Trie* trie = new Trie(); + trie->insert("apple"); + cout << (trie->search("apple") == true ? "true" : "false") << endl; // return true + cout << (trie->search("app") == true ? "true" : "false") << endl; // return false + trie->insert("pple"); + trie->insert("aple"); + trie->insert("pappaple"); + trie->insert("abaple"); + trie->insert("aass"); + trie->insert("avva"); + trie->insert("aaaa"); + cout << (trie->startsWith("app") == true ? "true" : "false") << endl; // return true + trie->insert("app"); + cout << (trie->search("app") == true ? "true" : "false") << endl; // return true + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode208-implement-trie-prefix-tree_vector.cpp b/cpp-leetcode/leetcode208-implement-trie-prefix-tree_vector.cpp new file mode 100644 index 00000000..c8856036 --- /dev/null +++ b/cpp-leetcode/leetcode208-implement-trie-prefix-tree_vector.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +#include /* 包含智能指针std::unique_ptr */ +#include +using namespace std; + +class Trie { +public: + /** Initialize your data structure here. */ + Trie() : _root(new TrieNode()) {} + + /** Inserts a word into the trie. */ + void insert(string word) + { + TrieNode* p = _root.get(); + for (auto ch : word) + { + if (!p->children[ch - 'a']) + p->children[ch - 'a'] = new TrieNode(); + p = p->children[ch - 'a']; + } + p->isWord = true; + } + + /** return: 单词是否在trie 中 */ + bool search(string word) + { + const TrieNode* p = find(word); + return p && p->isWord; // p != nullptr && p->isWord + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + bool startsWith(string prefix) + { + return find(prefix) != nullptr; + } + +private: + struct TrieNode + { + bool isWord; + vector children; + TrieNode() : isWord(false), children(26, nullptr) {} + ~TrieNode() + { + for (auto child : children) + if (child) delete child; + } + }; + std::unique_ptr _root; + + const TrieNode* find(const string &prefix) + { + TrieNode* p = _root.get(); + for (auto ch : prefix) + { + p = p->children[ch - 'a']; + if (p == nullptr) break; + } + return p; + } +}; + +// Test +int main() +{ + Trie* trie = new Trie(); + trie->insert("apple"); + cout << (trie->search("apple") == true ? "true" : "false") << endl; // returns true + cout << (trie->search("app") == true ? "true" : "false") << endl; // returns false + trie->insert("pple"); + trie->insert("aple"); + trie->insert("pappaple"); + trie->insert("abaple"); + trie->insert("aass"); + trie->insert("avva"); + trie->insert("aaaa"); + cout << (trie->startsWith("app") == true ? "true" : "false") << endl; // return true + trie->insert("app"); + cout << (trie->search("app") == true ? "true" : "false") << endl; // return true + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode209-minimum-size-subarray-sum_prefix_sum.cpp b/cpp-leetcode/leetcode209-minimum-size-subarray-sum_prefix_sum.cpp new file mode 100644 index 00000000..950098cb --- /dev/null +++ b/cpp-leetcode/leetcode209-minimum-size-subarray-sum_prefix_sum.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +// 前缀和 + 二分查找 +class Solution { +public: + int minSubArrayLen(int target, vector& nums){ + int len = nums.size(); + if (len == 0) + return 0; + int minLen = INT_MAX; + // 构造前缀和 + vector preSum(len + 1); + preSum[0] = 0; + for (int i = 0; i < len; i++) + preSum[i + 1] = preSum[i] + nums[i]; + + for (int i = 0; i < len; i++) + { + int toFind = target + preSum[i]; /* preSum_right - preSum_[i] = target */ + auto rIt = lower_bound(preSum.begin(), preSum.end(), toFind); /* 找的是第一个 ≥x 的 */ + if (rIt != preSum.end()) + { + int curLen = rIt - (preSum.begin() + i); + minLen = min(minLen, curLen); + } + } + minLen = (minLen == INT_MAX) ? 0 : minLen; + return minLen; + } +}; + +// Test +int main() +{ + Solution sol; + int target = 7; + vector nums = {2, 3, 1, 2, 4, 3}; + auto res = sol.minSubArrayLen(target, nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode209-minimum-size-subarray-sum_sliding_window.cpp b/cpp-leetcode/leetcode209-minimum-size-subarray-sum_sliding_window.cpp new file mode 100644 index 00000000..44910c1e --- /dev/null +++ b/cpp-leetcode/leetcode209-minimum-size-subarray-sum_sliding_window.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +// 滑动窗口(双指针) +// 用 2 个指针,一个指向数组开始的位置,一个指向数组最后的位置, +// 并维护区间内的和 sum 大于等于 s 同时数组长度最小。 +class Solution { +public: + int minSubArrayLen(int target, vector& nums){ + int len = nums.size(); + if (len == 0) + return 0; + + int minLen = INT_MAX; + int left = 0, sum = 0; + for (int i = 0; i < len; ++i) /* i: right指针 */ + { + sum += nums[i]; + while (sum >= target) + { + minLen = min(minLen, i - left + 1); + sum -= nums[left]; + left++; + } + } + return (minLen == INT_MAX) ? 0 : minLen; + } +}; + +// Test +int main() +{ + Solution sol; + int target = 7; + vector nums = {2, 3, 1, 2, 4, 3}; + auto res = sol.minSubArrayLen(target, nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode21-merge-two-sorted-lists.cpp b/cpp-leetcode/leetcode21-merge-two-sorted-lists.cpp new file mode 100644 index 00000000..3d3c6426 --- /dev/null +++ b/cpp-leetcode/leetcode21-merge-two-sorted-lists.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +using namespace std; + +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) + { + // 头插法: 新建一个虚拟节点 + ListNode *cur = new ListNode(-1); + ListNode *fakeHead = cur; + + while (l1 != NULL || l2 != NULL) + { + if (l1 == NULL) + { + cur->next = l2; + break; // 把剩下一个链表挂接上,中止当前循环 + } + else if (l2 == NULL) + { + cur->next = l1; + break; + } + + if (l1->val <= l2->val) + { + cur->next = l1; + cur = l1; + l1 = l1->next; + } + else + { + cur->next = l2; + cur = l2; + l2 = l2->next; + } + } + + return fakeHead->next; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + ListNode *l2; + + l1 = new ListNode(1); + l1->next = new ListNode(3); + l1->next->next = new ListNode(6); + l1->next->next->next = NULL; + + l2 = new ListNode(5); + l2->next = new ListNode(8); + l2->next->next = new ListNode(10); + l2->next->next->next = NULL; + ListNode *res = sol.mergeTwoLists(l1, l2); + + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode211-design-add-and-search-words-data-structure_trie_with_dfs.cpp b/cpp-leetcode/leetcode211-design-add-and-search-words-data-structure_trie_with_dfs.cpp new file mode 100644 index 00000000..a37c2a86 --- /dev/null +++ b/cpp-leetcode/leetcode211-design-add-and-search-words-data-structure_trie_with_dfs.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +using namespace std; + +struct TrieNode { + TrieNode() : kids(26) {} + ~TrieNode() { + for (TrieNode* child : kids) + delete child; + } + vector kids; + bool isWord = false; +}; + +class WordDictionary { +public: + /** Initialize your data structure here. */ + WordDictionary() {} + void addWord(const string &word) { + TrieNode* node = &root; + for (const char c : word) + { + const int i = c - 'a'; + if (!node->kids[i]) + node->kids[i] = new TrieNode; + node = node->kids[i]; + } + node->isWord = true; + } + + bool search(const string &word) + { + return dfs(word, 0, &root); + } + +private: + TrieNode root; + + bool dfs(const string &word, int startPos, TrieNode* node) + { + if (startPos == word.length()) // 第1种出口 + return node->isWord; + if (word[startPos] != '.') // 第2种出口 + { + TrieNode* next = node->kids[word[startPos] - 'a']; + if (next == nullptr) return false; + return dfs(word, startPos + 1, next); + } + + // 如果word[startPos] == '.', .表示任意一个字母 -> 去26棵子树中搜索 + for (int i = 0; i < 26; i++) + if (node->kids[i] && dfs(word, startPos + 1, node->kids[i])) + return true; + + return false; + } +}; + +// Test +int main() +{ + WordDictionary* wordDict = new WordDictionary(); + wordDict->addWord("bad"); + wordDict->addWord("dad"); + wordDict->addWord("mad"); + bool res = wordDict->search("pad"); // return False + cout << (res == true ? "True" : "False") << endl; + res = wordDict->search("bad"); // return True + cout << (res == true ? "True" : "False") << endl; + res = wordDict->search(".ad"); // return True + cout << (res == true ? "True" : "False") << endl; + res = wordDict->search("b.."); // return True + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode212-word-search-ii_trie_dfs1.cpp b/cpp-leetcode/leetcode212-word-search-ii_trie_dfs1.cpp new file mode 100644 index 00000000..3d5a06f2 --- /dev/null +++ b/cpp-leetcode/leetcode212-word-search-ii_trie_dfs1.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + struct TrieNode { + TrieNode* kids[26]; + string word; + TrieNode() : word("") + { + for (int i = 0; i < 26; i++) + kids[i] = nullptr; + } + }; + +public: + vector findWords(vector>& board, vector& words) { + TrieNode *root = buildTrie(words); + vector res; + for (int i = 0; i < board.size(); i++) + { + for (int j = 0; j < board[0].size(); j++) + dfs(board, i, j, root, res); + } + return res; + } + + /** Insert all the words */ + TrieNode* buildTrie(vector& words) + { + TrieNode* root = new TrieNode(); + for (int j = 0; j < words.size(); j++) + { + string word = words[j]; + TrieNode* curr = root; + for (int i = 0; i < word.length(); i++) + { + char ch = word[i] - 'a'; + if (curr->kids[ch] == nullptr) + curr->kids[ch] = new TrieNode(); + curr = curr->kids[ch]; + } + curr->word = word; + } + return root; + } + + void dfs(vector>& board, int i, int j, TrieNode* p, vector& res) { + const int m = board.size(); + const int n = board[0].size(); + char ch = board[i][j]; + if (ch == '#' || p->kids[ch - 'a'] == nullptr) return; + p = p->kids[ch - 'a']; + if (p->word.size() > 0) + { + res.push_back(p->word); + p->word = ""; + } + + board[i][j] = '#'; + if (i > 0) dfs(board, i - 1, j, p, res); + if (j > 0) dfs(board, i, j - 1, p, res); + if (i < m - 1) dfs(board, i + 1, j, p, res); + if (j < n - 1) dfs(board, i, j + 1, p, res); + board[i][j] = ch; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'o', 'a', 'a', 'n'}, + {'e', 't', 'a', 'e'}, + {'i', 'h', 'k', 'r'}, + {'i', 'f', 'l', 'v'} + }; + vector words = {"oath", "pea", "eat", "rain"}; + auto res = sol.findWords(board, words); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode212-word-search-ii_trie_dfs2_set.cpp b/cpp-leetcode/leetcode212-word-search-ii_trie_dfs2_set.cpp new file mode 100644 index 00000000..c3e446cc --- /dev/null +++ b/cpp-leetcode/leetcode212-word-search-ii_trie_dfs2_set.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + struct TrieNode { + int id; + TrieNode* kids[26]; + TrieNode() + { + id = -1; + for (int i = 0; i < 26; i++) + kids[i] = nullptr; + } + }; + TrieNode* root; + unordered_set ids; /* 存放各个单词在原数组转为set后的虚拟index(set不能直接用index访问) */ + vector> B; + const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; + + vector findWords(vector>& board, vector& words) { + B = board; + root = new TrieNode(); + for (int i = 0; i < words.size(); i++) + insert(words[i], i); + + for (int i = 0; i < B.size(); i++) + for (int j = 0; j < B[0].size(); j++) + { + int u = B[i][j] - 'a'; + if (root->kids[u]) + dfs(i, j, root->kids[u]); + } + + vector res; + for (auto id : ids) + res.push_back(words[id]); + return res; + } + + void insert(string& word, int id) + { + auto p = root; + for (auto& c : word) + { + int u = c - 'a'; + if (!p->kids[u]) + p->kids[u] = new TrieNode(); + p = p->kids[u]; + } + p->id = id; + } + + void dfs(int x, int y, TrieNode* p) + { + if (p->id != -1) ids.insert(p->id); + char ch = B[x][y]; + B[x][y] = '.'; + for (int i = 0; i < 4; i++) + { + int a = x + dx[i], b = y + dy[i]; + if (a >= 0 && a < B.size() && b >= 0 && b < B[0].size() && B[a][b] != '.') + { + int u = B[a][b] - 'a'; + if (p->kids[u]) + dfs(a, b, p->kids[u]); + } + } + B[x][y] = ch; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'o', 'a', 'a', 'n'}, + {'e', 't', 'a', 'e'}, + {'i', 'h', 'k', 'r'}, + {'i', 'f', 'l', 'v'} + }; + vector words = {"oath", "pea", "eat", "rain"}; + auto res = sol.findWords(board, words); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode212-word-search-ii_trie_dfs3.cpp b/cpp-leetcode/leetcode212-word-search-ii_trie_dfs3.cpp new file mode 100644 index 00000000..da1a57a1 --- /dev/null +++ b/cpp-leetcode/leetcode212-word-search-ii_trie_dfs3.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include +#include +using namespace std; + +struct TrieNode { + vector kids; + const string *word; + TrieNode() : kids(26), word(nullptr) {} + ~TrieNode() + { + for (auto node : kids) delete node; + } +}; +class Solution { +public: + vector findWords(vector>& board, vector& words) { + TrieNode root; + for (const string &word : words) + { + TrieNode *cur = &root; + for (char c : word) + { + auto &next = cur->kids[c - 'a']; + if (!next) next = new TrieNode(); + cur = next; + } + cur->word = &word; + } + + const int n = board.size(); + const int m = board[0].size(); + vector res; + + function dfs = [&](int x, int y, TrieNode *node) { + if (x < 0 || x == m || y < 0 || y == n || board[y][x] == '#') + return; + + const char cur = board[y][x]; + TrieNode *next_node = node->kids[cur - 'a']; + + // 剪枝 + if (!next_node) return; + + if (next_node->word) + { + res.push_back(*next_node->word); + next_node->word = nullptr; + } + + board[y][x] = '#'; + dfs(x + 1, y, next_node); + dfs(x - 1, y, next_node); + dfs(x, y + 1, next_node); + dfs(x, y - 1, next_node); + board[y][x] = cur; + }; + + // 尝试所有的路径 + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + dfs(j, i, &root); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'o', 'a', 'a', 'n'}, + {'e', 't', 'a', 'e'}, + {'i', 'h', 'k', 'r'}, + {'i', 'f', 'l', 'v'} + }; + vector words = {"oath", "pea", "eat", "rain"}; + auto res = sol.findWords(board, words); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode213-house-robber-ii_solution_iterative.cpp b/cpp-leetcode/leetcode213-house-robber-ii_solution_iterative.cpp new file mode 100644 index 00000000..2427ea2d --- /dev/null +++ b/cpp-leetcode/leetcode213-house-robber-ii_solution_iterative.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + +class Solution { +public: + int rob(vector& nums) { + if (nums.size() == 0) return 0; + if (nums.size() == 1) return nums[0]; + int max1 = optSum(nums, 0, nums.size() - 2); // 情形2 + int max2 = optSum(nums, 1, nums.size() - 1); // 情形3 + return max(max1, max2); + } + // 情形1: 198.打家劫舍 的逻辑 + int optSum(vector& nums, int start, int end) { + if (end == start) return nums[start]; + vector opt(nums.size()); + opt[start] = nums[start]; + opt[start + 1] = max(nums[start], nums[start + 1]); + + for (int i = start + 2; i <= end; i++) { + opt[i] = max(opt[i - 2] + nums[i], opt[i - 1]); + } + return opt[end]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2,3,2}; + auto res = sol.rob(nums); + cout << res << endl; + + nums = {1,2,3,1}; + res = sol.rob(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode215-kth-largest-element-in-an-array-method1.cpp b/cpp-leetcode/leetcode215-kth-largest-element-in-an-array-method1.cpp new file mode 100644 index 00000000..e3863316 --- /dev/null +++ b/cpp-leetcode/leetcode215-kth-largest-element-in-an-array-method1.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int res; + priority_queue q; + + unsigned int i = 0; + while(i < nums.size()) + { + q.push(nums[i]); + i++; + } + + while(q.size() > nums.size() - k + 1) // 把k-1个最大的弹出来 + { + q.pop(); + } + res = q.top(); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 3,2,1,5,6,4 }; + int k = 2; + auto res = sol.findKthLargest(nums, k); + cout << res << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode215-kth-largest-element-in-an-array-method2.cpp b/cpp-leetcode/leetcode215-kth-largest-element-in-an-array-method2.cpp new file mode 100644 index 00000000..44c40454 --- /dev/null +++ b/cpp-leetcode/leetcode215-kth-largest-element-in-an-array-method2.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + sort(nums.begin(),nums.end()); + return nums[nums.size() - k]; /* 最后1个数(index是len-1)是第1大,而不是第0大。于是第k大的数的index的 len-1-(k-1) = len - k */ + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 3,2,1,5,6,4 }; + int k = 2; + auto res = sol.findKthLargest(nums, k); + cout << res << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode219-contains-duplicate-ii.cpp b/cpp-leetcode/leetcode219-contains-duplicate-ii.cpp new file mode 100644 index 00000000..8e4629e4 --- /dev/null +++ b/cpp-leetcode/leetcode219-contains-duplicate-ii.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution +{ +public: + bool containsNearbyDuplicate(vector &nums, int k) + { + unordered_map map; // value -> index + for (int i = 0; i < nums.size(); i++) + { + if (map.find(nums[i]) != map.end() && abs(map[nums[i]] - i) <= k) + return true; + else { + map[nums[i]] = i; + } + } + + return false; + } +}; + +int main() +{ + Solution sol; + vector nums = {1,2,3,1}; + int k = 3; + + bool res = sol.containsNearbyDuplicate(nums, k); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode22-generate-parentheses-solution1.cpp b/cpp-leetcode/leetcode22-generate-parentheses-solution1.cpp new file mode 100644 index 00000000..f88e9165 --- /dev/null +++ b/cpp-leetcode/leetcode22-generate-parentheses-solution1.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector generateParenthesis(int n) { + unordered_set st; + if (n == 0) st.insert(""); + else { + vector pre = generateParenthesis(n - 1); + for (string str : pre) { + for (int i = 0; i < str.size(); ++i) { + if (str[i] == '(') { + string s(str); + s.insert(s.begin() + i + 1, '('); + s.insert(s.begin() + i + 2, ')'); // 在每一个'('之后加入一对() + st.insert(s); + } + } + st.insert("()" + str); + } + } + return vector(st.begin(), st.end()); + } +}; + +// Test +int main() +{ + Solution sol; + int n = 3; + vector res = sol.generateParenthesis(n); + + for(string str : res) + { + cout << str << endl; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode223-rectangle-area_solution1.cpp b/cpp-leetcode/leetcode223-rectangle-area_solution1.cpp new file mode 100644 index 00000000..b296edc7 --- /dev/null +++ b/cpp-leetcode/leetcode223-rectangle-area_solution1.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +class Solution { +public: + int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { + long x1 = max(A, E); // 左下角的横坐标 + long y1 = max(B, F); // 左下角的纵坐标 + long x2 = min(C, G); // 右上角的横坐标 + long y2 = min(D, H); // 右上角的纵坐标 + long commonArea; // 重叠区域的面积, 不相交时值为0 + if (x1 >= x2 || y1 >= y2) + commonArea = 0; + else + commonArea = max(long(0), (x2 - x1) * (y2 - y1)); + return (C - A) * (D - B) + (G - E) * (H - F) - commonArea; + } +}; + +// Test +int main() +{ + Solution sol; + int ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2; + auto res = sol.computeArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode224-basic-calculator_stack.cpp b/cpp-leetcode/leetcode224-basic-calculator_stack.cpp new file mode 100644 index 00000000..26d5fd4a --- /dev/null +++ b/cpp-leetcode/leetcode224-basic-calculator_stack.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int calculate(string s) { + stack nums; // 存储原字符串中的数 + stack ops; // 存储原字符串中的符号(含括号和+-) + for (int i = 0; i < s.size(); i++) + { + auto c = s[i]; + if (c == ' ') continue; // 过滤空格 + if (isdigit(c)) + { + int n = 0; + int j = i; + while (j < s.size() && isdigit(s[j])) + n = n*10 + (s[j++] - '0'); + i = j-1; + nums.push(n); + } + else if (c == '(') ops.push(c); + else if (c == ')') + { + while (ops.top() != '(') + myEval(nums, ops); + ops.pop(); + } + else + { + if (i == 0 || s[i - 1] == '(' || s[i - 1] == '+' || s[i - 1] == '-') // 特殊处理符号和正号 + nums.push(0); + while (!ops.empty() && ops.top() != '(') /* 由于此题中运算符只有+或-, 故不需要比较不同运算符的优先级了(括号前面已经处理了) */ + myEval(nums, ops); + ops.push(c); + } + } + while (!ops.empty()) myEval(nums, ops); + return nums.top(); + } + void myEval(stack& nums, stack& ops) + { + if (ops.empty()) return; + int res; + + auto b = nums.top(); + nums.pop(); + int a = 0; + if (nums.size() > 0) + { + a = nums.top(); + nums.pop(); + } + auto c = ops.top(); + ops.pop(); + + if (c == '+') res = a + b; + else if (c == '-') res = a - b; + nums.push(res); + } +}; + +// Test +int main() +{ + Solution sol; + // string s = "(1+(4+5+2)-3)+(6+8)"; //"-2+ 1"; + string s = "1-(-2)"; //"-2+ 1"; + auto res = sol.calculate(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode225-implement-stack-using-queues_one_queue.cpp b/cpp-leetcode/leetcode225-implement-stack-using-queues_one_queue.cpp new file mode 100644 index 00000000..60b77eef --- /dev/null +++ b/cpp-leetcode/leetcode225-implement-stack-using-queues_one_queue.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +using namespace std; + +class MyStack { +public: + queue q; + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + q.push(x); + for (int i = 0; i < q.size() - 1; i++) + { + q.push(q.front()); + q.pop(); + } + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + int res = q.front(); + q.pop(); + return res; + } + + /** Get the top element. */ + int top() { + return q.front(); + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q.empty(); + } +}; + +// Test +int main() +{ + MyStack *st = new MyStack(); + st->push(1); + st->push(2); + int res1 = st->top(); // 返回 2 + cout << res1 << endl; + int res2 = st->pop(); // 返回 2 + cout << res2 << endl; + bool isEmpty = st->empty(); // 返回 False + cout << (isEmpty ? "False" : "True") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode225-implement-stack-using-queues_two_queues1.cpp b/cpp-leetcode/leetcode225-implement-stack-using-queues_two_queues1.cpp new file mode 100644 index 00000000..3e9beeba --- /dev/null +++ b/cpp-leetcode/leetcode225-implement-stack-using-queues_two_queues1.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +using namespace std; + +class MyStack { +public: + queue q1; + queue q2; // 辅助队列 + + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + q1.push(x); + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + int size = q1.size(); + while (size > 1) { // 将q1 导入q2,但要留下最后一个元素 + q2.push(q1.front()); + q1.pop(); + size--; + } + + int res = q1.front(); + q1.pop(); + + q1 = q2; // 将q2赋值给q1 + while (!q2.empty()) // 清空q2 + q2.pop(); + return res; + } + + /** Get the top element. */ + int top() { + return q1.back(); + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q1.empty(); + } +}; + +// Test +int main() +{ + MyStack *st = new MyStack(); + st->push(1); + st->push(2); + int res1 = st->top(); // 返回 2 + cout << res1 << endl; + int res2 = st->pop(); // 返回 2 + cout << res2 << endl; + bool isEmpty = st->empty(); // 返回 False + cout << (isEmpty ? "False" : "True") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode225-implement-stack-using-queues_two_queues2.cpp b/cpp-leetcode/leetcode225-implement-stack-using-queues_two_queues2.cpp new file mode 100644 index 00000000..ef5e0788 --- /dev/null +++ b/cpp-leetcode/leetcode225-implement-stack-using-queues_two_queues2.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +using namespace std; + +class MyStack { +public: + queue q1; + queue q2; // 辅助队列 + + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + q1.push(x); + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + int size = q1.size(); + while (size > 1) { // 将q1 导入q2,但要留下最后一个元素 + q2.push(q1.front()); + q1.pop(); + size--; + } + + int res = q1.front(); + q1.pop(); + swap(q1, q2); + + return res; + } + + /** Get the top element. */ + int top() { + return q1.back(); + } + + /** Returns whether the stack is empty. */ + bool empty() { + return q1.empty(); + } +}; + +// Test +int main() +{ + MyStack *st = new MyStack(); + st->push(1); + st->push(2); + int res1 = st->top(); // 返回 2 + cout << res1 << endl; + int res2 = st->pop(); // 返回 2 + cout << res2 << endl; + bool isEmpty = st->empty(); // 返回 False + cout << (isEmpty ? "False" : "True") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode227-basic-calculator-ii_stack1.cpp b/cpp-leetcode/leetcode227-basic-calculator-ii_stack1.cpp new file mode 100644 index 00000000..e2060021 --- /dev/null +++ b/cpp-leetcode/leetcode227-basic-calculator-ii_stack1.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +using namespace std; +// 特点: 没有括号, 使用栈来做 +class Solution { +public: + int calculate(string s) { + string temp; + for (auto ch : s) + { + if (ch != ' ') + temp.push_back(ch); + } + s = "+" + temp; + + int len = s.size(); + vector nums; + + for (int i=0; i < len; i++) + { + if (s[i] == '+' || s[i] == '-') + { + int j = i+1; // 找出"+200"这种结构中的数字 + while (j < len && isdigit(s[j])) j++; // 循环结束时, j多跑了1位 + int endPos = j-1; + int num = stoi(s.substr(i+1, endPos-(i+1)+1)); + if (s[i] == '+') nums.push_back(num); + else nums.push_back(-num); + i = endPos; + } + else if (s[i] == '*' || s[i] == '/') + { + int j = i+1; // 找出"*100"这种结构中的数字 + while (j < len && isdigit(s[j])) j++; + int endPos = j-1; + int num = stoi(s.substr(i+1, endPos-(i+1)+1)); + if (s[i] == '*') + nums.back() = nums.back() * num; + else nums.back() = nums.back() / num; + i = endPos; + } + } + int sum = 0; + for (int i=0; i < nums.size(); i++) sum += nums[i]; + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + string s = " 3+5 / 2 "; + auto res = sol.calculate(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode227-basic-calculator-ii_stack2.cpp b/cpp-leetcode/leetcode227-basic-calculator-ii_stack2.cpp new file mode 100644 index 00000000..533603aa --- /dev/null +++ b/cpp-leetcode/leetcode227-basic-calculator-ii_stack2.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +#include +#include /* 含有 accumulate 函数 */ +using namespace std; + +// 特点: 没有括号, 使用栈来做 +class Solution { +public: + int calculate(string s) { + auto spaceEndIts = remove(s.begin(), s.end(), ' '); + s.erase(spaceEndIts, s.end()); + s = "+" + s; + + int len = s.size(); + vector nums; + + for (int i=0; i < len; i++) + { + if (s[i] == '+' || s[i] == '-') + { + int j = i+1; // 找出"+200"这种结构中的数字 + while (j < len && isdigit(s[j])) j++; // 循环结束时, j多跑了1位 + int endPos = j-1; + int num = stoi(s.substr(i+1, endPos-(i+1)+1)); + if (s[i] == '+') nums.push_back(num); + else nums.push_back(-num); + i = endPos; + } + else if (s[i] == '*' || s[i] == '/') + { + int j = i+1; // 找出"*100"这种结构中的数字 + while (j < len && isdigit(s[j])) j++; + int endPos = j-1; + int num = stoi(s.substr(i+1, endPos-(i+1)+1)); + if (s[i] == '*') + nums.back() = nums.back() * num; + else nums.back() = nums.back() / num; + i = endPos; + } + } + int sum = accumulate(nums.begin(), nums.end(), 0); + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + string s = " 3+5 / 2 "; + auto res = sol.calculate(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode229-majority-element-ii_Moore_voting_method.cpp b/cpp-leetcode/leetcode229-majority-element-ii_Moore_voting_method.cpp new file mode 100644 index 00000000..373cf888 --- /dev/null +++ b/cpp-leetcode/leetcode229-majority-element-ii_Moore_voting_method.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector majorityElement(vector& nums) { + vector res; + const int len = nums.size(); + int cand1, cand2; /* 最多有2个众数(出现超过 ⌊n/3⌋ 次), 后面打擂台更新 */ + int votes1 = 0, votes2 = 0; + // 第1阶段 - 成对抵销 + for (int i = 0; i < len; i++) + { + // votes1 之前已经出现过, 这里再次出现 + if (votes1 > 0 && nums[i] == cand1) votes1++; + else if (votes2 > 0 && nums[i] == cand2) votes2++; + // cand1 第一次出现 + else if (votes1 == 0) + { + cand1 = nums[i]; + votes1 = 1; + } + else if (votes2 == 0) + { + cand2 = nums[i]; + votes2 = 1; + } + else /* cand1或cand2 之前已经出现过, 但此时第3个数(竞争者)第1次出现 */ + { + votes1--; + votes2--; + } + } + + // 第2阶段 - 计数, 数目要超过三分之一 + votes1 = 0, votes2 = 0; + for (auto &num : nums) + { + if (num == cand1) votes1++; + else if (num == cand2) votes2++; + } + if (votes1 > len / 3) + res.push_back(cand1); + if (votes2 > len / 3) + res.push_back(cand2); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 3, 3, 2, 2, 2}; + auto res = sol.majorityElement(nums); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode23-merge-k-sorted-lists.cpp b/cpp-leetcode/leetcode23-merge-k-sorted-lists.cpp new file mode 100644 index 00000000..953a02ca --- /dev/null +++ b/cpp-leetcode/leetcode23-merge-k-sorted-lists.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode *mergeKLists(vector &lists) + { + if (lists.empty()) + return NULL; + + ListNode *res; + auto cmp = [](ListNode *n1, ListNode *n2) + { + return n1->val > n2->val; + }; + + /* 使用node的val构造一个小顶堆 */ + priority_queue, decltype(cmp)> nodesQ(cmp); + for (auto list : lists) + { + if (list != NULL) + { + nodesQ.push(list); + } + } + + ListNode *fakeHead = new ListNode(-1); /* 创建虚拟头结点 */ + ListNode *cur = fakeHead; + while (!nodesQ.empty()) + { + cur->next = nodesQ.top(); /* 取出最小值对应的结点指针,挂接在游标指针上 */ + cur = cur->next; + nodesQ.pop(); + + if (cur->next != NULL) /* 只要挂接点后面还有结点,则将其压入栈,继续从中拿出最大值,循环往复 */ + { + nodesQ.push(cur->next); + } + } + + return fakeHead->next; + } +}; + +// Test +int main() +{ + Solution sol; + // l1 = {1,2,4}, l2 = {1,3,4} + ListNode *l1 = new ListNode(1); + l1 -> next = new ListNode(2); + l1 -> next -> next = new ListNode(4); + ListNode *l2 = new ListNode(1); + l1 -> next = new ListNode(3); + l1 -> next -> next = new ListNode(4); + vector vec; + vec.push_back(l1); + vec.push_back(l2); + ListNode* res = sol.mergeKLists(vec); + + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode230-kth-smallest-element-in-a-bst_travesal.cpp b/cpp-leetcode/leetcode230-kth-smallest-element-in-a-bst_travesal.cpp new file mode 100644 index 00000000..6e8805bb --- /dev/null +++ b/cpp-leetcode/leetcode230-kth-smallest-element-in-a-bst_travesal.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + if (root == NULL) return 0; + int res; + vector vals; + inorder(root, vals); + if (vals.size() < k) res = 0; + else res = vals[k-1]; + + return res; + } + void inorder(TreeNode* root, vector& vals) + { + if (root == NULL) return; + inorder(root->left, vals); + vals.push_back(root->val); + inorder(root->right, vals); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(10); + root->left = new TreeNode(5); + root->right = new TreeNode(15); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(7); + root->right->right = new TreeNode(18); + + auto res = sol.kthSmallest(root, 3); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode232-implement-queue-using-stacks_two_stacks.cpp b/cpp-leetcode/leetcode232-implement-queue-using-stacks_two_stacks.cpp new file mode 100644 index 00000000..f76e4aaf --- /dev/null +++ b/cpp-leetcode/leetcode232-implement-queue-using-stacks_two_stacks.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +using namespace std; + +class MyQueue { + stack s1, s2; + int front; + +public: + /** Initialize your data structure here. */ + MyQueue() {} + + /** Push element x to the back of queue. */ + void push(int x) { + if (s1.empty()) + front = x; + + s1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + if (s2.empty()) + { + while (!s1.empty()) + { /* 把s1中的元素全部移到s2中 */ + s2.push(s1.top()); + s1.pop(); + } + } + int res = s2.top(); + s2.pop(); + + return res; + } + + /** Get the front element. */ + int peek() { + if (!s2.empty()) + return s2.top(); + + return front; + } + + /** Returns whether the queue is empty. */ + bool empty() { + return s1.empty() && s2.empty(); + } +}; + +// Test +int main() +{ + MyQueue* q = new MyQueue(); + q->push(1); + q->push(2); + int val = q->peek(); + cout << val << endl; + int val2 = q->pop(); // return 1, queue is [2] + cout << val2 << endl; + bool isEmpty = q->empty(); + cout << (isEmpty ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode233-number-of-digit-one_case_by_classification.cpp b/cpp-leetcode/leetcode233-number-of-digit-one_case_by_classification.cpp new file mode 100644 index 00000000..e316f86a --- /dev/null +++ b/cpp-leetcode/leetcode233-number-of-digit-one_case_by_classification.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int countDigitOne(int n) { + if (n == 0) return 0; /* 0 <= n <= 10^9 */ + + int curDigit; + int count = 0; // 记录1的数量 + long highDigt, lastDigit, weigh = 1; // weigh用来记录置1的位置处于个位、十位、百位、千位等... + while (weigh <= n) // weigh每次乘10相对于从低位向高位方向逐位移动,直到超过n时结束循环 + { + highDigt = n / (weigh * 10); // 得到某一个位数置1后的商,即当前数之前的部分 + lastDigit = n % weigh; // 得到某一位数置1后的余数,即当前数之后的部分 + curDigit = (n / weigh) % 10; // 当前置1的位置原来(置1之前)的数 + + if (curDigit == 0) // 当前位置的数字=0时 + count += highDigt * weigh; + if (curDigit == 1) // 当前位置的数字=1时 + count += highDigt * weigh + lastDigit + 1; + if (curDigit > 1) // 当前位置的数字>1时 + count += (highDigt + 1) * weigh; + + weigh *= 10; + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 13; + auto res = sol.countDigitOne(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode235-lowest-common-ancestor-of-a-binary-search-tree_solution1.cpp b/cpp-leetcode/leetcode235-lowest-common-ancestor-of-a-binary-search-tree_solution1.cpp new file mode 100644 index 00000000..378cffc3 --- /dev/null +++ b/cpp-leetcode/leetcode235-lowest-common-ancestor-of-a-binary-search-tree_solution1.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +using namespace std; +/** Definition for a binary tree node. */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr) return nullptr; + if (root == p || root == q) + return root; + + TreeNode* left = lowestCommonAncestor(root->left, p, q); + TreeNode* right = lowestCommonAncestor(root->right, p, q); + + if (left != nullptr && right != nullptr) + return root; + + TreeNode* res = left == nullptr ? right : left; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(6); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(8); + TreeNode *n3 = new TreeNode(0); + TreeNode *n4 = new TreeNode(4); + TreeNode *n5 = new TreeNode(7); + TreeNode *n6 = new TreeNode(9); + TreeNode *n7 = new TreeNode(3); + TreeNode *n8 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + TreeNode *res = sol.lowestCommonAncestor(root, n1, n7); /* 输出2与3的LCA */ + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode235-lowest-common-ancestor-of-a-binary-search-tree_solution2.cpp b/cpp-leetcode/leetcode235-lowest-common-ancestor-of-a-binary-search-tree_solution2.cpp new file mode 100644 index 00000000..6f5d0288 --- /dev/null +++ b/cpp-leetcode/leetcode235-lowest-common-ancestor-of-a-binary-search-tree_solution2.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +using namespace std; +/** Definition for a binary tree node. */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + int pVal(p->val), qVal(q->val); + + while (root) { + int rootVal = root->val; + if ((rootVal > pVal && rootVal > qVal)) root = root->left; + else if (rootVal < pVal && rootVal < qVal) root = root->right; + else return root; + } + return root; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(6); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(8); + TreeNode *n3 = new TreeNode(0); + TreeNode *n4 = new TreeNode(4); + TreeNode *n5 = new TreeNode(7); + TreeNode *n6 = new TreeNode(9); + TreeNode *n7 = new TreeNode(3); + TreeNode *n8 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + TreeNode *res = sol.lowestCommonAncestor(root, n1, n7); /* 输出2与3的LCA */ + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode236-lowest-common-ancestor-of-a-binary-tree_recursive.cpp b/cpp-leetcode/leetcode236-lowest-common-ancestor-of-a-binary-tree_recursive.cpp new file mode 100644 index 00000000..9dd3d18d --- /dev/null +++ b/cpp-leetcode/leetcode236-lowest-common-ancestor-of-a-binary-tree_recursive.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +using namespace std; +/* Definition for a binary tree node. */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr) return nullptr; + if (root == p || root == q) + return root; + + TreeNode* left = lowestCommonAncestor(root->left, p, q); /* 在左子树中是否能找到P或Q结点, 返回dfs结束时的TreeNode */ + TreeNode* right = lowestCommonAncestor(root->right, p, q); /* 在右子树中是否能找到P或Q结点, 返回dfs结束时的TreeNode */ + if (left != nullptr && right != nullptr) + return root; + + TreeNode* res = left == nullptr ? right : left; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(3); + TreeNode *n1 = new TreeNode(5); + TreeNode *n2 = new TreeNode(1); + TreeNode *n3 = new TreeNode(6); + TreeNode *n4 = new TreeNode(2); + TreeNode *n5 = new TreeNode(0); + TreeNode *n6 = new TreeNode(8); + TreeNode *n7 = new TreeNode(7); + TreeNode *n8 = new TreeNode(4); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n2->left = n5; + n2->right = n6; + n4->left = n7; + n4->right = n8; + TreeNode *res = sol.lowestCommonAncestor(root, n3, n8); /* 输出6与4的LCA */ + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode237-delete-node-in-a-linked-list_solution1.cpp b/cpp-leetcode/leetcode237-delete-node-in-a-linked-list_solution1.cpp new file mode 100644 index 00000000..77460e71 --- /dev/null +++ b/cpp-leetcode/leetcode237-delete-node-in-a-linked-list_solution1.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + void deleteNode(ListNode* node) { + node->val = node->next->val; /* 将要删除的node记作toBeDel, 这一步的作用是将结点toBeDel的value更新为与它的下一个node相等的值 */ + node->next = node->next->next; // 将结点toBeDel的下一个结点跳过(删掉) + } +}; + +// Test +int main() +{ + Solution sol; // 5->2->3->8->6 + ListNode* head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = new ListNode(6); + head->next->next->next->next->next = nullptr; + + auto node = head->next->next; // 要删除的node的val为3 + sol.deleteNode(node); + + auto p = head; + while (p != nullptr) + { + cout << p->val << " "; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode237-delete-node-in-a-linked-list_solution2.cpp b/cpp-leetcode/leetcode237-delete-node-in-a-linked-list_solution2.cpp new file mode 100644 index 00000000..3238ed14 --- /dev/null +++ b/cpp-leetcode/leetcode237-delete-node-in-a-linked-list_solution2.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + void deleteNode(ListNode* node) { + *node = *(node->next); // 可以直接使用指针对结构体赋值 + } +}; + +// Test +int main() +{ + Solution sol; // 5->2->3->8->6 + ListNode* head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = new ListNode(6); + head->next->next->next->next->next = nullptr; + + auto node = head->next->next; // 要删除的node的val为3 + sol.deleteNode(node); + + auto p = head; + while (p != nullptr) + { + cout << p->val << " "; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode238-product-of-array-except-self_prefix_sum.cpp b/cpp-leetcode/leetcode238-product-of-array-except-self_prefix_sum.cpp new file mode 100644 index 00000000..74142aba --- /dev/null +++ b/cpp-leetcode/leetcode238-product-of-array-except-self_prefix_sum.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector productExceptSelf(vector& nums) { + const int len = nums.size(); + vector preProd(len); + preProd[0] = 1; + for (int i = 1; i < len; i++) + preProd[i] = preProd[i-1] * nums[i-1]; + + // 接下来求rightProduct + int right = 1; + for (int i = len-1; i >= 0; i--) + { + preProd[i] *= right; + right *= nums[i]; + } + return preProd; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {3, 2, 8, 5}; + auto res = sol.productExceptSelf(nums); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode239-sliding-window-max.cpp b/cpp-leetcode/leetcode239-sliding-window-max.cpp new file mode 100644 index 00000000..1fc7a80b --- /dev/null +++ b/cpp-leetcode/leetcode239-sliding-window-max.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector res; + vector maxSlidingWindow(vector& nums, int k) { + deque indexQ; // 双端队列,存储的是当前窗口最大值的索引,维护操作: 保持单调递减,队头是最大值 + + cout << "Current deque:" << endl; + for (int i = 0; i < nums.size(); i++) { + // 依次地将数组元素加入到队列中 + // 注意: 确保队列元素间的距离都在k以内 + while (!indexQ.empty() && i - k + 1 > indexQ.front()) /* 倒着数第k个与队列开头数的index比较。窗口长度>k时,从队列中删掉最前面的数 */ + indexQ.pop_front(); + while (!indexQ.empty() && nums[i] >= nums[indexQ.back()]) + indexQ.pop_back(); /* 不断地把左侧比自己小的数从队列中删掉, 遇到下一个比自己大的数时自己会被删掉 */ + + indexQ.push_back(i); + for (int idx:indexQ) + { + cout << idx << "[" << nums[idx] << "]" << " "; + } + cout << endl; + + if (i >= k - 1) // 只要窗口大小 ≥ k 时, 窗口就会有最大值,将其放进res(结果vector)中 + { + res.push_back(nums[indexQ.front()]); + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,3,-1,-3,5,3,6,7}; + int k = 3; + auto res = sol.maxSlidingWindow(nums, k); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode24-swap-nodes-in-pairs_iterate.cpp b/cpp-leetcode/leetcode24-swap-nodes-in-pairs_iterate.cpp new file mode 100644 index 00000000..eb21ccc7 --- /dev/null +++ b/cpp-leetcode/leetcode24-swap-nodes-in-pairs_iterate.cpp @@ -0,0 +1,59 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *swapPairs(ListNode *head) + { + if (head == NULL || head->next == NULL) + return head; + + ListNode *fakeHead = new ListNode(-1); + fakeHead->next = head; + ListNode *cur = fakeHead; + while (cur->next != NULL && cur->next->next != NULL) + { + ListNode *swap1 = cur->next; /* ①与②号结点交换 */ + ListNode *swap2 = cur->next->next; + cur->next = swap2; + swap1->next = swap2->next; /*交换后①号结点的next指针指向③号结点*/ + swap2->next = swap1; + cur = swap1; + } + return fakeHead->next; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = NULL; + + ListNode *res = sol.swapPairs(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode24-swap-nodes-in-pairs_recursive.cpp b/cpp-leetcode/leetcode24-swap-nodes-in-pairs_recursive.cpp new file mode 100644 index 00000000..3c2251b1 --- /dev/null +++ b/cpp-leetcode/leetcode24-swap-nodes-in-pairs_recursive.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *swapPairs(ListNode *head) + { + if (head == NULL || head->next == NULL) + return head; + + ListNode *newHead = head->next; + head-> next = swapPairs(newHead -> next); + newHead -> next = head; + + return newHead; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = NULL; + + ListNode *res = sol.swapPairs(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode240-search-a-2d-matrix-ii_binary_search.cpp b/cpp-leetcode/leetcode240-search-a-2d-matrix-ii_binary_search.cpp new file mode 100644 index 00000000..e84cf2ef --- /dev/null +++ b/cpp-leetcode/leetcode240-search-a-2d-matrix-ii_binary_search.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool searchMatrix(vector>& M, int target) { + int rows = M.size(); + int cols = M.front().size(); + int i = 0; + int j = cols - 1; + bool found = false; + while (i < rows && j >= 0) /* j >= 0别漏了= */ + { + if (M[i][j] == target) return true; + else if (M[i][j] < target) i++; + else j--; + } + return found; + } +}; + +// Test +int main() +{ + Solution sol; + vector> M + { + {1, 4, 7, 11, 15}, + {2, 5, 8, 12, 19}, + {3, 6, 9, 16, 22}, + {10, 13, 14, 17, 24}, + {18, 21, 23, 26, 30} + }; + + int k = 5; + auto res = sol.searchMatrix(M, k); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode25-reverse-nodes-in-k-group_recursive.cpp b/cpp-leetcode/leetcode25-reverse-nodes-in-k-group_recursive.cpp new file mode 100644 index 00000000..7831796e --- /dev/null +++ b/cpp-leetcode/leetcode25-reverse-nodes-in-k-group_recursive.cpp @@ -0,0 +1,75 @@ +#include +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(NULL) {} + ListNode(int x) : val(x), next(NULL) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + if (head == NULL || head->next == NULL) + return head; + + ListNode *p = head; + + // 以下循环代码等价于判断当 len < k 时直接返回head + for (int i = 0; i < k; i++) + { + // 剩余结点数量小于k的话,则不需要反转 + if (p == NULL) + return head; + p = p->next; + } + // 反转前 k 个元素 + ListNode *newHead = reverse(head, p); + // 下一轮的开始的地方就是p + head->next = reverseKGroup(p, k); + + return newHead; + } + + /* 左闭右开区间 */ + ListNode* reverse(ListNode *head, ListNode *tail) { + ListNode *pre = NULL; + ListNode *nextP = NULL; + while (head != tail) + { + nextP = head->next; + head->next = pre; + pre = head; + head = nextP; + } + return pre; + } +}; + +// Test +int main() +{ + Solution sol; + + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = NULL; + int k = 2; + ListNode *res = sol.reverseKGroup(head, k); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode257-binary-tree-path_dfs.cpp b/cpp-leetcode/leetcode257-binary-tree-path_dfs.cpp new file mode 100644 index 00000000..5717bd37 --- /dev/null +++ b/cpp-leetcode/leetcode257-binary-tree-path_dfs.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector binaryTreePaths(TreeNode* root) { + vector res; + dfs(root, "", res); + return res; + } + void dfs(TreeNode *root, string path, vector& res) + { + string curPath = path; + if (!root) return; + // 由于是从上到下的访问顺序, root的值必然需先放进去 + curPath.append(to_string(root->val)); /* curPath.push_back(root->val + '0'); 使用这种方式没法处理结点值是负数的情形 */ + if (root->left == nullptr && root->right == nullptr) + res.push_back(curPath); + else + { + curPath.append("->"); + dfs(root->left, curPath, res); + dfs(root->right, curPath, res); + } + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->right->left = new TreeNode(4); + root->right->right = nullptr; + + vector res = sol.binaryTreePaths(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode258-add-digits_iterative1.cpp b/cpp-leetcode/leetcode258-add-digits_iterative1.cpp new file mode 100644 index 00000000..b044f3c5 --- /dev/null +++ b/cpp-leetcode/leetcode258-add-digits_iterative1.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +class Solution { +public: + int addDigits(int num) { + while(num > 9) + { + num = add(num); + } + + return num; + } + + int add(int num) + { + string str = to_string(num); + int sum = 0; + for(char ch : str) + { + sum += ch - '0'; + } + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 222222222; + auto res = sol.addDigits(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode258-add-digits_iterative2.cpp b/cpp-leetcode/leetcode258-add-digits_iterative2.cpp new file mode 100644 index 00000000..b08bb6e1 --- /dev/null +++ b/cpp-leetcode/leetcode258-add-digits_iterative2.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +class Solution { +public: + int addDigits(int num) { + while(num > 9) + { + num = add(num); + } + + return num; + } + + int add(int num) /* 题中整数num ≥ 0 */ + { + string str = to_string(num); + int sum = 0; + for(char ch : str) + { + sum += ch - '0'; + } + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 222222222; + auto res = sol.addDigits(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode258-add-digits_repeat-recursive.cpp b/cpp-leetcode/leetcode258-add-digits_repeat-recursive.cpp new file mode 100644 index 00000000..4c746ee2 --- /dev/null +++ b/cpp-leetcode/leetcode258-add-digits_repeat-recursive.cpp @@ -0,0 +1,33 @@ +#include +#include +using namespace std; + +/* 此题递归法更快, 0 ms */ +class Solution { +public: + int addDigits(int num) { + if(num < 10) /* 注意临界条件, 应使用 <10 或 ≤ 9 */ + return num; + + long sum = 0; + while(num > 0) + { + long lastDigit = num % 10; + sum += lastDigit; + num /= 10; + } + + return addDigits(sum); /* 再调用1次以免还剩下的数位数>1 */ + } +}; + +// Test +int main() +{ + Solution sol; + int n = 222222222; + auto res = sol.addDigits(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode26-remove-duplicates-from-sorted-array_in_place.cpp b/cpp-leetcode/leetcode26-remove-duplicates-from-sorted-array_in_place.cpp new file mode 100644 index 00000000..015ce465 --- /dev/null +++ b/cpp-leetcode/leetcode26-remove-duplicates-from-sorted-array_in_place.cpp @@ -0,0 +1,30 @@ +#include +#include +using namespace std; +/* 本题要求原地in-place 操作 */ +class Solution { +public: + int removeDuplicates(vector& nums) { + if (nums.empty()) return 0; + int p = 0; // 用指针p 指向发现的新值的index + for (int i = 0; i < nums.size(); i++) + { + if (nums[p] != nums[i]) + { + p++; + nums[p] = nums[i]; + } + } + return p + 1; + } +}; + +// 下面是测试 +int main() +{ + Solution sol; + vector arr = {3, 2, 4, 8, 3}; + auto res = sol.removeDuplicates(arr); + printf("%d ",res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode260-single-number-iii_bit_operation.cpp b/cpp-leetcode/leetcode260-single-number-iii_bit_operation.cpp new file mode 100644 index 00000000..b89f8e27 --- /dev/null +++ b/cpp-leetcode/leetcode260-single-number-iii_bit_operation.cpp @@ -0,0 +1,36 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector singleNumber(vector& nums) { + int theXor = 0; + for (int num : nums) // 对nums数组中的所有数异或运算, 算出两个落单数的异或结果 + theXor ^= num; + int mask = 1; + while ((theXor & mask) == 0) /* 从低位开始向高位扫描, 找出两数的异或结果中的第1个1, 这恰好是两个落单数第一个不同的bit位 */ + mask <<= 1; + /* 接下来, 想办法把所有数分为2组, 且每个组只有1个落单的数, 只需要找一个概率均为50%的条件即可, 比如判断数组中的每一个元素与mask最高位的同一个位置的二进制位是1还是0 */ + int group1 = 0, group2 = 0; + vector res; + for (int num : nums) + { + if (num & mask) + group1 ^= num; + else group2 ^= num; + } + res = {group1, group2}; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 1, 3, 2, 5}; + printf("%d ", sol.singleNumber(nums)); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode262-trips-and-users_mysql.sql b/cpp-leetcode/leetcode262-trips-and-users_mysql.sql new file mode 100644 index 00000000..fff82090 --- /dev/null +++ b/cpp-leetcode/leetcode262-trips-and-users_mysql.sql @@ -0,0 +1,10 @@ +# Write your MySQL query statement below +SELECT tb1.Request_at as Day, Round(SUM(case when tb1.Status = 'completed' then 0 else 1 end)/count(*), 2) as 'Cancellation Rate' +From Trips as tb1 +inner join Users as tb2 +on tb1.Client_Id = tb2.Users_Id and tb2.Banned = "No" +inner join Users as tb3 +on tb1.Driver_id = tb3.Users_Id and tb3.Banned = "No" +WHERE tb1.Request_at between "2013-10-01" and "2013-10-03" +GROUP BY tb1.Request_at +ORDER BY Day \ No newline at end of file diff --git a/cpp-leetcode/leetcode268-missing-number_sum.cpp b/cpp-leetcode/leetcode268-missing-number_sum.cpp new file mode 100644 index 00000000..6fadee13 --- /dev/null +++ b/cpp-leetcode/leetcode268-missing-number_sum.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int missingNumber(vector& nums) { + const int len = nums.size(); // len = n-1 + int expectSum = len*(len+1)/2; // (n-1)*n/2 + int sum = 0; + for (int i = 0; i < len; i++) + sum += nums[i]; + + return (expectSum - sum); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {9, 6, 4, 2, 3, 5, 7, 0, 1}; + auto res = sol.missingNumber(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode27-remove-element_solution1.cpp b/cpp-leetcode/leetcode27-remove-element_solution1.cpp new file mode 100644 index 00000000..23563030 --- /dev/null +++ b/cpp-leetcode/leetcode27-remove-element_solution1.cpp @@ -0,0 +1,35 @@ +#include +#include +using namespace std; + +class Solution { +public: + int removeElement(vector& nums, int val) { + if(nums.empty()) + return 0; + + // 双指针法 + int p = 0; /* p是从头开始走的指针,也有计数器的作用。只有遇到不等于目标值val的时候才移动1步, 且nums[p]总是更新为≠val的值 */ + for(int i = 0; i < nums.size(); i++) /* 一开始p和循环指针i都指向0,后面不同步移动 */ + { + if(nums[i] != val) + { + nums[p] = nums[i]; + p++; + } + } + return p; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {0,1,2,2,3,0,4,2}; + int target = 2; + int res = sol.removeElement(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode273-integer-to-english-words_my_solution.cpp b/cpp-leetcode/leetcode273-integer-to-english-words_my_solution.cpp new file mode 100644 index 00000000..996c9f89 --- /dev/null +++ b/cpp-leetcode/leetcode273-integer-to-english-words_my_solution.cpp @@ -0,0 +1,133 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string numberToWords(int num) { + if (num == 0) return "Zero"; + string res = ""; + vector weighPosfix = {"", "Thousand", "Million", "Billion"}; + vector> kvVect; + auto str = to_string(num); + int len = str.size(); + for (int i = len - 1; i >= 0; i -= 3) + { + if (i >= 2) + kvVect.push_back(make_pair(str.substr(i - 2, 3), weighPosfix[(len - i) / 3])); + else kvVect.push_back(make_pair(str.substr(0, i + 1), weighPosfix[(len - i) / 3])); + } + reverse(kvVect.begin(), kvVect.end()); + + for (int i = 0; i < kvVect.size(); i++) + { + if (i != kvVect.size() - 1) + res += (ThreeDigitsNumToString(kvVect[i].first) == "" ? "" : + (ThreeDigitsNumToString(kvVect[i].first) + " " + kvVect[i].second)) + " "; + else res += (ThreeDigitsNumToString(kvVect[i].first) == "" ? "" : + (ThreeDigitsNumToString(kvVect[i].first) + " " + kvVect[i].second)); + } + res.erase(res.find_last_not_of(' ')+1); + + res = replaceAll(res, " ", " "); // 将连续的多个空格替换成1个 + return res; + } + + string ThreeDigitsNumToString(string str) + { + string res; + vector tenTo19Prefix = {"Thir", "Four", "Fif", "Six", "Seven", "Eigh", "Nine"}; + vector twentyTo90Prefix = {"Twen", "Thir", "For", "Fif", "Six", "Seven", "Eigh", "Nine"}; /* 这里是"For", 而不是"Four" */ + + string validStr = ""; + unordered_map dict = { + {1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"}, {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}, + {9, "Nine"}, {10, "Ten"}, {11, "Eleven"}, {12, "Twelve"} }; + + for (int i = 13; i <= 19; i++) + { + if (dict.find(i) == dict.end()) + { + dict[i] = "teen"; + } + } + for (int i = 13; i <= 19; i++) + { + dict[i] = tenTo19Prefix[i % 13] + dict[i]; + } + for (int i = 20; i <= 90; i += 10) + { + if (dict.find(i) == dict.end()) + { + dict[i] = "ty"; + } + } + for (int i = 20; i <= 90; i += 10) + { + dict[i] = twentyTo90Prefix[i / 10 - 2] + dict[i]; + } + int len = str.size(); + + // 去掉先导0 + int validNum = stoi(str); + if (validNum == 0) return ""; + + if (validNum > 0 && validNum < 100) + { + res = LastTwoDigitsToString(validNum, dict); + } + if (validNum >= 100) + { + res.append(dict[str[0] - '0']); + res = res.append(" Hundred"); + if (validNum > 100 && validNum % 100 != 0) + res.append(" ").append(LastTwoDigitsToString(validNum % 100, dict)); + } + + return res; + } + + string LastTwoDigitsToString(int num, unordered_map dict) + { + string res = ""; + if (num > 0 && num <= 19 || (num % 10 == 0)) + { + res.append(dict[num]); + } + else if (num % 10 != 0 && num < 100) + { + int rem = num % 10; + string prefix; + if (num - rem == 40) prefix = "Forty"; // 这两个是特殊情况 + else if (num - rem == 90) prefix = "Ninety"; + else prefix = dict[num - rem]; + + res.append(prefix).append(" ").append(dict[rem]); + } + return res; + } + + string replaceAll(string str, const string& sub_str, const string& new_str) { + string resultStr = str; + int pos = 0; + while((pos = resultStr.find(sub_str)) != string::npos) // 替换所有指定子串 + { + resultStr.replace(pos, sub_str.length(), new_str); + } + return resultStr; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 1000000001; + auto res = sol.numberToWords(num); /* Expected: "One Billion One" */ + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode274-h-index_bucket_sort.cpp b/cpp-leetcode/leetcode274-h-index_bucket_sort.cpp new file mode 100644 index 00000000..94f7ef6f --- /dev/null +++ b/cpp-leetcode/leetcode274-h-index_bucket_sort.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int hIndex(vector& C) { + // 举例: 0 1 3 5 6 + const int len = C.size(); + vector bucket(len + 1, 0); + for (auto& count : C) + bucket[min(count, len)] += 1; /* C中有重复数, 所以需要加上来 */ + int h = 0; + int res = 0; + for (int i = len; i >= 0 && h < i; i--) + { + if (h + bucket[i] > i) + { + res = i; + break; + } + else { + h += bucket[i]; + if (h <= i) + res = h; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector citations = {3, 0, 6, 1, 5}; + auto res = sol.hIndex(citations); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode274-h-index_sort_and_two_pointers.cpp b/cpp-leetcode/leetcode274-h-index_sort_and_two_pointers.cpp new file mode 100644 index 00000000..b0e1be73 --- /dev/null +++ b/cpp-leetcode/leetcode274-h-index_sort_and_two_pointers.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int hIndex(vector& C) { + sort(C.begin(), C.end()); + int len = C.size(); + int h = 0, j = len - 1; + while (C[j] > h) + { + h++; + if(j == 0) break; + else j--; + } + return h; + } +}; + +// Test +int main() +{ + Solution sol; + vector citations = {3, 0, 6, 1, 5}; + auto res = sol.hIndex(citations); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode275-h-index-ii_binary_search1.cpp b/cpp-leetcode/leetcode275-h-index-ii_binary_search1.cpp new file mode 100644 index 00000000..91c7efdf --- /dev/null +++ b/cpp-leetcode/leetcode275-h-index-ii_binary_search1.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int hIndex(vector& C) { + const int n = C.size(); + if (n == 1 && C[0] == 0) return 0; + if (n == 1 && C[0] >= 1) return 1; + + int left = 0; + int right = n - 1; + while (left < right) + { + int mid = left + (right - left)/2; + int count = n - mid; // count: 引用次数处于区间[mid, largest]的论文的数量 + int minCite = C[mid]; // minCite: 上述区间的论文引用量的最小值 + if (count <= minCite) + right = mid; + else + left = mid + 1; + } + /* + 跳出while循环后,left=right,只剩下1个元素。为什么我们在 return 语句中检查 HIndex? + 情况 1:如果代码执行过程中, right 至少有一次出现 right = mid 的情况,那么循环结束时right 必须是 HIndex。 + 情况 2:right 永远不出现right = mid的情况,即程序永远不会跳到 right = mid,那么循环结束时 right 可以是 HIndex,也可以不是。因此我们需要单独进行检查。 + */ + return (C[right] >= n - right) ? n - right : 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector C = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.hIndex(C); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode275-h-index-ii_binary_search2.cpp b/cpp-leetcode/leetcode275-h-index-ii_binary_search2.cpp new file mode 100644 index 00000000..41dd0652 --- /dev/null +++ b/cpp-leetcode/leetcode275-h-index-ii_binary_search2.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int hIndex(vector& citations) { + int left = 0, N = citations.size(); + int right = N-1; + while (left <= right) + { + int mid = left + (right-left)/2; + if (citations[mid] >= (N-mid)) right = mid - 1; + else left = mid + 1; + } + return N - left; + } +}; + +// Test +int main() +{ + Solution sol; + vector C = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.hIndex(C); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode275-h-index-ii_two_pointers.cpp b/cpp-leetcode/leetcode275-h-index-ii_two_pointers.cpp new file mode 100644 index 00000000..ac6c003c --- /dev/null +++ b/cpp-leetcode/leetcode275-h-index-ii_two_pointers.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int hIndex(vector& C) { + const int len = C.size(); + int i = 0, j = len - 1; // 双指针: i从0扫描到目标结果h时结束, j从len-1扫描到0, 扫描到0时break + while (C[j] > i) + { + i++; + if (j == 0) break; + else j--; + } + return i; + } +}; + +// Test +int main() +{ + Solution sol; + vector C = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.hIndex(C); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode278-first-bad-version_binary_search.cpp b/cpp-leetcode/leetcode278-first-bad-version_binary_search.cpp new file mode 100644 index 00000000..bbb05f89 --- /dev/null +++ b/cpp-leetcode/leetcode278-first-bad-version_binary_search.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int firstBadVersion(int n) { + int left = 0; + int right = n; // 在区间 [0, n]中搜索 + while (left < right) + { + int mid = left + (right - left) / 2; // 防止溢出 + if (isBadVersion(mid) == true) + right = mid; + else left = mid + 1; + } + return left; + } + // 以下是自己加的, 提交代码时需删掉 + bool isBadVersion(int num) + { + return num == 4; // 把测试数据中bad的值放在这 + } +}; + +// Test +int main() +{ + Solution sol; + int n = 5, bad = 4; + auto res = sol.firstBadVersion(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode279-perfect-squares_math-method.cpp b/cpp-leetcode/leetcode279-perfect-squares_math-method.cpp new file mode 100644 index 00000000..e2650cd9 --- /dev/null +++ b/cpp-leetcode/leetcode279-perfect-squares_math-method.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +/* 解题思路见题解 */ +class Solution { +public: + int numSquares(int n) { + while (n % 4 == 0) + n /= 4; + + if (n % 8 == 7) + return 4; // (path 1) + + for (int i = 0; i * i <= n; i++) + { + int r = (int)sqrt(n - i * i); + if (i * i + r * r == n) + { + if (i == 0 || r == 0) + return 1; // (path 2) + + return 2; // (path 3) + } + } + + return 3; // (path 4) + } +}; + +// Test +int main() +{ + Solution sol; + int k = 12; + int res = sol.numSquares(k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode28-implement-strstr_direct-solution.cpp b/cpp-leetcode/leetcode28-implement-strstr_direct-solution.cpp new file mode 100644 index 00000000..6675c28f --- /dev/null +++ b/cpp-leetcode/leetcode28-implement-strstr_direct-solution.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int strStr(string haystack, string needle) { + /* 思路: 从长字符串的开头开始找长度和模式串长度相同的子串,判断是否equal,直到模式串尾部与长字符串尾部对齐 */ + int len = needle.size(); + if(haystack.size() < len) + return -1; + int gap = haystack.size() - len; + for(int i = 0; i <= gap; i++) + { + string sub = haystack.substr(i, len); + if(sub == needle) + return i; + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "babad"; + string t = "ab"; + auto res = sol.strStr(s, t); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode28-implement-strstr_solution2.cpp b/cpp-leetcode/leetcode28-implement-strstr_solution2.cpp new file mode 100644 index 00000000..172a312d --- /dev/null +++ b/cpp-leetcode/leetcode28-implement-strstr_solution2.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +/* 本解法是暴力法, 比较慢 */ +class Solution { +public: + int strStr(string haystack, string needle) { + const int lenN = needle.size(); + for (int i = 0; ; i++) { + for (int j = 0; ; j++) { + if (j == lenN) return i; /* 当for循环不给上界判断条件时, 如果短串needle能遍历到底, 循环结束时 j == lenN。 + 如果加上界时, j <= lenN - 1 */ + if (i + j == haystack.size()) /* 结束循环时, 最大公共子串长度 < needle长度, 不满足要求 */ + return -1; + if (needle[j] != haystack[i + j]) /* 持续考察等长区间 needle[0...j] 与 haystack[i..i+j], 比较前者的指针j 和后者的指针i+j 处的字符 + 是否相等, 不相等就结束循环, 看短的能不能一直跑到末尾 */ + break; + } + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "babad"; + string t = "ab"; + auto res = sol.strStr(s, t); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode282-expression-add-operators_backtrakcing1.cpp b/cpp-leetcode/leetcode282-expression-add-operators_backtrakcing1.cpp new file mode 100644 index 00000000..3d5fe030 --- /dev/null +++ b/cpp-leetcode/leetcode282-expression-add-operators_backtrakcing1.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector res; + vector addOperators(string num, int target) { /* target: 目标和 */ + /* + Follow up: + 如果加一种运算符/(除号)怎么办? + 如果加入括号怎么办? + 先转为逆波兰表达式, 再想办法解决 + */ + backtrack(num, target, "", 0, /*curEval (long) */ 0, /*prev*/ 0); + return res; + } + void backtrack(string& numStr, int target, string curExp, int startPos, long curEval, long prev) /* prev: pre eval, 即cur Eval撤销最近一次+-*运算的结果 */ + { + if (startPos == numStr.size()) // 全部字符处理完了 + { + if (curEval == target) + { + res.push_back(curExp); + } + return; + } + for (int i = startPos; i < numStr.size(); i++) + { + if (numStr[startPos] == '0' && i > startPos) // 拆分出来的数有先导0: 0674 367482 + // | | + // 0 + 2 + break; + long curNum = stol(numStr.substr(startPos, i - startPos + 1)); // 当前在处理的子字符串: [startPos, i] + if (startPos == 0) /* 拆分出来的第1个数不参与运算 */ + { + backtrack(numStr, target, curExp + to_string(curNum), i + 1, curNum, curNum); + } + else + { + backtrack(numStr, target, curExp + "+" + to_string(curNum), i + 1, curEval + curNum, curNum); // 在curNum之前插入1个+, 运算+curNum给整体表达式的sum贡献了+curSum = curSum, curEval更新为curEval + curNum + backtrack(numStr, target, curExp + "-" + to_string(curNum), i + 1, curEval - curNum, -curNum); // 在curNum之前插入1个-, 运算-curNum给整体表达式的sum贡献了-curSum + + backtrack(numStr, target, curExp + "*" + to_string(curNum), i + 1, curEval - prev + curNum * prev, curNum * prev); // 在curNum之前插入1个*, 运算*curNum给整体表达式的sum贡献了+prev*curSum, 由于需要先恢复 □ ± 3 * 2 中的 □ 值(□ ± 3 = curEval), 故curEval更新为□ ± 3 * 2 = curEval - prev + prev * curNum, prev在多次函数调用过程中依次为3,6(只记录做乘法运算的话) + } + } + } +}; + +// Test +int main() +{ + Solution sol; + string num = "1325"; + int targetNum = 31; + auto res = sol.addOperators(num, targetNum); + for (auto& str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode282-expression-add-operators_backtrakcing2.cpp b/cpp-leetcode/leetcode282-expression-add-operators_backtrakcing2.cpp new file mode 100644 index 00000000..a7f738c4 --- /dev/null +++ b/cpp-leetcode/leetcode282-expression-add-operators_backtrakcing2.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector addOperators(string num, int target) { + vector res; + string exp(num.length() * 2, '\0'); // 模拟string buffer + dfs(num, target, 0, exp, 0, 0, 0, res); + return res; + } +private: + void dfs(const string& num, const int target, // input + int pos, string& exp, int len, long prev, long curr, // state + vector& res) // output + { + if (pos == num.length()) + { + if (curr == target) + res.push_back(exp.substr(0, len)); + return; + } + + long n = 0; + int s = pos; // 初始处理到的字符的位置 + int l = len; // len: 初始表达式的长度, L处放操作符op + if (s != 0) len++; // 放数字 + while (pos < num.size()) + { + n = n * 10 + (num[pos] - '0'); // 直接用数字算, 不做字符串转换 + if (num[s] == '0' && pos - s > 0) + break; // 0xx... invalid number + if (n > INT_MAX) + break; // too long + exp[len++] = num[pos++]; // 维护一个expression, 时间复杂度为O(1)的拷贝 + if (s == 0) + { + dfs(num, target, pos, exp, len, n, n, res); + continue; + } + exp[l] = '+'; + dfs(num, target, pos, exp, len, n, curr + n, res); // 使用len, 省去了拼接 curExp + op + num.substr(pos, l) 的过程 + exp[l] = '-'; + dfs(num, target, pos, exp, len, -n, curr - n, res); + exp[l] = '*'; + dfs(num, target, pos, exp, len, prev * n, curr - prev + prev * n, res); + } + } +}; + +// Test +int main() +{ + Solution sol; + string num = "1325"; + int targetNum = 31; + auto res = sol.addOperators(num, targetNum); + for (auto& str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode284-peeking-iterator_followup_using_template.cpp b/cpp-leetcode/leetcode284-peeking-iterator_followup_using_template.cpp new file mode 100644 index 00000000..ddfe7dac --- /dev/null +++ b/cpp-leetcode/leetcode284-peeking-iterator_followup_using_template.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +using namespace std; + +template +class Iterator { + struct Data; + Data* data; +public: + Iterator(const vector& nums); + Iterator(const Iterator& iter); + // Returns the next element in the iteration. + T next(); + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + +template +class PeekingIterator : public Iterator { +public: + PeekingIterator(const vector& nums) : Iterator(nums) { + flag = Iterator::hasNext(); + if (flag) { + nextElement = Iterator::next(); + } + } + + T peek() { + return nextElement; + } + + T next() { + T ret = nextElement; + flag = Iterator::hasNext(); + if (flag) { + nextElement = Iterator::next(); + } + return ret; + } + + bool hasNext() const { + return flag; + } +private: + T nextElement; + bool flag; +}; + +// Test +/* 本题如果用C++实现没办法本地debug, 因为其中的 Iterator类没实现 */ +int main() +{ + // const vector nums = {1, 2, 3}; + // PeekingIterator* it = new PeekingIterator(nums); // [1,2,3] + // int val = it->next(); // 返回 1, 指针移动到下一个元素 [1,2,3] + // cout << val << endl; + // it->peek(); // 返回 2, 指针未发生移动 [1,2,3] + // it->next(); // 返回 2, 指针移动到下一个元素 [1,2,3] + // it->next(); // 返回 3, 指针移动到下一个元素 [1,2,3] + // bool hasNext = it->hasNext(); // 返回 False + // cout << (hasNext ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode284-peeking-iterator_solution1.cpp b/cpp-leetcode/leetcode284-peeking-iterator_solution1.cpp new file mode 100644 index 00000000..a11ac6ff --- /dev/null +++ b/cpp-leetcode/leetcode284-peeking-iterator_solution1.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +using namespace std; + +class Iterator { + struct Data; + Data* data; +public: + Iterator(const vector& nums); + Iterator(const Iterator& iter); + // Returns the next element in the iteration. + int next(); + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + +class PeekingIterator : public Iterator { + int _nextValue = 0; + bool _hasNext = false; +public: + PeekingIterator(const vector& nums) : Iterator(nums) { + _hasNext = Iterator::hasNext(); + if (_hasNext) + _nextValue = Iterator::next(); + } + + int peek() { + return _nextValue; + } + + int next() { + int nextValue = _nextValue; + _hasNext = Iterator::hasNext(); + if (_hasNext) + _nextValue = Iterator::next(); + return nextValue; + } + + bool hasNext() const { + return _hasNext; + } +}; + +// Test +/* 本题如果用C++实现没办法本地debug, 因为其中的 Iterator类没实现 */ +int main() +{ + // const vector nums = {1, 2, 3}; + // PeekingIterator* it = new PeekingIterator(nums); // [1,2,3] + // int val = it->next(); // 返回 1, 指针移动到下一个元素 [1,2,3] + // cout << val << endl; + // it->peek(); // 返回 2, 指针未发生移动 [1,2,3] + // it->next(); // 返回 2, 指针移动到下一个元素 [1,2,3] + // it->next(); // 返回 3, 指针移动到下一个元素 [1,2,3] + // bool hasNext = it->hasNext(); // 返回 False + // cout << (hasNext ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode284-peeking-iterator_solution2.cpp b/cpp-leetcode/leetcode284-peeking-iterator_solution2.cpp new file mode 100644 index 00000000..9f32175c --- /dev/null +++ b/cpp-leetcode/leetcode284-peeking-iterator_solution2.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; + +class Iterator { + struct Data; + Data* data; +public: + Iterator(const vector& nums); + Iterator(const Iterator& iter); + // Returns the next element in the iteration. + int next(); + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + +class PeekingIterator : public Iterator { + int _nextValue; + bool _hasNext; +public: + PeekingIterator(const vector& nums) : Iterator(nums) { + if (Iterator::hasNext()) + { + _nextValue = Iterator::next(); + _hasNext = true; + } + else + { + _nextValue = 0; + _hasNext = false; + } + } + + int peek() { + return _nextValue; + } + + int next() { + int nextValue = _nextValue; + _hasNext = Iterator::hasNext(); + if (_hasNext) + _nextValue = Iterator::next(); + return nextValue; + } + + bool hasNext() const { + return _hasNext; + } +}; + +// Test +/* 本题如果用C++实现没办法本地debug, 因为其中的 Iterator类没实现 */ +int main() +{ + // const vector nums = {1, 2, 3}; + // PeekingIterator* it = new PeekingIterator(nums); // [1,2,3] + // int val = it->next(); // 返回 1, 指针移动到下一个元素 [1,2,3] + // cout << val << endl; + // it->peek(); // 返回 2, 指针未发生移动 [1,2,3] + // it->next(); // 返回 2, 指针移动到下一个元素 [1,2,3] + // it->next(); // 返回 3, 指针移动到下一个元素 [1,2,3] + // bool hasNext = it->hasNext(); // 返回 False + // cout << (hasNext ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode284-peeking-iterator_with_main.cpp b/cpp-leetcode/leetcode284-peeking-iterator_with_main.cpp new file mode 100644 index 00000000..ccae3b78 --- /dev/null +++ b/cpp-leetcode/leetcode284-peeking-iterator_with_main.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Iterator { + const vector* nums; + int index; +public: + Iterator(const vector& nums) { + this->nums = &nums; + this->index = 0; + } + Iterator(const Iterator& iter); + + // Returns the next element in the iteration. + int next() { + return (*nums)[index++]; + } + + // Returns true if the iteration has more elements. + bool hasNext() const { + return index < (*nums).size(); + } +}; + +class PeekingIterator : public Iterator { +private: + int nextElement; + bool flag; +public: + PeekingIterator(const vector& nums) : Iterator(nums) { + // Initialize any member here. + // **DO NOT** save a copy of nums and manipulate it directly. + // You should only use the Iterator interface methods. + flag = Iterator::hasNext(); + if (flag) { + nextElement = Iterator::next(); + } + } + + // Returns the next element in the iteration without advancing the iterator. + int peek() { + return nextElement; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + int next() { + int ret = nextElement; + flag = Iterator::hasNext(); + if (flag) { + nextElement = Iterator::next(); + } + return ret; + } + + bool hasNext() const { + return flag; + } +}; + +// Test +int main() +{ + /** 用gcc/g++编译, 需要用这种方式初始化vector: + */ + int a[3] = {1, 2, 3}; + vector nums(a, a + 3); + + PeekingIterator peekingIterator(nums); + assert(1 == peekingIterator.next()); + assert(2 == peekingIterator.peek()); + assert(2 == peekingIterator.next()); + assert(3 == peekingIterator.next()); + assert(!peekingIterator.hasNext()); + + cout << "OK~" << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode29-divide-two-integers.cpp b/cpp-leetcode/leetcode29-divide-two-integers.cpp new file mode 100644 index 00000000..1ad60334 --- /dev/null +++ b/cpp-leetcode/leetcode29-divide-two-integers.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int divide(int dividend, int divisor) { + /* + 1、除法的本质是多次减法 + 2、用移位实现乘2以及除2的操作 + */ + if (dividend == INT_MIN && divisor == -1) return INT_MAX; /* 临界情况 */ + long res = 0; + long m = fabs(dividend), n = fabs(divisor); + int sign; + if((dividend < 0 && divisor < 0) || (dividend > 0 && divisor > 0)) + sign = 1; + else sign = -1; + + while(m >= n) + { + long d = n, c = 1; // 除数n的倍数d, 计数c + while(m >= (d << 1)) + { + d <<= 1; // d=n*(2^i), 每次扩大2倍 + c <<= 1; // c=2^i,与d同步加倍 + } + res += c; + m -= d; + } + + return sign == 1 ? res : -res; + } +}; + +// Test +int main() +{ + Solution sol; + int m = 1314887, n = 13; + auto res = sol.divide(m,n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode290-word-pattern_first_index_seq_equal.cpp b/cpp-leetcode/leetcode290-word-pattern_first_index_seq_equal.cpp new file mode 100644 index 00000000..9c6532ce --- /dev/null +++ b/cpp-leetcode/leetcode290-word-pattern_first_index_seq_equal.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include +using namespace std; +/** + * @Author: https://github.com/yanglr + * @Date: 2021-08-17 19:32:27 + * @Title: LeetCode290. 单词规律 + * @中文题目: 290. 单词规律 + * @EnglishTitle: 290. Word Pattern + * @Alias: LC290 - 力扣290 + * @Tag: 字符串 + * Created by 极客学长 on 2021-08-17. +*/ +class Solution { +public: + bool wordPattern(string pat, string s) { + vector pFirstIndex; + vector words; + vector sFirstIndex; + for (auto ch : pat) + { + int firstIndex = pat.find_first_of(ch); + pFirstIndex.push_back(firstIndex); + } + + istringstream iss(s); + while (iss >> s) + words.push_back(s); + + for (auto& w : words) + { + auto it = find(words.begin(), words.end(), w); + if (it != words.end()) + sFirstIndex.push_back(it - words.begin()); + } + + return pFirstIndex == sFirstIndex; + } +}; + +// Test +int main() +{ + Solution sol; + string pattern = "abba", str = "dog cat cat dog"; + auto res = sol.wordPattern(pattern, str); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_level_order_queue.cpp b/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_level_order_queue.cpp new file mode 100644 index 00000000..5bfb91d1 --- /dev/null +++ b/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_level_order_queue.cpp @@ -0,0 +1,90 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Codec { +public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + queue q; + q.push(root); + string res; + while (!q.empty()) + { + TreeNode* node = q.front(); + q.pop(); + if (!node) res.append("#,"); + else + { + res.append(to_string(node->val)).append(","); + q.push(node->left); + q.push(node->right); + } + } + if (res.size() >=2 && res.substr(res.size() - 2) == "#,") + res.pop_back(); /* 删掉末尾多余的, */ + + return res; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector nodes; + for (int i = 0; i < data.size(); i++) + { + int j = i; + while (j < data.size() && data[j] != ',') + j++; + string str = data.substr(i, j - i); + if (str == "#") + nodes.push_back(nullptr); + else nodes.push_back(new TreeNode(stol(str))); + i = j; + } + + int i = 0, j = 1; + while (j < nodes.size()) + { + if (nodes[i] != nullptr) + { + nodes[i]->left = nodes[j]; + nodes[i]->right = nodes[j + 1]; + j += 2; // nodes[i] 有意义时, 才有两个子结点, j 才加上2 + } + i += 1; + } + return nodes.front(); + } +}; + +// Test +int main() +{ + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(4); + root->right = new TreeNode(5); + root->right->left = nullptr; + root->right->right = new TreeNode(6); + Codec ser, deser; + string serializedStr = ser.serialize(root); + cout << serializedStr << endl; + TreeNode* res = deser.deserialize(serializedStr); + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_preorder_dfs1.cpp b/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_preorder_dfs1.cpp new file mode 100644 index 00000000..a55868b2 --- /dev/null +++ b/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_preorder_dfs1.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +// 更精彩的解法: 使用先序遍历(bfs), 如果知道了先序遍历的序列化字符串, 是可以唯一确定一棵树的 +class Codec { +public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (root == nullptr) return "#"; + return to_string(root->val).append(",").append(serialize(root->left)).append(",").append(serialize(root->right)); + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector nodes; + for (int i = 0; i < data.size(); i++) + { + int j = i; + while (j < data.size() && data[j] != ',') + j++; + string str = data.substr(i, j - i); + if (str == "#") + nodes.push_back(nullptr); + else nodes.push_back(new TreeNode(stoi(str))); + i = j; + } + + // 以下基于先序遍历递归处理 + return dfs(nodes, 0); + } + TreeNode* dfs(vector& nodes, int cur) + { + if (nodes[cur] == nullptr) return nullptr; // nodes[cur] 其实就是平时写的root结点 + + TreeNode* left = dfs(nodes, cur + 1); + int leftLen = getNum(left); + TreeNode* right = dfs(nodes, cur + leftLen + 1); + nodes[cur]->left = left; + nodes[cur]->right = right; + return nodes[cur]; + } + int getNum(TreeNode* node) /* 在序列化字符串中占的位置数 */ + { + if (node == nullptr) return 1; // 该node是NULL时, 会表示成"#", 占用1个位置 + return 1 + getNum(node->left) + getNum(node->right); + } +}; + +// Test +int main() +{ + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(4); + root->right = new TreeNode(5); + root->right->left = nullptr; + root->right->right = new TreeNode(6); + Codec ser, deser; + string serializedStr = ser.serialize(root); + cout << serializedStr << endl; + TreeNode* res = deser.deserialize(serializedStr); + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_preorder_dfs2.cpp b/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_preorder_dfs2.cpp new file mode 100644 index 00000000..0d29b2e5 --- /dev/null +++ b/cpp-leetcode/leetcode297-serialize-and-deserialize-binary-tree_preorder_dfs2.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +// 先序遍历2 +class Codec { +public: + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (root == nullptr) return "#"; + return to_string(root->val).append(",").append(serialize(root->left)).append(",").append(serialize(root->right)); + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + queue q; + for (int i = 0; i < data.size(); i++) + { + int j = i; + while (j < data.size() && data[j] != ',') + j++; + string str = data.substr(i, j - i); + q.push(str); + i = j; + } + + // 以下基于先序遍历递归处理 + return dfs(q); + } + TreeNode* dfs(queue& q) + { + string cur = q.front(); + q.pop(); + + if (cur=="#") return nullptr; + TreeNode* root = new TreeNode(stoi(cur)); + + TreeNode* left = dfs(q); + TreeNode* right = dfs(q); + root->left = left; + root->right = right; + return root; + } +}; + +// Test +int main() +{ + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(4); + root->right = new TreeNode(5); + root->right->left = nullptr; + root->right->right = new TreeNode(6); + Codec ser, deser; + string serializedStr = ser.serialize(root); + cout << serializedStr << endl; + TreeNode* res = deser.deserialize(serializedStr); + cout << res->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode299-bulls-and-cows_guess_hashmap1.cpp b/cpp-leetcode/leetcode299-bulls-and-cows_guess_hashmap1.cpp new file mode 100644 index 00000000..44c42692 --- /dev/null +++ b/cpp-leetcode/leetcode299-bulls-and-cows_guess_hashmap1.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string getHint(string secret, string guess) { + const int len = secret.size(); + unordered_map dict; + for (auto& ch : secret) + { + dict[ch]++; + } + int total = 0; + for (auto& ch : guess) + { + if (dict[ch] > 0) + total++; + dict[ch]--; /* 当前字符用1次后, 就从哈希表中删掉它 */ + } + int bulls = 0; + for (int i = 0; i < len; i++) + { + if (secret[i] == guess[i]) /* 对比两个字符串, 统计位置相同的字符的数量 */ + bulls++; + } + return to_string(bulls) + "A" + to_string(total - bulls) + "B"; + } +}; + +// Test +int main() +{ + Solution sol; + string secret = "1122", guess = "2211"; + auto res = sol.getHint(secret, guess); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode299-bulls-and-cows_guess_hashmap_using_array.cpp b/cpp-leetcode/leetcode299-bulls-and-cows_guess_hashmap_using_array.cpp new file mode 100644 index 00000000..73bb180b --- /dev/null +++ b/cpp-leetcode/leetcode299-bulls-and-cows_guess_hashmap_using_array.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string getHint(string secret, string guess) { + const int len = secret.size(); + int dict[11]; /* 数组模拟哈希表, 由于全是数字, 所以哈希表的key是0~9, 共10个, 预留1个 */ + memset(dict, 0, sizeof(dict)); + for (auto& ch : secret) + { + dict[ch - '0']++; + } + int total = 0; + for (auto& ch : guess) + { + if (dict[ch - '0'] > 0) + total++; + dict[ch - '0']--; /* 当前字符用1次后, 就从哈希表中删掉它 */ + } + int bulls = 0; + for (int i = 0; i < len; i++) + { + if (secret[i] == guess[i]) /* 对比两个字符串, 统计位置相同的字符的数量 */ + bulls++; + } + return to_string(bulls).append("A") + to_string(total - bulls).append("B"); + } +}; + +// Test +int main() +{ + Solution sol; + string secret = "1122", guess = "2211"; + auto res = sol.getHint(secret, guess); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode299-bulls-and-cows_guess_solution1.cpp b/cpp-leetcode/leetcode299-bulls-and-cows_guess_solution1.cpp new file mode 100644 index 00000000..e35a65bf --- /dev/null +++ b/cpp-leetcode/leetcode299-bulls-and-cows_guess_solution1.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string getHint(string secret, string guess) { /* secret.length == guess.length */ + string res; + int len1 = secret.size(), len2 = guess.size(); + int count1 = 0; // 计数器: 统计 字符相同且index相等 的数量 + vector arrS, arrG; + for (int i=0; i < len1; i++) + { + if (secret[i] == guess[i]) + count1++; + else + { + arrS.push_back(secret[i]); + arrG.push_back(guess[i]); + } + } + int count2 = 0; + int len = arrG.size(); + for (int i = 0; i < len; i++) + { + auto it = find(arrS.begin(), arrS.end(), arrG[i]); + if (it != arrS.end()) + { + count2++; + if (it == arrS.end() - 1) arrS.pop_back(); + else arrS.erase(it); + } + } + + res = to_string(count1) + "A" + to_string(count2) + "B"; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string secret = "1122", guess = "2211"; + auto res = sol.getHint(secret, guess); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode3-longest-substring-without-repeating_map.cpp b/cpp-leetcode/leetcode3-longest-substring-without-repeating_map.cpp new file mode 100644 index 00000000..25370330 --- /dev/null +++ b/cpp-leetcode/leetcode3-longest-substring-without-repeating_map.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + int n = s.length(), res = 0; + unordered_map dict; + // 双指针i, j + for (int j = 0, i = 0; j < n; j++) + { + if (dict.find(s[j]) != dict.end()) // 如果当前字符出现过,curStartIdx更新为该字符上一次出现的位置 + { + i = max(dict[s[j]], i); + } + res = max(res, j - i + 1); // 使用贪心思想进行子串延伸,关键! + dict[s[j]] = j + 1; /* 如果当前字符没出现过,将其index记录在dict中。下标 +1 代表 i 要移动的下个位置。 */ + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "pwwkew"; + int res = sol.lengthOfLongestSubstring(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode30-substring-with-concatenation-of-all-words_hashmap_dict.cpp b/cpp-leetcode/leetcode30-substring-with-concatenation-of-all-words_hashmap_dict.cpp new file mode 100644 index 00000000..5f6094da --- /dev/null +++ b/cpp-leetcode/leetcode30-substring-with-concatenation-of-all-words_hashmap_dict.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findSubstring(string s, vector& words) { + vector res; + int wordsCount = words.size(); + if (wordsCount == 0) return {}; + int wordLen = words.front().size(); + // 目标哈希表 needWordDict, map: string -> count + unordered_map needDict; + for (auto word : words) + { + if (needDict.find(word) != needDict.end()) + needDict[word]++; + else needDict[word] = 0; + } + for (int i = 0; i < s.size() - wordLen*wordsCount + 1; i++) + { + int count = 0; + // 构建已有串的哈希表 hasWordsDict + unordered_map hasWordsDict; + while (count < wordsCount) + { + string curWord = s.substr(i + count * wordLen, wordLen); + if (needDict.find(curWord) != needDict.end()) + { + if (hasWordsDict.find(curWord) != hasWordsDict.end()) + hasWordsDict[curWord]++; + else hasWordsDict[curWord] = 0; + } + else break; + + if (hasWordsDict[curWord] > needDict[curWord]) break; + count++; + } + if (count == wordsCount) res.push_back(i); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "barfoofoobarthefoobarman"; + vector words = {"bar","foo","the"}; + auto res = sol.findSubstring(s, words); + for(auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode300-longest-increasing-subsequence_binary_search_and_greedy.cpp b/cpp-leetcode/leetcode300-longest-increasing-subsequence_binary_search_and_greedy.cpp new file mode 100644 index 00000000..2f4a6f9f --- /dev/null +++ b/cpp-leetcode/leetcode300-longest-increasing-subsequence_binary_search_and_greedy.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector dp(n, 1); /* dp[i]: 以 nums[i] 结尾的LIS(最长上升子序列)的长度 */ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < i; j++) + { + if (nums[j] < nums[i]) /* 新来的数nums[j]是否能形成1个新的LIS, 使得nums[j]是新LIS中第2大的数且新LIS长度=LIS的长度+1? 如果能就更新之 */ + dp[i] = max(dp[i], dp[j] + 1); + } + } + int res = 0; + for (int i = 0; i < n; i++) + res = max(res, dp[i]); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {10, 9, 2, 5, 3, 7}; + auto res = sol.lengthOfLIS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode300-longest-increasing-subsequence_dp.cpp b/cpp-leetcode/leetcode300-longest-increasing-subsequence_dp.cpp new file mode 100644 index 00000000..2f4a6f9f --- /dev/null +++ b/cpp-leetcode/leetcode300-longest-increasing-subsequence_dp.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector dp(n, 1); /* dp[i]: 以 nums[i] 结尾的LIS(最长上升子序列)的长度 */ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < i; j++) + { + if (nums[j] < nums[i]) /* 新来的数nums[j]是否能形成1个新的LIS, 使得nums[j]是新LIS中第2大的数且新LIS长度=LIS的长度+1? 如果能就更新之 */ + dp[i] = max(dp[i], dp[j] + 1); + } + } + int res = 0; + for (int i = 0; i < n; i++) + res = max(res, dp[i]); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {10, 9, 2, 5, 3, 7}; + auto res = sol.lengthOfLIS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode301-remove-invalid-parentheses_bfs.cpp b/cpp-leetcode/leetcode301-remove-invalid-parentheses_bfs.cpp new file mode 100644 index 00000000..cec17ff8 --- /dev/null +++ b/cpp-leetcode/leetcode301-remove-invalid-parentheses_bfs.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector removeInvalidParentheses(string s) + { + unordered_set st; + deque q; + vector res; + if (isValid(s)) + { + res.push_back(s); + return res; + } + unordered_set visited; + q.push_back(s); + visited.insert(s); + bool found = false; + while (!q.empty()) + { + int size = q.size(); + for (int i = 0; i < size; i++) + { + string curStr = q.front(); + q.pop_front(); + for (int j = 0; j < curStr.size(); j++) + { + if (curStr[j] != '(' && curStr[j] != ')') + continue; + string newStr = curStr.substr(0, j) + curStr.substr(j + 1, curStr.size() - 1 - j); + if (visited.count(newStr)) + continue; + if (isValid(newStr)) + { + found = true; + st.insert(newStr); + } + visited.insert(newStr); + q.push_back(newStr); + } + } + if (found) break; + } + vector temp(st.begin(), st.end()); + res.insert(res.end(), temp.begin(), temp.end()); + if (res.size() == 0) + res.push_back(s); + return res; + } + /* 判断str中的的括号表达式是否是合法的 */ + bool isValid(string str) + { + int leftPar = 0; + int index = 0; + while (index < str.size()) + { + if (str[index] == '(') + leftPar++; + else if (str[index] == ')') + { + if (leftPar == 0) + return false; + leftPar--; + } + index++; + } + return leftPar == 0; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "(a)())()"; + auto res = sol.removeInvalidParentheses(s); + for (auto& str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode301-remove-invalid-parentheses_dfs.cpp b/cpp-leetcode/leetcode301-remove-invalid-parentheses_dfs.cpp new file mode 100644 index 00000000..99e769e5 --- /dev/null +++ b/cpp-leetcode/leetcode301-remove-invalid-parentheses_dfs.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector res; + vector removeInvalidParentheses(string s) { + int lCount = 0, rCount = 0; + for (auto& ch : s) + if (ch == '(') lCount++; + else if (ch == ')') { + if (lCount == 0) rCount++; + else lCount--; + } + + dfs(s, 0, "", 0, lCount, rCount) ; + return res; + } + /* s: 原字符串, start pos: 表示枚举到哪个字符了, path: 字符串删完之后剩下的字符串, count: 当前左括号数量-右括号数量的差值是多少, + l: 当前还能删除多少左括号, r: 当前还能删除多少右括号 */ + void dfs(string& s, int startPos, string path, int count, int lCount, int rCount) { + if (startPos == s.size()) { + if (!count) res.push_back(path); + return; + } + + if (s[startPos] != '(' && s[startPos] != ')') /* 根据题意: 只能删掉左右括号, 原字符串中的非括号的字符需要全部留下 */ + dfs(s, startPos + 1, path + s[startPos], count, lCount, rCount) ; + else if (s[startPos] == '(') { + // 双指针技巧统计连续相等的字符 + int k = startPos; + while (k < s.size() && s[k] == '(') k++; + lCount -= k - startPos; // k-startPos: 当前连续的左括号数量, 先删掉它们 + for (int i = k - startPos; i >= 0; i-- ) { + if (lCount >= 0) dfs(s, k, path, count, lCount, rCount) ; + path += '('; // 回溯: 加回来删除的1个括号 + count++; + lCount++; + } + } else if (s[startPos] == ')') { + int k = startPos; + while (k < s.size() && s[k] == ')') k++; + rCount -= k - startPos; // k-startPos: 当前连续的右括号数量, 先删掉它们 + for (int i = k - startPos; i >= 0; i--) { + if (count >= 0 && rCount >= 0) dfs(s, k, path, count, lCount, rCount) ; /* count >= 0: 需要保证字符串的任意前缀中左括号数量>=右括号数量 */ + path += ')'; // 回溯: 加回来删除的1个括号 + count--; + rCount++; + } + } + } +}; + +// Test +int main() +{ + Solution sol; + string s = "(a)())()"; + auto res = sol.removeInvalidParentheses(s); + for (auto& str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode303-range-sum-query-immutable_prefix_sum.cpp b/cpp-leetcode/leetcode303-range-sum-query-immutable_prefix_sum.cpp new file mode 100644 index 00000000..d7c8eb2e --- /dev/null +++ b/cpp-leetcode/leetcode303-range-sum-query-immutable_prefix_sum.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class NumArray { +private: + vector preSum; +public: + NumArray(vector& nums) { + int len = nums.size(); + preSum.resize(len + 1); + for (int i=0; i < len; i++) + preSum[i+1] = preSum[i] + nums[i]; + } + + int sumRange(int left, int right) { + int res; + if (left == 0 && right < preSum.size()) + res = preSum[right+1]; + if (left > 0 && right < preSum.size()) + res = preSum[right+1] - preSum[left]; + return res; + } +}; +/** + * 你的 NumArray 对象会按如下方式进行初始化和调用: + * NumArray* obj = new NumArray(nums); + * int param_1 = obj->sumRange(left,right); + */ + +// Test +int main() +{ + vector nums = {-2, 0, 3, -5, 2, -1}; + NumArray* arr = new NumArray(nums); + int res1 = arr->sumRange(0, 2); // return 1 ((-2) + 0 + 3) + cout << res1 << endl; + int res2 = arr->sumRange(2, 5); /* return -1 (3 + (-5) + 2 + (-1)) */ + cout << res2 << endl; + int res3 = arr->sumRange(0, 5); /* return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) */ + cout << res3 << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode304-range-sum-query-2d-immutable_prefix_sum.cpp b/cpp-leetcode/leetcode304-range-sum-query-2d-immutable_prefix_sum.cpp new file mode 100644 index 00000000..3f0ff2ce --- /dev/null +++ b/cpp-leetcode/leetcode304-range-sum-query-2d-immutable_prefix_sum.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +class NumMatrix { +private: + vector> _preSum; +public: + NumMatrix(const vector>& matrix) { + if (matrix.empty()) return; + int m = matrix.size(); + int n = matrix[0].size(); + + _preSum = vector>(m + 1, vector(n + 1, 0)); + for (int i = 1; i <= m; i++) + { + for (int j = 1; j <= n; j++) + { + _preSum[i][j] = matrix[i - 1][j - 1] + _preSum[i - 1][j] + _preSum[i][j - 1] - _preSum[i - 1][j - 1]; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) + { + return _preSum[row2 + 1][col2 + 1] - _preSum[row2 + 1][col1] - _preSum[row1][col2 + 1] + _preSum[row1][col1]; + } +}; + +// Test +int main() +{ + vector> mat = {{3, 0, 1, 4, 2}, {5, 6, 3, 2, 1}, {1, 2, 0, 1, 5}, {4, 1, 0, 1, 7}, {1, 0, 3, 0, 5}}; + auto M = new NumMatrix(mat); + int res = M->sumRegion(2, 1, 4, 3); // return 8 + cout << res << endl; + res = M->sumRegion(1, 1, 2, 2); // return 11 + cout << res << endl; + res = M->sumRegion(1, 2, 2, 4); // return 12 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode306-additive-number_two_pointers.cpp b/cpp-leetcode/leetcode306-additive-number_two_pointers.cpp new file mode 100644 index 00000000..791e4d76 --- /dev/null +++ b/cpp-leetcode/leetcode306-additive-number_two_pointers.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isAdditiveNumber(string num) { + if (num == "") + return false; + + int len = num.size(); + for (int i = 1; i < len; i++) // 用双指针i, j分别作为substr{n-2}和substr{n-1}的开始位置 + { + for (int j = i + 1; j < len; j++) + { + string s1 = num.substr(0, i); // substr[0, i] + string s2 = num.substr(i, j - i); // substr[i, j] + if ((s1.size() > 1 && s1[0] == '0') || (s2.size() > 1 && s2[0] == '0')) + continue; // 出现开头是字符0的情况, 不处理 + + auto preNum = stoll(s1); + auto curNum = stoll(s2); + auto nextNum = preNum + curNum; + + auto combinedStr = s1 + s2 + to_string(nextNum); + while (combinedStr.size() < num.size()) // 继续前移 + { + preNum = curNum; + curNum = nextNum; + nextNum = preNum + curNum; // 迭代地使用递推关系 + combinedStr += to_string(nextNum); + } + + if (combinedStr == num) + return true; + } + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "199100199"; + auto res = sol.isAdditiveNumber(s); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode309-best-time-to-buy-and-sell-stock-with-cooldown_dp.cpp b/cpp-leetcode/leetcode309-best-time-to-buy-and-sell-stock-with-cooldown_dp.cpp new file mode 100644 index 00000000..d11461d9 --- /dev/null +++ b/cpp-leetcode/leetcode309-best-time-to-buy-and-sell-stock-with-cooldown_dp.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxProfit(vector& prices) { + int hold = INT_MIN, sold = 0, cooled = 0; + for (int i = 0; i < prices.size(); i++) + { + int preHold = hold; + int preSold = sold; + int preCooled = cooled; + + int p = prices[i]; + hold = max(preHold, preCooled - p); + sold = preHold + p; /* 如果hold的初始值设置为0就会有问题了, 可以将hold的初始值设置为 INT_MIN */ + cooled = max(preCooled, preSold); + } + return max(sold, cooled); + } +}; + +// Test +int main() +{ + Solution sol; + vector prices = {1,2,3,0,2}; + auto res = sol.maxProfit(prices); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode31-next-permutation_solution1.cpp b/cpp-leetcode/leetcode31-next-permutation_solution1.cpp new file mode 100644 index 00000000..199716ba --- /dev/null +++ b/cpp-leetcode/leetcode31-next-permutation_solution1.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void nextPermutation(vector& nums) { + next_permutation(nums.begin(), nums.end()); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 5}; + sol.nextPermutation(nums); + + for (int num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode31-next-permutation_two_pointers_with_swap.cpp b/cpp-leetcode/leetcode31-next-permutation_two_pointers_with_swap.cpp new file mode 100644 index 00000000..4434c339 --- /dev/null +++ b/cpp-leetcode/leetcode31-next-permutation_two_pointers_with_swap.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void nextPermutation(vector& nums) { + int len = nums.size(); + if (len == 1) return; + // 核心: 提升最后一个可以提升(与后一位连起来看是升序的)的数, 原数组中允许有重复的数. 使用双指针实现. + int i = len - 1; + while (i > 0 && nums[i - 1] >= nums[i]) i--; /* 从后向前找第一个降序的位置i */ + if (i == 0) // 从前到后是单调递减的, 已经是最大的排列数组 + reverse(nums.begin(), nums.end()); + else /* 从后向前, 找到了第一个降序对 nums[i-1] < nums[i], 此时i-1位置就是全局中第1处可以提升的 */ + { + int j = i; /* 指针j从i处出发往后走, 每发现1个比nums[i-1]大的数就移动j。由于nums[i]~ nums[len - 1]是从前往后递减的, 找到那个恰好大于nums[i-1]的数时停下 */ + while (j < len && nums[j] > nums[i - 1]) j++; + swap(nums[i - 1], nums[j - 1]); // 提升最后一个可以提升的数, swap完之后, 后半段依旧是递减的 + reverse(nums.begin() + i, nums.end()); // 将低位变成所有低位的最小排列 + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 5}; + sol.nextPermutation(nums); + + for (int num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode313-super-ugly-number_dp.cpp b/cpp-leetcode/leetcode313-super-ugly-number_dp.cpp new file mode 100644 index 00000000..d8ff2b65 --- /dev/null +++ b/cpp-leetcode/leetcode313-super-ugly-number_dp.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) + { + int k = primes.size(); + vectorp(k,0); /* p数组放有每个质数 2, 3, 5...等的指针, 一开始都是0 */ + + vectorresults({1}); + + for (int i=0; i primes = {2, 7, 13, 19}; + auto res = sol.nthSuperUglyNumber(n, primes); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode313-super-ugly-number_priority_queue.cpp b/cpp-leetcode/leetcode313-super-ugly-number_priority_queue.cpp new file mode 100644 index 00000000..f8da3f01 --- /dev/null +++ b/cpp-leetcode/leetcode313-super-ugly-number_priority_queue.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +using namespace std; + +typedef pair PII; /* kvp: value -> index */ +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) + { + int k = primes.size(); + vectorp(k, 0); /* p数组放有每个质数 2, 3, 5...等的指针, 一开始都是0 */ + vectorresults({1}); + priority_queue, greater<>>q; /* 小顶堆 */ + + /* 初始化堆, 把1与primes中元素相乘的结果都放进去 */ + for (int i=0; i primes = {2, 7, 13, 19}; + auto res = sol.nthSuperUglyNumber(n, primes); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode313-super-ugly-number_set.cpp b/cpp-leetcode/leetcode313-super-ugly-number_set.cpp new file mode 100644 index 00000000..8631f6f9 --- /dev/null +++ b/cpp-leetcode/leetcode313-super-ugly-number_set.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + int k = primes.size(); + set st = {1}; /* 1是必须有的, 1是质因数的总数量为0时的特例 */ + int count = 0; + long firstNum; + while (count < n) + { + auto it = st.begin(); + firstNum = *it; + st.erase(it); + + for (int i = 0; i < k; i++) + { + if (firstNum * primes[i] < INT_MAX) + st.insert(firstNum * primes[i]); + else break; /* 别漏了 */ + } + count++; + } + return firstNum; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 12; + vector primes = {2, 7, 13, 19}; + auto res = sol.nthSuperUglyNumber(n, primes); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode316-remove-duplicate-letters_stack_greedy.cpp b/cpp-leetcode/leetcode316-remove-duplicate-letters_stack_greedy.cpp new file mode 100644 index 00000000..d452e60b --- /dev/null +++ b/cpp-leetcode/leetcode316-remove-duplicate-letters_stack_greedy.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string removeDuplicateLetters(string s) { + stack st; + unordered_map chDict; + unordered_map used; + for (auto ch : s) + chDict[ch]++; + for (int i = 0; i < s.size(); i++) + { + char ch = s[i]; + if (used[ch] == true) + chDict[ch]--; + else if (st.empty() || st.top() < ch) + { + st.push(ch); + used[ch] = true; + chDict[ch]--; + } + else + { + while (!st.empty() && st.top() >= ch && chDict[st.top()] > 0) + { + used[st.top()] = false; + st.pop(); + } + st.push(ch); + chDict[ch]--; + used[ch] = true; + } + } + string res; + while (!st.empty()) + { + res.push_back(st.top()); + st.pop(); + } + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "cbacdcbc"; + auto res = sol.removeDuplicateLetters(s); + // 预期结果为 "acdb" + cout << res << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation1.cpp b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation1.cpp new file mode 100644 index 00000000..c0cf24da --- /dev/null +++ b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation1.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxProduct(vector& words) { + const int len = words.size(); + int res = 0; + vector hash(len); /* 将所有单词哈希化, 原数组words中的每一个word对应一个映射后的二进制数 */ + for (int i = 0; i < len; i++) + { + for (auto& ch : words[i]) + hash[i] |= 1 << (ch - 'a'); /* 用26个bit做哈希映射: 从低位到高位遍历, 如果一个字母出现, 则将其对应的bit位置为1 */ + for (int j = 0; j < i; j++) + { + if ((hash[i] & hash[j]) == 0) /* 如果两个hash值 hash[i] 与 hash[j]的按位与结果为0, 那么表示没共同的字母 */ + res = max(res, int(words[i].size() * words[j].size())); /* size()的返回值是unsigned int, 需要转换成int */ + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector s = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef", "foo"}; + auto res = sol.maxProduct(s); + // 预期输出结果为: 16 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation1_with_cache.cpp b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation1_with_cache.cpp new file mode 100644 index 00000000..d0ffeba4 --- /dev/null +++ b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation1_with_cache.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxProduct(vector& words) { + const int len = words.size(); + vector lens(len); // cache lengths + for (int i = 0; i < len; i++) + lens[i] = words[i].size(); + + int res = 0; + vector hash(len); + for (int i = 0; i < len; i++) + { + for (auto& ch : words[i]) + hash[i] |= 1 << (ch - 'a'); + for (int j = 0; j < i; j++) + { + if ((hash[i] & hash[j]) == 0) + res = max(res, lens[i] * lens[j]); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector s = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef", "foo"}; + auto res = sol.maxProduct(s); + // 预期输出结果为: 16 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation_with_hashmap.cpp b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation_with_hashmap.cpp new file mode 100644 index 00000000..d9c2da19 --- /dev/null +++ b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_bit_operation_with_hashmap.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxProduct(vector& words) { + unordered_map maxlen; // 映射: one word's bit mask -> current largest word length + for (string word : words) + { + int mask = 0; + for (const char& ch : word) + mask |= 1 << (ch - 'a'); + maxlen[mask] = max(maxlen[mask], (int) word.size()); + } + int result = 0; + for (auto& kv1 : maxlen) + { + for (auto& kv2 : maxlen) + { + if (!(kv1.first & kv2.first)) + result = max(result, kv1.second * kv2.second); + } + } + return result; + } +}; + +// Test +int main() +{ + Solution sol; + vector s = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef", "foo"}; + auto res = sol.maxProduct(s); + // 预期输出结果为: 16 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_brute_force.cpp b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_brute_force.cpp new file mode 100644 index 00000000..773bd587 --- /dev/null +++ b/cpp-leetcode/leetcode318-maximum-product-of-word-lengths_brute_force.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +/* 该暴力解法通过了32/167 个test case 后出现了超时TLE */ +class Solution { +public: + int maxProduct(vector& words) { + long maxProd = 0; + unordered_map dict; // string -> count + for (auto &word : words) + dict[word]++; + vector kvVect; + for (auto &kvp : dict) + kvVect.push_back(kvp.first); + auto cmp = [](const string& s1, const string& s2) + { + return s1.size() > s2.size(); + }; + sort(kvVect.begin(), kvVect.end(), cmp); + for (int i = 0; i < kvVect.size(); i++) + { + for (int j = 0; j < kvVect.size(); j++) + { + long len1 = kvVect[i].size(); + long len2 = kvVect[j].size(); + if (i != j && !hasCommonChar(kvVect[i], kvVect[j]) && len1 * len2 > maxProd) + { + maxProd = max(maxProd, len1 * len2); + } + } + } + return maxProd; + } + bool hasCommonChar(string s1, string s2) + { + unordered_set st1(s1.begin(), s1.end()); + unordered_set st2(s2.begin(), s2.end()); + bool exist = false; + for (auto &key : s1) + { + if (count(s2.begin(), s2.end(), key)) + exist = true; + } + return exist; + } +}; + +// Test +int main() +{ + Solution sol; + vector s = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef", "foo"}; + auto res = sol.maxProduct(s); + // 预期输出结果为: 16 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode319-bulb-switcher_math.cpp b/cpp-leetcode/leetcode319-bulb-switcher_math.cpp new file mode 100644 index 00000000..3b8b9be1 --- /dev/null +++ b/cpp-leetcode/leetcode319-bulb-switcher_math.cpp @@ -0,0 +1,22 @@ +#include +#include +using namespace std; + +class Solution { +public: + int bulbSwitch(int n) { + if (n <= 1) return n; + return sqrt(n); + } +}; + +// Test +int main() +{ + Solution sol; + int n = 89; + auto res = sol.bulbSwitch(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode32-longest-valid-parentheses_dp.cpp b/cpp-leetcode/leetcode32-longest-valid-parentheses_dp.cpp new file mode 100644 index 00000000..8a9d3c61 --- /dev/null +++ b/cpp-leetcode/leetcode32-longest-valid-parentheses_dp.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int longestValidParentheses(string s) { + int maxLen = 0; + int len = s.size(); + vector dp(len, 0); // dp[0] = 0 + for (int i = 1; i < len; i++) + { + if (s[i] == ')') + { + if (s[i-1] == '(') + { + int prePartLen = i >= 2 ? dp[i-2] : 0; + dp[i] = prePartLen + 2; + } + else if(s[i-1] == ')') + { + int splitIndex = i - 1 - dp[i-1]; + if (splitIndex >= 0 && s[splitIndex] == '(') + { + int prePartLen = splitIndex >= 1 ? dp[splitIndex-1] : 0; + dp[i] = prePartLen + dp[i-1] + 2; + } + } + maxLen = max(maxLen, dp[i]); + } + } + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + string s = ")()())"; + auto res = sol.longestValidParentheses(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode32-longest-valid-parentheses_stack1.cpp b/cpp-leetcode/leetcode32-longest-valid-parentheses_stack1.cpp new file mode 100644 index 00000000..91f0064e --- /dev/null +++ b/cpp-leetcode/leetcode32-longest-valid-parentheses_stack1.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int longestValidParentheses(string s) { + stack st; // 用栈存每一个字符在原串中的index + st.push(-1); + int len = s.size(); + int maxLen = 0; + for (int i=0; i +#include +#include +using namespace std; + +class Solution { +public: + int longestValidParentheses(string s) { + stack st; // 用栈存每一个字符在原串中的index + st.push(-1); + int len = s.size(); + int maxLen = 0; + for (int i=0; i +#include +#include +using namespace std; + +class Solution { +public: + int coinChange(vector& coins, int amount) { + int dp[amount + 1]; // dp[i]: 凑成金额 i 所需的 最少的硬币个数 + fill(dp, dp + amount + 1, 10001); + dp[0] = 0; + for (int i = 1; i <= amount; i++) /* 填充 dp[1] ~ dp[amount] */ + { + for (auto& coin : coins) + { + if (i < coin) continue; // 当前面值大于要凑的总额 + dp[i] = min(dp[i], dp[i - coin] + 1); + } + } + return dp[amount] == 10001 ? -1 : dp[amount]; + } +}; + +// Test +int main() +{ + Solution sol; + vector coins = {1, 2, 5}; + int amount = 11; + auto res = sol.coinChange(coins, amount); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode322-coin-change_dp_using_vector.cpp b/cpp-leetcode/leetcode322-coin-change_dp_using_vector.cpp new file mode 100644 index 00000000..da030b02 --- /dev/null +++ b/cpp-leetcode/leetcode322-coin-change_dp_using_vector.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, 10001); // dp[i]: 凑成金额 i 所需的 最少的硬币个数, 且数据范围0 <= amount <= 10^4 + dp[0] = 0; + for (int i = 1; i <= amount; i++) /* 填充 dp[1] ~ dp[amount] */ + { + for (auto& coin : coins) + { + if (i < coin) continue; // 当前面值大于要凑的总额 + dp[i] = min(dp[i], dp[i - coin] + 1); + } + } + return dp[amount] == 10001 ? -1 : dp[amount]; + } +}; + +// Test +int main() +{ + Solution sol; + vector coins = {1, 2, 5}; + int amount = 11; + auto res = sol.coinChange(coins, amount); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode326-power-of-three_iterative1.cpp b/cpp-leetcode/leetcode326-power-of-three_iterative1.cpp new file mode 100644 index 00000000..835d64d3 --- /dev/null +++ b/cpp-leetcode/leetcode326-power-of-three_iterative1.cpp @@ -0,0 +1,25 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool isPowerOfThree(int n) { + while (n > 0 && (n % 3 == 0)) /* 记住: 这里需用 while, 而不是if */ + { + n /= 3; + } + return n == 1; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 45; + auto res = sol.isPowerOfThree(n); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode326-power-of-three_iterative2.cpp b/cpp-leetcode/leetcode326-power-of-three_iterative2.cpp new file mode 100644 index 00000000..45afdfd2 --- /dev/null +++ b/cpp-leetcode/leetcode326-power-of-three_iterative2.cpp @@ -0,0 +1,26 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool isPowerOfThree(int n) { + if (n <= 0 || n == INT_MAX) return false; /* 2147483647的数字之和是46, 不是3的倍数, 自然不是3的次方 */ + while (n > 0 && (n % 3) == 0) + { + n /= 3; + } + return n == 1; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 45; + auto res = sol.isPowerOfThree(n); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode326-power-of-three_log1.cpp b/cpp-leetcode/leetcode326-power-of-three_log1.cpp new file mode 100644 index 00000000..d102c4b7 --- /dev/null +++ b/cpp-leetcode/leetcode326-power-of-three_log1.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPowerOfThree(int n) { + if(n <= 0) return false; + double x = log10(n)/log10(3); + if(int(x) == x) return true; + return false; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 45; + auto res = sol.isPowerOfThree(n); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode326-power-of-three_log2.cpp b/cpp-leetcode/leetcode326-power-of-three_log2.cpp new file mode 100644 index 00000000..0fd014d2 --- /dev/null +++ b/cpp-leetcode/leetcode326-power-of-three_log2.cpp @@ -0,0 +1,22 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPowerOfThree(int n) { + return fmod(log10(n)/log10(3), 1) == 0; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 45; + auto res = sol.isPowerOfThree(n); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode328-odd-even-linked-list_simulate.cpp b/cpp-leetcode/leetcode328-odd-even-linked-list_simulate.cpp new file mode 100644 index 00000000..592d06ee --- /dev/null +++ b/cpp-leetcode/leetcode328-odd-even-linked-list_simulate.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + auto oddFake = new ListNode(-1); /* 用于构建奇数位结点形成的链表 */ + auto evenFake = new ListNode(-1); /* 用于构建偶数位结点形成的链表 */ + auto oddP = oddFake; + auto evenP = evenFake; + while (head != nullptr) + { + oddP->next = head; /* head指针从1号结点出发(每次走两格, 始终指向奇数编号的结点) */ + evenP->next = head->next; + oddP = oddP->next; + evenP = evenP->next; + ListNode* nextP = nullptr; /* nextP指针用来占位 */ + if (head->next != nullptr) + nextP = head->next->next; + head = nextP; /* head指针: 每次走两格 */ + } + + oddP->next = evenFake->next; /* 把偶数段链表挂接到奇数段链表后面 */ + return oddFake->next; + } +}; + +// Test +int main() +{ + Solution sol; // 2->5->6->4->7 + ListNode *head = new ListNode(2); + head->next = new ListNode(5); + head->next->next = new ListNode(6); + head->next->next->next = new ListNode(4); + head->next->next->next->next = new ListNode(7); + head->next->next->next->next->next = NULL; + ListNode *res = sol.oddEvenList(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode33-search-in-rotated-sorted-array_binary_search.cpp b/cpp-leetcode/leetcode33-search-in-rotated-sorted-array_binary_search.cpp new file mode 100644 index 00000000..f5683078 --- /dev/null +++ b/cpp-leetcode/leetcode33-search-in-rotated-sorted-array_binary_search.cpp @@ -0,0 +1,41 @@ +#include +#include +using namespace std; + +/* 分情况的二分搜索 */ +class Solution { +public: + int search(vector& nums, int target) { + int n = nums.size(); + if(n == 0) return -1; + int left = 0, right = n-1; + while(left <= right) + { + int mid = (left + right) / 2; + if (nums[mid] == target) return mid; + /* 比较 nums[right], nums[mid], nums[left], target 几处的值 */ + if (nums[mid] < nums[right]) // 包括mid在内的后半段有序 + { + if (nums[mid] < target && nums[right] >= target) left = mid + 1; + else right = mid - 1; + } else // 包括mid在内的前半段有序 + { + if (nums[left] <= target && nums[mid] > target) right = mid - 1; + else left = mid + 1; + } + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {4, 5, 6, 7, 0, 1, 2}; + int target = 0; + int res = sol.search(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode335-self-crossing_case_by_classification.cpp b/cpp-leetcode/leetcode335-self-crossing_case_by_classification.cpp new file mode 100644 index 00000000..4b96b49e --- /dev/null +++ b/cpp-leetcode/leetcode335-self-crossing_case_by_classification.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isSelfCrossing(vector& A) { + const int N = A.size(); + if (N <= 3) return false; + for (int i = 3; i < N; i++) + { + // case1: 4步之内有交点 + if (A[i-1] <= A[i-3] && A[i] >= A[i-2]) + return true; + // case 2: 5步之内有交点 + if (i >= 4 && A[i-3] == A[i-1] && A[i] + A[i-4] >= A[i-2]) + return true; + // case 3: 6步之内有交点 + if (i >= 5 && A[i-3] >= A[i-1] && A[i-1] + A[i-5] >= A[i-3] && A[i-2] >= A[i-4] && A[i-4] + A[i] >= A[i-2]) + return true; + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2,1,1,2}; + auto res = sol.isSelfCrossing(nums); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode337-house-robber-iii_binary_tree_recursive.cpp b/cpp-leetcode/leetcode337-house-robber-iii_binary_tree_recursive.cpp new file mode 100644 index 00000000..8d9a4c4b --- /dev/null +++ b/cpp-leetcode/leetcode337-house-robber-iii_binary_tree_recursive.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { + unordered_map robDict; /* 记忆化 */ + unordered_map noRobDict; +public: + int rob(TreeNode* root) { + return dfs(root, 1); + } + int dfs(TreeNode* node, int flag) /* flag: 1表示可抢可不抢, 0表示后续不能抢 */ + { + if (node == nullptr) return 0; + if (flag == 0 && noRobDict.find(node) != noRobDict.end()) + return noRobDict[node]; + if (flag == 1 && robDict.find(node) != robDict.end()) + return robDict[node]; + + int res; + if (flag == 0) + res = dfs(node->left, 1) + dfs(node->right, 1); + else + { + int option1 = node->val + dfs(node->left, 0) + dfs(node->right, 0); + int option2 = dfs(node->left, 1) + dfs(node->right, 1); + res = max(option1, option2); + } + + if (flag == 0) + noRobDict[node] = res; + else robDict[node] = res; + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(4); + root->right = new TreeNode(5); + root->left->left = new TreeNode(1); + root->left->right = new TreeNode(3); + root->right->right = new TreeNode(1); + + auto res = sol.rob(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode34-find-first-and-last-position-of-element-in-sorted-array_binary_search.cpp b/cpp-leetcode/leetcode34-find-first-and-last-position-of-element-in-sorted-array_binary_search.cpp new file mode 100644 index 00000000..8f67cefc --- /dev/null +++ b/cpp-leetcode/leetcode34-find-first-and-last-position-of-element-in-sorted-array_binary_search.cpp @@ -0,0 +1,50 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector searchRange(vector& nums, int target) { + vector res(2, -1); + if (nums.empty()) return res; /* 处理输入: nums = {} */ + + const int len = nums.size(); + int left = 0, right = len - 1; + while (left < right) + { + int mid = (left + right) / 2; + if (nums[mid] < target) + left = mid + 1; + else right = mid; + } + if (nums[right] != target) + return res; + + res[0] = right; + left = right, right = nums.size(); + + while (left < right) + { + int mid = (left + right) / 2; + if (nums[mid] <= target) + left = mid + 1; + else right = mid; + } + res[1] = left - 1; + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 7, 7, 8, 8, 10}; + int target = 8; + auto res = sol.searchRange(nums, target); + for (auto &pos : res) + cout << pos << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode347-top-k-frequent-elements_priority_queue.cpp b/cpp-leetcode/leetcode347-top-k-frequent-elements_priority_queue.cpp new file mode 100644 index 00000000..41c3331a --- /dev/null +++ b/cpp-leetcode/leetcode347-top-k-frequent-elements_priority_queue.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + vector res; + unordered_map dict; // map: value -> count + for (auto num : nums) + { + if (dict.find(num) == dict.end()) dict[num] = 0; + else dict[num]++; + } + auto cmp = [](pair p1, pair p2) + { + return p1.second < p2.second; /* 大顶堆, p2代表顶部值 */ + }; + + priority_queue, vector>, decltype(cmp)> q(cmp); + for (auto kvp : dict) q.push(kvp); + while (k > 0) + { + res.push_back(q.top().first); + q.pop(); + + k--; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,1,1,2,2,3}; + int k = 2; + auto res = sol.topKFrequent(nums, k); + + for (auto num : res) cout << num << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode35-search-insert-position_binary_search.cpp b/cpp-leetcode/leetcode35-search-insert-position_binary_search.cpp new file mode 100644 index 00000000..73dd6805 --- /dev/null +++ b/cpp-leetcode/leetcode35-search-insert-position_binary_search.cpp @@ -0,0 +1,30 @@ +#include +#include +using namespace std; + +class Solution { +public: + int searchInsert(vector& nums, int target) { + int L = 0, R = nums.size() - 1; + while (L < R) + { + int M = (L + R) / 2; + if (nums[M] < target) + L = M + 1; + else R = M; + } + return (nums[L] < target) ? L + 1 : L; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 5, 6}; + int target = 4; + int res = sol.searchInsert(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode35-search-insert-postion_solution1.cpp b/cpp-leetcode/leetcode35-search-insert-postion_solution1.cpp new file mode 100644 index 00000000..94e43264 --- /dev/null +++ b/cpp-leetcode/leetcode35-search-insert-postion_solution1.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +/* 基于find库函数来做, 分两种情况处理 */ +class Solution { +public: + int searchInsert(vector& nums, int target) { + int len = nums.size(); + int pos = -1; + auto it = find(nums.begin(), nums.end(), target); + if (it != nums.end()) + { + pos = it - nums.begin(); + return pos; + } + else + { + if (target < nums[0]) return 0; + if (target > nums[len-1]) return len; + for (int i = 1; i < len; i++) + { + if (target > nums[i-1] && target < nums[i]) /* 题意: 数组中不会出现元素相等的情况 */ + pos = i; /* 此时pos是insertPos, 即需要插入的位置 */ + } + } + return pos; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,3,5,6}; + auto target = 5; + printf("%d", sol.searchInsert(nums, target)); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode350-intersection-of-two-arrays-ii_dict.cpp b/cpp-leetcode/leetcode350-intersection-of-two-arrays-ii_dict.cpp new file mode 100644 index 00000000..e48eddbd --- /dev/null +++ b/cpp-leetcode/leetcode350-intersection-of-two-arrays-ii_dict.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + unordered_map dict1; // map: value -> count + unordered_map dict2; + unordered_map interDict; + for (auto n : nums1) + { + if (dict1.find(n) == dict1.end()) dict1[n] = 1; + else dict1[n]++; + } + for (auto n : nums2) + { + if (dict2.find(n) == dict2.end()) dict2[n] = 1; + else dict2[n]++; + } + for (auto n : nums1) + { + if (dict2.find(n) != dict2.end()) interDict[n] = min(dict1[n], dict2[n]); + } + vector res; + for (auto kvp : interDict) + { + int count = kvp.second; + while(count > 0) + { + res.push_back(kvp.first); + count--; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums1 = {1, 2, 2, 1}; + vector nums2 = {2, 2}; + auto res = sol.intersect(nums1, nums2); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_lower_bound.cpp b/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_lower_bound.cpp new file mode 100644 index 00000000..804a3757 --- /dev/null +++ b/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_lower_bound.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +using namespace std; + +class SummaryRanges { +private: + vector> vec; +public: + void addNum(int val) { + auto cmp = [](const vector& a, const vector& b) { + return a[0] < b[0]; + }; + vector newRange = {val, val}; + auto it = lower_bound(vec.begin(), vec.end(), newRange, cmp); + int start = val, end = val; + if (it != vec.begin() && (*(it - 1))[1] + 1 >= val) // *(it - 1) 是迭代器指针it前一个区间 + it--; + while (it != vec.end() && val + 1 >= (*it)[0] && val - 1 <= (*it)[1]) + { + start = min(start, (*it)[0]); // *(it) 是当前迭代器指针it指向的区间 + end = max(end, (*it)[1]); + it = vec.erase(it); + } + vec.insert(it, {start, end}); + } + + vector> getIntervals() { + return vec; + } +}; + +void print2dVec(vector> res) +{ + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + cout << "----------------\n"; +} + +int main() +{ + // vector nums = {0, 2, 3, 4, 6, 8, 9}; + SummaryRanges* sr = new SummaryRanges(); + // sr->addNum(val); + vector> ranges = sr->getIntervals(); + print2dVec(ranges); + + sr->addNum(1); // arr = {1} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}} + sr->addNum(3); // arr = {1, 3} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}, {3, 3}} + sr->addNum(7); // arr = {1, 3, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}, {3, 3}, {7, 7}} + sr->addNum(2); // arr = {1, 2, 3, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 3}, {7, 7}} + sr->addNum(6); // arr = {1, 2, 3, 6, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 3}, {6, 7}} + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_set.cpp b/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_set.cpp new file mode 100644 index 00000000..74e529d4 --- /dev/null +++ b/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_set.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; + +class SummaryRanges { +private: + struct cmp { + bool operator()(const vector& a, const vector& b) const + { + return a[0] < b[0]; + } + }; + set, cmp> st; +public: + SummaryRanges() { + } + void addNum(int val) { + auto it = st.lower_bound({val, val}); + int start = val, end = val; + if (it != st.begin() && (*(prev(it)))[1] + 1 >= start) it--; + while (it != st.end() && end + 1 >= (*it)[0]) + { + start = min(start, (*it)[0]); + end = max(end, (*it)[1]); + it = st.erase(it); + } + st.insert(it, {start, end}); + } + vector> getIntervals() { + vector> res; + for (const auto& val : st) res.push_back(val); + return res; + } +}; + +void print2dVec(vector> res) +{ + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + cout << "----------------\n"; +} + +int main() +{ + // vector nums = {0, 2, 3, 4, 6, 8, 9}; + SummaryRanges* sr = new SummaryRanges(); + // sr->addNum(val); + vector> ranges = sr->getIntervals(); + print2dVec(ranges); + + sr->addNum(1); // arr = {1} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}} + sr->addNum(3); // arr = {1, 3} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}, {3, 3}} + sr->addNum(7); // arr = {1, 3, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}, {3, 3}, {7, 7}} + sr->addNum(2); // arr = {1, 2, 3, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 3}, {7, 7}} + sr->addNum(6); // arr = {1, 2, 3, 6, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 3}, {6, 7}} + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_upper_bound.cpp b/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_upper_bound.cpp new file mode 100644 index 00000000..47f2a3a7 --- /dev/null +++ b/cpp-leetcode/leetcode352-data-stream-as-disjoint-intervals_using_upper_bound.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +using namespace std; + +class SummaryRanges { +private: + vector> _ranges; +public: + /** Initialize your data structure here. */ + SummaryRanges() { + } + void addNum(int val) { + vector newRange = vector(2, val); + auto cmp = [](const vector& a, const vector& b) { + return a[0] < b[0]; + }; + auto it = upper_bound(_ranges.begin(), _ranges.end(), newRange, cmp); /* 寻找要插入的位置 */ + if (it == _ranges.begin()) + { + if (it != _ranges.end() && (*it)[0] == val + 1) + (*it)[0] = val; + else + _ranges.insert(it, newRange); + } + else + { + int curPos = it - _ranges.begin(); + int prePos = curPos - 1; + if (val > _ranges[prePos][1]) + { + if (val == _ranges[prePos][1] + 1) + { + newRange[0] = _ranges[prePos][0]; + _ranges.erase(_ranges.begin() + prePos); + curPos--; + } + if (curPos < _ranges.size() && val == _ranges[curPos][0] - 1) + { + newRange[1] = _ranges[curPos][1]; + _ranges.erase(_ranges.begin() + curPos); + } + _ranges.insert(_ranges.begin() + curPos, newRange); + } + } + } + vector> getIntervals() { + return _ranges; + } +}; + +void print2dVec(vector> res) +{ + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + cout << "----------------\n"; +} + +int main() +{ + // vector nums = {0, 2, 3, 4, 6, 8, 9}; + SummaryRanges* sr = new SummaryRanges(); + // sr->addNum(val); + vector> ranges = sr->getIntervals(); + print2dVec(ranges); + + sr->addNum(1); // arr = {1} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}} + sr->addNum(3); // arr = {1, 3} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}, {3, 3}} + sr->addNum(7); // arr = {1, 3, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 1}, {3, 3}, {7, 7}} + sr->addNum(2); // arr = {1, 2, 3, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 3}, {7, 7}} + sr->addNum(6); // arr = {1, 2, 3, 6, 7} + print2dVec(sr->getIntervals()); // 返回 {{1, 3}, {6, 7}} + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode36-valid-sudoku_bit_operation.cpp b/cpp-leetcode/leetcode36-valid-sudoku_bit_operation.cpp new file mode 100644 index 00000000..c20d2fd6 --- /dev/null +++ b/cpp-leetcode/leetcode36-valid-sudoku_bit_operation.cpp @@ -0,0 +1,61 @@ +#include +#include +// #include +using namespace std; + +class Solution { +public: + bool isValidSudoku(vector>& board) { + vector row(9); // row[j]表示第j 行的9个数字各自的存在情况,同理于col, boxes + vector col(9); + vector boxes(9); + + int shiftInt = 0; + for (int i = 0; i < 9; i++) + { + for (int j = 0; j < 9; j++) + { + if (board[i][j] == '.') + continue; + + shiftInt = 1 << (board[i][j] - '0'); // 转为二进制,移位结束后目标位为1,其他位均为0 + /* 每个格子若有数字,必为 1 ~ 9,该方法适用于 遍历行/遍历列/遍历box */ + int boxPos = (i / 3) * 3 + j / 3; //将大数独棋盘分成9个小棋盘,编号0~8 + + // 如果当前数字shiftInt在row[j] 或col[i] 或 boxes中已经存在,&运算后不为0, + // 只有当前数字没出现过,&运算后为0 + if ((col[i] & shiftInt) != 0 || (row[j] & shiftInt) != 0 || (boxes[boxPos] & shiftInt) != 0) + return false; + + //第 n 位代表 n 这个数字是否存在(1→存在, 0→不存在),同理于col[i] boxes[boxPos] + row[j] |= shiftInt; + col[i] |= shiftInt; + boxes[boxPos] |= shiftInt; + } + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board /* 不能使用=进行赋值初始化, 自动调用构造函数 */ + { + {'5','3','.','.','7','.','.','.','.'}, + {'6','.','.','1','9','5','.','.','.'}, + {'.','9','8','.','.','.','.','6','.'}, + {'8','.','.','.','6','.','.','.','3'}, + {'4','.','.','8','.','3','.','.','1'}, + {'7','.','.','.','2','.','.','.','6'}, + {'.','6','.','.','.','.','2','8','.'}, + {'.','.','.','4','1','9','.','.','5'}, + {'.','.','.','.','8','.','.','7','9'} + }; + + bool isValid = sol.isValidSudoku(board); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode36-valid-sudoku_direct_force.cpp b/cpp-leetcode/leetcode36-valid-sudoku_direct_force.cpp new file mode 100644 index 00000000..0f991e8c --- /dev/null +++ b/cpp-leetcode/leetcode36-valid-sudoku_direct_force.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include /* 使用set就够了,不一定需要unordered_set */ +#include +using namespace std; + +class Solution { +public: + bool isValidSudoku(vector> &board) + { + bool isValid = true; + + // 遍历行 + for (int i = 0; i < 9; i++) + { + set st; + vector rowVec = board[i]; + int dotCount = 0; + for (int k = 0; k < 9; k++) + { + if (rowVec[k] == '.') + { + dotCount++; + } + else + st.insert(rowVec[k]); + } + int uniqueCharCount = st.size(); + if (uniqueCharCount + dotCount != 9) + { + isValid = false; + } + } + + // 遍历列 + for (int i = 0; i < 9; i++) + { + set st; + int dotCount = 0; + for (int k = 0; k < 9; k++) + { + if (board[k][i] == '.') + { + dotCount++; + } + else + st.insert(board[k][i]); + } + int uniqueCharCount = st.size(); + if (uniqueCharCount + dotCount != 9) + { + isValid = false; + } + } + + // 遍历小grid: 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 + for (int si = 0; si <= 6; si += 3) + for (int sj = 0; sj <= 6; sj += 3) + { + set st; + int dotCount = 0; + for (int i = si; i < si + 3; i++) + { + for (int j = sj; j < sj + 3; j++) + { + if (board[i][j] == '.') + dotCount += 1; + else + st.insert(board[i][j]); + } + } + if (st.size() + dotCount != 9) + isValid = false; + } + return isValid; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board /* 不能使用=进行赋值初始化, 自动调用构造函数 */ + { + {'5','3','.','.','7','.','.','.','.'}, + {'6','.','.','1','9','5','.','.','.'}, + {'.','9','8','.','.','.','.','6','.'}, + {'8','.','.','.','6','.','.','.','3'}, + {'4','.','.','8','.','3','.','.','1'}, + {'7','.','.','.','2','.','.','.','6'}, + {'.','6','.','.','.','.','2','8','.'}, + {'.','.','.','4','1','9','.','.','5'}, + {'.','.','.','.','8','.','.','7','9'} + }; + + bool isValid = sol.isValidSudoku(board); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode36-valid-sudoku_direct_set.cpp b/cpp-leetcode/leetcode36-valid-sudoku_direct_set.cpp new file mode 100644 index 00000000..bd7408ce --- /dev/null +++ b/cpp-leetcode/leetcode36-valid-sudoku_direct_set.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include /* 使用set就够了,不一定需要unordered_set */ +#include +using namespace std; + +class Solution { +public: + bool isValidSudoku(vector>& board) { + set st; + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + char ch = board[i][j]; + // 使用i / 3 + "," + j / 3 得到对应第几行第几列的方块(box) + if (ch != '.'){ + string val; + val.push_back(ch); + /* 对于任意一个值不为'.'的字符 + 1.把所在row的信息插入到大九宫格中; + 2.把所在column的信息插入到大九宫格中; + 3.把所在的小方块(box)的信息插入到大九宫格中。 + 插入如果失败说明出现了重复。 */ + if (!st.insert(val + " in row " + to_string(i)).second || + !st.insert(val + " in column " + to_string(j)).second || + !st.insert(val + " in box " + to_string(i / 3) + "," + to_string(j / 3)).second) + return false; /* set插入失败时,表示出现了重复 */ + } + } + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board /* 不能使用=进行赋值初始化, 自动调用构造函数 */ + { + {'5','3','.','.','7','.','.','.','.'}, + {'6','.','.','1','9','5','.','.','.'}, + {'.','9','8','.','.','.','.','6','.'}, + {'8','.','.','.','6','.','.','.','3'}, + {'4','.','.','8','.','3','.','.','1'}, + {'7','.','.','.','2','.','.','.','6'}, + {'.','6','.','.','.','.','2','8','.'}, + {'.','.','.','4','1','9','.','.','5'}, + {'.','.','.','.','8','.','.','7','9'} + }; + + bool isValid = sol.isValidSudoku(board); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode367-valid-perfect-square_math.cpp b/cpp-leetcode/leetcode367-valid-perfect-square_math.cpp new file mode 100644 index 00000000..d902f1d5 --- /dev/null +++ b/cpp-leetcode/leetcode367-valid-perfect-square_math.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPerfectSquare(int num) { + int i = 1; // i: 表示奇数, 1是用于下面循环的奇数初始值 + while (num > 0) + { + num -= i; + i += 2; + } + if (num == 0) return true; + return false; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 14; + auto res = sol.isPerfectSquare(num); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode37-sudoku-solver_dfs.cpp b/cpp-leetcode/leetcode37-sudoku-solver_dfs.cpp new file mode 100644 index 00000000..1eef4e18 --- /dev/null +++ b/cpp-leetcode/leetcode37-sudoku-solver_dfs.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void solveSudoku(vector>& board) { + dfs(board, 0, 0); + } + /* dfs表示第i行第j列是否能合法地填完. 其中i是行索引row, j是列索引col */ + bool dfs(vector>& board, int i, int j) + { + if (i == 9) return true; /* 9行(全局)都填好了 */ + if (j == 9) return dfs(board, i + 1, 0); /* 填完了当前行, 换一行继续 */ + if (board[i][j] != '.') return dfs(board, i, j + 1); /* 当前格子不为空白格, 表示是已经填好的数字, 就看同行的下一列 */ + for (char ch = '1'; ch <= '9'; ch++) + { + if (!isValid(board, i, j, ch)) continue; + board[i][j] = ch; + if (dfs(board, i, j + 1)) return true; + + board[i][j] = '.'; + } + return false; + } + bool isValid(vector>& board, int i, int j, char ch) + { + for (int row = 0; row < 9; row++) + { + if (board[row][j] == ch) return false; + } + for (int col = 0; col < 9; col++) + { + if (board[i][col] == ch) return false; + } + int x = i / 3 * 3; + int y = j / 3 * 3; + for (int p = 0; p < 3; p++) + { + for (int q = 0; q < 3; q++) + { + if (board[x + p][y + q] == ch) return false; + } + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board /* 不能使用=进行赋值初始化, 自动调用构造函数 */ + { + {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'} + }; + + sol.solveSudoku(board); + for (auto& rows : board) // 遍历每一行 + { + for (auto& elem : rows) // 输出每一个元素 + cout << elem << "\t"; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode37-sudoku-solver_dfs_pruning.cpp b/cpp-leetcode/leetcode37-sudoku-solver_dfs_pruning.cpp new file mode 100644 index 00000000..aff7adf9 --- /dev/null +++ b/cpp-leetcode/leetcode37-sudoku-solver_dfs_pruning.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void solveSudoku(vector>& board) { + dfs(board, 0, 0); + } + bool dfs(vector>& board, int i, int j) + { + if (i == 9) return true; + if (j == 9) + return dfs(board, i + 1, 0); + if (board[i][j] != '.') + return dfs(board, i, j + 1); + + for (int ch = '1'; ch <= '9'; ch++) + { + if (!isValid(board, i, j, ch)) continue; + board[i][j] = ch; + if (dfs(board, i, j + 1)) return true; + board[i][j] = '.'; + } + return false; + } + bool isValid(vector>& board, int i, int j, char ch) + { + for (int row = 0; row < 9; row++) + { + if (row != i && board[row][j] == ch) return false; + } + for (int col = 0; col < 9; col++) + { + if (col != j && board[i][col] == ch) return false; + } + int x = i / 3 * 3; + int y = j / 3 * 3; + for (int p = x; p < x + 3; p++) + { + for (int q = y; q < y + 3; q++) + { + if ((p != i || q != j) && board[p][q] == ch) return false; + } + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board /* 不能使用=进行赋值初始化, 自动调用构造函数 */ + { + {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, + {'.', '.', '.', '.', '8', '.', '.', '7', '9'} + }; + + sol.solveSudoku(board); + for (auto& rows : board) // 遍历每一行 + { + for (auto& elem : rows) // 输出每一个元素 + cout << elem << "\t"; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode370-range-addition(locked)_difference_array.cpp b/cpp-leetcode/leetcode370-range-addition(locked)_difference_array.cpp new file mode 100644 index 00000000..91e78663 --- /dev/null +++ b/cpp-leetcode/leetcode370-range-addition(locked)_difference_array.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector getModifiedArray(int length, vector> &updates) { + // 技巧: 差分数组 + vector diff(length + 1, 0); + for (int i = 1; i <= updates.size(); i++) + { + vector group = updates[i - 1]; + int startIndex = group[0]; + int endIndex = group[1]; + int inc = group[2]; + + rangeInc(diff, startIndex, endIndex, inc); + } + // 反推出前缀和 + vector preSum(length + 1, 0); + for (int i = 0; i <= length - 1; i++) + preSum[i + 1] = preSum[i] + diff[i]; + preSum.erase(preSum.begin()); /* 删除前缀和数组多余的数: 第一个元素0 */ + + return preSum; + } + // [l, r]范围的差分数组的所有元素+c + void rangeInc(vector& diff, int l, int r, int c) + { + diff[l] += c; + diff[r+1] -= c; + } +}; + +// Test +int main() +{ + Solution sol; + int len = 5; + vector> updates = {{1,3,2},{2,4,3},{0,2, -2}}; + auto res = sol.getModifiedArray(len, updates); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode371-sum-of-two-integers_accumulate1.cpp b/cpp-leetcode/leetcode371-sum-of-two-integers_accumulate1.cpp new file mode 100644 index 00000000..15217e68 --- /dev/null +++ b/cpp-leetcode/leetcode371-sum-of-two-integers_accumulate1.cpp @@ -0,0 +1,26 @@ +#include +#include /* 含有 accumulate 函数 */ +#include +#include +using namespace std; + +class Solution { +public: + int getSum(int a, int b) { + vector nums = {a, b}; + auto res = accumulate(nums.begin(), nums.end(), 0); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int a = 10; + int b = -3; + auto res = sol.getSum(a, b); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode371-sum-of-two-integers_accumulate2.cpp b/cpp-leetcode/leetcode371-sum-of-two-integers_accumulate2.cpp new file mode 100644 index 00000000..9fc1bedf --- /dev/null +++ b/cpp-leetcode/leetcode371-sum-of-two-integers_accumulate2.cpp @@ -0,0 +1,25 @@ +#include +#include /* 含有 accumulate 函数 */ +#include +#include +using namespace std; + +class Solution { +public: + int getSum(int a, int b) { + int nums[2] = {a, b}; + return accumulate(begin(nums), end(nums), 0); + } +}; + +// Test +int main() +{ + Solution sol; + int a = 10; + int b = -3; + auto res = sol.getSum(a, b); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode371-sum-of-two-integers_bit_op_iterative.cpp b/cpp-leetcode/leetcode371-sum-of-two-integers_bit_op_iterative.cpp new file mode 100644 index 00000000..c8ff0f1f --- /dev/null +++ b/cpp-leetcode/leetcode371-sum-of-two-integers_bit_op_iterative.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int getSum(int a, int b) { + unsigned int carry; + while (b != 0) /* 把b先拿过去与a相加(&运算求出进位值, 异或^求出和的不进位部分), 后面用b存储每一次的进位值 */ + { + carry = (unsigned long)(a & b) << 1; /* 单独处理进位, unsigned long有时可以换成unsigned int */ + a ^= b; /* 对位相加, 不处理进位的部分 */ + b = carry; + } + return a; + } +}; + +// Test +int main() +{ + Solution sol; + int a = 10; + int b = -3; + auto res = sol.getSum(a, b); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode371-sum-of-two-integers_bit_op_recursive.cpp b/cpp-leetcode/leetcode371-sum-of-two-integers_bit_op_recursive.cpp new file mode 100644 index 00000000..f3eb079a --- /dev/null +++ b/cpp-leetcode/leetcode371-sum-of-two-integers_bit_op_recursive.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int getSum(int a, int b) { + if(a == 0 || b == 0) return a | b; + int sum = a^b; /* 对位相加, 不处理进位的部分(一个1, 一个0, 异或会得到1, 无进位; 两个0, 异或得到0; 两个1, 结果为0, 把进位丢给下面一行的&运算去处理) */ + unsigned int carry = a & b; /* 处理进位: 两个二进制数对位相加时, 同一个bit位都为1时才会产生进位 */ + return getSum(sum, carry << 1); + } +}; + +// Test +int main() +{ + Solution sol; + int a = 10; + int b = -3; + auto res = sol.getSum(a, b); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode371-sum-of-two-integers_exp_and_log.cpp b/cpp-leetcode/leetcode371-sum-of-two-integers_exp_and_log.cpp new file mode 100644 index 00000000..357846ec --- /dev/null +++ b/cpp-leetcode/leetcode371-sum-of-two-integers_exp_and_log.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int getSum(int a, int b) { + return log(exp(a)*exp(b)); + } +}; + +// Test +int main() +{ + Solution sol; + int a = 10; + int b = -3; + auto res = sol.getSum(a, b); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode373-find-k-pairs-with-smallest-sums_priority_queue_using_pair.cpp b/cpp-leetcode/leetcode373-find-k-pairs-with-smallest-sums_priority_queue_using_pair.cpp new file mode 100644 index 00000000..ba6a2e75 --- /dev/null +++ b/cpp-leetcode/leetcode373-find-k-pairs-with-smallest-sums_priority_queue_using_pair.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { + int m = nums1.size(), n = nums2.size(); + priority_queue>, vector>>, greater<>> pq; + vector> res; + if (m == 0 || n == 0) + return res; + for (int i = 0; i < m; i++) + { + pq.push({ {nums1[i] + nums2[0]}, {i, 0} }); + } + while (!pq.empty() && k-- > 0) + { + int i = pq.top().second.first; + int j = pq.top().second.second; + pq.pop(); + + vector group = {nums1[i], nums2[j]}; + res.push_back(group); + if (j + 1 == n) continue; + pq.push({{nums1[i] + nums2[j + 1]}, {i, j + 1}}); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 12; + vector nums1 = {1, 7, 11}, nums2 = {2, 4, 6}; + int k = 3; + auto res = sol.kSmallestPairs(nums1, nums2, k); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode373-find-k-pairs-with-smallest-sums_priority_queue_using_tuple.cpp b/cpp-leetcode/leetcode373-find-k-pairs-with-smallest-sums_priority_queue_using_tuple.cpp new file mode 100644 index 00000000..4c1eaf27 --- /dev/null +++ b/cpp-leetcode/leetcode373-find-k-pairs-with-smallest-sums_priority_queue_using_tuple.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { + vector> res; + int n = nums1.size(), m = nums2.size(); + if (n == 0 || m == 0) + return res; + + priority_queue, vector>, greater<>> pq; + pq.push({nums1[0] + nums2[0], 0, 0}); + while (pq.size() && res.size() < k) + { + auto topP = pq.top(); + int i = get<1>(topP); + int j = get<2>(topP); + pq.pop(); + + res.push_back({nums1[i], nums2[j]}); + if (j == 0 && i + 1 < n) + pq.push({nums1[i + 1] + nums2[j], i + 1, j}); /* 关键操作 */ + + if (i < n && j + 1 < m) + pq.push({nums1[i] + nums2[j + 1], i, j + 1}); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 12; + vector nums1 = {1, 7, 11}, nums2 = {2, 4, 6}; + int k = 3; + auto res = sol.kSmallestPairs(nums1, nums2, k); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode38-count-and-say_solution1.cpp b/cpp-leetcode/leetcode38-count-and-say_solution1.cpp new file mode 100644 index 00000000..4be1c043 --- /dev/null +++ b/cpp-leetcode/leetcode38-count-and-say_solution1.cpp @@ -0,0 +1,55 @@ +#include +#include +// #include +using namespace std; + +/* +主体思路: 以已知a4=1211, 来求a5为例。 +首先将不同字符间(用虚线)划开进行分片,即 1|2|11,分别统计各个分片中连续相同的字符数即可。 +*/ +class Solution { +public: + string countAndSay(int n) { + if(n == 1) + return "1"; // f(1) = 1 + + string res = "1"; // f(1) = 1, 作为迭代的初始值放入到结果中 + for(int i=0; i +#include +// #include +using namespace std; + +/* +主体思路: 以已知a4=1211, 来求a5为例。 +首先将不同字符间(用虚线)划开进行分片,即 1|2|11,分别统计各个分片中连续相同的字符数即可。 +*/ +class Solution { +public: + string countAndSay(int n) { + string res = "1"; // f(1) = 1 + + while (n > 1) { + string curStr = ""; + for (int i = 0; i < res.size(); i++) { + int count = getRepeatCount(res.substr(i)); // 截取从当前字符到末尾的子串 + curStr += to_string(count); + curStr.push_back(res[i]); + + // 跳过重复的字符, 共处理一次即可 + i = i + count - 1; + } + n--; // 总共需要迭代 n-1 次 + + res = curStr; // 将结果用作下一轮循环的初始值 + } + return res; + } + + /* 得到字符串 str 中第一个分片中连续相等数的重复个数,例如: "111221" 返回 3, "2" 返回 1 */ + int getRepeatCount(string str) { + int count = 1; + char same = str[0]; + for (int i = 1; i < str.size(); i++) { + if (same == str[i]) { + count++; + } else { + break; + } + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 9; + string res = sol.countAndSay(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode38-count-and-say_solution3.cpp b/cpp-leetcode/leetcode38-count-and-say_solution3.cpp new file mode 100644 index 00000000..a5c1fbc4 --- /dev/null +++ b/cpp-leetcode/leetcode38-count-and-say_solution3.cpp @@ -0,0 +1,36 @@ +#include +#include +// #include +using namespace std; + +class Solution { +public: + string countAndSay(int n) { + if (n <= 0) return ""; + string res = "1"; + while (--n) { + string curStr = ""; + for (int i = 0; i < res.size(); ++i) { + int count = 1; // 出现第一个新字符, count置为1 + while (i + 1 < res.size() && res[i] == res[i + 1]) { /* 这里与上1层循环用的是同一个i, 且区间是上层循环的子区间, 故时间复杂度是O(n^2) */ + count++; + i++; + } + curStr += to_string(count) + res[i]; + } + res = curStr; // 将结果用作下一轮循环的初始值 + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 9; + string res = sol.countAndSay(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode383-ransom-note_brute_force.cpp b/cpp-leetcode/leetcode383-ransom-note_brute_force.cpp new file mode 100644 index 00000000..208f2427 --- /dev/null +++ b/cpp-leetcode/leetcode383-ransom-note_brute_force.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + for (char& ch : ransomNote) + { + auto it = find(magazine.begin(), magazine.end(), ch); + if (it != magazine.end()) + { + magazine.erase(it); + } + else return false; + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + string ransomNote = "aa", magazine = "ab"; + auto res = sol.canConstruct(ransomNote, magazine); + cout << (res == true ? "True" : "False") << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode383-ransom-note_hash_using_array.cpp b/cpp-leetcode/leetcode383-ransom-note_hash_using_array.cpp new file mode 100644 index 00000000..d34ce958 --- /dev/null +++ b/cpp-leetcode/leetcode383-ransom-note_hash_using_array.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + int freq1[128]; // 题意: 字符串ransomNote和magazine均只含小写字母 + fill(freq1, freq1 + 128, 0); + int freq2[128]; + fill(freq2, freq2 + 128, 0); + for (auto& ch : ransomNote) + freq1[ch]++; + for (auto& ch : magazine) + freq2[ch]++; + for (int i = 0; i < ransomNote.size(); i++) + { + char ch = ransomNote[i]; + if (freq1[ch] > freq2[ch]) return false; + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + string ransomNote = "aa", magazine = "ab"; + auto res = sol.canConstruct(ransomNote, magazine); + cout << (res == true ? "True" : "False") << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode383-ransom-note_hash_using_vector.cpp b/cpp-leetcode/leetcode383-ransom-note_hash_using_vector.cpp new file mode 100644 index 00000000..76ec06fb --- /dev/null +++ b/cpp-leetcode/leetcode383-ransom-note_hash_using_vector.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + vector freq1(128); // 题意: 字符串ransomNote和magazine均只含小写字母 + vector freq2(128); + for (auto& ch : ransomNote) + freq1[ch]++; + for (auto& ch : magazine) + freq2[ch]++; + for (int i = 0; i < ransomNote.size(); i++) + { + char ch = ransomNote[i]; + if (freq1[ch] > freq2[ch]) return false; + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + string ransomNote = "aa", magazine = "ab"; + auto res = sol.canConstruct(ransomNote, magazine); + cout << (res == true ? "True" : "False") << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode387-first-unique-character-in-a-string_hashmap.cpp b/cpp-leetcode/leetcode387-first-unique-character-in-a-string_hashmap.cpp new file mode 100644 index 00000000..5c9475d1 --- /dev/null +++ b/cpp-leetcode/leetcode387-first-unique-character-in-a-string_hashmap.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +class Solution { +public: + int firstUniqChar(string s) { + unordered_map dict; + for (char ch : s) + dict[ch]++; + for (int i = 0; i < s.size(); ++i) { + if (dict[s[i]] == 1) + return i; + } + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "leetcode"; + auto res = sol.firstUniqChar(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode389-find-the-difference_dict.cpp b/cpp-leetcode/leetcode389-find-the-difference_dict.cpp new file mode 100644 index 00000000..f1e2d5db --- /dev/null +++ b/cpp-leetcode/leetcode389-find-the-difference_dict.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; + +class Solution { +public: + char findTheDifference(string s, string t) { + unordered_map dictS; + unordered_map dictT; + for (auto ch1 : s) + dictS[ch1]++; + for (auto ch2 : t) + dictT[ch2]++; + + char res; + for (auto kvp : dictT) + { + char key = kvp.first; + int value = kvp.second; + + if (kvp.second != dictS[kvp.first]) + { + res = key; + break; + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abcd", t = "abcde"; + auto res = sol.findTheDifference(s, t); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode39-combination-sum_backtracking.cpp b/cpp-leetcode/leetcode39-combination-sum_backtracking.cpp new file mode 100644 index 00000000..d6274fa7 --- /dev/null +++ b/cpp-leetcode/leetcode39-combination-sum_backtracking.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +using namespace std; + +// dfs +class Solution { + vector> res; + +public: + vector> combinationSum(vector& candidates, int target) { + vector curGroup; + dfs(candidates, target, curGroup, 0, 0); + return res; + } + void dfs(vector &candidates, int target, vector &curGroup, int sum, int startPos) + { + if (sum > target) + return; + if (sum == target) + res.push_back(curGroup); + else + { + int curSum = sum; + for (int i = startPos; i < candidates.size(); i++) + { + sum = curSum; // 保证sum不受同层元素的影响 + sum = sum + candidates[i]; + curGroup.push_back(candidates[i]); + dfs(candidates, target, curGroup, sum, i); + curGroup.pop_back(); + } + } + } +}; + +// Test +int main() +{ + vector candidates = {2, 3, 6, 7}; + int target = 7; + Solution sol; + auto res = sol.combinationSum(candidates, target); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode390-elimination-game_find_law_recursive.cpp b/cpp-leetcode/leetcode390-elimination-game_find_law_recursive.cpp new file mode 100644 index 00000000..0aecf5cc --- /dev/null +++ b/cpp-leetcode/leetcode390-elimination-game_find_law_recursive.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int lastRemaining(int n) { + if (n == 1) return 1; + /* 递归: f(n) = 2(n/2 + 1 - f(n/2)) */ + return n == 1 ? 1 : 2 * (n/2 + 1 - lastRemaining(n/2)); + } +}; + +// Test +int main() +{ + Solution sol; + int n = 4; + auto res = sol.lastRemaining(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode392-is-subsequence_two_pointers.cpp b/cpp-leetcode/leetcode392-is-subsequence_two_pointers.cpp new file mode 100644 index 00000000..03e2a00d --- /dev/null +++ b/cpp-leetcode/leetcode392-is-subsequence_two_pointers.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isSubsequence(string s, string t) { + if (s.empty()) return true; + // 双指针法 + int i = 0, j = 0; + while (i < s.size() && j < t.size()) { /* s中的每一个字符t中都有, 且相对顺序一致 */ + if (s[i] == t[j]) i++; + j++; + } + return i == s.size(); + } +}; + +// Test +int main() +{ + Solution sol; + string s = "ab", t = "baab"; + auto res = sol.isSubsequence(s, t); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode393-utf-8-validation_bit_operation.cpp b/cpp-leetcode/leetcode393-utf-8-validation_bit_operation.cpp new file mode 100644 index 00000000..f239c28b --- /dev/null +++ b/cpp-leetcode/leetcode393-utf-8-validation_bit_operation.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool validUtf8(vector &data) { + int remain = 0; // remain: 还有几个字符(也就是还剩下几段8个bit?)需要检测 + for (int& num : data) + { + if (remain == 0) /* 检查开始的8个bit */ + { + if ((num >> 7) == 0b0) remain = 0; /* 直接删掉末尾的7位, 看二进制表示下的第1位是不是0 */ + else if ((num >> 5) == 0b110) remain = 1; /* 删掉末尾的5位, 看二进制表示下是不是以110开头 */ + else if ((num >> 4) == 0b1110) remain = 2; + else if ((num >> 3) == 0b11110) remain = 3; + else return false; + } + else /* 依次检查第1段8个bit以外的剩下段8个bit */ + { + if ((num >> 6) != 0b10) return false; + remain--; + } + } + return remain == 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector data = {197, 130, 1}; + auto res = sol.validUtf8(data); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode399-evaluate-division_dfs_with_hashmap1.cpp b/cpp-leetcode/leetcode399-evaluate-division_dfs_with_hashmap1.cpp new file mode 100644 index 00000000..a4212ce5 --- /dev/null +++ b/cpp-leetcode/leetcode399-evaluate-division_dfs_with_hashmap1.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { + unordered_map>> dict; //存储相关数据 +public: + vector calcEquation(vector>& equations, vector& values, vector>& queries) { + vector res; + for (int i = 0; i < equations.size(); i++) + { + auto eq = equations[i]; + dict[eq[0]].push_back({eq[1], values[i]}); // 放入所有的A/B + dict[eq[1]].push_back({eq[0], 1.0 / values[i]}); // 放入所有的B/A + } + for (int i = 0; i < queries.size(); i++) //遍历所有的query + { + auto eq = queries[i]; + if (dict.find(eq[0]) == dict.end() || dict.find(eq[1]) == dict.end()) + { + res.push_back(-1.0); // 提前处理: A不在哈希表中 + continue; + } + else if (eq[0] == eq[1]) + { + res.push_back(1.0); // 提前处理: A=B + continue; + } + unordered_set visited; + double temp = dfs(eq[0], eq[1], visited); //剩下的都扔给dfs + res.push_back(temp); + } + return res; + } + double dfs(string A, string B, unordered_set& visited) + { + if (A == B) return 1.0; + visited.insert(A); + double temp = -1.0; + for (auto& kvp : dict[A]) //遍历A所能通向的所有位置 + { + string med = kvp.first; // 选取一个位置叫media + if (visited.find(med) != visited.end()) + continue; //如果这个位置已经访问过了,就不要再考虑 + double temp2 = dfs(med, B, visited); //剩下的就交给dfs去算从med到B的距离。 + if (temp2 != -1.0) + { + temp = kvp.second * temp2; //只要从med到B可行的话,就算找到从A到B的解了(因为题目保证没有其他med能造成冲突) + break; + } + } + return temp; + } +}; + +// Test +int main() +{ + Solution sol; + vector> equations = {{"a", "b"}, {"b", "c"}, {"bc", "cd"}}; + vector values = {1.5, 2.5, 5.0}; + vector> queries = {{"a", "c"}, {"c", "b"}, {"bc", "cd"}, {"cd", "bc"}}; + auto res = sol.calcEquation(equations, values, queries); + for (auto& num : res) + cout << num << ""; + + return 0; +} diff --git a/cpp-leetcode/leetcode4-median-of-two-sorted-arrays.cpp b/cpp-leetcode/leetcode4-median-of-two-sorted-arrays.cpp new file mode 100644 index 00000000..9f654f01 --- /dev/null +++ b/cpp-leetcode/leetcode4-median-of-two-sorted-arrays.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + vector nums; + double res; + int m = nums1.size(); + int n = nums2.size(); + int len; + + int i = 0, j = 0; + while (i < m && j < n) // 只要一个指针扫到数组末尾,循环结束 + { + if(nums1[i] <= nums2[j]) + { + nums.push_back(nums1[i]); + i++; + } + else { + nums.push_back(nums2[j]); + j++; + } + } + + while(i < m) // 数组nums1没跑完,nums2已跑完时 + { + nums.push_back(nums1[i]); + i++; + } + + while(j < n) // 数组nums2没跑完,nums1已跑完时 + { + nums.push_back(nums2[j]); + j++; + } + len = nums.size(); + if(len % 2 == 0) + { + res = (nums[len/2] + nums[len/2-1])/2.0; + } + else res = nums[len/2]; + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums1 = {1,3}; + vector nums2 = {0,2,5}; + double res = sol.findMedianSortedArrays(nums1, nums2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode40-combination-sum-ii_backtracking.cpp b/cpp-leetcode/leetcode40-combination-sum-ii_backtracking.cpp new file mode 100644 index 00000000..9b8dd318 --- /dev/null +++ b/cpp-leetcode/leetcode40-combination-sum-ii_backtracking.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +// dfs +class Solution { + vector> res; +public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); // 先排序, 防止后面重复处理 + vector curGroup; + dfs(candidates, target, 0, 0, curGroup); + return res; + } + void dfs(const vector& candidates, int target, int startPos, int sum, vector& curGroup) + { + if (target == sum) + { + res.push_back(curGroup); + return; + } + if (sum > target) return; /* 当前sum已经超出target了, 后面加入正数不可能=target了, 于是递归终止 */ + for (int i = startPos; i < candidates.size(); i++) + { + /* 去重, 当目前子区间内第1个元素(index为0)以后的元素出现重复时, 需要去重处理 */ + if (i > startPos && candidates[i] == candidates[i-1]) continue; + curGroup.push_back(candidates[i]); + dfs(candidates, target, i+1, sum + candidates[i], curGroup); + curGroup.pop_back(); + } + } +}; + +// Test +int main() +{ + vector candidates = {10,1,2,7,6,1,5}; + int target = 8; + Solution sol; + auto res = sol.combinationSum2(candidates, target); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode401-binary-watch_bit_operation.cpp b/cpp-leetcode/leetcode401-binary-watch_bit_operation.cpp new file mode 100644 index 00000000..b5d55bb8 --- /dev/null +++ b/cpp-leetcode/leetcode401-binary-watch_bit_operation.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector readBinaryWatch(int turnedOn) { + // h: 小时, m: 分钟. 00:00 -> 11:59 + vector res = {}; + for (int h = 0; h < 12; h++) + { + for (int m = 0; m < 60; m++) + { + if (count1(h) + count1(m) == turnedOn) + { + string mStr = m < 10 ? "0" + to_string(m) : to_string(m); + res.push_back(to_string(h) + ":" + mStr); + } + } + } + return res; + } + + int count1(int n) + { + int count = 0; + while (n > 0) + { + n = n & (n - 1); + count++; + } + + return count; + } +}; + +// Test +int main() +{ + Solution sol; + int count = 6; + auto res = sol.readBinaryWatch(count); + for (auto str : res) cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode405-convert-a-number-to-hexadecimal_solution1.cpp b/cpp-leetcode/leetcode405-convert-a-number-to-hexadecimal_solution1.cpp new file mode 100644 index 00000000..a07b90a8 --- /dev/null +++ b/cpp-leetcode/leetcode405-convert-a-number-to-hexadecimal_solution1.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string toHex(int num) { + string res; + long N = num; // 预处理: 将精度提升到int64, 防止大整数溢出 + if (N == 0) return "0"; + unordered_map dict + { + {0, '0'}, + {1, '1'}, + {2, '2'}, + {3, '3'}, + {4, '4'}, + {5, '5'}, + {6, '6'}, + {7, '7'}, + {8, '8'}, + {9, '9'}, + {10, 'a'}, + {11, 'b'}, + {12, 'c'}, + {13, 'd'}, + {14, 'e'}, + {15, 'f'} + }; + if (N < 0) N = N + 0x100000000; /* 负数的补码: 其数字范围就是0到UINT_MAX(2^31-1), 即为16^8-1。 + 这里+ 0x100000000是为了将任意一个负数转换到正数范围内(且不影响计算结果), 理论上±2^32均可, 但我们后面的迭代需要是正数, 于是选择+0x100000000。 */ + while (N > 0) + { + long lastDigit = N % 16; + N /= 16; + res = dict[lastDigit] + res; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int num = -1; + auto res = sol.toHex(num); + // 预期结果是 ffffffff + cout << res << endl; /* 用Dev C++运行正常 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode405-convert-a-number-to-hexadecimal_solution2.cpp b/cpp-leetcode/leetcode405-convert-a-number-to-hexadecimal_solution2.cpp new file mode 100644 index 00000000..d36009fe --- /dev/null +++ b/cpp-leetcode/leetcode405-convert-a-number-to-hexadecimal_solution2.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string toHex(int num) { + string res; + long N = num; + if (N == 0) return "0"; + string dict = "0123456789abcdef"; + if (N < 0) N = N + 0x100000000; + while (N > 0) + { + long lastDigit = N % 16; + N /= 16; + res = dict[lastDigit] + res; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int num = -1; + auto res = sol.toHex(num); + // 预期结果是 ffffffff + cout << res << endl; /* 用Dev C++运行正常 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode406-queue-reconstruction-by-height_sort1.cpp b/cpp-leetcode/leetcode406-queue-reconstruction-by-height_sort1.cpp new file mode 100644 index 00000000..b4352fcb --- /dev/null +++ b/cpp-leetcode/leetcode406-queue-reconstruction-by-height_sort1.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> reconstructQueue(vector>& people) { + auto cmp = [](const vector& p1, const vector& p2) + { + if (p1[0] != p2[0]) + return p1[0] > p2[0]; + return p1[1] < p2[1]; + }; + sort(people.begin(), people.end(), cmp); + vector> res; + res.push_back(people[0]); // 先将最高的且位置尽量靠前的加进去 + for (int i = 1; i < people.size(); i++) + { + int pos = people[i][1]; + res.insert(res.begin() + pos, people[i]); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> people = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}; + auto res = sol.reconstructQueue(people); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode406-queue-reconstruction-by-height_sort2.cpp b/cpp-leetcode/leetcode406-queue-reconstruction-by-height_sort2.cpp new file mode 100644 index 00000000..4cbfe7a8 --- /dev/null +++ b/cpp-leetcode/leetcode406-queue-reconstruction-by-height_sort2.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> reconstructQueue(vector>& people) { + auto cmp = [](const vector& p1, const vector& p2) + { + if (p1[0] != p2[0]) + return p1[0] > p2[0]; + return p1[1] < p2[1]; + }; + sort(people.begin(), people.end(), cmp); + vector> res; + for (int i = 0; i < people.size(); i++) + { + if (res.empty()) + { + res.push_back(people[i]); + continue; + } + int pos = people[i][1]; + res.insert(res.begin() + pos, people[i]); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> people = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}; + auto res = sol.reconstructQueue(people); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode407-trapping-rain-water-ii_bfs1.cpp b/cpp-leetcode/leetcode407-trapping-rain-water-ii_bfs1.cpp new file mode 100644 index 00000000..2d467955 --- /dev/null +++ b/cpp-leetcode/leetcode407-trapping-rain-water-ii_bfs1.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; + +struct Cell { + int h, x, y; + bool operator< (const Cell& t) const + { + return h > t.h; + } +}; +class Solution { +public: + int trapRainWater(vector>& H) { + if (H.empty() || H[0].empty()) + return 0; + int n = H.size(); // 行数 + int m = H[0].size(); // 列数 + priority_queue heap; + vector> vis(n, vector(m)); // 访问状态 + for (int i = 0; i < n; i++) // 预处理每一行的第1个和最后一个格子 + { + vis[i][0] = vis[i][m - 1] = true; + heap.push({H[i][0], i, 0}); + heap.push({H[i][m - 1], i, m - 1}); + } + for (int i = 1; i + 1 < m; i++) // 预处理每一列的第2个和倒数第2行的格子, 因为每一列的第1个和最后一个格子已经预处理过了 + { + vis[0][i] = vis[n-1][i] = true; + heap.push({H[0][i], 0, i}); + heap.push({H[n - 1][i], n - 1, i}); + } + int res = 0; + while (!heap.empty()) + { + auto top = heap.top(); + heap.pop(); + + res += top.h - H[top.x][top.y]; /* top.h - H[top.x][top.y]: 每一个格子能帮助接到的水量, ≥ 0 */ + int dx[4] = {0, 1, 0, -1}; + int dy[4] = {1, 0, -1, 0}; + for (int i = 0; i < 4; i++) + { + int newX = top.x + dx[i]; + int newY = top.y + dy[i]; + + if (newX >= 0 && newX < n && newY >= 0 && newY < m && !vis[newX][newY]) /* 没出界, 且没被访问过 */ + { + heap.push({max(H[newX][newY], top.h), newX, newY}); + vis[newX][newY] = true; + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> nums = {{1, 4, 3, 1, 3, 2}, {3, 2, 1, 3, 2, 4}, {2, 3, 3, 2, 3, 1}}; + auto res = sol.trapRainWater(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode407-trapping-rain-water-ii_bfs2.cpp b/cpp-leetcode/leetcode407-trapping-rain-water-ii_bfs2.cpp new file mode 100644 index 00000000..c757d551 --- /dev/null +++ b/cpp-leetcode/leetcode407-trapping-rain-water-ii_bfs2.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int trapRainWater(vector>& H) { + priority_queue, vector>, greater<>> q; /* 小顶堆q, 堆中存储 pair of {h, n*x + y} */ + int rows = H.size(), cols = H[0].size(); + vector> visited(rows, vector(cols, false)); + int minimum = INT_MAX; + for (int i = 0; i < rows; i++) + { + for (int j = 0; j < cols; j++) + { + if (!(i==0 || i==rows-1 || j==0 || j==cols-1)) continue; + q.push({H[i][j], i * cols + j}); + visited[i][j] = true; + minimum = min(minimum, H[i][j]); + } + } + int dx[4] = {0, 1, 0, -1}; + int dy[4] = {1, 0, -1, 0}; + int res = 0; + while (!q.empty()) + { + pair val = q.top(); + q.pop(); + int height = val.first; + int x = val.second / cols; + int y = val.second % cols; + minimum = max(minimum, height); + for (int i = 0; i < 4; i++) + { + int nx = x + dx[i]; + int ny = y + dy[i]; + if (nx >= rows || nx < 0 || ny < 0 || ny >= cols || visited[nx][ny]) continue; + visited[nx][ny] = true; + if (H[nx][ny] < minimum) + res += minimum - H[nx][ny]; + q.push({H[nx][ny], nx * cols + ny}); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> nums = {{1, 4, 3, 1, 3, 2}, {3, 2, 1, 3, 2, 4}, {2, 3, 3, 2, 3, 1}}; + auto res = sol.trapRainWater(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode41-first-missing-positive_hashmap.cpp b/cpp-leetcode/leetcode41-first-missing-positive_hashmap.cpp new file mode 100644 index 00000000..dbf527d9 --- /dev/null +++ b/cpp-leetcode/leetcode41-first-missing-positive_hashmap.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int firstMissingPositive(vector &nums) { + unordered_map dict; + long max = 0; // max: 最长连续区间的结束位置的值 + for (int k = 0; k < nums.size(); k++) + { + if (nums[k] > 0) + dict[nums[k]] = 1; /* 题意: 找没有出现的最小的正整数, 于是0和负数不用考虑 */ + if (nums[k] > max) + max = nums[k]; + } + long res = max + 1; + for (long k = 1; k <= max; k++) + { + if (dict.count(k) == 0) + { + res = k; + break; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {3,4,-1,1}; + int res = sol.firstMissingPositive(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode41-first-missing-positive_index_sort.cpp b/cpp-leetcode/leetcode41-first-missing-positive_index_sort.cpp new file mode 100644 index 00000000..c17b93d3 --- /dev/null +++ b/cpp-leetcode/leetcode41-first-missing-positive_index_sort.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +/* index sort 解法 - wisdompeak */ +class Solution { +public: + int firstMissingPositive(vector& nums) + { + nums.insert(nums.begin(), 0); /* 由于数组下标从0开始, 这里在最前方插入1个0, 就可以应用刚才的算法思想了 */ + int len = nums.size(); + + for (int i = 0; i < len; i++) + { + while (nums[i] != i && nums[i] >= 0 && nums[i] < len && (nums[i] != nums[nums[i]])) + { + swap(nums[i], nums[nums[i]]); // 保证不出现数组越界 nums[i] >= 0 && nums[i] nums = {3,4,-1,1}; + int res = sol.firstMissingPositive(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode412-fizz-buzz_direct.cpp b/cpp-leetcode/leetcode412-fizz-buzz_direct.cpp new file mode 100644 index 00000000..cf2bbbed --- /dev/null +++ b/cpp-leetcode/leetcode412-fizz-buzz_direct.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector fizzBuzz(int n) { + vector res; + for (int i = 1; i <= n; i++) + { + if ((i % 3 == 0) && (i % 5 == 0)) res.push_back("FizzBuzz"); + else if (i % 3 == 0) res.push_back("Fizz"); + else if (i % 5 == 0) res.push_back("Buzz"); + else res.push_back(to_string(i)); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 15; + auto res = sol.fizzBuzz(n); + for (auto &str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode413-arithmetic-slices_dp.cpp b/cpp-leetcode/leetcode413-arithmetic-slices_dp.cpp new file mode 100644 index 00000000..ecfa488f --- /dev/null +++ b/cpp-leetcode/leetcode413-arithmetic-slices_dp.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int totalCount = 0; + int len = nums.size(); + vector dp(len, 0); // dp[i]表示长度为i的等差子数组的个数 + for (int i=2; i nums = { 1, 1, 2, 3, 4, 5 }; + auto res = sol.numberOfArithmeticSlices(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode413-arithmetic-slices_find_law.cpp b/cpp-leetcode/leetcode413-arithmetic-slices_find_law.cpp new file mode 100644 index 00000000..2e545fe0 --- /dev/null +++ b/cpp-leetcode/leetcode413-arithmetic-slices_find_law.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int totalCount = 0; + int len = nums.size(); + vector dp(len, 0); // dp[i]表示长度为i的等差子数组的个数 + for (int i = 2; i < len; i++) + { + if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) + dp[i] = dp[i - 1] + 1; /* 这里的dp[i-1]表示在末尾直接插入1个满足等差性质的数(这样算的数量和前一项相等), 而1表示生成一个新的数组, 相当于前面生成的数组窗口整体后移1位 */ + totalCount += dp[i]; + } + + return totalCount; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1, 1, 2, 3, 4, 5 }; + auto res = sol.numberOfArithmeticSlices(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode414-third-maximum-number_set.cpp b/cpp-leetcode/leetcode414-third-maximum-number_set.cpp new file mode 100644 index 00000000..15a9deed --- /dev/null +++ b/cpp-leetcode/leetcode414-third-maximum-number_set.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int thirdMax(vector& nums) { + set st(nums.begin(), nums.end()); + if (st.size() < 3) + { + auto it = st.end(); + it--; + return *it; + } + auto it = st.begin(); + advance(it, st.size() - 3); + return *it; + } +}; + +// Test +int main() +{ + Solution sol; + vector arr = {3, 2, 4, 10}; + auto res = sol.thirdMax(arr); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode414-third-maximum-number_sort_and_two_pointers.cpp b/cpp-leetcode/leetcode414-third-maximum-number_sort_and_two_pointers.cpp new file mode 100644 index 00000000..43971203 --- /dev/null +++ b/cpp-leetcode/leetcode414-third-maximum-number_sort_and_two_pointers.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int thirdMax(vector& nums) { + sort(nums.begin(), nums.end()); + int p = 0; // 用指针p 指向发现的新值的index + for(int i = 0; i < nums.size(); i++) + { + if (nums[p] != nums[i]) + { + p++; + nums[p] = nums[i]; + } + } + int len = p + 1; // 现在不含重复的数的子区间为 [0, p] + if (p + 1 < 3) return nums[p]; + return nums[p - 2]; + } +}; + +// Test +int main() +{ + Solution sol; + vector arr = {3, 2, 4, 10}; + auto res = sol.thirdMax(arr); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode415-add-strings_two_pointers.cpp b/cpp-leetcode/leetcode415-add-strings_two_pointers.cpp new file mode 100644 index 00000000..e6c6e395 --- /dev/null +++ b/cpp-leetcode/leetcode415-add-strings_two_pointers.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string addStrings(string num1, string num2) { + string result; + + int carry = 0; + int i = num1.length() - 1; + int j = num2.length() - 1; + // 双指针: 两字符串尾部对齐, 从低位向高位扫描, "越界"就置为0, 使其不影响计算 + while (i >= 0 || j >= 0 || carry > 0) { + int v1 = i >= 0 ? num1[i] - '0' : 0; + int v2 = j >= 0 ? num2[j] - '0' : 0; + int sum = v1 + v2 + carry; + result.push_back(sum % 10 + '0'); /* 把当前位加到结果数组中, 并更新进位值为下一轮循环做准备 */ + carry = sum / 10; + + i--; + j--; + } + + reverse(result.begin(), result.end()); /* 由于一开始低位放在数组的前面, 所以需要反转1次 */ + return result; + } +}; + +// Test +int main() +{ + Solution sol; + string num1 = "4591"; + string num2 = "123"; + auto res = sol.addStrings(num1, num2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp3.cpp b/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp3.cpp new file mode 100644 index 00000000..43ed2924 --- /dev/null +++ b/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp3.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canPartition(vector& nums) { + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % 2 != 0) return false; + vector dp(sum + 1, 0); // dp[i]: 类似于0-1背包问题, 存0或1, 子序列的和能达到i就记作1, 否则记为0 + dp[0] = 1; + for (const int& num : nums) + { + for (int i = sum; i >= 0; i--) + if (dp[i] == 1) dp[i + num] = 1; + if (dp[sum/2] == 1) return true; // 如果其中一组的和为 sum/2, 那么就返回true + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 5, 11, 5}; + auto res = sol.canPartition(nums); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp_using_array.cpp b/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp_using_array.cpp new file mode 100644 index 00000000..81711f6c --- /dev/null +++ b/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp_using_array.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canPartition(vector& nums) { + int sum0 = accumulate(nums.begin(), nums.end(), 0); + if (sum0 % 2 != 0) return false; + int sum = sum0/2; + bool dp[sum + 1]; // 原数组nums中的元素是否能凑出和为i, 如果能就将dp值更新为1。每来一个数nums[i], 都有选或不选两种状态 + fill(dp, dp + sum + 1, false); + dp[0] = true; + for (int& num : nums) + { + for (int j = sum; j >= 0; j--) + { + if (j >= num) /* 此处必须带上= */ + dp[j] = dp[j] || dp[j - num]; + } + } + return dp[sum]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 5, 11, 5}; + auto res = sol.canPartition(nums); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp_using_vector.cpp b/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp_using_vector.cpp new file mode 100644 index 00000000..abe93cde --- /dev/null +++ b/cpp-leetcode/leetcode416-partition-equal-subset-sum_dp_using_vector.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canPartition(vector& nums) { + int sum0 = accumulate(nums.begin(), nums.end(), 0); + if (sum0 % 2 != 0) return false; + int sum = sum0/2; + vector dp(sum + 1); // dp[i]: 原数组nums中的元素是否能凑出和为i, 如果能就将dp值更新为1。每来一个数nums[i], 都有选或不选两种状态 + dp[0] = true; + for (int& num : nums) + { + for (int j = sum; j >= 0; j--) + { + if (j >= num) /* 此处必须带上= */ + dp[j] = dp[j] || dp[j - num]; + } + } + return dp[sum]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 5, 11, 5}; + auto res = sol.canPartition(nums); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode42-trapping-rain-water_monotonic_stack_using_deque.cpp b/cpp-leetcode/leetcode42-trapping-rain-water_monotonic_stack_using_deque.cpp new file mode 100644 index 00000000..b43f0916 --- /dev/null +++ b/cpp-leetcode/leetcode42-trapping-rain-water_monotonic_stack_using_deque.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int trap(vector& height) { + if (height.empty()) return 0; + int maxArea = 0; + deque st; + + for (int i = 0; i < height.size(); i++) + { + while (!st.empty() && height[st.front()] < height[i]) + { + int base = height[st.front()]; + st.pop_front(); + if (st.empty()) continue; + int h = min(height[st.front()], height[i]) - base; + int width = i - st.front() - 1; + maxArea += h * width; + } + st.push_front(i); + } + return maxArea; + } +}; + +// Test +int main() +{ + Solution sol; + vector heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + auto res = sol.trap(heights); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode42-trapping-rain-water_observing_max_min.cpp b/cpp-leetcode/leetcode42-trapping-rain-water_observing_max_min.cpp new file mode 100644 index 00000000..7e2ffadf --- /dev/null +++ b/cpp-leetcode/leetcode42-trapping-rain-water_observing_max_min.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int trap(vector& height) { + if (height.empty()) return 0; + /* leftHeighest[i] (leftMaxH[i]): i左侧最高的bar; rightMaxH[i]: i右侧最高的bar */ + int N = height.size(); + vector leftMaxH(N, 0); + vector rightMaxH(N, 0); + + for (int i = 1; i < N; i++) + leftMaxH[i] = max(leftMaxH[i-1], height[i-1]); + for (int i = N-2; i >= 0; i--) + rightMaxH[i] = max(rightMaxH[i+1], height[i+1]); /* rightMaxH[i]: i右侧(后面)最高的bar */ + int maxArea = 0; + for (int i = 0; i < N; i++) + { + int h = min(leftMaxH[i], rightMaxH[i]) - height[i]; + h = (h >= 0 ? h : 0); + maxArea += h * 1; + } + + return maxArea; + } +}; + +// Test +int main() +{ + Solution sol; + vector heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + auto res = sol.trap(heights); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode429-n-ary-tree-level-order-traversal_level_order_deque.cpp b/cpp-leetcode/leetcode429-n-ary-tree-level-order-traversal_level_order_deque.cpp new file mode 100644 index 00000000..a9de36be --- /dev/null +++ b/cpp-leetcode/leetcode429-n-ary-tree-level-order-traversal_level_order_deque.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + vector> levelOrder(Node* root) { + if (root == nullptr) return {}; + vector> res; + deque q {root}; + + while (!q.empty()) + { + vector curLevel; + int curSize = q.size(); + for (int i = curSize; i > 0; i--) + { + Node* p = q.front(); + q.pop_front(); + curLevel.push_back(p->val); + // loop to handle children + for (auto child : p->children) + if (child) q.push_back(child); /* 判断/不判断空看起来没影响 */ + } + res.push_back(curLevel); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + auto res = sol.levelOrder(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode429-n-ary-tree-level-order-traversal_level_order_queue.cpp b/cpp-leetcode/leetcode429-n-ary-tree-level-order-traversal_level_order_queue.cpp new file mode 100644 index 00000000..096c1ba2 --- /dev/null +++ b/cpp-leetcode/leetcode429-n-ary-tree-level-order-traversal_level_order_queue.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + vector> levelOrder(Node* root) { + if (root == nullptr) return {}; + vector> res; + queue q; + q.push(root); + + while (!q.empty()) + { + vector curLevel; + int curSize = q.size(); + for (int i = curSize; i > 0; i--) + { + Node* p = q.front(); + q.pop(); + curLevel.push_back(p->val); + // loop to handle children + for (auto child : p->children) + if (child) q.push(child); /* 判断/不判断空看起来没影响 */ + } + res.push_back(curLevel); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + auto res = sol.levelOrder(root); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode43-multiply-strings_solution1.cpp b/cpp-leetcode/leetcode43-multiply-strings_solution1.cpp new file mode 100644 index 00000000..871d6d43 --- /dev/null +++ b/cpp-leetcode/leetcode43-multiply-strings_solution1.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string multiply(string num1, string num2) + { + if (num1 == "0" || num2 == "0") + return "0"; + + int n1 = num1.size(); + int n2 = num2.size(); + string res(n1 + n2, '0'); + + for (int i = n2 - 1; i >= 0; i--) + { + for (int j = n1 - 1; j >= 0; j--) + { + int temp = (res[i + j + 1] - '0') + (num1[j] - '0') * (num2[i] - '0'); + res[i + j + 1] = temp % 10 + '0'; // 当前位 + res[i + j] = res[i + j] + temp / 10; /*前一位加上进位,res[i+j]已经初始化为'0',加上int类型自动转化为char,所以此处不加'0' */ + } + } + + for (int i = 0; i < n1 + n2; i++) + if (res[i] != '0') + return res.substr(i); // trim掉结果数组中一开始连续的0 + + return res; + } +}; + +/* + 末位对齐 + 1 2 3 n1 i = 2 + x 4 5 6 n2 j = 2 + 7 3 8 + 6 1 5 + 4 9 2 + 结果中最低位index: 5 + 与之对应的高位(carry位)的index: 4 (i+j) + 分析知product长度: ≤ n1 + n2, 于是结果最末尾元素的index是i+j+1 +*/ + +// Test +int main() +{ + Solution sol; + string num1 = "123", num2 = "456"; + string res = sol.multiply(num1, num2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode43-multiply-strings_solution2.cpp b/cpp-leetcode/leetcode43-multiply-strings_solution2.cpp new file mode 100644 index 00000000..8fb9bd65 --- /dev/null +++ b/cpp-leetcode/leetcode43-multiply-strings_solution2.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string multiply(string num1, string num2) { + if(num1 == "0" || num2 == "0") + return "0"; + + int n1 = num1.size(); + int n2 = num2.size(); + string res(n1+n2, '0'); + + for(int i = n1 - 1; i>=0; i--) + { + for(int j = n2 - 1; j>=0; j--) + { + int x = num1[i] - '0'; + int y = num2[j] - '0'; + int curSum = x*y + (res[i+j+1] - '0') + (res[i+j] - '0')*10; + + res[i+j+1] = curSum % 10 + '0'; + res[i+j] = (curSum / 10) + '0'; + } + } + + for(int i = 0; i < n1 + n2; i++) + if(res[i] != '0') return res.substr(i); // trim掉结果数组中一开始连续的0 + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string num1 = "123", num2 = "456"; + string res = sol.multiply(num1, num2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode430-flatten-a-multilevel-doubly-linked-list_dfs1.cpp b/cpp-leetcode/leetcode430-flatten-a-multilevel-doubly-linked-list_dfs1.cpp new file mode 100644 index 00000000..e4a65270 --- /dev/null +++ b/cpp-leetcode/leetcode430-flatten-a-multilevel-doubly-linked-list_dfs1.cpp @@ -0,0 +1,135 @@ +#include +#include +#include +#include +using namespace std; +/* +// Definition for a Node. +*/ +class Node { +public: + int val; + Node* prev; + Node* next; + Node* child; + + Node(int val) : val(val), next(nullptr), prev(nullptr), child(nullptr) {} + Node(int val, Node* next, Node* prev) : val(val), next(next), prev(prev), child(nullptr) { + if (prev) prev->next = this; + if (next) next->prev = this; + } + Node(int val, Node* next, Node* prev, Node* child) : val(val), next(next), prev(prev), child(child) { + if (prev) prev->next = this; + if (next) next->prev = this; + } +}; +Node* gengerateNodes(vector nodes) { + Node* vHead = new Node(0); + Node* node = vHead; + + for (int val : nodes) { + node = new Node(val, nullptr, node); + } + vHead->next->prev = nullptr; + return vHead->next; +} +vector getNodeVals(Node* node) +{ + if (!node) return {}; + vector res; + Node* prev = nullptr; + while (node) + { + if (node->prev != prev) + assert(false); // 生成的链表有问题 + assert(node->child == nullptr); + res.push_back(node->val); + prev = node; + node = node->next; + } + return res; +} + +class Solution { +public: + Node* flatten(Node* head) { + dfs(head); + return head; + } + // 由题意: 需要将h结点往后走的最后一个child指针(下方代码中的childEnd)指向撸直前的next指针指向的结点 + Node* dfs(Node* h) + { + if (h == nullptr) return nullptr; + Node* child = h->child; + Node* nextP = h->next; + h->child = nullptr; + if (child && nextP) + { + Node* childEnd = dfs(child); + Node* nextEnd = dfs(nextP); + h->next = child; + child->prev = h; + childEnd->next = nextP; /* 核心语句 */ + nextP->prev = childEnd; // 配套语句 + return nextEnd; + } + else if (!child && nextP) /* 特殊情况1: h的child指针为空, 只需dfs处理nextP, 没有child意味着不需要做最后一个child指针与nextP的挂接 */ + { + Node* nextEnd = dfs(nextP); + return nextEnd; + } + else if (child && !nextP) /* 特殊情况2: h的next指针为空, 只需dfs处理child */ + { + Node* childEnd = dfs(child); + h->next = child; + child->prev = h; + return childEnd; + } + return h; + } +}; + +// Test +int main() +{ + Solution sol; + Node* node; + Node* resNode; + vector res; + + /** + 输入:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] + 输出:[1,2,3,7,8,11,12,9,10,4,5,6] + */ + Node* node1 = gengerateNodes({1, 2, 3, 4, 5, 6}); + Node* node7 = gengerateNodes({7, 8, 9, 10}); + Node* node11 = gengerateNodes({11, 12}); + node1->next->next->child = node7; + node7->next->child = node11; + + node = node1; + res = {1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6}; + resNode = sol.flatten(node); + assert(res == getNodeVals(resNode)); + + /** + 输入:head = [1,2,null,3] + 输出:[1,3,2] + */ + node = new Node(1, new Node(2), nullptr, new Node(3)); + res = {1, 3, 2}; + resNode = sol.flatten(node); + assert(res == getNodeVals(resNode)); + + /** + 输入:head = [] + 输出:[] + */ + node = nullptr; + res = {}; + resNode = sol.flatten(node); + assert(res == getNodeVals(resNode)); + + cout << "Works as expected." << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode430-flatten-a-multilevel-doubly-linked-list_dfs2.cpp b/cpp-leetcode/leetcode430-flatten-a-multilevel-doubly-linked-list_dfs2.cpp new file mode 100644 index 00000000..5f7f528b --- /dev/null +++ b/cpp-leetcode/leetcode430-flatten-a-multilevel-doubly-linked-list_dfs2.cpp @@ -0,0 +1,137 @@ +#include +#include +#include +#include +using namespace std; +/* +// Definition for a Node. +*/ +class Node { +public: + int val; + Node* prev; + Node* next; + Node* child; + + Node(int val) : val(val), next(nullptr), prev(nullptr), child(nullptr) {} + Node(int val, Node* next, Node* prev) : val(val), next(next), prev(prev), child(nullptr) { + if (prev) prev->next = this; + if (next) next->prev = this; + } + Node(int val, Node* next, Node* prev, Node* child) : val(val), next(next), prev(prev), child(child) { + if (prev) prev->next = this; + if (next) next->prev = this; + } +}; +Node* gengerateNodes(vector nodes) { + Node* vHead = new Node(0); + Node* node = vHead; + + for (int val : nodes) { + node = new Node(val, nullptr, node); + } + vHead->next->prev = nullptr; + return vHead->next; +} +vector getNodeVals(Node* node) +{ + if (!node) return {}; + vector res; + Node* prev = nullptr; + while (node) + { + if (node->prev != prev) + assert(false); // 生成的链表有问题 + assert(node->child == nullptr); + res.push_back(node->val); + prev = node; + node = node->next; + } + return res; +} + +class Solution { +public: + Node* flatten(Node* head) { + dfs(head); + return head; + } + + Node* dfs(Node* h) + { + if (h == nullptr) return nullptr; + + Node* next = h->next; + Node* child = h->child; + h->child = nullptr; + + if (child == nullptr && next == nullptr) + return h; + else if (child != nullptr && next == nullptr) + { + h->next = child; + child->prev = h; + Node* childEnd = dfs(child); + return childEnd; + } + else if (child == nullptr && next != nullptr) + { + Node* nextEnd = dfs(next); + return nextEnd; + } + else + { + h->next = child; + child->prev = h; + Node* childEnd = dfs(child); + childEnd->next = next; + next->prev = childEnd; + return dfs(next); + } + } +}; + +// Test +int main() +{ + Solution sol; + Node* node; + Node* resNode; + vector res; + + /** + 输入:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] + 输出:[1,2,3,7,8,11,12,9,10,4,5,6] + */ + Node* node1 = gengerateNodes({1, 2, 3, 4, 5, 6}); + Node* node7 = gengerateNodes({7, 8, 9, 10}); + Node* node11 = gengerateNodes({11, 12}); + node1->next->next->child = node7; + node7->next->child = node11; + + node = node1; + res = {1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6}; + resNode = sol.flatten(node); + assert(res == getNodeVals(resNode)); + + /** + 输入:head = [1,2,null,3] + 输出:[1,3,2] + */ + node = new Node(1, new Node(2), nullptr, new Node(3)); + res = {1, 3, 2}; + resNode = sol.flatten(node); + assert(res == getNodeVals(resNode)); + + /** + 输入:head = [] + 输出:[] + */ + node = nullptr; + res = {}; + resNode = sol.flatten(node); + assert(res == getNodeVals(resNode)); + + cout << "Works as expected." << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode435-non-overlapping-intervals_greedy.cpp b/cpp-leetcode/leetcode435-non-overlapping-intervals_greedy.cpp new file mode 100644 index 00000000..f64b189c --- /dev/null +++ b/cpp-leetcode/leetcode435-non-overlapping-intervals_greedy.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int eraseOverlapIntervals(vector>& R) { /* R: 代表ranges */ + auto cmp = [](const vector& p1, const vector& p2) + { + return p1[1] < p2[1]; + }; + sort(R.begin(), R.end(), cmp); + const int len = R.size(); + if (R.empty()) return 0; + int maxRemain = 1; // maxRemain: 最多保留下来多少个区间 + int curRight = R[0][1]; + for (int i = 1; i < len; i++) + { + if (R[i][0] >= curRight) /* 新来的区间的左边界R[i][0] 与当前区间的右边界比较, 如果≥成立说明可以再留下1个新的区间 */ + { + maxRemain++; + curRight = R[i][1]; + } + } + return len - maxRemain; + } +}; + +// Test +int main() +{ + Solution sol; + vector> ranges = {{1, 2}, {2, 3}, {3, 4}, {1, 3}}; + auto res = sol.eraseOverlapIntervals(ranges); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode438-find-all-anagrams-in-a-string_sliding_window_with_hash.cpp b/cpp-leetcode/leetcode438-find-all-anagrams-in-a-string_sliding_window_with_hash.cpp new file mode 100644 index 00000000..716d1117 --- /dev/null +++ b/cpp-leetcode/leetcode438-find-all-anagrams-in-a-string_sliding_window_with_hash.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findAnagrams(string s, string p) { + vector res; /* 存放这些子串的起始索引startPos */ + int restCount = p.size(); /* 维护一个固定长度的窗口, 窗口长度 = len(p), restCount: 剩下的待匹配字符的数量 */ + vector pFreq(26); /* 模拟一个计数哈希表 */ + for (int i = 0; i < p.size(); i++) + pFreq[p[i] - 'a']++; + vector sFreq(26); /* 模拟一个计数哈希表, sFreq: 字符串s中处于滑动窗口内的字符的频次 */ + for (int i = 0; i < s.size(); i++) + { + char c = s[i]; + sFreq[c - 'a']++; /* 向窗口末尾加入1个新字符 */ + if (sFreq[c - 'a'] <= pFreq[c - 'a']) /* 当前窗口中这个字符的数量还没到上限, 可以成功加入 */ + restCount--; + if (i >= p.size()) /* 删除原窗口最前面的那1个字符, 最新的startPos = i - len(p) + 1, 那么上一次的startPos = i - p.size() */ + { + char h = s[i - p.size()]; /* h: 上一轮中窗口中最前面的字符 */ + sFreq[h - 'a']--; + if (sFreq[h - 'a'] < pFreq[h - 'a']) + restCount++; + } + // 字符都匹配完成, 表示是一个有效的字母异位词(anagram) + if (restCount == 0) /* i - startPos + 1 = len(p) => startPos = i - len(p) + 1 */ + res.push_back(i - p.size() + 1); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string p = "ab"; + string s = "eidbaooo"; + + auto res = sol.findAnagrams(s, p); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode441-arranging-coins_binary_search.cpp b/cpp-leetcode/leetcode441-arranging-coins_binary_search.cpp new file mode 100644 index 00000000..ebbf9d1a --- /dev/null +++ b/cpp-leetcode/leetcode441-arranging-coins_binary_search.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +using namespace std; + +using LL = long long; +class Solution { +public: + int arrangeCoins(int n) { + LL left = 0, right = (LL)n + 1; + while (left < right) + { + LL mid = left + (right - left) / 2; // 防止整型溢出 + LL target = (mid + 1) * mid / 2; + if (target <= n) + left = mid + 1; + else right = mid; + } + return left - 1; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 10; + auto res = sol.arrangeCoins(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode441-arranging-coins_math1.cpp b/cpp-leetcode/leetcode441-arranging-coins_math1.cpp new file mode 100644 index 00000000..1113e4e8 --- /dev/null +++ b/cpp-leetcode/leetcode441-arranging-coins_math1.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +using namespace std; + +typedef long long LL; +class Solution { +public: + int arrangeCoins(int n) { + LL i = 0; + while ((LL)(i*(i+1)) < (LL)2*n) + i++; + if ((LL)(i*(i+1)) == (LL)2*n) return i; + return i - 1; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 10; + auto res = sol.arrangeCoins(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode441-arranging-coins_math2.cpp b/cpp-leetcode/leetcode441-arranging-coins_math2.cpp new file mode 100644 index 00000000..3e24fbf4 --- /dev/null +++ b/cpp-leetcode/leetcode441-arranging-coins_math2.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +using namespace std; + +typedef long long LL; +class Solution { +public: + int arrangeCoins(int n) { + return (sqrt((LL)8*n + 1) - 1) / 2; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 10; + auto res = sol.arrangeCoins(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode443-string-compression_two_pointers.cpp b/cpp-leetcode/leetcode443-string-compression_two_pointers.cpp new file mode 100644 index 00000000..cece26a6 --- /dev/null +++ b/cpp-leetcode/leetcode443-string-compression_two_pointers.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int compress(vector& chars) { + // 题意: 将原字符数组写成(letter+count)形式, 如果count是1不用写, 形式: lc, count的位数可能是1,2... */ + int left = 0, right = 0; /* 指针right: 0 -> len - 1, 指针left: 指向需要更新字符值位置的index */ + int len = chars.size(); + while (right < len) + { + int preRight = right; // preRight是连续重复字符区域的第1个字符的index + while (right < len && chars[right] == chars[preRight]) /* 只要right扫描到的值还是和之前的一样, 就继续前移 */ + right++; + + int repeatCount = right - preRight; + chars[left] = chars[preRight]; /* left处的字符需要更新为right遍历过的字符, 也能写出chars[left] = chars[right - 1]; */ + if (repeatCount == 1) /* count为1时, 无需操作原数组 */ + left++; + else if (repeatCount <= 9) + { + chars[left + 1] = repeatCount + '0'; + left += 2; /* 假如没新发现一个count>1的字符, 则left += 1, 如果发现一个1位的, 那么移动2位... */ + } + else + { + string countStr = to_string(repeatCount); + for (int i = 0; i < countStr.size(); i++) + chars[left + 1 + i] = countStr[i]; + left += countStr.size() + 1; /* 若没新发现一个count>1的字符, 则left += 1, 如果发现一个k位的, 那么移动k+1位... */ + } + } + return left; + } +}; + +// Test +int +main() +{ + Solution sol; + vector chars = {'a', 'a', 'b', 'b', 'c', 'c', 'c'}; + auto res = sol.compress(chars); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode445-add-two-numbers-ii_solution1.cpp b/cpp-leetcode/leetcode445-add-two-numbers-ii_solution1.cpp new file mode 100644 index 00000000..57653333 --- /dev/null +++ b/cpp-leetcode/leetcode445-add-two-numbers-ii_solution1.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* addTwoNumbers(ListNode* h1, ListNode* h2) { + // 题意: 两个非空链表, 故不需要判断NULL。且链表不能reverse + string numStr1 = "", numStr2 = ""; + vector resVals; + int len1 = getLen(h1, numStr1); + int len2 = getLen(h2, numStr2); + // 更新resVals + auto sumStr = addStrings(numStr1, numStr2); + for (auto &ch : sumStr) + resVals.push_back(ch - '0'); + + ListNode* fakeHead = new ListNode(-1); + ListNode* p = fakeHead; + fakeHead->next = new ListNode(resVals.front()); + for (int i = 0; i < resVals.size(); i++) + { + p->next = new ListNode(resVals[i]); + p = p->next; + } + p->next = nullptr; + + return fakeHead->next; + } + int getLen(ListNode* head, string& numStr) + { + int count = 0; + ListNode* p = head; + while (p != nullptr) + { + count++; + numStr.push_back(p->val + '0'); + p = p->next; + } + return count; + } + string addStrings(string num1, string num2) + { + string result; + + int carry = 0; + int i = num1.size() - 1; + int j = num2.size() - 1; + // 双指针: 两字符串尾部对齐, 从低位向高位扫描, "越界"就置为0, 使其不影响计算 + while (i >= 0 || j >= 0 || carry > 0) { + int v1 = i >= 0 ? num1[i] - '0' : 0; + int v2 = j >= 0 ? num2[j] - '0' : 0; + int sum = v1 + v2 + carry; + result.push_back(sum % 10 + '0'); /* 把当前位加到结果数组中, 并更新进位值为下一轮循环做准备 */ + carry = sum >= 10 ? 1 : 0; // 或写成 sum / 10 + + i--; + j--; + } + reverse(result.begin(), result.end()); /* 由于一开始低位放在数组的前面, 所以需要反转1次 */ + return result; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *l1; + ListNode *l2; + + l1 = new ListNode(7); + l1->next = new ListNode(2); + l1->next->next = new ListNode(4); + l1->next->next->next = new ListNode(3); + l1->next->next->next->next = NULL; + + l2 = new ListNode(5); + l2->next = new ListNode(6); + l2->next->next = new ListNode(4); + l2->next->next->next = NULL; + ListNode *res = sol.addTwoNumbers(l1, l2); + + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode446-arithmetic-slices-ii-subsequence_dfs.cpp b/cpp-leetcode/leetcode446-arithmetic-slices-ii-subsequence_dfs.cpp new file mode 100644 index 00000000..1e3fa659 --- /dev/null +++ b/cpp-leetcode/leetcode446-arithmetic-slices-ii-subsequence_dfs.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + using ll = long long; + int numberOfArithmeticSlices(vector &A) { + if (A.size() < 3) + return 0; + int res = 0, n = A.size(); + unordered_map> hashmap; + unordered_set uniqueNums; + for (int i = 0; i < n; i++) + hashmap[A[i]].insert(i); + for (int i = 0; i < n - 2; i++) + { + for (int j = i + 1; j < n - 1; j++) + { + ll d = (ll)A[j] - A[i]; + if (d == 0 && uniqueNums.count(A[i]) > 0) + continue; + if (d == 0) + { + uniqueNums.insert(A[i]); + calc(hashmap[A[i]].size(), 0, res); + continue; + } + dfs(hashmap, j, A[j], d, 2, res); + } + } + return res; + } + + void dfs(unordered_map> &hashmap, int idx, int prev, ll d, int n, int &res) + { + ll next = prev + d; + auto it = hashmap.find(next); + if (it == hashmap.end()) + { + calc(n, d, res); + return; + } + auto iter = it->second.upper_bound(idx); + if (iter == it->second.end()) + { + calc(n, d, res); + return; + } + for (int i = 0; iter != it->second.end(); i++, iter++) + dfs(hashmap, *iter, next, d, i == 0 ? n + 1 : 3, res); + } + + void calc(int n, ll d, int &res) // Compute combination C(n, d) + { + if (n < 3) + return; + if (d != 0) + res += n - 2; + else + res += pow(2, n) - 1 - n - n * (n - 1) / 2; // C(n,0)+C(n,1)+...C(n,n) = 2^n + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1, 1, 2, 3, 4, 5 }; + auto res = sol.numberOfArithmeticSlices(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode447-number-of-boomerangs_hashmap.cpp b/cpp-leetcode/leetcode447-number-of-boomerangs_hashmap.cpp new file mode 100644 index 00000000..dabd5d6e --- /dev/null +++ b/cpp-leetcode/leetcode447-number-of-boomerangs_hashmap.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + // n = points.length, n: [1, 500] + const int n = points.size(); + int res = 0; + for (int i = 0; i < n; i++) + { + unordered_map dict; + for (int j = 0; j < n; j++) + { + const int dx = points[j][0] - points[i][0]; + const int dy = points[j][1] - points[i][1]; + long long d = dx*dx + dy*dy; + if (i != j) dict[d]++; + } + for (auto& [k, c] : dict) + res += c*(c-1); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> points = {{0, 0}, {1, 0}, {2, 0}}; + auto res = sol.numberOfBoomerangs(points); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode447-number-of-boomerangs_sort.cpp b/cpp-leetcode/leetcode447-number-of-boomerangs_sort.cpp new file mode 100644 index 00000000..7483b830 --- /dev/null +++ b/cpp-leetcode/leetcode447-number-of-boomerangs_sort.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + // n = points.length, n: [1, 500] + const int n = points.size(); + int res = 0; + for (int i = 0; i < n; i++) + { + vector dists(n); + for (int j = 0; j < n; j++) + { + const int dx = points[j][0] - points[i][0]; + const int dy = points[j][1] - points[i][1]; + dists[j] = dx * dx + dy * dy; + } + sort(dists.begin(), dists.end()); + for (int k = 1; k < n; k++) + { + int p = 1; + while (k < n && dists[k] == dists[k - 1]) + { + k++; + p++; + } + res += p * (p - 1); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> points = {{0, 0}, {1, 0}, {2, 0}}; + auto res = sol.numberOfBoomerangs(points); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode448-find-all-numbers-disappeared-in-an-array.cpp b/cpp-leetcode/leetcode448-find-all-numbers-disappeared-in-an-array.cpp new file mode 100644 index 00000000..6a92cd6f --- /dev/null +++ b/cpp-leetcode/leetcode448-find-all-numbers-disappeared-in-an-array.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + unordered_set se(nums.begin(), nums.end()); + int i = 0; + int n = nums.size(); // 原始的size + vectorres; + for(i = 1; i <= n; ++i){ + if(se.find(i) == se.end()) + res.push_back(i); + } + return res; + } +}; + +int main() +{ + Solution sol; + vector nums = { 4,3,2,7,8,2,3,1 }; + auto res = sol.findDisappearedNumbers(nums); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode45-jump-game-ii_solution1.cpp b/cpp-leetcode/leetcode45-jump-game-ii_solution1.cpp new file mode 100644 index 00000000..3a5ee74a --- /dev/null +++ b/cpp-leetcode/leetcode45-jump-game-ii_solution1.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int jump(vector& nums) { + int minSteps = 0; + int endPos = 0; // 刚开始, 区间为[0, 0] + + int maxPos = 0; + for (int i = 0; i < nums.size() - 1; i++) + { + maxPos = max(maxPos, nums[i] + i); /* 此时, 区间更新为 [i, maxPos] */ + if (i == endPos) + { + endPos = maxPos; + minSteps++; + } + } + + return minSteps; + } +}; + +// Test +int main() +{ + Solution sol; + vectornums = {2,3,0,1,4}; + auto res = sol.jump(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode451-sort-characters-by-frequency_hashmap_and_sort.cpp b/cpp-leetcode/leetcode451-sort-characters-by-frequency_hashmap_and_sort.cpp new file mode 100644 index 00000000..1a8e7eb2 --- /dev/null +++ b/cpp-leetcode/leetcode451-sort-characters-by-frequency_hashmap_and_sort.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string frequencySort(string s) { + unordered_map dict; + for (auto& ch : s) + { + if (dict.find(ch) == dict.end()) + dict[ch] = 1; + else dict[ch]++; + } + string res; + vector> kvVect; + for (auto kvp : dict) + kvVect.push_back(kvp); + auto cmp = [](const pair& p1, const pair& p2) + { + return p1.second > p2.second; + }; + sort(kvVect.begin(), kvVect.end(), cmp); + for (auto kvp : kvVect) + { + while (kvp.second--) + res.push_back(kvp.first); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "BabBbBbBbbABBABBbAabbbGGGGKKKggggg"; + + auto res = sol.frequencySort(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode453-minimum-moves-to-equal-array-elements_math.cpp b/cpp-leetcode/leetcode453-minimum-moves-to-equal-array-elements_math.cpp new file mode 100644 index 00000000..59bcf8b5 --- /dev/null +++ b/cpp-leetcode/leetcode453-minimum-moves-to-equal-array-elements_math.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int minMoves(vector& nums) { + int sum0 = accumulate(nums.begin(), nums.end(), 0); + int n = nums.size(); + auto it = max_element(nums.begin(), nums.end()); + long long maxNum = *it; + if (n * maxNum == sum0) /* 数组中最大数=数组平均数时不需要移动, 包含 n == 1 的case */ + return 0; + + auto it1 = min_element(nums.begin(), nums.end()); + long long minNum = *it1; + + return (sum0 - n * minNum); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 7, 5}; + auto res = sol.minMoves(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode455-assign-cookies_two_pointers.cpp b/cpp-leetcode/leetcode455-assign-cookies_two_pointers.cpp new file mode 100644 index 00000000..6c46ba5d --- /dev/null +++ b/cpp-leetcode/leetcode455-assign-cookies_two_pointers.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findContentChildren(vector& g, vector& s) { + sort(g.begin(), g.end()); + sort(s.begin(), s.end()); + // 双指针 + int j = 0; // 遇到满足条件的情形, j才移动一步(同时是一个计数器) + for (int i = 0; i < s.size() && j < g.size(); ++i) { + if (s[i] >= g[j]) j++; + } + return j; + } +}; + +// Test +int main() +{ + Solution sol; + vector s = {1,2,3}; // cookies we have + vector g = {3}; + + int res = sol.findContentChildren(g, s); + cout << res << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode459-repeated-substring-pattern.cpp b/cpp-leetcode/leetcode459-repeated-substring-pattern.cpp new file mode 100644 index 00000000..bc0a9cc3 --- /dev/null +++ b/cpp-leetcode/leetcode459-repeated-substring-pattern.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool repeatedSubstringPattern(string s) { + // 如果可由子串重复形成, 那子串的长度必然能整除原串长度, 根据对称性, 为了减少重复计算, 从字符串中间出发遍历即可 */ + int len = s.size(); + for (int i = len/2; i >= 1; i--) + { + if (len % i == 0) + { + int count = len / i; + string combineStr = ""; + string subStr = s.substr(0, i); + for (int k = 0; k < count; k++) + combineStr += subStr; + + if (combineStr == s) return true; + } + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "abcabcabcabc"; + auto res = sol.repeatedSubstringPattern(str); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode46-permutations_iterative_solution.cpp b/cpp-leetcode/leetcode46-permutations_iterative_solution.cpp new file mode 100644 index 00000000..2635e141 --- /dev/null +++ b/cpp-leetcode/leetcode46-permutations_iterative_solution.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +using namespace std; + +/* +插板法: +1 +⬇ + +1 2 => 312, 132, 123 +2 1 => 321, 231, 213 +*/ + +class Solution +{ +public: + vector> permute(vector &nums) + { + queue> q; + q.push({nums[0]}); + + for (int i = 1; i < nums.size(); i++) + { + int len = q.size(); + while (len--) + { + auto arr = q.front(); + q.pop(); + + int M = arr.size(); + for (int k = 0; k <= M; k++) + { + auto temp = arr; + temp.insert(temp.begin() + k, nums[i]); + q.push(temp); + } + } + } + + vector> results; + while (!q.empty()) + { + results.push_back(q.front()); + q.pop(); + } + return results; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 3}; + vector> res = sol.permute(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode46-permutations_using_library_functions.cpp b/cpp-leetcode/leetcode46-permutations_using_library_functions.cpp new file mode 100644 index 00000000..6acc5fe6 --- /dev/null +++ b/cpp-leetcode/leetcode46-permutations_using_library_functions.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> permute(vector& nums) { + sort(nums.begin(), nums.end()); /* 先排序,得到字典序最小的,以满足next_permutation容器的需要 */ + vector> res; + res.push_back(nums); + while(next_permutation(nums.begin(), nums.end())) + { + res.push_back(nums); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,2,3}; + vector> res = sol.permute(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode461-hamming-distance_compare_string_char_by_char1.cpp b/cpp-leetcode/leetcode461-hamming-distance_compare_string_char_by_char1.cpp new file mode 100644 index 00000000..c01eeebe --- /dev/null +++ b/cpp-leetcode/leetcode461-hamming-distance_compare_string_char_by_char1.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int hammingDistance(int x, int y) { + string s1 = toBinary(x); + string s2 = toBinary(y); + int n1 = s1.size(), n2 = s2.size(); + int maxLen = max(n1, n2); + if (n1 < n2) s1.insert(s1.begin(), n2 - n1, '0'); + if (n1 > n2) s2.insert(s2.begin(), n1 - n2, '0'); + int distance = 0; + for (int i = 0; i < maxLen; i++) + { + if (s1[i] != s2[i]) distance++; + } + return distance; + } + string toBinary(long n) /* 非负整数转二进制表示的字符串 */ + { + string res = ""; + while (n > 0) + { + char r = n % 2 + '0'; + res.push_back(r); /* 记住: 放进去的结果会导致低位在前, 高位在后 */ + n /= 2; + } + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int x = 1, y = 4; + auto res = sol.hammingDistance(x, y); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode461-hamming-distance_compare_string_char_by_char2.cpp b/cpp-leetcode/leetcode461-hamming-distance_compare_string_char_by_char2.cpp new file mode 100644 index 00000000..31e4084f --- /dev/null +++ b/cpp-leetcode/leetcode461-hamming-distance_compare_string_char_by_char2.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int hammingDistance(int x, int y) { + string s1 = toBinary(x); + string s2 = toBinary(y); + int n1 = s1.size(), n2 = s2.size(); + int maxLen = max(n1, n2); + if (n1 < n2) s1.insert(s1.begin(), n2 - n1, '0'); + if (n1 > n2) s2.insert(s2.begin(), n1 - n2, '0'); + int distance = 0; + for (int i = 0; i < maxLen; i++) + { + if (s1[i] != s2[i]) distance++; + } + return distance; + } + string toBinary(long n) + { + return bitset<64>(n).to_string(); + } +}; + +// Test +int main() +{ + Solution sol; + int x = 1, y = 4; + auto res = sol.hammingDistance(x, y); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode461-hamming-distance_xor.cpp b/cpp-leetcode/leetcode461-hamming-distance_xor.cpp new file mode 100644 index 00000000..94bc8bc0 --- /dev/null +++ b/cpp-leetcode/leetcode461-hamming-distance_xor.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int hammingDistance(int x, int y) { + int theXor = x ^ y; /* xor是^的等价运算符, 是C++关键字, 所以这里使用theXor避免语法错误 */ + string xorStr = toBinary(theXor); + return count(xorStr.begin(), xorStr.end(), '1'); + } + string toBinary(long n) + { + return bitset<64>(n).to_string(); + } +}; + +// Test +int main() +{ + Solution sol; + int x = 1, y = 4; + auto res = sol.hammingDistance(x, y); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode463-island-perimeter_counting.cpp b/cpp-leetcode/leetcode463-island-perimeter_counting.cpp new file mode 100644 index 00000000..8a8501c1 --- /dev/null +++ b/cpp-leetcode/leetcode463-island-perimeter_counting.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int islandPerimeter(vector>& grid) { + // 由于1 <= row, col <= 100, 故不需要判断空 + int m = grid.size(); + int n = grid[0].size(); + int area = 0; + int conn = 0; // 每个格子的neighbor数量的总和 + + for (int y = 0; y < m; ++y) + { + for (int x = 0; x < n; ++x) + { + if (grid[y][x] == 1) + { + area++; + if (y > 0 && grid[y - 1][x] == 1) conn++; // 正上方的格子 + if (y < m - 1 && grid[y + 1][x] == 1) conn++; // 正下方的格子 + if (x > 0 && grid[y][x - 1] == 1) conn++; // 正左方的格子 + if (x < n - 1 && grid[y][x + 1] == 1) conn++; // 正右方的格子 + } + } + } + + return area * 4 - conn; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}}; + auto res = sol.islandPerimeter(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode463-island-perimeter_counting2.cpp b/cpp-leetcode/leetcode463-island-perimeter_counting2.cpp new file mode 100644 index 00000000..9b8e4f42 --- /dev/null +++ b/cpp-leetcode/leetcode463-island-perimeter_counting2.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int islandPerimeter(vector>& grid) { + const int n = grid.size(); + const int m = grid[0].size(); + int count = 0; + int dx[2] = {0, 1}; + int dy[2] = {1, 0}; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + if (grid[i][j] == 0) continue; + + count += 4; + for (int k = 0; k < 2; k++) + { + int nx = i + dx[k]; + int ny = j + dy[k]; + if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 1) + { + count -= 2; + } + } + } + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}}; + auto res = sol.islandPerimeter(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode463-island-perimeter_counting_optimize.cpp b/cpp-leetcode/leetcode463-island-perimeter_counting_optimize.cpp new file mode 100644 index 00000000..768d7e38 --- /dev/null +++ b/cpp-leetcode/leetcode463-island-perimeter_counting_optimize.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int islandPerimeter(vector>& grid) { + // 由于1 <= row, col <= 100, 故不需要判断空 + int m = grid.size(); + int n = grid[0].size(); + int area = 0; + int conn = 0; // 每个格子的neighbor数量的总和 + + for (int y = 0; y < m; y++) + { + for (int x = 0; x < n; x++) + { + if (grid[y][x] == 1) + { + area++; + if (y > 0 && grid[y - 1][x] == 1) conn++; /* 只考虑正上方的格子, 下方的格子根据对称性处理 */ + if (x > 0 && grid[y][x - 1] == 1) conn++; /* 正左方的格子, 右方的格子根据对称性处理 */ + } + } + } + return area * 4 - conn * 2; /* 只考虑左上, 根据对称性处理 */ + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}}; + auto res = sol.islandPerimeter(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode463-island-perimeter_dfs.cpp b/cpp-leetcode/leetcode463-island-perimeter_dfs.cpp new file mode 100644 index 00000000..be9971a9 --- /dev/null +++ b/cpp-leetcode/leetcode463-island-perimeter_dfs.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +using namespace std; + +class Solution { + bool visited[100][100]; + int dir[4][2] = {{-1, 0},{0, -1},{1, 0},{0, 1}}; + int row; + int col; + int res = 0; +public: + int islandPerimeter(vector>& grid) { + row = grid.size(); + col = row == 0 ? 0 : grid[0].size(); + if (col == 0) + return 0; + + for (auto& theRow : visited) + fill(theRow, theRow + col, false); + for (int i = 0; i < row; i++) + { + for (int j = 0; j < col; j++) + { + visited[i][j] = true; + if (grid[i][j] == 0) + continue; + + for (int k = 0; k < 4; k++) + { + int newX = i + dir[k][0]; + int newY = j + dir[k][1]; + if (isInRange(newX, newY) && grid[newX][newY] == 0) + res++; + else if (!isInRange(newX, newY)) + res++; + } + } + } + return res; + } + bool isInRange(int i, int j) + { + return i >= 0 && j >= 0 && i < row && j < col; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}}; + auto res = sol.islandPerimeter(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode47-permutations-ii_backtracking.cpp b/cpp-leetcode/leetcode47-permutations-ii_backtracking.cpp new file mode 100644 index 00000000..dff41802 --- /dev/null +++ b/cpp-leetcode/leetcode47-permutations-ii_backtracking.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> permuteUnique(vector& nums) { + if (nums.empty()) return {{}}; + if (nums.size() == 1) return {nums}; + vector> result; + dfs(nums, result, 0); /* dfs (backTracking): 开始回溯, 一开始要处理的区间是[0, len-1] */ + return result; + } + +private: + /* 每次去处理子区间 [startPos, len - 1], startPos表示将要处理的剩下数中第一个数的index */ + void dfs(vector nums, vector>& result, int startPos) { + if (startPos == nums.size() - 1) { /* 已经排列到len 位置,超出了数组范围,这意味着此时已经完成了排列 */ + result.push_back(nums); + return; + } + + unordered_set usedDict; /* 记录哪些数已经用过 */ + for (int i = startPos; i < nums.size(); ++i) { /* startPos 是当前正在选择的位, i 是startPos位置将要选择的数的当前位置 */ + swap(nums[i], nums[startPos]); /* Choose: 将第i位数字交换到startPos位置, 完成startPos位置的选择 */ + // 仅当"当前数"没被使用过时才可以递归调用 + if (!usedDict.count(nums[startPos])) { + usedDict.insert(nums[startPos]); + dfs(nums, result, startPos + 1); /* Explore using dfs: 递归的向前推进1步(1个格子), 选择下一位数字 */ + } + swap(nums[i], nums[startPos]); /* Un-choose: 重置为选择之前的状态,重新选择下一位数字 */ + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 2, 3}; + vector> res = sol.permuteUnique(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode473-matchsticks-to-square_dfs.cpp b/cpp-leetcode/leetcode473-matchsticks-to-square_dfs.cpp new file mode 100644 index 00000000..7ad4a40a --- /dev/null +++ b/cpp-leetcode/leetcode473-matchsticks-to-square_dfs.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + vector _nums; + vector used; +public: + bool makesquare(vector& bars) { + if (bars.empty()) return false; + used.resize(bars.size()); + _nums = bars; + int sum0 = accumulate(bars.begin(), bars.end(), 0); + if (sum0 % 4 != 0) return false; + sum0 /= 4; /* 如果有可能拼成正方形, 那么边长必为所有火柴长度之和的1/4 */ + sort(_nums.begin(), _nums.end(), greater()); // 先从大到小排序, 降低dfs深度 + return dfs(0, 0, sum0, 0); + } + bool dfs(int startPos, /* 当前长度 */int cur, int edgeLen, /* 当前拼的是第几根, 共4根 */int count) + { + if (count == 3) return true; + if (cur == edgeLen) return dfs(0, 0, edgeLen, count + 1); // 当前这条边拼好了, 接下来拼另一边 + for (int i = startPos; i < _nums.size(); i++) + { + if (used[i]) continue; + if (cur + _nums[i] <= edgeLen) + { + used[i] = true; + if (dfs(i+1, cur + _nums[i], edgeLen, count)) return true; + used[i] = false; // 回溯/Unchoose + } + if (cur == 0 || cur + _nums[i] == edgeLen) /* cur == 0: 第一根失败; 最后一根失败: cur + _nums[i] == edgeLen */ + return false; + while (i + 1 < _nums.size() && _nums[i] == _nums[i+1]) + i++; + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {10, 6, 5, 5, 5, 3, 3, 3, 2, 2, 2, 2}; + auto res = sol.makesquare(nums); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode474-ones-and-zeroes_dp1.cpp b/cpp-leetcode/leetcode474-ones-and-zeroes_dp1.cpp new file mode 100644 index 00000000..b262365b --- /dev/null +++ b/cpp-leetcode/leetcode474-ones-and-zeroes_dp1.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + vector> dp(m + 1, vector(n + 1)); + for (string& str : strs) + { + int zeros = 0, ones = 0; + for (char& ch : str) + { + if (ch == '0') + zeros++; + else ones++; + } + for (int i = m; i >= zeros; i--) /* 设置好边界: 数组不会越界, 同时当超过字符0、1的数量超过其容量m, n时, 更新dp数组时不考虑它们, 它们对dp表不会有任何影响。 */ + { + for (int j = n; j >= ones; j--) + dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1); + } + } + return dp[m][n]; + } +}; + +// Test +int main() +{ + Solution sol; + vector strs = {"10", "0001", "111001", "1", "0"}; + int m = 5; + int n = 3; + auto res = sol.findMaxForm(strs, m, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode474-ones-and-zeroes_dp2.cpp b/cpp-leetcode/leetcode474-ones-and-zeroes_dp2.cpp new file mode 100644 index 00000000..31d8472b --- /dev/null +++ b/cpp-leetcode/leetcode474-ones-and-zeroes_dp2.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + vector> dp(m + 1, vector(n + 1)); + auto newDp = dp; + for (string& str : strs) + { + int zeros = 0, ones = 0; + for (char& ch : str) + { + if (ch == '0') + zeros++; + else ones++; + } + for (int i = zeros; i <= m; i++) + { + for (int j = ones; j <= n; j++) + newDp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1); + } + dp = newDp; // 更新一下供下一次迭代使用 + } + return newDp[m][n]; + } +}; + +// Test +int main() +{ + Solution sol; + vector strs = {"10", "0001", "111001", "1", "0"}; + int m = 5; + int n = 3; + auto res = sol.findMaxForm(strs, m, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode476-number-complement_bit_operation1.cpp b/cpp-leetcode/leetcode476-number-complement_bit_operation1.cpp new file mode 100644 index 00000000..4db9e6e8 --- /dev/null +++ b/cpp-leetcode/leetcode476-number-complement_bit_operation1.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findComplement(int num) { + int res = 0; + int h = 0; // 记录几次方 + while (num > 0) + { + if(num % 2 == 0) res += pow(2, h); /* 该位为0, 就取反当1来算 */ + h++; + num /= 2; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 5; + auto res = sol.findComplement(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode476-number-complement_bit_operation2_mask.cpp b/cpp-leetcode/leetcode476-number-complement_bit_operation2_mask.cpp new file mode 100644 index 00000000..cbfbebd2 --- /dev/null +++ b/cpp-leetcode/leetcode476-number-complement_bit_operation2_mask.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findComplement(int num) { + unsigned mask = INT_MAX; + // unsigned mask = ~0; /* 也能这样写 */ + + /* 由于存储num 时, 有32个bit, 其高位有不少的0. 故此处按位取反时~num的高位会产生很多不必要的1 */ + while (num & mask) mask <<= 1; /* 这里的目标是把mask末尾与结果相关的bit位清零, 循环结束时mask的形式是111...00 */ + return ~num & (~mask); + } +}; + +// Test +int main() +{ + Solution sol; + int num = 5; + auto res = sol.findComplement(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode476-number-complement_converrt_to_string.cpp b/cpp-leetcode/leetcode476-number-complement_converrt_to_string.cpp new file mode 100644 index 00000000..7bbfe659 --- /dev/null +++ b/cpp-leetcode/leetcode476-number-complement_converrt_to_string.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findComplement(int num) { + string str = toReverseBinary(num); + return stoi(str, nullptr, 2); /* 从2进制串转十进制数, 第3个参数2表示二进制 */ + } + + string toReverseBinary(long n) /* 得到二进制数的补码字符串 */ + { + string res = ""; + while (n > 0) + { + char r = n % 2 == 0 ? '1' : '0'; /* 得到每一位的反转值 */ + res.push_back(r); /* 记住: 放进去的结果会导致低位在前, 高位在后 */ + n /= 2; + } + reverse(res.begin(), res.end()); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 5; + auto res = sol.findComplement(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode482-license-key-formatting.cpp b/cpp-leetcode/leetcode482-license-key-formatting.cpp new file mode 100644 index 00000000..cf10256b --- /dev/null +++ b/cpp-leetcode/leetcode482-license-key-formatting.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string licenseKeyFormatting(string s, int k) { + // 1.删除所有的- + string newStr = ""; + for (auto ch : s) + { + if (ch != '-') + { + if (ch >= 'a' && ch <= 'z') newStr.push_back(ch + 'A' - 'a'); + else newStr.push_back(ch); + } + } + + int len = newStr.size(); + // 2.从末尾开始loop, 每走k格加一个- + for (int i = len - 1; i >= 0; i--) + { + int gap = len - 1 - i; + if (gap > 0 && (gap % k == 0)) + { + newStr.insert(newStr.begin() + i + 1, '-'); + } + } + + return newStr; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "5F3Z-2e-9-w"; + int k = 4; + auto res = sol.licenseKeyFormatting(str, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode485-max-consecutive-ones_solution1.cpp b/cpp-leetcode/leetcode485-max-consecutive-ones_solution1.cpp new file mode 100644 index 00000000..32ddf35f --- /dev/null +++ b/cpp-leetcode/leetcode485-max-consecutive-ones_solution1.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + const int len = nums.size(); + int maxLen = 0; + int curCount = 0; + for (int i = 0; i < len; i++) + { + if (nums[i] == 1) + curCount++; + else curCount = 0; + if (curCount > maxLen) maxLen = curCount; + } + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,1,0,1,1,1}; + auto res = sol.findMaxConsecutiveOnes(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode485-max-consecutive-ones_solution2.cpp b/cpp-leetcode/leetcode485-max-consecutive-ones_solution2.cpp new file mode 100644 index 00000000..8e7cc99a --- /dev/null +++ b/cpp-leetcode/leetcode485-max-consecutive-ones_solution2.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + if (nums.empty()) return 0; + + const int len = nums.size(); + int maxLen = INT_MIN; + int count = 0; + for (int i = 0; i < len; i++) + { + if (nums[i] == 1) + count++; + else + { + maxLen = max(maxLen, count); + count = 0; + } + } + return max(maxLen, count); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1,1,0,1,1,1}; + auto res = sol.findMaxConsecutiveOnes(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode49-group-anagrams_solution1.cpp b/cpp-leetcode/leetcode49-group-anagrams_solution1.cpp new file mode 100644 index 00000000..ea8fa5c1 --- /dev/null +++ b/cpp-leetcode/leetcode49-group-anagrams_solution1.cpp @@ -0,0 +1,46 @@ +// #include +// #include +// #include +// #include +// #include +#include +using namespace std; + +class Solution +{ +public: + vector> groupAnagrams(vector &strs) + { + unordered_map> dict; /* 哈希表: key是排序后的的各个单词,value是该key对应的全部异位词 */ + vector> result; + for (int i = 0; i < strs.size(); i++) + { + string str = strs[i]; + sort(str.begin(), str.end()); /* 对当前扫描到的字符串按字典序有小到大排序, 排序后的结果可以作为key插入哈希表 */ + + if (dict.find(str) == dict.end()) /* 如果当前的key在哈希表中还不存在,就加进来 */ + { + vector item; + dict[str] = item; + } + dict[str].push_back(strs[i]); /* 如果当前的key在哈希表中已存在, 往其中加入其他字符串即可 */ + } + + for (auto kvpIt : dict) /* 把哈希表中的value遍历出来, 放入二维动态数组的结果中 */ + { + result.push_back(kvpIt.second); + } + + return result; + } +}; + +// Test +int main() +{ + Solution sol; + vector strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; + auto res = sol.groupAnagrams(strs); /* 加断点到当前行的下一行, debug时可以看到结果 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode492-construct-the-rectangle_math.cpp b/cpp-leetcode/leetcode492-construct-the-rectangle_math.cpp new file mode 100644 index 00000000..b4ee9df7 --- /dev/null +++ b/cpp-leetcode/leetcode492-construct-the-rectangle_math.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector constructRectangle(int area) { + /* 1 <= area <= 10^7 */ + int m = sqrt(area); + int W = m; + int i; // i 是 宽度W + for (i = m; i >= 1; i--) + { + if (area % i == 0) + break; + } + return {area/i, i}; // L = area/i; + } +}; +// Test +int main() +{ + Solution sol; + int n = 122122; + auto res = sol.constructRectangle(n); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode493-reverse-pairs_map_with_binary_search.cpp b/cpp-leetcode/leetcode493-reverse-pairs_map_with_binary_search.cpp new file mode 100644 index 00000000..baadbcb2 --- /dev/null +++ b/cpp-leetcode/leetcode493-reverse-pairs_map_with_binary_search.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +typedef long long LL; +class Solution { +public: + int reversePairs(vector& nums) { + map dict; // map: value -> count + int res = 0; + for (auto& num : nums) + { + LL target = (LL)2*num; + auto it = dict.upper_bound(target); // 找到第1个满足要求的数key1, 那哈希表中排在key1后面的数(比key1更大)也全满足 > 2*num + if (it != dict.end()) + { + for (auto it1 = it; it1 != dict.end(); it1++) + res += it1->second; + } + if (dict.count(num) > 0) + dict[num]++; + else dict[num] = 1; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.reversePairs(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode493-reverse-pairs_merge_sort1.cpp b/cpp-leetcode/leetcode493-reverse-pairs_merge_sort1.cpp new file mode 100644 index 00000000..00d154ad --- /dev/null +++ b/cpp-leetcode/leetcode493-reverse-pairs_merge_sort1.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int reversePairs(vector& nums) { + int size = nums.size(); + int left = 0; + int right = size - 1; + int res = 0; + vector temp(size); + mergesort(nums, temp, left, right, res); + return res; + } + void mergesort(vector& nums, vector& temp, int left, int right, int& res) + { + if (left >= right) return; // base case: 只剩一个元素就是有序的了 + int mid = left + (right - left) / 2; + + mergesort(nums, temp, left, mid, res); //对左区间排序 + mergesort(nums, temp, mid + 1, right, res); //对右区间排序 + int i = left; + int j = mid + 1; + while (i <= mid && j <= right) // 左右区间都是有序的了,进行统计操作 + { + if ((long long)nums[i] > 2 * (long long)nums[j]) // *2 会超 int 范围 + { + res += (mid - i + 1); // 反转对个数 + j++; + } + else i++; + } + + i = left; + j = mid + 1; + int p = 0; + while (i <= mid && j <= right) // 进行归并操作 + { + if (nums[i] > nums[j]) + temp[p++] = nums[j++]; + else + temp[p++] = nums[i++]; + } + while (i <= mid) //将左边剩余元素填充进temp中 + temp[p++] = nums[i++]; + while (j <= right) //将右序列剩余元素填充进temp中 + temp[p++] = nums[j++]; + p = 0; + while (left <= right) //将temp中的元素全部拷贝到原数组[left,right]中 + nums[left++] = temp[p++]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.reversePairs(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode493-reverse-pairs_merge_sort2.cpp b/cpp-leetcode/leetcode493-reverse-pairs_merge_sort2.cpp new file mode 100644 index 00000000..22c85634 --- /dev/null +++ b/cpp-leetcode/leetcode493-reverse-pairs_merge_sort2.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int res = 0; + int temp[50001]; +public: + int reversePairs(vector& nums) { + int n = nums.size(); + vector sorted = nums; + helper(nums, sorted, 0, n - 1); + return res; + } + void helper(vector& nums, vector& sorted, int a, int b) + { + if (a >= b) return; + int mid = a + (b - a) / 2; + helper(nums, sorted, a, mid); + helper(nums, sorted, mid + 1, b); + + for (int j = mid + 1; j <= b; j++) + { + auto it = upper_bound(sorted.begin() + a, sorted.begin() + mid + 1, 2 * (long)nums[j]); + res += sorted.begin() + mid + 1 - it; + } + int i = a, j = mid + 1, p = 0; + while (i <= mid && j <= b) + { + if (sorted[i] <= sorted[j]) + { + temp[p] = sorted[i]; + i++; + } + else + { + temp[p] = sorted[j]; + j++; + } + p++; + } + while (i <= mid) + { + temp[p] = sorted[i]; + i++; + p++; + } + while (j <= b) + { + temp[p] = sorted[j]; + j++; + p++; + } + for (int i = 0; i < b - a + 1; i++) + sorted[a + i] = temp[i]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.reversePairs(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode494-target-sum_backtracking.cpp b/cpp-leetcode/leetcode494-target-sum_backtracking.cpp new file mode 100644 index 00000000..a1895987 --- /dev/null +++ b/cpp-leetcode/leetcode494-target-sum_backtracking.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { + int count = 0; +public: + int findTargetSumWays(vector& nums, int target) { + int N = nums.size(); + if (N == 0 && target != 0) return 0; + int index = 0; + dfs(nums, N, index, 0, target); + return count; + } + /* index: 计算算到了index(index处于区间[0, N])处, index = 0表示第1个数还没加进来时 */ + void dfs(vector& nums, int N, int index, int curSum, int sum) { + if (index == N) return; + int cur = nums[index]; + // Choose + int theAdd = curSum + cur; + if (index == N - 1 && theAdd == sum) count++; + int theMinus = curSum - cur; + if (index == N - 1 && theMinus == sum) count++; + // Explore + dfs(nums, N, index + 1, theAdd, sum); + dfs(nums, N, index + 1, theMinus, sum); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 1, 1}; + int target = 3; + auto res = sol.findTargetSumWays(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode494-target-sum_dp_using_array.cpp b/cpp-leetcode/leetcode494-target-sum_dp_using_array.cpp new file mode 100644 index 00000000..47a8e62b --- /dev/null +++ b/cpp-leetcode/leetcode494-target-sum_dp_using_array.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + nums.insert(nums.begin(), 0); + const int N = nums.size(); + int sum = 0; + for (int& x : nums) sum += x; + if (target > sum || target < -sum) return 0; + int dp[N][2*sum + 1]; + for (auto& row : dp) + fill(row, row + 2*sum + 1, 0); + dp[0][0 + sum] = 1; + for (int i = 1; i < N; i++) + { + for (int s = -sum; s <= sum; s++) + { + if (s + nums[i] + sum <= 2 * sum) + dp[i][s + nums[i] + sum] += dp[i - 1][s + sum]; + if (s - nums[i] + sum >= 0) + dp[i][s - nums[i] + sum] += dp[i - 1][s + sum]; + } + } + return dp[N - 1][target + sum]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 1, 1}; + int target = 3; + auto res = sol.findTargetSumWays(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode494-target-sum_dp_using_hashmap.cpp b/cpp-leetcode/leetcode494-target-sum_dp_using_hashmap.cpp new file mode 100644 index 00000000..5f6e4819 --- /dev/null +++ b/cpp-leetcode/leetcode494-target-sum_dp_using_hashmap.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + unordered_map dict; + dict[0] = 1; + + for (auto& x : nums) + { + auto curDict = dict; + dict.clear(); + for (auto& kvp : curDict) + { + dict[kvp.first + x] += kvp.second; + dict[kvp.first - x] += kvp.second; + } + } + return dict[S]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 1, 1}; + int target = 3; + auto res = sol.findTargetSumWays(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode494-target-sum_dp_using_vector.cpp b/cpp-leetcode/leetcode494-target-sum_dp_using_vector.cpp new file mode 100644 index 00000000..2cc1b287 --- /dev/null +++ b/cpp-leetcode/leetcode494-target-sum_dp_using_vector.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + nums.insert(nums.begin(), 0); + const int N = nums.size(); + int sum = 0; + for (int& x : nums) sum += x; /* 题意: sum(nums[i]) <= 1000, 后面需要用作+offset确保dp数组的index >= 0 */ + if (target > sum || target < -sum) return 0; + auto dp = vector>(N, vector(2 * sum + 1, 0)); + dp[0][0 + sum] = 1; /* dp[i][S]: 用前i个数进行计算后得到和为S的方法的数量. + dp数组的第2维统一 +sum确保这一维的index >= 0 + */ + for (int i = 1; i < N; i++) + { + for (int s = -sum; s <= sum; s++) + { + if (s + nums[i] + sum <= 2 * sum) + dp[i][s + nums[i] + sum] += dp[i - 1][s + sum]; + if (s - nums[i] + sum >= 0) + dp[i][s - nums[i] + sum] += dp[i - 1][s + sum]; + } + } + return dp[N - 1][target + sum]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 1, 1, 1, 1}; + int target = 3; + auto res = sol.findTargetSumWays(nums, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode496-next-greater-element-i_brute_force.cpp b/cpp-leetcode/leetcode496-next-greater-element-i_brute_force.cpp new file mode 100644 index 00000000..1304ddc4 --- /dev/null +++ b/cpp-leetcode/leetcode496-next-greater-element-i_brute_force.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + vector res(nums1.size()); + for (int i = 0; i < nums1.size(); i++) + { + auto theIt = find(nums2.begin(), nums2.end(), nums1[i]); + bool exist = false; + for (auto it = theIt + 1; it < nums2.end(); it++) + { + if (*it > nums1[i]) + { + exist = true; + res[i] = *it; + break; + } + } + if (!exist) res[i] = -1; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums1 = {4, 1, 2}; + vector nums2 = {1, 3, 4, 2}; + auto res = sol.nextGreaterElement(nums1, nums2); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode496-next-greater-element-i_monotonic_stack.cpp b/cpp-leetcode/leetcode496-next-greater-element-i_monotonic_stack.cpp new file mode 100644 index 00000000..80f99819 --- /dev/null +++ b/cpp-leetcode/leetcode496-next-greater-element-i_monotonic_stack.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + unordered_map dict; /* 映射: nums2数组中每个数 -> index, 而由于nums1数组是其子集, 那nums1的数均能在dict的key中找到 */ + deque st; + for (int i = nums2.size() - 1; i >= 0; i--) /* 从后往前遍历, 维护一个单调递减栈, 遇到比top位置index在原数组中的大的数时就不断得弹出直到新来的数<=top对应的数, 否则就压入 */ + { + while (!st.empty() && nums2[i] > nums2[st.back()]) + st.pop_back(); + + dict[nums2[i]] = st.empty() ? -1 : nums2[st.back()]; + st.push_back(i); + } + vector res(nums1.size()); + for (int i = 0; i < nums1.size(); i++) + res[i] = dict[nums1[i]]; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums1 = {4, 1, 2}; + vector nums2 = {1, 3, 4, 2}; + auto res = sol.nextGreaterElement(nums1, nums2); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode498-diagonal-traverse_sol1.cpp b/cpp-leetcode/leetcode498-diagonal-traverse_sol1.cpp new file mode 100644 index 00000000..cb98ed05 --- /dev/null +++ b/cpp-leetcode/leetcode498-diagonal-traverse_sol1.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findDiagonalOrder(vector>& mat) { + const int rows = mat.size(); /* 由于1 <= m, n <= 10^4, 故不需要判空 */ + const int cols = mat[0].size(); + vector res; + int pathCount = rows + cols - 1; /* 先算出总的趟数 */ + int x = 0; + int y = 0; + for (int i = 0; i < pathCount; i++) /* i表示第i趟 */ + { + if (i % 2 == 0) // 走向: 右上方向 + { + while (y >= 0 && x < cols) + { + res.push_back(mat[y][x]); + y--; + x++; + } + // 在顶部越界了, 进行相应处理 + if (x < cols) y++; + else { + y = y + 2; + x--; + } + } + else { /* 走向: 左下方向 */ + while (y < rows && x >= 0) + { + res.push_back(mat[y][x]); + y++; + x--; + } + // 在底部越界了, 进行相应处理 + if (y < rows) x++; + else + { + y--; + x = x + 2; + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.findDiagonalOrder(mat); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode498-diagonal-traverse_sol2.cpp b/cpp-leetcode/leetcode498-diagonal-traverse_sol2.cpp new file mode 100644 index 00000000..9c417f9c --- /dev/null +++ b/cpp-leetcode/leetcode498-diagonal-traverse_sol2.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findDiagonalOrder(vector>& mat) { + if (mat.empty()) return {}; + int height = mat.size(); + int width = mat[0].size(); + vector res; + int direction = -1; // ↗方向(up): -1, ↙方向(down): 1 + int y = 0, x = 0; + while (true) + { + // 先处理4种越界情况 + if (x >= width) + { + y += 2; + x -= 1; + direction = -direction; + continue; + } + if (y >= height) + { + y -= 1; + x += 2; + direction = -direction; + continue; + } + if (y < 0) + { + y += 1; + direction = -direction; + continue; + } + if (x < 0) + { + x += 1; + direction = -direction; + continue; + } + res.push_back(mat[y][x]); + if (y == height - 1 && x == width - 1) + return res; + y += direction; + x -= direction; + } + } +}; + +// Test +int main() +{ + Solution sol; + vector> mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.findDiagonalOrder(mat); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode5-longest-palindromic-substring_back_tracking.cpp b/cpp-leetcode/leetcode5-longest-palindromic-substring_back_tracking.cpp new file mode 100644 index 00000000..1b9e7934 --- /dev/null +++ b/cpp-leetcode/leetcode5-longest-palindromic-substring_back_tracking.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { + int maxLen = 0; + int start = 0; + +public: + string longestPalindrome(string s) { + if (s.empty() || s.size() == 1) return s; + for (int i = 0; i < s.size(); i++) + { + backTrack(s, i, i); /* 回溯back tracking开始, 寻找长度为奇数的串 */ + backTrack(s, i, i + 1); /* 回溯开始, 寻找长度为偶数的串 */ + } + return s.substr(start, maxLen); + } + + void backTrack(string s, int left, int right) { + while(left >= 0 && right < s.length() && s[left] == s[right]) { + if(right - left + 1 > maxLen) { /* 发现新的更长的回文串时, 更新全局变量startPos和maxLen */ + start = left; + maxLen = right - left + 1; + } + left--; + right++; + } + } +}; + +// Test +int main() +{ + Solution sol; + string s = "babad"; + auto res = sol.longestPalindrome(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode5-longest-palindromic-substring_brute_force.cpp b/cpp-leetcode/leetcode5-longest-palindromic-substring_brute_force.cpp new file mode 100644 index 00000000..03271bd9 --- /dev/null +++ b/cpp-leetcode/leetcode5-longest-palindromic-substring_brute_force.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string longestPalindrome(string s) { + string res; + int len = s.size(); + // 先固定中心点 i + for (int i = 0; i < len; i++) + { + // 枚举长度是奇数的情况 + int l = i - 1, r = i + 1; + while (l >= 0 && r <= len && s[l] == s[r]) + { + l--, r++; + } + if (res.size() < r - l - 1) + { + res = s.substr(l + 1, r - l - 1); + } + + // 枚举长度是奇数的情况 + l = i, r = i + 1; + while (l >= 0 && r <= len && s[l] == s[r]) + { + l--, r++; + } + if (res.size() < r - l - 1) + { + res = s.substr(l + 1, r - l - 1); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "babad"; + auto res = sol.longestPalindrome(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode50-powx-n_exponentiating_by_squaring.cpp b/cpp-leetcode/leetcode50-powx-n_exponentiating_by_squaring.cpp new file mode 100644 index 00000000..eaad778b --- /dev/null +++ b/cpp-leetcode/leetcode50-powx-n_exponentiating_by_squaring.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +using namespace std; + +/* 快速幂(Exponentiation by squaring, 平方求幂) */ +class Solution { +public: + double myPow(double x, int n) { + if (x == 0 && n == 0) + return 1; + if (x == 1 && n == INT_MIN) + return 1; + + long N = abs(n); /* 使用long, 防止整型溢出 */ + if (n < 0) + x = 1.0 / x; + + double res = 1.0; + for (; N > 0; N >>= 1) // 指数exponent每次折半,进行迭代 + { + if ((N % 2) == 1) // 分奇偶两种情况处理 + res *= x; + x *= x; // 底数base每次求平方 => base^2 + } + return res; + } +}; +// Test +int main() +{ + Solution sol; + + double x = 2.10000; + int n = -3; + auto res = sol.myPow(x, n); + cout << res << endl; + + x = 0.999999999; + n = -2147483648; + res = sol.myPow(x, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode500-keyboard-row.cpp b/cpp-leetcode/leetcode500-keyboard-row.cpp new file mode 100644 index 00000000..bb46ae2d --- /dev/null +++ b/cpp-leetcode/leetcode500-keyboard-row.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findWords(vector& words) { + vector vect { + "qwertyuiop", + "asdfghjkl", + "zxcvbnm" + }; + vector res; + for (auto word : words) + { + AddInResult(vect[0], word, res); + AddInResult(vect[1], word, res); + AddInResult(vect[2], word, res); + } + return res; + } + + bool isContain(string str, char ch) + { + if (find(str.begin(), str.end(), ch) != str.end() || find(str.begin(), str.end(), ch - ('A' - 'a')) != str.end()) + return true; + return false; + } + + void AddInResult(string str, string word, vector& res) + { + char firstChar = word.front(); + if (isContain(str, firstChar)) + { + if (word.size() == 1) res.push_back(word); + else + { + int j = 1; + for (; j < word.size(); j++) + if (!isContain(str, word[j])) break; + if (j == word.size()) + res.push_back(word); + } + } + } +}; + +// Test +int main() +{ + Solution sol; + vector words = {"a","b"}; + auto res = sol.findWords(words); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode502-IPO_priority_queue1.cpp b/cpp-leetcode/leetcode502-IPO_priority_queue1.cpp new file mode 100644 index 00000000..fbbe13c2 --- /dev/null +++ b/cpp-leetcode/leetcode502-IPO_priority_queue1.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { + const int n = profits.size(); + vector> options; // map: 门槛capital -> profit + for (int i = 0; i < n; i++) + options.push_back({capital[i], profits[i]}); + sort(options.begin(), options.end()); // 用门槛从小到大的规则给pair排序 + priority_queue pq; // 大顶堆放的是profit + int count = 0; + int i = 0; + while (count < k) + { + while (i < n && options[i].first <= w) + { + pq.push(options[i].second); + i++; + } + if (!pq.empty()) + { + w += pq.top(); + pq.pop(); + count++; + } + else break; + } + + return w; + } +}; + +// Test +int main() +{ + Solution sol; + int k = 2, w = 0; + vector profits = {1, 2, 3}, capitals = {0, 1, 1}; + auto res = sol.findMaximizedCapital(k, w, profits, capitals); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode502-IPO_priority_queue2.cpp b/cpp-leetcode/leetcode502-IPO_priority_queue2.cpp new file mode 100644 index 00000000..40a77cc8 --- /dev/null +++ b/cpp-leetcode/leetcode502-IPO_priority_queue2.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { + const int n = profits.size(); + vector> options; // map: 门槛capital -> profit + for (int i = 0; i < n; i++) + options.push_back({capital[i], profits[i]}); + sort(options.begin(), options.end()); // 用门槛从小到大的规则给pair排序 + priority_queue pq; // 大顶堆放的是profit + int count = 0; + int i = 0; + while (count < k) + { + while (i < n && options[i].first <= w) + { + pq.push(options[i].second); + i++; + } + if (pq.empty()) break; + w += pq.top(); + pq.pop(); + count++; + } + + return w; + } +}; +// Test +int main() +{ + Solution sol; + int k = 2, w = 0; + vector profits = {1, 2, 3}, capitals = {0, 1, 1}; + auto res = sol.findMaximizedCapital(k, w, profits, capitals); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode506-relative-ranks_dict.cpp b/cpp-leetcode/leetcode506-relative-ranks_dict.cpp new file mode 100644 index 00000000..afdf0b70 --- /dev/null +++ b/cpp-leetcode/leetcode506-relative-ranks_dict.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findRelativeRanks(vector& score) { + vector copy = score; + int len = score.size(); + if (len == 1) return { "Gold Medal" }; + sort(score.begin(), score.end(), greater()); /* 从大到小排序, 排序后长度不变, 故len还能用 */ + // 将原位置上的每个数的rank放进dict + unordered_map rankDict; // map: score -> rank (string) + rankDict[score[0]] = "Gold Medal"; + rankDict[score[1]] = "Silver Medal"; + if (len > 2) rankDict[score[2]] = "Bronze Medal"; + for (int i = 3; i < len; i++) rankDict[score[i]] = to_string(i + 1); + + vector res = {}; + for (int i = 0; i < len; i++) + res.push_back(rankDict[copy[i]]); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector scores = {3,4,2,5,1}; + auto res = sol.findRelativeRanks(scores); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode509-Fibonacci-number.cpp b/cpp-leetcode/leetcode509-Fibonacci-number.cpp new file mode 100644 index 00000000..5482ce1b --- /dev/null +++ b/cpp-leetcode/leetcode509-Fibonacci-number.cpp @@ -0,0 +1,34 @@ +#include +#include +using namespace std; + +class Solution { +public: + int fib(int n) { + if (n == 0) + return 0; + if (n == 1) + return 1; + + vector f(n+1); // f is an array here + f[0] = 0; + f[1] = 1; + + for (int i = 2; i < n + 1; i++) + { + f[i] = f[i-2] + f[i-1]; + } + + return f[n]; + } +}; + +// Test +int main() +{ + int n = 9; + Solution sol; + printf("%d", sol.fib(n)); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode509-fibonacci-number_improved.cpp b/cpp-leetcode/leetcode509-fibonacci-number_improved.cpp new file mode 100644 index 00000000..65cc55b7 --- /dev/null +++ b/cpp-leetcode/leetcode509-fibonacci-number_improved.cpp @@ -0,0 +1,36 @@ +#include +#include +using namespace std; + +class Solution { +public: + int fib(int n) { + if (n == 0) + return 0; + if (n == 1) + return 1; + + int sum = 0; + int pre2BeforeLast = 0; + int pre1BeforeLast = 1; + + for (int i = 2; i < n + 1; i++) + { + sum = pre2BeforeLast + pre1BeforeLast; + pre2BeforeLast = pre1BeforeLast; + pre1BeforeLast = sum; + } + + return sum; + } +}; + +// Test +int main() +{ + int n = 9; + Solution sol; + printf("%d", sol.fib(n)); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode51-n-queens_dfs.cpp b/cpp-leetcode/leetcode51-n-queens_dfs.cpp new file mode 100644 index 00000000..8ac06e30 --- /dev/null +++ b/cpp-leetcode/leetcode51-n-queens_dfs.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +using namespace std; + +class Solution { + vector> res; + vector board; + int N; +public: + vector> solveNQueens(int n) { + N = n; + string curRow; + // 将棋盘 board 的格子全初始化为空白格(题中要求用.表示) + for (int i = 0; i < n; i++) + curRow += "."; + for (int i = 0; i < n; i++) + board.push_back(curRow); + + dfs(0); // 从第1行(行索引为0)开始放置 + return res; + } + /* dfs的作用: 外部接口是放置第i行, 内部操作是: 遍历当前行的每一列 */ + void dfs(int i) + { + if (i == N) + { + res.push_back(board); + return; + } + for (int j = 0; j < N; j++) + { + if (isValid(i, j)) + { + board[i][j] = 'Q'; + dfs(i + 1); + board[i][j] = '.'; + } + } + } + + bool isValid(int row, int col) + { + for (int i = 0; i < row; i++) + { + if (board[i][col] == 'Q') return false; + } + for (int j = 0; j < col; j++) + { + if (board[row][j] == 'Q') return false; + } + int k = 1; + while (row - k >= 0 && col - k >= 0) /* 确保 index 没越界 */ + { /* \ 斜线 (捺) 上出现了皇后, 返回false */ + if (board[row - k][col - k] == 'Q') return false; + k++; + } + k = 1; // 复位 + while (row - k >= 0 && col + k < N) + { + /* / 斜线 (撇) 上出现了皇后, 返回false */ + if (board[row - k][col + k] == 'Q') return false; + k++; + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 8; + auto res = sol.solveNQueens(n); // n = 8 时有92组解 + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << "\n"; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode517-super-washing-machines_greedy1.cpp b/cpp-leetcode/leetcode517-super-washing-machines_greedy1.cpp new file mode 100644 index 00000000..0c299370 --- /dev/null +++ b/cpp-leetcode/leetcode517-super-washing-machines_greedy1.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMinMoves(vector& machines) { + int len = machines.size(); + int sum = 0; + for (auto &num : machines) + sum += num; + if (sum % len != 0) return -1; + int avg = sum / len; + vector left(len, 0); + vector right(len, 0); + // 两端的两个洗衣机向一个传递一个方向, 需要提前处理, 其他洗衣机都有两个左右两个方向的输入、输出 + right[0] = machines[0] - avg; + left.back() = machines.back() - avg; + for (int i = 1; i < len - 1; i++) + { + left[i] = -right[i-1]; + right[i] = machines[i] - avg - left[i]; + } + int res = 0; + for (int i = 0; i < len; i++) /* 计算输出净值的最大值 */ + { + int curMax = 0; + if (left[i] >= 0) curMax += left[i]; + if (right[i] >= 0) curMax += right[i]; + res = max(res, curMax); + } + return res; + } +}; +// Test +int main() +{ + Solution sol; + vector machines = {3, 8, 4}; + auto res = sol.findMinMoves(machines); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode517-super-washing-machines_greedy1_optimize.cpp b/cpp-leetcode/leetcode517-super-washing-machines_greedy1_optimize.cpp new file mode 100644 index 00000000..f700ed99 --- /dev/null +++ b/cpp-leetcode/leetcode517-super-washing-machines_greedy1_optimize.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMinMoves(vector& machines) { + int len = machines.size(); + int sum = 0; + for (auto &num : machines) + sum += num; + if (sum % len != 0) return -1; + int avg = sum / len; + int left[len]; + fill(left, left + len, 0); + int right[len]; + fill(right, right + len, 0); + // 两端的两个洗衣机向一个传递一个方向, 需要提前处理, 其他洗衣机都有两个左右两个方向的输入、输出 + right[0] = machines[0] - avg; + left[len - 1] = machines[len - 1] - avg; + for (int i = 1; i < len - 1; i++) + { + left[i] = -right[i-1]; + right[i] = machines[i] - avg - left[i]; + } + int res = 0; + for (int i = 0; i < len; i++) /* 计算输出净值的最大值 */ + { + int curMax = 0; + if (left[i] >= 0) curMax += left[i]; + if (right[i] >= 0) curMax += right[i]; + res = max(res, curMax); + } + return res; + } +}; +// Test +int main() +{ + Solution sol; + vector machines = {3, 8, 4}; + auto res = sol.findMinMoves(machines); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode517-super-washing-machines_greedy2.cpp b/cpp-leetcode/leetcode517-super-washing-machines_greedy2.cpp new file mode 100644 index 00000000..5877f450 --- /dev/null +++ b/cpp-leetcode/leetcode517-super-washing-machines_greedy2.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMinMoves(vector& machines) { + int len = machines.size(); + int sum = 0; + for (auto &num : machines) + sum += num; + if (sum % len != 0) return -1; + int avg = sum / len; + int res = 0; + int totalDiff = 0; // 整体的净流量偏差 + int curMax = 0; + for (int &num : machines) + { + int curDiff = num - avg; /* 当前洗衣机的流量偏差 */ + totalDiff += num - avg; + if (curDiff >= 0) + curMax = max(curDiff, abs(totalDiff)); + else curMax = max((abs(curDiff) + 1)/2, abs(totalDiff)); /* 一个洗衣机一次最多只能移出去1件衣服, 但可以一次接收最多2件衣服。+1是为了统一处理curDiff是奇数、偶数的情形 */ + res = max(res, curMax); + }; + return res; + } +}; +// Test +int main() +{ + Solution sol; + vector machines = {3, 8, 4}; + auto res = sol.findMinMoves(machines); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode518-coin-change-2_dp_1d_array.cpp b/cpp-leetcode/leetcode518-coin-change-2_dp_1d_array.cpp new file mode 100644 index 00000000..e8ee736c --- /dev/null +++ b/cpp-leetcode/leetcode518-coin-change-2_dp_1d_array.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int change(int amount, vector& coins) { + int dp[amount + 1]; // dp[i]: 凑成金额 i 的组合方式的总数量 + fill(dp, dp + amount + 1, 0); + dp[0] = 1; // 可以使用一个tets case测试出来 + for (int& coin : coins) + { + for (int i = coin; i <= amount; i++) + { + dp[i] = dp[i - coin] + dp[i]; /* 当前面值的硬币, 如果选它接下来处理总金额 i-coin, 如果不选它继续处理总金额i */ + } + } + return dp[amount]; + } +}; + +// Test +int main() +{ + Solution sol; + vector coins = {1, 2, 5}; + int amount = 5; + auto res = sol.change(amount, coins); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode518-coin-change-2_dp_1d_vector.cpp b/cpp-leetcode/leetcode518-coin-change-2_dp_1d_vector.cpp new file mode 100644 index 00000000..ba0c0e76 --- /dev/null +++ b/cpp-leetcode/leetcode518-coin-change-2_dp_1d_vector.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int change(int amount, vector& coins) { + vector dp(amount + 1); // dp[i]: 凑成金额 i 的组合方式的总数量 + dp[0] = 1; // 可以使用一个tets case测试出来 + for (int& coin : coins) + { + for (int i = coin; i <= amount; i++) + { + dp[i] = dp[i - coin] + dp[i]; /* 当前面值的硬币, 如果选它接下来处理总金额 i-coin, 如果不选它继续处理总金额i */ + } + } + return dp[amount]; + } +}; + +// Test +int main() +{ + Solution sol; + vector coins = {1, 2, 5}; + int amount = 5; + auto res = sol.change(amount, coins); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode518-coin-change-2_dp_2d_array.cpp b/cpp-leetcode/leetcode518-coin-change-2_dp_2d_array.cpp new file mode 100644 index 00000000..6b07145b --- /dev/null +++ b/cpp-leetcode/leetcode518-coin-change-2_dp_2d_array.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int change(int amount, vector& coins) { + // dp[i][j]: 用前i种硬币组成amount j的方法数量 + //dp[i][j] = dp[i-1][j] + dp[i][j-coins[i]] + //dp[i][0] = 1 + //dp[n][amount] + int n = coins.size(); + int dp[n + 1][amount + 1]; + for (auto& row : dp) + fill(row, row + amount + 1, 0); + for (int i = 0; i <= n; i++) + dp[i][0] = 1; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= amount; j++) { + dp[i][j] += dp[i - 1][j]; + if (j >= coins[i - 1]) + dp[i][j] += dp[i][j - coins[i - 1]]; + } + } + return dp[n][amount]; + } +}; + +// Test +int main() +{ + Solution sol; + vector coins = {1, 2, 5}; + int amount = 5; + auto res = sol.change(amount, coins); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode519-random-flip-matrix_hashmap1.cpp b/cpp-leetcode/leetcode519-random-flip-matrix_hashmap1.cpp new file mode 100644 index 00000000..6b0bab93 --- /dev/null +++ b/cpp-leetcode/leetcode519-random-flip-matrix_hashmap1.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int r, c, k; // r: 矩阵的行数, c: 列数, k: 矩阵中元素的个数 + unordered_map dict; // 大脑中构建一个映射: x -> x, 默认用这个映射, 将不满足这个映射的特殊键值对存入哈希表 +public: + Solution(int m, int n) { + r = m; + c = n; + k = r*c; + } + + vector flip() { /* 先把矩阵(二维数组)拉平成1维数组, 再进行随机处理 */ + int key = rand() % k; + int val = key; // 默认的映射规则: x -> x (x的范围是: 0 -> k-1) + if (dict.count(key)) + val = dict[key]; + + if (!dict.count(k - 1)) + dict[k-1] = k - 1; + // 当key处的kvp用过后, 用最后一个kvp(key = k-1)覆盖之, 然后删掉最后一个kvp, 就可以在剩下的数中实现随机化选择 + dict[key] = dict[k-1]; + dict.erase(k - 1); + k--; // 表示删掉了末尾的一个数 + + int newRow = val / c; + int newCol = val % c; + return {newRow, newCol}; + } + + void reset() { + k = r*c; + dict.clear(); + } +}; + +// Test +int main() +{ + int m = 3; + int n = 1; + Solution* sol = new Solution(m, n); + vector res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + sol->reset(); + res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + + cout << "OK~" << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode519-random-flip-matrix_hashmap2.cpp b/cpp-leetcode/leetcode519-random-flip-matrix_hashmap2.cpp new file mode 100644 index 00000000..31f69c31 --- /dev/null +++ b/cpp-leetcode/leetcode519-random-flip-matrix_hashmap2.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int r, c, k; // r: 矩阵的行数, c: 列数, k: 矩阵中元素的个数 + unordered_map dict; // 大脑中构建一个映射: x -> x, 默认用这个映射, 将不满足这个映射的特殊键值对存入哈希表 +public: + Solution(int m, int n) { + r = m; + c = n; + k = r*c; + } + + vector flip() { /* 先把矩阵(二维数组)拉平成1维数组, 再进行随机处理 */ + int key = rand() % k; + int val = key; // 默认的映射规则: x -> x (x的范围是: 0 -> k-1) + if (dict.count(key)) + val = dict[key]; + if (dict.count(k - 1)) // 当key处的kvp用过后, 用最后一个kvp(key = k-1)覆盖之, 然后删掉最后一个kvp, 就可以在剩下的数中实现随机化选择 + { + dict[key] = dict[k-1]; + dict.erase(k - 1); + } + else + dict[key] = k - 1; + k--; // 表示删掉了末尾的一个数 + int newRow = val / c; + int newCol = val % c; + return {newRow, newCol}; + } + + void reset() { + k = r*c; + dict.clear(); + } +}; + +// Test +int main() +{ + int m = 3; + int n = 1; + Solution* sol = new Solution(m, n); + vector res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + sol->reset(); + res = sol->flip(); + cout << "{" << res[0] << ", " << res[1] << "}" << endl; + + cout << "OK~" << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode52-n-queens-II_dfs1.cpp b/cpp-leetcode/leetcode52-n-queens-II_dfs1.cpp new file mode 100644 index 00000000..6df96ba9 --- /dev/null +++ b/cpp-leetcode/leetcode52-n-queens-II_dfs1.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int res = 0; + unordered_set colSet; + unordered_set diffSet; /* \ 对角线(捺): 差相等 */ + unordered_set sumSet; /* / 对角线(撇): 和相等 */ +public: + int totalNQueens(int n) { + // 边界情况 + if (n <= 0) return res; + dfs(0, n); + return res; + } + void dfs(int row, int n) /* n: N皇后的N, 对应几行几列的棋盘 */ + { + if (row == n) + { + res++; + return; + } + // row 不能相等 + for (int i = 0; i < n; i++) + { + if (!colSet.count(i) && !diffSet.count(row - i) && !sumSet.count(row + i)) + { + colSet.insert(i); + diffSet.insert(row - i); + sumSet.insert(row + i); + dfs(row + 1, n); + + colSet.erase(i); + diffSet.erase(row - i); + sumSet.erase(row + i); + } + } + } +}; + +// Test +int main() +{ + Solution sol; + int n = 8; + auto res = sol.totalNQueens(n); // n = 8 时有92组解 + cout << res << "\n"; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode52-n-queens-II_dfs_with_bit_operation.cpp b/cpp-leetcode/leetcode52-n-queens-II_dfs_with_bit_operation.cpp new file mode 100644 index 00000000..1af67cee --- /dev/null +++ b/cpp-leetcode/leetcode52-n-queens-II_dfs_with_bit_operation.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int count; + int N; +public: + int totalNQueens(int n) + { + count = 0; + N = n; + dfs(0, 0, 0, 0); + return count; + } + /* row: rowSet + * set1: / 对角线(撇): x与y的和相等 + * set2: \ 对角线(捺): x与y的差相等 */ + void dfs(int dep, int row, int set1, int set2) + { + if (dep == N) + { + count++; + return; + } + for (int i = 0; i < N; i++) /* i代表列索引colIndex */ + { + int j = 1 << i; /* 二进制100...0 (共i个0) */ + if ((j & row) || (j & set1) || (j & set2)) /* j & row: 水平方向上一个位置上重复放第2个皇后Q, (j & set1): / 斜对角线(撇)上, (j & set2): \ 斜对角线(捺)上 */ + continue; + dfs(dep + 1, (j | row), (j | set1) << 1, (j | set2) >> 1); + } + } +}; + +// Test +int main() +{ + Solution sol; + int n = 8; + auto res = sol.totalNQueens(n); // n = 8 时有92组解 + cout << res << "\n"; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode520-detect-capital_classification_and_merge.cpp b/cpp-leetcode/leetcode520-detect-capital_classification_and_merge.cpp new file mode 100644 index 00000000..2cb65f8a --- /dev/null +++ b/cpp-leetcode/leetcode520-detect-capital_classification_and_merge.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool detectCapitalUse(string word) { + int len = word.size(); + // 情形1: 全大写 + bool isAllUpclass = false; + int upClassCount = 0; + for (auto ch : word) + { + if (isLowclass(ch)) break; + else upClassCount++; + } + isAllUpclass = upClassCount == len; + // 情形2: 全小写 + bool isAllLowclass = false; + int lowClassCount = 0; + for (auto ch : word) + { + if (isUpclass(ch)) break; + else lowClassCount++; + } + isAllLowclass = lowClassCount == len; + // 情形3: 首字母大写, 其他字母小写 + bool isOnlyFirstCharUpclass = false; + int lowClassCount2 = 0; + for (int i = 0; i < word.size(); i++) + { + if (isLowclass(word.front())) break; + if (i > 0 && isLowclass(word[i])) lowClassCount2++; + } + isOnlyFirstCharUpclass = (lowClassCount2 == len - 1); + return (isAllUpclass || isAllLowclass || isOnlyFirstCharUpclass); + } + + bool isUpclass(char ch) + { + return (ch >= 'A' && ch <= 'Z'); + } + bool isLowclass(char ch) + { + return (ch >= 'a' && ch <= 'z'); + } +}; + +// Test +int main() +{ + Solution sol; + string str = "Leetcode"; + auto res = sol.detectCapitalUse(str); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode523-continuous-subarray-sum_prefix_sum_with_mod.cpp b/cpp-leetcode/leetcode523-continuous-subarray-sum_prefix_sum_with_mod.cpp new file mode 100644 index 00000000..f9a349f9 --- /dev/null +++ b/cpp-leetcode/leetcode523-continuous-subarray-sum_prefix_sum_with_mod.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + public: + bool checkSubarraySum(vector& nums, int k) { + // 同余定理: (sum2 - sum1) % k == 0 <=> sum2 % k = sum1 % k + // sum2: sum[0..i], sum1: sum[0..j], 前缀和之差对应的区间[i+1, j], 长度为j-i + unordered_map dict; // map: 某个前缀和%k得到的余数->pos + dict[0] = -1; /* 特殊情况sum1 == N*k, 则前缀和之差的被减数(对应的余数为0)可有可无了, 长度按更长的算, 即i+1或i-(-1) */ + int preSum = 0; + for (int i = 0; i < nums.size(); i++) + { + preSum += nums[i]; // preSum[0..i] + if (k != 0) // 本题中 1 <= k <= 2^31 - 1 + preSum %= k; + if (dict.count(preSum)) + { + int len = i - dict[preSum]; // i - j + if (len >= 2) + return true; + } + else /* 哈希表中还不存在该余数, 就把其index 加进来 */ + dict[preSum] = i; + } + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {3, 6, 9, 1}; + int k = 6; + + auto res = sol.checkSubarraySum(nums, k); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode524-longest-word-in-dictionary-through-deleting_sort_with_two_pointers.cpp b/cpp-leetcode/leetcode524-longest-word-in-dictionary-through-deleting_sort_with_two_pointers.cpp new file mode 100644 index 00000000..51a97733 --- /dev/null +++ b/cpp-leetcode/leetcode524-longest-word-in-dictionary-through-deleting_sort_with_two_pointers.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string findLongestWord(string s, vector& dict) { + vector res; + for (string& str : dict) + { + int i = 0; + for (char& ch : s) + { + if (i < str.size() && ch == str[i]) i++; + } + if (i == str.size()) /* 指针i能走到末尾, 说明是可以做到的 */ + res.push_back(str); + } + if (res.empty()) return ""; + auto cmp = [](const string& s1, const string& s2) + { + if (s1.size() == s2.size()) + return s1 < s2; + return s1.size() > s2.size(); + }; + sort(res.begin(), res.end(), cmp); + return res.front(); + } +}; + +// Test +int main() +{ + Solution sol; + string str = "abpcplea"; + vector dict = {"ale", "apple", "monkey", "plea"}; + auto res = sol.findLongestWord(str, dict); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode524-longest-word-in-dictionary-through-deleting_two_pointers_no_sort.cpp b/cpp-leetcode/leetcode524-longest-word-in-dictionary-through-deleting_two_pointers_no_sort.cpp new file mode 100644 index 00000000..d89d1d3c --- /dev/null +++ b/cpp-leetcode/leetcode524-longest-word-in-dictionary-through-deleting_two_pointers_no_sort.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string findLongestWord(string s, vector& dict) { + string res = ""; + for (string& curStr : dict) + { + int i = 0; + for (char& ch : s) + { + if (i < curStr.size() && ch == curStr[i]) i++; + } + if (i == curStr.size()) /* 指针i能走到末尾, 说明是可以做到的 */ + { + if (res == "") res = curStr; + else if (curStr.size() > res.size() || (curStr.size() == res.size() && curStr < res)) + res = curStr; + } + } + // 存在时返回相应值, 不存在时返回空串 + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "abpcplea"; + vector dict = {"ale", "apple", "monkey", "plea"}; + auto res = sol.findLongestWord(str, dict); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode525-contiguous-array_hashmap_and_counter.cpp b/cpp-leetcode/leetcode525-contiguous-array_hashmap_and_counter.cpp new file mode 100644 index 00000000..e0082d5e --- /dev/null +++ b/cpp-leetcode/leetcode525-contiguous-array_hashmap_and_counter.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaxLength(vector &nums) { + unordered_map dict; + dict.insert({0, -1}); + + const int len = nums.size(); + int count = 0; + int maxLen = 0; + for (int i = 0; i < len; i++) + { + if (nums[i] == 0) count++; + else count--; + if (dict.find(count) != dict.end()) + { + int j = i - dict[count]; + maxLen = max(maxLen, j); + } + else dict[count] = i; + } + + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {0, 1, 0}; + auto res = sol.findMaxLength(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode525-contiguous-array_hashmap_and_two_counters.cpp b/cpp-leetcode/leetcode525-contiguous-array_hashmap_and_two_counters.cpp new file mode 100644 index 00000000..450ea485 --- /dev/null +++ b/cpp-leetcode/leetcode525-contiguous-array_hashmap_and_two_counters.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findMaxLength(vector &nums) { + unordered_map dict; + dict.insert({0, -1}); + + int zero = 0; // 数组中从0开始到i, 0出现的次数 + int one = 0; // 数组中从0开始到i, 1出现的次数 + int maxLen = 0; + for (int i = 0; i < nums.size(); i++) + { + if (nums[i] == 0) zero++; + else one++; + + int gap = zero - one; /* 一开始0与1的数量之差记作gap = zero - one, 假如后面0与1的数量之差又出现gap, 说明两者在新走过的这段距离中势均力敌(数量相等), 找到上一次出现的位置j, 两者相减即可. */ + if (dict.count(gap)) + { + int j = i - dict[gap]; + maxLen = max(maxLen, j); + } + else dict[gap] = i; + } + + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {0, 1, 0}; + auto res = sol.findMaxLength(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode526-beautiful-arrangement_backTacking2.cpp b/cpp-leetcode/leetcode526-beautiful-arrangement_backTacking2.cpp new file mode 100644 index 00000000..c2d81872 --- /dev/null +++ b/cpp-leetcode/leetcode526-beautiful-arrangement_backTacking2.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +using namespace std; + +vector curGroup; +vector> allGroups(20, vector()); + +class Solution { +public: + bool used[20]; + int count; + + int countArrangement(int N) + { + curGroup.clear(); + for (int i = 1; i <= N; i++) + allGroups[i].clear(); + + for (int i = 1; i <= N; i++) + { + for (int j = 1; j <= N; j++) + { + if (i % j == 0 || j % i == 0) + { + allGroups[i].push_back(j); + // cout << i << '' << j << endl; + } + } + curGroup.push_back(i); + } + + auto cmp = [](const int& i, const int& j) + { + return allGroups[i].size() < allGroups[j].size(); + }; + sort(curGroup.begin(), curGroup.end(), cmp); + + count = 0; + dfs(1, N); + + return count; + } + + void dfs(int startNum, int maxNum) + { + // cout << p << ' ' << maxNum << endl; + if (startNum == maxNum + 1) + { + count++; + return; + } + int index = curGroup[startNum - 1]; + // cout << index << endl ; + for (auto& num : allGroups[index]) + { + if (used[num] == false) + { + used[num] = true; + dfs(startNum + 1, maxNum); + used[num] = false; + } + } + } +}; + +// Test +int main() +{ + Solution sol; + int num = 5; + auto res = sol.countArrangement(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode528-random-pick-with-weight_prefix_sum_and_binary_search.cpp b/cpp-leetcode/leetcode528-random-pick-with-weight_prefix_sum_and_binary_search.cpp new file mode 100644 index 00000000..ca48b131 --- /dev/null +++ b/cpp-leetcode/leetcode528-random-pick-with-weight_prefix_sum_and_binary_search.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +private: + vector preSum; +public: + Solution(vector& w) { + const int len = w.size(); + preSum.resize(len); + preSum[0] = w[0]; + for (int i = 1; i < len; i++) + preSum[i] = preSum[i - 1] + w[i]; // 计算前缀和 + } + + int pickIndex() { + int sum = preSum.back(); + int randPos = rand() % sum + 1; /* 产生1到sum之间的随机数 */ + return lower_bound(preSum.begin(), preSum.end(), randPos) - preSum.begin(); + } +}; + +// Test +int main() +{ + vector w = {1, 3}; + Solution* sol = new Solution(w); + int num1 = sol->pickIndex(); + cout << num1 << endl; + int num2 = sol->pickIndex(); + cout << num2 << endl; + int num3 = sol->pickIndex(); + cout << num3 << endl; + int num4 = sol->pickIndex(); + cout << num4 << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode53-maximum-subarray.cpp b/cpp-leetcode/leetcode53-maximum-subarray.cpp new file mode 100644 index 00000000..1e7b7a3c --- /dev/null +++ b/cpp-leetcode/leetcode53-maximum-subarray.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxSubArray(vector& nums) { + int len = nums.size(); + if(len == 0) return 0; + if(len == 1) return nums[0]; + + int maxSum = INT_MIN; + int currentSum = 0; + for(int i = 0; i maxSum) /* 将最大和更新为当前和 */ + maxSum = currentSum; + + if(currentSum < 0) + currentSum = 0; /* 若currentSum=0,此时什么都不做,等价于置为0. */ + } + + return maxSum; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-2,1,-3,4,-1,2,1,-5,4}; + int res = sol.maxSubArray(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode530-minimum-absolute-difference-in-bst_in_order.cpp b/cpp-leetcode/leetcode530-minimum-absolute-difference-in-bst_in_order.cpp new file mode 100644 index 00000000..7d4aef48 --- /dev/null +++ b/cpp-leetcode/leetcode530-minimum-absolute-difference-in-bst_in_order.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int getMinimumDifference(TreeNode* root) { + vector vals; + inorder(root, vals); + int minGap = INT_MAX; + for (int i = 0; i < vals.size() - 1; i++) + { + if (abs(vals[i+1] - vals[i]) < minGap) + minGap = abs(vals[i+1] - vals[i]); + } + return minGap; + } + + void inorder(TreeNode* root, vector& vals) + { + if (root == nullptr) return; + inorder(root->left, vals); + vals.push_back(root->val); + inorder(root->right, vals); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(3); + root->right->left = new TreeNode(2); + root->right->right = NULL; + auto res = sol.getMinimumDifference(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode535-encode-and-decode-tinyurl_hash_and_random.cpp b/cpp-leetcode/leetcode535-encode-and-decode-tinyurl_hash_and_random.cpp new file mode 100644 index 00000000..38a8cf49 --- /dev/null +++ b/cpp-leetcode/leetcode535-encode-and-decode-tinyurl_hash_and_random.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + unordered_map dict; // shortUrl -> long url + string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + string randomStr(int k) // % 62 + { + string str = ""; + while (k > 0) + { + str += chars[rand() % 62]; + k--; + } + return str; + } + + // Encodes a URL to a shortened URL. + string encode(string longUrl) { + while (true) + { + string shortUrl = randomStr(6); + if (dict.count(shortUrl) == 0) + { + dict[shortUrl] = longUrl; + return "http://tinyurl.com/" + shortUrl; + } + } + return ""; + } + + // Decodes a shortened URL to its original URL. + string decode(string shortUrl) { + return dict[shortUrl.substr(19)]; + } +}; + +// Test +int main() +{ + Solution sol; + string longUrl = "https://leetcode.com/problems/design-tinyurl"; + string shortUrl = sol.encode(longUrl); + cout << shortUrl << endl; + auto res = sol.decode(shortUrl); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode54-spiral-matrix_solution1.cpp b/cpp-leetcode/leetcode54-spiral-matrix_solution1.cpp new file mode 100644 index 00000000..a20b1b40 --- /dev/null +++ b/cpp-leetcode/leetcode54-spiral-matrix_solution1.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector spiralOrder(vector>& M) { + if (M.empty()) return {}; + int rows = M.size(); // rows >= 1 + int cols = M[0].size(); // cols >= 1 + int totalCount = rows*cols; + + vector res; + int row = 0; + int col = 0; + int rowStep = 0; + int colStep = 1; + + int rowStartIndex = 0; + int colStartIndex = -1; + while (res.size() < totalCount) { + res.push_back(M[row][col]); + if (rowStep != 0) { + int nextRow = row + rowStep; + if (nextRow == rows) rows--; // 到达矩阵的下边界, 就开始缩小 + else if (nextRow == rowStartIndex) rowStartIndex++; /* 到达矩阵的上边界, 就开始扩大 */ + else { + row = nextRow; + continue; + } + colStep = -rowStep; + rowStep = 0; + col += colStep; + } else { // colStep != 0 + int nextCol = col + colStep; + if (nextCol == cols) cols--; /* 到达矩阵的右边界, 就开始缩小 */ + else if (nextCol == colStartIndex) colStartIndex++; /* 到达矩阵的左边界, 就开始扩大 */ + else { + col = nextCol; + continue; + } + rowStep = colStep; + colStep = 0; + row += rowStep; + } + } + + return res; + } +}; + +// M[0][0] -> M[0][2] (M[0][N-1]) +// M[1][c-1] -> M[r-1][c-1] +// M[r-1][c-1] -> M[r-1][0] +// M[r-1][0] -> M[1][0] (r = r-1) +// loop + +// Test +int main() +{ + Solution sol; + vector> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.spiralOrder(matrix); + for (auto &num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode54-spiral-matrix_solution2.cpp b/cpp-leetcode/leetcode54-spiral-matrix_solution2.cpp new file mode 100644 index 00000000..24fa53a9 --- /dev/null +++ b/cpp-leetcode/leetcode54-spiral-matrix_solution2.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector spiralOrder(vector> &M) { + if (M.empty()) return {}; + + vector res; + int rows = M.size(); // 行数 + int cols = M[0].size(); + + int circles = ((rows < cols ? rows : cols) - 1) / 2 + 1; // 圈数 + for (int k = 0; k < circles; k++) + { + for (int i = k; i < cols - k; i++) + res.push_back(M[k][i]); /* 从左到右, 所在行的index不变, 横坐标++ */ + for (int j = k + 1; j < rows - k; j++) + res.push_back(M[j][cols - 1 - k]); // M[k+1][y] ==> M[rows-k-1][y]; + for (int m = cols - k - 2; (m >= k) && (rows - k - 1 != k); m--) + res.push_back(M[rows - k - 1][m]); // 防止重复 + for (int n = rows - k - 2; (n > k) && (cols - k - 1 != k); n--) + res.push_back(M[n][k]); // 防止重复 + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.spiralOrder(matrix); + for (auto &num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode54-spiral-matrix_solution3.cpp b/cpp-leetcode/leetcode54-spiral-matrix_solution3.cpp new file mode 100644 index 00000000..2ecc32ad --- /dev/null +++ b/cpp-leetcode/leetcode54-spiral-matrix_solution3.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector spiralOrder(vector> &M) { + if (M.empty()) return {}; + int m = M.size(); // m >= 1 + int n = M[0].size(); // n >= 1 + + vector res; + int row = 0, col = -1; + while (true) + { + for (int i = 0; i < n; i++) /* 把第1行的每一列的数放进去 */ + res.push_back(M[row][++col]); + if (--m == 0) /* 每次减1表示水平向右方向1圈遍历完成, 当发现当前所在行的index为1(回到第2行)时, 直接break */ + break; + for (int i = 0; i < m; i++) /* 把第1行以外的每一行的最后一列的数放进去 */ + res.push_back(M[++row][col]); + if (--n == 0) /* 每次减1表示垂直向下1圈遍历完成, 当发现当前所在列的index为1(回到第2列)时, 直接break */ + break; + for (int i = 0; i < n; i++) + res.push_back(M[row][--col]); + if (--m == 0) /* 每次减1表示水平向左方向1圈遍历完成, 当发现当前所在行的index为1(回到第2行)时, 直接break */ + break; + for (int i = 0; i < m; i++) + res.push_back(M[--row][col]); + if (--n == 0) /* 每次减1表示垂直向上1圈遍历完成, 当发现当前所在列的index为1(回到第2列)时, 直接break */ + break; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.spiralOrder(matrix); + for (auto &num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode54-spiral-matrix_solution4.cpp b/cpp-leetcode/leetcode54-spiral-matrix_solution4.cpp new file mode 100644 index 00000000..5aab0139 --- /dev/null +++ b/cpp-leetcode/leetcode54-spiral-matrix_solution4.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector spiralOrder(vector> &M) { + if (M.empty()) return {}; + + vector res; + int rowBegin = 0; + int rowEnd = M.size() - 1; + int colBegin = 0; + int colEnd = M[0].size() - 1; + while (rowBegin <= rowEnd && colBegin <= colEnd) + { + // 向右遍历 + for (int j = colBegin; j <= colEnd; j++) + res.push_back(M[rowBegin][j]); + rowBegin++; + + // 向下遍历 + for (int j = rowBegin; j <= rowEnd; j++) + res.push_back(M[j][colEnd]); + colEnd--; + + if (rowBegin <= rowEnd) // 由于不是方阵, 需要判断还有没有行 + { + // 向左遍历 + for (int j = colEnd; j >= colBegin; j--) + res.push_back(M[rowEnd][j]); + } + rowEnd--; + + if (colBegin <= colEnd) // 由于不是方阵, 需要判断还有没有列 + { + // 向上遍历 + for (int j = rowEnd; j >= rowBegin; j--) + res.push_back(M[j][colBegin]); + } + colBegin++; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.spiralOrder(matrix); + for (auto &num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode543-diameter-of-binary-tree_recursive1.cpp b/cpp-leetcode/leetcode543-diameter-of-binary-tree_recursive1.cpp new file mode 100644 index 00000000..1d8b6ac3 --- /dev/null +++ b/cpp-leetcode/leetcode543-diameter-of-binary-tree_recursive1.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + if (root == nullptr) return 0; + + int lDepth = getMaxDepth(root->left); + int rDepth = getMaxDepth(root->right); + int disThroughRoot = lDepth + rDepth; + int leftMaxDis = diameterOfBinaryTree(root->left); + int rightMaxDis = diameterOfBinaryTree(root->right); + return max(disThroughRoot, max(leftMaxDis, rightMaxDis)); + } + int getMaxDepth(TreeNode* root) + { + if (root == nullptr) return 0; + + int lDepth = getMaxDepth(root->left); + int rDepth = getMaxDepth(root->right); + return max(lDepth, rDepth) + 1; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(3); + TreeNode *n3 = new TreeNode(4); + TreeNode *n4 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n3->left = NULL; + n3->right = NULL; + n4->left = NULL; + n4->right = NULL; + + auto res = sol.diameterOfBinaryTree(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode543-diameter-of-binary-tree_recursive2.cpp b/cpp-leetcode/leetcode543-diameter-of-binary-tree_recursive2.cpp new file mode 100644 index 00000000..43772064 --- /dev/null +++ b/cpp-leetcode/leetcode543-diameter-of-binary-tree_recursive2.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + if (root == nullptr) return 0; + int res = 0; + getMaxDepth(root, res); + return res; + } + int getMaxDepth(TreeNode* root, int& maxDist) + { + if (root == nullptr) return 0; + + int lDepth = getMaxDepth(root->left, maxDist); + int rDepth = getMaxDepth(root->right, maxDist); + maxDist = max(maxDist, lDepth + rDepth); + + return max(lDepth, rDepth) + 1; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + TreeNode *n1 = new TreeNode(2); + TreeNode *n2 = new TreeNode(3); + TreeNode *n3 = new TreeNode(4); + TreeNode *n4 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n3->left = NULL; + n3->right = NULL; + n4->left = NULL; + n4->right = NULL; + + auto res = sol.diameterOfBinaryTree(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode551-student-attendance-record-i_solution1.cpp b/cpp-leetcode/leetcode551-student-attendance-record-i_solution1.cpp new file mode 100644 index 00000000..0759de43 --- /dev/null +++ b/cpp-leetcode/leetcode551-student-attendance-record-i_solution1.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool checkRecord(string s) { + /** True: + 1、A的个数<2 + 2、连续L的个数<=2 + */ + if (count(s.begin(), s.end(), 'A') >= 2) + return false; + + const int len = s.size(); + int lMaxCount = 0; + + for (int i = 0; i < len; i++) + { + int lCount = 0; + if (s[i] == 'L') + { + lCount = 1; + for (int j = i + 1; j < len; j++) + { + if (s[j] == s[i]) + lCount++; + else break; + } + } + lMaxCount = max(lMaxCount, lCount); + } + return (lMaxCount <= 2); + } +}; + +// Test +int main() +{ + Solution sol; + string s = "LLL"; + auto res = sol.checkRecord(s); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode551-student-attendance-record-i_solution2.cpp b/cpp-leetcode/leetcode551-student-attendance-record-i_solution2.cpp new file mode 100644 index 00000000..647459f9 --- /dev/null +++ b/cpp-leetcode/leetcode551-student-attendance-record-i_solution2.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool checkRecord(string s) { + /** True: + 1、A的个数<2 + 2、连续L的个数<=2 + */ + if (count(s.begin(), s.end(), 'A') >= 2) + return false; + + int lCount = 0; + for (auto ch : s) + { + if (ch == 'L') + lCount++; + else lCount = 0; + + if (lCount > 2) + return false; + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "LLL"; + auto res = sol.checkRecord(s); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode557-reverse-words-in-a-string-iii_solution1.cpp b/cpp-leetcode/leetcode557-reverse-words-in-a-string-iii_solution1.cpp new file mode 100644 index 00000000..86c9e736 --- /dev/null +++ b/cpp-leetcode/leetcode557-reverse-words-in-a-string-iii_solution1.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include /* 含有stringstream类 */ +#include +using namespace std; + +class Solution { +public: + string reverseWords(string s) { + string res; + // 把word放进vector + vector words; + istringstream iss(s); + while (iss >> s) + words.push_back(s); + for (auto word : words) + { + for (int i = word.size() - 1; i >= 0; i--) + res.push_back(word[i]); + res.append(" "); + } + res.erase(res.find_last_not_of(' ') + 1); /* 删除最后多余的空格 */ + return res; + } +}; + +// test +int main() +{ + Solution sol; + string s = "madam lol level civic radar racecar refer"; + auto res = sol.reverseWords(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode557-reverse-words-in-a-string-iii_solution2.cpp b/cpp-leetcode/leetcode557-reverse-words-in-a-string-iii_solution2.cpp new file mode 100644 index 00000000..ac58cd16 --- /dev/null +++ b/cpp-leetcode/leetcode557-reverse-words-in-a-string-iii_solution2.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include /* 含有stringstream类 */ +#include +using namespace std; + +class Solution { +public: + string reverseWords(string s) { + string res; + // 把word放进vector + vector words; + istringstream iss(s); + while (iss >> s) + words.push_back(s); + for (auto word : words) + { + for (int i = word.size() - 1; i >= 0; i--) + res.push_back(word[i]); + res.append(" "); + } + res.pop_back(); /* 删除最后多余的空格 */ + return res; + } +}; + +// test +int main() +{ + Solution sol; + string s = "madam lol level civic radar racecar refer"; + auto res = sol.reverseWords(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode559-maximum-depth-of-n-ary-tree_bfs_deque.cpp b/cpp-leetcode/leetcode559-maximum-depth-of-n-ary-tree_bfs_deque.cpp new file mode 100644 index 00000000..c402fbf3 --- /dev/null +++ b/cpp-leetcode/leetcode559-maximum-depth-of-n-ary-tree_bfs_deque.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + int maxDepth(Node* root) { + if (root == nullptr) return 0; + vector> paths = levelOrder(root); + int res = paths.size(); + return res; + } + vector> levelOrder(Node* root) { + if (root == nullptr) return {}; + vector> res; + deque q {root}; + + while (!q.empty()) + { + vector curLevel; + int curSize = q.size(); + for (int i = curSize; i > 0; i--) + { + Node* p = q.front(); + q.pop_front(); + curLevel.push_back(p->val); + // loop to handle children + for (auto child : p->children) + if (child) q.push_back(child); /* 判断/不判断空看起来没影响 */ + } + res.push_back(curLevel); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + auto res = sol.maxDepth(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode559-maximum-depth-of-n-ary-tree_recursive.cpp b/cpp-leetcode/leetcode559-maximum-depth-of-n-ary-tree_recursive.cpp new file mode 100644 index 00000000..4264b194 --- /dev/null +++ b/cpp-leetcode/leetcode559-maximum-depth-of-n-ary-tree_recursive.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + int maxDepth(Node* root) { + if (root == nullptr) return 0; + int maxH = 0; + vector depths; + for (auto child : root->children) + maxH = max(maxH, maxDepth(child)); + return maxH + 1; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + auto res = sol.maxDepth(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode56-merge-intervals_solution1.cpp b/cpp-leetcode/leetcode56-merge-intervals_solution1.cpp new file mode 100644 index 00000000..2cf4cc3b --- /dev/null +++ b/cpp-leetcode/leetcode56-merge-intervals_solution1.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> merge(vector>& intervals) { + if (intervals.empty()) + return {}; + vector> q; /* pair: (start, end) */ + vector> res; + for (auto &range : intervals) + { + q.push_back({ range.front(), range.back() }); + } + + auto cmp = [](pair& range1, pair& range2) + { + return range1.first < range2.first; /* 按区间的start(下界)排序 */ + }; + sort(q.begin(), q.end(), cmp); + + for (const auto& range : q) { + // 无交集 + if (res.empty() || range.first > res.back().back()) { + res.push_back({range.first, range.second}); + } else { // 有交集: 只可能在 res 的右侧有交集, 因为已排序 + res.back().back() = max(res.back().back(), range.second); + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> intervals = {{1,3},{2,6},{8,10},{15,18}}; + auto res = sol.merge(intervals); /* 加断点到这一行和下一行, debug时可看到结果 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode56-merge-intervals_solution2.cpp b/cpp-leetcode/leetcode56-merge-intervals_solution2.cpp new file mode 100644 index 00000000..7791362d --- /dev/null +++ b/cpp-leetcode/leetcode56-merge-intervals_solution2.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> merge(vector>& intervals) { + if (intervals.empty()) + return {}; + vector> res; + vector> ranges; /* ranges 是 intervals 的另一种存储方式 + ** 扫描线算法: time, flag. 先自定义排序 + ** 进来一个start, 计数器+1, + ** 进来一个end, 计数器-1. + ** 计数器出现0 -> 1的转折点, 表示新的 start 进来了 + ** 计数器出现1 -> 0的转折点, 表示所有 []括号成对, merge 结束 + */ + for (auto &vect : intervals) + { + ranges.push_back({vect.front(), 1}); + ranges.push_back({vect.back(), -1}); + } + + auto cmp = [](pair& range1, pair& range2) + { + if (range1.first == range2.first) /* 相等时, flag为 1 的放在前面 */ + return range1.second > range2.second; + return range1.first < range2.first; + }; + sort(ranges.begin(), ranges.end(), cmp); + + int sumCounter = 0; + int start, end; + for (auto range : ranges) + { + if (range.second == 1) + { + sumCounter++; + if (sumCounter == 1) // 转折点: 0 -> 1, 新的start进来了 + { + start = range.first; + } + } + else /* -1 */ + { + sumCounter--; + if (sumCounter == 0) // 转折点: 1 -> 0, merge结束, 记录结束时的区间右边界end + { + end = range.first; + res.push_back({start, end}); + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> intervals = {{1,3},{2,6},{8,10},{15,18}}; + auto res = sol.merge(intervals); /* 加断点到这一行和下一行, debug时可看到结果 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_array1.cpp b/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_array1.cpp new file mode 100644 index 00000000..25b52711 --- /dev/null +++ b/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_array1.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int arrayPairSum(vector& nums) { + vector countDict(20001); + for (int i = 0; i < nums.size(); i++) + countDict[nums[i] + 10000]++; /* 数组中的数全加上10000映射到index >= 0的范围内, 方便实现数组模拟哈希表 */ + int res = 0; + bool odd = true; // 第1个元素(index = 0)的编号为1, 是奇数 + for (int i = 0; i < countDict.size(); i++) + { + while (countDict[i] > 0) + { + if (odd) + res += (i - 10000); + odd = !odd; + --countDict[i]; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {6, 2, 6, 5, 1, 2}; + int res = sol.arrayPairSum(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_stl_array.cpp b/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_stl_array.cpp new file mode 100644 index 00000000..de138572 --- /dev/null +++ b/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_stl_array.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int arrayPairSum(vector& nums) { + const int maxVal = 10000; + array countDict{}; + + for (int num : nums) + ++countDict[num + maxVal]; + + int ans = 0; + int n = -maxVal; + bool first = true; + + while (n <= maxVal) + { + if (countDict[n + maxVal] == 0) + { + ++n; + continue; + } + if (first) + { + ans += n; + first = false; + } + else first = true; + --countDict[n + maxVal]; + } + return ans; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {6, 2, 6, 5, 1, 2}; + int res = sol.arrayPairSum(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_stl_array_and_bit_operation.cpp b/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_stl_array_and_bit_operation.cpp new file mode 100644 index 00000000..ecda888a --- /dev/null +++ b/cpp-leetcode/leetcode561-array-partition-i_hash_simulation_with_stl_array_and_bit_operation.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int arrayPairSum(vector& nums) { + const int max_val = *max_element(nums.begin(), nums.end()); + const int min_val = *min_element(nums.begin(), nums.end()); + const int offset = -min_val; + vector countDict(max_val - min_val + 1); + + for (int num : nums) + ++countDict[num + offset]; + + int res = 0; + int index = 0; + int n = min_val; + + while (n <= max_val) + { + if (countDict[n + offset] == 0) + { + ++n; + continue; + } + res += (++index & 1) ? n : 0; + --countDict[n + offset]; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {6, 2, 6, 5, 1, 2}; + int res = sol.arrayPairSum(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode561-array-partition-i_sort.cpp b/cpp-leetcode/leetcode561-array-partition-i_sort.cpp new file mode 100644 index 00000000..9849b727 --- /dev/null +++ b/cpp-leetcode/leetcode561-array-partition-i_sort.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int arrayPairSum(vector& nums) { + sort(nums.begin(), nums.end()); + int sum = 0; + const int len = nums.size(); + for (int i = 0; i <= len - 1; i += 2) + sum += nums[i]; + return sum; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {6, 2, 6, 5, 1, 2}; + int res = sol.arrayPairSum(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode563-binary-tree-tilt_recursive.cpp b/cpp-leetcode/leetcode563-binary-tree-tilt_recursive.cpp new file mode 100644 index 00000000..e2a93575 --- /dev/null +++ b/cpp-leetcode/leetcode563-binary-tree-tilt_recursive.cpp @@ -0,0 +1,50 @@ +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int findTilt(TreeNode* root) { + int tiltSum = 0; + dfs(root, tiltSum); + return tiltSum; + } + // dfs: 计算当前结点的子树中所有孩子节点之和 + int dfs(TreeNode* root, int& tiltSum) + { + if (root == nullptr) return 0; + int leftValSum = dfs(root->left, tiltSum); + int rightValSum = dfs(root->right, tiltSum); + int curNodeTilt = abs(leftValSum - rightValSum); /* 计算当前结点的坡度 */ + tiltSum += curNodeTilt; + + return leftValSum + rightValSum + root->val; + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode *root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->right->left = new TreeNode(4); + root->right->right = nullptr; + + auto res = sol.findTilt(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode566-reshape-the-matrix_sol1.cpp b/cpp-leetcode/leetcode566-reshape-the-matrix_sol1.cpp new file mode 100644 index 00000000..6e60d41d --- /dev/null +++ b/cpp-leetcode/leetcode566-reshape-the-matrix_sol1.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> matrixReshape(vector>& mat, int r, int c) { + // 题意: 1 <= m, n <= 100, 不需要考虑为空原矩阵是空的情况 + const int m = mat.size(); + const int n = mat[0].size(); + if (m * n != r * c || (m == r && n == c)) return mat; + /** m*n == r*c时, 想象中把之前的矩阵水平拉直, 然后重新分组 + * 在长度为m*n的数组中每次取c个。 + */ + vector nums; + for (auto row : mat) + nums.insert(nums.end(), row.begin(), row.end()); + + vector> res(r, vector(c)); + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + res[i][j] = nums[c * i + j]; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> mat = {{1,2}, {3,4}}; + int r = 1; + int c = 4; + auto res = sol.matrixReshape(mat, r, c); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} diff --git a/cpp-leetcode/leetcode567-permutation-in-string_sliding_window_with_hash.cpp b/cpp-leetcode/leetcode567-permutation-in-string_sliding_window_with_hash.cpp new file mode 100644 index 00000000..d3c8f31b --- /dev/null +++ b/cpp-leetcode/leetcode567-permutation-in-string_sliding_window_with_hash.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int restCount = s1.size(); /* 维护一个固定长度的窗口, 长度= len(s1), restCount: 剩下的待匹配字符的数量 */ + vector s1Freq(26); /* 模拟一个计数哈希表 */ + for (int i = 0; i < s1.size(); i++) + s1Freq[s1[i] - 'a']++; + vector s2Freq(26); /* 模拟一个计数哈希表, s2Freq: 字符串s中处于滑动窗口内的字符的频次 */ + for (int i = 0; i < s2.size(); i++) + { + char c = s2[i]; + s2Freq[c - 'a']++; + if (s2Freq[c - 'a'] <= s1Freq[c - 'a']) /* 匹配到了一个待匹配的字符 */ + restCount--; + if (i >= s1.size()) /* 删除最前面的1个字符 */ + { + char h = s2[i - s1.size()]; + s2Freq[h - 'a']--; + if (s2Freq[h - 'a'] < s1Freq[h - 'a']) + restCount++; + } + // 字符都匹配完成, 表示是一个有效的字母异位词(anagram) + if (restCount == 0) /* i - startPos + 1 = len(s1) => startPos = i - len(s1) + 1 */ + return true; + } + return false; + } +}; + +// Test +// Test +int main() +{ + Solution sol; + string s1 = "ab"; + string s2 = "eidbaooo"; + + auto res = sol.checkInclusion(s2, s1); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode57-insert-interval_by_seg.cpp b/cpp-leetcode/leetcode57-insert-interval_by_seg.cpp new file mode 100644 index 00000000..59c68fb4 --- /dev/null +++ b/cpp-leetcode/leetcode57-insert-interval_by_seg.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + vector> res; + int k = 0; + int len = intervals.size(); + + // 原区间中, 左侧与新区间无交集的部分 + while (k < len && intervals[k][1] < newInterval[0]) + res.push_back(intervals[k++]); + + // 处理有交集的部分 + if (k < len) { + newInterval[0] = min(newInterval[0], intervals[k][0]); + + while (k < len && intervals[k][0] <= newInterval[1]) + newInterval[1] = max(newInterval[1], intervals[k++][1]); + } + res.push_back(newInterval); + + // 原区间中, 右侧与新区间无交集的部分 + while (k < len && intervals[k][0] > newInterval[1]) + res.push_back(intervals[k++]); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> intervals = {{1,3},{6,9}}; + vector newInterval = {2,5}; + auto res = sol.insert(intervals, newInterval); /* 加断点到下一行进行debug, 可以看到结果 */ + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode57-insert-interval_direct_brute_force.cpp b/cpp-leetcode/leetcode57-insert-interval_direct_brute_force.cpp new file mode 100644 index 00000000..09fec7e4 --- /dev/null +++ b/cpp-leetcode/leetcode57-insert-interval_direct_brute_force.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + intervals.push_back(newInterval); + merge(intervals); + return intervals; + } + void merge(vector> &segs) + { + vector> res; + sort(segs.begin(), segs.end()); + int start = INT_MIN, end = INT_MIN; // 左端点最小值 + for (auto seg : segs) + if (seg[0] > end) + { + if (start != INT_MIN) res.push_back({start, end}); + start = seg[0]; + end = seg[1]; + } + else end = max(end, seg[1]); + + if (start != INT_MIN) /* 循环结束时, 区间不空时, 把最后一个区间加进来 */ + res.push_back({start, end}); + + segs = res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> intervals = {{1,3},{6,9}}; + vector newInterval = {2,5}; + auto res = sol.insert(intervals, newInterval); /* 加断点到下一行进行debug, 可以看到结果 */ + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode57-insert-interval_sweep_line_algorithm.cpp b/cpp-leetcode/leetcode57-insert-interval_sweep_line_algorithm.cpp new file mode 100644 index 00000000..c8435660 --- /dev/null +++ b/cpp-leetcode/leetcode57-insert-interval_sweep_line_algorithm.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> insert(vector> &intervals, vector &newInterval) { + vector> q; + for (auto interval : intervals) + { + q.push_back({interval[0], 1}); + q.push_back({interval[1], -1}); + } + q.push_back({newInterval[0], 1}); + q.push_back({newInterval[1], -1}); + + auto cmp = [](const pair& a, const pair& b) + { + if (a.first == b.first) + return a.second > b.second; + else return a.first < b.first; + }; + + sort(q.begin(), q.end(), cmp); + int count = 0; + int start, end; + vector> results; + for (auto x : q) + { + count += x.second; + if (x.second == 1 && count == 1) + { + start = x.first; + } + else if (x.second == -1 && count == 0) + { + end = x.first; + results.push_back({start, end}); + } + } + return results; + } +}; + +// Test +int main() +{ + Solution sol; + vector> intervals = {{1,3},{6,9}}; + vector newInterval = {2,5}; + auto res = sol.insert(intervals, newInterval); /* 加断点到下一行进行debug, 可以看到结果 */ + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode575-distribute-candies_bool_array_trade_space_for_time.cpp b/cpp-leetcode/leetcode575-distribute-candies_bool_array_trade_space_for_time.cpp new file mode 100644 index 00000000..3f9f653c --- /dev/null +++ b/cpp-leetcode/leetcode575-distribute-candies_bool_array_trade_space_for_time.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +const int N = 1e5; +class Solution { +public: + int distributeCandies(vector& candyType) { + bool flags[2 * N + 1]; /* 标记当前num是否是重复出现, -10^5 <= candyType[i] <= 10^5 */ + fill(flags, flags + 2 * N + 1, false); + int count = 0; + int half = candyType.size() / 2; + for (auto &candy : candyType) + { + candy += N; + if (!flags[candy]) + { + if (++count >= half) + return count; + flags[candy] = true; + } + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + vector candyType = {1, 1, 2, 2, 3, 3}; + auto res = sol.distributeCandies(candyType); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode575-distribute-candies_haspmap1.cpp b/cpp-leetcode/leetcode575-distribute-candies_haspmap1.cpp new file mode 100644 index 00000000..b8a8fbcc --- /dev/null +++ b/cpp-leetcode/leetcode575-distribute-candies_haspmap1.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int distributeCandies(vector& candyType) { + const int len = candyType.size(); + // len/2 + unordered_map dict; // map: num -> count + for (auto& num : candyType) + dict[num]++; + int res; + if (dict.size() >= len/2) + res = len/2; + else res = dict.size(); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector candyType = {1,1,2,2,3,3}; + auto res = sol.distributeCandies(candyType); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode575-distribute-candies_haspmap2.cpp b/cpp-leetcode/leetcode575-distribute-candies_haspmap2.cpp new file mode 100644 index 00000000..6a2066c0 --- /dev/null +++ b/cpp-leetcode/leetcode575-distribute-candies_haspmap2.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int distributeCandies(vector& candyType) { + const int len = candyType.size(); + // len/2 + unordered_map dict; // map: num -> count + for (auto& num : candyType) + { + dict[num]++; + if (dict.size() >= len/2) + return len/2; + } + return dict.size(); + } +}; + +// Test +int main() +{ + Solution sol; + vector candyType = {1,1,2,2,3,3}; + auto res = sol.distributeCandies(candyType); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode575-distribute-candies_set.cpp b/cpp-leetcode/leetcode575-distribute-candies_set.cpp new file mode 100644 index 00000000..c184d77c --- /dev/null +++ b/cpp-leetcode/leetcode575-distribute-candies_set.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int distributeCandies(vector& candyType) { + const int len = candyType.size(); + // len/2 + unordered_set st(candyType.begin(), candyType.end()); + int res; + if (st.size() >= len/2) + res = len/2; + else res = st.size(); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector candyType = {1,1,2,2,3,3}; + auto res = sol.distributeCandies(candyType); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode58-length-of-last-word_reverse_traversal.cpp b/cpp-leetcode/leetcode58-length-of-last-word_reverse_traversal.cpp new file mode 100644 index 00000000..13278110 --- /dev/null +++ b/cpp-leetcode/leetcode58-length-of-last-word_reverse_traversal.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int lengthOfLastWord(string s) { + s.erase(s.find_last_not_of(' ')+1); // Trim尾部的空格 + s.erase(0, s.find_first_not_of(' ')); // Trim开头的空格 + int lastSpaceIndex = -1; + int res; + for (int i = s.size() - 1; i >= 0; i--) + { + if (s[i] == ' ') + { + lastSpaceIndex = i; + res = s.size() - 1 - (i+1) + 1; + break; + } + } + if (lastSpaceIndex == -1) return s.size(); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = " fly me to the moon "; + auto res = sol.lengthOfLastWord(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode58-length-of-last-word_stringstream.cpp b/cpp-leetcode/leetcode58-length-of-last-word_stringstream.cpp new file mode 100644 index 00000000..cb63b759 --- /dev/null +++ b/cpp-leetcode/leetcode58-length-of-last-word_stringstream.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int lengthOfLastWord(string s) { + string curWord; + istringstream iss(s); + while (iss >> s) /* 循环结束时, curWord成为最后一个单词 */ + curWord = s; + return curWord.size(); + } +}; + +// Test +int main() +{ + Solution sol; + string str = " fly me to the moon "; + auto res = sol.lengthOfLastWord(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode583-delete-operation-for-two-strings_dp1.cpp b/cpp-leetcode/leetcode583-delete-operation-for-two-strings_dp1.cpp new file mode 100644 index 00000000..e618bcdd --- /dev/null +++ b/cpp-leetcode/leetcode583-delete-operation-for-two-strings_dp1.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minDistance(string word1, string word2) { + int m = word1.size(); + int n = word2.size(); + vector> dp(m + 1, vector(n + 1, 501)); /* 按照题意"给定单词的长度不超过500", 故最多删除次数不会超过500, + 初始化为 INT_MAX/2也行, /2 避免后面代码中的+1时导致整型溢出 */ + for (int j = 0; j <= n; j++) + dp[0][j] = j; + for (int i = 0; i <= m; i++) + dp[i][0] = i; + + word1.insert(word1.begin(), '#'); /* 或者写城成 word1 = '#' + word1; */ + word2.insert(word2.begin(), '#'); + for (int i = 1; i <= m; i++) + { + for (int j = 1; j <= n; j++) + { + if (word1[i] == word2[j]) + dp[i][j] = min(dp[i][j], dp[i-1][j-1]); + else + { + dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1); + dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1); + } + } + } + return dp[m][n]; + } +}; + +// Test +int main() +{ + Solution sol; + string str1 = "sea"; + string str2 = "eat"; + auto res = sol.minDistance(str1, str2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode583-delete-operation-for-two-strings_dp1_optimize.cpp b/cpp-leetcode/leetcode583-delete-operation-for-two-strings_dp1_optimize.cpp new file mode 100644 index 00000000..ff7d276e --- /dev/null +++ b/cpp-leetcode/leetcode583-delete-operation-for-two-strings_dp1_optimize.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minDistance(string word1, string word2) { + const int m = word1.size(); + const int n = word2.size(); + int dp[m + 1][n + 1]; + for (auto& arr : dp) + fill(arr, arr + n + 1, 501); /* 按照题意"给定单词的长度不超过500", 故最多删除次数不会超过500, + 初始化为 INT_MAX/2也行, /2 避免后面代码中的+1时导致整型溢出 */ + for (int j = 0; j <= n; j++) + dp[0][j] = j; + for (int i = 0; i <= m; i++) + dp[i][0] = i; + + word1.insert(word1.begin(), '#'); + word2.insert(word2.begin(), '#'); + for (int i = 1; i <= m; i++) + { + for (int j = 1; j <= n; j++) + { + if (word1[i] == word2[j]) + dp[i][j] = min(dp[i][j], dp[i-1][j-1]); + else + { + dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1); + dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1); + } + } + } + + return dp[m][n]; + } +}; + +// Test +int main() +{ + Solution sol; + string str1 = "sea"; + string str2 = "eat"; + auto res = sol.minDistance(str1, str2); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_iterative_deque1.cpp b/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_iterative_deque1.cpp new file mode 100644 index 00000000..0a4e3224 --- /dev/null +++ b/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_iterative_deque1.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + Node(int _val) { + val = _val; + } + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + vector preorder(Node* root) { + if (root == nullptr) return {}; + + vector nums = {}; + deque st; /* 辅助栈, 输出(遍历)顺序: 根 左 右, 于是放入顺序遍历顺序: 右 左 根 */ + st.emplace_front(root); + + while (!st.empty()) + { + Node* p = st.front(); + nums.push_back(p->val); + st.pop_front(); + + // 逆序遍历children + const int len = p->children.size(); + for (int i = len-1; i >=0 ; i--) + st.emplace_front((p->children)[i]); + } + + return nums; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + vector res = sol.preorder(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_iterative_deque2.cpp b/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_iterative_deque2.cpp new file mode 100644 index 00000000..fbae7a8a --- /dev/null +++ b/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_iterative_deque2.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + Node(int _val) { + val = _val; + } + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + vector preorder(Node* root) { + if (root == nullptr) return {}; + + vector nums = {}; + deque st; /* 辅助栈, 输出(遍历)顺序: 根 左 右, 于是放入顺序遍历顺序: 右 左 根 */ + st.push_front(root); + + while (!st.empty()) + { + Node* p = st.front(); + nums.push_back(p->val); + st.pop_front(); + + // 逆序遍历children + const int len = p->children.size(); + for (int i = len-1; i >= 0; i--) + st.push_front((p->children)[i]); + } + + return nums; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + vector res = sol.preorder(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_recursive.cpp b/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_recursive.cpp new file mode 100644 index 00000000..bbb12b7b --- /dev/null +++ b/cpp-leetcode/leetcode589-n-ary-tree-preorder-traversal_recursive.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +using namespace std; +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + Node(int _val) { + val = _val; + } + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + vector preorder(Node* root) { + vector nums = {}; + preOrder(root, nums); + return nums; + } + void preOrder(Node* root, vector& nums) + { + if (root == nullptr) return; + nums.emplace_back(root->val); + for (auto child : root->children) + preOrder(child, nums); + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + vector res = sol.preorder(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode59-spiral-matrix-ii_solution.cpp b/cpp-leetcode/leetcode59-spiral-matrix-ii_solution.cpp new file mode 100644 index 00000000..40d92ada --- /dev/null +++ b/cpp-leetcode/leetcode59-spiral-matrix-ii_solution.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> generateMatrix(int n) { + vector> M(n, vector(n, 0)); /* 1 <= n <= 20, 故不需要判空 */ + + vector res; + int rowBegin = 0; + int rowEnd = n - 1; + int colBegin = 0; + int colEnd = n - 1; + + int num = 1; + while (rowBegin <= rowEnd && colBegin <= colEnd) + { + // 向右遍历 + for (int j = colBegin; j <= colEnd; j++) + M[rowBegin][j] = num++; + rowBegin++; + + // 向下遍历 + for (int j = rowBegin; j <= rowEnd; j++) + M[j][colEnd] = num++; + colEnd--; + + if (rowBegin <= rowEnd) // 由于不是方阵, 需要判断还有没有行 + { + // 向左遍历 + for (int j = colEnd; j >= colBegin; j--) + M[rowEnd][j] = num++; + } + rowEnd--; + + if (colBegin <= colEnd) // 由于不是方阵, 需要判断还有没有列 + { + // 向上遍历 + for (int j = rowEnd; j >= rowBegin; j--) + M[j][colBegin] = num++; + } + colBegin++; + } + + return M; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 6; + auto matrix = sol.generateMatrix(6); + for (auto& rows : matrix) // 遍历每一行 + { + for (auto& elem : rows) // 输出每一个元素 + cout << elem << "\t"; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode590-n-ary-tree-postorder-traversal_deque_with_extra_struct.cpp b/cpp-leetcode/leetcode590-n-ary-tree-postorder-traversal_deque_with_extra_struct.cpp new file mode 100644 index 00000000..319ab958 --- /dev/null +++ b/cpp-leetcode/leetcode590-n-ary-tree-postorder-traversal_deque_with_extra_struct.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +using namespace std; + +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +struct Pack { + int op; /* 0, to visit (表示还需要后续处理); 1, visited/print/save (不需要后续处理了, 就想取里面的值) */ + Node* node; + Pack(int op, Node* node) { + this->op = op; + this->node = node; + } +}; + +class Solution { +public: + vector postorder(Node* root) { + vector res; + deque st; + st.push_front(new Pack(0, root)); + + while (!st.empty()) + { + Pack* cur = st.front(); // 先front(), 再pop + st.pop_front(); + if (cur->node == nullptr) + continue; + if (cur->op == 1) + res.push_back(cur->node->val); + else + { + /* 基于deque的辅助栈, 要求每一个结点及其子树的输出(遍历)顺序: 左 右 根, 于是放入顺序遍历顺序: 根 右 左 */ + st.push_front(new Pack(1, cur->node)); + // 反向for loop + for (int i = (cur->node->children).size() - 1; i >= 0; i--) + st.push_front(new Pack(0, cur->node->children[i])); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + vector res = sol.postorder(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode590-n-ary-tree-postorder-traversal_recursive.cpp b/cpp-leetcode/leetcode590-n-ary-tree-postorder-traversal_recursive.cpp new file mode 100644 index 00000000..349e608d --- /dev/null +++ b/cpp-leetcode/leetcode590-n-ary-tree-postorder-traversal_recursive.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +using namespace std; + +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; + +class Solution { +public: + vector postorder(Node* root) { + if (root == nullptr) return {}; + vector res; + postOrder(root, res); + + return res; + } + void postOrder(Node* root, vector& res) + { + if (root == nullptr) return; + for (auto child : root->children) + postOrder(child, res); + res.push_back(root->val); + } +}; + +// Test +int main() +{ + Solution sol; + + Node* root = new Node(1); + auto child1 = new Node(3); + auto child11= new Node(5); + auto child12= new Node(6); + child1->children.push_back(child11); + child1->children.push_back(child12); + root->children.push_back(child1); + + auto child2 = new Node(2); + auto child3 = new Node(4); + root->children.push_back(child2); + root->children.push_back(child3); + + vector res = sol.postorder(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode593-valid-square_hashset.cpp b/cpp-leetcode/leetcode593-valid-square_hashset.cpp new file mode 100644 index 00000000..f8695ad9 --- /dev/null +++ b/cpp-leetcode/leetcode593-valid-square_hashset.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { + unordered_set set = + { + getLenSquare(p1, p2), + getLenSquare(p1, p3), + getLenSquare(p1, p4), + getLenSquare(p2, p3), + getLenSquare(p2, p4), + getLenSquare(p3, p4) + }; + + if (set.find(0) == set.end() && set.size() == 2) // 所有邻边+对角线中,菱形有3种长度, 平行四边形(含长方形)有4种长度, 其他四边形有6种长度 + { + return true; + } + + return false; + } + int getLenSquare(vector point1, vector point2) { + return (point2[0] - point1[0]) * (point2[0] - point1[0]) + (point2[1] - point1[1]) * (point2[1] - point1[1]); + } +}; + +// Test +int main() +{ + Solution sol; + vector p1 = {0, 0}, p2 = {1, 1}, p3 = {1, 0}, p4 = {0, 1}; + auto res = sol.validSquare(p1, p2, p3, p4); + + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode594-longest-harmonious-subsequence_hashmap1.cpp b/cpp-leetcode/leetcode594-longest-harmonious-subsequence_hashmap1.cpp new file mode 100644 index 00000000..46da4233 --- /dev/null +++ b/cpp-leetcode/leetcode594-longest-harmonious-subsequence_hashmap1.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findLHS(vector& nums) { + unordered_map dict; // map: num -> count + for (const auto& num : nums) + dict[num]++; + + int maxLen = 0; + for (const auto& kvp : dict) + { + int k = kvp.first; + if (dict.count(k + 1)) /* 往高处找(key -> key + 1), 进行贪心 */ + maxLen = max(maxLen, dict[k] + dict[k + 1]); + if (dict.count(k - 1)) /* 往低处找(key -> key - 1), 进行贪心 */ + maxLen = max(maxLen, dict[k] + dict[k - 1]); + } + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.findLHS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode594-longest-harmonious-subsequence_hashmap2.cpp b/cpp-leetcode/leetcode594-longest-harmonious-subsequence_hashmap2.cpp new file mode 100644 index 00000000..ed5d73ee --- /dev/null +++ b/cpp-leetcode/leetcode594-longest-harmonious-subsequence_hashmap2.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findLHS(vector& nums) { + unordered_map dict; + int n = nums.size(); + for (int i = 0; i < n; i++) + dict[nums[i]]++; + + int maxLen = 0; + for (auto it = dict.begin(); it != dict.end(); ++it) + { + int k = it->first; + if (dict.find(k + 1) != dict.end()) + { + maxLen = max(maxLen, it->second + dict[k + 1]); + } + } + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.findLHS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode594-longest-harmonious-subsequence_sort_and_two_pointers.cpp b/cpp-leetcode/leetcode594-longest-harmonious-subsequence_sort_and_two_pointers.cpp new file mode 100644 index 00000000..3f48a07c --- /dev/null +++ b/cpp-leetcode/leetcode594-longest-harmonious-subsequence_sort_and_two_pointers.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int findLHS(vector& nums) { + sort(nums.begin(), nums.end()); + int L = 0; + int r = 0; + const int len = nums.size(); + int maxLen = 0; + while (r < len) + { + while (nums[r] - nums[L] > 1) + L++; + if (nums[r] - nums[L] == 1) + maxLen = max(maxLen, r - L + 1); + r++; + } + return maxLen; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.findLHS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode595-big-countries_mysql.sql b/cpp-leetcode/leetcode595-big-countries_mysql.sql new file mode 100644 index 00000000..70fde0bc --- /dev/null +++ b/cpp-leetcode/leetcode595-big-countries_mysql.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +SELECT tb1.name, tb1.population, tb1.area +FROM World as tb1 +WHERE tb1.area >= 3000000 or tb1.population >= 25000000; \ No newline at end of file diff --git a/cpp-leetcode/leetcode596-classes-more-than-5-students_mysql.sql b/cpp-leetcode/leetcode596-classes-more-than-5-students_mysql.sql new file mode 100644 index 00000000..3591c852 --- /dev/null +++ b/cpp-leetcode/leetcode596-classes-more-than-5-students_mysql.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below +SELECT class +FROM courses +GROUP BY class +HAVING count(distinct(student)) >= 5; \ No newline at end of file diff --git a/cpp-leetcode/leetcode598-range-addition-ii_solution1.cpp b/cpp-leetcode/leetcode598-range-addition-ii_solution1.cpp new file mode 100644 index 00000000..ad6e8c06 --- /dev/null +++ b/cpp-leetcode/leetcode598-range-addition-ii_solution1.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxCount(int m, int n, vector>& ops) { + /* 数组row 存储水平向右方向1 的累加和, 数组col 存储竖直向下方向1 的累加和*/ + vector row(m); + vector col(n); + for (auto op : ops) + { + int maxRow = op[0]; + int maxCol = op[1]; + for (int i = 0; i < maxRow; i++) + row[i]++; + for (int j = 0; j < maxCol; j++) + col[j]++; + } + int rowIndex = 0, colIndex = 0; + while (rowIndex < m && row[rowIndex] == row[0]) /* row[0]是当前行的格子的最大值 */ + rowIndex++; + while (colIndex < n && col[colIndex] == col[0]) /* row[0]是当前列的格子的最大值 */ + colIndex++; + return rowIndex * colIndex; + } +}; + +// Test +int main() +{ + Solution sol; + int m = 4, n = 6; + vector> operations = {{2, 5}, {3, 2}}; + auto res = sol.maxCount(m, n, operations); // 预期结果是4 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode598-range-addition-ii_solution2_short_code.cpp b/cpp-leetcode/leetcode598-range-addition-ii_solution2_short_code.cpp new file mode 100644 index 00000000..2fce8754 --- /dev/null +++ b/cpp-leetcode/leetcode598-range-addition-ii_solution2_short_code.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxCount(int m, int n, vector>& ops) { + int maxXCount = m, maxYCount = n; + for (auto& op: ops) + { + maxXCount = min(maxXCount, op[0]); /* 横向最大值数量取决于短板 */ + maxYCount = min(maxYCount, op[1]); /* 纵向最大值数量取决于短板 */ + } + return maxXCount * maxYCount; + } +}; + +// Test +int main() +{ + Solution sol; + int m = 4, n = 6; + vector> operations = {{2, 5}, {3, 2}}; + auto res = sol.maxCount(m, n, operations); // 预期结果是4 + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode599-minimum-index-sum-of-two-list_hashmap.cpp b/cpp-leetcode/leetcode599-minimum-index-sum-of-two-list_hashmap.cpp new file mode 100644 index 00000000..c4b4da32 --- /dev/null +++ b/cpp-leetcode/leetcode599-minimum-index-sum-of-two-list_hashmap.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findRestaurant(vector& list1, vector& list2) { + vector res; + unordered_map dict; // map: string -> index + + int index = 0; + for (auto &s : list1) + { + index++; + dict[s] = index; + } + + int minIndexSum = INT_MAX; + index = 0; + for (auto &str : list2) + { + index++; + if (dict[str] > 0) + { + int indexSum = index + dict[str]; + if (indexSum < minIndexSum) + { + res.clear(); // 记住: 这里必须清空 + minIndexSum = indexSum; + } + if (indexSum == minIndexSum) + res.push_back(str); + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector list1 = {"Shogun", "Tapioca Express", "Burger King", "KFC"}; + vector list2 = {"KFC", "Burger King", "Tapioca Express", "Shogun"}; + auto res = sol.findRestaurant(list1, list2); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode599-minimum-index-sum-of-two-lists_sort.cpp b/cpp-leetcode/leetcode599-minimum-index-sum-of-two-lists_sort.cpp new file mode 100644 index 00000000..8b3f2755 --- /dev/null +++ b/cpp-leetcode/leetcode599-minimum-index-sum-of-two-lists_sort.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findRestaurant(vector& list1, vector& list2) { + vector res; + const int len1 = list1.size(); + const int len2 = list2.size(); + vector> kvVect; + + int indexSum = 0; + for (int i = 0; i < len1; i++) + { + auto it = find(list2.begin(), list2.end(), list1[i]); + if (it != list2.end()) + { + indexSum = it - list2.begin() + i; + kvVect.push_back({list1[i], indexSum}); + } + } + auto cmp = [](pair& p1, pair& p2) + { + if (p1.second == p2.second) + return p1.first < p2.first; + return p1.second < p2.second; + }; + sort(kvVect.begin(), kvVect.end(), cmp); + int minIndexSum = kvVect.front().second; + for (auto &kvp : kvVect) + { + if (kvp.second == minIndexSum) + res.push_back(kvp.first); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector list1 = {"Shogun","Tapioca Express","Burger King","KFC"}; + vector list2 = {"KFC","Burger King","Tapioca Express","Shogun"}; + auto res = sol.findRestaurant(list1, list2); + for (auto str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode6-zigzag-conversion-solution1.cpp b/cpp-leetcode/leetcode6-zigzag-conversion-solution1.cpp new file mode 100644 index 00000000..fb95e7ca --- /dev/null +++ b/cpp-leetcode/leetcode6-zigzag-conversion-solution1.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string convert(string s, int numRows) { + string res; + // base case + if (s.empty() || numRows <= 1) + return s; + + // handle first row + for (int i = 0; i < s.size(); i += (numRows - 1) * 2) + res.push_back(s[i]); + + // handle middle rows + for (int j = 1; j < numRows - 1; j++) + { + bool down = true; + for (int i = j; i < s.size();) // Since the step has two possible values, so not add increase logic here. + { + res.push_back(s[i]); // Add first element of current row, then add others + if (down) // going down + i += (numRows - 1 - j) * 2; + else // going up + i += 2*j; + + down = !down; // switch direction + } + } + + // handle last row + for (int i = numRows - 1; i < s.size(); i += (numRows - 1) * 2) + res.push_back(s[i]); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "PAYPALISHIRING"; + int numRows = 4; + auto res = sol.convert(s, numRows); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode6-zigzag-conversion-solution2.cpp b/cpp-leetcode/leetcode6-zigzag-conversion-solution2.cpp new file mode 100644 index 00000000..63dedd65 --- /dev/null +++ b/cpp-leetcode/leetcode6-zigzag-conversion-solution2.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +using namespace std; + +class Solution +{ +public: + string convert(string s, int numRows) + { + string res(s.size(), ' '); + if (s.empty() || numRows <= 1) + return s; + + int pos = 0; + for (int i = 0; i < numRows; i++) + { + int gap1 = 2 * (numRows - 1 - i); + int gap2 = 2 * i; + + int index = i; + while (pos < s.size()) + { + if (gap1 > 0) + { + if (index >= s.size()) + break; + res[pos++] = s[index]; // Add char row by row + index += gap1; + } + + if (gap2 > 0) + { + if (index >= s.size()) + break; + res[pos++] = s[index]; + index += gap2; + } + } + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "PAYPALISHIRING"; + int numRows = 4; + auto res = sol.convert(s, numRows); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode60-permutation-sequence_factorial.cpp b/cpp-leetcode/leetcode60-permutation-sequence_factorial.cpp new file mode 100644 index 00000000..8c6d30ec --- /dev/null +++ b/cpp-leetcode/leetcode60-permutation-sequence_factorial.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include /* 含memset */ +using namespace std; + +class Solution { +public: + string getPermutation(int n, int k) { + int f[n]; // 记录阶乘 n! 的结果 + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int i = 1; i < n; i++) + f[i] = i*f[i-1]; + vector digits; /* 1 <= n <= 9 */ + for (int i = 1; i <= n; i++) + digits.push_back(i); + + k--; // 1-indexed -> 0-indexed + string res = ""; + for (int i = n - 1; i >= 0; i--) + { + int index = k / f[i]; + res.push_back(digits[index] + '0'); + digits.erase(digits.begin() + index); + k = k % f[i]; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 4; + int k = 9; + auto res = sol.getPermutation(n, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode60-permutation-sequence_next_permutation1.cpp b/cpp-leetcode/leetcode60-permutation-sequence_next_permutation1.cpp new file mode 100644 index 00000000..033817ac --- /dev/null +++ b/cpp-leetcode/leetcode60-permutation-sequence_next_permutation1.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string getPermutation(int n, int k) { + string s(n, '0'); + + for (int i = 0; i < n; i++) + s[i] += i + 1; + for (int i = 0; i < k - 1; i++) + next_permutation(s.begin(), s.end()); + return s; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 4; + int k = 9; + auto res = sol.getPermutation(n, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode60-permutation-sequence_next_permutation2.cpp b/cpp-leetcode/leetcode60-permutation-sequence_next_permutation2.cpp new file mode 100644 index 00000000..01c298ca --- /dev/null +++ b/cpp-leetcode/leetcode60-permutation-sequence_next_permutation2.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string getPermutation(int n, int k) { + string res; + res.reserve(n); + for (int i = 1; i != n + 1; i++) + res.push_back(i + '0'); + while (--k) + next_permutation(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 4; + int k = 9; + auto res = sol.getPermutation(n, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp.cpp b/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp.cpp new file mode 100644 index 00000000..74f86530 --- /dev/null +++ b/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findIntegers(int n) { + vector f(32); + f[0] = 1; + f[1] = 2; + for (int i = 2; i < 32; i++) + f[i] = f[i - 1] + f[i - 2]; + string numStr = toBinary(n); + int res = 0; + for (int i = 0; i < numStr.size(); i++) { + if (numStr[i] == '0') /* 选出numStr[i] = '1'的digit */ + continue; + res += f[numStr.size() - i - 1]; + if (i != 0 && numStr[i - 1] == '1') + return res; + } + return res + 1; + } + string toBinary(long n) /* 非负整数转二进制表示的字符串 */ + { + string res = ""; + while (n > 0) + { + char r = n % 2 + '0'; + res.push_back(r); /* 放进去的结果会导致低位在前, 高位在后 */ + n /= 2; + } + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 666; + auto res = sol.findIntegers(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp_no_array_with_bit_operation.cpp b/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp_no_array_with_bit_operation.cpp new file mode 100644 index 00000000..a31d314c --- /dev/null +++ b/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp_no_array_with_bit_operation.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findIntegers(int num) { + int res = 0; + int preBit = 0; // 记录当前的digit是否为1 + int k = 30; // 指针k, 从二进制数的末位开始向前移动 + while (k >= 0) + { + if (num & (1 << k)) // 从低位向高位扫描, 判断第k位是否为1 + { + res += getF(k); + if (preBit) return res; // 出现了连续的1, 直接返回res + preBit = 1; // 当前digit是1, 于是将preBit更新为1 + } + else preBit = 0; + + --k; + } + return res + 1; // 算上 num 本身 + } + int getF(int k) /* 计算f(k) */ + { + int f_i_1 = 1, f_i_2 = 2, f_i_3 = 3; + if (k == 0) return f_i_1; + if (k == 1) return f_i_2; + for (int i = 2; i <= k; i++) /* 已知f1, 求fn总共需要迭代n-1+1-maxIndexGap(2) = n-2 次 */ + { + // f_n = f_n-1 + f_n-2 + f_i_3 = f_i_2 + f_i_1; + f_i_1 = f_i_2; + f_i_2 = f_i_3; + } + return f_i_3; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 666; + auto res = sol.findIntegers(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp_with_bit_operation.cpp b/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp_with_bit_operation.cpp new file mode 100644 index 00000000..acbb11e0 --- /dev/null +++ b/cpp-leetcode/leetcode600-non-negative-integers-without-consecutive-ones_dp_with_bit_operation.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findIntegers(int num) { + int f[32]; + f[0] = 1; + f[1] = 2; + for (int i = 2; i < 32; ++i) + f[i] = f[i - 1] + f[i - 2]; + int res = 0; + int preBit = 0; // 记录当前的digit是否为1 + int k = 30; // 指针k, 从二进制数的末位开始向前移动 + while (k >= 0) + { + if (num & (1 << k)) // 从低位向高位扫描, 判断第k位是否为1 + { + res += f[k]; + if (preBit) return res; // 出现了连续的1, 直接返回res + preBit = 1; // 当前digit是1, 于是将preBit更新为1 + } + else preBit = 0; + + --k; + } + return res + 1; // 算上 num 本身 + } +}; + +// Test +int main() +{ + Solution sol; + int n = 666; + auto res = sol.findIntegers(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode61-rotate-list_solution1.cpp b/cpp-leetcode/leetcode61-rotate-list_solution1.cpp new file mode 100644 index 00000000..01ca2045 --- /dev/null +++ b/cpp-leetcode/leetcode61-rotate-list_solution1.cpp @@ -0,0 +1,70 @@ +#include +using namespace std; +/** + * Definition for singly-linked list. +*/ +struct ListNode +{ + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution +{ +public: + ListNode *rotateRight(ListNode *head, int k) + { + if (head == NULL) + return head; + int len = 1; + ListNode *tail = head; + + /* while循环一次,得到长度len。这里tail是当前结点cur, 当tail的next为 NULL时, tail成为尾结点 */ + while (tail->next) + { + tail = tail->next; + ++len; + } + int shift = k % len; + if (shift == 0) + return head; + + ListNode* prev = head; + /* 再while循环一次, 迭代次数为 len - shift - 1, 结束时得到断开点的prev结点 */ + while (--len > shift) // 遍历 len - shift - 1 个结点 + { + prev = prev->next; + } + + ListNode* newHead = prev->next; + tail->next = head; + prev->next = NULL; + + return newHead; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = NULL; + + int k = 50; + ListNode *res = sol.rotateRight(head, k); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode611-valid-triangle-number_sort_and_two_pointers.cpp b/cpp-leetcode/leetcode611-valid-triangle-number_sort_and_two_pointers.cpp new file mode 100644 index 00000000..9061b07f --- /dev/null +++ b/cpp-leetcode/leetcode611-valid-triangle-number_sort_and_two_pointers.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int triangleNumber(vector& nums) { + // 先排序, 然后 a < b < c, 对应指针为 i,j,k, 固定k (k一开始=len-1, 最后k>=2), 剩下两个数用双指针找 + int len = nums.size(); + if (len < 3) return 0; + sort(nums.begin(), nums.end()); + int groupCount = 0; + for (int k = len - 1; k >= 2; k--) + { + int i = 0; + int j = k - 1; + while (i < j) + { + if (nums[i] + nums[j] > nums[k]) + { + groupCount += j - i; /* 对于每一趟(k确定时): 只要出现第1次满足要求的, 则只要j对应的数还在i对应数的右侧, 就可以继续统计。当 j = i+1时只要1组, 于是该情形下共有j-i组。最后把每一趟的组合数相加 */ + j--; + } + else i++; + } + } + return groupCount; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 2, 3, 4}; + auto res = sol.triangleNumber(nums); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode617-merge-two-binary-trees_recursive.cpp b/cpp-leetcode/leetcode617-merge-two-binary-trees_recursive.cpp new file mode 100644 index 00000000..1d222d82 --- /dev/null +++ b/cpp-leetcode/leetcode617-merge-two-binary-trees_recursive.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +// 递归解法 +class Solution { +public: + TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { + if (root1 == nullptr) return root2; + if (root2 == nullptr) return root1; + auto newRoot = new TreeNode(root1->val + root2->val); + newRoot->left = mergeTrees(root1->left, root2->left); + newRoot->right = mergeTrees(root1->right, root2->right); + return newRoot; + } +}; + +int main() +{ + Solution sol; + + TreeNode* root1 = new TreeNode(3); + root1->left = new TreeNode(4); + root1->right = new TreeNode(5); + root1->left->left = new TreeNode(1); + root1->left->right = new TreeNode(3); + root1->right->right = new TreeNode(1); + + TreeNode* root2 = new TreeNode(10); + root2->left = new TreeNode(5); + root2->right = new TreeNode(15); + root2->left->left = new TreeNode(3); + root2->right->right = new TreeNode(18); + + auto root = sol.mergeTrees(root1, root2); + cout << root->val << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode62-unique-paths_dp.cpp b/cpp-leetcode/leetcode62-unique-paths_dp.cpp new file mode 100644 index 00000000..f9ecddd0 --- /dev/null +++ b/cpp-leetcode/leetcode62-unique-paths_dp.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int uniquePaths(int m, int n) { + int dp[m][n]; // dp数组 - dp[i][j]: 从位置(0, 0)走到位置(i, j)的unique path的数量 + memset(dp, 0, sizeof(dp)); + dp[0][0] = 1; /* 原点位置(0, 0)只有不动这一种走法, 对矩阵中间某个位置 dp[i][j] = dp[i-1][j] + dp[i][j-1] */ + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (i >= 1) + dp[i][j] += dp[i-1][j]; + if (j >= 1) + dp[i][j] += dp[i][j-1]; + } + } + return dp[m - 1][n - 1]; + } +}; + +// Test +int main() +{ + Solution sol; + int m = 3; + int n = 7; + auto res = sol.uniquePaths(m, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode621-task-scheduler_hash_count1.cpp b/cpp-leetcode/leetcode621-task-scheduler_hash_count1.cpp new file mode 100644 index 00000000..c0d7c769 --- /dev/null +++ b/cpp-leetcode/leetcode621-task-scheduler_hash_count1.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int leastInterval(vector& tasks, int n) { + unordered_map dict; + int maxFreq = -1; + int maxFreqCount = 0; + for (auto& ch : tasks) + dict[ch]++; + for (auto& kvp : dict) + maxFreq = max(maxFreq, kvp.second); + for (auto& kvp : dict) + { + if (kvp.second == maxFreq) maxFreqCount++; + } + int res = 0; + const int len = tasks.size(); + res = max((maxFreq - 1)*(n+1) + maxFreqCount, len); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector tasks = {'A','A','A','B','B','B'}; + int n = 2; + auto res = sol.leastInterval(tasks, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode621-task-scheduler_hash_count2.cpp b/cpp-leetcode/leetcode621-task-scheduler_hash_count2.cpp new file mode 100644 index 00000000..87ddc667 --- /dev/null +++ b/cpp-leetcode/leetcode621-task-scheduler_hash_count2.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int leastInterval(vector& tasks, int n) { + vector dict(128); + int maxFreq = -1; + int maxFreqCount = 0; + for (auto& ch : tasks) + dict[ch]++; + for (auto& count : dict) + maxFreq = max(maxFreq, count); + for (auto& count : dict) + { + if (count == maxFreq) maxFreqCount++; + } + int res = 0; + const int len = tasks.size(); + res = max((maxFreq - 1)*(n+1) + maxFreqCount, len); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector tasks = {'A','A','A','B','B','B'}; + int n = 2; + auto res = sol.leastInterval(tasks, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode621-task-scheduler_hash_count3.cpp b/cpp-leetcode/leetcode621-task-scheduler_hash_count3.cpp new file mode 100644 index 00000000..2e546226 --- /dev/null +++ b/cpp-leetcode/leetcode621-task-scheduler_hash_count3.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int leastInterval(vector& tasks, int n) { + int dict[128]; + fill(dict, dict + 128, 0); + int maxFreq = -1; + int maxFreqCount = 0; + for (auto& ch : tasks) + dict[ch]++; + for (auto& count : dict) + maxFreq = max(maxFreq, count); + for (auto& count : dict) + { + if (count == maxFreq) maxFreqCount++; + } + int res = 0; + const int len = tasks.size(); + res = max((maxFreq - 1)*(n+1) + maxFreqCount, len); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector tasks = {'A','A','A','B','B','B'}; + int n = 2; + auto res = sol.leastInterval(tasks, n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode627-swap-salary_mysql1.sql b/cpp-leetcode/leetcode627-swap-salary_mysql1.sql new file mode 100644 index 00000000..7371443f --- /dev/null +++ b/cpp-leetcode/leetcode627-swap-salary_mysql1.sql @@ -0,0 +1,7 @@ +# Write your MySQL query statement below +UPDATE salary +set + sex = CASE + when sex= 'm' then 'f' + else 'm' + end; \ No newline at end of file diff --git a/cpp-leetcode/leetcode627-swap-salary_mysql2.sql b/cpp-leetcode/leetcode627-swap-salary_mysql2.sql new file mode 100644 index 00000000..36dc4ab0 --- /dev/null +++ b/cpp-leetcode/leetcode627-swap-salary_mysql2.sql @@ -0,0 +1,3 @@ +# Write your MySQL query statement below +UPDATE salary +SET sex=(IF(sex='f', 'm', 'f')) \ No newline at end of file diff --git a/cpp-leetcode/leetcode63-unique-paths-ii_dp.cpp b/cpp-leetcode/leetcode63-unique-paths-ii_dp.cpp new file mode 100644 index 00000000..d2f7b003 --- /dev/null +++ b/cpp-leetcode/leetcode63-unique-paths-ii_dp.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int uniquePathsWithObstacles(vector>& G) { + const int m = G.size(); + const int n = G[0].size(); + int dp[m][n]; // dp数组 - dp[i][j]: 从位置(0, 0)走到位置(i, j)的unique path的数量 + memset(dp, 0, sizeof(dp)); + dp[0][0] = 1; /* 原点位置(0, 0)只有不动这1种走法, 对矩阵中间某个位置 dp[i][j] = dp[i-1][j] + dp[i][j-1] */ + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (G[i][j] == 1) + dp[i][j] = 0; + else + { + if (i >= 1) + dp[i][j] += dp[i-1][j]; + if (j >= 1) + dp[i][j] += dp[i][j-1]; + } + } + } + return dp[m-1][n-1]; + } +}; + +// Test +int main() +{ + Solution sol; + vector> G = + { + {0, 0, 0}, + {0, 1, 0}, + {0, 0, 0} + }; + auto res = sol.uniquePathsWithObstacles(G); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode633-sum-of-square-numbers-solution1.cpp b/cpp-leetcode/leetcode633-sum-of-square-numbers-solution1.cpp new file mode 100644 index 00000000..74142e65 --- /dev/null +++ b/cpp-leetcode/leetcode633-sum-of-square-numbers-solution1.cpp @@ -0,0 +1,29 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool judgeSquareSum(int c) { + for (long i = 0; c - 2 * i * i >= 0; i++) /* 边界条件: 当i=2147482647(INT_MAX)时,如果用int,2 * i * i会越界,需改为 long */ + { + double diff = c - i*i; /* 做一次循环,用目标和减去循环变量的平方,如果剩下的部分依然是完全平方,开方上取整=开方下取整 即可 */ + if ((int)(ceil(sqrt(diff))) == (int)(floor(sqrt(diff)))) + return true; + } + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 666; + bool res = sol.judgeSquareSum(n); + + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode633-sum-of-square-numbers-solution2.cpp b/cpp-leetcode/leetcode633-sum-of-square-numbers-solution2.cpp new file mode 100644 index 00000000..1d0c5a76 --- /dev/null +++ b/cpp-leetcode/leetcode633-sum-of-square-numbers-solution2.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool judgeSquareSum(int c) { + for (long i = 0; c - 2 * i * i >= 0; i++) + { + int diff = c - i * i; + if (IsPerfectSquare(diff)) + return true; + } + + return false; + } + + bool IsPerfectSquare(int num) + { + double sq1 = sqrt(num); + int sq2 = (int)sqrt(num); + if (fabs(sq1 - (double)sq2) < 10e-10) + return true; + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 666; + bool res = sol.judgeSquareSum(n); + + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode633-sum-of-square-numbers_binary_search.cpp b/cpp-leetcode/leetcode633-sum-of-square-numbers_binary_search.cpp new file mode 100644 index 00000000..bc19ca6b --- /dev/null +++ b/cpp-leetcode/leetcode633-sum-of-square-numbers_binary_search.cpp @@ -0,0 +1,33 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool judgeSquareSum(int c) { + long long l = 0; + auto r = (long long)sqrt(c); + while (l <= r) + { + long long sum = l * l + r * r; + if (sum == c) return true; + + if (sum < c) l++; + else r--; + } + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 666; + bool res = sol.judgeSquareSum(n); + + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode638-shopping-offers_dfs_backtracking2.cpp b/cpp-leetcode/leetcode638-shopping-offers_dfs_backtracking2.cpp new file mode 100644 index 00000000..caf41b2e --- /dev/null +++ b/cpp-leetcode/leetcode638-shopping-offers_dfs_backtracking2.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { + int res = INT_MAX; + vector buy; +public: + int shoppingOffers(vector& price, vector>& special, vector& needs) { + buy.resize(needs.size(), 0); + dfs(price, special, needs, 0, 0); + return res; + } + void dfs(vector& price, vector>& special, vector& needs, int money, int index) + { + if (index == special.size()) + { //当遍历完大礼包数组时,判断当前选择是否更优惠 + int extra = 0; + for (int i = 0; i < needs.size(); i++) + { // 将buy数组补到与needs数组相同 + extra += (needs[i] - buy[i]) * price[i]; + } + res = min(res, money + extra); + return; + } + for (int i = index; i <= special.size(); i++) + { + int j = 0; + for (; j < needs.size() && i < special.size(); j++) + { // 判断该大礼包是否可选,当不会多买时,便可选 + if (buy[j] + special[i][j] > needs[j]) + break; + } + if (j == needs.size() || i == special.size()) + { + for (int j = 0; j < needs.size() && i < special.size(); j++) + { // 买入special[i][j]个j + buy[j] += special[i][j]; + } + if (i < special.size()) money += special[i][needs.size()]; // 花钱special[i][needs.size()]买下该大礼包 + dfs(price, special, needs, money, i); // 递归 + for (int j = 0; j < needs.size() && i < special.size(); j++) + { // 回溯退货 + buy[j] -= special[i][j]; + } + if (i < special.size()) money -= special[i][needs.size()]; // 回溯退款 + } + } + } +}; + +// Test +int main() +{ + Solution sol; + vector price = {2, 5}; + vector needs = {3, 2}; + vector> special = {{3, 0, 5}, {1, 2, 10}}; + auto res = sol.shoppingOffers(price, special, needs); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode638-shopping-offers_dfs_with_memorization.cpp b/cpp-leetcode/leetcode638-shopping-offers_dfs_with_memorization.cpp new file mode 100644 index 00000000..3620f06f --- /dev/null +++ b/cpp-leetcode/leetcode638-shopping-offers_dfs_with_memorization.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { + unordered_map memo; + int N; +public: + int shoppingOffers(vector& price, vector>& special, vector& needs) { + N = price.size(); + vector> specials; // 筛选出真正便宜的打包价 + for (int i = 0; i < special.size(); i++) + { + int sum = 0; + for (int j = 0; j < N; j++) + sum += special[i][j] * price[j]; + if (sum > special[i].back()) + specials.push_back(special[i]); + } + string key; + for (int i = 0; i < N; i++) + key += "0"; + memo[key] = 0; + + return dfs(price, specials, needs); + } + string getKey(vector &needs) + { + string key; + for (int i = 0; i < needs.size(); i++) + key += to_string(needs[i]); + return key; + } + int dfs(vector &price, vector> &specials, vector &needs) + { + string key = getKey(needs); + if (memo.find(key) != memo.end()) + return memo[key]; + + int res = INT_MAX; + int special_used = 0; + for (int i = 0; i < specials.size(); i++) + { + int canUse = 1; // canUse: 打包优惠能不能用, 当special的数量门槛高时无法使用 + for (int j = 0; j < N; j++) + { + if (specials[i][j] > needs[j]) + { + canUse = 0; + break; + } + } + if (canUse == 1) + { + special_used = 1; + vector needs_temp = needs; + for (int j = 0; j < N; j++) + needs_temp[j] = needs[j] - specials[i][j]; + res = min(res, specials[i][N] + dfs(price, specials, needs_temp)); + } + } + if (special_used == 0) + { + res = 0; + for (int i = 0; i < N; i++) + res += price[i] * needs[i]; + } + memo[key] = res; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector price = {2, 5}; + vector needs = {3, 2}; + vector> special = {{3, 0, 5}, {1, 2, 10}}; + auto res = sol.shoppingOffers(price, special, needs); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode64-minimum-path-sum_dp1_using_array.cpp b/cpp-leetcode/leetcode64-minimum-path-sum_dp1_using_array.cpp new file mode 100644 index 00000000..beda5bde --- /dev/null +++ b/cpp-leetcode/leetcode64-minimum-path-sum_dp1_using_array.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int minPathSum(vector>& grid) { + const int M = grid.size(); + const int N = grid[0].size(); + int dp[M][N]; + for (auto& row : dp) + fill(row, row + N, 0); + for (int i = 0; i < M; i++) + { + for (int j = 0; j < N; j++) + { + if (i == 0 && j == 0) + dp[i][j] = grid[0][0]; + else if (i == 0) + dp[i][j] = dp[0][j - 1] + grid[0][j]; + else if (j == 0) + dp[i][j] = dp[i - 1][0] + grid[i][0]; + else dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + } + } + return dp[M - 1][N - 1]; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{1, 2, 3}, {4, 5, 6}}; + auto res = sol.minPathSum(grid); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode64-minimum-path-sum_dp1_using_vector.cpp b/cpp-leetcode/leetcode64-minimum-path-sum_dp1_using_vector.cpp new file mode 100644 index 00000000..4cd0fa5d --- /dev/null +++ b/cpp-leetcode/leetcode64-minimum-path-sum_dp1_using_vector.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int minPathSum(vector>& grid) { + const int M = grid.size(); + const int N = grid[0].size(); + vector> dp(M, vector(N, 0)); + for (int i = 0; i < M; i++) + { + for (int j = 0; j < N; j++) + { + if (i == 0 && j == 0) + dp[i][j] = grid[0][0]; + else if (i == 0) + dp[i][j] = dp[0][j - 1] + grid[0][j]; + else if (j == 0) + dp[i][j] = dp[i - 1][0] + grid[i][0]; + else dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + } + } + return dp[M - 1][N - 1]; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{1, 2, 3}, {4, 5, 6}}; + auto res = sol.minPathSum(grid); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode645-set-mismatch_bucket_sort.cpp b/cpp-leetcode/leetcode645-set-mismatch_bucket_sort.cpp new file mode 100644 index 00000000..b674ce54 --- /dev/null +++ b/cpp-leetcode/leetcode645-set-mismatch_bucket_sort.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + for (int i = 0; i < n; i++) + { + while (nums[i] != i + 1 && nums[nums[i] - 1] != nums[i]) /* 不断地swap, 把index是i的数放到合适的位置上, nums[nums[i] - 1] != nums[i] 表示遇到相等的数不需要swap, 否则会死循环 */ + { + swap(nums[i], nums[nums[i] - 1]); + } + } + int repeatNum = -1, missingNum = -1; + for (int i = 0; i < n; i++) + { + if (nums[i] != i + 1) + { + repeatNum = nums[i]; + missingNum = (i == 0) ? 1 : nums[i - 1] + 1; + } + } + return {repeatNum, missingNum}; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 2, 4}; + auto res = sol.findErrorNums(nums); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode645-set-mismatch_hash_set.cpp b/cpp-leetcode/leetcode645-set-mismatch_hash_set.cpp new file mode 100644 index 00000000..c1e52c6a --- /dev/null +++ b/cpp-leetcode/leetcode645-set-mismatch_hash_set.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findErrorNums(vector& nums) { + int len = nums.size(); + vector cmpList; + for (int i = 1; i <= len; i++) + cmpList.push_back(i); + auto sum1 = accumulate(nums.begin(), nums.end(), 0); + unordered_set set1(nums.begin(), nums.end()); + auto sum2 = accumulate(set1.begin(), set1.end(), 0); + int repeatedNum = sum1 - sum2; + int missingNum; + for (auto &k : cmpList) + { + if (set1.count(k) == 0) + { + missingNum = k; + break; + } + } + + return {repeatedNum, missingNum}; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 2, 4}; + auto res = sol.findErrorNums(nums); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode645-set-mismatch_hashmap.cpp b/cpp-leetcode/leetcode645-set-mismatch_hashmap.cpp new file mode 100644 index 00000000..7c2d3081 --- /dev/null +++ b/cpp-leetcode/leetcode645-set-mismatch_hashmap.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + unordered_map dict; // map: value -> count + for (int i = 1; i <= n; i++) + dict[i] = 0; + for (auto& curNum : nums) + { + if (dict.count(curNum) == 0) dict[curNum] = 1; + else dict[curNum]++; + } + int missingNum, repeatNum; + for (auto& kvp : dict) + { + if (kvp.second == 0) missingNum = kvp.first; + if (kvp.second == 2) repeatNum = kvp.first; + } + return {repeatNum, missingNum}; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 2, 4}; + auto res = sol.findErrorNums(nums); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode647-palindromic-substrings_brute_force.cpp b/cpp-leetcode/leetcode647-palindromic-substrings_brute_force.cpp new file mode 100644 index 00000000..9ee46b07 --- /dev/null +++ b/cpp-leetcode/leetcode647-palindromic-substrings_brute_force.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int countSubstrings(string s) { + int N = s.size(); + int count = 0; + for (int i = 0; i < N; i++) + { + for (int j = i; j < N; j++) + { + int curLen = j - i + 1; + if (isValidPar(s.substr(i, curLen))) + count++; + } + } + return count; + } + bool isValidPar(string str) + { + string temp(str); + reverse(str.begin(), str.end()); + return temp == str; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abc"; + auto res = sol.countSubstrings(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode647-palindromic-substrings_dp.cpp b/cpp-leetcode/leetcode647-palindromic-substrings_dp.cpp new file mode 100644 index 00000000..dacdaaec --- /dev/null +++ b/cpp-leetcode/leetcode647-palindromic-substrings_dp.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int countSubstrings(string s) { + string t = "#"; + for (auto ch : s) + { + t.push_back(ch); + t.push_back('#'); + } + int n = t.size(); + vector P(n); + int maxCenter = -1; + int maxRight = -1; + for (int i = 0; i < n; i++) + { + int r; + if (i <= maxRight) + { + int j = maxCenter * 2 - i; + r = min(P[j], maxRight - i); + while (i - r >= 0 && i + r < n && t[i - r] == t[i + r]) + r++; + } + else + { + r = 0; + while (i - r >= 0 && i + r < n && t[i - r] == t[i + r]) + r++; + } + P[i] = r - 1; + if (i + P[i] > maxRight) + { + maxRight = i + P[i]; + maxCenter = i; + } + } + int res = 0; + for (int i = 0; i < n; i++) + { + res += (P[i] + 1) / 2; + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abc"; + auto res = sol.countSubstrings(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode647-palindromic-substrings_odd_even_enumeration1.cpp b/cpp-leetcode/leetcode647-palindromic-substrings_odd_even_enumeration1.cpp new file mode 100644 index 00000000..71313129 --- /dev/null +++ b/cpp-leetcode/leetcode647-palindromic-substrings_odd_even_enumeration1.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int countSubstrings(string s) { + int count = 0; + const int N = s.size(); + for (int i = 0; i < N; i++) // 枚举中心位置的index + { + // 枚举回文子串长度为奇数的情况 + for (int j = i, k = i; j >= 0 && k < N; j--, k++) /* 指针j(代表L)和k(代表R)是当前回文串的左右边界 */ + { + if (s[j] != s[k]) + break; + count++; + } + // 偶数情况 + for (int j = i, k = i + 1; j >= 0 && k < N; j--, k++) /* 指针j(代表L)和k(代表R)的起点距离为1 */ + { + if (s[j] != s[k]) + break; + count++; + } + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abc"; + auto res = sol.countSubstrings(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode647-palindromic-substrings_odd_even_enumeration2.cpp b/cpp-leetcode/leetcode647-palindromic-substrings_odd_even_enumeration2.cpp new file mode 100644 index 00000000..22d4d526 --- /dev/null +++ b/cpp-leetcode/leetcode647-palindromic-substrings_odd_even_enumeration2.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int countSubstrings(string s) { + int count = 0; + const int N = s.size(); + for (int i = 0; i < N; i++) + { + int len = 0; + // 长度为奇数时 + while (i - len >= 0 && i + len < N && s[i - len] == s[i + len]) + len++; + count += len; // 此时len = countOdd(满足条件的长度为奇数的回文子串的数量), len是对不同半径的计数器 + + len = 0; + // 长度为偶数时 + while (i - len >= 0 && i + 1 + len < N && s[i - len] == s[i + 1 + len]) + len++; + count += len; // 此时 len = countEven(满足条件的长度为偶数的回文子串的数量) + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "abc"; + auto res = sol.countSubstrings(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode65-valid-number-AC.cpp b/cpp-leetcode/leetcode65-valid-number-AC.cpp new file mode 100644 index 00000000..8cd12ac4 --- /dev/null +++ b/cpp-leetcode/leetcode65-valid-number-AC.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include /* 含有isdigit、isalpha等函数 */ +using namespace std; + +class Solution { +public: + // 有效数字格式如下 + // [+|-][数字][.][数字][e|E][数字] + bool isNumber(string s) { + bool success = false; // 最开始匹配失败 + int k = 0; + if (s[k] == '+' || s[k] == '-') k++; // 过滤+|- + while (isdigit(s[k])) // 不管前面是否有符号+|-,一旦有数字,至此一定是匹配成功的 + { + k++; + success = true; + } + if (s[k] == '.') k++; // 过滤. + while (isdigit(s[k])) // 不管前面是否匹配成功,如果这里有数字,那么至此也一定是匹配成功的,如+.9或-9等 + { + k++; + success = true; + } + if (!success) return false; // 至此,底数已经匹配完成,如果匹配失败后面就不用再进行了 + // 下面判断是否有指数 + if (s[k] == 'e' || s[k] == 'E') + { + k++, success = false; // 过滤 'e' 和 'E' + if (s[k] == '+' || s[k] == '-') k++; // 过滤 +|- + while (isdigit(s[k])) // 过滤数字 + { + k++; + success = true; + } + } + // 如何没有匹配到结尾了,说明是不合法数字 + if (k < s.length()) return false; + // 如果到了最后一位,看是否匹配成功 + return success; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "95a5453"; + auto res = sol.isNumber(s); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode650-2-keys-keyboard_dp.cpp b/cpp-leetcode/leetcode650-2-keys-keyboard_dp.cpp new file mode 100644 index 00000000..db6ad6af --- /dev/null +++ b/cpp-leetcode/leetcode650-2-keys-keyboard_dp.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minSteps(int n) { + vector dp(n + 1, INT_MAX); // dp[i]: 得到i个A的最少操作次数 + dp[1] = 0; + for (int i = 2; i <= n; i++) + { + for (int j = 2; j <= i; j++) + { + if (i % j != 0) continue; + int k = i / j; + dp[i] = min(dp[i], dp[k] + 1 + (j - 1)); + } + } + return dp[n]; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 10000; + auto res = sol.minSteps(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode650-2-keys-keyboard_dp_optimize_with_greedy.cpp b/cpp-leetcode/leetcode650-2-keys-keyboard_dp_optimize_with_greedy.cpp new file mode 100644 index 00000000..04166464 --- /dev/null +++ b/cpp-leetcode/leetcode650-2-keys-keyboard_dp_optimize_with_greedy.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minSteps(int n) { + vector dp(n + 1, INT_MAX); // dp[i]: 得到i个A的最少操作次数 + dp[1] = 0; + for (int i = 2; i <= n; i++) + { + for (int j = 2; j <= i; j++) + { + if (i % j != 0) continue; + int k = i / j; + dp[i] = min(dp[i], dp[k] + 1 + (j - 1)); + break; /* 用贪心思想优化 */ + } + } + return dp[n]; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 10000; + auto res = sol.minSteps(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode66-plus-one_iteration.cpp b/cpp-leetcode/leetcode66-plus-one_iteration.cpp new file mode 100644 index 00000000..5228de27 --- /dev/null +++ b/cpp-leetcode/leetcode66-plus-one_iteration.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector plusOne(vector& digits) { + const int len = digits.size(); + for(int i = len - 1; i >= 0; --i) + { + if(digits[i] == 9) + digits[i] = 0; + else { + digits[i] += 1; + return digits; // 发现不需要继续进位时, 直接返回 + } + if(digits.front() == 0) + digits.insert(digits.begin(), 1); + } + return digits; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + auto res = sol.plusOne(nums); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode662-maximum-width-of-binary-tree_add_lables_for_TreeNode.cpp b/cpp-leetcode/leetcode662-maximum-width-of-binary-tree_add_lables_for_TreeNode.cpp new file mode 100644 index 00000000..6e3f9129 --- /dev/null +++ b/cpp-leetcode/leetcode662-maximum-width-of-binary-tree_add_lables_for_TreeNode.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +using namespace std; + +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + if (!root) return 0; + queue> q; // 队列q: 存储TreeNode及其在满二叉树中对应的编号(从1开始, root编号为1) + q.push({root, 1}); + int res = -1; + while (!q.empty()) + { + int size = q.size(); + int baseTopNum = q.front().second; // Num表示No., 在这表示编号 + int curTopNum; + + for (int i = 0; i < size; i++) /* 这个size 不能直接取q.size(), 而是需要提前取到, 否则结果不对 */ + { + auto topKvp = q.front(); + q.pop(); + auto topNode = topKvp.first; + curTopNum = topKvp.second; + auto p = curTopNum - baseTopNum + 1; // 计算出当前队头queue_front处的结点编号 + if (topNode->left) + q.push({topNode->left, p * 2}); + if (topNode->right) + q.push({topNode->right, p * 2 + 1}); + } + res = max(res, curTopNum - baseTopNum + 1); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + TreeNode *n1 = new TreeNode(3); + TreeNode *n2 = new TreeNode(6); + TreeNode *n3 = new TreeNode(3); + TreeNode *n4 = new TreeNode(5); + root->left = n1; + root->right = n2; + n1->left = n3; + n1->right = n4; + n3->left = NULL; + n3->right = NULL; + n4->left = NULL; + n4->right = NULL; + + auto res = sol.widthOfBinaryTree(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode67-add-binary.cpp b/cpp-leetcode/leetcode67-add-binary.cpp new file mode 100644 index 00000000..8e5c44f9 --- /dev/null +++ b/cpp-leetcode/leetcode67-add-binary.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string addBinary(string a, string b) { + string res; + int i = a.size() - 1; + int j = b.size() - 1; + int carry = 0; + while (i >= 0 || j >= 0) // 双指针, 让两个数的末位对齐, 两个指针 i, j均从末尾开始走 + { + int digitA = i >= 0 ? a[i--] - '0' : 0; + int digitB = j >= 0 ? b[j--] - '0' : 0; + int sum = digitA + digitB + carry; + carry = sum >= 2 ? 1 : 0; + sum = sum >= 2 ? sum - 2 : sum; + res.append(to_string(sum)); + } + if (carry == 1) + res.append("1"); + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string a = "1010", b = "111"; + auto res = sol.addBinary(a, b); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode670-maximum-swap.cpp b/cpp-leetcode/leetcode670-maximum-swap.cpp new file mode 100644 index 00000000..55d9b64d --- /dev/null +++ b/cpp-leetcode/leetcode670-maximum-swap.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int maximumSwap(int num) { + string str = to_string(num); + vector lastDict(10, 0); + for (int i = 0; i < str.size(); ++i) { + lastDict[str[i] - '0'] = i; // 记录每个数最后出现位置的索引 + } + /* 双指针,一个从原数字的头部开始,一个从索引表的末尾开始 */ + for (int i = 0; i < str.size(); ++i) { /* 从原数字的头部向后扫,保证了尽量是高位 */ + for (int k = 9; k > str[i] - '0'; k--) { /* 从dict的尾部向前扫,保证了尽量靠后且最大 */ + if (lastDict[k] > i) /* 最大数字可能不止出现一次,希望能跟较低位的最大数交换 */ + { + swap(str[i], str[lastDict[k]]); + return stoi(str); + } + } + } + + return num; + } +}; + +// Test +int main() +{ + Solution sol; + int num = 2736; + int res = sol.maximumSwap(num); + cout << res < +#include +#include +using namespace std; + +class Solution { +public: + int findNumberOfLIS(vector& nums) { + int N = nums.size(); + vector> table(N, vector{}); + vector> paths; + vector q; /* q: 数组模拟队列, 存 LIS 中的数 */ + int i, j, k, res = 0; + for (auto& num : nums) + { + i = lower_bound(q.begin(), q.end(), num) - q.begin(); + k = 1; + if (i > 0) + { + j = upper_bound(table[i - 1].begin(), table[i - 1].end(), -num) - table[i - 1].begin(); + k = paths[i - 1].back() - paths[i - 1][j]; + } + table[i].push_back(-num); + + if (i == q.size()) + { + q.push_back(num); + paths.push_back({0, k}); + } + else + { + q[i] = num; + paths[i].push_back(paths[i].back() + k); + } + } + return paths.back().back(); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 5, 4, 7}; + auto res = sol.findNumberOfLIS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_binary_search_twice_and_dp.cpp b/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_binary_search_twice_and_dp.cpp new file mode 100644 index 00000000..fe56ca14 --- /dev/null +++ b/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_binary_search_twice_and_dp.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findNumberOfLIS(vector& nums) { + if (nums.empty()) return 0; + const int N = nums.size(); + + vector>> dp(N + 1); /* dp table */ + int curMaxLen = 0; + for (int i = 0; i < N; i++) + { + // bsearch insertion point + int L = 0, R = curMaxLen; + while (L < R) + { + int mid = L + (R - L) / 2; + if (dp[mid].back().first < nums[i]) + L = mid + 1; + else R = mid; + } + // bsearch number of options + int options = 1; + int row = L - 1; + if (row >= 0) + { + int L1 = 0, R1 = dp[row].size(); + while (L1 < R1) + { + int mid = L1 + (R1 - L1) / 2; + if (dp[row][mid].first < nums[i]) + R1 = mid; + else L1 = mid + 1; + } + options = dp[row].back().second; + options -= (L1 == 0) ? 0 : dp[row][L1 - 1].second; + } + + dp[L].push_back({nums[i], dp[L].empty() ? options : dp[L].back().second + options}); + if (L == curMaxLen) curMaxLen++; + } + return dp[curMaxLen - 1].back().second; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 5, 4, 7}; + auto res = sol.findNumberOfLIS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_dp_2d_array.cpp b/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_dp_2d_array.cpp new file mode 100644 index 00000000..4588523b --- /dev/null +++ b/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_dp_2d_array.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findNumberOfLIS(vector& nums) { + int N = nums.size(); + // dp[i][0] -> LIS 的长度 + // dp[i][1] -> 同一长度的LIS 的个数 + vector > dp(N, vector(2, 1)); + int maxLen = 1; + for (int i = 0; i < N; i++) + { + for (int j = i + 1; j < N; j++) + { + if (nums[j] > nums[i]) + { + if (dp[i][0] + 1 > dp[j][0]) /* 新来的数nums[j]是否能使得LIS的长度+1? */ + { + dp[j][0] = dp[i][0] + 1; + // 下面这行容易忘记(dp[j][1]的初始值是1, 需要先更新为当前LIS的个数) + dp[j][1] = dp[i][1]; + maxLen = max(maxLen, dp[j][0]); + } + else if (dp[i][0] + 1 == dp[j][0]) + dp[j][1] += dp[i][1]; + } + } + } + int count = 0; + for (int i = 0; i < N; i++) + { + if (dp[i][0] == maxLen) + count += dp[i][1]; + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 5, 4, 7}; + auto res = sol.findNumberOfLIS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_dp_using_pair.cpp b/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_dp_using_pair.cpp new file mode 100644 index 00000000..18be2665 --- /dev/null +++ b/cpp-leetcode/leetcode673-number-of-longest-increasing-subsequence_dp_using_pair.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int findNumberOfLIS(vector& nums) { + int N = nums.size(); + int res = 0; + int maxLen = 0; + vector> dp(N, {1, 1}); /* dp[i]: pair of {以nums[i]结尾的LIS的长度, 以nums[i]结尾的LIS 的数量} */ + for (int i = 0; i < N; i++) + { + for (int j = 0; j < i; j++) + { + if (nums[i] > nums[j]) + { + if (dp[i].first == dp[j].first + 1) + dp[i].second += dp[j].second; + if (dp[j].first + 1 > dp[i].first) + dp[i] = {dp[j].first + 1, dp[j].second}; + } + } + if (maxLen == dp[i].first) res += dp[i].second; + if (maxLen < dp[i].first) + { + maxLen = dp[i].first; + res = dp[i].second; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 3, 5, 4, 7}; + auto res = sol.findNumberOfLIS(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode677-map-sum-pairs_hashmap.cpp b/cpp-leetcode/leetcode677-map-sum-pairs_hashmap.cpp new file mode 100644 index 00000000..18dd6186 --- /dev/null +++ b/cpp-leetcode/leetcode677-map-sum-pairs_hashmap.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class MapSum { + unordered_map dict; +public: + /** Initialize your data structure here. */ + MapSum() { + } + + void insert(string key, int val) { + if (dict.count(key) == 0) + dict[key] = val; + else dict[key] = val; + } + + int sum(string prefix) { + int sum = 0; + for (auto& kvp : dict) + { + if (kvp.first.find(prefix) != string::npos && kvp.first.find(prefix) == 0) /* 需要是前缀, 而不仅仅是子串 */ + sum += kvp.second; + } + return sum; + } +}; + +// Test +int main() +{ + MapSum* map = new MapSum(); + map->insert("apple",3); + int sum1 = map->sum("ap"); + cout << sum1 << endl; + map->insert("app",2); + sum1 = map->sum("ap"); + cout << sum1 << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode678-valid-parenthesis-string_stack_two_pass.cpp b/cpp-leetcode/leetcode678-valid-parenthesis-string_stack_two_pass.cpp new file mode 100644 index 00000000..62da43b6 --- /dev/null +++ b/cpp-leetcode/leetcode678-valid-parenthesis-string_stack_two_pass.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool checkValidString(string s) + { + vector st; + int stars = 0; + for (char ch : s) + { + if (ch == '(' || ch == '*') + { + st.push_back(ch); + if (ch == '*') stars++; + } + else // ch == ')' + { + if (st.empty()) return false; + bool seenLeft = false; // 策略: 尽可能拿左括号去与当前的字符ch(右括号)做匹配, 因为后期*可以代表空串, 也可代表右括号, 所以*的作用是很大的, 我们这里先尽量使用左括号。bool值seenLeft记录从后向扫描字符串s时是否出现了左括号 */ + int size = st.size(); + for (int i = size - 1; i >= 0; i--) /* 从后向前扫描字符串s, 试着找与当前的字符ch(右括号)匹配的左括号( */ + { + if (st[i] == '(') /* 从后向前扫描字符串s, 试着找左括号(, 出现1个左括号说明能匹配上, 将其删掉后break */ + { + seenLeft = true; + st.erase(st.begin() + i); + break; + } + } + if (!seenLeft) /* 如果字符串s中不存在左括号(全是*), 就使用一个潜在的左括号*充当左括号, 依然能匹配上, 用完后将其删掉 */ + { + st.pop_back(); + stars--; + } + } + } + + int size = st.size(); + stars = 0; + for (int i = size - 1; i >= 0; i--) // 再一次从后向扫描字符串s, 这次遍历的目标的判断左括号 + { + if (st[i] == '(') /* 合法情况是: 左括号数量>=右括号数量, 否则非法 */ + { + if (stars <= 0) // 当前字符是左括号(, 急需一个*充当右括号)与之匹配一下, 不够匹配就返回false + return false; + stars--; // 能匹配上, 就抵消掉一个* + } + else // st[i] == '*', *不影响结果 + stars++; + } + return true; + } +}; + +//Test +int main() +{ + Solution sol; + string str = "(*))"; + bool res = sol.checkValidString(str); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode678-valid-parenthesis-string_two_counters.cpp b/cpp-leetcode/leetcode678-valid-parenthesis-string_two_counters.cpp new file mode 100644 index 00000000..ea0b4322 --- /dev/null +++ b/cpp-leetcode/leetcode678-valid-parenthesis-string_two_counters.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool checkValidString(string s) + { + int countMin = 0; // 未匹配上的左括号的最小数量,对应的策略是将*尽量用作右括号) + int countMax = 0; // 未匹配上的左括号的最大数量, 对应的策略是将*尽量用作左括号( + // 未匹配上的左括号的数量可以用区间[countMin, countMax]表示 + + for (auto& ch : s) + { + if (ch == '(') + { + countMin++; + countMax++; + } + else if (ch == '*') + { + countMin--; + countMax++; + } + else if (ch == ')') + { + countMin--; + countMax--; + } + + if (countMax < 0) return false; + if (countMin < 0) countMin = 0; // 没办法完全按对应的最佳策略进行, 让步一下, 用掉一个星号* + } + /* 遍历完时, [countMin, countMax] ≥ 0, 最终要求左右括号平衡, 那么此区间需要包含一个 count = 0的状态, 那么countMin必须为0 */ + return countMin == 0; + } +}; + +//Test +int main() +{ + Solution sol; + string str = "(*))"; + bool res = sol.checkValidString(str); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode678-valid-parenthesis-string_two_counters2.cpp b/cpp-leetcode/leetcode678-valid-parenthesis-string_two_counters2.cpp new file mode 100644 index 00000000..6bf599ca --- /dev/null +++ b/cpp-leetcode/leetcode678-valid-parenthesis-string_two_counters2.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool checkValidString(string s) { + int maxDiff = 0, minDiff = 0; + // Diff 表示 左括号数量 - 右括号数量, maxDiff表示其最大值, minDiff表示其最小值 + for (int i = 0; i < s.length(); i++) + { + maxDiff += (s[i] == '(' || s[i] == '*') ? 1 : -1; + minDiff += (s[i] == ')' || s[i] == '*') ? -1 : 1; + if (maxDiff < 0) return false; + minDiff = std::max(0, minDiff); + } + return minDiff == 0; + } +}; + +//Test +int main() +{ + Solution sol; + string str = "(*))"; + bool res = sol.checkValidString(str); + cout << (res == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode68-text-justification_simulation1.cpp b/cpp-leetcode/leetcode68-text-justification_simulation1.cpp new file mode 100644 index 00000000..5fe4e54a --- /dev/null +++ b/cpp-leetcode/leetcode68-text-justification_simulation1.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector fullJustify(vector& words, int maxWidth) { + vector res; + int n = words.size(); + int p = 0; // p: word index + while (p < n) + { + int j = p + 1; + int curLen = words[p].size(); + // check 每一行, 如果这些单词形成的串长度超过maxWidth, 直接 break, 否则继续添加 + while (j < n) + { + int totalLen = curLen + 1 + words[j].size(); // 相邻两个单词至少要保证有1个空格 + if (totalLen > maxWidth) break; + curLen = totalLen; // 否则更新 curLen 并 check 下一个 + j++; + } + if (j == p + 1) // 当前行只有一个单词时, 左对齐并补全空格 + { + string lineStr = words[p]; + if (maxWidth > curLen) + appendSpaces(lineStr, maxWidth - curLen); + res.push_back(lineStr); + } + else + { + string curLine = ""; + int remainSpCount = maxWidth - curLen; // remainSpCount:最后一处填充空格数 + int partsCount = j - 1 - p; /* partsCount: 单词之间能填充连续空格的位置个数(单词数 - 1) */ + if (j == n) /* 如果是最后一行, 左对齐, 且单词之间只能填充一个空格, 末尾填充剩余空格数 */ + { + for (int i = 0; i <= partsCount; i++) + { + curLine.append(words[p + i]); + if (i < partsCount) curLine.push_back(' '); + } + appendSpaces(curLine, remainSpCount); + } + else + { // 非最后一行且有多个单词, aveSpCount: 单词之间平均填充空格数 + int aveSpCount = remainSpCount / partsCount; + remainSpCount -= aveSpCount * partsCount; + for (int i = 0; i <= partsCount; i++) + { + curLine.append(words[p + i]); + if (i < remainSpCount) appendSpaces(curLine, aveSpCount + 2); + else if (i < partsCount) appendSpaces(curLine, aveSpCount + 1); + } + } + res.push_back(curLine); + } + p = j; + } + return res; + } + void appendSpaces(string& s, int n) + { + s.insert(s.end(), n, ' '); + } +}; + +// Test +int main() +{ + Solution sol; + vector words = {"This", "is", "an", "example", "of", "text", "justification."}; + int maxWidth = 16; + auto res = sol.fullJustify(words, maxWidth); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode688-knight-probability-in-chessboard_dp1.cpp b/cpp-leetcode/leetcode688-knight-probability-in-chessboard_dp1.cpp new file mode 100644 index 00000000..0f930455 --- /dev/null +++ b/cpp-leetcode/leetcode688-knight-probability-in-chessboard_dp1.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include /* std::memset在这个头文件中 */ +using namespace std; + +double f[25][25][101]; /* dp[i][j][k]: 跳k 步后到达格子(i,j), 此时继续按"日"字向前跳, 跳到大K步时留在棋盘上的概率之和(走法的总概率)。 */ +class Solution { +public: + double knightProbability(int N, int K, int r, int c) { + memset(f, 0.0, sizeof(f)); + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + f[i][j][K] = 1; /* 预处理边界 */ + int dx[] = {-2,-1,1,2,2,1,-1,-2}; /* 8组方向向量 */ + int dy[] = {1,2,2,1,-1,-2,-2,-1}; + for (int k = K - 1; k >= 0; k--) + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + for (int u = 0; u < 8; u++) /* 枚举8个方向, 累加其中合法方向的概率 */ + { + int x = i + dx[u], y = j + dy[u]; + if (x >= 0 && x < N && y >= 0 && y < N) + f[i][j][k] += f[x][y][k+1] / 8; + } + return f[r][c][0]; + } +}; + +// Test +int main() +{ + Solution sol; + int N = 3; + int K = 2; + int r = 0; + int c = 0; + auto res = sol.knightProbability(N, K, r, c); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode688-knight-probability-in-chessboard_dp2.cpp b/cpp-leetcode/leetcode688-knight-probability-in-chessboard_dp2.cpp new file mode 100644 index 00000000..ac6ced56 --- /dev/null +++ b/cpp-leetcode/leetcode688-knight-probability-in-chessboard_dp2.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include /* std::memset在这个头文件中 */ +#include +using namespace std; + +class Solution { +public: + double knightProbability(int N, int K, int r, int c) { + vector> dp0(N, vector(N, 0.0)); + dp0[r][c] = 1.0; + int dirs[8][2] = {{1, 2}, {-1, -2}, {1, -2}, {-1, 2}, + {2, 1}, {-2, -1}, {2, -1}, {-2, 1}}; + for (int k = 0; k < K; k++) + { + vector> dp1(N, vector(N, 0.0)); + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + for (int m = 0; m < 8; m++) + { + int x = j + dirs[m][0]; + int y = i + dirs[m][1]; + if (x < 0 || y < 0 || x >= N || y >= N) continue; + dp1[i][j] += dp0[y][x]; + } + std::swap(dp0, dp1); + } + double res = 0; + for (int i = 0; i < N; ++i) + for (int j = 0; j < N; ++j) + res += dp0[i][j]; + + return res / pow(8, K); + } +}; + +// Test +int main() +{ + Solution sol; + int N = 3; + int K = 2; + int r = 0; + int c = 0; + auto res = sol.knightProbability(N, K, r, c); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode69-sqrtx_Newton_method.cpp b/cpp-leetcode/leetcode69-sqrtx_Newton_method.cpp new file mode 100644 index 00000000..c7634148 --- /dev/null +++ b/cpp-leetcode/leetcode69-sqrtx_Newton_method.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int mySqrt(int x) { + const int eps = 1e-7; + if (x == 0) return 0; + double preX = 0; /* preX是区间的边界bound之一, 特定情况下preX和nextX(变量名末尾的X表示横坐标)可能会左右互换. 在区间[0, 1]上开始找,不断调整区间的边界 */ + double nextX = 1; + while (nextX - preX > eps || preX - nextX > eps) + { + preX = nextX; + nextX = (nextX + x / nextX) / 2.0; + } + return (int)nextX; // 转 int + } +}; + +// Test +int main() +{ + Solution sol; + int num = 666; + auto res = sol.mySqrt(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode69-sqrtx_binary_search.cpp b/cpp-leetcode/leetcode69-sqrtx_binary_search.cpp new file mode 100644 index 00000000..b9ac951f --- /dev/null +++ b/cpp-leetcode/leetcode69-sqrtx_binary_search.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int mySqrt(int x) { + // 二分搜索 + int l = 0, r = x; + while (l < r) + { + auto mid = (l + (long long)r + 1)/2; + // check(性质): t^2 <= x + if (mid <= x/mid) /* 防止溢出 */ + l = mid; + else r = mid - 1; + } + return l; // 或 r, 循环结束时 l = r + } +}; + +// Test +int main() +{ + Solution sol; + int num = 666; + auto res = sol.mySqrt(num); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode695-max-area-of-island_flood_fill_dfs1.cpp b/cpp-leetcode/leetcode695-max-area-of-island_flood_fill_dfs1.cpp new file mode 100644 index 00000000..6f67674f --- /dev/null +++ b/cpp-leetcode/leetcode695-max-area-of-island_flood_fill_dfs1.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +using namespace std; + +class Solution { + int dx[4] = {-1, 0, 1, 0}; + int dy[4] = {0, 1, 0, -1}; + int m, n; +public: + int maxAreaOfIsland(vector>& grid) { + m = grid.size(); + n = grid[0].size(); + int res = 0; + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (grid[i][j] == 1) + res = max(res, dfs(grid, i, j)); + } + } + return res; + } + int dfs(vector>& grid, int x, int y) /* G[i][j] == 1时才调用dfs */ + { + int res = 1; // 把当前格子加进来 + grid[x][y] = 0; /* 加完之后就将用水(0)代替之前的陆地(1), 目的是避免重复访问。用这种方法就不需要使用visited数组记录状态了 */ + for (int i = 0; i < 4; i++) + { + auto a = x + dx[i]; + auto b = y + dy[i]; + if (a >= 0 && a < m && b >= 0 && b < n) // 确保没越界 + { + if (grid[a][b] == 1) + res += dfs(grid, a, b); // 把连通块数累加一下 + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = + { + {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, + {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0}, + {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0} + }; + auto res = sol.maxAreaOfIsland(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode695-max-area-of-island_flood_fill_dfs2.cpp b/cpp-leetcode/leetcode695-max-area-of-island_flood_fill_dfs2.cpp new file mode 100644 index 00000000..6f183634 --- /dev/null +++ b/cpp-leetcode/leetcode695-max-area-of-island_flood_fill_dfs2.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +using namespace std; + +class Solution { + int dx[4] = {-1, 0, 1, 0}; + int dy[4] = {0, 1, 0, -1}; + int m, n; +public: + int maxAreaOfIsland(vector>& grid) { + m = grid.size(); + n = grid[0].size(); + int res = 0; + /* 由于1 <= m, n <= 50, 故不需要判空 */ + int maxArea = 0; + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + maxArea = max(maxArea, dfs(grid, i, j)); + } + return maxArea; + } + int dfs(vector>& grid, int x, int y) + { + // 判断当前传入坐标位置是否越界或是否为水域 + if(x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0) + return 0; + + grid[x][y] = 0; // 已访问过的岛屿也修改为0,避免重复访问 + int area = 1; // 每个岛屿的面积为1 + for (int i = 0; i < 4; i++) + { + auto a = x + dx[i]; + auto b = y + dy[i]; + area += dfs(grid, a, b); + } + return area; + } +}; + +// Test +int main() +{ + Solution sol; + vector> grid = + { + {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, + {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0}, + {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0} + }; + auto res = sol.maxAreaOfIsland(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode7-reverse-integer.cpp b/cpp-leetcode/leetcode7-reverse-integer.cpp new file mode 100644 index 00000000..073bde5c --- /dev/null +++ b/cpp-leetcode/leetcode7-reverse-integer.cpp @@ -0,0 +1,30 @@ +#include +#include +using namespace std; + +class Solution { +public: + int reverse(int x) { + int sign = 1; + if(x < 0) + sign = -1; + string str = to_string(x); + std::reverse(str.begin(), str.end()); /* Leetcode的C++编译环境中出现了多个reverse函数,无法准确匹配到,所以需要加上std命名空间。 */ + long res = stol(str); /* 如果reverse后得到的字符串末尾有-,会在这里自动删除 */ + if(res < INT_MIN || res > INT_MAX) + return 0; + + return sign*res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = -666666666; + auto res = sol.reverse(n); + cout << res << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search1.cpp b/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search1.cpp new file mode 100644 index 00000000..f5f00cdc --- /dev/null +++ b/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search1.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + const int N = nums.size(); + sort(begin(nums), end(nums)); + int left = 0; // 当前的最小距离可能是(有相等的数时), 也可能不是0, 搜索区间的起点从0开始比较稳妥 + int right = nums[N - 1] - nums[0]; // 最大距离 + while (left < right) + { + int guess = left + (right - left) / 2; // guess: mid + if (possible(nums, guess, k)) + right = guess; + else + left = guess + 1; + } + return left; + } + bool possible(vector& nums, int d, int k) + { + const int N = nums.size(); + long count = 0; + int i = 0, j = 0; + while (i < N || j < N) + { + while (j < N && nums[j] - nums[i] <= d) j++; + count += j - i - 1; + i++; + } + return count >= k; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 6, 1}; + int k = 3; + auto res = sol.smallestDistancePair(nums, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search2.cpp b/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search2.cpp new file mode 100644 index 00000000..4096f04b --- /dev/null +++ b/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search2.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + sort(nums.begin(), nums.end()); + const int N = nums.size(); + int left = 0, right = nums[N - 1] - nums[0]; + while (left < right) + { + int mid = (right - left) / 2 + left; + int count = 0; + int i = 0; + for (int j = 0; j < N; j++) + { + while (nums[j] - nums[i] > mid) + i++; + count += j - i; + } + if (count >= k) + right = mid; + else + left = mid + 1; + } + return left; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 6, 1}; + int k = 3; + auto res = sol.smallestDistancePair(nums, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search3.cpp b/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search3.cpp new file mode 100644 index 00000000..43048e25 --- /dev/null +++ b/cpp-leetcode/leetcode719-find-k-th-smallest-pair-distance_sort_and_binary_search3.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + const int N = nums.size(); + sort(begin(nums), end(nums)); + int left = 0; // 当前的最小距离可能是(有相等的数时), 也可能不是0, 搜索区间的起点从0开始比较稳妥 + int right = nums[N - 1] - nums[0]; // 最大距离 + while (left < right) + { + int guess = left + (right - left) / 2; // guess: mid + if (possible(nums, guess, k)) + right = guess; + else + left = guess + 1; + } + return left; + } + bool possible(vector& nums, int d, int k) + { + const int N = nums.size(); + long count = 0; // count可能会超过2^31, 故用long存储比较稳妥 + int i = 0, j = 0; + while (i < N || j < N) + { + while (j < N && nums[j] - nums[i] <= d) j++; + count += j - i - 1; + i++; + } + return count >= k; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 6, 1}; + int k = 3; + auto res = sol.smallestDistancePair(nums, k); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode720-longest-word-in-dictionary_hashset_and_pruning.cpp b/cpp-leetcode/leetcode720-longest-word-in-dictionary_hashset_and_pruning.cpp new file mode 100644 index 00000000..04a7c061 --- /dev/null +++ b/cpp-leetcode/leetcode720-longest-word-in-dictionary_hashset_and_pruning.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string longestWord(vector& words) { + if (words.empty()) return ""; + + string best = ""; // best表示当前最长目标词 + unordered_set st(words.begin(), words.end()); // 取出所有的key 放进 set + + for (auto& word : words) + { + if ((word.size() < best.size()) || (word.size() == best.size() && word > best)) /* word > best 表示按题意来的留下字典序小的, 删掉字典序较大的 */ + continue; /* 剪枝 pruning */ + + bool isValid = true; + string prefix; + for (int i = 0; i < word.length() - 1 && isValid; i++) + { + prefix.push_back(word[i]); + if (st.count(prefix) == 0) /* 如果一直有效, 其子串应该一直在set中 */ + isValid = false; + } + if (isValid) + best = word; + } + + return best; + } +}; + +// Test +int main() +{ + Solution sol; + vector words = { "a", "banana", "app", "appl", "ap", "apply", "apple" }; + // vector words = { "yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y" }; + // vector words = { "r","kt","jtgt","j","jtg","rdwy","chkext","c","l","zo","lnp","k","jt","chke","ktui","rd","jtgtha","ch","chkex" }; + // vector words = {"b", "br", "bre", "brea", "break", "breakf", "breakfa", "breakfas", "breakfast", "l", "lu", "lun", "lunc", "lunch", "d", "di", "din", "dinn", "dinne", "dinner"}; + auto res = sol.longestWord(words); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode720-longest-word-in-dictionary_hashset_and_sort.cpp b/cpp-leetcode/leetcode720-longest-word-in-dictionary_hashset_and_sort.cpp new file mode 100644 index 00000000..93181c26 --- /dev/null +++ b/cpp-leetcode/leetcode720-longest-word-in-dictionary_hashset_and_sort.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string longestWord(vector& words) { + if (words.empty()) return ""; + /* 按单词长度排序, 当发现长度相等的, 把字典序小的放靠前一点 */ + auto cmp = [](const string& s1, const string& s2) + { /* 注意: 签名使用const string& 代替string会变快一点 */ + if (s1.size() != s2.size()) + return s1.size() > s2.size(); + return s1 < s2; + }; + sort(words.begin(), words.end(), cmp); + + string best = ""; /* best表示当前最长目标词 */ + unordered_set st(words.begin(), words.end()); /* 取出所有的key 放进 set */ + for (auto& word : words) + { + bool isValid = true; + string prefix; + for (int i = 0; i < word.length() - 1 && isValid; i++) + { + prefix.push_back(word[i]); + if (st.count(prefix) == 0) /* 如果一直有效, 其子串应该一直在set中 */ + isValid = false; + } + if (isValid) + return word; /* 找到的第一个合法的解即为所求 */ + } + + return ""; + } +}; + +// Test +int main() +{ + Solution sol; + vector words = { "a", "banana", "app", "appl", "ap", "apply", "apple" }; + // vector words = { "yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y" }; + // vector words = { "r","kt","jtgt","j","jtg","rdwy","chkext","c","l","zo","lnp","k","jt","chke","ktui","rd","jtgtha","ch","chkex" }; + // vector words = {"b", "br", "bre", "brea", "break", "breakf", "breakfa", "breakfas", "breakfast", "l", "lu", "lun", "lunc", "lunch", "d", "di", "din", "dinn", "dinne", "dinner"}; + auto res = sol.longestWord(words); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode725-split-linked-list-in-parts_solution1.cpp b/cpp-leetcode/leetcode725-split-linked-list-in-parts_solution1.cpp new file mode 100644 index 00000000..7c63cd83 --- /dev/null +++ b/cpp-leetcode/leetcode725-split-linked-list-in-parts_solution1.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + vector splitListToParts(ListNode* head, int k) { + vector res; + int len = 0; + ListNode* p = head; + while (p) + { + p = p->next; + len++; + } + int div, rem, i, j; + div = len / k; // 平均长度 div = totalLen/k + rem = len % k; /* 计算余数, 前一部分(前totalLen%k个)长度为div + 1, 后一部分为div */ + for (i = 0; i < k; i++) + { + ListNode* fakeHead = new ListNode(0); // 新建一个虚拟头结点 + p = fakeHead; + for (j = 0; j < div; j++) + { // 向每一部分添加div个结点 + ListNode* node = new ListNode(head->val); + p->next = node; + p = p->next; + if (head) head = head->next; + } + if (rem > 0 && head) // 向前一部分(前totalLen%k个)分别追加1个结点 + { + ListNode* node = new ListNode(head->val); + p->next = node; + if (head) head = head->next; + rem--; + } + res.push_back(fakeHead->next); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode* head = new ListNode(1); /* {1,4,3,2,5} */ + head->next = new ListNode(4); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(2); + head->next->next->next->next = new ListNode(5); + head->next->next->next->next->next = nullptr; + int k = 3; + auto res = sol.splitListToParts(head, k); + for (auto& list : res) + { + ListNode* p = list; + while (p != nullptr) + { + cout << p->val << " "; + p = p->next; + } + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode728-self-dividing-numbers_math.cpp b/cpp-leetcode/leetcode728-self-dividing-numbers_math.cpp new file mode 100644 index 00000000..23a97ecd --- /dev/null +++ b/cpp-leetcode/leetcode728-self-dividing-numbers_math.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector selfDividingNumbers(int left, int right) { + vector nums; + for (int i = left; i <= right; i++) + { + if (isSelfDiv(i)) nums.push_back(i); + } + return nums; + } + bool isSelfDiv(int n) + { + if (n < 10) return true; + if (n % 10 == 0) return false; + + int temp = n; + while (temp != 0) + { + int rem = temp % 10; + if (rem == 0) return false; + if (rem > 1 && n % rem != 0) // 原数不是末位数字倍数的数需要排除 + return false; + temp /= 10; + } + return true; + } +}; + +// Test +int main() +{ + Solution sol; + int left = 2, right = 50; + vector res = sol.selfDividingNumbers(left, right); + for (int i : res) + printf("%d ", i); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode73-set-matrix-zeroes_extra_space_const.cpp b/cpp-leetcode/leetcode73-set-matrix-zeroes_extra_space_const.cpp new file mode 100644 index 00000000..41f14195 --- /dev/null +++ b/cpp-leetcode/leetcode73-set-matrix-zeroes_extra_space_const.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void setZeroes(vector> &M) { + int rows = M.size(); + if (!rows) return; + int cols = M[0].size(); + if (!cols) return; + + int flag = 2e3; /* 1 <= m, n <= 200, 故设置一个范围外的flag即可 */ + for (int i = 0; i < rows; i++) /* 先把需要改的坐标都标上flag, 最后将标flag的位置进行一次性置0 */ + for (int j = 0; j < cols; j++) + if (M[i][j] == 0) + { + for (int k = 0; k < cols; k++) + if (M[i][k] != 0) // 将同一行不为0的数的位置把值更新为flag + M[i][k] = flag; + for (int k = 0; k < rows; k++) + if (M[k][j] != 0) // 将同一列不为0的数的位置把值更新为flag + M[k][j] = flag; + } + + for (int i = 0; i < rows; i++) + for (int j = 0; j < cols; j++) + if (M[i][j] == flag) + M[i][j] = 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector> M = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; + sol.setZeroes(M); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode73-set-matrix-zeroes_extra_space_n.cpp b/cpp-leetcode/leetcode73-set-matrix-zeroes_extra_space_n.cpp new file mode 100644 index 00000000..634600f3 --- /dev/null +++ b/cpp-leetcode/leetcode73-set-matrix-zeroes_extra_space_n.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void setZeroes(vector>& M) { + int r = M.size(); + int c = M[0].size(); + vector> N = M; + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + if (N[i][j] == 0) + setRelatedCellsToZero(i, j, r, c, M); + } + } + } + void setRelatedCellsToZero(int i, int j, int r, int c, vector>& M) + { // M[i][j] = 0 + for (int k = 0; k < c; k++) + M[i][k] = 0; + for (int k = 0; k < r; k++) + M[k][j] = 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector> M = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; + sol.setZeroes(M); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode73-word-search_dfs1_naive.cpp b/cpp-leetcode/leetcode73-word-search_dfs1_naive.cpp new file mode 100644 index 00000000..ddcc8f3b --- /dev/null +++ b/cpp-leetcode/leetcode73-word-search_dfs1_naive.cpp @@ -0,0 +1,60 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + vector> visited(m, vector(n, 0)); + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (dfs(board, i, j, visited, word, 0)) + return true; + } + } + return false; + } + // 是否能找到index = curPos处的字符, curPos: 在目标单词中的index + bool dfs(vector>& board, int x, int y, vector>& visited, string word, int curPos) + { + if (curPos == word.size()) return true; + int m = board.size(); + int n = board[0].size(); + if (x < 0 || x >= m || y < 0 || y >= n) return false; + if (visited[x][y] == 1) return false; + if (board[x][y] != word[curPos]) return false; + vector> dirs({{1, 0}, {-1, 0}, {0, 1}, {0, -1}}); // 右/左/上/下 + visited[x][y] = 1; + for (auto dir : dirs) + { + auto dirX = dir.first; + auto dirY = dir.second; + if (dfs(board, x + dirX, y + dirY, visited, word, curPos + 1)) return true; + } + visited[x][y] = 0; + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'A', 'B', 'C', 'E'}, + {'S', 'F', 'C', 'S'}, + {'A', 'D', 'E', 'E'} + }; + string word = "ABCCED"; + + bool isValid = sol.exist(board, word); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode73-word-search_dfs1_optimize_direction_vectors.cpp b/cpp-leetcode/leetcode73-word-search_dfs1_optimize_direction_vectors.cpp new file mode 100644 index 00000000..0fae02e7 --- /dev/null +++ b/cpp-leetcode/leetcode73-word-search_dfs1_optimize_direction_vectors.cpp @@ -0,0 +1,59 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + vector> visited(m, vector(n, 0)); + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (dfs(board, i, j, visited, word, 0)) + return true; + } + } + return false; + } + // 是否能找到index = curPos处的字符, curPos: 在目标单词中的index + bool dfs(vector>& board, int x, int y, vector>& visited, string& word, int curPos) + { + if (curPos == word.size()) return true; + int m = board.size(); + int n = board[0].size(); + if (x < 0 || x >= m || y < 0 || y >= n) return false; + if (visited[x][y] == 1) return false; + if (board[x][y] != word[curPos]) return false; + + int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, 1, -1}; /* 方向变量不使用vector, 速度会变快, 依次表示右/左/上/下 */ + visited[x][y] = 1; + for (int i = 0; i < 4; i++) + { + if (dfs(board, x + dx[i], y + dy[i], visited, word, curPos + 1)) return true; + } + visited[x][y] = 0; + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'A', 'B', 'C', 'E'}, + {'S', 'F', 'C', 'S'}, + {'A', 'D', 'E', 'E'} + }; + string word = "ABCCED"; + + bool isValid = sol.exist(board, word); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode73-word-search_dfs1_using_global_vars.cpp b/cpp-leetcode/leetcode73-word-search_dfs1_using_global_vars.cpp new file mode 100644 index 00000000..0f5aa08a --- /dev/null +++ b/cpp-leetcode/leetcode73-word-search_dfs1_using_global_vars.cpp @@ -0,0 +1,63 @@ +#include +#include +using namespace std; + +class Solution { + vector> M; + string str; +public: + bool exist(vector>& board, string word) { + M = board; + str = word; + int m = M.size(); + int n = M[0].size(); + vector> visited(m, vector(n, 0)); + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (dfs(i, j, visited, 0)) + return true; + } + } + return false; + } + bool dfs(int x, int y, vector>& visited, int curPos) + { + if (curPos == str.size()) return true; + int m = M.size(); + int n = M[0].size(); + if (x < 0 || x >= m || y < 0 || y >= n) return false; + if (visited[x][y] == 1) return false; + if (M[x][y] != str[curPos]) return false; + vector> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // 右/左/上/下 + visited[x][y] = 1; + for (auto dir : dirs) + { + auto dirX = dir.first; + auto dirY = dir.second; + if (dfs(x + dirX, y + dirY, visited, curPos + 1)) return true; + } + visited[x][y] = 0; + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'A', 'B', 'C', 'E'}, + {'S', 'F', 'C', 'S'}, + {'A', 'D', 'E', 'E'} + }; + string word = "ABCCED"; + + bool isValid = sol.exist(board, word); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode73-word-search_dfs3_no_visited_array.cpp b/cpp-leetcode/leetcode73-word-search_dfs3_no_visited_array.cpp new file mode 100644 index 00000000..141e5304 --- /dev/null +++ b/cpp-leetcode/leetcode73-word-search_dfs3_no_visited_array.cpp @@ -0,0 +1,59 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (dfs(board, i, j, word, 0)) + return true; + } + } + return false; + } + + bool dfs(vector>& board, int x, int y, string& str, int curPos) + { + if (board[x][y] != str[curPos]) return false; + if (curPos == str.size() - 1) return true; + int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, 1, -1}; /* 推荐写法: 使用两个定长数组做方向向量, 右/左/上/下 */ + char ch = board[x][y]; + board[x][y] = '*'; /* word中只含有英文字母, 这里用英文字母以外的字符都行, 比如使用星号 */ + for (int i = 0; i < 4; i++) + { + int newX = x + dx[i], newY = y + dy[i]; + if (newX >= 0 && newX < board.size() && newY >= 0 && newY < board[0].size()) + { + if (dfs(board, newX, newY, str, curPos + 1)) + return true; + } + } + board[x][y] = ch; + + return false; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board + { + {'A', 'B', 'C', 'E'}, + {'S', 'F', 'C', 'S'}, + {'A', 'D', 'E', 'E'} + }; + string word = "ABCCED"; + + bool isValid = sol.exist(board, word); + cout << (isValid == true ? "true" : "false") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode739-daily-temperatures_monotonic_stack.cpp b/cpp-leetcode/leetcode739-daily-temperatures_monotonic_stack.cpp new file mode 100644 index 00000000..8c249967 --- /dev/null +++ b/cpp-leetcode/leetcode739-daily-temperatures_monotonic_stack.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector dailyTemperatures(vector& T) { + /* 单调递减的单调栈: 存所有待处理的元素的index + 有一个栈, 每次来一个新元素T[i], 就将它与栈顶元素比较, 如果 T[i] > st.top, 就将栈顶元素出栈, 否则就将(当前元素的index)入栈, 栈内的各个index对应的原数组中的数是单调递减的。 + */ + const int len = T.size(); + vector res(len); /* 由于每个元素初始化为0, 而不存在更大的数时题目要求返回0, 所有不存在更大的数时不需要额外处理了 */ + deque st; + for (int i = 0; i < len; i++) + { + while (!st.empty() && T[i] > T[st.back()]) + { + res[st.back()] = i - st.back(); + st.pop_back(); + } + st.push_back(i); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector T = {73, 74, 75, 71, 69, 72, 76, 73}; + auto res = sol.dailyTemperatures(T); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode74-search-a-2d-matrix_binary_search.cpp b/cpp-leetcode/leetcode74-search-a-2d-matrix_binary_search.cpp new file mode 100644 index 00000000..9cbc3376 --- /dev/null +++ b/cpp-leetcode/leetcode74-search-a-2d-matrix_binary_search.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool searchMatrix(vector>& M, int target) { + const int rows = M.size(); + const int cols = M.front().size(); + int i = 0; + int j = cols - 1; + bool found = false; + while (i < rows && j >= 0) /* j >= 0别漏了= */ + { + if (M[i][j] == target) return true; + else if (M[i][j] < target) i++; // 如果矩阵右上角的值不大于target,水平线行数+1 + else j--; // 如果矩阵右上角的值比target大,竖直线列数-1 + } + return found; + } +}; + +// Test +int main() +{ + Solution sol; + vector> M + { + {1, 3, 5, 7}, + {10, 11, 16, 20}, + {23, 30, 34, 60} + }; + + int k = 3; + auto res = sol.searchMatrix(M, k); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode746-min-cost-climbing-stairs_dp_using_vector.cpp b/cpp-leetcode/leetcode746-min-cost-climbing-stairs_dp_using_vector.cpp new file mode 100644 index 00000000..25f75296 --- /dev/null +++ b/cpp-leetcode/leetcode746-min-cost-climbing-stairs_dp_using_vector.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + const int N = cost.size(); + vector dp(N); /* 题意: 2 <= cost.length <= 1000 */ + dp[0] = cost[0]; + dp[1] = cost[1]; + for (int i = 2; i < N; i++) + dp[i] = cost[i] + min(dp[i-2], dp[i-1]); + return min(dp[N-2], dp[N-1]); + } +}; + +// Test +int main() +{ + Solution sol; + vector costs = {10, 15, 20}; + auto res = sol.minCostClimbingStairs(costs); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode75-sort-colors_two_pointers1.cpp b/cpp-leetcode/leetcode75-sort-colors_two_pointers1.cpp new file mode 100644 index 00000000..8e9c52fc --- /dev/null +++ b/cpp-leetcode/leetcode75-sort-colors_two_pointers1.cpp @@ -0,0 +1,42 @@ +#include +#include +using namespace std; + +class Solution { +public: + void sortColors(vector& nums) { + /* 用两个指针 zero, two作为分隔板. zero: 使得所有在zero左边的元素都为0; two, 使得所有在two右边的元素都为2. + * 另外始终让让遍历的指针i指向两个分隔板之间的部分, 即始终保持i <= two 和 i >= zero + */ + const int len = nums.size(); + int zero = 0, two = len - 1; + int i = 0; + while (i <= two) /* 始终保持i <= two */ + { + if (nums[i] == 0) + { + swap(nums[i], nums[zero]); + zero++; + } + else if (nums[i] == 2) + { + swap(nums[i], nums[two]); + two--; + } + else i++; + i = max(zero, i); /* 始终保持 i >= zero */ + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2,0,2,1,1,0}; + sol.sortColors(nums); + for (auto &num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode75-sort-colors_two_pointers2.cpp b/cpp-leetcode/leetcode75-sort-colors_two_pointers2.cpp new file mode 100644 index 00000000..6664904d --- /dev/null +++ b/cpp-leetcode/leetcode75-sort-colors_two_pointers2.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +class Solution { +public: + void sortColors(vector& nums) { + const int len = nums.size(); + int zero = 0, two = len - 1; + for (int i = 0; i <= two; i++) + { + if (nums[i] == 2) + { + swap(nums[i], nums[two]); + two--; + i--; /* i扫描完后就i++了, 这里i--是为了处理从two位置新swap到i位置的值(可能是0、1、2) */ + } + else if (nums[i] == 0) + { + swap(nums[i], nums[zero]); + zero++; /* 这里不需要i--是因为左边都是处理完了的 */ + } + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2,0,2,1,1,0}; + sol.sortColors(nums); + for (auto &num : nums) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode76-minimum-window-substring.cpp b/cpp-leetcode/leetcode76-minimum-window-substring.cpp new file mode 100644 index 00000000..116c714c --- /dev/null +++ b/cpp-leetcode/leetcode76-minimum-window-substring.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string minWindow(string s, string t) + { + if (s.empty() || s == "" || t.empty() || t == "" || s.length() < t.length()) + { + return ""; + } + + vector gapMap(128, 0); + for (char ch : t) // 先遍历字符串t来初始化gapMap + { + gapMap[ch]++; + } + + int right = 0, left = 0, gapSum = t.size(), start = 0, minLen = INT_MAX; + while (right < s.size()) + { + char ch = s[right]; + if (gapMap[ch] > 0) + { + gapMap[ch]--; + gapSum--; + } + else + gapMap[ch]--; /* 如果该字符不是需要的,加到map中,每出现一次累记1个-1 */ + + if (gapSum == 0) + { + while (left < right && gapMap[s[left]] < 0) /* 右移左边界, 依次扔掉当前的字符, gapMap中相应的值+1 */ + { + gapMap[s[left++]]++; + } + if (right - left + 1 < minLen) // 更新窗口长度 + { + minLen = right - left + 1; + start = left; + } + + // 当while循环结束, 即字符在gapMap中的值当为0且左边界继续右移时 + gapMap[s[left++]]++; + gapSum++; + } + + right++; + } + return minLen == INT_MAX ? "" : s.substr(start, minLen); + } +}; + +// Test +int main() +{ + Solution sol; + string s = "ADOBECODEBANC", t = "ABC"; + auto res = sol.minWindow(s, t); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode76-minimum-window-substring2.cpp b/cpp-leetcode/leetcode76-minimum-window-substring2.cpp new file mode 100644 index 00000000..ed639382 --- /dev/null +++ b/cpp-leetcode/leetcode76-minimum-window-substring2.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string minWindow(string s, string t) + { + vector map(128, 0); + int remain = 0; + for (char ch : t) + map[ch]++; // map数组存着字符串 t 中各字母的数量。 + + remain = t.length(); + int left = 0, right = 0, start = 0, minLen = INT_MAX; + while (right < s.length()) + { + char rch = s[right]; + if (map[rch] > 0) + remain--; + map[rch]--; //先把右边的字符加入窗口 + if (remain == 0) //窗口中已经包含所需的全部字符 + { + while (left < right && map[s[left]] < 0) //缩减窗口 + { + map[s[left++]]++; + } //此时窗口符合要求 + if (right - left + 1 < minLen) //更新信息 + { + minLen = right - left + 1; + start = left; + } + map[s[left]]++; //左边界右移之前需要释放map[s[left]] + left++; + remain++; + } + right++; + } + return minLen == INT_MAX ? "" : s.substr(start, minLen); + } +}; + +// Test +int main() +{ + Solution sol; + string s = "ADOBECODEBANC", t = "ABC"; + auto res = sol.minWindow(s, t); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode763-partition-labels_hashmap_using_array.cpp b/cpp-leetcode/leetcode763-partition-labels_hashmap_using_array.cpp new file mode 100644 index 00000000..aeee46a0 --- /dev/null +++ b/cpp-leetcode/leetcode763-partition-labels_hashmap_using_array.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector partitionLabels(string s) { + vector lastIndexDict(128, 0); /* 将小写字母的ASCII码作为key, value是最后一次出现的pos */ + const int len = 0; + for (int i = 0; i < len; i++) + lastIndexDict[s[i]] = i; + vector res; + int start = 0; // 用区间[start, end]表示一个片段(label) + int end = 0; + for (int i = 0; i < len; i++) /* 从前往后扫描字符, 看当前区间是否需要扩展 */ + { + int curChLastIndex = lastIndexDict[s[i]]; + end = max(end, curChLastIndex); + if (i == end) + { + int curLen = end - start + 1; + res.push_back(curLen); + start = end + 1; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "ababcbacadefegdehijhklij"; + auto res = sol.partitionLabels(s); + for (auto &num : res) + cout << num << endl; + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode768-max-chunks-to-make-sorted-ii_greedy_sliding_window.cpp b/cpp-leetcode/leetcode768-max-chunks-to-make-sorted-ii_greedy_sliding_window.cpp new file mode 100644 index 00000000..c4ef340e --- /dev/null +++ b/cpp-leetcode/leetcode768-max-chunks-to-make-sorted-ii_greedy_sliding_window.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxChunksToSorted(vector& arr) { + vector sortedArr(arr); + sort(sortedArr.begin(), sortedArr.end()); + + long arrSum = 0; + long sortedSum = 0; + int maxCount = 0; + int n = arr.size(); + for (int i = 0; i < n; i++) + { + arrSum += arr[i]; + sortedSum += sortedArr[i]; + if (arrSum == sortedSum) /* 当区间[0, i]中的数已经处于正确的区间上时, + 该数字及其前面相邻的数组成的片段只要排序就满足要求了。 + 这个片段已处理完毕,可以为数量贡献1了。 */ + maxCount++; + } + return maxCount; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 1, 3, 4, 4}; + int res = sol.maxChunksToSorted(nums); + cout << res < +#include +#include +using namespace std; + +class Solution { +public: + int maxChunksToSorted(vector& arr) { + int res = 0; + int curMax = 0; + const int len = arr.size(); + for (int i = 0; i < len; i++) + { + curMax = max(curMax, arr[i]); + if (i == curMax) res++; /* 当index = i处的数已经处于正确位置上时, + 该数字及其前面相邻的数组成的片段已经有序。 + 这个片段已处理完毕,可以为数量贡献1了。 */ + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 0, 2, 3, 4}; + int res = sol.maxChunksToSorted(nums); + cout << res < +#include +#include +using namespace std; + +class Solution { + vector> res; +public: + vector> combine(int n, int k) { + vector curGroup; + dfs(n, k, 1, curGroup); + return res; + } + void dfs(int n, int k, int startNum, vector& curGroup) + { + if (curGroup.size() == k) + { + res.push_back(curGroup); + return; + } + + for (int i = startNum; i <= n; i++) + { + // 取到第1个, 放进 curGroup + curGroup.push_back(i); + // dfs取下一个 + dfs(n, k, i+1, curGroup); + // clean up + curGroup.pop_back(); + } + } +}; + +// Test +int main() +{ + Solution sol; + int n = 7, k = 5; + auto res = sol.combine(n, k); /* 加断点到下一行进行debug, 可以看到结果 */ + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode77-combinations_iterative.cpp b/cpp-leetcode/leetcode77-combinations_iterative.cpp new file mode 100644 index 00000000..30118b66 --- /dev/null +++ b/cpp-leetcode/leetcode77-combinations_iterative.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> combine(int n, int k) { + vector> res; + vector curGroup; + // 迭代法: 先加入一个最小的满足条件的组合, 然后用对各位微调生成更多 + for (int i = 1; i <= k; i++) + curGroup.push_back(i); + + while (true) + { + int i = k-1; + while (i >=0 && curGroup[i] == i+1 + n-k) + i--; + if (i == -1) // 取到最大的数 + break; + curGroup[i]++; + for (int j = i+1; j +#include +#include +#include +using namespace std; + +class Solution { + const int dx[4] = {0, 1, 0, -1}; + const int dy[4] = {1, 0, -1, 0}; +public: + int swimInWater(vector>& grid) { + const int n = grid.size(); + int left = 0; + int right = n * n; // 搜索区间为: [0, n^2) + while (left < right) + { + int mid = left + (right - left) / 2; + if (hasPath(grid, n, mid)) + right = mid; + else left = mid + 1; + } + return left; + } + bool hasPath(vector>& grid, int n, int t) + { + if (grid[0][0] > t) return false; + queue q; // queue中存储的元素: y * N + x + vector visited(n * n); + q.push(0); // 0*N + 0 + + while (!q.empty()) + { + const int x = q.front() % n; + const int y = q.front() / n; + q.pop(); + if (x == n - 1 && y == n - 1) return true; + for (int i = 0; i < 4; i++) + { + const int tx = x + dx[i]; + const int ty = y + dy[i]; + if (tx < 0 || ty < 0 || tx >= n || ty >= n || grid[ty][tx] > t) + continue; + const int key = ty * n + tx; + if (visited[key]) + continue; + visited[key] = 1; + q.push(key); + } + } + return false; + }; +}; + +// Test +int main() +{ + Solution sol; + vector> grid = {{0, 2}, {1, 3}}; + auto res = sol.swimInWater(grid); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode78-subsets_bfs.cpp b/cpp-leetcode/leetcode78-subsets_bfs.cpp new file mode 100644 index 00000000..8450792d --- /dev/null +++ b/cpp-leetcode/leetcode78-subsets_bfs.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +// 方法: 回溯/dfs +class Solution { +public: + vector> subsets(vector& nums) { + if (nums.empty()) return {{}}; + const int len = nums.size(); + vector> res; + vector curSet; + res.push_back({}); /* 空集必然是其中一个子集 */ + for (int i = 1; i <= len; i++) + dfs(nums, i, 0, curSet, res); + return res; + } + + void dfs(const vector& nums, int len, int startPos, vector& curSet, vector>& res) + { + if (len == curSet.size()) + { + res.push_back(curSet); + return; + } + + for (int i = startPos; i < nums.size(); i++) + { + curSet.push_back(nums[i]); // Choose + dfs(nums, len, i+1, curSet, res); // Explore + curSet.pop_back(); // Un-choose/Clean up state + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1,2,3 }; + auto res = sol.subsets(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode78-subsets_bit_operation.cpp b/cpp-leetcode/leetcode78-subsets_bit_operation.cpp new file mode 100644 index 00000000..3b472f31 --- /dev/null +++ b/cpp-leetcode/leetcode78-subsets_bit_operation.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> subsets(vector& nums) { + const int n = nums.size(); + vector> res; + for (int s = 0; s < (1 << n); ++s) { // s表示一个状态state + vector curSet; + for (int i = 0; i < n; ++i) + if ((s & (1 << i)) > 0) /* 从末位开始, 循环判断当前位是不是1. 注意位运算的优先级不比+、>、<、=高, 可以加括号后判断>0, 也可以简写为 if (s & (1 << i)) */ + curSet.push_back(nums[i]); + res.push_back(curSet); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1,2,3 }; + auto res = sol.subsets(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode78-subsets_bit_switch_brute_force.cpp b/cpp-leetcode/leetcode78-subsets_bit_switch_brute_force.cpp new file mode 100644 index 00000000..a05a0076 --- /dev/null +++ b/cpp-leetcode/leetcode78-subsets_bit_switch_brute_force.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> subsets(vector& nums) { + int len = nums.size(); + long long count = pow(2, len); /* 子集总的数量 */ + vector> res { {} }; // 空集必然是其中一个子集, 所以直接就在初始化放进来了 + for (int i = 1; i < count; i++) { + vector curSet; + string str = toBinary(i); // 转为二进制的字符串 + int curLen = str.size(); + if (len - curLen > 0) /* 如果位数不够会在左侧填补上字符'0' */ + str.insert(str.begin(), len - curLen, '0'); + for (int j = 0; j < str.size(); j++) + { + if (str[j] == '1') + curSet.push_back(nums[j]); + } + res.push_back(curSet); + } + return res; + } + + string toBinary(long n) /* 将非负整数转为二进制串 */ + { + string res = ""; + while (n > 0) + { + char r = n % 2 + '0'; + res.push_back(r); + n /= 2; + } + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1,2,3 }; + auto res = sol.subsets(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode78-subsets_iterative.cpp b/cpp-leetcode/leetcode78-subsets_iterative.cpp new file mode 100644 index 00000000..8450792d --- /dev/null +++ b/cpp-leetcode/leetcode78-subsets_iterative.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +// 方法: 回溯/dfs +class Solution { +public: + vector> subsets(vector& nums) { + if (nums.empty()) return {{}}; + const int len = nums.size(); + vector> res; + vector curSet; + res.push_back({}); /* 空集必然是其中一个子集 */ + for (int i = 1; i <= len; i++) + dfs(nums, i, 0, curSet, res); + return res; + } + + void dfs(const vector& nums, int len, int startPos, vector& curSet, vector>& res) + { + if (len == curSet.size()) + { + res.push_back(curSet); + return; + } + + for (int i = startPos; i < nums.size(); i++) + { + curSet.push_back(nums[i]); // Choose + dfs(nums, len, i+1, curSet, res); // Explore + curSet.pop_back(); // Un-choose/Clean up state + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 1,2,3 }; + auto res = sol.subsets(nums); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode783-minimum-distance-between-bst-nodes_in_order.cpp b/cpp-leetcode/leetcode783-minimum-distance-between-bst-nodes_in_order.cpp new file mode 100644 index 00000000..b0779232 --- /dev/null +++ b/cpp-leetcode/leetcode783-minimum-distance-between-bst-nodes_in_order.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int minDiffInBST(TreeNode* root) { + vector vals; + inorder(root, vals); + int minGap = INT_MAX; + for (int i = 0; i < vals.size() - 1; i++) + { + if (abs(vals[i + 1] - vals[i]) < minGap) + minGap = abs(vals[i + 1] - vals[i]); + } + return minGap; + } + + void inorder(TreeNode* root, vector& vals) + { + if (root == nullptr) return; + inorder(root->left, vals); + vals.push_back(root->val); + inorder(root->right, vals); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode *root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(3); + root->right->left = new TreeNode(2); + root->right->right = NULL; + auto res = sol.minDiffInBST(root); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode8-string-to-integer-atoi_solution1.cpp b/cpp-leetcode/leetcode8-string-to-integer-atoi_solution1.cpp new file mode 100644 index 00000000..992cd6f9 --- /dev/null +++ b/cpp-leetcode/leetcode8-string-to-integer-atoi_solution1.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include /* 含有isdigit、isalpha等函数 */ +using namespace std; + +class Solution { +public: + int myAtoi(string s) { + s.erase(0, s.find_first_not_of(' ')); //去掉前导空格 + if(s == "") return 0; + if((s[0] == '-' && s[1] =='+') || (s[0]=='+' && s[0] == '-')) return 0; //两种符号直接特判 + bool is_neg = false; + if(s[0] == '-') + { + is_neg = true; + s.erase(0,1); + } + if(s[0] == '+') s.erase(0,1); + + int res = 0; + for(int i = 0; i < s.size(); i++){ + if( !isdigit(s[i])) + break; + int digit = s[i] - '0'; + if(res > (INT_MAX - digit) / 10){ /* 假如循环结束后 res > INT_MAX(/比*更不易越界,所以改用/处理),这里进行特殊处理 */ + if(is_neg) + return INT_MIN; + return INT_MAX; + } + res = res * 10 + digit; /* 向右扫描, 每移1位,高位x10, sum = sum*10 + digit, 不断迭代 */ + } + return is_neg ? -res : res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "-5------+"; + int res = sol.myAtoi(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode8-string-to-integer-atoi_solution2.cpp b/cpp-leetcode/leetcode8-string-to-integer-atoi_solution2.cpp new file mode 100644 index 00000000..8d0b0803 --- /dev/null +++ b/cpp-leetcode/leetcode8-string-to-integer-atoi_solution2.cpp @@ -0,0 +1,27 @@ +#include +#include +#include /* 含有stringstream类 */ +#include +using namespace std; + +class Solution { +public: + int myAtoi(string s) { + stringstream ss; + int res = 0; + ss << s; + ss >> res; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string str = "-5------+"; + int res = sol.myAtoi(str); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode80-remove-duplicates-from-sorted-array-ii.cpp b/cpp-leetcode/leetcode80-remove-duplicates-from-sorted-array-ii.cpp new file mode 100644 index 00000000..7993306c --- /dev/null +++ b/cpp-leetcode/leetcode80-remove-duplicates-from-sorted-array-ii.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int removeDuplicates(vector& nums) { + int i = 1, p = 0; // 用指针p 指向发现的新值的index + int count = 1; + int n = nums.size(); + while (i < n) { + if (nums[p] == nums[i] && count == 0) i++; + else { + if (nums[p] == nums[i]) count--; + else count = 1; + p++; + nums[p] = nums[i]; + i++; + } + } + return nums.empty() ? 0 : p + 1; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = { 0,0,1,1,1,2,2,2,2,3,3,3,6,6 }; + auto res = sol.removeDuplicates(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode819-most-common-word_hashmap_and_stringstream.cpp b/cpp-leetcode/leetcode819-most-common-word_hashmap_and_stringstream.cpp new file mode 100644 index 00000000..a067b828 --- /dev/null +++ b/cpp-leetcode/leetcode819-most-common-word_hashmap_and_stringstream.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string mostCommonWord(string paragraph, vector& banned) { + string s1 = ""; + for (auto& ch : paragraph) + { + if (isalpha(ch) || ch == ' ' || ch == ',') /* 注意这里逗号","的处理 */ + { + char newCh; + if (ch >= 'A' && ch <= 'Z') newCh = ch - 'A' + 'a'; /* 遇到大写字母转小写 */ + else if (ch == ',') newCh = ' '; + else newCh = ch; + s1 += newCh; + } + } + stringstream ss(s1); + unordered_map wordDict; + while (ss >> s1) + { + if (find(banned.begin(), banned.end(), s1) == banned.end()) /* 只统计不在banned数组中的单词 */ + wordDict[s1]++; + } + string commonWord; + int maxCount = 0; + for (auto& kvp : wordDict) + maxCount = max(maxCount, kvp.second); + for (auto& kvp : wordDict) + { + string word = kvp.first; + if (kvp.second == maxCount) + commonWord = word; + } + return commonWord; + } +}; + +int main() +{ + Solution sol; + string s = "a, a, a, a, b,b,b,c, c"; + vector banned = {"a"}; + auto res = sol.mostCommonWord(s, banned); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode82-remove-duplicates-from-sorted-list-ii_recursive.cpp b/cpp-leetcode/leetcode82-remove-duplicates-from-sorted-list-ii_recursive.cpp new file mode 100644 index 00000000..38be38db --- /dev/null +++ b/cpp-leetcode/leetcode82-remove-duplicates-from-sorted-list-ii_recursive.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if(head == NULL || head->next == NULL ) return head; + + if (head->val != head->next->val) + { + head->next = deleteDuplicates(head->next); /* 如果头结点和后边的节点不相等, 则头结点是需要的, 保留头结点, + 后边的所有节点的处理由递归解决. 要处理的数的规模由len变为len-1 */ + return head; + } + + int curVal = head->val; + while (head != NULL && head->val == curVal) /* 如果头结点和后边的节点相等 */ + { + ListNode *toDel = head; + head = head->next; + delete toDel; // 释放内存 + } + return deleteDuplicates(head); + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *head = new ListNode(2); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(4); + head->next->next->next->next = new ListNode(4); + head->next->next->next->next->next = new ListNode(5); + head->next->next->next->next->next->next = NULL; + + auto res = sol.deleteDuplicates(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode82-remove-duplicates-from-sorted-list-ii_traversal_and_two_pointers.cpp b/cpp-leetcode/leetcode82-remove-duplicates-from-sorted-list-ii_traversal_and_two_pointers.cpp new file mode 100644 index 00000000..49597e76 --- /dev/null +++ b/cpp-leetcode/leetcode82-remove-duplicates-from-sorted-list-ii_traversal_and_two_pointers.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +/** + * Definition for singly-linked list. + */ +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +/* Time: O(n); Space: O(1) */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if(head == NULL || head->next == NULL ) + return head; + + ListNode *fakeNode = new ListNode(-1); + fakeNode->next = head; + ListNode *pre = fakeNode; + ListNode *cur = head; + while (cur != NULL) + { + // 出现了相等的情况, pre->next 直接指向 cur->next, 删除所有重复数字 + if (cur->next != NULL && cur->val == cur->next->val) + { + int curVal = cur->val; + while (cur != NULL && cur->val == curVal) + { + ListNode *toDel = cur; + cur = cur->next; + pre->next = cur; + delete toDel; /* 释放内存 */ + } + } + else /* 没有出现相等的情况时, 正常遍历即可, pre 移到 cur 的地方 */ + { + pre = cur; + cur = cur->next; + } + } + return fakeNode->next; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *head = new ListNode(2); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(4); + head->next->next->next->next = new ListNode(4); + head->next->next->next->next->next = new ListNode(5); + head->next->next->next->next->next->next = NULL; + + auto res = sol.deleteDuplicates(head); + ListNode *p = res; + while (p != NULL) + { + cout << p->val << endl; + p = p->next; + } + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode821-shortest-distance-to-a-character_naive_solution.cpp b/cpp-leetcode/leetcode821-shortest-distance-to-a-character_naive_solution.cpp new file mode 100644 index 00000000..982b2af0 --- /dev/null +++ b/cpp-leetcode/leetcode821-shortest-distance-to-a-character_naive_solution.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector shortestToChar(string s, char c) { + // 题意: 计算 abs[i] = indexGap(i, nearest_c), 1 <= s.length <= 10^4 + // 输出 abs[i]的数组 + vector indexes; // indexes of char c + for (int i = 0; i < s.size(); i++) + { + if (s[i] == c) indexes.push_back(i); + } + vector res; + for (int i = 0; i < s.size(); i++) + { + vector gaps; // gap for char s[i] to char c + for (auto index : indexes) + gaps.push_back(abs(index - i)); + auto it = min_element(gaps.begin(), gaps.end()); + res.push_back(*it); + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "loveleetcode"; + char c = 'e'; + auto res = sol.shortestToChar(s, c); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode821-shortest-distance-to-a-character_two_pointers1.cpp b/cpp-leetcode/leetcode821-shortest-distance-to-a-character_two_pointers1.cpp new file mode 100644 index 00000000..82694102 --- /dev/null +++ b/cpp-leetcode/leetcode821-shortest-distance-to-a-character_two_pointers1.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector shortestToChar(string s, char c) { + vector gaps(s.size()); + vector chars(s.begin(), s.end()); + + for (int i = 0; i < chars.size(); i++) + { + // 如果当前字符就是要搜索的字符c, 距离为 0 + if (chars[i] == c) gaps[i] = 0; + else /* 否则分别向左、向右找最近的字符c */ + { + int leftDistance = INT_MAX, rightDistance = INT_MAX; + for (int left = i; left >= 0; left--) + { + if (chars[left] == c) // 向左找, 找到第一个 + { + leftDistance = i - left; + break; + } + } + for (int right = i; right < chars.size(); right++) // 向右找, 找到第一个 + { + if (chars[right] == c) + { + rightDistance = right - i; + break; + } + } + gaps[i] = min(leftDistance, rightDistance); + } + } + + return gaps; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "loveleetcode"; + char c = 'e'; + auto res = sol.shortestToChar(s, c); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode821-shortest-distance-to-a-character_two_pointers2.cpp b/cpp-leetcode/leetcode821-shortest-distance-to-a-character_two_pointers2.cpp new file mode 100644 index 00000000..58603603 --- /dev/null +++ b/cpp-leetcode/leetcode821-shortest-distance-to-a-character_two_pointers2.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector shortestToChar(string s, char c) { + vector cIndexes; // 存放字符c在原数组中的下标索引 + int n = s.size(); + vector res(n); + + for (int i = 0; i < n; i++) + if (s[i] == c) cIndexes.push_back(i); + + int len = cIndexes.size(); + int left = 0, right = 0; /* 双指针left, right, left: 从左向右扫描原数组时的下标, right: 数组cIndexes中字符c的下标 */ + for (int i = 0; i < n; i++) + { + /* 用 [left, right] 记录要搜索的范围, 最开始的搜索范围是[0, 字符c的第1个索引], 确保该范围内只有1个字符c。 + 当 i 恰好扫描完当前这个区间时, 更新left 和 right, 扫描下一个区间[字符c的第1个索引+1, 字符c的第2个索引]。 + 依此类推~ + */ + if (i > cIndexes[right]) + { + left = right; + if (right < len - 1) right++; + } + res[i] = min(abs(cIndexes[right] - i), abs(cIndexes[left] - i)); + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "loveleetcode"; + char c = 'e'; + auto res = sol.shortestToChar(s, c); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode837-new-21-game_dp_and_sliding_window_using_array.cpp b/cpp-leetcode/leetcode837-new-21-game_dp_and_sliding_window_using_array.cpp new file mode 100644 index 00000000..12b9b053 --- /dev/null +++ b/cpp-leetcode/leetcode837-new-21-game_dp_and_sliding_window_using_array.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + double new21Game(int N, int K, int W) { + if (K == 0) return 1.0; + if (N >= K + W - 1) return 1.0; + if (N < K) return 0.0; + // dp[i] = (1/w) * (dp[i - 1] + ... + dp[i - w]) + double dp[K + W]; // 最大能达到的点数是 K+W-1 + fill(dp, dp + K + W, 0.0); + double prob = 1.0 / W; + dp[0] = 1.0; + double sum = 1.0; + for (int i = 1; i < K + W; i++) + { + dp[i] = prob * sum; + if (i < K) sum += dp[i]; + if (i - W >= 0) sum -= dp[i - W]; + } + double res = 0.0; + for (int i = K; i <= N; i++) + res += dp[i]; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int N = 21, K = 17, W = 10; + auto res = sol.new21Game(N, K, W); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode837-new-21-game_dp_and_sliding_window_using_vector.cpp b/cpp-leetcode/leetcode837-new-21-game_dp_and_sliding_window_using_vector.cpp new file mode 100644 index 00000000..e81ed1fc --- /dev/null +++ b/cpp-leetcode/leetcode837-new-21-game_dp_and_sliding_window_using_vector.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + double new21Game(int N, int K, int W) { + if (K == 0) return 1.0; + if (N >= K + W - 1) return 1.0; + if (N < K) return 0.0; + // dp[i] = (1/w) * (dp[i - 1] + ... + dp[i - w]) + vector dp(K + W); // 最大能达到的点数是 K+W-1 + double prob = 1.0 / W; + dp[0] = 1.0; + double sum = 1.0; + for (int i = 1; i < K + W; i++) + { + dp[i] = prob * sum; + if (i < K) sum += dp[i]; + if (i - W >= 0) sum -= dp[i - W]; + } + double res = 0.0; + for (int i = K; i <= N; i++) + res += dp[i]; + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int N = 21, K = 17, W = 10; + auto res = sol.new21Game(N, K, W); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode84-largest-rectangle-in-histogram_monotonic_stack.cpp b/cpp-leetcode/leetcode84-largest-rectangle-in-histogram_monotonic_stack.cpp new file mode 100644 index 00000000..ba39dcff --- /dev/null +++ b/cpp-leetcode/leetcode84-largest-rectangle-in-histogram_monotonic_stack.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int largestRectangleArea(vector& heights) { + if (heights.empty()) return 0; + + int res = 0; + vector tempArr(heights); + tempArr.insert(tempArr.begin(), 0); + tempArr.push_back(0); + + deque st; + for (int i = 0; i < tempArr.size(); i++) + { + while (!st.empty() && tempArr[st.back()] > tempArr[i]) + { + int cur = st.back(); + st.pop_back(); + int left = st.back() + 1; + int right = i - 1; + res = max(res, (right - left + 1) * tempArr[cur]); + } + st.push_back(i); // push索引 + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector heights= {2,1,5,6,2,3}; + auto res = sol.largestRectangleArea(heights); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode85-maximal-rectangle_monotone_stack.cpp b/cpp-leetcode/leetcode85-maximal-rectangle_monotone_stack.cpp new file mode 100644 index 00000000..d947bdad --- /dev/null +++ b/cpp-leetcode/leetcode85-maximal-rectangle_monotone_stack.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int maximalRectangle(vector>& matrix) { + if (matrix.empty()) return 0; + int m = matrix.size(); + int n = matrix[0].size(); + int res = 0; + vector row(n, 0); + /* 以下循环是为了计算出目标矩阵的下界, 每次把row[j]更新为第0 ~ i-1行第j列压缩后得到的新值(row相当于 + leetcode84输入的heights数组), 如果出现连续1就累加, 否则表示无法形成柱子(悬空了)就直接清零. */ + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (matrix[i][j] == '1') row[j] += 1; + else row[j] = 0; + } + int curArea = largestRecArea(row); /* 对于压缩后得到的二维数组中的当前行 row, 可以直接使用leetcode84的解法 */ + res = max(res, curArea); + } + return res; + } + int largestRecArea(vector row) + { + row.insert(row.begin(), 0); /* 在数组首尾都加零, 前者避免 i - stack.top() - 1 时遇到栈空,后者保证恰好能进行一次退栈。 */ + row.push_back(0); + stack st; /* 栈中存放当前数在原矩阵中的水平方向的index */ + st.push(0); + int area = 0; + for (int i = 1; i < row.size(); i++) + { + if (row[i] > row[st.top()]) st.push(i); + else + { + while (row[st.top()] > row[i]) + { + int H = row[st.top()]; + st.pop(); + int W = i - st.top() - 1; + area = max(area, H * W); + } + st.push(i); + } + } + return area; + } +}; + +// Test +int main() +{ + Solution sol; + vector> matrix + { + {'1', '0', '1', '0', '0'}, + {'1', '0', '1', '1', '1'}, + {'1', '1', '1', '1', '1'}, + {'1', '0', '0', '1', '0'} + }; + auto res = sol.maximalRectangle(matrix); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode859-buddy-strings_case_by_classification.cpp b/cpp-leetcode/leetcode859-buddy-strings_case_by_classification.cpp new file mode 100644 index 00000000..5e637b1c --- /dev/null +++ b/cpp-leetcode/leetcode859-buddy-strings_case_by_classification.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool buddyStrings(string s, string goal) { + int len1 = s.size(); + int len2 = goal.size(); + if (len1 != len2) return false; + if (s == goal) // 如果字符串s与字符串goal相同, 那么s中必须有某个字符至少出现了2次, 这样swap1次可以得到自己 + { + unordered_map dict; + for (int i = 0; i < len1; i++) + { + auto ch = s[i]; + dict[ch]++; + if (dict[ch] >= 2) return true; + } + } + else if (s != goal) /* 两个字符串不相等的情况下如果要恰好swap一次就能相等, 那么两个字符串必然只有两个位置(不同index)的字符不一样 */ + { + vector indexes; + for (int i = 0; i < len1; i++) + { + if (s[i] != goal[i]) indexes.push_back(i); + } + if (indexes.size() != 2) return false; + int pos1 = indexes.front(); + int pos2 = indexes.back(); + if (s[pos1] == goal[pos2] && s[pos2] == goal[pos1]) return true; + } + return false; + } +}; + +// Test +int main() +{ + Solution sol; + string s = "ab"; + string goal = "ba"; + auto res = sol.buddyStrings(s, goal); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode86-partition-list.cpp b/cpp-leetcode/leetcode86-partition-list.cpp new file mode 100644 index 00000000..436c4d4d --- /dev/null +++ b/cpp-leetcode/leetcode86-partition-list.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + ListNode* h1 = new ListNode(0); // 虚拟结点h1 (fakeHead1) + ListNode* h2 = new ListNode(0); + ListNode* p = h1; + ListNode* q = h2; + while (head != nullptr) /* 把head 用作 cur */ + { + if (head->val < x) + { + p->next = head; + p = p->next; + } + else { + q->next = head; + q = q->next; + } + head = head->next; + } + p->next = h2->next; + q->next = nullptr; /* 防止成环, 尾部需要置NULL, 且置NULL操作必须在两链表挂接之后 */ + + return h1->next; + } +}; + +// Test +int main() +{ + Solution sol; + ListNode *head = new ListNode(1); /* {1,4,3,2,5,2} */ + head->next = new ListNode(4); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(2); + head->next->next->next->next = new ListNode(5); + head->next->next->next->next->next = new ListNode(2); + head->next->next->next->next->next->next = nullptr; + int x = 3; + auto res = sol.partition(head, x); + ListNode *p = res; + while (p != nullptr) + { + cout << p->val << " "; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode869-reordered-power-of-2_convert_to_string_with_hashmap.cpp b/cpp-leetcode/leetcode869-reordered-power-of-2_convert_to_string_with_hashmap.cpp new file mode 100644 index 00000000..3c43d93f --- /dev/null +++ b/cpp-leetcode/leetcode869-reordered-power-of-2_convert_to_string_with_hashmap.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool reorderedPowerOf2(int n) { + for (int i = 1; i <= 1e9; i *= 2) + { + if (canOrderToSame(i, n)) return true; + } + return false; + } + bool canOrderToSame(int i, int n) /* 判断整数i是否重新排序后能和n相等 */ + { + unordered_map dict1, dict2; + for (auto ch : to_string(i)) dict1[ch]++; /* 转为字符串, 统计其中每一个字符出现的次数 */ + for (auto ch : to_string(n)) dict2[ch]++; + return dict1 == dict2; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 24; + auto res = sol.reorderedPowerOf2(n); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode869-reordered-power-of-2_count_no_array.cpp b/cpp-leetcode/leetcode869-reordered-power-of-2_count_no_array.cpp new file mode 100644 index 00000000..41078c4a --- /dev/null +++ b/cpp-leetcode/leetcode869-reordered-power-of-2_count_no_array.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool reorderedPowerOf2(int n) { + for (int i = 1; i <= 1e9; i *= 2) + { + if (canOrderToSame(i, n)) return true; + } + return false; + } + bool canOrderToSame(int i, int& n) /* 判断整数i是否重新排序后能和n相等 */ + { + for (int d = 0; d <= 9; d++) /* 枚举每一位的数字(0~9之间), 只要出现某一个数字在整数i和n中的数量不相等就返回false */ + { + int count1 = countTimes(i, d); + int count2 = countTimes(n, d); + if (count1 != count2) return false; + } + return true; + } + int countTimes(long int x, int d) /* 统计每一位的数digit(简写为d)在整数x中出现的次数 */ + { + int count = 0; + while (x) + { + if (x % 10 == d) + count++; + x = x / 10; + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 24; + auto res = sol.reorderedPowerOf2(n); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode869-reordered-power-of-2_count_with_vector.cpp b/cpp-leetcode/leetcode869-reordered-power-of-2_count_with_vector.cpp new file mode 100644 index 00000000..3856dd81 --- /dev/null +++ b/cpp-leetcode/leetcode869-reordered-power-of-2_count_with_vector.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool reorderedPowerOf2(int n) { + for (int i = 1; i <= 1e9; i *= 2) + { + if (canOrderToSame(i, n)) return true; + } + return false; + } + bool canOrderToSame(int i, int& n) /* 判断整数i是否重新排序后能和n相等 */ + { + vector dict1(11), dict2(11); + for (int d = 0; d <= 9; d++) + { + dict1[d] = countTimes(i, d); + dict2[d] = countTimes(n, d); + } + return dict1 == dict2; + } + int countTimes(long int x, int d) /* 计算每一位的数digit(简写为d)在整数x中出现的次数 */ + { + int count = 0; + while (x) + { + if (x % 10 == d) + count++; + x = x / 10; + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 24; + auto res = sol.reorderedPowerOf2(n); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode874-walking-robot-simulation_hashmap_with_hashset.cpp b/cpp-leetcode/leetcode874-walking-robot-simulation_hashmap_with_hashset.cpp new file mode 100644 index 00000000..fb7b89ce --- /dev/null +++ b/cpp-leetcode/leetcode874-walking-robot-simulation_hashmap_with_hashset.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int robotSim(vector& commands, vector>& obstacles) { + int x = 0; + int y = 0; + int dirs[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + int d = 1; // 初始状态时方向应该朝北 N: {0, 1} + unordered_map> dict; + for (const auto& obstacle : obstacles) + dict[obstacle[0]].insert(obstacle[1]); + int res = 0; + for (int& c : commands) + { + if (c == -2) d = (d - 1 + 4) % 4; + else if (c == -1) d = (d + 1) % 4; + else + { + while (c--) + { + int tx = x + dirs[d][0]; + int ty = y + dirs[d][1]; + if (dict.count(tx) && dict.at(tx).count(ty)) + break; + x = tx; + y = ty; + res = max(res, x * x + y * y); + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> obstacles = {{2, 4}}; + vector commands = {4, -1, 4, -2, 4}; + auto res = sol.robotSim(commands, obstacles); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode874-walking-robot-simulation_hashset_with_string.cpp b/cpp-leetcode/leetcode874-walking-robot-simulation_hashset_with_string.cpp new file mode 100644 index 00000000..54875ba9 --- /dev/null +++ b/cpp-leetcode/leetcode874-walking-robot-simulation_hashset_with_string.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int robotSim(vector& commands, vector>& obstacles) { + unordered_set obSet; // 压缩信息: 以"x-y"的形式存储障碍物的坐标信息 + for (auto& obp : obstacles) obSet.insert(pathStr(obp[0], obp[1])); + int x = 0, y = 0; + int idx = 0; // idx: 此时落在方向数组中的index, index in direction array + int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; /* 第1个元素表示向北的方向, 机器人一开始面向北方, 4个依次表示北、东、南、西(0,1,2,3) */ + int res = 0; // 当前机器人所在位置与原点之间的欧式距离的平方 + for (auto& c : commands) + { + if (c == -2) idx = (idx + 3) % 4; // 左转1次(相当于右转3次), +3后%4 防止数组越界 + else if (c == -1) idx = (idx + 1) % 4; // 右转1次, +1后%4 防止数组越界 + else + { + for (int i = 0; i < c; i++) + { + int a = x + dx[idx]; + int b = y + dy[idx]; + if (obSet.count(pathStr(a, b))) break; + x = a; // 从临时变量中更新 + y = b; + res = max(res, x * x + y * y); + } + } + } + return res; + } + string pathStr(int x, int y) + { + return to_string(x) + '#' + to_string(y); + } +}; + +// Test +int main() +{ + Solution sol; + vector> obstacles = {{2, 4}}; + vector commands = {4, -1, 4, -2, 4}; + auto res = sol.robotSim(commands, obstacles); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode874-walking-robot-simulation_set_with_hashcode.cpp b/cpp-leetcode/leetcode874-walking-robot-simulation_set_with_hashcode.cpp new file mode 100644 index 00000000..9c30fb49 --- /dev/null +++ b/cpp-leetcode/leetcode874-walking-robot-simulation_set_with_hashcode.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +private: + int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; +public: + int robotSim(vector& commands, vector>& obstacles) { + unordered_set obSet; + for(const auto& vec: obstacles) + obSet.insert(hashcode(vec[0], vec[1])); + + pair pos = make_pair(0, 0); + int index = 0; + int res = 0; + for(int& c : commands) + if (c == -1) index = (index + 1) % 4; + else if (c == -2) index = (index + 3) % 4; + else { + assert (c > 0); + for (int i = 0 ; i < c; i++) + { + pair nextPos = make_pair(pos.first + dir[index][0], pos.second + dir[index][1]); + if (obSet.count(hashcode(nextPos.first, nextPos.second)) == 0) + { + pos = nextPos; + res = max(res, pos.first * pos.first + pos.second * pos.second); + } + else break; + } + } + return res; + } +private: + long long hashcode(int a, int b) + { + return ((long long)a + 30000ll) * 60001ll + (long long)b + 30000ll; + } +}; + +// Test +int main() +{ + Solution sol; + vector> obstacles = {{2, 4}}; + vector commands = {4, -1, 4, -2, 4}; + auto res = sol.robotSim(commands, obstacles); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode874-walking-robot-simulation_set_with_pair1.cpp b/cpp-leetcode/leetcode874-walking-robot-simulation_set_with_pair1.cpp new file mode 100644 index 00000000..b5b92fbc --- /dev/null +++ b/cpp-leetcode/leetcode874-walking-robot-simulation_set_with_pair1.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int robotSim(vector& commands, vector>& obstacles) { + int dx[] = {0, 1, 0, -1}; + int dy[] = {1, 0, -1, 0}; + int x = 0, y = 0; + int curIdx = 0; + const int comLen = commands.size(); + int res = 0; + set> obSet; + for (int i = 0; i < obstacles.size(); ++i) + { + obSet.insert(make_pair(obstacles[i][0], obstacles[i][1])); + } + for (int i = 0; i < comLen; ++i) + { + if (commands[i] == -2) // 取模是为了防止数组越界 + curIdx = (curIdx + 3) % 4; + else if (commands[i] == -1) + curIdx = (curIdx + 1) % 4; + else { + for (int j = 0; j < commands[i]; j++) + { + int nx = x + dx[curIdx]; + int ny = y + dy[curIdx]; + if (obSet.count(make_pair(nx, ny)) == 0) + { + x = nx; + y = ny; + res = max(res, x * x + y * y); + } + else break; + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector> obstacles = {{2, 4}}; + vector commands = {4, -1, 4, -2, 4}; + auto res = sol.robotSim(commands, obstacles); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode877-stone-game_math_solution.cpp b/cpp-leetcode/leetcode877-stone-game_math_solution.cpp new file mode 100644 index 00000000..2fc865aa --- /dev/null +++ b/cpp-leetcode/leetcode877-stone-game_math_solution.cpp @@ -0,0 +1,21 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool stoneGame(vector& piles) { + return true; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 3, 4, 5}; + auto res = sol.stoneGame(nums); + cout << (res == true ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode88-merge-sorted-array.cpp b/cpp-leetcode/leetcode88-merge-sorted-array.cpp new file mode 100644 index 00000000..4b113c24 --- /dev/null +++ b/cpp-leetcode/leetcode88-merge-sorted-array.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + vector res; /* 题意: len(nums1) = m + n */ + int i = 0, j = 0; + while (i < m && j < n) // 只要一个指针扫到数组末尾,循环结束 + { + if(nums1[i] <= nums2[j]) + { + res.push_back(nums1[i]); + i++; + } + else { + res.push_back(nums2[j]); + j++; + } + } + + while(i < m) // 数组nums1没跑完,nums2已跑完时 + { + res.push_back(nums1[i]); + i++; + } + + while(j < n) // 数组nums2没跑完,nums1已跑完时 + { + res.push_back(nums2[j]); + j++; + } + + // 无需 return, 但需要更新nums1 + nums1 = res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums1 = {1,2,3,0,0,0}; + vector nums2 = {0,2,5}; + int m = 3, n = 3; + sol.merge(nums1, m, nums2, n); + + for(auto num : nums1) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode9-palindrome-number-method2.cpp b/cpp-leetcode/leetcode9-palindrome-number-method2.cpp new file mode 100644 index 00000000..7e83195c --- /dev/null +++ b/cpp-leetcode/leetcode9-palindrome-number-method2.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) return false; + string str = to_string(x); + int len = str.size(); + int l = 0, r = len - 1; + + while (l < len/2 && r >= len/2) + { + if (str[l] != str[r]) + { + return false; + } + + l++; + r--; + } + return true; + } +}; + +// Below is testing +int main() +{ + Solution sol; + int num = -101; + // cout << std::boolalpha << sol.isPalindrome(num) << endl; + cout << (sol.isPalindrome(num) == true ? "true" : "false") << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode9-palindrome-number-method3.cpp b/cpp-leetcode/leetcode9-palindrome-number-method3.cpp new file mode 100644 index 00000000..a7bb0671 --- /dev/null +++ b/cpp-leetcode/leetcode9-palindrome-number-method3.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) return false; + string str = to_string(x); + + string rs; + rs.assign(str.rbegin(), str.rend()); // Use reverse iterators + + if (rs == str) + return true; + else + return false; + } +}; + +// Below is testing +int main() +{ + Solution sol; + int num = -101; + // cout << std::boolalpha << sol.isPalindrome(num) << endl; + cout << (sol.isPalindrome(num) == true ? "true" : "false") << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode9-palindrome-number-method4.cpp b/cpp-leetcode/leetcode9-palindrome-number-method4.cpp new file mode 100644 index 00000000..8153b9f9 --- /dev/null +++ b/cpp-leetcode/leetcode9-palindrome-number-method4.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) return false; + + vector digits; + while(x) + { + digits.push_back(x % 10); + x /= 10; + } + vector temp = digits; + + reverse(digits.begin(), digits.end()); + if (temp == digits) + return true; + else + return false; + } +}; + +// Below is testing +int main() +{ + Solution sol; + int num = -101; + // cout << std::boolalpha << sol.isPalindrome(num) << endl; + cout << (sol.isPalindrome(num) == true ? "true" : "false") << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode9-palindrome-number.cpp b/cpp-leetcode/leetcode9-palindrome-number.cpp new file mode 100644 index 00000000..7e83195c --- /dev/null +++ b/cpp-leetcode/leetcode9-palindrome-number.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) return false; + string str = to_string(x); + int len = str.size(); + int l = 0, r = len - 1; + + while (l < len/2 && r >= len/2) + { + if (str[l] != str[r]) + { + return false; + } + + l++; + r--; + } + return true; + } +}; + +// Below is testing +int main() +{ + Solution sol; + int num = -101; + // cout << std::boolalpha << sol.isPalindrome(num) << endl; + cout << (sol.isPalindrome(num) == true ? "true" : "false") << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode90-subsets-ii_bfs1.cpp b/cpp-leetcode/leetcode90-subsets-ii_bfs1.cpp new file mode 100644 index 00000000..3fb341a2 --- /dev/null +++ b/cpp-leetcode/leetcode90-subsets-ii_bfs1.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +using namespace std; + +// 方法: 回溯/dfs +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + if (nums.empty()) return {{}}; + const int len = nums.size(); + vector> res; + if (len > 1) + sort(nums.begin(), nums.end()); + res.push_back({}); /* 空集必然是其中一个子集 */ + vector curSet; + for (int i = 1; i <= len; i++) + dfs(nums, i, 0, curSet, res); + return res; + } + + void dfs(const vector& nums, int len, int startPos, vector& curSet, vector>& res) + { + if (len == curSet.size()) + { + res.push_back(curSet); + return; + } + + for (int i = startPos; i < nums.size(); i++) + { + /* 去重, 当目前子区间内第1个元素(index为0)以后的元素出现重复时, 需要去重处理 */ + if (i > startPos && nums[i] == nums[i - 1]) continue; + curSet.push_back(nums[i]); // Choose + dfs(nums, len, i+1, curSet, res); // Explore + curSet.pop_back(); // Un-choose + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 1, 3}; + auto res = sol.subsetsWithDup(nums); + for (auto& row : res) // 遍历每一行 + { + cout << "{"; + for (int i = 0; i < row.size(); i++) // 输出每一个元素 + { + auto elem = row[i]; + if (row.size() >= 2 && i <= row.size() - 2) + cout << elem << ", "; + if (i == row.size() - 1) cout << elem; + } + cout << "}\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode90-subsets-ii_bfs2.cpp b/cpp-leetcode/leetcode90-subsets-ii_bfs2.cpp new file mode 100644 index 00000000..306518d6 --- /dev/null +++ b/cpp-leetcode/leetcode90-subsets-ii_bfs2.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +using namespace std; + +// 方法: 回溯/dfs +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + vector> res; + if (nums.size() < 1) return res; + sort(nums.begin(), nums.end()); + vector curSet; + dfs(nums, 0, curSet, res); + return res; + } + void dfs(vector& nums, int startPos, vector& curSet, vector>& res) + { + if (startPos == nums.size()) + { + res.push_back(curSet); + return; + } + curSet.push_back(nums[startPos]); + dfs(nums, startPos + 1, curSet, res); + curSet.pop_back(); + /* 跳过相同值 */ + while (startPos + 1 < nums.size() && nums[startPos + 1] == nums[startPos]) + startPos++; + dfs(nums, startPos + 1, curSet, res); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {1, 2, 1, 3}; + auto res = sol.subsetsWithDup(nums); + for (auto& row : res) // 遍历每一行 + { + cout << "{"; + for (int i = 0; i < row.size(); i++) // 输出每一个元素 + { + auto elem = row[i]; + if (row.size() >= 2 && i <= row.size() - 2) + cout << elem << ", "; + if (i == row.size() - 1) cout << elem; + } + cout << "}\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode912-sort-an-array_count_sort.cpp b/cpp-leetcode/leetcode912-sort-an-array_count_sort.cpp new file mode 100644 index 00000000..80d30cfd --- /dev/null +++ b/cpp-leetcode/leetcode912-sort-an-array_count_sort.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +const int N = 5e4; +class Solution { +public: + vector sortArray(vector& nums) { + vector dict(2*N + 1, 0); // dict[id]: value -> count + vector res; + for (auto& num : nums) + dict[num + N]++; + for (int i = 0; i < dict.size(); i++) + { + while (dict[i] > 0) + { + res.push_back(i - N); + dict[i]--; + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 1, 3, 1, 2, 3, 3}; + auto res = sol.sortArray(nums); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode912-sort-an-array_merge_sort.cpp b/cpp-leetcode/leetcode912-sort-an-array_merge_sort.cpp new file mode 100644 index 00000000..1f7fcb78 --- /dev/null +++ b/cpp-leetcode/leetcode912-sort-an-array_merge_sort.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +const int N = 2e5 + 10; +int A[N], tmp[N]; +class Solution { +public: + vector sortArray(vector& nums) { + const int len = nums.size(); + mergeSort(nums, 0, len - 1); + return nums; + } + void mergeSort(vector& A, int l, int r) + { + if (l >= r) return; + + int mid = (l+r)/2; + mergeSort(A, l, mid); + mergeSort(A, mid+1, r); + int i = l, j = mid+1, k=0; + while (i <= mid && j <= r) + { + if (A[i] <= A[j]) tmp[k++] = A[i++]; + else tmp[k++] = A[j++]; + } + // 上面这次循环结束时, 如果左半边没处理完需要进行如下操作 + while (i <= mid) tmp[k++] = A[i++]; + while (j <= r) tmp[k++] = A[j++]; + for (int i=l, j=0; i <= r; i++, j++) A[i] = tmp[j]; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 1, 3, 1, 2, 3, 3}; + auto res = sol.sortArray(nums); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode912-sort-an-array_quick_sort.cpp b/cpp-leetcode/leetcode912-sort-an-array_quick_sort.cpp new file mode 100644 index 00000000..889658ba --- /dev/null +++ b/cpp-leetcode/leetcode912-sort-an-array_quick_sort.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +const int N = 2e5 + 10; +class Solution { +public: + vector sortArray(vector& nums) { + const int len = nums.size(); + quickSort(nums, 0, len - 1); + return nums; + } + void quickSort(vector& A, int l, int r) + { + if (l >= r) return; + int x = A[(l+r)/2]; // 分界点取中间点比较保险, 因为有时会遇到最坏的情形(极度散乱, 熵最大时)~ + int i = l - 1, j = r + 1; /* 每次交换完之后, 向中间一定1位 */ + // 双指针 + while (i < j) + { + i++; + while (A[i] < x) i++; + j--; + while (A[j] > x) j--; + if (i < j) swap(A[i], A[j]); + } + // 递归处理左侧 + quickSort(A, l, j); + // 递归处理右侧 + quickSort(A, j+1, r); + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 1, 3, 1, 2, 3, 3}; + auto res = sol.sortArray(nums); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode912-sort-an-array_using_sort_function.cpp b/cpp-leetcode/leetcode912-sort-an-array_using_sort_function.cpp new file mode 100644 index 00000000..f31679c3 --- /dev/null +++ b/cpp-leetcode/leetcode912-sort-an-array_using_sort_function.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector sortArray(vector& nums) { + sort(nums.begin(), nums.end()); + return nums; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {5, 1, 3, 1, 2, 3, 3}; + auto res = sol.sortArray(nums); + for (auto& num : res) + cout << num << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode92-reverse-linked-list-ii.cpp b/cpp-leetcode/leetcode92-reverse-linked-list-ii.cpp new file mode 100644 index 00000000..d060a4c9 --- /dev/null +++ b/cpp-leetcode/leetcode92-reverse-linked-list-ii.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +using namespace std; +/** + * Definition for singly-linked list. +*/ +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int left, int right) { + auto fakeNode = new ListNode(-1); + fakeNode->next = head; + auto a = fakeNode; + for (int i = 0; i < left - 1; i++) + a = a->next; + auto b = a->next, c = b->next; + for (int i = 0; i < right - left; i++) + { + auto d = c->next; + c->next = b; + b = c; + c = d; + } + a->next->next = c; + a->next = b; + auto res = fakeNode->next; + delete fakeNode; + + return res; + } +}; + +// Test +int main() +{ + Solution sol; // 5->2->3->8->6 + ListNode *head = new ListNode(5); + head->next = new ListNode(2); + head->next->next = new ListNode(3); + head->next->next->next = new ListNode(8); + head->next->next->next->next = new ListNode(6); + head->next->next->next->next->next = nullptr; + + int left = 2, right = 4; + ListNode *res = sol.reverseBetween(head, left, right); /* 5->8->3->2->6 */ + ListNode *p = res; + while (p != nullptr) + { + cout << p->val << endl; + p = p->next; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode93-restore-ip-addresses_dfs.cpp b/cpp-leetcode/leetcode93-restore-ip-addresses_dfs.cpp new file mode 100644 index 00000000..f4532701 --- /dev/null +++ b/cpp-leetcode/leetcode93-restore-ip-addresses_dfs.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector restoreIpAddresses(string s) { + vector res; + dfs(s, 0, 0, "", "", res); + return res; + } + /* seg: 当前扫描的两个.之间的部分, ip: 当前从index=0处开始拼接起来的字符串, 合法的segIndex: [0, 2] */ + void dfs(string s, int startPos, int segIndex, string seg, string ip, vector& res) + { + if (startPos == s.size() && segIndex == 3 && isValidSeg(seg)) + res.push_back(ip + seg); + else if (startPos < s.size() && segIndex <= 3) + { + char ch = s[startPos]; + /* 例如, 当输入字符串是"10203040"且恰好处理到其中的字符'2'时, 有可能得到"102.", 也可能得到"10.2" */ + if (isValidSeg(seg + ch)) /* 尝试往seg中添加原串s(只有数字, 不含有点.)中的一个新字符 */ + dfs(s, startPos + 1, segIndex, seg + ch, ip, res); + if (seg != "" && segIndex < 3) /* 尝试往当前的ip串末尾加入一个点. */ + dfs(s, startPos, segIndex + 1, "", ip + seg + ".", res); + } + } + + bool isValidSeg(string seg) + { + return stoi(seg) <= 255 && (seg == "0" || seg[0] != '0'); + } +}; + +// Test +int main() +{ + Solution sol; + string S = "25525511135"; + vector res = sol.restoreIpAddresses(S); + + for (string str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode93-restore-ip-addresses_enum.cpp b/cpp-leetcode/leetcode93-restore-ip-addresses_enum.cpp new file mode 100644 index 00000000..d4302afe --- /dev/null +++ b/cpp-leetcode/leetcode93-restore-ip-addresses_enum.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector restoreIpAddresses(string s) { + vector res; + for (int i = 1; i < 4; i++) + { + for (int j = 1; j < 4; j++) + { + for (int k = 1; k < 4; k++) + { + for (int m = 1; m < 4; m++) + { + if (i + j + k + m != s.size()) + continue; + int a = stoi(s.substr(0, i)); + int b = stoi(s.substr(i, j)); + int c = stoi(s.substr(i + j, k)); + + int d = stoi(s.substr(i + j + k)); + if (a <= 255 && b <= 255 && c <= 255 && d <= 255) + { + string buffer = to_string(a) + "." + to_string(b) + "." + to_string(c) + "." + to_string(d); + /* 处理先导0, 比如 "0.0.0.0"是合法的, 而"0.01.0.0"不是, 下面的+3是表示3个点. */ + if (buffer.size() == s.size() + 3) + { + res.push_back(buffer); + } + } + } + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + string S = "25525511135"; + vector res = sol.restoreIpAddresses(S); + + for (string str : res) + cout << str << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode938-range-sum-of-bst_inorder1.cpp b/cpp-leetcode/leetcode938-range-sum-of-bst_inorder1.cpp new file mode 100644 index 00000000..6d1d7148 --- /dev/null +++ b/cpp-leetcode/leetcode938-range-sum-of-bst_inorder1.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + int rangeSumBST(TreeNode* root, int low, int high) { + vector nums; + inorder(root, nums); + int sum = 0; + for (auto& num : nums) + { + if (num >= low && num <= high) + sum += num; + } + return sum; + } + void inorder(TreeNode* root, vector& nums) + { + if (!root) return; + inorder(root->left, nums); + nums.push_back(root->val); + inorder(root->right, nums); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(10); + root->left = new TreeNode(5); + root->right = new TreeNode(15); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(7); + root->right->right = new TreeNode(18); + + auto res = sol.rangeSumBST(root, 7, 15); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode938-range-sum-of-bst_inorder2.cpp b/cpp-leetcode/leetcode938-range-sum-of-bst_inorder2.cpp new file mode 100644 index 00000000..f29f5d54 --- /dev/null +++ b/cpp-leetcode/leetcode938-range-sum-of-bst_inorder2.cpp @@ -0,0 +1,54 @@ +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { + int L; + int H; +public: + int rangeSumBST(TreeNode* root, int low, int high) { + int sum = 0; + L = low; + H = high; + inorder(root, sum); + return sum; + } + void inorder(TreeNode* root, int& sum) + { + if (!root) return; + inorder(root->left, sum); + int num = root->val; + if (num >= L && num <= H) + sum += num; + inorder(root->right, sum); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(10); + root->left = new TreeNode(5); + root->right = new TreeNode(15); + root->left->left = new TreeNode(3); + root->left->right = new TreeNode(7); + root->right->right = new TreeNode(18); + + auto res = sol.rangeSumBST(root, 7, 15); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_deque.cpp b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_deque.cpp new file mode 100644 index 00000000..e9ec8e76 --- /dev/null +++ b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_deque.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 中序遍历顺序: 左根右 */ +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + if(root == NULL) + return {}; + vector res; + deque st; /* 辅助栈, 处理顺序是: + 访问root -> 遍历左子树 -> 输出左子树 -> 输出root -> 遍历右子树 -> 输出右子树 */ + TreeNode* p = root; + + while (!st.empty() || p != NULL) + { + /* 遍历part 1: 把根结点、左子树的结点依次压入栈中, 这样如果在访问右子树之前出栈, 根结点必然最后一个出来 */ + while (p != NULL) + { + st.push_front(p); + p = p -> left; + } + + p = st.front(); + st.pop_front(); + res.push_back(p -> val); /* 按序向 res数组中插入栈的top位置的每个值 */ + + /* 遍历part 2: 把剩下的右子树的结点依次压入栈中 */ + p = p -> right; + } + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.inorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_deque_with_extra_struct.cpp b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_deque_with_extra_struct.cpp new file mode 100644 index 00000000..50675e58 --- /dev/null +++ b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_deque_with_extra_struct.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; +struct Pack { + int op; /* 0, to visit; 1, visited, need print/save */ + TreeNode* node; + Pack(int op, TreeNode* node) { + this->op = op; + this->node = node; + } +}; + +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + vector res; + deque st; + st.push_front(new Pack(0, root)); + + while (!st.empty()) + { + Pack* cur = st.front(); // 先front(), 再pop + st.pop_front(); + if (cur->node == nullptr) + continue; /* 此时该 TreeNode的val/left/right都没法取到, 故不需要处理 */ + if (cur->op == 1) + res.push_back(cur->node->val); + else + { + /* 基于deque的辅助栈, 要求每一个结点及其子树的输出(遍历)顺序: 左 根 右, 于是放入顺序遍历顺序: 右 根 左 */ + st.push_front(new Pack(0, cur->node->right)); + st.push_front(new Pack(1, cur->node)); + st.push_front(new Pack(0, cur->node->left)); + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.inorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_recursive.cpp b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_recursive.cpp new file mode 100644 index 00000000..0824cdc6 --- /dev/null +++ b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_recursive.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +/* 中序遍历顺序: 左根右 */ +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + if(root == NULL) + return {}; + + TreeNode* p = root; + vector res = inorderTraversal(root->left); // left + res.push_back(root->val); + vector right = inorderTraversal(root->right); + res.insert(res.end(), right.begin(), right.end()); + + return res; + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.inorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_recursive2.cpp b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_recursive2.cpp new file mode 100644 index 00000000..6b88a43a --- /dev/null +++ b/cpp-leetcode/leetcode94-binary-tree-inorder-traversal_recursive2.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + if (root == NULL) return {}; + vector vals; + inorderHelper(root, vals); + return vals; + } + void inorderHelper(TreeNode* root, vector& vals) /* 这里的引用传递&不能忘了 */ + { + if (root == NULL) return; + inorderHelper(root->left, vals); + vals.push_back(root->val); + inorderHelper(root->right, vals); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(1); + root->left = NULL; + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + vector res = sol.inorderTraversal(root); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode949-largest-time-for-given-digits_brute_force.cpp b/cpp-leetcode/leetcode949-largest-time-for-given-digits_brute_force.cpp new file mode 100644 index 00000000..d1a47b60 --- /dev/null +++ b/cpp-leetcode/leetcode949-largest-time-for-given-digits_brute_force.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + /** + * 4个数字全排列总共有24种可能, 判断每一种可能是否能组成合法时间值, 如果能, 再和当前保存的最大值进行比较; + * 最大值是一个int值, 用来表示分钟数; + */ + string largestTimeFromDigits(vector& arr) { + int largest = -1; + // 依次暴力枚举出4个数 + for(int i = 0; i < 4; i++) { + for(int j = 0; j < 4; j++) { + for(int k = 0; k < 4; k++) { + if(i == j || i == k || j == k) continue; + // 0,1,2,3 总和为6, 故剩下的index为6-three sum of index + int l = 6 - i - j - k; + + int res = composeTime(i, j, k, l, arr); + largest = max(largest, res); + } + } + } + if(largest == -1) return ""; + + string str1(5, '0'); + sprintf(&str1[0], "%02d:%02d", largest / 60, largest % 60); + return str1; + } + /* 判断输入的四个数字按照输入顺序组成的时间是否合法, 如果合法, 返回分钟数 */ + int composeTime(int a, int b, int c, int d, vector& nums) + { + int hours = nums[a] * 10 + nums[b]; + int min = nums[c] * 10 + nums[d]; + + if(hours < 24 && min < 60) + return hours * 60 + min; + + return -1; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 0, 6, 6}; + auto res = sol.largestTimeFromDigits(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode949-largest-time-for-given-digits_classification.cpp b/cpp-leetcode/leetcode949-largest-time-for-given-digits_classification.cpp new file mode 100644 index 00000000..dbd1026a --- /dev/null +++ b/cpp-leetcode/leetcode949-largest-time-for-given-digits_classification.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string largestTimeFromDigits(vector& arr) { + sort(arr.begin(), arr.end()); + if (arr[0]*10 + arr[1] > 23) return ""; + + vector> hhs; // hour, i, j + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + { + if (i != j && (arr[i]*10 + arr[j] < 24)) + hhs.push_back({arr[i]*10 + arr[j], i, j}); + } + } + sort(hhs.begin(), hhs.end(), greater<>()); + vector validHhs; + vector last2num; + bool ok = getValidLast2num(hhs, arr, last2num, validHhs); + if (!ok) return ""; + int hour = validHhs.at(0); + int digitB = hour % 10; + int digitA = hour / 10; + + if (last2num[0] >= 6 && last2num[1] >= 6) return ""; + string res = to_string(digitA) + to_string(digitB) + ":"; + string minu; + if (last2num[0] < 6 && last2num[1] < 6) + { + sort(last2num.begin(), last2num.end(), greater<>()); + minu.push_back(last2num[0] + '0'); + minu.push_back(last2num[1] + '0'); + res += minu; + } + else if (last2num[0] >= 6 || last2num[1] >= 6) + { + sort(last2num.begin(), last2num.end()); + minu.push_back(last2num[0] + '0'); + minu.push_back(last2num[1] + '0'); + res += minu; + } + return res; + } + bool getValidLast2num(vector> hhs, vector arr, vector& last2num, vector& validHhs) + { + bool canGetValidLast2num = false; + for (int k = 0; k < hhs.size(); k++) + { + vector hh = hhs[k]; + last2num.clear(); // 这个地方很关键 + for (int i = 0; i < 4; i++) + { + if (i != hh.at(1) && i != hh.at(2)) + last2num.push_back(arr[i]); + } + if ((last2num[0]*10 + last2num[1] <= 60) || (last2num[1]*10 + last2num[0] <= 60)) + { + canGetValidLast2num = true; + validHhs = hh; + break; + } + } + return canGetValidLast2num; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 0, 6, 6}; + auto res = sol.largestTimeFromDigits(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode949-largest-time-for-given-digits_next_permutation.cpp b/cpp-leetcode/leetcode949-largest-time-for-given-digits_next_permutation.cpp new file mode 100644 index 00000000..66fa4cd6 --- /dev/null +++ b/cpp-leetcode/leetcode949-largest-time-for-given-digits_next_permutation.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + string largestTimeFromDigits(vector& A) { + string res = ""; + sort(A.begin(), A.end()); + do + { + if ((A[0] == 2 && A[1] <= 3 || A[0] < 2) && A[2] <= 5) + { + string curTime = to_string(A[0]) + to_string(A[1]) + ":" + + to_string(A[2])+to_string(A[3]); + if (curTime > res) res = curTime; + } + } while (next_permutation(A.begin(), A.end())); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 0, 6, 6}; + auto res = sol.largestTimeFromDigits(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode949-largest-time-for-given-digits_regex_and_backtracking.cpp b/cpp-leetcode/leetcode949-largest-time-for-given-digits_regex_and_backtracking.cpp new file mode 100644 index 00000000..313b98b3 --- /dev/null +++ b/cpp-leetcode/leetcode949-largest-time-for-given-digits_regex_and_backtracking.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string res = ""; + string largestTimeFromDigits(vector& A) + { + regex pattern("([0-1][0-9]:[0-5][0-9])|([2][0-3]:[0-5][0-9])"); + map dict; // 存储每个数字digit出现的次数 + for (int i = 0; i < A.size(); i++) + dict[A[i]]++; + + string str = ""; + backTrack(dict, str, pattern); + return res; + } + void backTrack(map dict, string str, regex& pattern) + { + if (str.length() == 2) + str += ":"; + + if (str.length() == 5) + { + if (regex_match(str, pattern)) + res = max(res, str); //valid time + + return; + } + for (auto it = dict.begin(); it != dict.end(); it++) + { + if (it->second != 0) + { + int val = it->first; + dict[val]--; + backTrack(dict, str + to_string(val), pattern); + dict[val]++; + } + } + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {2, 0, 6, 6}; + auto res = sol.largestTimeFromDigits(nums); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode95-unique-binary-search-trees-ii_dfs.cpp b/cpp-leetcode/leetcode95-unique-binary-search-trees-ii_dfs.cpp new file mode 100644 index 00000000..4e4d8d8d --- /dev/null +++ b/cpp-leetcode/leetcode95-unique-binary-search-trees-ii_dfs.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + vector generateTrees(int n) { + // [1, 2, ... i ... n] + // 按二叉搜索树的特性进行分组: [1, i-1] i [i+1, n] + // f(1, n) = { combination(f(1, 1 - 1), f(i + 1, n) ) }, 1 <= i <= n + if (n == 1) + return { new TreeNode(1) }; + return helper(1, n); + } + vector helper(int start, int end) + { + vector res; + if (start > end) + { + res.push_back(nullptr); + return res; + } + for (int i = start; i <= end; i++) + { + auto leftChildren = helper(start, i - 1); + auto rightChildren = helper(i + 1, end); + for (auto left : leftChildren) + { + for (auto right : rightChildren) + { + auto root = new TreeNode(i); + root->left = left; + root->right = right; + res.push_back(root); + } + } + } + return res; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 3; + auto res = sol.generateTrees(n); + for (auto& node : res) + cout << node->val << " "; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode96-unique-binary-search-trees_dp_using_array.cpp b/cpp-leetcode/leetcode96-unique-binary-search-trees_dp_using_array.cpp new file mode 100644 index 00000000..68d87226 --- /dev/null +++ b/cpp-leetcode/leetcode96-unique-binary-search-trees_dp_using_array.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int numTrees(int n) { + int dp[n+1]; + fill(dp, dp + n + 1, 0); + dp[0] = 1; // root == null的树, 只有1棵 + + for (int i = 1; i <= n; i++) + { + for (int k = 0; k <= i-1; k++) + { + dp[i] += dp[k] * dp[i - 1 - k]; + } + } + return dp[n]; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 3; + auto res = sol.numTrees(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode96-unique-binary-search-trees_dp_using_vector.cpp b/cpp-leetcode/leetcode96-unique-binary-search-trees_dp_using_vector.cpp new file mode 100644 index 00000000..f34187c3 --- /dev/null +++ b/cpp-leetcode/leetcode96-unique-binary-search-trees_dp_using_vector.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int numTrees(int n) { + vector dp(n+1, 0); + dp[0] = 1; // root == null的树, 只有1棵 + for (int i = 1; i <= n; i++) + { + for (int k = 0; k <= i-1; k++) + { + dp[i] += dp[k] * dp[i - 1 - k]; + } + } + return dp[n]; + } +}; + +// Test +int main() +{ + Solution sol; + int n = 3; + auto res = sol.numTrees(n); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode976-largest-perimeter-triangle_sort.cpp b/cpp-leetcode/leetcode976-largest-perimeter-triangle_sort.cpp new file mode 100644 index 00000000..10bcfa33 --- /dev/null +++ b/cpp-leetcode/leetcode976-largest-perimeter-triangle_sort.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int largestPerimeter(vector& nums) { + sort(nums.begin(), nums.end(), greater()); + const int len = nums.size(); + for (int i = 0; i < len - 2; i++) + { + if (nums[i] < nums[i + 1] + nums[i + 2]) + return nums[i] + nums[i + 1] + nums[i + 2]; + } + return 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {3, 2, 3, 4}; + auto res = sol.largestPerimeter(nums); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort1.cpp b/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort1.cpp new file mode 100644 index 00000000..cb7ca57c --- /dev/null +++ b/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort1.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector sortedSquares(vector& nums) { + vector squares; + for (auto& num : nums) squares.push_back(num * num); + sort(squares.begin(), squares.end()); + return squares; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-4, -1, 0, 3, 10}; + auto res = sol.sortedSquares(nums); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort1_optimize.cpp b/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort1_optimize.cpp new file mode 100644 index 00000000..130acdbd --- /dev/null +++ b/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort1_optimize.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector sortedSquares(vector& nums) { + vector squares; + for (auto& num : nums) squares.push_back(num * num); + if (nums.front() >= 0) return squares; + if (nums.back() <= 0) + { + reverse(squares.begin(), squares.end()); + return squares; + } + sort(squares.begin(), squares.end()); + return squares; + } +}; +// Test +int main() +{ + Solution sol; + vector nums = {-4, -1, 0, 3, 10}; + auto res = sol.sortedSquares(nums); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort_by_abs.cpp b/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort_by_abs.cpp new file mode 100644 index 00000000..d76f0c64 --- /dev/null +++ b/cpp-leetcode/leetcode977-squares-of-a-sorted-array_sort_by_abs.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector sortedSquares(vector& nums) { + vector squares; + auto cmp = [](const int& p1, const int& p2) + { + return abs(p1) < abs(p2); + }; + sort(nums.begin(), nums.end(), cmp); + for (auto& num : nums) squares.push_back(num * num); + return squares; + } +}; + +// Test +int main() +{ + Solution sol; + vector nums = {-4, -1, 0, 3, 10}; + auto res = sol.sortedSquares(nums); + printf("%d ", res); + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode987-vertical-order-traversal-of-a-binary-tree_dfs1.cpp b/cpp-leetcode/leetcode987-vertical-order-traversal-of-a-binary-tree_dfs1.cpp new file mode 100644 index 00000000..b1dfdcff --- /dev/null +++ b/cpp-leetcode/leetcode987-vertical-order-traversal-of-a-binary-tree_dfs1.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. + */ +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} +}; + +class Solution { + unordered_map>> dict; /* x -> array of (y, val), dict size: 不同x值的个数 */ + int minX = 1000; /* 记录最左边结点的横坐标x, 为了方便后面从哈希表中找到同一条竖直扫描线上的点 */ +public: + vector> verticalTraversal(TreeNode* root) + { + vector> res; + dfs(root, 0, 0); + int maxX = minX + dict.size() - 1; + for (int i = minX; i <= maxX; i++) + { + auto cmp = [](pair& p1, pair& p2) + { + if (p1.first != p2.first) + return (p1.first > p2.first); + return p1.second < p2.second; + }; + auto arr = dict[i]; // array of (y, val) for given x + sort(arr.begin(), arr.end(), cmp); + vector vLine; + for (int j = 0; j < arr.size(); j++) + vLine.push_back(arr[j].second); + res.push_back(vLine); + } + return res; + } + void dfs(TreeNode* root, int x, int y) + { + if (!root) return; + dict[x].push_back({y, root->val}); + minX = min(minX, x); + dfs(root->left, x - 1, y - 1); + dfs(root->right, x + 1, y - 1); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->right->left = new TreeNode(4); + root->right->right = nullptr; + + auto res = sol.verticalTraversal(root); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode987-vertical-order-traversal-of-a-binary-tree_dfs2.cpp b/cpp-leetcode/leetcode987-vertical-order-traversal-of-a-binary-tree_dfs2.cpp new file mode 100644 index 00000000..6d891d20 --- /dev/null +++ b/cpp-leetcode/leetcode987-vertical-order-traversal-of-a-binary-tree_dfs2.cpp @@ -0,0 +1,73 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. + */ +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} +}; + +class Solution { + unordered_map>> dict; /* x -> array of (y, val), dict size: 不同x值的个数 */ + int minX = 1000; /* 记录最左边结点的横坐标x, 为了方便后面从哈希表中找到同一条竖直扫描线上的点 */ +public: + vector> verticalTraversal(TreeNode* root) + { + vector> res; + dfs(root, 0, 0); + for (int i = 0; i < dict.size(); i++) /* i: 不同x值的个数 */ + { + int x = minX + i; /* 遍历完x所在的区间 [minX, maxX] */ + auto cmp = [](pair& p1, pair& p2) + { + if (p1.first != p2.first) + return (p1.first > p2.first); + return p1.second < p2.second; + }; + auto arr = dict[x]; // array of (y, val) for given x + sort(arr.begin(), arr.end(), cmp); + vector vLine; + for (int j = 0; j < arr.size(); j++) + vLine.push_back(arr[j].second); + res.push_back(vLine); + } + return res; + } + void dfs(TreeNode* root, int x, int y) + { + if (!root) return; + dict[x].push_back({y, root->val}); + minX = min(minX, x); /* 与主函数verticalTraversal()中的语句 int x = minX + i; 配合使用 */ + dfs(root->left, x - 1, y - 1); + dfs(root->right, x + 1, y - 1); + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->right->left = new TreeNode(4); + root->right->right = nullptr; + + auto res = sol.verticalTraversal(root); + for (auto& row : res) // 遍历每一行 + { + for (auto& elem : row) // 输出每一个元素 + cout << elem << " "; + cout << "\n"; + } + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode989-add-to-array-form-of-integer_add_logic.cpp b/cpp-leetcode/leetcode989-add-to-array-form-of-integer_add_logic.cpp new file mode 100644 index 00000000..64c9de38 --- /dev/null +++ b/cpp-leetcode/leetcode989-add-to-array-form-of-integer_add_logic.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector addToArrayForm(vector& A, int k) { + if (k == 0) return A; /* 题目中k的范围是 k >= 0, 为0时不需要计算, 直接返回A */ + const int len = A.size(); + vector res; + // 数组A与数k的末位对齐, 对位相加, 记录进位 + int carry = 0; + int i = len - 1; // i: 数组A中从后往前的指针 + while (k > 0 || i >= 0) + { + int sum = (k % 10) + carry; + sum += (i >= 0 ? A[i] : 0); // 保证访问A[i]前不越界 + res.push_back(sum % 10); + carry = sum / 10; // 或写成 carry = (sum <= 9) ? 0 : 1; + k /= 10; // 删掉数k的最后一位, 继续进行下一轮迭代 + + i--; + } + if (carry == 1) res.push_back(1); /* 如果最高位产生进位, 需要在最后增加一位, 值为1 */ + reverse(res.begin(), res.end()); + return res; + } +}; + +// Test +int main() +{ + Solution sol; + vector A = {2, 7, 4}; + int K = 81; + + auto res = sol.addToArrayForm(A, K); + for (auto &num : res) + cout << num << endl; + + return 0; +} diff --git a/cpp-leetcode/leetcode99-recover-binary-search-tree_Morris_traversal_inorder.cpp b/cpp-leetcode/leetcode99-recover-binary-search-tree_Morris_traversal_inorder.cpp new file mode 100644 index 00000000..4bb1590b --- /dev/null +++ b/cpp-leetcode/leetcode99-recover-binary-search-tree_Morris_traversal_inorder.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + void recoverTree(TreeNode* root) { + TreeNode* first = nullptr; /* first: 记录第1个交换的点(逆序对) */ + TreeNode* second; /* second: 记录第2个交换的点 */ + TreeNode* last = nullptr; // last: 当前遍历指针所在位置的上一个node + while (root != nullptr) + { + if (root->left == nullptr) /* 如果没有左子树, 就遍历当前点 */ + { + if (last != nullptr && last->val > root->val) // 出现了逆序对 + { + if (first == nullptr) // 如果是第1个逆序对, 就把逆序对的两个点都存下来 + { + first = last; + second = root; + } + else second = root; /* 如果是第2个逆序对, 只需把逆序对的第2个点都存下来 */ + } + last = root; // 把当前点赋值给last, 为下一轮迭代做准备 + root = root->right; + } + else // 搭桥: 需要先找到前驱结点 + { + auto p = root->left; + while (p->right != nullptr && p->right != root) /* 如果当前结点(root)不为空且没有出现环路, 就继续向右移 */ + p = p->right; + if (p->right == nullptr) + { + p->right = root; /* 搭桥 */ + root = root->left; + } + else + { + // 拆桥 + p->right = nullptr; + if (last != nullptr && last->val > root->val) // 出现了逆序对, 下面的做法与前面相同 + { + if (first == nullptr) + { + first = last; + second = root; + } + else second = root; + } + last = root; + root = root->right; + } + } + } + swap(first->val, second->val); // 把错误交换了的结点的值恢复回来 + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(1); + root->right = new TreeNode(4); + root->right->left = new TreeNode(2); + + sol.recoverTree(root); + cout << root->val << endl; /* 输出恢复后的根结点的值 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode99-recover-binary-search-tree_inorder_traversal_recursive.cpp b/cpp-leetcode/leetcode99-recover-binary-search-tree_inorder_traversal_recursive.cpp new file mode 100644 index 00000000..93820884 --- /dev/null +++ b/cpp-leetcode/leetcode99-recover-binary-search-tree_inorder_traversal_recursive.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. +*/ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { + TreeNode* lastSeen = new TreeNode(INT_MIN); + TreeNode* first = nullptr; + TreeNode* second = nullptr; +public: + void recoverTree(TreeNode* root) + { + inOrder(root); + int tempVal = first->val; + first->val = second->val; + second->val = tempVal; + } + + void inOrder(TreeNode* node) + { + if (node == nullptr) return; + + inOrder(node->left); + if (node->val >= lastSeen->val) + lastSeen = node; + else /* 出现异常点 */ + { + if (first == nullptr) /* 第1处异常点 */ + { + first = lastSeen; + second = node; + lastSeen = node; + } + else /* 第2处异常点 */ + { + second = node; + return; + } + } + inOrder(node->right); + } +}; + +// Test +int main() +{ + Solution sol; + + TreeNode* root = new TreeNode(3); + root->left = new TreeNode(1); + root->right = new TreeNode(4); + root->right->left = new TreeNode(2); + + sol.recoverTree(root); + cout << root->val << endl; /* 输出恢复后的根结点的值 */ + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode991-broken-calculator_direct_method.cpp b/cpp-leetcode/leetcode991-broken-calculator_direct_method.cpp new file mode 100644 index 00000000..094831db --- /dev/null +++ b/cpp-leetcode/leetcode991-broken-calculator_direct_method.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int brokenCalc(int startValue, int target) { + if (startValue > target) return startValue - target; + + int count = 0; + while (startValue < target) + { + if (target % 2 == 0) + { + target /= 2; + count++; + } + else { + target += 1; + count++; + } + } + while (startValue > target) + { + target += 1; + count++; + if (startValue == target) return count; + } + return count; + } +}; + +// Test +int main() +{ + Solution sol; + int startValue = 3; + int target = 10; + auto res = sol.brokenCalc(startValue, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode991-broken-calculator_optimize2.cpp b/cpp-leetcode/leetcode991-broken-calculator_optimize2.cpp new file mode 100644 index 00000000..e0c02c76 --- /dev/null +++ b/cpp-leetcode/leetcode991-broken-calculator_optimize2.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int brokenCalc(int startValue, int target) { + if (startValue > target) return startValue - target; + int count = 0; + while (target > startValue) + { + count++; + if (target % 2 == 1) + target++; + else target /= 2; + } + return count + (startValue - target); /* 一旦出现 startValue >= target 的情形, 方法1代码中的第二个while循环就不需要了 */ + } +}; + +// Test +int main() +{ + Solution sol; + int startValue = 3; + int target = 10; + auto res = sol.brokenCalc(startValue, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode991-broken-calculator_optimize_remove_one_loop.cpp b/cpp-leetcode/leetcode991-broken-calculator_optimize_remove_one_loop.cpp new file mode 100644 index 00000000..b4999059 --- /dev/null +++ b/cpp-leetcode/leetcode991-broken-calculator_optimize_remove_one_loop.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int brokenCalc(int startValue, int target) { + if (startValue > target) return startValue - target; + + int count = 0; + while (startValue < target) + { + if (target % 2 == 0) + { + target /= 2; + count++; + } + else { + target += 1; + count++; + } + } + return count + (startValue - target); /* 一旦出现 startValue >= target 的情形, 方法1代码中的第二个while循环就不需要了 */ + } +}; + +// Test +int main() +{ + Solution sol; + int startValue = 3; + int target = 10; + auto res = sol.brokenCalc(startValue, target); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode993-cousins-in-binary-tree_dfs.cpp b/cpp-leetcode/leetcode993-cousins-in-binary-tree_dfs.cpp new file mode 100644 index 00000000..674384e7 --- /dev/null +++ b/cpp-leetcode/leetcode993-cousins-in-binary-tree_dfs.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +using namespace std; +/** + * Definition for a binary tree node. + */ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + bool isCousins(TreeNode* root, int x, int y) { + unordered_map depths; /* map: value -> depth */ + unordered_map parents; /* map: value -> parent value */ + dfs(root, 0, depths, parents); + if (depths[x] == depths[y] && parents[x] != parents[y]) + return true; + return false; + } + void dfs(TreeNode* root, int depth, unordered_map& depths, unordered_map& parents) + { + if (root == nullptr) return; + depths[root->val] = depth; + if (root->left != nullptr) + { + parents[root->left->val] = root->val; + dfs(root->left, depth + 1, depths, parents); + } + if (root->right != nullptr) + { + parents[root->right->val] = root->val; + dfs(root->right, depth + 1, depths, parents); + } + return; + } +}; + +// Test +int main() +{ + Solution sol; + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->right = new TreeNode(4); + root->right->right = new TreeNode(5); + auto res = sol.isCousins(root, 2, 3); + cout << (res ? "True" : "False") << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/leetcode999-available-captures-for-rook_dfs.cpp b/cpp-leetcode/leetcode999-available-captures-for-rook_dfs.cpp new file mode 100644 index 00000000..6a365cb6 --- /dev/null +++ b/cpp-leetcode/leetcode999-available-captures-for-rook_dfs.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +using namespace std; + +class Solution { + const int dx[4] = {-1, 0, 0, 1}; + const int dy[4] = {0, 1, -1, 0}; + const int N = 8; +public: + int numRookCaptures(vector>& board) { + int pCount = 0; + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + if (board[i][j] == 'R') + { + // 一旦发现一个 'R', 就检测其上下左右4个方向 + for (int k = 0; k < 4; k++) + { + int nx = i, ny = j; + while (nx >= 0 && nx < N && ny >= 0 && ny < N) /* 如果没越界 */ + { + if (board[nx][ny] == 'B') /* 遇到自己一方的象B时, 停在原处 */ + break; + else if (board[nx][ny] == 'p') /* 遇到对方的卒p时, 进入该格子, 然后停止 */ + { + pCount++; + break; + } + nx += dx[k]; + ny += dy[k]; + } + } + // 题意: 棋盘上最多只有一个 'R' 存在 + return pCount; + } + } + } + // 如果棋盘上没有车(R)或棋盘上没有能吃掉的卒 + return 0; + } +}; + +// Test +int main() +{ + Solution sol; + vector> board = + { + {'.','.','.','.','.','.','.','.'}, + {'.','.','.','p','.','.','.','.'}, + {'.','.','.','R','.','.','.','p'}, + {'.','.','.','.','.','.','.','.'}, + {'.','.','.','.','.','.','.','.'}, + {'.','.','.','p','.','.','.','.'}, + {'.','.','.','.','.','.','.','.'}, + {'.','.','.','.','.','.','.','.'} + }; + auto res = sol.numRookCaptures(board); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS.sln b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS.sln new file mode 100644 index 00000000..66aceddd --- /dev/null +++ b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lintcode77-LCS", "Lintcode77-LCS\Lintcode77-LCS.vcxproj", "{2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Debug|x64.ActiveCfg = Debug|x64 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Debug|x64.Build.0 = Debug|x64 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Debug|x86.ActiveCfg = Debug|Win32 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Debug|x86.Build.0 = Debug|Win32 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Release|x64.ActiveCfg = Release|x64 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Release|x64.Build.0 = Release|x64 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Release|x86.ActiveCfg = Release|Win32 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3BD7453C-0C62-4159-907E-519509BE6452} + EndGlobalSection +EndGlobal diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.cpp b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.cpp new file mode 100644 index 00000000..a559fd0e Binary files /dev/null and b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.cpp differ diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.vcxproj b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.vcxproj new file mode 100644 index 00000000..9e2d2d7e --- /dev/null +++ b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.vcxproj @@ -0,0 +1,165 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {2708665B-A16C-4348-9CAD-E4BD6B2D6A6F} + Win32Proj + Lintcode77LCS + 10.0.16299.0 + + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + Use + Level3 + Disabled + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Use + Level3 + Disabled + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Use + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Use + Level3 + MaxSpeed + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + Create + Create + Create + Create + + + + + + \ No newline at end of file diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.vcxproj.filters b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.vcxproj.filters new file mode 100644 index 00000000..fe325ae5 --- /dev/null +++ b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/Lintcode77-LCS.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/stdafx.cpp b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/stdafx.cpp new file mode 100644 index 00000000..716b654c Binary files /dev/null and b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/stdafx.cpp differ diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/stdafx.h b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/stdafx.h new file mode 100644 index 00000000..94d4ed87 Binary files /dev/null and b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/stdafx.h differ diff --git a/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/targetver.h b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/targetver.h new file mode 100644 index 00000000..567cd346 Binary files /dev/null and b/cpp-leetcode/lintcode77-LCS/Lintcode77-LCS/targetver.h differ diff --git a/cpp-leetcode/temp/leetcode20-valid-parentheses-temp.cpp b/cpp-leetcode/temp/leetcode20-valid-parentheses-temp.cpp new file mode 100644 index 00000000..b26780a1 --- /dev/null +++ b/cpp-leetcode/temp/leetcode20-valid-parentheses-temp.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + const vector left = { '(', '[', '{' }; + const vector right = { ')', ']', '}'}; + + bool isValid(string s) { + bool isValid; + bool isSym = true; + bool isCombineValid; + int len = s.size(); + if(len % 2 != 0 || find(right.begin(), right.end(), s.front()) != right.end() || find(left.begin(), left.end(), s.back()) != left.end()) return false; + + string curStr; + int i, lIndex, rIndex; + + // 情形1, 对称 + for (i = 0; i < len/2; i++) + { + char lch = s[i]; + char rch = s[len-i-1]; + if(!isAlwaysNeighbor(s) && (find(right.begin(), right.end(), lch) != right.end() || find(left.begin(), left.end(), rch) != left.end())) + return false; + lIndex = distance(left.begin(), find(left.begin(), left.end(), lch)); + rIndex = distance(right.begin(), find(right.begin(), right.end(), rch)); + if(lIndex != rIndex) + isSym = false; + } + if(isSym == false && i > 0) { + curStr = s.substr(lIndex, rIndex-lIndex+1); + isCombineValid = isAlwaysNeighbor(curStr); + } + isValid = isSym || isCombineValid || isAlwaysNeighbor(s); + + // 情形2, 自行成对 + + // 情形3: 边缘对称,内部相邻 + return isValid; + } + + bool isAlwaysNeighbor(string s){ + bool isAlwaysNeighbor = true; + for(int k = 0; k < (s.size()+1)/2; k = k+2) + { + char lch = s[k]; + char rch = s[k+1]; + int lIndex = distance(left.begin(), find(left.begin(), left.end(), lch)); + int rIndex = distance(right.begin(), find(right.begin(), right.end(), rch)); + if(lIndex != rIndex) + isAlwaysNeighbor = false; + } + return isAlwaysNeighbor; + } +}; + +//Test +int main() +{ + Solution sol; + string str = "()[]{}"; // "(}{)"; + bool res = sol.isValid(str); + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode498_sol1.cpp b/cpp-leetcode/temp/leetcode498_sol1.cpp new file mode 100644 index 00000000..8bb07d02 --- /dev/null +++ b/cpp-leetcode/temp/leetcode498_sol1.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector findDiagonalOrder(vector>& M) { + int m = M.size(); + int n = M[0].size(); + vector res; + int pathCount = m + n - 1; + bool needRev = false; + for (int x = 0; x < pathCount; x++) + { + vector curPath = getPath(x, 0, M, m, n); + if (!needRev) res.insert(res.end(), curPath.begin(), curPath.end()); + else + { + reverse(curPath.begin(), curPath.end()); + res.insert(res.end(), curPath.begin(), curPath.end()); + } + needRev = !needRev; + } + // dx = -1, dy = 1 + // path0: M[0][0] + // path1(需反向): M[1][0] -> M[0][1] + // path2: M[2][0] -> M[1][1] -> M[0][2] + return res; + } + vector getPath(int x, int y, vector>& M, int maxR, int maxC) + { + vector path; + bool isValid = x >= 0 && x < maxC && y < maxR && y >= 0; + if (isValid) + path.push_back(M[y][x]); + for (int i = x - 1; i >= 0; i--) + { + int newX = x - 1; + int newY = y + 1; + isValid = newX >= 0 && newX < maxC && newY < maxR && newY >= 0; + if (isValid) + path.push_back(M[newY][newX]); + } + return path; + } +}; + +// Test +int main() +{ + Solution sol; + vector> mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + auto res = sol.findDiagonalOrder(mat); + for (auto &num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode54-spiral-matrix-temp.cpp b/cpp-leetcode/temp/leetcode54-spiral-matrix-temp.cpp new file mode 100644 index 00000000..62b70186 --- /dev/null +++ b/cpp-leetcode/temp/leetcode54-spiral-matrix-temp.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector spiralOrder(vector>& M) { + if (M.empty()) return {}; + int r = M.size(); // rowCount >= 1 + int c = M[0].size(); // colCount >= 1 + int allCount = r*c; + vector res; + if (r == 1) + { + for (int i = 0; i < c; i++) + { + res.push_back(M[0][i]); + } + return res; + } + if (c == 1) + { + for (int i = 0; i < r; i++) + { + res.push_back(M[i][0]); + } + return res; + } + + while (allCount > 0) + { + int offset = 0; + while (r >= 1 && c >= 1) + { + getRectEdgeSeq(r, c, offset, M, res, allCount); + } + } + + return res; + } + + void getRectEdgeSeq(int& r, int& c, int& offset, vector> M, vector &res, int &allCount) + { + for (int i = 0; i < c - offset; i++) + { + if (allCount != 0) + { + res.push_back(M[0 + offset][i + offset]); + allCount--; + if (M[0 + offset][i + offset] == 6) cout << "found A"; + } + } + // 如果能形成矩形 + if (c >= 2 && r >= 2) + { + for (int j = 1; j < r - 1 - offset; j++) + { + if (allCount != 0) + { + res.push_back(M[j + offset][c - 1 - offset]); + if ((M[j + offset][c - 1 - offset]) == 6) cout << "found B"; + allCount--; + } + } + for (int i = c - 1 - offset; i >= 0; i--) + { + if (allCount != 0) + { + res.push_back(M[r - 1 - offset][i]); + if (M[r - 1 - offset][i] == 6) cout << "found C\n"; + allCount--; + } + } + for (int j = r - 2 - offset; j > 0; j--) + { + if (allCount != 0) + { + res.push_back(M[j - offset][0 + offset]); + if (M[j - offset][0 + offset] == 6) cout << "found D"; + allCount--; + } + } + } + r--; + c--; + offset++; + } +}; + +// Test +int main() +{ + Solution sol; + vector> M = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; + auto res = sol.spiralOrder(M); + for (auto num : res) + cout << num << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode65-valid-number-temp.cpp b/cpp-leetcode/temp/leetcode65-valid-number-temp.cpp new file mode 100644 index 00000000..29bb3242 --- /dev/null +++ b/cpp-leetcode/temp/leetcode65-valid-number-temp.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isNumber(string s) { + if (s.find("Infinity") != string::npos || s.find("infinity") != string::npos || (s.front() == '.' && s.back() == '.') || (s.front() == '+' && s.back() == '+') || (s.front() == '-' && s.back() == '-')) + { + return false; + } + if ((s.find("+") != string::npos && s.find("+") != 0) || (s.find("-") != string::npos && s.find("-") != 0)){ + return false; + } + if (s.find("e") == 0 || s.find("e") == (s.size() - 1) || count(s.begin(), s.end(), '.') == 2){ + return false; + } + if (s.find(".e") != string::npos || s.find(".E") != string::npos || s.find("..") != string::npos || s.find("--") != string::npos || s.find("-+") != string::npos){ + return false; + } + bool hasE; + if (s.find("E") != string::npos || s.find("e") != string::npos) + { + hasE = true; + if(s.back() == 'E' || s.back() == 'e') + { + return false; + } + if(s.front() == '.' && (s.find('e') > 0 || s.find('E') > 0)) + { + return true; + } + } + if(!hasE) + { + bool isValid = isDoubleOrInt(s); + if(isValid) + return true; + } + else + { + vector arr; + arr = (s.find('e') != string::npos) ? split(s, 'e') : split(s, 'E'); + string newPart1 = arr[0]; + if (newPart1.find(" ") != string::npos) + { + return false; + } + + string newPart2; + bool isPart1Valid, isPart2Valid; + isPart1Valid = isDoubleOrInt(newPart1); + + if (arr.size() == 1) + { + if (isPart1Valid) + return true; + } + + if (arr.size() == 2) + { + newPart2 = arr[1]; + if (newPart2 == "") // handle test case like: "0e" + { + return false; + } + + isPart2Valid = isDoubleOrInt(newPart2); + if (newPart1.find("E") != string::npos || newPart1.find("e") != string::npos || newPart1.find(".") != string::npos || find_if(newPart1.begin(), newPart1.end(), [](char c) { return std::isalpha(c); }) != newPart1.end()){ + return false; + } + if (newPart2.find("E") != string::npos || newPart2.find("e") != string::npos || newPart2.find(".") != string::npos || find_if(newPart2.begin(), newPart2.end(), [](char c) { return std::isalpha(c); }) != newPart2.end()){ + return false; + } + + if (isPart1Valid && isPart2Valid) + { + return true; + } + } + } + return false; + } + + vector split(const string& s, char separator) + { + vector tokens; + string token; + istringstream tokenStream(s); + while (getline(tokenStream, token, separator)) + { + tokens.push_back(token); + } + return tokens; + } + + bool isDoubleOrInt(string str) + { + bool isDouble, isInt; + if (str.find_first_of("abcdfghijklmnopqrstuvwxyzABCDFGHIJKLMNOPQRSTUVWXYZ_") != string::npos) + { + return false; + } + + stringstream sstr1(str); + double part; + isDouble = static_cast(sstr1 >> part); + + stringstream sstr2(str); + int64_t part2; + isInt = static_cast(sstr2 >> part2); + + return (isDouble || isInt); + } +}; + +// Test +int main() +{ + Solution sol; + string s = "95a5453"; + auto res = sol.isNumber(s); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode696-count-binary-substrings_temp.cpp b/cpp-leetcode/temp/leetcode696-count-binary-substrings_temp.cpp new file mode 100644 index 00000000..45b2d772 --- /dev/null +++ b/cpp-leetcode/temp/leetcode696-count-binary-substrings_temp.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int countBinarySubstrings(string s) { + // 先考察子串"01"、子串"10"是否存在, 然后向外扩展 ... 直到循环变量达到 len/2 + vector vect1 = {"01"}; // 存"01"及其扩展 + vector vect2 = {"10"}; // 存"10"及其扩展 + int len = s.size(); + extend(vect1, 0, len); + extend(vect2, 1, len); + + int count = 0; + for (auto str : vect1) + { + int startPos = 0; + while (string::npos != (startPos = s.find(str, startPos))) + { + ++startPos; + count++; + } + } + for (auto str : vect2) + { + int startPos = 0; + while (string::npos != (startPos = s.find(str, startPos))) + { + ++startPos; + count++; + } + } + return count; + } + void extend(vector& vect, int startDigit, int len) + { + if (startDigit == 0) + { + for (int i = 1; i < len/2; i++) + { + vect.push_back("0" + vect[i - 1] + "1"); + } + } + if (startDigit == 1) + { + for (int i = 1; i < len/2; i++) + { + vect.push_back("1" + vect[i - 1] + "0"); + } + } + } +}; + +// Test +int main() +{ + Solution sol; + string str = "00110011"; + auto res = sol.countBinarySubstrings(str); + + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode71-simplify-path-temp.cpp b/cpp-leetcode/temp/leetcode71-simplify-path-temp.cpp new file mode 100644 index 00000000..203a6cd9 --- /dev/null +++ b/cpp-leetcode/temp/leetcode71-simplify-path-temp.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +using namespace std; + +/* 49 / 256 test cases passed. */ + +class Solution { +public: + string simplifyPath(string path) { + // 1.遇到//, 替换为/ + path = replaceAll(path, "//", "/"); + + // 2.遇到 /.. (看是否能朝着根目录/的方向靠近) + // 向前找最近的一个/, 如果能找到, 把 / 与 /..之间的内容删掉 + while (path.find("/..") != string::npos && path.find("/..") != -1 && path.size() > 3) + { + int pos = path.find("/.."); + string part2 = path.substr(pos + 3, path.size() - pos - 3); + auto preIt = find(path.begin(), path.begin() + pos, '/'); + if (preIt != path.end()) + { + string part1 = path.substr(0, preIt - path.begin()); + path = part1.append(part2); + } + } + + // 3.遇到 /. 直接删掉 + path = replaceAll(path, "/.", ""); + // 4.删除末尾的/, 迭代地删除 + if (path != "/") path.erase(path.find_last_not_of('/') + 1); + return path; + } + string replaceAll(std::string str, const std::string& from, const std::string& to) { + size_t start_pos = 0; + while((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); + } + return str; + } +}; + +// Test +int main() +{ + Solution sol; + string path = "/a/./b/../../c/"; + auto res = sol.simplifyPath(path); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode720-longest-word-in-dictionary_solution_temp.cpp b/cpp-leetcode/temp/leetcode720-longest-word-in-dictionary_solution_temp.cpp new file mode 100644 index 00000000..1e4e9d23 --- /dev/null +++ b/cpp-leetcode/temp/leetcode720-longest-word-in-dictionary_solution_temp.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +using namespace std; + +/* 42 / 59 test cases passed. */ +class Solution { +public: + string longestWord(vector& words) { + if (words.empty()) return ""; + auto cmp0 = [](const string& s1, const string& s2) + { + return s1.size() < s2.size(); + }; + sort(words.begin(), words.end(), cmp0); + + vector> kvVect; + for (auto word : words) + { + if (isAllPrefixExist(word, words) && isSubstrCountMeet(word, words)) + kvVect.push_back(make_pair(word, word.size())); + } + auto cmp = [](const pair& p1, const pair& p2) + { + if (p1.second == p2.second) return p1.first < p2.first; + return p1.second > p2.second; + }; + sort(kvVect.begin(), kvVect.end(), cmp); + return kvVect.front().first; + } + + bool isAllPrefixExist(string theWord, vector words) + { + int len = theWord.size(); + int containCount = 0; + int i = len; + while (i > 0) + { + if (find(words.begin(), words.end(), theWord.substr(0, i)) != words.end()) + containCount++; + i--; + } + return containCount == len; + } + + bool isSubstrCountMeet(string theWord, vector words) + { + int count = 0; + bool hasFirstLetter = false; + vector numsWithLen; + for (auto word : words) + { + if (word.size() == 1) + numsWithLen.push_back(word); + } + if (find(numsWithLen.begin(), numsWithLen.end(), theWord.substr(0, 1)) != numsWithLen.end()) + hasFirstLetter = true; + + for (auto word : words) + { + if (theWord.find(word) != string::npos) + count++; + } + return hasFirstLetter && (count >= theWord.size()); + } +}; + +// Test +int main() +{ + Solution sol; + // vector words = { "a", "banana", "app", "appl", "ap", "apply", "apple" }; + // vector words = { "yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y" }; + // vector words = { "r","kt","jtgt","j","jtg","rdwy","chkext","c","l","zo","lnp","k","jt","chke","ktui","rd","jtgtha","ch","chkex" }; + vector words = { "tgjrbffdokudfdunnbfyylfandlhzf","tgjrbffdokudfdunnbfyylfandlhsz","tgjrbffdokudfdunnbfyylfandlhcx","tgjrbffdokudfdunnbfyylfandlhdg","tgjrbffdokudfdunnbfyylfandlhwz","tgjrbffdokudfdunnbfyylfandlhtk","tgjrbffdokudfdunnbfyylfandlhdd","tgjrbffdokudfdunnbfyylfandlhtf","tgjrbffdokudfdunnbfyylfandlhbg","tgjrbffdokudfdunnbfyylfandlhju","tgjrbffdokudfdunnbfyylfandlhyx","tgjrbffdokudfdunnbfyylfandlhxd","tgjrbffdokudfdunnbfyylfandlhfr","tgjrbffdokudfdunnbfyylfandlhiy","tgjrbffdokudfdunnbfyylfandlhlu","tgjrbffdokudfdunnbfyylfandlhc","tgjrbffdokudfdunnbfyylfandlhxc","tgjrbffdokudfdunnbfyylfandlhvh","tgjrbffdokudfdunnbfyylfandlhhj","tgjrbffdokudfdunnbfyylfandlhoy","tgjrbffdokudfdunnbfyylfandlhp","tgjrbffdokudfdunnbfyylfandlhje","tgjrbffdokudfdunnbfyylfandlhhe","tgjrbffdokudfdunnbfyylfandlhcs","tgjrbffdokudfdunnbfyylfandlhib","tgjrbffdokudfdunnbfyylfandlhag","tgjrbffdokudfdunnbfyylfandlhmd","tgjrbffdokudfdunnbfyylfandlhez","tgjrbffdokudfdunnbfyylfandlhhu","tgjrbffdokudfdunnbfyylfandlhep","tgjrbffdokudfdunnbfyylfandlhuk","tgjrbffdokudfdunnbfyylfandlhuf","tgjrbffdokudfdunnbfyylfandlhrb","tgjrbffdokudfdunnbfyylfandlhdl","tgjrbffdokudfdunnbfyylfandlhhk","tgjrbffdokudfdunnbfyylfandlhht","tgjrbffdokudfdunnbfyylfandlhlw","tgjrbffdokudfdunnbfyylfandlhnc","tgjrbffdokudfdunnbfyylfandlhfw","tgjrbffdo","tgjrbffdokudfdunnbfyylfandlhqc","tgjrbffdokudfdunnbfyylfandlhpc","tgjrbffdokudfdunnbfyylfandlhqk","tgjrbffdokudfdunnbfyylfandlhcm","tgjrbffdokudfdunnbfyylfandlhgb","tgjrbffdokudfdunnbfyylfandlhsb","tgjrbffdokudfdunnbfyylfandlhpf","tgjrbffdokudfdunnbfyylfandlhaw","tgjrbffdokudfdunnbfyylfandlhyz","tgjrbffdokudfdunnbfyylfandlhra","tgjrbffdokudfdunnbfyylfandlhre","tgjrbffdokudfdunnbfyylfandlhij","tgjrbffdokudfdunnbfyylfandlhku","tgjrbffdokudfdunnbfyylfandlhyd","tgjrbffdokudfdunnbfyylfandlhpl","tgjrbffdokudfdunnbfyylfandlhto","tgjrbffdokudfdunnbfyylfandlhjz","tgjrbffdokudfdunnbfyylfandlhjg","tgjrbffdokudfdunnbfyylfandlhty","tgjrbffdokudfdunnbfyylfandlhcd","tgjrbffdokudfdunnbfyylfandlhjo","tgjrbffdokudfdunnbfyylfandlhrt","tgjrbffdokudfdunnbfyylfandlhfs","tgjrbffdokudfdunnbfyylfandlhbj","tgjrbffdokudfdunnbfyylfandlhyr","tgjrbffdokudfdunnbfyylfandlhwj","tgjrbffdokudfdunnbfyylfandlhlm","tgjrbffdokudfdunnbfyylfandlhwh","tgjrbffdokudfdunnbfyylfandlhtz","tgjrbffdokudfdunnbfyylfandlhca","tgjrbffdokudfdunnbfyylfandlhnk","tgjrbffdokudfdunnbfyylfandlhq","tgjrbffdokudfdunnbfyylfandlhsi","tgjrbffdokudfdunnbfyylfandlhky","tgjrbffdokudfdunnbfyylfandlhru","tgjrbffdokudfdunnbfyylfandlhjw","tgjrbffdokudfdunnbfyylfandlhfp","tgjrbffdokudfdunnbfyylfandlhlf","tgjrbffdokudfdunnbfyylfandlhkb","tgjrbffdokudfdunnbfyylfandlhmu","tgjrbffdokudfdunnbfyylfandlhfn","tgjrbffdokudfdunnbfyylfandlhxj","tgjrbffdokudfdunnbfyylfandlhsy","tgjrbffdokudfdunnbfyylfandlhse","tgjrbffdokudfdunnbfyylfandlhom","tgjrbffdokudfdunnbfyylfandlhoh","tgjrbffdokudfdunnbfyylfandlhny","tgjrbffdokudfdunnbfyylfandlhls","tgjrbffdokudfdunnbfyylfandlhgx","tgjrbffdokudfdunnbfyylfandlhee","tgjrbffdokudfdunnbfyylfandlhab","tgjrbffdokudfdunnbfyylfandlhzd","tgjrbffdokudfdunnb","tgjrbffdokudfdunnbfyylfandlhnm","tgjrbffdokudfdunnbfyylfandlhtc","tgjrbffdokudfdunnbfyylfandlhdm","tgjrbffdokudfdunnbfyylfandlhn","tgjrbffdokudfdunnbfyylfandlhwd","tgjrbffdokudfdunnbfyylfandlhsg","tgjrbffdokudfdunnbfyylfandlhau","tgjrbffdokudfdunnbfyylfandlhvj","tgjrbffdokudfdunnbfyylfandlhji","tgjrbffdokudfdunnbfyylfandlhrw","tgjrbffdokudfdunnbfyylfandlhcn","tgjrbffdokudfdunnbfyylfandlhqt","tgjrbffdokudfdunnbfyylfandlh","tgjrbffdokudfdunnbfyylfandlhjd","tgjrbffdokudfdunnbfyylfandlhkl","tgj","tgjrbffdokudfdunnbfyylfandlhci","tgjrbffdokudfdunnbfyylfandlhzp","tgjrbffdokudfdunnbfyylfandlhnp","tgjrbffdokudfdunnbfyylfandlhgi","tgjrbffdokudfdunnbfyylfandlhrz","tgjrbffdokudfdunnbfyylfandlhkc","tgjrbffdokudfdunnbfyylfandlhti","tgjrbffdokudfdunnbfyylfandlhye","tgjrbffdokudfdunnbfyylfandlhbr","tgjrbffdokudfdunnbfyylfandlhqq","tgjrbffdokudfdunnbfyylfandlhnv","tgjrbffdokudfdunnbfyylfandlhzb","tgjrbffdokudfdunnbfyylfandlhkm","tgjrbffdokudfdunnbfyylfandlhcc","tgjrbffdokudfdunnbfyylfandlhhl","tgjrbffdokudfdunnbfyylfandlheg","tgjrbffdokudfdunnbfyylfandlhxb","tgjrbffdokudfdunnbfyylfandlhmj","tgjrbffdokudfdunnbfyylfandlhwc","tgjrbffdokudfdunnbfyylfandlhfg","tgjrbffdokudfdunnbfyylfandlhgl","tgjrbffdokudfdunnbfyylfandlhex","tgjrbffdokudfdunnbfyylfandlhfk","tgjrbffdokudfdunnbfyylfandlhl","tgjrbffdokudfdunnbfyylfandlhgy","tgjrbffdokudfdunnbfyylfandlhft","tgjrbffdokudfdunnbfyylfandlhuu","tgjrbffdokudfdunnbfyylfandlhgm","tgjrbffdokudfdunnbfyylfandlhgv","tgjrbffdokudfdunnbfyylfandlhno","tgjrbffdokudfdunnbfyylfandlhis","tgjrbffdokudfdunnbfyylfandlhvb","tgjrbffdokudfdunnbfyylfandlhvm","tgjrbffdokudfdunnbfyylfandlhyv","tgjrbffdokudfdunnbfyylfa","tgjrbffdokudfdunnbfyylfandlhko","tgjrbffdokudfdunnbfyylfandlhhp","tgjrbffdokudfdunnbfyylfandlhjl","tgjrbffdokudfdunnbfyylfandlhel","tgjrbffdokudfdunnbfyylfandlhml","tgjrbffdokudfdunnbfyylfandlhjn","tgjrbffdokudfdunnbfyylfandlhbl","tgjrbffdokudfdunnbfyylfandlhac","tgjrbffdokudfdunnbfyylfandlhyg","tgjrbffdokudfdunnbfyylfandlhzx","tgjrbffdokudfdunnbfyylfandlhoc","tgjrbffdokudfdunnbfyylfandlhmi","tgjr","tgjrbffdokudfdunnbfyylfandlhhz","tgjrbffdokudfdunnbfyylfandlhrq","tgjrbffdokudfdunnbfyylfandlhhn","tgjrbffdokudfdunnbfyylfandlhi","tgjrbffdokudfdunnbfyylfandlhmc","tgjrbffdokudfdunnbfyylfandlhgc","tgjrbffdokudfdunnbfyylfandlhfo","tgjrbffdokudfdunnbfyylfandlhhc","tgjrbffdokudfdunnbfyylfandlhyy","tgjrbffdokudfdunnbfyylfandlhat","tgjrbffdokudfdunnbfyylfandlhly","tgjrbffdokudfdunnbfyylfandlhrv","tgjrbffdokudfdunnbfyylfandlhj","tgjrbffdokudfdunnbfyylfandlhgp","tgjrbffdokudfdunnbfyylfandlhwl","tgjrbffdokudfdunnbfyylfandlhuh","tgjrbffdokudfdunnbfyylfandlhbf","tgjrbffdokudfdunnbfyylfandlhcg","tgjrbffdokudfdunnbfyylfandlhys","tgjrbffdokudfdunnbfyylfandlhck","tgjrbffdokudfdunnbfyylfandlhyw","tgjrbffdokudfdunnbfyylfandlhwt","tgjrbffdokudfdunnbfyylfandlhds","tgjrbffdokudfdunnbfyylfandlhur","tgjrbffdokudfdunnbfyylfandlhbe","tgjrbffdokudfdunnbfyylfandlhxh","tgjrbffdokudfdunnbfyylfandlhpq","tgjrbffdokudfdunnbfyylfandlhio","tgjrbffdokudfdunnbfyylfandlhm","tgjrbffdokudfdunnbfyylfandlhh","tgjrbffdokudfdunnbfyylfandlhmt","tgjrbffdokudfdunnbfyylfandlhpp","tgjrbffdokudfdunnbfyylfandlhdq","tgjrbffdokudfdu","tgjrbffdokudfdunnbfyylfandlhor","tgjrbffdokudfdunnbfyylfandlhvc","tgjrbffdokudfdunnbfyylfandlhfz","tgjrbffdokudfdunnbfyylfandlhpz","tgjrbffdokudfdunnbfyylfandlhwy","tgjrbffdokudfdunnbfyylfandlhla","tgjrbffdokudfdunnbfyylfandlhzm","tgjrbffdokudfdunnbfyylfandlhiq","tgjrbffdokudfdunnbfyylfandlhoz","tgjrbffdokudfdunnbfyylfandlhjr","tgjrbffdokudfdunnbfyylfandlhxr","tgjrbffdokudfdunnbfyylfandlhec","tgjrbffdokudfdunnbfyylfandlhmv","tgjrbffdokudfdunnbfyylfandlhfy","tgjrbffdokudfdunnbfyylfandlham","tgjrbffdokudfdunnbfyylfandlhuj","tgjrbffdokudfdunnbfyylfandlhsh","tgjrbffdokudfdunnbfyylfandlhbz","tgjrbffdokudfdunnbfyylfandlhmo","tgjrbffdokudfdunnbfyylfandlhyn","tgjrbffdokudfdunnbfyylfandlhrl","tgjrbffdokudfdunnbfyylfandlhus","tgjrbffdokudfdunnbfyylfandlhgr","tgjrbffdokudfdunnbfyylfandlhcr","tgjrbffdokudfdunnbfyylfandlhhb","tgjrbffdokudfdunnbfyylfandlhzq","tgjrbffdokudfdunnbfyylfandlhfv","tgjrbffdokudfdunnbfyylfandlhjf","tgjrbffdokudfdunnbfyylfandlhk","tgjrbffdokudfdunnbfyylfandlhlo","tgjrbffdokudfdunnbfyylfandlhww","tgjrbffdokudfdunnbfyylfandlhdr","tgjrbffdokudfdunnbfyylfandlhyj","tgjrbffdokudfdunnbfyylfandlhia","tgjrbffdokudfdunnbfyylfandlhkv","tgjrbffdokudfdunnbfyylfandlhwu","tgjrbffdokudfdunnbfyylfandlhnx","tgjrbffdokudfdunnbfyylfandlhuc","tgjrbffdokudfdunnbfyylfandlhqx","tgjrbffdokudfdunnbfyylfandlhfq","tgjrbffdokudfdunnbfyylfandlhzk","tgjrbffdokudfdunnbfyylfandlhpk","tgjrbffdokudfdunnbfyylfandlhta","tgjrbffdokudfdunnbfyylfandlhle","tgjrbffdokudfdunnbfyylfandlhkp","tgjrbffdokudfdunnbfyylfandlhou","tgjrbffdokudfdun","tgjrbffdokudfdunnbfyylfandlhcz","tgjrbffdokudfdunnbfyylfandlhev","tgjrbffdokudfdunnbfyylfandlhyu","tgjrbffdokudfdunnbfyylfandlhdc","tgjrbffdokudfdunnbfyylfandlhga","tgjrbffdokudfdunnbfyylfandlhnf","tgjrbffdokudfdunnbfyylfandlhlc","tgjrbffdokudfdunnbfyylfandlhyp","tgjrbffdokudfdunnbfyylfandlhtx","tgjrbffdokudfdunnbfyylfandlhmg","tgjrbffdokudfdunnbfyylfandlhnq","tgjrbffdokudfdunnbfyylfandlhqg","tgjrbffdokudfdunnbfyylfandlhms","tgjrbffdokudfdunnbfyylfandlhxf","tgjrbffdokudfdunnbfyylfandlhkr","tgjrbffdokudfdunnbfyylfandlhri","tgjrbffdokudfdunnbfyylfandlhix","tgjrbffdokudfdunnbfyylfandlhkw","tgjrbffdokudfdunnbfyylfandlhpr","tgjrbffdokudfdunnbfyylfandlhsj","tgjrbffdokudfdunnbfyylfandlhic","tgjrbffdokudfdunnbfyylfandlhry","tgjrbffdokudfdunnbfyylfandlhhq","tgjrbffdokudfdunnbfyylfandlhog","tgjrbffdokudfdunnbfyylfandlhqz","tgjrbffdokudfdunnbfyylfandlhux","tgjrbffdokudfdunnbfyylfandlhlb","tgjrbffdokudfdunnbfyylfandlhlj","tgjrbffdokudfdunnbfyylfandlhaq","tgjrbffdokudfdunnbfyylfandlhbw","tgjrbffdokudfdunnbfyylfandlhkk","tgjrbffdokudfdunnbfyylfandlhub","tgjrbffdokudfdunnbfyylfandlhqh","tgjrbffdokudfdunnbfyylfandlhiv","tgjrbffdokudfdunnbfyylfandlhge","tgjrbffdokudfdunnbfyylfandlhek","tgjrbffdokudfdunnbfyylfandlhwq","tgjrbffdokudfdunnbfyylfandlhvr","tgjrbffdokudfdunnbfyylfandlhzi","tgjrbffdokudfdunnbfyylfandlhgu","tgjrbffdokudfdunnbfyylfandlhud","tgjrbffdokudfdunnbfyylfandlhsa","tgjrbffdokudfdunnbfyylfandlhmp","tgjrbffdokudfdunnbfyylfandlhrj","tgjrbffdokudfdunnbfyylfandlhed","tgjrbffdokudfdunnbfyylfandlhen","tgjrbffdokudfdunnbfyylfandlhxz","tgjrbffdokudfdunnbfyylfandlhvq","tgjrbffdokudfdunnbfyylfandlhqf","tgjrbffdokudfdunnbfyylfandlhgd","tgjrbffdokudfdunnbfyylfandlhew","tgjrbffdokudfdunnbfyylfandlhnj","tgjrbf","tgjrbffdokudfdunnbfyylfandlhul","tgjrbffdokudfdunnbfyylfandlhjt","tgjrbffdokudfdunnbfyylfandlhiu","tgjrbffdokudfdunnbfyylfandlhgg","tgjrbffdokudfdunnbfyylfandlhnu","tgjrb","tgjrbffdokudfdunnbfyylfandlhqe","tgjrbffdokudfdunnbfyylfandlhd","tgjrbffdokudfdunnbfyylfandlhsq","tgjrbffdokudfdunnbfyylfandlhy","tgjrbffdokudfdunnbfyylfandlhdx","tgjrbffdokudfdunnbfyylfandlhan","tgjrbffdokudfdunnbfyylfandlhcl","tgjrbffdokudfdunnbfyylfandlhon","tgjrbffdokudfdunnbfyylfandlhjv","tgjrbffdokudfdunnbfyylfandlhni","tgjrbffdokudfdunnbfyylfandlhwb","tgjrbffdokudfdunnbfyylfandlhxe","tgjrbffdokudfdunnbfyylfandlhrm","tgjrbffdokudfdunnbfyylfandlhax","tgjrbffdokudfdunnbfyylfandlhdp","tgjrbffdokudfdunnbfyylfandlhot","tgjrbffdokudfdunnbfyylfandlhwa","tgjrbffdokudfdunnbfyylfandlhfl","tgjrbffdokudfdunnbfyylfandlhho","tgjrbffdokudfdunnbfyylfandlhrs","tgjrbffdokudfdunnbfyylfandlhaj","tgjrbffdokudfdunnbfyylfandlhzh","tgjrbffdokudfdunnbfyylfandlhdw","tgjrbffdokudfdunnbfyylfandlhsu","tgjrbffdokudfdunnbfyylfandlhxy","tgjrbffdokudfdunnbfyylfandlhpj","tgjrbffdokudfdunnbfyylfandlhav","tgjrbffdokudfdunnbfyylfandlhjk","tgjrbffdokudfdunnbfyylfandlhcp","tgjrbffdokudfdunnbfyylfandlhhd","tgjrbffdokudfdunnbfyylfandlhkh","tgjrbffdokudfdunnbfyylfandlhgf","tgjrbffdokudfdunnbfyylfandlhhy","tgjrbffdokudfdunnbfyylfandlhha","tgjrbffdokudfdunnbfyylfandlhsd","tgjrbffdokudfdunnbfyylfandlhnn","tgjrbffdokudfdunnbfyylfandlhyl","tgjrbffdokudfdunnbfyylfandlhvs","tgjrbffdokudfdunnbfyylfandlhhf","tgjrbffdokudfdunnbfyylfandlhwe","tgjrbffdokudfdunnbfyylfandlhef","tgjrbffdokudfdunnbfyylfandlha","tgjrbffdokudfdunnbfyylfandlhjx","tgjrbffdokudfdunnbfyylfandlhsw","tgjrbffdokudfdunnbfyylfandlht","tgjrbffdokudfdunnbfyylfandlhvy","tgjrbffdokudfdunnbfyylfandlho","tgjrbffdokudfdunnbfyylfandlhss","tgjrbffdokudfdunnbfyylfandlhgh","tgjrbffdokudfdunnbfyylfandlhod","tgjrbffdokudfdunnbfyylfandlhpu","tgjrbffdokudfdunnbfyylfandlhie","tgjrbffdokudfdunnbfyylfandlhpb","tgjrbffdokudfdunnbfyylfandlhcu","tgjrbffdokudfdunnbfyylfandlhpv","tgjrbffdokudfdunnbfyylfandlhxp","tgjrbffdokudfdunnbfyylfandlhtu","tgjrbffdokudfdunnbfyylfandlhmm","tgjrbffdokudfdunnbfyylfandlhqu","tgjrbffdokudfdunnbfyylfandlhif","tgjrbffdokudfdunnbfyylfandlhtm","tgjrbffdokudfdunnbfyylfandlhsp","tgjrbffdokudfdunnbfyylfandlhpm","tgjrbffdokudfdunnbfyylfandlhfx","tgjrbffdokudfdunnbfyylfandlhtb","tgjrbffdokudfdunnbfyylfandlhdv","tgjrbffdokudfdunnbfyylfandlhma","tgjrbffdokudfdunnbfyylfandlhdb","tgjrbffdokudfdunnbfyylfandlhpe","tgjrbffdokudfdunnbfyylfandlhql","tgjrbffdokudfdunnbfyylfandlhao","tgjrbffdokudfdunnbfyylfandlhjh","tgjrbffdokudfdunnbfyylfandlhiw","tgjrbffdokudfdunnbfyylfandlhid","tgjrbffdokudfdunnbfyylfandlhxo","tgjrbffdokudfdunnbfyylfandlhzs","tgjrbffdokudfdunnbfyylfandlhqs","tgjrbffdokudfdunnbfyylfandlhvn","tgjrbffdokudfdunnbfyylfandlhna","tgjrbffdokudfdunnbfyylfandlhtg","tgjrbffdokudfdunnbfyylfandlhqn","tgjrbffdokudfdunnbfyylfandlhpt","tgjrbffdokudfdunnbfyylfandlheu","tgjrbffdokudfdunnbfyylfandlhdt","tgjrbffdokudfdunnbfyylfandlhbh","tgjrbffdokudfdunnbfyylfandlhvd","tgjrbffdokudfdunnbfyylfandlhym","tgjrbffdokudfdunnbfyylfandlhnb","tgjrbffdokudfdunnbfyylfandlhpn","tgjrbffdokudfdunnbfyylfandlhlv","tgjrbffdokudfdunnbfyylfandlhai","tgjrbffdokudfdunnbfyylfandlhzc","tgjrbffdokudfdunnbfyylfandlhvo","tgjrbffdokudfdunnbfyylfandlhob","tgjrbffdokudfdunnbfyylfandlhit","tgjrbffdokudfdunnbfyylfandlhtp","t","tgjrbffdokudfdunnbfyylfandlhst","tgjrbffdokudfdunnbfyylfandlhpg","tgjrbffdokudfdunnbfyylfandlhsf","tgjrbffdokudfdunnbfyylfandlhmz","tgjrbffdokudfdunnbfyylfandlhvk","tgjrbffdokudfdunnbfyylfandlhlq","tgjrbffdokudfdunnbfyylfandlhja","tgjrbffdokudfdunnbfyylfandlhdk","tgjrbffdokudfdunnbfyylfandlhvg","tgjrbffdokudfdunnbfyylfandlhah","tgjrbffdokudfdunnbfyylfandlhmk","tgjrbffdokudfdunnbfyylfandlhxm","tgjrbffdokudfdunnbfyylfandlhwk","tgjrbffdokudfdunnbfyyl","tgjrbffdokudfdunnbfyylfandlhpd","tgjrbffdokudfdunnbfyylfandlhxg","tgjrbffdokudfdunnbfyylfandlhwf","tgjrbffdokudfdunnbfyylfandlhnl","tgjrbffdokudfdunnbfyylfandlhxn","tgjrbffdokudfdunnbfyylfandlhkj","tgjrbffdokudfdunnbfyylfandlhjp","tgjrbffdokudfdunnbfyylfandlhae","tgjrbffdokudfdunnbfyylfandlhjm","tgjrbffdokudfdunnbfyylfandlhey","tgjrbffdokudfdunnbfyylfandlhpy","tgjrbffdokudfdunnbfyylfandlhtj","tgjrbffdokudfdunnbfyylfandlhmn","tgjrbffdokudfdunnbfyylfandlhyo","tgjrbffdokudfdunnbfyylfandlhdn","tgjrbffdokudfdunnbfyylfandlhjb","tgjrbffdokudfdunnbfyylfandlhco","tgjrbffdokudfdunnbf","tgjrbffdokudfdunnbfyylfandlhxq","tgjrbffdokudfdunnbfyylfandlhap","tgjrbffdokudfdunnbfyylfandlhzz","tgjrbffdokudfdunnbfyylfandlhzy","tgjrbffdokudfdunnbfyylfandlhso","tgjrbffdokudfdunnbfyylfandlhrk","tgjrbffdokudfdunnbfyylfandlhnr","tgjrbffdokudfdunnbfyylfandlhph","tgjrbffdokudfdunnbfyylfandlhng","tgjrbffdokudfdunnbfyylfandlhx","tgjrbffdokudfdunnbfyylfandlhvx","tgjrbffdokudfdunnbfyylfandlhth","tgjrbffdokudfdunnbfyylfandlhqr","tgjrbffdokudfdunnbfyylfandlhz","tgjrbffdokudfdunnbfyylfandlhe","tgjrbffdokudfdunnbfyylfandlhiz","tgjrbffdokudfdunnbfyylfandlhbp","tgjrbffdokudfdunnbfyylfandlhop","tgjrbffdokudfdunnbfyylfandlhow","tgjrbffdokudfdunnbfyylfandlhwx","tgjrbffdokudfdunnbfyylfandlhlr","tgjrbffdokudfdunnbfyylfandlhb","tgjrbffdokudfdunnbfyylfandlhya","tgjrbffdokudfdunnbfyylfandlhzv","tgjrbffdokudfdunnbfyylfandlhcj","tgjrbffdokudfdunnbfyylfandlhkx","tgjrbffdokudfdunnbfyylfandlhet","tgjrbffdokudfdunnbfyylfandlhhs","tgjrbffdokudfdunnbfyylfandlhkg","tgjrbffdokudfdunnbfyylfandlhu","tgjrbffdokudfdunnbfyylfandlhsr","tgjrbffdokudfdunnbfyylfandlhsm","tgjrbffdokudfdunnbfyylfandlhyb","tgjrbffdokudfdunnbfyylfandlhcw","tgjrbffdokudfdunnbfyylfandlhrf","tgjrbffdokudfdunnbfyylfandlhxi","tgjrbffdokudfdunnbfyylfandlhui","tgjrbffdokudfdunnbfyylfandlhgo","tgjrbffdokudfdunnbfyylfandlhbu","tgjrbffdokudfdunnbfyylfandlhbq","tgjrbffdokudfdunnbfyylfandlhfj","tgjrbffdokudfdunnbfyylfandlhmx","tgjrbffdokudfdunnbfyylfandlhda","tgjrbffdokudfdunnbfyylfandlhvi","tgjrbffdokudfdunnbfyylfandlhrr","tgjrbffdokudfdunnbfyylfandlhoj","tgjrbffdokudfdunnbfyylfandlhir","tgjrbffdokudfdunnbfyylfandlhct","tgjrbffdokudfdunnbfyylfandlhnh","tgjrbffdokudfdunnbfyylfandlhpo","tgjrbffdokudfdunnbfyylfandlhsv","tgjrbffdokudfd","tg","tgjrbffdokudf","tgjrbffdokudfdunnbfyylfandlhfe","tgjrbffdokudfdunnbfyylfandlhg","tgjrbffdokudfdunnbfyylfandlhte","tgjrbffdokudfdunnbfyylfandlher","tgjrbffdokudfdunnbfyylfandlhyf","tgjrbffdokudfdunnbfyylfandlhpi","tgjrbffdokudfdunnbfyylfandlhbb","tgjrbffdokudfdunnbfyylfandlhii","tgjrbffdokudfdunnbfyylfandlhff","tgjrbffdokudfdunnbfyylfandlhbk","tgjrbffdokudfdunnbfyylfandlhtq","tgjrbffdokudfdunnbfyylfandlhuq","tgjrbffdokudfdunnbfyylfandlhbi","tgjrbffdokudfdunnbfyylfandlheh","tgjrbffdokudfdunnbfyylfandlhhi","tgjrbffdokudfdunnbfyylfandlhdh","tgjrbffdokudfdunnbfyylfandlhes","tgjrbffdokudfdunnbfyylfandlhwg","tgjrbffdokudfdunnbfyylfandlhuv","tgjrbffdokudfdunnbfyylfandlhzj","tgjrbffdokudfdunnbfyylfandlhgz","tgjrbffdokudfdunnbfyylfandlhei","tgjrbffdokudfdunnbfyylfandlhok","tgjrbffdokudfdunnbfyylfandlhip","tgjrbffdokudfdunnbfyylfandlhrd","tgjrbffdokudfdunnbfyylfandlhyk","tgjrbffdokudfdunnbfyylfandlhhg","tgjrbffdokudfdunnbfyylfandlhkz","tgjrbffdokudfdunnbfyylfandlhrh","tgjrbffdokudfdunnbfyylfandlhgq","tgjrbffdokudfdunnbfyylfandlhnz","tgjrbffdokudfdunnbfyylfandlhrx","tgjrbffdokudfdunnbfyylfandlhwo","tgjrbffdokudfdunnbfyylfandlhhx","tgjrbffdokudfdunnbfyylfandlhva","tgjrbffdokudfdunnbfyylfandlhut","tgjrbffdokudfdunnbfyylfandlhde","tgjrbffdokudfdunnbfyylfandlhuz","tgjrbffdokudfdunnbfyylfandlhby","tgjrbffdokudfdunnbfyylfandlhcb","tgjrbffdoku","tgjrbffdokudfdunnbfyylfandlhce","tgjrbffdokudfdunnbfyylfandlhej","tgjrbffdokudfdunnbfyylfandlhcf","tgjrbffdokudfdunnbfyylfandlhks","tgjrbffdokudfdunnbfyylfandlhnd","tgjrbffdokudfdunnbfyylfandlhr","tgjrbffdokudfdunnbfyylfandlhsk","tgjrbffdokud","tgjrbffdokudfdunnbfyylfandlhpa","tgjrbffdokudfdunnbfyylfandlhqa","tgjrbffdokudfdunnbfyylfandlhmq","tgjrbffdokudfdunnbfyylfandlhcv","tgjrbffdokudfdunnbfyylfandlhof","tgjrbffdokudfdunnbfyylfandlhzg","tgjrbffdokudfdunnbfyylfandlhol","tgjrbffdokudfdunnbfyylfandlhoa","tgjrbffdokudfdunnbfyylfandlhik","tgjrbffdokudfdunnbfyylfandlhxw","tgjrbffdokudfdunnbfyylfandlhln","tgjrbffdokudfdunnbfyylfandlhbn","tgjrbffdokudfdunnbfyylfandlhzl","tgjrbffdokudfdunnbfyylfandlhme","tgjrbffdokudfdunnbfy","tgjrbffdokudfdunnbfyylfandlhbv","tgjrbffdokudfdunnbfyylfandlhqp","tgjrbffdokudfdunn","tgjrbffdokudfdunnbfyylfandlhvw","tgjrbffdokudfdunnbfyylfandlhas","tgjrbffdokudfdunnbfyylfandlhwn","tgjrbffdokudfdunnbfyylfandlhaf","tgjrbffdokudfdunnbfyylfandlhxs","tgjrbffdokudfdunnbfyylfan","tgjrbffdokudfdunnbfyylfandlhvf","tgjrbffdokudfdunnbfyylfandlhgk","tgjrbffdokudfdunnbfyylfandlhov","tgjrbffdokudfdunnbfyylfandlhmf","tgjrbffdokudfdunnbfyylfandlhld","tgjrbffdokudfdunnbfyylfandlhyh","tgjrbffdokudfdunnbfyylfandlhhr","tgjrbffdokudfdunnbfyylfandlhun","tgjrbffdokudfdunnbfyylfandlhmw","tgjrbffdokudfdunnbfyylfandlhil","tgjrbffdokudfdunnbfyylfandlhrg","tgjrbffdokudfdunnbfyylfandlhch","tgjrbffdokudfdunnbfyylfandlhqy","tgjrbffdokudfdunnbfyylfandlhfi","tgjrbffdokudfdunnbfyylfandlhhh","tgjrbffdokudfdunnbfyylfandlhug","tgjrbffdokudfdunnbfyylfandlhtn","tgjrbffdokudfdunnbfyylfandlhlp","tgjrbffdokudfdunnbfyylfandlhjj","tgjrbffdokudfdunnbfyylfandlhvz","tgjrbffdokudfdunnbfyylfandlhmh","tgjrbffdokudfdunnbfyylfandlhal","tgjrbffdokudfdunnbfyylfandlhvt","tgjrbffdokudfdunnbfyylfandlhdu","tgjrbffdokudfdunnbfyylfandlhbt","tgjrbffdokudfdunnbfyylfandlhuo","tgjrbffdokudfdunnbfyylfandlheq","tgjrbffdokudfdunnbfyylfandlhos","tgjrbffdokudfdunnbfyylfandlhxl","tgjrbffdokudfdunnbfyylfandlhw","tgjrbffdokudfdunnbfyylfandlhem","tgjrbffdokudfdunnbfyylfandlhmb","tgjrbffdokudfdunnbfyylfandlhbs","tgjrbffdokudfdunnbfyylfandlhgj","tgjrbffdokudfdunnbfyylfandlhih","tgjrbffdokudfdunnbfyylfandlhgs","tgjrbffdokudfdunnbfyylfandlhig","tgjrbffdokudfdunnbfyylfandlhbo","tgjrbffdokudfdunnbfyylfandlhua","tgjrbffdokudfdunnbfyylfandlhqd","tgjrbffdokudfdunnbfyylfandlhns","tgjrbffdokudfdunnbfyylfandlhtv","tgjrbffdokudfdunnbfyylfandlhdj","tgjrbffdokudfdunnbfyylfandlhgw","tgjrbffdokudfdunnbfyylfandlhfa","tgjrbffdokudfdunnbfyylfandlhgn","tgjrbffdokudfdunnbfyylfandl","tgjrbffdokudfdunnbfyylfandlhpx","tgjrbffdokudfdunnbfyylfandlhxk","tgjrbffdokudfdunnbfyylfandlhwr","tgjrbffdokudfdunnbfyylfandlhwm","tgjrbffdokudfdunnbfyylfandlhsl","tgjrbffdokudfdunnbfyylfandlhtw","tgjrbffdokudfdunnbfyylfandlhfh","tgjrbffdokudfdunnbfyylfandlhlg","tgjrbffdokudfdunnbfyylfandlhtt","tgjrbffdokudfdunnbfyylfandlhvv","tgjrbffdokudfdunnbfyylfandlhza","tgjrbffdokudfdunnbfyylfandlhjs","tgjrbffdokudfdunnbfyylfandlhwp","tgjrbffdokudfdunnbfyylfandlhps","tgjrbffdokudfdunnbfyylfandlhqb","tgjrbffdokudfdunnbfyylfandlhki","tgjrbffdokudfdunnbfyylfandlhdz","tgjrbffdokudfdunnbfyylfandlhxv","tgjrbffdokudfdunnbfyylfandlhox","tgjrbffdokudfdunnbfyylfandlhjq","tgjrbffdokudfdunnbfyylfandlhxt","tgjrbffdokudfdunnbfyylfandlhuy","tgjrbffdokudfdunnbfyylfandlhzw","tgjrbffdokudfdunnbfyylfandlhbd","tgjrbffdokudfdunnbfyylfandlhlt","tgjrbffdokudfdunnbfyylfandlhze","tgjrbffdokudfdunnbfyylfandlhum","tgjrbffdokudfdunnbfyylfandlhqv","tgjrbffdokudfdunnbfyylfandlhak","tgjrbffdokudfdunnbfyylfandlhvl","tgjrbffdokudfdunnbfyylfandlhhw","tgjrbffdokudfdunnbfyylfandlhbx","tgjrbffdokudfdunnbfyylfand","tgjrbffdokudfdunnbfyylfandlhfd","tgjrbffdokudfdunnbfyylfandlhim","tgjrbffdokudfdunnbfyylfandlhvp","tgjrbffdokudfdunnbfyylfandlhlh","tgjrbffdokudfdunnbfyylfandlhfc","tgjrbffdokudfdunnbfyylfandlhdo","tgjrbffdokudfdunnbfyylfandlhzo","tgjrbffdokudfdunnbfyylfandlhqo","tgjrbffdokudfdunnbfyylfandlhad","tgjrbffdokudfdunnbfyylfandlhwi","tgjrbffdokudfdunnbfyylfandlhzr","tgjrbffdokudfdunnbfyylfandlhsx","tgjrbffdokudfdunnbfyylfandlhf","tgjrbffdokudfdunnbfyylfandlhhm","tgjrbff","tgjrbffdokudfdunnbfyylfandlhkd","tgjrbffdokudfdunnbfyylfandlhuw","tgjrbffdokudfdunnbfyylfandlhwv","tgjrbffdokudfdunnbfyylfandlhlk","tgjrbffdokudfdunnbfyylfandlhnt","tgjrbffdokudfdunnbfyylfandlhlx","tgjrbffdokudfdunnbfyylfandlhvu","tgjrbffdokudfdunnbfyylfandlhke","tgjrbffdokudfdunnbfyylfandlhsc","tgjrbffdokudfdunnbfyylfandlhkf","tgjrbffdokudfdunnbfyylfandlhdy","tgjrbffdokudfdunnbfyylfandlhsn","tgjrbffdokudfdunnbfyylfandlhne","tgjrbffdokudfdunnbfyylfandlhdi","tgjrbffdokudfdunnbfyylfandlhli","tgjrbffdokudfdunnbfyylfandlhqm","tgjrbffdokudfdunnbfyylfandlhoq","tgjrbffdokudfdunnbfyylfandlhcy","tgjrbffdokudfdunnbfyylfandlhxa","tgjrbffdokudfdunnbfyylfandlhkq","tgjrbffdokudfdunnbfyylfandlhws","tgjrbffdokudfdunnbfyylfandlhhv","tgjrbffdokudfdunnbfyylfandlhjc","tgjrbffdokudfdunnbfyylfandlhfb","tgjrbffdokudfdunnbfyylfandlhv","tgjrbffd","tgjrbffdokudfdunnbfyylfandlhgt","tgjrbffdokudfdunnbfyylfandlhqj","tgjrbffdokudfdunnbfyylfandlhyt","tgjrbffdokudfdunnbfyylfandlhro","tgjrbffdokudfdunnbfyylfandlhyq","tgjrbffdokudfdunnbfyylfandlhbc","tgjrbffdokudfdunnbfyylfandlhbm","tgjrbffdokudfdunnbfyylfandlhba","tgjrbffdokudfdunnbfyylfandlhqi","tgjrbffdokudfdunnbfyylfandlhup","tgjrbffdokudfdunnbfyylfandlhyc","tgjrbffdokudfdunnbfyylfandlhkt","tgjrbffdokudfdunnbfyy","tgjrbffdokudfdunnbfyylfandlhtr","tgjrbffdokudfdunnbfyylfandlhpw","tgjrbffdokudfdunnbfyylfandlhcq","tgjrbffdokudfdunnbfyylfandlhzt","tgjrbffdokudfdunnbfyylf","tgjrbffdokudfdunnbfyylfandlhnw","tgjrbffdokudfdunnbfyylfandlhxu","tgjrbffdokudfdunnbfyylfandlhar","tgjrbffdokudfdunnbfyylfandlhfm","tgjrbffdokudfdunnbfyylfandlhmy","tgjrbffdokudfdunnbfyylfandlhoi","tgjrbffdokudfdunnbfyylfandlhay","tgjrbffdokudfdunnbfyylfandlheb","tgjrbffdokudfdunnbfyylfandlhaz","tgjrbffdokudfdunnbfyylfandlhrc","tgjrbffdokudfdunnbfyylfandlhka","tgjrbffdokudfdunnbfyylfandlhtl","tgjrbffdokudfdunnbfyylfandlhrn","tgjrbffdokudfdunnbfyylfandlhve","tgjrbffdokudfdunnbfyylfandlhts","tgjrbffdokudfdunnbfyylfandlhrp","tgjrbffdokudfdunnbfyylfandlhoe","tgjrbffdokudfdunnbfyylfandlhzn","tgjrbffdokudfdunnbfyylfandlhtd","tgjrbffdokudfdunnbfyylfandlhkn","tgjrbffdokudfdunnbfyylfandlheo","tgjrbffdokudfdunnbfyylfandlhzu","tgjrbffdokudfdunnbfyylfandlhea","tgjrbffdokudfdunnbfyylfandlhs","tgjrbffdokudfdunnbfyylfandlhyi","tgjrbffdokudfdunnbfyylfandlhfu","tgjrbffdokudfdunnbfyylfandlhlz","tgjrbffdokudfdunnbfyylfandlhmr","tgjrbffdokudfdunnbfyylfandlhxx","tgjrbffdokudfdunnbfyylfandlhue","tgjrbffdokudfdunnbfyylfandlhoo","tgjrbffdokudfdunnbfyylfandlhin","tgjrbffdok","tgjrbffdokudfdunnbfyylfandlhqw","tgjrbffdokudfdunnbfyylfandlhdf","tgjrbffdokudfdunnbfyylfandlhjy","tgjrbffdokudfdunnbfyylfandlhll","tgjrbffdokudfdunnbfyylfandlhaa" }; + auto res = sol.longestWord(words); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/temp/leetcode720-longest-word-in-dictionary_solution_temp2.cpp b/cpp-leetcode/temp/leetcode720-longest-word-in-dictionary_solution_temp2.cpp new file mode 100644 index 00000000..0aa2a9f9 --- /dev/null +++ b/cpp-leetcode/temp/leetcode720-longest-word-in-dictionary_solution_temp2.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include +using namespace std; + +/* 39 / 59 test cases passed. */ +class Solution { +public: + string longestWord(vector& words) { + if (words.empty()) return ""; + + map dict; + for (auto word : words) + { + if (isAllPrefixExist(word, words) && isSubstrCountMeet(word, words)) + dict.insert(make_pair(word, word.size())); + } + int maxLen = 0; + for (auto kvp : dict) + { + if (kvp.second > maxLen) + maxLen = kvp.second; + } + + map dict2; + for (auto kvp : dict) + { + if (kvp.second == maxLen) + { + dict2.insert(make_pair(kvp.first, kvp.second)); + } + } + auto firstKvp = *std::next(dict2.begin(), 0); + return firstKvp.first; + } + + bool isAllPrefixExist(string theWord, vector words) + { + int len = theWord.size(); + int containCount = 0; + int i = len; + while (i > 0) + { + if (find(words.begin(), words.end(), theWord.substr(0, i)) != words.end()) + containCount++; + i--; + } + return containCount == len; + } + + bool isSubstrCountMeet(string theWord, vector words) + { + int count = 0; + bool hasFirstLetter = false; + vector numsWithLen; + for (auto word : words) + { + if (word.size() == 1) + numsWithLen.push_back(word); + } + if (find(numsWithLen.begin(), numsWithLen.end(), theWord.substr(0, 1)) != numsWithLen.end()) + hasFirstLetter = true; + + for (auto word : words) + { + if (theWord.find(word) != string::npos) + count++; + } + return hasFirstLetter && (count >= theWord.size()); + } +}; + +// Test +int main() +{ + Solution sol; + // vector words = { "a", "banana", "app", "appl", "ap", "apply", "apple" }; + vector words = { "cxkhcgbrleqmcdgafmukhijsctpsgz","cxkhcgbrleqmcdgafmukhijsctpssg","cxkhcgbrleqmcdgafmukhijsctpsha","cxkhcgbrleqmcdgafmukhijsctpsqw","cxkhcgbrleqmcdgafmukhijsctpsas","cxkhcgbrleqmcdgafmukhijsctpstf","cxkhcgbrleqmcdgafmukhijsctpsid","cxkhcgbrleqmcdgafmukhijsctpsau","cxkhcgbrleqmcdgafmukhijsctpsdj","cxkhcgbrleqmcdgafmukhijsctpssb","cxkhcgbrleqmcdgafmukhijsctpsma","cxkhcgbrleqmcdgafmukhijsctpssl","cxkhcgbrleqmcdgafmukhijsctpsgy","cxk","cxkhcgbrleqmcdgafmukhijsctpsua","cxkhcgbrleqmcdgafmukhijsctpsyb","cxkhcgbrleqmcdgafmukhijsctpsgf","cxkhcgbrleqmcdgafmukhijsctpszn","cxkhcgbrleqmcdgafmukhijsctpsch","cxkhcgbrleqmcdgafmukhijsctpsrb","cxkhcgbrleqmcdgafmukhijsctpsnp","cxkhcgbrleqmcdgafmukhijsctpscy","cxkhcgbrleqmcdgafmukhijsctpsjp","cxkhcgbrleqmcdgafmukhijsctpsjo","cxkhcgbrleqmcdgafmukhijsctpsbb","cxkhcgbrleqmcdgafmukhijsc","cxkhcgbrleqmcdgafmukhijsctpsuj","cxkhcgbrleqmcdgafmukhijsctpsaz","cxkhcgbrleq","cxkhcgbrleqmcdgafmukhijsctpsdw","cxkhcgbrleqmcdgafmukhijsctpsnk","cxkhcgbrleqmcdgafmukhijsctpszk","cxkhcgbrleqmcdgafmukhijsctpswt","cxkhcgbrleqmcdgafmukhijs","cxkhcgbrleqmcdgafmukhijsctpshx","cxkhcgbrleqmcdgafmukhijsctpszt","cxkhcgbrleqmcdgafmukhijsctpsfr","cxkhcgbrleqmcdgafmukhijsctpspa","cxkhcgbrleqmcdgafmukhijsctpsbs","cxkhcgbrleqmcdgafmukhijsctpsxt","cxkhcgbrleqmcdgafmukhijsctpsyk","cxkhcgbrleqmcdgafmukhijsctpsra","cxkhcgbrleqmcdgafmukhijsctpssh","cxkhcgbrleqmcdgafmukhijsctpsj","cxkhcgbrleqmcdgafmukhijsctpsnd","cxkhcgbrleqmcdgafmukhijsctpsrr","cxkhcgbrleqmcdgafmukhijsctpslw","cxkhcgbrleqmcdgafmukhijsctpsnc","cxkhcgbrleqmcdgafmukhijsctpsih","cxkhcgbrleqmcdgafmukhijsctpslx","cxkhcgbrleqmcdgafmukhijsctpsvf","cxkhcgbrleqmcdgafmukhijsctpstl","cxkhcgbrleqmcdgafmukhijsctpssw","cxkhcgbrleqmcdgafmukhijsctpsle","cxkhcgbrleqmcdgafmukhijsctpspo","cxkhcgbrleqmcdgafmukhijsctpsrw","cxkhcgbrleqmcdgafmukhijsctpsxc","cxkhcgbrleqmcdgafmukhijsctpsrq","cxkhcgbrleqmcdgafmuk","cxkhcgbrleqmcdgafmukhijsctpsla","cxkhcgbrleqmcdgafmukhijsctpsgc","cxkhcgbrleqmcdgafmukhijsctpsay","cxkhcgbrleqmcdgafmukhijsctpscb","cxkhcgbrleqmcdgafmukhijsctpsaj","cxkhcgbrleqmcdgafmu","cxkhcgbrleqmcdgafmukhijsctpsgj","cxkhcgbrleqmcdgafmukhijsctpspl","cxkhcgbrleqmcdgafmukhijsctpsvz","cxkhc","cxkhcgbrleqmcdgafmukhijsctpsji","cxkhcgbrleqmcdgafmukhijsctpsjl","cxkhcgbrleqmcdgafmukhijsctpsef","cxkhcgbrleqmcdgafmukhijsctpsyi","cxkhcgbrleqmcdgafmukhijsctpsqa","cxkhcgbrleqmcdgafmukhijsctpszd","cxkhcgbrleqmcdgafmukhijsctpsyg","cxkhcgbrleqmcdgafmukhijsctpsbn","cxkhcgbrleqmcdgafmukhijsctpsfm","cxkhcgbrleqmcdgafmukhijsctpsuz","cxkhcgbrleqmcdgafmukhijsctpss","cxkhcgbrleqmcdgafmukhijsctpscp","cxkhcgbrleqmcdgafmukhijsctpsgg","cxkhcgb","cxkhcgbrleqmcdgafmukhijsctpskw","cxkhcgbrleqmcdgafmukhijsctpsky","cxkhcgbrleqmcdgafmukhijsctpswz","cxkhcgbrleqmcdgafmukhijsctpsdn","cxkhcgbrleqmcdgafmukhijsctpsjd","cxkhcgbrleqmcdgafmukhijsctpstz","cxkhcgbrleqmcdgafmukhijsctpspu","cxkhcgbrleqmcdgafmukhijsctpsxb","cxkhcgbrleqmcdgafmukhijsctpsum","cxkhcgbrleqmcdgafmukhijsctpsot","cxkhcgbrleqmcdgafmukhijsctpszs","cxkhcgbrleqmcdgafmukhijsctpscj","cxkhcgbrleqmcdgafmukhijsctpspt","cxkhcgbrleqmcdgafmukhijsctpsgr","cxkhcgbrleqmcdgafmukhijsctpsuv","cxkhcgbrleqmcdgafmukhijsctpsfj","cxkhcgbrleqmcdgafmukhijsctpssz","cxkhcgbrleqmcdgafmukhijsctpsyd","cxkhcgbrleqmcdgafmukhijsctpsfs","cxkhcgbrleqmcdgafmukhijsctpsae","cxkhcgbrleqmcdgafmukhijsctpsli","cxkhcgbrleqmcdgafmukhijsctpswn","cxkhcgbrleqmcdgafmukhijsctpscv","cxkhcgbrleqmcdgafmukhijsctpsxo","cxkhcgbrleqmcdgafmukhijsctpsjn","cxkhcgbrleqmcdgafmukhijsctpsnb","cxkhcgbrleqmcdgafmukhijsctpsur","cxkhcgbrleqmcdgafmukhijsctpsrc","c","cxkhcgbrleqmcdgafmukhijsctpsdl","cxkhcgbrleqmcdgafmukhijsctpsie","cxkhcgbrleqmcdgafmukhijsctpsvn","cxkhcgbrleqmcdgafmukhijsctpsfc","cxkhcgbrleqmcdgafmukhijsctpski","cxkhcgbrleqmcdgafmukhijsctpsic","cxkhcgbrleqmcdgafmukhijsctpsff","cxkhcgbrleqmcdgafmukhijsctpsui","cxkhcgbrleqmcdgafmukhijsctpsvw","cxkhcgbrleqmcdgafmukhijsctpskc","cxkhcgbrleqmcdgafmukhijsctpstx","cxkhcgbrleqmcdgafmukhijsctpsri","cxkhcgbrleqmcdgafmukhijsctpsqn","cxkhcgbrleqmcdgafmukhijsctpsdv","cxkhcgbrleqmcdgafmukhijsctpsds","cxkhcgbrleqmcdgafmukhijsctpsvg","cxkhcgbrleqmcdgafmukhijsctpscd","cxkhcgbrleqmcdgafmukhijsctpswe","cxkhcgbrleqmcdgafmukhijsctpsib","cxkhcgbrleqmcdgafmukhijsctpsuc","cxkhcgbrleqmcdgafmukhijsctpsxi","cxkhcgbrleqmcdgafmukhijsctpspz","cxkhcgbrleqmcdgafmukhijsctpsdc","cxkhcgbrleqmcdgafmukhijsctpszr","cxkhcgbrleqmcdgafmukhijsctpshe","cxkhcgbrleqmcdgafmukhijsctpsh","cxkhcgbrleqmcdgafmukhijsctpsxs","cxkhcgbrleqmcdgafmukhijsctpsto","cxkhcgbrleqmcdgafmukhijsctpsws","cxkhcgbr","cxkhcgbrleqmcdgafmukhijsctpssa","cxkhcgbrleqmcdgafmukhijsctpswv","cxkhcgbrleqmcdgafmukhijsctpsgn","cxkhcgbrleqmcdgafmukhijsctpsao","cxkhcgbrleqmcdgafmukhijsctpszm","cxkhcgbrleqmcdgafmukhijsctpsva","cxkhcgbrleqmcdgafmukhijsctpsgh","cxkhcgbrleqmcdgafmukhijsctpsip","cxkhcgbrleqmcdgafmukhijsctpsgs","cxkhcgbrleqmcdgafmukhijsctpsxz","cxkhcgbrleqmcdga","cxkhcgbrleqmcdgafmukhijsctpseg","cxkhcgbrleqmcdgafmukhijsctpsku","cxkhcgbrleqmcdgafmukhijsctpsdz","cxkhcgbrleqmcdgafmukhijsctpsso","cxkhcgbrleqmcdgafmukhijsctpshw","cxkhcgbrleqmcdgafmukhijsctpsou","cxkhcgbrleqmcdgafmukhijsctpssc","cxkhcgbrleqmcdgafmukhijsctpsrj","cxkhcgbrleqmcdgafmukhijsctpset","cxkhcgbrleqmcdgafmukhijsctpscr","cxkhcgbrleqmcdgafmukhijsctpsya","cxkhcgbrleqmcdgafmukhijsctpsej","cxkhcgbrleqmcdgafmukhijsctpsub","cxkhcgbrleqmcdgafmukhijsctpszx","cxkhcgbrleqmcdgafmukhijsctpsxq","cxkh","cxkhcgbrleqmcdgafmukhijsctpsdu","cxkhcgbrleqmcdgafmukhijsctpsw","cxkhcgbrleqmcdgafmukhijsctpseq","cxkhcgbrleqmcdgafmukhijsctpsxn","cxkhcgbrleqmcdgafmukhijsctpswr","cxkhcgbrleqmcdgafmukhijsctpszv","cxkhcgbrleqmcdgafmukhijsctpsjc","cxkhcgbrleqmcdgafmukhijsctpspi","cxkhcgbrleqmcdgafmukhijsctpspg","cxkhcgbrleqmcdgafmukhijsctpsbt","cxkhcgbrleqmcdgafmukhijsctpsdt","cxkhcgbrleqmcdgafmukhijsctpsdg","cxkhcgbrleqmcdgafmukhijsctpsmb","cxkhcgbrleqmcdgafmukhijsctpsgo","cxkhcgbrleqmcdgafmukhijsctpsfb","cxkhcgbrleqmcdgafmukhijsctpska","cxkhcgbrleqmcdgafmukhijsctpslq","cxkhcgbrleqmcdgafmukhijsctpsi","cxkhcgbrleqmcdgafmukhijsctpstw","cxkhcgbrleqmcdgafmukhijsctpspx","cxkhcgbrleqmcdgafmukhijsctpspe","cxkhcgbrleqmcdgafmukhijsctpspp","cxkhcgbrleqmcdgafmukhijsctpsbh","cxkhcgbrleqmcdgafmukhijsctpsbf","cxkhcgbrleqmcdgafmukhijsctpsuy","cxkhcgbrleqmcdgafmukhijsctpsey","cxkhcgbrleqmcdgafmukhijsctpsy","cxkhcgbrleqmcdgafmukhijsctpsgu","cxkhcgbrleqmcdgafmukhijsctpsmc","cxkhcgbrleqmcdgafmukhijsctpsbr","cxkhcgbrleqmcdgafmukhijsctpsmy","cxkhcgbrleqmcdgafmukhijsctpsps","cxkhcgbrleqmcdgafmukhijsctpsfq","cxkhcgbrleqmcdgafmukhijsctpsxe","cxkhcgbrleqmcdgafmukhijsctpszc","cxkhcgbrleqmcdgafmukhijsctpsyt","cxkhcgbrleqmcdgafmukhijsctpsut","cxkhcgbrleqmcdgafmukhijsctpshm","cxkhcgbrleqmcdgafmukhijsctpstn","cxkhcgbrleqmcdgafmukhijsctpsll","cxkhcgbrleqmcdgafmukhijsctpsfu","cxkhcgbrleqmcdgafmukhijsctpsbq","cxkhcgbrleqmcdgafmukhijsctpsgt","cxkhcgbrleqmcdgafmukhijsctpsuf","cxkhcgbrleqmcdgafmukhijsctpsjf","cxkhcgbrleqmcdgafmukhijsctpsuq","cxkhcgbrleqmcdgafmukhijsctpse","cxkhcgbrleqmcdgafmukhijsctpskb","cxkhcgbrleqmcdgafmukhijsctpsml","cxkhcgbrleqmcdgafmukhijsctpsnu","cxkhcgbrleqmcdgafmukhijsctpsco","cxkhcgbrleqmcdgafmukhijsctpsxw","cxkhcgbrleqmcdgafmukhijsctpsfo","cxkhcgbrleqmcdgafmukhijsctpsdr","cxkhcgbrleqmcdgafmukhijsctpsfz","cxkhcgbrleqmcdgafmukhijsctpsza","cxkhcgbrleqmcdgafmukhijsctpsnf","cxkhcgbrleqmcdgafmukhijsctpscu","cxkhcgbrleqmcdgafmukhijsctpsoa","cxkhcgbrleqmcdgafmukhijsctpsqr","cxkhcgbrleqmcdgafmukhijsctpsgb","cxkhcgbrleqmcdgafmukhijsctpshd","cxkhcgbrl","cxkhcgbrleqmcdgafmukhijsctpsik","cxkhcgbrleqmcd","cxkhcgbrleqmcdgafmukhijsctpser","cxkhcgbrleqmcdgafmukhijsctpscq","cxkhcgbrleqmcdgafmukhijsctpsvv","cxkhcgbrleqmcdgafmukhijsctpsrm","cxkhcgbrleqmcdgafmukhijsctpstq","cxkhcgbrleqmcdgafmukhijsctpsvo","cxkhcgbrleqmcdgafmukhijsctpspn","cxkhcgbrleqmcdgafmukhijsctpseo","cxkhcgbrleqmcdgafmukhijsctpsm","cxkhcgbrleqmcdgafmukhijsctpsix","cxkhcgbrleqmcdgafmukhijsctpsil","cxkhcgbrleqmcdgafmukhijsctpsif","cxkhcgbrleqmcdgafmukhijsctpsuk","cxkhcgbrleqmcdgafmukhijsctpsjt","cxkhcgbrleqmcdgafmukhijsctpsms","cxkhcgbrleqmcdgafmukhijsctpsyn","cxkhcgbrleqmcdgafmukhijsctpslm","cxkhcgbrleqmcdgafmukhijsctpstb","cxkhcgbrleqmcdgafmukhijsctpsuh","cxkhcgbrleqmcdgafmukhijsctpsmk","cxkhcgbrleqmcdgafmukhijsctpsyx","cxkhcgbrleqmcdgafmukhijsctpszp","cxkhcgbrleqmcdgafmukhijsctpsdd","cxkhcgbrleqmcdgafmukhijsctpsex","cxkhcgbrleqmcdgafmukhijsctpsny","cxkhcgbrleqmcdgafmukhijsctpsdm","cxkhcgbrleqmcdgafmukhijsctpshc","cxkhcgbrleqmcdgafmukhijsctpspj","cxkhcgbrleqmcdgafmukhijsctpsug","cxkhcgbrleqmcdgafmukhijsctpsew","cxkhcgbrleqmcdgafmukhijsctpswg","cxkhcgbrleqmcdgafmukhijsctpsko","cxkhcgbrleqmcdgafmukhijsctpsmj","cxkhcgbrleqmcdgafmukhijsctpsdp","cxkhcgbrleqmcdgafmukhijsctpsro","cxkhcgbrleqmcdgafmukhijsctpsci","cxkhcgbrleqmcdgafmukhijsctpsyu","cxkhcgbrleqmcdgafmukhijsctpscc","cxkhcgbrleqmcdgafmukhijsctpstk","cxkhcgbrleqmcdgafmukhijsctpsld","cxkhcgbrleqmcdgafmukhijsctpsnw","cxkhcgbrleqmcdgafmukhijsctpsz","cxkhcgbrleqmcdgafmukhijsctpsqp","cxkhcgbrleqmcdgafmukhijsctpshp","cxkhcgbrleqmcdgafmukhijsctpsbc","cxkhcgbrleqmcdgafmukhijsctpsmq","cxkhcgbrleqmcdgafmukhijsctpsys","cxkhcgbrleqmcdgafmukhijsctpsbd","cxkhcgbrleqmcdgafmukhijsctpsav","cxkhcgbrleqmcdgafmukhijsctpswi","cxkhcgbrleqmcdgafmukhijsctpsqi","cxkhcgbrleqmcdgafmukhijsctpsqc","cxkhcgbrleqmcdgafmukhijsctpsak","cxkhcgbrleqmcdgafmukhijsctpsah","cxkhcgbrleqmcdgafmukhijsctpscg","cxkhcgbrleqmcdgafmukhijsctpsfi","cxkhcgbrleqmcdgafmukhijsctpswc","cxkhcgbrleqmcdgafmukhijsctpskd","cxkhcgbrleqmcdgafmukhijsctpsjv","cxkhcgbrleqmcdgafmukhijsctpsgi","cxkhcgbrleqmcdgafmukhijsctpsus","cxkhcgbrleqmcdgafmukhijsctpsbl","cxkhcgbrleqmcdgafmukhijsctpsvk","cxkhcgbrleqmcdgafmukhijsctpsqf","cxkhcgbrleqmcdgafmukhijsctpslj","cxkhcgbrleqmcdgafmukhijsctpszz","cxkhcgbrleqmcdgafmukhijsctpsx","cxkhcgbrleqmcdgafmukhijsctpsxf","cxkhcgbrleqmcdgafmukhijsctpsyr","cxkhcgbrleqmcdgafmukhijsctpsve","cxkhcgbrleqmcdgafmukhijsctpseb","cxkhcgbrleqmcdgafmukhijsctpszy","cxkhcgbrleqmcdgafmukhijsctpsmh","cxkhcgbrleqmcdgafmukhijsctpsa","cxkhcgbrleqmcdgafmukhijsctpsmm","cxkhcgbrleqmcdgafmukhijsctpspw","cxkhcgbrleqmcdgafmukhijsctpsce","cxkhcgbrleqmcdgafmukhijsctpsyc","cxkhcgbrleqmcdgafmukhijsctpssu","cxkhcgbrleqmcdgafmukhijsctpsdi","cxkhcgbrleqmcdgafmukhijsctpsmp","cxkhcgbrleqmcdgafmukhijsctpsiq","cxkhcgbrleqmcdgafmukhijsctpsvj","cxkhcgbrleqmcdgafmukhijsctpszq","cxkhcgbrleqmcdgafmukhijsctpsrx","cxkhcgbrleqmcdgafmukhijsctpson","cxkhcgbrleqmcdgafmukhijsctpskk","cxkhcgbrleqmcdgafmukhijsctpskp","cxkhcgbrleqmcdgafmukhijsctpsow","cxkhcgbrleqmcdgafmukhijsctpsr","cxkhcgbrleqmcdgafmukhijsctpsne","cxkhcgbrleqmcdgafmukhijsctpsqx","cxkhcgbrleqmcdgafmukhijsctpskf","cxkhcgbrleqmcdgafmukhijsctpssr","cxkhcgbrleqmcdgafmukhijsctpsgv","cxkhcgbrleqmcdgafmukhijsctpsaw","cxkhcgbrleqmcdgafmukhijsctpsv","cxkhcgbrleqmcdgafmukhijsctpsmx","cxkhcgbrleqmcdgafmukhijsctpsmg","cxkhcgbrleqmcdgafmukhijsctpsag","cxkhcgbrleqmcdgafmukhijsctpssy","cxkhcgbrleqmcdgafmukhijsctpsfe","cxkhcgbrleqmcdgafmukhijsctpsev","cxkhcgbrleqmcdgafmukhijsctpskq","cxkhcgbrleqmcdgafmukhijsctpscz","cxkhcgbrleqmcdgafmukhijsctpstm","cxkhcgbrleqmcdgafmukhijsctpsxy","cxkhcgbrleqmcdgafmukhijsctpsio","cxkhcgbrleqmcdgafmukhijsctpsan","cxkhcgbrleqmcdgafmukhijsctpsu","cxkhcgbrleqmcdgafmukhijsctpsnn","cxkhcgbrleqmcdgafmukhijsctpsno","cxkhcgbrleqmcdgafmukhijsctpsaf","cxkhcgbrleqmcdgafmukhijsctpswq","cxkhcgbrleqmcdgafmukhijsctpsoj","cxkhcgbrleqmcdgafmukhijsctpsd","cxkhcgbrleqmcdgafmukhijsctpsvd","cxkhcgbrleqmcdgafmukhijsctpsqe","cxkhcgbrleqmcdgafmukhijsctpsru","cxkhcgbrleqmcdgafmukhijsctpsyj","cxkhcgbrleqmcdgafmukhijsctpsju","cxkhcgbrleqmcdgafmukhijsctpsjh","cxkhcgbrleqmcdgafmukhijsctpsvm","cxkhcgbrleqmcdgafmukhijsctpsis","cxkhcgbrleqmcdgafmukhijsctpsue","cxkhcgbrleqmcdgafmukhijsctpsni","cxkhcgbrleqmcdgafmukhijsctpstr","cxkhcgbrleqmcdgafmukhijsctpsfd","cxkhcgbrleqmcdgafmukhijsctpsop","cxkhcgbrleqmcdgafmukhijsctpslk","cxkhcgbrleqmcdgafmukhijsctpsep","cxkhcgbrleqmcdgafmukhijsctpsjb","cxkhcgbrleqmcdgafmukhijsctpszg","cxkhcgbrleqmcdgafmukhijsctpscw","cxkhcgbrleqmcdgafmukhijsctpsul","cxkhcgbrleqmcdgafmukhijsctpssi","cxkhcgbrleqmcdgafmukhijsctpsja","cxkhcgbrleqmcdgafmukhijsctpszb","cxkhcgbrleqmcdgafmukhijsctpsge","cxkhcgbrleqmcdgafmukhijsctpsme","cxkhcgbrleqmcdgafmukhijsctpsvq","cxkhcgbrleqmcdgafmukhijsctpsnx","cxkhcgbrleqmcdgafmukhijsctpsfh","cxkhcgbrleqmcdgafmukhijsctpsn","cxkhcgbrleqmcdgafmukhijsctpsmv","cxkhcgbrleqmcdgafmukhijsctpsvx","cxkhcgbrleqmcdgafmukhijsctpsor","cxkhcgbrleqmcdgafmukhijsctpsaq","cxkhcgbrleqmcdgafmukhijsctpswl","cxkhcgbrleqmcdgafmukhijsctpsbo","cx","cxkhcgbrleqmcdgafmukhijsctpswf","cxkhcgbrleqmcdgafmukhijsctpst","cxkhcgbrleqmcdgafmukhijsctpsl","cxkhcgbrleqmcdgafmukhijsctpsqh","cxkhcgbrleqmcdgafmukhijsctpskv","cxkhcgbrleqmcdgafmukhijsctpsbe","cxkhcgbrleqmcdgafmukhijsctpswm","cxkhcgbrleqmcdgafmukhijsctpsxu","cxkhcgbrleqmcdgafmukhijsctpsqu","cxkhcgbrleqmcdgafmukhijsctpsjg","cxkhcgbrleqmcdgafmukhijsctpsoe","cxkhcgbrleqmcdgafmukhijsctpso","cxkhcgbrleqmcdgafmukhijsctpsbx","cxkhcgbrleqmcdgafmukhijsctps","cxkhcgbrleqmcdgafmukhijsctpsby","cxkhcgbrleqmcdgafmukhijsctpsvi","cxkhcgbrleqmcdgafmukhijsctpsoq","cxkhcgbrleqmcdgafmukhijsctpsdk","cxkhcgbrleqmcdgafmukhijsctpsim","cxkhcgbrleqmcdgafmukhijsctpspq","cxkhcgbrleqmcdgafmukhijsctpsf","cxkhcgbrleqmcdgafmukhijsctpsfk","cxkhcgbrleqmcdgafmukhijsctpsq","cxkhcgbrleqmcdgafmukhijsctpsfa","cxkhcgbrleqmcdgafmukhijsctpswy","cxkhcgbrleqmcdgafmukhijsctpslh","cxkhcgbrleqmcdgafmukhijsctpsxk","cxkhcgbrleqmcdgafmukhijsctpslc","cxkhcgbrleqmcdgafmukhijsctpsyp","cxkhcgbrleqmcdgafmukhijsctpsts","cxkhcgbrleqmcdgafmukhijsctpshg","cxkhcgbrleqmcdgafmukhijsctpsyf","cxkhcgbrleqmcdgafmukhijsctpsup","cxkhcgbrleqmcdgafmukhijsctpshj","cxkhcgbrleqmcdgafmukhijsctpsbj","cxkhcgbrleqmcdgafmukhijsctpssq","cxkhcgbrleqmcdgafmukhijsctpssm","cxkhcgbrleqmcdgafmukhijsctpskz","cxkhcgbrleqmcdgafmukhijsctpspd","cxkhcgbrleqmcdgafmukhijsctpsyh","cxkhcgbrleqmcdgafmukhijsctpsg","cxkhcgbrleqmcdgafmukhijsctpswo","cxkhcgbrleqmcdgafmukhijsctpshq","cxkhcgbrleqmcdgafmukhijsctpsjw","cxkhcgbrleqmcdgafmukhijsctpsgq","cxkhcgbrleqmcdgafmukhijsctpscf","cxkhcgbrleqmcdgafmukh","cxkhcgbrleqmcdgafmukhijsctpsrf","cxkhcgbrleqmcdgafmukhijsctp","cxkhcgbrleqmcdgafmukhijsctpshk","cxkhcgbrleqmcdgafmukhijsctpsrl","cxkhcgbrleqmcdgafmukhijsctpsuw","cxkhcgbrleqmcdgafmukhijsctpsnt","cxkhcgbrleqmcdgafmukhijsctpsrz","cxkhcgbrleqmcdgafmukhijsctpsia","cxkhcgbrleqmcdgafmukhijsctpsk","cxkhcgbrleqmcdgafmukhijsctpsmo","cxkhcgbrleqmcdgafmukhijsctpslp","cxkhcgbrleqmcdgafmukhijsctpsfn","cxkhcgbrleqmcdgafmukhijsctpsgm","cxkhcgbrleqmcdgafmukhijsctpsei","cxkhcgbrleqmcdgafmukhijsctpsai","cxkhcgbrleqmcdgafmukhijsctpsom","cxkhcgbrleqmcdgafmukhijsctpsvb","cxkhcgbrleqmcdgafmukhijsctpslf","cxkhcgbrleqmcdgafmukhijsctpsbz","cxkhcgbrleqmcdgafmukhijsctpsbm","cxkhcgbrleqmcdgafmukhijsctpspr","cxkhcgbrleqmcdgafmukhijsctpsxl","cxkhcgbrleqmcdgafmukhijsctpsgw","cxkhcgbrleqmcdgafmukhijsctpsqy","cxkhcgbrleqmcdgafmukhijsctpsmd","cxkhcgbrleqmcdgafmukhijsctpsel","cxkhcgbrleqmcdgafmukhijsctpsrt","cxkhcgbrleqmcdgafmukhijsctpskm","cxkhcgbrleqmcdgafmukhijsctpswj","cxkhcgbrleqmcdgafmukhijsctpsns","cxkhcgbrleqmcdgafmukhijsctpsc","cxkhcgbrleqmcdgafmukhijsctpsij","cxkhcgbrleqmcdgafmukhijsctpsvu","cxkhcgbrleqmcdgafmukhijsctpsud","cxkhcgbrleqmcdgafmukhijsctpskx","cxkhcgbrleqmcdgafmukhijsctpsgx","cxkhcgbrleqmcdgafmukhijsctpsiu","cxkhcgbrleqmcdgafmukhijsctpsti","cxkhcgbrleqmcdgafmukhijsctpsqd","cxkhcgbrleqmcdgafmukhijsctpslr","cxkhcgbrleqmcdgafmukhijsctpsdh","cxkhcgbrleqmcdgafmukhijsctpswd","cxkhcgbrleqmcdgafmukhijsctpspb","cxkhcgbrleqmcdgafmukhijsctpsdb","cxkhcgbrleqmcdgafmukhijsctpsvh","cxkhcgbrleqmcdgafmukhijsctpssd","cxkhcgbrleqmcdgafmukhijsctpsap","cxkhcgbrleqm","cxkhcgbrleqmcdgafmukhijsctpsbu","cxkhcgbrleqmcdgafmukhijsctpsiw","cxkhcgbrleqmcdgafmukhijsctpsb","cxkhcgbrleqmcdgafmukhijsctpsoi","cxkhcgbrleqmcdgafmukhijsctpsmn","cxkhcgbrleqmcdgafmukhijsctpsux","cxkhcgbrleqmcdgafmukhijsctpsft","cxkhcgbrleqmcdgafmukhijsctpsgl","cxkhcgbrleqmcdgafmukhijsctpsye","cxkhcgbrleqmcdgafmukhijsctpsqo","cxkhcgbrleqmcdgafmukhijsctpsss","cxkhcgbrleqmcdgafmukhijsctpsrv","cxkhcgbrleqmcdgafmukhijsctpswh","cxkhcgbrleqmcdgafmukhijsctpsee","cxkhcgbrleqmcdgafmukhijsctpsty","cxkhcgbrleqmcdgafmukhijsctpsym","cxkhcgbrleqmcdgafmukhijsctpshi","cxkhcgbrleqmcdgafmukhijsctpsit","cxkhcgbrleqmcdgafmukhijsctpsam","cxkhcgbrleqmcdgafmukhijsctpsgd","cxkhcgbrleqmcdgafmukhijsctpstv","cxkhcgbrleqmcdgafmukhijsctpshh","cxkhcgbrleqmcdgafmukhijsctpsho","cxkhcgbrleqmcdgafmukhijsctpsmw","cxkhcgbrleqmcdgafmukhijsctpsse","cxkhcgbrleqmcdgafmukhijsctpsgp","cxkhcgbrleqmcdgafmukhijsctpsqt","cxkhcgbrleqmcdgafmukhijsctpsgk","cxkhcgbrleqmcdgafmukhijsctpsga","cxkhcgbrleqmcdgafmukhijsctpstj","cxkhcgbrleqmcdgafmukhijsctpsyq","cxkhcgbrleqmcdgafmukhijsctpsox","cxkhcgbrleqmcdgafmukhijsctpsuo","cxkhcgbrleqmcdgafmukhijsctpswb","cxkhcgbrleqmcdgafmukhijsctpscm","cxkhcgbrleqmcdgafmukhijsctpseu","cxkhcgbrleqmcdgafmukhijsctpsmr","cxkhcgbrleqmcdgafmukhijsctpsog","cxkhcgbrleqmcdgafmukhijsctpscs","cxkhcgbrleqmcdgafmukhijsctpseh","cxkhcgbrleqmcdgafmukhijsctpsjq","cxkhcgbrleqmcdgafmukhijsctpsvs","cxkhcgbrleqmcdgafmukhijsctpsat","cxkhcgbrleqmcdgafmukhijsctpstd","cxkhcgbrleqmcdgafmukhijsctpsok","cxkhcgbrleqmcdgafmukhijsctpswp","cxkhcgbrleqmcdgafmukhijsctpssx","cxkhcgbrleqmcdgafmukhijsctpsyy","cxkhcgbrleqmcdgafmukhijsctpsab","cxkhcgbrleqmcdgafmukhijsctpsxp","cxkhcgbrleqmcdgafmukhijsctpsqk","cxkhcgbrleqmcdgafmukhijsctpsrp","cxkhcgbrleqmcdgafmukhijsctpsmf","cxkhcgbrleqmcdgafmukhijsctpsnv","cxkhcgbrleqmcdgafmukhijsctpsls","cxkhcgbrleqmcdgafmukhijsctpsal","cxkhcgbrleqmcdgafmukhijsctpsnl","cxkhcgbrleqmcdgafmukhijsctpswu","cxkhcgbrleqmcdgafmukhijsctpsmu","cxkhcgbrleqmcdgafmukhijsctpsyz","cxkhcgbrleqmcdgafmukhijsctpstp","cxkhcgbrleqmcdgafmukhijsctpshf","cxkhcgbrleqmcdgafmukhijsctpszl","cxkhcgbrleqmcdgafmukhijsctpsob","cxkhcgbrleqmcdgafmukhijsctpsp","cxkhcgbrleqmcdgafmukhijsctpsvl","cxkhcgbrleqmcdgafmukhij","cxkhcgbrleqmcdgafmukhijsctpsek","cxkhcgbrleqmcdgafmukhijsctpsrd","cxkhcgbrleqmcdgafmukhijsctpsly","cxkhcgbrleqmcdgafmukhijsctpsxg","cxkhcgbrleqmcdgafmukhijsctpszw","cxkhcgbrleqmcdgafmukhijsctpszi","cxkhcgbrleqmcdgafmukhijsctpsqv","cxkhcgbrleqmcdgafmukhijsctpsed","cxkhcgbrleqmcdgaf","cxkhcgbrleqmcdgafmukhijsctpsjy","cxkhcgbrleqmcdgafmukhijsctpsfw","cxkhcgbrleqmcdgafmukhijsctpsun","cxkhcgbrleqmcdgafmukhijsctpsyl","cxkhcgbrleqmcdgafmukhijsctpszh","cxkhcgbrleqmcdgafmukhijsctpsec","cxkhcgbrleqmcdgafmukhijsctpskr","cxkhcgbrleqmcdgafmukhijsctpsxh","cxkhcgbrleqmcdgafmukhijsctpspm","cxkhcgbrleqmcdgafmukhijsctpshr","cxkhcgbrleqmcdgafmukhijsctpsoh","cxkhcgbrleqmcdgafmukhijsctpsvc","cxkhcgbrleqmcdgafmukhijsctpsir","cxkhcgbrleqmcdgafmukhijsctpsvy","cxkhcgbrleqmcdgafmukhijsctpsyw","cxkhcgbrleqmc","cxkhcgbrleqmcdgafmukhijsctpsnh","cxkhcgbrleqmcdgafmukhijsctpsvr","cxkhcgbrleqmcdgafmukhijsctpspc","cxkhcgbrleqmcdgafmukhijsctpsfy","cxkhcgbrleqmcdgafmukhijsctpsna","cxkhcgbrleqmcdgafmukhijsctpsiy","cxkhcgbrleqmcdgafmukhijsctpsnz","cxkhcgbrleqmcdgafmukhijsctpsfl","cxkhcgbrleqmcdgafmukhijsctpsbp","cxkhcgbrleqmcdgafmukhijsctpshz","cxkhcgbrleqmcdgafmukhijsctpswa","cxkhcgbrleqmcdgafmukhijsctpskt","cxkhcgbrleqmcdgafmukhijsctpsbi","cxkhcgbrleqmcdgafmukhijsctpshl","cxkhcgbrleqmcdgafmukhijsctpscn","cxkhcgbrleqmcdgafmukhijsctpspy","cxkhcgbrleqmcdgafmukhijsctpsct","cxkhcgbrleqmcdgafmukhijsctpsov","cxkhcgbrleqmcdgafmukhijsctpsqb","cxkhcgbrleqmcdgafmukhijsctpsos","cxkhcgbrleqmcdgafmukhijsctpsez","cxkhcgbrleqmcdgafmukhijsctpstg","cxkhcgbrleqmcdgafmukhijsctpsjj","cxkhcgbrleqmcdgafmukhijsctpsks","cxkhcgbrleqmcdgafmukhijsctpslo","cxkhcgbrleqmcdgafmukhijsctpsmt","cxkhcgbrleqmcdgafmukhijsctpsjs","cxkhcgbrleqmcdgafmukhijsctpssk","cxkhcgbrleqmcdgafmukhijsctpsxv","cxkhcgbrleqmcdgafmukhijsctpsst","cxkhcgbrleqmcdgafmukhijsctpsql","cxkhcgbrleqmcdgafmukhijsctpssf","cxkhcgbrleqmcdgafmukhijsctpsww","cxkhcgbrleqmcdgafmukhijsctpspf","cxkhcgbrleqmcdgafmukhijsctpste","cxkhcgbrleqmcdgafmukhijsctpsjm","cxkhcgbrleqmcdgafmukhijsctpsem","cxkhcgbrleqmcdgafmukhijsctpscx","cxkhcgbrleqmcdgafmukhijsctpsth","cxkhcgbrleqmcdgafmukhijsctpsjk","cxkhcgbrleqmcdgafmukhijsctpsxx","cxkhcgbrleqmcdgafmukhijsctpsdq","cxkhcgbrleqmcdgafmukhijsctpsze","cxkhcgbrleqmcdgafmukhijsctpsvt","cxkhcgbrleqmcdgafmukhijsctpsii","cxkhcgbrleqmcdgafmukhijsctpsda","cxkhcgbrleqmcdgafmukhijsctpsxd","cxkhcgbrleqmcdgafmukhijsctpszj","cxkhcgbrleqmcdgafmukhijsctpsin","cxkhcgbrleqmcdgafmukhijsctpslg","cxkhcgbrleqmcdgafmukhijsctpssn","cxkhcgbrleqmcdgafmukhijsctpszu","cxkhcgbrleqmcdgafmukhijsctpsck","cxkhcgbrleqmcdgafmukhijsctpskg","cxkhcgbrleqmcdgafmukhijsctpsod","cxkhcgbrleqmcdgafmukhijsctpsxm","cxkhcgbrleqmcdgafmukhijsctpsrh","cxkhcgbrleqmcdgafmukhijsctpsnq","cxkhcgbrleqmcdgafmukhijsctpsre","cxkhcgbrleqmcdgafmukhijsctpsph","cxkhcgbrleqmcdgafmukhijsctpskh","cxkhcgbrleqmcdgafmukhijsctpsbk","cxkhcgbrleqmcdgafmukhijsctpsqg","cxkhcgbrleqmcdgafmukhijsctpsbv","cxkhcgbrleqmcdg","cxkhcgbrleqmcdgafmukhijsctpstu","cxkhcgbrleqmcdgafmukhijsctpsoz","cxkhcgbrleqmcdgafmukhijsctpssj","cxkhcgbrleqmcdgafmukhijsctpshu","cxkhcgbrleqmcdgafmukhijsctpsyo","cxkhcgbrleqmcdgafmukhijsctpsrg","cxkhcgbrleqmcdgafmukhijsctpsta","cxkhcgbrleqmcdgafmukhijsctpswk","cxkhcgbrleqmcdgafmukhijsctpsht","cxkhcgbrleqmcdgafmukhijsctpslb","cxkhcgbrleqmcdgafmukhijsctpssv","cxkhcgbrleqmcdgafmukhijsctpsol","cxkhcgbrleqmcdgafmukhijsctpslv","cxkhcgbrleqmcdgafmukhijsctpshv","cxkhcgbrleqmcdgafmukhijsctpske","cxkhcgbrleqmcdgafmukhijsctpsdf","cxkhcgbrleqmcdgafmukhijsctpskj","cxkhcgbrleqmcdgafmukhijsctpsfx","cxkhcgbrleqmcdgafmukhijsctpskl","cxkhcgbrleqmcdgafmukhijsctpsof","cxkhcgbrleqmcdgafmukhijsctpsqj","cxkhcgbrleqmcdgafmukhijsctpsry","cxkhcgbrleqmcdgafmukhijsctpstt","cxkhcgbrleqmcdgafmukhijsctpsqm","cxkhcgbrleqmcdgafmukhijsctpssp","cxkhcgbrleqmcdgafmukhijsctpspv","cxkhcgbrleqmcdgafmukhijsctpsiz","cxkhcgbrleqmcdgafmukhijsctpsar","cxkhcgbrleqmcdgafmukhijsctpsln","cxkhcgbrleqmcdgafmukhijsctpsdo","cxkhcg","cxkhcgbrleqmcdgafmukhi","cxkhcgbrleqmcdgafmukhijsctpsdx","cxkhcgbrleqmcdgafmukhijsct","cxkhcgbrleqmcdgafmukhijsctpstc","cxkhcgbrleqmcdgafmukhijsctpsac","cxkhcgbrleqmcdgafmukhijsctpsea","cxkhcgbrleqmcdgafmukhijsctpsaa","cxkhcgbrleqmcdgafmukhijsctpsjr","cxkhcgbrleqmcdgafmukhijsctpsqq","cxkhcgbrleqmcdgafmukhijsctpsxj","cxkhcgbrleqmcdgafmukhijsctpsnm","cxkhcgbrleqmcdgafmukhijsctpsjz","cxkhcgbrleqmcdgafmukhijsctpsjx","cxkhcgbrleqmcdgafmukhijsctpsrk","cxkhcgbrleqmcdgafmukhijsctpsuu","cxkhcgbrle","cxkhcgbrleqmcdgafmukhijsctpsfv","cxkhcgbrleqmcdgafmukhijsctpshb","cxkhcgbrleqmcdgafmukhijsctpsrs","cxkhcgbrleqmcdgafmukhijsctpscl","cxkhcgbrleqmcdgafmukhijsctpsmi","cxkhcgbrleqmcdgafmukhijsctpslz","cxkhcgbrleqmcdgafmukhijsctpsfp","cxkhcgbrleqmcdgafmukhijsctpsyv","cxkhcgbrleqmcdgafmukhijsctpsad","cxkhcgbrleqmcdgafmukhijsctpspk","cxkhcgbrleqmcdgafmukhijsctpsxa","cxkhcgbrleqmcdgafmukhijsctpshs","cxkhcgbrleqmcdgafmukhijsctpszf","cxkhcgbrleqmcdgafmukhijsctpsnj","cxkhcgbrleqmcdgafmukhijsctpshn","cxkhcgbrleqmcdgafmukhijsctpsng","cxkhcgbrleqmcdgafmukhijsctpswx","cxkhcgbrleqmcdgafmukhijsctpsiv","cxkhcgbrleqmcdgafmukhijsctpsbg","cxkhcgbrleqmcdgafmukhijsctpslu","cxkhcgbrleqmcdgafmukhijsctpsnr","cxkhcgbrleqmcdgafmukhijsctpsje","cxkhcgbrleqmcdgafmukhijsctpsmz","cxkhcgbrleqmcdgafmukhijsctpsrn","cxkhcgbrleqmcdgafmukhijsctpsen","cxkhcgbrleqmcdgafmukhijsctpsvp","cxkhcgbrleqmcdgafmukhijsctpsoc","cxkhcgbrleqmcdgafmukhijsctpsbw","cxkhcgbrleqmcdgafmukhijsctpshy","cxkhcgbrleqmcdgafm","cxkhcgbrleqmcdgafmukhijsctpsqz","cxkhcgbrleqmcdgafmukhijsctpsxr","cxkhcgbrleqmcdgafmukhijsctpslt","cxkhcgbrleqmcdgafmukhijsctpsdy","cxkhcgbrleqmcdgafmukhijsctpsde","cxkhcgbrleqmcdgafmukhijsctpsig","cxkhcgbrleqmcdgafmukhijsctpsax","cxkhcgbrleqmcdgafmukhijsctpsqs","cxkhcgbrleqmcdgafmukhijsctpsoo","cxkhcgbrleqmcdgafmukhijsctpsba","cxkhcgbrleqmcdgafmukhijsctpsca","cxkhcgbrleqmcdgafmukhijsctpses","cxkhcgbrleqmcdgafmukhijsctpszo","cxkhcgbrleqmcdgafmukhijsctpsoy","cxkhcgbrleqmcdgafmukhijsctpskn","cxkhcgbrleqmcdgafmukhijsctpsfg" }; + // vector words = { "yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y" }; + // vector words = { "r","kt","jtgt","j","jtg","rdwy","chkext","c","l","zo","lnp","k","jt","chke","ktui","rd","jtgtha","ch","chkex" }; + // vector words = {"b", "br", "bre", "brea", "break", "breakf", "breakfa", "breakfas", "breakfast", "l", "lu", "lun", "lunc", "lunch", "d", "di", "din", "dinn", "dinne", "dinner"}; + auto res = sol.longestWord(words); + cout << res << endl; + + return 0; +} \ No newline at end of file diff --git a/cpp-leetcode/test.cpp b/cpp-leetcode/test.cpp new file mode 100644 index 00000000..676dd94b --- /dev/null +++ b/cpp-leetcode/test.cpp @@ -0,0 +1,16 @@ +#include +#include +#include +#include +using namespace std; + +// Test +int main() +{ + // Solution sol; + vector nums = {1, 3, 2, 2, 5, 2, 3, 7}; + // auto res = sol.findLHS(nums); + // cout << res << endl; + + return 0; +} diff --git a/csharp-leetcode/C# script/.vscode/launch.json b/csharp-leetcode/C# script/.vscode/launch.json new file mode 100644 index 00000000..b0256f91 --- /dev/null +++ b/csharp-leetcode/C# script/.vscode/launch.json @@ -0,0 +1,18 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Script Debug", + "type": "coreclr", + "request": "launch", + "program": "dotnet", + "args": [ + "exec", + "C:/Users/bryang/.dotnet/tools/.store/dotnet-script/1.1.0/dotnet-script/1.1.0/tools/net5.0/any/dotnet-script.dll", + "${file}" + ], + "cwd": "${workspaceRoot}", + "stopAtEntry": true + } + ] +} \ No newline at end of file diff --git a/csharp-leetcode/C# script/lcof67-offer-strToInt.csx b/csharp-leetcode/C# script/lcof67-offer-strToInt.csx new file mode 100644 index 00000000..014bc8de --- /dev/null +++ b/csharp-leetcode/C# script/lcof67-offer-strToInt.csx @@ -0,0 +1,27 @@ +public class Solution { + public int StrToInt(string str) { + char[] c = str.Trim().ToCharArray(); + if(c.Length == 0) return 0; + int res = 0, boundray = int.MaxValue / 10; + int i = 1, sign = 1; + if(c[0] == '-') sign = -1; + else if(c[0] != '+') i = 0; + for(int j = i; j < c.Length; j++) { + if(c[j] < '0' || c[j] > '9') break; + if(res > boundray || res == boundray && c[j] > '7') + return sign == 1 ? int.MaxValue : int.MinValue; + res = res * 10 + (c[j] - '0'); + } + return sign * res; + + } +} + +// Test +void Test () { + var sol = new Solution (); + var input = "4193 with words"; + Console.WriteLine (sol.StrToInt(input)); +} + +Test (); \ No newline at end of file diff --git a/csharp-leetcode/C# script/leetcode118-pascal-triangle.csx b/csharp-leetcode/C# script/leetcode118-pascal-triangle.csx new file mode 100644 index 00000000..6e2583ff --- /dev/null +++ b/csharp-leetcode/C# script/leetcode118-pascal-triangle.csx @@ -0,0 +1,35 @@ +#r "nuget: NUnit, 3.12.0" +#r "nuget: NUnitLite, 3.12.0" +using NUnit.Framework; +using NUnitLite; + +class Solution { + public IList> Generate (int numRows) { + var results = new List> (numRows); + if (numRows > 0) + results.Add(new [] { 1 }); + + for (int i = 1; i < numRows; i++) { + var preRow = results[i - 1]; + var row = new int[i + 1]; + + results.Add (row); + row[0] = row[i] = 1; + for (int j = 1; j < row.Length - 1; j++) { + row[j] = preRow[j - 1] + preRow[j]; + } + } + return results; + } +} + +public class MyTests { + [Test] + public void Test() + { + Solution sol = new Solution(); + sol.Generate (3); + } +} + +new AutoRun().Execute (Args.ToArray ()); \ No newline at end of file diff --git a/csharp-leetcode/C# script/leetcode137-SingleNumber2.csx b/csharp-leetcode/C# script/leetcode137-SingleNumber2.csx new file mode 100644 index 00000000..2f76cfeb --- /dev/null +++ b/csharp-leetcode/C# script/leetcode137-SingleNumber2.csx @@ -0,0 +1,26 @@ +using System; +public class Solution +{ + public int SingleNumber(int[] nums) + { + int a = 0, b = 0; + for(int i = 0;i < nums.Length;i++) + { + b = (b ^ nums[i]) & ~a; + a = (a ^ nums[i]) & ~b; + } + return b; + } +} + +void test() +{ + var sol = new Solution(); + var input = new int[] { 2,2,3,2 }; + Console.WriteLine (sol.SingleNumber(input)); + + input = new int[] { 0,1,0,1,0,1,99 }; + Console.WriteLine(sol.SingleNumber(input)); +} + +test(); \ No newline at end of file diff --git a/csharp-leetcode/C# script/leetcode215-kth-largest-element-in-an-array.csx b/csharp-leetcode/C# script/leetcode215-kth-largest-element-in-an-array.csx new file mode 100644 index 00000000..c071e181 --- /dev/null +++ b/csharp-leetcode/C# script/leetcode215-kth-largest-element-in-an-array.csx @@ -0,0 +1,24 @@ +public class Solution { + public int FindKthLargest(int[] nums, int k) { + List lst = new List(); + foreach(int n in nums) + { + lst.Add(n); + } + lst.Sort((x,y) => -x.CompareTo(y)); /* 对list从大到小排序 */ + + return lst[k-1]; + } +} + +// Test +void test() +{ + Solution sol = new Solution(); + int[] nums = {3,2,1,5,6,4}; + int k = 2; + int res = sol.FindKthLargest(nums, k); + System.Console.WriteLine(res); +} + +test(); \ No newline at end of file diff --git a/csharp-leetcode/C# script/leetcode29.divide-two-integers.csx b/csharp-leetcode/C# script/leetcode29.divide-two-integers.csx new file mode 100644 index 00000000..e7ee00b4 --- /dev/null +++ b/csharp-leetcode/C# script/leetcode29.divide-two-integers.csx @@ -0,0 +1,52 @@ +public class Solution { + public int Divide (int a, int b) { + if (b == 0) throw new DivideByZeroException(); + if (a == 0) return 0; + + var result = 0; + int sign = 1; + /* 要点 + 1、要考虑整数溢出的间题,转换成负数进行计算,因为负数的范围比正数大[int的范围(-2^31 ~ 2^31-1, -2147483648~2147483647)] + 2、用移位实现乘2以及除2的操作 + 3、除法的本质是多次减法 + C++不允许负数进行左移操作, C#可以 + */ + if (a > 0) { + sign = -sign; + a = -a; + } + if (b > 0) { + sign = -sign; + b = -b; + } + + var n = -1; + while (b >= (int.MinValue >> 1)) { + b <<= 1; // b*2^n + n <<= 1; + } + while (true) { + if (a <= b) { + result += n; + a -= b; + } + if (n == -1) break; + b >>= 1; + n >>= 1; + } + + if (sign == 1) { + return result == int.MinValue ? int.MaxValue : -result; + } + return result; + } +} + +// Test +void Test () { + var sol = new Solution (); + int dividend = 7, divisor = -3; + Console.WriteLine(sol.Divide(dividend, divisor)); +} + +Test(); \ No newline at end of file diff --git a/csharp-leetcode/C# script/leetcode65-valid-number.csx b/csharp-leetcode/C# script/leetcode65-valid-number.csx new file mode 100644 index 00000000..32064fd1 --- /dev/null +++ b/csharp-leetcode/C# script/leetcode65-valid-number.csx @@ -0,0 +1,61 @@ +public class Solution { + public bool IsNumber (string s) { + s = s.Trim (); + if (s.Contains ("Infinity") || s.Contains ("infinity")) return false; + + string[] arr = s.Split (new char[] { 'e', 'E' }); + string newPart1 = arr[0]; + if (newPart1.IndexOf (" ", StringComparison.Ordinal) >= 0) + return false; + bool isPart1Double = double.TryParse (newPart1, out var part1); + string newPart2 = arr.ElementAtOrDefault (1); + if (newPart2 == String.Empty) // handle test case like: "0e" + return false; + + if (newPart2 != String.Empty && newPart2 != null) { + char ch = newPart2[0]; + if (ch == '.' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) + return false; /* 检测类似 69e.60, 3.31ec250这样的数字。字母检查也可使用Char.IsLetter(char) */ + } + + if (newPart2 != null) { + foreach (char ch in newPart2) { + if (ch == '0') + newPart2 = newPart2.Substring (1); + } + } + + bool isPart2Int = Int64.TryParse (newPart2, out var part2); + if (arr.Length == 1) { + if (isPart1Double) + return true; + } + + if (arr.Length == 2) { + if (isPart1Double && newPart2 == String.Empty) + return true; + if (isPart1Double && isPart2Int) + return true; + } + + return false; + } +} + +void test () { + var sol = new Solution (); + + var input = "2e00"; + Console.WriteLine (sol.IsNumber (input)); + + input = "69e.60"; + Console.WriteLine (sol.IsNumber (input)); + + input = "3.31ec250"; + Console.WriteLine (sol.IsNumber (input)); + + input = "infinity"; + Console.WriteLine (sol.IsNumber (input)); +} + +test (); \ No newline at end of file diff --git a/csharp-leetcode/C# script/omnisharp.json b/csharp-leetcode/C# script/omnisharp.json new file mode 100644 index 00000000..024e9cfc --- /dev/null +++ b/csharp-leetcode/C# script/omnisharp.json @@ -0,0 +1,6 @@ +{ + "script": { + "enableScriptNuGetReferences": true, + "defaultTargetFramework": "net5.0" + } +} \ No newline at end of file diff --git a/csharp-leetcode/README.md b/csharp-leetcode/README.md new file mode 100644 index 00000000..92f7e3b3 --- /dev/null +++ b/csharp-leetcode/README.md @@ -0,0 +1,175 @@ +# Leetcode 刷题方法及AC 代码 - C#版 + +## 使用VS code刷题及如何快速配置C#运行环境 + +十分推荐使用C# script的环境来刷题,这样就不用每次都去创建项目了,只需要在一开始配置一次即可一劳永逸。 + +[scriptcs](http://scriptcs.net)开源项目的作者 Filip W 大佬的 dotnet-script 是基于微软的 roslyn 及其推出的 csx 开发的,其 debug 功能是与 微软官方的vs code 的 C# 插件 (Omnisharp) 相适配的,OmiSharp插件天然支持 intellisence,整体上很不错的。不需要创建 project 就能编译、运行、debug以及加 unit test并debug unit test. 不需写任何多余的代码。 + + +### 前期准备: +安装 .NET core SDK (版本在2.0以上)、VS code、VS code 的 C# 插件 + + +### 配置步骤: + + +### 1、全局安装 dotnet-script +打开cmd,执行如下命令: +```bash +dotnet tool install -g dotnet-script +``` + + +### 2、在 vs code 中安装 scriptcs runner 插件 + +[https://marketplace.visualstudio.com/items?itemName=filipw.scriptcsRunner](https://marketplace.visualstudio.com/items?itemName=filipw.scriptcsRunner) +安装好后,Windows上可以用 Ctrl+shift+r 快捷键运行整个 csx 文件或其中某一个选择的snippet。 + +Ctrl + F5: 运行 +F5: 调试 + +### 3、在需要存放项目文件的文件夹中打开vs code 并进行一次性地初始化项目 +打开需要存放项目文件的文件夹,右击 Open with code,在 VS code的 Terminal 中输入如下命令: +```bash +dotnet script init +``` + +或 +```bash +dotnet script init leetcode1 +``` + + +会自动生成 .vscode/launch.json 文件和 omnisharp.json 文件,后面不需要动的,当然你甚至可以在vs code中设置为不显示在文件列表中。 + + + + +### 4、为 vs code 安装 C# 代码格式化插件 + +**1**: 从repo [https://github.com/yanglr/DevToolsBackup/tree/main/vs%20code](https://github.com/yanglr/DevToolsBackup/tree/main/vs%20code) 下载 C# fixformat 的 vsix 安装包 + +**2**: 打开 vsix 所在文件夹,然后用如下命令进行安装: + +```bash +code --install-extension ./csharp-fixformat-0.0.84.vsix +``` + +**3**: 打开任一个 `.cs` 文件, 然后按 F1, 键入"Format document with...", 将 "C# FixFormat" 设置为默认格式化工具 + +**4**: 接下来你就可以用快捷键 `Ctrl + K + F` 来格式化 C# 代码了. + + + +### 5、注意事项 + +我们所操作的文件目录(比如,这里的 D:\coding\2021\csxLeetcode )支持放 .cs 和 .csx 文件。 +csx 文件中不能加 namespace、public static void Main()。 +using System; 这种语句会默认自动导入,也可省略。 + + + + +### 6、此环境下 Leetcode的玩法 + + +#### 不带 class 的 leetcode 玩法 +leetcode-demo.csx + + +```csharp +using System; +using System.Text; + +public class Solution { + public int Add (int a, int b) { + return a + b; + } +} + +public void Main () { + var sol = new Solution (); + Console.WriteLine (sol.Add (8, 5)); +} + +Main (); +``` + + + +#### 带 class 和 基于Nunit 的 Unit test 的 leetcode 玩法 + +nunit-test.csx +```csharp +#r "nuget: NUnit, 3.12.0" +#r "nuget: NUnitLite, 3.12.0" +using NUnit.Framework; +using NUnitLite; + +public class MyTests { + [Test] + public void Test() + { + Assert.IsTrue(true); + } +} +new AutoRun().Execute (Args.ToArray ()); +``` + + +此处 unit test的debug方法是: + +- 加断点 +- 按F5 + + + +这里 codelen 上的 Run Test/Debug Test 都是无效的,就别点了。 + + +如果按F5, 断点无法hit,那么可以清空当前文件夹中的 TestResult.xml,或者用一个 Assert 会失败的任意 Test 去实现debug中hit断点,再按F5 (continue) 时进入目标断点~ + + + +对于 Leetcode,如果需要加入可调试的 unit tests,可以这样玩: +nunit-test2.csx + +```csharp +#r "nuget: NUnit, 3.12.0" +#r "nuget: NUnitLite, 3.12.0" +using NUnit.Framework; +using NUnitLite; + +public class Solution { + public int Add(int a, int b) { + return a + b; + } + + [Test] + public void Test() { + Assert.AreEqual (23, this.Add(8, 15)); + } +} + +new AutoRun().Execute(Args.ToArray()); +``` + + + +### 相关repo: + +ilipw/dotnet-script: Run C# scripts from the .NET CLI - Filip W +[https://github.com/filipw/dotnet-script](https://github.com/filipw/dotnet-script) + + +Experimenting with dotnet scripts +From <[https://blog.schroederspace.com/tumbleweed-technology/experimenting-with-dotnet-scripts](https://blog.schroederspace.com/tumbleweed-technology/experimenting-with-dotnet-scripts)> + + +nunit-scripts.csx +[https://gist.github.com/jpschroeder/635ec6677d36805cee02adee702b4d47](https://gist.github.com/jpschroeder/635ec6677d36805cee02adee702b4d47) + + +[mono](https://github.com/mono)/[roslyn](https://github.com/mono/roslyn) +[https://github.com/mono/roslyn/blob/master/src/Scripting/CSharpTest/ScriptTests.cs](https://github.com/mono/roslyn/blob/master/src/Scripting/CSharpTest/ScriptTests.cs) diff --git a/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/.vscode/launch.json b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/.vscode/launch.json new file mode 100644 index 00000000..dd312003 --- /dev/null +++ b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/net5.0/leetcode137-SingleNumber2.dll", + "args": [], + "cwd": "${workspaceFolder}", + // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console + "console": "internalConsole", + "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/.vscode/tasks.json b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/.vscode/tasks.json new file mode 100644 index 00000000..7208d423 --- /dev/null +++ b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/leetcode137-SingleNumber2.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/leetcode137-SingleNumber2.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/leetcode137-SingleNumber2.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/Program.cs b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/Program.cs new file mode 100644 index 00000000..b1850f51 --- /dev/null +++ b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/Program.cs @@ -0,0 +1,27 @@ +using System; + +namespace leetcode137_SingleNumber2 +{ + public class Solution { + public int SingleNumber (int[] nums) { + int a = 0, b = 0; + for (int i = 0; i < nums.Length; i++) { + b = (b ^ nums[i]) & ~a; + a = (a ^ nums[i]) & ~b; + } + return b; + } + } + class Program + { + static void Main(string[] args) + { + var sol = new Solution (); + var input = new int[] { 2, 2, 3, 2 }; + Console.WriteLine (sol.SingleNumber (input)); + + input = new int[] { 0, 1, 0, 1, 0, 1, 99 }; + Console.WriteLine (sol.SingleNumber (input)); + } + } +} diff --git a/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/leetcode137-SingleNumber2.csproj b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/leetcode137-SingleNumber2.csproj new file mode 100644 index 00000000..add3ec2b --- /dev/null +++ b/csharp-leetcode/vs code projects/leetcode137-SingleNumber2/leetcode137-SingleNumber2.csproj @@ -0,0 +1,9 @@ + + + + Exe + net5.0 + leetcode137_SingleNumber2 + + + diff --git a/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion.sln b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion.sln new file mode 100644 index 00000000..1ff52285 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeetCode-6ZigZagConversion", "LeetCode-6ZigZagConversion\LeetCode-6ZigZagConversion.csproj", "{E5B32C35-2B79-45CD-AE59-7B44849AEEFC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E5B32C35-2B79-45CD-AE59-7B44849AEEFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E5B32C35-2B79-45CD-AE59-7B44849AEEFC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5B32C35-2B79-45CD-AE59-7B44849AEEFC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E5B32C35-2B79-45CD-AE59-7B44849AEEFC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {806FF40A-55E6-4D69-BF12-A5116D5DA16D} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/App.config b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/LeetCode-6ZigZagConversion.csproj b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/LeetCode-6ZigZagConversion.csproj new file mode 100644 index 00000000..f2a550ed --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/LeetCode-6ZigZagConversion.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {E5B32C35-2B79-45CD-AE59-7B44849AEEFC} + Exe + LeetCode_6ZigZagConversion + LeetCode-6ZigZagConversion + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/Program.cs b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/Program.cs new file mode 100644 index 00000000..9e306049 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/Program.cs @@ -0,0 +1,54 @@ +using System; + +namespace LeetCode_6ZigZagConversion +{ + public class Solution + { + public string Convert(string s, int numRows) + { + char[] res = new char[s.Length]; + // string res = new string(' ', s.Length); + if (numRows <= 1) + return s; + + int pos = 0; + for (int i = 0; i < numRows; i++) + { + int gap1 = 2 * (numRows - 1 - i); + int gap2 = 2 * i; + + int index = i; + while (pos < s.Length) + { + if (gap1 > 0) + { + if (index >= s.Length) + break; + res[pos++] = s[index]; // Add char row by row + index += gap1; + } + + if (gap2 > 0) + { + if (index >= s.Length) + break; + res[pos++] = s[index]; + index += gap2; + } + } + } + + return new string(res); + } + } + + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + string res = sol.Convert("PAYPALISHIRING", 3); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..2860e8e1 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode-6ZigZagConversion/LeetCode-6ZigZagConversion/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LeetCode-6ZigZagConversion")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LeetCode-6ZigZagConversion")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e5b32c35-2b79-45cd-ae59-7b44849aeefc")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/App.config b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Leetcode1-Two-Sum.csproj b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Leetcode1-Two-Sum.csproj new file mode 100644 index 00000000..5fd1a391 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Leetcode1-Two-Sum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B1652DE2-E8E7-4DAD-9F2C-C7097B47F2CD} + Exe + Leetcode1_TwoSum_csharp + Leetcode1-TwoSum-csharp + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Program.cs b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Program.cs new file mode 100644 index 00000000..742d8639 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Program.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; + +namespace Leetcode1_TwoSum_csharp +{ + public class Solution + { + public int[] TwoSum(int[] nums, int target) + { + int[] res = {0, 0}; + int len = nums.Length; + Dictionary dict = new Dictionary(); + for (int i = 0; i < len; i++) + { + int query = target - nums[i]; + if (dict.ContainsKey(query)) + { + int min = (i <= dict[query]) ? i : dict[query]; + int max = (i <= dict[query]) ? dict[query] : i; + return new int[] { min, max }; + } + else if (!dict.ContainsKey(nums[i])) + { + dict.Add(nums[i], i); + } + } + + return res; + } + } + + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + int[] nums = { 3, 3 ,4 }; + int target = 6; + int[] res = {0, 0}; + + res = sol.TwoSum(nums, target); + + foreach (var item in res) + { + Console.WriteLine(item.ToString()); + } + + } + } +} \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..0d4f8531 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum-csharp/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode1-TwoSum-csharp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode1-TwoSum-csharp")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b1652de2-e8e7-4dad-9f2c-c7097b47f2cd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum.sln b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum.sln new file mode 100644 index 00000000..7b169e9e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode1-TwoSum/Leetcode1-TwoSum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30907.101 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode1-Two-Sum", "Leetcode1-TwoSum-csharp\Leetcode1-Two-Sum.csproj", "{B1652DE2-E8E7-4DAD-9F2C-C7097B47F2CD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B1652DE2-E8E7-4DAD-9F2C-C7097B47F2CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1652DE2-E8E7-4DAD-9F2C-C7097B47F2CD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1652DE2-E8E7-4DAD-9F2C-C7097B47F2CD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1652DE2-E8E7-4DAD-9F2C-C7097B47F2CD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {82B11307-0AFE-4016-8B4D-7FD4B648D31A} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12.sln b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12.sln new file mode 100644 index 00000000..db9d9855 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode12", "Leetcode12\Leetcode12.csproj", "{17659FA9-ACC3-4AF5-8A87-1A1FD8D5058B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {17659FA9-ACC3-4AF5-8A87-1A1FD8D5058B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {17659FA9-ACC3-4AF5-8A87-1A1FD8D5058B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {17659FA9-ACC3-4AF5-8A87-1A1FD8D5058B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {17659FA9-ACC3-4AF5-8A87-1A1FD8D5058B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {25817126-DDA5-4E2F-AA15-A87ED5F9EF67} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/App.config b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Leetcode12.csproj b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Leetcode12.csproj new file mode 100644 index 00000000..35e180f4 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Leetcode12.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {17659FA9-ACC3-4AF5-8A87-1A1FD8D5058B} + Exe + Leetcode12 + Leetcode12 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Program.cs b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Program.cs new file mode 100644 index 00000000..2895b7ed --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; + +namespace Leetcode12 +{ + public class Solution + { + public string IntToRoman(int num) + { + string res = String.Empty; + List val = new List { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; + List str = new List { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; + for(int i = 0;i < val.Count; ++i) + { + while(num >= val[i]) + { + num -= val[i]; + res += str[i]; + } + } + return res; + } + } + + class Program + { + static void Main(string[] args) + { + string str; + while((str = Console.ReadLine()) != null) + { + Solution sol = new Solution(); + Console.WriteLine(sol.IntToRoman(int.Parse(str))); + } + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4a23075d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode12-integer-to-roman/Leetcode12/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode12")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Leetcode12")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("17659fa9-acc3-4af5-8a87-1a1fd8d5058b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13.sln b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13.sln new file mode 100644 index 00000000..069d0d3a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode13", "Leetcode13\Leetcode13.csproj", "{7CEC0912-C635-44BC-B748-541D9998A501}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7CEC0912-C635-44BC-B748-541D9998A501}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7CEC0912-C635-44BC-B748-541D9998A501}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7CEC0912-C635-44BC-B748-541D9998A501}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7CEC0912-C635-44BC-B748-541D9998A501}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {49196145-5BB3-494E-AEB3-2F995690D646} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/App.config b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Leetcode13.csproj b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Leetcode13.csproj new file mode 100644 index 00000000..0c0a1818 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Leetcode13.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {7CEC0912-C635-44BC-B748-541D9998A501} + Exe + Leetcode13 + Leetcode13 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Program.cs b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Program.cs new file mode 100644 index 00000000..d552cc20 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Program.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; + +namespace Leetcode13 +{ + public class Solution + { + static readonly Dictionary dict = new Dictionary + { + {'I', 1}, + {'V', 5}, + {'X', 10}, + {'L', 50}, + {'C', 100}, + {'D', 500}, + {'M', 1000} + }; + + public int RomanToInt(string s) + { + int sum = 0; + for(int i = 0;i < s.Length;i++) + { + int currentValue = dict[s[i]]; + if(i == s.Length - 1 || dict[s[i + 1]] <= currentValue) + sum += currentValue; + else + sum -= currentValue; + } + return sum; + } + } + + class Program + { + static void Main(string[] args) + { + string str; + while((str = Console.ReadLine()) != null) + { + Solution sol = new Solution(); + Console.WriteLine(sol.RomanToInt(str)); + } + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..c26cba60 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode13-roman-to-integer/Leetcode13/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode13")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Leetcode13")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7cec0912-c635-44bc-b748-541d9998a501")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136.sln b/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136.sln new file mode 100644 index 00000000..7a574b80 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode136", "leetcode136\leetcode136.csproj", "{D786D2BA-1A65-4CB6-821F-591C532DEC2C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D786D2BA-1A65-4CB6-821F-591C532DEC2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D786D2BA-1A65-4CB6-821F-591C532DEC2C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D786D2BA-1A65-4CB6-821F-591C532DEC2C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D786D2BA-1A65-4CB6-821F-591C532DEC2C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {88C08D01-35CE-4D2F-894D-0F2BE26AFE0E} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136/Program.cs b/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136/Program.cs new file mode 100644 index 00000000..cd7594e3 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136/Program.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.Linq; + +namespace leetcoce136a +{ + public class Solution + { + public int SingleNumber(int[] nums) + { + int res = 0; + Dictionary dict = new Dictionary(); + foreach (var num in nums) + { + if (!dict.ContainsKey(num)) + { + dict.Add(num, 1); + } + else + dict[num]++; + } + + res = dict.FirstOrDefault(kv => kv.Value == 1).Key; + + return res; + } + + public static void Main() + { + var sol = new Solution(); + int[] input = { 4, 1, 2, 1, 2 }; + + System.Console.WriteLine(sol.SingleNumber(input)); + } + } +} \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136/leetcode136.csproj b/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136/leetcode136.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode136-single-number/leetcode136/leetcode136.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2.sln b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2.sln new file mode 100644 index 00000000..6caf8976 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode_single-number2", "Leetcode_single-number2\Leetcode_single-number2.csproj", "{7C9E09C8-BA1E-4559-800D-E15BC980EE99}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7C9E09C8-BA1E-4559-800D-E15BC980EE99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7C9E09C8-BA1E-4559-800D-E15BC980EE99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7C9E09C8-BA1E-4559-800D-E15BC980EE99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7C9E09C8-BA1E-4559-800D-E15BC980EE99}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D5D293BB-0620-4721-AE09-294014B12C66} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/App.config b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Leetcode_single-number2.csproj b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Leetcode_single-number2.csproj new file mode 100644 index 00000000..64ae9477 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Leetcode_single-number2.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {7C9E09C8-BA1E-4559-800D-E15BC980EE99} + Exe + Leetcode_single_number2 + Leetcode_single-number2 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Program.cs b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Program.cs new file mode 100644 index 00000000..bc942588 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Program.cs @@ -0,0 +1,27 @@ +using System; + +namespace Leetcode_single_number2 +{ + public class Solution + { + public int SingleNumber(int[] nums) + { + int a = 0, b = 0; + for(int i = 0;i < nums.Length;i++) + { + b = (b ^ nums[i]) & ~a; + a = (a ^ nums[i]) & ~b; + } + return b; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + int[] nums = { 1, 2, 2, 2, 1, 1, 80 }; + Console.WriteLine(sol.SingleNumber(nums)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..1ce8fe98 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode137-single-number2/Leetcode_single-number2/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode_single-number2")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Leetcode_single-number2")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7c9e09c8-ba1e-4559-800d-e15bc980ee99")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151.sln b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151.sln new file mode 100644 index 00000000..fe4a1c2c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode151", "Leetcode151\Leetcode151.csproj", "{F215EC4F-0624-4E25-A227-DF0CE0E90C4C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F215EC4F-0624-4E25-A227-DF0CE0E90C4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F215EC4F-0624-4E25-A227-DF0CE0E90C4C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F215EC4F-0624-4E25-A227-DF0CE0E90C4C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F215EC4F-0624-4E25-A227-DF0CE0E90C4C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FFD108B5-716F-4490-BF7D-4D908F07C34B} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/App.config b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Leetcode151.csproj b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Leetcode151.csproj new file mode 100644 index 00000000..1b884d22 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Leetcode151.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {F215EC4F-0624-4E25-A227-DF0CE0E90C4C} + Exe + Leetcode151 + Leetcode151 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Program.cs b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Program.cs new file mode 100644 index 00000000..fdeb2d3b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Program.cs @@ -0,0 +1,34 @@ +using System; +using System.Text; + +namespace Leetcode151_ReverseWordsInString +{ + public class Program + { + public class Solution + { + public string ReverseWords(string s) + { + StringBuilder sb = new StringBuilder(); + s = s.Trim(); + s = s.Replace(" ", " "); + var words = s.Split(' '); + for (int i = words.Length; i > 0; i--) + { + foreach (var ch in words[i-1]) + { + sb.Append(ch); + } + sb.Append(" "); + } + return sb.ToString().Trim(); + } + } + public static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.ReverseWords(" a b "); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..34b41242 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode151-reverse-words-in-a-string/Leetcode151/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode151")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode151")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f215ec4f-0624-4e25-a227-df0ce0e90c4c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle.sln b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle.sln new file mode 100644 index 00000000..c3db5c02 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode168-ExcelSheetColumnTitle", "Leetcode168-ExcelSheetColumnTitle\Leetcode168-ExcelSheetColumnTitle.csproj", "{5343E7DD-6F91-4FD1-AD9C-D92F6F976935}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5343E7DD-6F91-4FD1-AD9C-D92F6F976935}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5343E7DD-6F91-4FD1-AD9C-D92F6F976935}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5343E7DD-6F91-4FD1-AD9C-D92F6F976935}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5343E7DD-6F91-4FD1-AD9C-D92F6F976935}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7E557133-2016-41A9-99F5-C3AC512169E4} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/App.config b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle.csproj b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle.csproj new file mode 100644 index 00000000..56c814cb --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {5343E7DD-6F91-4FD1-AD9C-D92F6F976935} + Exe + Leetcode168_ExcelSheetColumnTitle + Leetcode168-ExcelSheetColumnTitle + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Program.cs b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Program.cs new file mode 100644 index 00000000..a4255654 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Program.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode168_ExcelSheetColumnTitle +{ + public class Solution + { + public string ConvertToTitle(int n) + { + var list = new List(); + StringBuilder sb = new StringBuilder(); + while (n != 0) + { + if (n % 26 == 0) + { + sb.Append('Z'); + n -= 26; + } + else + { + var rem = n % 26; + sb.Append((char)(rem - 1 + 'A')); + } + n /= 26; + } + + char[] charArr = sb.ToString().ToCharArray(); + Array.Reverse(charArr); + return new string(charArr); + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.ConvertToTitle(26); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..b0090039 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode168-ExcelSheetColumnTitle/Leetcode168-ExcelSheetColumnTitle/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode168-ExcelSheetColumnTitle")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode168-ExcelSheetColumnTitle")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5343e7dd-6f91-4fd1-ad9c-d92f6f976935")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum.sln b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum.sln new file mode 100644 index 00000000..0613386d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode171-Excel-TitleToNum", "leetcode171-Excel-TitleToNum\leetcode171-Excel-TitleToNum.csproj", "{0F108F3B-E4E1-4605-ABE8-B024BF637060}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0F108F3B-E4E1-4605-ABE8-B024BF637060}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0F108F3B-E4E1-4605-ABE8-B024BF637060}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0F108F3B-E4E1-4605-ABE8-B024BF637060}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0F108F3B-E4E1-4605-ABE8-B024BF637060}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {19917AFF-6371-4678-980D-C262F91279C9} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/App.config b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/Program.cs b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/Program.cs new file mode 100644 index 00000000..ae0b2c5f --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/Program.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode171_Excel_TitleToNum +{ + class Program + { + public class Solution + { + public int TitleToNumber(string s) + { + int len = s.Length; + int sum = 0; + int weigh = 1; // 该位的权, 26^0 ~ 26^(n-1) + for (int i = len; i >= 1; i--) + { + sum += (s[i - 1] - 'A' + 1) * weigh; // 从低位开始累加 + weigh *= 26; + } + return sum; + } + } + + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.TitleToNumber("AAA"); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..50e8ab4f --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("leetcode171-Excel-TitleToNum")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("leetcode171-Excel-TitleToNum")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0f108f3b-e4e1-4605-abe8-b024bf637060")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum.csproj b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum.csproj new file mode 100644 index 00000000..3b6ec107 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum/leetcode171-Excel-TitleToNum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {0F108F3B-E4E1-4605-ABE8-B024BF637060} + Exe + leetcode171_Excel_TitleToNum + leetcode171-Excel-TitleToNum + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1.sln b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1.sln new file mode 100644 index 00000000..5be53464 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode191-NumberOf1", "Leetcode191-NumberOf1\Leetcode191-NumberOf1.csproj", "{BAEA05D1-F5F6-4FC8-858E-77474D28F8C3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BAEA05D1-F5F6-4FC8-858E-77474D28F8C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BAEA05D1-F5F6-4FC8-858E-77474D28F8C3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BAEA05D1-F5F6-4FC8-858E-77474D28F8C3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BAEA05D1-F5F6-4FC8-858E-77474D28F8C3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A7A63543-903B-4BCF-B402-A70E05BD0C8E} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/App.config b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Leetcode191-NumberOf1.csproj b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Leetcode191-NumberOf1.csproj new file mode 100644 index 00000000..7c516d6e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Leetcode191-NumberOf1.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {BAEA05D1-F5F6-4FC8-858E-77474D28F8C3} + Exe + Leetcode191_NumberOf1 + Leetcode191-NumberOf1 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Program.cs b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Program.cs new file mode 100644 index 00000000..b7174924 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode191_NumberOf1 +{ + public class Solution + { + public int HammingWeight(uint n) + { + int count = 0; + while (n > 0) + { + n = n & (n - 1); + count++; + } + + return count; + } + } + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..49f65e62 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode191-NumberOf1/Leetcode191-NumberOf1/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode191-NumberOf1")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode191-NumberOf1")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("baea05d1-f5f6-4fc8-858e-77474d28f8c3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd.sln b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd.sln new file mode 100644 index 00000000..2b77a379 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode201-RangeBitwiseAnd", "Leetcode201-RangeBitwiseAnd\Leetcode201-RangeBitwiseAnd.csproj", "{D45FDB62-3F8B-4140-8EAD-0599016053F2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D45FDB62-3F8B-4140-8EAD-0599016053F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D45FDB62-3F8B-4140-8EAD-0599016053F2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D45FDB62-3F8B-4140-8EAD-0599016053F2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D45FDB62-3F8B-4140-8EAD-0599016053F2}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {FC584E87-DE1E-45E5-B4A1-889D406AAD9B} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/App.config b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd.csproj b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd.csproj new file mode 100644 index 00000000..f3be233e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {D45FDB62-3F8B-4140-8EAD-0599016053F2} + Exe + Leetcode201_RangeBitwiseAnd + Leetcode201-RangeBitwiseAnd + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Program.cs b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Program.cs new file mode 100644 index 00000000..ccaf6860 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Program.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode201_RangeBitwiseAnd +{ + class Program + { + public class Solution + { + public int RangeBitwiseAnd(int m, int n) + { + // 题中规定数据范围: m,n中较大值<=31s + int shiftCount = 0; + int common = 0; + GetCommonDigits(m, n, ref common, ref shiftCount); + var res = common << shiftCount; // 末位补0 + + return res; + } + + public void GetCommonDigits(int a, int b, ref int common, ref int shiftCount) + { + shiftCount = 0; + while (a != b) + { + a = a >> 1; + b = b >> 1; + shiftCount++; + } + common = a; + } + } + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.RangeBitwiseAnd(20, 23); + + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..54c8476c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode201-RangeBitwiseAnd/Leetcode201-RangeBitwiseAnd/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode201-RangeBitwiseAnd")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode201-RangeBitwiseAnd")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d45fdb62-3f8b-4140-8ead-0599016053f2")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum.sln b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum.sln new file mode 100644 index 00000000..04f1247b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode202-HappyNum", "Leetcode202-HappyNum\Leetcode202-HappyNum.csproj", "{4B586D46-877A-4CA0-8675-8F5BC729F680}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4B586D46-877A-4CA0-8675-8F5BC729F680}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4B586D46-877A-4CA0-8675-8F5BC729F680}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4B586D46-877A-4CA0-8675-8F5BC729F680}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4B586D46-877A-4CA0-8675-8F5BC729F680}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {74F58F27-A5EB-4D58-9C97-DAE94CB60254} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/App.config b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Leetcode202-HappyNum.csproj b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Leetcode202-HappyNum.csproj new file mode 100644 index 00000000..d659c400 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Leetcode202-HappyNum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {4B586D46-877A-4CA0-8675-8F5BC729F680} + Exe + Leetcode202_HappyNum + Leetcode202-HappyNum + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Program.cs b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Program.cs new file mode 100644 index 00000000..529fd78d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Program.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode202_HappyNum +{ + public class Solution + { + public bool IsHappy(int n) + { + HashSet unhappy = new HashSet(); + while (n != 1 && !unhappy.Contains(n)) + { + unhappy.Add(n); + int sum = 0; + while (n != 0) + { + var r = n - (n / 10) * 10; + sum += r * r; + n /= 10; + } + n = sum; + } + return n == 1; + } + } + + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + bool isHappy = sol.IsHappy(2); + Console.WriteLine(isHappy); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..dbf867dc --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-HappyNum/Leetcode202-HappyNum/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode202-HappyNum")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode202-HappyNum")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4b586d46-877a-4ca0-8675-8f5bc729f680")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum.sln b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum.sln new file mode 100644 index 00000000..e1da100b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode202-HappyNum", "Leetcode202-HappyNum\Leetcode202-HappyNum.csproj", "{DA57263B-043A-4714-A562-97B319403E32}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DA57263B-043A-4714-A562-97B319403E32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DA57263B-043A-4714-A562-97B319403E32}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DA57263B-043A-4714-A562-97B319403E32}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DA57263B-043A-4714-A562-97B319403E32}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1E1E3D1B-F77C-473C-9FF5-D51748812011} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/App.config b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Leetcode202-HappyNum.csproj b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Leetcode202-HappyNum.csproj new file mode 100644 index 00000000..f53f2e05 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Leetcode202-HappyNum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {DA57263B-043A-4714-A562-97B319403E32} + Exe + Leetcode202_HappyNum + Leetcode202-HappyNum + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Program.cs b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Program.cs new file mode 100644 index 00000000..fc3596c6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Program.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode202_HappyNum +{ + public class Solution + { + public bool IsHappy(int n) + { + bool isHappy = default(bool); + List list = new List(); + + if (n == 4) + return false; + + + while (list.LastOrDefault() != 4) + { + var s = getSquareSum(n); + list.Add(s); + if (list.FirstOrDefault(x => x == 4) != null) + break; + } + + if (n == 1) + isHappy = true; + return isHappy; + } + + private int getSquareSum(int n) + { + if (n < 10) + return n * n; + + int sum = 0; + while (n % 10 != 0) + { + var r = n / 10; + sum += r*r; + n = n / 10; + } + + return sum; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.IsHappy(19); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..69c605d4 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode202-happy-number/Leetcode202-HappyNum/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode202-HappyNum")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode202-HappyNum")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("da57263b-043a-4714-a562-97b319403e32")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod.sln b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod.sln new file mode 100644 index 00000000..4af1ad8a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode204—count-primes_sieveMethod", "leetcode204—count-primes_sieveMethod\leetcode204—count-primes_sieveMethod.csproj", "{D10F2A83-BFF0-43DC-8D8B-CDC7A8B98686}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D10F2A83-BFF0-43DC-8D8B-CDC7A8B98686}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D10F2A83-BFF0-43DC-8D8B-CDC7A8B98686}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D10F2A83-BFF0-43DC-8D8B-CDC7A8B98686}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D10F2A83-BFF0-43DC-8D8B-CDC7A8B98686}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6E593941-6888-4B1B-91F8-E4FD31D55A88} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/App.config b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Leetcode204-GetPrime_ieveMethod.csproj b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Leetcode204-GetPrime_ieveMethod.csproj new file mode 100644 index 00000000..06973b36 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Leetcode204-GetPrime_ieveMethod.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {D10F2A83-BFF0-43DC-8D8B-CDC7A8B98686} + Exe + Leetcode204_GetPrime_ieveMethod + leetcode204—count-primes_sieveMethod + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Program.cs b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Program.cs new file mode 100644 index 00000000..44a9d99b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Program.cs @@ -0,0 +1,36 @@ +using System; + +namespace Leetcode204_GetPrime_SieveMethod +{ + public class Solution + { + public int CountPrimes(int n) + { + if (n < 2) return 0; + bool[] isDelete = new bool[n]; + int max = (int) Math.Sqrt(n); + var count = 0; + for (int i = 2; i < n; i++) + { + if (isDelete[i]) + continue; + count++; + if (i > max) + continue; + for (int j = i * i; j < n; j += i) + isDelete[j] = true; + } + return count; + } + } + + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var result = sol.CountPrimes(100156150); + Console.WriteLine(sol); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..d531683c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode204-count-primes_sieveMethod/leetcode204-count-primes_sieveMethod/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("leetcode204—count-primes_sieveMethod")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("leetcode204—count-primes_sieveMethod")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d10f2a83-bff0-43dc-8d8b-cdc7a8b98686")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205.sln b/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205.sln new file mode 100644 index 00000000..8abcc006 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode205", "leetcode205\leetcode205.csproj", "{2ED9A91F-B109-4095-AEE2-AFFC9B36E8C7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2ED9A91F-B109-4095-AEE2-AFFC9B36E8C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2ED9A91F-B109-4095-AEE2-AFFC9B36E8C7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2ED9A91F-B109-4095-AEE2-AFFC9B36E8C7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2ED9A91F-B109-4095-AEE2-AFFC9B36E8C7}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {115757D1-09B8-420C-AA64-C4B25E80A470} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205/Program.cs b/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205/Program.cs new file mode 100644 index 00000000..f070d5c7 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace leetcode205 +{ + public class Solution + { + public bool IsIsomorphic(string s, string t) + { + List indexS = new List(); + List indexT = new List(); + + for (int i = 0; i < s.Length; i++) + indexS.Add(s.IndexOf(s[i])); + + for (int j = 0; j < t.Length; j++) + indexT.Add(t.IndexOf(t[j])); + + return indexS.SequenceEqual(indexT); + } + + static void Main(string[] args) + { + var sol = new Solution(); + Console.WriteLine(sol.IsIsomorphic("paper", "title")); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205/leetcode205.csproj b/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205/leetcode205.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode205-isomorphic-strings/leetcode205/leetcode205.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax.sln b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax.sln new file mode 100644 index 00000000..7ee6725c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode215-KthMax", "Leetcode215-KthMax\Leetcode215-KthMax.csproj", "{ADC5BDC2-20FC-489A-9EEB-1DB2FA8EE8AC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {ADC5BDC2-20FC-489A-9EEB-1DB2FA8EE8AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ADC5BDC2-20FC-489A-9EEB-1DB2FA8EE8AC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ADC5BDC2-20FC-489A-9EEB-1DB2FA8EE8AC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ADC5BDC2-20FC-489A-9EEB-1DB2FA8EE8AC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {4B230649-3602-4D8A-86C6-F013BBEA6189} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/App.config b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Leetcode215-KthMax.csproj b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Leetcode215-KthMax.csproj new file mode 100644 index 00000000..db4b4259 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Leetcode215-KthMax.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {ADC5BDC2-20FC-489A-9EEB-1DB2FA8EE8AC} + Exe + Leetcode215_KthMax + Leetcode215-KthMax + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Program.cs b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Program.cs new file mode 100644 index 00000000..097ae4d3 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Program.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode215_KthMax +{ + public class Solution + { + public IList TopKFrequent(int[] nums, int k) + { + var dict = new Dictionary(); + IList result = new List(); + foreach (var num in nums) + { + if (!dict.ContainsKey(num)) + dict.Add(num, 1); + else dict[num]++; + } + var r = dict.OrderByDescending(f => f.Value).Take(k).ToList(); + + for (int i = 0; i < k; i++) + result.Add(r.ElementAtOrDefault(i).Key); + + return result; + } + } + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..03efbdb5 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode215-KthMax/Leetcode215-KthMax/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode215-KthMax")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode215-KthMax")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("adc5bdc2-20fc-489a-9eeb-1db2fa8ee8ac")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree.sln b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree.sln new file mode 100644 index 00000000..30c47326 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode226-Invert_binary_tree", "Leetcode226-Invert_binary_tree\Leetcode226-Invert_binary_tree.csproj", "{2BCC2095-D16F-4541-BB4A-2457732F5951}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2BCC2095-D16F-4541-BB4A-2457732F5951}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2BCC2095-D16F-4541-BB4A-2457732F5951}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2BCC2095-D16F-4541-BB4A-2457732F5951}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2BCC2095-D16F-4541-BB4A-2457732F5951}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {E0EE89F9-1FE6-42B9-8721-48C3A2D5529C} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/App.config b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree.csproj b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree.csproj new file mode 100644 index 00000000..7ed378ec --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {2BCC2095-D16F-4541-BB4A-2457732F5951} + Exe + Leetcode226_Invert_binary_tree + Leetcode226-Invert_binary_tree + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Program.cs b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Program.cs new file mode 100644 index 00000000..4a72b483 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Program.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode226_Invert_binary_tree +{ + class Program + { + // Definition for a binary tree node. + //public class TreeNode + //{ + // public int val; + // public TreeNode left; + // public TreeNode right; + // public TreeNode(int x) { val = x; } + //} + public class Solution + { + public TreeNode InvertTree(TreeNode root) + { + TreeNode p; + p = root.left; + root.left = root.right; + root.right = p; + + TreeNode left = InvertTree(root.left); + TreeNode right = InvertTree(root.right); + return root; + } + } + + static void Main(string[] args) + { + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..a7f7e5c7 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode226-Invert_binary_tree/Leetcode226-Invert_binary_tree/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode226-Invert_binary_tree")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode226-Invert_binary_tree")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2bcc2095-d16f-4541-bb4a-2457732f5951")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram.sln b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram.sln new file mode 100644 index 00000000..8f5fc98d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode242-ValidAnagram", "Leetcode242-ValidAnagram\Leetcode242-ValidAnagram.csproj", "{362D7281-25AC-46A1-BE69-CFBE79782491}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {362D7281-25AC-46A1-BE69-CFBE79782491}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {362D7281-25AC-46A1-BE69-CFBE79782491}.Debug|Any CPU.Build.0 = Debug|Any CPU + {362D7281-25AC-46A1-BE69-CFBE79782491}.Release|Any CPU.ActiveCfg = Release|Any CPU + {362D7281-25AC-46A1-BE69-CFBE79782491}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {988CBFAC-0370-49FC-AD8E-7B2F8CB332B9} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/App.config b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Leetcode242-ValidAnagram.csproj b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Leetcode242-ValidAnagram.csproj new file mode 100644 index 00000000..685c86e9 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Leetcode242-ValidAnagram.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {362D7281-25AC-46A1-BE69-CFBE79782491} + Exe + Leetcode242_ValidAnagram + Leetcode242-ValidAnagram + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Program.cs b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Program.cs new file mode 100644 index 00000000..8e449886 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Program.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; + +namespace Leetcode242_ValidAnagram +{ + public class Solution + { + public bool IsAnagram(string s, string t) + { + if (s.Length != t.Length) + return false; + + int[] counts = new int[26]; + for(int i = 0;i < s.Length;i++) + { + counts[s[i] - 'a']++; + counts[t[i]-'a']--; + } + + foreach (var count in counts) + if (count != 0) + return false; + + return true; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + string str; + while ((str = Console.ReadLine())!=null) + { + string[] strArr = str.Split(' '); + if (strArr.Length < 2) + return; + + string s = strArr[0], t = strArr[1]; + bool result = sol.IsAnagram(s, t); + Console.WriteLine(result); + } + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..bd39e436 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode242-valid-anagram/Leetcode242-ValidAnagram/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode242-ValidAnagram")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Leetcode242-ValidAnagram")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("362d7281-25ac-46a1-be69-cfbe79782491")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278.sln b/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278.sln new file mode 100644 index 00000000..bcb17b1e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "leetcode278", "leetcode278.\leetcode278.csproj", "{64C3E315-D608-4E3A-94D3-FFDA140CC361}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {64C3E315-D608-4E3A-94D3-FFDA140CC361}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64C3E315-D608-4E3A-94D3-FFDA140CC361}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64C3E315-D608-4E3A-94D3-FFDA140CC361}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64C3E315-D608-4E3A-94D3-FFDA140CC361}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2085FFE7-BAC9-44B2-8B26-4B717BF225A8} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278/Program.cs b/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278/Program.cs new file mode 100644 index 00000000..b3611d7e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278/Program.cs @@ -0,0 +1,36 @@ +using System; + +namespace leetcode278 +{ + public class Solution + { + /* The isBadVersion API is defined in the parent class VersionControl. + bool IsBadVersion(int version); */ + + public class Solution : VersionControl + { + public int FirstBadVersion(int n) + { + int left = 0; + int right = n; + while (left < right) + { + int mid = left + (right - left) / 2; + if (isBadVersion(mid)) + { + right = mid; + } + else + left = mid + 1; + } + + return left; + } + } + + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278/leetcode278.csproj b/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278/leetcode278.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode278-first-bad-version/leetcode278/leetcode278.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares.sln b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares.sln new file mode 100644 index 00000000..cdef7ff7 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode279-PerfectSquares", "Leetcode279-PerfectSquares\Leetcode279-PerfectSquares.csproj", "{23526D46-411E-4BE3-B286-115CE00ACE12}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {23526D46-411E-4BE3-B286-115CE00ACE12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {23526D46-411E-4BE3-B286-115CE00ACE12}.Debug|Any CPU.Build.0 = Debug|Any CPU + {23526D46-411E-4BE3-B286-115CE00ACE12}.Release|Any CPU.ActiveCfg = Release|Any CPU + {23526D46-411E-4BE3-B286-115CE00ACE12}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {29D33F6D-A605-48E9-8FBD-16C8343D55E8} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/App.config b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Leetcode279-PerfectSquares.csproj b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Leetcode279-PerfectSquares.csproj new file mode 100644 index 00000000..ed095e99 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Leetcode279-PerfectSquares.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {23526D46-411E-4BE3-B286-115CE00ACE12} + Exe + Leetcode279_PerfectSquares + Leetcode279-PerfectSquares + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Program.cs b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Program.cs new file mode 100644 index 00000000..0b5559f7 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Program.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode279_PerfectSquares +{ + class Program + { + public class Solution + { + public int NumSquares(int n) // 已知 n>0 + { + while (n % 4 == 0) + n /= 4; + + if (n % 8 == 7) + return 4; + + for (int i = 0; i * i <= n; i++) + { + int r = (int)Math.Sqrt(n - i * i); + if (i * i + r * r == n) + { + if (i == 0 || r == 0) + return 1; + + return 2; + } + } + + return 3; + } + } + static void Main(string[] args) + { + Solution sol = new Solution(); + string str = String.Empty; + while ((str = Console.ReadLine()) != null) + { + int n = int.Parse(str); + int result = sol.NumSquares(n); + Console.WriteLine(result); + } + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..18c06244 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode279-Perfect-Squares/Leetcode279-PerfectSquares/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode279-PerfectSquares")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode279-PerfectSquares")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("23526d46-411e-4be3-b286-115ce00ace12")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290.sln b/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290.sln new file mode 100644 index 00000000..dd5e8b2a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode290", "leetcode290\leetcode290.csproj", "{F845E0DA-2F32-4C95-BC97-9C6B48A56628}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F845E0DA-2F32-4C95-BC97-9C6B48A56628}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F845E0DA-2F32-4C95-BC97-9C6B48A56628}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F845E0DA-2F32-4C95-BC97-9C6B48A56628}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F845E0DA-2F32-4C95-BC97-9C6B48A56628}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5D45A9ED-DD1A-4FC7-AD43-7EDCF9D22558} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290/Program.cs b/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290/Program.cs new file mode 100644 index 00000000..cbda433e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290/Program.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace leetcode290 +{ + public class Solution + { + public bool WordPattern(string pattern, string str) + { + List indexP = new List(); + List indexS = new List(); + + for (int i = 0; i < pattern.Length; i++) + indexP.Add(pattern.IndexOf(pattern[i])); + + var arr = str.Split(' '); // 出现在第几个word的位置?即在split数组中的位置 + + for (int i = 0; i < arr.Length; i++) + indexS.Add(arr.ToList().FindIndex(s => s == arr[i])); + + return indexS.SequenceEqual(indexP); + } + + static void Main(string[] args) + { + var sol = new Solution(); + Console.WriteLine(sol.WordPattern("abba", "dog cat cat dog")); + } + } +} \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290/leetcode290.csproj b/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290/leetcode290.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode290-word-pattern/leetcode290/leetcode290.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum.sln b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum.sln new file mode 100644 index 00000000..9ea029dc --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode306-AdditiveNum", "Leetcode306-AdditiveNum\Leetcode306-AdditiveNum.csproj", "{8919EF70-5EC1-45E1-8DFB-F54920A8420C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8919EF70-5EC1-45E1-8DFB-F54920A8420C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8919EF70-5EC1-45E1-8DFB-F54920A8420C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8919EF70-5EC1-45E1-8DFB-F54920A8420C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8919EF70-5EC1-45E1-8DFB-F54920A8420C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6B02DA48-6034-4CFE-A4A5-7C0505A67BC6} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/App.config b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Leetcode306-AdditiveNum.csproj b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Leetcode306-AdditiveNum.csproj new file mode 100644 index 00000000..6398c25a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Leetcode306-AdditiveNum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {8919EF70-5EC1-45E1-8DFB-F54920A8420C} + Exe + Leetcode306_AdditiveNum + Leetcode306-AdditiveNum + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Program.cs b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Program.cs new file mode 100644 index 00000000..b38b2a01 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Program.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode306_AdditiveNum +{ + public class Solution + { + public bool IsAdditiveNumber(string num) + { + if (String.IsNullOrEmpty(num)) + return false; + + int len = num.Length; + for (int i = 1; i < len; i++) + { + for (int j = i + 1; j < len; j++) + { + string s1 = num.Substring(0, i); // Substring(startIndex, length) + string s2 = num.Substring(i, j - i); + var d1 = long.Parse(s1); + var d2 = long.Parse(s2); + var next = d1 + d2; + + if ((s1.Length > 1 && s1[0] == '0') || (s2.Length > 1 && s2[0] == '0')) + continue; + + var now = s1 + s2 + next.ToString(); + //if (num.IndexOf(now) >= 0) + //{ + while (now.Length < num.Length) // Move forward + { + d1 = d2; + d2 = next; + next = d1 + d2; + now += next.ToString(); + } + //} + if (now == num) + return true; + } + } + return false; + } + } + class Program + { + static void Main(string[] args) + { + var sol = new Solution(); + var res = sol.IsAdditiveNumber("199100199"); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..13a6aea2 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode306-Additive-Num/Leetcode306-AdditiveNum/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode306-AdditiveNum")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode306-AdditiveNum")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8919ef70-5ec1-45e1-8dfb-f54920a8420c")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345.sln b/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345.sln new file mode 100644 index 00000000..d647ad53 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2048 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode345", "leetcode345\leetcode345.csproj", "{23D1C37E-5620-4D50-99D7-6ABC5BF3CD7D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {23D1C37E-5620-4D50-99D7-6ABC5BF3CD7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {23D1C37E-5620-4D50-99D7-6ABC5BF3CD7D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {23D1C37E-5620-4D50-99D7-6ABC5BF3CD7D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {23D1C37E-5620-4D50-99D7-6ABC5BF3CD7D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BEE8C660-2980-408B-B275-4C7CAD463AF5} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345/Program.cs b/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345/Program.cs new file mode 100644 index 00000000..2a9c3ded --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345/Program.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace leetcode345 +{ + public class Solution + { + public string ReverseVowels(string s) + { + var vowels = new List { 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' }; + int vCount = 0; + + List vList = new List(); + for (int i = 0; i < s.Length; i++) + { + var ch = s[i]; + if (vowels.Contains(ch)) + { + vList.Add(ch); + vCount++; + } + } + + vList.Reverse(); + + StringBuilder buffer = new StringBuilder(); + int vOutCount = 0; + for (int i = 0; i < s.Length; i++) + { + var ch = s[i]; + if (!vowels.Contains(ch)) + buffer.Append(ch); + if (vowels.Contains(ch)) + { + buffer.Append(vList[vOutCount]); + vOutCount++; + } + } + + return buffer.ToString(); + } + + static void Main(string[] args) + { + var sol = new Solution(); + Console.WriteLine(sol.ReverseVowels("aA")); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345/leetcode345.csproj b/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345/leetcode345.csproj new file mode 100644 index 00000000..23df6047 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode345-reverse-vowels-of-a-string/leetcode345/leetcode345.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp2.1 + + + diff --git a/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349.sln b/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349.sln new file mode 100644 index 00000000..cb890560 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode349", "leetcode349\leetcode349.csproj", "{AB28BF48-7631-4CBF-81E2-5C1019482B9E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AB28BF48-7631-4CBF-81E2-5C1019482B9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB28BF48-7631-4CBF-81E2-5C1019482B9E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB28BF48-7631-4CBF-81E2-5C1019482B9E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB28BF48-7631-4CBF-81E2-5C1019482B9E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {ADC8AB44-7DE4-4A07-947E-DCE875D72D9C} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349/Program.cs b/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349/Program.cs new file mode 100644 index 00000000..a5b2111d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Linq; + +namespace leetcode349 +{ + class Program + { + public int[] Intersection(int[] nums1, int[] nums2) + { + var res = nums1.Intersect(nums2); + return res.ToArray(); + } + + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349/leetcode349.csproj b/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349/leetcode349.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode349-intersection-of-two-arrays/leetcode349/leetcode349.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/leetcode372-SuperPow.sln b/csharp-leetcode/vs projects/leetcode372-SuperPow/leetcode372-SuperPow.sln new file mode 100644 index 00000000..82ee7996 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/leetcode372-SuperPow.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "solution1", "solution1\solution1.csproj", "{DBFBA8C6-2994-4FC1-9BAF-02638EDDC572}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "solution2", "solution2\solution2.csproj", "{CE85B693-68D7-4EED-BEFD-0EFCE950358B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "solution3", "solution3\solution3.csproj", "{7C20B6C9-8B00-44E9-88FC-EDD1E0A9B539}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DBFBA8C6-2994-4FC1-9BAF-02638EDDC572}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DBFBA8C6-2994-4FC1-9BAF-02638EDDC572}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DBFBA8C6-2994-4FC1-9BAF-02638EDDC572}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DBFBA8C6-2994-4FC1-9BAF-02638EDDC572}.Release|Any CPU.Build.0 = Release|Any CPU + {CE85B693-68D7-4EED-BEFD-0EFCE950358B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE85B693-68D7-4EED-BEFD-0EFCE950358B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE85B693-68D7-4EED-BEFD-0EFCE950358B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE85B693-68D7-4EED-BEFD-0EFCE950358B}.Release|Any CPU.Build.0 = Release|Any CPU + {7C20B6C9-8B00-44E9-88FC-EDD1E0A9B539}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7C20B6C9-8B00-44E9-88FC-EDD1E0A9B539}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7C20B6C9-8B00-44E9-88FC-EDD1E0A9B539}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7C20B6C9-8B00-44E9-88FC-EDD1E0A9B539}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C52A0008-B544-4105-8E52-241584D52038} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/solution1/Program.cs b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution1/Program.cs new file mode 100644 index 00000000..cae74d51 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution1/Program.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode372_SuperPow +{ + public class Solution + { + public int SuperPow(int a, int[] b) + { + int res = 0; + StringBuilder sb = new StringBuilder(); + foreach (var item in b) + sb.Append(item); + int.TryParse(sb.ToString(), out int p); + var val = (int)Math.Pow(a, p); + res = val - (val / 1337) * 1337; // val%1337 == val - (val / 1337) * 1337 + + return res; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.SuperPow(2147483647, new int[] { 2, 0, 0 }); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/solution1/solution1.csproj b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution1/solution1.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution1/solution1.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/solution2/Program.cs b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution2/Program.cs new file mode 100644 index 00000000..2c62498f --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution2/Program.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode372_SuperPow +{ + public class Solution + { + const int Mod0 = 1337; + public int SuperPow(int a, int[] b) + { + if (b.Length == 0) + return 1; + + var res = 1; + for (int i = b.Length - 1; i >= 0; i--) + { + res = powMod(a, b[i]) * res % Mod0; + a = powMod(a, 10); + } + + return res; + } + + private int powMod(int a, int m) + { + a %= Mod0; + int result = 1; + for (int i = 0; i < m; i++) + result = result * a % Mod0; + + return result; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.SuperPow(2147483647, new int[] { 2, 0, 0 }); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/solution2/solution2.csproj b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution2/solution2.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution2/solution2.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/solution3/Program.cs b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution3/Program.cs new file mode 100644 index 00000000..fed4bdf6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution3/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode372_SuperPow +{ + public class Solution + { + const int Mod0 = 1337; + public int SuperPow(int a, int[] b) + { + if (b.Length == 0) + return 1; + + var res = 1; + for (int i = b.Length - 1; i >= 0; i--) + { + var powModResult = powMod(a, b[i]) * res; + res = powModResult - (powModResult / Mod0) * Mod0; + a = powMod(a, 10); + } + + return res; + } + + private int powMod(int a, int m) + { + a = a - (a / Mod0) * Mod0; + int result = 1; + for (int i = 0; i < m; i++) + result = result * a - (result * a / Mod0) * Mod0; + + return result; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.SuperPow(2147483647, new int[] { 2, 0, 0 }); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode372-SuperPow/solution3/solution3.csproj b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution3/solution3.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode372-SuperPow/solution3/solution3.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38.sln b/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38.sln new file mode 100644 index 00000000..3cd53acc --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode38", "leetcode38\leetcode38.csproj", "{CB835C01-64B1-4486-B73A-92A9949AB499}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CB835C01-64B1-4486-B73A-92A9949AB499}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CB835C01-64B1-4486-B73A-92A9949AB499}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CB835C01-64B1-4486-B73A-92A9949AB499}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CB835C01-64B1-4486-B73A-92A9949AB499}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5224DC35-51D0-454A-8667-63F94E053CF4} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38/Program.cs b/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38/Program.cs new file mode 100644 index 00000000..3da2c283 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Text; + +namespace leetcode38 +{ + public class Solution + { + public string CountAndSay(int n) + { + if (n == 1) + return "1"; + + string res = "1"; + for (int i = 0; i < n - 1; i++) + { + StringBuilder buffer = new StringBuilder(); + char currentChar = default(char); + int currentCharCount = 0; + + currentChar = res[0]; + + foreach (var ch in res) + { + if (ch == currentChar) + currentCharCount++; + else + { + buffer.Append(currentCharCount.ToString()).Append(currentChar); + currentChar = ch; + currentCharCount = 1; + } + } + + buffer.Append(currentCharCount.ToString()).Append(currentChar); + res = buffer.ToString(); + } + + return res; + } + + public static void Main() + { + var sol = new Solution(); + Console.WriteLine(sol.CountAndSay(8)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38/leetcode38.csproj b/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38/leetcode38.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode38-count-and-say/leetcode38/leetcode38.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number.sln b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number.sln new file mode 100644 index 00000000..ef311f6a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode413-The3rdMax", "Leetcode413-The3rdMax\Leetcode413-The3rdMax.csproj", "{5C4E128E-F789-42EB-BF1A-11BCB5445B53}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5C4E128E-F789-42EB-BF1A-11BCB5445B53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5C4E128E-F789-42EB-BF1A-11BCB5445B53}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5C4E128E-F789-42EB-BF1A-11BCB5445B53}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5C4E128E-F789-42EB-BF1A-11BCB5445B53}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8283E007-B3A3-4355-BDD7-CB09EEF071AD} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/App.config b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/Program.cs b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/Program.cs new file mode 100644 index 00000000..c191e8c3 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/Program.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode413_The3rdMax +{ + public class Solution + { + public int ThirdMax(int[] nums) + { + int res = 0; + Dictionary dict = new Dictionary(); + foreach (var num in nums) + { + if (!dict.ContainsKey(num)) + dict.Add(num, 1); + else dict[num]++; + } + var list = dict.ToList(); + list.Sort((x, y) => -x.Key.CompareTo(y.Key)); + dict.OrderByDescending(kv => kv.Key); + + if (list.Count > 2) + res = list.ElementAtOrDefault(2).Key; + else + { + res = list.First().Key; + } + + return res; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + int res = sol.ThirdMax(new int[] { 1,2 }); + + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..1b27bc8b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode413-The3rdMax")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode413-The3rdMax")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5c4e128e-f789-42eb-bf1a-11bcb5445b53")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/leetcode414-third-maximum-number.csproj b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/leetcode414-third-maximum-number.csproj new file mode 100644 index 00000000..56b9c5c4 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode414-third-maximum-number/leetcode414-third-maximum-number/leetcode414-third-maximum-number.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {5C4E128E-F789-42EB-BF1A-11BCB5445B53} + Exe + Leetcode413_The3rdMax + Leetcode413-The3rdMax + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485.sln b/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485.sln new file mode 100644 index 00000000..fe8d11df --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode485", "leetcode485\leetcode485.csproj", "{146EEFB2-758D-459A-8251-3612AB390079}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {146EEFB2-758D-459A-8251-3612AB390079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {146EEFB2-758D-459A-8251-3612AB390079}.Debug|Any CPU.Build.0 = Debug|Any CPU + {146EEFB2-758D-459A-8251-3612AB390079}.Release|Any CPU.ActiveCfg = Release|Any CPU + {146EEFB2-758D-459A-8251-3612AB390079}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C8C017F7-5072-489F-A860-CDA1369E40BE} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485/Program.cs b/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485/Program.cs new file mode 100644 index 00000000..b5ccd6e9 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485/Program.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; + +namespace leetcode485 +{ + public class Solution + { + public int FindMaxConsecutiveOnes(int[] nums) + { + int maxCount = 0; + + for (int i = 0; i < nums.Length; i++) + { + + } + + return 0; + } + + public static void Main(string[] args) + { + var sol = new Solution(); + var input = new int[] { 1, 1, 0, 1, 1, 1 }; + Console.WriteLine(sol.FindMaxConsecutiveOnes(input)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485/leetcode485.csproj b/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485/leetcode485.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode485-max-consecutive-ones/leetcode485/leetcode485.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams.sln b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams.sln new file mode 100644 index 00000000..75bd058d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode49-GroupAnagrams", "Leetcode49-GroupAnagrams\Leetcode49-GroupAnagrams.csproj", "{55B08DB7-BC60-4CD2-B8FE-30C13729EB7E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {55B08DB7-BC60-4CD2-B8FE-30C13729EB7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55B08DB7-BC60-4CD2-B8FE-30C13729EB7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55B08DB7-BC60-4CD2-B8FE-30C13729EB7E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55B08DB7-BC60-4CD2-B8FE-30C13729EB7E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {75DFEFA7-8010-410C-B5EE-8C829967BCF0} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/App.config b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Leetcode49-GroupAnagrams.csproj b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Leetcode49-GroupAnagrams.csproj new file mode 100644 index 00000000..46d962c0 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Leetcode49-GroupAnagrams.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {55B08DB7-BC60-4CD2-B8FE-30C13729EB7E} + Exe + Leetcode49_GroupAnagrams + Leetcode49-GroupAnagrams + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Program.cs b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Program.cs new file mode 100644 index 00000000..b9bb97eb --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Program.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; + +namespace Leetcode49_GroupAnagrams +{ + public class Solution + { + public IList> GroupAnagrams(string[] strs) + { + IList> res = new List>(); + if (strs == null || strs.Length == 0) + return res; + + Dictionary dict = new Dictionary(); + foreach (var str in strs) + { + char[] ch = str.ToCharArray(); + Array.Sort(ch); + string s = new string(ch); + if (dict.ContainsKey(s)) + { + IList list = res[dict[s]]; + list.Add(str); + } + else + { + IList list = new List(); + list.Add(str); + dict.Add(s, res.Count); + res.Add(list); + } + } + + return res; + } + } + + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + string[] strs = { "eat", "tea", "tan", "ate", "nat", "bat" }; + + var result = sol.GroupAnagrams(strs); + Console.WriteLine(result); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..35d15e44 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode49-group-anagrams/Leetcode49-GroupAnagrams/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode49-GroupAnagrams")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Leetcode49-GroupAnagrams")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("55b08db7-bc60-4cd2-b8fe-30c13729eb7e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507.sln b/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507.sln new file mode 100644 index 00000000..516745b5 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2048 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode507", "leetcode507\leetcode507.csproj", "{BAE7E555-9E51-4425-B1BD-EC33E4A86565}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BAE7E555-9E51-4425-B1BD-EC33E4A86565}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BAE7E555-9E51-4425-B1BD-EC33E4A86565}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BAE7E555-9E51-4425-B1BD-EC33E4A86565}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BAE7E555-9E51-4425-B1BD-EC33E4A86565}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {36025D52-2521-4711-96DC-7767AFCA8CB9} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507/Program.cs b/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507/Program.cs new file mode 100644 index 00000000..88db380d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507/Program.cs @@ -0,0 +1,18 @@ +using System; + +namespace leetcode507 +{ + public class Solution + { + public bool CheckPerfectNumber(int num) + { + return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; + } + + public static void Main(string[] args) + { + var sol = new Solution(); + Console.WriteLine(sol.CheckPerfectNumber(60)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507/leetcode507.csproj b/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507/leetcode507.csproj new file mode 100644 index 00000000..23df6047 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num-2/leetcode507/leetcode507.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp2.1 + + + diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum.sln b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum.sln new file mode 100644 index 00000000..7f218fe2 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode507-PerfectNum", "Leetcode507-PerfectNum\Leetcode507-PerfectNum.csproj", "{EBF8A23D-ADC6-43BB-85B1-4047ED296418}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EBF8A23D-ADC6-43BB-85B1-4047ED296418}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EBF8A23D-ADC6-43BB-85B1-4047ED296418}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EBF8A23D-ADC6-43BB-85B1-4047ED296418}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EBF8A23D-ADC6-43BB-85B1-4047ED296418}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BE611880-B65B-4246-B578-40527B058FD1} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/App.config b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Leetcode507-PerfectNum.csproj b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Leetcode507-PerfectNum.csproj new file mode 100644 index 00000000..d54f5afa --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Leetcode507-PerfectNum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {EBF8A23D-ADC6-43BB-85B1-4047ED296418} + Exe + Leetcode507_PerfectNum + Leetcode507-PerfectNum + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Program.cs b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Program.cs new file mode 100644 index 00000000..f27ac3cf --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Program.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode507_PerfectNum +{ + public class Solution + { + public bool CheckPerfectNumber(int num) + { + if (num == 1) + return false; + + int[] divisors = {}; + for (int i = 2; i*i<=num; i++) // Store the smaller one in divisor pair, then another is num/smaller + { + if (num - (num/i) * i == 0) + divisors = divisors.Concat(new int[] + { + i + }).ToArray(); + } + + int sum = 1; // 1 is divisor of any integer + foreach (var divisor in divisors) + sum += divisor + num/divisor; + return num == sum; + } + } + class Program + { + static void Main(string[] args) + { + var sol = new Solution(); + Console.WriteLine(sol.CheckPerfectNumber(28)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..b48195c7 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode507-Perfect-Num/Leetcode507-PerfectNum/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode507-PerfectNum")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode507-PerfectNum")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ebf8a23d-adc6-43bb-85b1-4047ed296418")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3.sln b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3.sln new file mode 100644 index 00000000..f471b643 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode557.ReverseWordsInAString3", "Leetcode557.ReverseWordsInAString3\Leetcode557.ReverseWordsInAString3.csproj", "{2621E37F-8B7A-4C51-A3C5-C2DAE9BD4901}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2621E37F-8B7A-4C51-A3C5-C2DAE9BD4901}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2621E37F-8B7A-4C51-A3C5-C2DAE9BD4901}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2621E37F-8B7A-4C51-A3C5-C2DAE9BD4901}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2621E37F-8B7A-4C51-A3C5-C2DAE9BD4901}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {33C55C53-AD3A-4EAC-BD27-133899D0F632} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/App.config b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Leetcode557.ReverseWordsInAString3.csproj b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Leetcode557.ReverseWordsInAString3.csproj new file mode 100644 index 00000000..9fad4f89 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Leetcode557.ReverseWordsInAString3.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {2621E37F-8B7A-4C51-A3C5-C2DAE9BD4901} + Exe + Leetcode557.ReverseWordsInAString3 + Leetcode557.ReverseWordsInAString3 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Program.cs b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Program.cs new file mode 100644 index 00000000..e26b9a18 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Program.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode557.ReverseWordsInAString3 +{ + public class Solution + { + public string ReverseWords(string s) + { + StringBuilder sb = new StringBuilder(); + s = s.Trim(); + var words = s.Split(' '); + + foreach (var word in words) + { + for (int i = word.Length - 1; i >= 0; i--) + { + sb.Append(word[i]); + } + sb.Append(" "); + } + return sb.ToString().Trim(); + } + } + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..9feda23f --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode557-reverse-words-in-a-string-iii/Leetcode557.ReverseWordsInAString3/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode557.ReverseWordsInAString3")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode557.ReverseWordsInAString3")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2621e37f-8b7a-4c51-a3c5-c2dae9bd4901")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2.sln b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2.sln new file mode 100644 index 00000000..1c31edd5 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode593-valid-square-solution2", "leetcode593-valid-square-solution2\leetcode593-valid-square-solution2.csproj", "{89C53AC4-5C37-483B-822A-CA0FF0E7062D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {89C53AC4-5C37-483B-822A-CA0FF0E7062D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89C53AC4-5C37-483B-822A-CA0FF0E7062D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {89C53AC4-5C37-483B-822A-CA0FF0E7062D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {89C53AC4-5C37-483B-822A-CA0FF0E7062D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2E04C6C8-2117-47E8-9C28-916069B91414} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/App.config b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/Program.cs b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/Program.cs new file mode 100644 index 00000000..7ab1ee60 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/Program.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Leetcode593_ValidSquare +{ + public class Solution + { + public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) + { + if (GetLenSquare(p1, p2) == 0 || GetLenSquare(p2, p3) == 0 || GetLenSquare(p3, p4) == 0 || GetLenSquare(p1, p4) == 0) + return false; + + return GetLenSquare(p1, p2) == GetLenSquare(p3, p4) && GetLenSquare(p1, p3) == GetLenSquare(p2, p4) && GetLenSquare(p1, p4) == GetLenSquare(p2, p3) && + (GetLenSquare(p1, p2) == GetLenSquare(p1, p3) || GetLenSquare(p1, p2) == GetLenSquare(p1, p4) || GetLenSquare(p1, p3) == GetLenSquare(p1, p4)); + } + + private int GetLenSquare(int[] point1, int[] point2) => (point2[0] - point1[0]) * (point2[0] - point1[0]) + + (point2[1] - point1[1]) * (point2[1] - point1[1]); + } + + class Program + { + static void Main(string[] args) + { + // 以下为test + Solution sol = new Solution(); + //int[] p1 = { 0, 0 }; + //int[] p2 = { 0, 0 }; + //int[] p3 = { 0, 0 }; + //int[] p4 = { 0, 0 }; + + //int[] p1 = { 1, 1 }; + //int[] p2 = { 0, 1 }; + //int[] p3 = { 1, 2 }; + //int[] p4 = { 0, 0 }; + int[] p1 = { 0, 0 }; + int[] p2 = { 1, 1 }; + int[] p3 = { 1, 0 }; + int[] p4 = { 0, 1 }; + bool result = sol.ValidSquare(p1, p2, p3, p4); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..d0e196bf --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode539-ValidSquare")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode539-ValidSquare")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("89c53ac4-5c37-483b-822a-ca0ff0e7062d")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2.csproj b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2.csproj new file mode 100644 index 00000000..32d5781e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2/leetcode593-valid-square-solution2.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {89C53AC4-5C37-483B-822A-CA0FF0E7062D} + Exe + leetcode593-valid-square-solution2 + leetcode593-valid-square-solution2 + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square.sln b/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square.sln new file mode 100644 index 00000000..8b0bd7be --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2048 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode593-valid-square", "leetcode593-valid-square\leetcode593-valid-square.csproj", "{05A2E07D-41CE-43BD-A24F-8D339BB5EC0F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {05A2E07D-41CE-43BD-A24F-8D339BB5EC0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {05A2E07D-41CE-43BD-A24F-8D339BB5EC0F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {05A2E07D-41CE-43BD-A24F-8D339BB5EC0F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {05A2E07D-41CE-43BD-A24F-8D339BB5EC0F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C9575909-934B-4B7E-A708-B53C1E3D7D35} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square/Program.cs b/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square/Program.cs new file mode 100644 index 00000000..a7cd0e24 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square/Program.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace leetcode593-valid-square +{ + public class Solution + { + public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) + { + HashSet set = new HashSet + { + GetLenSquare(p1, p2), + GetLenSquare(p1, p3), + GetLenSquare(p1, p4), + GetLenSquare(p2, p3), + GetLenSquare(p2, p4), + GetLenSquare(p3, p4) + }; + + if (!set.Any(x => x == 0) && set.Count == 2) + { + return true; + } + + return false; + } + + private int GetLenSquare(int[] point1, int[] point2) => (point2[0] - point1[0]) * (point2[0] - point1[0]) + + (point2[1] - point1[1]) * (point2[1] - point1[1]); + + public static void Main(string[] args) + { + var sol = new Solution(); + var p1 = new []{0, 0}; + var p2 = new []{1, 1}; + var p3 = new []{1, 0}; + var p4 = new []{0, 1}; + Console.WriteLine(sol.ValidSquare(p1, p2, p3, p4)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square/leetcode593-valid-square.csproj b/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square/leetcode593-valid-square.csproj new file mode 100644 index 00000000..23df6047 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode593-valid-square/leetcode593-valid-square/leetcode593-valid-square.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp2.1 + + + diff --git a/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag.sln b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag.sln new file mode 100644 index 00000000..5147744c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode6-Zigzag", "Leetcode6-Zigzag\Leetcode6-Zigzag.csproj", "{BCCDB6F0-69E9-411F-9B9A-D078C84E0DEA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BCCDB6F0-69E9-411F-9B9A-D078C84E0DEA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BCCDB6F0-69E9-411F-9B9A-D078C84E0DEA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BCCDB6F0-69E9-411F-9B9A-D078C84E0DEA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BCCDB6F0-69E9-411F-9B9A-D078C84E0DEA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2A23BC6C-EAC5-4454-B4E6-5B08424F7626} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/App.config b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Leetcode6-Zigzag.csproj b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Leetcode6-Zigzag.csproj new file mode 100644 index 00000000..1a30ae19 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Leetcode6-Zigzag.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {BCCDB6F0-69E9-411F-9B9A-D078C84E0DEA} + Exe + Leetcode6_Zigzag + Leetcode6-Zigzag + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Program.cs b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Program.cs new file mode 100644 index 00000000..e0c29e90 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Program.cs @@ -0,0 +1,54 @@ +using System; +using System.Text; + +namespace Leetcode6_Zigzag +{ + public class Solution + { + public string Convert(string s, int numRows) + { + StringBuilder sb = new StringBuilder(); + // base case + if (numRows == 1) + return s; + + // handle first row + for (int i = 0; i < s.Length; i += (numRows - 1) * 2) + sb.Append(s[i]); + + // handle middle rows + for (int j = 1; j < numRows - 1; j++) + { + bool down = true; + for (int i = j; i < s.Length;) + { + sb.Append(s[i]); + if (down) // going down + i += (numRows - 1 - j) * 2; + else // going up + i += 2*j; + + down = !down; // switch direction + } + } + + // handle last row + for (int i = numRows - 1; i < s.Length; i += (numRows - 1) * 2) + sb.Append(s[i]); + + return sb.ToString(); + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + String str = "PAYPALISHIRING"; + int numRows = 4; + + var res = sol.Convert(str, numRows); + Console.WriteLine(res); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..786b802c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode6-Zigzag/Leetcode6-Zigzag/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode6-Zigzag")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode6-Zigzag")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("bccdb6f0-69e9-411f-9b9a-d078c84e0dea")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum.sln b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum.sln new file mode 100644 index 00000000..47586d6b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeetCode611-ValidTriangleNum", "LeetCode611-ValidTriangleNum\LeetCode611-ValidTriangleNum.csproj", "{878B9040-CF99-4B3C-8844-4A1337ECA909}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {878B9040-CF99-4B3C-8844-4A1337ECA909}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {878B9040-CF99-4B3C-8844-4A1337ECA909}.Debug|Any CPU.Build.0 = Debug|Any CPU + {878B9040-CF99-4B3C-8844-4A1337ECA909}.Release|Any CPU.ActiveCfg = Release|Any CPU + {878B9040-CF99-4B3C-8844-4A1337ECA909}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0203BB73-6F67-4AA8-94E0-6F97BCD0B7AB} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/App.config b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/LeetCode611-ValidTriangleNum.csproj b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/LeetCode611-ValidTriangleNum.csproj new file mode 100644 index 00000000..29404e65 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/LeetCode611-ValidTriangleNum.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {878B9040-CF99-4B3C-8844-4A1337ECA909} + Exe + LeetCode611_ValidTriangleNum + LeetCode611-ValidTriangleNum + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/Program.cs b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/Program.cs new file mode 100644 index 00000000..eb62febd --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/Program.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LeetCode611_ValidTriangleNum +{ + public class Solution + { + public int TriangleNumber(int[] nums) + { + var n = nums.Length; + if (n < 3) + return 0; + + Array.Sort(nums); + // Array.Sort(array, (x, y) => -x.CompareTo(y)); + var groupCount = 0; + + for (int c = n - 1; c >= 2; c--) + { + int b = c - 1; + int a = 0; + while (a != b) + { + if (nums[a] + nums[b] > nums[c]) + { + groupCount += b - a; // 贪心法 + b--; + } + else + a++; + } + } + + return groupCount; + } + } + class Program + { + static void Main(string[] args) + { + int[] nums = { 2,2,3,4 }; + Solution sol = new Solution(); + sol.TriangleNumber(nums); + + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..b39cba87 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode611-valid-triangle-num/LeetCode611-ValidTriangleNum/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LeetCode611-ValidTriangleNum")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LeetCode611-ValidTriangleNum")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("878b9040-cf99-4b3c-8844-4a1337eca909")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633.sln b/csharp-leetcode/vs projects/leetcode633/leetcode633.sln new file mode 100644 index 00000000..27fe6700 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode633", "leetcode633\leetcode633.csproj", "{90CA5CA2-F16E-4033-B30B-6EB16D164430}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {90CA5CA2-F16E-4033-B30B-6EB16D164430}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {90CA5CA2-F16E-4033-B30B-6EB16D164430}.Debug|Any CPU.Build.0 = Debug|Any CPU + {90CA5CA2-F16E-4033-B30B-6EB16D164430}.Release|Any CPU.ActiveCfg = Release|Any CPU + {90CA5CA2-F16E-4033-B30B-6EB16D164430}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {52C1D15D-EC47-4685-ACA9-E30EA3096F99} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization1.cs b/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization1.cs new file mode 100644 index 00000000..89514d38 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization1.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace leetcode633 +{ + public class Optimization1 + { + public bool JudgeSquareSum(int c) + { + for (int i = 0; c - 2 * i * i >= 0; i++) + { + int diff = c - i * i; + if (IsPerfectSquare(diff)) + return true; + } + + return false; + } + private bool IsPerfectSquare(int num) + { + double sq1 = Math.Sqrt(num); + int sq2 = (int)Math.Sqrt(num); + if (Math.Abs(sq1 - (double)sq2) < 10e-10) + return true; + return false; + } + + //public static void Main(string[] args) + //{ + // Solution sol = new Solution(); + // Console.WriteLine(sol.JudgeSquareSum(25)); + //} + } +} diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization2.cs b/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization2.cs new file mode 100644 index 00000000..652ac1f6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization2.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace leetcode633 +{ + public class Optimization2 + { + public bool JudgeSquareSum(int c) + { + for (int i = 0; i <= c && c - i * i >= 0; i++) + { + int diff = c - i * i; + if (IsPerfectSquare(diff)) + return true; + } + + return false; + } + public bool IsPerfectSquare(int num) + { + // TRUE only if n mod 16 is 0, 1, 4, or 9 + if ((0x0213 & (1 << (num & 15))) != 0) + { + int t = (int)Math.Floor(Math.Sqrt((double)num) + 0.5); + return t * t == num; + } + return false; + } + + //public static void Main(string[] args) + //{ + // Solution sol = new Solution(); + // Console.WriteLine(sol.JudgeSquareSum(25)); + //} + } +} diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization3.cs b/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization3.cs new file mode 100644 index 00000000..8a1945b2 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633/Optimization3.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace leetcode633 +{ + public class Optimization3 + { + public bool JudgeSquareSum(int c) + { + for (int i = 0; c - i * i >= 0; i++) + { + long diff = c - i * i; + if (IsSquareFast(diff)) + return true; + } + + return false; + } + + bool IsSquareFast(long n) + { + if ((0x2030213 & (1 << (int)(n & 31))) > 0) + { + long t = (long)Math.Round(Math.Sqrt((double)n)); + bool result = t * t == n; + return result; + } + return false; + } + + //public static void Main(string[] args) + //{ + // Solution sol = new Solution(); + // Console.WriteLine(sol.JudgeSquareSum(25)); + //} + } +} diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633/Solution.cs b/csharp-leetcode/vs projects/leetcode633/leetcode633/Solution.cs new file mode 100644 index 00000000..bd50392d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633/Solution.cs @@ -0,0 +1,26 @@ +using System; + +namespace leetcode633 +{ + public class Solution + { + public bool JudgeSquareSum(int c) + { + for (int i = 0; c - 2 * i * i >= 0; i++) + { + double diff = c - i * i; + // 若向上取整=向下取整,则该数开方后是整数 + if ((int)(Math.Ceiling(Math.Sqrt(diff))) == (int)(Math.Floor(Math.Sqrt(diff)))) + return true; + } + + return false; + } + + public static void Main(string[] args) + { + Solution sol = new Solution(); + Console.WriteLine(sol.JudgeSquareSum(25)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633/Solution2.cs b/csharp-leetcode/vs projects/leetcode633/leetcode633/Solution2.cs new file mode 100644 index 00000000..1a7b1171 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633/Solution2.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace leetcode633 +{ + public class Solution2 + { + public class Solution + { + public bool JudgeSquareSum(int c) + { + for (int i = 0; c - 2 * i * i >= 0; i++) + { + double diff = c - i * i; + if (Math.Abs(Math.Sqrt(diff) % 1) < 0.000001) + return true; + } + + return false; + } + } + + //public static void Main(string[] args) + //{ + // Solution sol = new Solution(); + // Console.WriteLine(sol.JudgeSquareSum(25)); + //} + } +} diff --git a/csharp-leetcode/vs projects/leetcode633/leetcode633/leetcode633.csproj b/csharp-leetcode/vs projects/leetcode633/leetcode633/leetcode633.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633/leetcode633/leetcode633.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers.sln b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers.sln new file mode 100644 index 00000000..aa6f885c --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode633_sum-of-square-numbers", "Leetcode633_sum-of-square-numbers\Leetcode633_sum-of-square-numbers.csproj", "{515B58E4-143A-4532-BB03-3533CA0ECDC1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {515B58E4-143A-4532-BB03-3533CA0ECDC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {515B58E4-143A-4532-BB03-3533CA0ECDC1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {515B58E4-143A-4532-BB03-3533CA0ECDC1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {515B58E4-143A-4532-BB03-3533CA0ECDC1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F5779686-076D-4504-952E-376B6535F2EB} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/App.config b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers.csproj b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers.csproj new file mode 100644 index 00000000..9028256a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {515B58E4-143A-4532-BB03-3533CA0ECDC1} + Exe + Leetcode633_sum_of_square_numbers + Leetcode633_sum-of-square-numbers + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Program.cs b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Program.cs new file mode 100644 index 00000000..8a59ca8a --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Program.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; + +namespace Leetcode633_sum_of_square_numbers +{ + public class Solution + { + public bool IsPerfectSquare(int num) + { + int i = 1; + while (num > 0) + { + num -= i; + i += 2; + } + + if (num == 0) + return true; + return false; + } + } + + class Program + { + static void Main(string[] args) + { + string str; + while ((str = Console.ReadLine()) != null) + { + int n = int.Parse(str); + Solution sol = new Solution(); + bool result = sol.IsPerfectSquare(n); + Console.WriteLine(result); + } + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..822c430e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode633_sum-of-square-numbers/Leetcode633_sum-of-square-numbers/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode633_sum-of-square-numbers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode633_sum-of-square-numbers")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("515b58e4-143a-4532-bb03-3533ca0ecdc1")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number.sln b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number.sln new file mode 100644 index 00000000..8ac7a5c5 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode65-valid-number", "leetcode65-valid-number\leetcode65-valid-number.csproj", "{9B192CE4-0D44-4EB2-B934-2D66E95E562E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9B192CE4-0D44-4EB2-B934-2D66E95E562E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B192CE4-0D44-4EB2-B934-2D66E95E562E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B192CE4-0D44-4EB2-B934-2D66E95E562E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B192CE4-0D44-4EB2-B934-2D66E95E562E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A9591625-3527-493A-9F90-9FF0903C9E47} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/App.config b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/Program.cs b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/Program.cs new file mode 100644 index 00000000..be196d78 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/Program.cs @@ -0,0 +1,65 @@ +using System; +using System.Linq; + +namespace leetcode65_valid_number +{ + class Program + { + public class Solution + { + public string ToNum(string s) + { + string num = String.Empty; + + s = s.Trim(); + string[] arr = s.Split('E'); + int LastZeroCountInPart1 = 0; + foreach (char ch in arr[0].Reverse()) + { + if (ch == '0') + LastZeroCountInPart1++; + else + { + break; + } + } + + bool isPart1Double = double.TryParse(arr[0], out var part1); + int decimalDigitCountInPart1 = arr[0].IndexOf('.') == -1 ? 0 : arr[0].Length - 1 - arr[0].IndexOf('.'); + + string newPart2 = arr.ElementAtOrDefault(1); + bool isPart2Int = int.TryParse(newPart2, out var part2); + if (arr.Length == 1) + { + if (isPart1Double) + num = part1.ToString(); + } + if (arr.Length == 2) + { + if (part2 < 0 || part2 - decimalDigitCountInPart1 < 0) + { + if (isPart1Double && isPart2Int) + num = Decimal.Parse((part1 * Math.Pow(10, part2)).ToString(), System.Globalization.NumberStyles.Float).ToString(); + } + else if (part2 - decimalDigitCountInPart1 >= 0) + { + num = part1.ToString().Replace(".", "") + new String('0', part2 - decimalDigitCountInPart1); + } + + } + + return num + new String('0', LastZeroCountInPart1); + } + } + + static void Main(string[] args) + { + Solution sol = new Solution(); + string str; + while ((str = Console.ReadLine()) != null) + { + Console.WriteLine(sol.ToNum(str)); + } + } + } +} \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..e2abc15d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("leetcode65-valid-number")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("leetcode65-valid-number")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9b192ce4-0d44-4eb2-b934-2d66e95e562e")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/leetcode65-valid-number.csproj b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/leetcode65-valid-number.csproj new file mode 100644 index 00000000..dbfd1cd4 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode65-valid-number/leetcode65-valid-number/leetcode65-valid-number.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {9B192CE4-0D44-4EB2-B934-2D66E95E562E} + Exe + LeetCode65_Valid_Number + leetcode65-valid-number + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693.sln b/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693.sln new file mode 100644 index 00000000..1ff6a132 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2048 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode693", "leetcode693\leetcode693.csproj", "{83DD4923-CF04-41A5-8224-E85FF4C8F970}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {83DD4923-CF04-41A5-8224-E85FF4C8F970}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {83DD4923-CF04-41A5-8224-E85FF4C8F970}.Debug|Any CPU.Build.0 = Debug|Any CPU + {83DD4923-CF04-41A5-8224-E85FF4C8F970}.Release|Any CPU.ActiveCfg = Release|Any CPU + {83DD4923-CF04-41A5-8224-E85FF4C8F970}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {092343F0-AE8A-4B71-8426-65165595B023} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693/Program.cs b/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693/Program.cs new file mode 100644 index 00000000..e28a4246 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693/Program.cs @@ -0,0 +1,22 @@ +using System; + +namespace leetcode693 +{ + public class Solution + { + + public bool HasAlternatingBits(int n) + { + string str = Convert.ToString(n, 2); + if (str.IndexOf("00", StringComparison.Ordinal) != -1 || str.IndexOf("11", StringComparison.Ordinal) != -1) + return false; + + return true; + } + + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693/leetcode693.csproj b/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693/leetcode693.csproj new file mode 100644 index 00000000..23df6047 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode693-binary-number-with-alternating-bits/leetcode693/leetcode693.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp2.1 + + + diff --git a/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar.sln b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar.sln new file mode 100644 index 00000000..023d5646 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode717-1bitN2bitChar", "Leetcode717-1bitN2bitChar\Leetcode717-1bitN2bitChar.csproj", "{49F4CA5C-780E-485A-883E-F9C2A27F9787}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {49F4CA5C-780E-485A-883E-F9C2A27F9787}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {49F4CA5C-780E-485A-883E-F9C2A27F9787}.Debug|Any CPU.Build.0 = Debug|Any CPU + {49F4CA5C-780E-485A-883E-F9C2A27F9787}.Release|Any CPU.ActiveCfg = Release|Any CPU + {49F4CA5C-780E-485A-883E-F9C2A27F9787}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {59DE27FE-865C-4DDA-AF34-927D4047FDC6} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/App.config b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar.csproj b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar.csproj new file mode 100644 index 00000000..47f8f687 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {49F4CA5C-780E-485A-883E-F9C2A27F9787} + Exe + Leetcode717_1bitN2bitChar + Leetcode717-1bitN2bitChar + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Program.cs b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Program.cs new file mode 100644 index 00000000..381cbb39 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Program.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode717_1bitN2bitChar +{ + public class Solution + { + public bool IsOneBitCharacter(int[] bits) + { + bool IsTail0 = false; + int len = bits.Length; + if (len == 1) + return true; + if (bits.Last() == 0 && bits[len - 2] == 0) + return true; + int oneCounts = 0; + for (int i = len - 2; i >= 0; i--) + { + if (bits[i] == 1) + oneCounts++; + } + IsTail0 = (oneCounts & 1) != 0; // there is bracket () for & + + return IsTail0; + } + } + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..9fc4a16d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode717-1bitN2bitChar/Leetcode717-1bitN2bitChar/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode717-1bitN2bitChar")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode717-1bitN2bitChar")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("49f4ca5c-780e-485a-883e-f9c2a27f9787")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode728/leetcode728.sln b/csharp-leetcode/vs projects/leetcode728/leetcode728.sln new file mode 100644 index 00000000..6db4dcc8 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728/leetcode728.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode728", "leetcode728\leetcode728.csproj", "{ED25F305-93F0-40E0-BABA-E214ED9A8632}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {ED25F305-93F0-40E0-BABA-E214ED9A8632}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ED25F305-93F0-40E0-BABA-E214ED9A8632}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ED25F305-93F0-40E0-BABA-E214ED9A8632}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ED25F305-93F0-40E0-BABA-E214ED9A8632}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A67AA485-7FD1-4B92-B2DE-21D04F6CAA12} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode728/leetcode728/Program.cs b/csharp-leetcode/vs projects/leetcode728/leetcode728/Program.cs new file mode 100644 index 00000000..928d280e --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728/leetcode728/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; + +namespace leetcode728 +{ + public class Solution + { + public IList SelfDividingNumbers(int left, int right) + { + List list = new List(); + for (int i = left; i <= right; ++i) + { + if (isSelfDiv(i)) + list.Add(i); + } + return list; + } + + bool isSelfDiv(int n) + { + if (n < 10) + return true; + if (n % 10 == 0) + return false; + + int t = n; + while (t != 0) + { + int rem = t % 10; + if (rem == 0) + return false; + if (rem > 1 && n % rem != 0) // 原数不是末位数字倍数的数需要排除 + return false; + t /= 10; + } + return true; + } + + static void Main(string[] args) + { + var sol = new Solution(); + var res = sol.SelfDividingNumbers(5, 50); + foreach (var item in res) + Console.WriteLine(item); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode728/leetcode728/leetcode728.csproj b/csharp-leetcode/vs projects/leetcode728/leetcode728/leetcode728.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728/leetcode728/leetcode728.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers.sln b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers.sln new file mode 100644 index 00000000..aec29327 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2000 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode728_self-dividing-numbers", "Leetcode728_self-dividing-numbers\Leetcode728_self-dividing-numbers.csproj", "{5DC69322-ED95-4430-AD5A-2743755C3296}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5DC69322-ED95-4430-AD5A-2743755C3296}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DC69322-ED95-4430-AD5A-2743755C3296}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DC69322-ED95-4430-AD5A-2743755C3296}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DC69322-ED95-4430-AD5A-2743755C3296}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9A3CA6EE-745A-43CA-8432-D4E1356EA0E5} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/App.config b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers.csproj b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers.csproj new file mode 100644 index 00000000..23004379 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {5DC69322-ED95-4430-AD5A-2743755C3296} + Exe + Leetcode728_self_dividing_numbers + Leetcode728_self-dividing-numbers + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Program.cs b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Program.cs new file mode 100644 index 00000000..5aa133c8 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Program.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode728_self_dividing_numbers +{ + public class Solution + { + public IList SelfDividingNumbers(int left, int right) + { + List list = new List(); + for (int i = left; i <= right; ++i) + { + if (isSelfDiv(i)) + list.Add(i); + } + return list; + } + + bool isSelfDiv(int n) + { + if (n < 10) + return true; + if (n % 10 == 0) + return false; + + int t = n; + while (t != 0) + { + int rem = t % 10; + if (rem == 0) + return false; + if (rem >1 && n % rem != 0) + return false; + t /= 10; + } + return true; + } + } + class Program + { + static void Main(string[] args) + { + var sol = new Solution(); + sol.SelfDividingNumbers(2, 30); + + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..91dde4f9 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode728_self-dividing-numbers/Leetcode728_self-dividing-numbers/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode728_self-dividing-numbers")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode728_self-dividing-numbers")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5dc69322-ed95-4430-ad5a-2743755c3296")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget.sln b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget.sln new file mode 100644 index 00000000..be802367 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode744-FindSmallestLetterGreaterThanTarget", "Leetcode744-FindSmallestLetterGreaterThanTarget\Leetcode744-FindSmallestLetterGreaterThanTarget.csproj", "{ECC698A7-D2B1-4381-845B-DD9EC8814C84}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {ECC698A7-D2B1-4381-845B-DD9EC8814C84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ECC698A7-D2B1-4381-845B-DD9EC8814C84}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ECC698A7-D2B1-4381-845B-DD9EC8814C84}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ECC698A7-D2B1-4381-845B-DD9EC8814C84}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3FC48347-D1A7-4DCC-BA9A-22CC4698F3F4} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/App.config b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Leetcode744-FindSmallestLetterGreaterThanTarget.csproj b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Leetcode744-FindSmallestLetterGreaterThanTarget.csproj new file mode 100644 index 00000000..809d730f --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Leetcode744-FindSmallestLetterGreaterThanTarget.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {ECC698A7-D2B1-4381-845B-DD9EC8814C84} + Exe + Leetcode744_FindSmallestLetterGreaterThanTarget + Leetcode744-FindSmallestLetterGreaterThanTarget + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Program.cs b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Program.cs new file mode 100644 index 00000000..c1be7f54 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Program.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode744_FindSmallestLetterGreaterThanTarget +{ + public class Solution + { + public char NextGreatestLetter(char[] letters, char target) + { + List list = letters.ToList(); + list.Add(target); + list.Sort((x, y) => x.CompareTo(y)); + if (list.LastOrDefault() <= target) + return list.FirstOrDefault(); + return list.FirstOrDefault(x => x > target); + } + } + class Program + { + static void Main(string[] args) + { + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..c33bb31b --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode744-find-smallest-letter-greater-than-target/Leetcode744-FindSmallestLetterGreaterThanTarget/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode744-FindSmallestLetterGreaterThanTarget")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode744-FindSmallestLetterGreaterThanTarget")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ecc698a7-d2b1-4381-845b-dd9ec8814c84")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.sln b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.sln new file mode 100644 index 00000000..69734332 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode762-PrimeNumberofSetBitsinBinaryRepresentation", "leetcode762-PrimeNumberofSetBitsinBinaryRepresentation\leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.csproj", "{C8FDA0EC-632B-42A1-8FFB-CACC056226DE}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C8FDA0EC-632B-42A1-8FFB-CACC056226DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8FDA0EC-632B-42A1-8FFB-CACC056226DE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8FDA0EC-632B-42A1-8FFB-CACC056226DE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8FDA0EC-632B-42A1-8FFB-CACC056226DE}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {DDB323C1-3F1D-4090-AF1F-E02B92A15989} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/App.config b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/Program.cs b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/Program.cs new file mode 100644 index 00000000..d62e2d92 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/Program.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode762_PrimeNumberofSetBitsinBinaryRepresentation +{ + public class Solution + { + public int CountPrimeSetBits(int L, int R) + { + int count = 0; + for (int i = L; i < R; i++) + { + if (IsPrime(CountOf1(i))) + count++; + } + + return count; + } + + public int CountOf1(int n) + { + int count = 0; + while (n != 0) + { + n = n & (n - 1); + count++; + } + return count; + } + + public bool IsPrime(int m) + { + for (int i = 2; i*i <= m; i++) + { + if (m % i == 0) + return false; + } + return true; + } + } + + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + int count = sol.CountPrimeSetBits(2, 8); + + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..f9d291f9 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("leetcode762-PrimeNumberofSetBitsinBinaryRepresentation")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("leetcode762-PrimeNumberofSetBitsinBinaryRepresentation")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c8fda0ec-632b-42a1-8ffb-cacc056226de")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.csproj b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.csproj new file mode 100644 index 00000000..f75dc080 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode762-prime-number-of-set-bits-in-binary-representation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation/leetcode762-PrimeNumberofSetBitsinBinaryRepresentation.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {C8FDA0EC-632B-42A1-8FFB-CACC056226DE} + Exe + leetcode762_PrimeNumberofSetBitsinBinaryRepresentation + leetcode762-PrimeNumberofSetBitsinBinaryRepresentation + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771.sln b/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771.sln new file mode 100644 index 00000000..33fc2027 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode771", "leetcode771\leetcode771.csproj", "{D58F0B27-9776-4F45-AB0F-F9078FD1FE1C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D58F0B27-9776-4F45-AB0F-F9078FD1FE1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D58F0B27-9776-4F45-AB0F-F9078FD1FE1C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D58F0B27-9776-4F45-AB0F-F9078FD1FE1C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D58F0B27-9776-4F45-AB0F-F9078FD1FE1C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {36D1AF04-2869-4064-883D-A36003ED2075} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771/Program.cs b/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771/Program.cs new file mode 100644 index 00000000..a94da33f --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771/Program.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace leetcode771 +{ + public class Solution + { + public int NumJewelsInStones(string J, string S) + { + int jCount = 0; + + S.ToCharArray().GroupBy(c => c).ToList().ForEach(s => { + if (J.Contains(s.Key)) + jCount += s.Count(); + }); + + return jCount; + } + + static void Main(string[] args) + { + var sol = new Solution(); + string J = "aA"; + string S = "azAtttta"; + Console.WriteLine(sol.NumJewelsInStones(J, S)); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771/leetcode771.csproj b/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771/leetcode771.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode771-jewels-and-stones/leetcode771/leetcode771.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78.sln b/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78.sln new file mode 100644 index 00000000..1db2d4c0 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2048 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode78", "leetcode78\leetcode78.csproj", "{CEA04404-9549-438D-8332-82611265D1DA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CEA04404-9549-438D-8332-82611265D1DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CEA04404-9549-438D-8332-82611265D1DA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CEA04404-9549-438D-8332-82611265D1DA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CEA04404-9549-438D-8332-82611265D1DA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {18296A86-EAF4-462C-A674-E56AD7860292} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78/Program.cs b/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78/Program.cs new file mode 100644 index 00000000..6c8193bf --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78/Program.cs @@ -0,0 +1,35 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +namespace leetcode78 { + public class Solution { + public IList> Subsets(int[] nums) { + double count = Math.Pow(2, nums.Length); /* 大的思路: 转为二进制(长度与原数组中数字个数相等)的字符串, 然后枚举. 由于各个元素中不存在相等的数,于是每个二进制数位都有出现/不出现(0, 1)两种状态, 共有2^n组 */ + IList> res = new List>(); + res.Add(new List()); + for (int i = 1; i < count; i++) { + var curSet = new List (); + string str = Convert.ToString(i, 2).PadLeft(nums.Length, '0'); /* Convert.ToString(i, 2)表示转为二进制的字符串, PadLeft表示如果位数不够会在左侧填补上字符'0' */ + for (int j = 0; j < str.Length; j++) + { + if (str[j] == '1') + curSet.Add(nums[j]); + } + res.Add(curSet); + } + + return res; + } + + static void Main (string[] args) { + var sol = new Solution (); + var res = sol.Subsets(new int[] { 1, 2, 3 }); + foreach (var theSet in res) + { + theSet.ToList().ForEach(x => Console.Write(x + ",")); + Console.WriteLine(); + } + } + } +} \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78/leetcode78.csproj b/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78/leetcode78.csproj new file mode 100644 index 00000000..23df6047 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode78-subsets/leetcode78/leetcode78.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp2.1 + + + diff --git a/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830.sln b/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830.sln new file mode 100644 index 00000000..037846c7 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29009.5 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "leetcode830", "leetcode830\leetcode830.csproj", "{5EE6919D-3C40-4183-8996-8F4F94B8A10B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5EE6919D-3C40-4183-8996-8F4F94B8A10B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5EE6919D-3C40-4183-8996-8F4F94B8A10B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5EE6919D-3C40-4183-8996-8F4F94B8A10B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5EE6919D-3C40-4183-8996-8F4F94B8A10B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2EB848EE-286F-4A04-9B0D-367DC0CAB7A1} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830/Program.cs b/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830/Program.cs new file mode 100644 index 00000000..7a8078ad --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830/Program.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace leetcode830 +{ + public class Solution + { + public IList> LargeGroupPositions(string S) + { + // Setup initial state + List> group = new List>(); + // Loop thru all the groups + for (int i = 0; i < S.Length;) // i as slow point, fast( >= i) as fast point + { + // Reset inner loop state + int fast = i, maxCount = 0; + // Calculate group size + while (fast < S.Length && S[i] == S[fast]) + { + maxCount++; + fast++; + } + // Estimate group size and count in if needed + if (maxCount >= 3) + group.Add(new[] { i, fast - 1 }); + // Move start head to the beginning of the next group + i += maxCount; + } + // Here is the list of large groups + return group; + } + + static void Main(string[] args) + { + var sol = new Solution(); + Console.WriteLine(sol.LargeGroupPositions("abcdddeeeeaabbbcd")); + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830/leetcode830.csproj b/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830/leetcode830.csproj new file mode 100644 index 00000000..958d2f1d --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode830-positions-of-large-groups/leetcode830/leetcode830.csproj @@ -0,0 +1,8 @@ + + + + Exe + netcoreapp3.0 + + + diff --git a/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode.sln b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode.sln new file mode 100644 index 00000000..157e6649 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2043 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Leetcode89-GrayCode", "Leetcode89-GrayCode\Leetcode89-GrayCode.csproj", "{B0D1D369-4791-4815-8DC2-FE84872D7000}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0D1D369-4791-4815-8DC2-FE84872D7000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0D1D369-4791-4815-8DC2-FE84872D7000}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0D1D369-4791-4815-8DC2-FE84872D7000}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0D1D369-4791-4815-8DC2-FE84872D7000}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5675E7F9-E77B-4284-807C-B8E8A0C70828} + EndGlobalSection +EndGlobal diff --git a/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/App.config b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Leetcode89-GrayCode.csproj b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Leetcode89-GrayCode.csproj new file mode 100644 index 00000000..e143b158 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Leetcode89-GrayCode.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {B0D1D369-4791-4815-8DC2-FE84872D7000} + Exe + Leetcode89_GrayCode + Leetcode89-GrayCode + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Program.cs b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Program.cs new file mode 100644 index 00000000..330f7757 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Program.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Leetcode89_GrayCode +{ + public class Solution + { + public IList GrayCode(int n) + { + int len = 1< res = new List(len); + for (int i = 0; i < len; i++) + { + res.Add(i ^ (i >> 1)); + } + + return res; + } + } + class Program + { + static void Main(string[] args) + { + Solution sol = new Solution(); + var res = sol.GrayCode(2); + + } + } +} diff --git a/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Properties/AssemblyInfo.cs b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..70d5bc02 --- /dev/null +++ b/csharp-leetcode/vs projects/leetcode89-gray-code/Leetcode89-GrayCode/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Leetcode89-GrayCode")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Leetcode89-GrayCode")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b0d1d369-4791-4815-8dc2-fe84872d7000")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..c3afc259 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,3 @@ +## 说明 + +本文件夹包含一些优质的算法文档、读过的NOI国家队论文等. diff --git a/docs/noi2014-paper-bit-operation.pdf b/docs/noi2014-paper-bit-operation.pdf new file mode 100644 index 00000000..1a9fe6ff Binary files /dev/null and b/docs/noi2014-paper-bit-operation.pdf differ diff --git a/go-leetcode/README.md b/go-leetcode/README.md new file mode 100644 index 00000000..226d139b --- /dev/null +++ b/go-leetcode/README.md @@ -0,0 +1,7 @@ +# 算法刷题与练习 +LeetCode - Solutions + +Go语言版解法【原创】 +
    + +欢迎访问作者的个人网站: [极客中心](https://www.geekzl.com) diff --git a/go-leetcode/go.mod b/go-leetcode/go.mod new file mode 100644 index 00000000..23abd17b --- /dev/null +++ b/go-leetcode/go.mod @@ -0,0 +1,3 @@ +module test + +go 1.16 diff --git a/go-leetcode/leetcode215.go b/go-leetcode/leetcode215.go new file mode 100644 index 00000000..2404204a --- /dev/null +++ b/go-leetcode/leetcode215.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "sort" +) + +// Test +func main() { + input := []int{3, 2, 1, 5, 6, 4} + res := findKthLargest(input, 2) + fmt.Printf("%d\n", res) +} + +// Submit to leetcode +func findKthLargest(nums []int, k int) int { + // 排序 + sort.Ints(nums) + return nums[len(nums)-k] +} diff --git a/java-cc189-cracking_the_code_interview/lcci01.03-string-to-url-lcci.java/Solution.java b/java-cc189-cracking_the_code_interview/lcci01.03-string-to-url-lcci.java/Solution.java new file mode 100644 index 00000000..246c328e --- /dev/null +++ b/java-cc189-cracking_the_code_interview/lcci01.03-string-to-url-lcci.java/Solution.java @@ -0,0 +1,31 @@ +// import java.io.*; + +class Solution { + public String replaceSpaces(String S, int length) { + if(length > S.length()) return ""; + S = S.substring(0, length); + + StringBuilder res = new StringBuilder(); + for(int i=0; i < length; i++) + { + char ch = S.charAt(i); + if(ch != ' ') + res.append(ch); + else { + res.append("%20"); + } + } + + return res.toString(); + } + + // Test + public static void main(String[] args) { + Solution sol = new Solution(); + String S = "Mr John Smith "; + int length = 14; + String res = sol.replaceSpaces(S, length); + + System.out.println(res); + } +} \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/java-leetcode.iml b/java-leetcode_intelliJ_idea/java-leetcode.iml new file mode 100644 index 00000000..62f5ece8 --- /dev/null +++ b/java-leetcode_intelliJ_idea/java-leetcode.iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/lcci17.10.java/lcci17.10.java.iml b/java-leetcode_intelliJ_idea/lcci17.10.java/lcci17.10.java.iml new file mode 100644 index 00000000..c90834f2 --- /dev/null +++ b/java-leetcode_intelliJ_idea/lcci17.10.java/lcci17.10.java.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/lcci17.10.java/src/Solution.java b/java-leetcode_intelliJ_idea/lcci17.10.java/src/Solution.java new file mode 100644 index 00000000..a0184af5 --- /dev/null +++ b/java-leetcode_intelliJ_idea/lcci17.10.java/src/Solution.java @@ -0,0 +1,32 @@ +public class Solution { + int findMajorityElement(int[] nums) { + int candidate = getCandidate(nums); + return validate(nums, candidate) ? candidate : -1; + } + int getCandidate(int[] nums) { + int majority = 0; + int count = 0; + for (int n : nums) { + if (count == 0) { // 前面的集合中没有主要元素 + majority = n; + } + if (n == majority) { + count++; + } else { + count--; + } + } + return majority; + } + + boolean validate(int[] nums, int majority) { + int count = 0; + for (int n : nums) { + if (n == majority) { + count++; + } + } + + return count > nums.length / 2; + } +} diff --git a/java-leetcode_intelliJ_idea/leetcode1-two-sum.java/leetcode1-two-sum.java.iml b/java-leetcode_intelliJ_idea/leetcode1-two-sum.java/leetcode1-two-sum.java.iml new file mode 100644 index 00000000..c90834f2 --- /dev/null +++ b/java-leetcode_intelliJ_idea/leetcode1-two-sum.java/leetcode1-two-sum.java.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/leetcode1-two-sum.java/src/Solution.java b/java-leetcode_intelliJ_idea/leetcode1-two-sum.java/src/Solution.java new file mode 100644 index 00000000..0b366506 --- /dev/null +++ b/java-leetcode_intelliJ_idea/leetcode1-two-sum.java/src/Solution.java @@ -0,0 +1,32 @@ +import java.util.*; + +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap dict = new HashMap(); /* HashMap只能装integer,不能装int */ + int[] result = new int[2]; + for (int i = 0; i < nums.length; i++) + { + dict.put(nums[i], i); // 顺序的map映射: value->index + } + for (int i = 0; i < nums.length; i++) + { + int query = target - nums[i]; + if (dict.containsKey(query) && dict.get(query) > i) // dict[query] > i是为了防止重复计算 + { + result[0] = i; + result[1] = dict.get(query); + break; + } + } + return result; + } + + // Test + public static void main(String[] args) { + Solution sol = new Solution(); + int[] nums = {2,7,11,15}; + int target = 9; + int[] res = sol.twoSum(nums, target); + System.out.println(Arrays.toString(res)); + } +} \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/leetcode137-single-num.java/leetcode137-single-num.java.iml b/java-leetcode_intelliJ_idea/leetcode137-single-num.java/leetcode137-single-num.java.iml new file mode 100644 index 00000000..c90834f2 --- /dev/null +++ b/java-leetcode_intelliJ_idea/leetcode137-single-num.java/leetcode137-single-num.java.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/leetcode137-single-num.java/src/Solution.java b/java-leetcode_intelliJ_idea/leetcode137-single-num.java/src/Solution.java new file mode 100644 index 00000000..a5a06428 --- /dev/null +++ b/java-leetcode_intelliJ_idea/leetcode137-single-num.java/src/Solution.java @@ -0,0 +1,31 @@ +class Solution { + public int singleNumber(int[] nums) + { + int[] bits = new int[32]; + for (int num : nums) + { + for (int i = 0; i < 32; i++) + { + bits[i] = bits[i] + ((num >> i) & 1); // num>>i: [二进制下移位]丢掉num末尾i个bit位, + // digit & 1 用于高位清零, 检查数字的最后一位是否为偶数, 比number%2速度快 + // 于是最后的作用是将第i位转换为二进制的 0/1 + } + } + + int res = 0; + for (int i = 0; i < 32; i++) + { + res += (bits[i] % 3) << i; + } + + return res; + } + + // Test + public static void main(String[] args) { + Solution sol = new Solution(); + int[] nums = {2,2,3,2}; + int res = sol.singleNumber(nums); + System.out.println(res); + } +} \ No newline at end of file diff --git a/java-leetcode_intelliJ_idea/leetcode76-minimum-window-substring.java/Solution.java b/java-leetcode_intelliJ_idea/leetcode76-minimum-window-substring.java/Solution.java new file mode 100644 index 00000000..7f1aca2d --- /dev/null +++ b/java-leetcode_intelliJ_idea/leetcode76-minimum-window-substring.java/Solution.java @@ -0,0 +1,56 @@ +/** 重要提示: + * File name should be renamed to "Solution.java" when run locally. + * Class name should be changed to "Main" (including test logic in bottom main()) when run in . + */ +public class Solution { + public String minWindow(String s, String t) { + if (s == null || t == null || s.length() < t.length()) { + return ""; + } + + int[] gapMap = new int[128]; + for (char ch : t.toCharArray()) // 先遍历字符串t来初始化gapMap + { + gapMap[ch]++; + } + + int right = 0; + int left = 0; + int gapSum = t.length(); + int start = 0; + int minLen = Integer.MAX_VALUE; + while (right < s.length()) { + char rch = s.charAt(right); + if (gapMap[rch] > 0) + gapSum--; + gapMap[rch]--; /* 如果该字符不是需要的,加到map中,每出现一次累记1个-1。如果该字符在map中有的话就减1表示抵消一个。*/ + + if (gapSum == 0) { + while (left < right && gapMap[s.charAt(left)] < 0) // 右移左边界, 依次扔掉当前的字符, gapMap中相应的值+1 + { + gapMap[s.charAt(left++)]++; + } + if (right - left + 1 < minLen) // 更新窗口长度 + { + minLen = right - left + 1; + start = left; + } + + // 当while循环结束, 即字符在gapMap中的值当为0且左边界继续右移时 + gapMap[s.charAt(left++)]++; + gapSum++; + } + + right++; + } + return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen); + } + + // Test + public static void main(String[] args) { + Solution sol = new Solution(); + String s = "ADOBECODEBANC", t = "ABC"; + String res = sol.minWindow(s, t); + System.out.println(res); + } +} diff --git a/java-leetcode_intelliJ_idea/leetcode84-largest-rectangle-in-histogram_monotonic_stack.java b/java-leetcode_intelliJ_idea/leetcode84-largest-rectangle-in-histogram_monotonic_stack.java new file mode 100644 index 00000000..bb2fd078 --- /dev/null +++ b/java-leetcode_intelliJ_idea/leetcode84-largest-rectangle-in-histogram_monotonic_stack.java @@ -0,0 +1,18 @@ +class Solution { + public int largestRectangleArea(int[] heights) { + if (heights == null || heights.length == 0) return 0; + + int[] tempArrs = new int[heights.length + 2]; + System.arraycopy(heights, 0, tempArrs, 1, heights.length); + Stack stack = new Stack<>(); + int area = 0; + for (int i = 0; i < tempArrs.length; i++) { + while (!stack.isEmpty() && tempArrs[i] < tempArrs[stack.peek()]) { + int height = tempArrs[stack.pop()]; + area = Math.max(area, (i - stack.peek() - 1) * height); + } + stack.push(i); // push索引 + } + return area; + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/.vscode/launch.json b/java-leetcode_vscode/.vscode/launch.json new file mode 100644 index 00000000..ac60bd58 --- /dev/null +++ b/java-leetcode_vscode/.vscode/launch.json @@ -0,0 +1,14 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "java", + "name": "Debug (Launch) - Current File", + "request": "launch", + "mainClass": "${file}" + } + ] +} \ No newline at end of file diff --git a/java-leetcode_vscode/Leetcode1.java b/java-leetcode_vscode/Leetcode1.java new file mode 100644 index 00000000..99e5a224 --- /dev/null +++ b/java-leetcode_vscode/Leetcode1.java @@ -0,0 +1,29 @@ +import java.util.Arrays; + +/** 如果有多种方法, 可以将文件名和class 名字都改为 Leetcode1_method2或Leetcode1b 这种格式 */ +class Leetcode1 { + public int[] twoSum(int[] nums, int target) { + int[] res = new int[2]; + // 双指针, 先固定一个 + for (int i = 0; i < nums.length; i++) { + for (int j = i + 1; j < nums.length; j++) { + if (nums[i] + nums[j] == target) { + res[0] = i; + res[1] = j; + return res; + } + } + } + return res; + } + + // Test + public static void main(String[] args) { + Leetcode1 sol = new Leetcode1(); + int[] nums = { 2, 1, 5, 6, 2, 3 }; + int target = 7; + int[] res = sol.twoSum(nums, target); + + System.out.println(Arrays.toString(res)); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Leetcode405a.java b/java-leetcode_vscode/Leetcode405a.java new file mode 100644 index 00000000..af5475b6 --- /dev/null +++ b/java-leetcode_vscode/Leetcode405a.java @@ -0,0 +1,47 @@ +import java.util.*; + +/** 如果有多种方法, 可以将文件名和class 名字都改为 Leetcode1_method2或Leetcode1b 这种格式 */ +class Leetcode405a { + public String toHex(int num) { + String res = ""; + long N = num; // 预处理 + if (N == 0) + return "0"; + HashMap dict = new HashMap() { + { + put(0, '0'); + put(1, '1'); + put(2, '2'); + put(3, '3'); + put(4, '4'); + put(5, '5'); + put(6, '6'); + put(7, '7'); + put(8, '8'); + put(9, '9'); + put(10, 'a'); + put(11, 'b'); + put(12, 'c'); + put(13, 'd'); + put(14, 'e'); + put(15, 'f'); + } + }; + if (N < 0) N = 4294967296L + N; /* 4294967296L就是 0x0000000100000000(16^8=2^32), Java中 + * 不使用BigInteger无法存储该数, 只能hard code在这里了 + */ + while (N > 0) { + long lastDigit = N % 16; + N /= 16; + res = dict.get((int) lastDigit) + res; + } + return res; + } + + public static void main(String[] args) { + Leetcode405a sol = new Leetcode405a(); + int num = 7; + String res = sol.toHex(num); + System.out.println(res); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Leetcode405b.java b/java-leetcode_vscode/Leetcode405b.java new file mode 100644 index 00000000..21f17ddc --- /dev/null +++ b/java-leetcode_vscode/Leetcode405b.java @@ -0,0 +1,24 @@ +/** 如果有多种方法, 可以将文件名和class 名字都改为 Leetcode1_method2或Leetcode1b 这种格式 */ +class Leetcode405b { + public String toHex(int num) { + String res = ""; + long N = num; // 预处理 + if (N == 0) return "0"; + String dict = "0123456789abcdef"; + if (N < 0) N = 4294967296L + N; /* 4294967296L就是 0x0000000100000000(16^8=2^32), Java中不使用BigInteger无法存储, 只能hard code在这里了 */ + while (N > 0) + { + long lastDigit = N % 16; + N /= 16; + res = dict.charAt((int)lastDigit) + res; + } + return res; + } + + public static void main(String[] args) { + Leetcode405a sol = new Leetcode405a(); + int num = 7; + String res = sol.toHex(num); + System.out.println(res); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Leetcode84.java b/java-leetcode_vscode/Leetcode84.java new file mode 100644 index 00000000..f545e0b5 --- /dev/null +++ b/java-leetcode_vscode/Leetcode84.java @@ -0,0 +1,29 @@ +import java.util.Stack; + +class Leetcode84 { + public int largestRectangleArea(int[] heights) { + if (heights == null || heights.length == 0) return 0; + + int[] tempArrs = new int[heights.length + 2]; + System.arraycopy(heights, 0, tempArrs, 1, heights.length); + Stack stack = new Stack<>(); + int area = 0; + for (int i = 0; i < tempArrs.length; i++) { + while (!stack.isEmpty() && tempArrs[i] < tempArrs[stack.peek()]) { + int height = tempArrs[stack.pop()]; + area = Math.max(area, (i - stack.peek() - 1) * height); + } + stack.push(i); // push: 数组下标 + } + return area; + } + + // Test + public static void main(String[] args) { + int[] heights = { 2, 1, 5, 6, 2, 3 }; + Leetcode84 sol = new Leetcode84(); + int res = sol.largestRectangleArea(heights); + + System.out.println(res); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Leetcode93b.java b/java-leetcode_vscode/Leetcode93b.java new file mode 100644 index 00000000..85a524e0 --- /dev/null +++ b/java-leetcode_vscode/Leetcode93b.java @@ -0,0 +1,37 @@ +import java.util.*; +public class Leetcode93b { + public List restoreIpAddresses(String s) { + List res = new ArrayList<> (); + for (int i = 1; i < 4; i++) { + for (int j = 1; j < 4; j++) { + for (int k = 1; k < 4; k++) { + for (int m = 1; m < 4; m++) { + if (i + j + k + m != s.length()) { + continue; + } + int a = Integer.valueOf(s.substring(0, i)); + int b = Integer.valueOf(s.substring(i, i + j)); + int c = Integer.valueOf(s.substring(i + j, i + j + k)); + + int d = Integer.valueOf(s.substring(i + j + k)); + if (a <= 255 && b <= 255 && c <= 255 && d <= 255) { + String temp = a + "." + b + "." + c + "." + d; + /* 处理先导0, "0.0.0.0"是合法的, 而"0.01.0.0"不是, 下面的+3是表示3个点. */ + if (temp.length() == s.length() + 3) { + res.add(temp); + } + } + } + } + } + } + return res; + } + public static void main(String[] args) { + Leetcode93b sol = new Leetcode93b(); + String s = "25525511135"; + List res = sol.restoreIpAddresses(s); + + System.out.println(Arrays.toString(res.toArray())); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Solutions/Leetcode1.java.md b/java-leetcode_vscode/Solutions/Leetcode1.java.md new file mode 100644 index 00000000..988eddef --- /dev/null +++ b/java-leetcode_vscode/Solutions/Leetcode1.java.md @@ -0,0 +1,7 @@ +## 本题代码: + +[Leetcode1.java](../Leetcode1.java) + +**ps:** + +本代码提交到LeetCode 前需要把代码开头的`class LeetcodeXXX`改为`class Solution`, 并删除代码开头的import语句和代码末尾的main方法(`public static void main ...`). diff --git a/java-leetcode_vscode/Solutions/Leetcode84.java.md b/java-leetcode_vscode/Solutions/Leetcode84.java.md new file mode 100644 index 00000000..fc712597 --- /dev/null +++ b/java-leetcode_vscode/Solutions/Leetcode84.java.md @@ -0,0 +1,7 @@ +## 本题代码: + +[Leetcode84.java](../Leetcode84.java) + +**ps:** + +本代码提交到LeetCode 前需要把代码开头的`class LeetcodeXXX`改为`class Solution`, 并删除代码开头的import语句和代码末尾的main方法(`public static void main ...`). diff --git a/java-leetcode_vscode/Test.java b/java-leetcode_vscode/Test.java new file mode 100644 index 00000000..c2eff641 --- /dev/null +++ b/java-leetcode_vscode/Test.java @@ -0,0 +1,6 @@ +public class Test { + public static void main(String[] args) { + String lang = "java"; + System.out.print("See u again, " + lang); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Test2.java b/java-leetcode_vscode/Test2.java new file mode 100644 index 00000000..b36602d1 --- /dev/null +++ b/java-leetcode_vscode/Test2.java @@ -0,0 +1,21 @@ +class Test2 { + public int sum(int a, int b) { + return a + b; + } + + // Test + public static void main(String[] args) { + Test2 sol = new Test2(); + int a = 2, b = 5; + int res = sol.sum(a, b); + + System.out.println(res); + /* To print array */ + // System.out.println(Arrays.toString(arr)); + + /* To print list in Java 8 */ + // System.out.println(Arrays.toString(list.toArray())); + // list.forEach(System.out::println); + // list.stream().forEach(System.out::println); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/Test3.java b/java-leetcode_vscode/Test3.java new file mode 100644 index 00000000..3162b017 --- /dev/null +++ b/java-leetcode_vscode/Test3.java @@ -0,0 +1,16 @@ +class Test3 { + public boolean isValid(String s) { + // ... + return false; + } +} + +class Main { + public static void main(String[] args) { + Test3 sol = new Test3(); + String s = "()[]{}"; + boolean res = sol.isValid(s); + + System.out.println(res); + } +} \ No newline at end of file diff --git a/java-leetcode_vscode/ebook/C++ for Java Programmers_gvsu_JavaToC++11.pdf b/java-leetcode_vscode/ebook/C++ for Java Programmers_gvsu_JavaToC++11.pdf new file mode 100644 index 00000000..82e7f357 Binary files /dev/null and b/java-leetcode_vscode/ebook/C++ for Java Programmers_gvsu_JavaToC++11.pdf differ diff --git a/leetcode-ac-tracking.md b/leetcode-ac-tracking.md new file mode 100644 index 00000000..d7b430f6 --- /dev/null +++ b/leetcode-ac-tracking.md @@ -0,0 +1,1955 @@ +# 🚀 LeetCode题解进度表 + +## LeetCode中文题大全 + +[leetcode中文题1-400](https://github.com/yanglr/leetcode-ac/tree/master/中文题1-2000/leetcode1-400) + +[leetcode中文题401-2000](https://github.com/yanglr/leetcode-ac/tree/master/中文题1-2000/leetcode401-2000) + + + +快速搜索题号、题解、代码、标签等,请善用 `Ctrl`+`F`(或者 `Command`+`F`)。 + + +| 题号 | 题解 | 代码 | 标签 | 难度 | 有无锁 | AC状态 | +| --- | --- | --- | --- | --- | --- | --- | +| [0001](https://leetcode-cn.com/problems/two-sum) | 两数之和 | | `数组`,`哈希表` | 简单 | | | +| [0002](https://leetcode-cn.com/problems/add-two-numbers) | 两数相加 | | `递归`,`链表`,`数学` | 中等 | | | +| [0003](https://leetcode-cn.com/problems/longest-substring-without-repeating-characters) | 无重复字符的最长子串 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | | | +| [0004](https://leetcode-cn.com/problems/median-of-two-sorted-arrays) | 寻找两个正序数组的中位数 | | `数组`,`二分查找`,`分治` | 困难 | | | +| [0005](https://leetcode-cn.com/problems/longest-palindromic-substring) | 最长回文子串 | | `字符串`,`动态规划` | 中等 | | | +| [0006](https://leetcode-cn.com/problems/zigzag-conversion) | Z 字形变换 | | `字符串` | 中等 | | | +| [0007](https://leetcode-cn.com/problems/reverse-integer) | 整数反转 | | `数学` | 简单 | | | +| [0008](https://leetcode-cn.com/problems/string-to-integer-atoi) | 字符串转换整数 (atoi) | | `字符串` | 中等 | | | +| [0009](https://leetcode-cn.com/problems/palindrome-number) | 回文数 | | `数学` | 简单 | | ✅ | +| [0010](https://leetcode-cn.com/problems/regular-expression-matching) | 正则表达式匹配 | | `递归`,`字符串`,`动态规划` | 困难 | | | +| [0011](https://leetcode-cn.com/problems/container-with-most-water) | 盛最多水的容器 | | `贪心`,`数组`,`双指针` | 中等 | | | +| [0012](https://leetcode-cn.com/problems/integer-to-roman) | 整数转罗马数字 | | `哈希表`,`数学`,`字符串` | 中等 | | | +| [0013](https://leetcode-cn.com/problems/roman-to-integer) | 罗马数字转整数 | | `哈希表`,`数学`,`字符串` | 简单 | | ✅ | +| [0014](https://leetcode-cn.com/problems/longest-common-prefix) | 最长公共前缀 | | `字符串` | 简单 | | | +| [0015](https://leetcode-cn.com/problems/3sum) | 三数之和 | | `数组`,`双指针`,`排序` | 中等 | | | +| [0016](https://leetcode-cn.com/problems/3sum-closest) | 最接近的三数之和 | | `数组`,`双指针`,`排序` | 中等 | | | +| [0017](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number) | 电话号码的字母组合 | | `哈希表`,`字符串`,`回溯` | 中等 | | | +| [0018](https://leetcode-cn.com/problems/4sum) | 四数之和 | | `数组`,`双指针`,`排序` | 中等 | | | +| [0019](https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list) | 删除链表的倒数第 N 个结点 | | `链表`,`双指针` | 中等 | | | +| [0020](https://leetcode-cn.com/problems/valid-parentheses) | 有效的括号 | | `栈`,`字符串` | 简单 | | | +| [0021](https://leetcode-cn.com/problems/merge-two-sorted-lists) | 合并两个有序链表 | | `递归`,`链表` | 简单 | | | +| [0022](https://leetcode-cn.com/problems/generate-parentheses) | 括号生成 | | `字符串`,`动态规划`,`回溯` | 中等 | | | +| [0023](https://leetcode-cn.com/problems/merge-k-sorted-lists) | 合并K个升序链表 | | `链表`,`分治`,`堆(优先队列)`,`归并排序` | 困难 | | | +| [0024](https://leetcode-cn.com/problems/swap-nodes-in-pairs) | 两两交换链表中的节点 | | `递归`,`链表` | 中等 | | | +| [0025](https://leetcode-cn.com/problems/reverse-nodes-in-k-group) | K 个一组翻转链表 | | `递归`,`链表` | 困难 | | | +| [0026](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array) | 删除有序数组中的重复项 | | `数组`,`双指针` | 简单 | | | +| [0027](https://leetcode-cn.com/problems/remove-element) | 移除元素 | | `数组`,`双指针` | 简单 | | | +| [0028](https://leetcode-cn.com/problems/implement-strstr) | 实现 strStr() | | `双指针`,`字符串`,`字符串匹配` | 简单 | | | +| [0029](https://leetcode-cn.com/problems/divide-two-integers) | 两数相除 | | `位运算`,`数学` | 中等 | | | +| [0030](https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words) | 串联所有单词的子串 | | `哈希表`,`字符串`,`滑动窗口` | 困难 | | | +| [0031](https://leetcode-cn.com/problems/next-permutation) | 下一个排列 | | `数组`,`双指针` | 中等 | | | +| [0032](https://leetcode-cn.com/problems/longest-valid-parentheses) | 最长有效括号 | | `栈`,`字符串`,`动态规划` | 困难 | | | +| [0033](https://leetcode-cn.com/problems/search-in-rotated-sorted-array) | 搜索旋转排序数组 | | `数组`,`二分查找` | 中等 | | | +| [0034](https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array) | 在排序数组中查找元素的第一个和最后一个位置 | | `数组`,`二分查找` | 中等 | | | +| [0035](https://leetcode-cn.com/problems/search-insert-position) | 搜索插入位置 | | `数组`,`二分查找` | 简单 | | | +| [0036](https://leetcode-cn.com/problems/valid-sudoku) | 有效的数独 | | `数组`,`哈希表`,`矩阵` | 中等 | | | +| [0037](https://leetcode-cn.com/problems/sudoku-solver) | 解数独 | | `数组`,`回溯`,`矩阵` | 困难 | | | +| [0038](https://leetcode-cn.com/problems/count-and-say) | 外观数列 | | `字符串` | 中等 | | ✅ | +| [0039](https://leetcode-cn.com/problems/combination-sum) | 组合总和 | | `数组`,`回溯` | 中等 | | | +| [0040](https://leetcode-cn.com/problems/combination-sum-ii) | 组合总和 II | | `数组`,`回溯` | 中等 | | | +| [0041](https://leetcode-cn.com/problems/first-missing-positive) | 缺失的第一个正数 | | `数组`,`哈希表` | 困难 | | | +| [0042](https://leetcode-cn.com/problems/trapping-rain-water) | 接雨水 | | `栈`,`数组`,`双指针`,`动态规划`,`单调栈` | 困难 | | | +| [0043](https://leetcode-cn.com/problems/multiply-strings) | 字符串相乘 | | `数学`,`字符串`,`模拟` | 中等 | | | +| [0044](https://leetcode-cn.com/problems/wildcard-matching) | 通配符匹配 | | `贪心`,`递归`,`字符串`,`动态规划` | 困难 | | | +| [0045](https://leetcode-cn.com/problems/jump-game-ii) | 跳跃游戏 II | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [0046](https://leetcode-cn.com/problems/permutations) | 全排列 | | `数组`,`回溯` | 中等 | | | +| [0047](https://leetcode-cn.com/problems/permutations-ii) | 全排列 II | | `数组`,`回溯` | 中等 | | | +| [0048](https://leetcode-cn.com/problems/rotate-image) | 旋转图像 | | `数组`,`数学`,`矩阵` | 中等 | | | +| [0049](https://leetcode-cn.com/problems/group-anagrams) | 字母异位词分组 | | `哈希表`,`字符串`,`排序` | 中等 | | | +| [0050](https://leetcode-cn.com/problems/powx-n) | Pow(x, n) | | `递归`,`数学` | 中等 | | | +| [0051](https://leetcode-cn.com/problems/n-queens) | N 皇后 | | `数组`,`回溯` | 困难 | | | +| [0052](https://leetcode-cn.com/problems/n-queens-ii) | N皇后 II | | `回溯` | 困难 | | | +| [0053](https://leetcode-cn.com/problems/maximum-subarray) | 最大子序和 | | `数组`,`分治`,`动态规划` | 简单 | | | +| [0054](https://leetcode-cn.com/problems/spiral-matrix) | 螺旋矩阵 | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [0055](https://leetcode-cn.com/problems/jump-game) | 跳跃游戏 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [0056](https://leetcode-cn.com/problems/merge-intervals) | 合并区间 | | `数组`,`排序` | 中等 | | | +| [0057](https://leetcode-cn.com/problems/insert-interval) | 插入区间 | | `数组` | 中等 | | | +| [0058](https://leetcode-cn.com/problems/length-of-last-word) | 最后一个单词的长度 | | `字符串` | 简单 | | ✅ | +| [0059](https://leetcode-cn.com/problems/spiral-matrix-ii) | 螺旋矩阵 II | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [0060](https://leetcode-cn.com/problems/permutation-sequence) | 排列序列 | | `递归`,`数学` | 困难 | | | +| [0061](https://leetcode-cn.com/problems/rotate-list) | 旋转链表 | | `链表`,`双指针` | 中等 | | | +| [0062](https://leetcode-cn.com/problems/unique-paths) | 不同路径 | | `数学`,`动态规划`,`组合数学` | 中等 | | | +| [0063](https://leetcode-cn.com/problems/unique-paths-ii) | 不同路径 II | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [0064](https://leetcode-cn.com/problems/minimum-path-sum) | 最小路径和 | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [0065](https://leetcode-cn.com/problems/valid-number) | 有效数字 | | `字符串` | 困难 | | | +| [0066](https://leetcode-cn.com/problems/plus-one) | 加一 | | `数组`,`数学` | 简单 | | | +| [0067](https://leetcode-cn.com/problems/add-binary) | 二进制求和 | | `位运算`,`数学`,`字符串`,`模拟` | 简单 | | ✅ | +| [0068](https://leetcode-cn.com/problems/text-justification) | 文本左右对齐 | | `字符串`,`模拟` | 困难 | | | +| [0069](https://leetcode-cn.com/problems/sqrtx) | x 的平方根 | | `数学`,`二分查找` | 简单 | | | +| [0070](https://leetcode-cn.com/problems/climbing-stairs) | 爬楼梯 | | `记忆化搜索`,`数学`,`动态规划` | 简单 | | | +| [0071](https://leetcode-cn.com/problems/simplify-path) | 简化路径 | | `栈`,`字符串` | 中等 | | | +| [0072](https://leetcode-cn.com/problems/edit-distance) | 编辑距离 | | `字符串`,`动态规划` | 困难 | | | +| [0073](https://leetcode-cn.com/problems/set-matrix-zeroes) | 矩阵置零 | | `数组`,`哈希表`,`矩阵` | 中等 | | | +| [0074](https://leetcode-cn.com/problems/search-a-2d-matrix) | 搜索二维矩阵 | | `数组`,`二分查找`,`矩阵` | 中等 | | | +| [0075](https://leetcode-cn.com/problems/sort-colors) | 颜色分类 | | `数组`,`双指针`,`排序` | 中等 | | | +| [0076](https://leetcode-cn.com/problems/minimum-window-substring) | 最小覆盖子串 | | `哈希表`,`字符串`,`滑动窗口` | 困难 | | | +| [0077](https://leetcode-cn.com/problems/combinations) | 组合 | | `数组`,`回溯` | 中等 | | | +| [0078](https://leetcode-cn.com/problems/subsets) | 子集 | | `位运算`,`数组`,`回溯` | 中等 | | | +| [0079](https://leetcode-cn.com/problems/word-search) | 单词搜索 | | `数组`,`回溯`,`矩阵` | 中等 | | | +| [0080](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii) | 删除有序数组中的重复项 II | | `数组`,`双指针` | 中等 | | | +| [0081](https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii) | 搜索旋转排序数组 II | | `数组`,`二分查找` | 中等 | | | +| [0082](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii) | 删除排序链表中的重复元素 II | | `链表`,`双指针` | 中等 | | | +| [0083](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list) | 删除排序链表中的重复元素 | | `链表` | 简单 | | | +| [0084](https://leetcode-cn.com/problems/largest-rectangle-in-histogram) | 柱状图中最大的矩形 | | `栈`,`数组`,`单调栈` | 困难 | | | +| [0085](https://leetcode-cn.com/problems/maximal-rectangle) | 最大矩形 | | `栈`,`数组`,`动态规划`,`矩阵`,`单调栈` | 困难 | | | +| [0086](https://leetcode-cn.com/problems/partition-list) | 分隔链表 | | `链表`,`双指针` | 中等 | | | +| [0087](https://leetcode-cn.com/problems/scramble-string) | 扰乱字符串 | | `字符串`,`动态规划` | 困难 | | | +| [0088](https://leetcode-cn.com/problems/merge-sorted-array) | 合并两个有序数组 | | `数组`,`双指针`,`排序` | 简单 | | | +| [0089](https://leetcode-cn.com/problems/gray-code) | 格雷编码 | | `位运算`,`数学`,`回溯` | 中等 | | ✅ | +| [0090](https://leetcode-cn.com/problems/subsets-ii) | 子集 II | | `位运算`,`数组`,`回溯` | 中等 | | | +| [0091](https://leetcode-cn.com/problems/decode-ways) | 解码方法 | | `字符串`,`动态规划` | 中等 | | | +| [0092](https://leetcode-cn.com/problems/reverse-linked-list-ii) | 反转链表 II | | `链表` | 中等 | | | +| [0093](https://leetcode-cn.com/problems/restore-ip-addresses) | 复原 IP 地址 | | `字符串`,`回溯` | 中等 | | | +| [0094](https://leetcode-cn.com/problems/binary-tree-inorder-traversal) | 二叉树的中序遍历 | | `栈`,`树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0095](https://leetcode-cn.com/problems/unique-binary-search-trees-ii) | 不同的二叉搜索树 II | | `树`,`二叉搜索树`,`动态规划`,`回溯`,`二叉树` | 中等 | | | +| [0096](https://leetcode-cn.com/problems/unique-binary-search-trees) | 不同的二叉搜索树 | | `树`,`二叉搜索树`,`数学`,`动态规划`,`二叉树` | 中等 | | | +| [0097](https://leetcode-cn.com/problems/interleaving-string) | 交错字符串 | | `字符串`,`动态规划` | 中等 | | | +| [0098](https://leetcode-cn.com/problems/validate-binary-search-tree) | 验证二叉搜索树 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0099](https://leetcode-cn.com/problems/recover-binary-search-tree) | 恢复二叉搜索树 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0100](https://leetcode-cn.com/problems/same-tree) | 相同的树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0101](https://leetcode-cn.com/problems/symmetric-tree) | 对称二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0102](https://leetcode-cn.com/problems/binary-tree-level-order-traversal) | 二叉树的层序遍历 | | `树`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0103](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal) | 二叉树的锯齿形层序遍历 | | `树`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0104](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree) | 二叉树的最大深度 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0105](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal) | 从前序与中序遍历序列构造二叉树 | | `树`,`数组`,`哈希表`,`分治`,`二叉树` | 中等 | | | +| [0106](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal) | 从中序与后序遍历序列构造二叉树 | | `树`,`数组`,`哈希表`,`分治`,`二叉树` | 中等 | | | +| [0107](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii) | 二叉树的层序遍历 II | | `树`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0108](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree) | 将有序数组转换为二叉搜索树 | | `树`,`二叉搜索树`,`数组`,`分治`,`二叉树` | 简单 | | | +| [0109](https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree) | 有序链表转换二叉搜索树 | | `树`,`二叉搜索树`,`链表`,`分治`,`二叉树` | 中等 | | | +| [0110](https://leetcode-cn.com/problems/balanced-binary-tree) | 平衡二叉树 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0111](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree) | 二叉树的最小深度 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0112](https://leetcode-cn.com/problems/path-sum) | 路径总和 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0113](https://leetcode-cn.com/problems/path-sum-ii) | 路径总和 II | | `树`,`深度优先搜索`,`回溯`,`二叉树` | 中等 | | | +| [0114](https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list) | 二叉树展开为链表 | | `栈`,`树`,`深度优先搜索`,`链表`,`二叉树` | 中等 | | | +| [0115](https://leetcode-cn.com/problems/distinct-subsequences) | 不同的子序列 | | `字符串`,`动态规划` | 困难 | | | +| [0116](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node) | 填充每个节点的下一个右侧节点指针 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0117](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii) | 填充每个节点的下一个右侧节点指针 II | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0118](https://leetcode-cn.com/problems/pascals-triangle) | 杨辉三角 | | `数组`,`动态规划` | 简单 | | | +| [0119](https://leetcode-cn.com/problems/pascals-triangle-ii) | 杨辉三角 II | | `数组`,`动态规划` | 简单 | | | +| [0120](https://leetcode-cn.com/problems/triangle) | 三角形最小路径和 | | `数组`,`动态规划` | 中等 | | | +| [0121](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock) | 买卖股票的最佳时机 | | `数组`,`动态规划` | 简单 | | | +| [0122](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii) | 买卖股票的最佳时机 II | | `贪心`,`数组`,`动态规划` | 简单 | | | +| [0123](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii) | 买卖股票的最佳时机 III | | `数组`,`动态规划` | 困难 | | | +| [0124](https://leetcode-cn.com/problems/binary-tree-maximum-path-sum) | 二叉树中的最大路径和 | | `树`,`深度优先搜索`,`动态规划`,`二叉树` | 困难 | | | +| [0125](https://leetcode-cn.com/problems/valid-palindrome) | 验证回文串 | | `双指针`,`字符串` | 简单 | | | +| [0126](https://leetcode-cn.com/problems/word-ladder-ii) | 单词接龙 II | | `广度优先搜索`,`哈希表`,`字符串`,`回溯` | 困难 | | | +| [0127](https://leetcode-cn.com/problems/word-ladder) | 单词接龙 | | `广度优先搜索`,`哈希表`,`字符串` | 困难 | | | +| [0128](https://leetcode-cn.com/problems/longest-consecutive-sequence) | 最长连续序列 | | `并查集`,`数组`,`哈希表` | 中等 | | | +| [0129](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers) | 求根节点到叶节点数字之和 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0130](https://leetcode-cn.com/problems/surrounded-regions) | 被围绕的区域 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [0131](https://leetcode-cn.com/problems/palindrome-partitioning) | 分割回文串 | | `字符串`,`动态规划`,`回溯` | 中等 | | | +| [0132](https://leetcode-cn.com/problems/palindrome-partitioning-ii) | 分割回文串 II | | `字符串`,`动态规划` | 困难 | | | +| [0133](https://leetcode-cn.com/problems/clone-graph) | 克隆图 | | `深度优先搜索`,`广度优先搜索`,`图`,`哈希表` | 中等 | | | +| [0134](https://leetcode-cn.com/problems/gas-station) | 加油站 | | `贪心`,`数组` | 中等 | | | +| [0135](https://leetcode-cn.com/problems/candy) | 分发糖果 | | `贪心`,`数组` | 困难 | | | +| [0136](https://leetcode-cn.com/problems/single-number) | 只出现一次的数字 | | `位运算`,`数组` | 简单 | | ✅ | +| [0137](https://leetcode-cn.com/problems/single-number-ii) | 只出现一次的数字 II | | `位运算`,`数组` | 中等 | | | +| [0138](https://leetcode-cn.com/problems/copy-list-with-random-pointer) | 复制带随机指针的链表 | | `哈希表`,`链表` | 中等 | | | +| [0139](https://leetcode-cn.com/problems/word-break) | 单词拆分 | | `字典树`,`记忆化搜索`,`哈希表`,`字符串`,`动态规划` | 中等 | | | +| [0140](https://leetcode-cn.com/problems/word-break-ii) | 单词拆分 II | | `字典树`,`记忆化搜索`,`哈希表`,`字符串`,`动态规划`,`回溯` | 困难 | | | +| [0141](https://leetcode-cn.com/problems/linked-list-cycle) | 环形链表 | | `哈希表`,`链表`,`双指针` | 简单 | | | +| [0142](https://leetcode-cn.com/problems/linked-list-cycle-ii) | 环形链表 II | | `哈希表`,`链表`,`双指针` | 中等 | | | +| [0143](https://leetcode-cn.com/problems/reorder-list) | 重排链表 | | `栈`,`递归`,`链表`,`双指针` | 中等 | | | +| [0144](https://leetcode-cn.com/problems/binary-tree-preorder-traversal) | 二叉树的前序遍历 | | `栈`,`树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0145](https://leetcode-cn.com/problems/binary-tree-postorder-traversal) | 二叉树的后序遍历 | | `栈`,`树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0146](https://leetcode-cn.com/problems/lru-cache) | LRU 缓存机制 | | `设计`,`哈希表`,`链表`,`双向链表` | 中等 | | | +| [0147](https://leetcode-cn.com/problems/insertion-sort-list) | 对链表进行插入排序 | | `链表`,`排序` | 中等 | | | +| [0148](https://leetcode-cn.com/problems/sort-list) | 排序链表 | | `链表`,`双指针`,`分治`,`排序`,`归并排序` | 中等 | | | +| [0149](https://leetcode-cn.com/problems/max-points-on-a-line) | 直线上最多的点数 | | `几何`,`哈希表`,`数学` | 困难 | | | +| [0150](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation) | 逆波兰表达式求值 | | `栈`,`数组`,`数学` | 中等 | | | +| [0151](https://leetcode-cn.com/problems/reverse-words-in-a-string) | 翻转字符串里的单词 | | `双指针`,`字符串` | 中等 | | | +| [0152](https://leetcode-cn.com/problems/maximum-product-subarray) | 乘积最大子数组 | | `数组`,`动态规划` | 中等 | | | +| [0153](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array) | 寻找旋转排序数组中的最小值 | | `数组`,`二分查找` | 中等 | | | +| [0154](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii) | 寻找旋转排序数组中的最小值 II | | `数组`,`二分查找` | 困难 | | | +| [0155](https://leetcode-cn.com/problems/min-stack) | 最小栈 | | `栈`,`设计` | 简单 | | | +| [0156](https://leetcode-cn.com/problems/binary-tree-upside-down) | 上下翻转二叉树 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0157](https://leetcode-cn.com/problems/read-n-characters-given-read4) | 用 Read4 读取 N 个字符 | | `字符串`,`交互`,`模拟` | 简单 | 🔒 | | +| [0158](https://leetcode-cn.com/problems/read-n-characters-given-read4-ii-call-multiple-times) | 用 Read4 读取 N 个字符 II | | `字符串`,`交互`,`模拟` | 困难 | 🔒 | | +| [0159](https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters) | 至多包含两个不同字符的最长子串 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | 🔒 | | +| [0160](https://leetcode-cn.com/problems/intersection-of-two-linked-lists) | 相交链表 | | `哈希表`,`链表`,`双指针` | 简单 | | | +| [0161](https://leetcode-cn.com/problems/one-edit-distance) | 相隔为 1 的编辑距离 | | `双指针`,`字符串` | 中等 | 🔒 | | +| [0162](https://leetcode-cn.com/problems/find-peak-element) | 寻找峰值 | | `数组`,`二分查找` | 中等 | | | +| [0163](https://leetcode-cn.com/problems/missing-ranges) | 缺失的区间 | | `数组` | 简单 | 🔒 | | +| [0164](https://leetcode-cn.com/problems/maximum-gap) | 最大间距 | | `数组`,`桶排序`,`基数排序`,`排序` | 困难 | | | +| [0165](https://leetcode-cn.com/problems/compare-version-numbers) | 比较版本号 | | `双指针`,`字符串` | 中等 | | | +| [0166](https://leetcode-cn.com/problems/fraction-to-recurring-decimal) | 分数到小数 | | `哈希表`,`数学`,`字符串` | 中等 | | | +| [0167](https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted) | 两数之和 II - 输入有序数组 | | `数组`,`双指针`,`二分查找` | 简单 | | | +| [0168](https://leetcode-cn.com/problems/excel-sheet-column-title) | Excel表列名称 | | `数学`,`字符串` | 简单 | | | +| [0169](https://leetcode-cn.com/problems/majority-element) | 多数元素 | | `数组`,`哈希表`,`分治`,`计数`,`排序` | 简单 | | | +| [0170](https://leetcode-cn.com/problems/two-sum-iii-data-structure-design) | 两数之和 III - 数据结构设计 | | `设计`,`数组`,`哈希表`,`双指针`,`数据流` | 简单 | 🔒 | | +| [0171](https://leetcode-cn.com/problems/excel-sheet-column-number) | Excel表列序号 | | `数学`,`字符串` | 简单 | | | +| [0172](https://leetcode-cn.com/problems/factorial-trailing-zeroes) | 阶乘后的零 | | `数学` | 简单 | | | +| [0173](https://leetcode-cn.com/problems/binary-search-tree-iterator) | 二叉搜索树迭代器 | | `栈`,`树`,`设计`,`二叉搜索树`,`二叉树`,`迭代器` | 中等 | | | +| [0174](https://leetcode-cn.com/problems/dungeon-game) | 地下城游戏 | | `数组`,`动态规划`,`矩阵` | 困难 | | | +| [0175](https://leetcode-cn.com/problems/combine-two-tables) | 组合两个表 | | `数据库` | 简单 | | | +| [0176](https://leetcode-cn.com/problems/second-highest-salary) | 第二高的薪水 | | `数据库` | 简单 | | | +| [0177](https://leetcode-cn.com/problems/nth-highest-salary) | 第N高的薪水 | | `数据库` | 中等 | | | +| [0178](https://leetcode-cn.com/problems/rank-scores) | 分数排名 | | `数据库` | 中等 | | | +| [0179](https://leetcode-cn.com/problems/largest-number) | 最大数 | | `贪心`,`字符串`,`排序` | 中等 | | | +| [0180](https://leetcode-cn.com/problems/consecutive-numbers) | 连续出现的数字 | | `数据库` | 中等 | | | +| [0181](https://leetcode-cn.com/problems/employees-earning-more-than-their-managers) | 超过经理收入的员工 | | `数据库` | 简单 | | | +| [0182](https://leetcode-cn.com/problems/duplicate-emails) | 查找重复的电子邮箱 | | `数据库` | 简单 | | | +| [0183](https://leetcode-cn.com/problems/customers-who-never-order) | 从不订购的客户 | | `数据库` | 简单 | | | +| [0184](https://leetcode-cn.com/problems/department-highest-salary) | 部门工资最高的员工 | | `数据库` | 中等 | | | +| [0185](https://leetcode-cn.com/problems/department-top-three-salaries) | 部门工资前三高的所有员工 | | `数据库` | 困难 | | | +| [0186](https://leetcode-cn.com/problems/reverse-words-in-a-string-ii) | 翻转字符串里的单词 II | | `双指针`,`字符串` | 中等 | 🔒 | | +| [0187](https://leetcode-cn.com/problems/repeated-dna-sequences) | 重复的DNA序列 | | `位运算`,`哈希表`,`字符串`,`滑动窗口`,`哈希函数`,`滚动哈希` | 中等 | | | +| [0188](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv) | 买卖股票的最佳时机 IV | | `数组`,`动态规划` | 困难 | | | +| [0189](https://leetcode-cn.com/problems/rotate-array) | 旋转数组 | | `数组`,`数学`,`双指针` | 中等 | | | +| [0190](https://leetcode-cn.com/problems/reverse-bits) | 颠倒二进制位 | | `位运算`,`分治` | 简单 | | | +| [0191](https://leetcode-cn.com/problems/number-of-1-bits) | 位1的个数 | | `位运算` | 简单 | | ✅ | +| [0192](https://leetcode-cn.com/problems/word-frequency) | 统计词频 | | | 中等 | | | +| [0193](https://leetcode-cn.com/problems/valid-phone-numbers) | 有效电话号码 | | | 简单 | | | +| [0194](https://leetcode-cn.com/problems/transpose-file) | 转置文件 | | | 中等 | | | +| [0195](https://leetcode-cn.com/problems/tenth-line) | 第十行 | | | 简单 | | | +| [0196](https://leetcode-cn.com/problems/delete-duplicate-emails) | 删除重复的电子邮箱 | | `数据库` | 简单 | | | +| [0197](https://leetcode-cn.com/problems/rising-temperature) | 上升的温度 | | `数据库` | 简单 | | | +| [0198](https://leetcode-cn.com/problems/house-robber) | 打家劫舍 | | `数组`,`动态规划` | 中等 | | | +| [0199](https://leetcode-cn.com/problems/binary-tree-right-side-view) | 二叉树的右视图 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0200](https://leetcode-cn.com/problems/number-of-islands) | 岛屿数量 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [0201](https://leetcode-cn.com/problems/bitwise-and-of-numbers-range) | 数字范围按位与 | | `位运算` | 中等 | | | +| [0202](https://leetcode-cn.com/problems/happy-number) | 快乐数 | | `哈希表`,`数学`,`双指针` | 简单 | | ✅ | +| [0203](https://leetcode-cn.com/problems/remove-linked-list-elements) | 移除链表元素 | | `递归`,`链表` | 简单 | | | +| [0204](https://leetcode-cn.com/problems/count-primes) | 计数质数 | | `数组`,`数学`,`枚举`,`数论` | 简单 | | ✅ | +| [0205](https://leetcode-cn.com/problems/isomorphic-strings) | 同构字符串 | | `哈希表`,`字符串` | 简单 | | | +| [0206](https://leetcode-cn.com/problems/reverse-linked-list) | 反转链表 | | `递归`,`链表` | 简单 | | | +| [0207](https://leetcode-cn.com/problems/course-schedule) | 课程表 | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序` | 中等 | | | +| [0208](https://leetcode-cn.com/problems/implement-trie-prefix-tree) | 实现 Trie (前缀树) | | `设计`,`字典树`,`哈希表`,`字符串` | 中等 | | | +| [0209](https://leetcode-cn.com/problems/minimum-size-subarray-sum) | 长度最小的子数组 | | `数组`,`二分查找`,`前缀和`,`滑动窗口` | 中等 | | | +| [0210](https://leetcode-cn.com/problems/course-schedule-ii) | 课程表 II | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序` | 中等 | | | +| [0211](https://leetcode-cn.com/problems/design-add-and-search-words-data-structure) | 添加与搜索单词 - 数据结构设计 | | `深度优先搜索`,`设计`,`字典树`,`字符串` | 中等 | | | +| [0212](https://leetcode-cn.com/problems/word-search-ii) | 单词搜索 II | | `字典树`,`数组`,`字符串`,`回溯`,`矩阵` | 困难 | | | +| [0213](https://leetcode-cn.com/problems/house-robber-ii) | 打家劫舍 II | | `数组`,`动态规划` | 中等 | | | +| [0214](https://leetcode-cn.com/problems/shortest-palindrome) | 最短回文串 | | `字符串`,`字符串匹配`,`哈希函数`,`滚动哈希` | 困难 | | | +| [0215](https://leetcode-cn.com/problems/kth-largest-element-in-an-array) | 数组中的第K个最大元素 | | `数组`,`分治`,`快速选择`,`排序`,`堆(优先队列)` | 中等 | | | +| [0216](https://leetcode-cn.com/problems/combination-sum-iii) | 组合总和 III | | `数组`,`回溯` | 中等 | | | +| [0217](https://leetcode-cn.com/problems/contains-duplicate) | 存在重复元素 | | `数组`,`哈希表`,`排序` | 简单 | | | +| [0218](https://leetcode-cn.com/problems/the-skyline-problem) | 天际线问题 | | `树状数组`,`线段树`,`数组`,`分治`,`有序集合`,`扫描线`,`堆(优先队列)` | 困难 | | | +| [0219](https://leetcode-cn.com/problems/contains-duplicate-ii) | 存在重复元素 II | | `数组`,`哈希表`,`滑动窗口` | 简单 | | | +| [0220](https://leetcode-cn.com/problems/contains-duplicate-iii) | 存在重复元素 III | | `数组`,`桶排序`,`有序集合`,`排序`,`滑动窗口` | 中等 | | | +| [0221](https://leetcode-cn.com/problems/maximal-square) | 最大正方形 | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [0222](https://leetcode-cn.com/problems/count-complete-tree-nodes) | 完全二叉树的节点个数 | | `树`,`深度优先搜索`,`二分查找`,`二叉树` | 中等 | | | +| [0223](https://leetcode-cn.com/problems/rectangle-area) | 矩形面积 | | `几何`,`数学` | 中等 | | | +| [0224](https://leetcode-cn.com/problems/basic-calculator) | 基本计算器 | | `栈`,`递归`,`数学`,`字符串` | 困难 | | | +| [0225](https://leetcode-cn.com/problems/implement-stack-using-queues) | 用队列实现栈 | | `栈`,`设计`,`队列` | 简单 | | | +| [0226](https://leetcode-cn.com/problems/invert-binary-tree) | 翻转二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0227](https://leetcode-cn.com/problems/basic-calculator-ii) | 基本计算器 II | | `栈`,`数学`,`字符串` | 中等 | | | +| [0228](https://leetcode-cn.com/problems/summary-ranges) | 汇总区间 | | `数组` | 简单 | | | +| [0229](https://leetcode-cn.com/problems/majority-element-ii) | 求众数 II | | `数组`,`哈希表`,`计数`,`排序` | 中等 | | | +| [0230](https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst) | 二叉搜索树中第K小的元素 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0231](https://leetcode-cn.com/problems/power-of-two) | 2 的幂 | | `位运算`,`递归`,`数学` | 简单 | | | +| [0232](https://leetcode-cn.com/problems/implement-queue-using-stacks) | 用栈实现队列 | | `栈`,`设计`,`队列` | 简单 | | | +| [0233](https://leetcode-cn.com/problems/number-of-digit-one) | 数字 1 的个数 | | `递归`,`数学`,`动态规划` | 困难 | | | +| [0234](https://leetcode-cn.com/problems/palindrome-linked-list) | 回文链表 | | `栈`,`递归`,`链表`,`双指针` | 简单 | | | +| [0235](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree) | 二叉搜索树的最近公共祖先 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0236](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree) | 二叉树的最近公共祖先 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0237](https://leetcode-cn.com/problems/delete-node-in-a-linked-list) | 删除链表中的节点 | | `链表` | 简单 | | | +| [0238](https://leetcode-cn.com/problems/product-of-array-except-self) | 除自身以外数组的乘积 | | `数组`,`前缀和` | 中等 | | | +| [0239](https://leetcode-cn.com/problems/sliding-window-maximum) | 滑动窗口最大值 | | `队列`,`数组`,`滑动窗口`,`单调队列`,`堆(优先队列)` | 困难 | | | +| [0240](https://leetcode-cn.com/problems/search-a-2d-matrix-ii) | 搜索二维矩阵 II | | `数组`,`二分查找`,`分治`,`矩阵` | 中等 | | | +| [0241](https://leetcode-cn.com/problems/different-ways-to-add-parentheses) | 为运算表达式设计优先级 | | `递归`,`记忆化搜索`,`数学`,`字符串`,`动态规划` | 中等 | | | +| [0242](https://leetcode-cn.com/problems/valid-anagram) | 有效的字母异位词 | | `哈希表`,`字符串`,`排序` | 简单 | | | +| [0243](https://leetcode-cn.com/problems/shortest-word-distance) | 最短单词距离 | | `数组`,`字符串` | 简单 | 🔒 | | +| [0244](https://leetcode-cn.com/problems/shortest-word-distance-ii) | 最短单词距离 II | | `设计`,`数组`,`哈希表`,`双指针`,`字符串` | 中等 | 🔒 | | +| [0245](https://leetcode-cn.com/problems/shortest-word-distance-iii) | 最短单词距离 III | | `数组`,`字符串` | 中等 | 🔒 | | +| [0246](https://leetcode-cn.com/problems/strobogrammatic-number) | 中心对称数 | | `哈希表`,`双指针`,`字符串` | 简单 | 🔒 | | +| [0247](https://leetcode-cn.com/problems/strobogrammatic-number-ii) | 中心对称数 II | | `递归`,`数组`,`字符串` | 中等 | 🔒 | | +| [0248](https://leetcode-cn.com/problems/strobogrammatic-number-iii) | 中心对称数 III | | `递归`,`数组`,`字符串` | 困难 | 🔒 | | +| [0249](https://leetcode-cn.com/problems/group-shifted-strings) | 移位字符串分组 | | `数组`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [0250](https://leetcode-cn.com/problems/count-univalue-subtrees) | 统计同值子树 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0251](https://leetcode-cn.com/problems/flatten-2d-vector) | 展开二维向量 | | `设计`,`数组`,`双指针`,`迭代器` | 中等 | 🔒 | | +| [0252](https://leetcode-cn.com/problems/meeting-rooms) | 会议室 | | `数组`,`排序` | 简单 | 🔒 | | +| [0253](https://leetcode-cn.com/problems/meeting-rooms-ii) | 会议室 II | | `贪心`,`数组`,`双指针`,`排序`,`堆(优先队列)` | 中等 | 🔒 | | +| [0254](https://leetcode-cn.com/problems/factor-combinations) | 因子的组合 | | `数组`,`回溯` | 中等 | 🔒 | | +| [0255](https://leetcode-cn.com/problems/verify-preorder-sequence-in-binary-search-tree) | 验证前序遍历序列二叉搜索树 | | `栈`,`树`,`二叉搜索树`,`递归`,`二叉树`,`单调栈` | 中等 | 🔒 | | +| [0256](https://leetcode-cn.com/problems/paint-house) | 粉刷房子 | | `数组`,`动态规划` | 中等 | 🔒 | | +| [0257](https://leetcode-cn.com/problems/binary-tree-paths) | 二叉树的所有路径 | | `树`,`深度优先搜索`,`字符串`,`二叉树` | 简单 | | | +| [0258](https://leetcode-cn.com/problems/add-digits) | 各位相加 | | `数学`,`数论`,`模拟` | 简单 | | | +| [0259](https://leetcode-cn.com/problems/3sum-smaller) | 较小的三数之和 | | `数组`,`双指针`,`二分查找`,`排序` | 中等 | 🔒 | | +| [0260](https://leetcode-cn.com/problems/single-number-iii) | 只出现一次的数字 III | | `位运算`,`数组` | 中等 | | | +| [0261](https://leetcode-cn.com/problems/graph-valid-tree) | 以图判树 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | 🔒 | | +| [0262](https://leetcode-cn.com/problems/trips-and-users) | 行程和用户 | | `数据库` | 困难 | | | +| [0263](https://leetcode-cn.com/problems/ugly-number) | 丑数 | | `数学` | 简单 | | | +| [0264](https://leetcode-cn.com/problems/ugly-number-ii) | 丑数 II | | `哈希表`,`数学`,`动态规划`,`堆(优先队列)` | 中等 | | | +| [0265](https://leetcode-cn.com/problems/paint-house-ii) | 粉刷房子 II | | `数组`,`动态规划` | 困难 | 🔒 | | +| [0266](https://leetcode-cn.com/problems/palindrome-permutation) | 回文排列 | | `位运算`,`哈希表`,`字符串` | 简单 | 🔒 | | +| [0267](https://leetcode-cn.com/problems/palindrome-permutation-ii) | 回文排列 II | | `哈希表`,`字符串`,`回溯` | 中等 | 🔒 | | +| [0268](https://leetcode-cn.com/problems/missing-number) | 丢失的数字 | | `位运算`,`数组`,`哈希表`,`数学`,`排序` | 简单 | | | +| [0269](https://leetcode-cn.com/problems/alien-dictionary) | 火星词典 | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序`,`数组`,`字符串` | 困难 | 🔒 | | +| [0270](https://leetcode-cn.com/problems/closest-binary-search-tree-value) | 最接近的二叉搜索树值 | | `树`,`深度优先搜索`,`二叉搜索树`,`二分查找`,`二叉树` | 简单 | 🔒 | | +| [0271](https://leetcode-cn.com/problems/encode-and-decode-strings) | 字符串的编码与解码 | | `设计`,`数组`,`字符串` | 中等 | 🔒 | | +| [0272](https://leetcode-cn.com/problems/closest-binary-search-tree-value-ii) | 最接近的二叉搜索树值 II | | `栈`,`树`,`深度优先搜索`,`二叉搜索树`,`双指针`,`二叉树`,`堆(优先队列)` | 困难 | 🔒 | | +| [0273](https://leetcode-cn.com/problems/integer-to-english-words) | 整数转换英文表示 | | `递归`,`数学`,`字符串` | 困难 | | | +| [0274](https://leetcode-cn.com/problems/h-index) | H 指数 | | `数组`,`计数排序`,`排序` | 中等 | | | +| [0275](https://leetcode-cn.com/problems/h-index-ii) | H 指数 II | | `数组`,`二分查找` | 中等 | | | +| [0276](https://leetcode-cn.com/problems/paint-fence) | 栅栏涂色 | | `动态规划` | 中等 | 🔒 | | +| [0277](https://leetcode-cn.com/problems/find-the-celebrity) | 搜寻名人 | | `贪心`,`图`,`双指针`,`交互` | 中等 | 🔒 | | +| [0278](https://leetcode-cn.com/problems/first-bad-version) | 第一个错误的版本 | | `二分查找`,`交互` | 简单 | | | +| [0279](https://leetcode-cn.com/problems/perfect-squares) | 完全平方数 | | `广度优先搜索`,`数学`,`动态规划` | 中等 | | | +| [0280](https://leetcode-cn.com/problems/wiggle-sort) | 摆动排序 | | `贪心`,`数组`,`排序` | 中等 | 🔒 | | +| [0281](https://leetcode-cn.com/problems/zigzag-iterator) | 锯齿迭代器 | | `设计`,`队列`,`数组`,`迭代器` | 中等 | 🔒 | | +| [0282](https://leetcode-cn.com/problems/expression-add-operators) | 给表达式添加运算符 | | `数学`,`字符串`,`回溯` | 困难 | | | +| [0283](https://leetcode-cn.com/problems/move-zeroes) | 移动零 | | `数组`,`双指针` | 简单 | | | +| [0284](https://leetcode-cn.com/problems/peeking-iterator) | 顶端迭代器 | | `设计`,`数组`,`迭代器` | 中等 | | | +| [0285](https://leetcode-cn.com/problems/inorder-successor-in-bst) | 二叉搜索树中的中序后继 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | 🔒 | | +| [0286](https://leetcode-cn.com/problems/walls-and-gates) | 墙与门 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | 🔒 | | +| [0287](https://leetcode-cn.com/problems/find-the-duplicate-number) | 寻找重复数 | | `位运算`,`数组`,`双指针`,`二分查找` | 中等 | | | +| [0288](https://leetcode-cn.com/problems/unique-word-abbreviation) | 单词的唯一缩写 | | `设计`,`数组`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [0289](https://leetcode-cn.com/problems/game-of-life) | 生命游戏 | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [0290](https://leetcode-cn.com/problems/word-pattern) | 单词规律 | | `哈希表`,`字符串` | 简单 | | | +| [0291](https://leetcode-cn.com/problems/word-pattern-ii) | 单词规律 II | | `哈希表`,`字符串`,`回溯` | 中等 | 🔒 | | +| [0292](https://leetcode-cn.com/problems/nim-game) | Nim 游戏 | | `脑筋急转弯`,`数学`,`博弈` | 简单 | | | +| [0293](https://leetcode-cn.com/problems/flip-game) | 翻转游戏 | | `字符串` | 简单 | 🔒 | | +| [0294](https://leetcode-cn.com/problems/flip-game-ii) | 翻转游戏 II | | `记忆化搜索`,`数学`,`动态规划`,`回溯`,`博弈` | 中等 | 🔒 | | +| [0295](https://leetcode-cn.com/problems/find-median-from-data-stream) | 数据流的中位数 | | `设计`,`双指针`,`数据流`,`排序`,`堆(优先队列)` | 困难 | | | +| [0296](https://leetcode-cn.com/problems/best-meeting-point) | 最佳的碰头地点 | | `数组`,`数学`,`矩阵`,`排序` | 困难 | 🔒 | | +| [0297](https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree) | 二叉树的序列化与反序列化 | | `树`,`深度优先搜索`,`广度优先搜索`,`设计`,`字符串`,`二叉树` | 困难 | | | +| [0298](https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence) | 二叉树最长连续序列 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0299](https://leetcode-cn.com/problems/bulls-and-cows) | 猜数字游戏 | | `哈希表`,`字符串`,`计数` | 中等 | | | +| [0300](https://leetcode-cn.com/problems/longest-increasing-subsequence) | 最长递增子序列 | | `数组`,`二分查找`,`动态规划` | 中等 | | | +| [0301](https://leetcode-cn.com/problems/remove-invalid-parentheses) | 删除无效的括号 | | `广度优先搜索`,`字符串`,`回溯` | 困难 | | | +| [0302](https://leetcode-cn.com/problems/smallest-rectangle-enclosing-black-pixels) | 包含全部黑色像素的最小矩形 | | `深度优先搜索`,`广度优先搜索`,`数组`,`二分查找`,`矩阵` | 困难 | 🔒 | | +| [0303](https://leetcode-cn.com/problems/range-sum-query-immutable) | 区域和检索 - 数组不可变 | | `设计`,`数组`,`前缀和` | 简单 | | | +| [0304](https://leetcode-cn.com/problems/range-sum-query-2d-immutable) | 二维区域和检索 - 矩阵不可变 | | `设计`,`数组`,`矩阵`,`前缀和` | 中等 | | | +| [0305](https://leetcode-cn.com/problems/number-of-islands-ii) | 岛屿数量 II | | `并查集`,`数组` | 困难 | 🔒 | | +| [0306](https://leetcode-cn.com/problems/additive-number) | 累加数 | | `字符串`,`回溯` | 中等 | | | +| [0307](https://leetcode-cn.com/problems/range-sum-query-mutable) | 区域和检索 - 数组可修改 | | `设计`,`树状数组`,`线段树`,`数组` | 中等 | | | +| [0308](https://leetcode-cn.com/problems/range-sum-query-2d-mutable) | 二维区域和检索 - 可变 | | `设计`,`树状数组`,`线段树`,`数组`,`矩阵` | 困难 | 🔒 | | +| [0309](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) | 最佳买卖股票时机含冷冻期 | | `数组`,`动态规划` | 中等 | | | +| [0310](https://leetcode-cn.com/problems/minimum-height-trees) | 最小高度树 | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序` | 中等 | | | +| [0311](https://leetcode-cn.com/problems/sparse-matrix-multiplication) | 稀疏矩阵的乘法 | | `数组`,`哈希表`,`矩阵` | 中等 | 🔒 | | +| [0312](https://leetcode-cn.com/problems/burst-balloons) | 戳气球 | | `数组`,`动态规划` | 困难 | | | +| [0313](https://leetcode-cn.com/problems/super-ugly-number) | 超级丑数 | | `数组`,`哈希表`,`数学`,`动态规划`,`堆(优先队列)` | 中等 | | | +| [0314](https://leetcode-cn.com/problems/binary-tree-vertical-order-traversal) | 二叉树的垂直遍历 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | 🔒 | | +| [0315](https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self) | 计算右侧小于当前元素的个数 | | `树状数组`,`线段树`,`数组`,`二分查找`,`分治`,`有序集合`,`归并排序` | 困难 | | | +| [0316](https://leetcode-cn.com/problems/remove-duplicate-letters) | 去除重复字母 | | `栈`,`贪心`,`字符串`,`单调栈` | 中等 | | | +| [0317](https://leetcode-cn.com/problems/shortest-distance-from-all-buildings) | 离建筑物最近的距离 | | `广度优先搜索`,`数组`,`矩阵` | 困难 | 🔒 | | +| [0318](https://leetcode-cn.com/problems/maximum-product-of-word-lengths) | 最大单词长度乘积 | | `位运算`,`数组`,`字符串` | 中等 | | | +| [0319](https://leetcode-cn.com/problems/bulb-switcher) | 灯泡开关 | | `脑筋急转弯`,`数学` | 中等 | | | +| [0320](https://leetcode-cn.com/problems/generalized-abbreviation) | 列举单词的全部缩写 | | `位运算`,`字符串`,`回溯` | 中等 | 🔒 | | +| [0321](https://leetcode-cn.com/problems/create-maximum-number) | 拼接最大数 | | `栈`,`贪心`,`单调栈` | 困难 | | | +| [0322](https://leetcode-cn.com/problems/coin-change) | 零钱兑换 | | `广度优先搜索`,`数组`,`动态规划` | 中等 | | | +| [0323](https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph) | 无向图中连通分量的数目 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | 🔒 | | +| [0324](https://leetcode-cn.com/problems/wiggle-sort-ii) | 摆动排序 II | | `数组`,`分治`,`快速选择`,`排序` | 中等 | | | +| [0325](https://leetcode-cn.com/problems/maximum-size-subarray-sum-equals-k) | 和等于 k 的最长子数组长度 | | `数组`,`哈希表` | 中等 | 🔒 | | +| [0326](https://leetcode-cn.com/problems/power-of-three) | 3的幂 | | `递归`,`数学` | 简单 | | | +| [0327](https://leetcode-cn.com/problems/count-of-range-sum) | 区间和的个数 | | `树状数组`,`线段树`,`数组`,`二分查找`,`分治`,`有序集合`,`归并排序` | 困难 | | | +| [0328](https://leetcode-cn.com/problems/odd-even-linked-list) | 奇偶链表 | | `链表` | 中等 | | | +| [0329](https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix) | 矩阵中的最长递增路径 | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序`,`记忆化搜索`,`动态规划` | 困难 | | | +| [0330](https://leetcode-cn.com/problems/patching-array) | 按要求补齐数组 | | `贪心`,`数组` | 困难 | | | +| [0331](https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree) | 验证二叉树的前序序列化 | | `栈`,`树`,`字符串`,`二叉树` | 中等 | | | +| [0332](https://leetcode-cn.com/problems/reconstruct-itinerary) | 重新安排行程 | | `深度优先搜索`,`图`,`欧拉回路` | 中等 | | | +| [0333](https://leetcode-cn.com/problems/largest-bst-subtree) | 最大 BST 子树 | | `树`,`深度优先搜索`,`二叉搜索树`,`动态规划`,`二叉树` | 中等 | 🔒 | | +| [0334](https://leetcode-cn.com/problems/increasing-triplet-subsequence) | 递增的三元子序列 | | `贪心`,`数组` | 中等 | | | +| [0335](https://leetcode-cn.com/problems/self-crossing) | 路径交叉 | | `几何`,`数组`,`数学` | 困难 | | | +| [0336](https://leetcode-cn.com/problems/palindrome-pairs) | 回文对 | | `字典树`,`数组`,`哈希表`,`字符串` | 困难 | | | +| [0337](https://leetcode-cn.com/problems/house-robber-iii) | 打家劫舍 III | | `树`,`深度优先搜索`,`动态规划`,`二叉树` | 中等 | | | +| [0338](https://leetcode-cn.com/problems/counting-bits) | 比特位计数 | | `位运算`,`动态规划` | 简单 | | | +| [0339](https://leetcode-cn.com/problems/nested-list-weight-sum) | 嵌套列表权重和 | | `深度优先搜索`,`广度优先搜索` | 中等 | 🔒 | | +| [0340](https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters) | 至多包含 K 个不同字符的最长子串 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | 🔒 | | +| [0341](https://leetcode-cn.com/problems/flatten-nested-list-iterator) | 扁平化嵌套列表迭代器 | | `栈`,`树`,`深度优先搜索`,`设计`,`队列`,`迭代器` | 中等 | | | +| [0342](https://leetcode-cn.com/problems/power-of-four) | 4的幂 | | `位运算`,`递归`,`数学` | 简单 | | | +| [0343](https://leetcode-cn.com/problems/integer-break) | 整数拆分 | | `数学`,`动态规划` | 中等 | | | +| [0344](https://leetcode-cn.com/problems/reverse-string) | 反转字符串 | | `递归`,`双指针`,`字符串` | 简单 | | | +| [0345](https://leetcode-cn.com/problems/reverse-vowels-of-a-string) | 反转字符串中的元音字母 | | `双指针`,`字符串` | 简单 | | ✅ | +| [0346](https://leetcode-cn.com/problems/moving-average-from-data-stream) | 数据流中的移动平均值 | | `设计`,`队列`,`数组`,`数据流` | 简单 | 🔒 | | +| [0347](https://leetcode-cn.com/problems/top-k-frequent-elements) | 前 K 个高频元素 | | `数组`,`哈希表`,`分治`,`桶排序`,`计数`,`快速选择`,`排序`,`堆(优先队列)` | 中等 | | | +| [0348](https://leetcode-cn.com/problems/design-tic-tac-toe) | 设计井字棋 | | `设计`,`数组`,`哈希表`,`矩阵` | 中等 | 🔒 | | +| [0349](https://leetcode-cn.com/problems/intersection-of-two-arrays) | 两个数组的交集 | | `数组`,`哈希表`,`双指针`,`二分查找`,`排序` | 简单 | | | +| [0350](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii) | 两个数组的交集 II | | `数组`,`哈希表`,`双指针`,`二分查找`,`排序` | 简单 | | | +| [0351](https://leetcode-cn.com/problems/android-unlock-patterns) | 安卓系统手势解锁 | | `动态规划`,`回溯` | 中等 | 🔒 | | +| [0352](https://leetcode-cn.com/problems/data-stream-as-disjoint-intervals) | 将数据流变为多个不相交区间 | | `设计`,`二分查找`,`有序集合` | 困难 | | | +| [0353](https://leetcode-cn.com/problems/design-snake-game) | 贪吃蛇 | | `设计`,`队列`,`数组`,`矩阵` | 中等 | 🔒 | | +| [0354](https://leetcode-cn.com/problems/russian-doll-envelopes) | 俄罗斯套娃信封问题 | | `数组`,`二分查找`,`动态规划`,`排序` | 困难 | | | +| [0355](https://leetcode-cn.com/problems/design-twitter) | 设计推特 | | `设计`,`哈希表`,`链表`,`堆(优先队列)` | 中等 | | | +| [0356](https://leetcode-cn.com/problems/line-reflection) | 直线镜像 | | `数组`,`哈希表`,`数学` | 中等 | 🔒 | | +| [0357](https://leetcode-cn.com/problems/count-numbers-with-unique-digits) | 计算各个位数不同的数字个数 | | `数学`,`动态规划`,`回溯` | 中等 | | | +| [0358](https://leetcode-cn.com/problems/rearrange-string-k-distance-apart) | K 距离间隔重排字符串 | | `贪心`,`哈希表`,`字符串`,`计数`,`排序`,`堆(优先队列)` | 困难 | 🔒 | | +| [0359](https://leetcode-cn.com/problems/logger-rate-limiter) | 日志速率限制器 | | `设计`,`哈希表` | 简单 | 🔒 | | +| [0360](https://leetcode-cn.com/problems/sort-transformed-array) | 有序转化数组 | | `数组`,`数学`,`双指针`,`排序` | 中等 | 🔒 | | +| [0361](https://leetcode-cn.com/problems/bomb-enemy) | 轰炸敌人 | | `数组`,`动态规划`,`矩阵` | 中等 | 🔒 | | +| [0362](https://leetcode-cn.com/problems/design-hit-counter) | 敲击计数器 | | `设计`,`队列`,`数组`,`哈希表`,`二分查找` | 中等 | 🔒 | | +| [0363](https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k) | 矩形区域不超过 K 的最大数值和 | | `数组`,`二分查找`,`动态规划`,`矩阵`,`有序集合` | 困难 | | | +| [0364](https://leetcode-cn.com/problems/nested-list-weight-sum-ii) | 加权嵌套序列和 II | | `栈`,`深度优先搜索`,`广度优先搜索` | 中等 | 🔒 | | +| [0365](https://leetcode-cn.com/problems/water-and-jug-problem) | 水壶问题 | | `深度优先搜索`,`广度优先搜索`,`数学` | 中等 | | | +| [0366](https://leetcode-cn.com/problems/find-leaves-of-binary-tree) | 寻找二叉树的叶子节点 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0367](https://leetcode-cn.com/problems/valid-perfect-square) | 有效的完全平方数 | | `数学`,`二分查找` | 简单 | | | +| [0368](https://leetcode-cn.com/problems/largest-divisible-subset) | 最大整除子集 | | `数组`,`数学`,`动态规划`,`排序` | 中等 | | | +| [0369](https://leetcode-cn.com/problems/plus-one-linked-list) | 给单链表加一 | | `链表`,`数学` | 中等 | 🔒 | | +| [0370](https://leetcode-cn.com/problems/range-addition) | 区间加法 | | `数组`,`前缀和` | 中等 | 🔒 | | +| [0371](https://leetcode-cn.com/problems/sum-of-two-integers) | 两整数之和 | | `位运算`,`数学` | 中等 | | | +| [0372](https://leetcode-cn.com/problems/super-pow) | 超级次方 | | `数学`,`分治` | 中等 | | | +| [0373](https://leetcode-cn.com/problems/find-k-pairs-with-smallest-sums) | 查找和最小的K对数字 | | `数组`,`堆(优先队列)` | 中等 | | | +| [0374](https://leetcode-cn.com/problems/guess-number-higher-or-lower) | 猜数字大小 | | `二分查找`,`交互` | 简单 | | | +| [0375](https://leetcode-cn.com/problems/guess-number-higher-or-lower-ii) | 猜数字大小 II | | `数学`,`动态规划`,`博弈` | 中等 | | | +| [0376](https://leetcode-cn.com/problems/wiggle-subsequence) | 摆动序列 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [0377](https://leetcode-cn.com/problems/combination-sum-iv) | 组合总和 Ⅳ | | `数组`,`动态规划` | 中等 | | | +| [0378](https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix) | 有序矩阵中第 K 小的元素 | | `数组`,`二分查找`,`矩阵`,`排序`,`堆(优先队列)` | 中等 | | | +| [0379](https://leetcode-cn.com/problems/design-phone-directory) | 电话目录管理系统 | | `设计`,`队列`,`数组`,`哈希表`,`链表` | 中等 | 🔒 | | +| [0380](https://leetcode-cn.com/problems/insert-delete-getrandom-o1) | O(1) 时间插入、删除和获取随机元素 | | `设计`,`数组`,`哈希表`,`数学`,`随机化` | 中等 | | | +| [0381](https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed) | O(1) 时间插入、删除和获取随机元素 - 允许重复 | | `设计`,`数组`,`哈希表`,`数学`,`随机化` | 困难 | | | +| [0382](https://leetcode-cn.com/problems/linked-list-random-node) | 链表随机节点 | | `水塘抽样`,`链表`,`数学`,`随机化` | 中等 | | | +| [0383](https://leetcode-cn.com/problems/ransom-note) | 赎金信 | | `哈希表`,`字符串`,`计数` | 简单 | | | +| [0384](https://leetcode-cn.com/problems/shuffle-an-array) | 打乱数组 | | `数组`,`数学`,`随机化` | 中等 | | | +| [0385](https://leetcode-cn.com/problems/mini-parser) | 迷你语法分析器 | | `栈`,`深度优先搜索`,`字符串` | 中等 | | | +| [0386](https://leetcode-cn.com/problems/lexicographical-numbers) | 字典序排数 | | `深度优先搜索`,`字典树` | 中等 | | | +| [0387](https://leetcode-cn.com/problems/first-unique-character-in-a-string) | 字符串中的第一个唯一字符 | | `队列`,`哈希表`,`字符串`,`计数` | 简单 | | | +| [0388](https://leetcode-cn.com/problems/longest-absolute-file-path) | 文件的最长绝对路径 | | `栈`,`深度优先搜索`,`字符串` | 中等 | | | +| [0389](https://leetcode-cn.com/problems/find-the-difference) | 找不同 | | `位运算`,`哈希表`,`字符串`,`排序` | 简单 | | | +| [0390](https://leetcode-cn.com/problems/elimination-game) | 消除游戏 | | `数学` | 中等 | | | +| [0391](https://leetcode-cn.com/problems/perfect-rectangle) | 完美矩形 | | `数组`,`扫描线` | 困难 | | | +| [0392](https://leetcode-cn.com/problems/is-subsequence) | 判断子序列 | | `双指针`,`字符串`,`动态规划` | 简单 | | | +| [0393](https://leetcode-cn.com/problems/utf-8-validation) | UTF-8 编码验证 | | `位运算`,`数组` | 中等 | | | +| [0394](https://leetcode-cn.com/problems/decode-string) | 字符串解码 | | `栈`,`递归`,`字符串` | 中等 | | | +| [0395](https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters) | 至少有 K 个重复字符的最长子串 | | `哈希表`,`字符串`,`分治`,`滑动窗口` | 中等 | | | +| [0396](https://leetcode-cn.com/problems/rotate-function) | 旋转函数 | | `数学`,`动态规划` | 中等 | | | +| [0397](https://leetcode-cn.com/problems/integer-replacement) | 整数替换 | | `位运算`,`记忆化搜索`,`动态规划` | 中等 | | | +| [0398](https://leetcode-cn.com/problems/random-pick-index) | 随机数索引 | | `水塘抽样`,`哈希表`,`数学`,`随机化` | 中等 | | | +| [0399](https://leetcode-cn.com/problems/evaluate-division) | 除法求值 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图`,`数组`,`最短路` | 中等 | | | +| [0400](https://leetcode-cn.com/problems/nth-digit) | 第 N 位数字 | | `数学`,`二分查找` | 中等 | | | +| [0401](https://leetcode-cn.com/problems/binary-watch) | 二进制手表 | | `位运算`,`回溯` | 简单 | | | +| [0402](https://leetcode-cn.com/problems/remove-k-digits) | 移掉 K 位数字 | | `栈`,`贪心`,`字符串`,`单调栈` | 中等 | | | +| [0403](https://leetcode-cn.com/problems/frog-jump) | 青蛙过河 | | `数组`,`动态规划` | 困难 | | | +| [0404](https://leetcode-cn.com/problems/sum-of-left-leaves) | 左叶子之和 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0405](https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal) | 数字转换为十六进制数 | | `位运算`,`数学` | 简单 | | | +| [0406](https://leetcode-cn.com/problems/queue-reconstruction-by-height) | 根据身高重建队列 | | `贪心`,`数组`,`排序` | 中等 | | | +| [0407](https://leetcode-cn.com/problems/trapping-rain-water-ii) | 接雨水 II | | `广度优先搜索`,`数组`,`矩阵`,`堆(优先队列)` | 困难 | | | +| [0408](https://leetcode-cn.com/problems/valid-word-abbreviation) | 有效单词缩写 | | `双指针`,`字符串` | 简单 | 🔒 | | +| [0409](https://leetcode-cn.com/problems/longest-palindrome) | 最长回文串 | | `贪心`,`哈希表`,`字符串` | 简单 | | | +| [0410](https://leetcode-cn.com/problems/split-array-largest-sum) | 分割数组的最大值 | | `贪心`,`数组`,`二分查找`,`动态规划` | 困难 | | | +| [0411](https://leetcode-cn.com/problems/minimum-unique-word-abbreviation) | 最短独占单词缩写 | | `位运算`,`字符串`,`回溯` | 困难 | 🔒 | | +| [0412](https://leetcode-cn.com/problems/fizz-buzz) | Fizz Buzz | | `数学`,`字符串`,`模拟` | 简单 | | | +| [0413](https://leetcode-cn.com/problems/arithmetic-slices) | 等差数列划分 | | `数组`,`动态规划` | 中等 | | | +| [0414](https://leetcode-cn.com/problems/third-maximum-number) | 第三大的数 | | `数组`,`排序` | 简单 | | | +| [0415](https://leetcode-cn.com/problems/add-strings) | 字符串相加 | | `数学`,`字符串`,`模拟` | 简单 | | | +| [0416](https://leetcode-cn.com/problems/partition-equal-subset-sum) | 分割等和子集 | | `数组`,`动态规划` | 中等 | | | +| [0417](https://leetcode-cn.com/problems/pacific-atlantic-water-flow) | 太平洋大西洋水流问题 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [0418](https://leetcode-cn.com/problems/sentence-screen-fitting) | 屏幕可显示句子的数量 | | `字符串`,`动态规划` | 中等 | 🔒 | | +| [0419](https://leetcode-cn.com/problems/battleships-in-a-board) | 甲板上的战舰 | | `深度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [0420](https://leetcode-cn.com/problems/strong-password-checker) | 强密码检验器 | | `贪心`,`字符串`,`堆(优先队列)` | 困难 | | | +| [0421](https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array) | 数组中两个数的最大异或值 | | `位运算`,`字典树`,`数组`,`哈希表` | 中等 | | | +| [0422](https://leetcode-cn.com/problems/valid-word-square) | 有效的单词方块 | | `数组`,`矩阵` | 简单 | 🔒 | | +| [0423](https://leetcode-cn.com/problems/reconstruct-original-digits-from-english) | 从英文中重建数字 | | `哈希表`,`数学`,`字符串` | 中等 | | | +| [0424](https://leetcode-cn.com/problems/longest-repeating-character-replacement) | 替换后的最长重复字符 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | | | +| [0425](https://leetcode-cn.com/problems/word-squares) | 单词方块 | | `字典树`,`数组`,`字符串`,`回溯` | 困难 | 🔒 | | +| [0426](https://leetcode-cn.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list) | 将二叉搜索树转化为排序的双向链表 | | `栈`,`树`,`深度优先搜索`,`二叉搜索树`,`链表`,`二叉树`,`双向链表` | 中等 | 🔒 | | +| [0427](https://leetcode-cn.com/problems/construct-quad-tree) | 建立四叉树 | | `树`,`数组`,`分治`,`矩阵` | 中等 | | | +| [0428](https://leetcode-cn.com/problems/serialize-and-deserialize-n-ary-tree) | 序列化和反序列化 N 叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`字符串` | 困难 | 🔒 | | +| [0429](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal) | N 叉树的层序遍历 | | `树`,`广度优先搜索` | 中等 | | | +| [0430](https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list) | 扁平化多级双向链表 | | `深度优先搜索`,`链表`,`双向链表` | 中等 | | | +| [0431](https://leetcode-cn.com/problems/encode-n-ary-tree-to-binary-tree) | 将 N 叉树编码为二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`设计`,`二叉树` | 困难 | 🔒 | | +| [0432](https://leetcode-cn.com/problems/all-oone-data-structure) | 全 O(1) 的数据结构 | | `设计`,`哈希表`,`链表`,`双向链表` | 困难 | | | +| [0433](https://leetcode-cn.com/problems/minimum-genetic-mutation) | 最小基因变化 | | `广度优先搜索`,`哈希表`,`字符串` | 中等 | | | +| [0434](https://leetcode-cn.com/problems/number-of-segments-in-a-string) | 字符串中的单词数 | | `字符串` | 简单 | | | +| [0435](https://leetcode-cn.com/problems/non-overlapping-intervals) | 无重叠区间 | | `贪心`,`数组`,`动态规划`,`排序` | 中等 | | | +| [0436](https://leetcode-cn.com/problems/find-right-interval) | 寻找右区间 | | `数组`,`二分查找`,`排序` | 中等 | | | +| [0437](https://leetcode-cn.com/problems/path-sum-iii) | 路径总和 III | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0438](https://leetcode-cn.com/problems/find-all-anagrams-in-a-string) | 找到字符串中所有字母异位词 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | | | +| [0439](https://leetcode-cn.com/problems/ternary-expression-parser) | 三元表达式解析器 | | `栈`,`递归`,`字符串` | 中等 | 🔒 | | +| [0440](https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order) | 字典序的第K小数字 | | `字典树` | 困难 | | | +| [0441](https://leetcode-cn.com/problems/arranging-coins) | 排列硬币 | | `数学`,`二分查找` | 简单 | | | +| [0442](https://leetcode-cn.com/problems/find-all-duplicates-in-an-array) | 数组中重复的数据 | | `数组`,`哈希表` | 中等 | | | +| [0443](https://leetcode-cn.com/problems/string-compression) | 压缩字符串 | | `双指针`,`字符串` | 中等 | | | +| [0444](https://leetcode-cn.com/problems/sequence-reconstruction) | 序列重建 | | `图`,`拓扑排序`,`数组` | 中等 | 🔒 | | +| [0445](https://leetcode-cn.com/problems/add-two-numbers-ii) | 两数相加 II | | `栈`,`链表`,`数学` | 中等 | | | +| [0446](https://leetcode-cn.com/problems/arithmetic-slices-ii-subsequence) | 等差数列划分 II - 子序列 | | `数组`,`动态规划` | 困难 | | | +| [0447](https://leetcode-cn.com/problems/number-of-boomerangs) | 回旋镖的数量 | | `数组`,`哈希表`,`数学` | 中等 | | | +| [0448](https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array) | 找到所有数组中消失的数字 | | `数组`,`哈希表` | 简单 | | | +| [0449](https://leetcode-cn.com/problems/serialize-and-deserialize-bst) | 序列化和反序列化二叉搜索树 | | `树`,`深度优先搜索`,`广度优先搜索`,`设计`,`二叉搜索树`,`字符串`,`二叉树` | 中等 | | | +| [0450](https://leetcode-cn.com/problems/delete-node-in-a-bst) | 删除二叉搜索树中的节点 | | `树`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0451](https://leetcode-cn.com/problems/sort-characters-by-frequency) | 根据字符出现频率排序 | | `哈希表`,`字符串`,`桶排序`,`计数`,`排序`,`堆(优先队列)` | 中等 | | | +| [0452](https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons) | 用最少数量的箭引爆气球 | | `贪心`,`数组`,`排序` | 中等 | | | +| [0453](https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements) | 最小操作次数使数组元素相等 | | `数组`,`数学` | 简单 | | | +| [0454](https://leetcode-cn.com/problems/4sum-ii) | 四数相加 II | | `数组`,`哈希表` | 中等 | | | +| [0455](https://leetcode-cn.com/problems/assign-cookies) | 分发饼干 | | `贪心`,`数组`,`排序` | 简单 | | | +| [0456](https://leetcode-cn.com/problems/132-pattern) | 132 模式 | | `栈`,`数组`,`二分查找`,`有序集合`,`单调栈` | 中等 | | | +| [0457](https://leetcode-cn.com/problems/circular-array-loop) | 环形数组是否存在循环 | | `数组`,`哈希表`,`双指针` | 中等 | | | +| [0458](https://leetcode-cn.com/problems/poor-pigs) | 可怜的小猪 | | `数学`,`动态规划`,`组合数学` | 困难 | | | +| [0459](https://leetcode-cn.com/problems/repeated-substring-pattern) | 重复的子字符串 | | `字符串`,`字符串匹配` | 简单 | | | +| [0460](https://leetcode-cn.com/problems/lfu-cache) | LFU 缓存 | | `设计`,`哈希表`,`链表`,`双向链表` | 困难 | | | +| [0461](https://leetcode-cn.com/problems/hamming-distance) | 汉明距离 | | `位运算` | 简单 | | | +| [0462](https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements-ii) | 最少移动次数使数组元素相等 II | | `数组`,`数学`,`排序` | 中等 | | | +| [0463](https://leetcode-cn.com/problems/island-perimeter) | 岛屿的周长 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵` | 简单 | | | +| [0464](https://leetcode-cn.com/problems/can-i-win) | 我能赢吗 | | `位运算`,`记忆化搜索`,`数学`,`动态规划`,`状态压缩`,`博弈` | 中等 | | | +| [0465](https://leetcode-cn.com/problems/optimal-account-balancing) | 最优账单平衡 | | `数组`,`回溯` | 困难 | 🔒 | | +| [0466](https://leetcode-cn.com/problems/count-the-repetitions) | 统计重复个数 | | `字符串`,`动态规划` | 困难 | | | +| [0467](https://leetcode-cn.com/problems/unique-substrings-in-wraparound-string) | 环绕字符串中唯一的子字符串 | | `字符串`,`动态规划` | 中等 | | | +| [0468](https://leetcode-cn.com/problems/validate-ip-address) | 验证IP地址 | | `字符串` | 中等 | | | +| [0469](https://leetcode-cn.com/problems/convex-polygon) | 凸多边形 | | `几何`,`数学` | 中等 | 🔒 | | +| [0470](https://leetcode-cn.com/problems/implement-rand10-using-rand7) | 用 Rand7() 实现 Rand10() | | `数学`,`拒绝采样`,`概率与统计`,`随机化` | 中等 | | | +| [0471](https://leetcode-cn.com/problems/encode-string-with-shortest-length) | 编码最短长度的字符串 | | `字符串`,`动态规划` | 困难 | 🔒 | | +| [0472](https://leetcode-cn.com/problems/concatenated-words) | 连接词 | | `深度优先搜索`,`字典树`,`字符串`,`动态规划` | 困难 | | | +| [0473](https://leetcode-cn.com/problems/matchsticks-to-square) | 火柴拼正方形 | | `位运算`,`数组`,`动态规划`,`回溯`,`状态压缩` | 中等 | | | +| [0474](https://leetcode-cn.com/problems/ones-and-zeroes) | 一和零 | | `数组`,`字符串`,`动态规划` | 中等 | | | +| [0475](https://leetcode-cn.com/problems/heaters) | 供暖器 | | `数组`,`二分查找`,`排序` | 中等 | | | +| [0476](https://leetcode-cn.com/problems/number-complement) | 数字的补数 | | `位运算` | 简单 | | | +| [0477](https://leetcode-cn.com/problems/total-hamming-distance) | 汉明距离总和 | | `位运算`,`数组`,`数学` | 中等 | | | +| [0478](https://leetcode-cn.com/problems/generate-random-point-in-a-circle) | 在圆内随机生成点 | | `几何`,`数学`,`拒绝采样`,`随机化` | 中等 | | | +| [0479](https://leetcode-cn.com/problems/largest-palindrome-product) | 最大回文数乘积 | | `数学` | 困难 | | | +| [0480](https://leetcode-cn.com/problems/sliding-window-median) | 滑动窗口中位数 | | `数组`,`哈希表`,`滑动窗口`,`堆(优先队列)` | 困难 | | | +| [0481](https://leetcode-cn.com/problems/magical-string) | 神奇字符串 | | `双指针`,`字符串` | 中等 | | | +| [0482](https://leetcode-cn.com/problems/license-key-formatting) | 密钥格式化 | | `字符串` | 简单 | | | +| [0483](https://leetcode-cn.com/problems/smallest-good-base) | 最小好进制 | | `数学`,`二分查找` | 困难 | | | +| [0484](https://leetcode-cn.com/problems/find-permutation) | 寻找排列 | | `栈`,`贪心`,`数组` | 中等 | 🔒 | | +| [0485](https://leetcode-cn.com/problems/max-consecutive-ones) | 最大连续 1 的个数 | | `数组` | 简单 | | | +| [0486](https://leetcode-cn.com/problems/predict-the-winner) | 预测赢家 | | `递归`,`数组`,`数学`,`动态规划`,`博弈` | 中等 | | | +| [0487](https://leetcode-cn.com/problems/max-consecutive-ones-ii) | 最大连续1的个数 II | | `数组`,`动态规划`,`滑动窗口` | 中等 | 🔒 | | +| [0488](https://leetcode-cn.com/problems/zuma-game) | 祖玛游戏 | | `字符串`,`回溯` | 困难 | | | +| [0489](https://leetcode-cn.com/problems/robot-room-cleaner) | 扫地机器人 | | `回溯`,`交互` | 困难 | 🔒 | | +| [0490](https://leetcode-cn.com/problems/the-maze) | 迷宫 | | `深度优先搜索`,`广度优先搜索`,`图` | 中等 | 🔒 | | +| [0491](https://leetcode-cn.com/problems/increasing-subsequences) | 递增子序列 | | `位运算`,`数组`,`哈希表`,`回溯` | 中等 | | | +| [0492](https://leetcode-cn.com/problems/construct-the-rectangle) | 构造矩形 | | `数学` | 简单 | | | +| [0493](https://leetcode-cn.com/problems/reverse-pairs) | 翻转对 | | `树状数组`,`线段树`,`数组`,`二分查找`,`分治`,`有序集合`,`归并排序` | 困难 | | | +| [0494](https://leetcode-cn.com/problems/target-sum) | 目标和 | | `数组`,`动态规划`,`回溯` | 中等 | | | +| [0495](https://leetcode-cn.com/problems/teemo-attacking) | 提莫攻击 | | `数组`,`模拟` | 简单 | | | +| [0496](https://leetcode-cn.com/problems/next-greater-element-i) | 下一个更大元素 I | | `栈`,`数组`,`哈希表`,`单调栈` | 简单 | | | +| [0497](https://leetcode-cn.com/problems/random-point-in-non-overlapping-rectangles) | 非重叠矩形中的随机点 | | `水塘抽样`,`数学`,`二分查找`,`有序集合`,`前缀和`,`随机化` | 中等 | | | +| [0498](https://leetcode-cn.com/problems/diagonal-traverse) | 对角线遍历 | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [0499](https://leetcode-cn.com/problems/the-maze-iii) | 迷宫 III | | `深度优先搜索`,`广度优先搜索`,`图`,`最短路`,`堆(优先队列)` | 困难 | 🔒 | | +| [0500](https://leetcode-cn.com/problems/keyboard-row) | 键盘行 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0501](https://leetcode-cn.com/problems/find-mode-in-binary-search-tree) | 二叉搜索树中的众数 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0502](https://leetcode-cn.com/problems/ipo) | IPO | | `贪心`,`数组`,`排序`,`堆(优先队列)` | 困难 | | | +| [0503](https://leetcode-cn.com/problems/next-greater-element-ii) | 下一个更大元素 II | | `栈`,`数组`,`单调栈` | 中等 | | | +| [0504](https://leetcode-cn.com/problems/base-7) | 七进制数 | | `数学` | 简单 | | | +| [0505](https://leetcode-cn.com/problems/the-maze-ii) | 迷宫 II | | `深度优先搜索`,`广度优先搜索`,`图`,`最短路`,`堆(优先队列)` | 中等 | 🔒 | | +| [0506](https://leetcode-cn.com/problems/relative-ranks) | 相对名次 | | `数组`,`排序`,`堆(优先队列)` | 简单 | | | +| [0507](https://leetcode-cn.com/problems/perfect-number) | 完美数 | | `数学` | 简单 | | | +| [0508](https://leetcode-cn.com/problems/most-frequent-subtree-sum) | 出现次数最多的子树元素和 | | `树`,`深度优先搜索`,`哈希表`,`二叉树` | 中等 | | | +| [0509](https://leetcode-cn.com/problems/fibonacci-number) | 斐波那契数 | | `递归`,`记忆化搜索`,`数学`,`动态规划` | 简单 | | | +| [0510](https://leetcode-cn.com/problems/inorder-successor-in-bst-ii) | 二叉搜索树中的中序后继 II | | `树`,`二叉搜索树`,`二叉树` | 中等 | 🔒 | | +| [0511](https://leetcode-cn.com/problems/game-play-analysis-i) | 游戏玩法分析 I | | `数据库` | 简单 | 🔒 | | +| [0512](https://leetcode-cn.com/problems/game-play-analysis-ii) | 游戏玩法分析 II | | `数据库` | 简单 | 🔒 | | +| [0513](https://leetcode-cn.com/problems/find-bottom-left-tree-value) | 找树左下角的值 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0514](https://leetcode-cn.com/problems/freedom-trail) | 自由之路 | | `深度优先搜索`,`广度优先搜索`,`字符串`,`动态规划` | 困难 | | | +| [0515](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row) | 在每个树行中找最大值 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0516](https://leetcode-cn.com/problems/longest-palindromic-subsequence) | 最长回文子序列 | | `字符串`,`动态规划` | 中等 | | | +| [0517](https://leetcode-cn.com/problems/super-washing-machines) | 超级洗衣机 | | `贪心`,`数组` | 困难 | | | +| [0518](https://leetcode-cn.com/problems/coin-change-2) | 零钱兑换 II | | `数组`,`动态规划` | 中等 | | | +| [0519](https://leetcode-cn.com/problems/random-flip-matrix) | 随机翻转矩阵 | | `水塘抽样`,`哈希表`,`数学`,`随机化` | 中等 | | | +| [0520](https://leetcode-cn.com/problems/detect-capital) | 检测大写字母 | | `字符串` | 简单 | | | +| [0521](https://leetcode-cn.com/problems/longest-uncommon-subsequence-i) | 最长特殊序列 Ⅰ | | `字符串` | 简单 | | | +| [0522](https://leetcode-cn.com/problems/longest-uncommon-subsequence-ii) | 最长特殊序列 II | | `数组`,`哈希表`,`双指针`,`字符串`,`排序` | 中等 | | | +| [0523](https://leetcode-cn.com/problems/continuous-subarray-sum) | 连续的子数组和 | | `数组`,`哈希表`,`数学`,`前缀和` | 中等 | | | +| [0524](https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting) | 通过删除字母匹配到字典里最长单词 | | `数组`,`双指针`,`字符串`,`排序` | 中等 | | | +| [0525](https://leetcode-cn.com/problems/contiguous-array) | 连续数组 | | `数组`,`哈希表`,`前缀和` | 中等 | | | +| [0526](https://leetcode-cn.com/problems/beautiful-arrangement) | 优美的排列 | | `位运算`,`数组`,`动态规划`,`回溯`,`状态压缩` | 中等 | | | +| [0527](https://leetcode-cn.com/problems/word-abbreviation) | 单词缩写 | | `贪心`,`字典树`,`数组`,`字符串`,`排序` | 困难 | 🔒 | | +| [0528](https://leetcode-cn.com/problems/random-pick-with-weight) | 按权重随机选择 | | `数学`,`二分查找`,`前缀和`,`随机化` | 中等 | | | +| [0529](https://leetcode-cn.com/problems/minesweeper) | 扫雷游戏 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [0530](https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst) | 二叉搜索树的最小绝对差 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0531](https://leetcode-cn.com/problems/lonely-pixel-i) | 孤独像素 I | | `数组`,`哈希表`,`矩阵` | 中等 | 🔒 | | +| [0532](https://leetcode-cn.com/problems/k-diff-pairs-in-an-array) | 数组中的 k-diff 数对 | | `数组`,`哈希表`,`双指针`,`二分查找`,`排序` | 中等 | | | +| [0533](https://leetcode-cn.com/problems/lonely-pixel-ii) | 孤独像素 II | | `数组`,`哈希表`,`矩阵` | 中等 | 🔒 | | +| [0534](https://leetcode-cn.com/problems/game-play-analysis-iii) | 游戏玩法分析 III | | `数据库` | 中等 | 🔒 | | +| [0535](https://leetcode-cn.com/problems/encode-and-decode-tinyurl) | TinyURL 的加密与解密 | | `设计`,`哈希表`,`字符串`,`哈希函数` | 中等 | | | +| [0536](https://leetcode-cn.com/problems/construct-binary-tree-from-string) | 从字符串生成二叉树 | | `树`,`深度优先搜索`,`字符串`,`二叉树` | 中等 | 🔒 | | +| [0537](https://leetcode-cn.com/problems/complex-number-multiplication) | 复数乘法 | | `数学`,`字符串`,`模拟` | 中等 | | | +| [0538](https://leetcode-cn.com/problems/convert-bst-to-greater-tree) | 把二叉搜索树转换为累加树 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0539](https://leetcode-cn.com/problems/minimum-time-difference) | 最小时间差 | | `数组`,`数学`,`字符串`,`排序` | 中等 | | | +| [0540](https://leetcode-cn.com/problems/single-element-in-a-sorted-array) | 有序数组中的单一元素 | | `数组`,`二分查找` | 中等 | | | +| [0541](https://leetcode-cn.com/problems/reverse-string-ii) | 反转字符串 II | | `双指针`,`字符串` | 简单 | | | +| [0542](https://leetcode-cn.com/problems/01-matrix) | 01 矩阵 | | `广度优先搜索`,`数组`,`动态规划`,`矩阵` | 中等 | | | +| [0543](https://leetcode-cn.com/problems/diameter-of-binary-tree) | 二叉树的直径 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0544](https://leetcode-cn.com/problems/output-contest-matches) | 输出比赛匹配对 | | `递归`,`字符串`,`模拟` | 中等 | 🔒 | | +| [0545](https://leetcode-cn.com/problems/boundary-of-binary-tree) | 二叉树的边界 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0546](https://leetcode-cn.com/problems/remove-boxes) | 移除盒子 | | `记忆化搜索`,`数组`,`动态规划` | 困难 | | | +| [0547](https://leetcode-cn.com/problems/number-of-provinces) | 省份数量 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | | | +| [0548](https://leetcode-cn.com/problems/split-array-with-equal-sum) | 将数组分割成和相等的子数组 | | `数组`,`前缀和` | 困难 | 🔒 | | +| [0549](https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence-ii) | 二叉树中最长的连续序列 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0550](https://leetcode-cn.com/problems/game-play-analysis-iv) | 游戏玩法分析 IV | | `数据库` | 中等 | 🔒 | | +| [0551](https://leetcode-cn.com/problems/student-attendance-record-i) | 学生出勤记录 I | | `字符串` | 简单 | | | +| [0552](https://leetcode-cn.com/problems/student-attendance-record-ii) | 学生出勤记录 II | | `动态规划` | 困难 | | | +| [0553](https://leetcode-cn.com/problems/optimal-division) | 最优除法 | | `数组`,`数学`,`动态规划` | 中等 | | | +| [0554](https://leetcode-cn.com/problems/brick-wall) | 砖墙 | | `数组`,`哈希表` | 中等 | | | +| [0555](https://leetcode-cn.com/problems/split-concatenated-strings) | 分割连接字符串 | | `贪心`,`数组`,`字符串` | 中等 | 🔒 | | +| [0556](https://leetcode-cn.com/problems/next-greater-element-iii) | 下一个更大元素 III | | `数学`,`双指针`,`字符串` | 中等 | | | +| [0557](https://leetcode-cn.com/problems/reverse-words-in-a-string-iii) | 反转字符串中的单词 III | | `双指针`,`字符串` | 简单 | | | +| [0558](https://leetcode-cn.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees) | 四叉树交集 | | `树`,`分治` | 中等 | | | +| [0559](https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree) | N 叉树的最大深度 | | `树`,`深度优先搜索`,`广度优先搜索` | 简单 | | | +| [0560](https://leetcode-cn.com/problems/subarray-sum-equals-k) | 和为K的子数组 | | `数组`,`哈希表`,`前缀和` | 中等 | | | +| [0561](https://leetcode-cn.com/problems/array-partition-i) | 数组拆分 I | | `贪心`,`数组`,`计数排序`,`排序` | 简单 | | | +| [0562](https://leetcode-cn.com/problems/longest-line-of-consecutive-one-in-matrix) | 矩阵中最长的连续1线段 | | `数组`,`动态规划`,`矩阵` | 中等 | 🔒 | | +| [0563](https://leetcode-cn.com/problems/binary-tree-tilt) | 二叉树的坡度 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0564](https://leetcode-cn.com/problems/find-the-closest-palindrome) | 寻找最近的回文数 | | `数学`,`字符串` | 困难 | | | +| [0565](https://leetcode-cn.com/problems/array-nesting) | 数组嵌套 | | `深度优先搜索`,`数组` | 中等 | | | +| [0566](https://leetcode-cn.com/problems/reshape-the-matrix) | 重塑矩阵 | | `数组`,`矩阵`,`模拟` | 简单 | | | +| [0567](https://leetcode-cn.com/problems/permutation-in-string) | 字符串的排列 | | `哈希表`,`双指针`,`字符串`,`滑动窗口` | 中等 | | | +| [0568](https://leetcode-cn.com/problems/maximum-vacation-days) | 最大休假天数 | | `数组`,`动态规划`,`矩阵` | 困难 | 🔒 | | +| [0569](https://leetcode-cn.com/problems/median-employee-salary) | 员工薪水中位数 | | `数据库` | 困难 | 🔒 | | +| [0570](https://leetcode-cn.com/problems/managers-with-at-least-5-direct-reports) | 至少有5名直接下属的经理 | | `数据库` | 中等 | 🔒 | | +| [0571](https://leetcode-cn.com/problems/find-median-given-frequency-of-numbers) | 给定数字的频率查询中位数 | | `数据库` | 困难 | 🔒 | | +| [0572](https://leetcode-cn.com/problems/subtree-of-another-tree) | 另一棵树的子树 | | `树`,`深度优先搜索`,`二叉树`,`字符串匹配`,`哈希函数` | 简单 | | | +| [0573](https://leetcode-cn.com/problems/squirrel-simulation) | 松鼠模拟 | | `数组`,`数学` | 中等 | 🔒 | | +| [0574](https://leetcode-cn.com/problems/winning-candidate) | 当选者 | | `数据库` | 中等 | 🔒 | | +| [0575](https://leetcode-cn.com/problems/distribute-candies) | 分糖果 | | `数组`,`哈希表` | 简单 | | | +| [0576](https://leetcode-cn.com/problems/out-of-boundary-paths) | 出界的路径数 | | `动态规划` | 中等 | | | +| [0577](https://leetcode-cn.com/problems/employee-bonus) | 员工奖金 | | `数据库` | 简单 | 🔒 | | +| [0578](https://leetcode-cn.com/problems/get-highest-answer-rate-question) | 查询回答率最高的问题 | | `数据库` | 中等 | 🔒 | | +| [0579](https://leetcode-cn.com/problems/find-cumulative-salary-of-an-employee) | 查询员工的累计薪水 | | `数据库` | 困难 | 🔒 | | +| [0580](https://leetcode-cn.com/problems/count-student-number-in-departments) | 统计各专业学生人数 | | `数据库` | 中等 | 🔒 | | +| [0581](https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray) | 最短无序连续子数组 | | `栈`,`贪心`,`数组`,`双指针`,`排序`,`单调栈` | 中等 | | | +| [0582](https://leetcode-cn.com/problems/kill-process) | 杀掉进程 | | `树`,`深度优先搜索`,`广度优先搜索`,`数组`,`哈希表` | 中等 | 🔒 | | +| [0583](https://leetcode-cn.com/problems/delete-operation-for-two-strings) | 两个字符串的删除操作 | | `字符串`,`动态规划` | 中等 | | | +| [0584](https://leetcode-cn.com/problems/find-customer-referee) | 寻找用户推荐人 | | `数据库` | 简单 | 🔒 | | +| [0585](https://leetcode-cn.com/problems/investments-in-2016) | 2016年的投资 | | `数据库` | 中等 | 🔒 | | +| [0586](https://leetcode-cn.com/problems/customer-placing-the-largest-number-of-orders) | 订单最多的客户 | | `数据库` | 简单 | 🔒 | | +| [0587](https://leetcode-cn.com/problems/erect-the-fence) | 安装栅栏 | | `几何`,`数组`,`数学` | 困难 | | | +| [0588](https://leetcode-cn.com/problems/design-in-memory-file-system) | 设计内存文件系统 | | `设计`,`字典树`,`哈希表`,`字符串` | 困难 | 🔒 | | +| [0589](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal) | N 叉树的前序遍历 | | `栈`,`树`,`深度优先搜索` | 简单 | | | +| [0590](https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal) | N 叉树的后序遍历 | | `栈`,`树`,`深度优先搜索` | 简单 | | | +| [0591](https://leetcode-cn.com/problems/tag-validator) | 标签验证器 | | `栈`,`字符串` | 困难 | | | +| [0592](https://leetcode-cn.com/problems/fraction-addition-and-subtraction) | 分数加减运算 | | `数学`,`字符串`,`模拟` | 中等 | | | +| [0593](https://leetcode-cn.com/problems/valid-square) | 有效的正方形 | | `几何`,`数学` | 中等 | | ✅ | +| [0594](https://leetcode-cn.com/problems/longest-harmonious-subsequence) | 最长和谐子序列 | | `数组`,`哈希表`,`排序` | 简单 | | | +| [0595](https://leetcode-cn.com/problems/big-countries) | 大的国家 | | `数据库` | 简单 | | | +| [0596](https://leetcode-cn.com/problems/classes-more-than-5-students) | 超过5名学生的课 | | `数据库` | 简单 | | | +| [0597](https://leetcode-cn.com/problems/friend-requests-i-overall-acceptance-rate) | 好友申请 I:总体通过率 | | `数据库` | 简单 | 🔒 | | +| [0598](https://leetcode-cn.com/problems/range-addition-ii) | 范围求和 II | | `数组`,`数学` | 简单 | | | +| [0599](https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists) | 两个列表的最小索引总和 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0600](https://leetcode-cn.com/problems/non-negative-integers-without-consecutive-ones) | 不含连续1的非负整数 | | `动态规划` | 困难 | | | +| [0601](https://leetcode-cn.com/problems/human-traffic-of-stadium) | 体育馆的人流量 | | `数据库` | 困难 | | | +| [0602](https://leetcode-cn.com/problems/friend-requests-ii-who-has-the-most-friends) | 好友申请 II :谁有最多的好友 | | `数据库` | 中等 | 🔒 | | +| [0603](https://leetcode-cn.com/problems/consecutive-available-seats) | 连续空余座位 | | `数据库` | 简单 | 🔒 | | +| [0604](https://leetcode-cn.com/problems/design-compressed-string-iterator) | 迭代压缩字符串 | | `设计`,`数组`,`哈希表`,`字符串`,`迭代器` | 简单 | 🔒 | | +| [0605](https://leetcode-cn.com/problems/can-place-flowers) | 种花问题 | | `贪心`,`数组` | 简单 | | | +| [0606](https://leetcode-cn.com/problems/construct-string-from-binary-tree) | 根据二叉树创建字符串 | | `树`,`深度优先搜索`,`字符串`,`二叉树` | 简单 | | | +| [0607](https://leetcode-cn.com/problems/sales-person) | 销售员 | | `数据库` | 简单 | 🔒 | | +| [0608](https://leetcode-cn.com/problems/tree-node) | 树节点 | | `数据库` | 中等 | 🔒 | | +| [0609](https://leetcode-cn.com/problems/find-duplicate-file-in-system) | 在系统中查找重复文件 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [0610](https://leetcode-cn.com/problems/triangle-judgement) | 判断三角形 | | `数据库` | 简单 | 🔒 | | +| [0611](https://leetcode-cn.com/problems/valid-triangle-number) | 有效三角形的个数 | | `贪心`,`数组`,`双指针`,`二分查找`,`排序` | 中等 | | | +| [0612](https://leetcode-cn.com/problems/shortest-distance-in-a-plane) | 平面上的最近距离 | | `数据库` | 中等 | 🔒 | | +| [0613](https://leetcode-cn.com/problems/shortest-distance-in-a-line) | 直线上的最近距离 | | `数据库` | 简单 | 🔒 | | +| [0614](https://leetcode-cn.com/problems/second-degree-follower) | 二级关注者 | | `数据库` | 中等 | 🔒 | | +| [0615](https://leetcode-cn.com/problems/average-salary-departments-vs-company) | 平均工资:部门与公司比较 | | `数据库` | 困难 | 🔒 | | +| [0616](https://leetcode-cn.com/problems/add-bold-tag-in-string) | 给字符串添加加粗标签 | | `字典树`,`数组`,`哈希表`,`字符串`,`字符串匹配` | 中等 | 🔒 | | +| [0617](https://leetcode-cn.com/problems/merge-two-binary-trees) | 合并二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0618](https://leetcode-cn.com/problems/students-report-by-geography) | 学生地理信息报告 | | `数据库` | 困难 | 🔒 | | +| [0619](https://leetcode-cn.com/problems/biggest-single-number) | 只出现一次的最大数字 | | `数据库` | 简单 | 🔒 | | +| [0620](https://leetcode-cn.com/problems/not-boring-movies) | 有趣的电影 | | `数据库` | 简单 | | | +| [0621](https://leetcode-cn.com/problems/task-scheduler) | 任务调度器 | | `贪心`,`数组`,`哈希表`,`计数`,`排序`,`堆(优先队列)` | 中等 | | | +| [0622](https://leetcode-cn.com/problems/design-circular-queue) | 设计循环队列 | | `设计`,`队列`,`数组`,`链表` | 中等 | | | +| [0623](https://leetcode-cn.com/problems/add-one-row-to-tree) | 在二叉树中增加一行 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0624](https://leetcode-cn.com/problems/maximum-distance-in-arrays) | 数组列表中的最大距离 | | `贪心`,`数组` | 中等 | 🔒 | | +| [0625](https://leetcode-cn.com/problems/minimum-factorization) | 最小因式分解 | | `贪心`,`数学` | 中等 | 🔒 | | +| [0626](https://leetcode-cn.com/problems/exchange-seats) | 换座位 | | `数据库` | 中等 | | | +| [0627](https://leetcode-cn.com/problems/swap-salary) | 变更性别 | | `数据库` | 简单 | | | +| [0628](https://leetcode-cn.com/problems/maximum-product-of-three-numbers) | 三个数的最大乘积 | | `数组`,`数学`,`排序` | 简单 | | | +| [0629](https://leetcode-cn.com/problems/k-inverse-pairs-array) | K个逆序对数组 | | `动态规划` | 困难 | | | +| [0630](https://leetcode-cn.com/problems/course-schedule-iii) | 课程表 III | | `贪心`,`数组`,`堆(优先队列)` | 困难 | | | +| [0631](https://leetcode-cn.com/problems/design-excel-sum-formula) | 设计 Excel 求和公式 | | `图`,`设计`,`拓扑排序` | 困难 | 🔒 | | +| [0632](https://leetcode-cn.com/problems/smallest-range-covering-elements-from-k-lists) | 最小区间 | | `贪心`,`数组`,`哈希表`,`排序`,`滑动窗口`,`堆(优先队列)` | 困难 | | | +| [0633](https://leetcode-cn.com/problems/sum-of-square-numbers) | 平方数之和 | | `数学`,`双指针`,`二分查找` | 中等 | | ✅ | +| [0634](https://leetcode-cn.com/problems/find-the-derangement-of-an-array) | 寻找数组的错位排列 | | `数学`,`动态规划` | 中等 | 🔒 | | +| [0635](https://leetcode-cn.com/problems/design-log-storage-system) | 设计日志存储系统 | | `设计`,`哈希表`,`字符串`,`有序集合` | 中等 | 🔒 | | +| [0636](https://leetcode-cn.com/problems/exclusive-time-of-functions) | 函数的独占时间 | | `栈`,`数组` | 中等 | | | +| [0637](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree) | 二叉树的层平均值 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0638](https://leetcode-cn.com/problems/shopping-offers) | 大礼包 | | `位运算`,`记忆化搜索`,`数组`,`动态规划`,`回溯`,`状态压缩` | 中等 | | | +| [0639](https://leetcode-cn.com/problems/decode-ways-ii) | 解码方法 II | | `字符串`,`动态规划` | 困难 | | | +| [0640](https://leetcode-cn.com/problems/solve-the-equation) | 求解方程 | | `数学`,`字符串`,`模拟` | 中等 | | | +| [0641](https://leetcode-cn.com/problems/design-circular-deque) | 设计循环双端队列 | | `设计`,`队列`,`数组`,`链表` | 中等 | | | +| [0642](https://leetcode-cn.com/problems/design-search-autocomplete-system) | 设计搜索自动补全系统 | | `设计`,`字典树`,`字符串`,`数据流` | 困难 | 🔒 | | +| [0643](https://leetcode-cn.com/problems/maximum-average-subarray-i) | 子数组最大平均数 I | | `数组`,`滑动窗口` | 简单 | | | +| [0644](https://leetcode-cn.com/problems/maximum-average-subarray-ii) | 子数组最大平均数 II | | `数组`,`二分查找` | 困难 | 🔒 | | +| [0645](https://leetcode-cn.com/problems/set-mismatch) | 错误的集合 | | `位运算`,`数组`,`哈希表`,`排序` | 简单 | | ✅ | +| [0646](https://leetcode-cn.com/problems/maximum-length-of-pair-chain) | 最长数对链 | | `贪心`,`数组`,`动态规划`,`排序` | 中等 | | | +| [0647](https://leetcode-cn.com/problems/palindromic-substrings) | 回文子串 | | `字符串`,`动态规划` | 中等 | | | +| [0648](https://leetcode-cn.com/problems/replace-words) | 单词替换 | | `字典树`,`数组`,`哈希表`,`字符串` | 中等 | | | +| [0649](https://leetcode-cn.com/problems/dota2-senate) | Dota2 参议院 | | `贪心`,`队列`,`字符串` | 中等 | | | +| [0650](https://leetcode-cn.com/problems/2-keys-keyboard) | 只有两个键的键盘 | | `数学`,`动态规划` | 中等 | | | +| [0651](https://leetcode-cn.com/problems/4-keys-keyboard) | 4键键盘 | | `数学`,`动态规划` | 中等 | 🔒 | | +| [0652](https://leetcode-cn.com/problems/find-duplicate-subtrees) | 寻找重复的子树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0653](https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst) | 两数之和 IV - 输入 BST | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉搜索树`,`哈希表`,`双指针`,`二叉树` | 简单 | | | +| [0654](https://leetcode-cn.com/problems/maximum-binary-tree) | 最大二叉树 | | `栈`,`树`,`数组`,`分治`,`二叉树`,`单调栈` | 中等 | | | +| [0655](https://leetcode-cn.com/problems/print-binary-tree) | 输出二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0656](https://leetcode-cn.com/problems/coin-path) | 金币路径 | | `数组`,`动态规划` | 困难 | 🔒 | | +| [0657](https://leetcode-cn.com/problems/robot-return-to-origin) | 机器人能否返回原点 | | `字符串`,`模拟` | 简单 | | | +| [0658](https://leetcode-cn.com/problems/find-k-closest-elements) | 找到 K 个最接近的元素 | | `数组`,`双指针`,`二分查找`,`排序`,`堆(优先队列)` | 中等 | | | +| [0659](https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences) | 分割数组为连续子序列 | | `贪心`,`数组`,`哈希表`,`堆(优先队列)` | 中等 | | | +| [0660](https://leetcode-cn.com/problems/remove-9) | 移除 9 | | `数学` | 困难 | 🔒 | | +| [0661](https://leetcode-cn.com/problems/image-smoother) | 图片平滑器 | | `数组`,`矩阵` | 简单 | | | +| [0662](https://leetcode-cn.com/problems/maximum-width-of-binary-tree) | 二叉树最大宽度 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0663](https://leetcode-cn.com/problems/equal-tree-partition) | 均匀树划分 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0664](https://leetcode-cn.com/problems/strange-printer) | 奇怪的打印机 | | `字符串`,`动态规划` | 困难 | | | +| [0665](https://leetcode-cn.com/problems/non-decreasing-array) | 非递减数列 | | `数组` | 中等 | | | +| [0666](https://leetcode-cn.com/problems/path-sum-iv) | 路径总和 IV | | `树`,`深度优先搜索`,`数组`,`二叉树` | 中等 | 🔒 | | +| [0667](https://leetcode-cn.com/problems/beautiful-arrangement-ii) | 优美的排列 II | | `数组`,`数学` | 中等 | | | +| [0668](https://leetcode-cn.com/problems/kth-smallest-number-in-multiplication-table) | 乘法表中第k小的数 | | `二分查找` | 困难 | | | +| [0669](https://leetcode-cn.com/problems/trim-a-binary-search-tree) | 修剪二叉搜索树 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0670](https://leetcode-cn.com/problems/maximum-swap) | 最大交换 | | `贪心`,`数学` | 中等 | | | +| [0671](https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree) | 二叉树中第二小的节点 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0672](https://leetcode-cn.com/problems/bulb-switcher-ii) | 灯泡开关 Ⅱ | | `位运算`,`深度优先搜索`,`广度优先搜索`,`数学` | 中等 | | | +| [0673](https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence) | 最长递增子序列的个数 | | `树状数组`,`线段树`,`数组`,`动态规划` | 中等 | | | +| [0674](https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence) | 最长连续递增序列 | | `数组` | 简单 | | | +| [0675](https://leetcode-cn.com/problems/cut-off-trees-for-golf-event) | 为高尔夫比赛砍树 | | `广度优先搜索`,`数组`,`矩阵`,`堆(优先队列)` | 困难 | | | +| [0676](https://leetcode-cn.com/problems/implement-magic-dictionary) | 实现一个魔法字典 | | `设计`,`字典树`,`哈希表`,`字符串` | 中等 | | | +| [0677](https://leetcode-cn.com/problems/map-sum-pairs) | 键值映射 | | `设计`,`字典树`,`哈希表`,`字符串` | 中等 | | | +| [0678](https://leetcode-cn.com/problems/valid-parenthesis-string) | 有效的括号字符串 | | `栈`,`贪心`,`字符串`,`动态规划` | 中等 | | | +| [0679](https://leetcode-cn.com/problems/24-game) | 24 点游戏 | | `数组`,`数学`,`回溯` | 困难 | | | +| [0680](https://leetcode-cn.com/problems/valid-palindrome-ii) | 验证回文字符串 Ⅱ | | `贪心`,`双指针`,`字符串` | 简单 | | | +| [0681](https://leetcode-cn.com/problems/next-closest-time) | 最近时刻 | | `字符串`,`枚举` | 中等 | 🔒 | | +| [0682](https://leetcode-cn.com/problems/baseball-game) | 棒球比赛 | | `栈`,`数组`,`模拟` | 简单 | | | +| [0683](https://leetcode-cn.com/problems/k-empty-slots) | K 个关闭的灯泡 | | `树状数组`,`数组`,`有序集合`,`滑动窗口` | 困难 | 🔒 | | +| [0684](https://leetcode-cn.com/problems/redundant-connection) | 冗余连接 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | | | +| [0685](https://leetcode-cn.com/problems/redundant-connection-ii) | 冗余连接 II | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 困难 | | | +| [0686](https://leetcode-cn.com/problems/repeated-string-match) | 重复叠加字符串匹配 | | `字符串`,`字符串匹配` | 中等 | | | +| [0687](https://leetcode-cn.com/problems/longest-univalue-path) | 最长同值路径 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0688](https://leetcode-cn.com/problems/knight-probability-in-chessboard) | "马"在棋盘上的概率 | | `动态规划` | 中等 | | | +| [0689](https://leetcode-cn.com/problems/maximum-sum-of-3-non-overlapping-subarrays) | 三个无重叠子数组的最大和 | | `数组`,`动态规划` | 困难 | | | +| [0690](https://leetcode-cn.com/problems/employee-importance) | 员工的重要性 | | `深度优先搜索`,`广度优先搜索`,`哈希表` | 简单 | | | +| [0691](https://leetcode-cn.com/problems/stickers-to-spell-word) | 贴纸拼词 | | `位运算`,`动态规划`,`回溯`,`状态压缩` | 困难 | | | +| [0692](https://leetcode-cn.com/problems/top-k-frequent-words) | 前K个高频单词 | | `字典树`,`哈希表`,`字符串`,`桶排序`,`计数`,`排序`,`堆(优先队列)` | 中等 | | | +| [0693](https://leetcode-cn.com/problems/binary-number-with-alternating-bits) | 交替位二进制数 | | `位运算` | 简单 | | | +| [0694](https://leetcode-cn.com/problems/number-of-distinct-islands) | 不同岛屿的数量 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`哈希表`,`哈希函数` | 中等 | 🔒 | | +| [0695](https://leetcode-cn.com/problems/max-area-of-island) | 岛屿的最大面积 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [0696](https://leetcode-cn.com/problems/count-binary-substrings) | 计数二进制子串 | | `双指针`,`字符串` | 简单 | | | +| [0697](https://leetcode-cn.com/problems/degree-of-an-array) | 数组的度 | | `数组`,`哈希表` | 简单 | | | +| [0698](https://leetcode-cn.com/problems/partition-to-k-equal-sum-subsets) | 划分为k个相等的子集 | | `位运算`,`记忆化搜索`,`数组`,`动态规划`,`回溯`,`状态压缩` | 中等 | | | +| [0699](https://leetcode-cn.com/problems/falling-squares) | 掉落的方块 | | `线段树`,`数组`,`有序集合` | 困难 | | | +| [0700](https://leetcode-cn.com/problems/search-in-a-binary-search-tree) | 二叉搜索树中的搜索 | | `树`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0701](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree) | 二叉搜索树中的插入操作 | | `树`,`二叉搜索树`,`二叉树` | 中等 | | | +| [0702](https://leetcode-cn.com/problems/search-in-a-sorted-array-of-unknown-size) | 搜索长度未知的有序数组 | | `数组`,`二分查找`,`交互` | 中等 | 🔒 | | +| [0703](https://leetcode-cn.com/problems/kth-largest-element-in-a-stream) | 数据流中的第 K 大元素 | | `树`,`设计`,`二叉搜索树`,`二叉树`,`数据流`,`堆(优先队列)` | 简单 | | | +| [0704](https://leetcode-cn.com/problems/binary-search) | 二分查找 | | `数组`,`二分查找` | 简单 | | | +| [0705](https://leetcode-cn.com/problems/design-hashset) | 设计哈希集合 | | `设计`,`数组`,`哈希表`,`链表`,`哈希函数` | 简单 | | | +| [0706](https://leetcode-cn.com/problems/design-hashmap) | 设计哈希映射 | | `设计`,`数组`,`哈希表`,`链表`,`哈希函数` | 简单 | | | +| [0707](https://leetcode-cn.com/problems/design-linked-list) | 设计链表 | | `设计`,`链表` | 中等 | | | +| [0708](https://leetcode-cn.com/problems/insert-into-a-sorted-circular-linked-list) | 循环有序列表的插入 | | `链表` | 中等 | 🔒 | | +| [0709](https://leetcode-cn.com/problems/to-lower-case) | 转换成小写字母 | | `字符串` | 简单 | | | +| [0710](https://leetcode-cn.com/problems/random-pick-with-blacklist) | 黑名单中的随机数 | | `哈希表`,`数学`,`二分查找`,`排序`,`随机化` | 困难 | | | +| [0711](https://leetcode-cn.com/problems/number-of-distinct-islands-ii) | 不同岛屿的数量 II | | `深度优先搜索`,`广度优先搜索`,`并查集`,`哈希表`,`哈希函数` | 困难 | 🔒 | | +| [0712](https://leetcode-cn.com/problems/minimum-ascii-delete-sum-for-two-strings) | 两个字符串的最小ASCII删除和 | | `字符串`,`动态规划` | 中等 | | | +| [0713](https://leetcode-cn.com/problems/subarray-product-less-than-k) | 乘积小于K的子数组 | | `数组`,`滑动窗口` | 中等 | | | +| [0714](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee) | 买卖股票的最佳时机含手续费 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [0715](https://leetcode-cn.com/problems/range-module) | Range 模块 | | `设计`,`线段树`,`有序集合` | 困难 | | | +| [0716](https://leetcode-cn.com/problems/max-stack) | 最大栈 | | `栈`,`设计`,`链表`,`双向链表`,`有序集合` | 简单 | 🔒 | | +| [0717](https://leetcode-cn.com/problems/1-bit-and-2-bit-characters) | 1比特与2比特字符 | | `数组` | 简单 | | | +| [0718](https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray) | 最长重复子数组 | | `数组`,`二分查找`,`动态规划`,`滑动窗口`,`哈希函数`,`滚动哈希` | 中等 | | | +| [0719](https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance) | 找出第 k 小的距离对 | | `数组`,`双指针`,`二分查找`,`排序` | 困难 | | | +| [0720](https://leetcode-cn.com/problems/longest-word-in-dictionary) | 词典中最长的单词 | | `字典树`,`数组`,`哈希表`,`字符串`,`排序` | 简单 | | | +| [0721](https://leetcode-cn.com/problems/accounts-merge) | 账户合并 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`字符串` | 中等 | | | +| [0722](https://leetcode-cn.com/problems/remove-comments) | 删除注释 | | `数组`,`字符串` | 中等 | | | +| [0723](https://leetcode-cn.com/problems/candy-crush) | 粉碎糖果 | | `数组`,`双指针`,`矩阵`,`模拟` | 中等 | 🔒 | | +| [0724](https://leetcode-cn.com/problems/find-pivot-index) | 寻找数组的中心下标 | | `数组`,`前缀和` | 简单 | | | +| [0725](https://leetcode-cn.com/problems/split-linked-list-in-parts) | 分隔链表 | | `链表` | 中等 | | | +| [0726](https://leetcode-cn.com/problems/number-of-atoms) | 原子的数量 | | `栈`,`哈希表`,`字符串` | 困难 | | | +| [0727](https://leetcode-cn.com/problems/minimum-window-subsequence) | 最小窗口子序列 | | `字符串`,`动态规划`,`滑动窗口` | 困难 | 🔒 | | +| [0728](https://leetcode-cn.com/problems/self-dividing-numbers) | 自除数 | | `数学` | 简单 | | ✅ | +| [0729](https://leetcode-cn.com/problems/my-calendar-i) | 我的日程安排表 I | | `设计`,`线段树`,`有序集合` | 中等 | | | +| [0730](https://leetcode-cn.com/problems/count-different-palindromic-subsequences) | 统计不同回文子序列 | | `字符串`,`动态规划` | 困难 | | | +| [0731](https://leetcode-cn.com/problems/my-calendar-ii) | 我的日程安排表 II | | `设计`,`线段树`,`有序集合` | 中等 | | | +| [0732](https://leetcode-cn.com/problems/my-calendar-iii) | 我的日程安排表 III | | `设计`,`线段树`,`有序集合` | 困难 | | | +| [0733](https://leetcode-cn.com/problems/flood-fill) | 图像渲染 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵` | 简单 | | | +| [0734](https://leetcode-cn.com/problems/sentence-similarity) | 句子相似性 | | `数组`,`哈希表`,`字符串` | 简单 | 🔒 | | +| [0735](https://leetcode-cn.com/problems/asteroid-collision) | 行星碰撞 | | `栈`,`数组` | 中等 | | | +| [0736](https://leetcode-cn.com/problems/parse-lisp-expression) | Lisp 语法解析 | | `栈`,`递归`,`哈希表`,`字符串` | 困难 | | | +| [0737](https://leetcode-cn.com/problems/sentence-similarity-ii) | 句子相似性 II | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [0738](https://leetcode-cn.com/problems/monotone-increasing-digits) | 单调递增的数字 | | `贪心`,`数学` | 中等 | | | +| [0739](https://leetcode-cn.com/problems/daily-temperatures) | 每日温度 | | `栈`,`数组`,`单调栈` | 中等 | | | +| [0740](https://leetcode-cn.com/problems/delete-and-earn) | 删除并获得点数 | | `数组`,`哈希表`,`动态规划` | 中等 | | | +| [0741](https://leetcode-cn.com/problems/cherry-pickup) | 摘樱桃 | | `数组`,`动态规划`,`矩阵` | 困难 | | | +| [0742](https://leetcode-cn.com/problems/closest-leaf-in-a-binary-tree) | 二叉树最近的叶节点 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [0743](https://leetcode-cn.com/problems/network-delay-time) | 网络延迟时间 | | `深度优先搜索`,`广度优先搜索`,`图`,`最短路`,`堆(优先队列)` | 中等 | | | +| [0744](https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target) | 寻找比目标字母大的最小字母 | | `数组`,`二分查找` | 简单 | | | +| [0745](https://leetcode-cn.com/problems/prefix-and-suffix-search) | 前缀和后缀搜索 | | `设计`,`字典树`,`字符串` | 困难 | | | +| [0746](https://leetcode-cn.com/problems/min-cost-climbing-stairs) | 使用最小花费爬楼梯 | | `数组`,`动态规划` | 简单 | | | +| [0747](https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others) | 至少是其他数字两倍的最大数 | | `数组`,`排序` | 简单 | | | +| [0748](https://leetcode-cn.com/problems/shortest-completing-word) | 最短补全词 | | `哈希表`,`字符串` | 简单 | | | +| [0749](https://leetcode-cn.com/problems/contain-virus) | 隔离病毒 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵`,`模拟` | 困难 | | | +| [0750](https://leetcode-cn.com/problems/number-of-corner-rectangles) | 角矩形的数量 | | `数组`,`数学`,`动态规划`,`矩阵` | 中等 | 🔒 | | +| [0751](https://leetcode-cn.com/problems/ip-to-cidr) | IP 到 CIDR | | `位运算`,`字符串` | 中等 | 🔒 | | +| [0752](https://leetcode-cn.com/problems/open-the-lock) | 打开转盘锁 | | `广度优先搜索`,`数组`,`哈希表`,`字符串` | 中等 | | | +| [0753](https://leetcode-cn.com/problems/cracking-the-safe) | 破解保险箱 | | `深度优先搜索`,`图`,`欧拉回路` | 困难 | | | +| [0754](https://leetcode-cn.com/problems/reach-a-number) | 到达终点数字 | | `数学`,`二分查找` | 中等 | | | +| [0755](https://leetcode-cn.com/problems/pour-water) | 倒水 | | `数组`,`模拟` | 中等 | 🔒 | | +| [0756](https://leetcode-cn.com/problems/pyramid-transition-matrix) | 金字塔转换矩阵 | | `位运算`,`深度优先搜索`,`广度优先搜索` | 中等 | | | +| [0757](https://leetcode-cn.com/problems/set-intersection-size-at-least-two) | 设置交集大小至少为2 | | `贪心`,`数组`,`排序` | 困难 | | | +| [0758](https://leetcode-cn.com/problems/bold-words-in-string) | 字符串中的加粗单词 | | `字典树`,`数组`,`哈希表`,`字符串`,`字符串匹配` | 中等 | 🔒 | | +| [0759](https://leetcode-cn.com/problems/employee-free-time) | 员工空闲时间 | | `数组`,`排序`,`堆(优先队列)` | 困难 | 🔒 | | +| [0760](https://leetcode-cn.com/problems/find-anagram-mappings) | 找出变位映射 | | `数组`,`哈希表` | 简单 | 🔒 | | +| [0761](https://leetcode-cn.com/problems/special-binary-string) | 特殊的二进制序列 | | `递归`,`字符串` | 困难 | | | +| [0762](https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation) | 二进制表示中质数个计算置位 | | `位运算`,`数学` | 简单 | | | +| [0763](https://leetcode-cn.com/problems/partition-labels) | 划分字母区间 | | `贪心`,`哈希表`,`双指针`,`字符串` | 中等 | | | +| [0764](https://leetcode-cn.com/problems/largest-plus-sign) | 最大加号标志 | | `数组`,`动态规划` | 中等 | | | +| [0765](https://leetcode-cn.com/problems/couples-holding-hands) | 情侣牵手 | | `贪心`,`深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 困难 | | | +| [0766](https://leetcode-cn.com/problems/toeplitz-matrix) | 托普利茨矩阵 | | `数组`,`矩阵` | 简单 | | | +| [0767](https://leetcode-cn.com/problems/reorganize-string) | 重构字符串 | | `贪心`,`哈希表`,`字符串`,`计数`,`排序`,`堆(优先队列)` | 中等 | | | +| [0768](https://leetcode-cn.com/problems/max-chunks-to-make-sorted-ii) | 最多能完成排序的块 II | | `栈`,`贪心`,`数组`,`排序`,`单调栈` | 困难 | | | +| [0769](https://leetcode-cn.com/problems/max-chunks-to-make-sorted) | 最多能完成排序的块 | | `栈`,`贪心`,`数组`,`排序`,`单调栈` | 中等 | | | +| [0770](https://leetcode-cn.com/problems/basic-calculator-iv) | 基本计算器 IV | | `栈`,`递归`,`哈希表`,`数学`,`字符串` | 困难 | | | +| [0771](https://leetcode-cn.com/problems/jewels-and-stones) | 宝石与石头 | | `哈希表`,`字符串` | 简单 | | | +| [0772](https://leetcode-cn.com/problems/basic-calculator-iii) | 基本计算器 III | | `栈`,`递归`,`数学`,`字符串` | 困难 | 🔒 | | +| [0773](https://leetcode-cn.com/problems/sliding-puzzle) | 滑动谜题 | | `广度优先搜索`,`数组`,`矩阵` | 困难 | | | +| [0774](https://leetcode-cn.com/problems/minimize-max-distance-to-gas-station) | 最小化去加油站的最大距离 | | `数组`,`二分查找` | 困难 | 🔒 | | +| [0775](https://leetcode-cn.com/problems/global-and-local-inversions) | 全局倒置与局部倒置 | | `数组`,`数学` | 中等 | | | +| [0776](https://leetcode-cn.com/problems/split-bst) | 拆分二叉搜索树 | | `树`,`二叉搜索树`,`递归`,`二叉树` | 中等 | 🔒 | | +| [0777](https://leetcode-cn.com/problems/swap-adjacent-in-lr-string) | 在LR字符串中交换相邻字符 | | `双指针`,`字符串` | 中等 | | | +| [0778](https://leetcode-cn.com/problems/swim-in-rising-water) | 水位上升的泳池中游泳 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`二分查找`,`矩阵`,`堆(优先队列)` | 困难 | | | +| [0779](https://leetcode-cn.com/problems/k-th-symbol-in-grammar) | 第K个语法符号 | | `位运算`,`递归`,`数学` | 中等 | | | +| [0780](https://leetcode-cn.com/problems/reaching-points) | 到达终点 | | `数学` | 困难 | | | +| [0781](https://leetcode-cn.com/problems/rabbits-in-forest) | 森林中的兔子 | | `贪心`,`哈希表`,`数学` | 中等 | | | +| [0782](https://leetcode-cn.com/problems/transform-to-chessboard) | 变为棋盘 | | `位运算`,`数组`,`数学`,`矩阵` | 困难 | | | +| [0783](https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes) | 二叉搜索树节点最小距离 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0784](https://leetcode-cn.com/problems/letter-case-permutation) | 字母大小写全排列 | | `位运算`,`字符串`,`回溯` | 中等 | | | +| [0785](https://leetcode-cn.com/problems/is-graph-bipartite) | 判断二分图 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | | | +| [0786](https://leetcode-cn.com/problems/k-th-smallest-prime-fraction) | 第 K 个最小的素数分数 | | `数组`,`二分查找`,`堆(优先队列)` | 困难 | | | +| [0787](https://leetcode-cn.com/problems/cheapest-flights-within-k-stops) | K 站中转内最便宜的航班 | | `深度优先搜索`,`广度优先搜索`,`图`,`动态规划`,`最短路`,`堆(优先队列)` | 中等 | | | +| [0788](https://leetcode-cn.com/problems/rotated-digits) | 旋转数字 | | `数学`,`动态规划` | 中等 | | | +| [0789](https://leetcode-cn.com/problems/escape-the-ghosts) | 逃脱阻碍者 | | `数组`,`数学` | 中等 | | | +| [0790](https://leetcode-cn.com/problems/domino-and-tromino-tiling) | 多米诺和托米诺平铺 | | `动态规划` | 中等 | | | +| [0791](https://leetcode-cn.com/problems/custom-sort-string) | 自定义字符串排序 | | `哈希表`,`字符串`,`排序` | 中等 | | | +| [0792](https://leetcode-cn.com/problems/number-of-matching-subsequences) | 匹配子序列的单词数 | | `字典树`,`哈希表`,`字符串`,`排序` | 中等 | | | +| [0793](https://leetcode-cn.com/problems/preimage-size-of-factorial-zeroes-function) | 阶乘函数后 K 个零 | | `数学`,`二分查找` | 困难 | | | +| [0794](https://leetcode-cn.com/problems/valid-tic-tac-toe-state) | 有效的井字游戏 | | `数组`,`字符串` | 中等 | | | +| [0795](https://leetcode-cn.com/problems/number-of-subarrays-with-bounded-maximum) | 区间子数组个数 | | `数组`,`双指针` | 中等 | | | +| [0796](https://leetcode-cn.com/problems/rotate-string) | 旋转字符串 | | `字符串`,`字符串匹配` | 简单 | | | +| [0797](https://leetcode-cn.com/problems/all-paths-from-source-to-target) | 所有可能的路径 | | `深度优先搜索`,`广度优先搜索`,`图`,`回溯` | 中等 | | | +| [0798](https://leetcode-cn.com/problems/smallest-rotation-with-highest-score) | 得分最高的最小轮调 | | `数组`,`前缀和` | 困难 | | | +| [0799](https://leetcode-cn.com/problems/champagne-tower) | 香槟塔 | | `动态规划` | 中等 | | | +| [0800](https://leetcode-cn.com/problems/similar-rgb-color) | 相似 RGB 颜色 | | `数学`,`字符串`,`枚举` | 简单 | 🔒 | | +| [0801](https://leetcode-cn.com/problems/minimum-swaps-to-make-sequences-increasing) | 使序列递增的最小交换次数 | | `数组`,`动态规划` | 困难 | | | +| [0802](https://leetcode-cn.com/problems/find-eventual-safe-states) | 找到最终的安全状态 | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序` | 中等 | | | +| [0803](https://leetcode-cn.com/problems/bricks-falling-when-hit) | 打砖块 | | `并查集`,`数组`,`矩阵` | 困难 | | | +| [0804](https://leetcode-cn.com/problems/unique-morse-code-words) | 唯一摩尔斯密码词 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0805](https://leetcode-cn.com/problems/split-array-with-same-average) | 数组的均值分割 | | `位运算`,`数组`,`数学`,`动态规划`,`状态压缩` | 困难 | | | +| [0806](https://leetcode-cn.com/problems/number-of-lines-to-write-string) | 写字符串需要的行数 | | `数组`,`字符串` | 简单 | | | +| [0807](https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline) | 保持城市天际线 | | `贪心`,`数组`,`矩阵` | 中等 | | | +| [0808](https://leetcode-cn.com/problems/soup-servings) | 分汤 | | `数学`,`动态规划`,`概率与统计` | 中等 | | | +| [0809](https://leetcode-cn.com/problems/expressive-words) | 情感丰富的文字 | | `数组`,`双指针`,`字符串` | 中等 | | | +| [0810](https://leetcode-cn.com/problems/chalkboard-xor-game) | 黑板异或游戏 | | `位运算`,`脑筋急转弯`,`数组`,`数学`,`博弈` | 困难 | | | +| [0811](https://leetcode-cn.com/problems/subdomain-visit-count) | 子域名访问计数 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0812](https://leetcode-cn.com/problems/largest-triangle-area) | 最大三角形面积 | | `几何`,`数组`,`数学` | 简单 | | | +| [0813](https://leetcode-cn.com/problems/largest-sum-of-averages) | 最大平均值和的分组 | | `数组`,`动态规划` | 中等 | | | +| [0814](https://leetcode-cn.com/problems/binary-tree-pruning) | 二叉树剪枝 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0815](https://leetcode-cn.com/problems/bus-routes) | 公交路线 | | `广度优先搜索`,`数组`,`哈希表` | 困难 | | | +| [0816](https://leetcode-cn.com/problems/ambiguous-coordinates) | 模糊坐标 | | `字符串`,`回溯` | 中等 | | | +| [0817](https://leetcode-cn.com/problems/linked-list-components) | 链表组件 | | `哈希表`,`链表` | 中等 | | | +| [0818](https://leetcode-cn.com/problems/race-car) | 赛车 | | `动态规划` | 困难 | | | +| [0819](https://leetcode-cn.com/problems/most-common-word) | 最常见的单词 | | `哈希表`,`字符串` | 简单 | | | +| [0820](https://leetcode-cn.com/problems/short-encoding-of-words) | 单词的压缩编码 | | `字典树`,`数组`,`哈希表`,`字符串` | 中等 | | | +| [0821](https://leetcode-cn.com/problems/shortest-distance-to-a-character) | 字符的最短距离 | | `数组`,`双指针`,`字符串` | 简单 | | | +| [0822](https://leetcode-cn.com/problems/card-flipping-game) | 翻转卡片游戏 | | `数组`,`哈希表` | 中等 | | | +| [0823](https://leetcode-cn.com/problems/binary-trees-with-factors) | 带因子的二叉树 | | `数组`,`哈希表`,`动态规划` | 中等 | | | +| [0824](https://leetcode-cn.com/problems/goat-latin) | 山羊拉丁文 | | `字符串` | 简单 | | | +| [0825](https://leetcode-cn.com/problems/friends-of-appropriate-ages) | 适龄的朋友 | | `数组`,`双指针`,`二分查找`,`排序` | 中等 | | | +| [0826](https://leetcode-cn.com/problems/most-profit-assigning-work) | 安排工作以达到最大收益 | | `贪心`,`数组`,`双指针`,`二分查找`,`排序` | 中等 | | | +| [0827](https://leetcode-cn.com/problems/making-a-large-island) | 最大人工岛 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 困难 | | | +| [0828](https://leetcode-cn.com/problems/count-unique-characters-of-all-substrings-of-a-given-string) | 统计子串中的唯一字符 | | `字符串`,`动态规划` | 困难 | | | +| [0829](https://leetcode-cn.com/problems/consecutive-numbers-sum) | 连续整数求和 | | `数学`,`枚举` | 困难 | | | +| [0830](https://leetcode-cn.com/problems/positions-of-large-groups) | 较大分组的位置 | | `字符串` | 简单 | | | +| [0831](https://leetcode-cn.com/problems/masking-personal-information) | 隐藏个人信息 | | `字符串` | 中等 | | | +| [0832](https://leetcode-cn.com/problems/flipping-an-image) | 翻转图像 | | `数组`,`双指针`,`矩阵`,`模拟` | 简单 | | | +| [0833](https://leetcode-cn.com/problems/find-and-replace-in-string) | 字符串中的查找与替换 | | `数组`,`字符串`,`排序` | 中等 | | | +| [0834](https://leetcode-cn.com/problems/sum-of-distances-in-tree) | 树中距离之和 | | `树`,`深度优先搜索`,`图`,`动态规划` | 困难 | | | +| [0835](https://leetcode-cn.com/problems/image-overlap) | 图像重叠 | | `数组`,`矩阵` | 中等 | | | +| [0836](https://leetcode-cn.com/problems/rectangle-overlap) | 矩形重叠 | | `几何`,`数学` | 简单 | | | +| [0837](https://leetcode-cn.com/problems/new-21-game) | 新21点 | | `数学`,`动态规划`,`滑动窗口`,`概率与统计` | 中等 | | | +| [0838](https://leetcode-cn.com/problems/push-dominoes) | 推多米诺 | | `双指针`,`字符串`,`动态规划` | 中等 | | | +| [0839](https://leetcode-cn.com/problems/similar-string-groups) | 相似字符串组 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`字符串` | 困难 | | | +| [0840](https://leetcode-cn.com/problems/magic-squares-in-grid) | 矩阵中的幻方 | | `数组`,`数学`,`矩阵` | 中等 | | | +| [0841](https://leetcode-cn.com/problems/keys-and-rooms) | 钥匙和房间 | | `深度优先搜索`,`广度优先搜索`,`图` | 中等 | | | +| [0842](https://leetcode-cn.com/problems/split-array-into-fibonacci-sequence) | 将数组拆分成斐波那契序列 | | `字符串`,`回溯` | 中等 | | | +| [0843](https://leetcode-cn.com/problems/guess-the-word) | 猜猜这个单词 | | `数组`,`数学`,`字符串`,`博弈`,`交互` | 困难 | | | +| [0844](https://leetcode-cn.com/problems/backspace-string-compare) | 比较含退格的字符串 | | `栈`,`双指针`,`字符串`,`模拟` | 简单 | | | +| [0845](https://leetcode-cn.com/problems/longest-mountain-in-array) | 数组中的最长山脉 | | `数组`,`双指针`,`动态规划`,`枚举` | 中等 | | | +| [0846](https://leetcode-cn.com/problems/hand-of-straights) | 一手顺子 | | `贪心`,`数组`,`哈希表`,`排序` | 中等 | | | +| [0847](https://leetcode-cn.com/problems/shortest-path-visiting-all-nodes) | 访问所有节点的最短路径 | | `位运算`,`广度优先搜索`,`图`,`动态规划`,`状态压缩` | 困难 | | | +| [0848](https://leetcode-cn.com/problems/shifting-letters) | 字母移位 | | `数组`,`字符串` | 中等 | | | +| [0849](https://leetcode-cn.com/problems/maximize-distance-to-closest-person) | 到最近的人的最大距离 | | `数组` | 中等 | | | +| [0850](https://leetcode-cn.com/problems/rectangle-area-ii) | 矩形面积 II | | `线段树`,`数组`,`有序集合`,`扫描线` | 困难 | | | +| [0851](https://leetcode-cn.com/problems/loud-and-rich) | 喧闹和富有 | | `深度优先搜索`,`图`,`拓扑排序`,`数组` | 中等 | | | +| [0852](https://leetcode-cn.com/problems/peak-index-in-a-mountain-array) | 山脉数组的峰顶索引 | | `数组`,`二分查找` | 简单 | | | +| [0853](https://leetcode-cn.com/problems/car-fleet) | 车队 | | `数组`,`排序` | 中等 | | | +| [0854](https://leetcode-cn.com/problems/k-similar-strings) | 相似度为 K 的字符串 | | `广度优先搜索`,`字符串` | 困难 | | | +| [0855](https://leetcode-cn.com/problems/exam-room) | 考场就座 | | `设计`,`有序集合` | 中等 | | | +| [0856](https://leetcode-cn.com/problems/score-of-parentheses) | 括号的分数 | | `栈`,`字符串` | 中等 | | | +| [0857](https://leetcode-cn.com/problems/minimum-cost-to-hire-k-workers) | 雇佣 K 名工人的最低成本 | | `贪心`,`数组`,`排序`,`堆(优先队列)` | 困难 | | | +| [0858](https://leetcode-cn.com/problems/mirror-reflection) | 镜面反射 | | `几何`,`数学` | 中等 | | | +| [0859](https://leetcode-cn.com/problems/buddy-strings) | 亲密字符串 | | `哈希表`,`字符串` | 简单 | | | +| [0860](https://leetcode-cn.com/problems/lemonade-change) | 柠檬水找零 | | `贪心`,`数组` | 简单 | | | +| [0861](https://leetcode-cn.com/problems/score-after-flipping-matrix) | 翻转矩阵后的得分 | | `贪心`,`位运算`,`数组`,`矩阵` | 中等 | | | +| [0862](https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k) | 和至少为 K 的最短子数组 | | `队列`,`数组`,`二分查找`,`前缀和`,`滑动窗口`,`单调队列`,`堆(优先队列)` | 困难 | | | +| [0863](https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree) | 二叉树中所有距离为 K 的结点 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0864](https://leetcode-cn.com/problems/shortest-path-to-get-all-keys) | 获取所有钥匙的最短路径 | | `位运算`,`广度优先搜索` | 困难 | | | +| [0865](https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes) | 具有所有最深节点的最小子树 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | | | +| [0866](https://leetcode-cn.com/problems/prime-palindrome) | 回文素数 | | `数学` | 中等 | | | +| [0867](https://leetcode-cn.com/problems/transpose-matrix) | 转置矩阵 | | `数组`,`矩阵`,`模拟` | 简单 | | | +| [0868](https://leetcode-cn.com/problems/binary-gap) | 二进制间距 | | `位运算`,`数学` | 简单 | | | +| [0869](https://leetcode-cn.com/problems/reordered-power-of-2) | 重新排序得到 2 的幂 | | `数学`,`计数`,`枚举`,`排序` | 中等 | | | +| [0870](https://leetcode-cn.com/problems/advantage-shuffle) | 优势洗牌 | | `贪心`,`数组`,`排序` | 中等 | | | +| [0871](https://leetcode-cn.com/problems/minimum-number-of-refueling-stops) | 最低加油次数 | | `贪心`,`数组`,`动态规划`,`堆(优先队列)` | 困难 | | | +| [0872](https://leetcode-cn.com/problems/leaf-similar-trees) | 叶子相似的树 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [0873](https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence) | 最长的斐波那契子序列的长度 | | `数组`,`哈希表`,`动态规划` | 中等 | | | +| [0874](https://leetcode-cn.com/problems/walking-robot-simulation) | 模拟行走机器人 | | `数组`,`模拟` | 简单 | | | +| [0875](https://leetcode-cn.com/problems/koko-eating-bananas) | 爱吃香蕉的珂珂 | | `数组`,`二分查找` | 中等 | | | +| [0876](https://leetcode-cn.com/problems/middle-of-the-linked-list) | 链表的中间结点 | | `链表`,`双指针` | 简单 | | | +| [0877](https://leetcode-cn.com/problems/stone-game) | 石子游戏 | | `数组`,`数学`,`动态规划`,`博弈` | 中等 | | | +| [0878](https://leetcode-cn.com/problems/nth-magical-number) | 第 N 个神奇数字 | | `数学`,`二分查找` | 困难 | | | +| [0879](https://leetcode-cn.com/problems/profitable-schemes) | 盈利计划 | | `数组`,`动态规划` | 困难 | | | +| [0880](https://leetcode-cn.com/problems/decoded-string-at-index) | 索引处的解码字符串 | | `栈`,`字符串` | 中等 | | | +| [0881](https://leetcode-cn.com/problems/boats-to-save-people) | 救生艇 | | `贪心`,`数组`,`双指针`,`排序` | 中等 | | | +| [0882](https://leetcode-cn.com/problems/reachable-nodes-in-subdivided-graph) | 细分图中的可到达结点 | | `图`,`最短路`,`堆(优先队列)` | 困难 | | | +| [0883](https://leetcode-cn.com/problems/projection-area-of-3d-shapes) | 三维形体投影面积 | | `几何`,`数组`,`数学`,`矩阵` | 简单 | | | +| [0884](https://leetcode-cn.com/problems/uncommon-words-from-two-sentences) | 两句话中的不常见单词 | | `哈希表`,`字符串` | 简单 | | | +| [0885](https://leetcode-cn.com/problems/spiral-matrix-iii) | 螺旋矩阵 III | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [0886](https://leetcode-cn.com/problems/possible-bipartition) | 可能的二分法 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | | | +| [0887](https://leetcode-cn.com/problems/super-egg-drop) | 鸡蛋掉落 | | `数学`,`二分查找`,`动态规划` | 困难 | | | +| [0888](https://leetcode-cn.com/problems/fair-candy-swap) | 公平的糖果棒交换 | | `数组`,`哈希表`,`二分查找`,`排序` | 简单 | | | +| [0889](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal) | 根据前序和后序遍历构造二叉树 | | `树`,`数组`,`哈希表`,`分治`,`二叉树` | 中等 | | | +| [0890](https://leetcode-cn.com/problems/find-and-replace-pattern) | 查找和替换模式 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [0891](https://leetcode-cn.com/problems/sum-of-subsequence-widths) | 子序列宽度之和 | | `数组`,`数学`,`排序` | 困难 | | | +| [0892](https://leetcode-cn.com/problems/surface-area-of-3d-shapes) | 三维形体的表面积 | | `几何`,`数组`,`数学`,`矩阵` | 简单 | | | +| [0893](https://leetcode-cn.com/problems/groups-of-special-equivalent-strings) | 特殊等价字符串组 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0894](https://leetcode-cn.com/problems/all-possible-full-binary-trees) | 所有可能的满二叉树 | | `树`,`递归`,`记忆化搜索`,`动态规划`,`二叉树` | 中等 | | | +| [0895](https://leetcode-cn.com/problems/maximum-frequency-stack) | 最大频率栈 | | `栈`,`设计`,`哈希表`,`有序集合` | 困难 | | | +| [0896](https://leetcode-cn.com/problems/monotonic-array) | 单调数列 | | `数组` | 简单 | | | +| [0897](https://leetcode-cn.com/problems/increasing-order-search-tree) | 递增顺序搜索树 | | `栈`,`树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0898](https://leetcode-cn.com/problems/bitwise-ors-of-subarrays) | 子数组按位或操作 | | `位运算`,`数组`,`动态规划` | 中等 | | | +| [0899](https://leetcode-cn.com/problems/orderly-queue) | 有序队列 | | `数学`,`字符串`,`排序` | 困难 | | | +| [0900](https://leetcode-cn.com/problems/rle-iterator) | RLE 迭代器 | | `设计`,`数组`,`计数`,`迭代器` | 中等 | | | +| [0901](https://leetcode-cn.com/problems/online-stock-span) | 股票价格跨度 | | `栈`,`设计`,`数据流`,`单调栈` | 中等 | | | +| [0902](https://leetcode-cn.com/problems/numbers-at-most-n-given-digit-set) | 最大为 N 的数字组合 | | `数组`,`数学`,`二分查找`,`动态规划` | 困难 | | | +| [0903](https://leetcode-cn.com/problems/valid-permutations-for-di-sequence) | DI 序列的有效排列 | | `动态规划` | 困难 | | | +| [0904](https://leetcode-cn.com/problems/fruit-into-baskets) | 水果成篮 | | `数组`,`哈希表`,`滑动窗口` | 中等 | | | +| [0905](https://leetcode-cn.com/problems/sort-array-by-parity) | 按奇偶排序数组 | | `数组`,`双指针`,`排序` | 简单 | | | +| [0906](https://leetcode-cn.com/problems/super-palindromes) | 超级回文数 | | `数学`,`枚举` | 困难 | | | +| [0907](https://leetcode-cn.com/problems/sum-of-subarray-minimums) | 子数组的最小值之和 | | `栈`,`数组`,`动态规划`,`单调栈` | 中等 | | | +| [0908](https://leetcode-cn.com/problems/smallest-range-i) | 最小差值 I | | `数组`,`数学` | 简单 | | | +| [0909](https://leetcode-cn.com/problems/snakes-and-ladders) | 蛇梯棋 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [0910](https://leetcode-cn.com/problems/smallest-range-ii) | 最小差值 II | | `贪心`,`数组`,`数学`,`排序` | 中等 | | | +| [0911](https://leetcode-cn.com/problems/online-election) | 在线选举 | | `设计`,`数组`,`哈希表`,`二分查找` | 中等 | | | +| [0912](https://leetcode-cn.com/problems/sort-an-array) | 排序数组 | | `数组`,`分治`,`桶排序`,`计数排序`,`基数排序`,`排序`,`堆(优先队列)`,`归并排序` | 中等 | | | +| [0913](https://leetcode-cn.com/problems/cat-and-mouse) | 猫和老鼠 | | `广度优先搜索`,`图`,`记忆化搜索`,`数学`,`动态规划`,`博弈` | 困难 | | | +| [0914](https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards) | 卡牌分组 | | `数组`,`哈希表`,`数学`,`计数`,`数论` | 简单 | | | +| [0915](https://leetcode-cn.com/problems/partition-array-into-disjoint-intervals) | 分割数组 | | `数组` | 中等 | | | +| [0916](https://leetcode-cn.com/problems/word-subsets) | 单词子集 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [0917](https://leetcode-cn.com/problems/reverse-only-letters) | 仅仅反转字母 | | `双指针`,`字符串` | 简单 | | | +| [0918](https://leetcode-cn.com/problems/maximum-sum-circular-subarray) | 环形子数组的最大和 | | `队列`,`数组`,`分治`,`动态规划`,`单调队列` | 中等 | | | +| [0919](https://leetcode-cn.com/problems/complete-binary-tree-inserter) | 完全二叉树插入器 | | `树`,`广度优先搜索`,`设计`,`二叉树` | 中等 | | | +| [0920](https://leetcode-cn.com/problems/number-of-music-playlists) | 播放列表的数量 | | `数学`,`动态规划`,`组合数学` | 困难 | | | +| [0921](https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid) | 使括号有效的最少添加 | | `栈`,`贪心`,`字符串` | 中等 | | | +| [0922](https://leetcode-cn.com/problems/sort-array-by-parity-ii) | 按奇偶排序数组 II | | `数组`,`双指针`,`排序` | 简单 | | | +| [0923](https://leetcode-cn.com/problems/3sum-with-multiplicity) | 三数之和的多种可能 | | `数组`,`哈希表`,`双指针`,`计数`,`排序` | 中等 | | | +| [0924](https://leetcode-cn.com/problems/minimize-malware-spread) | 尽量减少恶意软件的传播 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 困难 | | | +| [0925](https://leetcode-cn.com/problems/long-pressed-name) | 长按键入 | | `双指针`,`字符串` | 简单 | | | +| [0926](https://leetcode-cn.com/problems/flip-string-to-monotone-increasing) | 将字符串翻转到单调递增 | | `字符串`,`动态规划` | 中等 | | | +| [0927](https://leetcode-cn.com/problems/three-equal-parts) | 三等分 | | `数组`,`数学` | 困难 | | | +| [0928](https://leetcode-cn.com/problems/minimize-malware-spread-ii) | 尽量减少恶意软件的传播 II | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 困难 | | | +| [0929](https://leetcode-cn.com/problems/unique-email-addresses) | 独特的电子邮件地址 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0930](https://leetcode-cn.com/problems/binary-subarrays-with-sum) | 和相同的二元子数组 | | `数组`,`哈希表`,`前缀和`,`滑动窗口` | 中等 | | | +| [0931](https://leetcode-cn.com/problems/minimum-falling-path-sum) | 下降路径最小和 | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [0932](https://leetcode-cn.com/problems/beautiful-array) | 漂亮数组 | | `数组`,`数学`,`分治` | 中等 | | | +| [0933](https://leetcode-cn.com/problems/number-of-recent-calls) | 最近的请求次数 | | `设计`,`队列`,`数据流` | 简单 | | | +| [0934](https://leetcode-cn.com/problems/shortest-bridge) | 最短的桥 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [0935](https://leetcode-cn.com/problems/knight-dialer) | 骑士拨号器 | | `动态规划` | 中等 | | | +| [0936](https://leetcode-cn.com/problems/stamping-the-sequence) | 戳印序列 | | `栈`,`贪心`,`队列`,`字符串` | 困难 | | | +| [0937](https://leetcode-cn.com/problems/reorder-data-in-log-files) | 重新排列日志文件 | | `数组`,`字符串`,`排序` | 简单 | | | +| [0938](https://leetcode-cn.com/problems/range-sum-of-bst) | 二叉搜索树的范围和 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 简单 | | | +| [0939](https://leetcode-cn.com/problems/minimum-area-rectangle) | 最小面积矩形 | | `几何`,`数组`,`哈希表`,`数学`,`排序` | 中等 | | | +| [0940](https://leetcode-cn.com/problems/distinct-subsequences-ii) | 不同的子序列 II | | `字符串`,`动态规划` | 困难 | | | +| [0941](https://leetcode-cn.com/problems/valid-mountain-array) | 有效的山脉数组 | | `数组` | 简单 | | | +| [0942](https://leetcode-cn.com/problems/di-string-match) | 增减字符串匹配 | | `贪心`,`数组`,`数学`,`双指针`,`字符串` | 简单 | | | +| [0943](https://leetcode-cn.com/problems/find-the-shortest-superstring) | 最短超级串 | | `位运算`,`数组`,`字符串`,`动态规划`,`状态压缩` | 困难 | | | +| [0944](https://leetcode-cn.com/problems/delete-columns-to-make-sorted) | 删列造序 | | `数组`,`字符串` | 简单 | | | +| [0945](https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique) | 使数组唯一的最小增量 | | `贪心`,`数组`,`计数`,`排序` | 中等 | | | +| [0946](https://leetcode-cn.com/problems/validate-stack-sequences) | 验证栈序列 | | `栈`,`数组`,`模拟` | 中等 | | | +| [0947](https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column) | 移除最多的同行或同列石头 | | `深度优先搜索`,`并查集`,`图` | 中等 | | | +| [0948](https://leetcode-cn.com/problems/bag-of-tokens) | 令牌放置 | | `贪心`,`数组`,`双指针`,`排序` | 中等 | | | +| [0949](https://leetcode-cn.com/problems/largest-time-for-given-digits) | 给定数字能组成的最大时间 | | `字符串`,`枚举` | 中等 | | | +| [0950](https://leetcode-cn.com/problems/reveal-cards-in-increasing-order) | 按递增顺序显示卡牌 | | `队列`,`数组`,`排序`,`模拟` | 中等 | | | +| [0951](https://leetcode-cn.com/problems/flip-equivalent-binary-trees) | 翻转等价二叉树 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0952](https://leetcode-cn.com/problems/largest-component-size-by-common-factor) | 按公因数计算最大组件大小 | | `并查集`,`数组`,`数学` | 困难 | | | +| [0953](https://leetcode-cn.com/problems/verifying-an-alien-dictionary) | 验证外星语词典 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [0954](https://leetcode-cn.com/problems/array-of-doubled-pairs) | 二倍数对数组 | | `贪心`,`数组`,`哈希表`,`排序` | 中等 | | | +| [0955](https://leetcode-cn.com/problems/delete-columns-to-make-sorted-ii) | 删列造序 II | | `贪心`,`数组`,`字符串` | 中等 | | | +| [0956](https://leetcode-cn.com/problems/tallest-billboard) | 最高的广告牌 | | `数组`,`动态规划` | 困难 | | | +| [0957](https://leetcode-cn.com/problems/prison-cells-after-n-days) | N 天后的牢房 | | `位运算`,`数组`,`哈希表`,`数学` | 中等 | | | +| [0958](https://leetcode-cn.com/problems/check-completeness-of-a-binary-tree) | 二叉树的完全性检验 | | `树`,`广度优先搜索`,`二叉树` | 中等 | | | +| [0959](https://leetcode-cn.com/problems/regions-cut-by-slashes) | 由斜杠划分区域 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | | | +| [0960](https://leetcode-cn.com/problems/delete-columns-to-make-sorted-iii) | 删列造序 III | | `数组`,`字符串`,`动态规划` | 困难 | | | +| [0961](https://leetcode-cn.com/problems/n-repeated-element-in-size-2n-array) | 重复 N 次的元素 | | `数组`,`哈希表` | 简单 | | | +| [0962](https://leetcode-cn.com/problems/maximum-width-ramp) | 最大宽度坡 | | `栈`,`数组`,`单调栈` | 中等 | | | +| [0963](https://leetcode-cn.com/problems/minimum-area-rectangle-ii) | 最小面积矩形 II | | `几何`,`数组`,`数学` | 中等 | | | +| [0964](https://leetcode-cn.com/problems/least-operators-to-express-number) | 表示数字的最少运算符 | | `数学`,`动态规划` | 困难 | | | +| [0965](https://leetcode-cn.com/problems/univalued-binary-tree) | 单值二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0966](https://leetcode-cn.com/problems/vowel-spellchecker) | 元音拼写检查器 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [0967](https://leetcode-cn.com/problems/numbers-with-same-consecutive-differences) | 连续差相同的数字 | | `广度优先搜索`,`回溯` | 中等 | | | +| [0968](https://leetcode-cn.com/problems/binary-tree-cameras) | 监控二叉树 | | `树`,`深度优先搜索`,`动态规划`,`二叉树` | 困难 | | | +| [0969](https://leetcode-cn.com/problems/pancake-sorting) | 煎饼排序 | | `贪心`,`数组`,`双指针`,`排序` | 中等 | | | +| [0970](https://leetcode-cn.com/problems/powerful-integers) | 强整数 | | `哈希表`,`数学` | 中等 | | | +| [0971](https://leetcode-cn.com/problems/flip-binary-tree-to-match-preorder-traversal) | 翻转二叉树以匹配先序遍历 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0972](https://leetcode-cn.com/problems/equal-rational-numbers) | 相等的有理数 | | `数学`,`字符串` | 困难 | | | +| [0973](https://leetcode-cn.com/problems/k-closest-points-to-origin) | 最接近原点的 K 个点 | | `几何`,`数组`,`数学`,`分治`,`快速选择`,`排序`,`堆(优先队列)` | 中等 | | | +| [0974](https://leetcode-cn.com/problems/subarray-sums-divisible-by-k) | 和可被 K 整除的子数组 | | `数组`,`哈希表`,`前缀和` | 中等 | | | +| [0975](https://leetcode-cn.com/problems/odd-even-jump) | 奇偶跳 | | `栈`,`数组`,`动态规划`,`有序集合`,`单调栈` | 困难 | | | +| [0976](https://leetcode-cn.com/problems/largest-perimeter-triangle) | 三角形的最大周长 | | `贪心`,`数组`,`数学`,`排序` | 简单 | | ✅ | +| [0977](https://leetcode-cn.com/problems/squares-of-a-sorted-array) | 有序数组的平方 | | `数组`,`双指针`,`排序` | 简单 | | ✅ | +| [0978](https://leetcode-cn.com/problems/longest-turbulent-subarray) | 最长湍流子数组 | | `数组`,`动态规划`,`滑动窗口` | 中等 | | | +| [0979](https://leetcode-cn.com/problems/distribute-coins-in-binary-tree) | 在二叉树中分配硬币 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [0980](https://leetcode-cn.com/problems/unique-paths-iii) | 不同路径 III | | `位运算`,`数组`,`回溯`,`矩阵` | 困难 | | | +| [0981](https://leetcode-cn.com/problems/time-based-key-value-store) | 基于时间的键值存储 | | `设计`,`哈希表`,`字符串`,`二分查找` | 中等 | | | +| [0982](https://leetcode-cn.com/problems/triples-with-bitwise-and-equal-to-zero) | 按位与为零的三元组 | | `位运算`,`数组`,`哈希表` | 困难 | | | +| [0983](https://leetcode-cn.com/problems/minimum-cost-for-tickets) | 最低票价 | | `数组`,`动态规划` | 中等 | | | +| [0984](https://leetcode-cn.com/problems/string-without-aaa-or-bbb) | 不含 AAA 或 BBB 的字符串 | | `贪心`,`字符串` | 中等 | | | +| [0985](https://leetcode-cn.com/problems/sum-of-even-numbers-after-queries) | 查询后的偶数和 | | `数组`,`模拟` | 简单 | | | +| [0986](https://leetcode-cn.com/problems/interval-list-intersections) | 区间列表的交集 | | `数组`,`双指针` | 中等 | | | +| [0987](https://leetcode-cn.com/problems/vertical-order-traversal-of-a-binary-tree) | 二叉树的垂序遍历 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 困难 | | | +| [0988](https://leetcode-cn.com/problems/smallest-string-starting-from-leaf) | 从叶结点开始的最小字符串 | | `树`,`深度优先搜索`,`字符串`,`二叉树` | 中等 | | | +| [0989](https://leetcode-cn.com/problems/add-to-array-form-of-integer) | 数组形式的整数加法 | | `数组`,`数学` | 简单 | | | +| [0990](https://leetcode-cn.com/problems/satisfiability-of-equality-equations) | 等式方程的可满足性 | | `并查集`,`图`,`数组`,`字符串` | 中等 | | | +| [0991](https://leetcode-cn.com/problems/broken-calculator) | 坏了的计算器 | | `贪心`,`数学` | 中等 | | | +| [0992](https://leetcode-cn.com/problems/subarrays-with-k-different-integers) | K 个不同整数的子数组 | | `数组`,`哈希表`,`计数`,`滑动窗口` | 困难 | | | +| [0993](https://leetcode-cn.com/problems/cousins-in-binary-tree) | 二叉树的堂兄弟节点 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | | | +| [0994](https://leetcode-cn.com/problems/rotting-oranges) | 腐烂的橘子 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [0995](https://leetcode-cn.com/problems/minimum-number-of-k-consecutive-bit-flips) | K 连续位的最小翻转次数 | | `位运算`,`数组`,`前缀和`,`滑动窗口` | 困难 | | | +| [0996](https://leetcode-cn.com/problems/number-of-squareful-arrays) | 正方形数组的数目 | | `位运算`,`数组`,`数学`,`动态规划`,`回溯`,`状态压缩` | 困难 | | | +| [0997](https://leetcode-cn.com/problems/find-the-town-judge) | 找到小镇的法官 | | `图`,`数组`,`哈希表` | 简单 | | | +| [0998](https://leetcode-cn.com/problems/maximum-binary-tree-ii) | 最大二叉树 II | | `树`,`二叉树` | 中等 | | | +| [0999](https://leetcode-cn.com/problems/available-captures-for-rook) | 可以被一步捕获的棋子数 | | `数组`,`矩阵`,`模拟` | 简单 | | | +| [1000](https://leetcode-cn.com/problems/minimum-cost-to-merge-stones) | 合并石头的最低成本 | | `数组`,`动态规划` | 困难 | | | +| [1001](https://leetcode-cn.com/problems/grid-illumination) | 网格照明 | | `数组`,`哈希表` | 困难 | | | +| [1002](https://leetcode-cn.com/problems/find-common-characters) | 查找常用字符 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [1003](https://leetcode-cn.com/problems/check-if-word-is-valid-after-substitutions) | 检查替换后的词是否有效 | | `栈`,`字符串` | 中等 | | | +| [1004](https://leetcode-cn.com/problems/max-consecutive-ones-iii) | 最大连续1的个数 III | | `数组`,`二分查找`,`前缀和`,`滑动窗口` | 中等 | | | +| [1005](https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations) | K 次取反后最大化的数组和 | | `贪心`,`数组`,`排序` | 简单 | | | +| [1006](https://leetcode-cn.com/problems/clumsy-factorial) | 笨阶乘 | | `栈`,`数学`,`模拟` | 中等 | | | +| [1007](https://leetcode-cn.com/problems/minimum-domino-rotations-for-equal-row) | 行相等的最少多米诺旋转 | | `贪心`,`数组` | 中等 | | | +| [1008](https://leetcode-cn.com/problems/construct-binary-search-tree-from-preorder-traversal) | 前序遍历构造二叉搜索树 | | `栈`,`树`,`二叉搜索树`,`数组`,`二叉树`,`单调栈` | 中等 | | | +| [1009](https://leetcode-cn.com/problems/complement-of-base-10-integer) | 十进制整数的反码 | | `位运算` | 简单 | | | +| [1010](https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) | 总持续时间可被 60 整除的歌曲 | | `数组`,`哈希表`,`计数` | 中等 | | | +| [1011](https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days) | 在 D 天内送达包裹的能力 | | `贪心`,`数组`,`二分查找` | 中等 | | | +| [1012](https://leetcode-cn.com/problems/numbers-with-repeated-digits) | 至少有 1 位重复的数字 | | `数学`,`动态规划` | 困难 | | | +| [1013](https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum) | 将数组分成和相等的三个部分 | | `贪心`,`数组` | 简单 | | | +| [1014](https://leetcode-cn.com/problems/best-sightseeing-pair) | 最佳观光组合 | | `数组`,`动态规划` | 中等 | | | +| [1015](https://leetcode-cn.com/problems/smallest-integer-divisible-by-k) | 可被 K 整除的最小整数 | | `哈希表`,`数学` | 中等 | | | +| [1016](https://leetcode-cn.com/problems/binary-string-with-substrings-representing-1-to-n) | 子串能表示从 1 到 N 数字的二进制串 | | `字符串` | 中等 | | | +| [1017](https://leetcode-cn.com/problems/convert-to-base-2) | 负二进制转换 | | `数学` | 中等 | | | +| [1018](https://leetcode-cn.com/problems/binary-prefix-divisible-by-5) | 可被 5 整除的二进制前缀 | | `数组` | 简单 | | | +| [1019](https://leetcode-cn.com/problems/next-greater-node-in-linked-list) | 链表中的下一个更大节点 | | `栈`,`数组`,`链表`,`单调栈` | 中等 | | | +| [1020](https://leetcode-cn.com/problems/number-of-enclaves) | 飞地的数量 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [1021](https://leetcode-cn.com/problems/remove-outermost-parentheses) | 删除最外层的括号 | | `栈`,`字符串` | 简单 | | | +| [1022](https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers) | 从根到叶的二进制数之和 | | `树`,`深度优先搜索`,`二叉树` | 简单 | | | +| [1023](https://leetcode-cn.com/problems/camelcase-matching) | 驼峰式匹配 | | `字典树`,`双指针`,`字符串`,`字符串匹配` | 中等 | | | +| [1024](https://leetcode-cn.com/problems/video-stitching) | 视频拼接 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [1025](https://leetcode-cn.com/problems/divisor-game) | 除数博弈 | | `脑筋急转弯`,`数学`,`动态规划`,`博弈` | 简单 | | | +| [1026](https://leetcode-cn.com/problems/maximum-difference-between-node-and-ancestor) | 节点与其祖先之间的最大差值 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [1027](https://leetcode-cn.com/problems/longest-arithmetic-subsequence) | 最长等差数列 | | `数组`,`哈希表`,`二分查找`,`动态规划` | 中等 | | | +| [1028](https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal) | 从先序遍历还原二叉树 | | `树`,`深度优先搜索`,`字符串`,`二叉树` | 困难 | | | +| [1029](https://leetcode-cn.com/problems/two-city-scheduling) | 两地调度 | | `贪心`,`数组`,`排序` | 中等 | | | +| [1030](https://leetcode-cn.com/problems/matrix-cells-in-distance-order) | 距离顺序排列矩阵单元格 | | `几何`,`数组`,`数学`,`矩阵`,`排序` | 简单 | | | +| [1031](https://leetcode-cn.com/problems/maximum-sum-of-two-non-overlapping-subarrays) | 两个非重叠子数组的最大和 | | `数组`,`动态规划`,`滑动窗口` | 中等 | | | +| [1032](https://leetcode-cn.com/problems/stream-of-characters) | 字符流 | | `设计`,`字典树`,`数组`,`字符串`,`数据流` | 困难 | | | +| [1033](https://leetcode-cn.com/problems/moving-stones-until-consecutive) | 移动石子直到连续 | | `脑筋急转弯`,`数学` | 简单 | | | +| [1034](https://leetcode-cn.com/problems/coloring-a-border) | 边框着色 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [1035](https://leetcode-cn.com/problems/uncrossed-lines) | 不相交的线 | | `数组`,`动态规划` | 中等 | | | +| [1036](https://leetcode-cn.com/problems/escape-a-large-maze) | 逃离大迷宫 | | `深度优先搜索`,`广度优先搜索`,`数组`,`哈希表` | 困难 | | | +| [1037](https://leetcode-cn.com/problems/valid-boomerang) | 有效的回旋镖 | | `几何`,`数学` | 简单 | | | +| [1038](https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree) | 把二叉搜索树转换为累加树 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树` | 中等 | | | +| [1039](https://leetcode-cn.com/problems/minimum-score-triangulation-of-polygon) | 多边形三角剖分的最低得分 | | `数组`,`动态规划` | 中等 | | | +| [1040](https://leetcode-cn.com/problems/moving-stones-until-consecutive-ii) | 移动石子直到连续 II | | `数组`,`数学`,`双指针`,`排序` | 中等 | | | +| [1041](https://leetcode-cn.com/problems/robot-bounded-in-circle) | 困于环中的机器人 | | `数学`,`字符串`,`模拟` | 中等 | | | +| [1042](https://leetcode-cn.com/problems/flower-planting-with-no-adjacent) | 不邻接植花 | | `深度优先搜索`,`广度优先搜索`,`图` | 中等 | | | +| [1043](https://leetcode-cn.com/problems/partition-array-for-maximum-sum) | 分隔数组以得到最大和 | | `数组`,`动态规划` | 中等 | | | +| [1044](https://leetcode-cn.com/problems/longest-duplicate-substring) | 最长重复子串 | | `字符串`,`二分查找`,`后缀数组`,`滑动窗口`,`哈希函数`,`滚动哈希` | 困难 | | | +| [1045](https://leetcode-cn.com/problems/customers-who-bought-all-products) | 买下所有产品的客户 | | `数据库` | 中等 | 🔒 | | +| [1046](https://leetcode-cn.com/problems/last-stone-weight) | 最后一块石头的重量 | | `数组`,`堆(优先队列)` | 简单 | | | +| [1047](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string) | 删除字符串中的所有相邻重复项 | | `栈`,`字符串` | 简单 | | | +| [1048](https://leetcode-cn.com/problems/longest-string-chain) | 最长字符串链 | | `数组`,`哈希表`,`双指针`,`字符串`,`动态规划` | 中等 | | | +| [1049](https://leetcode-cn.com/problems/last-stone-weight-ii) | 最后一块石头的重量 II | | `数组`,`动态规划` | 中等 | | | +| [1050](https://leetcode-cn.com/problems/actors-and-directors-who-cooperated-at-least-three-times) | 合作过至少三次的演员和导演 | | `数据库` | 简单 | 🔒 | | +| [1051](https://leetcode-cn.com/problems/height-checker) | 高度检查器 | | `数组`,`计数排序`,`排序` | 简单 | | | +| [1052](https://leetcode-cn.com/problems/grumpy-bookstore-owner) | 爱生气的书店老板 | | `数组`,`滑动窗口` | 中等 | | | +| [1053](https://leetcode-cn.com/problems/previous-permutation-with-one-swap) | 交换一次的先前排列 | | `贪心`,`数组` | 中等 | | | +| [1054](https://leetcode-cn.com/problems/distant-barcodes) | 距离相等的条形码 | | `贪心`,`数组`,`哈希表`,`计数`,`排序`,`堆(优先队列)` | 中等 | | | +| [1055](https://leetcode-cn.com/problems/shortest-way-to-form-string) | 形成字符串的最短路径 | | `贪心`,`字符串`,`动态规划` | 中等 | 🔒 | | +| [1057](https://leetcode-cn.com/problems/campus-bikes) | 校园自行车分配 | | `贪心`,`数组`,`排序` | 中等 | 🔒 | | +| [1058](https://leetcode-cn.com/problems/minimize-rounding-error-to-meet-target) | 最小化舍入误差以满足目标 | | `贪心`,`数组`,`数学`,`字符串` | 中等 | 🔒 | | +| [1059](https://leetcode-cn.com/problems/all-paths-from-source-lead-to-destination) | 从始点到终点的所有路径 | | `深度优先搜索`,`图` | 中等 | 🔒 | | +| [1060](https://leetcode-cn.com/problems/missing-element-in-sorted-array) | 有序数组中的缺失元素 | | `数组`,`二分查找` | 中等 | 🔒 | | +| [1061](https://leetcode-cn.com/problems/lexicographically-smallest-equivalent-string) | 按字典序排列最小的等效字符串 | | `并查集`,`字符串` | 中等 | 🔒 | | +| [1062](https://leetcode-cn.com/problems/longest-repeating-substring) | 最长重复子串 | | `字符串`,`二分查找`,`动态规划`,`后缀数组`,`哈希函数`,`滚动哈希` | 中等 | 🔒 | | +| [1063](https://leetcode-cn.com/problems/number-of-valid-subarrays) | 有效子数组的数目 | | `栈`,`数组`,`单调栈` | 困难 | 🔒 | | +| [1064](https://leetcode-cn.com/problems/fixed-point) | 不动点 | | `数组`,`二分查找` | 简单 | 🔒 | | +| [1065](https://leetcode-cn.com/problems/index-pairs-of-a-string) | 字符串的索引对 | | `字典树`,`数组`,`字符串`,`排序` | 简单 | 🔒 | | +| [1066](https://leetcode-cn.com/problems/campus-bikes-ii) | 校园自行车分配 II | | `位运算`,`数组`,`动态规划`,`回溯`,`状态压缩` | 中等 | 🔒 | | +| [1067](https://leetcode-cn.com/problems/digit-count-in-range) | 范围内的数字计数 | | `数学`,`动态规划` | 困难 | 🔒 | | +| [1068](https://leetcode-cn.com/problems/product-sales-analysis-i) | 产品销售分析 I | | `数据库` | 简单 | 🔒 | | +| [1069](https://leetcode-cn.com/problems/product-sales-analysis-ii) | 产品销售分析 II | | `数据库` | 简单 | 🔒 | | +| [1070](https://leetcode-cn.com/problems/product-sales-analysis-iii) | 产品销售分析 III | | `数据库` | 中等 | 🔒 | | +| [1071](https://leetcode-cn.com/problems/greatest-common-divisor-of-strings) | 字符串的最大公因子 | | `数学`,`字符串` | 简单 | | | +| [1072](https://leetcode-cn.com/problems/flip-columns-for-maximum-number-of-equal-rows) | 按列翻转得到最大值等行数 | | `数组`,`哈希表`,`矩阵` | 中等 | | | +| [1073](https://leetcode-cn.com/problems/adding-two-negabinary-numbers) | 负二进制数相加 | | `数组`,`数学` | 中等 | | | +| [1074](https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target) | 元素和为目标值的子矩阵数量 | | `数组`,`哈希表`,`矩阵`,`前缀和` | 困难 | | | +| [1075](https://leetcode-cn.com/problems/project-employees-i) | 项目员工 I | | `数据库` | 简单 | 🔒 | | +| [1076](https://leetcode-cn.com/problems/project-employees-ii) | 项目员工II | | `数据库` | 简单 | 🔒 | | +| [1077](https://leetcode-cn.com/problems/project-employees-iii) | 项目员工 III | | `数据库` | 中等 | 🔒 | | +| [1078](https://leetcode-cn.com/problems/occurrences-after-bigram) | Bigram 分词 | | `字符串` | 简单 | | | +| [1079](https://leetcode-cn.com/problems/letter-tile-possibilities) | 活字印刷 | | `字符串`,`回溯` | 中等 | | | +| [1080](https://leetcode-cn.com/problems/insufficient-nodes-in-root-to-leaf-paths) | 根到叶路径上的不足节点 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [1081](https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters) | 不同字符的最小子序列 | | `栈`,`贪心`,`字符串`,`单调栈` | 中等 | | | +| [1082](https://leetcode-cn.com/problems/sales-analysis-i) | 销售分析 I | | `数据库` | 简单 | 🔒 | | +| [1083](https://leetcode-cn.com/problems/sales-analysis-ii) | 销售分析 II | | `数据库` | 简单 | 🔒 | | +| [1084](https://leetcode-cn.com/problems/sales-analysis-iii) | 销售分析III | | `数据库` | 简单 | 🔒 | | +| [1085](https://leetcode-cn.com/problems/sum-of-digits-in-the-minimum-number) | 最小元素各数位之和 | | `数组`,`数学` | 简单 | 🔒 | | +| [1086](https://leetcode-cn.com/problems/high-five) | 前五科的均分 | | `数组`,`哈希表`,`排序` | 简单 | 🔒 | | +| [1087](https://leetcode-cn.com/problems/brace-expansion) | 花括号展开 | | `广度优先搜索`,`字符串`,`回溯` | 中等 | 🔒 | | +| [1088](https://leetcode-cn.com/problems/confusing-number-ii) | 易混淆数 II | | `数学`,`回溯` | 困难 | 🔒 | | +| [1089](https://leetcode-cn.com/problems/duplicate-zeros) | 复写零 | | `数组`,`双指针` | 简单 | | | +| [1090](https://leetcode-cn.com/problems/largest-values-from-labels) | 受标签影响的最大值 | | `贪心`,`数组`,`哈希表`,`计数`,`排序` | 中等 | | | +| [1091](https://leetcode-cn.com/problems/shortest-path-in-binary-matrix) | 二进制矩阵中的最短路径 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [1092](https://leetcode-cn.com/problems/shortest-common-supersequence) | 最短公共超序列 | | `字符串`,`动态规划` | 困难 | | | +| [1093](https://leetcode-cn.com/problems/statistics-from-a-large-sample) | 大样本统计 | | `数学`,`双指针`,`概率与统计` | 中等 | | | +| [1094](https://leetcode-cn.com/problems/car-pooling) | 拼车 | | `数组`,`前缀和`,`排序`,`模拟`,`堆(优先队列)` | 中等 | | | +| [1095](https://leetcode-cn.com/problems/find-in-mountain-array) | 山脉数组中查找目标值 | | `数组`,`二分查找`,`交互` | 困难 | | | +| [1096](https://leetcode-cn.com/problems/brace-expansion-ii) | 花括号展开 II | | `栈`,`广度优先搜索`,`字符串`,`回溯` | 困难 | | | +| [1097](https://leetcode-cn.com/problems/game-play-analysis-v) | 游戏玩法分析 V | | `数据库` | 困难 | 🔒 | | +| [1098](https://leetcode-cn.com/problems/unpopular-books) | 小众书籍 | | `数据库` | 中等 | 🔒 | | +| [1099](https://leetcode-cn.com/problems/two-sum-less-than-k) | 小于 K 的两数之和 | | `数组`,`双指针`,`二分查找`,`排序` | 简单 | 🔒 | | +| [1100](https://leetcode-cn.com/problems/find-k-length-substrings-with-no-repeated-characters) | 长度为 K 的无重复字符子串 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | 🔒 | | +| [1101](https://leetcode-cn.com/problems/the-earliest-moment-when-everyone-become-friends) | 彼此熟识的最早时间 | | `并查集`,`数组` | 中等 | 🔒 | | +| [1102](https://leetcode-cn.com/problems/path-with-maximum-minimum-value) | 得分最高的路径 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵`,`堆(优先队列)` | 中等 | 🔒 | | +| [1103](https://leetcode-cn.com/problems/distribute-candies-to-people) | 分糖果 II | | `数学`,`模拟` | 简单 | | | +| [1104](https://leetcode-cn.com/problems/path-in-zigzag-labelled-binary-tree) | 二叉树寻路 | | `树`,`数学`,`二叉树` | 中等 | | | +| [1105](https://leetcode-cn.com/problems/filling-bookcase-shelves) | 填充书架 | | `数组`,`动态规划` | 中等 | | | +| [1106](https://leetcode-cn.com/problems/parsing-a-boolean-expression) | 解析布尔表达式 | | `栈`,`递归`,`字符串` | 困难 | | | +| [1107](https://leetcode-cn.com/problems/new-users-daily-count) | 每日新用户统计 | | `数据库` | 中等 | 🔒 | | +| [1108](https://leetcode-cn.com/problems/defanging-an-ip-address) | IP 地址无效化 | | `字符串` | 简单 | | | +| [1109](https://leetcode-cn.com/problems/corporate-flight-bookings) | 航班预订统计 | | `数组`,`前缀和` | 中等 | | | +| [1110](https://leetcode-cn.com/problems/delete-nodes-and-return-forest) | 删点成林 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [1111](https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings) | 有效括号的嵌套深度 | | `栈`,`字符串` | 中等 | | | +| [1112](https://leetcode-cn.com/problems/highest-grade-for-each-student) | 每位学生的最高成绩 | | `数据库` | 中等 | 🔒 | | +| [1113](https://leetcode-cn.com/problems/reported-posts) | 报告的记录 | | `数据库` | 简单 | 🔒 | | +| [1114](https://leetcode-cn.com/problems/print-in-order) | 按序打印 | | `多线程` | 简单 | | | +| [1115](https://leetcode-cn.com/problems/print-foobar-alternately) | 交替打印FooBar | | `多线程` | 中等 | | | +| [1116](https://leetcode-cn.com/problems/print-zero-even-odd) | 打印零与奇偶数 | | `多线程` | 中等 | | | +| [1117](https://leetcode-cn.com/problems/building-h2o) | H2O 生成 | | `多线程` | 中等 | | | +| [1118](https://leetcode-cn.com/problems/number-of-days-in-a-month) | 一月有多少天 | | `数学` | 简单 | 🔒 | | +| [1119](https://leetcode-cn.com/problems/remove-vowels-from-a-string) | 删去字符串中的元音 | | `字符串` | 简单 | 🔒 | | +| [1120](https://leetcode-cn.com/problems/maximum-average-subtree) | 子树的最大平均值 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1121](https://leetcode-cn.com/problems/divide-array-into-increasing-sequences) | 将数组分成几个递增序列 | | `贪心`,`数组` | 困难 | 🔒 | | +| [1122](https://leetcode-cn.com/problems/relative-sort-array) | 数组的相对排序 | | `数组`,`哈希表`,`计数排序`,`排序` | 简单 | | | +| [1123](https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves) | 最深叶节点的最近公共祖先 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | | | +| [1124](https://leetcode-cn.com/problems/longest-well-performing-interval) | 表现良好的最长时间段 | | `栈`,`数组`,`哈希表`,`前缀和`,`单调栈` | 中等 | | | +| [1125](https://leetcode-cn.com/problems/smallest-sufficient-team) | 最小的必要团队 | | `位运算`,`数组`,`动态规划`,`状态压缩` | 困难 | | | +| [1126](https://leetcode-cn.com/problems/active-businesses) | 查询活跃业务 | | `数据库` | 中等 | 🔒 | | +| [1127](https://leetcode-cn.com/problems/user-purchase-platform) | 用户购买平台 | | `数据库` | 困难 | 🔒 | | +| [1128](https://leetcode-cn.com/problems/number-of-equivalent-domino-pairs) | 等价多米诺骨牌对的数量 | | `数组`,`哈希表`,`计数` | 简单 | | | +| [1129](https://leetcode-cn.com/problems/shortest-path-with-alternating-colors) | 颜色交替的最短路径 | | `广度优先搜索`,`图` | 中等 | | | +| [1130](https://leetcode-cn.com/problems/minimum-cost-tree-from-leaf-values) | 叶值的最小代价生成树 | | `栈`,`贪心`,`动态规划`,`单调栈` | 中等 | | | +| [1131](https://leetcode-cn.com/problems/maximum-of-absolute-value-expression) | 绝对值表达式的最大值 | | `数组`,`数学` | 中等 | | | +| [1132](https://leetcode-cn.com/problems/reported-posts-ii) | 报告的记录 II | | `数据库` | 中等 | 🔒 | | +| [1133](https://leetcode-cn.com/problems/largest-unique-number) | 最大唯一数 | | `数组`,`哈希表`,`排序` | 简单 | 🔒 | | +| [1134](https://leetcode-cn.com/problems/armstrong-number) | 阿姆斯特朗数 | | `数学` | 简单 | 🔒 | | +| [1135](https://leetcode-cn.com/problems/connecting-cities-with-minimum-cost) | 最低成本联通所有城市 | | `并查集`,`图`,`最小生成树`,`堆(优先队列)` | 中等 | 🔒 | | +| [1136](https://leetcode-cn.com/problems/parallel-courses) | 平行课程 | | `图`,`拓扑排序` | 中等 | 🔒 | | +| [1137](https://leetcode-cn.com/problems/n-th-tribonacci-number) | 第 N 个泰波那契数 | | `记忆化搜索`,`数学`,`动态规划` | 简单 | | | +| [1138](https://leetcode-cn.com/problems/alphabet-board-path) | 字母板上的路径 | | `哈希表`,`字符串` | 中等 | | | +| [1139](https://leetcode-cn.com/problems/largest-1-bordered-square) | 最大的以 1 为边界的正方形 | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [1140](https://leetcode-cn.com/problems/stone-game-ii) | 石子游戏 II | | `数组`,`数学`,`动态规划`,`博弈` | 中等 | | | +| [1141](https://leetcode-cn.com/problems/user-activity-for-the-past-30-days-i) | 查询近30天活跃用户数 | | `数据库` | 简单 | 🔒 | | +| [1142](https://leetcode-cn.com/problems/user-activity-for-the-past-30-days-ii) | 过去30天的用户活动 II | | `数据库` | 简单 | 🔒 | | +| [1143](https://leetcode-cn.com/problems/longest-common-subsequence) | 最长公共子序列 | | `字符串`,`动态规划` | 中等 | | | +| [1144](https://leetcode-cn.com/problems/decrease-elements-to-make-array-zigzag) | 递减元素使数组呈锯齿状 | | `贪心`,`数组` | 中等 | | | +| [1145](https://leetcode-cn.com/problems/binary-tree-coloring-game) | 二叉树着色游戏 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [1146](https://leetcode-cn.com/problems/snapshot-array) | 快照数组 | | `设计`,`数组`,`哈希表`,`二分查找` | 中等 | | | +| [1147](https://leetcode-cn.com/problems/longest-chunked-palindrome-decomposition) | 段式回文 | | `贪心`,`双指针`,`字符串`,`动态规划`,`哈希函数`,`滚动哈希` | 困难 | | | +| [1148](https://leetcode-cn.com/problems/article-views-i) | 文章浏览 I | | `数据库` | 简单 | 🔒 | | +| [1149](https://leetcode-cn.com/problems/article-views-ii) | 文章浏览 II | | `数据库` | 中等 | 🔒 | | +| [1150](https://leetcode-cn.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) | 检查一个数是否在数组中占绝大多数 | | `数组`,`二分查找` | 简单 | 🔒 | | +| [1151](https://leetcode-cn.com/problems/minimum-swaps-to-group-all-1s-together) | 最少交换次数来组合所有的 1 | | `数组`,`滑动窗口` | 中等 | 🔒 | | +| [1152](https://leetcode-cn.com/problems/analyze-user-website-visit-pattern) | 用户网站访问行为分析 | | `数组`,`哈希表`,`排序` | 中等 | 🔒 | | +| [1153](https://leetcode-cn.com/problems/string-transforms-into-another-string) | 字符串转化 | | `哈希表`,`字符串` | 困难 | 🔒 | | +| [1154](https://leetcode-cn.com/problems/day-of-the-year) | 一年中的第几天 | | `数学`,`字符串` | 简单 | | | +| [1155](https://leetcode-cn.com/problems/number-of-dice-rolls-with-target-sum) | 掷骰子的N种方法 | | `动态规划` | 中等 | | | +| [1156](https://leetcode-cn.com/problems/swap-for-longest-repeated-character-substring) | 单字符重复子串的最大长度 | | `字符串`,`滑动窗口` | 中等 | | | +| [1157](https://leetcode-cn.com/problems/online-majority-element-in-subarray) | 子数组中占绝大多数的元素 | | `设计`,`树状数组`,`线段树`,`数组`,`二分查找` | 困难 | | | +| [1158](https://leetcode-cn.com/problems/market-analysis-i) | 市场分析 I | | `数据库` | 中等 | 🔒 | | +| [1159](https://leetcode-cn.com/problems/market-analysis-ii) | 市场分析 II | | `数据库` | 困难 | 🔒 | | +| [1160](https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters) | 拼写单词 | | `数组`,`哈希表`,`字符串` | 简单 | | | +| [1161](https://leetcode-cn.com/problems/maximum-level-sum-of-a-binary-tree) | 最大层内元素和 | | `树`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1162](https://leetcode-cn.com/problems/as-far-from-land-as-possible) | 地图分析 | | `广度优先搜索`,`数组`,`动态规划`,`矩阵` | 中等 | | | +| [1163](https://leetcode-cn.com/problems/last-substring-in-lexicographical-order) | 按字典序排在最后的子串 | | `双指针`,`字符串` | 困难 | | | +| [1164](https://leetcode-cn.com/problems/product-price-at-a-given-date) | 指定日期的产品价格 | | `数据库` | 中等 | 🔒 | | +| [1165](https://leetcode-cn.com/problems/single-row-keyboard) | 单行键盘 | | `哈希表`,`字符串` | 简单 | 🔒 | | +| [1166](https://leetcode-cn.com/problems/design-file-system) | 设计文件系统 | | `设计`,`字典树`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [1167](https://leetcode-cn.com/problems/minimum-cost-to-connect-sticks) | 连接棒材的最低费用 | | `贪心`,`数组`,`堆(优先队列)` | 中等 | 🔒 | | +| [1168](https://leetcode-cn.com/problems/optimize-water-distribution-in-a-village) | 水资源分配优化 | | `并查集`,`图`,`最小生成树` | 困难 | 🔒 | | +| [1169](https://leetcode-cn.com/problems/invalid-transactions) | 查询无效交易 | | `数组`,`哈希表`,`字符串`,`排序` | 中等 | | | +| [1170](https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character) | 比较字符串最小字母出现频次 | | `数组`,`哈希表`,`字符串`,`二分查找`,`排序` | 中等 | | | +| [1171](https://leetcode-cn.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list) | 从链表中删去总和值为零的连续节点 | | `哈希表`,`链表` | 中等 | | | +| [1172](https://leetcode-cn.com/problems/dinner-plate-stacks) | 餐盘栈 | | `栈`,`设计`,`哈希表`,`堆(优先队列)` | 困难 | | | +| [1173](https://leetcode-cn.com/problems/immediate-food-delivery-i) | 即时食物配送 I | | `数据库` | 简单 | 🔒 | | +| [1174](https://leetcode-cn.com/problems/immediate-food-delivery-ii) | 即时食物配送 II | | `数据库` | 中等 | 🔒 | | +| [1175](https://leetcode-cn.com/problems/prime-arrangements) | 质数排列 | | `数学` | 简单 | | | +| [1176](https://leetcode-cn.com/problems/diet-plan-performance) | 健身计划评估 | | `数组`,`滑动窗口` | 简单 | 🔒 | | +| [1177](https://leetcode-cn.com/problems/can-make-palindrome-from-substring) | 构建回文串检测 | | `位运算`,`哈希表`,`字符串`,`前缀和` | 中等 | | | +| [1178](https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle) | 猜字谜 | | `位运算`,`字典树`,`数组`,`哈希表`,`字符串` | 困难 | | | +| [1179](https://leetcode-cn.com/problems/reformat-department-table) | 重新格式化部门表 | | `数据库` | 简单 | | | +| [1180](https://leetcode-cn.com/problems/count-substrings-with-only-one-distinct-letter) | 统计只含单一字母的子串 | | `数学`,`字符串` | 简单 | 🔒 | | +| [1181](https://leetcode-cn.com/problems/before-and-after-puzzle) | 前后拼接 | | `数组`,`哈希表`,`字符串`,`排序` | 中等 | 🔒 | | +| [1182](https://leetcode-cn.com/problems/shortest-distance-to-target-color) | 与目标颜色间的最短距离 | | `数组`,`二分查找`,`动态规划` | 中等 | 🔒 | | +| [1183](https://leetcode-cn.com/problems/maximum-number-of-ones) | 矩阵中 1 的最大数量 | | `贪心`,`堆(优先队列)` | 困难 | 🔒 | | +| [1184](https://leetcode-cn.com/problems/distance-between-bus-stops) | 公交站间的距离 | | `数组` | 简单 | | | +| [1185](https://leetcode-cn.com/problems/day-of-the-week) | 一周中的第几天 | | `数学` | 简单 | | | +| [1186](https://leetcode-cn.com/problems/maximum-subarray-sum-with-one-deletion) | 删除一次得到子数组最大和 | | `数组`,`动态规划` | 中等 | | | +| [1187](https://leetcode-cn.com/problems/make-array-strictly-increasing) | 使数组严格递增 | | `数组`,`二分查找`,`动态规划` | 困难 | | | +| [1188](https://leetcode-cn.com/problems/design-bounded-blocking-queue) | 设计有限阻塞队列 | | `多线程` | 中等 | 🔒 | | +| [1189](https://leetcode-cn.com/problems/maximum-number-of-balloons) | "气球" 的最大数量 | | `哈希表`,`字符串`,`计数` | 简单 | | | +| [1190](https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses) | 反转每对括号间的子串 | | `栈`,`字符串` | 中等 | | | +| [1191](https://leetcode-cn.com/problems/k-concatenation-maximum-sum) | K 次串联后最大子数组之和 | | `数组`,`动态规划` | 中等 | | | +| [1192](https://leetcode-cn.com/problems/critical-connections-in-a-network) | 查找集群内的「关键连接」 | | `深度优先搜索`,`图`,`双连通分量` | 困难 | | | +| [1193](https://leetcode-cn.com/problems/monthly-transactions-i) | 每月交易 I | | `数据库` | 中等 | 🔒 | | +| [1194](https://leetcode-cn.com/problems/tournament-winners) | 锦标赛优胜者 | | `数据库` | 困难 | 🔒 | | +| [1195](https://leetcode-cn.com/problems/fizz-buzz-multithreaded) | 交替打印字符串 | | `多线程` | 中等 | | | +| [1196](https://leetcode-cn.com/problems/how-many-apples-can-you-put-into-the-basket) | 最多可以买到的苹果数量 | | `贪心`,`数组`,`排序` | 简单 | 🔒 | | +| [1197](https://leetcode-cn.com/problems/minimum-knight-moves) | 进击的骑士 | | `广度优先搜索` | 中等 | 🔒 | | +| [1198](https://leetcode-cn.com/problems/find-smallest-common-element-in-all-rows) | 找出所有行中最小公共元素 | | `数组`,`哈希表`,`二分查找`,`计数`,`矩阵` | 中等 | 🔒 | | +| [1199](https://leetcode-cn.com/problems/minimum-time-to-build-blocks) | 建造街区的最短时间 | | `贪心`,`数学`,`堆(优先队列)` | 困难 | 🔒 | | +| [1200](https://leetcode-cn.com/problems/minimum-absolute-difference) | 最小绝对差 | | `数组`,`排序` | 简单 | | | +| [1201](https://leetcode-cn.com/problems/ugly-number-iii) | 丑数 III | | `数学`,`二分查找`,`数论` | 中等 | | | +| [1202](https://leetcode-cn.com/problems/smallest-string-with-swaps) | 交换字符串中的元素 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`哈希表`,`字符串` | 中等 | | | +| [1203](https://leetcode-cn.com/problems/sort-items-by-groups-respecting-dependencies) | 项目管理 | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序` | 困难 | | | +| [1204](https://leetcode-cn.com/problems/last-person-to-fit-in-the-bus) | 最后一个能进入电梯的人 | | `数据库` | 中等 | 🔒 | | +| [1205](https://leetcode-cn.com/problems/monthly-transactions-ii) | 每月交易II | | `数据库` | 中等 | 🔒 | | +| [1206](https://leetcode-cn.com/problems/design-skiplist) | 设计跳表 | | `设计`,`链表` | 困难 | | | +| [1207](https://leetcode-cn.com/problems/unique-number-of-occurrences) | 独一无二的出现次数 | | `数组`,`哈希表` | 简单 | | | +| [1208](https://leetcode-cn.com/problems/get-equal-substrings-within-budget) | 尽可能使字符串相等 | | `字符串`,`二分查找`,`前缀和`,`滑动窗口` | 中等 | | | +| [1209](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string-ii) | 删除字符串中的所有相邻重复项 II | | `栈`,`字符串` | 中等 | | | +| [1210](https://leetcode-cn.com/problems/minimum-moves-to-reach-target-with-rotations) | 穿过迷宫的最少移动次数 | | `广度优先搜索`,`数组`,`矩阵` | 困难 | | | +| [1211](https://leetcode-cn.com/problems/queries-quality-and-percentage) | 查询结果的质量和占比 | | `数据库` | 简单 | 🔒 | | +| [1212](https://leetcode-cn.com/problems/team-scores-in-football-tournament) | 查询球队积分 | | `数据库` | 中等 | 🔒 | | +| [1213](https://leetcode-cn.com/problems/intersection-of-three-sorted-arrays) | 三个有序数组的交集 | | `数组`,`哈希表`,`二分查找`,`计数` | 简单 | 🔒 | | +| [1214](https://leetcode-cn.com/problems/two-sum-bsts) | 查找两棵二叉搜索树之和 | | `栈`,`树`,`深度优先搜索`,`二叉搜索树`,`双指针`,`二分查找`,`二叉树` | 中等 | 🔒 | | +| [1215](https://leetcode-cn.com/problems/stepping-numbers) | 步进数 | | `广度优先搜索`,`回溯` | 中等 | 🔒 | | +| [1216](https://leetcode-cn.com/problems/valid-palindrome-iii) | 验证回文字符串 III | | `字符串`,`动态规划` | 困难 | 🔒 | | +| [1217](https://leetcode-cn.com/problems/minimum-cost-to-move-chips-to-the-same-position) | 玩筹码 | | `贪心`,`数组`,`数学` | 简单 | | | +| [1218](https://leetcode-cn.com/problems/longest-arithmetic-subsequence-of-given-difference) | 最长定差子序列 | | `数组`,`哈希表`,`动态规划` | 中等 | | | +| [1219](https://leetcode-cn.com/problems/path-with-maximum-gold) | 黄金矿工 | | `数组`,`回溯`,`矩阵` | 中等 | | | +| [1220](https://leetcode-cn.com/problems/count-vowels-permutation) | 统计元音字母序列的数目 | | `动态规划` | 困难 | | | +| [1221](https://leetcode-cn.com/problems/split-a-string-in-balanced-strings) | 分割平衡字符串 | | `贪心`,`字符串`,`计数` | 简单 | | | +| [1222](https://leetcode-cn.com/problems/queens-that-can-attack-the-king) | 可以攻击国王的皇后 | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [1223](https://leetcode-cn.com/problems/dice-roll-simulation) | 掷骰子模拟 | | `数组`,`动态规划` | 困难 | | | +| [1224](https://leetcode-cn.com/problems/maximum-equal-frequency) | 最大相等频率 | | `数组`,`哈希表` | 困难 | | | +| [1225](https://leetcode-cn.com/problems/report-contiguous-dates) | 报告系统状态的连续日期 | | `数据库` | 困难 | 🔒 | | +| [1226](https://leetcode-cn.com/problems/the-dining-philosophers) | 哲学家进餐 | | `多线程` | 中等 | | | +| [1227](https://leetcode-cn.com/problems/airplane-seat-assignment-probability) | 飞机座位分配概率 | | `脑筋急转弯`,`数学`,`动态规划`,`概率与统计` | 中等 | | | +| [1228](https://leetcode-cn.com/problems/missing-number-in-arithmetic-progression) | 等差数列中缺失的数字 | | `数组`,`数学` | 简单 | 🔒 | | +| [1229](https://leetcode-cn.com/problems/meeting-scheduler) | 安排会议日程 | | `数组`,`双指针`,`排序` | 中等 | 🔒 | | +| [1230](https://leetcode-cn.com/problems/toss-strange-coins) | 抛掷硬币 | | `数学`,`动态规划`,`概率与统计` | 中等 | 🔒 | | +| [1231](https://leetcode-cn.com/problems/divide-chocolate) | 分享巧克力 | | `数组`,`二分查找` | 困难 | 🔒 | | +| [1232](https://leetcode-cn.com/problems/check-if-it-is-a-straight-line) | 缀点成线 | | `几何`,`数组`,`数学` | 简单 | | | +| [1233](https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem) | 删除子文件夹 | | `字典树`,`数组`,`字符串` | 中等 | | | +| [1234](https://leetcode-cn.com/problems/replace-the-substring-for-balanced-string) | 替换子串得到平衡字符串 | | `字符串`,`滑动窗口` | 中等 | | | +| [1235](https://leetcode-cn.com/problems/maximum-profit-in-job-scheduling) | 规划兼职工作 | | `数组`,`二分查找`,`动态规划`,`排序` | 困难 | | | +| [1236](https://leetcode-cn.com/problems/web-crawler) | 网络爬虫 | | `深度优先搜索`,`广度优先搜索`,`字符串`,`交互` | 中等 | 🔒 | | +| [1237](https://leetcode-cn.com/problems/find-positive-integer-solution-for-a-given-equation) | 找出给定方程的正整数解 | | `数学`,`双指针`,`二分查找`,`交互` | 中等 | | | +| [1238](https://leetcode-cn.com/problems/circular-permutation-in-binary-representation) | 循环码排列 | | `位运算`,`数学`,`回溯` | 中等 | | | +| [1239](https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters) | 串联字符串的最大长度 | | `位运算`,`数组`,`字符串`,`回溯` | 中等 | | | +| [1240](https://leetcode-cn.com/problems/tiling-a-rectangle-with-the-fewest-squares) | 铺瓷砖 | | `动态规划`,`回溯` | 困难 | | | +| [1241](https://leetcode-cn.com/problems/number-of-comments-per-post) | 每个帖子的评论数 | | `数据库` | 简单 | 🔒 | | +| [1242](https://leetcode-cn.com/problems/web-crawler-multithreaded) | 多线程网页爬虫 | | `深度优先搜索`,`广度优先搜索`,`多线程` | 中等 | 🔒 | | +| [1243](https://leetcode-cn.com/problems/array-transformation) | 数组变换 | | `数组`,`模拟` | 简单 | 🔒 | | +| [1244](https://leetcode-cn.com/problems/design-a-leaderboard) | 力扣排行榜 | | `设计`,`哈希表`,`排序` | 中等 | 🔒 | | +| [1245](https://leetcode-cn.com/problems/tree-diameter) | 树的直径 | | `树`,`深度优先搜索`,`广度优先搜索` | 中等 | 🔒 | | +| [1246](https://leetcode-cn.com/problems/palindrome-removal) | 删除回文子数组 | | `数组`,`动态规划` | 困难 | 🔒 | | +| [1247](https://leetcode-cn.com/problems/minimum-swaps-to-make-strings-equal) | 交换字符使得字符串相同 | | `贪心`,`数学`,`字符串` | 中等 | | | +| [1248](https://leetcode-cn.com/problems/count-number-of-nice-subarrays) | 统计「优美子数组」 | | `数组`,`哈希表`,`数学`,`滑动窗口` | 中等 | | | +| [1249](https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses) | 移除无效的括号 | | `栈`,`字符串` | 中等 | | | +| [1250](https://leetcode-cn.com/problems/check-if-it-is-a-good-array) | 检查「好数组」 | | `数组`,`数学`,`数论` | 困难 | | | +| [1251](https://leetcode-cn.com/problems/average-selling-price) | 平均售价 | | `数据库` | 简单 | 🔒 | | +| [1252](https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix) | 奇数值单元格的数目 | | `数组`,`数学`,`模拟` | 简单 | | | +| [1253](https://leetcode-cn.com/problems/reconstruct-a-2-row-binary-matrix) | 重构 2 行二进制矩阵 | | `贪心`,`数组`,`矩阵` | 中等 | | | +| [1254](https://leetcode-cn.com/problems/number-of-closed-islands) | 统计封闭岛屿的数目 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [1255](https://leetcode-cn.com/problems/maximum-score-words-formed-by-letters) | 得分最高的单词集合 | | `位运算`,`数组`,`字符串`,`动态规划`,`回溯`,`状态压缩` | 困难 | | | +| [1256](https://leetcode-cn.com/problems/encode-number) | 加密数字 | | `位运算`,`数学`,`字符串` | 中等 | 🔒 | | +| [1257](https://leetcode-cn.com/problems/smallest-common-region) | 最小公共区域 | | `树`,`深度优先搜索`,`广度优先搜索`,`数组`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [1258](https://leetcode-cn.com/problems/synonymous-sentences) | 近义词句子 | | `并查集`,`数组`,`哈希表`,`字符串`,`回溯` | 中等 | 🔒 | | +| [1259](https://leetcode-cn.com/problems/handshakes-that-dont-cross) | 不相交的握手 | | `数学`,`动态规划` | 困难 | 🔒 | | +| [1260](https://leetcode-cn.com/problems/shift-2d-grid) | 二维网格迁移 | | `数组`,`矩阵`,`模拟` | 简单 | | | +| [1261](https://leetcode-cn.com/problems/find-elements-in-a-contaminated-binary-tree) | 在受污染的二叉树中查找元素 | | `树`,`深度优先搜索`,`广度优先搜索`,`设计`,`二叉树` | 中等 | | | +| [1262](https://leetcode-cn.com/problems/greatest-sum-divisible-by-three) | 可被三整除的最大和 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [1263](https://leetcode-cn.com/problems/minimum-moves-to-move-a-box-to-their-target-location) | 推箱子 | | `广度优先搜索`,`数组`,`矩阵`,`堆(优先队列)` | 困难 | | | +| [1264](https://leetcode-cn.com/problems/page-recommendations) | 页面推荐 | | `数据库` | 中等 | 🔒 | | +| [1265](https://leetcode-cn.com/problems/print-immutable-linked-list-in-reverse) | 逆序打印不可变链表 | | `栈`,`递归`,`链表`,`双指针` | 中等 | 🔒 | | +| [1266](https://leetcode-cn.com/problems/minimum-time-visiting-all-points) | 访问所有点的最小时间 | | `几何`,`数组`,`数学` | 简单 | | | +| [1267](https://leetcode-cn.com/problems/count-servers-that-communicate) | 统计参与通信的服务器 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`计数`,`矩阵` | 中等 | | | +| [1268](https://leetcode-cn.com/problems/search-suggestions-system) | 搜索推荐系统 | | `字典树`,`数组`,`字符串` | 中等 | | | +| [1269](https://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps) | 停在原地的方案数 | | `动态规划` | 困难 | | | +| [1270](https://leetcode-cn.com/problems/all-people-report-to-the-given-manager) | 向公司CEO汇报工作的所有人 | | `数据库` | 中等 | 🔒 | | +| [1271](https://leetcode-cn.com/problems/hexspeak) | 十六进制魔术数字 | | `数学`,`字符串` | 简单 | 🔒 | | +| [1272](https://leetcode-cn.com/problems/remove-interval) | 删除区间 | | `数组` | 中等 | 🔒 | | +| [1273](https://leetcode-cn.com/problems/delete-tree-nodes) | 删除树节点 | | `树`,`深度优先搜索`,`广度优先搜索` | 中等 | 🔒 | | +| [1274](https://leetcode-cn.com/problems/number-of-ships-in-a-rectangle) | 矩形内船只的数目 | | `数组`,`分治`,`交互` | 困难 | 🔒 | | +| [1275](https://leetcode-cn.com/problems/find-winner-on-a-tic-tac-toe-game) | 找出井字棋的获胜者 | | `数组`,`哈希表`,`矩阵`,`模拟` | 简单 | | | +| [1276](https://leetcode-cn.com/problems/number-of-burgers-with-no-waste-of-ingredients) | 不浪费原料的汉堡制作方案 | | `数学` | 中等 | | | +| [1277](https://leetcode-cn.com/problems/count-square-submatrices-with-all-ones) | 统计全为 1 的正方形子矩阵 | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [1278](https://leetcode-cn.com/problems/palindrome-partitioning-iii) | 分割回文串 III | | `字符串`,`动态规划` | 困难 | | | +| [1279](https://leetcode-cn.com/problems/traffic-light-controlled-intersection) | 红绿灯路口 | | `多线程` | 简单 | 🔒 | | +| [1280](https://leetcode-cn.com/problems/students-and-examinations) | 学生们参加各科测试的次数 | | `数据库` | 简单 | 🔒 | | +| [1281](https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer) | 整数的各位积和之差 | | `数学` | 简单 | | | +| [1282](https://leetcode-cn.com/problems/group-the-people-given-the-group-size-they-belong-to) | 用户分组 | | `数组`,`哈希表` | 中等 | | | +| [1283](https://leetcode-cn.com/problems/find-the-smallest-divisor-given-a-threshold) | 使结果不超过阈值的最小除数 | | `数组`,`二分查找` | 中等 | | | +| [1284](https://leetcode-cn.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix) | 转化为全零矩阵的最少反转次数 | | `位运算`,`广度优先搜索`,`数组`,`矩阵` | 困难 | | | +| [1285](https://leetcode-cn.com/problems/find-the-start-and-end-number-of-continuous-ranges) | 找到连续区间的开始和结束数字 | | `数据库` | 中等 | 🔒 | | +| [1286](https://leetcode-cn.com/problems/iterator-for-combination) | 字母组合迭代器 | | `设计`,`字符串`,`回溯`,`迭代器` | 中等 | | | +| [1287](https://leetcode-cn.com/problems/element-appearing-more-than-25-in-sorted-array) | 有序数组中出现次数超过25%的元素 | | `数组` | 简单 | | | +| [1288](https://leetcode-cn.com/problems/remove-covered-intervals) | 删除被覆盖区间 | | `数组`,`排序` | 中等 | | | +| [1289](https://leetcode-cn.com/problems/minimum-falling-path-sum-ii) | 下降路径最小和 II | | `数组`,`动态规划`,`矩阵` | 困难 | | | +| [1290](https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer) | 二进制链表转整数 | | `链表`,`数学` | 简单 | | | +| [1291](https://leetcode-cn.com/problems/sequential-digits) | 顺次数 | | `枚举` | 中等 | | | +| [1292](https://leetcode-cn.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold) | 元素和小于等于阈值的正方形的最大边长 | | `数组`,`二分查找`,`矩阵`,`前缀和` | 中等 | | | +| [1293](https://leetcode-cn.com/problems/shortest-path-in-a-grid-with-obstacles-elimination) | 网格中的最短路径 | | `广度优先搜索`,`数组`,`矩阵` | 困难 | | | +| [1294](https://leetcode-cn.com/problems/weather-type-in-each-country) | 不同国家的天气类型 | | `数据库` | 简单 | 🔒 | | +| [1295](https://leetcode-cn.com/problems/find-numbers-with-even-number-of-digits) | 统计位数为偶数的数字 | | `数组` | 简单 | | | +| [1296](https://leetcode-cn.com/problems/divide-array-in-sets-of-k-consecutive-numbers) | 划分数组为连续数字的集合 | | `贪心`,`数组`,`哈希表`,`排序` | 中等 | | | +| [1297](https://leetcode-cn.com/problems/maximum-number-of-occurrences-of-a-substring) | 子串的最大出现次数 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | | | +| [1298](https://leetcode-cn.com/problems/maximum-candies-you-can-get-from-boxes) | 你能从盒子里获得的最大糖果数 | | `广度优先搜索`,`数组` | 困难 | | | +| [1299](https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side) | 将每个元素替换为右侧最大元素 | | `数组` | 简单 | | | +| [1300](https://leetcode-cn.com/problems/sum-of-mutated-array-closest-to-target) | 转变数组后最接近目标值的数组和 | | `数组`,`二分查找`,`排序` | 中等 | | | +| [1301](https://leetcode-cn.com/problems/number-of-paths-with-max-score) | 最大得分的路径数目 | | `数组`,`动态规划`,`矩阵` | 困难 | | | +| [1302](https://leetcode-cn.com/problems/deepest-leaves-sum) | 层数最深叶子节点的和 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1303](https://leetcode-cn.com/problems/find-the-team-size) | 求团队人数 | | `数据库` | 简单 | 🔒 | | +| [1304](https://leetcode-cn.com/problems/find-n-unique-integers-sum-up-to-zero) | 和为零的N个唯一整数 | | `数组`,`数学` | 简单 | | | +| [1305](https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees) | 两棵二叉搜索树中的所有元素 | | `树`,`深度优先搜索`,`二叉搜索树`,`二叉树`,`排序` | 中等 | | | +| [1306](https://leetcode-cn.com/problems/jump-game-iii) | 跳跃游戏 III | | `深度优先搜索`,`广度优先搜索`,`数组` | 中等 | | | +| [1307](https://leetcode-cn.com/problems/verbal-arithmetic-puzzle) | 口算难题 | | `数组`,`数学`,`字符串`,`回溯` | 困难 | | | +| [1308](https://leetcode-cn.com/problems/running-total-for-different-genders) | 不同性别每日分数总计 | | `数据库` | 中等 | 🔒 | | +| [1309](https://leetcode-cn.com/problems/decrypt-string-from-alphabet-to-integer-mapping) | 解码字母到整数映射 | | `字符串` | 简单 | | | +| [1310](https://leetcode-cn.com/problems/xor-queries-of-a-subarray) | 子数组异或查询 | | `位运算`,`数组`,`前缀和` | 中等 | | | +| [1311](https://leetcode-cn.com/problems/get-watched-videos-by-your-friends) | 获取你好友已观看的视频 | | `广度优先搜索`,`数组`,`哈希表`,`排序` | 中等 | | | +| [1312](https://leetcode-cn.com/problems/minimum-insertion-steps-to-make-a-string-palindrome) | 让字符串成为回文串的最少插入次数 | | `字符串`,`动态规划` | 困难 | | | +| [1313](https://leetcode-cn.com/problems/decompress-run-length-encoded-list) | 解压缩编码列表 | | `数组` | 简单 | | | +| [1314](https://leetcode-cn.com/problems/matrix-block-sum) | 矩阵区域和 | | `数组`,`矩阵`,`前缀和` | 中等 | | | +| [1315](https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent) | 祖父节点值为偶数的节点和 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1316](https://leetcode-cn.com/problems/distinct-echo-substrings) | 不同的循环子字符串 | | `字典树`,`字符串`,`动态规划`,`滑动窗口`,`哈希函数`,`滚动哈希` | 困难 | | | +| [1317](https://leetcode-cn.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers) | 将整数转换为两个无零整数的和 | | `数学` | 简单 | | | +| [1318](https://leetcode-cn.com/problems/minimum-flips-to-make-a-or-b-equal-to-c) | 或运算的最小翻转次数 | | `位运算` | 中等 | | | +| [1319](https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected) | 连通网络的操作次数 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`图` | 中等 | | | +| [1320](https://leetcode-cn.com/problems/minimum-distance-to-type-a-word-using-two-fingers) | 二指输入的的最小距离 | | `字符串`,`动态规划` | 困难 | | | +| [1321](https://leetcode-cn.com/problems/restaurant-growth) | 餐馆营业额变化增长 | | `数据库` | 中等 | 🔒 | | +| [1322](https://leetcode-cn.com/problems/ads-performance) | 广告效果 | | `数据库` | 简单 | 🔒 | | +| [1323](https://leetcode-cn.com/problems/maximum-69-number) | 6 和 9 组成的最大数字 | | `贪心`,`数学` | 简单 | | | +| [1324](https://leetcode-cn.com/problems/print-words-vertically) | 竖直打印单词 | | `数组`,`字符串`,`模拟` | 中等 | | | +| [1325](https://leetcode-cn.com/problems/delete-leaves-with-a-given-value) | 删除给定值的叶子节点 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | | | +| [1326](https://leetcode-cn.com/problems/minimum-number-of-taps-to-open-to-water-a-garden) | 灌溉花园的最少水龙头数目 | | `贪心`,`数组`,`动态规划` | 困难 | | | +| [1327](https://leetcode-cn.com/problems/list-the-products-ordered-in-a-period) | 列出指定时间段内所有的下单产品 | | `数据库` | 简单 | 🔒 | | +| [1328](https://leetcode-cn.com/problems/break-a-palindrome) | 破坏回文串 | | `贪心`,`字符串` | 中等 | | | +| [1329](https://leetcode-cn.com/problems/sort-the-matrix-diagonally) | 将矩阵按对角线排序 | | `数组`,`矩阵`,`排序` | 中等 | | | +| [1330](https://leetcode-cn.com/problems/reverse-subarray-to-maximize-array-value) | 翻转子数组得到最大的数组值 | | `贪心`,`数组`,`数学` | 困难 | | | +| [1331](https://leetcode-cn.com/problems/rank-transform-of-an-array) | 数组序号转换 | | `数组`,`哈希表`,`排序` | 简单 | | | +| [1332](https://leetcode-cn.com/problems/remove-palindromic-subsequences) | 删除回文子序列 | | `双指针`,`字符串` | 简单 | | | +| [1333](https://leetcode-cn.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance) | 餐厅过滤器 | | `数组`,`排序` | 中等 | | | +| [1334](https://leetcode-cn.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance) | 阈值距离内邻居最少的城市 | | `图`,`动态规划`,`最短路` | 中等 | | | +| [1335](https://leetcode-cn.com/problems/minimum-difficulty-of-a-job-schedule) | 工作计划的最低难度 | | `数组`,`动态规划` | 困难 | | | +| [1336](https://leetcode-cn.com/problems/number-of-transactions-per-visit) | 每次访问的交易次数 | | `数据库` | 困难 | 🔒 | | +| [1337](https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix) | 矩阵中战斗力最弱的 K 行 | | `数组`,`二分查找`,`矩阵`,`排序`,`堆(优先队列)` | 简单 | | | +| [1338](https://leetcode-cn.com/problems/reduce-array-size-to-the-half) | 数组大小减半 | | `贪心`,`数组`,`哈希表`,`排序`,`堆(优先队列)` | 中等 | | | +| [1339](https://leetcode-cn.com/problems/maximum-product-of-splitted-binary-tree) | 分裂二叉树的最大乘积 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [1340](https://leetcode-cn.com/problems/jump-game-v) | 跳跃游戏 V | | `数组`,`动态规划`,`排序` | 困难 | | | +| [1341](https://leetcode-cn.com/problems/movie-rating) | 电影评分 | | `数据库` | 中等 | 🔒 | | +| [1342](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero) | 将数字变成 0 的操作次数 | | `位运算`,`数学` | 简单 | | | +| [1343](https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold) | 大小为 K 且平均值大于等于阈值的子数组数目 | | `数组`,`滑动窗口` | 中等 | | | +| [1344](https://leetcode-cn.com/problems/angle-between-hands-of-a-clock) | 时钟指针的夹角 | | `数学` | 中等 | | | +| [1345](https://leetcode-cn.com/problems/jump-game-iv) | 跳跃游戏 IV | | `广度优先搜索`,`数组`,`哈希表` | 困难 | | | +| [1346](https://leetcode-cn.com/problems/check-if-n-and-its-double-exist) | 检查整数及其两倍数是否存在 | | `数组`,`哈希表`,`双指针`,`二分查找`,`排序` | 简单 | | | +| [1347](https://leetcode-cn.com/problems/minimum-number-of-steps-to-make-two-strings-anagram) | 制造字母异位词的最小步骤数 | | `哈希表`,`字符串` | 中等 | | | +| [1348](https://leetcode-cn.com/problems/tweet-counts-per-frequency) | 推文计数 | | `设计`,`哈希表`,`二分查找`,`有序集合`,`排序` | 中等 | | | +| [1349](https://leetcode-cn.com/problems/maximum-students-taking-exam) | 参加考试的最大学生数 | | `位运算`,`数组`,`动态规划`,`状态压缩`,`矩阵` | 困难 | | | +| [1350](https://leetcode-cn.com/problems/students-with-invalid-departments) | 院系无效的学生 | | `数据库` | 简单 | 🔒 | | +| [1351](https://leetcode-cn.com/problems/count-negative-numbers-in-a-sorted-matrix) | 统计有序矩阵中的负数 | | `数组`,`二分查找`,`矩阵` | 简单 | | | +| [1352](https://leetcode-cn.com/problems/product-of-the-last-k-numbers) | 最后 K 个数的乘积 | | `设计`,`队列`,`数组`,`数学`,`数据流` | 中等 | | | +| [1353](https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended) | 最多可以参加的会议数目 | | `贪心`,`数组`,`堆(优先队列)` | 中等 | | | +| [1354](https://leetcode-cn.com/problems/construct-target-array-with-multiple-sums) | 多次求和构造目标数组 | | `数组`,`堆(优先队列)` | 困难 | | | +| [1355](https://leetcode-cn.com/problems/activity-participants) | 活动参与者 | | `数据库` | 中等 | 🔒 | | +| [1356](https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits) | 根据数字二进制下 1 的数目排序 | | `位运算`,`数组`,`计数`,`排序` | 简单 | | | +| [1357](https://leetcode-cn.com/problems/apply-discount-every-n-orders) | 每隔 n 个顾客打折 | | `设计`,`数组`,`哈希表` | 中等 | | | +| [1358](https://leetcode-cn.com/problems/number-of-substrings-containing-all-three-characters) | 包含所有三种字符的子字符串数目 | | `哈希表`,`字符串`,`滑动窗口` | 中等 | | | +| [1359](https://leetcode-cn.com/problems/count-all-valid-pickup-and-delivery-options) | 有效的快递序列数目 | | `数学`,`动态规划`,`组合数学` | 困难 | | | +| [1360](https://leetcode-cn.com/problems/number-of-days-between-two-dates) | 日期之间隔几天 | | `数学`,`字符串` | 简单 | | | +| [1361](https://leetcode-cn.com/problems/validate-binary-tree-nodes) | 验证二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`并查集`,`图`,`二叉树` | 中等 | | | +| [1362](https://leetcode-cn.com/problems/closest-divisors) | 最接近的因数 | | `数学` | 中等 | | | +| [1363](https://leetcode-cn.com/problems/largest-multiple-of-three) | 形成三的最大倍数 | | `贪心`,`数组`,`动态规划` | 困难 | | | +| [1364](https://leetcode-cn.com/problems/number-of-trusted-contacts-of-a-customer) | 顾客的可信联系人数量 | | `数据库` | 中等 | 🔒 | | +| [1365](https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number) | 有多少小于当前数字的数字 | | `数组`,`哈希表`,`计数`,`排序` | 简单 | | | +| [1366](https://leetcode-cn.com/problems/rank-teams-by-votes) | 通过投票对团队排名 | | `数组`,`哈希表`,`字符串`,`计数`,`排序` | 中等 | | | +| [1367](https://leetcode-cn.com/problems/linked-list-in-binary-tree) | 二叉树中的列表 | | `树`,`深度优先搜索`,`广度优先搜索`,`链表`,`二叉树` | 中等 | | | +| [1368](https://leetcode-cn.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid) | 使网格图至少有一条有效路径的最小代价 | | `广度优先搜索`,`图`,`数组`,`矩阵`,`最短路`,`堆(优先队列)` | 困难 | | | +| [1369](https://leetcode-cn.com/problems/get-the-second-most-recent-activity) | 获取最近第二次的活动 | | `数据库` | 困难 | 🔒 | | +| [1370](https://leetcode-cn.com/problems/increasing-decreasing-string) | 上升下降字符串 | | `哈希表`,`字符串`,`计数` | 简单 | | | +| [1371](https://leetcode-cn.com/problems/find-the-longest-substring-containing-vowels-in-even-counts) | 每个元音包含偶数次的最长子字符串 | | `位运算`,`哈希表`,`字符串`,`前缀和` | 中等 | | | +| [1372](https://leetcode-cn.com/problems/longest-zigzag-path-in-a-binary-tree) | 二叉树中的最长交错路径 | | `树`,`深度优先搜索`,`动态规划`,`二叉树` | 中等 | | | +| [1373](https://leetcode-cn.com/problems/maximum-sum-bst-in-binary-tree) | 二叉搜索子树的最大键值和 | | `树`,`深度优先搜索`,`二叉搜索树`,`动态规划`,`二叉树` | 困难 | | | +| [1374](https://leetcode-cn.com/problems/generate-a-string-with-characters-that-have-odd-counts) | 生成每种字符都是奇数个的字符串 | | `字符串` | 简单 | | | +| [1375](https://leetcode-cn.com/problems/bulb-switcher-iii) | 灯泡开关 III | | `数组` | 中等 | | | +| [1376](https://leetcode-cn.com/problems/time-needed-to-inform-all-employees) | 通知所有员工所需的时间 | | `树`,`深度优先搜索`,`广度优先搜索` | 中等 | | | +| [1377](https://leetcode-cn.com/problems/frog-position-after-t-seconds) | T 秒后青蛙的位置 | | `树`,`深度优先搜索`,`广度优先搜索`,`图` | 困难 | | | +| [1378](https://leetcode-cn.com/problems/replace-employee-id-with-the-unique-identifier) | 使用唯一标识码替换员工ID | | `数据库` | 简单 | 🔒 | | +| [1379](https://leetcode-cn.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree) | 找出克隆二叉树中的相同节点 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1380](https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix) | 矩阵中的幸运数 | | `数组`,`矩阵` | 简单 | | | +| [1381](https://leetcode-cn.com/problems/design-a-stack-with-increment-operation) | 设计一个支持增量操作的栈 | | `栈`,`设计`,`数组` | 中等 | | | +| [1382](https://leetcode-cn.com/problems/balance-a-binary-search-tree) | 将二叉搜索树变平衡 | | `贪心`,`树`,`深度优先搜索`,`二叉搜索树`,`分治`,`二叉树` | 中等 | | | +| [1383](https://leetcode-cn.com/problems/maximum-performance-of-a-team) | 最大的团队表现值 | | `贪心`,`数组`,`排序`,`堆(优先队列)` | 困难 | | | +| [1384](https://leetcode-cn.com/problems/total-sales-amount-by-year) | 按年度列出销售总额 | | `数据库` | 困难 | 🔒 | | +| [1385](https://leetcode-cn.com/problems/find-the-distance-value-between-two-arrays) | 两个数组间的距离值 | | `数组`,`双指针`,`二分查找`,`排序` | 简单 | | | +| [1386](https://leetcode-cn.com/problems/cinema-seat-allocation) | 安排电影院座位 | | `贪心`,`位运算`,`数组`,`哈希表` | 中等 | | | +| [1387](https://leetcode-cn.com/problems/sort-integers-by-the-power-value) | 将整数按权重排序 | | `记忆化搜索`,`动态规划`,`排序` | 中等 | | | +| [1388](https://leetcode-cn.com/problems/pizza-with-3n-slices) | 3n 块披萨 | | `贪心`,`数组`,`动态规划`,`堆(优先队列)` | 困难 | | | +| [1389](https://leetcode-cn.com/problems/create-target-array-in-the-given-order) | 按既定顺序创建目标数组 | | `数组`,`模拟` | 简单 | | | +| [1390](https://leetcode-cn.com/problems/four-divisors) | 四因数 | | `数组`,`数学` | 中等 | | | +| [1391](https://leetcode-cn.com/problems/check-if-there-is-a-valid-path-in-a-grid) | 检查网格中是否存在有效路径 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [1392](https://leetcode-cn.com/problems/longest-happy-prefix) | 最长快乐前缀 | | `字符串`,`字符串匹配`,`哈希函数`,`滚动哈希` | 困难 | | | +| [1393](https://leetcode-cn.com/problems/capital-gainloss) | 股票的资本损益 | | `数据库` | 中等 | 🔒 | | +| [1394](https://leetcode-cn.com/problems/find-lucky-integer-in-an-array) | 找出数组中的幸运数 | | `数组`,`哈希表`,`计数` | 简单 | | | +| [1395](https://leetcode-cn.com/problems/count-number-of-teams) | 统计作战单位数 | | `树状数组`,`数组`,`动态规划` | 中等 | | | +| [1396](https://leetcode-cn.com/problems/design-underground-system) | 设计地铁系统 | | `设计`,`哈希表`,`字符串` | 中等 | | | +| [1397](https://leetcode-cn.com/problems/find-all-good-strings) | 找到所有好字符串 | | `字符串`,`动态规划`,`字符串匹配` | 困难 | | | +| [1398](https://leetcode-cn.com/problems/customers-who-bought-products-a-and-b-but-not-c) | 购买了产品 A 和产品 B 却没有购买产品 C 的顾客 | | `数据库` | 中等 | 🔒 | | +| [1399](https://leetcode-cn.com/problems/count-largest-group) | 统计最大组的数目 | | `哈希表`,`数学` | 简单 | | | +| [1400](https://leetcode-cn.com/problems/construct-k-palindrome-strings) | 构造 K 个回文字符串 | | `贪心`,`哈希表`,`字符串`,`计数` | 中等 | | | +| [1401](https://leetcode-cn.com/problems/circle-and-rectangle-overlapping) | 圆和矩形是否有重叠 | | `几何`,`数学` | 中等 | | | +| [1402](https://leetcode-cn.com/problems/reducing-dishes) | 做菜顺序 | | `贪心`,`数组`,`动态规划`,`排序` | 困难 | | | +| [1403](https://leetcode-cn.com/problems/minimum-subsequence-in-non-increasing-order) | 非递增顺序的最小子序列 | | `贪心`,`数组`,`排序` | 简单 | | | +| [1404](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one) | 将二进制表示减到 1 的步骤数 | | `位运算`,`字符串` | 中等 | | | +| [1405](https://leetcode-cn.com/problems/longest-happy-string) | 最长快乐字符串 | | `贪心`,`字符串`,`堆(优先队列)` | 中等 | | | +| [1406](https://leetcode-cn.com/problems/stone-game-iii) | 石子游戏 III | | `数组`,`数学`,`动态规划`,`博弈` | 困难 | | | +| [1407](https://leetcode-cn.com/problems/top-travellers) | 排名靠前的旅行者 | | `数据库` | 简单 | 🔒 | | +| [1408](https://leetcode-cn.com/problems/string-matching-in-an-array) | 数组中的字符串匹配 | | `字符串`,`字符串匹配` | 简单 | | | +| [1409](https://leetcode-cn.com/problems/queries-on-a-permutation-with-key) | 查询带键的排列 | | `树状数组`,`数组`,`模拟` | 中等 | | | +| [1410](https://leetcode-cn.com/problems/html-entity-parser) | HTML 实体解析器 | | `哈希表`,`字符串` | 中等 | | | +| [1411](https://leetcode-cn.com/problems/number-of-ways-to-paint-n-3-grid) | 给 N x 3 网格图涂色的方案数 | | `动态规划` | 困难 | | | +| [1412](https://leetcode-cn.com/problems/find-the-quiet-students-in-all-exams) | 查找成绩处于中游的学生 | | `数据库` | 困难 | 🔒 | | +| [1413](https://leetcode-cn.com/problems/minimum-value-to-get-positive-step-by-step-sum) | 逐步求和得到正数的最小值 | | `数组`,`前缀和` | 简单 | | | +| [1414](https://leetcode-cn.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k) | 和为 K 的最少斐波那契数字数目 | | `贪心` | 中等 | | | +| [1415](https://leetcode-cn.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n) | 长度为 n 的开心字符串中字典序第 k 小的字符串 | | `字符串`,`回溯` | 中等 | | | +| [1416](https://leetcode-cn.com/problems/restore-the-array) | 恢复数组 | | `字符串`,`动态规划` | 困难 | | | +| [1417](https://leetcode-cn.com/problems/reformat-the-string) | 重新格式化字符串 | | `字符串` | 简单 | | | +| [1418](https://leetcode-cn.com/problems/display-table-of-food-orders-in-a-restaurant) | 点菜展示表 | | `数组`,`哈希表`,`字符串`,`有序集合`,`排序` | 中等 | | | +| [1419](https://leetcode-cn.com/problems/minimum-number-of-frogs-croaking) | 数青蛙 | | `字符串`,`计数` | 中等 | | | +| [1420](https://leetcode-cn.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons) | 生成数组 | | `动态规划` | 困难 | | | +| [1421](https://leetcode-cn.com/problems/npv-queries) | 净现值查询 | | `数据库` | 中等 | 🔒 | | +| [1422](https://leetcode-cn.com/problems/maximum-score-after-splitting-a-string) | 分割字符串的最大得分 | | `字符串` | 简单 | | | +| [1423](https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards) | 可获得的最大点数 | | `数组`,`前缀和`,`滑动窗口` | 中等 | | | +| [1424](https://leetcode-cn.com/problems/diagonal-traverse-ii) | 对角线遍历 II | | `数组`,`排序`,`堆(优先队列)` | 中等 | | | +| [1425](https://leetcode-cn.com/problems/constrained-subsequence-sum) | 带限制的子序列和 | | `队列`,`数组`,`动态规划`,`滑动窗口`,`单调队列`,`堆(优先队列)` | 困难 | | | +| [1426](https://leetcode-cn.com/problems/counting-elements) | 数元素 | | `数组`,`哈希表` | 简单 | 🔒 | | +| [1427](https://leetcode-cn.com/problems/perform-string-shifts) | 字符串的左右移 | | `数组`,`数学`,`字符串` | 简单 | 🔒 | | +| [1428](https://leetcode-cn.com/problems/leftmost-column-with-at-least-a-one) | 至少有一个 1 的最左端列 | | `数组`,`二分查找`,`交互`,`矩阵` | 中等 | 🔒 | | +| [1429](https://leetcode-cn.com/problems/first-unique-number) | 第一个唯一数字 | | `设计`,`队列`,`数组`,`哈希表`,`数据流` | 中等 | 🔒 | | +| [1430](https://leetcode-cn.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree) | 判断给定的序列是否是二叉树从根到叶的路径 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1431](https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies) | 拥有最多糖果的孩子 | | `数组` | 简单 | | | +| [1432](https://leetcode-cn.com/problems/max-difference-you-can-get-from-changing-an-integer) | 改变一个整数能得到的最大差值 | | `贪心`,`数学` | 中等 | | | +| [1433](https://leetcode-cn.com/problems/check-if-a-string-can-break-another-string) | 检查一个字符串是否可以打破另一个字符串 | | `贪心`,`字符串`,`排序` | 中等 | | | +| [1434](https://leetcode-cn.com/problems/number-of-ways-to-wear-different-hats-to-each-other) | 每个人戴不同帽子的方案数 | | `位运算`,`数组`,`动态规划`,`状态压缩` | 困难 | | | +| [1435](https://leetcode-cn.com/problems/create-a-session-bar-chart) | 制作会话柱状图 | | `数据库` | 简单 | 🔒 | | +| [1436](https://leetcode-cn.com/problems/destination-city) | 旅行终点站 | | `哈希表`,`字符串` | 简单 | | | +| [1437](https://leetcode-cn.com/problems/check-if-all-1s-are-at-least-length-k-places-away) | 是否所有 1 都至少相隔 k 个元素 | | `数组` | 简单 | | | +| [1438](https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit) | 绝对差不超过限制的最长连续子数组 | | `队列`,`数组`,`有序集合`,`滑动窗口`,`单调队列`,`堆(优先队列)` | 中等 | | | +| [1439](https://leetcode-cn.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows) | 有序矩阵中的第 k 个最小数组和 | | `数组`,`二分查找`,`矩阵`,`堆(优先队列)` | 困难 | | | +| [1440](https://leetcode-cn.com/problems/evaluate-boolean-expression) | 计算布尔表达式的值 | | `数据库` | 中等 | 🔒 | | +| [1441](https://leetcode-cn.com/problems/build-an-array-with-stack-operations) | 用栈操作构建数组 | | `栈`,`数组`,`模拟` | 简单 | | | +| [1442](https://leetcode-cn.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor) | 形成两个异或相等数组的三元组数目 | | `位运算`,`数组`,`哈希表`,`数学`,`前缀和` | 中等 | | | +| [1443](https://leetcode-cn.com/problems/minimum-time-to-collect-all-apples-in-a-tree) | 收集树上所有苹果的最少时间 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表` | 中等 | | | +| [1444](https://leetcode-cn.com/problems/number-of-ways-of-cutting-a-pizza) | 切披萨的方案数 | | `记忆化搜索`,`数组`,`动态规划`,`矩阵` | 困难 | | | +| [1445](https://leetcode-cn.com/problems/apples-oranges) | 苹果和桔子 | | `数据库` | 中等 | 🔒 | | +| [1446](https://leetcode-cn.com/problems/consecutive-characters) | 连续字符 | | `字符串` | 简单 | | | +| [1447](https://leetcode-cn.com/problems/simplified-fractions) | 最简分数 | | `数学` | 中等 | | | +| [1448](https://leetcode-cn.com/problems/count-good-nodes-in-binary-tree) | 统计二叉树中好节点的数目 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1449](https://leetcode-cn.com/problems/form-largest-integer-with-digits-that-add-up-to-target) | 数位成本和为目标值的最大数字 | | `数组`,`动态规划` | 困难 | | | +| [1450](https://leetcode-cn.com/problems/number-of-students-doing-homework-at-a-given-time) | 在既定时间做作业的学生人数 | | `数组` | 简单 | | | +| [1451](https://leetcode-cn.com/problems/rearrange-words-in-a-sentence) | 重新排列句子中的单词 | | `字符串`,`排序` | 中等 | | | +| [1452](https://leetcode-cn.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list) | 收藏清单 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [1453](https://leetcode-cn.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard) | 圆形靶内的最大飞镖数量 | | `几何`,`数组`,`数学` | 困难 | | | +| [1454](https://leetcode-cn.com/problems/active-users) | 活跃用户 | | `数据库` | 中等 | 🔒 | | +| [1455](https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) | 检查单词是否为句中其他单词的前缀 | | `字符串`,`字符串匹配` | 简单 | | | +| [1456](https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length) | 定长子串中元音的最大数目 | | `字符串`,`滑动窗口` | 中等 | | | +| [1457](https://leetcode-cn.com/problems/pseudo-palindromic-paths-in-a-binary-tree) | 二叉树中的伪回文路径 | | `位运算`,`树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1458](https://leetcode-cn.com/problems/max-dot-product-of-two-subsequences) | 两个子序列的最大点积 | | `数组`,`动态规划` | 困难 | | | +| [1459](https://leetcode-cn.com/problems/rectangles-area) | 矩形面积 | | `数据库` | 中等 | 🔒 | | +| [1460](https://leetcode-cn.com/problems/make-two-arrays-equal-by-reversing-sub-arrays) | 通过翻转子数组使两个数组相等 | | `数组`,`哈希表`,`排序` | 简单 | | | +| [1461](https://leetcode-cn.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k) | 检查一个字符串是否包含所有长度为 K 的二进制子串 | | `位运算`,`哈希表`,`字符串`,`哈希函数`,`滚动哈希` | 中等 | | | +| [1462](https://leetcode-cn.com/problems/course-schedule-iv) | 课程表 IV | | `深度优先搜索`,`广度优先搜索`,`图`,`拓扑排序` | 中等 | | | +| [1463](https://leetcode-cn.com/problems/cherry-pickup-ii) | 摘樱桃 II | | `数组`,`动态规划`,`矩阵` | 困难 | | | +| [1464](https://leetcode-cn.com/problems/maximum-product-of-two-elements-in-an-array) | 数组中两元素的最大乘积 | | `数组`,`排序`,`堆(优先队列)` | 简单 | | | +| [1465](https://leetcode-cn.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts) | 切割后面积最大的蛋糕 | | `贪心`,`数组`,`排序` | 中等 | | | +| [1466](https://leetcode-cn.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero) | 重新规划路线 | | `深度优先搜索`,`广度优先搜索`,`图` | 中等 | | | +| [1467](https://leetcode-cn.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls) | 两个盒子中球的颜色数相同的概率 | | `数学`,`动态规划`,`回溯`,`组合数学`,`概率与统计` | 困难 | | | +| [1468](https://leetcode-cn.com/problems/calculate-salaries) | 计算税后工资 | | `数据库` | 中等 | 🔒 | | +| [1469](https://leetcode-cn.com/problems/find-all-the-lonely-nodes) | 寻找所有的独生节点 | | `树`,`深度优先搜索`,`广度优先搜索`,`二叉树` | 简单 | 🔒 | | +| [1470](https://leetcode-cn.com/problems/shuffle-the-array) | 重新排列数组 | | `数组` | 简单 | | | +| [1471](https://leetcode-cn.com/problems/the-k-strongest-values-in-an-array) | 数组中的 k 个最强值 | | `数组`,`双指针`,`排序` | 中等 | | | +| [1472](https://leetcode-cn.com/problems/design-browser-history) | 设计浏览器历史记录 | | `栈`,`设计`,`数组`,`链表`,`数据流`,`双向链表` | 中等 | | | +| [1473](https://leetcode-cn.com/problems/paint-house-iii) | 粉刷房子 III | | `数组`,`动态规划` | 困难 | | | +| [1474](https://leetcode-cn.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list) | 删除链表 M 个节点之后的 N 个节点 | | `链表` | 简单 | 🔒 | | +| [1475](https://leetcode-cn.com/problems/final-prices-with-a-special-discount-in-a-shop) | 商品折扣后的最终价格 | | `栈`,`数组`,`单调栈` | 简单 | | | +| [1476](https://leetcode-cn.com/problems/subrectangle-queries) | 子矩形查询 | | `设计`,`数组`,`矩阵` | 中等 | | | +| [1477](https://leetcode-cn.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum) | 找两个和为目标值且不重叠的子数组 | | `数组`,`哈希表`,`二分查找`,`动态规划`,`滑动窗口` | 中等 | | | +| [1478](https://leetcode-cn.com/problems/allocate-mailboxes) | 安排邮筒 | | `数组`,`数学`,`动态规划`,`排序` | 困难 | | | +| [1479](https://leetcode-cn.com/problems/sales-by-day-of-the-week) | 周内每天的销售情况 | | `数据库` | 困难 | 🔒 | | +| [1480](https://leetcode-cn.com/problems/running-sum-of-1d-array) | 一维数组的动态和 | | `数组`,`前缀和` | 简单 | | | +| [1481](https://leetcode-cn.com/problems/least-number-of-unique-integers-after-k-removals) | 不同整数的最少数目 | | `贪心`,`数组`,`哈希表`,`计数`,`排序` | 中等 | | | +| [1482](https://leetcode-cn.com/problems/minimum-number-of-days-to-make-m-bouquets) | 制作 m 束花所需的最少天数 | | `数组`,`二分查找` | 中等 | | | +| [1483](https://leetcode-cn.com/problems/kth-ancestor-of-a-tree-node) | 树节点的第 K 个祖先 | | `树`,`深度优先搜索`,`广度优先搜索`,`设计`,`二分查找`,`动态规划` | 困难 | | | +| [1484](https://leetcode-cn.com/problems/group-sold-products-by-the-date) | 按日期分组销售产品 | | `数据库` | 简单 | 🔒 | | +| [1485](https://leetcode-cn.com/problems/clone-binary-tree-with-random-pointer) | 克隆含随机指针的二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | 🔒 | | +| [1486](https://leetcode-cn.com/problems/xor-operation-in-an-array) | 数组异或操作 | | `位运算`,`数学` | 简单 | | | +| [1487](https://leetcode-cn.com/problems/making-file-names-unique) | 保证文件名唯一 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [1488](https://leetcode-cn.com/problems/avoid-flood-in-the-city) | 避免洪水泛滥 | | `贪心`,`数组`,`哈希表`,`二分查找`,`堆(优先队列)` | 中等 | | | +| [1489](https://leetcode-cn.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree) | 找到最小生成树里的关键边和伪关键边 | | `并查集`,`图`,`最小生成树`,`排序`,`强连通分量` | 困难 | | | +| [1490](https://leetcode-cn.com/problems/clone-n-ary-tree) | 克隆 N 叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表` | 中等 | 🔒 | | +| [1491](https://leetcode-cn.com/problems/average-salary-excluding-the-minimum-and-maximum-salary) | 去掉最低工资和最高工资后的工资平均值 | | `数组`,`排序` | 简单 | | | +| [1492](https://leetcode-cn.com/problems/the-kth-factor-of-n) | n 的第 k 个因子 | | `数学` | 中等 | | | +| [1493](https://leetcode-cn.com/problems/longest-subarray-of-1s-after-deleting-one-element) | 删掉一个元素以后全为 1 的最长子数组 | | `数学`,`动态规划`,`滑动窗口` | 中等 | | | +| [1494](https://leetcode-cn.com/problems/parallel-courses-ii) | 并行课程 II | | `位运算`,`图`,`动态规划`,`状态压缩` | 困难 | | | +| [1495](https://leetcode-cn.com/problems/friendly-movies-streamed-last-month) | 上月播放的儿童适宜电影 | | `数据库` | 简单 | 🔒 | | +| [1496](https://leetcode-cn.com/problems/path-crossing) | 判断路径是否相交 | | `哈希表`,`字符串` | 简单 | | | +| [1497](https://leetcode-cn.com/problems/check-if-array-pairs-are-divisible-by-k) | 检查数组对是否可以被 k 整除 | | `数组`,`哈希表`,`计数` | 中等 | | | +| [1498](https://leetcode-cn.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition) | 满足条件的子序列数目 | | `数组`,`双指针`,`二分查找`,`排序` | 中等 | | | +| [1499](https://leetcode-cn.com/problems/max-value-of-equation) | 满足不等式的最大值 | | `队列`,`数组`,`滑动窗口`,`单调队列`,`堆(优先队列)` | 困难 | | | +| [1500](https://leetcode-cn.com/problems/design-a-file-sharing-system) | 设计文件分享系统 | | `设计`,`哈希表`,`数据流`,`堆(优先队列)` | 中等 | 🔒 | | +| [1501](https://leetcode-cn.com/problems/countries-you-can-safely-invest-in) | 可以放心投资的国家 | | `数据库` | 中等 | 🔒 | | +| [1502](https://leetcode-cn.com/problems/can-make-arithmetic-progression-from-sequence) | 判断能否形成等差数列 | | `数组`,`排序` | 简单 | | | +| [1503](https://leetcode-cn.com/problems/last-moment-before-all-ants-fall-out-of-a-plank) | 所有蚂蚁掉下来前的最后一刻 | | `脑筋急转弯`,`数组`,`模拟` | 中等 | | | +| [1504](https://leetcode-cn.com/problems/count-submatrices-with-all-ones) | 统计全 1 子矩形 | | `栈`,`数组`,`动态规划`,`矩阵`,`单调栈` | 中等 | | | +| [1505](https://leetcode-cn.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits) | 最多 K 次交换相邻数位后得到的最小整数 | | `贪心`,`树状数组`,`线段树`,`字符串` | 困难 | | | +| [1506](https://leetcode-cn.com/problems/find-root-of-n-ary-tree) | 找到 N 叉树的根节点 | | `位运算`,`树`,`深度优先搜索`,`哈希表` | 中等 | 🔒 | | +| [1507](https://leetcode-cn.com/problems/reformat-date) | 转变日期格式 | | `字符串` | 简单 | | | +| [1508](https://leetcode-cn.com/problems/range-sum-of-sorted-subarray-sums) | 子数组和排序后的区间和 | | `数组`,`双指针`,`二分查找`,`排序` | 中等 | | | +| [1509](https://leetcode-cn.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves) | 三次操作后最大值与最小值的最小差 | | `贪心`,`数组`,`排序` | 中等 | | | +| [1510](https://leetcode-cn.com/problems/stone-game-iv) | 石子游戏 IV | | `数学`,`动态规划`,`博弈` | 困难 | | | +| [1511](https://leetcode-cn.com/problems/customer-order-frequency) | 消费者下单频率 | | `数据库` | 简单 | 🔒 | | +| [1512](https://leetcode-cn.com/problems/number-of-good-pairs) | 好数对的数目 | | `数组`,`哈希表`,`数学`,`计数` | 简单 | | | +| [1513](https://leetcode-cn.com/problems/number-of-substrings-with-only-1s) | 仅含 1 的子串数 | | `数学`,`字符串` | 中等 | | | +| [1514](https://leetcode-cn.com/problems/path-with-maximum-probability) | 概率最大的路径 | | `图`,`最短路`,`堆(优先队列)` | 中等 | | | +| [1515](https://leetcode-cn.com/problems/best-position-for-a-service-centre) | 服务中心的最佳位置 | | `几何`,`数学`,`随机化` | 困难 | | | +| [1516](https://leetcode-cn.com/problems/move-sub-tree-of-n-ary-tree) | 移动 N 叉树的子树 | | `树`,`深度优先搜索` | 困难 | 🔒 | | +| [1517](https://leetcode-cn.com/problems/find-users-with-valid-e-mails) | 查找拥有有效邮箱的用户 | | `数据库` | 简单 | 🔒 | | +| [1518](https://leetcode-cn.com/problems/water-bottles) | 换酒问题 | | `数学`,`模拟` | 简单 | | | +| [1519](https://leetcode-cn.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label) | 子树中标签相同的节点数 | | `树`,`深度优先搜索`,`广度优先搜索` | 中等 | | | +| [1520](https://leetcode-cn.com/problems/maximum-number-of-non-overlapping-substrings) | 最多的不重叠子字符串 | | `贪心`,`字符串` | 困难 | | | +| [1521](https://leetcode-cn.com/problems/find-a-value-of-a-mysterious-function-closest-to-target) | 找到最接近目标值的函数值 | | `位运算`,`线段树`,`数组`,`二分查找` | 困难 | | | +| [1522](https://leetcode-cn.com/problems/diameter-of-n-ary-tree) | N 叉树的直径 | | `树`,`深度优先搜索` | 中等 | 🔒 | | +| [1523](https://leetcode-cn.com/problems/count-odd-numbers-in-an-interval-range) | 在区间范围内统计奇数数目 | | `数学` | 简单 | | | +| [1524](https://leetcode-cn.com/problems/number-of-sub-arrays-with-odd-sum) | 和为奇数的子数组数目 | | `数组`,`数学`,`动态规划`,`前缀和` | 中等 | | | +| [1525](https://leetcode-cn.com/problems/number-of-good-ways-to-split-a-string) | 字符串的好分割数目 | | `位运算`,`字符串`,`动态规划` | 中等 | | | +| [1526](https://leetcode-cn.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array) | 形成目标数组的子数组最少增加次数 | | `栈`,`贪心`,`数组`,`动态规划`,`单调栈` | 困难 | | | +| [1527](https://leetcode-cn.com/problems/patients-with-a-condition) | 患某种疾病的患者 | | `数据库` | 简单 | 🔒 | | +| [1528](https://leetcode-cn.com/problems/shuffle-string) | 重新排列字符串 | | `数组`,`字符串` | 简单 | | | +| [1529](https://leetcode-cn.com/problems/bulb-switcher-iv) | 灯泡开关 IV | | `贪心`,`字符串` | 中等 | | | +| [1530](https://leetcode-cn.com/problems/number-of-good-leaf-nodes-pairs) | 好叶子节点对的数量 | | `树`,`深度优先搜索`,`二叉树` | 中等 | | | +| [1531](https://leetcode-cn.com/problems/string-compression-ii) | 压缩字符串 II | | `字符串`,`动态规划` | 困难 | | | +| [1532](https://leetcode-cn.com/problems/the-most-recent-three-orders) | 最近的三笔订单 | | `数据库` | 中等 | 🔒 | | +| [1533](https://leetcode-cn.com/problems/find-the-index-of-the-large-integer) | 找到最大整数的索引 | | `数组`,`二分查找`,`交互` | 中等 | 🔒 | | +| [1534](https://leetcode-cn.com/problems/count-good-triplets) | 统计好三元组 | | `数组`,`枚举` | 简单 | | | +| [1535](https://leetcode-cn.com/problems/find-the-winner-of-an-array-game) | 找出数组游戏的赢家 | | `数组`,`模拟` | 中等 | | | +| [1536](https://leetcode-cn.com/problems/minimum-swaps-to-arrange-a-binary-grid) | 排布二进制网格的最少交换次数 | | `贪心`,`数组`,`矩阵` | 中等 | | | +| [1537](https://leetcode-cn.com/problems/get-the-maximum-score) | 最大得分 | | `贪心`,`数组`,`双指针`,`动态规划` | 困难 | | | +| [1538](https://leetcode-cn.com/problems/guess-the-majority-in-a-hidden-array) | 找出隐藏数组中出现次数最多的元素 | | `数组`,`数学`,`交互` | 中等 | 🔒 | | +| [1539](https://leetcode-cn.com/problems/kth-missing-positive-number) | 第 k 个缺失的正整数 | | `数组`,`二分查找` | 简单 | | | +| [1540](https://leetcode-cn.com/problems/can-convert-string-in-k-moves) | K 次操作转变字符串 | | `哈希表`,`字符串` | 中等 | | | +| [1541](https://leetcode-cn.com/problems/minimum-insertions-to-balance-a-parentheses-string) | 平衡括号字符串的最少插入次数 | | `栈`,`贪心`,`字符串` | 中等 | | | +| [1542](https://leetcode-cn.com/problems/find-longest-awesome-substring) | 找出最长的超赞子字符串 | | `位运算`,`哈希表`,`字符串` | 困难 | | | +| [1543](https://leetcode-cn.com/problems/fix-product-name-format) | 产品名称格式修复 | | `数据库` | 简单 | 🔒 | | +| [1544](https://leetcode-cn.com/problems/make-the-string-great) | 整理字符串 | | `栈`,`字符串` | 简单 | | | +| [1545](https://leetcode-cn.com/problems/find-kth-bit-in-nth-binary-string) | 找出第 N 个二进制字符串中的第 K 位 | | `递归`,`字符串` | 中等 | | | +| [1546](https://leetcode-cn.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target) | 和为目标值且不重叠的非空子数组的最大数目 | | `贪心`,`数组`,`哈希表`,`前缀和` | 中等 | | | +| [1547](https://leetcode-cn.com/problems/minimum-cost-to-cut-a-stick) | 切棍子的最小成本 | | `数组`,`动态规划` | 困难 | | | +| [1548](https://leetcode-cn.com/problems/the-most-similar-path-in-a-graph) | 图中最相似的路径 | | `图`,`动态规划` | 困难 | 🔒 | | +| [1549](https://leetcode-cn.com/problems/the-most-recent-orders-for-each-product) | 每件商品的最新订单 | | `数据库` | 中等 | 🔒 | | +| [1550](https://leetcode-cn.com/problems/three-consecutive-odds) | 存在连续三个奇数的数组 | | `数组` | 简单 | | | +| [1551](https://leetcode-cn.com/problems/minimum-operations-to-make-array-equal) | 使数组中所有元素相等的最小操作数 | | `数学` | 中等 | | | +| [1552](https://leetcode-cn.com/problems/magnetic-force-between-two-balls) | 两球之间的磁力 | | `数组`,`二分查找`,`排序` | 中等 | | | +| [1553](https://leetcode-cn.com/problems/minimum-number-of-days-to-eat-n-oranges) | 吃掉 N 个橘子的最少天数 | | `记忆化搜索`,`动态规划` | 困难 | | | +| [1554](https://leetcode-cn.com/problems/strings-differ-by-one-character) | 只有一个不同字符的字符串 | | `哈希表`,`字符串`,`哈希函数`,`滚动哈希` | 中等 | 🔒 | | +| [1555](https://leetcode-cn.com/problems/bank-account-summary) | 银行账户概要 | | `数据库` | 中等 | 🔒 | | +| [1556](https://leetcode-cn.com/problems/thousand-separator) | 千位分隔数 | | `字符串` | 简单 | | | +| [1557](https://leetcode-cn.com/problems/minimum-number-of-vertices-to-reach-all-nodes) | 可以到达所有点的最少点数目 | | `图` | 中等 | | | +| [1558](https://leetcode-cn.com/problems/minimum-numbers-of-function-calls-to-make-target-array) | 得到目标数组的最少函数调用次数 | | `贪心`,`数组` | 中等 | | | +| [1559](https://leetcode-cn.com/problems/detect-cycles-in-2d-grid) | 二维网格图中探测环 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 困难 | | | +| [1560](https://leetcode-cn.com/problems/most-visited-sector-in-a-circular-track) | 圆形赛道上经过次数最多的扇区 | | `数组`,`模拟` | 简单 | | | +| [1561](https://leetcode-cn.com/problems/maximum-number-of-coins-you-can-get) | 你可以获得的最大硬币数目 | | `贪心`,`数组`,`数学`,`博弈`,`排序` | 中等 | | | +| [1562](https://leetcode-cn.com/problems/find-latest-group-of-size-m) | 查找大小为 M 的最新分组 | | `数组`,`二分查找`,`模拟` | 中等 | | | +| [1563](https://leetcode-cn.com/problems/stone-game-v) | 石子游戏 V | | `数组`,`数学`,`动态规划`,`博弈` | 困难 | | | +| [1564](https://leetcode-cn.com/problems/put-boxes-into-the-warehouse-i) | 把箱子放进仓库里 I | | `贪心`,`数组`,`排序` | 中等 | 🔒 | | +| [1565](https://leetcode-cn.com/problems/unique-orders-and-customers-per-month) | 按月统计订单数与顾客数 | | `数据库` | 简单 | 🔒 | | +| [1566](https://leetcode-cn.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times) | 重复至少 K 次且长度为 M 的模式 | | `数组`,`枚举` | 简单 | | | +| [1567](https://leetcode-cn.com/problems/maximum-length-of-subarray-with-positive-product) | 乘积为正数的最长子数组长度 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [1568](https://leetcode-cn.com/problems/minimum-number-of-days-to-disconnect-island) | 使陆地分离的最少天数 | | `深度优先搜索`,`广度优先搜索`,`数组`,`矩阵`,`强连通分量` | 困难 | | | +| [1569](https://leetcode-cn.com/problems/number-of-ways-to-reorder-array-to-get-same-bst) | 将子数组重新排序得到同一个二叉查找树的方案数 | | `树`,`并查集`,`二叉搜索树`,`记忆化搜索`,`数组`,`数学`,`分治`,`动态规划`,`二叉树`,`组合数学` | 困难 | | | +| [1570](https://leetcode-cn.com/problems/dot-product-of-two-sparse-vectors) | 两个稀疏向量的点积 | | `设计`,`数组`,`哈希表`,`双指针` | 中等 | 🔒 | | +| [1571](https://leetcode-cn.com/problems/warehouse-manager) | 仓库经理 | | `数据库` | 简单 | 🔒 | | +| [1572](https://leetcode-cn.com/problems/matrix-diagonal-sum) | 矩阵对角线元素的和 | | `数组`,`矩阵` | 简单 | | | +| [1573](https://leetcode-cn.com/problems/number-of-ways-to-split-a-string) | 分割字符串的方案数 | | `数学`,`字符串` | 中等 | | | +| [1574](https://leetcode-cn.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted) | 删除最短的子数组使剩余数组有序 | | `栈`,`数组`,`双指针`,`二分查找`,`单调栈` | 中等 | | | +| [1575](https://leetcode-cn.com/problems/count-all-possible-routes) | 统计所有可行路径 | | `记忆化搜索`,`数组`,`动态规划` | 困难 | | | +| [1576](https://leetcode-cn.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters) | 替换所有的问号 | | `字符串` | 简单 | | | +| [1577](https://leetcode-cn.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers) | 数的平方等于两数乘积的方法数 | | `数组`,`哈希表`,`数学`,`双指针` | 中等 | | | +| [1578](https://leetcode-cn.com/problems/minimum-deletion-cost-to-avoid-repeating-letters) | 避免重复字母的最小删除成本 | | `贪心`,`数组`,`字符串`,`动态规划` | 中等 | | | +| [1579](https://leetcode-cn.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable) | 保证图可完全遍历 | | `并查集`,`图` | 困难 | | | +| [1580](https://leetcode-cn.com/problems/put-boxes-into-the-warehouse-ii) | 把箱子放进仓库里 II | | `贪心`,`数组`,`排序` | 中等 | 🔒 | | +| [1581](https://leetcode-cn.com/problems/customer-who-visited-but-did-not-make-any-transactions) | 进店却未进行过交易的顾客 | | `数据库` | 简单 | 🔒 | | +| [1582](https://leetcode-cn.com/problems/special-positions-in-a-binary-matrix) | 二进制矩阵中的特殊位置 | | `数组`,`矩阵` | 简单 | | | +| [1583](https://leetcode-cn.com/problems/count-unhappy-friends) | 统计不开心的朋友 | | `数组`,`模拟` | 中等 | | | +| [1584](https://leetcode-cn.com/problems/min-cost-to-connect-all-points) | 连接所有点的最小费用 | | `并查集`,`数组`,`最小生成树` | 中等 | | | +| [1585](https://leetcode-cn.com/problems/check-if-string-is-transformable-with-substring-sort-operations) | 检查字符串是否可以通过排序子字符串得到另一个字符串 | | `贪心`,`字符串`,`排序` | 困难 | | | +| [1586](https://leetcode-cn.com/problems/binary-search-tree-iterator-ii) | 二叉搜索树迭代器 II | | `栈`,`树`,`设计`,`二叉搜索树`,`二叉树`,`迭代器` | 中等 | 🔒 | | +| [1587](https://leetcode-cn.com/problems/bank-account-summary-ii) | 银行账户概要 II | | `数据库` | 简单 | 🔒 | | +| [1588](https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays) | 所有奇数长度子数组的和 | | `数组`,`前缀和` | 简单 | | | +| [1589](https://leetcode-cn.com/problems/maximum-sum-obtained-of-any-permutation) | 所有排列中的最大和 | | `贪心`,`数组`,`前缀和`,`排序` | 中等 | | | +| [1590](https://leetcode-cn.com/problems/make-sum-divisible-by-p) | 使数组和能被 P 整除 | | `数组`,`哈希表`,`前缀和` | 中等 | | | +| [1591](https://leetcode-cn.com/problems/strange-printer-ii) | 奇怪的打印机 II | | `图`,`拓扑排序`,`数组`,`矩阵` | 困难 | | | +| [1592](https://leetcode-cn.com/problems/rearrange-spaces-between-words) | 重新排列单词间的空格 | | `字符串` | 简单 | | | +| [1593](https://leetcode-cn.com/problems/split-a-string-into-the-max-number-of-unique-substrings) | 拆分字符串使唯一子字符串的数目最大 | | `哈希表`,`字符串`,`回溯` | 中等 | | | +| [1594](https://leetcode-cn.com/problems/maximum-non-negative-product-in-a-matrix) | 矩阵的最大非负积 | | `数组`,`动态规划`,`矩阵` | 中等 | | | +| [1595](https://leetcode-cn.com/problems/minimum-cost-to-connect-two-groups-of-points) | 连通两组点的最小成本 | | `位运算`,`数组`,`动态规划`,`状态压缩`,`矩阵` | 困难 | | | +| [1596](https://leetcode-cn.com/problems/the-most-frequently-ordered-products-for-each-customer) | 每位顾客最经常订购的商品 | | `数据库` | 中等 | 🔒 | | +| [1597](https://leetcode-cn.com/problems/build-binary-expression-tree-from-infix-expression) | 根据中缀表达式构造二叉表达式树 | | `栈`,`树`,`字符串`,`二叉树` | 困难 | 🔒 | | +| [1598](https://leetcode-cn.com/problems/crawler-log-folder) | 文件夹操作日志搜集器 | | `栈`,`数组`,`字符串` | 简单 | | | +| [1599](https://leetcode-cn.com/problems/maximum-profit-of-operating-a-centennial-wheel) | 经营摩天轮的最大利润 | | `数组`,`模拟` | 中等 | | | +| [1600](https://leetcode-cn.com/problems/throne-inheritance) | 皇位继承顺序 | | `树`,`深度优先搜索`,`设计`,`哈希表` | 中等 | | | +| [1601](https://leetcode-cn.com/problems/maximum-number-of-achievable-transfer-requests) | 最多可达成的换楼请求数目 | | `位运算`,`枚举` | 困难 | | | +| [1602](https://leetcode-cn.com/problems/find-nearest-right-node-in-binary-tree) | 找到二叉树中最近的右侧节点 | | `树`,`广度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1603](https://leetcode-cn.com/problems/design-parking-system) | 设计停车系统 | | `设计`,`计数`,`模拟` | 简单 | | | +| [1604](https://leetcode-cn.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period) | 警告一小时内使用相同员工卡大于等于三次的人 | | `数组`,`哈希表`,`字符串`,`排序` | 中等 | | | +| [1605](https://leetcode-cn.com/problems/find-valid-matrix-given-row-and-column-sums) | 给定行和列的和求可行矩阵 | | `贪心`,`数组`,`矩阵` | 中等 | | | +| [1606](https://leetcode-cn.com/problems/find-servers-that-handled-most-number-of-requests) | 找到处理最多请求的服务器 | | `贪心`,`数组`,`有序集合`,`堆(优先队列)` | 困难 | | | +| [1607](https://leetcode-cn.com/problems/sellers-with-no-sales) | 没有卖出的卖家 | | `数据库` | 简单 | 🔒 | | +| [1608](https://leetcode-cn.com/problems/special-array-with-x-elements-greater-than-or-equal-x) | 特殊数组的特征值 | | `数组`,`二分查找`,`排序` | 简单 | | | +| [1609](https://leetcode-cn.com/problems/even-odd-tree) | 奇偶树 | | `树`,`广度优先搜索`,`二叉树` | 中等 | | | +| [1610](https://leetcode-cn.com/problems/maximum-number-of-visible-points) | 可见点的最大数目 | | `几何`,`数组`,`数学`,`排序`,`滑动窗口` | 困难 | | | +| [1611](https://leetcode-cn.com/problems/minimum-one-bit-operations-to-make-integers-zero) | 使整数变为 0 的最少操作次数 | | `位运算`,`记忆化搜索`,`动态规划` | 困难 | | | +| [1612](https://leetcode-cn.com/problems/check-if-two-expression-trees-are-equivalent) | 检查两棵二叉表达式树是否等价 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1613](https://leetcode-cn.com/problems/find-the-missing-ids) | 找到遗失的ID | | `数据库` | 中等 | 🔒 | | +| [1614](https://leetcode-cn.com/problems/maximum-nesting-depth-of-the-parentheses) | 括号的最大嵌套深度 | | `栈`,`字符串` | 简单 | | | +| [1615](https://leetcode-cn.com/problems/maximal-network-rank) | 最大网络秩 | | `图` | 中等 | | | +| [1616](https://leetcode-cn.com/problems/split-two-strings-to-make-palindrome) | 分割两个字符串得到回文串 | | `贪心`,`双指针`,`字符串` | 中等 | | | +| [1617](https://leetcode-cn.com/problems/count-subtrees-with-max-distance-between-cities) | 统计子树中城市之间最大距离 | | `位运算`,`树`,`动态规划`,`状态压缩`,`枚举` | 困难 | | | +| [1618](https://leetcode-cn.com/problems/maximum-font-to-fit-a-sentence-in-a-screen) | 找出适应屏幕的最大字号 | | `数组`,`字符串`,`二分查找`,`交互` | 中等 | 🔒 | | +| [1619](https://leetcode-cn.com/problems/mean-of-array-after-removing-some-elements) | 删除某些元素后的数组均值 | | `数组`,`排序` | 简单 | | | +| [1620](https://leetcode-cn.com/problems/coordinate-with-maximum-network-quality) | 网络信号最好的坐标 | | `数组`,`枚举` | 中等 | | | +| [1621](https://leetcode-cn.com/problems/number-of-sets-of-k-non-overlapping-line-segments) | 大小为 K 的不重叠线段的数目 | | `数学`,`动态规划` | 中等 | | | +| [1622](https://leetcode-cn.com/problems/fancy-sequence) | 奇妙序列 | | `设计`,`线段树`,`数学` | 困难 | | | +| [1623](https://leetcode-cn.com/problems/all-valid-triplets-that-can-represent-a-country) | 三人国家代表队 | | `数据库` | 简单 | 🔒 | | +| [1624](https://leetcode-cn.com/problems/largest-substring-between-two-equal-characters) | 两个相同字符之间的最长子字符串 | | `哈希表`,`字符串` | 简单 | | | +| [1625](https://leetcode-cn.com/problems/lexicographically-smallest-string-after-applying-operations) | 执行操作后字典序最小的字符串 | | `广度优先搜索`,`字符串` | 中等 | | | +| [1626](https://leetcode-cn.com/problems/best-team-with-no-conflicts) | 无矛盾的最佳球队 | | `数组`,`动态规划`,`排序` | 中等 | | | +| [1627](https://leetcode-cn.com/problems/graph-connectivity-with-threshold) | 带阈值的图连通性 | | `并查集`,`数组`,`数学` | 困难 | | | +| [1628](https://leetcode-cn.com/problems/design-an-expression-tree-with-evaluate-function) | 设计带解析函数的表达式树 | | `栈`,`树`,`设计`,`数学`,`二叉树` | 中等 | 🔒 | | +| [1629](https://leetcode-cn.com/problems/slowest-key) | 按键持续时间最长的键 | | `数组`,`字符串` | 简单 | | | +| [1630](https://leetcode-cn.com/problems/arithmetic-subarrays) | 等差子数组 | | `数组`,`排序` | 中等 | | | +| [1631](https://leetcode-cn.com/problems/path-with-minimum-effort) | 最小体力消耗路径 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`二分查找`,`矩阵`,`堆(优先队列)` | 中等 | | | +| [1632](https://leetcode-cn.com/problems/rank-transform-of-a-matrix) | 矩阵转换后的秩 | | `贪心`,`并查集`,`图`,`拓扑排序`,`数组`,`矩阵` | 困难 | | | +| [1633](https://leetcode-cn.com/problems/percentage-of-users-attended-a-contest) | 各赛事的用户注册率 | | `数据库` | 简单 | 🔒 | | +| [1634](https://leetcode-cn.com/problems/add-two-polynomials-represented-as-linked-lists) | 求两个多项式链表的和 | | `链表`,`数学`,`双指针` | 中等 | 🔒 | | +| [1635](https://leetcode-cn.com/problems/hopper-company-queries-i) | Hopper 公司查询 I | | `数据库` | 困难 | 🔒 | | +| [1636](https://leetcode-cn.com/problems/sort-array-by-increasing-frequency) | 按照频率将数组升序排序 | | `数组`,`哈希表`,`排序` | 简单 | | | +| [1637](https://leetcode-cn.com/problems/widest-vertical-area-between-two-points-containing-no-points) | 两点之间不包含任何点的最宽垂直面积 | | `数组`,`排序` | 中等 | | | +| [1638](https://leetcode-cn.com/problems/count-substrings-that-differ-by-one-character) | 统计只差一个字符的子串数目 | | `哈希表`,`字符串`,`动态规划` | 中等 | | | +| [1639](https://leetcode-cn.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary) | 通过给定词典构造目标字符串的方案数 | | `数组`,`字符串`,`动态规划` | 困难 | | | +| [1640](https://leetcode-cn.com/problems/check-array-formation-through-concatenation) | 能否连接形成数组 | | `数组`,`哈希表` | 简单 | | | +| [1641](https://leetcode-cn.com/problems/count-sorted-vowel-strings) | 统计字典序元音字符串的数目 | | `动态规划` | 中等 | | | +| [1642](https://leetcode-cn.com/problems/furthest-building-you-can-reach) | 可以到达的最远建筑 | | `贪心`,`数组`,`堆(优先队列)` | 中等 | | | +| [1643](https://leetcode-cn.com/problems/kth-smallest-instructions) | 第 K 条最小指令 | | `数组`,`数学`,`动态规划`,`组合数学` | 困难 | | | +| [1644](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree-ii) | 二叉树的最近公共祖先 II | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1645](https://leetcode-cn.com/problems/hopper-company-queries-ii) | Hopper Company Queries II | | `数据库` | 困难 | 🔒 | | +| [1646](https://leetcode-cn.com/problems/get-maximum-in-generated-array) | 获取生成数组中的最大值 | | `数组`,`动态规划`,`模拟` | 简单 | | | +| [1647](https://leetcode-cn.com/problems/minimum-deletions-to-make-character-frequencies-unique) | 字符频次唯一的最小删除次数 | | `贪心`,`字符串`,`排序` | 中等 | | | +| [1648](https://leetcode-cn.com/problems/sell-diminishing-valued-colored-balls) | 销售价值减少的颜色球 | | `贪心`,`数组`,`数学`,`二分查找`,`排序`,`堆(优先队列)` | 中等 | | | +| [1649](https://leetcode-cn.com/problems/create-sorted-array-through-instructions) | 通过指令创建有序数组 | | `树状数组`,`线段树`,`数组`,`二分查找`,`分治`,`有序集合`,`归并排序` | 困难 | | | +| [1650](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree-iii) | 二叉树的最近公共祖先 III | | `树`,`哈希表`,`二叉树` | 中等 | 🔒 | | +| [1651](https://leetcode-cn.com/problems/hopper-company-queries-iii) | Hopper Company Queries III | | `数据库` | 困难 | 🔒 | | +| [1652](https://leetcode-cn.com/problems/defuse-the-bomb) | 拆炸弹 | | `数组` | 简单 | | | +| [1653](https://leetcode-cn.com/problems/minimum-deletions-to-make-string-balanced) | 使字符串平衡的最少删除次数 | | `栈`,`字符串`,`动态规划` | 中等 | | | +| [1654](https://leetcode-cn.com/problems/minimum-jumps-to-reach-home) | 到家的最少跳跃次数 | | `广度优先搜索`,`数组`,`动态规划` | 中等 | | | +| [1655](https://leetcode-cn.com/problems/distribute-repeating-integers) | 分配重复整数 | | `位运算`,`数组`,`动态规划`,`回溯`,`状态压缩` | 困难 | | | +| [1656](https://leetcode-cn.com/problems/design-an-ordered-stream) | 设计有序流 | | `设计`,`数组`,`哈希表`,`数据流` | 简单 | | | +| [1657](https://leetcode-cn.com/problems/determine-if-two-strings-are-close) | 确定两个字符串是否接近 | | `哈希表`,`字符串`,`排序` | 中等 | | | +| [1658](https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero) | 将 x 减到 0 的最小操作数 | | `数组`,`哈希表`,`双指针`,`二分查找`,`前缀和` | 中等 | | | +| [1659](https://leetcode-cn.com/problems/maximize-grid-happiness) | 最大化网格幸福感 | | `位运算`,`记忆化搜索`,`动态规划`,`状态压缩` | 困难 | | | +| [1660](https://leetcode-cn.com/problems/correct-a-binary-tree) | 纠正二叉树 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | 🔒 | | +| [1661](https://leetcode-cn.com/problems/average-time-of-process-per-machine) | 每台机器的进程平均运行时间 | | `数据库` | 简单 | 🔒 | | +| [1662](https://leetcode-cn.com/problems/check-if-two-string-arrays-are-equivalent) | 检查两个字符串数组是否相等 | | `数组`,`字符串` | 简单 | | | +| [1663](https://leetcode-cn.com/problems/smallest-string-with-a-given-numeric-value) | 具有给定数值的最小字符串 | | `贪心`,`字符串` | 中等 | | | +| [1664](https://leetcode-cn.com/problems/ways-to-make-a-fair-array) | 生成平衡数组的方案数 | | `数组`,`动态规划` | 中等 | | | +| [1665](https://leetcode-cn.com/problems/minimum-initial-energy-to-finish-tasks) | 完成所有任务的最少初始能量 | | `贪心`,`数组`,`排序` | 困难 | | | +| [1666](https://leetcode-cn.com/problems/change-the-root-of-a-binary-tree) | 改变二叉树的根节点 | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1667](https://leetcode-cn.com/problems/fix-names-in-a-table) | 修复表中的名字 | | `数据库` | 简单 | 🔒 | | +| [1668](https://leetcode-cn.com/problems/maximum-repeating-substring) | 最大重复子字符串 | | `字符串`,`字符串匹配` | 简单 | | | +| [1669](https://leetcode-cn.com/problems/merge-in-between-linked-lists) | 合并两个链表 | | `链表` | 中等 | | | +| [1670](https://leetcode-cn.com/problems/design-front-middle-back-queue) | 设计前中后队列 | | `设计`,`队列`,`数组`,`链表`,`数据流` | 中等 | | | +| [1671](https://leetcode-cn.com/problems/minimum-number-of-removals-to-make-mountain-array) | 得到山形数组的最少删除次数 | | `贪心`,`数组`,`二分查找`,`动态规划` | 困难 | | | +| [1672](https://leetcode-cn.com/problems/richest-customer-wealth) | 最富有客户的资产总量 | | `数组`,`矩阵` | 简单 | | | +| [1673](https://leetcode-cn.com/problems/find-the-most-competitive-subsequence) | 找出最具竞争力的子序列 | | `栈`,`贪心`,`数组`,`单调栈` | 中等 | | | +| [1674](https://leetcode-cn.com/problems/minimum-moves-to-make-array-complementary) | 使数组互补的最少操作次数 | | `数组`,`哈希表`,`前缀和` | 中等 | | | +| [1675](https://leetcode-cn.com/problems/minimize-deviation-in-array) | 数组的最小偏移量 | | `贪心`,`数组`,`有序集合`,`堆(优先队列)` | 困难 | | | +| [1676](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree-iv) | 二叉树的最近公共祖先 IV | | `树`,`深度优先搜索`,`二叉树` | 中等 | 🔒 | | +| [1677](https://leetcode-cn.com/problems/products-worth-over-invoices) | 发票中的产品金额 | | `数据库` | 简单 | 🔒 | | +| [1678](https://leetcode-cn.com/problems/goal-parser-interpretation) | 设计 Goal 解析器 | | `字符串` | 简单 | | | +| [1679](https://leetcode-cn.com/problems/max-number-of-k-sum-pairs) | K 和数对的最大数目 | | `数组`,`哈希表`,`双指针`,`排序` | 中等 | | | +| [1680](https://leetcode-cn.com/problems/concatenation-of-consecutive-binary-numbers) | 连接连续二进制数字 | | `位运算`,`数学`,`模拟` | 中等 | | | +| [1681](https://leetcode-cn.com/problems/minimum-incompatibility) | 最小不兼容性 | | `位运算`,`数组`,`动态规划`,`状态压缩` | 困难 | | | +| [1682](https://leetcode-cn.com/problems/longest-palindromic-subsequence-ii) | 最长回文子序列 II | | `字符串`,`动态规划` | 中等 | 🔒 | | +| [1683](https://leetcode-cn.com/problems/invalid-tweets) | 无效的推文 | | `数据库` | 简单 | 🔒 | | +| [1684](https://leetcode-cn.com/problems/count-the-number-of-consistent-strings) | 统计一致字符串的数目 | | `位运算`,`数组`,`哈希表`,`字符串` | 简单 | | | +| [1685](https://leetcode-cn.com/problems/sum-of-absolute-differences-in-a-sorted-array) | 有序数组中差绝对值之和 | | `数组`,`数学`,`前缀和` | 中等 | | | +| [1686](https://leetcode-cn.com/problems/stone-game-vi) | 石子游戏 VI | | `贪心`,`数组`,`数学`,`博弈`,`排序`,`堆(优先队列)` | 中等 | | | +| [1687](https://leetcode-cn.com/problems/delivering-boxes-from-storage-to-ports) | 从仓库到码头运输箱子 | | `线段树`,`队列`,`数组`,`动态规划`,`单调队列`,`堆(优先队列)` | 困难 | | | +| [1688](https://leetcode-cn.com/problems/count-of-matches-in-tournament) | 比赛中的配对次数 | | `数学`,`模拟` | 简单 | | | +| [1689](https://leetcode-cn.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers) | 十-二进制数的最少数目 | | `贪心`,`字符串` | 中等 | | | +| [1690](https://leetcode-cn.com/problems/stone-game-vii) | 石子游戏 VII | | `数组`,`数学`,`动态规划`,`博弈` | 中等 | | | +| [1691](https://leetcode-cn.com/problems/maximum-height-by-stacking-cuboids) | 堆叠长方体的最大高度 | | `数组`,`动态规划`,`排序` | 困难 | | | +| [1692](https://leetcode-cn.com/problems/count-ways-to-distribute-candies) | 计算分配糖果的不同方式 | | `动态规划` | 困难 | 🔒 | | +| [1693](https://leetcode-cn.com/problems/daily-leads-and-partners) | 每天的领导和合伙人 | | `数据库` | 简单 | 🔒 | | +| [1694](https://leetcode-cn.com/problems/reformat-phone-number) | 重新格式化电话号码 | | `字符串` | 简单 | | | +| [1695](https://leetcode-cn.com/problems/maximum-erasure-value) | 删除子数组的最大得分 | | `数组`,`哈希表`,`滑动窗口` | 中等 | | | +| [1696](https://leetcode-cn.com/problems/jump-game-vi) | 跳跃游戏 VI | | `队列`,`数组`,`动态规划`,`滑动窗口`,`单调队列`,`堆(优先队列)` | 中等 | | | +| [1697](https://leetcode-cn.com/problems/checking-existence-of-edge-length-limited-paths) | 检查边长度限制的路径是否存在 | | `并查集`,`图`,`数组`,`排序` | 困难 | | | +| [1698](https://leetcode-cn.com/problems/number-of-distinct-substrings-in-a-string) | 字符串的不同子字符串个数 | | `字典树`,`字符串`,`后缀数组`,`哈希函数`,`滚动哈希` | 中等 | 🔒 | | +| [1699](https://leetcode-cn.com/problems/number-of-calls-between-two-persons) | 两人之间的通话次数 | | `数据库` | 中等 | 🔒 | | +| [1700](https://leetcode-cn.com/problems/number-of-students-unable-to-eat-lunch) | 无法吃午餐的学生数量 | | `栈`,`队列`,`数组`,`模拟` | 简单 | | | +| [1701](https://leetcode-cn.com/problems/average-waiting-time) | 平均等待时间 | | `数组`,`模拟` | 中等 | | | +| [1702](https://leetcode-cn.com/problems/maximum-binary-string-after-change) | 修改后的最大二进制字符串 | | `贪心`,`字符串` | 中等 | | | +| [1703](https://leetcode-cn.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones) | 得到连续 K 个 1 的最少相邻交换次数 | | `贪心`,`数组`,`前缀和`,`滑动窗口` | 困难 | | | +| [1704](https://leetcode-cn.com/problems/determine-if-string-halves-are-alike) | 判断字符串的两半是否相似 | | `字符串`,`计数` | 简单 | | | +| [1705](https://leetcode-cn.com/problems/maximum-number-of-eaten-apples) | 吃苹果的最大数目 | | `贪心`,`数组`,`堆(优先队列)` | 中等 | | | +| [1706](https://leetcode-cn.com/problems/where-will-the-ball-fall) | 球会落何处 | | `深度优先搜索`,`数组`,`动态规划`,`矩阵`,`模拟` | 中等 | | | +| [1707](https://leetcode-cn.com/problems/maximum-xor-with-an-element-from-array) | 与数组中元素的最大异或值 | | `位运算`,`字典树`,`数组` | 困难 | | | +| [1708](https://leetcode-cn.com/problems/largest-subarray-length-k) | 长度为 K 的最大子数组 | | `贪心`,`数组` | 简单 | 🔒 | | +| [1709](https://leetcode-cn.com/problems/biggest-window-between-visits) | 访问日期之间最大的空档期 | | `数据库` | 中等 | 🔒 | | +| [1710](https://leetcode-cn.com/problems/maximum-units-on-a-truck) | 卡车上的最大单元数 | | `贪心`,`数组`,`排序` | 简单 | | | +| [1711](https://leetcode-cn.com/problems/count-good-meals) | 大餐计数 | | `数组`,`哈希表` | 中等 | | | +| [1712](https://leetcode-cn.com/problems/ways-to-split-array-into-three-subarrays) | 将数组分成三个子数组的方案数 | | `数组`,`双指针`,`二分查找`,`前缀和` | 中等 | | | +| [1713](https://leetcode-cn.com/problems/minimum-operations-to-make-a-subsequence) | 得到子序列的最少操作次数 | | `贪心`,`数组`,`哈希表`,`二分查找` | 困难 | | | +| [1714](https://leetcode-cn.com/problems/sum-of-special-evenly-spaced-elements-in-array) | 数组中特殊等间距元素的和 | | `数组`,`动态规划` | 困难 | 🔒 | | +| [1715](https://leetcode-cn.com/problems/count-apples-and-oranges) | 苹果和橘子的个数 | | `数据库` | 中等 | 🔒 | | +| [1716](https://leetcode-cn.com/problems/calculate-money-in-leetcode-bank) | 计算力扣银行的钱 | | `数学` | 简单 | | | +| [1717](https://leetcode-cn.com/problems/maximum-score-from-removing-substrings) | 删除子字符串的最大得分 | | `栈`,`贪心`,`字符串` | 中等 | | | +| [1718](https://leetcode-cn.com/problems/construct-the-lexicographically-largest-valid-sequence) | 构建字典序最大的可行序列 | | `数组`,`回溯` | 中等 | | | +| [1719](https://leetcode-cn.com/problems/number-of-ways-to-reconstruct-a-tree) | 重构一棵树的方案数 | | `树`,`图`,`拓扑排序` | 困难 | | | +| [1720](https://leetcode-cn.com/problems/decode-xored-array) | 解码异或后的数组 | | `位运算`,`数组` | 简单 | | | +| [1721](https://leetcode-cn.com/problems/swapping-nodes-in-a-linked-list) | 交换链表中的节点 | | `链表`,`双指针` | 中等 | | | +| [1722](https://leetcode-cn.com/problems/minimize-hamming-distance-after-swap-operations) | 执行交换操作后的最小汉明距离 | | `深度优先搜索`,`并查集`,`数组` | 中等 | | | +| [1723](https://leetcode-cn.com/problems/find-minimum-time-to-finish-all-jobs) | 完成所有工作的最短时间 | | `位运算`,`数组`,`动态规划`,`回溯`,`状态压缩` | 困难 | | | +| [1724](https://leetcode-cn.com/problems/checking-existence-of-edge-length-limited-paths-ii) | 检查边长度限制的路径是否存在 II | | `并查集`,`图`,`最小生成树` | 困难 | 🔒 | | +| [1725](https://leetcode-cn.com/problems/number-of-rectangles-that-can-form-the-largest-square) | 可以形成最大正方形的矩形数目 | | `数组` | 简单 | | | +| [1726](https://leetcode-cn.com/problems/tuple-with-same-product) | 同积元组 | | `数组`,`哈希表` | 中等 | | | +| [1727](https://leetcode-cn.com/problems/largest-submatrix-with-rearrangements) | 重新排列后的最大子矩阵 | | `贪心`,`数组`,`矩阵`,`排序` | 中等 | | | +| [1728](https://leetcode-cn.com/problems/cat-and-mouse-ii) | 猫和老鼠 II | | `广度优先搜索`,`图`,`记忆化搜索`,`数学`,`动态规划`,`博弈` | 困难 | | | +| [1729](https://leetcode-cn.com/problems/find-followers-count) | 求关注者的数量 | | `数据库` | 简单 | 🔒 | | +| [1730](https://leetcode-cn.com/problems/shortest-path-to-get-food) | 获取食物的最短路径 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | 🔒 | | +| [1731](https://leetcode-cn.com/problems/the-number-of-employees-which-report-to-each-employee) | 每位经理的下属员工数量 | | `数据库` | 简单 | 🔒 | | +| [1732](https://leetcode-cn.com/problems/find-the-highest-altitude) | 找到最高海拔 | | `数组`,`前缀和` | 简单 | | | +| [1733](https://leetcode-cn.com/problems/minimum-number-of-people-to-teach) | 需要教语言的最少人数 | | `贪心`,`数组` | 中等 | | | +| [1734](https://leetcode-cn.com/problems/decode-xored-permutation) | 解码异或后的排列 | | `位运算`,`数组` | 中等 | | | +| [1735](https://leetcode-cn.com/problems/count-ways-to-make-array-with-product) | 生成乘积数组的方案数 | | `数组`,`数学`,`动态规划` | 困难 | | | +| [1736](https://leetcode-cn.com/problems/latest-time-by-replacing-hidden-digits) | 替换隐藏数字得到的最晚时间 | | `字符串` | 简单 | | | +| [1737](https://leetcode-cn.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions) | 满足三条件之一需改变的最少字符数 | | `哈希表`,`字符串`,`计数`,`前缀和` | 中等 | | | +| [1738](https://leetcode-cn.com/problems/find-kth-largest-xor-coordinate-value) | 找出第 K 大的异或坐标值 | | `位运算`,`数组`,`分治`,`矩阵`,`前缀和`,`快速选择`,`堆(优先队列)` | 中等 | | | +| [1739](https://leetcode-cn.com/problems/building-boxes) | 放置盒子 | | `贪心`,`数学`,`二分查找` | 困难 | | | +| [1740](https://leetcode-cn.com/problems/find-distance-in-a-binary-tree) | 找到二叉树中的距离 | | `树`,`深度优先搜索`,`广度优先搜索`,`哈希表`,`二叉树` | 中等 | 🔒 | | +| [1741](https://leetcode-cn.com/problems/find-total-time-spent-by-each-employee) | 查找每个员工花费的总时间 | | `数据库` | 简单 | 🔒 | | +| [1742](https://leetcode-cn.com/problems/maximum-number-of-balls-in-a-box) | 盒子中小球的最大数量 | | `哈希表`,`数学`,`计数` | 简单 | | | +| [1743](https://leetcode-cn.com/problems/restore-the-array-from-adjacent-pairs) | 从相邻元素对还原数组 | | `数组`,`哈希表` | 中等 | | | +| [1744](https://leetcode-cn.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day) | 你能在你最喜欢的那天吃到你最喜欢的糖果吗? | | `数组`,`前缀和` | 中等 | | | +| [1745](https://leetcode-cn.com/problems/palindrome-partitioning-iv) | 回文串分割 IV | | `字符串`,`动态规划` | 困难 | | | +| [1746](https://leetcode-cn.com/problems/maximum-subarray-sum-after-one-operation) | 经过一次操作后的最大子数组和 | | `数组`,`动态规划` | 中等 | 🔒 | | +| [1747](https://leetcode-cn.com/problems/leetflex-banned-accounts) | 应该被禁止的Leetflex账户 | | `数据库` | 中等 | 🔒 | | +| [1748](https://leetcode-cn.com/problems/sum-of-unique-elements) | 唯一元素的和 | | `数组`,`哈希表`,`计数` | 简单 | | | +| [1749](https://leetcode-cn.com/problems/maximum-absolute-sum-of-any-subarray) | 任意子数组和的绝对值的最大值 | | `数组`,`动态规划` | 中等 | | | +| [1750](https://leetcode-cn.com/problems/minimum-length-of-string-after-deleting-similar-ends) | 删除字符串两端相同字符后的最短长度 | | `双指针`,`字符串` | 中等 | | | +| [1751](https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended-ii) | 最多可以参加的会议数目 II | | `数组`,`二分查找`,`动态规划` | 困难 | | | +| [1752](https://leetcode-cn.com/problems/check-if-array-is-sorted-and-rotated) | 检查数组是否经排序和轮转得到 | | `数组` | 简单 | | | +| [1753](https://leetcode-cn.com/problems/maximum-score-from-removing-stones) | 移除石子的最大得分 | | `贪心`,`数学`,`堆(优先队列)` | 中等 | | | +| [1754](https://leetcode-cn.com/problems/largest-merge-of-two-strings) | 构造字典序最大的合并字符串 | | `贪心`,`双指针`,`字符串` | 中等 | | | +| [1755](https://leetcode-cn.com/problems/closest-subsequence-sum) | 最接近目标值的子序列和 | | `位运算`,`数组`,`双指针`,`动态规划`,`状态压缩` | 困难 | | | +| [1756](https://leetcode-cn.com/problems/design-most-recently-used-queue) | 设计最近使用(MRU)队列 | | `栈`,`设计`,`数组`,`哈希表`,`有序集合` | 中等 | 🔒 | | +| [1757](https://leetcode-cn.com/problems/recyclable-and-low-fat-products) | 可回收且低脂的产品 | | `数据库` | 简单 | 🔒 | | +| [1758](https://leetcode-cn.com/problems/minimum-changes-to-make-alternating-binary-string) | 生成交替二进制字符串的最少操作数 | | `字符串` | 简单 | | | +| [1759](https://leetcode-cn.com/problems/count-number-of-homogenous-substrings) | 统计同构子字符串的数目 | | `数学`,`字符串` | 中等 | | | +| [1760](https://leetcode-cn.com/problems/minimum-limit-of-balls-in-a-bag) | 袋子里最少数目的球 | | `数组`,`二分查找` | 中等 | | | +| [1761](https://leetcode-cn.com/problems/minimum-degree-of-a-connected-trio-in-a-graph) | 一个图中连通三元组的最小度数 | | `图` | 困难 | | | +| [1762](https://leetcode-cn.com/problems/buildings-with-an-ocean-view) | 能看到海景的建筑物 | | `栈`,`数组`,`单调栈` | 中等 | 🔒 | | +| [1763](https://leetcode-cn.com/problems/longest-nice-substring) | 最长的美好子字符串 | | `位运算`,`哈希表`,`字符串`,`滑动窗口` | 简单 | | | +| [1764](https://leetcode-cn.com/problems/form-array-by-concatenating-subarrays-of-another-array) | 通过连接另一个数组的子数组得到一个数组 | | `贪心`,`数组`,`字符串匹配` | 中等 | | | +| [1765](https://leetcode-cn.com/problems/map-of-highest-peak) | 地图中的最高点 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [1766](https://leetcode-cn.com/problems/tree-of-coprimes) | 互质树 | | `树`,`深度优先搜索`,`广度优先搜索`,`数学` | 困难 | | | +| [1767](https://leetcode-cn.com/problems/find-the-subtasks-that-did-not-execute) | 寻找没有被执行的任务对 | | `数据库` | 困难 | 🔒 | | +| [1768](https://leetcode-cn.com/problems/merge-strings-alternately) | 交替合并字符串 | | `双指针`,`字符串` | 简单 | | | +| [1769](https://leetcode-cn.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box) | 移动所有球到每个盒子所需的最小操作数 | | `数组`,`字符串` | 中等 | | | +| [1770](https://leetcode-cn.com/problems/maximum-score-from-performing-multiplication-operations) | 执行乘法运算的最大分数 | | `数组`,`动态规划` | 中等 | | | +| [1771](https://leetcode-cn.com/problems/maximize-palindrome-length-from-subsequences) | 由子序列构造的最长回文串的长度 | | `字符串`,`动态规划` | 困难 | | | +| [1772](https://leetcode-cn.com/problems/sort-features-by-popularity) | 按受欢迎程度排列功能 | | `数组`,`哈希表`,`字符串`,`排序` | 中等 | 🔒 | | +| [1773](https://leetcode-cn.com/problems/count-items-matching-a-rule) | 统计匹配检索规则的物品数量 | | `数组`,`字符串` | 简单 | | | +| [1774](https://leetcode-cn.com/problems/closest-dessert-cost) | 最接近目标价格的甜点成本 | | `数组`,`动态规划`,`回溯` | 中等 | | | +| [1775](https://leetcode-cn.com/problems/equal-sum-arrays-with-minimum-number-of-operations) | 通过最少操作次数使数组的和相等 | | `贪心`,`数组`,`哈希表`,`计数` | 中等 | | | +| [1776](https://leetcode-cn.com/problems/car-fleet-ii) | 车队 II | | `栈`,`数组`,`数学`,`单调栈`,`堆(优先队列)` | 困难 | | | +| [1777](https://leetcode-cn.com/problems/products-price-for-each-store) | 每家商店的产品价格 | | `数据库` | 简单 | 🔒 | | +| [1778](https://leetcode-cn.com/problems/shortest-path-in-a-hidden-grid) | 未知网格中的最短路径 | | `深度优先搜索`,`广度优先搜索`,`图`,`交互` | 中等 | 🔒 | | +| [1779](https://leetcode-cn.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate) | 找到最近的有相同 X 或 Y 坐标的点 | | `数组` | 简单 | | | +| [1780](https://leetcode-cn.com/problems/check-if-number-is-a-sum-of-powers-of-three) | 判断一个数字是否可以表示成三的幂的和 | | `数学` | 中等 | | | +| [1781](https://leetcode-cn.com/problems/sum-of-beauty-of-all-substrings) | 所有子字符串美丽值之和 | | `哈希表`,`字符串`,`计数` | 中等 | | | +| [1782](https://leetcode-cn.com/problems/count-pairs-of-nodes) | 统计点对的数目 | | `图`,`双指针`,`二分查找` | 困难 | | | +| [1783](https://leetcode-cn.com/problems/grand-slam-titles) | 大满贯数量 | | `数据库` | 中等 | 🔒 | | +| [1784](https://leetcode-cn.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones) | 检查二进制字符串字段 | | `字符串` | 简单 | | | +| [1785](https://leetcode-cn.com/problems/minimum-elements-to-add-to-form-a-given-sum) | 构成特定和需要添加的最少元素 | | `贪心`,`数组` | 中等 | | | +| [1786](https://leetcode-cn.com/problems/number-of-restricted-paths-from-first-to-last-node) | 从第一个节点出发到最后一个节点的受限路径数 | | `图`,`拓扑排序`,`动态规划`,`最短路`,`堆(优先队列)` | 中等 | | | +| [1787](https://leetcode-cn.com/problems/make-the-xor-of-all-segments-equal-to-zero) | 使所有区间的异或结果为零 | | `位运算`,`数组`,`动态规划` | 困难 | | | +| [1788](https://leetcode-cn.com/problems/maximize-the-beauty-of-the-garden) | 最大化花园的美观度 | | `贪心`,`数组`,`前缀和` | 困难 | 🔒 | | +| [1789](https://leetcode-cn.com/problems/primary-department-for-each-employee) | 员工的直属部门 | | `数据库` | 简单 | 🔒 | | +| [1790](https://leetcode-cn.com/problems/check-if-one-string-swap-can-make-strings-equal) | 仅执行一次字符串交换能否使两个字符串相等 | | `哈希表`,`字符串`,`计数` | 简单 | | | +| [1791](https://leetcode-cn.com/problems/find-center-of-star-graph) | 找出星型图的中心节点 | | `图` | 简单 | | | +| [1792](https://leetcode-cn.com/problems/maximum-average-pass-ratio) | 最大平均通过率 | | `贪心`,`数组`,`堆(优先队列)` | 中等 | | | +| [1793](https://leetcode-cn.com/problems/maximum-score-of-a-good-subarray) | 好子数组的最大分数 | | `栈`,`数组`,`双指针`,`单调栈` | 困难 | | | +| [1794](https://leetcode-cn.com/problems/count-pairs-of-equal-substrings-with-minimum-difference) | 统计距离最小的子串对个数 | | `贪心`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [1795](https://leetcode-cn.com/problems/rearrange-products-table) | 每个产品在不同商店的价格 | | `数据库` | 简单 | 🔒 | | +| [1796](https://leetcode-cn.com/problems/second-largest-digit-in-a-string) | 字符串中第二大的数字 | | `哈希表`,`字符串` | 简单 | | | +| [1797](https://leetcode-cn.com/problems/design-authentication-manager) | 设计一个验证系统 | | `设计`,`哈希表` | 中等 | | | +| [1798](https://leetcode-cn.com/problems/maximum-number-of-consecutive-values-you-can-make) | 你能构造出连续值的最大数目 | | `贪心`,`数组` | 中等 | | | +| [1799](https://leetcode-cn.com/problems/maximize-score-after-n-operations) | N 次操作后的最大分数和 | | `位运算`,`数组`,`数学`,`动态规划`,`回溯`,`状态压缩`,`数论` | 困难 | | | +| [1800](https://leetcode-cn.com/problems/maximum-ascending-subarray-sum) | 最大升序子数组和 | | `数组` | 简单 | | | +| [1801](https://leetcode-cn.com/problems/number-of-orders-in-the-backlog) | 积压订单中的订单总数 | | `数组`,`模拟`,`堆(优先队列)` | 中等 | | | +| [1802](https://leetcode-cn.com/problems/maximum-value-at-a-given-index-in-a-bounded-array) | 有界数组中指定下标处的最大值 | | `贪心`,`二分查找` | 中等 | | | +| [1803](https://leetcode-cn.com/problems/count-pairs-with-xor-in-a-range) | 统计异或值在范围内的数对有多少 | | `位运算`,`字典树`,`数组` | 困难 | | | +| [1804](https://leetcode-cn.com/problems/implement-trie-ii-prefix-tree) | 实现 Trie (前缀树) II | | `设计`,`字典树`,`哈希表`,`字符串` | 中等 | 🔒 | | +| [1805](https://leetcode-cn.com/problems/number-of-different-integers-in-a-string) | 字符串中不同整数的数目 | | `哈希表`,`字符串` | 简单 | | | +| [1806](https://leetcode-cn.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation) | 还原排列的最少操作步数 | | `数组`,`数学`,`模拟` | 中等 | | | +| [1807](https://leetcode-cn.com/problems/evaluate-the-bracket-pairs-of-a-string) | 替换字符串中的括号内容 | | `数组`,`哈希表`,`字符串` | 中等 | | | +| [1808](https://leetcode-cn.com/problems/maximize-number-of-nice-divisors) | 好因子的最大数目 | | `递归`,`数学` | 困难 | | | +| [1809](https://leetcode-cn.com/problems/ad-free-sessions) | 没有广告的剧集 | | `数据库` | 简单 | 🔒 | | +| [1810](https://leetcode-cn.com/problems/minimum-path-cost-in-a-hidden-grid) | 隐藏网格下的最小消耗路径 | | `深度优先搜索`,`广度优先搜索`,`图`,`交互`,`堆(优先队列)` | 中等 | 🔒 | | +| [1811](https://leetcode-cn.com/problems/find-interview-candidates) | 寻找面试候选人 | | `数据库` | 中等 | 🔒 | | +| [1812](https://leetcode-cn.com/problems/determine-color-of-a-chessboard-square) | 判断国际象棋棋盘中一个格子的颜色 | | `数学`,`字符串` | 简单 | | | +| [1813](https://leetcode-cn.com/problems/sentence-similarity-iii) | 句子相似性 III | | `数组`,`双指针`,`字符串` | 中等 | | | +| [1814](https://leetcode-cn.com/problems/count-nice-pairs-in-an-array) | 统计一个数组中好对子的数目 | | `数组`,`哈希表`,`数学`,`计数` | 中等 | | | +| [1815](https://leetcode-cn.com/problems/maximum-number-of-groups-getting-fresh-donuts) | 得到新鲜甜甜圈的最多组数 | | `位运算`,`记忆化搜索`,`数组`,`动态规划`,`状态压缩` | 困难 | | | +| [1816](https://leetcode-cn.com/problems/truncate-sentence) | 截断句子 | | `数组`,`字符串` | 简单 | | | +| [1817](https://leetcode-cn.com/problems/finding-the-users-active-minutes) | 查找用户活跃分钟数 | | `数组`,`哈希表` | 中等 | | | +| [1818](https://leetcode-cn.com/problems/minimum-absolute-sum-difference) | 绝对差值和 | | `贪心`,`数组`,`二分查找`,`有序集合` | 中等 | | | +| [1819](https://leetcode-cn.com/problems/number-of-different-subsequences-gcds) | 序列中不同最大公约数的数目 | | `数组`,`数学`,`计数`,`数论` | 困难 | | | +| [1820](https://leetcode-cn.com/problems/maximum-number-of-accepted-invitations) | 最多邀请的个数 | | `数组`,`回溯`,`矩阵` | 中等 | 🔒 | | +| [1821](https://leetcode-cn.com/problems/find-customers-with-positive-revenue-this-year) | 寻找今年具有正收入的客户 | | `数据库` | 简单 | 🔒 | | +| [1822](https://leetcode-cn.com/problems/sign-of-the-product-of-an-array) | 数组元素积的符号 | | `数组`,`数学` | 简单 | | | +| [1823](https://leetcode-cn.com/problems/find-the-winner-of-the-circular-game) | 找出游戏的获胜者 | | `递归`,`数组`,`数学`,`模拟` | 中等 | | | +| [1824](https://leetcode-cn.com/problems/minimum-sideway-jumps) | 最少侧跳次数 | | `贪心`,`数组`,`动态规划` | 中等 | | | +| [1825](https://leetcode-cn.com/problems/finding-mk-average) | 求出 MK 平均值 | | `设计`,`队列`,`有序集合`,`堆(优先队列)` | 困难 | | | +| [1826](https://leetcode-cn.com/problems/faulty-sensor) | 有缺陷的传感器 | | `数组`,`双指针` | 简单 | 🔒 | | +| [1827](https://leetcode-cn.com/problems/minimum-operations-to-make-the-array-increasing) | 最少操作使数组递增 | | `贪心`,`数组` | 简单 | | | +| [1828](https://leetcode-cn.com/problems/queries-on-number-of-points-inside-a-circle) | 统计一个圆中点的数目 | | `几何`,`数组`,`数学` | 中等 | | | +| [1829](https://leetcode-cn.com/problems/maximum-xor-for-each-query) | 每个查询的最大异或值 | | `位运算`,`数组`,`前缀和` | 中等 | | | +| [1830](https://leetcode-cn.com/problems/minimum-number-of-operations-to-make-string-sorted) | 使字符串有序的最少操作次数 | | `数学`,`字符串`,`组合数学` | 困难 | | | +| [1831](https://leetcode-cn.com/problems/maximum-transaction-each-day) | 每天的最大交易 | | `数据库` | 中等 | 🔒 | | +| [1832](https://leetcode-cn.com/problems/check-if-the-sentence-is-pangram) | 判断句子是否为全字母句 | | `哈希表`,`字符串` | 简单 | | | +| [1833](https://leetcode-cn.com/problems/maximum-ice-cream-bars) | 雪糕的最大数量 | | `贪心`,`数组`,`排序` | 中等 | | | +| [1834](https://leetcode-cn.com/problems/single-threaded-cpu) | 单线程 CPU | | `数组`,`排序`,`堆(优先队列)` | 中等 | | | +| [1835](https://leetcode-cn.com/problems/find-xor-sum-of-all-pairs-bitwise-and) | 所有数对按位与结果的异或和 | | `位运算`,`数组`,`数学` | 困难 | | | +| [1836](https://leetcode-cn.com/problems/remove-duplicates-from-an-unsorted-linked-list) | 从未排序的链表中移除重复元素 | | `哈希表`,`链表` | 中等 | 🔒 | | +| [1837](https://leetcode-cn.com/problems/sum-of-digits-in-base-k) | K 进制表示下的各位数字总和 | | `数学` | 简单 | | | +| [1838](https://leetcode-cn.com/problems/frequency-of-the-most-frequent-element) | 最高频元素的频数 | | `数组`,`二分查找`,`前缀和`,`滑动窗口` | 中等 | | | +| [1839](https://leetcode-cn.com/problems/longest-substring-of-all-vowels-in-order) | 所有元音按顺序排布的最长子字符串 | | `字符串`,`滑动窗口` | 中等 | | | +| [1840](https://leetcode-cn.com/problems/maximum-building-height) | 最高建筑高度 | | `数组`,`数学` | 困难 | | | +| [1841](https://leetcode-cn.com/problems/league-statistics) | 联赛信息统计 | | `数据库` | 中等 | 🔒 | | +| [1842](https://leetcode-cn.com/problems/next-palindrome-using-same-digits) | 下个由相同数字构成的回文串 | | `双指针`,`字符串` | 困难 | 🔒 | | +| [1843](https://leetcode-cn.com/problems/suspicious-bank-accounts) | Suspicious Bank Accounts | | `数据库` | 中等 | 🔒 | | +| [1844](https://leetcode-cn.com/problems/replace-all-digits-with-characters) | 将所有数字用字符替换 | | `字符串` | 简单 | | | +| [1845](https://leetcode-cn.com/problems/seat-reservation-manager) | 座位预约管理系统 | | `设计`,`堆(优先队列)` | 中等 | | | +| [1846](https://leetcode-cn.com/problems/maximum-element-after-decreasing-and-rearranging) | 减小和重新排列数组后的最大元素 | | `贪心`,`数组`,`排序` | 中等 | | | +| [1847](https://leetcode-cn.com/problems/closest-room) | 最近的房间 | | `数组`,`二分查找`,`排序` | 困难 | | | +| [1848](https://leetcode-cn.com/problems/minimum-distance-to-the-target-element) | 到目标元素的最小距离 | | `数组` | 简单 | | | +| [1849](https://leetcode-cn.com/problems/splitting-a-string-into-descending-consecutive-values) | 将字符串拆分为递减的连续值 | | `字符串`,`回溯` | 中等 | | | +| [1850](https://leetcode-cn.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number) | 邻位交换的最小次数 | | `贪心`,`双指针`,`字符串` | 中等 | | | +| [1851](https://leetcode-cn.com/problems/minimum-interval-to-include-each-query) | 包含每个查询的最小区间 | | `数组`,`二分查找`,`排序`,`扫描线`,`堆(优先队列)` | 困难 | | | +| [1852](https://leetcode-cn.com/problems/distinct-numbers-in-each-subarray) | 每个子数组的数字种类数 | | `数组`,`哈希表`,`滑动窗口` | 中等 | 🔒 | | +| [1853](https://leetcode-cn.com/problems/convert-date-format) | 转换日期格式 | | `数据库` | 简单 | 🔒 | | +| [1854](https://leetcode-cn.com/problems/maximum-population-year) | 人口最多的年份 | | `数组`,`计数` | 简单 | | | +| [1855](https://leetcode-cn.com/problems/maximum-distance-between-a-pair-of-values) | 下标对中的最大距离 | | `贪心`,`数组`,`双指针`,`二分查找` | 中等 | | | +| [1856](https://leetcode-cn.com/problems/maximum-subarray-min-product) | 子数组最小乘积的最大值 | | `栈`,`数组`,`前缀和`,`单调栈` | 中等 | | | +| [1857](https://leetcode-cn.com/problems/largest-color-value-in-a-directed-graph) | 有向图中最大颜色值 | | `图`,`拓扑排序`,`记忆化搜索`,`哈希表`,`动态规划`,`计数` | 困难 | | | +| [1858](https://leetcode-cn.com/problems/longest-word-with-all-prefixes) | 包含所有前缀的最长单词 | | `深度优先搜索`,`字典树` | 中等 | 🔒 | | +| [1859](https://leetcode-cn.com/problems/sorting-the-sentence) | 将句子排序 | | `字符串`,`排序` | 简单 | | | +| [1860](https://leetcode-cn.com/problems/incremental-memory-leak) | 增长的内存泄露 | | `模拟` | 中等 | | | +| [1861](https://leetcode-cn.com/problems/rotating-the-box) | 旋转盒子 | | `数组`,`双指针`,`矩阵` | 中等 | | | +| [1862](https://leetcode-cn.com/problems/sum-of-floored-pairs) | 向下取整数对和 | | `数组`,`数学`,`二分查找`,`前缀和` | 困难 | | | +| [1863](https://leetcode-cn.com/problems/sum-of-all-subset-xor-totals) | 找出所有子集的异或总和再求和 | | `位运算`,`数组`,`回溯` | 简单 | | | +| [1864](https://leetcode-cn.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating) | 构成交替字符串需要的最小交换次数 | | `贪心`,`字符串` | 中等 | | | +| [1865](https://leetcode-cn.com/problems/finding-pairs-with-a-certain-sum) | 找出和为指定值的下标对 | | `设计`,`数组`,`哈希表` | 中等 | | | +| [1866](https://leetcode-cn.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible) | 恰有 K 根木棍可以看到的排列数目 | | `数学`,`动态规划`,`组合数学` | 困难 | | | +| [1867](https://leetcode-cn.com/problems/orders-with-maximum-quantity-above-average) | Orders With Maximum Quantity Above Average | | `数据库` | 中等 | 🔒 | | +| [1868](https://leetcode-cn.com/problems/product-of-two-run-length-encoded-arrays) | 两个行程编码数组的积 | | `数组`,`双指针` | 中等 | 🔒 | | +| [1869](https://leetcode-cn.com/problems/longer-contiguous-segments-of-ones-than-zeros) | 哪种连续子字符串更长 | | `字符串` | 简单 | | | +| [1870](https://leetcode-cn.com/problems/minimum-speed-to-arrive-on-time) | 准时到达的列车最小时速 | | `数组`,`二分查找` | 中等 | | | +| [1871](https://leetcode-cn.com/problems/jump-game-vii) | 跳跃游戏 VII | | `双指针`,`字符串`,`前缀和` | 中等 | | | +| [1872](https://leetcode-cn.com/problems/stone-game-viii) | 石子游戏 VIII | | `数组`,`数学`,`动态规划`,`博弈`,`前缀和` | 困难 | | | +| [1873](https://leetcode-cn.com/problems/calculate-special-bonus) | 计算特殊奖金 | | `数据库` | 简单 | 🔒 | | +| [1874](https://leetcode-cn.com/problems/minimize-product-sum-of-two-arrays) | 两个数组的最小乘积和 | | `贪心`,`数组`,`排序` | 中等 | 🔒 | | +| [1875](https://leetcode-cn.com/problems/group-employees-of-the-same-salary) | Group Employees of the Same Salary | | `数据库` | 中等 | 🔒 | | +| [1876](https://leetcode-cn.com/problems/substrings-of-size-three-with-distinct-characters) | 长度为三且各字符不同的子字符串 | | `哈希表`,`字符串`,`计数`,`滑动窗口` | 简单 | | | +| [1877](https://leetcode-cn.com/problems/minimize-maximum-pair-sum-in-array) | 数组中最大数对和的最小值 | | `贪心`,`数组`,`双指针`,`排序` | 中等 | | | +| [1878](https://leetcode-cn.com/problems/get-biggest-three-rhombus-sums-in-a-grid) | 矩阵中最大的三个菱形和 | | `数组`,`数学`,`矩阵`,`前缀和`,`排序`,`堆(优先队列)` | 中等 | | | +| [1879](https://leetcode-cn.com/problems/minimum-xor-sum-of-two-arrays) | 两个数组最小的异或值之和 | | `位运算`,`数组`,`动态规划`,`状态压缩` | 困难 | | | +| [1880](https://leetcode-cn.com/problems/check-if-word-equals-summation-of-two-words) | 检查某单词是否等于两单词之和 | | `字符串` | 简单 | | | +| [1881](https://leetcode-cn.com/problems/maximum-value-after-insertion) | 插入后的最大值 | | `贪心`,`字符串` | 中等 | | | +| [1882](https://leetcode-cn.com/problems/process-tasks-using-servers) | 使用服务器处理任务 | | `数组`,`堆(优先队列)` | 中等 | | | +| [1883](https://leetcode-cn.com/problems/minimum-skips-to-arrive-at-meeting-on-time) | 准时抵达会议现场的最小跳过休息次数 | | `数组`,`动态规划` | 困难 | | | +| [1884](https://leetcode-cn.com/problems/egg-drop-with-2-eggs-and-n-floors) | 鸡蛋掉落-两枚鸡蛋 | | `数学`,`动态规划` | 中等 | | | +| [1885](https://leetcode-cn.com/problems/count-pairs-in-two-arrays) | Count Pairs in Two Arrays | | `数组`,`二分查找`,`排序` | 中等 | 🔒 | | +| [1886](https://leetcode-cn.com/problems/determine-whether-matrix-can-be-obtained-by-rotation) | 判断矩阵经轮转后是否一致 | | `数组`,`矩阵` | 简单 | | | +| [1887](https://leetcode-cn.com/problems/reduction-operations-to-make-the-array-elements-equal) | 使数组元素相等的减少操作次数 | | `数组`,`排序` | 中等 | | | +| [1888](https://leetcode-cn.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating) | 使二进制字符串字符交替的最少反转次数 | | `贪心`,`字符串` | 中等 | | | +| [1889](https://leetcode-cn.com/problems/minimum-space-wasted-from-packaging) | 装包裹的最小浪费空间 | | `数组`,`二分查找`,`前缀和`,`排序` | 困难 | | | +| [1890](https://leetcode-cn.com/problems/the-latest-login-in-2020) | 2020年最后一次登录 | | `数据库` | 简单 | 🔒 | | +| [1891](https://leetcode-cn.com/problems/cutting-ribbons) | 割绳子 | | `数组`,`二分查找` | 中等 | 🔒 | | +| [1892](https://leetcode-cn.com/problems/page-recommendations-ii) | 页面推荐Ⅱ | | `数据库` | 困难 | 🔒 | | +| [1893](https://leetcode-cn.com/problems/check-if-all-the-integers-in-a-range-are-covered) | 检查是否区域内所有整数都被覆盖 | | `数组`,`哈希表`,`前缀和` | 简单 | | | +| [1894](https://leetcode-cn.com/problems/find-the-student-that-will-replace-the-chalk) | 找到需要补充粉笔的学生编号 | | `数组`,`二分查找`,`前缀和`,`模拟` | 中等 | | | +| [1895](https://leetcode-cn.com/problems/largest-magic-square) | 最大的幻方 | | `数组`,`矩阵`,`前缀和` | 中等 | | | +| [1896](https://leetcode-cn.com/problems/minimum-cost-to-change-the-final-value-of-expression) | 反转表达式值的最少操作次数 | | `栈`,`数学`,`字符串`,`动态规划` | 困难 | | | +| [1897](https://leetcode-cn.com/problems/redistribute-characters-to-make-all-strings-equal) | 重新分配字符使所有字符串都相等 | | `哈希表`,`字符串`,`计数` | 简单 | | | +| [1898](https://leetcode-cn.com/problems/maximum-number-of-removable-characters) | 可移除字符的最大数目 | | `数组`,`字符串`,`二分查找` | 中等 | | | +| [1899](https://leetcode-cn.com/problems/merge-triplets-to-form-target-triplet) | 合并若干三元组以形成目标三元组 | | `贪心`,`数组` | 中等 | | | +| [1900](https://leetcode-cn.com/problems/the-earliest-and-latest-rounds-where-players-compete) | 最佳运动员的比拼回合 | | `记忆化搜索`,`动态规划` | 困难 | | | +| [1901](https://leetcode-cn.com/problems/find-a-peak-element-ii) | 找出顶峰元素 II | | `数组`,`二分查找`,`分治`,`矩阵` | 中等 | | | +| [1902](https://leetcode-cn.com/problems/depth-of-bst-given-insertion-order) | Depth of BST Given Insertion Order | | `树`,`二叉搜索树`,`二叉树`,`有序集合` | 中等 | 🔒 | | +| [1903](https://leetcode-cn.com/problems/largest-odd-number-in-string) | 字符串中的最大奇数 | | `贪心`,`数学`,`字符串` | 简单 | | | +| [1904](https://leetcode-cn.com/problems/the-number-of-full-rounds-you-have-played) | 你完成的完整对局数 | | `数学`,`字符串` | 中等 | | | +| [1905](https://leetcode-cn.com/problems/count-sub-islands) | 统计子岛屿 | | `深度优先搜索`,`广度优先搜索`,`并查集`,`数组`,`矩阵` | 中等 | | | +| [1906](https://leetcode-cn.com/problems/minimum-absolute-difference-queries) | 查询差绝对值的最小值 | | `数组`,`哈希表` | 中等 | | | +| [1907](https://leetcode-cn.com/problems/count-salary-categories) | 按分类统计薪水 | | `数据库` | 中等 | 🔒 | | +| [1908](https://leetcode-cn.com/problems/game-of-nim) | Game of Nim | | `位运算`,`脑筋急转弯`,`数组`,`数学`,`动态规划`,`博弈` | 中等 | 🔒 | | +| [1909](https://leetcode-cn.com/problems/remove-one-element-to-make-the-array-strictly-increasing) | 删除一个元素使数组严格递增 | | `数组` | 简单 | | | +| [1910](https://leetcode-cn.com/problems/remove-all-occurrences-of-a-substring) | 删除一个字符串中所有出现的给定子字符串 | | `字符串` | 中等 | | | +| [1911](https://leetcode-cn.com/problems/maximum-alternating-subsequence-sum) | 最大子序列交替和 | | `数组`,`动态规划` | 中等 | | | +| [1912](https://leetcode-cn.com/problems/design-movie-rental-system) | 设计电影租借系统 | | `设计`,`数组`,`哈希表`,`有序集合`,`堆(优先队列)` | 困难 | | | +| [1913](https://leetcode-cn.com/problems/maximum-product-difference-between-two-pairs) | 两个数对之间的最大乘积差 | | `数组`,`排序` | 简单 | | | +| [1914](https://leetcode-cn.com/problems/cyclically-rotating-a-grid) | 循环轮转矩阵 | | `数组`,`矩阵`,`模拟` | 中等 | | | +| [1915](https://leetcode-cn.com/problems/number-of-wonderful-substrings) | 最美子字符串的数目 | | `位运算`,`哈希表`,`字符串`,`前缀和` | 中等 | | | +| [1916](https://leetcode-cn.com/problems/count-ways-to-build-rooms-in-an-ant-colony) | 统计为蚁群构筑房间的不同顺序 | | `树`,`图`,`拓扑排序`,`数学`,`动态规划`,`组合数学` | 困难 | | | +| [1917](https://leetcode-cn.com/problems/leetcodify-friends-recommendations) | Leetcodify Friends Recommendations | | `数据库` | 困难 | 🔒 | | +| [1918](https://leetcode-cn.com/problems/kth-smallest-subarray-sum) | Kth Smallest Subarray Sum | | `数组`,`二分查找`,`滑动窗口` | 中等 | 🔒 | | +| [1919](https://leetcode-cn.com/problems/leetcodify-similar-friends) | 兴趣相同的朋友 | | | 困难 | 🔒 | | +| [1920](https://leetcode-cn.com/problems/build-array-from-permutation) | 基于排列构建数组 | | `数组`,`模拟` | 简单 | | | +| [1921](https://leetcode-cn.com/problems/eliminate-maximum-number-of-monsters) | 消灭怪物的最大数量 | | `贪心`,`数组`,`排序` | 中等 | | | +| [1922](https://leetcode-cn.com/problems/count-good-numbers) | 统计好数字的数目 | | `递归`,`数学` | 中等 | | | +| [1923](https://leetcode-cn.com/problems/longest-common-subpath) | 最长公共子路径 | | `数组`,`二分查找`,`后缀数组`,`哈希函数`,`滚动哈希` | 困难 | | | +| [1924](https://leetcode-cn.com/problems/erect-the-fence-ii) | Erect the Fence II | | | 困难 | 🔒 | | +| [1925](https://leetcode-cn.com/problems/count-square-sum-triples) | 统计平方和三元组的数目 | | `数学`,`枚举` | 简单 | | | +| [1926](https://leetcode-cn.com/problems/nearest-exit-from-entrance-in-maze) | 迷宫中离入口最近的出口 | | `广度优先搜索`,`数组`,`矩阵` | 中等 | | | +| [1927](https://leetcode-cn.com/problems/sum-game) | 求和游戏 | | `贪心`,`数学`,`博弈` | 中等 | | | +| [1928](https://leetcode-cn.com/problems/minimum-cost-to-reach-destination-in-time) | 规定时间内到达终点的最小花费 | | `图`,`动态规划` | 困难 | | | +| [1929](https://leetcode-cn.com/problems/concatenation-of-array) | 数组串联 | | `数组` | 简单 | | | +| [1930](https://leetcode-cn.com/problems/unique-length-3-palindromic-subsequences) | 长度为 3 的不同回文子序列 | | `哈希表`,`字符串`,`前缀和` | 中等 | | | +| [1931](https://leetcode-cn.com/problems/painting-a-grid-with-three-different-colors) | 用三种不同颜色为网格涂色 | | `动态规划` | 困难 | | | +| [1932](https://leetcode-cn.com/problems/merge-bsts-to-create-single-bst) | 合并多棵二叉搜索树 | | `树`,`深度优先搜索`,`哈希表`,`二分查找`,`二叉树` | 困难 | | | +| [1933](https://leetcode-cn.com/problems/check-if-string-is-decomposable-into-value-equal-substrings) | 判断字符串是否可分解为值均等的子串 | | | 简单 | 🔒 | | +| [1934](https://leetcode-cn.com/problems/confirmation-rate) | Confirmation Rate | | | 中等 | 🔒 | | +| [1935](https://leetcode-cn.com/problems/maximum-number-of-words-you-can-type) | 可以输入的最大单词数 | | `字符串` | 简单 | | | +| [1936](https://leetcode-cn.com/problems/add-minimum-number-of-rungs) | 新增的最少台阶数 | | | 中等 | | | +| [1937](https://leetcode-cn.com/problems/maximum-number-of-points-with-cost) | 扣分后的最大得分 | | | 中等 | | | +| [1938](https://leetcode-cn.com/problems/maximum-genetic-difference-query) | 查询最大基因差 | | | 困难 | | | +| [1939](https://leetcode-cn.com/problems/users-that-actively-request-confirmation-messages) | Users That Actively Request Confirmation Messages | | | 简单 | | | + + diff --git a/posts/leetcode1.md b/posts/leetcode1.md new file mode 100644 index 00000000..fa63d7f7 --- /dev/null +++ b/posts/leetcode1.md @@ -0,0 +1,233 @@ +### [1. 两数之和](https://leetcode-cn.com/problems/two-sum/) + +
      ●  难度: 简单
    + + + +给定一个整数数组 `nums` 和一个整数目标值 `target`,请你在该数组中找出 **和为目标值** *`target`* 的那 **两个** 整数,并返回它们的数组下标。 + +你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 + +你可以按任意顺序返回答案。 + +
    + +**示例 1:** + +``` +输入:nums = [2,7,11,15], target = 9 +输出:[0,1] +解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 +``` + +**示例 2:** + +``` +输入:nums = [3,2,4], target = 6 +输出:[1,2] +``` + +**示例 3:** + +``` +输入:nums = [3,3], target = 6 +输出:[0,1] +``` + + + +**提示:** + +- `2 <= nums.length <= 104` +- `-109 <= nums[i] <= 109` +- `-109 <= target <= 109` +- **只会存在一个有效答案** + +**进阶:** 你可以想出一个时间复杂度小于 O(n2) 的算法吗? + +
    + +### 英文题目: 2 sum (Two sum) + +Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`. +You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. +You can return the answer in any order. + +
    + +**Example 1:** + +**Input:** nums = [2,7,11,15], target = 9 +**Output:** [0,1] + +**Explaination:** Because nums[0] + nums[1] == 9, we return [0, 1]. + + +**Example 2:** +**Input:** nums = [3,2,4], target = 6 +**Output:** [1,2] + + +**Example 3:** +**Input:** nums = [3,3], target = 6 +**Output:** [0,1] + + +  +**Constraints:** + +- `2 <= nums.length <= 103` +- `-109 <= nums[i] <= 109` +- `-109 <= target <= 109` +- **Only one valid answer exists.** + + + +### 分析: + +**方法1**: 暴力法,复杂度O(n^2),会TLE(超时). + +**方法2**: 双指针法, 固定一个, 找另一个. 发现第一次出现`nums[i] + nums[j] == target`就返回结果. + +**方法3**: hashmap查表,在表中找 target - 当前循环变量i对应的那个数。用一个哈希表(C++中用unordered_map, C#中用dictionary, Python中用dict,Java中可以直接用HashMap),存储每个数对应的下标,复杂度O(n); + +**方法4**: 快排 + 双指针 + +
    + +### 方法2 AC代码: + +```cpp +class Solution { +public: + vector twoSum(vector& nums, int target) { + vector res(2); + // 双指针, 先固定一个 + for (int i = 0; i < nums.size(); i++) + { + for (int j = i + 1; j < nums.size(); j++) + { + if (nums[i] + nums[j] == target) + { + res[0] = i; + res[1] = j; + return res; + } + } + } + return res; + } +}; +``` + + +### 方法3 AC代码: +​ +```cpp +class Solution { + public: + vector twoSum(vector &nums, int target) + { + unordered_map dict; + vector result; + for(int i = 0; i < nums.size(); i++) { + dict[nums[i]] = i; // 顺序的map映射: value->index + } + for(int i = 0; i < nums.size(); i++) + { + int query = target - nums[i]; + if(dict.find(query) != dict.end() && dict[query] > i) // dict[query] > i是为了防止重复计算 + { + result.push_back(i); + result.push_back(dict[query]); + break; + } + } + return result; + } +}; +``` + +### 方法3的另一种写法: + +```cpp +class Solution { +public: + vector twoSum(vector &nums, int target) + { + unordered_map dict; + vector res(2,-1), emptyVect; + for(int i=0;iindex + else { + res[1]=i; + res[0]=dict[query]; + return res; + } + } + return emptyVect; + } +}; +``` +​ + +### 方法4 AC代码: + +- 定义一个struct, 存储 index 和 value +- 使用两个指针, l 和 r, l++, r-- + +left自增, right 自减 + + +**注意**: 如果要在一个struct上调用STL中的sort方法,需要先为其定义好 compare 函数。 +​ + +具体代码如下: +```cpp +typedef struct node{ + int index; + int value; + node(){}; + node(int i, int v) : index(i), value(v){} +} Node; + +bool compare(const Node& a, const Node& b){ + return a.value < b.value; +} + +class Solution { +public: + vector twoSum(vector &nums, int target) { + + int len = nums.size(); + assert(len >= 2); + + vector ret(2, 0); // 初始化:ret包含2个值为0的元素 + + vector nums2(len); + for(int i = 0; i < len; i++){ + nums2[i] = Node(i+1, nums[i]); + } + + sort(nums2.begin(), nums2.end(), compare); // 在定义的struct上调用快排,T(n)=O(n*log(n)) + + int l = 0; + int r = len - 1; + while(l < r){ + int sum = nums2[l].value + nums2[r].value; + if(sum == target){ + ret[0] = min(nums2[l].index, nums2[r].index)-1; // 注意,这里需要减去1 + ret[1] = max(nums2[l].index, nums2[r].index)-1; + break; + } else if(sum < target){ + l++; + } else { + r--; + } + } + return ret; // 用两个指针来扫 + } +}; +``` diff --git a/posts/leetcode11.md b/posts/leetcode11.md new file mode 100644 index 00000000..1d291110 --- /dev/null +++ b/posts/leetcode11.md @@ -0,0 +1,107 @@ +### [11. 盛最多水的容器](https://leetcode-cn.com/problems/container-with-most-water/) + +### 英文题: Container with most water + +难度: 中等 + + + +给你 `n` 个非负整数 `a1,a2,...,a``n`,每个数代表坐标中的一个点 `(i, ai)` 。在坐标内画 `n` 条垂直线,垂直线 `i` 的两个端点分别为 `(i, ai)` 和 `(i, 0)` 。找出其中的两条线,使得它们与 `x` 轴共同构成的容器可以容纳最多的水。 + +**说明:** 你不能倾斜容器。 + + + +**示例 1:** + +![img](https://aliyun-lc-upload.oss-cn-hangzhou.aliyuncs.com/aliyun-lc-upload/uploads/2018/07/25/question_11.jpg) + +``` +输入:[1,8,6,2,5,4,8,3,7] +输出:49 +解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 +``` + +**示例 2:** + +``` +输入:height = [1,1] +输出:1 +``` + +**示例 3:** + +``` +输入:height = [4,3,2,1,4] +输出:16 +``` + +**示例 4:** + +``` +输入:height = [1,2,1] +输出:2 +``` + + + +**提示:** + +- `n = height.length` +- `2 <= n <= 3 * 104` +- `0 <= height[i] <= 3 * 104` + + + +### 分析: + +使用双指针(左右对撞型),以打擂台的方式更新值。 + +面积 area = 首尾高度差x水平index之差 = `min(height[left], height[right]) * (right - left)` + +
    + +### 已AC的C++代码: + +```cpp +class Solution { +public: + int maxArea(vector& height) { + int len = height.size(); + int left = 0; + int right = len - 1; + + int maxArea = INT_MIN; + while(left < right) + { + int area = min(height[left], height[right]) * (right - left); + if(area > maxArea) + maxArea = area; + + if(height[left] <= height[right]) + left++; + else right--; + } + return maxArea; + } +}; +``` + + + + + + + + + + + + + + + + + + + diff --git a/posts/leetcode36.md b/posts/leetcode36.md new file mode 100644 index 00000000..2bfc988a --- /dev/null +++ b/posts/leetcode36.md @@ -0,0 +1,280 @@ +## [36. 有效的数独](https://leetcode-cn.com/problems/valid-sudoku/) + +### 英文题目: Valid sudoku + + +难度: 中等 + + +请你判断一个 `9x9` 的数独是否有效。只需要 **根据以下规则** ,验证已经填入的数字是否有效即可。 + +1. 数字 `1-9` 在每一行只能出现一次。 +2. 数字 `1-9` 在每一列只能出现一次。 +3. 数字 `1-9` 在每一个以粗实线分隔的 `3x3` 宫内只能出现一次。(请参考示例图) + +数独部分空格内已填入了数字,空白格用 `'.'` 表示。 + +**注意:** + +- 一个有效的数独(部分已被填充)不一定是可解的。 +- 只需要根据以上规则,验证已经填入的数字是否有效即可。 + + + +**示例 1:** + +![img](https://cdn.jsdelivr.net/gh/dbdgs/dbdgs.github.io/docs/.vuepress/public/img/sudu0.png) + +``` +输入:board = +[["5","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +输出:true +``` + +**示例 2:** + +``` +输入:board = +[["8","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +输出:false +解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。 +``` + + + +**提示:** + +- `board.length == 9` +- `board[i].length == 9` +- `board[i][j]` 是一位数字或者 `'.'` + +
    + +## 分析 + +### 方法1、蛮力直接法 + +使用set, +对于行遍历: 每一行中, isValid: unique的数字数量+'.'的数量 = 9, +对于列遍历:每一列中, isValid: unique的数字数量+'.'的数量 = 9, +对于box遍历:每个3行3列九宫格中,isValid: unique的数字数量+'.'的数量 = 9。 + +
    + +已AC代码: +```cpp +class Solution { +public: + bool isValidSudoku(vector> &board) + { + bool isValid = true; + + // 遍历行 + for (int i = 0; i < 9; i++) + { + set st; + vector rowVec = board[i]; + int dotCount = 0; + for (int k = 0; k < 9; k++) + { + if (rowVec[k] == '.') + { + dotCount++; + } + else + st.insert(rowVec[k]); + } + int uniqueCharCount = st.size(); + if (uniqueCharCount + dotCount != 9) + { + isValid = false; + } + } + + // 遍历列 + for (int i = 0; i < 9; i++) + { + set st; + int dotCount = 0; + for (int k = 0; k < 9; k++) + { + if (board[k][i] == '.') + { + dotCount++; + } + else + st.insert(board[k][i]); + } + int uniqueCharCount = st.size(); + if (uniqueCharCount + dotCount != 9) + { + isValid = false; + } + } + + // 遍历小grid: 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 + for (int si = 0; si <= 6; si += 3) + for (int sj = 0; sj <= 6; sj += 3) + { + set st; + int dotCount = 0; + for (int i = si; i < si + 3; i++) + { + for (int j = sj; j < sj + 3; j++) + { + if (board[i][j] == '.') + dotCount += 1; + else + st.insert(board[i][j]); + } + } + if (st.size() + dotCount != 9) + isValid = false; + } + return isValid; + } +}; +``` + +
    + +跟国外的小伙伴想到一块去了。 + + +
    + + +### 方法2:set插入方法 - 改进 + +坐标中任意一点(i,j),可以map到对应的的第几行第几列的方块(box)中,box的坐标为(i/3, j/3)。 + +于是把一个小的九宫格中的数全压缩到一个box中,比如: + +![是否有插入失败的1](https://cdn.jsdelivr.net/gh/dbdgs/dbdgs.github.io/docs/.vuepress/public/img/sudu1.png) + +
    + +以最中间那个九宫格为例,使用int型的/3可以得到: + +![是否有插入失败的2](https://cdn.jsdelivr.net/gh/dbdgs/dbdgs.github.io/docs/.vuepress/public/img/sudu3.png) + + +对于任意一个值不为'.'的字符,进行如下操作: + +1.把所在row的信息插入到大九宫格中; + +2.把所在column的信息插入到大九宫格中; + +3.把所在的小方块(box)的信息插入到大九宫格中。 + +插入如果失败说明出现了重复。 + + +#### 已AC的C++代码: + +```cpp +class Solution { +public: + bool isValidSudoku(vector>& board) { + set st; + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + char ch = board[i][j]; + // 使用i / 3 + "," + j / 3 得到对应第几行第几列的方块(box) + if (ch != '.'){ + string val; + val.push_back(ch); + /* 对于任意一个值不为'.'的字符 + 1.把所在row的信息插入到大九宫格中; + 2.把所在column的信息插入到大九宫格中; + 3.把所在的小方块(box)的信息插入到大九宫格中。 + 插入如果失败说明出现了重复。 */ + if (!st.insert(val + " in row " + to_string(i)).second || + !st.insert(val + " in column " + to_string(j)).second || + !st.insert(val + " in box " + to_string(i / 3) + "," + to_string(j / 3)).second) + return false; /* set插入失败时,表示出现了重复 */ + } + } + } + return true; + } +}; +``` + +Java的HashSet有同样的写法,Java中插入失败,会出现 `set.Add() == false`。 + + +### 方法3:使用位操作 + +此题,使用位操作,是几种解法中速度最快的算法了。 + +具体做法是: + +![方法3](https://cdn.jsdelivr.net/gh/dbdgs/dbdgs.github.io/docs/.vuepress/public/img/sudu2.png) + +将大数独棋盘分成9个小棋盘,编号0~8。 + +窗口中的每个小方格若有数字,必为 1 ~ 9 (记作k),该方法适用于 遍历行/遍历列/遍历box。 + +然后把 二进制数 1 左移 k 位,得到偏移量shift,后续使用按位或`|`来判断是否存在。 + + +#### 已AC的C++代码: + +```cpp +class Solution { +public: + bool isValidSudoku(vector>& board) { + vector row(9); // row[j]表示第j 行的9个数字各自的存在情况,同理于col, boxes + vector col(9); + vector boxes(9); + + int shiftInt = 0; + for (int i = 0; i < 9; i++) + { + for (int j = 0; j < 9; j++) + { + if (board[i][j] == '.') + continue; + + shiftInt = 1 << (board[i][j] - '0'); // 转为二进制,移位结束后目标位为1,其他位均为0 + /* 每个格子若有数字,必为 1 ~ 9,该方法适用于 遍历行/遍历列/遍历box */ + int boxPos = (i / 3) * 3 + j / 3; //将大数独棋盘分成9个小棋盘,编号0~8 + + // 如果当前数字shiftInt在row[j] 或col[i] 或 boxes中已经存在,&运算后不为0, + // 只有当前数字没出现过,&运算后为0 + if ((col[i] & shiftInt) != 0 || (row[j] & shiftInt) != 0 || (boxes[boxPos] & shiftInt) != 0) + return false; + + //第 n 位代表 n 这个数字是否存在(1→存在, 0→不存在),同理于col[i] boxes[boxPos] + row[j] |= shiftInt; + col[i] |= shiftInt; + boxes[boxPos] |= shiftInt; + } + } + return true; + } +}; +``` + +后两种方法,参考: + + + + diff --git a/posts/leetcode38.md b/posts/leetcode38.md new file mode 100644 index 00000000..83311ca2 --- /dev/null +++ b/posts/leetcode38.md @@ -0,0 +1,218 @@ +## [38. 外观数列](https://leetcode-cn.com/problems/count-and-say/) (报数) + +### 英文题目: Count and Say + +难度: 中等 + +给定一个正整数 `n` ,输出外观数列的第 `n` 项。 + +「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。 + +你可以将其视作是由递归公式定义的数字字符串序列: + +- `countAndSay(1) = "1"` +- `countAndSay(n)` 是对 `countAndSay(n-1)` 的描述,然后转换成另一个数字字符串。 + + + +前五项如下: + +``` +1. 1 +2. 11 +3. 21 +4. 1211 +5. 111221 +第一项是数字 1 +描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11" +描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21" +描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211" +描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221" +``` + +要 **描述** 一个数字字符串,首先要将字符串分割为 **最小** 数量的组,每个组都由连续的最多 **相同字符** 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。 + + + +例如,数字字符串 `"3322251"` 的描述如下图: + +![count and say](https://pic.rmb.bdstatic.com/bjh/8514fdc080a7eb404f6edb5807428395.png) + + +**示例 1:** + +``` +输入:n = 1 +输出:"1" +解释:这是一个基本样例。 +``` + +**示例 2:** + +``` +输入:n = 4 +输出:"1211" +解释: +countAndSay(1) = "1" +countAndSay(2) = 读 "1" = 一 个 1 = "11" +countAndSay(3) = 读 "11" = 二 个 1 = "21" +countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211" +``` + + + +**提示:** + +- `1 <= n <= 30` + + +## 分析: + +本题可使用递归或迭代来解决,下面的几种方法都使用了迭代。 + +
    + +主体思路: 以已知a4=1211, 来求a5为例来说明如何用迭代法实现。 +首先将不同字符间(用虚线)划开进行分片,即 1|2|11,分别统计各个分片中连续相同的字符数即可。 + + +### 方法1 + +本题从f(1)到f(n)需要迭代 n-1 次来解决,每次迭代以上一次的迭代结果作为起点,将该迭代结果res中不同字符间(用虚线)划开进行分片,即 1|2|11。 + +当循环变量从0 -> n-1 且没到末尾的分片时, 每出现新的字符时,把已处理的连续相同字符的信息插入到结果字符串中。而到末尾分片时,需要单独把末尾连续相同字符的信息插入到结果字符串中,因为对末尾一段字符来说,不会再有新的字符了,该数据也需要写入。 + +#### 已AC的C++代码 + +```cpp +class Solution { +public: + string countAndSay(int n) { + if(n == 1) + return "1"; // f(1) = 1 + + string res = "1"; // f(1) = 1, 作为迭代的初始值放入到结果中 + for(int i=0; i 1) { + string curStr = ""; + for (int i = 0; i < res.size(); i++) { + int count = getRepeatCount(res.substr(i)); // 截取从当前字符到末尾的子串 + curStr += to_string(count); + curStr.push_back(res[i]); + + // 跳过重复的字符, 共处理一次即可 + i = i + count - 1; + } + n--; // 总共需要迭代 n-1 次 + + res = curStr; // 将结果用作下一轮循环的初始值 + } + return res; + } + + /* 得到字符串 str 中第一个分片中连续相等数的重复个数,例如: "111221" 返回 3, "2" 返回 1 */ + int getRepeatCount(string str) { + int count = 1; + char same = str[0]; + for (int i = 1; i < str.size(); i++) { + if (same == str[i]) { + count++; + } else { + break; + } + } + return count; + } +}; +``` + + +### 方法3 + +懂了方法1 或 方法2后,也可以用下面的方式完成。 + +#### 已AC的C++代码 + +```cpp +class Solution { +public: + string countAndSay(int n) { + if (n <= 0) return ""; + + string res = "1"; + while (--n) { + string curStr = ""; + for (int i = 0; i < res.size(); ++i) { + int count = 1; // 出现第一个新字符, count置为1 + while (i + 1 < res.size() && res[i] == res[i + 1]) { /* 这里与上1层循环用的是同一个i, 且区间是上层循环的子区间, 故时间复杂度是O(n^2) */ + count++; + i++; + } + curStr += to_string(count) + res[i]; + } + res = curStr; // 将结果用作下一轮循环的初始值 + } + return res; + } +}; +``` + +以上3种方法都是`迭代法`的实现,本题还可以使用递归来做,有兴趣的小伙伴可以试试~ + +
    + +本人公众号 [大白技术控](https://www.ershicimi.com/a/yOzq9w3e), 2万读者。 + +知乎 [Bravo Yeung](https://www.zhihu.com/people/legege007), 4.5万读者。 + +B站 [极客学长呀](https://space.bilibili.com/1443957), 后续会用视频的形式来带大家刷LeetCode题,欢迎点个关注,敬请期待~ + +
    + +更多清晰易懂的代码 (C++/Java/C#/Python/Go) 的 LeetCode 题解,会在我的 github 仓库 中持续更新, 欢迎小伙伴们 star/fork,如果有不错的解法也欢迎提PR。 + +
    + +**ps:** 仓库的代码中可以直接拿来本地调试喔,框架已搭好,根据自己的需求调整 test case即可~ diff --git a/posts/leetcode4.md b/posts/leetcode4.md new file mode 100644 index 00000000..7c06cd09 --- /dev/null +++ b/posts/leetcode4.md @@ -0,0 +1,119 @@ +### [4. 寻找两个正序数组的中位数](https://leetcode-cn.com/problems/median-of-two-sorted-arrays/) + +### 英文题目: Median of two sorted arrays + +
      ●  难度: 困难
    + +给定两个大小分别为 `m` 和 `n` 的正序(从小到大)数组 `nums1` 和 `nums2`。请你找出并返回这两个正序数组的 **中位数** 。 + + + +**示例 1:** + +``` +输入:nums1 = [1,3], nums2 = [2] +输出:2.00000 +解释:合并数组 = [1,2,3] ,中位数 2 +``` + +**示例 2:** + +``` +输入:nums1 = [1,2], nums2 = [3,4] +输出:2.50000 +解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5 +``` + +**示例 3:** + +``` +输入:nums1 = [0,0], nums2 = [0,0] +输出:0.00000 +``` + +**示例 4:** + +``` +输入:nums1 = [], nums2 = [1] +输出:1.00000 +``` + +**示例 5:** + +``` +输入:nums1 = [2], nums2 = [] +输出:2.00000 +``` + + + +**提示:** + +- `nums1.length == m` +- `nums2.length == n` +- `0 <= m <= 1000` +- `0 <= n <= 1000` +- `1 <= m + n <= 2000` +- `-106 <= nums1[i], nums2[i] <= 106` + + +**进阶:**你能设计一个时间复杂度为 `O(log (m+n))` 的算法解决此问题吗? + +
    + +### 思路 +先合并两个有序数组,然后根据数组长度的奇偶来取到中位数。如果是偶数个,就取中间两个的平均数;如果是奇数个,直接取最中间的即可。 + +与 `leetcode 88. 合并两个有序数组` 类似。 + +
    + + +### 已AC的C++代码: +```cpp +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + vector nums; + double res; + int m = nums1.size(); + int n = nums2.size(); + int len; + + int i = 0, j = 0; + while (i < m && j < n) // 只要一个指针扫到数组末尾,循环结束 + { + if(nums1[i] <= nums2[j]) + { + nums.push_back(nums1[i]); + i++; + } + else { + nums.push_back(nums2[j]); + j++; + } + } + + while(i < m) // 数组nums1没跑完,nums2已跑完时 + { + nums.push_back(nums1[i]); + i++; + } + + while(j < n) // 数组nums2没跑完,nums1已跑完时 + { + nums.push_back(nums2[j]); + j++; + } + len = nums.size(); + if(len % 2 == 0) + { + res = (nums[len/2] + nums[len/2-1])/2.0; + } + else res = nums[len/2]; + + return res; + } +}; +``` + diff --git a/pull_request_template.md b/pull_request_template.md new file mode 100644 index 00000000..af39019b --- /dev/null +++ b/pull_request_template.md @@ -0,0 +1,3 @@ +# Pull request template + +**Title**: write the concise behavior of your PR. diff --git a/python3-leetcode/README.md b/python3-leetcode/README.md new file mode 100644 index 00000000..e52a9d0b --- /dev/null +++ b/python3-leetcode/README.md @@ -0,0 +1 @@ +# Leetcode 刷题方法及AC 代码 - Python3 版 diff --git a/python3-leetcode/leetcode009-leetcode9-palindrome-number.py b/python3-leetcode/leetcode009-leetcode9-palindrome-number.py new file mode 100644 index 00000000..df1ba6b8 --- /dev/null +++ b/python3-leetcode/leetcode009-leetcode9-palindrome-number.py @@ -0,0 +1,14 @@ +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + else: + str0 = str(x) + reversedStr = str0[::-1] + if reversedStr == str0: + return True + return False + +# Below is testing +sol = Solution() +print(sol.isPalindrome(616)) \ No newline at end of file diff --git a/python3-leetcode/leetcode013-leetcode13-roman-to-integer.py b/python3-leetcode/leetcode013-leetcode13-roman-to-integer.py new file mode 100644 index 00000000..cd374bc7 --- /dev/null +++ b/python3-leetcode/leetcode013-leetcode13-roman-to-integer.py @@ -0,0 +1,26 @@ +class Solution: + def romanToInt(self, s: str) -> int: + d = dict() + d = { + 'I': 1, + 'V': 5, + 'X': 10, + 'L': 50, + 'C': 100, + 'D': 500, + 'M': 1000 + } + + sum0 = 0 + for i in range(len(s)): + currentValue = d[s[i]] + + if i == len(s) -1 or d[s[i+1]] <= currentValue: # d[s[i+1]]: nextValue + sum0 += d[s[i]] + else: + sum0 -= d[s[i]] + + return sum0 + +sol = Solution() +print(sol.romanToInt("MCMXCIV")) \ No newline at end of file diff --git a/python3-leetcode/leetcode058-leetcode58-length-of-last-word.py b/python3-leetcode/leetcode058-leetcode58-length-of-last-word.py new file mode 100644 index 00000000..3bfe0c1d --- /dev/null +++ b/python3-leetcode/leetcode058-leetcode58-length-of-last-word.py @@ -0,0 +1,11 @@ +class Solution: + def lengthOfLastWord(self, s: str) -> int: + newStr = s.strip() + lastSpacePos = newStr.rfind(' ') + if lastSpacePos == -1: + return len(newStr) + else: + return len(newStr) - lastSpacePos - 1 + +sol = Solution() +print(sol.lengthOfLastWord('Hello my baby')) \ No newline at end of file diff --git a/python3-leetcode/leetcode067-leetcode67-add-binary.py b/python3-leetcode/leetcode067-leetcode67-add-binary.py new file mode 100644 index 00000000..b1f7c43d --- /dev/null +++ b/python3-leetcode/leetcode067-leetcode67-add-binary.py @@ -0,0 +1,10 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + num1 = int(a, 2) + num2 = int(b, 2) + sum0 = num1 + num2 + return format(sum0, 'b') + +# 测试 +sol = Solution() +print(sol.addBinary('11', '1101')) \ No newline at end of file diff --git a/python3-leetcode/leetcode076-leetcode76-minimum-window-substring.py b/python3-leetcode/leetcode076-leetcode76-minimum-window-substring.py new file mode 100644 index 00000000..1e8f6df1 --- /dev/null +++ b/python3-leetcode/leetcode076-leetcode76-minimum-window-substring.py @@ -0,0 +1,48 @@ +class Solution: + def minWindow(self, s: str, t: str) -> str: + """ + Build the counter + """ + d = dict(collections. Counter(t)) + formed = 0 + slow = 0 + min_str = None + min_length = sys.maxsize - 1 + for fast in range(len(s)): + """ + skip if s[fast] doesn't matter + """ + ch = s[fast] + fast += 1 + if ch not in d: + continue + """ + use the ch to update d + """ + d[ch] -= 1 + if d[ch] == 0: + formed += 1 + + """ + If all character are satisfied, then need to move the left pointer + """ + while formed == len(d) and slow <= fast: + """ + save the result + """ + curr_length = fast - slow + if curr_length < min_length: + min_length = curr_length + min_str = s[slow:fast] + + """ + update the left boundary + """ + ch = s[slow] + slow += 1 + if ch not in d: + continue + d[ch] += 1 + if d[ch] == 1: + formed -= 1 + return min_str if min_str is not None else "" \ No newline at end of file diff --git a/python3-leetcode/leetcode089-leetcode89-gray-code.py b/python3-leetcode/leetcode089-leetcode89-gray-code.py new file mode 100644 index 00000000..84cf7475 --- /dev/null +++ b/python3-leetcode/leetcode089-leetcode89-gray-code.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +from typing import List + +class Solution: + def grayCode(self, n: int) -> List[int]: + res = [] + for i in range(1 << n): + res.append((i >> 1) ^ i) + return res + +# Below is testing +obj = Solution() +print(obj.grayCode(2)) \ No newline at end of file diff --git a/python3-leetcode/leetcode136-single-number-method1.py b/python3-leetcode/leetcode136-single-number-method1.py new file mode 100644 index 00000000..362bd4bb --- /dev/null +++ b/python3-leetcode/leetcode136-single-number-method1.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +from typing import List + +class Solution: + def singleNumber(self, nums: List[int]) -> int: + res = 0 + d = dict() + for num in nums: + if num not in d: + d[num] = 1 + else: + d[num] += 1 + res = next(k for k, val in d.items() if val == 1) + return res + +#以下是测试 +sol = Solution() +print(sol.singleNumber([6, 4, 6, 2, 4])) \ No newline at end of file diff --git a/python3-leetcode/leetcode136-single-number-method2.py b/python3-leetcode/leetcode136-single-number-method2.py new file mode 100644 index 00000000..6926fcee --- /dev/null +++ b/python3-leetcode/leetcode136-single-number-method2.py @@ -0,0 +1,12 @@ +from typing import List + +class Solution: + def singleNumber(self, nums: List[int]) -> int: + r = 0 + for i in nums: + r ^= i + return r + +#以下是测试 +sol = Solution() +print(sol.singleNumber([6, 4, 6, 2, 4])) \ No newline at end of file diff --git a/python3-leetcode/leetcode202-happy-number.py b/python3-leetcode/leetcode202-happy-number.py new file mode 100644 index 00000000..ceea1e9e --- /dev/null +++ b/python3-leetcode/leetcode202-happy-number.py @@ -0,0 +1,18 @@ +class Solution: + def isHappy(self, n: int) -> bool: + unhappy = set() + while n not in unhappy and n != 1: + unhappy.add(n) + n = self.GetSquareSum(n) + return n == 1 + + def GetSquareSum(self, n: int) -> bool: + sum0 = 0 + while n > 0: + r = n - int(n/10)*10 + n = int(n/10) + sum0 += r * r + return sum0 + +sol = Solution() +print(sol.isHappy(19)) \ No newline at end of file diff --git a/python3-leetcode/leetcode204-count-primes-method1.py b/python3-leetcode/leetcode204-count-primes-method1.py new file mode 100644 index 00000000..a3eb1ecb --- /dev/null +++ b/python3-leetcode/leetcode204-count-primes-method1.py @@ -0,0 +1,19 @@ +class Solution: + def countPrimes(self, n: int) -> int: + if n < 2: + return 0 + else: + isDelete = [False]*n + max0 = int(math.sqrt(n)) + count = 0 + for i in range(2, n): + if isDelete[i] == True: + continue + count += 1 + + if i > max0: + continue + + for j in range(i*i, n, i): + isDelete[j] = True + return count \ No newline at end of file diff --git a/python3-leetcode/leetcode345-reverse-vowels-of-a-string.py b/python3-leetcode/leetcode345-reverse-vowels-of-a-string.py new file mode 100644 index 00000000..744d2759 --- /dev/null +++ b/python3-leetcode/leetcode345-reverse-vowels-of-a-string.py @@ -0,0 +1,25 @@ +class Solution: + def reverseVowels(self, s: str) -> str: + vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'] + vList = list() + + vCount = 0 + for index in range(len(s)): + if s[index] in vowels: + vList.append(s[index]) + + res_str = '' + vList.reverse() + + vOutCount = 0 + for index in range(len(s)): + if s[index] not in vowels: + res_str += s[index] + else: + res_str += vList[vOutCount] + vOutCount += 1 + + return res_str + +sol = Solution() +print(sol.reverseVowels("hiHeyBaby")) \ No newline at end of file diff --git a/python3-leetcode/leetcode645-set-mismatch.py b/python3-leetcode/leetcode645-set-mismatch.py new file mode 100644 index 00000000..8ab4c94f --- /dev/null +++ b/python3-leetcode/leetcode645-set-mismatch.py @@ -0,0 +1,16 @@ +from typing import List + +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + res = list() + nums.sort() + stdList = range(1, len(nums) + 1) # len(nums) = n + repeatedNum = sum(nums) - sum(set(nums)) + res.append(repeatedNum) + missingNum = (set(stdList) - set(nums)).pop() + res.append(missingNum) + return res + +# below is testing +sol = Solution() +print(sol.findErrorNums([4,2, 1,2])) diff --git a/python3-leetcode/leetcode976-largest-perimeter-triangle.py b/python3-leetcode/leetcode976-largest-perimeter-triangle.py new file mode 100644 index 00000000..3ec4ca32 --- /dev/null +++ b/python3-leetcode/leetcode976-largest-perimeter-triangle.py @@ -0,0 +1,15 @@ +from typing import List +class Solution: + def largestPerimeter(self, A: List[int]) -> int: + if (len(A) < 3): + return 0 + + A.sort(reverse=True) + for i in range(len(A)-2): + if A[i] < A[i+1] + A[i+2]: # Can build a triangle + return A[i] + A[i+1] + A[i+2] + return 0 + +# Below is testing +sol = Solution() +print(sol.largestPerimeter([4, 5, 2, 7])) \ No newline at end of file diff --git a/python3-leetcode/leetcode977-squares-of-a-sorted-array.py b/python3-leetcode/leetcode977-squares-of-a-sorted-array.py new file mode 100644 index 00000000..e4760481 --- /dev/null +++ b/python3-leetcode/leetcode977-squares-of-a-sorted-array.py @@ -0,0 +1,13 @@ +from typing import List + +class Solution: + def sortedSquares(self, A: List[int]) -> List[int]: + B = sorted(A, key = abs) # sort by absolute values + res = list() + for elem in B: + res.append(elem*elem) + return res + +# below is testing +sol = Solution() +print(sol.sortedSquares([-4,-2, 3,6])) \ No newline at end of file diff --git a/sorting 14-PHP/gnuplot.graph b/sorting 14-PHP/gnuplot.graph deleted file mode 100644 index b9d3daf5..00000000 --- a/sorting 14-PHP/gnuplot.graph +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/gnuplot -persist -set terminal png -set xlabel "Размер массива, чисел" -set ylabel "Время сортировки, секунд" -set key top left -set style line 1 lt 1 lw 3 pt 6 -set style line 2 lt 2 lw 3 pt 6 -set style line 3 lt 3 lw 3 pt 6 -set style line 4 lt 4 lw 3 pt 6 -set style line 5 lt 5 lw 3 pt 6 -set style line 6 lt 6 lw 3 pt 6 -set style line 7 lt 7 lw 3 pt 6 -set style line 8 lt 8 lw 3 pt 6 -set style line 9 lt 9 lw 3 pt 6 -set style line 10 lt 1 lw 3 pt 4 -set style line 11 lt 2 lw 3 pt 4 -set style line 12 lt 3 lw 3 pt 4 -set style line 13 lt 4 lw 3 pt 4 -set style line 14 lt 5 lw 3 pt 4 -set style line 15 lt 6 lw 3 pt 4 -set style line 666 lt 8 pt 7 - - -set output "graph0-1000.png" -set xrange [0:1000] -set title "Время сортировки int'ов, не превышаюших размерность массива\nРазмер массива - до 1 тысячи элементов" - -plot "result_sort.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSort.txt" title "countingSort" with linespoints linestyle 8, \ - "result_quickSort.txt" title "quickSort" with linespoints linestyle 2, \ - "result_combSort.txt" title "combSort" with linespoints linestyle 3, \ - "result_heapSort.txt" title "heapSort" with linespoints linestyle 9, \ - "result_mergeSort.txt" title "mergeSort" with linespoints linestyle 4, \ - "result_shellSort.txt" title "shellSort" with linespoints linestyle 5, \ - "result_selectionSort.txt" title "selectionSort" with linespoints linestyle 7, \ - "result_insertSort.txt" title "insertSort" with linespoints linestyle 6, \ - "result_gnomeSort.txt" title "gnomeSort" with linespoints linestyle 10, \ - "result_combinedBubbleSort.txt" title "combinedBubbleSort" with linespoints linestyle 11, \ - "result_cocktailSort.txt" title "cocktailSort" with linespoints linestyle 12, \ - "result_bubbleSort.txt" title "bubbleSort" with linespoints linestyle 13, \ - "result_oddEvenSort.txt" title "oddEvenSort" with linespoints linestyle 14, \ - "result_bubbleSortWithFlag.txt" title "bubbleSortWithFlag" with linespoints linestyle 15 - -set output "graph1000-30000.png" -set xrange [1000:30000] -set title "Время сортировки int'ов, не превышаюших размерность массива\nРазмер массива - до 30 тысяч элементов" - -plot "result_sort.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSort.txt" title "countingSort" with linespoints linestyle 8, \ - "result_quickSort.txt" title "quickSort" with linespoints linestyle 2, \ - "result_combSort.txt" title "combSort" with linespoints linestyle 3, \ - "result_heapSort.txt" title "heapSort" with linespoints linestyle 9, \ - "result_mergeSort.txt" title "mergeSort" with linespoints linestyle 4 - -set output "graph200000.png" -set xrange [0:200000] -set title "Время сортировки int'ов, не превышаюших размерность массива\nРазмер массива - до 200 тысяч элементов" - -plot "result_sort.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSort.txt" title "countingSort" with linespoints linestyle 8, \ - "result_quickSort.txt" title "quickSort" with linespoints linestyle 2, \ - "result_combSort.txt" title "combSort" with linespoints linestyle 3, \ - "result_heapSort.txt" title "heapSort" with linespoints linestyle 9, \ - "result_mergeSort.txt" title "mergeSort" with linespoints linestyle 4 - -set output "graph2000000.png" -set xrange [0:2000000] -set title "Время сортировки int'ов, не превышаюших размерность массива\nРазмер массива - до 2 миллионов элементов" - -plot "result_sort.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSort.txt" title "countingSort" with linespoints linestyle 8, \ - "result_quickSort.txt" title "quickSort" with linespoints linestyle 2 - - - -set output "big_graph0-1000.png" -set xrange [0:1000] -set title "Время сортировки int'ов вплоть до максимально возможного значения\nРазмер массива - до 1 тысячи элементов" - -plot "result_sortbig.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSortbig.txt" title "countingSort - fail" with linespoints linestyle 666, \ - "result_quickSortbig.txt" title "quickSort" with linespoints linestyle 2, \ - "result_combSortbig.txt" title "combSort" with linespoints linestyle 3, \ - "result_heapSortbig.txt" title "heapSort" with linespoints linestyle 9, \ - "result_mergeSortbig.txt" title "mergeSort" with linespoints linestyle 4, \ - "result_shellSortbig.txt" title "shellSort" with linespoints linestyle 5, \ - "result_selectionSortbig.txt" title "selectionSort" with linespoints linestyle 7, \ - "result_insertSortbig.txt" title "insertSort" with linespoints linestyle 6, \ - "result_gnomeSortbig.txt" title "gnomeSort" with linespoints linestyle 10, \ - "result_combinedBubbleSortbig.txt" title "combinedBubbleSort" with linespoints linestyle 11, \ - "result_cocktailSortbig.txt" title "cocktailSort" with linespoints linestyle 12, \ - "result_bubbleSortbig.txt" title "bubbleSort" with linespoints linestyle 13, \ - "result_oddEvenSortbig.txt" title "oddEvenSort" with linespoints linestyle 14, \ - "result_bubbleSortWithFlagbig.txt" title "bubbleSortWithFlag" with linespoints linestyle 15 - -set output "big_graph1000-30000.png" -set xrange [1000:30000] -set title "Время сортировки int'ов вплоть до максимально возможного значения\nРазмер массива - до 30 тысяч элементов" - -plot "result_sortbig.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSortbig.txt" title "countingSort - fail" with linespoints linestyle 666, \ - "result_quickSortbig.txt" title "quickSort" with linespoints linestyle 2, \ - "result_combSortbig.txt" title "combSort" with linespoints linestyle 3, \ - "result_heapSortbig.txt" title "heapSort" with linespoints linestyle 9, \ - "result_mergeSortbig.txt" title "mergeSort" with linespoints linestyle 4 - -set output "big_graph200000.png" -set xrange [0:200000] -set title "Время сортировки int'ов вплоть до максимально возможного значения\nРазмер массива - до 200 тысяч элементов" - -plot "result_sortbig.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSortbig.txt" title "countingSort - fail" with linespoints linestyle 666, \ - "result_quickSortbig.txt" title "quickSort" with linespoints linestyle 2, \ - "result_combSortbig.txt" title "combSort" with linespoints linestyle 3, \ - "result_heapSortbig.txt" title "heapSort" with linespoints linestyle 9, \ - "result_mergeSortbig.txt" title "mergeSort" with linespoints linestyle 4 - -set output "big_graph2000000.png" -set xrange [0:2000000] -set title "Время сортировки int'ов вплоть до максимально возможного значения\nРазмер массива - до 2 миллионов элементов" - -plot "result_sortbig.txt" title "sort (native)" with linespoints linestyle 1, \ - "result_countingSortbig.txt" title "countingSort - fail" with linespoints linestyle 666, \ - "result_quickSortbig.txt" title "quickSort" with linespoints linestyle 2 diff --git a/sorting 14-PHP/result_bubbleSort.txt b/sorting 14-PHP/result_bubbleSort.txt deleted file mode 100644 index c7dc29a2..00000000 --- a/sorting 14-PHP/result_bubbleSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000008 -100 0.003816 -200 0.014863 -400 0.061536 -600 0.135463 -800 0.237562 -1000 0.369104 diff --git a/sorting 14-PHP/result_bubbleSortWithFlag.txt b/sorting 14-PHP/result_bubbleSortWithFlag.txt deleted file mode 100644 index 56c6ad10..00000000 --- a/sorting 14-PHP/result_bubbleSortWithFlag.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000008 -100 0.004142 -200 0.016407 -400 0.065648 -600 0.142573 -800 0.255842 -1000 0.394800 diff --git a/sorting 14-PHP/result_bubbleSortWithFlagbig.txt b/sorting 14-PHP/result_bubbleSortWithFlagbig.txt deleted file mode 100644 index 4d0fc6d1..00000000 --- a/sorting 14-PHP/result_bubbleSortWithFlagbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000012 -100 0.004172 -200 0.016420 -400 0.063860 -600 0.146209 -800 0.259958 -1000 0.413176 diff --git a/sorting 14-PHP/result_bubbleSortbig.txt b/sorting 14-PHP/result_bubbleSortbig.txt deleted file mode 100644 index b4ccc1cb..00000000 --- a/sorting 14-PHP/result_bubbleSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000012 -100 0.004154 -200 0.016635 -400 0.064875 -600 0.145661 -800 0.262456 -1000 0.403347 diff --git a/sorting 14-PHP/result_cocktailSort.txt b/sorting 14-PHP/result_cocktailSort.txt deleted file mode 100644 index 57860619..00000000 --- a/sorting 14-PHP/result_cocktailSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000010 -100 0.003570 -200 0.014315 -400 0.057345 -600 0.126576 -800 0.226548 -1000 0.359726 diff --git a/sorting 14-PHP/result_cocktailSortbig.txt b/sorting 14-PHP/result_cocktailSortbig.txt deleted file mode 100644 index d62b965f..00000000 --- a/sorting 14-PHP/result_cocktailSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000011 -100 0.003666 -200 0.014302 -400 0.057372 -600 0.126309 -800 0.224978 -1000 0.348229 diff --git a/sorting 14-PHP/result_combSort.txt b/sorting 14-PHP/result_combSort.txt deleted file mode 100644 index 26141c67..00000000 --- a/sorting 14-PHP/result_combSort.txt +++ /dev/null @@ -1,17 +0,0 @@ -1 0.000014 -100 0.000913 -200 0.002118 -400 0.004438 -600 0.007358 -800 0.010546 -1000 0.013320 -5000 0.088933 -10000 0.208863 -15000 0.356441 -20000 0.523417 -25000 0.687661 -30000 0.842685 -40000 1.185906 -50000 1.531888 -100000 3.349796 -200000 7.202026 diff --git a/sorting 14-PHP/result_combSortbig.txt b/sorting 14-PHP/result_combSortbig.txt deleted file mode 100644 index 3d026267..00000000 --- a/sorting 14-PHP/result_combSortbig.txt +++ /dev/null @@ -1,17 +0,0 @@ -1 0.000008 -100 0.000756 -200 0.001919 -400 0.004181 -600 0.007092 -800 0.010347 -1000 0.013590 -5000 0.091078 -10000 0.221508 -15000 0.382653 -20000 0.533014 -25000 0.701544 -30000 0.866291 -40000 1.216402 -50000 1.559452 -100000 3.613463 -200000 7.439258 diff --git a/sorting 14-PHP/result_combinedBubbleSort.txt b/sorting 14-PHP/result_combinedBubbleSort.txt deleted file mode 100644 index b6fcbad9..00000000 --- a/sorting 14-PHP/result_combinedBubbleSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000009 -100 0.003039 -200 0.011632 -400 0.046245 -600 0.104461 -800 0.183662 -1000 0.285671 diff --git a/sorting 14-PHP/result_combinedBubbleSortbig.txt b/sorting 14-PHP/result_combinedBubbleSortbig.txt deleted file mode 100644 index 08acfb20..00000000 --- a/sorting 14-PHP/result_combinedBubbleSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000007 -100 0.002925 -200 0.011560 -400 0.046190 -600 0.102375 -800 0.181870 -1000 0.283335 diff --git a/sorting 14-PHP/result_countingSort.txt b/sorting 14-PHP/result_countingSort.txt deleted file mode 100644 index 29ebbfb7..00000000 --- a/sorting 14-PHP/result_countingSort.txt +++ /dev/null @@ -1,21 +0,0 @@ -1 0.000024 -100 0.000213 -200 0.000353 -400 0.000721 -600 0.001018 -800 0.001389 -1000 0.001689 -5000 0.011301 -10000 0.021289 -15000 0.032652 -20000 0.045483 -25000 0.056114 -30000 0.065536 -40000 0.089884 -50000 0.109705 -100000 0.222924 -200000 0.452024 -300000 0.681795 -500000 1.126496 -1000000 2.322539 -2000000 4.745404 diff --git a/sorting 14-PHP/result_countingSortbig.txt b/sorting 14-PHP/result_countingSortbig.txt deleted file mode 100644 index 4a3b60a2..00000000 --- a/sorting 14-PHP/result_countingSortbig.txt +++ /dev/null @@ -1 +0,0 @@ -0 0 \ No newline at end of file diff --git a/sorting 14-PHP/result_gnomeSort.txt b/sorting 14-PHP/result_gnomeSort.txt deleted file mode 100644 index 6776c245..00000000 --- a/sorting 14-PHP/result_gnomeSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000007 -100 0.002929 -200 0.010533 -400 0.042923 -600 0.095522 -800 0.171180 -1000 0.260513 diff --git a/sorting 14-PHP/result_gnomeSortbig.txt b/sorting 14-PHP/result_gnomeSortbig.txt deleted file mode 100644 index 66b4341a..00000000 --- a/sorting 14-PHP/result_gnomeSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000010 -100 0.002911 -200 0.011322 -400 0.045024 -600 0.104108 -800 0.177914 -1000 0.278019 diff --git a/sorting 14-PHP/result_heapSort.txt b/sorting 14-PHP/result_heapSort.txt deleted file mode 100644 index 3069686e..00000000 --- a/sorting 14-PHP/result_heapSort.txt +++ /dev/null @@ -1,17 +0,0 @@ -1 0.000019 -100 0.001532 -200 0.002976 -400 0.006762 -600 0.010898 -800 0.014725 -1000 0.019042 -5000 0.112170 -10000 0.245967 -15000 0.383814 -20000 0.535770 -25000 0.679672 -30000 0.832588 -40000 1.142799 -50000 1.467391 -100000 3.149066 -200000 6.737085 diff --git a/sorting 14-PHP/result_heapSortbig.txt b/sorting 14-PHP/result_heapSortbig.txt deleted file mode 100644 index f9d2fdcd..00000000 --- a/sorting 14-PHP/result_heapSortbig.txt +++ /dev/null @@ -1,17 +0,0 @@ -1 0.000020 -100 0.001355 -200 0.003117 -400 0.006671 -600 0.010737 -800 0.014726 -1000 0.019091 -5000 0.114365 -10000 0.246101 -15000 0.393934 -20000 0.533065 -25000 0.688747 -30000 0.856102 -40000 1.147781 -50000 1.478132 -100000 3.163812 -200000 6.934217 diff --git a/sorting 14-PHP/result_insertSort.txt b/sorting 14-PHP/result_insertSort.txt deleted file mode 100644 index 4d9c5d7a..00000000 --- a/sorting 14-PHP/result_insertSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000009 -100 0.002612 -200 0.010445 -400 0.042636 -600 0.094321 -800 0.168513 -1000 0.262699 diff --git a/sorting 14-PHP/result_insertSortbig.txt b/sorting 14-PHP/result_insertSortbig.txt deleted file mode 100644 index fbb29538..00000000 --- a/sorting 14-PHP/result_insertSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000008 -100 0.002582 -200 0.010050 -400 0.040779 -600 0.090098 -800 0.161146 -1000 0.247832 diff --git a/sorting 14-PHP/result_mergeSort.txt b/sorting 14-PHP/result_mergeSort.txt deleted file mode 100644 index 41c90a29..00000000 --- a/sorting 14-PHP/result_mergeSort.txt +++ /dev/null @@ -1,17 +0,0 @@ -1 0.000010 -100 0.001949 -200 0.003841 -400 0.008472 -600 0.013236 -800 0.018944 -1000 0.023178 -5000 0.125271 -10000 0.268598 -15000 0.414421 -20000 0.574107 -25000 0.735394 -30000 0.898466 -40000 1.279142 -50000 1.674868 -100000 3.504640 -200000 7.384443 diff --git a/sorting 14-PHP/result_mergeSortbig.txt b/sorting 14-PHP/result_mergeSortbig.txt deleted file mode 100644 index 36a31ae8..00000000 --- a/sorting 14-PHP/result_mergeSortbig.txt +++ /dev/null @@ -1,17 +0,0 @@ -1 0.000015 -100 0.002247 -200 0.003881 -400 0.008614 -600 0.013109 -800 0.018944 -1000 0.025351 -5000 0.125995 -10000 0.275753 -15000 0.411807 -20000 0.570253 -25000 0.730240 -30000 0.890999 -40000 1.269316 -50000 1.660547 -100000 3.480213 -200000 7.290968 diff --git a/sorting 14-PHP/result_oddEvenSort.txt b/sorting 14-PHP/result_oddEvenSort.txt deleted file mode 100644 index 8abe4161..00000000 --- a/sorting 14-PHP/result_oddEvenSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000010 -100 0.003967 -200 0.017262 -400 0.063205 -600 0.139731 -800 0.253171 -1000 0.389973 diff --git a/sorting 14-PHP/result_oddEvenSortbig.txt b/sorting 14-PHP/result_oddEvenSortbig.txt deleted file mode 100644 index 4a921e37..00000000 --- a/sorting 14-PHP/result_oddEvenSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000010 -100 0.003831 -200 0.015046 -400 0.061607 -600 0.140885 -800 0.243981 -1000 0.390715 diff --git a/sorting 14-PHP/result_quickSort.txt b/sorting 14-PHP/result_quickSort.txt deleted file mode 100644 index 81c3d7c4..00000000 --- a/sorting 14-PHP/result_quickSort.txt +++ /dev/null @@ -1,21 +0,0 @@ -1 0.003451 -100 0.000913 -200 0.001962 -400 0.004234 -600 0.006968 -800 0.009329 -1000 0.011652 -5000 0.051169 -10000 0.090892 -15000 0.138479 -20000 0.190838 -25000 0.246133 -30000 0.301558 -40000 0.414183 -50000 0.529592 -100000 1.115839 -200000 2.382208 -300000 3.748483 -500000 6.499192 -1000000 13.884851 -2000000 29.593196 diff --git a/sorting 14-PHP/result_quickSortbig.txt b/sorting 14-PHP/result_quickSortbig.txt deleted file mode 100644 index c0c7cca3..00000000 --- a/sorting 14-PHP/result_quickSortbig.txt +++ /dev/null @@ -1,21 +0,0 @@ -1 0.000013 -100 0.000671 -200 0.001297 -400 0.002860 -600 0.004443 -800 0.005916 -1000 0.007885 -5000 0.044832 -10000 0.097366 -15000 0.152782 -20000 0.212167 -25000 0.275616 -30000 0.344688 -40000 0.475761 -50000 0.585204 -100000 1.222421 -200000 2.659175 -300000 4.128098 -500000 7.161415 -1000000 15.281192 -2000000 32.682795 diff --git a/sorting 14-PHP/result_selectionSort.txt b/sorting 14-PHP/result_selectionSort.txt deleted file mode 100644 index 181e7a1c..00000000 --- a/sorting 14-PHP/result_selectionSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000014 -100 0.002021 -200 0.007180 -400 0.029290 -600 0.063076 -800 0.110643 -1000 0.174500 diff --git a/sorting 14-PHP/result_selectionSortbig.txt b/sorting 14-PHP/result_selectionSortbig.txt deleted file mode 100644 index c3b3e106..00000000 --- a/sorting 14-PHP/result_selectionSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000013 -100 0.001944 -200 0.007066 -400 0.028126 -600 0.063487 -800 0.112926 -1000 0.173721 diff --git a/sorting 14-PHP/result_shellSort.txt b/sorting 14-PHP/result_shellSort.txt deleted file mode 100644 index f4919784..00000000 --- a/sorting 14-PHP/result_shellSort.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000011 -100 0.000906 -200 0.003064 -400 0.009345 -600 0.017498 -800 0.032947 -1000 0.044074 diff --git a/sorting 14-PHP/result_shellSortbig.txt b/sorting 14-PHP/result_shellSortbig.txt deleted file mode 100644 index 7694f9be..00000000 --- a/sorting 14-PHP/result_shellSortbig.txt +++ /dev/null @@ -1,7 +0,0 @@ -1 0.000011 -100 0.001165 -200 0.002936 -400 0.010112 -600 0.019007 -800 0.035845 -1000 0.049137 diff --git a/sorting 14-PHP/result_sort.txt b/sorting 14-PHP/result_sort.txt deleted file mode 100644 index 1c7e6c44..00000000 --- a/sorting 14-PHP/result_sort.txt +++ /dev/null @@ -1,21 +0,0 @@ -1 0.000006 -100 0.000033 -200 0.000071 -400 0.000158 -600 0.000253 -800 0.000354 -1000 0.000515 -5000 0.003704 -10000 0.008930 -15000 0.012613 -20000 0.017607 -25000 0.024281 -30000 0.031112 -40000 0.046971 -50000 0.059144 -100000 0.127831 -200000 0.286880 -300000 0.491236 -500000 0.889442 -1000000 2.031517 -2000000 4.614716 diff --git a/sorting 14-PHP/result_sortbig.txt b/sorting 14-PHP/result_sortbig.txt deleted file mode 100644 index b77a37dc..00000000 --- a/sorting 14-PHP/result_sortbig.txt +++ /dev/null @@ -1,21 +0,0 @@ -1 0.000004 -100 0.000022 -200 0.000048 -400 0.000144 -600 0.000189 -800 0.000254 -1000 0.000335 -5000 0.002390 -10000 0.005633 -15000 0.010903 -20000 0.015356 -25000 0.023451 -30000 0.033750 -40000 0.043521 -50000 0.057527 -100000 0.124826 -200000 0.292951 -300000 0.490067 -500000 0.863034 -1000000 1.971014 -2000000 4.587246 diff --git a/sorting 14-PHP/sort.php b/sorting 14-PHP/sort.php deleted file mode 100644 index d887f5f8..00000000 --- a/sorting 14-PHP/sort.php +++ /dev/null @@ -1,498 +0,0 @@ -"); - define('T', " "); -} -error_reporting(E_ALL); - -/* -Available algorithms: - <= 0.010 (when size is 8000) - - sort (native) - - <= 0.100 (when size is 8000) - - countingSort - - quickSort - - <= 0.200 (when size is 8000) - - combSort - - heapSort - - <= 1.000 (when size is 8000) - - mergeSort - - <= 10.000 (when size is 8000) - - shellSort - - <= 20.000 (when size is 8000) - - selectionSort - - insertSort - - gnomeSort - - combinedBubbleSort - - <= 30.000 (when size is 8000) - - cocktailSort - - bubbleSort - - oddEvenSort - - bubbleSortWithFlag -*/ - - -// runTests(array('countingSort', 'heapSort', 'shellSort', 'insertSort', 'selectionSort', 'combSort', 'quickSort', 'mergeSort', 'gnomeSort', 'cocktailSort', 'oddEvenSort', 'bubbleSort', 'bubbleSortWithFlag', 'combinedBubbleSort'/*, 'stupidSort'*/), 8000, 2); - // runTests(array('heapSort', 'countingSort'), 10000); - - if (in_array('--bigInt', $argv)) { - define('BIGINT', true); - } else { - define('BIGINT', false); - - } - -$sizes = array(1, 100, 200, 400, 600, 800, 1000, 5000, 10000, 15000, 20000, 25000, 30000); -if (isset($argv[2]) && $argv[2] == 'extra') { - $sizes = array_merge($sizes, array(40000, 50000, 100000, 200000)); - if (isset($argv[3]) && $argv[3] == 'super') { - $sizes = array_merge($sizes, array(300000, 500000, 1000000, 2000000)); - } -} else if (isset($argv[2]) && $argv[2] == 'micro') { - $sizes = array(1, 100, 200, 400, 600, 800, 1000); -} -if (isset($argv[1])) { - echo "Benchmarking ".$argv[1].EOL; - batchTest(array($argv[1]), $sizes, 3); -} else { - batchTest(array('quickSort', 'combSort', 'mergeSort', 'shellSort'), $sizes, 3); -} -// batchTest(array('insertSort', 'selectionSort'), $sizes, 3); - -function countingSort(&$a) { - $k = max($a); - $c = array(); - $n = count($a); - for ($i = 0; $i <= $k; $i++) - $c[$i] = 0; - for ($i = 0;$i < $n; $i++) { - $c[$a[$i]]++; - } - $b = 0; - for ($j = 0;$j <= $k; $j++) { - for ($i = 0; $i < $c[$j]; $i++) { - $a[$b] = $j; - $b++; - } - } -} - -function heapSort(&$a) { - $n = count($a); - heapMake($a); - while ($n > 0) { - list($a[0], $a[$n - 1]) = array($a[$n - 1], $a[0]); - $n--; - heapify($a, 0, $n); - } -} - -function heapMake(&$a) { - $n = count($a); - for ($i = ($n - 1); $i >= 0; $i--) { - heapify($a, $i, $n); - } -} - -function heapify(&$a, $pos, $n) { - while (2 * $pos + 1 < $n) { - $t = 2 * $pos +1; - if (2 * $pos + 2 < $n && $a[2 * $pos + 2] >= $a[$t]) { - $t = 2 * $pos + 2; - } - if ($a[$pos] < $a[$t]) { - list($a[$pos], $a[$t]) = array($a[$t], $a[$pos]); - $pos = $t; - } - else break; - } -} - -function batchTest(array $functions, $sizes, $testSize = 1) { - $times = array(); - $files = array(); - foreach ($functions as $f) { - $files[$f] = fopen('result_'.$f.(BIGINT ? 'big' : null).'.txt', 'w'); - foreach ($sizes as $s) - $times[$f][$s] = 0; - } - - foreach ($sizes as $arraySize) { - echo 'Start '.$arraySize; - for ($i = 0; $i < $testSize; $i ++) { - $a = fillArray($arraySize, BIGINT); - $expected = $a; - sort($expected); - foreach ($functions as $function) { - echo '.'; - $array = $a; - $time = testAlgorithm($function, $array); - $times[$function][$arraySize] += $time; - if ($array != $expected) { - echo $function." is wrong".EOL; - if ($batchSize <= 10) { - echo "expected: "; - printArray($expected); - echo "actual: "; - printArray($array); - } - } - } - } - - foreach ($files as $function => $res) { - fwrite($res, $arraySize."\t".sprintf("%f", $times[$function][$arraySize] / $testSize).PHP_EOL); - } - echo 'done'.EOL; - } - - foreach ($files as $res) { - fclose($res); - } - - // foreach ($times as $f => $times) { - // echo $f.EOL; - // echo "arraySize".T."time".EOL; - // if (file_exists($f.'.txt')) unlink($f.'.txt'); - // foreach ($times as $arraySize => $time) { - // echo $arraySize.T.sprintf("%f", $time / $testSize).EOL; - // file_put_contents($f.'.txt', $arraySize.T.sprintf("%f", $time / $testSize).PHP_EOL, FILE_APPEND); - // } - // } -} - -// runTests(array('shellSort'), 10000); - -function shellSort(&$a) { - $n = count($a); - $d = floor($n / 2); - while ($d > 0) { - for ($i = 0; $i < ($n - $d); $i++) { - $j = $i; - while ($j >= 0 && $a[$j] > $a[$j + $d]) { - list($a[$j], $a[$j + $d]) = array($a[$j + $d], $a[$j]); - $j--; - } - } - $d = floor($d / 2); - } -} - -function insertSort(&$a) { - $n = count($a); - for ($i = 0; $i < ($n - 1); $i++) { - $key = $i + 1; - $tmp = $a[$key]; - for ($j = ($i + 1); $j > 0; $j--) { - if ($tmp < $a[$j - 1]) { - $a[$j] = $a[$j - 1]; - $key = $j - 1; - } - } - $a[$key] = $tmp; - } -} - -function selectionSort(&$a) { - $n = count($a); - for ($i = 0; $i < ($n - 1); $i++) { - $key = $i; - for ($j = ($i + 1); $j < $n; $j++) { - if ($a[$j] < $a[$key]) $key = $j; - } - if ($key != $i) { - list($a[$key], $a[$i]) = array($a[$i], $a[$key]); - } - } -} - -function mergeSort(&$a, $first = 0, $last = null) { - if (is_null($last)) $last = count($a) - 1; - $function = __FUNCTION__; - if ($first < $last) { - $function($a, $first, floor(($first + $last) / 2)); - $function($a, floor(($first + $last) / 2) + 1, $last); - - $tmp = array(); - - $middle = floor(($first + $last) / 2); - $start = $first; - $final = $middle + 1; - for ($i = $first; $i <= $last; $i++) { - if (($start <= $middle) && (($final > $last) || ($a[$start] < $a[$final]))) { - $tmp[$i] = $a[$start]; - $start++; - } else { - $tmp[$i] = $a[$final]; - $final++; - } - } - - for ($i = $first; $i <= $last; $i++) { - $a[$i] = $tmp[$i]; - } - } -} - -function quickSort(&$a, $l = 0, $r = 0) { - if($r == 0) $r = count($a)-1; - $i = $l; - $j = $r; - $x = $a[($l + $r) / 2]; - do { - while ($a[$i] < $x) $i++; - while ($a[$j] > $x) $j--; - if ($i <= $j) { - if ($a[$i] > $a[$j]) - list($a[$i], $a[$j]) = array($a[$j], $a[$i]); - $i++; - $j--; - } - } while ($i <= $j); - $function = __FUNCTION__; - if ($i < $r) $function($a, $i, $r); - if ($j > $l) $function($a, $l, $j); -} - -function gnomeSort(&$a) { - $n = count($a); - $i = 1; - $j = 2; - while ($i < $n) { - if ($a[$i - 1] < $a[$i]) { - $i = $j; - $j++; - } else { - list($a[$i], $a[$i - 1]) = array($a[$i - 1], $a[$i]); - $i--; - if ($i == 0) { - $i = $j; - $j++; - } - } - } -} - -function oddEvenSort(&$a) { - $n = count($a); - $sorted = false; - while (!$sorted) { - $sorted = true; - for ($i = 1; $i < ($n - 1); $i += 2) { - if ($a[$i] > $a[$i + 1]) { - //echo "Swap "; - list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]); - //printArray($a, array($i, $i + 1), 'blue'); - if ($sorted) $sorted = false; - } - } - - for ($i = 0; $i < ($n - 1); $i += 2) { - if ($a[$i] > $a[$i + 1]) { - //echo "Swap "; - list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]); - //printArray($a, array($i, $i + 1), 'blue'); - if ($sorted) $sorted = false; - } - } - } -} - -function combSort(&$a) { - $gap = $n = count($a); - $swapped = true; - while ($gap > 1 || $swapped) { - if ($gap > 1) $gap = floor($gap / 1.24733); - $i = 0; - $swapped = false; - while ($i + $gap < $n) { - if ($a[$i] > $a[$i + $gap]) { - list($a[$i], $a[$i + $gap]) = array($a[$i + $gap], $a[$i]); - if (!$swapped) $swapped = true; - } - $i++; - } - } -} - -function fakeSort(&$a) {} - - -function cocktailSort(&$a) { - $n = count($a); - $left = 0; - $right = $n - 1; - do { - //echo "# Left: ".$left." Right: ".$right.EOL; - for ($i = $left; $i < $right; $i++) { - //echo "Comparation: "; - //printArray($a, array($i, $i + 1)); - if ($a[$i] > $a[$i + 1]) { - //echo "Swap "; - list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]); - //printArray($a, array($i, $i + 1), 'blue'); - } - } - $right -= 1; - for ($i = $right; $i > $left; $i--) { - //echo "Comparation: "; - //printArray($a, array($i, $i - 1)); - if ($a[$i] < $a[$i - 1]) { - //echo "Swap "; - list($a[$i], $a[$i - 1]) = array($a[$i - 1], $a[$i]); - //printArray($a, array($i, $i - 1), 'blue'); - } - } - $left += 1; - } while ($left <= $right); -} - -function runTests($functions, $arraySize = 100, $batchSize = 1) { - $times = array('sort' => 0); - foreach ($functions as $f) $times[$f] = 0; - - for ($i = 0; $i < $batchSize; $i ++) { - echo "Iteration #".$i.EOL; - $a = fillArray($arraySize); - $expected = $a; - // sort($expected); - $times['sort'] += testAlgorithm('sort', $expected); - foreach ($functions as $function) { - $array = $a; - $time = testAlgorithm($function, $array); - echo "+".$time.EOL; - $times[$function] += $time; - if ($array != $expected) { - echo $function." is wrong".EOL; - if ($batchSize <= 10) { - echo "expected: "; - printArray($expected); - echo "actual: "; - printArray($array); - } - } - } - } - - asort($times); - foreach ($times as $function => $time) { - echo "time ".$function."(x".$batchSize.")".T.round($times[$function] / $batchSize, 3).T.round($times[$function], 3).EOL; - } - - echo "Total time".T.T.round(array_sum($times), 3).EOL; - //echo "Average time: ".round($times / $batchSize, 3).EOL; -} -function testAlgorithm($function, &$a) { - $st = microtime(true); - //call_user_func($function, $a); - $function($a); - $en = microtime(true) - $st; - return $en; -} -function fillArray($s, $isBigInt = false) { - $limit = $s; - if ($isBigInt) { - $limit = PHP_INT_MAX; - } - $a = array(); - for ($i=0; $i<$s;$i++) { - $a[] = rand(1, $limit); - } - return $a; -} -function printArray($a, $keys = null, $color = 'red') { - if (!is_null($keys)) foreach ($keys as $k) $a[$k] = "".$a[$k].""; - echo '['; - echo implode(', ', $a); - echo ']'.EOL; -} - -function bubbleSort(&$a) { - $n = count($a); - // bubble sorting - for ($j = 0; $j < ($n - 1); $j++) { - //echo "Iteration #".$j.EOL; - for ($i = 0; $i < ($n - $j - 1); $i++) { - //echo T.'#'.$i.T.'v'.$a[$i].EOL; - //echo "Comparation: "; - //printArray($a, array($i, $i + 1)); - if ($a[$i] > $a[$i + 1]) { - //echo "Swap: "; - list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]); - //printArray($a, array($i, $i + 1), 'blue'); - } - } - } -} - -function bubbleSortWithFlag(&$a) { - $n = count($a); - // bubble sorting - for ($j = 0; $j < ($n - 1); $j++) { - //echo "Iteration #".$j.EOL; - $flag = false; - for ($i = 0; $i < ($n - $j - 1); $i++) { - //echo T.'#'.$i.T.'v'.$a[$i].EOL; - //echo "Comparation: "; - //printArray($a, array($i, $i + 1)); - if ($a[$i] > $a[$i + 1]) { - //echo "Swap: "; - list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]); - //printArray($a, array($i, $i + 1), 'blue'); - if (!$flag) $flag = true; - } - } - if (!$flag) break; - } -} - -function combinedBubbleSort(&$a) { - $n = count($a); - // bubble sorting - for ($j = 0; $j < ($n - 1); $j++) { - //echo "Iteration #".$j.EOL; - $flag = false; - $min = $j; - for ($i = $j; $i < ($n - $j - 1); $i++) { - //echo T.'#'.$i.T.'v'.$a[$i].EOL; - //echo "Comparation: "; - //printArray($a, array($i, $i + 1)); - if ($a[$i] > $a[$i + 1]) { - //echo "Swap: "; - list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]); - //printArray($a, array($i, $i + 1), 'blue'); - if (!$flag) $flag = true; - } - if ($a[$i] < $a[$min]) $min = $i; - } - if (!$flag) break; - if ($min != $j) { - //echo "Swap: "; - list($a[$min], $a[$j]) = array($a[$j], $a[$min]); - //printArray($a, array($min, $j), 'yellow'); - } - } -} - -function stupidSort(&$a) { - $n = count($a); - for ($i = 1; $i < $n; $i ++) { - //echo "Iteration #".$i.EOL; - if ($a[$i] < $a[$i - 1]) { - //echo "Swap :"; - list($a[$i], $a[$i - 1]) = array($a[$i - 1], $a[$i]); - //printArray($a, array($i, $i - 1)); - $i = 0; - continue; - } - } -} diff --git a/tempSolutions/ZJNUoj1259_LuckyNum-brute-sol.cs b/tempSolutions/ZJNUoj1259_LuckyNum-brute-sol.cs deleted file mode 100644 index 4e03f682..00000000 --- a/tempSolutions/ZJNUoj1259_LuckyNum-brute-sol.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Diagnostics; - -namespace ZJNUoj1259_LuckyNum -{ - class Program - { - public class Solution - { - public const Int64 N = 100000000; - public string GetKthLuckyNum(int n) - { - Dictionary luckyNums = new Dictionary(); - int count = 0; - for (Int64 i = 0; i <= N; i++) - { - if (IsLuckyNum(i.ToString())) - { - count++; - luckyNums.Add(count, i.ToString()); - } - } - - bool canGetValue = luckyNums.TryGetValue(n, out var result); - return result; - } - - private bool IsLuckyNum(string str) - { - int count4 = str.Count(f => f == '4'); - int count7 = str.Count(f => f == '7'); - - return count4 + count7 == str.Length; - } - } - - static void Main(string[] args) - { - string str; - while ((str = Console.ReadLine()) != null) - { - Stopwatch stopWatch = new Stopwatch(); - stopWatch.Start(); - - int k = int.Parse(str); - var sol = new Solution(); - Console.WriteLine(sol.GetKthLuckyNum(k)); - - stopWatch.Stop(); - TimeSpan ts = stopWatch.Elapsed; - string elapsedTime = $"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds/10:00}"; - Console.WriteLine($"RunTime{elapsedTime}"); - } - } - } -} diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 00000000..17ba13c9 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,3 @@ +## 说明 + +本文件夹包含leetcode刷题神器(浏览器插件等)等. \ No newline at end of file diff --git a/tools/leetboard_v1.3.0.0.crx b/tools/leetboard_v1.3.0.0.crx new file mode 100644 index 00000000..cfb13997 Binary files /dev/null and b/tools/leetboard_v1.3.0.0.crx differ diff --git a/tools/leetcode cheatsheet_v0.8.20.crx b/tools/leetcode cheatsheet_v0.8.20.crx new file mode 100644 index 00000000..9cef8a95 Binary files /dev/null and b/tools/leetcode cheatsheet_v0.8.20.crx differ diff --git a/tools/leetcode cheatsheet_v0.9.0.crx b/tools/leetcode cheatsheet_v0.9.0.crx new file mode 100644 index 00000000..113240fb Binary files /dev/null and b/tools/leetcode cheatsheet_v0.9.0.crx differ diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0001.leetcode1 Two Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0001.leetcode1 Two Sum-zh.md" new file mode 100644 index 00000000..0689f5d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0001.leetcode1 Two Sum-zh.md" @@ -0,0 +1,158 @@ +# [1. 两数之和](https://leetcode-cn.com/problems/two-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0001.Two%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。

    + +

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

    + +

    你可以按任意顺序返回答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,7,11,15], target = 9
    +输出:[0,1]
    +解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,2,4], target = 6
    +输出:[1,2]
    +
    + +

    示例 3:

    + +
    +输入:nums = [3,3], target = 6
    +输出:[0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 103
    • +
    • -109 <= nums[i] <= 109
    • +
    • -109 <= target <= 109
    • +
    • 只会存在一个有效答案
    • +
    + + +## 解法 + + + +用哈希表(字典)存放数组值以及对应的下标。 + +遍历数组,当发现 `target - nums[i]` 在哈希表中,说明找到了目标值。 + + + +### **Python3** + + + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + helper = {} + for i, v in enumerate(nums): + num = target - v + if num in helper: + return [helper[num], i] + helper[v] = i +``` + +### **Java** + + + +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + Map map = new HashMap<>(); + for (int i = 0, n = nums.length; i < n; ++i) { + int num = target - nums[i]; + if (map.containsKey(num)) { + return new int[]{map.get(num), i}; + } + map.put(nums[i], i); + } + return null; + } +} +``` + +### **JavaScript** + +```js +var twoSum = function (nums, target) { + const map = new Map(); + for (let i = 0; i < nums.length; i++) { + if (map.has(target - nums[i])) { + return [map.get(target - nums[i]), i]; + } + map.set(nums[i], i); + } + return []; +}; +``` + +### **Swift** + +```swift +class Solution { + func twoSum(_ nums: [Int], _ target: Int) -> [Int] { + var map = [Int: Int]() + var i = 0 + for num in nums { + map[num] = i + i = i + 1 + } + i = 0 + for num in nums { + if let otherIndex = map[target - num], otherIndex != i { + return [i, otherIndex] + } + i = i + 1 + } + return [] + } +} +``` + +### **Nim** + +```nim +import std/enumerate + +proc twoSum(nums: seq[int], target: int): seq[int] = + var + bal: int + tdx: int + for idx, val in enumerate(nums): + bal = target - val + if bal in nums: + tdx = nums.find(bal) + if idx != tdx: + return @[idx, tdx] + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0002.leetcode2 Add Two Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0002.leetcode2 Add Two Numbers-zh.md" new file mode 100644 index 00000000..386d6b09 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0002.leetcode2 Add Two Numbers-zh.md" @@ -0,0 +1,350 @@ +# [2. 两数相加](https://leetcode-cn.com/problems/add-two-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0002.Add%20Two%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

    + +

    请你将两个数相加,并以相同形式返回一个表示和的链表。

    + +

    你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

    + +

     

    + +

    示例 1:

    + +
    +输入:l1 = [2,4,3], l2 = [5,6,4]
    +输出:[7,0,8]
    +解释:342 + 465 = 807.
    +
    + +

    示例 2:

    + +
    +输入:l1 = [0], l2 = [0]
    +输出:[0]
    +
    + +

    示例 3:

    + +
    +输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
    +输出:[8,9,9,9,0,0,0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每个链表中的节点数在范围 [1, 100]
    • +
    • 0 <= Node.val <= 9
    • +
    • 题目数据保证列表表示的数字不含前导零
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + carry, cur = 0, dummy + while l1 or l2 or carry: + s = (0 if not l1 else l1.val) + (0 if not l2 else l2.val) + carry + carry, val = divmod(s, 10) + cur.next = ListNode(val) + cur = cur.next + l1 = None if not l1 else l1.next + l2 = None if not l2 else l2.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + int carry = 0; + ListNode* cur = dummy; + while (l1 || l2 || carry) { + int s = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; + carry = s / 10; + cur->next = new ListNode(s % 10); + cur = cur->next; + l1 = l1 ? l1->next : nullptr; + l2 = l2 ? l2->next : nullptr; + } + return dummy->next; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + const dummy = new ListNode(); + let carry = 0; + let cur = dummy; + while (l1 || l2 || carry) { + const s = (l1?.val || 0) + (l2?.val || 0) + carry; + carry = Math.floor(s / 10); + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1?.next; + l2 = l2?.next; + } + return dummy.next; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + carry := 0 + cur := dummy + for l1 != nil || l2 != nil || carry != 0 { + s := carry + if l1 != nil { + s += l1.Val + } + if l2 != nil { + s += l2.Val + } + carry = s / 10 + cur.Next = &ListNode{s % 10, nil} + cur = cur.Next + if l1 != nil { + l1 = l1.Next + } + if l2 != nil { + l2 = l2.Next + } + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + dummy = ListNode.new() + carry = 0 + cur = dummy + while !l1.nil? || !l2.nil? || carry > 0 + s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry + carry = s / 10 + cur.next = ListNode.new(s % 10) + cur = cur.next + l1 = l1.nil? ? l1 : l1.next + l2 = l2.nil? ? l2 : l2.next + end + dummy.next +end +``` + +### **Swift** + +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { + var dummy = ListNode.init() + var carry = 0 + var l1 = l1 + var l2 = l2 + var cur = dummy + while l1 != nil || l2 != nil || carry != 0 { + let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry + carry = s / 10 + cur.next = ListNode.init(s % 10) + cur = cur.next! + l1 = l1?.next + l2 = l2?.next + } + return dummy.next + } +} +``` + +### **Nim** + +```nim +#[ + # Driver code in the solution file + # Definition for singly-linked list. + type + Node[int] = ref object + value: int + next: Node[int] + + SinglyLinkedList[T] = object + head, tail: Node[T] +]# + +# More efficient code churning ... +proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = + var + aggregate: SinglyLinkedList + psum: seq[char] + temp_la, temp_lb: seq[int] + + while not l1.head.isNil: + temp_la.add(l1.head.value) + l1.head = l1.head.next + + while not l2.head.isNil: + temp_lb.add(l2.head.value) + l2.head = l2.head.next + + psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) + for i in psum: aggregate.append(($i).parseInt()) + + result = aggregate +``` + + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0002.leetcode2 Add Two Numbers.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0002.leetcode2 Add Two Numbers.md" new file mode 100644 index 00000000..386d6b09 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0002.leetcode2 Add Two Numbers.md" @@ -0,0 +1,350 @@ +# [2. 两数相加](https://leetcode-cn.com/problems/add-two-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0002.Add%20Two%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

    + +

    请你将两个数相加,并以相同形式返回一个表示和的链表。

    + +

    你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

    + +

     

    + +

    示例 1:

    + +
    +输入:l1 = [2,4,3], l2 = [5,6,4]
    +输出:[7,0,8]
    +解释:342 + 465 = 807.
    +
    + +

    示例 2:

    + +
    +输入:l1 = [0], l2 = [0]
    +输出:[0]
    +
    + +

    示例 3:

    + +
    +输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
    +输出:[8,9,9,9,0,0,0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每个链表中的节点数在范围 [1, 100]
    • +
    • 0 <= Node.val <= 9
    • +
    • 题目数据保证列表表示的数字不含前导零
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + carry, cur = 0, dummy + while l1 or l2 or carry: + s = (0 if not l1 else l1.val) + (0 if not l2 else l2.val) + carry + carry, val = divmod(s, 10) + cur.next = ListNode(val) + cur = cur.next + l1 = None if not l1 else l1.next + l2 = None if not l2 else l2.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + int carry = 0; + ListNode* cur = dummy; + while (l1 || l2 || carry) { + int s = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; + carry = s / 10; + cur->next = new ListNode(s % 10); + cur = cur->next; + l1 = l1 ? l1->next : nullptr; + l2 = l2 ? l2->next : nullptr; + } + return dummy->next; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + const dummy = new ListNode(); + let carry = 0; + let cur = dummy; + while (l1 || l2 || carry) { + const s = (l1?.val || 0) + (l2?.val || 0) + carry; + carry = Math.floor(s / 10); + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1?.next; + l2 = l2?.next; + } + return dummy.next; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + carry := 0 + cur := dummy + for l1 != nil || l2 != nil || carry != 0 { + s := carry + if l1 != nil { + s += l1.Val + } + if l2 != nil { + s += l2.Val + } + carry = s / 10 + cur.Next = &ListNode{s % 10, nil} + cur = cur.Next + if l1 != nil { + l1 = l1.Next + } + if l2 != nil { + l2 = l2.Next + } + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + dummy = ListNode.new() + carry = 0 + cur = dummy + while !l1.nil? || !l2.nil? || carry > 0 + s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry + carry = s / 10 + cur.next = ListNode.new(s % 10) + cur = cur.next + l1 = l1.nil? ? l1 : l1.next + l2 = l2.nil? ? l2 : l2.next + end + dummy.next +end +``` + +### **Swift** + +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { + var dummy = ListNode.init() + var carry = 0 + var l1 = l1 + var l2 = l2 + var cur = dummy + while l1 != nil || l2 != nil || carry != 0 { + let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry + carry = s / 10 + cur.next = ListNode.init(s % 10) + cur = cur.next! + l1 = l1?.next + l2 = l2?.next + } + return dummy.next + } +} +``` + +### **Nim** + +```nim +#[ + # Driver code in the solution file + # Definition for singly-linked list. + type + Node[int] = ref object + value: int + next: Node[int] + + SinglyLinkedList[T] = object + head, tail: Node[T] +]# + +# More efficient code churning ... +proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = + var + aggregate: SinglyLinkedList + psum: seq[char] + temp_la, temp_lb: seq[int] + + while not l1.head.isNil: + temp_la.add(l1.head.value) + l1.head = l1.head.next + + while not l2.head.isNil: + temp_lb.add(l2.head.value) + l2.head = l2.head.next + + psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) + for i in psum: aggregate.append(($i).parseInt()) + + result = aggregate +``` + + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0003.leetcode3 Longest Substring Without Repeating Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0003.leetcode3 Longest Substring Without Repeating Characters-zh.md" new file mode 100644 index 00000000..b3b8d8f9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0003.leetcode3 Longest Substring Without Repeating Characters-zh.md" @@ -0,0 +1,159 @@ +# [3. 无重复字符的最长子串](https://leetcode-cn.com/problems/longest-substring-without-repeating-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0003.Longest%20Substring%20Without%20Repeating%20Characters/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    + +

     

    + +

    示例 1:

    + +
    +输入: s = "abcabcbb"
    +输出: 3 
    +解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
    +
    + +

    示例 2:

    + +
    +输入: s = "bbbbb"
    +输出: 1
    +解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
    +
    + +

    示例 3:

    + +
    +输入: s = "pwwkew"
    +输出: 3
    +解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
    +     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
    +
    + +

    示例 4:

    + +
    +输入: s = ""
    +输出: 0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 5 * 104
    • +
    • s 由英文字母、数字、符号和空格组成
    • +
    + + +## 解法 + + + +- 定义一个哈希表存放字符及其出现的位置; +- 定义 i, j 分别表示不重复子串的开始位置和结束位置; +- j 向后遍历,若遇到与 `[i, j]` 区间内字符相同的元素,更新 i 的值,此时 `[i, j]` 区间内不存在重复字符,计算 res 的最大值。 + + + +### **Python3** + + + +```python +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + res, chars = 0, dict() + i = j = 0 + while j < len(s): + if s[j] in chars: + # chars[s[j]]+1 可能比 i 还小,通过 max 函数来锁住左边界 + # e.g. 在"tmmzuxt"这个字符串中,遍历到最后一步时,最后一个字符't'和第一个字符't'是相等的。如果没有 max 函数,i 就会回到第一个't'的索引0处的下一个位置 + i = max(i, chars[s[j]] + 1) + res = max(res, j - i + 1) + chars[s[j]] = j + j += 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int lengthOfLongestSubstring(String s) { + int res = 0; + Map chars = new HashMap<>(); + for (int i = 0, j = 0; j < s.length(); ++j) { + char c = s.charAt(j); + if (chars.containsKey(c)) { + // chars.get(c)+1 可能比 i 还小,通过 max 函数来锁住左边界 + // e.g. 在"tmmzuxt"这个字符串中,遍历到最后一步时,最后一个字符't'和第一个字符't'是相等的。如果没有 max 函数,i 就会回到第一个't'的索引0处的下一个位置 + i = Math.max(i, chars.get(c) + 1); + } + chars.put(c, j); + res = Math.max(res, j - i + 1); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function lengthOfLongestSubstring(s: string): number { + // 滑动窗口+哈希表 + let left = -1; + let maxLen = 0; + let hashTable = new Map(); + for (let right = 0; right < s.length; right++) { + let cur = s.charAt(right); + if (hashTable.has(cur)) { + left = Math.max(left, hashTable.get(cur)); + } + hashTable.set(cur, right); + maxLen = Math.max(maxLen, right - left); + } + return maxLen; + }; +``` + +### **Swift** + +```swift +class Solution { + func lengthOfLongestSubstring(_ s: String) -> Int { + var map = [Character: Int]() + var currentStartingIndex = 0 + var i = 0 + var maxLength = 0 + for char in s { + if map[char] != nil { + if map[char]! >= currentStartingIndex { + maxLength = max(maxLength, i - currentStartingIndex) + currentStartingIndex = map[char]! + 1 + } + } + map[char] = i + i += 1 + } + return max(maxLength, i - currentStartingIndex) + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0004.leetcode4 Median of Two Sorted Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0004.leetcode4 Median of Two Sorted Arrays-zh.md" new file mode 100644 index 00000000..f0eb5430 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0004.leetcode4 Median of Two Sorted Arrays-zh.md" @@ -0,0 +1,96 @@ +# [4. 寻找两个正序数组的中位数](https://leetcode-cn.com/problems/median-of-two-sorted-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0004.Median%20of%20Two%20Sorted%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给定两个大小分别为 mn 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数

    + +

     

    + +

    示例 1:

    + +
    +输入:nums1 = [1,3], nums2 = [2]
    +输出:2.00000
    +解释:合并数组 = [1,2,3] ,中位数 2
    +
    + +

    示例 2:

    + +
    +输入:nums1 = [1,2], nums2 = [3,4]
    +输出:2.50000
    +解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
    +
    + +

    示例 3:

    + +
    +输入:nums1 = [0,0], nums2 = [0,0]
    +输出:0.00000
    +
    + +

    示例 4:

    + +
    +输入:nums1 = [], nums2 = [1]
    +输出:1.00000
    +
    + +

    示例 5:

    + +
    +输入:nums1 = [2], nums2 = []
    +输出:2.00000
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums1.length == m
    • +
    • nums2.length == n
    • +
    • 0 <= m <= 1000
    • +
    • 0 <= n <= 1000
    • +
    • 1 <= m + n <= 2000
    • +
    • -106 <= nums1[i], nums2[i] <= 106
    • +
    + +

     

    + +

    进阶:你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0005.leetcode5 Longest Palindromic Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0005.leetcode5 Longest Palindromic Substring-zh.md" new file mode 100644 index 00000000..55f9c690 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0005.leetcode5 Longest Palindromic Substring-zh.md" @@ -0,0 +1,80 @@ +# [5. 最长回文子串](https://leetcode-cn.com/problems/longest-palindromic-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0005.Longest%20Palindromic%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,找到 s 中最长的回文子串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "babad"
    +输出:"bab"
    +解释:"aba" 同样是符合题意的答案。
    +
    + +

    示例 2:

    + +
    +输入:s = "cbbd"
    +输出:"bb"
    +
    + +

    示例 3:

    + +
    +输入:s = "a"
    +输出:"a"
    +
    + +

    示例 4:

    + +
    +输入:s = "ac"
    +输出:"a"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 仅由数字和英文字母(大写和/或小写)组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0006.leetcode6 ZigZag Conversion-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0006.leetcode6 ZigZag Conversion-zh.md" new file mode 100644 index 00000000..872697ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0006.leetcode6 ZigZag Conversion-zh.md" @@ -0,0 +1,91 @@ +# [6. Z 字形变换](https://leetcode-cn.com/problems/zigzag-conversion) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0006.ZigZag%20Conversion/README_EN.md) + +## 题目描述 + + + +

    将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

    + +

    比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

    + +
    +P   A   H   N
    +A P L S I I G
    +Y   I   R
    + +

    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"

    + +

    请你实现这个将字符串进行指定行数变换的函数:

    + +
    +string convert(string s, int numRows);
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "PAYPALISHIRING", numRows = 3
    +输出:"PAHNAPLSIIGYIR"
    +
    +示例 2: + +
    +输入:s = "PAYPALISHIRING", numRows = 4
    +输出:"PINALSIGYAHRPI"
    +解释:
    +P     I    N
    +A   L S  I G
    +Y A   H R
    +P     I
    +
    + +

    示例 3:

    + +
    +输入:s = "A", numRows = 1
    +输出:"A"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 由英文字母(小写和大写)、',''.' 组成
    • +
    • 1 <= numRows <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0007.leetcode7 Reverse Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0007.leetcode7 Reverse Integer-zh.md" new file mode 100644 index 00000000..1f981501 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0007.leetcode7 Reverse Integer-zh.md" @@ -0,0 +1,129 @@ +# [7. 整数反转](https://leetcode-cn.com/problems/reverse-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0007.Reverse%20Integer/README_EN.md) + +## 题目描述 + + + +

    给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

    + +

    如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

    +假设环境不允许存储 64 位整数(有符号或无符号)。 + +

     

    + +

    示例 1:

    + +
    +输入:x = 123
    +输出:321
    +
    + +

    示例 2:

    + +
    +输入:x = -123
    +输出:-321
    +
    + +

    示例 3:

    + +
    +输入:x = 120
    +输出:21
    +
    + +

    示例 4:

    + +
    +输入:x = 0
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • -231 <= x <= 231 - 1
    • +
    + +## 解法 + + + + + +### **Python3** + + + +转字符串,进行翻转。 + +```python +class Solution: + def reverse(self, x: int) -> int: + y = int(str(abs(x))[::-1]) + res = -y if x < 0 else y + return 0 if res < -2**31 or res > 2**31 -1 else res +``` + +### **Java** + + + +```java +class Solution { + public int reverse(int x) { + long res = 0; + // 考虑负数情况,所以这里条件为: x != 0 + while (x != 0) { + res = res * 10 + (x % 10); + x /= 10; + } + return res < Integer.MIN_VALUE || res > Integer.MAX_VALUE ? 0 : (int) res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int reverse(int x) { + long long ans = 0; + while (x) { + ans = ans * 10 + x % 10; + x /= 10; + } + return ans < INT_MIN || ans > INT_MAX ? 0 : ans; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @return {number} + */ +var reverse = function (x) { + let res = 0; + while (x) { + res = res * 10 + (x % 10); + x = ~~(x / 10); + } + return res < Math.pow(-2, 31) || res > Math.pow(2, 31) - 1 ? 0 : res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0008.leetcode8 String to Integer (atoi)-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0008.leetcode8 String to Integer (atoi)-zh.md" new file mode 100644 index 00000000..88f02e62 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0008.leetcode8 String to Integer (atoi)-zh.md" @@ -0,0 +1,200 @@ +# [8. 字符串转换整数 (atoi)](https://leetcode-cn.com/problems/string-to-integer-atoi) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0008.String%20to%20Integer%20%28atoi%29/README_EN.md) + +## 题目描述 + + + +

    请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。

    + +

    函数 myAtoi(string s) 的算法如下:

    + +
      +
    • 读入字符串并丢弃无用的前导空格
    • +
    • 检查下一个字符(假设还未到字符末尾)为正还是负号,读取该字符(如果有)。 确定最终结果是负数还是正数。 如果两者都不存在,则假定结果为正。
    • +
    • 读入下一个字符,直到到达下一个非数字字符或到达输入的结尾。字符串的其余部分将被忽略。
    • +
    • 将前面步骤读入的这些数字转换为整数(即,"123" -> 123, "0032" -> 32)。如果没有读入数字,则整数为 0 。必要时更改符号(从步骤 2 开始)。
    • +
    • 如果整数数超过 32 位有符号整数范围 [−231,  231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被固定为 −231 ,大于 231 − 1 的整数应该被固定为 231 − 1
    • +
    • 返回整数作为最终结果。
    • +
    + +

    注意:

    + +
      +
    • 本题中的空白字符只包括空格字符 ' '
    • +
    • 除前导空格或数字后的其余字符串外,请勿忽略 任何其他字符。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "42"
    +输出:42
    +解释:加粗的字符串为已经读入的字符,插入符号是当前读取的字符。
    +第 1 步:"42"(当前没有读入字符,因为没有前导空格)
    +         ^
    +第 2 步:"42"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
    +         ^
    +第 3 步:"42"(读入 "42")
    +           ^
    +解析得到整数 42 。
    +由于 "42" 在范围 [-231, 231 - 1] 内,最终结果为 42 。
    + +

    示例 2:

    + +
    +输入:s = "   -42"
    +输出:-42
    +解释:
    +第 1 步:"   -42"(读入前导空格,但忽视掉)
    +            ^
    +第 2 步:"   -42"(读入 '-' 字符,所以结果应该是负数)
    +             ^
    +第 3 步:"   -42"(读入 "42")
    +               ^
    +解析得到整数 -42 。
    +由于 "-42" 在范围 [-231, 231 - 1] 内,最终结果为 -42 。
    +
    + +

    示例 3:

    + +
    +输入:s = "4193 with words"
    +输出:4193
    +解释:
    +第 1 步:"4193 with words"(当前没有读入字符,因为没有前导空格)
    +         ^
    +第 2 步:"4193 with words"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
    +         ^
    +第 3 步:"4193 with words"(读入 "4193";由于下一个字符不是一个数字,所以读入停止)
    +             ^
    +解析得到整数 4193 。
    +由于 "4193" 在范围 [-231, 231 - 1] 内,最终结果为 4193 。
    +
    + +

    示例 4:

    + +
    +输入:s = "words and 987"
    +输出:0
    +解释:
    +第 1 步:"words and 987"(当前没有读入字符,因为没有前导空格)
    +         ^
    +第 2 步:"words and 987"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
    +         ^
    +第 3 步:"words and 987"(由于当前字符 'w' 不是一个数字,所以读入停止)
    +         ^
    +解析得到整数 0 ,因为没有读入任何数字。
    +由于 0 在范围 [-231, 231 - 1] 内,最终结果为 0 。
    + +

    示例 5:

    + +
    +输入:s = "-91283472332"
    +输出:-2147483648
    +解释:
    +第 1 步:"-91283472332"(当前没有读入字符,因为没有前导空格)
    +         ^
    +第 2 步:"-91283472332"(读入 '-' 字符,所以结果应该是负数)
    +          ^
    +第 3 步:"-91283472332"(读入 "91283472332")
    +                     ^
    +解析得到整数 -91283472332 。
    +由于 -91283472332 小于范围 [-231, 231 - 1] 的下界,最终结果被截断为 -231 = -2147483648 。
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 200
    • +
    • s 由英文字母(大写和小写)、数字(0-9)、' ''+''-''.' 组成
    • +
    + + +## 解法 + + + +遍历字符串,注意做溢出处理。 + +同[面试题 67. 把字符串转换成整数](/lcof/面试题67.%20把字符串转换成整数/README.md)。 + + + +### **Python3** + + + +```python +class Solution: + def myAtoi(self, s: str) -> int: + if not s: + return 0 + n = len(s) + if n == 0: + return 0 + i = 0 + while s[i] == ' ': + i += 1 + # 仅包含空格 + if i == n: + return 0 + sign = -1 if s[i] == '-' else 1 + if s[i] in ['-', '+']: + i += 1 + res, flag = 0, (2 ** 31 - 1) // 10 + while i < n: + # 非数字,跳出循环体 + if not s[i].isdigit(): + break + c = int(s[i]) + # 溢出判断 + if res > flag or (res == flag and c > 7): + return 2 ** 31 - 1 if sign > 0 else -2 ** 31 + res = res * 10 + c + i += 1 + return sign * res +``` + +### **Java** + + + +```java +class Solution { + public int myAtoi(String s) { + if (s == null) return 0; + int n = s.length(); + if (n == 0) return 0; + int i = 0; + while (s.charAt(i) == ' ') { + // 仅包含空格 + if (++i == n) return 0; + } + int sign = 1; + if (s.charAt(i) == '-') sign = -1; + if (s.charAt(i) == '-' || s.charAt(i) == '+') ++i; + int res = 0, flag = Integer.MAX_VALUE / 10; + for (; i < n; ++i) { + // 非数字,跳出循环体 + if (s.charAt(i) < '0' || s.charAt(i) > '9') break; + // 溢出判断 + if (res > flag || (res == flag && s.charAt(i) > '7')) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; + res = res * 10 + (s.charAt(i) - '0'); + } + return sign * res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0009.leetcode9 Palindrome Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0009.leetcode9 Palindrome Number-zh.md" new file mode 100644 index 00000000..d3732df3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0009.leetcode9 Palindrome Number-zh.md" @@ -0,0 +1,104 @@ +# [9. 回文数](https://leetcode-cn.com/problems/palindrome-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0009.Palindrome%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false

    + +

    回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

    + +

     

    + +

    示例 1:

    + +
    +输入:x = 121
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:x = -121
    +输出:false
    +解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
    +
    + +

    示例 3:

    + +
    +输入:x = 10
    +输出:false
    +解释:从右向左读, 为 01 。因此它不是一个回文数。
    +
    + +

    示例 4:

    + +
    +输入:x = -101
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • -231 <= x <= 231 - 1
    • +
    + +

     

    + +

    进阶:你能不将整数转为字符串来解决这个问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + y, t = 0, x + while t: + y = y * 10 + t % 10 + t //= 10 + return x == y +``` + +### **Java** + + + +```java +class Solution { + public boolean isPalindrome(int x) { + if (x < 0) return false; + int y = 0, t = x; + while (t != 0) { + y = y * 10 + t % 10; + t /= 10; + } + return x == y; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0010.leetcode10 Regular Expression Matching-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0010.leetcode10 Regular Expression Matching-zh.md" new file mode 100644 index 00000000..969c774f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0010.leetcode10 Regular Expression Matching-zh.md" @@ -0,0 +1,98 @@ +# [10. 正则表达式匹配](https://leetcode-cn.com/problems/regular-expression-matching) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0010.Regular%20Expression%20Matching/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。

    + +
      +
    • '.' 匹配任意单个字符
    • +
    • '*' 匹配零个或多个前面的那一个元素
    • +
    + +

    所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。

    +  + +

    示例 1:

    + +
    +输入:s = "aa" p = "a"
    +输出:false
    +解释:"a" 无法匹配 "aa" 整个字符串。
    +
    + +

    示例 2:

    + +
    +输入:s = "aa" p = "a*"
    +输出:true
    +解释:因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。
    +
    + +

    示例 3:

    + +
    +输入:s = "ab" p = ".*"
    +输出:true
    +解释:".*" 表示可匹配零个或多个('*')任意字符('.')。
    +
    + +

    示例 4:

    + +
    +输入:s = "aab" p = "c*a*b"
    +输出:true
    +解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
    +
    + +

    示例 5:

    + +
    +输入:s = "mississippi" p = "mis*is*p*."
    +输出:false
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 20
    • +
    • 0 <= p.length <= 30
    • +
    • s 可能为空,且只包含从 a-z 的小写字母。
    • +
    • p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *
    • +
    • 保证每次出现字符 * 时,前面都匹配到有效的字符
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0011.leetcode11 Container With Most Water-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0011.leetcode11 Container With Most Water-zh.md" new file mode 100644 index 00000000..45eb546e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0011.leetcode11 Container With Most Water-zh.md" @@ -0,0 +1,194 @@ +# [11. 盛最多水的容器](https://leetcode-cn.com/problems/container-with-most-water) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0011.Container%20With%20Most%20Water/README_EN.md) + +## 题目描述 + + + +

    给你 n 个非负整数 a1,a2,...,an每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai)(i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

    + +

    说明:你不能倾斜容器。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:[1,8,6,2,5,4,8,3,7]
    +输出:49 
    +解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
    + +

    示例 2:

    + +
    +输入:height = [1,1]
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:height = [4,3,2,1,4]
    +输出:16
    +
    + +

    示例 4:

    + +
    +输入:height = [1,2,1]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • n = height.length
    • +
    • 2 <= n <= 3 * 104
    • +
    • 0 <= height[i] <= 3 * 104
    • +
    + + +## 解法 + + + +双指针解决。 + +一开始,我们考虑相距最远的两个柱子所能容纳水的面积。水的宽度是两根柱子之间的距离,而水的高度取决于两根柱子之间较短的那个。 + +- 当前柱子是最两侧的柱子,水的宽度最大,其他的组合,水的宽度都比这个小; +- 当前左侧柱子较短,决定了水的高度。如果移动左侧的柱子,新的水面高度不确定,但一定不会超过右侧的柱子高度; +- 如果移动右侧的柱子,新的水面高度一定不会超过左侧的柱子高度,也就是不会超过当前的水面高度。 + +可见,如果固定左侧的柱子,向内移动右侧的柱子,水的高度一定不会增加,且宽度一定减少,所以水的面积一定减少。所以左侧的柱子跟右侧其他柱子的组合,都可以排除了。也就是代码中的 `i++`。 + +移动左侧的柱子中,重复进行上面的操作。 + +在此过程中,我们不断排除掉无法成为构成最大值的柱子组合,而每一次都获取到可能为最大值的面积 t。那么遍历结束之后,我们就可以得到最大值。 + + + +### **Python3** + + + +```python +class Solution: + def maxArea(self, height: List[int]) -> int: + i, j = 0, len(height) - 1 + res = 0 + while i < j: + t = (j - i) * min(height[i], height[j]) + res = max(res, t) + if height[i] < height[j]: + i += 1 + else: + j -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxArea(int[] height) { + int i = 0, j = height.length - 1; + int res = 0; + while (i < j) { + int t = (j - i) * Math.min(height[i], height[j]); + res = Math.max(res, t); + if (height[i] < height[j]) ++i; + else --j; + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxArea(vector& height) { + int i = 0, j = height.size() - 1; + int res = 0; + while (i < j) { + int t = (j - i) * min(height[i], height[j]); + res = max(res, t); + if (height[i] < height[j]) ++i; + else --j; + } + return res; + } +}; +``` + +### **Go** + +```go +func maxArea(height []int) int { + i, j := 0, len(height) - 1 + res := 0 + for i != j { + t := (j - i) * min(height[i], height[j]) + res = max(res, t) + if height[i] < height[j] { + i++ + } else { + j-- + } + } + return res +} + +func min(a, b int) int { + if a > b { + return b + } + return a +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function (height) { + let i = 0, + j = height.length - 1; + let res = 0; + while (i < j) { + const t = (j - i) * Math.min(height[i], height[j]); + res = Math.max(res, t); + if (height[i] < height[j]) ++i; + else --j; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0012.leetcode12 Integer to Roman-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0012.leetcode12 Integer to Roman-zh.md" new file mode 100644 index 00000000..e6b262ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0012.leetcode12 Integer to Roman-zh.md" @@ -0,0 +1,148 @@ +# [12. 整数转罗马数字](https://leetcode-cn.com/problems/integer-to-roman) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0012.Integer%20to%20Roman/README_EN.md) + +## 题目描述 + + + +

    罗马数字包含以下七种字符: I, V, X, LCD 和 M

    + +
    +字符          数值
    +I             1
    +V             5
    +X             10
    +L             50
    +C             100
    +D             500
    +M             1000
    + +

    例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

    + +

    通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

    + +
      +
    • I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
    • +
    • X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
    • +
    • C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
    • +
    + +

    给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。

    + +

     

    + +

    示例 1:

    + +
    +输入: 3
    +输出: "III"
    + +

    示例 2:

    + +
    +输入: 4
    +输出: "IV"
    + +

    示例 3:

    + +
    +输入: 9
    +输出: "IX"
    + +

    示例 4:

    + +
    +输入: 58
    +输出: "LVIII"
    +解释: L = 50, V = 5, III = 3.
    +
    + +

    示例 5:

    + +
    +输入: 1994
    +输出: "MCMXCIV"
    +解释: M = 1000, CM = 900, XC = 90, IV = 4.
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num <= 3999
    • +
    + + +## 解法 + + + +贪心算法实现。 + + + +### **Python3** + + + +```python +class Solution: + def intToRoman(self, num: int) -> str: + nums = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')] + res = [] + for k, v in nums: + while num >= k: + num -= k + res.append(v) + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String intToRoman(int num) { + int[] nums = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + String[] romans = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < nums.length; ++i) { + while (num >= nums[i]) { + num -= nums[i]; + sb.append(romans[i]); + } + } + return sb.toString(); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string intToRoman(int num) { + vector nums{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + vector romans{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + string ans; + for (int i = 0; i < nums.size(); ++i) { + while (num >= nums[i]) { + num -= nums[i]; + ans.append(romans[i]); + } + } + return ans; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0013.leetcode13 Roman to Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0013.leetcode13 Roman to Integer-zh.md" new file mode 100644 index 00000000..ea8d4514 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0013.leetcode13 Roman to Integer-zh.md" @@ -0,0 +1,190 @@ +# [13. 罗马数字转整数](https://leetcode-cn.com/problems/roman-to-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0013.Roman%20to%20Integer/README_EN.md) + +## 题目描述 + + + +

    罗马数字包含以下七种字符: I, V, X, LCD 和 M

    + +
    +字符          数值
    +I             1
    +V             5
    +X             10
    +L             50
    +C             100
    +D             500
    +M             1000
    + +

    例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

    + +

    通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

    + +
      +
    • I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
    • +
    • X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
    • +
    • C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
    • +
    + +

    给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

    + +

     

    + +

    示例 1:

    + +
    +输入: "III"
    +输出: 3
    + +

    示例 2:

    + +
    +输入: "IV"
    +输出: 4
    + +

    示例 3:

    + +
    +输入: "IX"
    +输出: 9
    + +

    示例 4:

    + +
    +输入: "LVIII"
    +输出: 58
    +解释: L = 50, V= 5, III = 3.
    +
    + +

    示例 5:

    + +
    +输入: "MCMXCIV"
    +输出: 1994
    +解释: M = 1000, CM = 900, XC = 90, IV = 4.
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 15
    • +
    • s 仅含字符 ('I', 'V', 'X', 'L', 'C', 'D', 'M')
    • +
    • 题目数据保证 s 是一个有效的罗马数字,且表示整数在范围 [1, 3999]
    • +
    • 题目所给测试用例皆符合罗马数字书写规则,不会出现跨位等情况。
    • +
    • IL 和 IM 这样的例子并不符合题目要求,49 应该写作 XLIX,999 应该写作 CMXCIX 。
    • +
    • 关于罗马数字的详尽书写规则,可以参考 罗马数字 - Mathematics
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def romanToInt(self, s: str) -> int: + nums = { + 'M': 1000, + 'CM': 900, + 'D': 500, + 'CD': 400, + 'C': 100, + 'XC': 90, + 'L': 50, + 'XL': 40, + 'X': 10, + 'IX': 9, + 'V': 5, + 'IV': 4, + 'I': 1 + } + i = res = 0 + while i < len(s): + if i + 1 < len(s) and s[i:i + 2] in nums: + res += nums[s[i: i + 2]] + i += 2 + else: + res += nums[s[i: i + 1]] + i += 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int romanToInt(String s) { + Map nums = new HashMap<>(); + nums.put("M", 1000); + nums.put("CM", 900); + nums.put("D", 500); + nums.put("CD", 400); + nums.put("C", 100); + nums.put("XC", 90); + nums.put("L", 50); + nums.put("XL", 40); + nums.put("X", 10); + nums.put("IX", 9); + nums.put("V", 5); + nums.put("IV", 4); + nums.put("I", 1); + int res = 0; + for (int i = 0; i < s.length();) { + if (i + 1 < s.length() && nums.get(s.substring(i, i + 2)) != null) { + res += nums.get(s.substring(i, i + 2)); + i += 2; + } else { + res += nums.get(s.substring(i, i + 1)); + i += 1; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { + public: + int romanToInt(string s) { + unordered_map nums{ + {'I', 1}, + {'V', 5}, + {'X', 10}, + {'L', 50}, + {'C', 100}, + {'D', 500}, + {'M', 1000}, + }; + int ans = 0; + for (int i = 0; i < s.size() - 1; ++i) { + if (nums[s[i]] < nums[s[i + 1]]) + ans -= nums[s[i]]; + else + ans += nums[s[i]]; + } + return ans + nums[s.back()]; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0014.leetcode14 Longest Common Prefix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0014.leetcode14 Longest Common Prefix-zh.md" new file mode 100644 index 00000000..d48527f7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0014.leetcode14 Longest Common Prefix-zh.md" @@ -0,0 +1,110 @@ +# [14. 最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0014.Longest%20Common%20Prefix/README_EN.md) + +## 题目描述 + + + +

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

    + +

    如果不存在公共前缀,返回空字符串 ""

    + +

     

    + +

    示例 1:

    + +
    +输入:strs = ["flower","flow","flight"]
    +输出:"fl"
    +
    + +

    示例 2:

    + +
    +输入:strs = ["dog","racecar","car"]
    +输出:""
    +解释:输入不存在公共前缀。
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= strs.length <= 200
    • +
    • 0 <= strs[i].length <= 200
    • +
    • strs[i] 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + n = len(strs) + if n == 0: + return '' + for i in range(len(strs[0])): + for j in range(1, n): + if len(strs[j]) <= i or strs[j][i] != strs[0][i]: + return strs[0][:i] + return strs[0] +``` + +### **Java** + + + +```java +class Solution { + public String longestCommonPrefix(String[] strs) { + int n; + if ((n = strs.length) == 0) return ""; + for (int i = 0; i < strs[0].length(); ++i) { + for (int j = 1; j < n; ++j) { + if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) { + return strs[0].substring(0, i); + } + } + } + return strs[0]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string longestCommonPrefix(vector& strs) { + int n; + if ((n = strs.size()) == 0) return ""; + for (int i = 0; i < strs[0].size(); ++i) { + for (int j = 1; j < n; ++j) { + if (strs[j].size() <= i || strs[j][i] != strs[0][i]) { + return strs[0].substr(0, i); + } + } + } + return strs[0]; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0015.leetcode15 3Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0015.leetcode15 3Sum-zh.md" new file mode 100644 index 00000000..ce3c2597 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0015.leetcode15 3Sum-zh.md" @@ -0,0 +1,174 @@ +# [15. 三数之和](https://leetcode-cn.com/problems/3sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0015.3Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

    + +

    注意:答案中不可以包含重复的三元组。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [-1,0,1,2,-1,-4]
    +输出:[[-1,-1,2],[-1,0,1]]
    +
    + +

    示例 2:

    + +
    +输入:nums = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:nums = [0]
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 3000
    • +
    • -105 <= nums[i] <= 105
    • +
    + + +## 解法 + + + +“排序 + 双指针”实现。 + + + +### **Python3** + + + +```python +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + if nums is None or len(nums) < 3: + return [] + nums.sort() + n = len(nums) + res = [] + for i in range(n - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + p, q = i + 1, n - 1 + while p < q: + if p > i + 1 and nums[p] == nums[p - 1]: + p += 1 + continue + if q < n - 1 and nums[q] == nums[q + 1]: + q -= 1 + continue + if nums[i] + nums[p] + nums[q] < 0: + p += 1 + elif nums[i] + nums[p] + nums[q] > 0: + q -= 1 + else: + res.append([nums[i], nums[p], nums[q]]) + p += 1 + q -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public List> threeSum(int[] nums) { + int n; + if (nums == null || (n = nums.length) < 3) { + return Collections.emptyList(); + } + Arrays.sort(nums); + List> res = new ArrayList<>(); + for (int i = 0; i < n - 2; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + int p = i + 1, q = n - 1; + while (p < q) { + if (p > i + 1 && nums[p] == nums[p - 1]) { + ++p; + continue; + } + if (q < n - 1 && nums[q] == nums[q + 1]) { + --q; + continue; + } + if (nums[p] + nums[q] + nums[i] < 0) { + ++p; + } else if (nums[p] + nums[q] + nums[i] > 0) { + --q; + } else { + res.add(Arrays.asList(nums[p], nums[q], nums[i])); + ++p; + --q; + } + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function (nums) { + let len = nums.length; + if (len < 3) return []; + let res = []; + nums.sort((a, b) => a - b); + for (let i = 0; i < len - 2; i++) { + if (nums[i] > 0) break; + if (i > 0 && nums[i] === nums[i - 1]) continue; + let left = i + 1, right = len - 1; + while (left < right) { + if (nums[i] + nums[left] + nums[right] === 0) { + res.push([nums[i], nums[left], nums[right]]); + while (nums[left] === nums[left + 1]) left++; + left++; + while (nums[right] === nums[right - 1]) right--; + right--; + continue; + } else if (nums[i] + nums[left] + nums[right] > 0) { + right--; + continue; + } else { + left++; + continue; + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0016.leetcode16 3Sum Closest-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0016.leetcode16 3Sum Closest-zh.md" new file mode 100644 index 00000000..d7488c60 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0016.leetcode16 3Sum Closest-zh.md" @@ -0,0 +1,171 @@ +# [16. 最接近的三数之和](https://leetcode-cn.com/problems/3sum-closest) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0016.3Sum%20Closest/README_EN.md) + +## 题目描述 + + + +

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

    + +

     

    + +

    示例:

    + +
    输入:nums = [-1,2,1,-4], target = 1
    +输出:2
    +解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= nums.length <= 10^3
    • +
    • -10^3 <= nums[i] <= 10^3
    • +
    • -10^4 <= target <= 10^4
    • +
    + + +## 解法 + + + +双指针解决。 + + + +### **Python3** + + + +```python +class Solution: + def threeSumClosest(self, nums: List[int], target: int) -> int: + def twoSumClosest(nums, start, end, target): + res = 0 + diff = 10000 + while start < end: + val = nums[start] + nums[end] + if val == target: + return val + if abs(val - target) < diff: + res = val + diff = abs(val - target) + if val < target: + start += 1 + else: + end -= 1 + return res + + nums.sort() + res, n = 0, len(nums) + diff = 10000 + for i in range(n - 2): + t = twoSumClosest(nums, i + 1, n - 1, target - nums[i]) + if abs(nums[i] + t - target) < diff: + res = nums[i] + t + diff = abs(nums[i] + t - target) + return res +``` + +### **Java** + + + +```java +class Solution { + public int threeSumClosest(int[] nums, int target) { + Arrays.sort(nums); + int res = 0; + int n = nums.length; + int diff = Integer.MAX_VALUE; + for (int i = 0; i < n - 2; ++i) { + int t = twoSumClosest(nums, i + 1, n - 1, target - nums[i]); + if (Math.abs(nums[i] + t - target) < diff) { + res = nums[i] + t; + diff = Math.abs(nums[i] + t - target); + } + } + return res; + } + + private int twoSumClosest(int[] nums, int start, int end, int target) { + int res = 0; + int diff = Integer.MAX_VALUE; + while (start < end) { + int val = nums[start] + nums[end]; + if (val == target) { + return val; + } + if (Math.abs(val - target) < diff) { + res = val; + diff = Math.abs(val - target); + } + if (val < target) { + ++start; + } else { + --end; + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function (nums, target) { + let len = nums.length; + nums.sort((a, b) => a - b); + let diff = Infinity; + let res; + for (let i = 0; i < len - 2; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + let left = i + 1, right = len - 1; + let cur = nums[i] + nums[i + 1] + nums[i + 2]; + if (cur > target) { + let newDiff = Math.abs((cur - target)) + if (newDiff < diff) { + diff = newDiff; + res = cur; + } + break; + } + while (left < right) { + cur = nums[i] + nums[left] + nums[right]; + if (cur === target) return target; + let newDiff = Math.abs((cur - target)) + if (newDiff < diff) { + diff = newDiff; + res = cur; + } + if (cur < target) { + while (nums[left] === nums[left + 1]) left++; + left++; + continue; + } else { + while (nums[right] === nums[right - 1]) right--; + right--; + continue; + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0017.leetcode17 Letter Combinations of a Phone Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0017.leetcode17 Letter Combinations of a Phone Number-zh.md" new file mode 100644 index 00000000..ff45441a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0017.leetcode17 Letter Combinations of a Phone Number-zh.md" @@ -0,0 +1,121 @@ +# [17. 电话号码的字母组合](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

    + +

    给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

    + +

    + +

     

    + +

    示例 1:

    + +
    +输入:digits = "23"
    +输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
    +
    + +

    示例 2:

    + +
    +输入:digits = ""
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:digits = "2"
    +输出:["a","b","c"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= digits.length <= 4
    • +
    • digits[i] 是范围 ['2', '9'] 的一个数字。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + n = len(digits) + if n == 0: + return [] + chars = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] + strs = [chars[int(d) - 2] for d in digits] + res = [] + for s in strs: + if not res: + res = list(s) + else: + cache = [] + for item in res: + for letter in s: + cache.append(item + letter) + res = cache + return res +``` + +### **Java** + + + +```java +class Solution { + public List letterCombinations(String digits) { + int n; + if ((n = digits.length()) == 0) return Collections.emptyList(); + List chars = Arrays.asList("abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"); + + List strs = new ArrayList<>(); + for (char c : digits.toCharArray()) { + strs.add(chars.get(c - '0' - 2)); + } + List res = new ArrayList<>(); + for (String str : strs) { + if (res.size() == 0) { + for (char c : str.toCharArray()) { + res.add(String.valueOf(c)); + } + } else { + List cache = new ArrayList<>(); + for (String item : res) { + for (char c : str.toCharArray()) { + cache.add(item + String.valueOf(c)); + } + } + res = cache; + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0018.leetcode18 4Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0018.leetcode18 4Sum-zh.md" new file mode 100644 index 00000000..c2d8fc40 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0018.leetcode18 4Sum-zh.md" @@ -0,0 +1,182 @@ +# [18. 四数之和](https://leetcode-cn.com/problems/4sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0018.4Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

    + +

    注意:答案中不可以包含重复的四元组。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,0,-1,0,-2,2], target = 0
    +输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
    +
    + +

    示例 2:

    + +
    +输入:nums = [], target = 0
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 200
    • +
    • -109 <= nums[i] <= 109
    • +
    • -109 <= target <= 109
    • +
    + + +## 解法 + + + +“排序 + 双指针”实现。 + + + +### **Python3** + + + +```python +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + res = [] + if nums is None or len(nums) < 4: + return res + n = len(nums) + nums.sort() + for i in range(n - 3): + if i > 0 and nums[i] == nums[i - 1]: + continue + for j in range(i + 1, n - 2): + if j > i + 1 and nums[j] == nums[j - 1]: + continue + p, q = j + 1, n - 1 + while p < q: + if p > j + 1 and nums[p] == nums[p - 1]: + p += 1 + continue + if q < n - 1 and nums[q] == nums[q + 1]: + q -= 1 + continue + t = nums[i] + nums[j] + nums[p] + nums[q] + if t == target: + res.append([nums[i], nums[j], nums[p], nums[q]]) + p += 1 + q -= 1 + elif t < target: + p += 1 + else: + q -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public List> fourSum(int[] nums, int target) { + int n; + if (nums == null || (n = (nums.length)) < 4) { + return Collections.emptyList(); + } + Arrays.sort(nums); + List> res = new ArrayList<>(); + for (int i = 0; i < n - 3; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < n - 2; ++j) { + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + int p = j + 1, q = n - 1; + while (p < q) { + if (p > j + 1 && nums[p] == nums[p - 1]) { + ++p; + continue; + } + if (q < n - 1 && nums[q] == nums[q + 1]) { + --q; + continue; + } + int t = nums[i] + nums[j] + nums[p] + nums[q]; + if (t == target) { + res.add(Arrays.asList(nums[i], nums[j], nums[p], nums[q])); + ++p; + --q; + } else if (t < target) { + ++p; + } else { + --q; + } + } + } + } + return res; + } +} +``` + +### **JavaScript** +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function (nums, target) { + let len = nums.length; + let res = []; + if (len < 4) return []; + nums.sort((a, b) => a - b); + for (i = 0; i < len - 3; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + if (nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 3] < target) continue; + if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break; + for (j = i + 1; j < len - 2; j++) { + if (j > i + 1 && nums[j] === nums[j - 1]) continue; + let left = j + 1, right = len - 1; + while (left < right) { + if (nums[i] + nums[j] + nums[left] + nums[right] === target) { + res.push([nums[i], nums[j], nums[left], nums[right]]); + while (nums[left] === nums[left + 1]) left++; + left++; + while (nums[right] === nums[right - 1]) right--; + right--; + continue; + } else if (nums[i] + nums[j] + nums[left] + nums[right] > target) { + right--; + continue; + } else { + left++; + continue; + } + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0019.leetcode19 Remove Nth Node From End of List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0019.leetcode19 Remove Nth Node From End of List-zh.md" new file mode 100644 index 00000000..f827fb81 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0019.leetcode19 Remove Nth Node From End of List-zh.md" @@ -0,0 +1,235 @@ +# [19. 删除链表的倒数第 N 个结点](https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/README_EN.md) + +## 题目描述 + + + +

    给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

    + +

    进阶:你能尝试使用一趟扫描实现吗?

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4,5], n = 2
    +输出:[1,2,3,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [1], n = 1
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:head = [1,2], n = 1
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中结点的数目为 sz
    • +
    • 1 <= sz <= 30
    • +
    • 0 <= Node.val <= 100
    • +
    • 1 <= n <= sz
    • +
    + + +## 解法 + + + +利用快慢指针。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + dummy = ListNode(next=head) + fast = slow = dummy + for _ in range(n): + fast = fast.next + while fast.next: + slow, fast = slow.next, fast.next + slow.next = slow.next.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(0, head); + ListNode fast = dummy, slow = dummy; + while (n-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + slow.next = slow.next.next; + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode* dummy = new ListNode(0, head); + ListNode* fast = dummy; + ListNode* slow = dummy; + while (n--) { + fast = fast->next; + } + while (fast->next) { + slow = slow->next; + fast = fast->next; + } + slow->next = slow->next->next; + return dummy->next; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNthFromEnd(head *ListNode, n int) *ListNode { + dummy := &ListNode{0, head} + fast := dummy + slow := dummy + for n > 0 { + fast = fast.Next + n -= 1 + } + for fast.Next != nil { + slow = slow.Next + fast = fast.Next + } + slow.Next = slow.Next.Next + return dummy.Next +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function(head, n) { + const dummy = new ListNode(0, head); + let fast = dummy, slow = dummy; + while (n--) { + fast = fast.next; + } + while (fast.next) { + slow = slow.next; + fast = fast.next; + } + slow.next = slow.next.next; + return dummy.next; +}; +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @param {Integer} n +# @return {ListNode} +def remove_nth_from_end(head, n) + dummy = ListNode.new(0, head) + fast = slow = dummy + while n > 0 + fast = fast.next + n -= 1 + end + while fast.next + slow = slow.next + fast = fast.next + end + slow.next = slow.next.next + return dummy.next +end +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0020.leetcode20 Valid Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0020.leetcode20 Valid Parentheses-zh.md" new file mode 100644 index 00000000..e02661e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0020.leetcode20 Valid Parentheses-zh.md" @@ -0,0 +1,143 @@ +# [20. 有效的括号](https://leetcode-cn.com/problems/valid-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0020.Valid%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

    + +

    有效字符串需满足:

    + +
      +
    1. 左括号必须用相同类型的右括号闭合。
    2. +
    3. 左括号必须以正确的顺序闭合。
    4. +
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "()"
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:s = "()[]{}"
    +输出:true
    +
    + +

    示例 3:

    + +
    +输入:s = "(]"
    +输出:false
    +
    + +

    示例 4:

    + +
    +输入:s = "([)]"
    +输出:false
    +
    + +

    示例 5:

    + +
    +输入:s = "{[]}"
    +输出:true
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s 仅由括号 '()[]{}' 组成
    • +
    + + +## 解法 + + + +栈实现。 + +遍历括号字符串,遇到左括号时,将左括号压入栈中;遇到右括号时,弹出栈顶元素(栈若为空,直接返回 false),判断是否是相同类型的括号。若不匹配,直接返回 false。 + +遍历结束,栈若为空,说明括号字符串有效。 + + + +### **Python3** + + + +```python +class Solution: + def isValid(self, s: str) -> bool: + q = [] + parentheses = {'()', '[]', '{}'} + for ch in s: + if ch in '([{': + q.append(ch) + elif not q or q.pop() + ch not in parentheses: + return False + return not q +``` + +### **Java** + + + +```java +class Solution { + public boolean isValid(String s) { + char[] chars = s.toCharArray(); + Deque q = new ArrayDeque<>(); + for (char ch : chars) { + boolean left = ch == '(' || ch == '[' || ch == '{'; + if (left) q.push(ch); + else if (q.isEmpty() || !match(q.pop(), ch)) return false; + } + return q.isEmpty(); + } + + private boolean match(char l, char r) { + return (l == '(' && r == ')') || (l == '{' && r == '}') || (l == '[' && r == ']'); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isValid(string s) { + stack q; + for (int i = 0, n = s.length(); i < n; ++i) { + if (s[i] == '{' || s[i] == '[' || s[i] == '(') q.push(s[i]); + else if (q.empty() || !match(q.top(), s[i])) return false; + else q.pop(); + } + return q.empty(); + } +private: + bool match(char l, char r) { + return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0021.leetcode21 Merge Two Sorted Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0021.leetcode21 Merge Two Sorted Lists-zh.md" new file mode 100644 index 00000000..2c31ffd0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0021.leetcode21 Merge Two Sorted Lists-zh.md" @@ -0,0 +1,285 @@ +# [21. 合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0021.Merge%20Two%20Sorted%20Lists/README_EN.md) + +## 题目描述 + + + +

    将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

    + +

     

    + +

    示例 1:

    + +
    +输入:l1 = [1,2,4], l2 = [1,3,4]
    +输出:[1,1,2,3,4,4]
    +
    + +

    示例 2:

    + +
    +输入:l1 = [], l2 = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:l1 = [], l2 = [0]
    +输出:[0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 两个链表的节点数目范围是 [0, 50]
    • +
    • -100 <= Node.val <= 100
    • +
    • l1l2 均按 非递减顺序 排列
    • +
    + + +## 解法 + + + +迭代遍历两链表,比较节点值 val 的大小,进行节点串联,得到最终链表。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + cur = dummy + while l1 and l2: + if l1.val <= l2.val: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + cur.next = l1 or l2 + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + ListNode* cur = dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + cur->next = l1; + l1 = l1->next; + } else { + cur->next = l2; + l2 = l2->next; + } + cur = cur->next; + } + cur->next = l1 ? l1 : l2; + return dummy->next; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + cur := dummy + for l1 != nil && l2 != nil { + if l1.Val <= l2.Val { + cur.Next = l1 + l1 = l1.Next + } else { + cur.Next = l2 + l2 = l2.Next + } + cur = cur.Next + } + if l1 != nil { + cur.Next = l1 + } else if l2 != nil { + cur.Next = l2 + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def merge_two_lists(l1, l2) + dummy = ListNode.new() + cur = dummy + while l1 && l2 + if l1.val <= l2.val + cur.next = l1 + l1 = l1.next + else + cur.next = l2 + l2 = l2.next + end + cur = cur.next + end + cur.next = l1 || l2 + dummy.next +end +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0022.leetcode22 Generate Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0022.leetcode22 Generate Parentheses-zh.md" new file mode 100644 index 00000000..5280e7ed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0022.leetcode22 Generate Parentheses-zh.md" @@ -0,0 +1,167 @@ +# [22. 括号生成](https://leetcode-cn.com/problems/generate-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0022.Generate%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3
    +输出:["((()))","(()())","(())()","()(())","()()()"]
    +
    + +

    示例 2:

    + +
    +输入:n = 1
    +输出:["()"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 8
    • +
    + + +## 解法 + + + +dfs + + + +### **Python3** + + + +```python +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + def dfs(ans, l, r, n): + if len(ans) == (n << 1): + self.res.append(ans) + return + if l < n: + dfs(ans + '(', l + 1, r, n) + if r < l: + dfs(ans + ')', l, r + 1, n) + + self.res = [] + dfs('', 0, 0, n) + return self.res +``` + +### **Java** + + + +```java +class Solution { + public List generateParenthesis(int n) { + List res = new ArrayList<>(); + dfs(res, "", 0, 0, n); + return res; + } + + private void dfs(List res, String ans, int l, int r, int n) { + if (ans.length() == (n << 1)) { + res.add(ans); + return; + } + if (l < n) { + dfs(res, ans + "(", l + 1, r, n); + } + if (r < l) { + dfs(res, ans + ")", l, r + 1, n); + } + } +} +``` + +### **TypeScript** + +```ts +function generateParenthesis(n: number): string[] { + let ans = []; + dfs(n, 0, 0, '', ans); + return ans; +}; + +function dfs(n: number, left: number, right: number, str: string, ans: string[]) { + if (str.length == 2 * n) { + ans.push(str); + return; + } + if (left < n) { + dfs(n, left + 1, right, str + '(', ans); + } + if (right < left) { + dfs(n, left, right + 1, str + ')', ans); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector generateParenthesis(int n) { + vector res; + dfs(res, "", 0, 0, n); + return res; + } + +private: + void dfs(vector& res, string ans, int l, int r, int n) { + if (ans.size() == (n << 1)) { + res.push_back(ans); + return; + } + if (l < n) dfs(res, ans + "(", l + 1, r, n); + if (r < l) dfs(res, ans + ")", l, r + 1, n); + } +}; +``` + +### **Go** + +```go +func generateParenthesis(n int) []string { + res := new([]string) + dfs(res, "", 0, 0, n) + return *res +} + +func dfs(res *[]string, ans string, l, r, n int) { + if len(ans) == (n << 1) { + *res = append(*res, ans) + return + } + if l < n { + dfs(res, ans+"(", l+1, r, n) + } + if r < l { + dfs(res, ans+")", l, r+1, n) + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0023.leetcode23 Merge k Sorted Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0023.leetcode23 Merge k Sorted Lists-zh.md" new file mode 100644 index 00000000..cc2f1e99 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0023.leetcode23 Merge k Sorted Lists-zh.md" @@ -0,0 +1,367 @@ +# [23. 合并K个升序链表](https://leetcode-cn.com/problems/merge-k-sorted-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0023.Merge%20k%20Sorted%20Lists/README_EN.md) + +## 题目描述 + + + +

    给你一个链表数组,每个链表都已经按升序排列。

    + +

    请你将所有链表合并到一个升序链表中,返回合并后的链表。

    + +

     

    + +

    示例 1:

    + +
    输入:lists = [[1,4,5],[1,3,4],[2,6]]
    +输出:[1,1,2,3,4,4,5,6]
    +解释:链表数组如下:
    +[
    +  1->4->5,
    +  1->3->4,
    +  2->6
    +]
    +将它们合并到一个有序链表中得到。
    +1->1->2->3->4->4->5->6
    +
    + +

    示例 2:

    + +
    输入:lists = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    输入:lists = [[]]
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • k == lists.length
    • +
    • 0 <= k <= 10^4
    • +
    • 0 <= lists[i].length <= 500
    • +
    • -10^4 <= lists[i][j] <= 10^4
    • +
    • lists[i]升序 排列
    • +
    • lists[i].length 的总和不超过 10^4
    • +
    + + +## 解法 + + + +合并前后两个链表,结果放在后一个链表位置上,依次循环下去。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeKLists(self, lists: List[ListNode]) -> ListNode: + if not lists: + return None + n = len(lists) + for i in range(1, n): + lists[i] = self.mergeTwoLists(lists[i - 1], lists[i]) + return lists[n - 1] + + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + cur = dummy + while l1 and l2: + if l1.val <= l2.val: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + cur.next = l1 or l2 + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + int n; + if (lists == null || (n = lists.length) == 0) { + return null; + } + for (int i = 1; i < n; ++i) { + lists[i] = mergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; + } + + private ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + int n = lists.size(); + if (n == 0) { + return nullptr; + } + for (int i = 1; i < n; ++i) { + lists[i] = mergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; + } + +private: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + ListNode* cur = dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + cur->next = l1; + l1 = l1->next; + } else { + cur->next = l2; + l2 = l2->next; + } + cur = cur->next; + } + cur->next = l1 ? l1 : l2; + return dummy->next; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeKLists(lists []*ListNode) *ListNode { + n := len(lists) + if n == 0 { + return nil + } + for i := 1; i < n; i++ { + lists[i] = mergeTwoLists(lists[i-1], lists[i]) + } + return lists[n-1] +} + + func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + cur := dummy + for l1 != nil && l2 != nil { + if l1.Val <= l2.Val { + cur.Next = l1 + l1 = l1.Next + } else { + cur.Next = l2 + l2 = l2.Next + } + cur = cur.Next + } + if l1 != nil { + cur.Next = l1 + } else if l2 != nil { + cur.Next = l2 + } + return dummy.Next +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode[]} lists + * @return {ListNode} + */ +var mergeKLists = function(lists) { + const n = lists.length; + if (n == 0) { + return null; + } + for (let i = 1; i < n; ++i) { + lists[i] = mergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; +}; + +function mergeTwoLists(l1, l2) { + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode[]} lists +# @return {ListNode} +def merge_k_lists(lists) + n = lists.length + i = 1 + while i < n + lists[i] = merge_two_lists(lists[i - 1], lists[i]) + i += 1 + end + lists[n - 1] +end + +def merge_two_lists(l1, l2) + dummy = ListNode.new() + cur = dummy + while l1 && l2 + if l1.val <= l2.val + cur.next = l1 + l1 = l1.next + else + cur.next = l2 + l2 = l2.next + end + cur = cur.next + end + cur.next = l1 || l2 + dummy.next +end +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeKLists(ListNode[] lists) { + int n = lists.Length; + if (n == 0) { + return null; + } + for (int i = 1; i < n; ++i) { + lists[i] = MergeTwoLists(lists[i - 1], lists[i]); + } + return lists[n - 1]; + } + + private ListNode MergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0024.leetcode24 Swap Nodes in Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0024.leetcode24 Swap Nodes in Pairs-zh.md" new file mode 100644 index 00000000..5665a529 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0024.leetcode24 Swap Nodes in Pairs-zh.md" @@ -0,0 +1,233 @@ +# [24. 两两交换链表中的节点](https://leetcode-cn.com/problems/swap-nodes-in-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0024.Swap%20Nodes%20in%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

    + +

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4]
    +输出:[2,1,4,3]
    +
    + +

    示例 2:

    + +
    +输入:head = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:head = [1]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目在范围 [0, 100]
    • +
    • 0 <= Node.val <= 100
    • +
    + +

     

    + +

    进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)

    + +## 解法 + + + +设置虚拟头节点 dummy,pre 指针初始指向 dummy,遍历链表,每次交换 pre 后面的两个节点即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + dummy = ListNode(next=head) + pre, cur = dummy, head + while cur and cur.next: + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre, cur = cur, cur.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy, cur = head; + while (cur != null && cur.next != null) { + ListNode t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; + } + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + const dummy = new ListNode(0, head); + let pre = dummy; + let cur = head; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; + } + return dummy.next; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode *dummy = new ListNode(0, head); + ListNode *pre = dummy, *cur = head; + while (cur != nullptr && cur->next != nullptr) { + ListNode *t = cur->next; + cur->next = t->next; + t->next = cur; + pre->next = t; + pre = cur; + cur = cur->next; + } + return dummy->next; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func swapPairs(head *ListNode) *ListNode { + dummy := &ListNode{0, head} + pre, cur := dummy, head + for cur != nil && cur.Next != nil { + t := cur.Next + cur.Next = t.Next + t.Next = cur + pre.Next = t + pre = cur + cur = cur.Next + } + return dummy.Next +} +``` + +### **Ruby** + +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @return {ListNode} +def swap_pairs(head) + dummy = ListNode.new(0, head) + pre = dummy + cur = head + while !cur.nil? && !cur.next.nil? + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre = cur + cur = cur.next + end + dummy.next +end +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0025.leetcode25 Reverse Nodes in k-Group-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0025.leetcode25 Reverse Nodes in k-Group-zh.md" new file mode 100644 index 00000000..90870315 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0025.leetcode25 Reverse Nodes in k-Group-zh.md" @@ -0,0 +1,318 @@ +# [25. K 个一组翻转链表](https://leetcode-cn.com/problems/reverse-nodes-in-k-group) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/README_EN.md) + +## 题目描述 + + + +

    给你一个链表,每 个节点一组进行翻转,请你返回翻转后的链表。

    + +

    是一个正整数,它的值小于或等于链表的长度。

    + +

    如果节点总数不是 的整数倍,那么请将最后剩余的节点保持原有顺序。

    + +

    进阶:

    + +
      +
    • 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
    • +
    • 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4,5], k = 2
    +输出:[2,1,4,3,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [1,2,3,4,5], k = 3
    +输出:[3,2,1,4,5]
    +
    + +

    示例 3:

    + +
    +输入:head = [1,2,3,4,5], k = 1
    +输出:[1,2,3,4,5]
    +
    + +

    示例 4:

    + +
    +输入:head = [1], k = 1
    +输出:[1]
    +
    + +
      +
    + +

    提示:

    + +
      +
    • 列表中节点的数量在范围 sz
    • +
    • 1 <= sz <= 5000
    • +
    • 0 <= Node.val <= 1000
    • +
    • 1 <= k <= sz
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseKGroup(self, head: ListNode, k: int) -> ListNode: + def reverseList(head): + pre, p = None, head + while p: + q = p.next + p.next = pre + pre = p + p = q + return pre + + dummy = ListNode(next=head) + pre = cur = dummy + while cur.next: + for _ in range(k): + cur = cur.next + if cur is None: + return dummy.next + t = cur.next + cur.next = None + start = pre.next + pre.next = reverseList(start) + start.next = t + pre = start + cur = pre + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy, cur = dummy; + while (cur.next != null) { + for (int i = 0; i < k && cur != null; ++i) { + cur = cur.next; + } + if (cur == null) { + return dummy.next; + } + ListNode t = cur.next; + cur.next = null; + ListNode start = pre.next; + pre.next = reverseList(start); + start.next = t; + pre = start; + cur = pre; + } + return dummy.next; + } + + private ListNode reverseList(ListNode head) { + ListNode pre = null, p = head; + while (p != null) { + ListNode q = p.next; + p.next = pre; + pre = p; + p = q; + } + return pre; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseKGroup(head: ListNode | null, k: number): ListNode | null { + let dummy = new ListNode(0, head); + let pre = dummy; + // pre->head-> ... ->tail-> next + while (head != null) { + let tail = pre; + for (let i=0; i next -> ... -> tail -> pre + while (pre != tail) { + let t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + return [tail, head] +} +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + dummy := &ListNode{0, head} + pre := dummy + cur := dummy + for cur.Next != nil { + for i := 0; i < k && cur != nil; i++ { + cur = cur.Next + } + if cur == nil { + return dummy.Next + } + t := cur.Next + cur.Next = nil + start := pre.Next + pre.Next = reverseList(start) + start.Next = t + pre = start + cur = pre + } + return dummy.Next +} + +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + dummyHead := &ListNode{} + cur := head + for cur != nil { + tmp := cur.Next + cur.Next = dummyHead.Next + dummyHead.Next = cur + cur = tmp + } + return dummyHead.Next +} +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseKGroup(ListNode head, int k) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy, cur = dummy; + while (cur.next != null) + { + for (int i = 0; i < k && cur != null; ++i) + { + cur = cur.next; + } + if (cur == null) + { + return dummy.next; + } + ListNode t = cur.next; + cur.next = null; + ListNode start = pre.next; + pre.next = ReverseList(start); + start.next = t; + pre = start; + cur = pre; + } + return dummy.next; + } + + private ListNode ReverseList(ListNode head) { + ListNode pre = null, p = head; + while (p != null) + { + ListNode q = p.next; + p.next = pre; + pre = p; + p = q; + } + return pre; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0026.leetcode26 Remove Duplicates from Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0026.leetcode26 Remove Duplicates from Sorted Array-zh.md" new file mode 100644 index 00000000..7a54047e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0026.leetcode26 Remove Duplicates from Sorted Array-zh.md" @@ -0,0 +1,183 @@ +# [26. 删除有序数组中的重复项](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0026.Remove%20Duplicates%20from%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。

    + +

    不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

    + +

     

    + +

    说明:

    + +

    为什么返回数值是整数,但输出的答案是数组呢?

    + +

    请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

    + +

    你可以想象内部操作如下:

    + +
    +// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
    +int len = removeDuplicates(nums);
    +
    +// 在函数里修改输入数组对于调用者是可见的。
    +// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
    +for (int i = 0; i < len; i++) {
    +    print(nums[i]);
    +}
    +
    +  + +

    示例 1:

    + +
    +输入:nums = [1,1,2]
    +输出:2, nums = [1,2]
    +解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 不需要考虑数组中超出新长度后面的元素。
    +
    + +

    示例 2:

    + +
    +输入:nums = [0,0,1,1,1,2,2,3,3,4]
    +输出:5, nums = [0,1,2,3,4]
    +解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 3 * 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • nums 已按升序排列
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + cnt, n = 0, len(nums) + for i in range(1, n): + if nums[i] == nums[i - 1]: + cnt += 1 + else: + nums[i - cnt] = nums[i] + return n - cnt +``` + +### **Java** + + + +```java +class Solution { + public int removeDuplicates(int[] nums) { + int cnt = 0, n = nums.length; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function (nums) { + let cnt = 0; + const n = nums.length; + for (let i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; +}; +``` + +### **Go** + +```go +func removeDuplicates(nums []int) int { + cnt := 0 + n := len(nums) + for i := 1; i < n; i++ { + if nums[i] == nums[i - 1] { + cnt++ + } else { + nums[i - cnt] = nums[i] + } + } + return n - cnt +} +``` + +### **C++** + +```cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + int cnt = 0, n = nums.size(); + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +}; +``` + +### **C#** + +```cs +public class Solution { + public int RemoveDuplicates(int[] nums) { + int cnt = 0; + int n = nums.Length; + for (int i = 1; i < n; ++i) + { + if (nums[i] == nums[i - 1]) + { + ++cnt; + } + else + { + nums[i - cnt] = nums[i]; + } + } + return n - cnt; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0027.leetcode27 Remove Element-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0027.leetcode27 Remove Element-zh.md" new file mode 100644 index 00000000..fcbba857 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0027.leetcode27 Remove Element-zh.md" @@ -0,0 +1,161 @@ +# [27. 移除元素](https://leetcode-cn.com/problems/remove-element) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0027.Remove%20Element/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。

    + +

    不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组

    + +

    元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

    + +

     

    + +

    说明:

    + +

    为什么返回数值是整数,但输出的答案是数组呢?

    + +

    请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

    + +

    你可以想象内部操作如下:

    + +
    +// nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝
    +int len = removeElement(nums, val);
    +
    +// 在函数里修改输入数组对于调用者是可见的。
    +// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
    +for (int i = 0; i < len; i++) {
    +    print(nums[i]);
    +}
    +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3,2,2,3], val = 3
    +输出:2, nums = [2,2]
    +解释:函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。例如,函数返回的新长度为 2 ,而 nums = [2,2,3,3] 或 nums = [2,2,0,0],也会被视作正确答案。
    +
    + +

    示例 2:

    + +
    +输入:nums = [0,1,2,2,3,0,4,2], val = 2
    +输出:5, nums = [0,1,4,0,3]
    +解释:函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 50
    • +
    • 0 <= val <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + cnt, n = 0, len(nums) + for i in range(n): + if nums[i] == val: + cnt += 1 + else: + nums[i - cnt] = nums[i] + return n - cnt +``` + +### **Java** + + + +```java +class Solution { + public int removeElement(int[] nums, int val) { + int cnt = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + if (nums[i] == val) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int removeElement(vector& nums, int val) { + int cnt = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + if (nums[i] == val) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function (nums, val) { + let cnt = 0; + const n = nums.length; + for (let i = 0; i < n; ++i) { + if (nums[i] == val) ++cnt; + else nums[i - cnt] = nums[i]; + } + return n - cnt; +}; +``` + +### **Go** + +```go +func removeElement(nums []int, val int) int { + cnt, n := 0, len(nums) + for i := 0; i < n; i++ { + if (nums[i] == val) { + cnt++ + } else { + nums[i - cnt] = nums[i] + } + } + return n - cnt +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0028.leetcode28 Implement strStr()-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0028.leetcode28 Implement strStr()-zh.md" new file mode 100644 index 00000000..036b178b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0028.leetcode28 Implement strStr()-zh.md" @@ -0,0 +1,82 @@ +# [28. 实现 strStr()](https://leetcode-cn.com/problems/implement-strstr) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0028.Implement%20strStr%28%29/README_EN.md) + +## 题目描述 + + + +

    实现 strStr() 函数。

    + +

    给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1

    + +

     

    + +

    说明:

    + +

    当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

    + +

    对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

    + +

     

    + +

    示例 1:

    + +
    +输入:haystack = "hello", needle = "ll"
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:haystack = "aaaaa", needle = "bba"
    +输出:-1
    +
    + +

    示例 3:

    + +
    +输入:haystack = "", needle = ""
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= haystack.length, needle.length <= 5 * 104
    • +
    • haystackneedle 仅由小写英文字符组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0029.leetcode29 Divide Two Integers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0029.leetcode29 Divide Two Integers-zh.md" new file mode 100644 index 00000000..19b66573 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0029.leetcode29 Divide Two Integers-zh.md" @@ -0,0 +1,68 @@ +# [29. 两数相除](https://leetcode-cn.com/problems/divide-two-integers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0029.Divide%20Two%20Integers/README_EN.md) + +## 题目描述 + + + +

    给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。

    + +

    返回被除数 dividend 除以除数 divisor 得到的商。

    + +

    整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2

    + +

     

    + +

    示例 1:

    + +
    输入: dividend = 10, divisor = 3
    +输出: 3
    +解释: 10/3 = truncate(3.33333..) = truncate(3) = 3
    + +

    示例 2:

    + +
    输入: dividend = 7, divisor = -3
    +输出: -2
    +解释: 7/-3 = truncate(-2.33333..) = -2
    + +

     

    + +

    提示:

    + +
      +
    • 被除数和除数均为 32 位有符号整数。
    • +
    • 除数不为 0。
    • +
    • 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0030.leetcode30 Substring with Concatenation of All Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0030.leetcode30 Substring with Concatenation of All Words-zh.md" new file mode 100644 index 00000000..707f06e4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0030.leetcode30 Substring with Concatenation of All Words-zh.md" @@ -0,0 +1,63 @@ +# [30. 串联所有单词的子串](https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0030.Substring%20with%20Concatenation%20of%20All%20Words/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

    + +

    注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

    + +

     

    + +

    示例 1:

    + +
    输入:
    +  s = "barfoothefoobarman",
    +  words = ["foo","bar"]
    +输出:[0,9]
    +解释:
    +从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。
    +输出的顺序不重要, [9,0] 也是有效答案。
    +
    + +

    示例 2:

    + +
    输入:
    +  s = "wordgoodgoodgoodbestword",
    +  words = ["word","good","best","word"]
    +输出:[]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0031.leetcode31 Next Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0031.leetcode31 Next Permutation-zh.md" new file mode 100644 index 00000000..00303ad0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0031.leetcode31 Next Permutation-zh.md" @@ -0,0 +1,83 @@ +# [31. 下一个排列](https://leetcode-cn.com/problems/next-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0031.Next%20Permutation/README_EN.md) + +## 题目描述 + + + +

    实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

    + +

    如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

    + +

    必须 原地 修改,只允许使用额外常数空间。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3]
    +输出:[1,3,2]
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,2,1]
    +输出:[1,2,3]
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,1,5]
    +输出:[1,5,1]
    +
    + +

    示例 4:

    + +
    +输入:nums = [1]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0032.leetcode32 Longest Valid Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0032.leetcode32 Longest Valid Parentheses-zh.md" new file mode 100644 index 00000000..fb875bb7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0032.leetcode32 Longest Valid Parentheses-zh.md" @@ -0,0 +1,78 @@ +# [32. 最长有效括号](https://leetcode-cn.com/problems/longest-valid-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0032.Longest%20Valid%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

    + +

     

    + +
    +
    +

    示例 1:

    + +
    +输入:s = "(()"
    +输出:2
    +解释:最长有效括号子串是 "()"
    +
    + +

    示例 2:

    + +
    +输入:s = ")()())"
    +输出:4
    +解释:最长有效括号子串是 "()()"
    +
    + +

    示例 3:

    + +
    +输入:s = ""
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 3 * 104
    • +
    • s[i]'('')'
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0033.leetcode33 Search in Rotated Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0033.leetcode33 Search in Rotated Sorted Array-zh.md" new file mode 100644 index 00000000..cdb94ce2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0033.leetcode33 Search in Rotated Sorted Array-zh.md" @@ -0,0 +1,170 @@ +# [33. 搜索旋转排序数组](https://leetcode-cn.com/problems/search-in-rotated-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0033.Search%20in%20Rotated%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    整数数组 nums 按升序排列,数组中的值 互不相同

    + +

    在传递给函数之前,nums 在预先未知的某个下标 k0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2]

    + +

    给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [4,5,6,7,0,1,2], target = 0
    +输出:4
    +
    + +

    示例 2:

    + +
    +输入:nums = [4,5,6,7,0,1,2], target = 3
    +输出:-1
    + +

    示例 3:

    + +
    +输入:nums = [1], target = 0
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5000
    • +
    • -10^4 <= nums[i] <= 10^4
    • +
    • nums 中的每个值都 独一无二
    • +
    • 题目数据保证 nums 在预先未知的某个下标上进行了旋转
    • +
    • -10^4 <= target <= 10^4
    • +
    + +

     

    + +

    进阶:你可以设计一个时间复杂度为 O(log n) 的解决方案吗?

    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def search(self, nums: List[int], target: int) -> int: + l, r = 0, len(nums) - 1 + while l <= r: + mid = (l + r) >> 1 + if nums[mid] == target: + return mid + if nums[mid] > target: + if nums[mid] >= nums[r] and target < nums[l]: + l = mid + 1 + else: + r = mid - 1 + else: + if nums[mid] <= nums[l] and target > nums[r]: + r = mid - 1 + else: + l = mid + 1 + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int search(int[] nums, int target) { + int l = 0, r = nums.length - 1; + while (l <= r) { + int mid = (l + r) >>> 1; + if (nums[mid] == target) return mid; + if (nums[mid] > target) { + if (nums[mid] >= nums[r] && target < nums[l]) l = mid + 1; + else r = mid - 1; + } else { + if (nums[mid] <= nums[l] && target > nums[r]) r = mid - 1; + else l = mid + 1; + } + } + return -1; + } +} +``` + +### **C++** + + + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int l = 0, r = nums.size() - 1; + while (l <= r) { + int mid = (l + r) >> 1; + if (nums[mid] == target) return mid; + if (nums[mid] > target) { + if (nums[mid] >= nums[r] && target < nums[l]) l = mid + 1; + else r = mid - 1; + } else { + if (nums[mid] <= nums[l] && target > nums[r]) r = mid - 1; + else l = mid + 1; + } + } + return -1; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + let l = 0, r = nums.length - 1; + if (l > r) return -1; + while (l <= r) { + let mid = l + Math.floor((r - l) / 2); + if (nums[mid] === target) return mid; + else if (nums[mid] <= nums[r] && target <= nums[r] && target >= nums[mid]) + l = mid + 1; + else if (nums[mid] >= nums[l] && target <= nums[mid] && target >= nums[l]) + r = mid - 1; + else if (nums[mid] >= nums[r]) + l = mid + 1; + else if (nums[mid] <= nums[l]) + r = mid - 1; + else return -1; + } + return -1; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0034.leetcode34 Find First and Last Position of Element in Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0034.leetcode34 Find First and Last Position of Element in Sorted Array-zh.md" new file mode 100644 index 00000000..c8923fa2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0034.leetcode34 Find First and Last Position of Element in Sorted Array-zh.md" @@ -0,0 +1,243 @@ +# [34. 在排序数组中查找元素的第一个和最后一个位置](https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0034.Find%20First%20and%20Last%20Position%20of%20Element%20in%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

    + +

    如果数组中不存在目标值 target,返回 [-1, -1]

    + +

    进阶:

    + +
      +
    • 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [5,7,7,8,8,10], target = 8
    +输出:[3,4]
    + +

    示例 2:

    + +
    +输入:nums = [5,7,7,8,8,10], target = 6
    +输出:[-1,-1]
    + +

    示例 3:

    + +
    +输入:nums = [], target = 0
    +输出:[-1,-1]
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 105
    • +
    • -109 <= nums[i] <= 109
    • +
    • nums 是一个非递减数组
    • +
    • -109 <= target <= 109
    • +
    + + +## 解法 + + + +二分查找。 + +两遍二分,分别查找出左边界和右边界。 + + + +### **Python3** + + + +```python +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + if len(nums) == 0: + return [-1, -1] + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + if nums[left] != target: + return [-1, -1] + l, right = left, len(nums) - 1 + while left < right: + mid = (left + right + 1) >> 1 + if nums[mid] <= target: + left = mid + else: + right = mid - 1 + return [l, left] +``` + +### **Java** + + + +```java +class Solution { + public int[] searchRange(int[] nums, int target) { + if (nums.length == 0) { + return new int[]{-1, -1}; + } + // find first position + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >>> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (nums[left] != target) { + return new int[]{-1, -1}; + } + int l = left; + + // find last position + right = nums.length - 1; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return new int[]{l, left}; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector searchRange(vector& nums, int target) { + if (nums.size() == 0) { + return vector{-1, -1}; + } + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (nums[left] != target) { + return vector{-1, -1}; + } + int l = left; + right = nums.size() - 1; + while (left < right) { + int mid = left + right + 1 >> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return vector{l, left}; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var searchRange = function(nums, target) { + if (nums.length == 0) { + return [-1, -1]; + } + let left = 0; + let right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + if (nums[left] != target) { + return [-1, -1]; + } + let l = left; + right = nums.length - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return [l, left]; +}; +``` + +### **Go** + +```go +func searchRange(nums []int, target int) []int { + if len(nums) == 0 { + return []int{-1, -1} + } + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= target { + right = mid + } else { + left = mid + 1 + } + } + if nums[left] != target { + return []int{-1, -1} + } + l := left + right = len(nums) - 1 + for left < right { + mid := (left + right + 1) >> 1 + if nums[mid] <= target { + left = mid + } else { + right = mid - 1 + } + } + return []int{l, left} +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0035.leetcode35 Search Insert Position-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0035.leetcode35 Search Insert Position-zh.md" new file mode 100644 index 00000000..81c17062 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0035.leetcode35 Search Insert Position-zh.md" @@ -0,0 +1,150 @@ +# [35. 搜索插入位置](https://leetcode-cn.com/problems/search-insert-position) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0035.Search%20Insert%20Position/README_EN.md) + +## 题目描述 + + + +

    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

    + +

    你可以假设数组中无重复元素。

    + +

    示例 1:

    + +
    输入: [1,3,5,6], 5
    +输出: 2
    +
    + +

    示例 2:

    + +
    输入: [1,3,5,6], 2
    +输出: 1
    +
    + +

    示例 3:

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

    示例 4:

    + +
    输入: [1,3,5,6], 0
    +输出: 0
    +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int searchInsert(int[] nums, int target) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >>> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int searchInsert(vector& nums, int target) { + int left = 0, right = nums.size(); + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func searchInsert(nums []int, target int) int { + left, right := 0, len(nums) + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= target { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var searchInsert = function(nums, target) { + let left = 0; + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0036.leetcode36 Valid Sudoku-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0036.leetcode36 Valid Sudoku-zh.md" new file mode 100644 index 00000000..3dd2be65 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0036.leetcode36 Valid Sudoku-zh.md" @@ -0,0 +1,222 @@ +# [36. 有效的数独](https://leetcode-cn.com/problems/valid-sudoku) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0036.Valid%20Sudoku/README_EN.md) + +## 题目描述 + + + +

    请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。

    + +
      +
    1. 数字 1-9 在每一行只能出现一次。
    2. +
    3. 数字 1-9 在每一列只能出现一次。
    4. +
    5. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
    6. +
    + +

    数独部分空格内已填入了数字,空白格用 '.' 表示。

    + +

    注意:

    + +
      +
    • 一个有效的数独(部分已被填充)不一定是可解的。
    • +
    • 只需要根据以上规则,验证已经填入的数字是否有效即可。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:board = 
    +[["5","3",".",".","7",".",".",".","."]
    +,["6",".",".","1","9","5",".",".","."]
    +,[".","9","8",".",".",".",".","6","."]
    +,["8",".",".",".","6",".",".",".","3"]
    +,["4",".",".","8",".","3",".",".","1"]
    +,["7",".",".",".","2",".",".",".","6"]
    +,[".","6",".",".",".",".","2","8","."]
    +,[".",".",".","4","1","9",".",".","5"]
    +,[".",".",".",".","8",".",".","7","9"]]
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:board = 
    +[["8","3",".",".","7",".",".",".","."]
    +,["6",".",".","1","9","5",".",".","."]
    +,[".","9","8",".",".",".",".","6","."]
    +,["8",".",".",".","6",".",".",".","3"]
    +,["4",".",".","8",".","3",".",".","1"]
    +,["7",".",".",".","2",".",".",".","6"]
    +,[".","6",".",".",".",".","2","8","."]
    +,[".",".",".","4","1","9",".",".","5"]
    +,[".",".",".",".","8",".",".","7","9"]]
    +输出:false
    +解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
    + +

     

    + +

    提示:

    + +
      +
    • board.length == 9
    • +
    • board[i].length == 9
    • +
    • board[i][j] 是一位数字或者 '.'
    • +
    + +## 解法 + + + +求第 i 行、第 j 列,以及第 k 个 `3*3` 宫格是否含有相同数字,如果是,则返回 false。遍历结束,返回 true。 + + + +### **Python3** + + + +```python +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + row = [[False] * 9 for _ in range(9)] + col = [[False] * 9 for _ in range(9)] + sub = [[False] * 9 for _ in range(9)] + for i in range(9): + for j in range(9): + c = board[i][j] + if c == '.': + continue + num = int(c) - 1 + k = i // 3 * 3 + j // 3 + if row[i][num] or col[j][num] or sub[k][num]: + return False + row[i][num] = True + col[j][num] = True + sub[k][num] = True + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isValidSudoku(char[][] board) { + boolean[][] row = new boolean[9][9]; + boolean[][] col = new boolean[9][9]; + boolean[][] sub = new boolean[9][9]; + for (int i = 0; i < 9; ++i) { + for (int j = 0; j < 9; ++j) { + char c = board[i][j]; + if (c == '.') { + continue; + } + int num = c - '0' - 1; + int k = i / 3 * 3 + j / 3; + if (row[i][num] || col[j][num] || sub[k][num]) { + return false; + } + row[i][num] = true; + col[j][num] = true; + sub[k][num] = true; + } + } + return true; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isValidSudoku(vector>& board) { + vector> row(9, vector(9, false)); + vector> col(9, vector(9, false)); + vector> sub(9, vector(9, false)); + for (int i = 0; i < 9; ++i) { + for (int j = 0; j < 9; ++j) { + char c = board[i][j]; + if (c == '.') continue; + int num = c - '0' - 1; + int k = i / 3 * 3 + j / 3; + if (row[i][num] || col[j][num] || sub[k][num]) { + return false; + } + row[i][num] = true; + col[j][num] = true; + sub[k][num] = true; + } + } + return true; + } +}; +``` + +### **Go** + +```go +func isValidSudoku(board [][]byte) bool { + row, col, sub := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} + for i := 0; i < 9; i++ { + for j := 0; j < 9; j++ { + num := board[i][j] - byte('1') + if num < 0 || num > 9 { + continue + } + k := i/3*3 + j/3 + if row[i][num] || col[j][num] || sub[k][num] { + return false + } + row[i][num] = true + col[j][num] = true + sub[k][num] = true + } + } + return true +} +``` + +### **JavaScript** + +```js +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function(board) { + let row = [...Array(9)].map(() => Array(9).fill(false)); + let col = [...Array(9)].map(() => Array(9).fill(false)); + let sub = [...Array(9)].map(() => Array(9).fill(false)); + for (let i = 0; i < 9; ++i) { + for (let j = 0; j < 9; ++j) { + const num = board[i][j].charCodeAt() - '1'.charCodeAt(); + if (num < 0 || num > 9) { + continue; + } + const k = Math.floor(i / 3) * 3 + Math.floor(j / 3); + if (row[i][num] || col[j][num] || sub[k][num]) { + return false; + } + row[i][num] = true; + col[j][num] = true; + sub[k][num] = true; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0037.leetcode37 Sudoku Solver-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0037.leetcode37 Sudoku Solver-zh.md" new file mode 100644 index 00000000..08724c76 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0037.leetcode37 Sudoku Solver-zh.md" @@ -0,0 +1,79 @@ +# [37. 解数独](https://leetcode-cn.com/problems/sudoku-solver) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0037.Sudoku%20Solver/README_EN.md) + +## 题目描述 + + + +

    编写一个程序,通过填充空格来解决数独问题。

    + +

    数独的解法需 遵循如下规则

    + +
      +
    1. 数字 1-9 在每一行只能出现一次。
    2. +
    3. 数字 1-9 在每一列只能出现一次。
    4. +
    5. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
    6. +
    + +

    数独部分空格内已填入了数字,空白格用 '.' 表示。

    + +

     

    + +
    +
    +
    +

    示例:

    + +
    +输入:board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
    +输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
    +解释:输入的数独如上图所示,唯一有效的解决方案如下所示:
    +
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    • board.length == 9
    • +
    • board[i].length == 9
    • +
    • board[i][j] 是一位数字或者 '.'
    • +
    • 题目数据 保证 输入数独仅有一个解
    • +
    +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0038.leetcode38 Count and Say-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0038.leetcode38 Count and Say-zh.md" new file mode 100644 index 00000000..0b9847ed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0038.leetcode38 Count and Say-zh.md" @@ -0,0 +1,101 @@ +# [38. 外观数列](https://leetcode-cn.com/problems/count-and-say) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0038.Count%20and%20Say/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 n ,输出外观数列的第 n 项。

    + +

    「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。

    + +

    你可以将其视作是由递归公式定义的数字字符串序列:

    + +
      +
    • countAndSay(1) = "1"
    • +
    • countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
    • +
    + +

    前五项如下:

    + +
    +1.     1
    +2.     11
    +3.     21
    +4.     1211
    +5.     111221
    +第一项是数字 1 
    +描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"
    +描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"
    +描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"
    +描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"
    +
    + +

    描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。

    + +

    例如,数字字符串 "3322251" 的描述如下图:

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    +输入:n = 1
    +输出:"1"
    +解释:这是一个基本样例。
    +
    + +

    示例 2:

    + +
    +输入:n = 4
    +输出:"1211"
    +解释:
    +countAndSay(1) = "1"
    +countAndSay(2) = 读 "1" = 一 个 1 = "11"
    +countAndSay(3) = 读 "11" = 二 个 1 = "21"
    +countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 30
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0039.leetcode39 Combination Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0039.leetcode39 Combination Sum-zh.md" new file mode 100644 index 00000000..8bec593b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0039.leetcode39 Combination Sum-zh.md" @@ -0,0 +1,80 @@ +# [39. 组合总和](https://leetcode-cn.com/problems/combination-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0039.Combination%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    + +

    candidates 中的数字可以无限制重复被选取。

    + +

    说明:

    + +
      +
    • 所有数字(包括 target)都是正整数。
    • +
    • 解集不能包含重复的组合。 
    • +
    + +

    示例 1:

    + +
    输入:candidates = [2,3,6,7], target = 7,
    +所求解集为:
    +[
    +  [7],
    +  [2,2,3]
    +]
    +
    + +

    示例 2:

    + +
    输入:candidates = [2,3,5], target = 8,
    +所求解集为:
    +[
    +  [2,2,2,2],
    +  [2,3,3],
    +  [3,5]
    +]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= candidates.length <= 30
    • +
    • 1 <= candidates[i] <= 200
    • +
    • candidate 中的每个元素都是独一无二的。
    • +
    • 1 <= target <= 500
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0040.leetcode40 Combination Sum II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0040.leetcode40 Combination Sum II-zh.md" new file mode 100644 index 00000000..3783c442 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0040.leetcode40 Combination Sum II-zh.md" @@ -0,0 +1,70 @@ +# [40. 组合总和 II](https://leetcode-cn.com/problems/combination-sum-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0040.Combination%20Sum%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    + +

    candidates 中的每个数字在每个组合中只能使用一次。

    + +

    说明:

    + +
      +
    • 所有数字(包括目标数)都是正整数。
    • +
    • 解集不能包含重复的组合。 
    • +
    + +

    示例 1:

    + +
    输入: candidates = [10,1,2,7,6,1,5], target = 8,
    +所求解集为:
    +[
    +  [1, 7],
    +  [1, 2, 5],
    +  [2, 6],
    +  [1, 1, 6]
    +]
    +
    + +

    示例 2:

    + +
    输入: candidates = [2,5,2,1,2], target = 5,
    +所求解集为:
    +[
    +  [1,2,2],
    +  [5]
    +]
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0041.leetcode41 First Missing Positive-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0041.leetcode41 First Missing Positive-zh.md" new file mode 100644 index 00000000..5eb9e690 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0041.leetcode41 First Missing Positive-zh.md" @@ -0,0 +1,76 @@ +# [41. 缺失的第一个正数](https://leetcode-cn.com/problems/first-missing-positive) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0041.First%20Missing%20Positive/README_EN.md) + +## 题目描述 + + + +

    给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。

    + +

     

    + +

    进阶:你可以实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案吗?

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,0]
    +输出:3
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,4,-1,1]
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:nums = [7,8,9,11,12]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 300
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0042.leetcode42 Trapping Rain Water-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0042.leetcode42 Trapping Rain Water-zh.md" new file mode 100644 index 00000000..39487ed6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0042.leetcode42 Trapping Rain Water-zh.md" @@ -0,0 +1,206 @@ +# [42. 接雨水](https://leetcode-cn.com/problems/trapping-rain-water) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0042.Trapping%20Rain%20Water/README_EN.md) + +## 题目描述 + + + +

    给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
    +输出:6
    +解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 
    +
    + +

    示例 2:

    + +
    +输入:height = [4,2,0,3,2,5]
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == height.length
    • +
    • 0 <= n <= 3 * 104
    • +
    • 0 <= height[i] <= 105
    • +
    + + +## 解法 + + + +动态规划法。 + +对于下标 i,水能达到的最大高度等于下标 i 左右两侧的最大高度的最小值,再减去 `height[i]` 就能得到当前柱子所能存的水量。 + +同[面试题 17.21. 直方图的水量](/lcci/17.21.Volume%20of%20Histogram/README.md) + + + +### **Python3** + + + +```python +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n < 3: + return 0 + + lmx, rmx = [height[0]] * n, [height[n - 1]] * n + for i in range(1, n): + lmx[i] = max(lmx[i - 1], height[i]) + rmx[n - 1 - i] = max(rmx[n - i], height[n - 1 - i]) + + res = 0 + for i in range(n): + res += min(lmx[i], rmx[i]) - height[i] + return res +``` + +### **Java** + + + +```java +class Solution { + public int trap(int[] height) { + int n = height.length; + if (n < 3) { + return 0; + } + + int[] lmx = new int[n]; + int[] rmx = new int[n]; + lmx[0] = height[0]; + rmx[n - 1] = height[n - 1]; + for (int i = 1; i < n; ++i) { + lmx[i] = Math.max(lmx[i - 1], height[i]); + rmx[n - 1 - i] = Math.max(rmx[n - i], height[n - i - 1]); + } + + int res = 0; + for (int i = 0; i < n; ++i) { + res += Math.min(lmx[i], rmx[i]) - height[i]; + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function trap(height: number[]): number { + let ans = 0; + let left = 0, right = height.length - 1; + let maxLeft = 0, maxRight = 0; + while (left < right) { + if (height[left] < height[right]) { + // move left + if (height[left] >= maxLeft) { + maxLeft = height[left]; + } else { + ans += (maxLeft - height[left]); + } + ++left; + } else { + // move right + if (height[right] >= maxRight) { + maxRight = height[right]; + } else { + ans += (maxRight - height[right]); + } + --right; + } + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + if (n < 3) { + return 0; + } + + vector lmx(n, height[0]); + vector rmx(n, height[n - 1]); + for (int i = 1; i < n; ++i) { + lmx[i] = max(lmx[i - 1], height[i]); + rmx[n - 1 - i] = max(rmx[n - i], height[n - 1 - i]); + } + + int res = 0; + for (int i = 0; i < n; ++i) { + res += min(lmx[i], rmx[i]) - height[i]; + } + return res; + } +}; +``` + +### **Go** + +```go +func trap(height []int) int { + n := len(height) + if n < 3 { + return 0 + } + + lmx, rmx := make([]int, n), make([]int, n) + lmx[0], rmx[n-1] = height[0], height[n-1] + for i := 1; i < n; i++ { + lmx[i] = max(lmx[i-1], height[i]) + rmx[n-1-i] = max(rmx[n-i], height[n-1-i]) + } + + res := 0 + for i := 0; i < n; i++ { + res += min(lmx[i], rmx[i]) - height[i] + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0043.leetcode43 Multiply Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0043.leetcode43 Multiply Strings-zh.md" new file mode 100644 index 00000000..80bc1f29 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0043.leetcode43 Multiply Strings-zh.md" @@ -0,0 +1,59 @@ +# [43. 字符串相乘](https://leetcode-cn.com/problems/multiply-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0043.Multiply%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

    + +

    示例 1:

    + +
    输入: num1 = "2", num2 = "3"
    +输出: "6"
    + +

    示例 2:

    + +
    输入: num1 = "123", num2 = "456"
    +输出: "56088"
    + +

    说明:

    + +
      +
    1. num1 和 num2 的长度小于110。
    2. +
    3. num1 和 num2 只包含数字 0-9
    4. +
    5. num1 和 num2 均不以零开头,除非是数字 0 本身。
    6. +
    7. 不能使用任何标准库的大数类型(比如 BigInteger)直接将输入转换为整数来处理
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0044.leetcode44 Wildcard Matching-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0044.leetcode44 Wildcard Matching-zh.md" new file mode 100644 index 00000000..55f9ca8c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0044.leetcode44 Wildcard Matching-zh.md" @@ -0,0 +1,95 @@ +# [44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0044.Wildcard%20Matching/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。

    + +
    '?' 可以匹配任何单个字符。
    +'*' 可以匹配任意字符串(包括空字符串)。
    +
    + +

    两个字符串完全匹配才算匹配成功。

    + +

    说明:

    + +
      +
    • s 可能为空,且只包含从 a-z 的小写字母。
    • +
    • p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *
    • +
    + +

    示例 1:

    + +
    输入:
    +s = "aa"
    +p = "a"
    +输出: false
    +解释: "a" 无法匹配 "aa" 整个字符串。
    + +

    示例 2:

    + +
    输入:
    +s = "aa"
    +p = "*"
    +输出: true
    +解释: '*' 可以匹配任意字符串。
    +
    + +

    示例 3:

    + +
    输入:
    +s = "cb"
    +p = "?a"
    +输出: false
    +解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
    +
    + +

    示例 4:

    + +
    输入:
    +s = "adceb"
    +p = "*a*b"
    +输出: true
    +解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce".
    +
    + +

    示例 5:

    + +
    输入:
    +s = "acdcb"
    +p = "a*c?b"
    +输出: false
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0045.leetcode45 Jump Game II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0045.leetcode45 Jump Game II-zh.md" new file mode 100644 index 00000000..fc2b63d8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0045.leetcode45 Jump Game II-zh.md" @@ -0,0 +1,144 @@ +# [45. 跳跃游戏 II](https://leetcode-cn.com/problems/jump-game-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0045.Jump%20Game%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组,你最初位于数组的第一个位置。

    + +

    数组中的每个元素代表你在该位置可以跳跃的最大长度。

    + +

    你的目标是使用最少的跳跃次数到达数组的最后一个位置。

    + +

    示例:

    + +
    输入: [2,3,1,1,4]
    +输出: 2
    +解释: 跳到最后一个位置的最小跳跃数是 2。
    +     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
    +
    + +

    说明:

    + +

    假设你总是可以到达数组的最后一个位置。

    + + +## 解法 + + + +贪心。 + + + +### **Python3** + + + +```python +class Solution: + def jump(self, nums: List[int]) -> int: + end = mx = steps = 0 + for i, num in enumerate(nums[:-1]): + mx = max(mx, i + num) + if i == end: + end = mx + steps += 1 + return steps +``` + +### **Java** + + + +```java +class Solution { + public int jump(int[] nums) { + int end = 0; + int mx = 0; + int steps = 0; + for (int i = 0; i < nums.length - 1; ++i) { + mx = Math.max(mx, i + nums[i]); + if (i == end) { + end = mx; + ++steps; + } + } + return steps; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int jump(vector& nums) { + int mx = 0, steps = 0, end = 0; + for (int i = 0; i < nums.size() - 1; ++i) { + mx = max(mx, i + nums[i]); + if (i == end) { + end = mx; + ++steps; + } + } + return steps; + } +}; +``` + +### **Go** + +```go +func jump(nums []int) int { + mx, steps, end := 0, 0, 0 + for i := 0; i < len(nums)-1; i++ { + mx = max(mx, i+nums[i]) + if i == end { + end = mx + steps++ + } + } + return steps +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int Jump(int[] nums) { + int end = 0; + int mx = 0; + int steps = 0; + for (int i = 0; i < nums.Length - 1; ++i) + { + mx = Math.Max(mx, i + nums[i]); + if (i == end) + { + end = mx; + ++steps; + } + } + return steps; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0046.leetcode46 Permutations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0046.leetcode46 Permutations-zh.md" new file mode 100644 index 00000000..f6493b5d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0046.leetcode46 Permutations-zh.md" @@ -0,0 +1,179 @@ +# [46. 全排列](https://leetcode-cn.com/problems/permutations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0046.Permutations/README_EN.md) + +## 题目描述 + + + +

    给定一个 没有重复 数字的序列,返回其所有可能的全排列。

    + +

    示例:

    + +
    输入: [1,2,3]
    +输出:
    +[
    +  [1,2,3],
    +  [1,3,2],
    +  [2,1,3],
    +  [2,3,1],
    +  [3,1,2],
    +  [3,2,1]
    +]
    + + +## 解法 + + + + + +### **Python3** + + + +回溯法: + +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(nums, i, res, path, used): + if i == len(nums): + res.append(copy.deepcopy(path)) + return + for j in range(len(nums)): + if not used[j]: + path.append(nums[j]) + used[j] = True + dfs(nums, i + 1, res, path, used) + used[j] = False + path.pop() + + res, path = [], [] + used = [False] * len(nums) + dfs(nums, 0, res, path, used) + return res +``` + +切分数组: + +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + if len(nums) <= 1: + return [nums] + res = [] + for i, num in enumerate(nums): + n = nums[:i] + nums[i + 1:] + for item in self.permute(n): + res.append([num] + item) + return res +``` + +### **Java** + + + +回溯法: + +```java +class Solution { + public List> permute(int[] nums) { + List> res = new ArrayList<>(); + List path = new ArrayList<>(); + boolean[] used = new boolean[nums.length]; + dfs(nums, 0, res, path, used); + return res; + } + + private void dfs(int[] nums, int i, List> res, List path, boolean[] used) { + if (i == nums.length) { + res.add(new ArrayList<>(path)); + return; + } + for (int j = 0; j < nums.length; ++j) { + if (!used[j]) { + path.add(nums[j]); + used[j] = true; + dfs(nums, i + 1, res, path, used); + used[j] = false; + path.remove(path.size() - 1); + } + } + } +} +``` + +- 递归: + +```java +class Solution { + public List> permute(int[] nums) { + List> res = new ArrayList<>(); + permute(res, nums, 0); + return res; + } + + private void permute(List> res, int[] nums, int start) { + if (start == nums.length) { + List t = new ArrayList<>(); + for (int e : nums) { + t.add(e); + } + res.add(t); + return; + } + for (int i = start; i < nums.length; ++i) { + swap(nums, i, start); + permute(res, nums, start + 1); + swap(nums, i, start); + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function(nums) { + let res = []; + let solution = []; + let record = new Array(nums.length).fill(false); + dfs(nums, 0, record, solution, res); + return res; +}; + +function dfs (nums, depth, record, solution, res) { + if (depth == nums.length) { + res.push(solution.slice()); + return; + } + for (let i = 0; i < nums.length; i++) { + if (!record[i]) { + solution.push(nums[i]); + record[i] = true; + dfs(nums, depth + 1, record, solution, res); + solution.pop(); + record[i] = false; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0047.leetcode47 Permutations II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0047.leetcode47 Permutations II-zh.md" new file mode 100644 index 00000000..0a1d4d49 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0047.leetcode47 Permutations II-zh.md" @@ -0,0 +1,68 @@ +# [47. 全排列 II](https://leetcode-cn.com/problems/permutations-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0047.Permutations%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个可包含重复数字的序列 nums按任意顺序 返回所有不重复的全排列。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,1,2]
    +输出:
    +[[1,1,2],
    + [1,2,1],
    + [2,1,1]]
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3]
    +输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 8
    • +
    • -10 <= nums[i] <= 10
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0048.leetcode48 Rotate Image-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0048.leetcode48 Rotate Image-zh.md" new file mode 100644 index 00000000..049110a8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0048.leetcode48 Rotate Image-zh.md" @@ -0,0 +1,112 @@ +# [48. 旋转图像](https://leetcode-cn.com/problems/rotate-image) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0048.Rotate%20Image/README_EN.md) + +## 题目描述 + + + +

    给定一个 × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。

    + +

    你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    +输出:[[7,4,1],[8,5,2],[9,6,3]]
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
    +输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
    +
    + +

    示例 3:

    + +
    +输入:matrix = [[1]]
    +输出:[[1]]
    +
    + +

    示例 4:

    + +
    +输入:matrix = [[1,2],[3,4]]
    +输出:[[3,1],[4,2]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • matrix.length == n
    • +
    • matrix[i].length == n
    • +
    • 1 <= n <= 20
    • +
    • -1000 <= matrix[i][j] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + s, n = 0, len(matrix) + while s < (n >> 1): + e = n - s - 1 + for i in range(s, e): + t = matrix[i][e] + matrix[i][e] = matrix[s][i] + matrix[s][i] = matrix[n - i - 1][s] + matrix[n - i - 1][s] = matrix[e][n - i - 1] + matrix[e][n - i - 1] = t + s += 1 +``` + +### **Java** + + + +```java +class Solution { + public void rotate(int[][] matrix) { + int s = 0, n = matrix.length; + while (s < (n >> 1)) { + int e = n - s - 1; + for (int i = s; i < e; ++i) { + int t = matrix[i][e]; + matrix[i][e] = matrix[s][i]; + matrix[s][i] = matrix[n - i - 1][s]; + matrix[n - i - 1][s] = matrix[e][n - i - 1]; + matrix[e][n - i - 1] = t; + } + ++s; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0049.leetcode49 Group Anagrams-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0049.leetcode49 Group Anagrams-zh.md" new file mode 100644 index 00000000..15c38b11 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0049.leetcode49 Group Anagrams-zh.md" @@ -0,0 +1,57 @@ +# [49. 字母异位词分组](https://leetcode-cn.com/problems/group-anagrams) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0049.Group%20Anagrams/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

    + +

    示例:

    + +
    输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
    +输出:
    +[
    +  ["ate","eat","tea"],
    +  ["nat","tan"],
    +  ["bat"]
    +]
    + +

    说明:

    + +
      +
    • 所有输入均为小写字母。
    • +
    • 不考虑答案输出的顺序。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0050.leetcode50 Pow(x, n)-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0050.leetcode50 Pow(x, n)-zh.md" new file mode 100644 index 00000000..675a9926 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0050.leetcode50 Pow(x, n)-zh.md" @@ -0,0 +1,113 @@ +# [50. Pow(x, n)](https://leetcode-cn.com/problems/powx-n) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0050.Pow%28x%2C%20n%29/README_EN.md) + +## 题目描述 + + + +

    实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。

    + +

     

    + +

    示例 1:

    + +
    +输入:x = 2.00000, n = 10
    +输出:1024.00000
    +
    + +

    示例 2:

    + +
    +输入:x = 2.10000, n = 3
    +输出:9.26100
    +
    + +

    示例 3:

    + +
    +输入:x = 2.00000, n = -2
    +输出:0.25000
    +解释:2-2 = 1/22 = 1/4 = 0.25
    +
    + +

     

    + +

    提示:

    + +
      +
    • -100.0 < x < 100.0
    • +
    • -231 <= n <= 231-1
    • +
    • -104 <= xn <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def myPow(self, x: float, n: int) -> float: + if n == 0: + return 1 + if n < 0: + return 1 / self.myPow(x, -n) + y = self.myPow(x, n >> 1) + return y * y if (n & 1) == 0 else y * y * x +``` + +### **Java** + + + +```java +class Solution { + public double myPow(double x, int n) { + long N = n; + return N >= 0 ? pow(x, N) : 1.0 / pow(x, -N); + } + + public double pow(double x, long N) { + if (N == 0) { + return 1.0; + } + double y = pow(x, N >> 1); + return (N & 1) == 0 ? y * y : y * y * x; + } +} +``` + +### **TypeScript** + +```ts +function myPow(x: number, n: number): number { + let res = 1; + if (n < 0) { + n = -n; + x = 1 / x; + } + for (let i = n; i != 0; i = Math.floor(i / 2)) { + if ((i & 1) == 1) { + res *= x; + } + x *= x; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0051.leetcode51 N-Queens-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0051.leetcode51 N-Queens-zh.md" new file mode 100644 index 00000000..76f38dae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0051.leetcode51 N-Queens-zh.md" @@ -0,0 +1,74 @@ +# [51. N 皇后](https://leetcode-cn.com/problems/n-queens) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0051.N-Queens/README_EN.md) + +## 题目描述 + + + +

    n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

    + +

    给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。

    + +
    +
    +

    每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q''.' 分别代表了皇后和空位。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 4
    +输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
    +解释:如上图所示,4 皇后问题存在两个不同的解法。
    +
    + +

    示例 2:

    + +
    +输入:n = 1
    +输出:[["Q"]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 9
    • +
    • 皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0052.leetcode52 N-Queens II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0052.leetcode52 N-Queens II-zh.md" new file mode 100644 index 00000000..758cba99 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0052.leetcode52 N-Queens II-zh.md" @@ -0,0 +1,72 @@ +# [52. N皇后 II](https://leetcode-cn.com/problems/n-queens-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0052.N-Queens%20II/README_EN.md) + +## 题目描述 + + + +

    n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

    + +

    给你一个整数 n ,返回 n 皇后问题 不同的解决方案的数量。

    + +

     

    + +
    +
    +

    示例 1:

    + +
    +输入:n = 4
    +输出:2
    +解释:如上图所示,4 皇后问题存在两个不同的解法。
    +
    + +

    示例 2:

    + +
    +输入:n = 1
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 9
    • +
    • 皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0053.leetcode53 Maximum Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0053.leetcode53 Maximum Subarray-zh.md" new file mode 100644 index 00000000..af1d4d9d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0053.leetcode53 Maximum Subarray-zh.md" @@ -0,0 +1,179 @@ +# [53. 最大子序和](https://leetcode-cn.com/problems/maximum-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0053.Maximum%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
    +输出:6
    +解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1]
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:nums = [0]
    +输出:0
    +
    + +

    示例 4:

    + +
    +输入:nums = [-1]
    +输出:-1
    +
    + +

    示例 5:

    + +
    +输入:nums = [-100000]
    +输出:-100000
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 3 * 104
    • +
    • -105 <= nums[i] <= 105
    • +
    + +

     

    + +

    进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。

    + + +## 解法 + + + +设 `dp[i]` 表示 `[0..i]` 中,以 `nums[i]` 结尾的最大子数组和,状态转移方程 `dp[i] = nums[i] + max(dp[i - 1], 0)`。 + +由于 `dp[i]` 只与子问题 `dp[i-1]` 有关,故可以用一个变量 f 来表示。 + + + +### **Python3** + + + +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + res = f = nums[0] + for num in nums[1:]: + f = num + max(f, 0) + res = max(res, f) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxSubArray(int[] nums) { + int f = nums[0], res = nums[0]; + for (int i = 1, n = nums.length; i < n; ++i) { + f = nums[i] + Math.max(f, 0); + res = Math.max(res, f); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxSubArray(vector& nums) { + int f = nums[0], res = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + f = nums[i] + max(f, 0); + res = max(res, f); + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function (nums) { + let f = nums[0], + res = nums[0]; + for (let i = 1; i < nums.length; ++i) { + f = nums[i] + Math.max(f, 0); + res = Math.max(res, f); + } + return res; +}; +``` + +### **Go** + +```go +func maxSubArray(nums []int) int { + f, res := nums[0], nums[0] + for i := 1; i < len(nums); i++ { + if f > 0 { + f += nums[i] + } else { + f = nums[i] + } + if f > res { + res = f + } + } + return res +} +``` + +### **C#** + +```cs +public class Solution { + public int MaxSubArray(int[] nums) { + int res = nums[0], f = nums[0]; + for (int i = 1; i < nums.Length; ++i) + { + f = nums[i] + Math.Max(f, 0); + res = Math.Max(res, f); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0054.leetcode54 Spiral Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0054.leetcode54 Spiral Matrix-zh.md" new file mode 100644 index 00000000..6c21f1a0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0054.leetcode54 Spiral Matrix-zh.md" @@ -0,0 +1,154 @@ +# [54. 螺旋矩阵](https://leetcode-cn.com/problems/spiral-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0054.Spiral%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    +输出:[1,2,3,6,9,8,7,4,5]
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    +输出:[1,2,3,4,8,12,11,10,9,5,6,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 10
    • +
    • -100 <= matrix[i][j] <= 100
    • +
    + + +## 解法 + + + +从外往里一圈一圈遍历并存储矩阵元素即可。 + + + +### **Python3** + + + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + def add(i1, j1, i2, j2): + if i1 == i2: + return [matrix[i1][j] for j in range(j1, j2 + 1)] + if j1 == j2: + return [matrix[i][j1] for i in range(i1, i2 + 1)] + return [matrix[i1][j] for j in range(j1, j2)] + [matrix[i][j2] for i in range(i1, i2)] + [matrix[i2][j] for j in range(j2, j1, -1)] + [matrix[i][j1] for i in range(i2, i1, -1)] + m, n = len(matrix), len(matrix[0]) + i1, j1, i2, j2 = 0, 0, m - 1, n - 1 + res = [] + while i1 <= i2 and j1 <= j2: + res += add(i1, j1, i2, j2) + i1, j1, i2, j2 = i1 + 1, j1 + 1, i2 - 1, j2 - 1 + return res +``` + +### **Java** + + + +```java +class Solution { + private List res; + + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + res = new ArrayList<>(); + int i1 = 0, i2 = m - 1; + int j1 = 0, j2 = n - 1; + while (i1 <= i2 && j1 <= j2) { + add(matrix, i1++, j1++, i2--, j2--); + } + return res; + } + + private void add(int[][] matrix, int i1, int j1, int i2, int j2) { + if (i1 == i2) { + for (int j = j1; j <= j2; ++j) { + res.add(matrix[i1][j]); + } + return; + } + if (j1 == j2) { + for (int i = i1; i <= i2; ++i) { + res.add(matrix[i][j1]); + } + return; + } + for (int j = j1; j < j2; ++j) { + res.add(matrix[i1][j]); + } + for (int i = i1; i < i2; ++i) { + res.add(matrix[i][j2]); + } + for (int j = j2; j > j1; --j) { + res.add(matrix[i2][j]); + } + for (int i = i2; i > i1; --i) { + res.add(matrix[i][j1]); + } + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { + let m = matrix.length; + if (m === 0) return []; + let res = []; + let top = 0, bottom = m - 1, left = 0, right = matrix[0].length - 1; + while (left < right && bottom > top) { + for (let i = left; i < right; i++) res.push(matrix[top][i]); + for (let i = top; i < bottom; i++) res.push(matrix[i][right]); + for (let i = right; i > left; i--) res.push(matrix[bottom][i]); + for (let i = bottom; i > top; i--) res.push(matrix[i][left]); + top++; + bottom--; + left++; + right--; + } + if (left === right) { + for (i = top; i <= bottom; i++) res.push(matrix[i][left]); + } else if (top === bottom) { + for (i = left; i <= right; i++) res.push(matrix[top][i]); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0055.leetcode55 Jump Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0055.leetcode55 Jump Game-zh.md" new file mode 100644 index 00000000..219f48a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0055.leetcode55 Jump Game-zh.md" @@ -0,0 +1,149 @@ +# [55. 跳跃游戏](https://leetcode-cn.com/problems/jump-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0055.Jump%20Game/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组 nums ,你最初位于数组的 第一个下标

    + +

    数组中的每个元素代表你在该位置可以跳跃的最大长度。

    + +

    判断你是否能够到达最后一个下标。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,3,1,1,4]
    +输出:true
    +解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,2,1,0,4]
    +输出:false
    +解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 3 * 104
    • +
    • 0 <= nums[i] <= 105
    • +
    + +## 解法 + + + +贪心。 + + + +### **Python3** + + + +```python +class Solution: + def canJump(self, nums: List[int]) -> bool: + mx = 0 + for i, num in enumerate(nums): + if i > mx: + return False + mx = max(mx, i + num) + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean canJump(int[] nums) { + int mx = 0; + for (int i = 0; i < nums.length; ++i) { + if (i > mx) { + return false; + } + mx = Math.max(mx, i + nums[i]); + } + return true; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool canJump(vector& nums) { + int mx = 0; + for (int i = 0; i < nums.size(); ++i) { + if (i > mx) { + return false; + } + mx = max(mx, i + nums[i]); + } + return true; + } +}; +``` + +### **Go** + +```go +func canJump(nums []int) bool { + mx := 0 + for i, num := range nums { + if i > mx { + return false + } + mx = max(mx, i+num) + } + return true +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public bool CanJump(int[] nums) { + int mx = 0; + for (int i = 0; i < nums.Length; ++i) + { + if (i > mx) + { + return false; + } + mx = Math.Max(mx, i + nums[i]); + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0056.leetcode56 Merge Intervals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0056.leetcode56 Merge Intervals-zh.md" new file mode 100644 index 00000000..37c3bc9a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0056.leetcode56 Merge Intervals-zh.md" @@ -0,0 +1,67 @@ +# [56. 合并区间](https://leetcode-cn.com/problems/merge-intervals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0056.Merge%20Intervals/README_EN.md) + +## 题目描述 + + + +

    以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
    +输出:[[1,6],[8,10],[15,18]]
    +解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[1,4],[4,5]]
    +输出:[[1,5]]
    +解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= intervals.length <= 104
    • +
    • intervals[i].length == 2
    • +
    • 0 <= starti <= endi <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0057.leetcode57 Insert Interval-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0057.leetcode57 Insert Interval-zh.md" new file mode 100644 index 00000000..77d304dd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0057.leetcode57 Insert Interval-zh.md" @@ -0,0 +1,92 @@ +# [57. 插入区间](https://leetcode-cn.com/problems/insert-interval) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0057.Insert%20Interval/README_EN.md) + +## 题目描述 + + + +

    给你一个 无重叠的按照区间起始端点排序的区间列表。

    + +

    在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[1,3],[6,9]], newInterval = [2,5]
    +输出:[[1,5],[6,9]]
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
    +输出:[[1,2],[3,10],[12,16]]
    +解释:这是因为新的区间 [4,8][3,5],[6,7],[8,10] 重叠。
    + +

    示例 3:

    + +
    +输入:intervals = [], newInterval = [5,7]
    +输出:[[5,7]]
    +
    + +

    示例 4:

    + +
    +输入:intervals = [[1,5]], newInterval = [2,3]
    +输出:[[1,5]]
    +
    + +

    示例 5:

    + +
    +输入:intervals = [[1,5]], newInterval = [2,7]
    +输出:[[1,7]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= intervals.length <= 104
    • +
    • intervals[i].length == 2
    • +
    • 0 <= intervals[i][0] <= intervals[i][1] <= 105
    • +
    • intervals 根据 intervals[i][0]升序 排列
    • +
    • newInterval.length == 2
    • +
    • 0 <= newInterval[0] <= newInterval[1] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0058.leetcode58 Length of Last Word-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0058.leetcode58 Length of Last Word-zh.md" new file mode 100644 index 00000000..c8706b55 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0058.leetcode58 Length of Last Word-zh.md" @@ -0,0 +1,94 @@ +# [58. 最后一个单词的长度](https://leetcode-cn.com/problems/length-of-last-word) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0058.Length%20of%20Last%20Word/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。

    + +

    单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "Hello World"
    +输出:5
    +
    + +

    示例 2:

    + +
    +输入:s = " "
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s 仅有英文字母和空格 ' ' 组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def lengthOfLastWord(self, s: str) -> int: + last_word_length = 0 + meet_word = False + for i in range(len(s) - 1, -1, -1): + ch = ord(s[i]) + if ch >= 65 and ch <= 122: + meet_word = True + last_word_length += 1 + elif meet_word: + break + return last_word_length +``` + +### **Java** + + + +```java +class Solution { + public int lengthOfLastWord(String s) { + int n = s.length(); + int lastWordLength = 0; + boolean meetWord = false; + for (int i = n - 1; i >= 0; --i) { + char ch = s.charAt(i); + if (ch >= 'A' && ch <= 'z') { + meetWord = true; + ++lastWordLength; + } else if (meetWord) { + break; + } + } + return lastWordLength; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0059.leetcode59 Spiral Matrix II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0059.leetcode59 Spiral Matrix II-zh.md" new file mode 100644 index 00000000..6d5f45fd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0059.leetcode59 Spiral Matrix II-zh.md" @@ -0,0 +1,146 @@ +# [59. 螺旋矩阵 II](https://leetcode-cn.com/problems/spiral-matrix-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0059.Spiral%20Matrix%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3
    +输出:[[1,2,3],[8,9,4],[7,6,5]]
    +
    + +

    示例 2:

    + +
    +输入:n = 1
    +输出:[[1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + res = [[0] * n for _ in range(n)] + num = 1 + m1, m2 = 0, n - 1 + while m1 < m2: + for j in range(m1, m2): + res[m1][j] = num + num += 1 + for i in range(m1, m2): + res[i][m2] = num + num += 1 + for j in range(m2, m1, -1): + res[m2][j] = num + num += 1 + for i in range(m2, m1, -1): + res[i][m1] = num + num += 1 + m1 += 1 + m2 -= 1 + if m1 == m2: + res[m1][m1] = num + return res +``` + +### **Java** + + + +```java +class Solution { + public int[][] generateMatrix(int n) { + int[][] res = new int[n][n]; + int num = 1; + int m1 = 0, m2 = n - 1; + while (m1 < m2) { + for (int j = m1; j < m2; ++j) { + res[m1][j] = num++; + } + for (int i = m1; i < m2; ++i) { + res[i][m2] = num++; + } + for (int j = m2; j > m1; --j) { + res[m2][j] = num++; + } + for (int i = m2; i > m1; --i) { + res[i][m1] = num++; + } + ++m1; + --m2; + } + if (m1 == m2) { + res[m1][m1] = num; + } + + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> generateMatrix(int n) { + vector> res(n, vector(n, 0)); + int num = 1; + int m1 = 0, m2 = n - 1; + while (m1 < m2) { + for (int j = m1; j < m2; ++j) { + res[m1][j] = num++; + } + for (int i = m1; i < m2; ++i) { + res[i][m2] = num++; + } + for (int j = m2; j > m1; --j) { + res[m2][j] = num++; + } + for (int i = m2; i > m1; --i) { + res[i][m1] = num++; + } + ++m1; + --m2; + } + if (m1 == m2) { + res[m1][m1] = num; + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0060.leetcode60 Permutation Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0060.leetcode60 Permutation Sequence-zh.md" new file mode 100644 index 00000000..66361597 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0060.leetcode60 Permutation Sequence-zh.md" @@ -0,0 +1,85 @@ +# [60. 排列序列](https://leetcode-cn.com/problems/permutation-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0060.Permutation%20Sequence/README_EN.md) + +## 题目描述 + + + +

    给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。

    + +

    按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:

    + +
      +
    1. "123"
    2. +
    3. "132"
    4. +
    5. "213"
    6. +
    7. "231"
    8. +
    9. "312"
    10. +
    11. "321"
    12. +
    + +

    给定 n 和 k,返回第 k 个排列。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, k = 3
    +输出:"213"
    +
    + +

    示例 2:

    + +
    +输入:n = 4, k = 9
    +输出:"2314"
    +
    + +

    示例 3:

    + +
    +输入:n = 3, k = 1
    +输出:"123"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 9
    • +
    • 1 <= k <= n!
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0061.leetcode61 Rotate List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0061.leetcode61 Rotate List-zh.md" new file mode 100644 index 00000000..a575dfe6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0061.leetcode61 Rotate List-zh.md" @@ -0,0 +1,267 @@ +# [61. 旋转链表](https://leetcode-cn.com/problems/rotate-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0061.Rotate%20List/README_EN.md) + +## 题目描述 + + + +

    给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4,5], k = 2
    +输出:[4,5,1,2,3]
    +
    + +

    示例 2:

    + +
    +输入:head = [0,1,2], k = 4
    +输出:[2,0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目在范围 [0, 500]
    • +
    • -100 <= Node.val <= 100
    • +
    • 0 <= k <= 2 * 109
    • +
    + + +## 解法 + + + +将链表右半部分的 k 的节点拼接到 head 即可。 + +注:k 对链表长度 n 取余,即 `k %= n`。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def rotateRight(self, head: ListNode, k: int) -> ListNode: + if k == 0 or head is None or head.next is None: + return head + n, cur = 0, head + while cur: + n, cur = n + 1, cur.next + k %= n + if k == 0: + return head + + slow = fast = head + for _ in range(k): + fast = fast.next + while fast.next: + slow, fast = slow.next, fast.next + + start = slow.next + slow.next = None + fast.next = head + return start +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode rotateRight(ListNode head, int k) { + if (k == 0 || head == null || head.next == null) { + return head; + } + int n = 0; + for (ListNode cur = head; cur != null; cur = cur.next) { + ++n; + } + k %= n; + if (k == 0) { + return head; + } + ListNode slow = head, fast = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + + ListNode start = slow.next; + slow.next = null; + fast.next = head; + return start; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function rotateRight(head: ListNode | null, k: number): ListNode | null { + if (k == 0 || head == null || head.next == null) return head; + // mod n + let n = 0; + let p = head; + while (p != null) { + ++n; + p = p.next; + } + k %= n; + if (k == 0) return head; + + let fast = head, slow = head; + for (let i = 0; i < k; ++i) { + fast = fast.next; + } + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + let start = slow.next; + slow.next = null; + fast.next = head; + return start; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + if (k == 0 || !head || !head->next) { + return head; + } + int n = 0; + for (ListNode *cur = head; !!cur; cur = cur->next) { + ++n; + } + k %= n; + if (k == 0) { + return head; + } + ListNode *slow = head, *fast = head; + while (k-- > 0) { + fast = fast->next; + } + while (fast->next) { + slow = slow->next; + fast = fast->next; + } + + ListNode *start = slow->next; + slow->next = nullptr; + fast->next = head; + return start; + } +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RotateRight(ListNode head, int k) { + if (k == 0 || head == null || head.next == null) + { + return head; + } + var n = 0; + for (ListNode cur = head; cur != null; cur = cur.next) + { + ++n; + } + k %= n; + if (k == 0) + { + return head; + } + ListNode slow = head, fast = head; + while (k-- > 0) + { + fast = fast.next; + } + while (fast.next != null) + { + slow = slow.next; + fast = fast.next; + } + + ListNode start = slow.next; + slow.next = null; + fast.next = head; + return start; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0062.leetcode62 Unique Paths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0062.leetcode62 Unique Paths-zh.md" new file mode 100644 index 00000000..9878681f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0062.leetcode62 Unique Paths-zh.md" @@ -0,0 +1,146 @@ +# [62. 不同路径](https://leetcode-cn.com/problems/unique-paths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0062.Unique%20Paths/README_EN.md) + +## 题目描述 + + + +

    一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。

    + +

    机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。

    + +

    问总共有多少条不同的路径?

    + +

     

    + +

    示例 1:

    + +
    +输入:m = 3, n = 7
    +输出:28
    + +

    示例 2:

    + +
    +输入:m = 3, n = 2
    +输出:3
    +解释:
    +从左上角开始,总共有 3 条路径可以到达右下角。
    +1. 向右 -> 向下 -> 向下
    +2. 向下 -> 向下 -> 向右
    +3. 向下 -> 向右 -> 向下
    +
    + +

    示例 3:

    + +
    +输入:m = 7, n = 3
    +输出:28
    +
    + +

    示例 4:

    + +
    +输入:m = 3, n = 3
    +输出:6
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m, n <= 100
    • +
    • 题目数据保证答案小于等于 2 * 109
    • +
    + +## 解法 + + + +动态规划。 + +假设 `dp[i][j]` 表示到达网格 `(i,j)` 的路径数,则 `dp[i][j] = dp[i - 1][j] + dp[i][j - 1]`。 + + + +### **Python3** + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + dp = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + return dp[-1][-1] +``` + +### **Java** + + + +```java +class Solution { + public int uniquePaths(int m, int n) { + int[][] dp = new int[m][n]; + for (int i = 0; i < m; ++i) { + Arrays.fill(dp[i], 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + return dp[m - 1][n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector> dp(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + return dp[m - 1][n - 1]; + } +}; +``` + +### **Go** + +```go +func uniquePaths(m int, n int) int { + dp := make([][]int, m) + for i := 0; i < m; i++ { + dp[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if i == 0 || j == 0 { + dp[i][j] = 1 + } else { + dp[i][j] = dp[i-1][j] + dp[i][j-1] + } + } + } + return dp[m-1][n-1] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0063.leetcode63 Unique Paths II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0063.leetcode63 Unique Paths II-zh.md" new file mode 100644 index 00000000..224c6119 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0063.leetcode63 Unique Paths II-zh.md" @@ -0,0 +1,175 @@ +# [63. 不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0063.Unique%20Paths%20II/README_EN.md) + +## 题目描述 + + + +

    一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。

    + +

    机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

    + +

    现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?

    + +

    + +

    网格中的障碍物和空位置分别用 10 来表示。

    + +

     

    + +

    示例 1:

    + +
    +输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
    +输出:2
    +解释:
    +3x3 网格的正中间有一个障碍物。
    +从左上角到右下角一共有 2 条不同的路径:
    +1. 向右 -> 向右 -> 向下 -> 向下
    +2. 向下 -> 向下 -> 向右 -> 向右
    +
    + +

    示例 2:

    + +
    +输入:obstacleGrid = [[0,1],[0,0]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == obstacleGrid.length
    • +
    • n == obstacleGrid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • obstacleGrid[i][j]01
    • +
    + +## 解法 + + + +动态规划。 + +假设 `dp[i][j]` 表示到达网格 `(i,j)` 的路径数,先初始化 dp 第一列和第一行的所有值,然后判断。 + +- 若 `obstacleGrid[i][j] == 1`,说明路径数为 0,`dp[i][j] = 0`; +- 若 `obstacleGrid[i][j] == 0`,则 `dp[i][j] = dp[i - 1][j] + dp[i][j - 1]`。 + +最后返回 `dp[m - 1][n - 1]` 即可。 + + + +### **Python3** + + + +```python +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + m, n = len(obstacleGrid), len(obstacleGrid[0]) + dp = [[0] * n for _ in range(m)] + for i in range(m): + if obstacleGrid[i][0] == 1: + break + dp[i][0] = 1 + for j in range(n): + if obstacleGrid[0][j] == 1: + break + dp[0][j] = 1 + for i in range(1, m): + for j in range(1, n): + if obstacleGrid[i][j] == 0: + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + return dp[-1][-1] +``` + +### **Java** + + + +```java +class Solution { + public int uniquePathsWithObstacles(int[][] obstacleGrid) { + int m = obstacleGrid.length, n = obstacleGrid[0].length; + int[][] dp = new int[m][n]; + for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) { + dp[i][0] = 1; + } + for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j) { + dp[0][j] = 1; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (obstacleGrid[i][j] == 0) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m - 1][n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int m = obstacleGrid.size(), n = obstacleGrid[0].size(); + vector> dp(m, vector(n)); + for (int i = 0; i < m && obstacleGrid[i][0] == 0; ++i) { + dp[i][0] = 1; + } + for (int j = 0; j < n && obstacleGrid[0][j] == 0; ++j) { + dp[0][j] = 1; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (obstacleGrid[i][j] == 0) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m - 1][n - 1]; + } +}; +``` + +### **Go** + +```go +func uniquePathsWithObstacles(obstacleGrid [][]int) int { + m, n := len(obstacleGrid), len(obstacleGrid[0]) + dp := make([][]int, m) + for i := 0; i < m; i++ { + dp[i] = make([]int, n) + } + for i := 0; i < m && obstacleGrid[i][0] == 0; i++ { + dp[i][0] = 1 + } + for j := 0; j < n && obstacleGrid[0][j] == 0; j++ { + dp[0][j] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if obstacleGrid[i][j] == 0 { + dp[i][j] = dp[i-1][j] + dp[i][j-1] + } + } + } + return dp[m-1][n-1] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0064.leetcode64 Minimum Path Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0064.leetcode64 Minimum Path Sum-zh.md" new file mode 100644 index 00000000..6a0c83cc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0064.leetcode64 Minimum Path Sum-zh.md" @@ -0,0 +1,158 @@ +# [64. 最小路径和](https://leetcode-cn.com/problems/minimum-path-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0064.Minimum%20Path%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

    + +

    说明:每次只能向下或者向右移动一步。

    + +

     

    + +

    示例 1:

    + +
    +输入:grid = [[1,3,1],[1,5,1],[4,2,1]]
    +输出:7
    +解释:因为路径 1→3→1→1→1 的总和最小。
    +
    + +

    示例 2:

    + +
    +输入:grid = [[1,2,3],[4,5,6]]
    +输出:12
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • 0 <= grid[i][j] <= 100
    • +
    + +## 解法 + + + +动态规划。假设 `dp[i][j]` 表示到达网格 `(i,j)` 的最小数字和,先初始化 dp 第一列和第一行的所有值,然后利用递推公式:`dp[i][j] = min(dp[i -1][j], dp[i][j - 1]) + grid[i][j]` 求得 dp。 + +最后返回 `dp[m - 1][n - 1]` 即可。 + + + +### **Python3** + + + +```python +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + dp = [[grid[0][0]] * n for _ in range(m)] + for i in range(1, m): + dp[i][0] = dp[i - 1][0] + grid[i][0] + for j in range(1, n): + dp[0][j] = dp[0][j - 1] + grid[0][j] + for i in range(1, m): + for j in range(1, n): + dp[i][j] = min(dp[i -1][j], dp[i][j - 1]) + grid[i][j] + return dp[-1][-1] +``` + +### **Java** + + + +```java +class Solution { + public int minPathSum(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] dp = new int[m][n]; + dp[0][0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + dp[i][0] = dp[i - 1][0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + dp[0][j] = dp[0][j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + } + } + return dp[m - 1][n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> dp(m, vector(n, grid[0][0])); + for (int i = 1; i < m; ++i) { + dp[i][0] = dp[i - 1][0] + grid[i][0]; + } + for (int j = 1; j < n; ++j) { + dp[0][j] = dp[0][j - 1] + grid[0][j]; + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + } + } + return dp[m - 1][n - 1]; + } +}; +``` + +### **Go** + +```go +func minPathSum(grid [][]int) int { + m, n := len(grid), len(grid[0]) + dp := make([][]int, m) + for i := 0; i < m; i++ { + dp[i] = make([]int, n) + } + dp[0][0] = grid[0][0] + for i := 1; i < m; i++ { + dp[i][0] = dp[i-1][0] + grid[i][0] + } + for j := 1; j < n; j++ { + dp[0][j] = dp[0][j-1] + grid[0][j] + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j] + } + } + return dp[m-1][n-1] +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0065.leetcode65 Valid Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0065.leetcode65 Valid Number-zh.md" new file mode 100644 index 00000000..92821dcb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0065.leetcode65 Valid Number-zh.md" @@ -0,0 +1,118 @@ +# [65. 有效数字](https://leetcode-cn.com/problems/valid-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0065.Valid%20Number/README_EN.md) + +## 题目描述 + + + +

    有效数字(按顺序)可以分成以下几个部分:

    + +
      +
    1. 一个 小数 或者 整数
    2. +
    3. (可选)一个 'e''E' ,后面跟着一个 整数
    4. +
    + +

    小数(按顺序)可以分成以下几个部分:

    + +
      +
    1. (可选)一个符号字符('+''-'
    2. +
    3. 下述格式之一: +
        +
      1. 至少一位数字,后面跟着一个点 '.'
      2. +
      3. 至少一位数字,后面跟着一个点 '.' ,后面再跟着至少一位数字
      4. +
      5. 一个点 '.' ,后面跟着至少一位数字
      6. +
      +
    4. +
    + +

    整数(按顺序)可以分成以下几个部分:

    + +
      +
    1. (可选)一个符号字符('+''-'
    2. +
    3. 至少一位数字
    4. +
    + +

    部分有效数字列举如下:

    + +
      +
    • ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]
    • +
    + +

    部分无效数字列举如下:

    + +
      +
    • ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]
    • +
    + +

    给你一个字符串 s ,如果 s 是一个 有效数字 ,请返回 true

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "0"
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:s = "e"
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:s = "."
    +输出:false
    +
    + +

    示例 4:

    + +
    +输入:s = ".1"
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 20
    • +
    • s 仅含英文字母(大写和小写),数字(0-9),加号 '+' ,减号 '-' ,或者点 '.'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0066.leetcode66 Plus One-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0066.leetcode66 Plus One-zh.md" new file mode 100644 index 00000000..fd294beb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0066.leetcode66 Plus One-zh.md" @@ -0,0 +1,78 @@ +# [66. 加一](https://leetcode-cn.com/problems/plus-one) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0066.Plus%20One/README_EN.md) + +## 题目描述 + + + +

    给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。

    + +

    最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

    + +

    你可以假设除了整数 0 之外,这个整数不会以零开头。

    + +

     

    + +

    示例 1:

    + +
    +输入:digits = [1,2,3]
    +输出:[1,2,4]
    +解释:输入数组表示数字 123。
    +
    + +

    示例 2:

    + +
    +输入:digits = [4,3,2,1]
    +输出:[4,3,2,2]
    +解释:输入数组表示数字 4321。
    +
    + +

    示例 3:

    + +
    +输入:digits = [0]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= digits.length <= 100
    • +
    • 0 <= digits[i] <= 9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0067.leetcode67 Add Binary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0067.leetcode67 Add Binary-zh.md" new file mode 100644 index 00000000..4b6f2701 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0067.leetcode67 Add Binary-zh.md" @@ -0,0 +1,142 @@ +# [67. 二进制求和](https://leetcode-cn.com/problems/add-binary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0067.Add%20Binary/README_EN.md) + +## 题目描述 + + + +

    给你两个二进制字符串,返回它们的和(用二进制表示)。

    + +

    输入为 非空 字符串且只包含数字 1 和 0

    + +

     

    + +

    示例 1:

    + +
    输入: a = "11", b = "1"
    +输出: "100"
    + +

    示例 2:

    + +
    输入: a = "1010", b = "1011"
    +输出: "10101"
    + +

     

    + +

    提示:

    + +
      +
    • 每个字符串仅由字符 '0''1' 组成。
    • +
    • 1 <= a.length, b.length <= 10^4
    • +
    • 字符串如果不是 "0" ,就都不含前导零。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def addBinary(self, a: str, b: str) -> str: + return bin(int(a, 2) + int(b, 2))[2:] +``` + +### **Java** + + + +```java +class Solution { + public String addBinary(String a, String b) { + StringBuilder sb = new StringBuilder(); + int i = a.length() - 1, j = b.length() - 1, carry = 0; + while (i >= 0 || j >= 0 || carry != 0) { + int s = carry + (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0); + sb.append(s % 2); + carry = s / 2; + --i; + --j; + } + return sb.reverse().toString(); + } +} +``` + +### **C#** + +```cs +using System; +using System.Collections.Generic; + +public class Solution { + public string AddBinary(string a, string b) { + var list = new List(Math.Max(a.Length, b.Length) + 1); + var i = a.Length - 1; + var j = b.Length - 1; + var carry = 0; + while (i >= 0 || j >= 0) + { + if (i >= 0) + { + carry += a[i] - '0'; + } + if (j >= 0) + { + carry += b[j] - '0'; + } + list.Add((char)((carry % 2) + '0')); + carry /= 2; + --i; + --j; + } + if (carry > 0) list.Add((char) (carry + '0')); + list.Reverse(); + return new string(list.ToArray()); + } +} +``` + +### **Go** + +```go +func addBinary(a string, b string) string { + for len(a) > len(b) { + b = "0" + b + } + for len(a) < len(b) { + a = "0" + a + } + zero := []byte("0")[0] + ret := make([]byte, len(a)) + for right := len(a) - 1; right > 0; right-- { + t := ret[right] + a[right] + b[right] - zero*2 + ret[right] = t%2 + zero + if t >= 2 { + ret[right-1] = 1 + } + } + t := ret[0] + a[0] + b[0] - zero*2 + ret[0] = t%2 + zero + if t >= 2 { + ret = append([]byte("1"), ret...) + } + + return string(ret) +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0068.leetcode68 Text Justification-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0068.leetcode68 Text Justification-zh.md" new file mode 100644 index 00000000..2fdfd380 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0068.leetcode68 Text Justification-zh.md" @@ -0,0 +1,100 @@ +# [68. 文本左右对齐](https://leetcode-cn.com/problems/text-justification) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0068.Text%20Justification/README_EN.md) + +## 题目描述 + + + +

    给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

    + +

    你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

    + +

    要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

    + +

    文本的最后一行应为左对齐,且单词之间不插入额外的空格。

    + +

    说明:

    + +
      +
    • 单词是指由非空格字符组成的字符序列。
    • +
    • 每个单词的长度大于 0,小于等于 maxWidth
    • +
    • 输入单词数组 words 至少包含一个单词。
    • +
    + +

    示例:

    + +
    输入:
    +words = ["This", "is", "an", "example", "of", "text", "justification."]
    +maxWidth = 16
    +输出:
    +[
    +   "This    is    an",
    +   "example  of text",
    +   "justification.  "
    +]
    +
    + +

    示例 2:

    + +
    输入:
    +words = ["What","must","be","acknowledgment","shall","be"]
    +maxWidth = 16
    +输出:
    +[
    +  "What   must   be",
    +  "acknowledgment  ",
    +  "shall be        "
    +]
    +解释: 注意最后一行的格式应为 "shall be    " 而不是 "shall     be",
    +     因为最后一行应为左对齐,而不是左右两端对齐。       
    +     第二行同样为左对齐,这是因为这行只包含一个单词。
    +
    + +

    示例 3:

    + +
    输入:
    +words = ["Science","is","what","we","understand","well","enough","to","explain",
    +         "to","a","computer.","Art","is","everything","else","we","do"]
    +maxWidth = 20
    +输出:
    +[
    +  "Science  is  what we",
    +  "understand      well",
    +  "enough to explain to",
    +  "a  computer.  Art is",
    +  "everything  else  we",
    +  "do                  "
    +]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0069.leetcode69 Sqrt(x)-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0069.leetcode69 Sqrt(x)-zh.md" new file mode 100644 index 00000000..ad01f5e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0069.leetcode69 Sqrt(x)-zh.md" @@ -0,0 +1,181 @@ +# [69. x 的平方根](https://leetcode-cn.com/problems/sqrtx) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0069.Sqrt%28x%29/README_EN.md) + +## 题目描述 + + + +

    实现 int sqrt(int x) 函数。

    + +

    计算并返回 x 的平方根,其中 x 是非负整数。

    + +

    由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

    + +

    示例 1:

    + +
    输入: 4
    +输出: 2
    +
    + +

    示例 2:

    + +
    输入: 8
    +输出: 2
    +说明: 8 的平方根是 2.82842..., 
    +     由于返回类型是整数,小数部分将被舍去。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def mySqrt(self, x: int) -> int: + if x == 0: + return 0 + left, right = 1, x + while left < right: + mid = (left + right + 1) >> 1 + # mid*mid <= x + if x // mid >= mid: + left = mid + else: + right = mid - 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int mySqrt(int x) { + if (x == 0) { + return 0; + } + int left = 1, right = x; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if (x / mid >= mid) { + // mid*mid <= x + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int mySqrt(int x) { + if (x == 0) { + return 0; + } + int left = 1, right = x; + while (left < right) { + int mid = left + ((right - left + 1) >> 1); + if (x / mid >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @return {number} + */ +var mySqrt = function(x) { + if (x == 0) { + return 0; + } + let left = 1; + let right = x; + while (left < right) { + const mid = (left + right + 1) >>> 1; + if (x / mid >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; +``` + +### **Go** + +```go +func mySqrt(x int) int { + if x == 0 { + return 0 + } + left, right := 1, x + for left < right { + mid := left + (right-left+1)>>1 + if x/mid >= mid { + left = mid + } else { + right = mid - 1 + } + } + return left +} +``` + +### **C#** + +```cs +public class Solution { + public int MySqrt(int x) { + if (x == 0) { + return 0; + } + int left = 1, right = x; + while (left < right) + { + int mid = left + right + 1 >> 1; + if (x / mid >= mid) + { + left = mid; + } + else + { + right = mid - 1; + } + } + return left; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0070.leetcode70 Climbing Stairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0070.leetcode70 Climbing Stairs-zh.md" new file mode 100644 index 00000000..2af3fb22 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0070.leetcode70 Climbing Stairs-zh.md" @@ -0,0 +1,127 @@ +# [70. 爬楼梯](https://leetcode-cn.com/problems/climbing-stairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0070.Climbing%20Stairs/README_EN.md) + +## 题目描述 + + + +

    假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

    + +

    每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

    + +

    注意:给定 n 是一个正整数。

    + +

    示例 1:

    + +
    输入: 2
    +输出: 2
    +解释: 有两种方法可以爬到楼顶。
    +1.  1 阶 + 1 阶
    +2.  2 阶
    + +

    示例 2:

    + +
    输入: 3
    +输出: 3
    +解释: 有三种方法可以爬到楼顶。
    +1.  1 阶 + 1 阶 + 1 阶
    +2.  1 阶 + 2 阶
    +3.  2 阶 + 1 阶
    +
    + + +## 解法 + + + +想上第 `n` 级台阶,可从第 `n-1` 级台阶爬一级上去,也可从第 `n-2` 级台阶爬两级上去,即:`f(n) = f(n-1) + f(n-2)`。递推求解即可。 + + + +### **Python3** + + + +```python +class Solution: + def climbStairs(self, n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return b +``` + +### **Java** + + + +```java +class Solution { + public int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { + let a = 0, + b = 1; + for (let i = 0; i < n; ++i) { + const c = a + b; + a = b; + b = c; + } + return b; +}; +``` + +### **Go** + +```go +func climbStairs(n int) int { + a, b := 0, 1 + for i := 0; i < n; i++ { + a, b = b, a + b + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0071.leetcode71 Simplify Path-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0071.leetcode71 Simplify Path-zh.md" new file mode 100644 index 00000000..43169390 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0071.leetcode71 Simplify Path-zh.md" @@ -0,0 +1,95 @@ +# [71. 简化路径](https://leetcode-cn.com/problems/simplify-path) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0071.Simplify%20Path/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 path ,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 '/' 开头),请你将其转化为更加简洁的规范路径。

    + +

    在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。任意多个连续的斜杠(即,'//')都被视为单个斜杠 '/' 。 对于此问题,任何其他格式的点(例如,'...')均被视为文件/目录名称。

    + +

    请注意,返回的 规范路径 必须遵循下述格式:

    + +
      +
    • 始终以斜杠 '/' 开头。
    • +
    • 两个目录名之间必须只有一个斜杠 '/'
    • +
    • 最后一个目录名(如果存在)不能 '/' 结尾。
    • +
    • 此外,路径仅包含从根目录到目标文件或目录的路径上的目录(即,不含 '.''..')。
    • +
    + +

    返回简化后得到的 规范路径

    + +

     

    + +

    示例 1:

    + +
    +输入:path = "/home/"
    +输出:"/home"
    +解释:注意,最后一个目录名后面没有斜杠。 
    + +

    示例 2:

    + +
    +输入:path = "/../"
    +输出:"/"
    +解释:从根目录向上一级是不可行的,因为根目录是你可以到达的最高级。
    +
    + +

    示例 3:

    + +
    +输入:path = "/home//foo/"
    +输出:"/home/foo"
    +解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。
    +
    + +

    示例 4:

    + +
    +输入:path = "/a/./b/../../c/"
    +输出:"/c"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= path.length <= 3000
    • +
    • path 由英文字母,数字,'.''/''_' 组成。
    • +
    • path 是一个有效的 Unix 风格绝对路径。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0072.leetcode72 Edit Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0072.leetcode72 Edit Distance-zh.md" new file mode 100644 index 00000000..4a0790ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0072.leetcode72 Edit Distance-zh.md" @@ -0,0 +1,83 @@ +# [72. 编辑距离](https://leetcode-cn.com/problems/edit-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0072.Edit%20Distance/README_EN.md) + +## 题目描述 + + + +

    给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。

    + +

    你可以对一个单词进行如下三种操作:

    + +
      +
    • 插入一个字符
    • +
    • 删除一个字符
    • +
    • 替换一个字符
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:word1 = "horse", word2 = "ros"
    +输出:3
    +解释:
    +horse -> rorse (将 'h' 替换为 'r')
    +rorse -> rose (删除 'r')
    +rose -> ros (删除 'e')
    +
    + +

    示例 2:

    + +
    +输入:word1 = "intention", word2 = "execution"
    +输出:5
    +解释:
    +intention -> inention (删除 't')
    +inention -> enention (将 'i' 替换为 'e')
    +enention -> exention (将 'n' 替换为 'x')
    +exention -> exection (将 'n' 替换为 'c')
    +exection -> execution (插入 'u')
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= word1.length, word2.length <= 500
    • +
    • word1word2 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0073.leetcode73 Set Matrix Zeroes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0073.leetcode73 Set Matrix Zeroes-zh.md" new file mode 100644 index 00000000..fc4c1742 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0073.leetcode73 Set Matrix Zeroes-zh.md" @@ -0,0 +1,232 @@ +# [73. 矩阵置零](https://leetcode-cn.com/problems/set-matrix-zeroes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0073.Set%20Matrix%20Zeroes/README_EN.md) + +## 题目描述 + + + +

    给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法

    + +

    进阶:

    + +
      +
    • 一个直观的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
    • +
    • 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
    • +
    • 你能想出一个仅使用常量空间的解决方案吗?
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
    +输出:[[1,0,1],[0,0,0],[1,0,1]]
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
    +输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[0].length
    • +
    • 1 <= m, n <= 200
    • +
    • -231 <= matrix[i][j] <= 231 - 1
    • +
    + + +## 解法 + + + +### 方法一:使用两个标记数组 + +用两个数组标记每一行、每一列是否出现零。 + +遍历原数组,若元素为 0,将元素所在的行、列所对应的标记数组的位置为 true。 + +最后遍历原数组,用标记数组更新原数组。 + +### 方法二:使用两个标记变量 + +用矩阵的第一行和第一列代替方法一中的两个标记数组,以达到 `O(1)` 的额外空间。但这样会导致原数组的第一行和第一列被修改,无法记录它们是否原本包含 0。因此我们需要额外使用两个标记变量分别记录第一行和第一列是否原本包含 0。 + + + +### **Python3** + + + +方法一: + +```python +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + m, n = len(matrix), len(matrix[0]) + zero_rows = [False] * m + zero_cols = [False] * n + for i in range(m): + for j in range(n): + if matrix[i][j] == 0: + zero_rows[i] = zero_cols[j] = True + for i in range(m): + for j in range(n): + if zero_rows[i] or zero_cols[j]: + matrix[i][j] = 0 +``` + +方法二: + +```python +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + m, n = len(matrix), len(matrix[0]) + first_row_has_zero = any(matrix[0][j] == 0 for j in range(n)) + first_col_has_zero = any(matrix[i][0] == 0 for i in range(m)) + + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] == 0: + matrix[i][0] = matrix[0][j] = 0 + + for i in range(1, m): + for j in range(1, n): + if matrix[i][0] == 0 or matrix[0][j] == 0: + matrix[i][j] = 0 + + if first_row_has_zero: + for j in range(n): + matrix[0][j] = 0 + + if first_col_has_zero: + for i in range(m): + matrix[i][0] = 0 +``` + +### **Java** + + + +方法一: + +```java +class Solution { + public void setZeroes(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + boolean[] zeroRows = new boolean[m]; + boolean[] zeroCols = new boolean[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == 0) { + zeroRows[i] = zeroCols[j] = true; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (zeroRows[i] || zeroCols[j]) { + matrix[i][j] = 0; + } + } + } + } +} +``` + +方法二: + +```java +class Solution { + public void setZeroes(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + boolean firstRowHasZero = false; + boolean firstColHasZero = false; + for (int j = 0; j < n; ++j) { + if (matrix[0][j] == 0) { + firstRowHasZero = true; + break; + } + } + for (int i = 0; i < m; ++i) { + if (matrix[i][0] == 0) { + firstColHasZero = true; + break; + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + // 更新标记数组 + if (matrix[i][j] == 0) { + matrix[i][0] = matrix[0][j] = 0; + } + } + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + if (firstRowHasZero) { + for (int j = 0; j < n; ++j) { + matrix[0][j] = 0; + } + } + if (firstColHasZero) { + for (int i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + vector zeroRows(m), zeroCols(n); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 0) { + zeroRows[i] = zeroCols[j] = true; + } + } + } + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (zeroRows[i] || zeroCols[j]) { + matrix[i][j] = 0; + } + } + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0074.leetcode74 Search a 2D Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0074.leetcode74 Search a 2D Matrix-zh.md" new file mode 100644 index 00000000..d40eedeb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0074.leetcode74 Search a 2D Matrix-zh.md" @@ -0,0 +1,167 @@ +# [74. 搜索二维矩阵](https://leetcode-cn.com/problems/search-a-2d-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0074.Search%20a%202D%20Matrix/README_EN.md) + +## 题目描述 + + + +

    编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

    + +
      +
    • 每行中的整数从左到右按升序排列。
    • +
    • 每行的第一个整数大于前一行的最后一个整数。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • -104 <= matrix[i][j], target <= 104
    • +
    + +## 解法 + + + +将二维矩阵逻辑展开,然后二分查找即可。 + + + +### **Python3** + + + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + left, right = 0, m * n - 1 + while left < right: + mid = (left + right) >> 1 + x, y = divmod(mid, n) + if matrix[x][y] >= target: + right = mid + else: + left = mid + 1 + return matrix[left // n][left % n] == target +``` + +### **Java** + + + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int left = 0, right = m * n - 1; + while (left < right) { + int mid = (left + right) >> 1; + int x = mid / n, y = mid % n; + if (matrix[x][y] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return matrix[left / n][left % n] == target; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int left = 0, right = m * n - 1; + while (left < right) { + int mid = left + right >> 1; + int x = mid / n, y = mid % n; + if (matrix[x][y] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return matrix[left / n][left % n] == target; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + const m = matrix.length; + const n = matrix[0].length; + let left = 0; + let right = m * n - 1; + while (left < right) { + const mid = (left + right) >> 1; + const x = Math.floor(mid / n); + const y = mid % n; + if (matrix[x][y] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return matrix[Math.floor(left / n)][left % n] == target; +}; +``` + +### **Go** + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + left, right := 0, m*n-1 + for left < right { + mid := (left + right) >> 1 + x, y := mid/n, mid%n + if matrix[x][y] >= target { + right = mid + } else { + left = mid + 1 + } + } + return matrix[left/n][left%n] == target +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0075.leetcode75 Sort Colors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0075.leetcode75 Sort Colors-zh.md" new file mode 100644 index 00000000..17caec80 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0075.leetcode75 Sort Colors-zh.md" @@ -0,0 +1,170 @@ +# [75. 颜色分类](https://leetcode-cn.com/problems/sort-colors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0075.Sort%20Colors/README_EN.md) + +## 题目描述 + + + +

    给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

    + +

    此题中,我们使用整数 0、 12 分别表示红色、白色和蓝色。

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,0,2,1,1,0]
    +输出:[0,0,1,1,2,2]
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,0,1]
    +输出:[0,1,2]
    +
    + +

    示例 3:

    + +
    +输入:nums = [0]
    +输出:[0]
    +
    + +

    示例 4:

    + +
    +输入:nums = [1]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 300
    • +
    • nums[i]012
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以不使用代码库中的排序函数来解决这道题吗?
    • +
    • 你能想出一个仅使用常数空间的一趟扫描算法吗?
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + i, j = -1, len(nums) + cur = 0 + while cur < j: + if nums[cur] == 0: + i += 1 + nums[cur], nums[i] = nums[i], nums[cur] + cur += 1 + elif nums[cur] == 1: + cur += 1 + else: + j -= 1 + nums[cur], nums[j] = nums[j], nums[cur] +``` + +### **Java** + + + +```java +class Solution { + public void sortColors(int[] nums) { + int i = -1, j = nums.length; + int cur = 0; + while (cur < j) { + if (nums[cur] == 0) { + swap(nums, cur++, ++i); + } else if (nums[cur] == 1) { + ++cur; + } else { + swap(nums, cur, --j); + } + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + void sortColors(vector& nums) { + int i = -1, j = nums.size(), cur = 0; + while (cur < j) { + if (nums[cur] == 0) { + swap(nums[++i], nums[cur++]); + } else if (nums[cur] == 1) { + ++cur; + } else { + swap(nums[cur], nums[--j]); + } + } + } +}; +``` + +### **Go** + +```go +func sortColors(nums []int) { + i, j, cur := -1, len(nums), 0 + for cur < j { + if nums[cur] == 0 { + i++ + nums[cur], nums[i] = nums[i], nums[cur] + cur++ + } else if nums[cur] == 1 { + cur++ + } else { + j-- + nums[cur], nums[j] = nums[j], nums[cur] + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0076.leetcode76 Minimum Window Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0076.leetcode76 Minimum Window Substring-zh.md" new file mode 100644 index 00000000..d6c36ecd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0076.leetcode76 Minimum Window Substring-zh.md" @@ -0,0 +1,111 @@ +# [76. 最小覆盖子串](https://leetcode-cn.com/problems/minimum-window-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0076.Minimum%20Window%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ""

    + +

    注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "ADOBECODEBANC", t = "ABC"
    +输出:"BANC"
    +
    + +

    示例 2:

    + +
    +输入:s = "a", t = "a"
    +输出:"a"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length, t.length <= 105
    • +
    • st 由英文字母组成
    • +
    + +

     

    +进阶:你能设计一个在 o(n) 时间内解决此问题的算法吗? + +## 解法 + +滑动窗口 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **TypeScript** + +```ts +function minWindow(s: string, t: string): string { + let n1 = s.length, n2 = t.length; + if (n1 < n2) return ''; + let need = new Array(128).fill(0); + let window = new Array(128).fill(0); + for (let i = 0; i < n2; ++i) { + ++need[t.charCodeAt(i)]; + } + + let left = 0, right = 0; + let res = ''; + let count = 0; + let min = n1 + 1; + while (right < n1) { + let cur = s.charCodeAt(right); + ++window[cur]; + if (need[cur] > 0 && need[cur] >= window[cur]) { + ++count; + } + while (count == n2) { + cur = s.charCodeAt(left); + if (need[cur] > 0 && need[cur] >= window[cur]) { + --count; + } + if (right - left + 1 < min) { + min = right - left + 1; + res = s.slice(left, right + 1); + } + --window[cur]; + ++left; + } + ++right; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0077.leetcode77 Combinations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0077.leetcode77 Combinations-zh.md" new file mode 100644 index 00000000..89c28393 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0077.leetcode77 Combinations-zh.md" @@ -0,0 +1,53 @@ +# [77. 组合](https://leetcode-cn.com/problems/combinations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0077.Combinations/README_EN.md) + +## 题目描述 + + + +

    给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

    + +

    示例:

    + +
    输入: n = 4, k = 2
    +输出:
    +[
    +  [2,4],
    +  [3,4],
    +  [2,3],
    +  [1,2],
    +  [1,3],
    +  [1,4],
    +]
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0078.leetcode78 Subsets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0078.leetcode78 Subsets-zh.md" new file mode 100644 index 00000000..8b0ada17 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0078.leetcode78 Subsets-zh.md" @@ -0,0 +1,113 @@ +# [78. 子集](https://leetcode-cn.com/problems/subsets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0078.Subsets/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

    + +

    解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3]
    +输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    +
    + +

    示例 2:

    + +
    +输入:nums = [0]
    +输出:[[],[0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10
    • +
    • -10 <= nums[i] <= 10
    • +
    • nums 中的所有元素 互不相同
    • +
    + + +## 解法 + + + +回溯法的基本模板: + +```py +res = [] +path = [] + +def backtrack(未探索区域, res, path): + if path 满足条件: + res.add(path) # 深度拷贝 + # return # 如果不用继续搜索需要 return + for 选择 in 未探索区域当前可能的选择: + if 当前选择符合要求: + path.add(当前选择) + backtrack(新的未探索区域, res, path) + path.pop() +``` + + + +### **Python3** + + + +```python +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + def dfs(nums, i, res, path): + res.append(copy.deepcopy(path)) + while i < len(nums): + path.append(nums[i]) + dfs(nums, i + 1, res, path) + path.pop() + i += 1 + res, path = [], [] + dfs(nums, 0, res, path) + return res +``` + +### **Java** + + + +```java +class Solution { + public List> subsets(int[] nums) { + List path = new ArrayList<>(); + List> res = new ArrayList<>(); + dfs(nums, 0, res, path); + return res; + } + + private void dfs(int[] nums, int i, List> res, List path) { + res.add(new ArrayList<>(path)); + while (i < nums.length) { + path.add(nums[i]); + dfs(nums, i + 1, res, path); + path.remove(path.size() - 1); + ++i; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0079.leetcode79 Word Search-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0079.leetcode79 Word Search-zh.md" new file mode 100644 index 00000000..5d716a6f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0079.leetcode79 Word Search-zh.md" @@ -0,0 +1,172 @@ +# [79. 单词搜索](https://leetcode-cn.com/problems/word-search) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0079.Word%20Search/README_EN.md) + +## 题目描述 + + + +

    给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false

    + +

    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

    + +

     

    + +

    示例 1:

    + +
    +输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
    +输出:true
    +
    + +

    示例 3:

    + +
    +输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == board.length
    • +
    • n = board[i].length
    • +
    • 1 <= m, n <= 6
    • +
    • 1 <= word.length <= 15
    • +
    • boardword 仅由大小写英文字母组成
    • +
    + +

     

    + +

    进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?

    + + +## 解法 + + + +回溯(深度优先搜索 DFS )实现。 + + + +### **Python3** + + + +```python +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + def dfs(i, j, cur): + if cur == len(word): + return True + if i < 0 or i >= m or j < 0 or j >= n or visited[i][j] or word[cur] != board[i][j]: + return False + visited[i][j] = True + next = cur + 1 + res = dfs(i + 1, j, next) or dfs(i - 1, j, next) or dfs(i, j + 1, next) or dfs(i, j - 1, next) + visited[i][j] = False + return res + m, n = len(board), len(board[0]) + visited = [[False for _ in range(n)] for _ in range(m)] + for i in range(m): + for j in range(n): + res = dfs(i, j, 0) + if res: + return True + return False +``` + +### **Java** + + + +```java +class Solution { + private boolean[][] visited; + + public boolean exist(char[][] board, String word) { + int m = board.length, n = board[0].length; + visited = new boolean[m][n]; + char[] chars = word.toCharArray(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + boolean res = dfs(board, i, j, chars, 0); + if (res) return true; + } + } + return false; + } + + private boolean dfs(char[][] board, int i, int j, char[] chars, int cur) { + if (cur == chars.length) return true; + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; + if (visited[i][j] || board[i][j] != chars[cur]) return false; + visited[i][j] = true; + int next = cur + 1; + boolean res = dfs(board, i + 1, j, chars, next) + || dfs(board, i - 1, j, chars, next) + || dfs(board, i, j + 1, chars, next) + || dfs(board, i, j - 1, chars, next); + visited[i][j] = false; + return res; + } +} +``` + +### **TypeScript** + +```ts +function exist(board: string[][], word: string): boolean { + let m = board.length, n = board[0].length; + let visited = Array.from({ length: m }, v => new Array(n).fill(false)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (dfs(board, word, i, j, 0, visited)) { + return true; + } + } + } + return false; +}; + +function dfs(board: string[][], word: string, i: number, j: number, depth: number, visited: boolean[][]): boolean { + let m = board.length, n = board[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || visited[i][j]) { + return false; + } + if (board[i][j] != word.charAt(depth)) { + return false; + } + + if (depth == word.length - 1) { + return true; + } + + visited[i][j] = true; + ++depth; + let res = false; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + res = res || dfs(board, word, x, y, depth, visited); + } + visited[i][j] = false; + return res; +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0080.leetcode80 Remove Duplicates from Sorted Array II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0080.leetcode80 Remove Duplicates from Sorted Array II-zh.md" new file mode 100644 index 00000000..907b1b80 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0080.leetcode80 Remove Duplicates from Sorted Array II-zh.md" @@ -0,0 +1,177 @@ +# [80. 删除有序数组中的重复项 II](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0080.Remove%20Duplicates%20from%20Sorted%20Array%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现两次 ,返回删除后数组的新长度。

    + +

    不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。

    + +

     

    + +

    说明:

    + +

    为什么返回数值是整数,但输出的答案是数组呢?

    + +

    请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

    + +

    你可以想象内部操作如下:

    + +
    +// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
    +int len = removeDuplicates(nums);
    +
    +// 在函数里修改输入数组对于调用者是可见的。
    +// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
    +for (int i = 0; i < len; i++) {
    +    print(nums[i]);
    +}
    +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,1,1,2,2,3]
    +输出:5, nums = [1,1,2,2,3]
    +解释:函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。 不需要考虑数组中超出新长度后面的元素。
    +
    + +

    示例 2:

    + +
    +输入:nums = [0,0,1,1,1,1,2,3,3]
    +输出:7, nums = [0,0,1,1,2,3,3]
    +解释:函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。 不需要考虑数组中超出新长度后面的元素。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 3 * 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • nums 已按升序排列
    • +
    + + +## 解法 + + + +从数组下标 1 开始遍历数组。 + +用计数器 `cnt` 记录当前数字重复出现的次数,`cnt` 的最小计数为 0;用 `cur` 记录新数组下个待覆盖的元素位置。 + +遍历时,若当前元素 `nums[i]` 与上个元素 `nums[i-1]` 相同,则计数器 +1,否则计数器重置为 0。如果计数器小于 2,说明当前元素 `nums[i]` 可以添加到新数组中,即:`nums[cur] = nums[i]`,同时 `cur++`。 + +遍历结果,返回 `cur` 值即可。 + + + +### **Python3** + + + +```python +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + n = len(nums) + cnt, cur = 0, 1 + for i in range(1, n): + if nums[i] == nums[i - 1]: + cnt += 1 + else: + cnt = 0 + if cnt < 2: + nums[cur] = nums[i] + cur += 1 + return cur +``` + +### **Java** + + + +```java +class Solution { + public int removeDuplicates(int[] nums) { + int cnt = 0, cur = 1; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else cnt = 0; + if (cnt < 2) nums[cur++] = nums[i]; + } + return cur; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + int n = nums.size(); + int cnt = 0, cur = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] == nums[i - 1]) ++cnt; + else cnt = 0; + if (cnt < 2) nums[cur++] = nums[i]; + } + return cur; + } +}; +``` + +### **C#** + +```cs +public class Solution { + public int RemoveDuplicates(int[] nums) { + int cnt = 0, cur = 1; + for (int i = 1; i < nums.Length; ++i) + { + if (nums[i] == nums[i - 1]) ++cnt; + else cnt = 0; + if (cnt < 2) nums[cur++] = nums[i]; + } + return cur; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function (nums) { + if (nums.length == 0) return 0; + let len = nums.length; + let j = 0; + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] != nums[i - 1] || nums[i] != nums[i + 1]) { + nums[j++] = nums[i]; + } + } + nums[j] = nums[len - 1]; + return j + 1; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0081.leetcode81 Search in Rotated Sorted Array II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0081.leetcode81 Search in Rotated Sorted Array II-zh.md" new file mode 100644 index 00000000..11aa74cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0081.leetcode81 Search in Rotated Sorted Array II-zh.md" @@ -0,0 +1,141 @@ +# [81. 搜索旋转排序数组 II](https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0081.Search%20in%20Rotated%20Sorted%20Array%20II/README_EN.md) + +## 题目描述 + + + +

    已知存在一个按非降序排列的整数数组 nums ,数组中的值不必互不相同。

    + +

    在传递给函数之前,nums 在预先未知的某个下标 k0 <= k < nums.length)上进行了 旋转 ,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,4,4,5,6,6,7] 在下标 5 处经旋转后可能变为 [4,5,6,6,7,0,1,2,4,4]

    + +

    给你 旋转后 的数组 nums 和一个整数 target ,请你编写一个函数来判断给定的目标值是否存在于数组中。如果 nums 中存在这个目标值 target ,则返回 true ,否则返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,5,6,0,0,1,2], target = 0
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,5,6,0,0,1,2], target = 3
    +输出:false
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5000
    • +
    • -104 <= nums[i] <= 104
    • +
    • 题目数据保证 nums 在预先未知的某个下标上进行了旋转
    • +
    • -104 <= target <= 104
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 这是 搜索旋转排序数组 的延伸题目,本题中的 nums  可能包含重复元素。
    • +
    • 这会影响到程序的时间复杂度吗?会有怎样的影响,为什么?
    • +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def search(self, nums: List[int], target: int) -> bool: + l, r = 0, len(nums) - 1 + while l <= r: + mid = (l + r) >> 1 + if nums[mid] == target: + return True + if nums[mid] < nums[r] or nums[mid] < nums[l]: + if target > nums[mid] and target <= nums[r]: + l = mid + 1 + else: + r = mid - 1 + elif nums[mid] > nums[l] or nums[mid] > nums[r]: + if target < nums[mid] and target >= nums[l]: + r = mid - 1 + else: + l = mid + 1 + else: + r -= 1 + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean search(int[] nums, int target) { + int l = 0, r = nums.length - 1; + while (l <= r) { + int mid = (l + r) >>> 1; + if (nums[mid] == target) return true; + if (nums[mid] < nums[r] || nums[mid] < nums[l]) { + if (target > nums[mid] && target <= nums[r]) l = mid + 1; + else r = mid - 1; + } else if (nums[mid] > nums[l] || nums[mid] > nums[r]) { + if (target < nums[mid] && target >= nums[l]) r = mid - 1; + else l = mid + 1; + } else r--; + } + return false; + } +} +``` + +### **C++** + + + +```cpp +class Solution { +public: + bool search(vector& nums, int target) { + int l = 0, r = nums.size() - 1; + while (l <= r) { + int mid = (l + r) >> 1; + if (nums[mid] == target) return true; + if (nums[mid] < nums[r] || nums[mid] < nums[l]) { + if (target > nums[mid] && target <= nums[r]) l = mid + 1; + else r = mid - 1; + } else if (nums[mid] > nums[l] || nums[mid] > nums[r]) { + if (target < nums[mid] && target >= nums[l]) r = mid - 1; + else l = mid + 1; + } else r--; + } + return false; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0082.leetcode82 Remove Duplicates from Sorted List II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0082.leetcode82 Remove Duplicates from Sorted List II-zh.md" new file mode 100644 index 00000000..bc21d0d8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0082.leetcode82 Remove Duplicates from Sorted List II-zh.md" @@ -0,0 +1,143 @@ +# [82. 删除排序链表中的重复元素 II](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0082.Remove%20Duplicates%20from%20Sorted%20List%20II/README_EN.md) + +## 题目描述 + + + +

    存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。

    + +

    返回同样按升序排列的结果链表。

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,3,4,4,5]
    +输出:[1,2,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [1,1,1,2,3]
    +输出:[2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点数目在范围 [0, 300]
    • +
    • -100 <= Node.val <= 100
    • +
    • 题目数据保证链表已经按升序排列
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + dummy = ListNode(-1, head) + cur = dummy + while cur.next and cur.next.next: + if cur.next.val == cur.next.next.val: + val = cur.next.val + while cur.next and cur.next.val == val: + cur.next = cur.next.next + else: + cur = cur.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(-1, head); + ListNode cur = dummy; + while (cur.next != null && cur.next.next != null) { + if (cur.next.val == cur.next.next.val) { + int val = cur.next.val; + while (cur.next != null && cur.next.val == val) { + cur.next = cur.next.next; + } + } else { + cur = cur.next; + } + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* dummy = new ListNode(-1, head); + ListNode* cur = dummy; + while (cur->next != nullptr && cur->next->next != nullptr) { + if (cur->next->val == cur->next->next->val) { + int val = cur->next->val; + while (cur->next != nullptr && cur->next->val == val) { + cur->next = cur->next->next; + } + } else { + cur = cur->next; + } + } + return dummy->next; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0083.leetcode83 Remove Duplicates from Sorted List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0083.leetcode83 Remove Duplicates from Sorted List-zh.md" new file mode 100644 index 00000000..ba31bc2a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0083.leetcode83 Remove Duplicates from Sorted List-zh.md" @@ -0,0 +1,148 @@ +# [83. 删除排序链表中的重复元素](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0083.Remove%20Duplicates%20from%20Sorted%20List/README_EN.md) + +## 题目描述 + + + +

    存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次

    + +

    返回同样按升序排列的结果链表。

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,1,2]
    +输出:[1,2]
    +
    + +

    示例 2:

    + +
    +输入:head = [1,1,2,3,3]
    +输出:[1,2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点数目在范围 [0, 300]
    • +
    • -100 <= Node.val <= 100
    • +
    • 题目数据保证链表已经按升序排列
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + cur = head + while cur and cur.next: + if cur.val == cur.next.val: + cur.next = cur.next.next + else: + cur = cur.next + return head +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode cur = head; + while (cur != null && cur.next != null) { + if (cur.val == cur.next.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return head; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* cur = head; + while (cur != nullptr && cur->next != nullptr) { + if (cur->val == cur->next->val) { + cur->next = cur->next->next; + } else { + cur = cur->next; + } + } + return head; + } +}; +``` + +### **Go** + +```go +func deleteDuplicates(head *ListNode) *ListNode { + current := head + for current != nil && current.Next != nil { + if current.Val == current.Next.Val { + current.Next = current.Next.Next + } else { + current = current.Next + } + } + return head +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0084.leetcode84 Largest Rectangle in Histogram-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0084.leetcode84 Largest Rectangle in Histogram-zh.md" new file mode 100644 index 00000000..30371c28 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0084.leetcode84 Largest Rectangle in Histogram-zh.md" @@ -0,0 +1,61 @@ +# [84. 柱状图中最大的矩形](https://leetcode-cn.com/problems/largest-rectangle-in-histogram) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0084.Largest%20Rectangle%20in%20Histogram/README_EN.md) + +## 题目描述 + + + +

    给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

    + +

    求在该柱状图中,能够勾勒出来的矩形的最大面积。

    + +

     

    + +

    + +

    以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]

    + +

     

    + +

    + +

    图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

    + +

     

    + +

    示例:

    + +
    输入: [2,1,5,6,2,3]
    +输出: 10
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0085.leetcode85 Maximal Rectangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0085.leetcode85 Maximal Rectangle-zh.md" new file mode 100644 index 00000000..2f8776ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0085.leetcode85 Maximal Rectangle-zh.md" @@ -0,0 +1,89 @@ +# [85. 最大矩形](https://leetcode-cn.com/problems/maximal-rectangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0085.Maximal%20Rectangle/README_EN.md) + +## 题目描述 + + + +

    给定一个仅包含 01 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
    +输出:6
    +解释:最大矩形如上图所示。
    +
    + +

    示例 2:

    + +
    +输入:matrix = []
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:matrix = [["0"]]
    +输出:0
    +
    + +

    示例 4:

    + +
    +输入:matrix = [["1"]]
    +输出:1
    +
    + +

    示例 5:

    + +
    +输入:matrix = [["0","0"]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • rows == matrix.length
    • +
    • cols == matrix[0].length
    • +
    • 0 <= row, cols <= 200
    • +
    • matrix[i][j]'0''1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0086.leetcode86 Partition List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0086.leetcode86 Partition List-zh.md" new file mode 100644 index 00000000..8a400118 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0086.leetcode86 Partition List-zh.md" @@ -0,0 +1,154 @@ +# [86. 分隔链表](https://leetcode-cn.com/problems/partition-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0086.Partition%20List/README_EN.md) + +## 题目描述 + + + +

    给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

    + +

    你应当 保留 两个分区中每个节点的初始相对位置。

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,4,3,2,5,2], x = 3
    +输出:[1,2,2,4,3,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [2,1], x = 2
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目在范围 [0, 200]
    • +
    • -100 <= Node.val <= 100
    • +
    • -200 <= x <= 200
    • +
    + +## 解法 + + + +创建两个链表,一个存放小于 `x` 的节点,另一个存放大于等于 `x` 的节点,之后进行拼接即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def partition(self, head: ListNode, x: int) -> ListNode: + l1, l2 = ListNode(), ListNode() + cur1, cur2 = l1, l2 + while head: + if head.val < x: + cur1.next = head + cur1 = cur1.next + else: + cur2.next = head + cur2 = cur2.next + head = head.next + cur1.next = l2.next + cur2.next = None + return l1.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode partition(ListNode head, int x) { + ListNode l1 = new ListNode(0); + ListNode l2 = new ListNode(0); + ListNode cur1 = l1, cur2 = l2; + while (head != null) { + if (head.val < x) { + cur1.next = head; + cur1 = cur1.next; + } else { + cur2.next = head; + cur2 = cur2.next; + } + head = head.next; + } + cur1.next = l2.next; + cur2.next = null; + return l1.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + ListNode* l1 = new ListNode(); + ListNode* l2 = new ListNode(); + ListNode* cur1 = l1; + ListNode* cur2 = l2; + while (head != nullptr) { + if (head->val < x) { + cur1->next = head; + cur1 = cur1->next; + } else { + cur2->next = head; + cur2 = cur2->next; + } + head = head->next; + } + cur1->next = l2->next; + cur2->next = nullptr; + return l1->next; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0087.leetcode87 Scramble String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0087.leetcode87 Scramble String-zh.md" new file mode 100644 index 00000000..a3c24bac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0087.leetcode87 Scramble String-zh.md" @@ -0,0 +1,158 @@ +# [87. 扰乱字符串](https://leetcode-cn.com/problems/scramble-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0087.Scramble%20String/README_EN.md) + +## 题目描述 + + + +使用下面描述的算法可以扰乱字符串 s 得到字符串 t : +
      +
    1. 如果字符串的长度为 1 ,算法停止
    2. +
    3. 如果字符串的长度 > 1 ,执行下述步骤: +
        +
      • 在一个随机下标处将字符串分割成两个非空的子字符串。即,如果已知字符串 s ,则可以将其分成两个子字符串 xy ,且满足 s = x + y
      • +
      • 随机 决定是要「交换两个子字符串」还是要「保持这两个子字符串的顺序不变」。即,在执行这一步骤之后,s 可能是 s = x + y 或者 s = y + x
      • +
      • xy 这两个子字符串上继续从步骤 1 开始递归执行此算法。
      • +
      +
    4. +
    + +

    给你两个 长度相等 的字符串 s1 和 s2,判断 s2 是否是 s1 的扰乱字符串。如果是,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:s1 = "great", s2 = "rgeat"
    +输出:true
    +解释:s1 上可能发生的一种情形是:
    +"great" --> "gr/eat" // 在一个随机下标处分割得到两个子字符串
    +"gr/eat" --> "gr/eat" // 随机决定:「保持这两个子字符串的顺序不变」
    +"gr/eat" --> "g/r / e/at" // 在子字符串上递归执行此算法。两个子字符串分别在随机下标处进行一轮分割
    +"g/r / e/at" --> "r/g / e/at" // 随机决定:第一组「交换两个子字符串」,第二组「保持这两个子字符串的顺序不变」
    +"r/g / e/at" --> "r/g / e/ a/t" // 继续递归执行此算法,将 "at" 分割得到 "a/t"
    +"r/g / e/ a/t" --> "r/g / e/ a/t" // 随机决定:「保持这两个子字符串的顺序不变」
    +算法终止,结果字符串和 s2 相同,都是 "rgeat"
    +这是一种能够扰乱 s1 得到 s2 的情形,可以认为 s2 是 s1 的扰乱字符串,返回 true
    +
    + +

    示例 2:

    + +
    +输入:s1 = "abcde", s2 = "caebd"
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:s1 = "a", s2 = "a"
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • s1.length == s2.length
    • +
    • 1 <= s1.length <= 30
    • +
    • s1s2 由小写英文字母组成
    • +
    + + +## 解法 + + + +动态规划法。 + +假设 `dp[i][j][len]` 表示从字符串 S 中 i 开始长度为 len 的字符串是否能变换为从字符串 T 中 j 开始长度为 len 的字符串。题目可转变为求 `dp[0][0][n]`。 + +在 `len` 为 1 的情况下,只需要判断 `S[i]` 是否等于 `T[j]`。所以可以对 dp 进行初始化:`dp[i][j][1] = S[i] == T[j]`,其中,`i,j ∈ [0, n)`。 + +在 `len` 大于 1 的情况下,枚举 S 的长度 `i ∈ [1, len-1]`,`dp[i1][i2][i]` 表示 S1 能变成 T1,`dp[i1 + i][i2 + i][len - i]` 表示 S2 能变成 T2;或者 S1 能变成 T2,S2 能变成 T1。 + +![](https://cdn.jsdelivr.net/gh/dbdgs/dbdgs.github.io/docs/.vuepress/public/img/leetcode87-demo.png) + + + +### **Python3** + + + +```python +class Solution: + def isScramble(self, s1: str, s2: str) -> bool: + n = len(s1) + dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] + for i in range(n): + for j in range(n): + dp[i][j][1] = s1[i] == s2[j] + # 枚举长度区间[2, n] + for l in range(2, n + 1): + # 枚举s1的起始位置 + for i1 in range(n - l + 1): + # 枚举s2的起始位置 + for i2 in range(n - l + 1): + # 枚举分割的位置 + for i in range(1, l): + if dp[i1][i2][i] and dp[i1 + i][i2 + i][l - i]: + dp[i1][i2][l] = True + break + if dp[i1][i2 + l - i][i] and dp[i1 + i][i2][l - i]: + dp[i1][i2][l] = True + break + return dp[0][0][n] +``` + +### **Java** + + + +```java +class Solution { + public boolean isScramble(String s1, String s2) { + // 题目已说明 s1.length == s2.length,无须再判断长度是否相等 + int n = s1.length(); + boolean[][][] dp = new boolean[n][n][n + 1]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + // 长度为1时,两字符必须相等 + dp[i][j][1] = s1.charAt(i) == s2.charAt(j); + } + } + // 枚举长度区间[2, n] + for (int len = 2; len <= n; ++len) { + // 枚举s1的起始位置 + for (int i1 = 0; i1 <= n - len; ++i1) { + // 枚举s2的起始位置 + for (int i2 = 0; i2 <= n - len; ++i2) { + // 枚举分割的位置 + for (int i = 1; i < len; ++i) { + if (dp[i1][i2][i] && dp[i1 + i][i2 + i][len - i]) { + dp[i1][i2][len] = true; + break; + } + if (dp[i1][i2 + len - i][i] && dp[i1 + i][i2][len - i]) { + dp[i1][i2][len] = true; + break; + } + } + } + } + } + return dp[0][0][n]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0088.leetcode88 Merge Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0088.leetcode88 Merge Sorted Array-zh.md" new file mode 100644 index 00000000..f0950788 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0088.leetcode88 Merge Sorted Array-zh.md" @@ -0,0 +1,138 @@ +# [88. 合并两个有序数组](https://leetcode-cn.com/problems/merge-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0088.Merge%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给你两个有序整数数组 nums1 nums2,请你将 nums2 合并到 nums1 使 nums1 成为一个有序数组。

    + +

    初始化 nums1nums2 的元素数量分别为 mn 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nums2 的元素。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
    +输出:[1,2,2,3,5,6]
    +
    + +

    示例 2:

    + +
    +输入:nums1 = [1], m = 1, nums2 = [], n = 0
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums1.length == m + n
    • +
    • nums2.length == n
    • +
    • 0 <= m, n <= 200
    • +
    • 1 <= m + n <= 200
    • +
    • -109 <= nums1[i], nums2[i] <= 109
    • +
    + + +## 解法 + + + +双指针解决。 + + + +### **Python3** + + + +```python +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + i, j, k = m - 1, n - 1, m + n - 1 + while j >= 0: + if i >= 0 and nums1[i] > nums2[j]: + nums1[k] = nums1[i] + i -= 1 + else: + nums1[k] = nums2[j] + j -= 1 + k -= 1 +``` + +### **Java** + + + +```java +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = m - 1, j = n - 1, k = m + n - 1; + while (j >= 0) { + if (i >= 0 && nums1[i] > nums2[j]) { + nums1[k--] = nums1[i--]; + } else { + nums1[k--] = nums2[j--]; + } + } + } +} +``` + +### **Go** + +```go +func merge(nums1 []int, m int, nums2 []int, n int) { + i, j, k := m - 1, n - 1, m + n - 1 + for j >= 0 { + if i >= 0 && nums1[i] > nums2[j] { + nums1[k] = nums1[i] + i-- + } else { + nums1[k] = nums2[j] + j-- + } + k-- + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number} m + * @param {number[]} nums2 + * @param {number} n + * @return {void} Do not return anything, modify nums1 in-place instead. + */ +var merge = function (nums1, m, nums2, n) { + let i = m - 1, + j = n - 1, + k = m + n - 1; + while (j >= 0) { + if (i >= 0 && nums1[i] > nums2[j]) { + nums1[k--] = nums1[i--]; + } else { + nums1[k--] = nums2[j--]; + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0089.leetcode89 Gray Code-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0089.leetcode89 Gray Code-zh.md" new file mode 100644 index 00000000..7a672b13 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0089.leetcode89 Gray Code-zh.md" @@ -0,0 +1,73 @@ +# [89. 格雷编码](https://leetcode-cn.com/problems/gray-code) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0089.Gray%20Code/README_EN.md) + +## 题目描述 + + + +

    格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。

    + +

    给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。

    + +

    格雷编码序列必须以 0 开头。

    + +

     

    + +

    示例 1:

    + +
    输入: 2
    +输出: [0,1,3,2]
    +解释:
    +00 - 0
    +01 - 1
    +11 - 3
    +10 - 2
    +
    +对于给定的 n,其格雷编码序列并不唯一。
    +例如,[0,2,3,1] 也是一个有效的格雷编码序列。
    +
    +00 - 0
    +10 - 2
    +11 - 3
    +01 - 1
    + +

    示例 2:

    + +
    输入: 0
    +输出: [0]
    +解释: 我们定义格雷编码序列必须以 0 开头。
    +     给定编码总位数为 n 的格雷编码序列,其长度为 2nn = 0 时,长度为 20 = 1。
    +     因此,当 n = 0 时,其格雷编码序列为 [0]。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0090.leetcode90 Subsets II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0090.leetcode90 Subsets II-zh.md" new file mode 100644 index 00000000..a3d30dcc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0090.leetcode90 Subsets II-zh.md" @@ -0,0 +1,104 @@ +# [90. 子集 II](https://leetcode-cn.com/problems/subsets-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0090.Subsets%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。

    + +

    解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

    + +
    +
    +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,2]
    +输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
    +
    + +

    示例 2:

    + +
    +输入:nums = [0]
    +输出:[[],[0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10
    • +
    • -10 <= nums[i] <= 10
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + def dfs(nums, i, res, path): + res.append(copy.deepcopy(path)) + for j in range(i, len(nums)): + if j != i and nums[j] == nums[j - 1]: + continue + path.append(nums[j]) + dfs(nums, j + 1, res, path) + path.pop() + res, path = [], [] + nums.sort() + dfs(nums, 0, res, path) + return res +``` + +### **Java** + + + +```java +class Solution { + public List> subsetsWithDup(int[] nums) { + List path = new ArrayList<>(); + List> res = new ArrayList<>(); + Arrays.sort(nums); + dfs(nums, 0, res, path); + return res; + } + + private void dfs(int[] nums, int i, List> res, List path) { + res.add(new ArrayList<>(path)); + for (int j = i; j < nums.length; ++j) { + if (j != i && nums[j] == nums[j - 1]) { + continue; + } + path.add(nums[j]); + dfs(nums, i + 1, res, path); + path.remove(path.size() - 1); + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0091.leetcode91 Decode Ways-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0091.leetcode91 Decode Ways-zh.md" new file mode 100644 index 00000000..36ca8f4f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0091.leetcode91 Decode Ways-zh.md" @@ -0,0 +1,257 @@ +# [91. 解码方法](https://leetcode-cn.com/problems/decode-ways) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0091.Decode%20Ways/README_EN.md) + +## 题目描述 + + + +

    一条包含字母 A-Z 的消息通过以下映射进行了 编码

    + +
    +'A' -> 1
    +'B' -> 2
    +...
    +'Z' -> 26
    +
    + +

    解码 已编码的消息,所有数字必须基于上述映射的方法,反向映射回字母(可能有多种方法)。例如,"11106" 可以映射为:

    + +
      +
    • "AAJF" ,将消息分组为 (1 1 10 6)
    • +
    • "KJF" ,将消息分组为 (11 10 6)
    • +
    + +

    注意,消息不能分组为  (1 11 06) ,因为 "06" 不能映射为 "F" ,这是由于 "6""06" 在映射中并不等价。

    + +

    给你一个只含数字的 非空 字符串 s ,请计算并返回 解码 方法的 总数

    + +

    题目数据保证答案肯定是一个 32 位 的整数。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "12"
    +输出:2
    +解释:它可以解码为 "AB"(1 2)或者 "L"(12)。
    +
    + +

    示例 2:

    + +
    +输入:s = "226"
    +输出:3
    +解释:它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
    +
    + +

    示例 3:

    + +
    +输入:s = "0"
    +输出:0
    +解释:没有字符映射到以 0 开头的数字。
    +含有 0 的有效映射是 'J' -> "10" 和 'T'-> "20" 。
    +由于没有字符,因此没有有效的方法对此进行解码,因为所有数字都需要映射。
    +
    + +

    示例 4:

    + +
    +输入:s = "06"
    +输出:0
    +解释:"06" 不能映射到 "F" ,因为字符串含有前导 0("6""06" 在映射中并不等价)。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s 只包含数字,并且可能包含前导零。
    • +
    + + +## 解法 + + + +动态规划法。 + +假设 `dp[i]` 表示字符串 s 的前 i 个字符 `s[1..i]` 的解码方法数。 + +考虑最后一次解码中使用了 s 中的哪些字符: + +- 第一种情况是我们使用了一个字符,即 `s[i]` 进行解码,那么只要 `s[i]≠0`,它就可以被解码成 `A∼I` 中的某个字母。由于剩余的前 `i-1` 个字符的解码方法数为 `dp[i-1]`,所以 `dp[i] = dp[i-1]`。 +- 第二种情况是我们使用了两个字符,即 `s[i-1]` 和 `s[i]` 进行编码。与第一种情况类似,`s[i-1]` 不能等于 0,并且 `s[i-1]` 和 `s[i]` 组成的整数必须小于等于 26,这样它们就可以被解码成 `J∼Z` 中的某个字母。由于剩余的前 `i-2` 个字符的解码方法数为 `dp[i-2]`,所以 `dp[i] = dp[i-2]`。 + +将上面的两种状态转移方程在对应的条件满足时进行累加,即可得到 `dp[i]`的值。在动态规划完成后,最终的答案即为 `dp[n]`。 + +由于 `dp[i]` 的值仅与 `dp[i-1]` 和 `dp[i-2]` 有关,因此可以不定义 dp 数组,可以仅使用三个变量进行状态转移。 + + + +### **Python3** + + + +```python +class Solution: + def numDecodings(self, s: str) -> int: + n = len(s) + dp = [0] * (n + 1) + dp[0] = 1 + for i in range(1, n + 1): + if s[i - 1] != '0': + dp[i] += dp[i - 1] + if i > 1 and s[i - 2] != '0' and (int(s[i - 2]) * 10 + int(s[i - 1]) <= 26): + dp[i] += dp[i - 2] + return dp[n] +``` + +优化空间: + +```python +class Solution: + def numDecodings(self, s: str) -> int: + n = len(s) + a, b, c = 0, 1, 0 + for i in range(1, n + 1): + c = 0 + if s[i - 1] != '0': + c += b + if i > 1 and s[i - 2] != '0' and (int(s[i - 2]) * 10 + int(s[i - 1]) <= 26): + c += a + a, b = b, c + return c +``` + +### **Java** + + + +```java +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s.charAt(i - 1) != '0') { + dp[i] += dp[i - 1]; + } + if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + s.charAt(i - 1) - '0') <= 26) { + dp[i] += dp[i - 2]; + } + } + return dp[n]; + } +} +``` + +优化空间: + +```java +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int a = 0, b = 1, c = 0; + for (int i = 1; i <= n; ++i) { + c = 0; + if (s.charAt(i - 1) != '0') { + c += b; + } + if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + s.charAt(i - 1) - '0') <= 26) { + c += a; + } + a = b; + b = c; + } + return c; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); + vector dp(n + 1); + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + if (s[i - 1] != '0') { + dp[i] += dp[i - 1]; + } + if (i > 1 && s[i - 2] != '0') { + if ((s[i - 2] - '0') * 10 + s[i - 1] - '0' <= 26) { + dp[i] += dp[i - 2]; + } + } + } + return dp[n]; + } +}; +``` + +### **Go** + +```go +func numDecodings(s string) int { + n := len(s) + dp := make([]int, n+1) + dp[0] = 1 + for i := 1; i <= n; i++ { + if s[i-1] != '0' { + dp[i] += dp[i-1] + } + if i > 1 && s[i-2] != '0' { + if (s[i-2]-'0')*10+(s[i-1]-'0') <= 26 { + dp[i] += dp[i-2] + } + } + } + return dp[n] +} +``` + +### **C#** + +```cs +public class Solution { + public int NumDecodings(string s) { + if (s.Length == 0) return 0; + + var f0 = 1; + var f1 = 1; + var f2 = 1; + for (var i = 0; i < s.Length; ++i) + { + f0 = f1; + f1 = f2; + f2 = 0; + var two = i > 0 ? int.Parse(string.Format("{0}{1}", s[i - 1], s[i])) : 0; + if (two >= 10 && two <= 26) + { + f2 += f0; + } + if (s[i] != '0') + { + f2 += f1; + } + } + return f2; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0092.leetcode92 Reverse Linked List II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0092.leetcode92 Reverse Linked List II-zh.md" new file mode 100644 index 00000000..a874a730 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0092.leetcode92 Reverse Linked List II-zh.md" @@ -0,0 +1,246 @@ +# [92. 反转链表 II](https://leetcode-cn.com/problems/reverse-linked-list-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0092.Reverse%20Linked%20List%20II/README_EN.md) + +## 题目描述 + + + +给你单链表的头指针 head 和两个整数 leftright ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。 +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4,5], left = 2, right = 4
    +输出:[1,4,3,2,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [5], left = 1, right = 1
    +输出:[5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点数目为 n
    • +
    • 1 <= n <= 500
    • +
    • -500 <= Node.val <= 500
    • +
    • 1 <= left <= right <= n
    • +
    + +

     

    + +

    进阶: 你可以使用一趟扫描完成反转吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: + if head is None or head.next is None or left == right: + return head + dummy = ListNode(0, head) + pre = dummy + for _ in range(left - 1): + pre = pre.next + p, q = pre, pre.next + cur = q + for _ in range(right - left + 1): + t = cur.next + cur.next = pre + pre, cur = cur, t + p.next = pre + q.next = cur + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseBetween(ListNode head, int left, int right) { + if (head == null || head.next == null || left == right) { + return head; + } + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + for (int i = 0; i < left - 1; ++i) { + pre = pre.next; + } + ListNode p = pre; + ListNode q = pre.next; + ListNode cur = q; + for (int i = 0; i < right - left + 1; ++i) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} left + * @param {number} right + * @return {ListNode} + */ +var reverseBetween = function(head, left, right) { + if (!head || !head.next || left == right) { + return head; + } + const dummy = new ListNode(0, head); + let pre = dummy; + for (let i = 0; i < left - 1; ++i) { + pre = pre.next; + } + const p = pre; + const q = pre.next; + let cur = q; + for (let i = 0; i < right - left + 1; ++i) { + const t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int left, int right) { + if (head == nullptr || head->next == nullptr || left == right) { + return head; + } + ListNode *dummy = new ListNode(0, head); + ListNode *pre = dummy; + for (int i = 0; i < left - 1; ++i) { + pre = pre->next; + } + ListNode *p = pre, *q = pre->next; + ListNode *cur = q; + for (int i = 0; i < right - left + 1; ++i) { + ListNode *t = cur->next; + cur->next = pre; + pre = cur; + cur = t; + } + p->next = pre; + q->next = cur; + return dummy->next; + } +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseBetween(ListNode head, int left, int right) { + if (head == null || head.next == null || left == right) + { + return head; + } + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + for (int i = 0; i < left - 1; ++i) + { + pre = pre.next; + } + ListNode p = pre; + ListNode q = pre.next; + ListNode cur = q; + for (int i = 0; i < right - left + 1; ++i) + { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0093.leetcode93 Restore IP Addresses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0093.leetcode93 Restore IP Addresses-zh.md" new file mode 100644 index 00000000..bb4683b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0093.leetcode93 Restore IP Addresses-zh.md" @@ -0,0 +1,90 @@ +# [93. 复原 IP 地址](https://leetcode-cn.com/problems/restore-ip-addresses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0093.Restore%20IP%20Addresses/README_EN.md) + +## 题目描述 + + + +

    给定一个只包含数字的字符串,用以表示一个 IP 地址,返回所有可能从 s 获得的 有效 IP 地址 。你可以按任何顺序返回答案。

    + +

    有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

    + +

    例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "25525511135"
    +输出:["255.255.11.135","255.255.111.35"]
    +
    + +

    示例 2:

    + +
    +输入:s = "0000"
    +输出:["0.0.0.0"]
    +
    + +

    示例 3:

    + +
    +输入:s = "1111"
    +输出:["1.1.1.1"]
    +
    + +

    示例 4:

    + +
    +输入:s = "010010"
    +输出:["0.10.0.10","0.100.1.0"]
    +
    + +

    示例 5:

    + +
    +输入:s = "101023"
    +输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 3000
    • +
    • s 仅由数字组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0094.leetcode94 Binary Tree Inorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0094.leetcode94 Binary Tree Inorder Traversal-zh.md" new file mode 100644 index 00000000..d120336d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0094.leetcode94 Binary Tree Inorder Traversal-zh.md" @@ -0,0 +1,251 @@ +# [94. 二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0094.Binary%20Tree%20Inorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树的根节点 root ,返回它的 中序 遍历。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,null,2,3]
    +输出:[1,3,2]
    +
    + +

    示例 2:

    + +
    +输入:root = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:root = [1]
    +输出:[1]
    +
    + +

    示例 4:

    + +
    +输入:root = [1,2]
    +输出:[2,1]
    +
    + +

    示例 5:

    + +
    +输入:root = [1,null,2]
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [0, 100]
    • +
    • -100 <= Node.val <= 100
    • +
    + +

     

    + +

    进阶: 递归算法很简单,你可以通过迭代算法完成吗?

    + + +## 解法 + + + +递归遍历或利用栈实现非递归遍历。 + +非递归的思路如下: + +1. 定义一个栈 +2. 将树的左节点依次入栈 +3. 左节点为空时,弹出栈顶元素并处理 +4. 重复 2-3 的操作 + + + +### **Python3** + + + +递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + def inorder(root): + if root: + inorder(root.left) + res.append(root.val) + inorder(root.right) + res = [] + inorder(root) + return res +``` + +非递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: TreeNode) -> List[int]: + s = [] + res = [] + while root or s: + if root: + s.append(root) + root = root.left + else: + root = s.pop() + res.append(root.val) + root = root.right + return res +``` + +### **Java** + + + +递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private List res; + + public List inorderTraversal(TreeNode root) { + res = new ArrayList<>(); + inorder(root); + return res; + } + + private void inorder(TreeNode root) { + if (root != null) { + inorder(root.left); + res.add(root.val); + inorder(root.right); + } + } +} +``` + +非递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List inorderTraversal(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + List res = new ArrayList<>(); + Deque s = new ArrayDeque<>(); + while (root != null || !s.isEmpty()) { + if (root != null) { + s.push(root); + root = root.left; + } else { + root = s.pop(); + res.add(root.val); + root = root.right; + } + } + return res; + } +} +``` +### **JavaScript** + +递归: + +```js +var inorderTraversal = function(root) { + let res = []; + function inorder(root){ + if(root){ + inorder(root.left); + res.push(root.val); + inorder(root.right); + } + } + inorder(root); + return res; +}; +``` +非递归: + +```js +var inorderTraversal = function (root) { + let res = [], stk = []; + let cur = root; + while (cur || stk.length !== 0) { + while (cur) { + stk.push(cur); + cur = cur.left; + } + let top = stk.pop(); + res.push(top.val); + cur = top.right; + + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0095.leetcode95 Unique Binary Search Trees II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0095.leetcode95 Unique Binary Search Trees II-zh.md" new file mode 100644 index 00000000..fded2e73 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0095.leetcode95 Unique Binary Search Trees II-zh.md" @@ -0,0 +1,71 @@ +# [95. 不同的二叉搜索树 II](https://leetcode-cn.com/problems/unique-binary-search-trees-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0095.Unique%20Binary%20Search%20Trees%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树

    + +

     

    + +

    示例:

    + +
    输入:3
    +输出:
    +[
    +  [1,null,3,2],
    +  [3,2,null,1],
    +  [3,1,null,null,2],
    +  [2,1,3],
    +  [1,null,2,null,3]
    +]
    +解释:
    +以上的输出对应以下 5 种不同结构的二叉搜索树:
    +
    +   1         3     3      2      1
    +    \       /     /      / \      \
    +     3     2     1      1   3      2
    +    /     /       \                 \
    +   2     1         2                 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0096.leetcode96 Unique Binary Search Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0096.leetcode96 Unique Binary Search Trees-zh.md" new file mode 100644 index 00000000..d7e28894 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0096.leetcode96 Unique Binary Search Trees-zh.md" @@ -0,0 +1,105 @@ +# [96. 不同的二叉搜索树](https://leetcode-cn.com/problems/unique-binary-search-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0096.Unique%20Binary%20Search%20Trees/README_EN.md) + +## 题目描述 + + + +

    给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?

    + +

    示例:

    + +
    输入: 3
    +输出: 5
    +解释:
    +给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
    +
    +   1         3     3      2      1
    +    \       /     /      / \      \
    +     3     2     1      1   3      2
    +    /     /       \                 \
    +   2     1         2                 3
    + +## 解法 + + + +假设 n 个节点存在二叉搜索树的个数是 `G(n)`,1 为根节点,2 为根节点,...,n 为根节点,当 1 为根节点时,其左子树节点个数为 0,右子树节点个数为 n-1,同理当 2 为根节点时,其左子树节点个数为 1,右子树节点为 n-2,所以可得 `G(n) = G(0) * G(n-1) + G(1) * (n-2) + ... + G(n-1) * G(0)`。 + + + +### **Python3** + + + +```python +class Solution: + def numTrees(self, n: int) -> int: + dp = [0] * (n + 1) + dp[0] = 1 + for i in range(1, n + 1): + for j in range(i): + dp[i] += dp[j] * dp[i - j - 1] + return dp[-1] +``` + +### **Java** + + + +```java +class Solution { + public int numTrees(int n) { + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + dp[i] += dp[j] * dp[i - j - 1]; + } + } + return dp[n]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numTrees(int n) { + vector dp(n + 1); + dp[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + dp[i] += dp[j] * dp[i - j - 1]; + } + } + return dp[n]; + } +}; +``` + +### **Go** + +```go +func numTrees(n int) int { + dp := make([]int, n+1) + dp[0] = 1 + for i := 1; i <= n; i++ { + for j := 0; j < i; j++ { + dp[i] += dp[j] * dp[i-j-1] + } + } + return dp[n] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0097.leetcode97 Interleaving String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0097.leetcode97 Interleaving String-zh.md" new file mode 100644 index 00000000..f9980c9a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0097.leetcode97 Interleaving String-zh.md" @@ -0,0 +1,84 @@ +# [97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0097.Interleaving%20String/README_EN.md) + +## 题目描述 + + + +

    给定三个字符串 s1s2s3,请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。

    + +

    两个字符串 st 交错 的定义与过程如下,其中每个字符串都会被分割成若干 非空 子字符串:

    + +
      +
    • s = s1 + s2 + ... + sn
    • +
    • t = t1 + t2 + ... + tm
    • +
    • |n - m| <= 1
    • +
    • 交错s1 + t1 + s2 + t2 + s3 + t3 + ... 或者 t1 + s1 + t2 + s2 + t3 + s3 + ...
    • +
    + +

    提示:a + b 意味着字符串 ab 连接。

    + +

     

    + +

    示例 1:

    + +
    +输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:s1 = "", s2 = "", s3 = ""
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s1.length, s2.length <= 100
    • +
    • 0 <= s3.length <= 200
    • +
    • s1s2、和 s3 都由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0098.leetcode98 Validate Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0098.leetcode98 Validate Binary Search Tree-zh.md" new file mode 100644 index 00000000..c6528af4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0098.leetcode98 Validate Binary Search Tree-zh.md" @@ -0,0 +1,115 @@ +# [98. 验证二叉搜索树](https://leetcode-cn.com/problems/validate-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0098.Validate%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,判断其是否是一个有效的二叉搜索树。

    + +

    假设一个二叉搜索树具有如下特征:

    + +
      +
    • 节点的左子树只包含小于当前节点的数。
    • +
    • 节点的右子树只包含大于当前节点的数。
    • +
    • 所有左子树和右子树自身必须也是二叉搜索树。
    • +
    + +

    示例 1:

    + +
    输入:
    +    2
    +   / \
    +  1   3
    +输出: true
    +
    + +

    示例 2:

    + +
    输入:
    +    5
    +   / \
    +  1   4
    +     / \
    +    3   6
    +输出: false
    +解释: 输入为: [5,1,4,null,null,3,6]。
    +     根节点的值为 5 ,但是其右子节点值为 4 。
    +
    + + +## 解法 + + + +中序遍历,若是一个有效的二叉搜索树,那么遍历到的序列应该是单调递增的。所以只要比较判断遍历到的当前数是否 `>=` 上一个数即可。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + pre = None + def isValidBST(self, root: TreeNode) -> bool: + if not root: + return True + if not self.isValidBST(root.left): + return False + if self.pre is not None and self.pre >= root.val: + return False + self.pre = root.val + if not self.isValidBST(root.right): + return False + return True +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Integer pre = null; + public boolean isValidBST(TreeNode root) { + if (root == null) return true; + if (!isValidBST(root.left)) return false; + if (pre != null && pre >= root.val) return false; + pre = root.val; + if (!isValidBST(root.right)) return false; + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0099.leetcode99 Recover Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0099.leetcode99 Recover Binary Search Tree-zh.md" new file mode 100644 index 00000000..67cb9cee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0099.leetcode99 Recover Binary Search Tree-zh.md" @@ -0,0 +1,92 @@ +# [99. 恢复二叉搜索树](https://leetcode-cn.com/problems/recover-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0000-0099/0099.Recover%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。

    + +

    进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,3,null,null,2]
    +输出:[3,1,null,null,2]
    +解释:3 不能是 1 左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。
    +
    + +

    示例 2:

    + +
    +输入:root = [3,1,4,null,null,2]
    +输出:[2,1,4,null,null,3]
    +解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。
    + +

     

    + +

    提示:

    + +
      +
    • 树上节点的数目在范围 [2, 1000]
    • +
    • -231 <= Node.val <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + first = None + second = None + prev = None + def recoverTree(self, root: TreeNode) -> None: + """ + Do not return anything, modify root in-place instead. + """ + def dfs(root): + if root: + dfs(root.left) + if self.prev and root.val < self.prev.val: + if not self.first: + self.first = self.prev + self.second = root + self.prev = root + dfs(root.right) + dfs(root) + self.first.val, self.second.val = self.second.val, self.first.val +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0100.leetcode100 Same Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0100.leetcode100 Same Tree-zh.md" new file mode 100644 index 00000000..e457fda4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0100.leetcode100 Same Tree-zh.md" @@ -0,0 +1,178 @@ +# [100. 相同的树](https://leetcode-cn.com/problems/same-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0100.Same%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你两棵二叉树的根节点 pq ,编写一个函数来检验这两棵树是否相同。

    + +

    如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

    + +

     

    + +

    示例 1:

    + +
    +输入:p = [1,2,3], q = [1,2,3]
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:p = [1,2], q = [1,null,2]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:p = [1,2,1], q = [1,1,2]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 两棵树上的节点数目都在范围 [0, 100]
    • +
    • -104 <= Node.val <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: + if p == q: + return True + if p is None or q is None or p.val != q.val: + return False + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == q) return true; + if (p == null || q == null || p.val != q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == q) return true; + if (!p || !q || p->val != q->val) return false; + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == q { + return true + } + if p == nil || q == nil || p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function (p, q) { + if (!p && !q) return true; + if (p && q) { + return (p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) + } + return false; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0101.leetcode101 Symmetric Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0101.leetcode101 Symmetric Tree-zh.md" new file mode 100644 index 00000000..960102fa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0101.leetcode101 Symmetric Tree-zh.md" @@ -0,0 +1,162 @@ +# [101. 对称二叉树](https://leetcode-cn.com/problems/symmetric-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0101.Symmetric%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,检查它是否是镜像对称的。

    + +

     

    + +

    例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    + +
        1
    +   / \
    +  2   2
    + / \ / \
    +3  4 4  3
    +
    + +

     

    + +

    但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    + +
        1
    +   / \
    +  2   2
    +   \   \
    +   3    3
    +
    + +

     

    + +

    进阶:

    + +

    你可以运用递归和迭代两种方法解决这个问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if root is None: + return True + return self.is_symmetric(root.left, root.right) + + def is_symmetric(self, left: TreeNode, right: TreeNode) -> bool: + if left is None and right is None: + return True + if left is None or right is None or left.val != right.val: + return False + return self.is_symmetric(left.left, right.right) and self.is_symmetric(left.right, right.left) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean isSymmetric(TreeNode root) { + if (root == null) return true; + return isSymmetric(root.left, root.right); + } + + private boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null && right == null) return true; + if (left == null || right == null || left.val != right.val) return false; + return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (!root) return true; + return isSymmetric(root->left, root->right); + } + +private: + bool isSymmetric(TreeNode* left, TreeNode* right) { + if (!left && !right) return true; + if (!left && right || left && !right || left->val != right->val) return false; + return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left); + } +}; +``` +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function (root) { + let result = []; + if (!root) return result; + + let queue = []; + queue.push(root); + while (queue.length) { + let size = queue.length; + let levelItems = []; + while (size--) { + let node = queue.shift(); + levelItems.push(node.val); + if (node.left) { + queue.push(node.left); + } + if (node.right) { + queue.push(node.right); + } + } + result.push(levelItems); + } + return result; +}; + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0102.leetcode102 Binary Tree Level Order Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0102.leetcode102 Binary Tree Level Order Traversal-zh.md" new file mode 100644 index 00000000..4cbb1f7b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0102.leetcode102 Binary Tree Level Order Traversal-zh.md" @@ -0,0 +1,152 @@ +# [102. 二叉树的层序遍历](https://leetcode-cn.com/problems/binary-tree-level-order-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

    + +

     

    + +

    示例:
    +二叉树:[3,9,20,null,null,15,7],

    + +
    +    3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    +
    + +

    返回其层序遍历结果:

    + +
    +[
    +  [3],
    +  [9,20],
    +  [15,7]
    +]
    +
    + + +## 解法 + + + +队列实现。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def levelOrder(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + res = [] + q = [] + q.append(root) + while q: + size = len(q) + t = [] + for _ in range(size): + node = q.pop(0) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + t.append(node.val) + res.append(t) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrder(TreeNode root) { + if (root == null) return Collections.emptyList(); + Deque q = new ArrayDeque<>(); + q.offer(root); + List> res = new ArrayList<>(); + while (!q.isEmpty()) { + int size = q.size(); + List t = new ArrayList<>(); + while (size-- > 0) { + TreeNode node = q.poll(); + t.add(node.val); + if (node.left != null) q.offer(node.left); + if (node.right != null) q.offer(node.right); + } + res.add(t); + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + if (!root) return {}; + vector> res; + queue q{{root}}; + while (!q.empty()) { + vector oneLevel; + for (int i = q.size(); i > 0; --i) { + TreeNode* t = q.front(); + q.pop(); + oneLevel.push_back(t->val); + if (t->left) q.push(t->left); + if (t->right) q.push(t->right); + } + res.push_back(oneLevel); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0103.leetcode103 Binary Tree Zigzag Level Order Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0103.leetcode103 Binary Tree Zigzag Level Order Traversal-zh.md" new file mode 100644 index 00000000..93570dcf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0103.leetcode103 Binary Tree Zigzag Level Order Traversal-zh.md" @@ -0,0 +1,179 @@ +# [103. 二叉树的锯齿形层序遍历](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0103.Binary%20Tree%20Zigzag%20Level%20Order%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

    + +

    例如:
    +给定二叉树 [3,9,20,null,null,15,7],

    + +
    +    3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    +
    + +

    返回锯齿形层序遍历如下:

    + +
    +[
    +  [3],
    +  [20,9],
    +  [15,7]
    +]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + res = [] + q = collections.deque([root]) + left = False + while q: + size = len(q) + t = [] + for _ in range(size): + node = q.popleft() + t.append(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if left: + t.reverse() + res.append(t) + left = not left + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> zigzagLevelOrder(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Deque q = new ArrayDeque<>(); + q.offer(root); + List> res = new ArrayList<>(); + boolean left = false; + while (!q.isEmpty()) { + int size = q.size(); + List t = new ArrayList<>(); + while (size-- > 0) { + TreeNode node = q.pollFirst(); + t.add(node.val); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + if (left) { + Collections.reverse(t); + } + res.add(t); + left = !left; + } + return res; + } +} +``` + + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var zigzagLevelOrder = function (root) { + if (!root) { + return []; + } + let res = [], q = []; + q.push(root); + let leftToRight = true; + while (q.length) { + let levelSize = q.length, levelOutput = []; + for (let i = 0; i < levelSize; i++) { + let cur = q.shift(); + if (cur.left) { + q.push(cur.left); + } + if (cur.right) { + q.push(cur.right); + } + if (leftToRight) { + levelOutput.push(cur.val); + } else { + levelOutput.unshift(cur.val); + } + } + res.push(levelOutput); + leftToRight = !leftToRight; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0104.leetcode104 Maximum Depth of Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0104.leetcode104 Maximum Depth of Binary Tree-zh.md" new file mode 100644 index 00000000..415ab1a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0104.leetcode104 Maximum Depth of Binary Tree-zh.md" @@ -0,0 +1,105 @@ +# [104. 二叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,找出其最大深度。

    + +

    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

    + +

    说明: 叶子节点是指没有子节点的节点。

    + +

    示例:
    +给定二叉树 [3,9,20,null,null,15,7]

    + +
        3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    + +

    返回它的最大深度 3 。

    + + +## 解法 + + + +递归遍历左右子树,求左右子树的最大深度 +1 即可。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + l = self.maxDepth(root.left) + r = self.maxDepth(root.right) + return 1 + max(l, r) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + int l = maxDepth(root.left); + int r = maxDepth(root.right); + return 1 + Math.max(l, r); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxDepth(TreeNode* root) { + if (!root) return 0; + int l = maxDepth(root->left); + int r = maxDepth(root->right); + return max(l, r) + 1; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0105.leetcode105 Construct Binary Tree from Preorder and Inorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0105.leetcode105 Construct Binary Tree from Preorder and Inorder Traversal-zh.md" new file mode 100644 index 00000000..9d1f47a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0105.leetcode105 Construct Binary Tree from Preorder and Inorder Traversal-zh.md" @@ -0,0 +1,119 @@ +# [105. 从前序与中序遍历序列构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    根据一棵树的前序遍历与中序遍历构造二叉树。

    + +

    注意:
    +你可以假设树中没有重复的元素。

    + +

    例如,给出

    + +
    前序遍历 preorder = [3,9,20,15,7]
    +中序遍历 inorder = [9,3,15,20,7]
    + +

    返回如下的二叉树:

    + +
        3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    + + +## 解法 + + + +先遍历前序节点,对于前序的根节点,在中序节点 `[i1, i2]` 中找到根节点的位置 pos,就可以将中序节点分成:左子树 `[i1, pos - 1]`、右子树 `[pos + 1, i2]`。 + +通过左右子树的区间,可以计算出左、右子树节点的个数,假设为 m、n。然后在前序节点中,从根节点往后的 m 个节点为左子树,再往后的 n 个节点为右子树。 + +递归求解即可。 + +> 前序遍历:先遍历根节点,再遍历左右子树;中序遍历:先遍历左子树,再遍历根节点,最后遍历右子树。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + indexes = {} + def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: + def build(preorder, inorder, p1, p2, i1, i2) -> TreeNode: + if p1 > p2 or i1 > i2: + return None + root_val = preorder[p1] + pos = self.indexes[root_val] + root = TreeNode(root_val) + # pos==i1,说明只有右子树,左子树为空 + root.left = None if pos == i1 else build(preorder, inorder, p1 + 1, p1 - i1 + pos, i1, pos - 1) + # pos==i2,说明只有左子树,右子树为空 + root.right = None if pos == i2 else build(preorder, inorder, p1 - i1 + pos + 1, p2, pos + 1, i2) + return root + n = len(inorder) + for i in range(n): + self.indexes[inorder[i]] = i + return build(preorder, inorder, 0, n - 1, 0, n - 1) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private Map indexes = new HashMap<>(); + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = inorder.length; + for (int i = 0; i < n; ++i) { + indexes.put(inorder[i], i); + } + return build(preorder, inorder, 0, n - 1, 0, n - 1); + } + + private TreeNode build(int[] preorder, int[] inorder, int p1, int p2, int i1, int i2) { + if (p1 > p2 || i1 > i2) return null; + int rootVal = preorder[p1]; + int pos = indexes.get(rootVal); + TreeNode node = new TreeNode(rootVal); + // pos==i1,说明只有右子树,左子树为空 + node.left = pos == i1 ? null : build(preorder, inorder, p1 + 1, pos - i1 + p1, i1, pos - 1); + // pos==i2,说明只有左子树,右子树为空 + node.right = pos == i2 ? null : build(preorder, inorder, pos - i1 + p1 + 1, p2, pos + 1, i2); + return node; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0106.leetcode106 Construct Binary Tree from Inorder and Postorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0106.leetcode106 Construct Binary Tree from Inorder and Postorder Traversal-zh.md" new file mode 100644 index 00000000..3e1ca923 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0106.leetcode106 Construct Binary Tree from Inorder and Postorder Traversal-zh.md" @@ -0,0 +1,133 @@ +# [106. 从中序与后序遍历序列构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    根据一棵树的中序遍历与后序遍历构造二叉树。

    + +

    注意:
    +你可以假设树中没有重复的元素。

    + +

    例如,给出

    + +
    中序遍历 inorder = [9,3,15,20,7]
    +后序遍历 postorder = [9,15,7,20,3]
    + +

    返回如下的二叉树:

    + +
        3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    +
    + + +## 解法 + + + +思路同 [105](/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/README.md)。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + indexes = {} + def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: + def build(inorder, postorder, i1, i2, p1, p2): + if i1 > i2 or p1 > p2: + return None + root_val = postorder[p2] + pos = self.indexes[root_val] + root = TreeNode(root_val) + root.left = None if pos == i1 else build(inorder, postorder, i1, pos - 1, p1, p1 - i1 + pos - 1) + root.right = None if pos == i2 else build(inorder, postorder, pos + 1, i2, p1 - i1 + pos, p2 - 1) + return root + n = len(inorder) + for i in range(n): + self.indexes[inorder[i]] = i + return build(inorder, postorder, 0, n - 1, 0, n - 1) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private Map indexes = new HashMap<>(); + + public TreeNode buildTree(int[] inorder, int[] postorder) { + int n = inorder.length; + for (int i = 0; i < n; ++i) { + indexes.put(inorder[i], i); + } + return build(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1); + } + + private TreeNode build(int[] inorder, int[] postorder, int i1, int i2, int p1, int p2) { + if (i1 > i2 || p1 > p2) return null; + int rootVal = postorder[p2]; + int pos = indexes.get(rootVal); + TreeNode root = new TreeNode(rootVal); + root.left = pos == i1 ? null : build(inorder, postorder, i1, pos - 1, p1, p1 - i1 + pos - 1); + root.right = pos == i2 ? null : build(inorder, postorder, pos + 1, i2, p1 - i1 + pos, p2 - 1); + return root; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + TreeNode *buildTree(vector &inorder, vector &postorder) { + return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); + } + TreeNode *buildTree(vector &inorder, int iLeft, int iRight, vector &postorder, int pLeft, int pRight) { + if (iLeft > iRight || pLeft > pRight) return NULL; + TreeNode *cur = new TreeNode(postorder[pRight]); + int i = 0; + for (i = iLeft; i < inorder.size(); ++i) { + if (inorder[i] == cur->val) + break; + } + cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1); + cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1); + return cur; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0107.leetcode107 Binary Tree Level Order Traversal II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0107.leetcode107 Binary Tree Level Order Traversal II-zh.md" new file mode 100644 index 00000000..52015ee3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0107.leetcode107 Binary Tree Level Order Traversal II-zh.md" @@ -0,0 +1,159 @@ +# [107. 二叉树的层序遍历 II](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

    + +

    例如:
    +给定二叉树 [3,9,20,null,null,15,7],

    + +
    +    3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    +
    + +

    返回其自底向上的层序遍历为:

    + +
    +[
    +  [15,7],
    +  [9,20],
    +  [3]
    +]
    +
    + + +## 解法 + + + +同 [102](/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/README.md),最后反转一下结果即可。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + q = [root] + res = [] + while q: + size = len(q) + t = [] + for _ in range(size): + node = q.pop(0) + t.append(node.val) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + res.append(t) + return res[::-1] +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + if (root == null) return Collections.emptyList(); + Deque q = new ArrayDeque<>(); + List> res = new ArrayList<>(); + q.offer(root); + while (!q.isEmpty()) { + int size = q.size(); + List t = new ArrayList<>(); + while (size-- > 0) { + TreeNode node = q.poll(); + t.add(node.val); + if (node.left != null) q.offer(node.left); + if (node.right != null) q.offer(node.right); + } + res.add(0, t); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrderBottom = function (root) { + if (!root) { + return []; + } + let q = [], output = [], levelOutput = []; + q.push(root); + q.push(null); + while (q.length) { + let cur = q.shift(); + levelOutput.push(cur.val); + if (cur.left) { + q.push(cur.left); + } + if (cur.right) { + q.push(cur.right); + } + if (!q[0]) { + q.shift(); + output.unshift(levelOutput); + levelOutput = []; + if (q.length) { + q.push(null); + } + } + } + return output; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0108.leetcode108 Convert Sorted Array to Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0108.leetcode108 Convert Sorted Array to Binary Search Tree-zh.md" new file mode 100644 index 00000000..2d81953a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0108.leetcode108 Convert Sorted Array to Binary Search Tree-zh.md" @@ -0,0 +1,180 @@ +# [108. 将有序数组转换为二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0108.Convert%20Sorted%20Array%20to%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。

    + +

    高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [-10,-3,0,5,9]
    +输出:[0,-3,9,-10,null,5]
    +解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:
    +
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,3]
    +输出:[3,1]
    +解释:[1,3] 和 [3,1] 都是高度平衡二叉搜索树。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • nums严格递增 顺序排列
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def sortedArrayToBST(self, nums: List[int]) -> TreeNode: + def buildBST(nums, start, end): + if start > end: + return None + mid = (start + end) >> 1 + return TreeNode(nums[mid], buildBST(nums, start, mid - 1), buildBST(nums, mid + 1, end)) + + return buildBST(nums, 0, len(nums) - 1) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + return buildBST(nums, 0, nums.length - 1); + } + + private TreeNode buildBST(int[] nums, int start, int end) { + if (start > end) { + return null; + } + int mid = (start + end) >> 1; + TreeNode root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* sortedArrayToBST(vector& nums) { + return buildBST(nums, 0, nums.size() - 1); + } + +private: + TreeNode* buildBST(vector& nums, int start, int end) { + if (start > end) { + return nullptr; + } + int mid = (start + end) / 2; + TreeNode *root = new TreeNode(nums[mid]); + root->left = buildBST(nums, start, mid - 1); + root->right = buildBST(nums, mid + 1, end); + return root; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = function(nums) { + const buildBST = (nums, start, end) => { + if (start > end) { + return null; + } + const mid = (start + end) >> 1; + const root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } + + return buildBST(nums, 0, nums.length - 1); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0109.leetcode109 Convert Sorted List to Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0109.leetcode109 Convert Sorted List to Binary Search Tree-zh.md" new file mode 100644 index 00000000..3f46d0a3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0109.leetcode109 Convert Sorted List to Binary Search Tree-zh.md" @@ -0,0 +1,212 @@ +# [109. 有序链表转换二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0109.Convert%20Sorted%20List%20to%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

    + +

    本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

    + +

    示例:

    + +
    给定的有序链表: [-10, -3, 0, 5, 9],
    +
    +一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
    +
    +      0
    +     / \
    +   -3   9
    +   /   /
    + -10  5
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def sortedListToBST(self, head: ListNode) -> TreeNode: + def buildBST(nums, start, end): + if start > end: + return None + mid = (start + end) >> 1 + return TreeNode(nums[mid], buildBST(nums, start, mid - 1), buildBST(nums, mid + 1, end)) + + nums = [] + while head: + nums.append(head.val) + head = head.next + return buildBST(nums, 0, len(nums) - 1) +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode sortedListToBST(ListNode head) { + List nums = new ArrayList<>(); + for (; head != null; head = head.next) { + nums.add(head.val); + } + return buildBST(nums, 0, nums.size() - 1); + } + + private TreeNode buildBST(List nums, int start, int end) { + if (start > end) { + return null; + } + int mid = (start + end) >> 1; + TreeNode root = new TreeNode(nums.get(mid)); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* sortedListToBST(ListNode* head) { + vector nums; + for (; head != nullptr; head = head->next) { + nums.push_back(head->val); + } + return buildBST(nums, 0, nums.size() - 1); + } + +private: + TreeNode* buildBST(vector& nums, int start, int end) { + if (start > end) { + return nullptr; + } + int mid = (start + end) / 2; + TreeNode *root = new TreeNode(nums[mid]); + root->left = buildBST(nums, start, mid - 1); + root->right = buildBST(nums, mid + 1, end); + return root; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {ListNode} head + * @return {TreeNode} + */ +var sortedListToBST = function(head) { + const buildBST = (nums, start, end) => { + if (start > end) { + return null; + } + const mid = (start + end) >> 1; + const root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + } + + const nums = new Array(); + for (; head != null; head = head.next) { + nums.push(head.val); + } + return buildBST(nums, 0, nums.length - 1); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0110.leetcode110 Balanced Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0110.leetcode110 Balanced Binary Tree-zh.md" new file mode 100644 index 00000000..f93a12a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0110.leetcode110 Balanced Binary Tree-zh.md" @@ -0,0 +1,189 @@ +# [110. 平衡二叉树](https://leetcode-cn.com/problems/balanced-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0110.Balanced%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,判断它是否是高度平衡的二叉树。

    + +

    本题中,一棵高度平衡二叉树定义为:

    + +
    +

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

    +
    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,9,20,null,null,15,7]
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:root = [1,2,2,3,3,null,null,4,4]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:root = []
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数在范围 [0, 5000]
    • +
    • -104 <= Node.val <= 104
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isBalanced(self, root: TreeNode) -> bool: + def height(root): + if not root: + return 0 + return 1 + max(height(root.left), height(root.right)) + if not root: + return True + left_height, right_height = height(root.left), height(root.right) + return abs(left_height - right_height) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isBalanced(TreeNode root) { + if (root == null) { + return true; + } + int leftHeight = height(root.left); + int rightHeight = height(root.right); + return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right); + } + + private int height(TreeNode root) { + if (root == null) { + return 0; + } + int l = height(root.left); + int r = height(root.right); + return 1 + Math.max(l, r); + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ + var isBalanced = function(root) { + if (root == null) return true; + let left = root.left; + let right = root.right; + return isBalanced(left) && isBalanced(right) && Math.abs(depth(left) - depth(right)) <= 1; +}; + +function depth(root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isBalanced(TreeNode* root) { + if (root == nullptr) { + return true; + } + int leftHeight = height(root->left); + int rightHeight = height(root->right); + return abs(leftHeight - rightHeight) <= 1 && isBalanced(root->left) && isBalanced(root->right); + } +private: + int height(TreeNode* root) { + if (root == nullptr) { + return 0; + } + int l = height(root->left); + int r = height(root->right); + return 1 + max(l, r); + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0111.leetcode111 Minimum Depth of Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0111.leetcode111 Minimum Depth of Binary Tree-zh.md" new file mode 100644 index 00000000..1fd4ca58 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0111.leetcode111 Minimum Depth of Binary Tree-zh.md" @@ -0,0 +1,166 @@ +# [111. 二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,找出其最小深度。

    + +

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    + +

    说明:叶子节点是指没有子节点的节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,9,20,null,null,15,7]
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:root = [2,null,3,null,4,null,5,null,6]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数的范围在 [0, 105]
    • +
    • -1000 <= Node.val <= 1000
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + # 如果左子树和右子树其中一个为空,那么需要返回比较大的那个子树的深度+1 + if root.left is None: + return 1 + self.minDepth(root.right) + if root.right is None: + return 1 + self.minDepth(root.left) + # 左右子树都不为空,返回最小深度+1即可 + return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int minDepth(TreeNode root) { + if (root == null) { + return 0; + } + if (root.left == null) { + return 1 + minDepth(root.right); + } + if (root.right == null) { + return 1 + minDepth(root.left); + } + return 1 + Math.min(minDepth(root.left), minDepth(root.right)); + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function(root) { + if (root == null) return 0; + if (root.left == null) return minDepth(root.right) + 1; + if (root.right == null) return minDepth(root.left) + 1; + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if (root == nullptr) { + return 0; + } + if (root->left == nullptr) { + return 1 + minDepth(root->right); + } + if (root->right == nullptr) { + return 1 + minDepth(root->left); + } + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0112.leetcode112 Path Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0112.leetcode112 Path Sum-zh.md" new file mode 100644 index 00000000..1d3487ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0112.leetcode112 Path Sum-zh.md" @@ -0,0 +1,111 @@ +# [112. 路径总和](https://leetcode-cn.com/problems/path-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0112.Path%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum

    + +

    叶子节点 是指没有子节点的节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:root = [1,2,3], targetSum = 5
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:root = [1,2], targetSum = 0
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在范围 [0, 5000]
    • +
    • -1000 <= Node.val <= 1000
    • +
    • -1000 <= targetSum <= 1000
    • +
    + + +## 解法 + + + +递归求解,递归地询问它的子节点是否能满足条件即可。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def hasPathSum(self, root: TreeNode, sum: int) -> bool: + def dfs(root, sum): + if root is None: + return False + if root.val == sum and root.left is None and root.right is None: + return True + return dfs(root.left, sum - root.val) or dfs(root.right, sum - root.val) + return dfs(root, sum) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public boolean hasPathSum(TreeNode root, int sum) { + return dfs(root, sum); + } + + private boolean dfs(TreeNode root, int sum) { + if (root == null) return false; + if (root.val == sum && root.left == null && root.right == null) return true; + return dfs(root.left, sum - root.val) || dfs(root.right, sum - root.val); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0113.leetcode113 Path Sum II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0113.leetcode113 Path Sum II-zh.md" new file mode 100644 index 00000000..ddb4daf5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0113.leetcode113 Path Sum II-zh.md" @@ -0,0 +1,135 @@ +# [113. 路径总和 II](https://leetcode-cn.com/problems/path-sum-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0113.Path%20Sum%20II/README_EN.md) + +## 题目描述 + + + +

    给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

    + +

    叶子节点 是指没有子节点的节点。

    + +
    +
    +

     

    + +

    示例 1:

    + +
    +输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
    +输出:[[5,4,11,2],[5,8,4,5]]
    +
    + +

    示例 2:

    + +
    +输入:root = [1,2,3], targetSum = 5
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:root = [1,2], targetSum = 0
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点总数在范围 [0, 5000]
    • +
    • -1000 <= Node.val <= 1000
    • +
    • -1000 <= targetSum <= 1000
    • +
    +
    +
    + + +## 解法 + + + +深度优先搜索+路径记录。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: + def dfs(root, sum): + if root is None: + return + path.append(root.val) + if root.val == sum and root.left is None and root.right is None: + res.append(path.copy()) + dfs(root.left, sum - root.val) + dfs(root.right, sum - root.val) + path.pop() + if not root: + return [] + res = [] + path = [] + dfs(root, sum) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private List> res; + private List path; + + public List> pathSum(TreeNode root, int sum) { + if (root == null) return Collections.emptyList(); + res = new ArrayList<>(); + path = new ArrayList<>(); + dfs(root, sum); + return res; + } + + private void dfs(TreeNode root, int sum) { + if (root == null) return; + path.add(root.val); + if (root.val == sum && root.left == null && root.right == null) { + res.add(new ArrayList<>(path)); + } + dfs(root.left, sum - root.val); + dfs(root.right, sum - root.val); + path.remove(path.size() - 1); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0114.leetcode114 Flatten Binary Tree to Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0114.leetcode114 Flatten Binary Tree to Linked List-zh.md" new file mode 100644 index 00000000..f0b6e1ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0114.leetcode114 Flatten Binary Tree to Linked List-zh.md" @@ -0,0 +1,204 @@ +# [114. 二叉树展开为链表](https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0114.Flatten%20Binary%20Tree%20to%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给你二叉树的根结点 root ,请你将它展开为一个单链表:

    + +
      +
    • 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null
    • +
    • 展开后的单链表应该与二叉树 先序遍历 顺序相同。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2,5,3,4,null,6]
    +输出:[1,null,2,null,3,null,4,null,5,null,6]
    +
    + +

    示例 2:

    + +
    +输入:root = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:root = [0]
    +输出:[0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中结点数在范围 [0, 2000]
    • +
    • -100 <= Node.val <= 100
    • +
    + +

     

    + +

    进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def flatten(self, root: TreeNode) -> None: + """ + Do not return anything, modify root in-place instead. + """ + while root: + if root.left: + pre = root.left + while pre.right: + pre = pre.right + pre.right = root.right + root.right = root.left + root.left = None + root = root.right +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public void flatten(TreeNode root) { + while (root != null) { + if (root.left != null) { + // 找到当前节点左子树的最右节点 + TreeNode pre = root.left; + while (pre.right != null) { + pre = pre.right; + } + + // 将左子树的最右节点指向原来的右子树 + pre.right = root.right; + + // 将当前节点指向左子树 + root.right = root.left; + root.left = null; + } + root = root.right; + } + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +/** + Do not return anything, modify root in-place instead. + */ +function flatten(root: TreeNode | null): void { + while (root != null) { + if (root.left != null) { + let pre = root.left; + while (pre.right != null) { + pre = pre.right; + } + pre.right = root.right; + root.right = root.left; + root.left = null; + } + root = root.right; + } +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + void flatten(TreeNode* root) { + while (root) { + if (root->left) { + TreeNode *pre = root->left; + while (pre->right) { + pre = pre->right; + } + pre->right = root->right; + root->right = root->left; + root->left = nullptr; + } + root = root->right; + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0115.leetcode115 Distinct Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0115.leetcode115 Distinct Subsequences-zh.md" new file mode 100644 index 00000000..1613d7ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0115.leetcode115 Distinct Subsequences-zh.md" @@ -0,0 +1,90 @@ +# [115. 不同的子序列](https://leetcode-cn.com/problems/distinct-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0115.Distinct%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。

    + +

    字符串的一个 子序列 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" 的一个子序列,而 "AEC" 不是)

    + +

    题目数据保证答案符合 32 位带符号整数范围。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "rabbbit", t = "rabbit"
    +输出3
    +解释:
    +如下图所示, 有 3 种可以从 s 中得到 "rabbit" 的方案。
    +(上箭头符号 ^ 表示选取的字母)
    +rabbbit
    +^^^^ ^^
    +rabbbit
    +^^ ^^^^
    +rabbbit
    +^^^ ^^^
    +
    + +

    示例 2:

    + +
    +输入:s = "babgbag", t = "bag"
    +输出5
    +解释:
    +如下图所示, 有 5 种可以从 s 中得到 "bag" 的方案。 
    +(上箭头符号 ^ 表示选取的字母)
    +babgbag
    +^^ ^
    +babgbag
    +^^    ^
    +babgbag
    +^    ^^
    +babgbag
    +  ^  ^^
    +babgbag
    +    ^^^
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length, t.length <= 1000
    • +
    • st 由英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0116.leetcode116 Populating Next Right Pointers in Each Node-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0116.leetcode116 Populating Next Right Pointers in Each Node-zh.md" new file mode 100644 index 00000000..1fc2414c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0116.leetcode116 Populating Next Right Pointers in Each Node-zh.md" @@ -0,0 +1,204 @@ +# [116. 填充每个节点的下一个右侧节点指针](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0116.Populating%20Next%20Right%20Pointers%20in%20Each%20Node/README_EN.md) + +## 题目描述 + + + +

    给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

    + +
    +struct Node {
    +  int val;
    +  Node *left;
    +  Node *right;
    +  Node *next;
    +}
    + +

    填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL

    + +

    初始状态下,所有 next 指针都被设置为 NULL

    + +

     

    + +

    进阶:

    + +
      +
    • 你只能使用常量级额外空间。
    • +
    • 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
    • +
    + +

     

    + +

    示例:

    + +

    + +
    +输入:root = [1,2,3,4,5,6,7]
    +输出:[1,#,2,3,#,4,5,6,7,#]
    +解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数量少于 4096
    • +
    • -1000 <= node.val <= 1000
    • +
    + +## 解法 + + + +“BFS 层次遍历”实现。 + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + +class Solution: + def connect(self, root: 'Node') -> 'Node': + if root is None or (root.left is None and root.right is None): + return root + q = collections.deque([root]) + while q: + size = len(q) + cur = None + for _ in range(size): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + node.next = cur + cur = node + return root +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root == null || (root.left == null && root.right == null)) { + return root; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + while (!q.isEmpty()) { + Node cur = null; + for (int i = 0, n = q.size(); i < n; ++i) { + Node node = q.pollFirst(); + if (node.right != null) { + q.offer(node.right); + } + if (node.left != null) { + q.offer(node.left); + } + node.next = cur; + cur = node; + } + } + return root; + } +} +``` + +### **C++** + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (!root || (!root->left && !root->right)) { + return root; + } + queue q; + q.push(root); + while (!q.empty()) { + Node* cur = nullptr; + for (int i = 0, n = q.size(); i < n; ++i) { + Node* node = q.front(); + q.pop(); + if (node->right) { + q.push(node->right); + } + if (node->left) { + q.push(node->left); + } + node->next = cur; + cur = node; + } + } + return root; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0117.leetcode117 Populating Next Right Pointers in Each Node II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0117.leetcode117 Populating Next Right Pointers in Each Node II-zh.md" new file mode 100644 index 00000000..b56e31bd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0117.leetcode117 Populating Next Right Pointers in Each Node II-zh.md" @@ -0,0 +1,209 @@ +# [117. 填充每个节点的下一个右侧节点指针 II](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0117.Populating%20Next%20Right%20Pointers%20in%20Each%20Node%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树

    + +
    +struct Node {
    +  int val;
    +  Node *left;
    +  Node *right;
    +  Node *next;
    +}
    + +

    填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL

    + +

    初始状态下,所有 next 指针都被设置为 NULL

    + +

     

    + +

    进阶:

    + +
      +
    • 你只能使用常量级额外空间。
    • +
    • 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
    • +
    + +

     

    + +

    示例:

    + +

    + +
    +输入:root = [1,2,3,4,5,null,7]
    +输出:[1,#,2,3,#,4,5,7,#]
    +解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),'#' 表示每层的末尾。
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数小于 6000
    • +
    • -100 <= node.val <= 100
    • +
    + +

     

    + +
      +
    + +## 解法 + + + +“BFS 层次遍历”实现。 + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + +class Solution: + def connect(self, root: 'Node') -> 'Node': + if root is None or (root.left is None and root.right is None): + return root + q = collections.deque([root]) + while q: + size = len(q) + cur = None + for _ in range(size): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + node.next = cur + cur = node + return root + +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root == null || (root.left == null && root.right == null)) { + return root; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + while (!q.isEmpty()) { + Node cur = null; + for (int i = 0, n = q.size(); i < n; ++i) { + Node node = q.pollFirst(); + if (node.right != null) { + q.offer(node.right); + } + if (node.left != null) { + q.offer(node.left); + } + node.next = cur; + cur = node; + } + } + return root; + } +} +``` + +### **C++** + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (!root || (!root->left && !root->right)) { + return root; + } + queue q; + q.push(root); + while (!q.empty()) { + Node* cur = nullptr; + for (int i = 0, n = q.size(); i < n; ++i) { + Node* node = q.front(); + q.pop(); + if (node->right) { + q.push(node->right); + } + if (node->left) { + q.push(node->left); + } + node->next = cur; + cur = node; + } + } + return root; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0118.leetcode118 Pascal's Triangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0118.leetcode118 Pascal's Triangle-zh.md" new file mode 100644 index 00000000..b0c8e31a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0118.leetcode118 Pascal's Triangle-zh.md" @@ -0,0 +1,140 @@ +# [118. 杨辉三角](https://leetcode-cn.com/problems/pascals-triangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0118.Pascal%27s%20Triangle/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

    + +

    + +

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    + +

    示例:

    + +
    输入: 5
    +输出:
    +[
    +     [1],
    +    [1,1],
    +   [1,2,1],
    +  [1,3,3,1],
    + [1,4,6,4,1]
    +]
    + + +## 解法 + + + +先设置每一行首尾元素为 1,其它元素为 0。然后根据杨辉三角,设置每一行其它元素即可。 + + + +### **Python3** + + + +```python +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + res = [] + for i in range(numRows): + t = [1 if j == 0 or j == i else 0 for j in range(i + 1)] + for j in range(1, i): + t[j] = res[i - 1][j - 1] + res[i - 1][j] + res.append(t) + return res +``` + +### **Java** + + + +```java +class Solution { + public List> generate(int numRows) { + List> res = new ArrayList<>(); + for (int i = 0; i < numRows; ++i) { + List t = new ArrayList<>(); + for (int j = 0; j < i + 1; ++j) { + boolean firstOrLast = j == 0 || j == i; + t.add(firstOrLast ? 1 : 0); + } + for (int j = 1; j < i; ++j) { + int val = res.get(i - 1).get(j - 1) + res.get(i - 1).get(j); + t.set(j, val); + } + res.add(t); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> generate(int numRows) { + vector> res; + for (int i = 0; i < numRows; ++i) { + vector t(i + 1); + t[0] = 1; + t[i] = 1; + for (int j = 1; j < i; ++j) { + t[j] = res[i - 1][j - 1] + res[i - 1][j]; + } + res.push_back(t); + } + return res; + } +}; +``` + +### **Go** + +```go +func generate(numRows int) [][]int { + res := make([][]int, numRows) + for i := 0; i < numRows; i++ { + t := make([]int, i+1) + t[0] = 1 + t[i] = 1 + for j := 1; j < i; j++ { + t[j] = res[i-1][j-1] + res[i-1][j] + } + res[i] = t + } + return res +} +``` + +### **JavaScript** + +```js +const generate = function (numRows) { + let arr = []; + for (let i = 0; i < numRows; i++) { + let row = []; + row[0] = 1; + row[i] = 1; + for (let j = 1; j < row.length - 1; j++) { + row[j] = arr[i - 1][j - 1] + arr[i - 1][j]; + } + arr.push(row); + } + return arr; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0119.leetcode119 Pascal's Triangle II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0119.leetcode119 Pascal's Triangle II-zh.md" new file mode 100644 index 00000000..ba25dc34 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0119.leetcode119 Pascal's Triangle II-zh.md" @@ -0,0 +1,119 @@ +# [119. 杨辉三角 II](https://leetcode-cn.com/problems/pascals-triangle-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0119.Pascal%27s%20Triangle%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

    + +

    + +

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    + +

    示例:

    + +
    输入: 3
    +输出: [1,3,3,1]
    +
    + +

    进阶:

    + +

    你可以优化你的算法到 O(k) 空间复杂度吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def getRow(self, rowIndex: int) -> List[int]: + row = [1] * (rowIndex + 1) + for i in range(2, rowIndex + 1): + for j in range(i - 1, 0, -1): + row[j] += row[j - 1] + return row +``` + +### **Java** + + + +```java +class Solution { + public List getRow(int rowIndex) { + List row = new ArrayList<>(); + for (int i = 0; i < rowIndex + 1; ++i) { + row.add(1); + } + for (int i = 2; i < rowIndex + 1; ++i) { + for (int j = i - 1; j > 0; --j) { + row.set(j, row.get(j) + row.get(j - 1)); + } + } + return row; + } +} +``` + +### **TypeScript** + +```ts +function getRow(rowIndex: number): number[] { + let ans = new Array(rowIndex + 1).fill(1); + for (let i = 2; i < rowIndex + 1; ++i) { + for (let j = i -1; j > 0; --j) { + ans[j] += ans[j - 1]; + } + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector getRow(int rowIndex) { + vector row(rowIndex + 1, 1); + for (int i = 2; i < rowIndex + 1; ++i) { + for (int j = i - 1; j > 0; --j) { + row[j] += row[j - 1]; + } + } + return row; + } +}; +``` + +### **Go** + +```go +func getRow(rowIndex int) []int { + row := make([]int, rowIndex+1) + row[0] = 1 + for i := 1; i <= rowIndex; i++ { + for j := i; j > 0; j-- { + row[j] += row[j-1] + } + } + return row +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0120.leetcode120 Triangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0120.leetcode120 Triangle-zh.md" new file mode 100644 index 00000000..8cfd068d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0120.leetcode120 Triangle-zh.md" @@ -0,0 +1,169 @@ +# [120. 三角形最小路径和](https://leetcode-cn.com/problems/triangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0120.Triangle/README_EN.md) + +## 题目描述 + + + +

    给定一个三角形 triangle ,找出自顶向下的最小路径和。

    + +

    每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。也就是说,如果正位于当前行的下标 i ,那么下一步可以移动到下一行的下标 ii + 1

    + +

     

    + +

    示例 1:

    + +
    +输入:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
    +输出:11
    +解释:如下面简图所示:
    +   2
    +  3 4
    + 6 5 7
    +4 1 8 3
    +自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
    +
    + +

    示例 2:

    + +
    +输入:triangle = [[-10]]
    +输出:-10
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= triangle.length <= 200
    • +
    • triangle[0].length == 1
    • +
    • triangle[i].length == triangle[i - 1].length + 1
    • +
    • -104 <= triangle[i][j] <= 104
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题吗?
    • +
    + + +## 解法 + + + +动态规划。 + + + +### **Python3** + + + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + for i in range(1, n): + for j in range(i + 1): + mi = float('inf') + if j > 0: + mi = min(mi, triangle[i - 1][j - 1]) + if j < i: + mi = min(mi, triangle[i - 1][j]) + triangle[i][j] += mi + return min(triangle[n - 1]) +``` + +### **Java** + + + +```java +class Solution { + public int minimumTotal(List> triangle) { + int n = triangle.size(); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i + 1; ++j) { + int mi = Integer.MAX_VALUE; + if (j > 0) { + mi = Math.min(mi, triangle.get(i - 1).get(j - 1)); + } + if (j < i) { + mi = Math.min(mi, triangle.get(i - 1).get(j)); + } + triangle.get(i).set(j, triangle.get(i).get(j) + mi); + } + } + int res = Integer.MAX_VALUE; + for (int val : triangle.get(n - 1)) { + res = Math.min(res, val); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minimumTotal(vector>& triangle) { + int n = triangle.size(); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i + 1; ++j) { + int mi = INT_MAX; + if (j > 0) mi = min(mi, triangle[i - 1][j - 1]); + if (j < i) mi = min(mi, triangle[i - 1][j]); + triangle[i][j] += mi; + } + } + int res = INT_MAX; + for (int& val : triangle[n - 1]) { + res = min(res, val); + } + return res; + } +}; +``` + +### **Go** + +```go +func minimumTotal(triangle [][]int) int { + n := len(triangle) + for i := 1; i < n; i++ { + for j := 0; j < i+1; j++ { + mi := 2000000 + if j > 0 && mi > triangle[i-1][j-1] { + mi = triangle[i-1][j-1] + } + if j < i && mi > triangle[i-1][j] { + mi = triangle[i-1][j] + } + triangle[i][j] += mi + } + } + + res := 2000000 + for j := 0; j < n; j++ { + if res > triangle[n-1][j] { + res = triangle[n-1][j] + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0121.leetcode121 Best Time to Buy and Sell Stock-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0121.leetcode121 Best Time to Buy and Sell Stock-zh.md" new file mode 100644 index 00000000..2b6e7b91 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0121.leetcode121 Best Time to Buy and Sell Stock-zh.md" @@ -0,0 +1,164 @@ +# [121. 买卖股票的最佳时机](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0121.Best%20Time%20to%20Buy%20and%20Sell%20Stock/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

    + +

    你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

    + +

    返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

    + +

     

    + +

    示例 1:

    + +
    +输入:[7,1,5,3,6,4]
    +输出:5
    +解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
    +     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
    +
    + +

    示例 2:

    + +
    +输入:prices = [7,6,4,3,1]
    +输出:0
    +解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= prices.length <= 105
    • +
    • 0 <= prices[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + res, mi = 0, prices[0] + for price in prices[1:]: + res = max(res, price - mi) + mi = min(mi, price) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxProfit(int[] prices) { + int res = 0, mi = prices[0]; + for (int i = 1; i < prices.length; ++i) { + res = Math.max(res, prices[i] - mi); + mi = Math.min(mi, prices[i]); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int res = 0, mi = prices[0]; + for (int i = 1; i < prices.size(); ++i) { + res = max(res, prices[i] - mi); + mi = min(mi, prices[i]); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int) int { + res, mi := 0, prices[0] + for i := 1; i < len(prices); i++ { + res = max(res, prices[i]-mi) + mi = min(min, prices[i]) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let res = 0; + let mi = prices[0]; + for (let i = 1; i < prices.length; ++i) { + res = Math.max(res, prices[i] - mi); + mi = Math.min(mi, prices[i]); + } + return res; +}; +``` + +### **C#** + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int res = 0, mi = prices[0]; + for (int i = 1; i < prices.Length; ++i) + { + res = Math.Max(res, prices[i] - mi); + mi = Math.Min(mi, prices[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0122.leetcode122 Best Time to Buy and Sell Stock II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0122.leetcode122 Best Time to Buy and Sell Stock II-zh.md" new file mode 100644 index 00000000..dde88c2d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0122.leetcode122 Best Time to Buy and Sell Stock II-zh.md" @@ -0,0 +1,261 @@ +# [122. 买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0122.Best%20Time%20to%20Buy%20and%20Sell%20Stock%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。

    + +

    设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

    + +

    注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

    + +

     

    + +

    示例 1:

    + +
    +输入: prices = [7,1,5,3,6,4]
    +输出: 7
    +解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
    +     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
    +
    + +

    示例 2:

    + +
    +输入: prices = [1,2,3,4,5]
    +输出: 4
    +解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
    +     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
    +
    + +

    示例 3:

    + +
    +输入: prices = [7,6,4,3,1]
    +输出: 0
    +解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= prices.length <= 3 * 104
    • +
    • 0 <= prices[i] <= 104
    • +
    + +## 解法 + + + +### 1. 贪心法 + +所有上涨交易日都做买卖,所有下跌交易日都不做买卖,这样便能实现利润最大化。 + +### 2. 动态规划法 + +设 f1 表示当天结束后持有股票的最大利润,f2 表示当前结束后没有持有股票的最大利润。 + +初始第 1 天结束时,`f1 = -prices[0]`,`f2 = 0`。 + +从第 2 天开始,当天结束时: + +- 若持有股票,则可能是前一天持有股票,然后继续持有;也可能是前一天没有持有股票,然后当天买入股票。最大利润 `f1 = max(f1, f2 - prices[i])`。 +- 若没有持有股票,则可能是前一天没持有股票,今天也没持有股票;或者前一天持有股票,然后今天卖出。最大利润 `f2 = max(f2, f1 + prices[i])`。 + +最后返回 f2 即可。 + + + +### **Python3** + + + +贪心: + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + res = 0 + for i in range(1, len(prices)): + t = prices[i] - prices[i - 1] + res += max(t, 0) + return res +``` + +动态规划: + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f1, f2 = -prices[0], 0 + for price in prices[1:]: + f1 = max(f1, f2 - price) + f2 = max(f2, f1 + price) + return f2 +``` + +### **Java** + + + +贪心: + +```java +class Solution { + public int maxProfit(int[] prices) { + int res = 0; + for (int i = 1; i < prices.length; ++i) { + // 策略是所有上涨交易日都做买卖,所以下跌交易日都不做买卖 + int t = prices[i] - prices[i - 1]; + res += Math.max(t, 0); + } + return res; + } +} +``` + +动态规划: + +```java +class Solution { + public int maxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, f2 - prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + } + return f2; + } +} +``` + +### **TypeScript** + +```ts +function maxProfit(prices: number[]): number { + let ans = 0; + for (let i = 1; i < prices.length; i++) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; +}; +``` + +### **C++** + +贪心: + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int res = 0; + for (int i = 1; i < prices.size(); ++i) { + int t = prices[i] - prices[i - 1]; + res += max(t, 0); + } + return res; + } +}; +``` + +动态规划: + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.size(); ++i) { + f1 = max(f1, f2 - prices[i]); + f2 = max(f2, f1 + prices[i]); + } + return f2; + } +}; +``` + +### **Go** + +贪心: + +```go +func maxProfit(prices []int) int { + res := 0 + for i := 1; i < len(prices); i++ { + t := prices[i] - prices[i-1] + if t > 0 { + res += t + } + } + return res +} +``` + +动态规划: + +```go +func maxProfit(prices []int) int { + f1, f2 := -prices[0], 0 + for _, price := range prices[1:] { + f1 = max(f1, f2-price) + f2 = max(f2, f1+price) + } + return f2 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +贪心: + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int res = 0; + for (int i = 1; i < prices.Length; ++i) + { + int t = prices[i] - prices[i - 1]; + res += Math.Max(t, 0); + } + return res; + } +} +``` + +动态规划: + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.Length; ++i) + { + f1 = Math.Max(f1, f2 - prices[i]); + f2 = Math.Max(f2, f1 + prices[i]); + } + return f2; + } +} +``` + + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0123.leetcode123 Best Time to Buy and Sell Stock III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0123.leetcode123 Best Time to Buy and Sell Stock III-zh.md" new file mode 100644 index 00000000..70b92fa2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0123.leetcode123 Best Time to Buy and Sell Stock III-zh.md" @@ -0,0 +1,173 @@ +# [123. 买卖股票的最佳时机 III](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0123.Best%20Time%20to%20Buy%20and%20Sell%20Stock%20III/README_EN.md) + +## 题目描述 + + + +

    给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

    + +

    设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。

    + +

    注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

    + +

     

    + +

    示例 1:

    + +
    +输入:prices = [3,3,5,0,0,3,1,4]
    +输出:6
    +解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
    +     随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
    + +

    示例 2:

    + +
    +输入:prices = [1,2,3,4,5]
    +输出:4
    +解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。   
    +     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。   
    +     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
    +
    + +

    示例 3:

    + +
    +输入:prices = [7,6,4,3,1] 
    +输出:0 
    +解释:在这个情况下, 没有交易完成, 所以最大利润为 0。
    + +

    示例 4:

    + +
    +输入:prices = [1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= prices.length <= 105
    • +
    • 0 <= prices[i] <= 105
    • +
    + +## 解法 + + + +动态规划法。 + +设 f1 表示第 1 次买入股票后的最大利润,f2 表示第 1 次卖出股票后的最大利润,f3 表示第 2 次买入股票后的最大利润,f4 表示第 2 次卖出股票后的最大利润。 + +遍历过程中,直接使用 f1, f2, f3, f4 计算,考虑的是在同一天买入和卖出时,收益是 0,不会对答案产生影响。 + +最后返回 f2 即可。 + + + +### **Python3** + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + # 第一次买入,第一次卖出,第二次买入,第二次卖出 + f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0 + for price in prices[1:]: + f1 = max(f1, -price) + f2 = max(f2, f1 + price) + f3 = max(f3, f2 - price) + f4 = max(f4, f3 + price) + return f4 +``` + +### **Java** + + + +```java +class Solution { + public int maxProfit(int[] prices) { + // 第一次买入,第一次卖出,第二次买入,第二次卖出 + int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, -prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + f3 = Math.max(f3, f2 - prices[i]); + f4 = Math.max(f4, f3 + prices[i]); + } + return f4; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; + for (int i = 1; i < prices.size(); ++i) { + f1 = max(f1, -prices[i]); + f2 = max(f2, f1 + prices[i]); + f3 = max(f3, f2 - prices[i]); + f4 = max(f4, f3 + prices[i]); + } + return f4; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int) int { + f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 + for i := 1; i < len(prices); i++ { + f1 = max(f1, -prices[i]) + f2 = max(f2, f1 + prices[i]) + f3 = max(f3, f2 - prices[i]) + f4 = max(f4, f3 + prices[i]) + } + return f4 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; + for (int i = 1; i < prices.Length; ++i) + { + f1 = Math.Max(f1, -prices[i]); + f2 = Math.Max(f2, f1 + prices[i]); + f3 = Math.Max(f3, f2 - prices[i]); + f4 = Math.Max(f4, f3 + prices[i]); + } + return f4; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0124.leetcode124 Binary Tree Maximum Path Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0124.leetcode124 Binary Tree Maximum Path Sum-zh.md" new file mode 100644 index 00000000..57ff9f59 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0124.leetcode124 Binary Tree Maximum Path Sum-zh.md" @@ -0,0 +1,70 @@ +# [124. 二叉树中的最大路径和](https://leetcode-cn.com/problems/binary-tree-maximum-path-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0124.Binary%20Tree%20Maximum%20Path%20Sum/README_EN.md) + +## 题目描述 + + + +

    路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

    + +

    路径和 是路径中各节点值的总和。

    + +

    给你一个二叉树的根节点 root ,返回其 最大路径和

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2,3]
    +输出:6
    +解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
    + +

    示例 2:

    + +
    +输入:root = [-10,9,20,null,null,15,7]
    +输出:42
    +解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目范围是 [1, 3 * 104]
    • +
    • -1000 <= Node.val <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0125.leetcode125 Valid Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0125.leetcode125 Valid Palindrome-zh.md" new file mode 100644 index 00000000..03a00afb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0125.leetcode125 Valid Palindrome-zh.md" @@ -0,0 +1,135 @@ +# [125. 验证回文串](https://leetcode-cn.com/problems/valid-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0125.Valid%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

    + +

    说明:本题中,我们将空字符串定义为有效的回文串。

    + +

    示例 1:

    + +
    输入: "A man, a plan, a canal: Panama"
    +输出: true
    +
    + +

    示例 2:

    + +
    输入: "race a car"
    +输出: false
    +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isPalindrome(self, s: str) -> bool: + i, j = 0, len(s) - 1 + while i < j: + if not s[i].isalnum(): + i += 1 + elif not s[j].isalnum(): + j -= 1 + elif s[i].lower() != s[j].lower(): + return False + else: + i += 1 + j -= 1 + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isPalindrome(String s) { + int i = 0, j = s.length() - 1; + while (i < j) { + if (!Character.isLetterOrDigit(s.charAt(i))) { + ++i; + } else if (!Character.isLetterOrDigit(s.charAt(j))) { + --j; + } else if (Character.toUpperCase(s.charAt(i)) != Character.toUpperCase(s.charAt(j))) { + return false; + } else { + ++i; + --j; + } + } + return true; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPalindrome(string s) { + int i = 0, j = s.size() - 1; + while (i < j) { + if (!isAlphaNum(s[i])) ++i; + else if (!isAlphaNum(s[j])) --j; + else if ((s[i] + 32 - 'a') % 32 != (s[j] + 32 - 'a') % 32) return false; + else { + ++i; + --j; + } + } + return true; + } + +private: + bool isAlphaNum(char &ch) { + if (ch >= 'a' && ch <= 'z') return true; + if (ch >= 'A' && ch <= 'Z') return true; + if (ch >= '0' && ch <= '9') return true; + return false; + } +}; +``` + +### **tTypeScript** + +```ts +function isPalindrome(s: string): boolean { + let left: number = 0, right: number = s.length - 1; + while (left < right) { + let char1: string = s.charAt(left); + let char2: string = s.charAt(right); + if (!(/[a-zA-Z0-9]/).test(char1)) { + ++left; + } else if (!(/[a-zA-Z0-9]/).test(char2)) { + --right; + } else if (char1.toLocaleLowerCase() != char2.toLocaleLowerCase()) { + return false; + } else { + ++left; + --right; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0126.leetcode126 Word Ladder II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0126.leetcode126 Word Ladder II-zh.md" new file mode 100644 index 00000000..8dfb2786 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0126.leetcode126 Word Ladder II-zh.md" @@ -0,0 +1,86 @@ +# [126. 单词接龙 II](https://leetcode-cn.com/problems/word-ladder-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0126.Word%20Ladder%20II/README_EN.md) + +## 题目描述 + + + +

    按字典 wordList 完成从单词 beginWord 到单词 endWord 转化,一个表示此过程的 转换序列 是形式上像 beginWord -> s1 -> s2 -> ... -> sk 这样的单词序列,并满足:

    + +
    +
    +
      +
    • 每对相邻的单词之间仅有单个字母不同。
    • +
    • 转换过程中的每个单词 si1 <= i <= k)必须是字典 wordList 中的单词。注意,beginWord 不必是字典 wordList 中的单词。
    • +
    • sk == endWord
    • +
    + +

    给你两个单词 beginWordendWord ,以及一个字典 wordList 。请你找出并返回所有从 beginWordendWord最短转换序列 ,如果不存在这样的转换序列,返回一个空列表。每个序列都应该以单词列表 [beginWord, s1, s2, ..., sk] 的形式返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
    +输出:[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
    +解释:存在 2 种最短的转换序列:
    +"hit" -> "hot" -> "dot" -> "dog" -> "cog"
    +"hit" -> "hot" -> "lot" -> "log" -> "cog"
    +
    + +

    示例 2:

    + +
    +输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
    +输出:[]
    +解释:endWord "cog" 不在字典 wordList 中,所以不存在符合要求的转换序列。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= beginWord.length <= 7
    • +
    • endWord.length == beginWord.length
    • +
    • 1 <= wordList.length <= 5000
    • +
    • wordList[i].length == beginWord.length
    • +
    • beginWordendWordwordList[i] 由小写英文字母组成
    • +
    • beginWord != endWord
    • +
    • wordList 中的所有单词 互不相同
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0127.leetcode127 Word Ladder-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0127.leetcode127 Word Ladder-zh.md" new file mode 100644 index 00000000..511df2e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0127.leetcode127 Word Ladder-zh.md" @@ -0,0 +1,79 @@ +# [127. 单词接龙](https://leetcode-cn.com/problems/word-ladder) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0127.Word%20Ladder/README_EN.md) + +## 题目描述 + + + +

    字典 wordList 中从单词 beginWord endWord转换序列 是一个按下述规格形成的序列:

    + +
      +
    • 序列中第一个单词是 beginWord
    • +
    • 序列中最后一个单词是 endWord
    • +
    • 每次转换只能改变一个字母。
    • +
    • 转换过程中的中间单词必须是字典 wordList 中的单词。
    • +
    + +

    给你两个单词 beginWord endWord 和一个字典 wordList ,找到从 beginWord 到 endWord最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0。

    +  + +

    示例 1:

    + +
    +输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
    +输出:5
    +解释:一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。
    +
    + +

    示例 2:

    + +
    +输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
    +输出:0
    +解释:endWord "cog" 不在字典中,所以无法进行转换。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= beginWord.length <= 10
    • +
    • endWord.length == beginWord.length
    • +
    • 1 <= wordList.length <= 5000
    • +
    • wordList[i].length == beginWord.length
    • +
    • beginWordendWordwordList[i] 由小写英文字母组成
    • +
    • beginWord != endWord
    • +
    • wordList 中的所有字符串 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0128.leetcode128 Longest Consecutive Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0128.leetcode128 Longest Consecutive Sequence-zh.md" new file mode 100644 index 00000000..939c9468 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0128.leetcode128 Longest Consecutive Sequence-zh.md" @@ -0,0 +1,69 @@ +# [128. 最长连续序列](https://leetcode-cn.com/problems/longest-consecutive-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0128.Longest%20Consecutive%20Sequence/README_EN.md) + +## 题目描述 + + + +

    给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

    + +

     

    + +

    进阶:你可以设计并实现时间复杂度为 O(n) 的解决方案吗?

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [100,4,200,1,3,2]
    +输出:4
    +解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
    + +

    示例 2:

    + +
    +输入:nums = [0,3,7,2,5,8,4,6,0,1]
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 104
    • +
    • -109 <= nums[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0129.leetcode129 Sum Root to Leaf Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0129.leetcode129 Sum Root to Leaf Numbers-zh.md" new file mode 100644 index 00000000..abd61d06 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0129.leetcode129 Sum Root to Leaf Numbers-zh.md" @@ -0,0 +1,87 @@ +# [129. 求根节点到叶节点数字之和](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0129.Sum%20Root%20to%20Leaf%20Numbers/README_EN.md) + +## 题目描述 + + + +给你一个二叉树的根节点 root ,树中每个节点都存放有一个 09 之间的数字。 +
    +
    +

    每条从根节点到叶节点的路径都代表一个数字:

    + +
      +
    • 例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123
    • +
    + +

    计算从根节点到叶节点生成的 所有数字之和

    + +

    叶节点 是指没有子节点的节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2,3]
    +输出:25
    +解释:
    +从根到叶子节点路径 1->2 代表数字 12
    +从根到叶子节点路径 1->3 代表数字 13
    +因此,数字总和 = 12 + 13 = 25
    + +

    示例 2:

    + +
    +输入:root = [4,9,0,5,1]
    +输出:1026
    +解释:
    +从根到叶子节点路径 4->9->5 代表数字 495
    +从根到叶子节点路径 4->9->1 代表数字 491
    +从根到叶子节点路径 4->0 代表数字 40
    +因此,数字总和 = 495 + 491 + 40 = 1026
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在范围 [1, 1000]
    • +
    • 0 <= Node.val <= 9
    • +
    • 树的深度不超过 10
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0130.leetcode130 Surrounded Regions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0130.leetcode130 Surrounded Regions-zh.md" new file mode 100644 index 00000000..9af38f94 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0130.leetcode130 Surrounded Regions-zh.md" @@ -0,0 +1,129 @@ +# [130. 被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0130.Surrounded%20Regions/README_EN.md) + +## 题目描述 + + + +给你一个 m x n 的矩阵 board ,由若干字符 'X''O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O''X' 填充。 +
    +
    +

     

    + +

    示例 1:

    + +
    +输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
    +输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
    +解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
    +
    + +

    示例 2:

    + +
    +输入:board = [["X"]]
    +输出:[["X"]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == board.length
    • +
    • n == board[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • board[i][j]'X''O'
    • +
    +
    +
    + + +## 解法 + +dfs/bfs 均可 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **TypeScript** + +```ts +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + let m = board.length, n = board[0].length; + if (m < 3 || n < 3) return; + let visited = Array.from({ length: m }, v => new Array(n).fill(false)); + // 第一行,最后一行, 第一列, 最后一列 + for (let i of [0, m-1]) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'X') { + visited[i][j] = true; + } else { + dfs(board, i, j, visited, true); + } + } + } + for (let i = 0; i < m; ++i) { + for (let j of [0, n - 1]) { + if (board[i][j] == 'X') { + visited[i][j] = true; + } else { + dfs(board, i, j, visited, true); + } + } + } + for (let i = 1; i < m - 1; ++i) { + for (let j = 1; j < n - 1; ++j) { + !visited[i][j] && dfs(board, i, j, visited); + } + } +}; + +function dfs(board: string[][], i: number, j: number, visited: boolean[][], edge = false): void { + let m = board.length, n = board[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || visited[i][j]) { + return; + } + + visited[i][j] = true; + if (board[i][j] == 'X') { + return; + } + if (!edge) { + board[i][j] = 'X'; + } + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + dfs(board, x, y, visited, edge); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0131.leetcode131 Palindrome Partitioning-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0131.leetcode131 Palindrome Partitioning-zh.md" new file mode 100644 index 00000000..64e4f4c9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0131.leetcode131 Palindrome Partitioning-zh.md" @@ -0,0 +1,67 @@ +# [131. 分割回文串](https://leetcode-cn.com/problems/palindrome-partitioning) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0131.Palindrome%20Partitioning/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

    + +

    回文串 是正着读和反着读都一样的字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aab"
    +输出:[["a","a","b"],["aa","b"]]
    +
    + +

    示例 2:

    + +
    +输入:s = "a"
    +输出:[["a"]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 16
    • +
    • s 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0132.leetcode132 Palindrome Partitioning II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0132.leetcode132 Palindrome Partitioning II-zh.md" new file mode 100644 index 00000000..5c5374fd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0132.leetcode132 Palindrome Partitioning II-zh.md" @@ -0,0 +1,79 @@ +# [132. 分割回文串 II](https://leetcode-cn.com/problems/palindrome-partitioning-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0132.Palindrome%20Partitioning%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。

    + +

    返回符合要求的 最少分割次数

    + +
    +
    +

     

    + +

    示例 1:

    + +
    +输入:s = "aab"
    +输出:1
    +解释:只需一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。
    +
    + +

    示例 2:

    + +
    +输入:s = "a"
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:s = "ab"
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 2000
    • +
    • s 仅由小写英文字母组成
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0133.leetcode133 Clone Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0133.leetcode133 Clone Graph-zh.md" new file mode 100644 index 00000000..88313177 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0133.leetcode133 Clone Graph-zh.md" @@ -0,0 +1,108 @@ +# [133. 克隆图](https://leetcode-cn.com/problems/clone-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0133.Clone%20Graph/README_EN.md) + +## 题目描述 + + + +

    给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。

    + +

    图中的每个节点都包含它的值 valint) 和其邻居的列表(list[Node])。

    + +
    class Node {
    +    public int val;
    +    public List<Node> neighbors;
    +}
    + +

     

    + +

    测试用例格式:

    + +

    简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(val = 1),第二个节点值为 2(val = 2),以此类推。该图在测试用例中使用邻接列表表示。

    + +

    邻接列表 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。

    + +

    给定节点将始终是图中的第一个节点(值为 1)。你必须将 给定节点的拷贝 作为对克隆图的引用返回。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:adjList = [[2,4],[1,3],[2,4],[1,3]]
    +输出:[[2,4],[1,3],[2,4],[1,3]]
    +解释:
    +图中有 4 个节点。
    +节点 1 的值是 1,它有两个邻居:节点 2 和 4 。
    +节点 2 的值是 2,它有两个邻居:节点 1 和 3 。
    +节点 3 的值是 3,它有两个邻居:节点 2 和 4 。
    +节点 4 的值是 4,它有两个邻居:节点 1 和 3 。
    +
    + +

    示例 2:

    + +

    + +
    输入:adjList = [[]]
    +输出:[[]]
    +解释:输入包含一个空列表。该图仅仅只有一个值为 1 的节点,它没有任何邻居。
    +
    + +

    示例 3:

    + +
    输入:adjList = []
    +输出:[]
    +解释:这个图是空的,它不含任何节点。
    +
    + +

    示例 4:

    + +

    + +
    输入:adjList = [[2],[1]]
    +输出:[[2],[1]]
    + +

     

    + +

    提示:

    + +
      +
    1. 节点数不超过 100 。
    2. +
    3. 每个节点值 Node.val 都是唯一的,1 <= Node.val <= 100
    4. +
    5. 无向图是一个简单图,这意味着图中没有重复的边,也没有自环。
    6. +
    7. 由于图是无向的,如果节点 p 是节点 q 的邻居,那么节点 q 也必须是节点 p 的邻居。
    8. +
    9. 图是连通图,你可以从给定节点访问到所有节点。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0134.leetcode134 Gas Station-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0134.leetcode134 Gas Station-zh.md" new file mode 100644 index 00000000..50567d4f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0134.leetcode134 Gas Station-zh.md" @@ -0,0 +1,85 @@ +# [134. 加油站](https://leetcode-cn.com/problems/gas-station) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0134.Gas%20Station/README_EN.md) + +## 题目描述 + + + +

    在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

    + +

    你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

    + +

    如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

    + +

    说明: 

    + +
      +
    • 如果题目有解,该答案即为唯一答案。
    • +
    • 输入数组均为非空数组,且长度相同。
    • +
    • 输入数组中的元素均为非负数。
    • +
    + +

    示例 1:

    + +
    输入: 
    +gas  = [1,2,3,4,5]
    +cost = [3,4,5,1,2]
    +
    +输出: 3
    +
    +解释:
    +从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
    +开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
    +开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
    +开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
    +开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
    +开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
    +因此,3 可为起始索引。
    + +

    示例 2:

    + +
    输入: 
    +gas  = [2,3,4]
    +cost = [3,4,3]
    +
    +输出: -1
    +
    +解释:
    +你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
    +我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
    +开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
    +开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
    +你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
    +因此,无论怎样,你都不可能绕环路行驶一周。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0135.leetcode135 Candy-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0135.leetcode135 Candy-zh.md" new file mode 100644 index 00000000..6b04da3b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0135.leetcode135 Candy-zh.md" @@ -0,0 +1,67 @@ +# [135. 分发糖果](https://leetcode-cn.com/problems/candy) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0135.Candy/README_EN.md) + +## 题目描述 + + + +

    老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。

    + +

    你需要按照以下要求,帮助老师给这些孩子分发糖果:

    + +
      +
    • 每个孩子至少分配到 1 个糖果。
    • +
    • 评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。
    • +
    + +

    那么这样下来,老师至少需要准备多少颗糖果呢?

    + +

     

    + +

    示例 1:

    + +
    +输入:[1,0,2]
    +输出:5
    +解释:你可以分别给这三个孩子分发 2、1、2 颗糖果。
    +
    + +

    示例 2:

    + +
    +输入:[1,2,2]
    +输出:4
    +解释:你可以分别给这三个孩子分发 1、2、1 颗糖果。
    +     第三个孩子只得到 1 颗糖果,这已满足上述两个条件。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0136.leetcode136 Single Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0136.leetcode136 Single Number-zh.md" new file mode 100644 index 00000000..c38179fc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0136.leetcode136 Single Number-zh.md" @@ -0,0 +1,115 @@ +# [136. 只出现一次的数字](https://leetcode-cn.com/problems/single-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0136.Single%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

    + +

    说明:

    + +

    你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

    + +

    示例 1:

    + +
    输入: [2,2,1]
    +输出: 1
    +
    + +

    示例 2:

    + +
    输入: [4,1,2,1,2]
    +输出: 4
    + + +## 解法 + + + +异或运算求解。 + +首先明确,两个相同的数异或之后的结果为 0。对该数组所有元素进行异或运算,结果就是那个只出现一次的数字。 + + + +### **Python3** + + + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + res = 0 + for num in nums: + res ^= num + return res +``` + +### **Java** + + + +```java +class Solution { + public int singleNumber(int[] nums) { + int res = 0; + for (int num : nums) { + res ^= num; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function (nums) { + let res = 0; + for (let num of nums) { + res ^= num; + } + return res; +}; +``` + +### **Go** + +```go +func singleNumber(nums []int) int { + res := 0 + for _, v := range nums { + res ^= v + } + return res +} +``` + +### **C++** + +```cpp +class Solution { +public: + int singleNumber(vector& nums) { + int res = 0; + for (auto num : nums) { + res ^= num; + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0137.leetcode137 Single Number II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0137.leetcode137 Single Number II-zh.md" new file mode 100644 index 00000000..e756ff81 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0137.leetcode137 Single Number II-zh.md" @@ -0,0 +1,102 @@ +# [137. 只出现一次的数字 II](https://leetcode-cn.com/problems/single-number-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0137.Single%20Number%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,2,3,2]
    +输出:3
    +
    + +

    示例 2:

    + +
    +输入:nums = [0,1,0,1,0,1,99]
    +输出:99
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 3 * 104
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次
    • +
    + +

     

    + +

    进阶:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

    + + +## 解法 + + + +统计所有数字每个位中 1 出现的次数,对于某个位,1 出现的次数一定是 3 的倍数 +1 或 0。对这个数 %3 得到的结果就是那个出现一次的数字在该位上的值。 + + + +### **Python3** + + + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + bits = [0] * 32 + for num in nums: + for i in range(32): + bits[i] += (num & 1) + num >>= 1 + res = 0 + for i in range(32): + if bits[i] % 3 != 0: + res |= (1 << i) + # 如果为负数,先将 0-32 位取反(即 res ^ 0xffffffff ),再将所有位取反(即 ~ ) + return res if bits[31] % 3 == 0 else ~(res ^ 0xffffffff) +``` + +### **Java** + + + +```java +class Solution { + public int singleNumber(int[] nums) { + int[] bits = new int[32]; + for (int num : nums) { + for (int i = 0; i < 32; ++i) { + bits[i] += (num & 1); + num >>= 1; + } + } + + int res = 0; + for (int i = 0; i < 32; ++i) { + if (bits[i] % 3 == 1) { + res |= (1 << i); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0138.leetcode138 Copy List with Random Pointer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0138.leetcode138 Copy List with Random Pointer-zh.md" new file mode 100644 index 00000000..f9cc72a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0138.leetcode138 Copy List with Random Pointer-zh.md" @@ -0,0 +1,397 @@ +# [138. 复制带随机指针的链表](https://leetcode-cn.com/problems/copy-list-with-random-pointer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0138.Copy%20List%20with%20Random%20Pointer/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。

    + +

    构造这个链表的 深拷贝。 深拷贝应该正好由 n全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点

    + +

    例如,如果原链表中有 XY 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 xy ,同样有 x.random --> y

    + +

    返回复制链表的头节点。

    + +

    用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

    + +
      +
    • val:一个表示 Node.val 的整数。
    • +
    • random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。
    • +
    + +

    你的代码 接受原链表的头节点 head 作为传入参数。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
    +输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
    +
    + +

    示例 2:

    + +

    + +
    +输入:head = [[1,1],[2,1]]
    +输出:[[1,1],[2,1]]
    +
    + +

    示例 3:

    + +

    + +
    +输入:head = [[3,null],[3,0],[3,null]]
    +输出:[[3,null],[3,0],[3,null]]
    +
    + +

    示例 4:

    + +
    +输入:head = []
    +输出:[]
    +解释:给定的链表为空(空指针),因此返回 null。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 1000
    • +
    • -10000 <= Node.val <= 10000
    • +
    • Node.random 为空(null)或指向链表中的节点。
    • +
    + + +## 解法 + + + +首先,遍历链表,完成对每个旧节点的复制。 + +```bash +A -> B -> C -> D -> null + +=> + +A -> A1 -> B -> B1 -> C -> C1 -> D -> D1 -> null +``` + +接着设置新节点的 ramdom 指针。 + +然后遍历链表,修改旧节点和新节点的指向,将旧节点指向下一个旧节点,而新节点指向下一个新节点。 + +最后返回第一个新节点即可。 + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + +class Solution: + def copyRandomList(self, head: 'Node') -> 'Node': + if head is None: + return None + + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + cur.next.random = None if cur.random is None else cur.random.next + cur = cur.next.next + + copy = head.next + cur = head + while cur: + next = cur.next + cur.next = next.next + next.next = None if next.next is None else next.next.next + cur = cur.next + return copy +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + int val; + Node next; + Node random; + + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; + } +} +*/ + +class Solution { + public Node copyRandomList(Node head) { + if (head == null) { + return null; + } + + Node cur = head; + while (cur != null) { + Node node = new Node(cur.val); + node.next = cur.next; + cur.next = node; + cur = node.next; + } + + cur = head; + while (cur != null) { + cur.next.random = cur.random == null ? null : cur.random.next; + cur = cur.next.next; + } + + Node copy = head.next; + cur = head; + while (cur != null) { + Node next = cur.next; + cur.next = next.next; + next.next = next.next == null ? null : next.next.next; + cur = cur.next; + } + return copy; + } +} +``` + +### **C++** + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + Node* cur = head; + while (cur) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + + cur = head; + while (cur) { + cur->next->random = cur->random ? cur->random->next : nullptr; + cur = cur->next->next; + } + + Node* copy = head->next; + cur = head; + while (cur) { + Node* next = cur->next; + cur->next = next->next; + next->next = next->next ? next->next->next : nullptr; + cur = cur->next; + } + return copy; + } +}; +``` + +### **C#** + +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; + + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ + +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + + Node cur = head; + while (cur != null) { + Node node = new Node(cur.val); + node.next = cur.next; + cur.next = node; + cur = node.next; + } + + cur = head; + while (cur != null) { + cur.next.random = cur.random == null ? null : cur.random.next; + cur = cur.next.next; + } + + Node copy = head.next; + cur = head; + while (cur != null) { + Node next = cur.next; + cur.next = next.next; + next.next = next.next == null ? null : next.next.next; + cur = cur.next; + } + return copy; + } +} +``` + +### **Go** + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + + cur := head + for cur != nil { + node := &Node{ + Val: cur.Val, + Next: cur.Next, + Random: nil, + } + cur.Next = node + cur = node.Next + } + + cur = head + for cur != nil { + if cur.Random == nil { + cur.Next.Random = nil + } else { + cur.Next.Random = cur.Random.Next + } + cur = cur.Next.Next + } + + copy := head.Next + cur = head + for cur != nil { + next := cur.Next + cur.Next = next.Next + if (next.Next == nil) { + next.Next = nil + } else { + next.Next = next.Next.Next + } + cur = cur.Next + } + return copy +} +``` + +### **JavaScript** + +```js +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head) { + if (head == null) { + return null; + } + let cur = head; + while (cur != null) { + let node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + + cur = head; + while (cur != null) { + cur.next.random = cur.random == null ? null : cur.random.next; + cur = cur.next.next; + } + + let copy = head.next; + cur = head; + while (cur != null) { + let next = cur.next; + cur.next = next.next; + next.next = next.next == null ? null : next.next.next; + cur = cur.next; + } + return copy; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0139.leetcode139 Word Break-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0139.leetcode139 Word Break-zh.md" new file mode 100644 index 00000000..85718383 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0139.leetcode139 Word Break-zh.md" @@ -0,0 +1,172 @@ +# [139. 单词拆分](https://leetcode-cn.com/problems/word-break) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0139.Word%20Break/README_EN.md) + +## 题目描述 + + + +

    给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

    + +

    说明:

    + +
      +
    • 拆分时可以重复使用字典中的单词。
    • +
    • 你可以假设字典中没有重复的单词。
    • +
    + +

    示例 1:

    + +
    输入: s = "leetcode", wordDict = ["leet", "code"]
    +输出: true
    +解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
    +
    + +

    示例 2:

    + +
    输入: s = "applepenapple", wordDict = ["apple", "pen"]
    +输出: true
    +解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
    +     注意你可以重复使用字典中的单词。
    +
    + +

    示例 3:

    + +
    输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
    +输出: false
    +
    + +## 解法 + + + +动态规划法。 + +`dp[i]` 表示前 i 个字符组成的字符串 `s[0...i-1]` 能否拆分成若干个字典中出现的单词。 + + + +### **Python3** + + + +```python +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + words = set(wordDict) + n = len(s) + dp = [False] * (n + 1) + dp[0] = True + for i in range(1, n + 1): + for j in range(i): + if dp[j] and s[j:i] in words: + dp[i] = True + break + return dp[n] +``` + +### **Java** + + + +```java +class Solution { + public boolean wordBreak(String s, List wordDict) { + Set words = new HashSet<>(wordDict); + int n = s.length(); + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (dp[j] && words.contains(s.substring(j, i))) { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + unordered_set words; + for (auto word : wordDict) { + words.insert(word); + } + int n = s.size(); + vector dp(n + 1, false); + dp[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (dp[j] && words.find(s.substr(j, i - j)) != words.end()) { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +}; +``` + +### **Go** + +```go +func wordBreak(s string, wordDict []string) bool { + words := make(map[string]bool) + for _, word := range wordDict { + words[word] = true + } + n := len(s) + dp := make([]bool, n+1) + dp[0] = true + for i := 1; i <= n; i++ { + for j := 0; j < i; j++ { + if dp[j] && words[s[j:i]] { + dp[i] = true + break + } + } + } + return dp[n] +} +``` + +### **C#** + +```cs +public class Solution { + public bool WordBreak(string s, IList wordDict) { + var words = new HashSet(wordDict); + int n = s.Length; + var dp = new bool[n + 1]; + dp[0] = true; + for (int i = 1; i <= n; ++i) + { + for (int j = 0; j < i; ++j) + { + if (dp[j] && words.Contains(s.Substring(j, i - j))) + { + dp[i] = true; + break; + } + } + } + return dp[n]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0140.leetcode140 Word Break II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0140.leetcode140 Word Break II-zh.md" new file mode 100644 index 00000000..022d4b6f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0140.leetcode140 Word Break II-zh.md" @@ -0,0 +1,82 @@ +# [140. 单词拆分 II](https://leetcode-cn.com/problems/word-break-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0140.Word%20Break%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

    + +

    说明:

    + +
      +
    • 分隔时可以重复使用字典中的单词。
    • +
    • 你可以假设字典中没有重复的单词。
    • +
    + +

    示例 1:

    + +
    输入:
    +s = "catsanddog"
    +wordDict = ["cat", "cats", "and", "sand", "dog"]
    +输出:
    +[
    +  "cats and dog",
    +  "cat sand dog"
    +]
    +
    + +

    示例 2:

    + +
    输入:
    +s = "pineapplepenapple"
    +wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
    +输出:
    +[
    +  "pine apple pen apple",
    +  "pineapple pen apple",
    +  "pine applepen apple"
    +]
    +解释: 注意你可以重复使用字典中的单词。
    +
    + +

    示例 3:

    + +
    输入:
    +s = "catsandog"
    +wordDict = ["cats", "dog", "sand", "and", "cat"]
    +输出:
    +[]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0141.leetcode141 Linked List Cycle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0141.leetcode141 Linked List Cycle-zh.md" new file mode 100644 index 00000000..83c26d03 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0141.leetcode141 Linked List Cycle-zh.md" @@ -0,0 +1,209 @@ +# [141. 环形链表](https://leetcode-cn.com/problems/linked-list-cycle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0141.Linked%20List%20Cycle/README_EN.md) + +## 题目描述 + + + +

    给定一个链表,判断链表中是否有环。

    + +

    如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos-1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

    + +

    如果链表中存在环,则返回 true 。 否则,返回 false

    + +

     

    + +

    进阶:

    + +

    你能用 O(1)(即,常量)内存解决此问题吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:head = [3,2,0,-4], pos = 1
    +输出:true
    +解释:链表中有一个环,其尾部连接到第二个节点。
    +
    + +

    示例 2:

    + +

    + +
    输入:head = [1,2], pos = 0
    +输出:true
    +解释:链表中有一个环,其尾部连接到第一个节点。
    +
    + +

    示例 3:

    + +

    + +
    输入:head = [1], pos = -1
    +输出:false
    +解释:链表中没有环。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目范围是 [0, 104]
    • +
    • -105 <= Node.val <= 105
    • +
    • pos-1 或者链表中的一个 有效索引
    • +
    + + +## 解法 + + + +定义快慢指针 `slow`、`fast`,初始指向 `head`。 + +快指针每次走两步,慢指针每次走一步,不断循环。当相遇时,说明链表存在环。如果循环结束依然没有相遇,说明链表不存在环。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + slow = fast = head + while fast and fast.next: + slow, fast = slow.next, fast.next.next + if slow == fast: + return True + return False +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + return true; + } + } + return false; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode* slow = head; + ListNode* fast = head; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + return true; + } + } + return false; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + let slow = head; + let fast = head; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) { + return true; + } + } + return false; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func hasCycle(head *ListNode) bool { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + if slow == fast { + return true + } + } + return false +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0142.leetcode142 Linked List Cycle II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0142.leetcode142 Linked List Cycle II-zh.md" new file mode 100644 index 00000000..75d2d51f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0142.leetcode142 Linked List Cycle II-zh.md" @@ -0,0 +1,253 @@ +# [142. 环形链表 II](https://leetcode-cn.com/problems/linked-list-cycle-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0142.Linked%20List%20Cycle%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

    + +

    为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos-1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

    + +

    说明:不允许修改给定的链表。

    + +

    进阶:

    + +
      +
    • 你是否可以使用 O(1) 空间解决此题?
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:head = [3,2,0,-4], pos = 1
    +输出:返回索引为 1 的链表节点
    +解释:链表中有一个环,其尾部连接到第二个节点。
    +
    + +

    示例 2:

    + +

    + +
    +输入:head = [1,2], pos = 0
    +输出:返回索引为 0 的链表节点
    +解释:链表中有一个环,其尾部连接到第一个节点。
    +
    + +

    示例 3:

    + +

    + +
    +输入:head = [1], pos = -1
    +输出:返回 null
    +解释:链表中没有环。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目范围在范围 [0, 104]
    • +
    • -105 <= Node.val <= 105
    • +
    • pos 的值为 -1 或者链表中的一个有效索引
    • +
    + + +## 解法 + + + +先利用快慢指针判断链表是否有环,没有环则直接返回 `null`。 + +若链表有环,我们分析快慢相遇时走过的距离。 + +对于慢指针(每次走 1 步),走过的距离为 `S=X+Y` ①;快指针(每次走 2 步)走过的距离为 `2S=X+Y+N(Y+Z)` ②。如下图所示,其中 `N` 表示快指针与慢指针相遇时在环中所走过的圈数,而我们要求的环入口,也即是 `X` 的距离: + +![](https://cdn.jsdelivr.net/gh/dbdgs/dbdgs.github.io/docs/.vuepress/public/img/leetcode142-linked-list-cycle-ii.png) + +我们根据式子 ①②,得出 `X+Y=N(Y+Z)` => `X=(N-1)(Y+Z)+Z`。 + +当 `N=1`(快指针在环中走了一圈与慢指针相遇) 时,`X=(1-1)(Y+Z)+Z`,即 `X=Z`。此时只要定义一个 `p` 指针指向头节点,然后慢指针与 `p` 开始同时走,当慢指针与 `p` 相遇时,也就到达了环入口,直接返回 `p` 即可。 + +当 `N>1`时,也是同样的,说明慢指针除了走 `Z` 步,还需要绕 `N-1` 圈才能与 `p` 相遇。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def detectCycle(self, head: ListNode) -> ListNode: + slow = fast = head + has_cycle = False + while not has_cycle and fast and fast.next: + slow, fast = slow.next, fast.next.next + has_cycle = slow == fast + if not has_cycle: + return None + p = head + while p != slow: + p, slow = p.next, slow.next + return p +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode slow = head, fast = head; + boolean hasCycle = false; + while (!hasCycle && fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + hasCycle = slow == fast; + } + if (!hasCycle) { + return null; + } + ListNode p = head; + while (p != slow) { + p = p.next; + slow = slow.next; + } + return p; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + ListNode* slow = head; + ListNode* fast = head; + bool hasCycle = false; + while (!hasCycle && fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + hasCycle = slow == fast; + } + if (!hasCycle) { + return nullptr; + } + ListNode* p = head; + while (p != slow) { + p = p->next; + slow = slow->next; + } + return p; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {ListNode} + */ +var detectCycle = function(head) { + let slow = head; + let fast = head; + let hasCycle = false; + while (!hasCycle && fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + hasCycle = slow == fast; + } + if (!hasCycle) { + return null; + } + let p = head; + while (p != slow) { + p = p.next; + slow = slow.next; + } + return p; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func detectCycle(head *ListNode) *ListNode { + slow, fast := head, head + hasCycle := false + for !hasCycle && fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + hasCycle = slow == fast + } + if !hasCycle { + return nil + } + p := head + for p != slow { + p, slow = p.Next, slow.Next + } + return p +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0143.leetcode143 Reorder List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0143.leetcode143 Reorder List-zh.md" new file mode 100644 index 00000000..f3fa4d97 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0143.leetcode143 Reorder List-zh.md" @@ -0,0 +1,271 @@ +# [143. 重排链表](https://leetcode-cn.com/problems/reorder-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0143.Reorder%20List/README_EN.md) + +## 题目描述 + + + +

    给定一个单链表 LL0L1→…→Ln-1Ln ,
    +将其重新排列后变为: L0LnL1Ln-1L2Ln-2→…

    + +

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    + +

    示例 1:

    + +
    给定链表 1->2->3->4, 重新排列为 1->4->2->3.
    + +

    示例 2:

    + +
    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
    + + +## 解法 + + + +先通过快慢指针找到链表中点,将链表划分为左右两部分。之后反转右半部分的链表,然后将左右两个链接依次连接即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reorderList(self, head: ListNode) -> None: + """ + Do not return anything, modify head in-place instead. + """ + if head is None or head.next is None: + return + + # 快慢指针找到链表中点 + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + + # cur 指向右半部分链表 + cur = slow.next + slow.next = None + + # 反转右半部分链表 + pre = None + while cur: + t = cur.next + cur.next = pre + pre, cur = cur, t + cur = head + # 此时 cur, pre 分别指向链表左右两半的第一个节点 + + while pre: + t = pre.next + pre.next = cur.next + cur.next = pre + cur, pre = pre.next, t +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public void reorderList(ListNode head) { + if (head == null || head.next == null) { + return; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + ListNode cur = slow.next; + slow.next = null; + + ListNode pre = null; + while (cur != null) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + while (pre != null) { + ListNode t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } + } +} +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public void ReorderList(ListNode head) { + if (head == null || head.next == null) + { + return; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + + ListNode cur = slow.next; + slow.next = null; + + ListNode pre = null; + while (cur != null) + { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + while (pre != null) + { + ListNode t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } + } +} +``` + +### **Go** + + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + func reorderList(head *ListNode) { + if head == nil || head.Next == nil { + return + } + slow, fast := head, head.Next + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + + cur := slow.Next + slow.Next = nil + + var pre *ListNode + for cur != nil { + t := cur.Next + cur.Next = pre + pre, cur = cur, t + } + cur = head + + for pre != nil { + t := pre.Next + pre.Next = cur.Next + cur.Next = pre + cur, pre = pre.Next, t + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {void} Do not return anything, modify head in-place instead. + */ +var reorderList = function(head) { + if (!head || !head.next) { + return; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + let cur = slow.next; + slow.next = null; + + let pre = null; + while (cur) { + const t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + cur = head; + + while (pre) { + const t = pre.next; + pre.next = cur.next; + cur.next = pre; + cur = pre.next; + pre = t; + } +}; +``` + + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0144.leetcode144 Binary Tree Preorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0144.leetcode144 Binary Tree Preorder Traversal-zh.md" new file mode 100644 index 00000000..781a9ae2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0144.leetcode144 Binary Tree Preorder Traversal-zh.md" @@ -0,0 +1,251 @@ +# [144. 二叉树的前序遍历](https://leetcode-cn.com/problems/binary-tree-preorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0144.Binary%20Tree%20Preorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,null,2,3]
    +输出:[1,2,3]
    +
    + +

    示例 2:

    + +
    +输入:root = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:root = [1]
    +输出:[1]
    +
    + +

    示例 4:

    + +
    +输入:root = [1,2]
    +输出:[1,2]
    +
    + +

    示例 5:

    + +
    +输入:root = [1,null,2]
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [0, 100]
    • +
    • -100 <= Node.val <= 100
    • +
    + +

     

    + +

    进阶:递归算法很简单,你可以通过迭代算法完成吗?

    + + +## 解法 + + + +递归遍历或利用栈实现非递归遍历。 + +非递归的思路如下: + +1. 定义一个栈,先将根节点压入栈 +2. 若栈不为空,每次从栈中弹出一个节点 +3. 处理该节点 +4. 先把节点右孩子压入栈,接着把节点左孩子压入栈(如果有孩子节点) +5. 重复 2-4 +6. 返回结果 + + + +### **Python3** + + + +递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + def preorder(root): + if root: + res.append(root.val) + preorder(root.left) + preorder(root.right) + res = [] + preorder(root) + return res +``` + +非递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + if root is None: + return [] + res = [] + s = [root] + while s: + node = s.pop() + res.append(node.val) + if node.right: + s.append(node.right) + if node.left: + s.append(node.left) + return res +``` + +### **Java** + + + +递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private List res; + + public List preorderTraversal(TreeNode root) { + res = new ArrayList<>(); + preorder(root); + return res; + } + + private void preorder(TreeNode root) { + if (root != null) { + res.add(root.val); + preorder(root.left); + preorder(root.right); + } + } +} +``` + +非递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + List res = new ArrayList<>(); + Deque s = new ArrayDeque<>(); + s.push(root); + while (!s.isEmpty()) { + TreeNode node = s.pop(); + res.add(node.val); + if (node.right != null) { + s.push(node.right); + } + if (node.left != null) { + s.push(node.left); + } + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + if (root == nullptr) return res; + stack s; + s.push(root); + while (!s.empty()) { + TreeNode *node = s.top(); + s.pop(); + res.push_back(node->val); + if (node->right) s.push(node->right); + if (node->left) s.push(node->left); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0145.leetcode145 Binary Tree Postorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0145.leetcode145 Binary Tree Postorder Traversal-zh.md" new file mode 100644 index 00000000..0572b300 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0145.leetcode145 Binary Tree Postorder Traversal-zh.md" @@ -0,0 +1,179 @@ +# [145. 二叉树的后序遍历](https://leetcode-cn.com/problems/binary-tree-postorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0145.Binary%20Tree%20Postorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,返回它的 后序 遍历。

    + +

    示例:

    + +
    输入: [1,null,2,3]  
    +   1
    +    \
    +     2
    +    /
    +   3 
    +
    +输出: [3,2,1]
    + +

    进阶: 递归算法很简单,你可以通过迭代算法完成吗?

    + + +## 解法 + + + +递归遍历或利用栈实现非递归遍历。 + +非递归的思路如下: + +先序遍历的顺序是:头、左、右,如果我们改变左右孩子的顺序,就能将顺序变成:头、右、左。 + +我们先不打印头节点,而是存放到另一个收集栈 s2 中,最后遍历结束,输出收集栈元素,即是后序遍历:左、右、头。 + + + +### **Python3** + + + +递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: TreeNode) -> List[int]: + def postorder(root): + if root: + postorder(root.left) + postorder(root.right) + res.append(root.val) + res = [] + postorder(root) + return res +``` + +非递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: TreeNode) -> List[int]: + if not root: + return [] + s1 = [root] + s2 = [] + while s1: + node = s1.pop() + s2.append(node.val) + if node.left: + s1.append(node.left) + if node.right: + s1.append(node.right) + return s2[::-1] +``` + +### **Java** + + + +递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private List res; + + public List postorderTraversal(TreeNode root) { + res = new ArrayList<>(); + postorder(root); + return res; + } + + private void postorder(TreeNode root) { + if (root != null) { + postorder(root.left); + postorder(root.right); + res.add(root.val); + } + } +} +``` + +非递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Deque s1 = new ArrayDeque<>(); + List s2 = new ArrayList<>(); + s1.push(root); + while (!s1.isEmpty()) { + TreeNode node = s1.pop(); + s2.add(node.val); + if (node.left != null) { + s1.push(node.left); + } + if (node.right != null) { + s1.push(node.right); + } + } + Collections.reverse(s2); + return s2; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0146.leetcode146 Lru Cache-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0146.leetcode146 Lru Cache-zh.md" new file mode 100644 index 00000000..d17a379b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0146.leetcode146 Lru Cache-zh.md" @@ -0,0 +1,276 @@ +# [146. LRU 缓存机制](https://leetcode-cn.com/problems/lru-cache) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0146.LRU%20Cache/README_EN.md) + +## 题目描述 + + + +
    运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制
    + +
    +
    +

    实现 LRUCache 类:

    + +
      +
    • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
    • +
    • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1
    • +
    • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
    • +
    + +

     

    +
    +
    + +

    进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

    + +

     

    + +

    示例:

    + +
    +输入
    +["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
    +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
    +输出
    +[null, null, null, 1, null, -1, null, -1, 3, 4]
    +
    +解释
    +LRUCache lRUCache = new LRUCache(2);
    +lRUCache.put(1, 1); // 缓存是 {1=1}
    +lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
    +lRUCache.get(1);    // 返回 1
    +lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
    +lRUCache.get(2);    // 返回 -1 (未找到)
    +lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
    +lRUCache.get(1);    // 返回 -1 (未找到)
    +lRUCache.get(3);    // 返回 3
    +lRUCache.get(4);    // 返回 4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= capacity <= 3000
    • +
    • 0 <= key <= 3000
    • +
    • 0 <= value <= 104
    • +
    • 最多调用 3 * 104getput
    • +
    + +## 解法 + + + +“哈希表 + 双向链表”实现。其中: + +- 双向链表按照被使用的顺序存储 kv 键值对,靠近头部的 kv 键值对是最近使用的,而靠近尾部的键值对是最久未使用的。 +- 哈希表通过缓存的 key 映射到双向链表中的位置。我们可以在 `O(1)` 时间内定位到缓存的 key 所对应的 value 在链表中的位置。 + +对于 `get` 操作,判断 key 是否存在哈希表中: + +- 若不存在,返回 -1 +- 若存在,则 key 对应的节点 node 是最近使用的节点。将该节点移动到双向链表的头部,最后返回该节点的值即可。 + +对于 `put` 操作,同样先判断 key 是否存在哈希表中: + +- 若不存在,则创建一个新的 node 节点,放入哈希表中。然后在双向链表的头部添加该节点。接着判断双向链表节点数是否超过 capacity。若超过,则删除双向链表的尾部节点,以及在哈希表中对应的项。 +- 若存在,则更新 node 节点的值,然后该节点移动到双向链表的头部。 + +双向链表节点(哈希表的 value)的结构如下: + +```java +class Node { + int key; + int value; + Node prev; + Node next; + Node() { + + } + Node(int key, int value) { + this.key = key; + this.value = value; + } +} +``` + +你可能会问,哈希表的 value 为何还要存放 key? + +这是因为,双向链表有一个删除尾节点的操作。我们定位到双向链表的尾节点,在链表中删除之后,还要找到该尾节点在哈希表中的位置,因此需要根据 value 中存放的 key,定位到哈希表的数据项,然后将其删除。 + + + +### **Python3** + + + +```python +class Node: + def __init__(self, key=0, value=0): + self.key = key + self.value = value + self.prev = None + self.next = None + +class LRUCache: + + def __init__(self, capacity: int): + self.cache = {} + self.head = Node() + self.tail = Node() + self.capacity = capacity + self.size = 0 + self.head.next = self.tail + self.tail.prev = self.head + + def get(self, key: int) -> int: + if key not in self.cache: + return -1 + node = self.cache[key] + self.move_to_head(node) + return node.value + + def put(self, key: int, value: int) -> None: + if key in self.cache: + node = self.cache[key] + node.value = value + self.move_to_head(node) + else: + node = Node(key, value) + self.cache[key] = node + self.add_to_head(node) + self.size += 1 + if self.size > self.capacity: + node = self.remove_tail() + self.cache.pop(node.key) + self.size -= 1 + + def move_to_head(self, node): + self.remove_node(node) + self.add_to_head(node) + + def remove_node(self, node): + node.prev.next = node.next + node.next.prev = node.prev + + def add_to_head(self, node): + node.next = self.head.next + self.head.next.prev = node + self.head.next = node + node.prev = self.head + + def remove_tail(self): + node = self.tail.prev + self.remove_node(node) + return node + + +# Your LRUCache object will be instantiated and called as such: +# obj = LRUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) +``` + +### **Java** + + + +```java +class LRUCache { + class Node { + int key; + int value; + Node prev; + Node next; + Node() { + + } + Node(int key, int value) { + this.key = key; + this.value = value; + } + } + + private Map cache; + private Node head; + private Node tail; + private int capacity; + private int size; + + public LRUCache(int capacity) { + cache = new HashMap<>(); + this.capacity = capacity; + head = new Node(); + tail = new Node(); + head.next = tail; + tail.prev = head; + } + + public int get(int key) { + if (!cache.containsKey(key)) { + return -1; + } + Node node = cache.get(key); + moveToHead(node); + return node.value; + } + + public void put(int key, int value) { + if (cache.containsKey(key)) { + Node node = cache.get(key); + node.value = value; + moveToHead(node); + } else { + Node node = new Node(key, value); + cache.put(key, node); + addToHead(node); + ++size; + if (size > capacity) { + node = removeTail(); + cache.remove(node.key); + --size; + } + } + } + + private void moveToHead(Node node) { + removeNode(node); + addToHead(node); + } + + private void removeNode(Node node) { + node.prev.next = node.next; + node.next.prev = node.prev; + } + + private void addToHead(Node node) { + node.next = head.next; + head.next.prev = node; + head.next = node; + node.prev = head; + } + + private Node removeTail() { + Node node = tail.prev; + removeNode(node); + return node; + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0147.leetcode147 Insertion Sort List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0147.leetcode147 Insertion Sort List-zh.md" new file mode 100644 index 00000000..fe583628 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0147.leetcode147 Insertion Sort List-zh.md" @@ -0,0 +1,170 @@ +# [147. 对链表进行插入排序](https://leetcode-cn.com/problems/insertion-sort-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0147.Insertion%20Sort%20List/README_EN.md) + +## 题目描述 + + + +

    对链表进行插入排序。

    + +


    +插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
    +每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

    + +

     

    + +

    插入排序算法:

    + +
      +
    1. 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
    2. +
    3. 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
    4. +
    5. 重复直到所有输入数据插入完为止。
    6. +
    + +

     

    + +

    示例 1:

    + +
    输入: 4->2->1->3
    +输出: 1->2->3->4
    +
    + +

    示例 2:

    + +
    输入: -1->5->3->4->0
    +输出: -1->0->3->4->5
    +
    + +## 解法 + + + +遍历链表,每次将遍历到的结点 cur 与前一个结点 pre 进行值比较: + +- 若结点 cur 的值比 pre 的大,说明当前 cur 已在正确的位置,直接往下遍历。 +- 否则,从链表第一个结点开始遍历,将结点 cur 插入到正确的位置。 + +依次遍历,直至 cur 指向空,遍历结束。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def insertionSortList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + dummy = ListNode(head.val, head) + pre, cur = dummy, head + while cur: + if pre.val <= cur.val: + pre, cur = cur, cur.next + continue + p = dummy + while p.next.val <= cur.val: + p = p.next + t = cur.next + cur.next = p.next + p.next = cur + pre.next = t + cur = t + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode insertionSortList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode dummy = new ListNode(head.val, head); + ListNode pre = dummy, cur = head; + while (cur != null) { + if (pre.val <= cur.val) { + pre = cur; + cur = cur.next; + continue; + } + ListNode p = dummy; + while (p.next.val <= cur.val) { + p = p.next; + } + ListNode t = cur.next; + cur.next = p.next; + p.next = cur; + pre.next = t; + cur = t; + } + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var insertionSortList = function(head) { + if (head == null || head.next == null) return head; + let dummy = new ListNode(head.val, head); + let prev = dummy, cur = head; + while (cur != null) { + if (prev.val <= cur.val) { + prev = cur; + cur = cur.next; + continue; + } + let p = dummy; + while (p.next.val <= cur.val) { + p = p.next; + } + let t = cur.next; + cur.next = p.next; + p.next = cur; + prev.next = t; + cur = t; + } + return dummy.next; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0148.leetcode148 Sort List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0148.leetcode148 Sort List-zh.md" new file mode 100644 index 00000000..1a9c220c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0148.leetcode148 Sort List-zh.md" @@ -0,0 +1,287 @@ +# [148. 排序链表](https://leetcode-cn.com/problems/sort-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0148.Sort%20List/README_EN.md) + +## 题目描述 + + + +

    给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

    + +

    进阶:

    + +
      +
    • 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:head = [4,2,1,3]
    +输出:[1,2,3,4]
    +
    + +

    示例 2:

    + +
    +输入:head = [-1,5,3,4,0]
    +输出:[-1,0,3,4,5]
    +
    + +

    示例 3:

    + +
    +输入:head = []
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目在范围 [0, 5 * 104] 内
    • +
    • -105 <= Node.val <= 105
    • +
    + + +## 解法 + + + +先用快慢指针找到链表中点,然后分成左右两个链表,递归排序左右链表。最后合并两个排序的链表即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def sortList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + t = slow.next + slow.next = None + l1, l2 = self.sortList(head), self.sortList(t) + dummy = ListNode() + cur = dummy + while l1 and l2: + if l1.val <= l2.val: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + cur.next = l1 or l2 + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode t = slow.next; + slow.next = null; + ListNode l1 = sortList(head); + ListNode l2 = sortList(t); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var sortList = function(head) { + if (!head || !head.next) { + return head; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + let t = slow.next; + slow.next = null; + let l1 = sortList(head); + let l2 = sortList(t); + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode SortList(ListNode head) { + if (head == null || head.next == null) + { + return head; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + ListNode t = slow.next; + slow.next = null; + ListNode l1 = SortList(head); + ListNode l2 = SortList(t); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) + { + if (l1.val <= l2.val) + { + cur.next = l1; + l1 = l1.next; + } + else + { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function sortList(head: ListNode | null): ListNode | null { + if (head == null || head.next == null) return head; + // 快慢指针定位中点 + let slow: ListNode = head, fast: ListNode = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + // 归并排序 + let mid: ListNode = slow.next; + slow.next = null; + let l1: ListNode = sortList(head); + let l2: ListNode = sortList(mid); + let dummy: ListNode = new ListNode(); + let cur: ListNode = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0149.leetcode149 Max Points on a Line-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0149.leetcode149 Max Points on a Line-zh.md" new file mode 100644 index 00000000..adad1688 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0149.leetcode149 Max Points on a Line-zh.md" @@ -0,0 +1,173 @@ +# [149. 直线上最多的点数](https://leetcode-cn.com/problems/max-points-on-a-line) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0149.Max%20Points%20on%20a%20Line/README_EN.md) + +## 题目描述 + + + +

    给定一个二维平面,平面上有 个点,求最多有多少个点在同一条直线上。

    + +

    示例 1:

    + +
    输入: [[1,1],[2,2],[3,3]]
    +输出: 3
    +解释:
    +^
    +|
    +|        o
    +|     o
    +|  o  
    ++------------->
    +0  1  2  3  4
    +
    + +

    示例 2:

    + +
    输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
    +输出: 4
    +解释:
    +^
    +|
    +|  o
    +|     o        o
    +|        o
    +|  o        o
    ++------------------->
    +0  1  2  3  4  5  6
    + +## 解法 + + + +在平面上确定一个点 `points[i]`,其他点与 `point[i]` 可以求得一个斜率,斜率相同的点意味着它们与 `points[i]` 在同一条直线上。 + +所以可以用哈希表作为计数器,其中斜率作为 key,然后累计当前点相同的斜率出现的次数。斜率可能是小数,我们可以用分数形式表示,先求分子分母的最大公约数,然后约分,最后将“分子.分母” 作为 key 即可。 + +需要注意,如果平面上有和当前点重叠的点,如果进行约分,会出现除 0 的情况,那么我们单独用一个变量 duplicate 统计重复点的个数,重复点一定是过当前点的直线的。 + + + +### **Python3** + + + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + def gcd(a, b) -> int: + return a if b == 0 else gcd(b, a % b) + + n = len(points) + if n < 3: + return n + res = 0 + for i in range(n - 1): + counter = collections.Counter() + t_max = duplicate = 0 + for j in range(i + 1, n): + delta_x = points[i][0] - points[j][0] + delta_y = points[i][1] - points[j][1] + if delta_x == 0 and delta_y == 0: + duplicate += 1 + continue + g = gcd(delta_x, delta_y) + d_x = delta_x // g + d_y = delta_y // g + key = f'{d_x}.{d_y}' + counter[key] += 1 + t_max = max(t_max, counter[key]) + res = max(res, t_max + duplicate + 1) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + if (n < 3) { + return n; + } + int res = 0; + for (int i = 0; i < n - 1; ++i) { + Map kCounter = new HashMap<>(); + int max = 0; + int duplicate = 0; + for (int j = i + 1; j < n; ++j) { + int deltaX = points[i][0] - points[j][0]; + int deltaY = points[i][1] - points[j][1]; + if (deltaX == 0 && deltaY == 0) { + ++duplicate; + continue; + } + int gcd = gcd(deltaX, deltaY); + int dX = deltaX / gcd; + int dY = deltaY / gcd; + String key = dX + "." + dY; + kCounter.put(key, kCounter.getOrDefault(key, 0) + 1); + max = Math.max(max, kCounter.get(key)); + } + res = Math.max(res, max + duplicate + 1); + } + return res; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +### **Go** + +```go +func maxPoints(points [][]int) int { + type pair struct { + first int + second int + } + n := len(points) + if n <= 2 { + return n + } + ans := 0 + for i := 0; i < n-1; i++ { + freq := make(map[pair]int) + for j := i + 1; j < n; j++ { + x1, y1, x2, y2 := points[i][0], points[i][1], points[j][0], points[j][1] + dx, dy := x2-x1, y2-y1 + g := gcd(dx, dy) + p := pair{dx / g, dy / g} + freq[p]++ + ans = max(ans, freq[p]+1) + } + } + return ans +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0150.leetcode150 Evaluate Reverse Polish Notation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0150.leetcode150 Evaluate Reverse Polish Notation-zh.md" new file mode 100644 index 00000000..395a00bf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0150.leetcode150 Evaluate Reverse Polish Notation-zh.md" @@ -0,0 +1,165 @@ +# [150. 逆波兰表达式求值](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0150.Evaluate%20Reverse%20Polish%20Notation/README_EN.md) + +## 题目描述 + + + +

    根据 逆波兰表示法,求表达式的值。

    + +

    有效的算符包括 +-*/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

    + +

     

    + +

    说明:

    + +
      +
    • 整数除法只保留整数部分。
    • +
    • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:tokens = ["2","1","+","3","*"]
    +输出:9
    +解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
    +
    + +

    示例 2:

    + +
    +输入:tokens = ["4","13","5","/","+"]
    +输出:6
    +解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
    +
    + +

    示例 3:

    + +
    +输入:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
    +输出:22
    +解释:
    +该算式转化为常见的中缀算术表达式为:
    +  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
    += ((10 * (6 / (12 * -11))) + 17) + 5
    += ((10 * (6 / -132)) + 17) + 5
    += ((10 * 0) + 17) + 5
    += (0 + 17) + 5
    += 17 + 5
    += 22
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= tokens.length <= 104
    • +
    • tokens[i] 要么是一个算符("+""-""*""/"),要么是一个在范围 [-200, 200] 内的整数
    • +
    + +

     

    + +

    逆波兰表达式:

    + +

    逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。

    + +
      +
    • 平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 )
    • +
    • 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * )
    • +
    + +

    逆波兰表达式主要有以下两个优点:

    + +
      +
    • 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
    • +
    • 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。
    • +
    + + +## 解法 + + + +栈实现。 + +遍历数组,遇到数字则压入栈中,遇到运算符号,则从栈中弹出右、左操作数,运算过后,将结果压入栈中。 + +遍历结束后,返回栈中的唯一元素。 + + + +### **Python3** + + + +```python +import operator + +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + opt = { + "+": operator.add, + "-": operator.sub, + "*": operator.mul, + "/": operator.truediv + } + s = [] + for token in tokens: + if token in opt: + s.append(int(opt[token](s.pop(-2), s.pop(-1)))) + else: + s.append(int(token)) + return s[0] +``` + +### **Java** + + + +```java +class Solution { + public int evalRPN(String[] tokens) { + Deque s = new ArrayDeque<>(); + int left, right; + for (String token : tokens) { + switch(token) { + case "+": + right = s.pop(); + left = s.pop(); + s.push(left + right); + break; + case "-": + right = s.pop(); + left = s.pop(); + s.push(left - right); + break; + case "*": + right = s.pop(); + left = s.pop(); + s.push(left * right); + break; + case "/": + right = s.pop(); + left = s.pop(); + s.push(left / right); + break; + default: + s.push(Integer.valueOf(token)); + } + } + return s.pop(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0151.leetcode151 Reverse Words in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0151.leetcode151 Reverse Words in a String-zh.md" new file mode 100644 index 00000000..5af43c85 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0151.leetcode151 Reverse Words in a String-zh.md" @@ -0,0 +1,132 @@ +# [151. 翻转字符串里的单词](https://leetcode-cn.com/problems/reverse-words-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0151.Reverse%20Words%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,逐个翻转字符串中的每个单词。

    + +

    说明:

    + +
      +
    • 无空格字符构成一个 单词
    • +
    • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
    • +
    • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:"the sky is blue"
    +输出:"blue is sky the"
    +
    + +

    示例 2:

    + +
    输入:"  hello world!  "
    +输出:"world! hello"
    +解释:输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
    +
    + +

    示例 3:

    + +
    输入:"a good   example"
    +输出:"example good a"
    +解释:如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
    +
    + +

    示例 4:

    + +
    输入:s = "  Bob    Loves  Alice   "
    +输出:"Alice Loves Bob"
    +
    + +

    示例 5:

    + +
    输入:s = "Alice does not even like bob"
    +输出:"bob like even not does Alice"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s 包含英文大小写字母、数字和空格 ' '
    • +
    • s至少存在一个 单词
    • +
    + +
      +
    + +

     

    + +

    进阶:

    + +
      +
    • 请尝试使用 O(1) 额外空间复杂度的原地解法。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def reverseWords(self, s: str) -> str: + words = s.strip().split() + return ' '.join(words[::-1]) +``` + +### **Java** + + + +```java +class Solution { + public String reverseWords(String s) { + List words = Arrays.asList(s.trim().split("\\s+")); + Collections.reverse(words); + return String.join(" ", words); + } +} +``` + +### **C#** + +```cs +public class Solution { + public string ReverseWords(string s) { + return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + } +} +``` + +### **TypeScript** + +```ts +function reverseWords(s: string): string { + let words: string[] = s.trim().split(/\s+/g); + words.reverse(); + return words.join(' '); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0152.leetcode152 Maximum Product Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0152.leetcode152 Maximum Product Subarray-zh.md" new file mode 100644 index 00000000..77f6fe97 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0152.leetcode152 Maximum Product Subarray-zh.md" @@ -0,0 +1,167 @@ +# [152. 乘积最大子数组](https://leetcode-cn.com/problems/maximum-product-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0152.Maximum%20Product%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

    + +

     

    + +

    示例 1:

    + +
    输入: [2,3,-2,4]
    +输出: 6
    +解释: 子数组 [2,3] 有最大乘积 6。
    +
    + +

    示例 2:

    + +
    输入: [-2,0,-1]
    +输出: 0
    +解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
    + + +## 解法 + + + +考虑当前位置 i: + +- 如果是一个负数的话,那么我们希望以它前一个位置结尾的某个段的积也是个负数,这样可以负负得正,并且我们希望这个积尽可能「负得更多」,即尽可能小。 +- 如果是一个正数的话,我们更希望以它前一个位置结尾的某个段的积也是个正数,并且希望它尽可能地大。 + +因此,分别维护 fmax 和 fmin。 + +- `fmax(i) = max(nums[i], fmax(i - 1) * nums[i], fmin(i - 1) * nums[i])` +- `fmin(i) = min(nums[i], fmax(i - 1) * nums[i], fmin(i - 1) * nums[i])` +- `res = max(fmax(i)), i∈[0, n)` + + + +### **Python3** + + + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + maxf = minf = res = nums[0] + for num in nums[1:]: + m, n = maxf, minf + maxf = max(num, m * num, n * num) + minf = min(num, m * num, n * num) + res = max(res, maxf) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxProduct(int[] nums) { + int maxf = nums[0], minf = nums[0], res = nums[0]; + for (int i = 1; i < nums.length; ++i) { + int m = maxf, n = minf; + maxf = Math.max(nums[i], Math.max(m * nums[i], n * nums[i])); + minf = Math.min(nums[i], Math.min(m * nums[i], n * nums[i])); + res = Math.max(res, maxf); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function maxProduct(nums: number[]): number { + let n = nums.length; + let preMax = nums[0], preMin = nums[0], ans = nums[0]; + for (let i = 1; i < n; ++i) { + let cur = nums[i]; + let x = preMax, y = preMin; + preMax = Math.max(x * cur, y * cur, cur); + preMin = Math.min(x * cur, y * cur, cur); + ans = Math.max(preMax, ans); + } + return ans; +}; +``` + +### **C#** + +```cs +public class Solution { + public int MaxProduct(int[] nums) { + int maxf = nums[0], minf = nums[0], res = nums[0]; + for (int i = 1; i < nums.Length; ++i) + { + int m = maxf, n = minf; + maxf = Math.Max(nums[i], Math.Max(nums[i] * m, nums[i] * n)); + minf = Math.Min(nums[i], Math.Min(nums[i] * m, nums[i] * n)); + res = Math.Max(res, maxf); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProduct(vector& nums) { + int maxf = nums[0], minf = nums[0], res = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int m = maxf, n = minf; + maxf = max(nums[i], max(nums[i] * m, nums[i] * n)); + minf = min(nums[i], min(nums[i] * m, nums[i] * n)); + res = max(res, maxf); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxProduct(nums []int) int { + maxf, minf, res := nums[0], nums[0], nums[0] + for i := 1; i < len(nums); i++ { + m, n := maxf, minf + maxf = max(nums[i], max(nums[i]*m, nums[i]*n)) + minf = min(nums[i], min(nums[i]*m, nums[i]*n)) + res = max(res, maxf) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0153.leetcode153 Find Minimum in Rotated Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0153.leetcode153 Find Minimum in Rotated Sorted Array-zh.md" new file mode 100644 index 00000000..42b6dc9a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0153.leetcode153 Find Minimum in Rotated Sorted Array-zh.md" @@ -0,0 +1,171 @@ +# [153. 寻找旋转排序数组中的最小值](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0153.Find%20Minimum%20in%20Rotated%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +已知一个长度为 n 的数组,预先按照升序排列,经由 1n旋转 后,得到输入数组。例如,原数组 nums = [0,1,2,4,5,6,7] 在变化后可能得到: +
      +
    • 若旋转 4 次,则可以得到 [4,5,6,7,0,1,2]
    • +
    • 若旋转 7 次,则可以得到 [0,1,2,4,5,6,7]
    • +
    + +

    注意,数组 [a[0], a[1], a[2], ..., a[n-1]] 旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], ..., a[n-2]]

    + +

    给你一个元素值 互不相同 的数组 nums ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的 最小元素

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3,4,5,1,2]
    +输出:1
    +解释:原数组为 [1,2,3,4,5] ,旋转 3 次得到输入数组。
    +
    + +

    示例 2:

    + +
    +输入:nums = [4,5,6,7,0,1,2]
    +输出:0
    +解释:原数组为 [0,1,2,4,5,6,7] ,旋转 4 次得到输入数组。
    +
    + +

    示例 3:

    + +
    +输入:nums = [11,13,15,17]
    +输出:11
    +解释:原数组为 [11,13,15,17] ,旋转 4 次得到输入数组。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 5000
    • +
    • -5000 <= nums[i] <= 5000
    • +
    • nums 中的所有整数 互不相同
    • +
    • nums 原来是一个升序排序的数组,并进行了 1n 次旋转
    • +
    + + +## 解法 + + + +二分查找。 + +若 `nums[m] > nums[r]`,说明最小值在 m 的右边,否则说明最小值在 m 的左边(包括 m)。 + + + +### **Python3** + + + +```python +class Solution: + def findMin(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + if nums[l] < nums[r]: + return nums[0] + while l < r: + m = (l + r) >> 1 + if nums[m] > nums[r]: + l = m + 1 + else: + r = m + return nums[l] +``` + +### **Java** + + + +```java +class Solution { + public int findMin(int[] nums) { + int l = 0, r = nums.length - 1; + // 说明是递增顺序,直接返回第一个元素 + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + int m = (l + r) >>> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; + } + return nums[l]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findMin(vector& nums) { + int l = 0, r = nums.size() - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + int m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; + } + return nums[l]; + } +}; +``` + +### **Go** + +```go +func findMin(nums []int) int { + l, r := 0, len(nums) - 1 + if nums[l] < nums[r] { + return nums[0] + } + for l < r { + m := (l + r) >> 1 + if nums[m] > nums[r] { + l = m + 1 + } else { + r = m + } + } + return nums[l] +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let l = 0, + r = nums.length - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; + } + return nums[l]; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0154.leetcode154 Find Minimum in Rotated Sorted Array II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0154.leetcode154 Find Minimum in Rotated Sorted Array II-zh.md" new file mode 100644 index 00000000..d08e0978 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0154.leetcode154 Find Minimum in Rotated Sorted Array II-zh.md" @@ -0,0 +1,150 @@ +# [154. 寻找旋转排序数组中的最小值 II](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0154.Find%20Minimum%20in%20Rotated%20Sorted%20Array%20II/README_EN.md) + +## 题目描述 + + + +已知一个长度为 n 的数组,预先按照升序排列,经由 1n旋转 后,得到输入数组。例如,原数组 nums = [0,1,4,4,5,6,7] 在变化后可能得到: +
      +
    • 若旋转 4 次,则可以得到 [4,5,6,7,0,1,4]
    • +
    • 若旋转 7 次,则可以得到 [0,1,4,4,5,6,7]
    • +
    + +

    注意,数组 [a[0], a[1], a[2], ..., a[n-1]] 旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], ..., a[n-2]]

    + +

    给你一个可能存在 重复 元素值的数组 nums ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的 最小元素

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,5]
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,2,2,0,1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 5000
    • +
    • -5000 <= nums[i] <= 5000
    • +
    • nums 原来是一个升序排序的数组,并进行了 1n 次旋转
    • +
    + +

     

    + +

    进阶:

    + + + + +## 解法 + + + +二分法。 + +若 `nums[m] > nums[r]`,说明最小值在 m 的右边;若 `nums[m] < nums[r]`,说明最小值在 m 的左边(包括 m);若相等,无法判断,直接将 r 减 1。循环比较。 + +最后返回 `nums[l]` 即可。 + + + +### **Python3** + + + +```python +class Solution: + def findMin(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + while l < r: + m = (l + r) >> 1 + if nums[m] > nums[r]: + l = m + 1 + elif nums[m] < nums[r]: + r = m + else: + r -= 1 + return nums[l] +``` + +### **Java** + + + +```java +class Solution { + public int findMin(int[] nums) { + int l = 0, r = nums.length - 1; + while (l < r) { + int m = (l + r) >>> 1; + if (nums[m] > nums[r]) l = m + 1; + else if (nums[m] < nums[r]) r = m; + else --r; + } + return nums[l]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findMin(vector& nums) { + int l = 0, r = nums.size() - 1; + while (l < r) { + int m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else if (nums[m] < nums[r]) r = m; + else --r; + } + return nums[l]; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let l = 0, + r = nums.length - 1; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else if (nums[m] < nums[r]) r = m; + else --r; + } + return nums[l]; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0155.leetcode155 Min Stack-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0155.leetcode155 Min Stack-zh.md" new file mode 100644 index 00000000..b101162d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0155.leetcode155 Min Stack-zh.md" @@ -0,0 +1,239 @@ +# [155. 最小栈](https://leetcode-cn.com/problems/min-stack) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0155.Min%20Stack/README_EN.md) + +## 题目描述 + + + +

    设计一个支持 pushpoptop 操作,并能在常数时间内检索到最小元素的栈。

    + +
      +
    • push(x) —— 将元素 x 推入栈中。
    • +
    • pop() —— 删除栈顶的元素。
    • +
    • top() —— 获取栈顶元素。
    • +
    • getMin() —— 检索栈中的最小元素。
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["MinStack","push","push","push","getMin","pop","top","getMin"]
    +[[],[-2],[0],[-3],[],[],[],[]]
    +
    +输出:
    +[null,null,null,null,-3,null,0,-2]
    +
    +解释:
    +MinStack minStack = new MinStack();
    +minStack.push(-2);
    +minStack.push(0);
    +minStack.push(-3);
    +minStack.getMin();   --> 返回 -3.
    +minStack.pop();
    +minStack.top();      --> 返回 0.
    +minStack.getMin();   --> 返回 -2.
    +
    + +

     

    + +

    提示:

    + +
      +
    • poptopgetMin 操作总是在 非空栈 上调用。
    • +
    + +## 解法 + +“辅助栈”实现。 + + + + + +### **Python3** + + + +```python +class MinStack: + + def __init__(self): + """ + initialize your data structure here. + """ + self.s = [] + self.mins = [float('inf')] + + def push(self, val: int) -> None: + self.s.append(val) + self.mins.append(min(self.mins[-1], val)) + + def pop(self) -> None: + self.s.pop() + self.mins.pop() + + def top(self) -> int: + return self.s[-1] + + def getMin(self) -> int: + return self.mins[-1] + + +# Your MinStack object will be instantiated and called as such: +# obj = MinStack() +# obj.push(val) +# obj.pop() +# param_3 = obj.top() +# param_4 = obj.getMin() +``` + +### **Java** + + + +```java +class MinStack { + private Deque s; + private Deque mins; + + /** initialize your data structure here. */ + public MinStack() { + s = new ArrayDeque<>(); + mins = new ArrayDeque<>(); + mins.push(Integer.MAX_VALUE); + } + + public void push(int val) { + s.push(val); + mins.push(Math.min(mins.peek(), val)); + } + + public void pop() { + s.pop(); + mins.pop(); + } + + public int top() { + return s.peek(); + } + + public int getMin() { + return mins.peek(); + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack obj = new MinStack(); + * obj.push(val); + * obj.pop(); + * int param_3 = obj.top(); + * int param_4 = obj.getMin(); + */ +``` + +### **C++** + +```cpp +class MinStack { +private: + stack s; + stack mins; + +public: + /** initialize your data structure here. */ + MinStack() { + mins.push(INT_MAX); + } + + void push(int val) { + s.push(val); + mins.push(min(mins.top(), val)); + } + + void pop() { + s.pop(); + mins.pop(); + } + + int top() { + return s.top(); + } + + int getMin() { + return mins.top(); + } +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(val); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ +``` + +### **JavaScript** + +```js +/** + * initialize your data structure here. + */ +var MinStack = function() { + this.s = []; + this.mins = [Infinity]; +}; + +/** + * @param {number} val + * @return {void} + */ +MinStack.prototype.push = function(val) { + this.s.push(val); + this.mins.push(Math.min(this.mins[this.mins.length - 1], val)); +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function() { + this.s.pop(); + this.mins.pop(); +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function() { + return this.s[this.s.length - 1]; +}; + +/** + * @return {number} + */ +MinStack.prototype.getMin = function() { + return this.mins[this.mins.length - 1]; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0156.leetcode156 Binary Tree Upside Down-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0156.leetcode156 Binary Tree Upside Down-zh.md" new file mode 100644 index 00000000..be8b6d69 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0156.leetcode156 Binary Tree Upside Down-zh.md" @@ -0,0 +1,78 @@ +# [156. 上下翻转二叉树](https://leetcode-cn.com/problems/binary-tree-upside-down) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0156.Binary%20Tree%20Upside%20Down/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,其中所有的右节点要么是具有兄弟节点(拥有相同父节点的左节点)的叶节点,要么为空,将此二叉树上下翻转并将它变成一棵树, 原来的右节点将转换成左叶节点。返回新的根。

    + +

    例子:

    + +
    输入: [1,2,3,4,5]
    +
    +    1
    +   / \
    +  2   3
    + / \
    +4   5
    +
    +输出: 返回二叉树的根 [4,5,2,#,#,3,1]
    +
    +   4
    +  / \
    + 5   2
    +    / \
    +   3   1  
    +
    + +

    说明:

    + +

    [4,5,2,#,#,3,1] 感到困惑? 下面详细介绍请查看 二叉树是如何被序列化的

    + +

    二叉树的序列化遵循层次遍历规则,当没有节点存在时,'#' 表示路径终止符。

    + +

    这里有一个例子:

    + +
       1
    +  / \
    + 2   3
    +    /
    +   4
    +    \
    +     5
    +
    + +

    上面的二叉树则被序列化为 [1,2,3,#,#,4,#,#,5].

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0157.leetcode157 Read N Characters Given Read4-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0157.leetcode157 Read N Characters Given Read4-zh.md" new file mode 100644 index 00000000..f0955fc2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0157.leetcode157 Read N Characters Given Read4-zh.md" @@ -0,0 +1,119 @@ +# [157. 用 Read4 读取 N 个字符](https://leetcode-cn.com/problems/read-n-characters-given-read4) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0157.Read%20N%20Characters%20Given%20Read4/README_EN.md) + +## 题目描述 + + + +

    给你一个文件,并且该文件只能通过给定的 read4 方法来读取,请实现一个方法使其能够读取 n 个字符。

    + +

    read4 方法:

    + +

    API read4 可以从文件中读取 4 个连续的字符,并且将它们写入缓存数组 buf 中。

    + +

    返回值为实际读取的字符个数。

    + +

    注意 read4() 自身拥有文件指针,很类似于 C 语言中的 FILE *fp

    + +

    read4 的定义:

    + +
    参数类型: char[] buf4
    +返回类型: int
    +
    +注意: buf4[] 是目标缓存区不是源缓存区,read4 的返回结果将会复制到 buf4[] 当中。
    +
    + +

    下列是一些使用 read4 的例子:

    + +

    + +
    File file("abcde"); // 文件名为 "abcde", 初始文件指针 (fp) 指向 'a' 
    +char[] buf4 = new char[4]; // 创建一个缓存区使其能容纳足够的字符
    +read4(buf4); // read4 返回 4。现在 buf4 = "abcd",fp 指向 'e'
    +read4(buf4); // read4 返回 1。现在 buf4 = "e",fp 指向文件末尾
    +read4(buf4); // read4 返回 0。现在 buf = "",fp 指向文件末尾
    + +

    read 方法:

    + +

    通过使用 read4 方法,实现 read 方法。该方法可以从文件中读取 n 个字符并将其存储到缓存数组 buf 中。您 不能 直接操作文件。

    + +

    返回值为实际读取的字符。

    + +

    read 的定义:

    + +
    参数类型:   char[] buf, int n
    +返回类型:   int
    +
    +注意: buf[] 是目标缓存区不是源缓存区,你需要将结果写入 buf[] 中。
    +
    + +

     

    + +

    示例 1:

    + +
    输入: file = "abc", n = 4
    +输出: 3
    +解释: 当执行你的 read 方法后,buf 需要包含 "abc"。 文件一共 3 个字符,因此返回 3。 注意 "abc" 是文件的内容,不是 buf 的内容,buf 是你需要写入结果的目标缓存区。 
    + +

    示例 2:

    + +
    输入: file = "abcde", n = 5
    +输出: 5
    +解释: 当执行你的 read 方法后,buf 需要包含 "abcde"。文件共 5 个字符,因此返回 5。
    +
    + +

    示例 3:

    + +
    输入: file = "abcdABCD1234", n = 12
    +输出: 12
    +解释: 当执行你的 read 方法后,buf 需要包含 "abcdABCD1234"。文件一共 12 个字符,因此返回 12。
    +
    + +

    示例 4:

    + +
    输入: file = "leetcode", n = 5
    +输出: 5
    +解释: 当执行你的 read 方法后,buf 需要包含 "leetc"。文件中一共 5 个字符,因此返回 5。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 不能 直接操作该文件,文件只能通过 read4 获取而 不能 通过 read
    • +
    • read  函数只在每个测试用例调用一次。
    • +
    • 你可以假定目标缓存数组 buf 保证有足够的空间存下 n 个字符。 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0158.leetcode158 Read N Characters Given Read4 II - Call multiple times-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0158.leetcode158 Read N Characters Given Read4 II - Call multiple times-zh.md" new file mode 100644 index 00000000..d2cafb84 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0158.leetcode158 Read N Characters Given Read4 II - Call multiple times-zh.md" @@ -0,0 +1,115 @@ +# [158. 用 Read4 读取 N 个字符 II](https://leetcode-cn.com/problems/read-n-characters-given-read4-ii-call-multiple-times) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0158.Read%20N%20Characters%20Given%20Read4%20II%20-%20Call%20multiple%20times/README_EN.md) + +## 题目描述 + + + +

    给你一个文件,并且该文件只能通过给定的 read4 方法来读取,请实现一个方法使其能够读取 n 个字符。注意:你的 read 方法可能会被调用多次。

    + +

    read4 的定义:

    + +

    read4 API 从文件中读取 4 个连续的字符,然后将这些字符写入缓冲区数组 buf4

    + +

    返回值是读取的实际字符数。

    + +

    请注意,read4() 有其自己的文件指针,类似于 C 中的 FILE * fp

    + +
    +参数类型: char[] buf4
    +返回类型: int
    +
    +注意: buf4[] 是目标缓存区不是源缓存区,read4 的返回结果将会复制到 buf4[] 当中。
    +
    + +

    下列是一些使用 read4 的例子:

    + +

    + +
    +File file("abcde"); // 文件名为 "abcde", 初始文件指针 (fp) 指向 'a' 
    +char[] buf4 = new char[4]; // 创建一个缓存区使其能容纳足够的字符
    +read4(buf4); // read4 返回 4。现在 buf4 = "abcd",fp 指向 'e'
    +read4(buf4); // read4 返回 1。现在 buf4 = "e",fp 指向文件末尾
    +read4(buf4); // read4 返回 0。现在 buf4 = "",fp 指向文件末尾
    + +

    read 方法:

    + +

    通过使用 read4 方法,实现 read 方法。该方法可以从文件中读取 n 个字符并将其存储到缓存数组 buf 中。您 不能 直接操作文件。

    + +

    返回值为实际读取的字符。

    + +

    read 的定义:

    + +
    +参数:   char[] buf, int n
    +返回值: int
    +
    +注意: buf[] 是目标缓存区不是源缓存区,你需要将结果写入 buf[] 中。
    +
    + +

     

    + +

    示例 1:

    + +
    +File file("abc");
    +Solution sol;
    +// 假定 buf 已经被分配了内存,并且有足够的空间来存储文件中的所有字符。
    +sol.read(buf, 1); // 当调用了您的 read 方法后,buf 需要包含 "a"。 一共读取 1 个字符,因此返回 1。
    +sol.read(buf, 2); // 现在 buf 需要包含 "bc"。一共读取 2 个字符,因此返回 2。
    +sol.read(buf, 1); // 由于已经到达了文件末尾,没有更多的字符可以读取,因此返回 0。
    +
    + +

    示例 2:

    + +
    +File file("abc");
    +Solution sol;
    +sol.read(buf, 4); // 当调用了您的 read 方法后,buf 需要包含 "abc"。 一共只能读取 3 个字符,因此返回 3。
    +sol.read(buf, 1); // 由于已经到达了文件末尾,没有更多的字符可以读取,因此返回 0。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 不能 直接操作该文件,文件只能通过 read4 获取而 不能 通过 read
    • +
    • read  函数可以被调用 多次
    • +
    • 请记得 重置 在 Solution 中声明的类变量(静态变量),因为类变量会 在多个测试用例中保持不变,影响判题准确。请 查阅 这里。
    • +
    • 你可以假定目标缓存数组 buf 保证有足够的空间存下 n 个字符。 
    • +
    • 保证在一个给定测试用例中,read 函数使用的是同一个 buf
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0159.leetcode159 Longest Substring with At Most Two Distinct Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0159.leetcode159 Longest Substring with At Most Two Distinct Characters-zh.md" new file mode 100644 index 00000000..f5ae296e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0159.leetcode159 Longest Substring with At Most Two Distinct Characters-zh.md" @@ -0,0 +1,54 @@ +# [159. 至多包含两个不同字符的最长子串](https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0159.Longest%20Substring%20with%20At%20Most%20Two%20Distinct%20Characters/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s ,找出 至多 包含两个不同字符的最长子串 t ,并返回该子串的长度。

    + +

    示例 1:

    + +
    输入: "eceba"
    +输出: 3
    +解释: t 是 "ece",长度为3。
    +
    + +

    示例 2:

    + +
    输入: "ccaabbb"
    +输出: 5
    +解释: t 是 "aabbb",长度为5。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0160.leetcode160 Intersection of Two Linked Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0160.leetcode160 Intersection of Two Linked Lists-zh.md" new file mode 100644 index 00000000..3d5062b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0160.leetcode160 Intersection of Two Linked Lists-zh.md" @@ -0,0 +1,234 @@ +# [160. 相交链表](https://leetcode-cn.com/problems/intersection-of-two-linked-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/README_EN.md) + +## 题目描述 + + + +

    编写一个程序,找到两个单链表相交的起始节点。

    + +

    如下面的两个链表

    + +

    + +

    在节点 c1 开始相交。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
    +输出:Reference of the node with value = 8
    +输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
    +
    + +

     

    + +

    示例 2:

    + +

    + +
    输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
    +输出:Reference of the node with value = 2
    +输入解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
    +
    + +

     

    + +

    示例 3:

    + +

    + +
    输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
    +输出:null
    +输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
    +解释:这两个链表不相交,因此返回 null。
    +
    + +

     

    + +

    注意:

    + +
      +
    • 如果两个链表没有交点,返回 null.
    • +
    • 在返回结果后,两个链表仍须保持原有的结构。
    • +
    • 可假定整个链表结构中没有循环。
    • +
    • 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
    • +
    + + +## 解法 + + + +使用两个指针 `cur1`, `cur2` 分别指向两个链表 `headA`, `headB`。 + +同时遍历链表,当 `cur1` 到达链表 `headA` 的末尾时,重新定位到链表 `headB` 的头节点;当 `cur2` 到达链表 `headB` 的末尾时,重新定位到链表 `headA` 的头节点。 + +若两指针相遇,所指向的结点就是第一个公共节点。若没相遇,说明两链表无公共节点,此时两个指针都指向 `null`。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + cur1, cur2 = headA, headB + while cur1 != cur2: + cur1 = headB if cur1 is None else cur1.next + cur2 = headA if cur2 is None else cur2.next + return cur1 +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + ListNode cur1 = headA, cur2 = headB; + while (cur1 != cur2) { + cur1 = cur1 == null ? headB : cur1.next; + cur2 = cur2 == null ? headA : cur2.next; + } + return cur1; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode* cur1 = headA; + ListNode* cur2 = headB; + while (cur1 != cur2) { + cur1 = cur1 ? cur1->next : headB; + cur2 = cur2 ? cur2->next : headA; + } + return cur1; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ + var getIntersectionNode = function(headA, headB) { + let cur1 = headA; + let cur2 = headB; + while (cur1 != cur2) { + cur1 = cur1 ? cur1.next : headB; + cur2 = cur2 ? cur2.next : headA; + } + return cur1; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + func getIntersectionNode(headA, headB *ListNode) *ListNode { + cur1, cur2 := headA, headB + for cur1 != cur2 { + if cur1 == nil { + cur1 = headB + } else { + cur1 = cur1.Next + } + if cur2 == nil { + cur2 = headA + } else { + cur2 = cur2.Next + } + } + return cur1 +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { + let p1: ListNode | null = headA; + let p2: ListNode | null = headB; + while (p1 != p2) { + p1 = p1 == null ? headB : p1.next; + p2 = p2 == null ? headA : p2.next; + } + return p1; +}; +``` +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0161.leetcode161 One Edit Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0161.leetcode161 One Edit Distance-zh.md" new file mode 100644 index 00000000..0b7712f9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0161.leetcode161 One Edit Distance-zh.md" @@ -0,0 +1,69 @@ +# [161. 相隔为 1 的编辑距离](https://leetcode-cn.com/problems/one-edit-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0161.One%20Edit%20Distance/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 s t,判断他们的编辑距离是否为 1。

    + +

    注意:

    + +

    满足编辑距离等于 1 有三种可能的情形:

    + +
      +
    1. s 中插入一个字符得到 t
    2. +
    3. s 中删除一个字符得到 t
    4. +
    5. s 中替换一个字符得到 t
    6. +
    + +

    示例 1:

    + +
    输入: s = "ab", t = "acb"
    +输出: true
    +解释: 可以将 'c' 插入字符串 s 来得到 t。
    +
    + +

    示例 2:

    + +
    输入: s = "cab", t = "ad"
    +输出: false
    +解释: 无法通过 1 步操作使 s 变为 t
    + +

    示例 3:

    + +
    输入: s = "1203", t = "1213"
    +输出: true
    +解释: 可以将字符串 s 中的 '0' 替换为 '1' 来得到 t
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0162.leetcode162 Find Peak Element-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0162.leetcode162 Find Peak Element-zh.md" new file mode 100644 index 00000000..4fdc4a94 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0162.leetcode162 Find Peak Element-zh.md" @@ -0,0 +1,153 @@ +# [162. 寻找峰值](https://leetcode-cn.com/problems/find-peak-element) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0162.Find%20Peak%20Element/README_EN.md) + +## 题目描述 + + + +

    峰值元素是指其值大于左右相邻值的元素。

    + +

    给你一个输入数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。

    + +

    你可以假设 nums[-1] = nums[n] = -∞

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,1]
    +输出:2
    +解释:3 是峰值元素,你的函数应该返回其索引 2。
    + +

    示例 2:

    + +
    +输入:nums = [1,2,1,3,5,6,4]
    +输出:1 或 5 
    +解释:你的函数可以返回索引 1,其峰值元素为 2;
    +     或者返回索引 5, 其峰值元素为 6。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • 对于所有有效的 i 都有 nums[i] != nums[i + 1]
    • +
    + +

     

    + +

    进阶:你可以实现时间复杂度为 O(logN) 的解决方案吗?

    + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def findPeakElement(self, nums: List[int]) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] > nums[mid + 1]: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int findPeakElement(int[] nums) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] > nums[mid + 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **TypeScript** + +```ts +function findPeakElement(nums: number[]): number { + let left = 0, right = nums.length - 1; + while (left < right) { + let mid: number = (left + right) >> 1; + if (nums[mid] <= nums[mid+1]) { + left = mid +1; + } else { + right = mid; + } + } + return left; +}; +``` + +### **Go** + +```go +func findPeakElement(nums []int) int { + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if nums[mid] > nums[mid+1] { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findPeakElement(vector& nums) { + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] > nums[mid + 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0163.leetcode163 Missing Ranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0163.leetcode163 Missing Ranges-zh.md" new file mode 100644 index 00000000..c52df28e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0163.leetcode163 Missing Ranges-zh.md" @@ -0,0 +1,46 @@ +# [163. 缺失的区间](https://leetcode-cn.com/problems/missing-ranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0163.Missing%20Ranges/README_EN.md) + +## 题目描述 + + + +

    给定一个排序的整数数组 nums ,其中元素的范围在 闭区间 [lower, upper] 当中,返回不包含在数组中的缺失区间。

    + +

    示例:

    + +
    输入: nums = [0, 1, 3, 50, 75], lower = 0 和 upper = 99,
    +输出: ["2", "4->49", "51->74", "76->99"]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0164.leetcode164 Maximum Gap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0164.leetcode164 Maximum Gap-zh.md" new file mode 100644 index 00000000..8c132036 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0164.leetcode164 Maximum Gap-zh.md" @@ -0,0 +1,61 @@ +# [164. 最大间距](https://leetcode-cn.com/problems/maximum-gap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0164.Maximum%20Gap/README_EN.md) + +## 题目描述 + + + +

    给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。

    + +

    如果数组元素个数小于 2,则返回 0。

    + +

    示例 1:

    + +
    输入: [3,6,9,1]
    +输出: 3
    +解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
    + +

    示例 2:

    + +
    输入: [10]
    +输出: 0
    +解释: 数组元素个数小于 2,因此返回 0。
    + +

    说明:

    + +
      +
    • 你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
    • +
    • 请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0165.leetcode165 Compare Version Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0165.leetcode165 Compare Version Numbers-zh.md" new file mode 100644 index 00000000..1ae17961 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0165.leetcode165 Compare Version Numbers-zh.md" @@ -0,0 +1,103 @@ +# [165. 比较版本号](https://leetcode-cn.com/problems/compare-version-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0165.Compare%20Version%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你两个版本号 version1version2 ,请你比较它们。

    + +

    版本号由一个或多个修订号组成,各修订号由一个 '.' 连接。每个修订号由 多位数字 组成,可能包含 前导零 。每个版本号至少包含一个字符。修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推。例如,2.5.330.1 都是有效的版本号。

    + +

    比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较 忽略任何前导零后的整数值 。也就是说,修订号 1 和修订号 001 相等 。如果版本号没有指定某个下标处的修订号,则该修订号视为 0 。例如,版本 1.0 小于版本 1.1 ,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 010 < 1

    + +

    返回规则如下:

    + +
      +
    • 如果 version1 version2 返回 1
    • +
    • 如果 version1 version2 返回 -1
    • +
    • 除此之外返回 0
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:version1 = "1.01", version2 = "1.001"
    +输出:0
    +解释:忽略前导零,"01" 和 "001" 都表示相同的整数 "1"
    +
    + +

    示例 2:

    + +
    +输入:version1 = "1.0", version2 = "1.0.0"
    +输出:0
    +解释:version1 没有指定下标为 2 的修订号,即视为 "0"
    +
    + +

    示例 3:

    + +
    +输入:version1 = "0.1", version2 = "1.1"
    +输出:-1
    +解释:version1 中下标为 0 的修订号是 "0",version2 中下标为 0 的修订号是 "1" 。0 < 1,所以 version1 < version2
    +
    + +

    示例 4:

    + +
    +输入:version1 = "1.0.1", version2 = "1"
    +输出:1
    +
    + +

    示例 5:

    + +
    +输入:version1 = "7.5.2.4", version2 = "7.5.3"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= version1.length, version2.length <= 500
    • +
    • version1version2 仅包含数字和 '.'
    • +
    • version1version2 都是 有效版本号
    • +
    • version1version2 的所有修订号都可以存储在 32 位整数
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0166.leetcode166 Fraction to Recurring Decimal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0166.leetcode166 Fraction to Recurring Decimal-zh.md" new file mode 100644 index 00000000..272f6f67 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0166.leetcode166 Fraction to Recurring Decimal-zh.md" @@ -0,0 +1,92 @@ +# [166. 分数到小数](https://leetcode-cn.com/problems/fraction-to-recurring-decimal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0166.Fraction%20to%20Recurring%20Decimal/README_EN.md) + +## 题目描述 + + + +

    给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数

    + +

    如果小数部分为循环小数,则将循环的部分括在括号内。

    + +

    如果存在多个答案,只需返回 任意一个

    + +

    对于所有给定的输入,保证 答案字符串的长度小于 104

    + +

     

    + +

    示例 1:

    + +
    +输入:numerator = 1, denominator = 2
    +输出:"0.5"
    +
    + +

    示例 2:

    + +
    +输入:numerator = 2, denominator = 1
    +输出:"2"
    +
    + +

    示例 3:

    + +
    +输入:numerator = 2, denominator = 3
    +输出:"0.(6)"
    +
    + +

    示例 4:

    + +
    +输入:numerator = 4, denominator = 333
    +输出:"0.(012)"
    +
    + +

    示例 5:

    + +
    +输入:numerator = 1, denominator = 5
    +输出:"0.2"
    +
    + +

     

    + +

    提示:

    + +
      +
    • -231 <= numerator, denominator <= 231 - 1
    • +
    • denominator != 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0167.leetcode167 Two Sum II - Input array is sorted-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0167.leetcode167 Two Sum II - Input array is sorted-zh.md" new file mode 100644 index 00000000..1c7e6600 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0167.leetcode167 Two Sum II - Input array is sorted-zh.md" @@ -0,0 +1,128 @@ +# [167. 两数之和 II - 输入有序数组](https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0167.Two%20Sum%20II%20-%20Input%20array%20is%20sorted/README_EN.md) + +## 题目描述 + + + +

    给定一个已按照 升序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target

    + +

    函数应该以长度为 2 的整数数组的形式返回这两个数的下标值numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length

    + +

    你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。

    +  + +

    示例 1:

    + +
    +输入:numbers = [2,7,11,15], target = 9
    +输出:[1,2]
    +解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
    +
    + +

    示例 2:

    + +
    +输入:numbers = [2,3,4], target = 6
    +输出:[1,3]
    +
    + +

    示例 3:

    + +
    +输入:numbers = [-1,0], target = -1
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= numbers.length <= 3 * 104
    • +
    • -1000 <= numbers[i] <= 1000
    • +
    • numbers递增顺序 排列
    • +
    • -1000 <= target <= 1000
    • +
    • 仅存在一个有效答案
    • +
    + + +## 解法 + + + +双指针解决。 + + + +### **Python3** + + + +```python +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + low, high = 0, len(numbers) - 1 + while low <= high: + if numbers[low] + numbers[high] == target: + return [low + 1, high + 1] + if numbers[low] + numbers[high] < target: + low += 1 + else: + high -= 1 + return [-1, -1] +``` + +### **Java** + + + +```java +class Solution { + public int[] twoSum(int[] numbers, int target) { + int low = 0, high = numbers.length - 1; + while (low <= high) { + if (numbers[low] + numbers[high] == target) { + return new int[]{low + 1, high + 1}; + } + if (numbers[low] + numbers[high] < target) { + ++low; + } else { + --high; + } + } + return new int[]{-1, -1}; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int low = 0, high = numbers.size() - 1; + while (low <= high) { + if (numbers[low] + numbers[high] == target) { + return {low + 1, high + 1}; + } + if (numbers[low] + numbers[high] < target) { + ++low; + } else { + --high; + } + } + return {-1, -1}; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0168.leetcode168 Excel Sheet Column Title-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0168.leetcode168 Excel Sheet Column Title-zh.md" new file mode 100644 index 00000000..588af56d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0168.leetcode168 Excel Sheet Column Title-zh.md" @@ -0,0 +1,117 @@ +# [168. Excel 表列名称](https://leetcode-cn.com/problems/excel-sheet-column-title) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0168.Excel%20Sheet%20Column%20Title/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数,返回它在 Excel 表中相对应的列名称。

    + +

    例如,

    + +
        1 -> A
    +    2 -> B
    +    3 -> C
    +    ...
    +    26 -> Z
    +    27 -> AA
    +    28 -> AB 
    +    ...
    +
    + +

    示例 1:

    + +
    输入: 1
    +输出: "A"
    +
    + +

    示例 2:

    + +
    输入: 28
    +输出: "AB"
    +
    + +

    示例 3:

    + +
    输入: 701
    +输出: "ZY"
    +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def convertToTitle(self, columnNumber: int) -> str: + res = [] + while columnNumber: + columnNumber -= 1 + res.append(chr(ord('A') + columnNumber % 26)) + columnNumber //= 26 + return ''.join(res[::-1]) +``` + +### **Java** + + + +```java +class Solution { + public String convertToTitle(int columnNumber) { + StringBuilder res = new StringBuilder(); + while (columnNumber != 0) { + --columnNumber; + res.append((char) ('A' + columnNumber % 26)); + columnNumber /= 26; + } + return res.reverse().toString(); + } +} +``` + +### **TypeScript** + +```ts +function convertToTitle(columnNumber: number): string { + let res: string[] = []; + while (columnNumber > 0) { + --columnNumber; + let num: number = columnNumber % 26; + res.unshift(String.fromCharCode(num + 65)); + columnNumber = Math.floor(columnNumber / 26); + } + return res.join(''); +}; +``` + +### **C#** + +```cs +public class Solution { + public string ConvertToTitle(int columnNumber) { + StringBuilder res = new StringBuilder(); + while (columnNumber != 0) { + --columnNumber; + res.Append((char) ('A' + columnNumber % 26)); + columnNumber /= 26; + } + return new string(res.ToString().Reverse().ToArray()); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0169.leetcode169 Majority Element-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0169.leetcode169 Majority Element-zh.md" new file mode 100644 index 00000000..f331ea74 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0169.leetcode169 Majority Element-zh.md" @@ -0,0 +1,154 @@ +# [169. 多数元素](https://leetcode-cn.com/problems/majority-element) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0169.Majority%20Element/README_EN.md) + +## 题目描述 + + + +

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

    + +

    你可以假设数组是非空的,并且给定的数组总是存在多数元素。

    + +

     

    + +

    示例 1:

    + +
    +输入:[3,2,3]
    +输出:3
    + +

    示例 2:

    + +
    +输入:[2,2,1,1,1,2,2]
    +输出:2
    +
    + +

     

    + +

    进阶:

    + +
      +
    • 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
    • +
    + + +## 解法 + + + +摩尔投票法。时间复杂度 O(n),空间复杂度 O(1)。 + + + +### **Python3** + + + +```python +class Solution: + def majorityElement(self, nums: List[int]) -> int: + cnt = major = 0 + for num in nums: + if cnt == 0: + major = num + cnt = 1 + else: + cnt += (1 if major == num else -1) + return major +``` + +### **Java** + + + +```java +class Solution { + public int majorityElement(int[] nums) { + int cnt = 0, major = 0; + for (int num : nums) { + if (cnt == 0) { + major = num; + cnt = 1; + } else { + cnt += (major == num ? 1 : -1); + } + } + return major; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var majorityElement = function(nums) { + let cnt = 0; + let major = 0; + for (const num of nums) { + if (cnt == 0) { + major = num; + cnt = 1; + } else { + cnt += (major == num ? 1 : -1); + } + } + return major; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int majorityElement(vector& nums) { + int cnt = 0, major = 0; + for (int num : nums) { + if (cnt == 0) { + major = num; + cnt = 1; + } else { + cnt += (major == num ? 1 : -1); + } + } + return major; + } +}; +``` + +### **C#** + +```cs +public class Solution { + public int MajorityElement(int[] nums) { + int cnt = 0, major = 0; + foreach (int num in nums) + { + if (cnt == 0) + { + major = num; + cnt = 1; + } + else + { + cnt += (major == num ? 1 : -1); + } + } + return major; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0170.leetcode170 Two Sum III - Data structure design-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0170.leetcode170 Two Sum III - Data structure design-zh.md" new file mode 100644 index 00000000..5c16df78 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0170.leetcode170 Two Sum III - Data structure design-zh.md" @@ -0,0 +1,144 @@ +# [170. 两数之和 III - 数据结构设计](https://leetcode-cn.com/problems/two-sum-iii-data-structure-design) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0170.Two%20Sum%20III%20-%20Data%20structure%20design/README_EN.md) + +## 题目描述 + + + +

    设计一个接收整数流的数据结构,该数据结构支持检查是否存在两数之和等于特定值。

    + +

    实现 TwoSum 类:

    + +
      +
    • TwoSum() 使用空数组初始化 TwoSum 对象
    • +
    • void add(int number) 向数据结构添加一个数 number
    • +
    • boolean find(int value) 寻找数据结构中是否存在一对整数,使得两数之和与给定的值相等。如果存在,返回 true ;否则,返回 false
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["TwoSum", "add", "add", "add", "find", "find"]
    +[[], [1], [3], [5], [4], [7]]
    +输出:
    +[null, null, null, null, true, false]
    +
    +解释:
    +TwoSum twoSum = new TwoSum();
    +twoSum.add(1);   // [] --> [1]
    +twoSum.add(3);   // [1] --> [1,3]
    +twoSum.add(5);   // [1,3] --> [1,3,5]
    +twoSum.find(4);  // 1 + 3 = 4,返回 true
    +twoSum.find(7);  // 没有两个整数加起来等于 7 ,返回 false
    + +

     

    + +

    提示:

    + +
      +
    • -105 <= number <= 105
    • +
    • -231 <= value <= 231 - 1
    • +
    • 最多调用 5 * 104addfind
    • +
    + +## 解法 + + + +“计数器”实现。 + + + +### **Python3** + + + +```python +class TwoSum: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.counter = collections.Counter() + + def add(self, number: int) -> None: + """ + Add the number to an internal data structure.. + """ + self.counter[number] += 1 + + def find(self, value: int) -> bool: + """ + Find if there exists any pair of numbers which sum is equal to the value. + """ + for num in self.counter.keys(): + other = value - num + if other in self.counter: + if other != num: + return True + if other == num and self.counter[num] > 1: + return True + return False + + +# Your TwoSum object will be instantiated and called as such: +# obj = TwoSum() +# obj.add(number) +# param_2 = obj.find(value) +``` + +### **Java** + + + +```java +class TwoSum { + private Map counter; + + /** Initialize your data structure here. */ + public TwoSum() { + counter = new HashMap<>(); + } + + /** Add the number to an internal data structure.. */ + public void add(int number) { + counter.put(number, counter.getOrDefault(number, 0) + 1); + } + + /** Find if there exists any pair of numbers which sum is equal to the value. */ + public boolean find(int value) { + for (int num : counter.keySet()) { + int other = value - num; + if (counter.containsKey(other)) { + if (num != other) { + return true; + } + if (num == other && counter.get(other) > 1) { + return true; + } + } + } + return false; + } +} + +/** + * Your TwoSum object will be instantiated and called as such: + * TwoSum obj = new TwoSum(); + * obj.add(number); + * boolean param_2 = obj.find(value); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0171.leetcode171 Excel Sheet Column Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0171.leetcode171 Excel Sheet Column Number-zh.md" new file mode 100644 index 00000000..6b2ff96b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0171.leetcode171 Excel Sheet Column Number-zh.md" @@ -0,0 +1,112 @@ +# [171. Excel表列序号](https://leetcode-cn.com/problems/excel-sheet-column-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0171.Excel%20Sheet%20Column%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个Excel表格中的列名称,返回其相应的列序号。

    + +

    例如,

    + +
        A -> 1
    +    B -> 2
    +    C -> 3
    +    ...
    +    Z -> 26
    +    AA -> 27
    +    AB -> 28 
    +    ...
    +
    + +

    示例 1:

    + +
    输入: "A"
    +输出: 1
    +
    + +

    示例 2:

    + +
    输入: "AB"
    +输出: 28
    +
    + +

    示例 3:

    + +
    输入: "ZY"
    +输出: 701
    + +

    致谢:
    +特别感谢 @ts 添加此问题并创建所有测试用例。

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def titleToNumber(self, columnTitle: str) -> int: + res = 0 + for c in columnTitle: + res = res * 26 + (ord(c) - ord('A') + 1) + return res +``` + +### **Java** + + + +```java +class Solution { + public int titleToNumber(String columnTitle) { + int res = 0; + for (char c : columnTitle.toCharArray()) { + res = res * 26 + (c - 'A' + 1); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function titleToNumber(columnTitle: string): number { + let res: number = 0; + for (let char of columnTitle) { + res = res * 26 + char.charCodeAt(0) - 64; + } + return res; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int titleToNumber(string columnTitle) { + int res = 0; + for (char c : columnTitle) { + res = res * 26 + (c - 'A' + 1); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0172.leetcode172 Factorial Trailing Zeroes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0172.leetcode172 Factorial Trailing Zeroes-zh.md" new file mode 100644 index 00000000..252ee67a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0172.leetcode172 Factorial Trailing Zeroes-zh.md" @@ -0,0 +1,69 @@ +# [172. 阶乘后的零](https://leetcode-cn.com/problems/factorial-trailing-zeroes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0172.Factorial%20Trailing%20Zeroes/README_EN.md) + +## 题目描述 + + + +

    给定一个整数 n,返回 n! 结果尾数中零的数量。

    + +

    示例 1:

    + +
    输入: 3
    +输出: 0
    +解释: 3! = 6, 尾数中没有零。
    + +

    示例 2:

    + +
    输入: 5
    +输出: 1
    +解释: 5! = 120, 尾数中有 1 个零.
    + +

    说明: 你算法的时间复杂度应为 O(log n) 

    + + +## 解法 + + + +统计5的个数 + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **TypeScript** + +```ts +function trailingZeroes(n: number): number { + let count = 0; + while (n > 0) { + n = Math.floor(n / 5); + count += n; + } + return count; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0173.leetcode173 Binary Search Tree Iterator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0173.leetcode173 Binary Search Tree Iterator-zh.md" new file mode 100644 index 00000000..c6aa07af --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0173.leetcode173 Binary Search Tree Iterator-zh.md" @@ -0,0 +1,231 @@ +# [173. 二叉搜索树迭代器](https://leetcode-cn.com/problems/binary-search-tree-iterator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0173.Binary%20Search%20Tree%20Iterator/README_EN.md) + +## 题目描述 + + + +实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器: +
    +
    +
      +
    • BSTIterator(TreeNode root) 初始化 BSTIterator 类的一个对象。BST 的根节点 root 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。
    • +
    • boolean hasNext() 如果向指针右侧遍历存在数字,则返回 true ;否则返回 false
    • +
    • int next()将指针向右移动,然后返回指针处的数字。
    • +
    + +

    注意,指针初始化为一个不存在于 BST 中的数字,所以对 next() 的首次调用将返回 BST 中的最小元素。

    +
    +
    + +

    你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 的中序遍历中至少存在一个下一个数字。

    + +

     

    + +

    示例:

    + +
    +
    +输入
    +["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
    +[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
    +输出
    +[null, 3, 7, true, 9, true, 15, true, 20, false]
    +
    +解释
    +BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
    +bSTIterator.next();    // 返回 3
    +bSTIterator.next();    // 返回 7
    +bSTIterator.hasNext(); // 返回 True
    +bSTIterator.next();    // 返回 9
    +bSTIterator.hasNext(); // 返回 True
    +bSTIterator.next();    // 返回 15
    +bSTIterator.hasNext(); // 返回 True
    +bSTIterator.next();    // 返回 20
    +bSTIterator.hasNext(); // 返回 False
    +
    +
    +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在范围 [1, 105]
    • +
    • 0 <= Node.val <= 106
    • +
    • 最多调用 105hasNextnext 操作
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以设计一个满足下述条件的解决方案吗?next()hasNext() 操作均摊时间复杂度为 O(1) ,并使用 O(h) 内存。其中 h 是树的高度。
    • +
    + + +## 解法 + + + +初始化数据时,递归中序遍历,将二叉搜索树每个结点的值保存在列表 `vals` 中。用 `cur/next` 指针记录外部即将遍历的位置,初始化为 0。 + +调用 `next()` 时,返回 `vals[cur]`,同时 `cur` 指针自增。调用 `hasNext()` 时,判断 `cur` 指针是否已经达到 `vals` 个数,若是,说明已经遍历结束,返回 false,否则返回 true。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + + def __init__(self, root: TreeNode): + def inorder(root): + if root is None: + return + inorder(root.left) + self.vals.append(root.val) + inorder(root.right) + + self.cur = 0 + self.vals = [] + inorder(root) + + def next(self) -> int: + res = self.vals[self.cur] + self.cur += 1 + return res + + def hasNext(self) -> bool: + return self.cur < len(self.vals) + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class BSTIterator { + + private List vals; + private int next; + + public BSTIterator(TreeNode root) { + next = 0; + vals = new ArrayList<>(); + inorder(root); + } + + public int next() { + return vals.get(next++); + } + + public boolean hasNext() { + return next < vals.size(); + } + + private void inorder(TreeNode root) { + if (root == null) { + return; + } + inorder(root.left); + vals.add(root.val); + inorder(root.right); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ +``` + +## **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + */ +var BSTIterator = function (root) { + this.stk = []; + this.cur = root; +} + + +/** + * @return {number} + */ +BSTIterator.prototype.next = function () { + while (this.cur) { + this.stk.push(this.cur); + this.cur = this.cur.left; + } + this.cur = this.stk.pop(); + let res = this.cur.val; + this.cur = this.cur.right; + return (res); +}; + +/** + * @return {boolean} + */ +BSTIterator.prototype.hasNext = function () { + if (this.stk.length === 0 && this.cur === null) return false; + return true; +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0174.leetcode174 Dungeon Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0174.leetcode174 Dungeon Game-zh.md" new file mode 100644 index 00000000..64580815 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0174.leetcode174 Dungeon Game-zh.md" @@ -0,0 +1,146 @@ +# [174. 地下城游戏](https://leetcode-cn.com/problems/dungeon-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0174.Dungeon%20Game/README_EN.md) + +## 题目描述 + + + + + + + +

    一些恶魔抓住了公主(P)并将她关在了地下城的右下角。地下城是由 M x N 个房间组成的二维网格。我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主。

    + + + +

    骑士的初始健康点数为一个正整数。如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡。

    + + + +

    有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为负整数,则表示骑士将损失健康点数);其他房间要么是空的(房间里的值为 0),要么包含增加骑士健康点数的魔法球(若房间里的值为正整数,则表示骑士将增加健康点数)。

    + + + +

    为了尽快到达公主,骑士决定每次只向右或向下移动一步。

    + + + +

     

    + + + +

    编写一个函数来计算确保骑士能够拯救到公主所需的最低初始健康点数。

    + + + +

    例如,考虑到如下布局的地下城,如果骑士遵循最佳路径 右 -> 右 -> 下 -> 下,则骑士的初始健康点数至少为 7

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    -2 (K)-33
    -5-101
    1030-5 (P)
    + + + + + +

     

    + + + +

    说明:

    + + + +
      +
    • +

      骑士的健康点数没有上限。

      +
    • +
    • 任何房间都可能对骑士的健康点数造成威胁,也可能增加骑士的健康点数,包括骑士进入的左上角房间以及公主被监禁的右下角房间。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0175.leetcode175 Combine Two Tables-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0175.leetcode175 Combine Two Tables-zh.md" new file mode 100644 index 00000000..46ae096b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0175.leetcode175 Combine Two Tables-zh.md" @@ -0,0 +1,62 @@ +# [175. 组合两个表](https://leetcode-cn.com/problems/combine-two-tables) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0175.Combine%20Two%20Tables/README_EN.md) + +## 题目描述 + + + +

    表1: Person

    + +
    +-------------+---------+
    +| 列名         | 类型     |
    ++-------------+---------+
    +| PersonId    | int     |
    +| FirstName   | varchar |
    +| LastName    | varchar |
    ++-------------+---------+
    +PersonId 是上表主键
    +
    + +

    表2: Address

    + +
    +-------------+---------+
    +| 列名         | 类型    |
    ++-------------+---------+
    +| AddressId   | int     |
    +| PersonId    | int     |
    +| City        | varchar |
    +| State       | varchar |
    ++-------------+---------+
    +AddressId 是上表主键
    +
    + +

     

    + +

    编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:

    + +

     

    + +
    FirstName, LastName, City, State
    +
    + + +## 解法 + + + +左连接。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT p.FirstName, p.LastName, a.City, a.State +FROM Person p +LEFT JOIN Address a +ON p.PersonId = a.PersonId; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0176.leetcode176 Second Highest Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0176.leetcode176 Second Highest Salary-zh.md" new file mode 100644 index 00000000..b2a97bd9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0176.leetcode176 Second Highest Salary-zh.md" @@ -0,0 +1,63 @@ +# [176. 第二高的薪水](https://leetcode-cn.com/problems/second-highest-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0176.Second%20Highest%20Salary/README_EN.md) + +## 题目描述 + + + +

    编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

    + +
    +----+--------+
    +| Id | Salary |
    ++----+--------+
    +| 1  | 100    |
    +| 2  | 200    |
    +| 3  | 300    |
    ++----+--------+
    +
    + +

    例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null

    + +
    +---------------------+
    +| SecondHighestSalary |
    ++---------------------+
    +| 200                 |
    ++---------------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +解法 1:使用 LIMIT 语句和子查询。 + +```sql +# Write your MySQL query statement below +SELECT +( + SELECT DISTINCT Salary + FROM Employee + ORDER BY Salary DESC + LIMIT 1 OFFSET 1 +) AS SecondHighestSalary; +``` + +解法 2:使用 `MAX()` 函数,从小于 `MAX()` 的 Salary 中挑选最大值 `MAX()` 即可。 + +```sql +# Write your MySQL query statement below +SELECT MAX(Salary) AS SecondHighestSalary +FROM Employee +WHERE Salary < ( + SELECT MAX(Salary) + FROM Employee +); +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0177.leetcode177 Nth Highest Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0177.leetcode177 Nth Highest Salary-zh.md" new file mode 100644 index 00000000..324447ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0177.leetcode177 Nth Highest Salary-zh.md" @@ -0,0 +1,54 @@ +# [177. 第N高的薪水](https://leetcode-cn.com/problems/nth-highest-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0177.Nth%20Highest%20Salary/README_EN.md) + +## 题目描述 + + + +

    编写一个 SQL 查询,获取 Employee 表中第 高的薪水(Salary)。

    + +
    +----+--------+
    +| Id | Salary |
    ++----+--------+
    +| 1  | 100    |
    +| 2  | 200    |
    +| 3  | 300    |
    ++----+--------+
    +
    + +

    例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 高的薪水,那么查询应返回 null

    + +
    +------------------------+
    +| getNthHighestSalary(2) |
    ++------------------------+
    +| 200                    |
    ++------------------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT +BEGIN + SET N = N - 1; + RETURN ( + # Write your MySQL query statement below. + SELECT ( + SELECT DISTINCT Salary + FROM Employee + ORDER BY Salary DESC + LIMIT 1 OFFSET N + ) + ); +END +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0178.leetcode178 Rank Scores-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0178.leetcode178 Rank Scores-zh.md" new file mode 100644 index 00000000..feb22d11 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0178.leetcode178 Rank Scores-zh.md" @@ -0,0 +1,89 @@ +# [178. 分数排名](https://leetcode-cn.com/problems/rank-scores) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0178.Rank%20Scores/README_EN.md) + +## 题目描述 + + + +

    编写一个 SQL 查询来实现分数排名。

    + +

    如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

    + +
    +----+-------+
    +| Id | Score |
    ++----+-------+
    +| 1  | 3.50  |
    +| 2  | 3.65  |
    +| 3  | 4.00  |
    +| 4  | 3.85  |
    +| 5  | 4.00  |
    +| 6  | 3.65  |
    ++----+-------+
    +
    + +

    例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):

    + +
    +-------+------+
    +| Score | Rank |
    ++-------+------+
    +| 4.00  | 1    |
    +| 4.00  | 1    |
    +| 3.85  | 2    |
    +| 3.65  | 3    |
    +| 3.65  | 3    |
    +| 3.50  | 4    |
    ++-------+------+
    +
    + +

    重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 `Rank`

    + + +## 解法 + + + + + +### **MySQL8** + +使用 `DENSE_RANK()` 函数,语法如下: + +```sql +DENSE_RANK() OVER ( + PARTITION BY [{,...}] + ORDER BY [ASC|DESC], [{,...}] +) +``` + +在这个语法中: + +- 首先,`PARTITION BY` 子句将 `FROM` 子句生成的结果集划分为分区。`DENSE_RANK()`函数应用于每个分区。 +- 其次,`ORDER BY` 子句指定 `DENSE_RANK()` 函数操作的每个分区中的行顺序。 + +与 `RANK()` 函数不同,`DENSE_RANK()` 函数始终返回连续的排名值。 + +题解如下: + +```sql +# Write your MySQL query statement below +SELECT Score, DENSE_RANK() OVER (ORDER BY Score DESC) 'Rank' +FROM Scores; +``` + +### **MySQL5** + +MySQL 8 开始才提供了 `ROW_NUMBER()`,`RANK()`,`DENSE_RANK()` 等[窗口函数](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html),在之前的版本,可以使用变量实现类似的功能: + +```sql +SELECT Score, + CONVERT(rk, SIGNED) `Rank` +FROM (SELECT Score, + IF(@latest = Score, @rank, @rank := @rank + 1) rk, + @latest := Score + FROM Scores, + (SELECT @rank := 0, @latest := NULL) tmp + ORDER BY Score DESC) s; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0179.leetcode179 Largest Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0179.leetcode179 Largest Number-zh.md" new file mode 100644 index 00000000..2c4d8c3c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0179.leetcode179 Largest Number-zh.md" @@ -0,0 +1,102 @@ +# [179. 最大数](https://leetcode-cn.com/problems/largest-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0179.Largest%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。

    + +

    注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。

    + +

     

    + +

    示例 1:

    + +
    +输入nums = [10,2]
    +输出:"210"
    + +

    示例 2:

    + +
    +输入nums = [3,30,34,5,9]
    +输出:"9534330"
    +
    + +

    示例 3:

    + +
    +输入nums = [1]
    +输出:"1"
    +
    + +

    示例 4:

    + +
    +输入nums = [10]
    +输出:"10"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 109
    • +
    + + +## 解法 + + + +先转成字符串列表,再对字符串列表进行字典序降序排列。最后将列表所有字符串拼接即可。 + + + +### **Python3** + + + +```python +from functools import cmp_to_key + +class Solution: + def largestNumber(self, nums: List[int]) -> str: + num_list = list(map(str, nums)) + num_list.sort(key=cmp_to_key(lambda x, y: int(y + x) - int(x + y))) + return '0' if num_list[0] == '0' else ''.join(num_list) +``` + +### **Java** + + + +```java +class Solution { + public String largestNumber(int[] nums) { + List numList = new ArrayList<>(); + for (int num : nums) { + numList.add(String.valueOf(num)); + } + numList.sort((a, b) -> (b + a).compareTo(a + b)); + if ("0".equals(numList.get(0))) return "0"; + StringBuilder sb = new StringBuilder(); + for (String s : numList) { + sb.append(s); + } + return sb.toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0180.leetcode180 Consecutive Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0180.leetcode180 Consecutive Numbers-zh.md" new file mode 100644 index 00000000..4ec2e4f6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0180.leetcode180 Consecutive Numbers-zh.md" @@ -0,0 +1,70 @@ +# [180. 连续出现的数字](https://leetcode-cn.com/problems/consecutive-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0180.Consecutive%20Numbers/README_EN.md) + +## 题目描述 + + + +

    表:Logs

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| id          | int     |
    +| num         | varchar |
    ++-------------+---------+
    +id 是这个表的主键。
    + +

     

    + +

    编写一个 SQL 查询,查找所有至少连续出现三次的数字。

    + +

    返回的结果表中的数据可以按 任意顺序 排列。

    + +

     

    + +

    查询结果格式如下面的例子所示:

    + +

     

    + +
    +Logs 表:
    ++----+-----+
    +| Id | Num |
    ++----+-----+
    +| 1  | 1   |
    +| 2  | 1   |
    +| 3  | 1   |
    +| 4  | 2   |
    +| 5  | 1   |
    +| 6  | 2   |
    +| 7  | 2   |
    ++----+-----+
    +
    +Result 表:
    ++-----------------+
    +| ConsecutiveNums |
    ++-----------------+
    +| 1               |
    ++-----------------+
    +1 是唯一连续出现至少三次的数字。
    +
    + + +## 解法 + + + + + +### **SQL** + +``` +select distinct(Num) as ConsecutiveNums from Logs Curr where + Num = (select Num from Logs where id = Curr.id - 1) and + Num = (select Num from Logs where id = Curr.id - 2) +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0181.leetcode181 Employees Earning More Than Their Managers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0181.leetcode181 Employees Earning More Than Their Managers-zh.md" new file mode 100644 index 00000000..c3fc3c23 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0181.leetcode181 Employees Earning More Than Their Managers-zh.md" @@ -0,0 +1,44 @@ +# [181. 超过经理收入的员工](https://leetcode-cn.com/problems/employees-earning-more-than-their-managers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0181.Employees%20Earning%20More%20Than%20Their%20Managers/README_EN.md) + +## 题目描述 + + + +

    Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。

    + +
    +----+-------+--------+-----------+
    +| Id | Name  | Salary | ManagerId |
    ++----+-------+--------+-----------+
    +| 1  | Joe   | 70000  | 3         |
    +| 2  | Henry | 80000  | 4         |
    +| 3  | Sam   | 60000  | NULL      |
    +| 4  | Max   | 90000  | NULL      |
    ++----+-------+--------+-----------+
    +
    + +

    给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

    + +
    +----------+
    +| Employee |
    ++----------+
    +| Joe      |
    ++----------+
    +
    + + +## 解法 + + + + + +### **SQL** + +``` +select Name as Employee from Employee Curr where + Salary > (select Salary from Employee where Id = Curr.ManagerId) +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0182.leetcode182 Duplicate Emails-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0182.leetcode182 Duplicate Emails-zh.md" new file mode 100644 index 00000000..5b28ab6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0182.leetcode182 Duplicate Emails-zh.md" @@ -0,0 +1,46 @@ +# [182. 查找重复的电子邮箱](https://leetcode-cn.com/problems/duplicate-emails) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0182.Duplicate%20Emails/README_EN.md) + +## 题目描述 + + + +

    编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

    + +

    示例:

    + +
    +----+---------+
    +| Id | Email   |
    ++----+---------+
    +| 1  | a@b.com |
    +| 2  | c@d.com |
    +| 3  | a@b.com |
    ++----+---------+
    +
    + +

    根据以上输入,你的查询应返回以下结果:

    + +
    +---------+
    +| Email   |
    ++---------+
    +| a@b.com |
    ++---------+
    +
    + +

    说明:所有电子邮箱都是小写字母。

    + + +## 解法 + + + + + +### **SQL** + +``` +select Email from Person group by Email having count(Email) > 1 +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0183.leetcode183 Customers Who Never Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0183.leetcode183 Customers Who Never Order-zh.md" new file mode 100644 index 00000000..38f5c629 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0183.leetcode183 Customers Who Never Order-zh.md" @@ -0,0 +1,57 @@ +# [183. 从不订购的客户](https://leetcode-cn.com/problems/customers-who-never-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0183.Customers%20Who%20Never%20Order/README_EN.md) + +## 题目描述 + + + +

    某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

    + +

    Customers 表:

    + +
    +----+-------+
    +| Id | Name  |
    ++----+-------+
    +| 1  | Joe   |
    +| 2  | Henry |
    +| 3  | Sam   |
    +| 4  | Max   |
    ++----+-------+
    +
    + +

    Orders 表:

    + +
    +----+------------+
    +| Id | CustomerId |
    ++----+------------+
    +| 1  | 3          |
    +| 2  | 1          |
    ++----+------------+
    +
    + +

    例如给定上述表格,你的查询应返回:

    + +
    +-----------+
    +| Customers |
    ++-----------+
    +| Henry     |
    +| Max       |
    ++-----------+
    +
    + + +## 解法 + + + + + +### **SQL** + +``` +select Name as Customers from Customers + where id not in (select CustomerId from Orders) +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0184.leetcode184 Department Highest Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0184.leetcode184 Department Highest Salary-zh.md" new file mode 100644 index 00000000..bca09e48 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0184.leetcode184 Department Highest Salary-zh.md" @@ -0,0 +1,69 @@ +# [184. 部门工资最高的员工](https://leetcode-cn.com/problems/department-highest-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0184.Department%20Highest%20Salary/README_EN.md) + +## 题目描述 + + + +

    Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。

    + +
    +----+-------+--------+--------------+
    +| Id | Name  | Salary | DepartmentId |
    ++----+-------+--------+--------------+
    +| 1  | Joe   | 70000  | 1            |
    +| 2  | Jim   | 90000  | 1            |
    +| 3  | Henry | 80000  | 2            |
    +| 4  | Sam   | 60000  | 2            |
    +| 5  | Max   | 90000  | 1            |
    ++----+-------+--------+--------------+
    + +

    Department 表包含公司所有部门的信息。

    + +
    +----+----------+
    +| Id | Name     |
    ++----+----------+
    +| 1  | IT       |
    +| 2  | Sales    |
    ++----+----------+
    + +

    编写一个 SQL 查询,找出每个部门工资最高的员工。对于上述表,您的 SQL 查询应返回以下行(行的顺序无关紧要)。

    + +
    +------------+----------+--------+
    +| Department | Employee | Salary |
    ++------------+----------+--------+
    +| IT         | Max      | 90000  |
    +| IT         | Jim      | 90000  |
    +| Sales      | Henry    | 80000  |
    ++------------+----------+--------+
    + +

    解释:

    + +

    Max 和 Jim 在 IT 部门的工资都是最高的,Henry 在销售部的工资最高。

    + + +## 解法 + + + + + +### **SQL** + +``` +SELECT + Department.NAME AS Department, + Employee.NAME AS Employee, + Salary +FROM + Employee, + Department +WHERE + Employee.DepartmentId = Department.Id + AND ( Employee.DepartmentId, Salary ) + IN (SELECT DepartmentId, max( Salary ) + FROM Employee + GROUP BY DepartmentId ) +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0185.leetcode185 Department Top Three Salaries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0185.leetcode185 Department Top Three Salaries-zh.md" new file mode 100644 index 00000000..8a565e1d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0185.leetcode185 Department Top Three Salaries-zh.md" @@ -0,0 +1,78 @@ +# [185. 部门工资前三高的所有员工](https://leetcode-cn.com/problems/department-top-three-salaries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0185.Department%20Top%20Three%20Salaries/README_EN.md) + +## 题目描述 + + + +

    Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId

    + +
    +----+-------+--------+--------------+
    +| Id | Name  | Salary | DepartmentId |
    ++----+-------+--------+--------------+
    +| 1  | Joe   | 85000  | 1            |
    +| 2  | Henry | 80000  | 2            |
    +| 3  | Sam   | 60000  | 2            |
    +| 4  | Max   | 90000  | 1            |
    +| 5  | Janet | 69000  | 1            |
    +| 6  | Randy | 85000  | 1            |
    +| 7  | Will  | 70000  | 1            |
    ++----+-------+--------+--------------+
    + +

    Department 表包含公司所有部门的信息。

    + +
    +----+----------+
    +| Id | Name     |
    ++----+----------+
    +| 1  | IT       |
    +| 2  | Sales    |
    ++----+----------+
    + +

    编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:

    + +
    +------------+----------+--------+
    +| Department | Employee | Salary |
    ++------------+----------+--------+
    +| IT         | Max      | 90000  |
    +| IT         | Randy    | 85000  |
    +| IT         | Joe      | 85000  |
    +| IT         | Will     | 70000  |
    +| Sales      | Henry    | 80000  |
    +| Sales      | Sam      | 60000  |
    ++------------+----------+--------+
    + +

    解释:

    + +

    IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。

    + + +## 解法 + + + + + +### **SQL** + +``` +SELECT + Department.NAME AS Department, + Employee.NAME AS Employee, + Salary +FROM + Employee, + Department +WHERE + Employee.DepartmentId = Department.Id + AND (SELECT + COUNT(DISTINCT e2.Salary) + FROM + Employee e2 + WHERE + e2.Salary > Employee.Salary + AND Employee.DepartmentId = e2.DepartmentId + ) < 3 +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0186.leetcode186 Reverse Words in a String II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0186.leetcode186 Reverse Words in a String II-zh.md" new file mode 100644 index 00000000..17990a8e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0186.leetcode186 Reverse Words in a String II-zh.md" @@ -0,0 +1,55 @@ +# [186. 翻转字符串里的单词 II](https://leetcode-cn.com/problems/reverse-words-in-a-string-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0186.Reverse%20Words%20in%20a%20String%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,逐个翻转字符串中的每个单词。

    + +

    示例:

    + +
    输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
    +输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
    + +

    注意:

    + +
      +
    • 单词的定义是不包含空格的一系列字符
    • +
    • 输入字符串中不会包含前置或尾随的空格
    • +
    • 单词与单词之间永远是以单个空格隔开的
    • +
    + +

    进阶:使用 O(1) 额外空间复杂度的原地解法。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0187.leetcode187 Repeated DNA Sequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0187.leetcode187 Repeated DNA Sequences-zh.md" new file mode 100644 index 00000000..d8d163a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0187.leetcode187 Repeated DNA Sequences-zh.md" @@ -0,0 +1,113 @@ +# [187. 重复的DNA序列](https://leetcode-cn.com/problems/repeated-dna-sequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0187.Repeated%20DNA%20Sequences/README_EN.md) + +## 题目描述 + + + +

    所有 DNA 都由一系列缩写为 'A''C''G''T' 的核苷酸组成,例如:"ACGAATTCCG"。在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。

    + +

    编写一个函数来找出所有目标子串,目标子串的长度为 10,且在 DNA 字符串 s 中出现次数超过一次。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
    +输出:["AAAAACCCCC","CCCCCAAAAA"]
    +
    + +

    示例 2:

    + +
    +输入:s = "AAAAAAAAAAAAA"
    +输出:["AAAAAAAAAA"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 105
    • +
    • s[i]'A''C''G''T'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findRepeatedDnaSequences(self, s: str) -> List[str]: + n = 10 + subs = set() + res = set() + for i in range(len(s) - n + 1): + sub = s[i:i + n] + if sub in subs: + res.add(sub) + subs.add(sub) + return list(res) +``` + +### **Java** + + + +```java +class Solution { + public List findRepeatedDnaSequences(String s) { + int len = 10; + Set subs = new HashSet<>(); + Set res = new HashSet<>(); + for (int i = 0; i < s.length() - len + 1; ++i) { + String sub = s.substring(i, i + len); + if (subs.contains(sub)) { + res.add(sub); + } + subs.add(sub); + } + return new ArrayList<>(res); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {string[]} + */ +var findRepeatedDnaSequences = function(s) { + let n = 10; + let subs = new Set(); + let res = new Set(); + for (let i = 0; i < s.length - n + 1; i++) { + let sub = s.slice(i, i + n); + if (subs.has(sub)) { + res.add(sub); + } + subs.add(sub); + } + return [...res]; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0188.leetcode188 Best Time to Buy and Sell Stock IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0188.leetcode188 Best Time to Buy and Sell Stock IV-zh.md" new file mode 100644 index 00000000..e31d3190 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0188.leetcode188 Best Time to Buy and Sell Stock IV-zh.md" @@ -0,0 +1,71 @@ +# [188. 买卖股票的最佳时机 IV](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0188.Best%20Time%20to%20Buy%20and%20Sell%20Stock%20IV/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。

    + +

    设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

    + +

    注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

    + +

     

    + +

    示例 1:

    + +
    +输入:k = 2, prices = [2,4,1]
    +输出:2
    +解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
    + +

    示例 2:

    + +
    +输入:k = 2, prices = [3,2,6,5,0,3]
    +输出:7
    +解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
    +     随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= k <= 100
    • +
    • 0 <= prices.length <= 1000
    • +
    • 0 <= prices[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0189.leetcode189 Rotate Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0189.leetcode189 Rotate Array-zh.md" new file mode 100644 index 00000000..d35d3854 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0189.leetcode189 Rotate Array-zh.md" @@ -0,0 +1,145 @@ +# [189. 旋转数组](https://leetcode-cn.com/problems/rotate-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0189.Rotate%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

    + +

     

    + +

    进阶:

    + +
      +
    • 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
    • +
    • 你可以使用空间复杂度为 O(1) 的 原地 算法解决这个问题吗?
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入: nums = [1,2,3,4,5,6,7], k = 3
    +输出: [5,6,7,1,2,3,4]
    +解释:
    +向右旋转 1 步: [7,1,2,3,4,5,6]
    +向右旋转 2 步: [6,7,1,2,3,4,5]
    +向右旋转 3 步: [5,6,7,1,2,3,4]
    +
    + +

    示例 2:

    + +
    +输入:nums = [-1,-100,3,99], k = 2
    +输出:[3,99,-1,-100]
    +解释: 
    +向右旋转 1 步: [99,-1,-100,3]
    +向右旋转 2 步: [3,99,-1,-100]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 2 * 104
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • 0 <= k <= 105
    • +
    + +
      +
    + + +## 解法 + + + +若 `k=3`,`nums=[1,2,3,4,5,6,7]`。 + +先将 `nums` 整体翻转:`[1,2,3,4,5,6,7]` -> `[7,6,5,4,3,2,1]` + +再翻转 `0~k-1` 范围内的元素:`[7,6,5,4,3,2,1]` -> `[5,6,7,4,3,2,1]` + +最后翻转 `k~n-1` 范围内的元素,即可得到最终结果:`[5,6,7,4,3,2,1]` -> `[5,6,7,1,2,3,4]` + + + +### **Python3** + + + +```python +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + n = len(nums) + k %= n + if n < 2 or k == 0: + return + nums[:] = nums[::-1] + nums[:k] = nums[:k][::-1] + nums[k:] = nums[k:][::-1] +``` + +### **Java** + + + +```java +class Solution { + public void rotate(int[] nums, int k) { + if (nums == null) { + return; + } + int n = nums.length; + k %= n; + if (n < 2 || k == 0) { + return; + } + + rotate(nums, 0, n - 1); + rotate(nums, 0, k - 1); + rotate(nums, k, n - 1); + } + + private void rotate(int[] nums, int i, int j) { + while (i < j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + ++i; + --j; + } + } +} +``` + +### **JavaScript** + + +使用原生 API 将数组的 `k~n-1` 范围内的元素插入到前面 + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {void} Do not return anything, modify nums in-place instead. + */ +var rotate = function (nums, k) { + k %= nums.length; + nums.splice(0, 0, ...nums.splice(-k, k)) +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0190.leetcode190 Reverse Bits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0190.leetcode190 Reverse Bits-zh.md" new file mode 100644 index 00000000..76f9c0f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0190.leetcode190 Reverse Bits-zh.md" @@ -0,0 +1,146 @@ +# [190. 颠倒二进制位](https://leetcode-cn.com/problems/reverse-bits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0190.Reverse%20Bits/README_EN.md) + +## 题目描述 + + + +

    颠倒给定的 32 位无符号整数的二进制位。

    + +

     

    + +

    提示:

    + +
      +
    • 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
    • +
    • 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825
    • +
    + +

     

    + +

    进阶:
    +如果多次调用这个函数,你将如何优化你的算法?

    + +

     

    + +

    示例 1:

    + +
    +输入: 00000010100101000001111010011100
    +输出: 00111001011110000010100101000000
    +解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
    +     因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000
    + +

    示例 2:

    + +
    +输入:11111111111111111111111111111101
    +输出:10111111111111111111111111111111
    +解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
    +     因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
    + +

    示例 1:

    + +
    +输入:n = 00000010100101000001111010011100
    +输出:964176192 (00111001011110000010100101000000)
    +解释:输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
    +     因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000
    + +

    示例 2:

    + +
    +输入:n = 11111111111111111111111111111101
    +输出:3221225471 (10111111111111111111111111111111)
    +解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
    +     因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
    + +

     

    + +

    提示:

    + +
      +
    • 输入是一个长度为 32 的二进制字符串
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def reverseBits(self, n: int) -> int: + res = 0 + for i in range(32): + res |= ((n & 1) << (31 - i)) + n >>= 1 + return res +``` + +### **Java** + + + +```java +public class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + int res = 0; + for (int i = 0; i < 32 && n != 0; ++i) { + res |= ((n & 1) << (31 - i)); + n >>>= 1; + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t res = 0; + for (int i = 0; i < 32; ++i) { + res |= ((n & 1) << (31 - i)); + n >>= 1; + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n) { + let res = 0; + for (let i = 0; i < 32 && n > 0; ++i) { + res |= (n & 1) << (31 - i); + n >>>= 1; + } + // 无符号右移 + return res >>> 0; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0191.leetcode191 Number of 1 Bits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0191.leetcode191 Number of 1 Bits-zh.md" new file mode 100644 index 00000000..63413ffa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0191.leetcode191 Number of 1 Bits-zh.md" @@ -0,0 +1,130 @@ +# [191. 位1的个数](https://leetcode-cn.com/problems/number-of-1-bits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0191.Number%20of%201%20Bits/README_EN.md) + +## 题目描述 + + + +

    编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。

    + +

     

    + +

    提示:

    + +
      +
    • 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
    • +
    • 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:00000000000000000000000000001011
    +输出:3
    +解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
    +
    + +

    示例 2:

    + +
    +输入:00000000000000000000000010000000
    +输出:1
    +解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
    +
    + +

    示例 3:

    + +
    +输入:11111111111111111111111111111101
    +输出:31
    +解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
    + +

     

    + +

    提示:

    + +
      +
    • 输入必须是长度为 32二进制串
    • +
    + +
      +
    + +

     

    + +

    进阶

    + +
      +
    • 如果多次调用这个函数,你将如何优化你的算法?
    • +
    + + +## 解法 + + + +`n & (n - 1)` 会消除 n 中最后一位中的 1。 + +同 [剑指 Offer 15. 二进制中 1 的个数](/lcof/面试题15.%20二进制中1的个数/README.md) + + + +### **Python3** + + + +```python +class Solution: + def hammingWeight(self, n: int) -> int: + res = 0 + while n: + n &= (n - 1) + res += 1 + return res +``` + +### **Java** + + + +```java +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int res = 0; + while (n != 0) { + n &= (n - 1); + ++res; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} n - a positive integer + * @return {number} + */ +var hammingWeight = function (n) { + let res = 0; + while (n) { + n &= n - 1; + ++res; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0192.leetcode192 Word Frequency-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0192.leetcode192 Word Frequency-zh.md" new file mode 100644 index 00000000..f39c4f52 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0192.leetcode192 Word Frequency-zh.md" @@ -0,0 +1,57 @@ +# [192. 统计词频](https://leetcode-cn.com/problems/word-frequency) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0192.Word%20Frequency/README_EN.md) + +## 题目描述 + + + +

    写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。

    + +

    为了简单起见,你可以假设:

    + +
      +
    • words.txt只包括小写字母和 ' ' 。
    • +
    • 每个单词只由小写字母组成。
    • +
    • 单词间由一个或多个空格字符分隔。
    • +
    + +

    示例:

    + +

    假设 words.txt 内容如下:

    + +
    the day is sunny the the
    +the sunny is is
    +
    + +

    你的脚本应当输出(以词频降序排列):

    + +
    the 4
    +is 3
    +sunny 2
    +day 1
    +
    + +

    说明:

    + +
      +
    • 不要担心词频相同的单词的排序问题,每个单词出现的频率都是唯一的。
    • +
    • 你可以使用一行 Unix pipes 实现吗?
    • +
    + + +## 解法 + + + + + +### **Bash** + + + +```sh + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0193.leetcode193 Valid Phone Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0193.leetcode193 Valid Phone Numbers-zh.md" new file mode 100644 index 00000000..9743d9a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0193.leetcode193 Valid Phone Numbers-zh.md" @@ -0,0 +1,49 @@ +# [193. 有效电话号码](https://leetcode-cn.com/problems/valid-phone-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0193.Valid%20Phone%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给定一个包含电话号码列表(一行一个电话号码)的文本文件 file.txt,写一个单行 bash 脚本输出所有有效的电话号码。

    + +

    你可以假设一个有效的电话号码必须满足以下两种格式: (xxx) xxx-xxxx 或 xxx-xxx-xxxx。(x 表示一个数字)

    + +

    你也可以假设每行前后没有多余的空格字符。

    + +

     

    + +

    示例:

    + +

    假设 file.txt 内容如下:

    + +
    +987-123-4567
    +123 456 7890
    +(123) 456-7890
    +
    + +

    你的脚本应当输出下列有效的电话号码:

    + +
    +987-123-4567
    +(123) 456-7890
    +
    + + +## 解法 + + + + + +### **Bash** + + + +```sh + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0194.leetcode194 Transpose File-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0194.leetcode194 Transpose File-zh.md" new file mode 100644 index 00000000..c686f61f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0194.leetcode194 Transpose File-zh.md" @@ -0,0 +1,47 @@ +# [194. 转置文件](https://leetcode-cn.com/problems/transpose-file) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0194.Transpose%20File/README_EN.md) + +## 题目描述 + + + +

    给定一个文件 file.txt,转置它的内容。

    + +

    你可以假设每行列数相同,并且每个字段由 ' ' 分隔。

    + +

     

    + +

    示例:

    + +

    假设 file.txt 文件内容如下:

    + +
    +name age
    +alice 21
    +ryan 30
    +
    + +

    应当输出:

    + +
    +name alice ryan
    +age 21 30
    +
    + + +## 解法 + + + + + +### **Bash** + + + +```sh + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0195.leetcode195 Tenth Line-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0195.leetcode195 Tenth Line-zh.md" new file mode 100644 index 00000000..ecdffae7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0195.leetcode195 Tenth Line-zh.md" @@ -0,0 +1,51 @@ +# [195. 第十行](https://leetcode-cn.com/problems/tenth-line) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0195.Tenth%20Line/README_EN.md) + +## 题目描述 + + + +

    给定一个文本文件 file.txt,请只打印这个文件中的第十行。

    + +

    示例:

    + +

    假设 file.txt 有如下内容:

    + +
    Line 1
    +Line 2
    +Line 3
    +Line 4
    +Line 5
    +Line 6
    +Line 7
    +Line 8
    +Line 9
    +Line 10
    +
    + +

    你的脚本应当显示第十行:

    + +
    Line 10
    +
    + +

    说明:
    +1. 如果文件少于十行,你应当输出什么?
    +2. 至少有三种不同的解法,请尝试尽可能多的方法来解题。

    + + +## 解法 + + + + + +### **Bash** + + + +```sh + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0196.leetcode196 Delete Duplicate Emails-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0196.leetcode196 Delete Duplicate Emails-zh.md" new file mode 100644 index 00000000..5aa32bc6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0196.leetcode196 Delete Duplicate Emails-zh.md" @@ -0,0 +1,53 @@ +# [196. 删除重复的电子邮箱](https://leetcode-cn.com/problems/delete-duplicate-emails) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0196.Delete%20Duplicate%20Emails/README_EN.md) + +## 题目描述 + + + +

    编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。

    + +
    +----+------------------+
    +| Id | Email            |
    ++----+------------------+
    +| 1  | john@example.com |
    +| 2  | bob@example.com  |
    +| 3  | john@example.com |
    ++----+------------------+
    +Id 是这个表的主键。
    +
    + +

    例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

    + +
    +----+------------------+
    +| Id | Email            |
    ++----+------------------+
    +| 1  | john@example.com |
    +| 2  | bob@example.com  |
    ++----+------------------+
    +
    + +

     

    + +

    提示:

    + +
      +
    • 执行 SQL 之后,输出是整个 Person 表。
    • +
    • 使用 delete 语句。
    • +
    + + +## 解法 + + + + + +### **SQL** + +``` +delete from Person where Id not in (select min(Id) from (select * from Person) as p group by p.Email) +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0197.leetcode197 Rising Temperature-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0197.leetcode197 Rising Temperature-zh.md" new file mode 100644 index 00000000..c6dd54f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0197.leetcode197 Rising Temperature-zh.md" @@ -0,0 +1,74 @@ +# [197. 上升的温度](https://leetcode-cn.com/problems/rising-temperature) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0197.Rising%20Temperature/README_EN.md) + +## 题目描述 + + + +
    +
    +

    Weather

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| recordDate    | date    |
    +| temperature   | int     |
    ++---------------+---------+
    +id 是这个表的主键
    +该表包含特定日期的温度信息
    + +

     

    + +

    编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id

    + +

    返回结果 不要求顺序

    + +

    查询结果格式如下例:

    + +
    +Weather
    ++----+------------+-------------+
    +| id | recordDate | Temperature |
    ++----+------------+-------------+
    +| 1  | 2015-01-01 | 10          |
    +| 2  | 2015-01-02 | 25          |
    +| 3  | 2015-01-03 | 20          |
    +| 4  | 2015-01-04 | 30          |
    ++----+------------+-------------+
    +
    +Result table:
    ++----+
    +| id |
    ++----+
    +| 2  |
    +| 4  |
    ++----+
    +2015-01-02 的温度比前一天高(10 -> 25)
    +2015-01-04 的温度比前一天高(20 -> 30)
    +
    +
    +
    + + +## 解法 + + + + + +### **SQL** + +``` +select w1.Id +from + Weather w1, + Weather w2 +where + DATEDIFF(w1.RecordDate, w2.RecordDate) = 1 and w1.Temperature > w2.Temperature +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0198.leetcode198 House Robber-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0198.leetcode198 House Robber-zh.md" new file mode 100644 index 00000000..8b660d53 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0198.leetcode198 House Robber-zh.md" @@ -0,0 +1,126 @@ +# [198. 打家劫舍](https://leetcode-cn.com/problems/house-robber) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0198.House%20Robber/README_EN.md) + +## 题目描述 + + + +

    你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

    + +

    给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。

    + +

     

    + +

    示例 1:

    + +
    +输入:[1,2,3,1]
    +输出:4
    +解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
    +     偷窃到的最高金额 = 1 + 3 = 4 。
    + +

    示例 2:

    + +
    +输入:[2,7,9,3,1]
    +输出:12
    +解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
    +     偷窃到的最高金额 = 2 + 9 + 1 = 12 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 400
    • +
    + + +## 解法 + + + +动态规划法。状态转移方程:`f(n) = Math.max(f(n - 2) + nums[n], nums[n - 1])`。 + + + +### **Python3** + + + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + a, b = 0, nums[0] + for num in nums[1:]: + a, b = b, max(num + a, b) + return b +``` + +### **Java** + + + +```java +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + int a = 0, b = nums[0]; + for (int i = 1; i < n; ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + int a = 0, b = nums[0]; + for (int i = 1; i < n; ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **Go** + +```go +func rob(nums []int) int { + a, b, n := 0, nums[0], len(nums) + for i := 1; i < n; i++ { + a, b = b, max(nums[i] + a, b) + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0199.leetcode199 Binary Tree Right Side View-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0199.leetcode199 Binary Tree Right Side View-zh.md" new file mode 100644 index 00000000..e1e1a316 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0199.leetcode199 Binary Tree Right Side View-zh.md" @@ -0,0 +1,108 @@ +# [199. 二叉树的右视图](https://leetcode-cn.com/problems/binary-tree-right-side-view) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0100-0199/0199.Binary%20Tree%20Right%20Side%20View/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

    + +

    示例:

    + +
    输入: [1,2,3,null,5,null,4]
    +输出: [1, 3, 4]
    +解释:
    +
    +   1            <---
    + /   \
    +2     3         <---
    + \     \
    +  5     4       <---
    +
    + + +## 解法 + + + +队列实现。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: TreeNode) -> List[int]: + if not root: + return [] + q = collections.deque([root]) + res = [] + while q: + size = len(q) + res.append(q[0].val) + for _ in range(size): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List rightSideView(TreeNode root) { + if (root == null) return Collections.emptyList(); + Deque q = new ArrayDeque<>(); + q.offer(root); + List res = new ArrayList<>(); + while (!q.isEmpty()) { + int size = q.size(); + res.add(q.peek().val); + while (size-- > 0) { + TreeNode node = q.poll(); + if (node.right != null) q.offer(node.right); + if (node.left != null) q.offer(node.left); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0200.leetcode200 Number of Islands-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0200.leetcode200 Number of Islands-zh.md" new file mode 100644 index 00000000..c6c20685 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0200.leetcode200 Number of Islands-zh.md" @@ -0,0 +1,113 @@ +# [200. 岛屿数量](https://leetcode-cn.com/problems/number-of-islands) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0200.Number%20of%20Islands/README_EN.md) + +## 题目描述 + + + +

    给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

    + +

    岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

    + +

    此外,你可以假设该网格的四条边均被水包围。

    + +

     

    + +

    示例 1:

    + +
    +输入:grid = [
    +  ["1","1","1","1","0"],
    +  ["1","1","0","1","0"],
    +  ["1","1","0","0","0"],
    +  ["0","0","0","0","0"]
    +]
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:grid = [
    +  ["1","1","0","0","0"],
    +  ["1","1","0","0","0"],
    +  ["0","0","1","0","0"],
    +  ["0","0","0","1","1"]
    +]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 300
    • +
    • grid[i][j] 的值为 '0''1'
    • +
    + + +## 解法 + + + +BFS/DFS 均可 + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **TypeScript** + +```ts +function numIslands(grid: string[][]): number { + let m = grid.length, n = grid[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(grid, i, j); + ++ans; + } + } + } + return ans; +}; + +function dfs(grid: string[][], i: number, j: number) { + let m = grid.length, n = grid[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || grid[i][j] == '0') { + return; + } + grid[i][j] = '0'; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + dfs(grid, x, y); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0201.leetcode201 Bitwise AND of Numbers Range-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0201.leetcode201 Bitwise AND of Numbers Range-zh.md" new file mode 100644 index 00000000..daf44392 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0201.leetcode201 Bitwise AND of Numbers Range-zh.md" @@ -0,0 +1,71 @@ +# [201. 数字范围按位与](https://leetcode-cn.com/problems/bitwise-and-of-numbers-range) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0201.Bitwise%20AND%20of%20Numbers%20Range/README_EN.md) + +## 题目描述 + + + +

    给你两个整数 leftright ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 leftright 端点)。

    + +

     

    + +

    示例 1:

    + +
    +输入:left = 5, right = 7
    +输出:4
    +
    + +

    示例 2:

    + +
    +输入:left = 0, right = 0
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:left = 1, right = 2147483647
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= left <= right <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0202.leetcode202 Happy Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0202.leetcode202 Happy Number-zh.md" new file mode 100644 index 00000000..b7e52f03 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0202.leetcode202 Happy Number-zh.md" @@ -0,0 +1,111 @@ +# [202. 快乐数](https://leetcode-cn.com/problems/happy-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0202.Happy%20Number/README_EN.md) + +## 题目描述 + + + +

    编写一个算法来判断一个数 n 是不是快乐数。

    + +

    「快乐数」定义为:

    + +
      +
    • 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
    • +
    • 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
    • +
    • 如果 可以变为  1,那么这个数就是快乐数。
    • +
    + +

    如果 n 是快乐数就返回 true ;不是,则返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:19
    +输出:true
    +解释:
    +12 + 92 = 82
    +82 + 22 = 68
    +62 + 82 = 100
    +12 + 02 + 02 = 1
    +
    + +

    示例 2:

    + +
    +输入:n = 2
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isHappy(self, n: int) -> bool: + def get_next(n): + s = 0 + while n > 0: + n, digit = divmod(n, 10) + s += digit ** 2 + return s + + visited = set() + while n != 1 and n not in visited: + visited.add(n) + n = get_next(n) + return n == 1 +``` + +### **Java** + + + +```java +class Solution { + public boolean isHappy(int n) { + Set visited = new HashSet<>(); + while (n != 1 && !visited.contains(n)) { + visited.add(n); + n = getNext(n); + } + return n == 1; + } + + private int getNext(int n) { + int s = 0; + while (n > 0) { + int digit = n % 10; + s += digit * digit; + n /= 10; + } + return s; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0203.leetcode203 Remove Linked List Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0203.leetcode203 Remove Linked List Elements-zh.md" new file mode 100644 index 00000000..d1d0e1d7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0203.leetcode203 Remove Linked List Elements-zh.md" @@ -0,0 +1,174 @@ +# [203. 移除链表元素](https://leetcode-cn.com/problems/remove-linked-list-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0203.Remove%20Linked%20List%20Elements/README_EN.md) + +## 题目描述 + + + +给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。 +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,6,3,4,5,6], val = 6
    +输出:[1,2,3,4,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [], val = 1
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:head = [7,7,7,7], val = 7
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 列表中的节点在范围 [0, 104]
    • +
    • 1 <= Node.val <= 50
    • +
    • 0 <= k <= 50
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeElements(self, head: ListNode, val: int) -> ListNode: + dummy = ListNode(-1, head) + pre = dummy + while pre and pre.next: + if pre.next.val != val: + pre = pre.next + else: + pre.next = pre.next.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeElements(ListNode head, int val) { + ListNode dummy = new ListNode(-1, head); + ListNode pre = dummy; + while (pre != null && pre.next != null) { + if (pre.next.val != val) pre = pre.next; + else pre.next = pre.next.next; + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + ListNode* dummy = new ListNode(); + dummy->next = head; + ListNode* p = dummy; + while (p->next) { + if (p->next->val == val) { + p->next = p->next->next; + } else { + p = p->next; + } + } + return dummy->next; + } +}; +``` + +### **Go** + +```go +func removeElements(head *ListNode, val int) *ListNode { + dummy := new(ListNode) + dummy.Next = head + p := dummy + for p.Next != nil { + if p.Next.Val == val { + p.Next = p.Next.Next + } else { + p = p.Next + } + } + return dummy.Next +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + + function removeElements(head: ListNode | null, val: number): ListNode | null { + let dummy: ListNode = new ListNode(0, head); + let cur: ListNode = dummy; + while (cur.next != null) { + if (cur.next.val == val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return dummy.next; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0204.leetcode204 Count Primes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0204.leetcode204 Count Primes-zh.md" new file mode 100644 index 00000000..945872b3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0204.leetcode204 Count Primes-zh.md" @@ -0,0 +1,104 @@ +# [204. 计数质数](https://leetcode-cn.com/problems/count-primes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0204.Count%20Primes/README_EN.md) + +## 题目描述 + + + +

    统计所有小于非负整数 n 的质数的数量。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 10
    +输出:4
    +解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
    +
    + +

    示例 2:

    + +
    输入:n = 0
    +输出:0
    +
    + +

    示例 3:

    + +
    输入:n = 1
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 5 * 106
    • +
    + + +## 解法 + + + +如果 x 是质数,那么大于 x 的 x 的倍数 2x,3x,… 一定不是质数,因此我们可以从这里入手。 + +我们设 `primes[i]` 表示数 i 是不是质数,如果是质数则为 true,否则为 false。从小到大遍历每个数,如果这个数为质数,则将其所有的倍数都标记为合数(除了该质数本身),即 false,这样在运行结束的时候我们即能知道质数的个数。 + +对于一个质数 x,我们从 2x 开始标记其实是冗余的,应该直接从 x⋅x 开始标记,因为 2x,3x,… 这些数一定在 x 之前就被其他数的倍数标记过了,例如 2 的所有倍数,3 的所有倍数等。 + + + +### **Python3** + + + +```python +class Solution: + def countPrimes(self, n: int) -> int: + if n < 2: + return 0 + res = 0 + primes = [True for _ in range(n)] + for i in range(2, n): + if primes[i]: + res += 1 + for j in range(i * i, n, i): + primes[j] = False + return res +``` + +### **Java** + + + +```java +class Solution { + public int countPrimes(int n) { + if (n < 2) return 0; + boolean[] primes = new boolean[n]; + Arrays.fill(primes, true); + int res = 0; + for (int i = 2; i < n; ++i) { + if (primes[i]) { + ++res; + if ((long) i * i < n) { + for (int j = i * i; j < n; j += i) { + primes[j] = false; + } + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0205.leetcode205 Isomorphic Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0205.leetcode205 Isomorphic Strings-zh.md" new file mode 100644 index 00000000..b99c0f17 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0205.leetcode205 Isomorphic Strings-zh.md" @@ -0,0 +1,96 @@ +# [205. 同构字符串](https://leetcode-cn.com/problems/isomorphic-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0205.Isomorphic%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 和 t,判断它们是否是同构的。

    + +

    如果 中的字符可以按某种映射关系替换得到 ,那么这两个字符串是同构的。

    + +

    每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "egg", t = "add"
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:s = "foo", t = "bar"
    +输出:false
    + +

    示例 3:

    + +
    +输入:s = "paper", t = "title"
    +输出:true
    + +

     

    + +

    提示:

    + +
      +
    • 可以假设 t 长度相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + a2b, b2a = {}, {} + n = len(s) + for i in range(n): + a, b = s[i], t[i] + if (a in a2b and a2b[a] != b) or (b in b2a and b2a[b] != a): + return False + a2b[a] = b + b2a[b] = a + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isIsomorphic(String s, String t) { + int n = s.length(); + Map a2b = new HashMap<>(); + Map b2a = new HashMap<>(); + for (int i = 0; i < n; ++i) { + char a = s.charAt(i), b = t.charAt(i); + if ((a2b.containsKey(a) && a2b.get(a) != b) || (b2a.containsKey(b) && b2a.get(b) != a)) return false; + a2b.put(a, b); + b2a.put(b, a); + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0206.leetcode206 Reverse Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0206.leetcode206 Reverse Linked List-zh.md" new file mode 100644 index 00000000..93127df1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0206.leetcode206 Reverse Linked List-zh.md" @@ -0,0 +1,153 @@ +# [206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0206.Reverse%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    反转一个单链表。

    + +

    示例:

    + +
    输入: 1->2->3->4->5->NULL
    +输出: 5->4->3->2->1->NULL
    + +

    进阶:
    +你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    + + +## 解法 + +定义指针 `p`、`q` 分别指向头节点和下一个节点,`pre` 指向头节点的前一个节点。 + +遍历链表,改变指针 `p` 指向的节点的指向,将其指向 `pre` 指针指向的节点,即 `p.next = pre`。然后 `pre` 指针指向 `p`,`p`、`q` 指针往前走。 + +当遍历结束后,返回 `pre` 指针即可。 + + + +### **Python3** + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + pre, p = None, head + while p: + q = p.next + p.next = pre + pre = p + p = q + return pre +``` + +### **Java** + +迭代版本: + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + ListNode pre = null, p = head; + while (p != null) { + ListNode q = p.next; + p.next = pre; + pre = p; + p = q; + } + return pre; + } +} +``` + +递归版本: + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode res = reverseList(head.next); + head.next.next = head; + head.next = null; + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + let node = head; + let pre = null; + while (node) { + let cur = node; + node = cur.next; + cur.next = pre; + pre = cur; + } + return pre; +}; +``` + +### **Go** + +```go +func reverseList(head *ListNode) *ListNode { + if head == nil ||head.Next == nil { + return head + } + dummyHead := &ListNode{} + cur := head + for cur != nil { + tmp := cur.Next + cur.Next = dummyHead.Next + dummyHead.Next = cur + cur = tmp + } + return dummyHead.Next +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0207.leetcode207 Course Schedule-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0207.leetcode207 Course Schedule-zh.md" new file mode 100644 index 00000000..5428f80c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0207.leetcode207 Course Schedule-zh.md" @@ -0,0 +1,76 @@ +# [207. 课程表](https://leetcode-cn.com/problems/course-schedule) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0207.Course%20Schedule/README_EN.md) + +## 题目描述 + + + +

    你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1

    + +

    在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] ,表示如果要学习课程 ai必须 先学习课程  bi

    + +
      +
    • 例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1
    • +
    + +

    请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:numCourses = 2, prerequisites = [[1,0]]
    +输出:true
    +解释:总共有 2 门课程。学习课程 1 之前,你需要完成课程 0 。这是可能的。
    + +

    示例 2:

    + +
    +输入:numCourses = 2, prerequisites = [[1,0],[0,1]]
    +输出:false
    +解释:总共有 2 门课程。学习课程 1 之前,你需要先完成​课程 0 ;并且学习课程 0 之前,你还应先完成课程 1 。这是不可能的。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= numCourses <= 105
    • +
    • 0 <= prerequisites.length <= 5000
    • +
    • prerequisites[i].length == 2
    • +
    • 0 <= ai, bi < numCourses
    • +
    • prerequisites[i] 中的所有课程对 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0208.leetcode208 Implement Trie (Prefix Tree)-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0208.leetcode208 Implement Trie (Prefix Tree)-zh.md" new file mode 100644 index 00000000..82e3a9a9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0208.leetcode208 Implement Trie (Prefix Tree)-zh.md" @@ -0,0 +1,272 @@ +# [208. 实现 Trie (前缀树)](https://leetcode-cn.com/problems/implement-trie-prefix-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0208.Implement%20Trie%20%28Prefix%20Tree%29/README_EN.md) + +## 题目描述 + + + +

    Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

    + +

    请你实现 Trie 类:

    + +
      +
    • Trie() 初始化前缀树对象。
    • +
    • void insert(String word) 向前缀树中插入字符串 word
    • +
    • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false
    • +
    • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false
    • +
    + +

     

    + +

    示例:

    + +
    +输入
    +["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
    +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
    +输出
    +[null, null, true, false, true, null, true]
    +
    +解释
    +Trie trie = new Trie();
    +trie.insert("apple");
    +trie.search("apple");   // 返回 True
    +trie.search("app");     // 返回 False
    +trie.startsWith("app"); // 返回 True
    +trie.insert("app");
    +trie.search("app");     // 返回 True
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word.length, prefix.length <= 2000
    • +
    • wordprefix 仅由小写英文字母组成
    • +
    • insertsearchstartsWith 调用次数 总计 不超过 3 * 104
    • +
    + + +## 解法 + + + +前缀树每个节点包括两部分: + +1. 指向子节点的指针数组 children,对于本题而言,数组长度为 26,即小写英文字母的数量。`children[0]` 对应小写字母 a,...,`children[25]` 对应小写字母 z。 +1. 布尔字段 `isEnd`,表示该节点是否为字符串的结尾。 + +### 1. 插入字符串 + +我们从字典树的根开始,插入字符串。对于当前字符对应的子节点,有两种情况: + +- 子节点存在。沿着指针移动到子节点,继续处理下一个字符。 +- 子节点不存在。创建一个新的子节点,记录在 `children` 数组的对应位置上,然后沿着指针移动到子节点,继续搜索下一个字符。 + +重复以上步骤,直到处理字符串的最后一个字符,然后将当前节点标记为字符串的结尾。 + +### 2. 查找前缀 + +我们从字典树的根开始,查找前缀。对于当前字符对应的子节点,有两种情况: + +- 子节点存在。沿着指针移动到子节点,继续搜索下一个字符。 +- 子节点不存在。说明字典树中不包含该前缀,返回空指针。 + +重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。 + +若搜索到了前缀的末尾,就说明字典树中存在该前缀。此外,若前缀末尾对应节点的 `isEnd` 为真,则说明字典树中存在该字符串。 + + + +### **Python3** + + + +```python +class Trie: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.children = [None] * 26 + self.is_end = False + + def insert(self, word: str) -> None: + """ + Inserts a word into the trie. + """ + node = self + for c in word: + index = ord(c) - ord("a") + if node.children[index] is None: + node.children[index] = Trie() + node = node.children[index] + node.is_end = True + + def search(self, word: str) -> bool: + """ + Returns if the word is in the trie. + """ + node = self._search_prefix(word) + return node is not None and node.is_end + + def startsWith(self, prefix: str) -> bool: + """ + Returns if there is any word in the trie that starts with the given prefix. + """ + node = self._search_prefix(prefix) + return node is not None + + def _search_prefix(self, prefix: str): + node = self + for c in prefix: + index = ord(c) - ord("a") + if node.children[index] is None: + return None + node = node.children[index] + return node + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.search(word) +# param_3 = obj.startsWith(prefix) +``` + +### **Java** + + + +```java +class Trie { + private Trie[] children; + private boolean isEnd; + + /** Initialize your data structure here. */ + public Trie() { + children = new Trie[26]; + isEnd = false; + } + + /** Inserts a word into the trie. */ + public void insert(String word) { + Trie node = this; + for (int i = 0; i < word.length(); ++i) { + char c = word.charAt(i); + int index = c - 'a'; + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + node = node.children[index]; + } + node.isEnd = true; + } + + /** Returns if the word is in the trie. */ + public boolean search(String word) { + Trie node = searchPrefix(word); + return node != null && node.isEnd; + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + public boolean startsWith(String prefix) { + Trie node = searchPrefix(prefix); + return node != null; + } + + private Trie searchPrefix(String prefix) { + Trie node = this; + for (int i = 0; i < prefix.length(); ++i) { + char c = prefix.charAt(i); + int index = c - 'a'; + if (node.children[index] == null) { + return null; + } + node = node.children[index]; + } + return node; + } +} + +/** + * Your Trie object will be instantiated and called as such: + * Trie obj = new Trie(); + * obj.insert(word); + * boolean param_2 = obj.search(word); + * boolean param_3 = obj.startsWith(prefix); + */ +``` + +### **JavaScript** + +```js +/** + * Initialize your data structure here. + */ +var Trie = function() { + this.children = {}; +}; + +/** + * Inserts a word into the trie. + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function(word) { + let node = this.children; + for (let char of word) { + if (!node[char]) { + node[char] = {}; + } + node = node[char]; + } + node.isEnd = true; +}; + +/** + * Returns if the word is in the trie. + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function(word) { + let node = this.searchPrefix(word); + return node != undefined && node.isEnd != undefined; +}; + +Trie.prototype.searchPrefix = function (prefix) { + let node = this.children; + for (let char of prefix) { + if (!node[char]) return false; + node = node[char]; + } + return node; +} + +/** + * Returns if there is any word in the trie that starts with the given prefix. + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function(prefix) { + return this.searchPrefix(prefix); +}; + +/** + * Your Trie object will be instantiated and called as such: + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0209.leetcode209 Minimum Size Subarray Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0209.leetcode209 Minimum Size Subarray Sum-zh.md" new file mode 100644 index 00000000..027063a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0209.leetcode209 Minimum Size Subarray Sum-zh.md" @@ -0,0 +1,198 @@ +# [209. 长度最小的子数组](https://leetcode-cn.com/problems/minimum-size-subarray-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0209.Minimum%20Size%20Subarray%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个含有 n 个正整数的数组和一个正整数 target

    + +

    找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度如果不存在符合条件的子数组,返回 0

    + +

     

    + +

    示例 1:

    + +
    +输入:target = 7, nums = [2,3,1,2,4,3]
    +输出:2
    +解释:子数组 [4,3] 是该条件下的长度最小的子数组。
    +
    + +

    示例 2:

    + +
    +输入:target = 4, nums = [1,4,4]
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:target = 11, nums = [1,1,1,1,1,1,1,1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target <= 109
    • +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。
    • +
    + +## 解法 + + + +“前缀和 + 二分查找”,先求出数组的前缀和 `preSum`,然后根据 `preSum[i] - preSum[j] >= target` => `preSum[i] >= preSum[j] + target`,对 `preSum[i]` 进行二分查找,然后更新最小长度即可。时间复杂度 `O(n logn)`。 + +也可以用“滑动窗口”。 + +使用指针 left, right 分别表示子数组的开始位置和结束位置,维护变量 sum 表示子数组 `nums[left...right]` 元素之和。初始时 left, right 均指向 0。每一次迭代,将 `nums[right]` 加到 sum,如果此时 `sum >= target`,更新最小长度即可。然后将 sum 减去 `nums[left]`,接着 left 指针右移直至 `sum < target`。每一次迭代最后,将 right 指针右移。时间复杂度 `O(n)`。 + + + +### **Python3** + + + +“前缀和 + 二分查找”。 + +```python +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + pre_sum = [0] * (n + 1) + for i in range(1, n + 1): + pre_sum[i] = pre_sum[i - 1] + nums[i - 1] + res = n + 1 + for i in range(1, n + 1): + t = pre_sum[i - 1] + target + left, right = 0, n + while left < right: + mid = (left + right) >> 1 + if pre_sum[mid] >= t: + right = mid + else: + left = mid + 1 + if pre_sum[left] - pre_sum[i - 1] >= target: + res = min(res, left - i + 1) + return 0 if res == n + 1 else res +``` + +“滑动窗口”。 + +```python +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + left = right = 0 + sum, res = 0, n + 1 + while right < n: + sum += nums[right] + while sum >= target: + res = min(res, right - left + 1) + sum -= nums[left] + left += 1 + right += 1 + return 0 if res == n + 1 else res +``` + +### **Java** + + + +“前缀和 + 二分查找”。 + +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + int[] preSum = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + preSum[i] = preSum[i - 1] +nums[i - 1]; + } + int res = n + 1; + for (int i = 1; i <= n; ++i) { + int t = preSum[i - 1] + target; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (preSum[mid] >= t) { + right = mid; + } else { + left = mid + 1; + } + } + if (preSum[left] - preSum[i - 1] >= target) { + res = Math.min(res, left - i + 1); + } + } + return res == n + 1 ? 0 : res; + } +} +``` + +“滑动窗口”。 + +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + int left = 0, right = 0; + int sum = 0, res = n + 1; + while (right < n) { + sum += nums[right]; + while (sum >= target) { + res = Math.min(res, right - left + 1); + sum -= nums[left++]; + } + ++right; + } + return res == n + 1 ? 0 : res; + } +} +``` + +### **C#** + +```cs +public class Solution { + public int MinSubArrayLen(int target, int[] nums) { + int n = nums.Length; + int left = 0, right = 0; + int sum = 0, res = n + 1; + while (right < n) + { + sum += nums[right]; + while (sum >= target) + { + res = Math.Min(res, right - left + 1); + sum -= nums[left++]; + } + ++right; + } + return res == n + 1 ? 0 : res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0210.leetcode210 Course Schedule II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0210.leetcode210 Course Schedule II-zh.md" new file mode 100644 index 00000000..162caf03 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0210.leetcode210 Course Schedule II-zh.md" @@ -0,0 +1,77 @@ +# [210. 课程表 II](https://leetcode-cn.com/problems/course-schedule-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0210.Course%20Schedule%20II/README_EN.md) + +## 题目描述 + + + +

    现在你总共有 n 门课需要选,记为 0 到 n-1

    + +

    在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]

    + +

    给定课程总量以及它们的先决条件,返回你为了学完所有课程所安排的学习顺序。

    + +

    可能会有多个正确的顺序,你只要返回一种就可以了。如果不可能完成所有课程,返回一个空数组。

    + +

    示例 1:

    + +
    输入: 2, [[1,0]] 
    +输出: [0,1]
    +解释: 总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。
    + +

    示例 2:

    + +
    输入: 4, [[1,0],[2,0],[3,1],[3,2]]
    +输出: [0,1,2,3] or [0,2,1,3]
    +解释: 总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。
    +     因此,一个正确的课程顺序是 [0,1,2,3] 。另一个正确的排序是 [0,2,1,3] 。
    +
    + +

    说明:

    + +
      +
    1. 输入的先决条件是由边缘列表表示的图形,而不是邻接矩阵。详情请参见图的表示法
    2. +
    3. 你可以假定输入的先决条件中没有重复的边。
    4. +
    + +

    提示:

    + +
      +
    1. 这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。
    2. +
    3. 通过 DFS 进行拓扑排序 - 一个关于Coursera的精彩视频教程(21分钟),介绍拓扑排序的基本概念。
    4. +
    5. +

      拓扑排序也可以通过 BFS 完成。

      +
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0211.leetcode211 Design Add and Search Words Data Structure-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0211.leetcode211 Design Add and Search Words Data Structure-zh.md" new file mode 100644 index 00000000..30b1e8aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0211.leetcode211 Design Add and Search Words Data Structure-zh.md" @@ -0,0 +1,186 @@ +# [211. 添加与搜索单词 - 数据结构设计](https://leetcode-cn.com/problems/design-add-and-search-words-data-structure) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0211.Design%20Add%20and%20Search%20Words%20Data%20Structure/README_EN.md) + +## 题目描述 + + + +

    请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

    + +

    实现词典类 WordDictionary

    + +
      +
    • WordDictionary() 初始化词典对象
    • +
    • void addWord(word)word 添加到数据结构中,之后可以对它进行匹配
    • +
    • bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回  falseword 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
    +[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
    +输出:
    +[null,null,null,null,false,true,true,true]
    +
    +解释:
    +WordDictionary wordDictionary = new WordDictionary();
    +wordDictionary.addWord("bad");
    +wordDictionary.addWord("dad");
    +wordDictionary.addWord("mad");
    +wordDictionary.search("pad"); // return False
    +wordDictionary.search("bad"); // return True
    +wordDictionary.search(".ad"); // return True
    +wordDictionary.search("b.."); // return True
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word.length <= 500
    • +
    • addWord 中的 word 由小写英文字母组成
    • +
    • search 中的 word 由 '.' 或小写英文字母组成
    • +
    • 最多调用 50000addWordsearch
    • +
    + +## 解法 + + + +“前缀树”实现。 + + + +### **Python3** + + + +```python +class Trie: + + def __init__(self): + self.children = [None] * 26 + self.is_end = False + + +class WordDictionary: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.trie = Trie() + + def addWord(self, word: str) -> None: + node = self.trie + for c in word: + index = ord(c) - ord('a') + if node.children[index] is None: + node.children[index] = Trie() + node = node.children[index] + node.is_end = True + + def search(self, word: str) -> bool: + return self._search(word, self.trie) + + def _search(self, word: str, node: Trie) -> bool: + for i in range(len(word)): + c = word[i] + index = ord(c) - ord('a') + if c != '.' and node.children[index] is None: + return False + if c == '.': + for j in range(26): + if node.children[j] is not None and self._search(word[i + 1:], node.children[j]): + return True + return False + node = node.children[index] + return node.is_end + +# Your WordDictionary object will be instantiated and called as such: +# obj = WordDictionary() +# obj.addWord(word) +# param_2 = obj.search(word) +``` + +### **Java** + + + +```java +class WordDictionary { + class Trie { + Trie[] children; + boolean isEnd; + Trie() { + children = new Trie[26]; + isEnd = false; + } + } + + private Trie trie; + + /** Initialize your data structure here. */ + public WordDictionary() { + trie = new Trie(); + } + + public void addWord(String word) { + Trie node = trie; + for (int i = 0; i < word.length(); ++i) { + char c = word.charAt(i); + int index = c - 'a'; + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + node = node.children[index]; + } + node.isEnd = true; + } + + public boolean search(String word) { + return search(word, trie); + } + + private boolean search(String word, Trie node) { + for (int i = 0; i < word.length(); ++i) { + char c = word.charAt(i); + int index = c - 'a'; + if (c != '.' && node.children[index] == null) { + return false; + } + if (c == '.') { + for (int j = 0; j < 26; ++j) { + if (node.children[j] != null && search(word.substring(i + 1), node.children[j])) { + return true; + } + } + return false; + } + node = node.children[index]; + } + return node.isEnd; + } +} + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary obj = new WordDictionary(); + * obj.addWord(word); + * boolean param_2 = obj.search(word); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0212.leetcode212 Word Search II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0212.leetcode212 Word Search II-zh.md" new file mode 100644 index 00000000..eb51f8df --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0212.leetcode212 Word Search II-zh.md" @@ -0,0 +1,73 @@ +# [212. 单词搜索 II](https://leetcode-cn.com/problems/word-search-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0212.Word%20Search%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。

    + +

    单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

    + +

     

    + +

    示例 1:

    + +
    +输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
    +输出:["eat","oath"]
    +
    + +

    示例 2:

    + +
    +输入:board = [["a","b"],["c","d"]], words = ["abcb"]
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == board.length
    • +
    • n == board[i].length
    • +
    • 1 <= m, n <= 12
    • +
    • board[i][j] 是一个小写英文字母
    • +
    • 1 <= words.length <= 3 * 104
    • +
    • 1 <= words[i].length <= 10
    • +
    • words[i] 由小写英文字母组成
    • +
    • words 中的所有字符串互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0213.leetcode213 House Robber II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0213.leetcode213 House Robber II-zh.md" new file mode 100644 index 00000000..242af2f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0213.leetcode213 House Robber II-zh.md" @@ -0,0 +1,163 @@ +# [213. 打家劫舍 II](https://leetcode-cn.com/problems/house-robber-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0213.House%20Robber%20II/README_EN.md) + +## 题目描述 + + + +

    你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

    + +

    给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,3,2]
    +输出:3
    +解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,1]
    +输出:4
    +解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
    +     偷窃到的最高金额 = 1 + 3 = 4 。
    + +

    示例 3:

    + +
    +输入:nums = [0]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 1000
    • +
    + + +## 解法 + + + +环状排列意味着第一个房屋和最后一个房屋中最多只能选择一个偷窃,因此可以把此环状排列房间问题约化为两个单排排列房屋子问题。 + + + +### **Python3** + + + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + def robRange(nums, l, r): + a, b = 0, nums[l] + for num in nums[l + 1: r + 1]: + a, b = b, max(num + a, b) + return b + + n = len(nums) + if n == 1: + return nums[0] + s1, s2 = robRange(nums, 0, n - 2), robRange(nums, 1, n - 1) + return max(s1, s2) +``` + +### **Java** + + + +```java +class Solution { + public int rob(int[] nums) { + int n = nums.length; + if (n == 1) { + return nums[0]; + } + int s1 = robRange(nums, 0, n - 2); + int s2 = robRange(nums, 1, n - 1); + return Math.max(s1, s2); + } + + private int robRange(int[] nums, int l, int r) { + int a = 0, b = nums[l]; + for (int i = l + 1; i <= r; ++i) { + int c = Math.max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + if (n == 1) return nums[0]; + int s1 = robRange(nums, 0, n - 2); + int s2 = robRange(nums, 1, n - 1); + return max(s1, s2); + } + + int robRange(vector& nums, int l, int r) { + int a = 0, b = nums[l]; + for (int i = l + 1; i <= r; ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **Go** + +```go +func rob(nums []int) int { + n := len(nums) + if n == 1 { + return nums[0] + } + s1, s2 := robRange(nums, 0, n-2), robRange(nums, 1, n-1) + return max(s1, s2) +} + +func robRange(nums []int, l, r int) int { + a, b := 0, nums[l] + for i := l + 1; i <= r; i++ { + a, b = b, max(nums[i]+a, b) + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0214.leetcode214 Shortest Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0214.leetcode214 Shortest Palindrome-zh.md" new file mode 100644 index 00000000..95823a38 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0214.leetcode214 Shortest Palindrome-zh.md" @@ -0,0 +1,65 @@ +# [214. 最短回文串](https://leetcode-cn.com/problems/shortest-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0214.Shortest%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aacecaaa"
    +输出:"aaacecaaa"
    +
    + +

    示例 2:

    + +
    +输入:s = "abcd"
    +输出:"dcbabcd"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 5 * 104
    • +
    • s 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0215.leetcode215 Kth Largest Element in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0215.leetcode215 Kth Largest Element in an Array-zh.md" new file mode 100644 index 00000000..9bab8c9d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0215.leetcode215 Kth Largest Element in an Array-zh.md" @@ -0,0 +1,176 @@ +# [215. 数组中的第K个最大元素](https://leetcode-cn.com/problems/kth-largest-element-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0215.Kth%20Largest%20Element%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

    + +

    示例 1:

    + +
    输入: [3,2,1,5,6,4] 和 k = 2
    +输出: 5
    +
    + +

    示例 2:

    + +
    输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
    +输出: 4
    + +

    说明:

    + +

    你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

    + + +## 解法 + + + +快速排序 partition 实现。 + + + +### **Python3** + + + +```python +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + def quickSort(nums, left, right, k): + if left == right: + return nums[left] + i, j = left - 1, right + 1 + x = nums[(left + right) >> 1] + while i < j: + while 1: + i += 1 + if nums[i] >= x: + break + while 1: + j -= 1 + if nums[j] <= x: + break + if i < j: + nums[i], nums[j] = nums[j], nums[i] + if j < k: + return quickSort(nums, j + 1, right, k) + return quickSort(nums, left, j, k) + + n = len(nums) + return quickSort(nums, 0, n - 1, n - k) +``` + +### **Java** + + + +```java +class Solution { + public int findKthLargest(int[] nums, int k) { + int n = nums.length; + return quickSort(nums, 0, n - 1, n - k); + } + + private int quickSort(int[] nums, int left, int right, int k) { + if (left == right) { + return nums[left]; + } + int i = left - 1, j = right + 1; + int x = nums[(left + right) >>> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + if (j < k) { + return quickSort(nums, j + 1, right, k); + } + return quickSort(nums, left, j, k); + + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int n = nums.size(); + return quickSort(nums, 0, n - 1, n - k); + } + + int quickSort(vector& nums, int left, int right, int k) { + if (left == right) { + return nums[left]; + } + int i = left - 1, j = right + 1; + int x = nums[left + right >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + swap(nums[i], nums[j]); + } + } + if (j < k) { + return quickSort(nums, j + 1, right, k); + } + return quickSort(nums, left, j, k); + } +}; +``` + +### **Go** + +```go +func findKthLargest(nums []int, k int) int { + n := len(nums) + return quickSort(nums, 0, n-1, n-k) +} + +func quickSort(nums []int, left, right, k int) int { + if left == right { + return nums[left] + } + i, j := left-1, right+1 + x := nums[(left+right)>>1] + for i < j { + for { + i++ + if nums[i] >= x { + break + } + } + for { + j-- + if nums[j] <= x { + break + } + } + if i < j { + nums[i], nums[j] = nums[j], nums[i] + } + } + if j < k { + return quickSort(nums, j+1, right, k) + } + return quickSort(nums, left, j, k) +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0216.leetcode216 Combination Sum III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0216.leetcode216 Combination Sum III-zh.md" new file mode 100644 index 00000000..b197b0be --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0216.leetcode216 Combination Sum III-zh.md" @@ -0,0 +1,59 @@ +# [216. 组合总和 III](https://leetcode-cn.com/problems/combination-sum-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0216.Combination%20Sum%20III/README_EN.md) + +## 题目描述 + + + +

    找出所有相加之和为 n 的 个数的组合组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

    + +

    说明:

    + +
      +
    • 所有数字都是正整数。
    • +
    • 解集不能包含重复的组合。 
    • +
    + +

    示例 1:

    + +
    输入: k = 3, n = 7
    +输出: [[1,2,4]]
    +
    + +

    示例 2:

    + +
    输入: k = 3, n = 9
    +输出: [[1,2,6], [1,3,5], [2,3,4]]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0217.leetcode217 Contains Duplicate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0217.leetcode217 Contains Duplicate-zh.md" new file mode 100644 index 00000000..ad284430 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0217.leetcode217 Contains Duplicate-zh.md" @@ -0,0 +1,82 @@ +# [217. 存在重复元素](https://leetcode-cn.com/problems/contains-duplicate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0217.Contains%20Duplicate/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组,判断是否存在重复元素。

    + +

    如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入: [1,2,3,1]
    +输出: true
    + +

    示例 2:

    + +
    +输入: [1,2,3,4]
    +输出: false
    + +

    示例 3:

    + +
    +输入: [1,1,1,3,3,4,3,2,4,2]
    +输出: true
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) +``` + +### **Java** + + + +```java +class Solution { + public boolean containsDuplicate(int[] nums) { + Set set = new HashSet<>(); + for (int e : nums) { + if (set.contains(e)) return true; + set.add(e); + } + return false; + } +} +``` + +### **TypeScript** + +```ts +function containsDuplicate(nums: number[]): boolean { + let unique: Set = new Set(nums); + return unique.size != nums.length; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0218.leetcode218 The Skyline Problem-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0218.leetcode218 The Skyline Problem-zh.md" new file mode 100644 index 00000000..4c31512b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0218.leetcode218 The Skyline Problem-zh.md" @@ -0,0 +1,81 @@ +# [218. 天际线问题](https://leetcode-cn.com/problems/the-skyline-problem) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0218.The%20Skyline%20Problem/README_EN.md) + +## 题目描述 + + + +

    城市的天际线是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。给你所有建筑物的位置和高度,请返回由这些建筑物形成的 天际线

    + +

    每个建筑物的几何信息由数组 buildings 表示,其中三元组 buildings[i] = [lefti, righti, heighti] 表示:

    + +
      +
    • lefti 是第 i 座建筑物左边缘的 x 坐标。
    • +
    • righti 是第 i 座建筑物右边缘的 x 坐标。
    • +
    • heighti 是第 i 座建筑物的高度。
    • +
    + +

    天际线 应该表示为由 “关键点” 组成的列表,格式 [[x1,y1],[x2,y2],...] ,并按 x 坐标 进行 排序关键点是水平线段的左端点。列表中最后一个点是最右侧建筑物的终点,y 坐标始终为 0 ,仅用于标记天际线的终点。此外,任何两个相邻建筑物之间的地面都应被视为天际线轮廓的一部分。

    + +

    注意:输出天际线中不得有连续的相同高度的水平线。例如 [...[2 3], [4 5], [7 5], [11 5], [12 7]...] 是不正确的答案;三条高度为 5 的线应该在最终输出中合并为一个:[...[2 3], [4 5], [12 7], ...]

    + +

     

    + +

    示例 1:

    + +
    +输入:buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
    +输出:[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
    +解释:
    +图 A 显示输入的所有建筑物的位置和高度,
    +图 B 显示由这些建筑物形成的天际线。图 B 中的红点表示输出列表中的关键点。
    + +

    示例 2:

    + +
    +输入:buildings = [[0,2,3],[2,5,3]]
    +输出:[[0,3],[5,0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= buildings.length <= 104
    • +
    • 0 <= lefti < righti <= 231 - 1
    • +
    • 1 <= heighti <= 231 - 1
    • +
    • buildingslefti 非递减排序
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0219.leetcode219 Contains Duplicate II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0219.leetcode219 Contains Duplicate II-zh.md" new file mode 100644 index 00000000..f7b4d497 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0219.leetcode219 Contains Duplicate II-zh.md" @@ -0,0 +1,78 @@ +# [219. 存在重复元素 II](https://leetcode-cn.com/problems/contains-duplicate-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0219.Contains%20Duplicate%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 ij 的差的 绝对值 至多为 k

    + +

     

    + +

    示例 1:

    + +
    输入: nums = [1,2,3,1], k = 3
    +输出: true
    + +

    示例 2:

    + +
    输入: nums = [1,0,1,1], k = 1
    +输出: true
    + +

    示例 3:

    + +
    输入: nums = [1,2,3,1,2,3], k = 2
    +输出: false
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: + helper = {} + for i, v in enumerate(nums): + if v in helper and i - helper[v] <= k: + return True + helper[v] = i + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean containsNearbyDuplicate(int[] nums, int k) { + Map helper = new HashMap<>(); + for (int i = 0, n = nums.length; i < n; ++i) { + if (helper.containsKey(nums[i])) { + int j = helper.get(nums[i]); + if (i - j <= k) { + return true; + } + } + helper.put(nums[i], i); + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0220.leetcode220 Contains Duplicate III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0220.leetcode220 Contains Duplicate III-zh.md" new file mode 100644 index 00000000..c25fdca1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0220.leetcode220 Contains Duplicate III-zh.md" @@ -0,0 +1,73 @@ +# [220. 存在重复元素 III](https://leetcode-cn.com/problems/contains-duplicate-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0220.Contains%20Duplicate%20III/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和两个整数 kt 。请你判断是否存在 两个不同下标 ij,使得 abs(nums[i] - nums[j]) <= t ,同时又满足 abs(i - j) <= k

    + +

    如果存在则返回 true,不存在返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,1], k = 3, t = 0
    +输出:true
    + +

    示例 2:

    + +
    +输入:nums = [1,0,1,1], k = 1, t = 2
    +输出:true
    + +

    示例 3:

    + +
    +输入:nums = [1,5,9,1,5,9], k = 2, t = 3
    +输出:false
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 2 * 104
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • 0 <= k <= 104
    • +
    • 0 <= t <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0221.leetcode221 Maximal Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0221.leetcode221 Maximal Square-zh.md" new file mode 100644 index 00000000..07ba5683 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0221.leetcode221 Maximal Square-zh.md" @@ -0,0 +1,74 @@ +# [221. 最大正方形](https://leetcode-cn.com/problems/maximal-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0221.Maximal%20Square/README_EN.md) + +## 题目描述 + + + +

    在一个由 '0''1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
    +输出:4
    +
    + +

    示例 2:

    + +
    +输入:matrix = [["0","1"],["1","0"]]
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:matrix = [["0"]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 300
    • +
    • matrix[i][j]'0''1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0222.leetcode222 Count Complete Tree Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0222.leetcode222 Count Complete Tree Nodes-zh.md" new file mode 100644 index 00000000..7cd431b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0222.leetcode222 Count Complete Tree Nodes-zh.md" @@ -0,0 +1,252 @@ +# [222. 完全二叉树的节点个数](https://leetcode-cn.com/problems/count-complete-tree-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0222.Count%20Complete%20Tree%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

    + +

    完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2,3,4,5,6]
    +输出:6
    +
    + +

    示例 2:

    + +
    +输入:root = []
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:root = [1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目范围是[0, 5 * 104]
    • +
    • 0 <= Node.val <= 5 * 104
    • +
    • 题目数据保证输入的树是 完全二叉树
    • +
    + +

     

    + +

    进阶:遍历树来统计节点是一种时间复杂度为 O(n) 的简单解决方案。你可以设计一个更快的算法吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countNodes(self, root: TreeNode) -> int: + def depth(root): + res = 0 + while root: + res += 1 + root = root.left + return res + + if root is None: + return 0 + left_depth = depth(root.left) + right_depth = depth(root.right) + if left_depth > right_depth: + return (1 << right_depth) + self.countNodes(root.left) + return (1 << left_depth) + self.countNodes(root.right) +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int countNodes(TreeNode root) { + if (root == null) { + return 0; + } + int leftDepth = depth(root.left); + int rightDepth = depth(root.right); + if (leftDepth > rightDepth) { + return (1 << rightDepth) + countNodes(root.left); + } + return (1 << leftDepth) + countNodes(root.right); + } + + private int depth(TreeNode root) { + int res = 0; + while (root != null) { + ++res; + root = root.left; + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int countNodes(TreeNode* root) { + if (!root) { + return 0; + } + int leftDepth = depth(root->left); + int rightDepth = depth(root->right); + if (leftDepth > rightDepth) { + return (1 << rightDepth) + countNodes(root->left); + } + return (1 << leftDepth) + countNodes(root->right); + } + +private: + int depth(TreeNode* root) { + int res = 0; + while (root) { + ++res; + root = root->left; + } + return res; + } +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func countNodes(root *TreeNode) int { + if root == nil { + return 0 + } + leftDepth := depth(root.Left) + rightDepth := depth(root.Right) + if leftDepth > rightDepth { + return (1 << rightDepth) + countNodes(root.Left) + } + return (1 << leftDepth) + countNodes(root.Right) +} + +func depth(root *TreeNode) int { + res := 0 + for root != nil { + res++ + root = root.Left + } + return res +} +``` + +### **C#** + +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int CountNodes(TreeNode root) { + if (root == null) + { + return 0; + } + int leftDepth = depth(root.left); + int rightDepth = depth(root.right); + if (leftDepth > rightDepth) + { + return (1 << rightDepth) + CountNodes(root.left); + } + return (1 << leftDepth) + CountNodes(root.right); + } + + private int depth(TreeNode root) { + int res = 0; + while (root != null) + { + ++res; + root = root.left; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0223.leetcode223 Rectangle Area-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0223.leetcode223 Rectangle Area-zh.md" new file mode 100644 index 00000000..a8598d85 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0223.leetcode223 Rectangle Area-zh.md" @@ -0,0 +1,51 @@ +# [223. 矩形面积](https://leetcode-cn.com/problems/rectangle-area) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0223.Rectangle%20Area/README_EN.md) + +## 题目描述 + + + +

    二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。

    + +

    每个矩形由其左下顶点和右上顶点坐标表示,如图所示。

    + +

    Rectangle Area

    + +

    示例:

    + +
    输入: -3, 0, 3, 4, 0, -1, 9, 2
    +输出: 45
    + +

    说明: 假设矩形面积不会超出 int 的范围。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0224.leetcode224 Basic Calculator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0224.leetcode224 Basic Calculator-zh.md" new file mode 100644 index 00000000..63da6784 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0224.leetcode224 Basic Calculator-zh.md" @@ -0,0 +1,73 @@ +# [224. 基本计算器](https://leetcode-cn.com/problems/basic-calculator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0224.Basic%20Calculator/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "1 + 1"
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:s = " 2-1 + 2 "
    +输出:3
    +
    + +

    示例 3:

    + +
    +输入:s = "(1+(4+5+2)-3)+(6+8)"
    +输出:23
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 3 * 105
    • +
    • s 由数字、'+''-''('')'、和 ' ' 组成
    • +
    • s 表示一个有效的表达式
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0225.leetcode225 Implement Stack using Queues-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0225.leetcode225 Implement Stack using Queues-zh.md" new file mode 100644 index 00000000..4e22da82 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0225.leetcode225 Implement Stack using Queues-zh.md" @@ -0,0 +1,179 @@ +# [225. 用队列实现栈](https://leetcode-cn.com/problems/implement-stack-using-queues) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0225.Implement%20Stack%20using%20Queues/README_EN.md) + +## 题目描述 + + + +

    请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(pushtoppopempty)。

    + +

    实现 MyStack 类:

    + +
      +
    • void push(int x) 将元素 x 压入栈顶。
    • +
    • int pop() 移除并返回栈顶元素。
    • +
    • int top() 返回栈顶元素。
    • +
    • boolean empty() 如果栈是空的,返回 true ;否则,返回 false
    • +
    + +

     

    + +

    注意:

    + +
      +
    • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsize 和 is empty 这些操作。
    • +
    • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["MyStack", "push", "push", "top", "pop", "empty"]
    +[[], [1], [2], [], [], []]
    +输出:
    +[null, null, null, 2, 2, false]
    +
    +解释:
    +MyStack myStack = new MyStack();
    +myStack.push(1);
    +myStack.push(2);
    +myStack.top(); // 返回 2
    +myStack.pop(); // 返回 2
    +myStack.empty(); // 返回 False
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= x <= 9
    • +
    • 最多调用100pushpoptopempty
    • +
    • 每次调用 poptop 都保证栈不为空
    • +
    + +

     

    + +

    进阶:你能否实现每种操作的均摊时间复杂度为 O(1) 的栈?换句话说,执行 n 个操作的总时间复杂度 O(n) ,尽管其中某个操作可能需要比其他操作更长的时间。你可以使用两个以上的队列。

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class MyStack: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.q = [] + + + def push(self, x: int) -> None: + """ + Push element x onto stack. + """ + self.q.append(x) + n = len(self.q) + for i in range(1, n): + self.q.append(self.q.pop(0)) + + + def pop(self) -> int: + """ + Removes the element on top of the stack and returns that element. + """ + return self.q.pop(0) + + + def top(self) -> int: + """ + Get the top element. + """ + return self.q[0] + + + def empty(self) -> bool: + """ + Returns whether the stack is empty. + """ + return len(self.q) == 0 + + + +# Your MyStack object will be instantiated and called as such: +# obj = MyStack() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.top() +# param_4 = obj.empty() +``` + +### **Java** + + + +```java +class MyStack { + + private Deque q; + + /** Initialize your data structure here. */ + public MyStack() { + q = new ArrayDeque<>(); + } + + /** Push element x onto stack. */ + public void push(int x) { + q.offerLast(x); + int n = q.size(); + while (n-- > 1) { + q.offerLast(q.pollFirst()); + } + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + return q.pollFirst(); + } + + /** Get the top element. */ + public int top() { + return q.peekFirst(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return q.isEmpty(); + } +} + +/** + * Your MyStack object will be instantiated and called as such: + * MyStack obj = new MyStack(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.top(); + * boolean param_4 = obj.empty(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0226.leetcode226 Invert Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0226.leetcode226 Invert Binary Tree-zh.md" new file mode 100644 index 00000000..3c706755 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0226.leetcode226 Invert Binary Tree-zh.md" @@ -0,0 +1,141 @@ +# [226. 翻转二叉树](https://leetcode-cn.com/problems/invert-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0226.Invert%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    翻转一棵二叉树。

    + +

    示例:

    + +

    输入:

    + +
         4
    +   /   \
    +  2     7
    + / \   / \
    +1   3 6   9
    + +

    输出:

    + +
         4
    +   /   \
    +  7     2
    + / \   / \
    +9   6 3   1
    + +

    备注:
    +这个问题是受到 Max Howell 原问题 启发的 :

    + +
    谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if root is None: + return None + root.left, root.right = root.right, root.left + self.invertTree(root.left) + self.invertTree(root.right) + return root +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) return null; + TreeNode t = root.left; + root.left = root.right; + root.right = t; + invertTree(root.left); + invertTree(root.right); + return root; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = function (root) { + if (!root) return null; + [root.left, root.right] = [root.right, root.left]; + invertTree(root.left); + invertTree(root.right); + return root; +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func invertTree(root *TreeNode) *TreeNode { + if (root == nil) { + return nil + } + root.Left, root.Right = root.Right, root.Left + invertTree(root.Left) + invertTree(root.Right) + return root +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0227.leetcode227 Basic Calculator II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0227.leetcode227 Basic Calculator II-zh.md" new file mode 100644 index 00000000..0ce855ea --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0227.leetcode227 Basic Calculator II-zh.md" @@ -0,0 +1,144 @@ +# [227. 基本计算器 II](https://leetcode-cn.com/problems/basic-calculator-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0227.Basic%20Calculator%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

    + +

    整数除法仅保留整数部分。

    + +
    +
    +

     

    + +

    示例 1:

    + +
    +输入:s = "3+2*2"
    +输出:7
    +
    + +

    示例 2:

    + +
    +输入:s = " 3/2 "
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:s = " 3+5 / 2 "
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 3 * 105
    • +
    • s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开
    • +
    • s 表示一个 有效表达式
    • +
    • 表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1]
    • +
    • 题目数据保证答案是一个 32-bit 整数
    • +
    +
    +
    + + +## 解法 + + + +遍历字符串 s,并用变量 `preSign` 记录每个数字之前的运算符,对于第一个数字,其之前的运算符视为加号。每次遍历到数字末尾时,根据 `preSign` 来决定计算方式: + +- 加号:将数字压入栈; +- 减号:将数字的相反数压入栈; +- 乘除号:计算数字与栈顶元素,并将栈顶元素替换为计算结果。 + + + +### **Python3** + + + +```python +class Solution: + def calculate(self, s: str) -> int: + num, n = 0, len(s) + pre_sign = '+' + stack = [] + for i in range(n): + if s[i].isdigit(): + num = num * 10 + int(s[i]) + if i == n - 1 or (not s[i].isdigit() and s[i] != ' '): + if pre_sign == '+': + stack.append(num) + elif pre_sign == '-': + stack.append(-num) + elif pre_sign == '*': + stack.append(stack.pop() * num) + else: + stack.append(int(stack.pop() / num)) + pre_sign = s[i] + num = 0 + res = 0 + while stack: + res += stack.pop() + return res +``` + +### **Java** + + + +```java +class Solution { + public int calculate(String s) { + int num = 0; + char preSign = '+'; + Deque stack = new ArrayDeque<>(); + for (int i = 0, n = s.length(); i < n; ++i) { + if (Character.isDigit(s.charAt(i))) { + num = num * 10 + (s.charAt(i) - '0'); + } + if (i == n - 1 || (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ')) { + switch (preSign) { + case '+': + stack.push(num); + break; + case '-': + stack.push(-num); + break; + case '*': + stack.push(stack.pop() * num); + break; + case '/': + stack.push(stack.pop() / num); + break; + } + preSign = s.charAt(i); + num = 0; + } + } + + int res = 0; + while (!stack.isEmpty()) { + res += stack.pop(); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0228.leetcode228 Summary Ranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0228.leetcode228 Summary Ranges-zh.md" new file mode 100644 index 00000000..5c0f1213 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0228.leetcode228 Summary Ranges-zh.md" @@ -0,0 +1,106 @@ +# [228. 汇总区间](https://leetcode-cn.com/problems/summary-ranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0228.Summary%20Ranges/README_EN.md) + +## 题目描述 + + + +

    给定一个无重复元素的有序整数数组 nums

    + +

    返回 恰好覆盖数组中所有数字最小有序 区间范围列表。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x

    + +

    列表中的每个区间范围 [a,b] 应该按如下格式输出:

    + +
      +
    • "a->b" ,如果 a != b
    • +
    • "a" ,如果 a == b
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [0,1,2,4,5,7]
    +输出:["0->2","4->5","7"]
    +解释:区间范围是:
    +[0,2] --> "0->2"
    +[4,5] --> "4->5"
    +[7,7] --> "7"
    +
    + +

    示例 2:

    + +
    +输入:nums = [0,2,3,4,6,8,9]
    +输出:["0","2->4","6","8->9"]
    +解释:区间范围是:
    +[0,0] --> "0"
    +[2,4] --> "2->4"
    +[6,6] --> "6"
    +[8,9] --> "8->9"
    +
    + +

    示例 3:

    + +
    +输入:nums = []
    +输出:[]
    +
    + +

    示例 4:

    + +
    +输入:nums = [-1]
    +输出:["-1"]
    +
    + +

    示例 5:

    + +
    +输入:nums = [0]
    +输出:["0"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 20
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • nums 中的所有值都 互不相同
    • +
    • nums 按升序排列
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0229.leetcode229 Majority Element II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0229.leetcode229 Majority Element II-zh.md" new file mode 100644 index 00000000..542031d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0229.leetcode229 Majority Element II-zh.md" @@ -0,0 +1,72 @@ +# [229. 求众数 II](https://leetcode-cn.com/problems/majority-element-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0229.Majority%20Element%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个大小为 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

    + +

    进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

    + +

     

    + +

    示例 1:

    + +
    +输入:[3,2,3]
    +输出:[3]
    + +

    示例 2:

    + +
    +输入:nums = [1]
    +输出:[1]
    +
    + +

    示例 3:

    + +
    +输入:[1,1,1,3,3,2,2,2]
    +输出:[1,2]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • -109 <= nums[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0230.leetcode230 Kth Smallest Element in a BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0230.leetcode230 Kth Smallest Element in a BST-zh.md" new file mode 100644 index 00000000..0836ab16 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0230.leetcode230 Kth Smallest Element in a BST-zh.md" @@ -0,0 +1,127 @@ +# [230. 二叉搜索树中第K小的元素](https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,1,4,null,2], k = 1
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:root = [5,3,6,2,4,null,null,1], k = 3
    +输出:3
    +
    + +

     

    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数为 n
    • +
    • 1 <= k <= n <= 104
    • +
    • 0 <= Node.val <= 104
    • +
    + +

     

    + +

    进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthSmallest(self, root: TreeNode, k: int) -> int: + def inorder(root): + if root is None: + return + inorder(root.left) + self.k -= 1 + if self.k == 0: + self.res = root.val + return + inorder(root.right) + self.k = k + inorder(root) + return self.res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int k; + private int res; + + public int kthSmallest(TreeNode root, int k) { + this.k = k; + inorder(root); + return res; + } + + private void inorder(TreeNode root) { + if (root == null) { + return; + } + inorder(root.left); + if (--k == 0) { + res = root.val; + return; + } + inorder(root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0231.leetcode231 Power of Two-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0231.leetcode231 Power of Two-zh.md" new file mode 100644 index 00000000..705dc7f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0231.leetcode231 Power of Two-zh.md" @@ -0,0 +1,101 @@ +# [231. 2 的幂](https://leetcode-cn.com/problems/power-of-two) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0231.Power%20of%20Two/README_EN.md) + +## 题目描述 + + + +

    给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

    + +

    示例 1:

    + +
    输入: 1
    +输出: true
    +解释: 20 = 1
    + +

    示例 2:

    + +
    输入: 16
    +输出: true
    +解释: 24 = 16
    + +

    示例 3:

    + +
    输入: 218
    +输出: false
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 +``` + +### **Java** + + + +```java +class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function(n) { + return n > 0 && (n & (n - 1)) == 0; +}; +``` + +### **Go** + +```go +func isPowerOfTwo(n int) bool { + return n > 0 && (n & (n - 1)) == 0 +} +``` + +### **TypeScript** + +```ts +function isPowerOfTwo(n: number): boolean { + return n > 0 && (n & (n - 1)) == 0; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0232.leetcode232 Implement Queue using Stacks-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0232.leetcode232 Implement Queue using Stacks-zh.md" new file mode 100644 index 00000000..04696524 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0232.leetcode232 Implement Queue using Stacks-zh.md" @@ -0,0 +1,201 @@ +# [232. 用栈实现队列](https://leetcode-cn.com/problems/implement-queue-using-stacks) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0232.Implement%20Queue%20using%20Stacks/README_EN.md) + +## 题目描述 + + + +

    请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

    + +

    实现 MyQueue 类:

    + +
      +
    • void push(int x) 将元素 x 推到队列的末尾
    • +
    • int pop() 从队列的开头移除并返回元素
    • +
    • int peek() 返回队列开头的元素
    • +
    • boolean empty() 如果队列为空,返回 true ;否则,返回 false
    • +
    + +

     

    + +

    说明:

    + +
      +
    • 你只能使用标准的栈操作 —— 也就是只有 push to toppeek/pop from topsize, 和 is empty 操作是合法的。
    • +
    • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["MyQueue", "push", "push", "peek", "pop", "empty"]
    +[[], [1], [2], [], [], []]
    +输出:
    +[null, null, null, 1, 1, false]
    +
    +解释:
    +MyQueue myQueue = new MyQueue();
    +myQueue.push(1); // queue is: [1]
    +myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
    +myQueue.peek(); // return 1
    +myQueue.pop(); // return 1, queue is [2]
    +myQueue.empty(); // return false
    +
    + +
      +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= x <= 9
    • +
    • 最多调用 100pushpoppeekempty
    • +
    • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class MyQueue: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.s1 = [] + self.s2 = [] + + + def push(self, x: int) -> None: + """ + Push element x to the back of queue. + """ + self.s1.append(x) + + + def pop(self) -> int: + """ + Removes the element from in front of queue and returns that element. + """ + self._move() + return self.s2.pop() + + def peek(self) -> int: + """ + Get the front element. + """ + self._move() + return self.s2[-1] + + + def empty(self) -> bool: + """ + Returns whether the queue is empty. + """ + return len(self.s1) + len(self.s2) == 0 + + + def _move(self): + """ + Move elements from s1 to s2. + """ + if len(self.s2) == 0: + while len(self.s1) > 0: + self.s2.append(self.s1.pop()) + + +# Your MyQueue object will be instantiated and called as such: +# obj = MyQueue() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.peek() +# param_4 = obj.empty() +``` + +### **Java** + + + +```java +class MyQueue { + + private Deque s1 = new ArrayDeque<>(); + private Deque s2 = new ArrayDeque<>(); + + /** Initialize your data structure here. */ + public MyQueue() { + + } + + /** Push element x to the back of queue. */ + public void push(int x) { + s1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + move(); + return s2.pop(); + } + + /** Get the front element. */ + public int peek() { + move(); + return s2.peek(); + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return s1.isEmpty() && s2.isEmpty(); + } + + /** Move elements from s1 to s2. */ + private void move() { + if (s2.isEmpty()) { + while (!s1.isEmpty()) { + s2.push(s1.pop()); + } + } + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0233.leetcode233 Number of Digit One-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0233.leetcode233 Number of Digit One-zh.md" new file mode 100644 index 00000000..53107af4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0233.leetcode233 Number of Digit One-zh.md" @@ -0,0 +1,64 @@ +# [233. 数字 1 的个数](https://leetcode-cn.com/problems/number-of-digit-one) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0233.Number%20of%20Digit%20One/README_EN.md) + +## 题目描述 + + + +

    给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 13
    +输出:6
    +
    + +

    示例 2:

    + +
    +输入:n = 0
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 2 * 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0234.leetcode234 Palindrome Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0234.leetcode234 Palindrome Linked List-zh.md" new file mode 100644 index 00000000..4d92e6f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0234.leetcode234 Palindrome Linked List-zh.md" @@ -0,0 +1,254 @@ +# [234. 回文链表](https://leetcode-cn.com/problems/palindrome-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0234.Palindrome%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    请判断一个链表是否为回文链表。

    + +

    示例 1:

    + +
    输入: 1->2
    +输出: false
    + +

    示例 2:

    + +
    输入: 1->2->2->1
    +输出: true
    +
    + +

    进阶:
    +你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

    + + +## 解法 + + + +先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + if head is None or head.next is None: + return True + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + pre, cur = None, slow.next + while cur: + t = cur.next + cur.next = pre + pre, cur = cur, t + while pre: + if pre.val != head.val: + return False + pre, head = pre.next, head.next + return True +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public boolean isPalindrome(ListNode head) { + if (head == null || head.next == null) { + return true; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode cur = slow.next; + slow.next = null; + ListNode pre = null; + while (cur != null) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + while (pre != null) { + if (pre.val != head.val) { + return false; + } + pre = pre.next; + head = head.next; + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {boolean} + */ +var isPalindrome = function(head) { + if (!head || !head.next) { + return true; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + let cur = slow.next; + slow.next = null; + let pre = null; + while (cur) { + let t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + while (pre) { + if (pre.val !== head.val) { + return false; + } + pre = pre.next; + head = head.next; + } + return true; +}; +``` + +### **C#** + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public bool IsPalindrome(ListNode head) { + if (head == null || head.next == null) + { + return true; + } + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + ListNode cur = slow.next; + slow.next = null; + ListNode pre = null; + while (cur != null) + { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + while (pre != null) + { + if (pre.val != head.val) + { + return false; + } + pre = pre.next; + head = head.next; + } + return true; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function isPalindrome(head: ListNode | null): boolean { + if (head == null || head.next == null) return true; + // 快慢指针定位到中点 + let slow: ListNode = head, fast: ListNode = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + // 翻转链表 + let cur: ListNode = slow.next; + slow.next = null; + let prev: ListNode = null; + while (cur != null) { + let t: ListNode = cur.next; + cur.next = prev; + prev = cur; + cur = t; + } + // 判断回文 + while (prev != null) { + if (prev.val != head.val) return false; + prev = prev.next; + head = head.next; + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0235.leetcode235 Lowest Common Ancestor of a Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0235.leetcode235 Lowest Common Ancestor of a Binary Search Tree-zh.md" new file mode 100644 index 00000000..c8c3fb3a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0235.leetcode235 Lowest Common Ancestor of a Binary Search Tree-zh.md" @@ -0,0 +1,205 @@ +# [235. 二叉搜索树的最近公共祖先](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

    + +

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

    + +

    例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5]

    + +

    + +

     

    + +

    示例 1:

    + +
    输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
    +输出: 6 
    +解释: 节点 2 和节点 8 的最近公共祖先是 6。
    +
    + +

    示例 2:

    + +
    输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
    +输出: 2
    +解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
    + +

     

    + +

    说明:

    + +
      +
    • 所有节点的值都是唯一的。
    • +
    • p、q 为不同节点且均存在于给定的二叉搜索树中。
    • +
    + + +## 解法 + + + +从上到下搜索,找到第一个值位于 `[p, q]` 之间的结点即可。既可以用迭代实现,也可以用递归实现。 + + + +### **Python3** + + + +迭代: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + while root: + if root.val < p.val and root.val < q.val: + root = root.right + elif root.val > p.val and root.val > q.val: + root = root.left + else: + return root +``` + +递归: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if root is None: + return None + if root.val < p.val and root.val < q.val: + return self.lowestCommonAncestor(root.right, p, q) + if root.val > p.val and root.val > q.val: + return self.lowestCommonAncestor(root.left, p, q) + return root +``` + +### **Java** + + + +迭代: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + while (root != null) { + if (root.val < p.val && root.val < q.val) root = root.right; + else if (root.val > p.val && root.val > q.val) root = root.left; + else return root; + } + return root; + } +} +``` + +递归: + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null) return null; + if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); + if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); + return root; + } +} +``` + +### **Go** + +迭代: + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + for root != nil { + // 如果 p、q 的值都小于 root,说明 p、q 肯定在 root 的左子树中; + // 如果 p、q 都大于 root,说明肯定在 root 的右子树中; + // 如果一个在左一个在右,则说明此时的 root 记为对应的最近公共祖先。 + if root.Val > p.Val && root.Val > q.Val { + root = root.Left + } else if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } else { + return root + } + } + return nil +} +``` + +递归: + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root == nil { + return root + } + if root.Val < p.Val && root.Val < q.Val { + return lowestCommonAncestor(root.Right, p, q) + } + if root.Val > p.Val && root.Val > q.Val { + return lowestCommonAncestor(root.Left, p, q) + } + return root +} +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0236.leetcode236 Lowest Common Ancestor of a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0236.leetcode236 Lowest Common Ancestor of a Binary Tree-zh.md" new file mode 100644 index 00000000..6eb5ab1c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0236.leetcode236 Lowest Common Ancestor of a Binary Tree-zh.md" @@ -0,0 +1,153 @@ +# [236. 二叉树的最近公共祖先](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

    + +

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    +输出:3
    +解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
    +
    + +

    示例 2:

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    +输出:5
    +解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。
    +
    + +

    示例 3:

    + +
    +输入:root = [1,2], p = 1, q = 2
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [2, 105] 内。
    • +
    • -109 <= Node.val <= 109
    • +
    • 所有 Node.val 互不相同
    • +
    • p != q
    • +
    • pq 均存在于给定的二叉树中。
    • +
    + + +## 解法 + + + +根据“**最近公共祖先**”的定义,若 root 是 p, q 的最近公共祖先 ,则只可能为以下情况之一: + +- 如果 p 和 q 分别是 root 的左右节点,那么 root 就是我们要找的最近公共祖先; +- 如果 p 和 q 都是 root 的左节点,那么返回 `lowestCommonAncestor(root.left, p, q)`; +- 如果 p 和 q 都是 root 的右节点,那么返回 `lowestCommonAncestor(root.right, p, q)`。 + +**边界条件讨论**: + +- 如果 root 为 null,则说明我们已经找到最底了,返回 null 表示没找到; +- 如果 root 与 p 相等或者与 q 相等,则返回 root; +- 如果左子树没找到,递归函数返回 null,证明 p 和 q 同在 root 的右侧,那么最终的公共祖先就是右子树找到的结点; +- 如果右子树没找到,递归函数返回 null,证明 p 和 q 同在 root 的左侧,那么最终的公共祖先就是左子树找到的结点。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if root is None or root == p or root == q: + return root + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + if left is None: + return right + if right is None: + return left + return root +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + if (left == null) return right; + if (right == null) return left; + return root; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + if (!root || root == p || root == q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (!left) return right; + if (!right) return left; + return root; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0237.leetcode237 Delete Node in a Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0237.leetcode237 Delete Node in a Linked List-zh.md" new file mode 100644 index 00000000..4866e692 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0237.leetcode237 Delete Node in a Linked List-zh.md" @@ -0,0 +1,151 @@ +# [237. 删除链表中的节点](https://leetcode-cn.com/problems/delete-node-in-a-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点。传入函数的唯一参数为 要被删除的节点

    + +

     

    + +

    现有一个链表 -- head = [4,5,1,9],它可以表示为:

    + +

    + +

     

    + +

    示例 1:

    + +
    输入:head = [4,5,1,9], node = 5
    +输出:[4,1,9]
    +解释:给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
    +
    + +

    示例 2:

    + +
    输入:head = [4,5,1,9], node = 1
    +输出:[4,5,9]
    +解释:给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表至少包含两个节点。
    • +
    • 链表中所有节点的值都是唯一的。
    • +
    • 给定的节点为非末尾节点并且一定是链表中的一个有效节点。
    • +
    • 不要从你的函数中返回任何结果。
    • +
    + + +## 解法 + + + +将 `node.next` 节点的值赋给 `node`,然后将 `node.next` 指向 `node.next` 的下一个节点。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def deleteNode(self, node): + """ + :type node: ListNode + :rtype: void Do not return anything, modify node in-place instead. + """ + node.val = node.next.val + node.next = node.next.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public void deleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} node + * @return {void} Do not return anything, modify node in-place instead. + */ +var deleteNode = function (node) { + node.val = node.next.val; + node.next = node.next.next; +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func deleteNode(node *ListNode) { + node.Val = node.Next.Val + node.Next = node.Next.Next +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode* node) { + node->val = node->next->val; + node->next = node->next->next; + } +}; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0238.leetcode238 Product of Array Except Self-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0238.leetcode238 Product of Array Except Self-zh.md" new file mode 100644 index 00000000..ae4cd0d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0238.leetcode238 Product of Array Except Self-zh.md" @@ -0,0 +1,103 @@ +# [238. 除自身以外数组的乘积](https://leetcode-cn.com/problems/product-of-array-except-self) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0238.Product%20of%20Array%20Except%20Self/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

    + +

     

    + +

    示例:

    + +
    输入: [1,2,3,4]
    +输出: [24,12,8,6]
    + +

     

    + +

    提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。

    + +

    说明: 不要使用除法,且在 O(n) 时间复杂度内完成此题。

    + +

    进阶:
    +你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + output = [1 for _ in nums] + left = right = 1 + for i in range(n): + output[i] = left + left *= nums[i] + for i in range(n - 1, -1, -1): + output[i] *= right + right *= nums[i] + return output +``` + +### **Java** + + + +```java +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] output = new int[n]; + for (int i = 0, left = 1; i < n; ++i) { + output[i] = left; + left *= nums[i]; + } + for (int i = n - 1, right = 1; i >= 0; --i) { + output[i] *= right; + right *= nums[i]; + } + return output; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function (nums) { + const n = nums.length; + let output = new Array(n); + for (let i = 0, left = 1; i < n; ++i) { + output[i] = left; + left *= nums[i]; + } + for (let i = n - 1, right = 1; i >= 0; --i) { + output[i] *= right; + right *= nums[i]; + } + return output; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0239.leetcode239 Sliding Window Maximum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0239.leetcode239 Sliding Window Maximum-zh.md" new file mode 100644 index 00000000..39685e11 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0239.leetcode239 Sliding Window Maximum-zh.md" @@ -0,0 +1,127 @@ +# [239. 滑动窗口最大值](https://leetcode-cn.com/problems/sliding-window-maximum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0239.Sliding%20Window%20Maximum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

    + +

    返回滑动窗口中的最大值。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
    +输出:[3,3,5,5,6,7]
    +解释:
    +滑动窗口的位置                最大值
    +---------------               -----
    +[1  3  -1] -3  5  3  6  7       3
    + 1 [3  -1  -3] 5  3  6  7       3
    + 1  3 [-1  -3  5] 3  6  7       5
    + 1  3  -1 [-3  5  3] 6  7       5
    + 1  3  -1  -3 [5  3  6] 7       6
    + 1  3  -1  -3  5 [3  6  7]      7
    +
    + +

    示例 2:

    + +
    +输入:nums = [1], k = 1
    +输出:[1]
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,-1], k = 1
    +输出:[1,-1]
    +
    + +

    示例 4:

    + +
    +输入:nums = [9,11], k = 2
    +输出:[11]
    +
    + +

    示例 5:

    + +
    +输入:nums = [4,-2], k = 2
    +输出:[4]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    • 1 <= k <= nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function (nums, k) { + let len = nums.length; + if (len < k) return []; + let res = [], win = []; + for (let i = 0; i < k; i++) { + while (win.length > 0 && nums[i] >= nums[win[win.length - 1]]) + win.pop(); + win.push(i); + } + res.push(nums[win[0]]); + for (let i = k; i < len; i++) { + while (win.length > 0 && nums[i] >= nums[win[win.length - 1]]) + win.pop(); + if (win.length > 0 && win[0] < i - k + 1) + win.shift(); + win.push(i); + res.push(nums[win[0]]); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0240.leetcode240 Search a 2D Matrix II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0240.leetcode240 Search a 2D Matrix II-zh.md" new file mode 100644 index 00000000..a3528bf4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0240.leetcode240 Search a 2D Matrix II-zh.md" @@ -0,0 +1,166 @@ +# [240. 搜索二维矩阵 II](https://leetcode-cn.com/problems/search-a-2d-matrix-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0240.Search%20a%202D%20Matrix%20II/README_EN.md) + +## 题目描述 + + + +

    编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

    + +
      +
    • 每行的元素从左到右升序排列。
    • +
    • 每列的元素从上到下升序排列。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= n, m <= 300
    • +
    • -109 <= matix[i][j] <= 109
    • +
    • 每行的所有元素从左到右升序排列
    • +
    • 每列的所有元素从上到下升序排列
    • +
    • -109 <= target <= 109
    • +
    + + +## 解法 + + + +从左下角(或右上角)开始查找即可。 + + + +### **Python3** + + + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` + +### **TypeScript** + +```ts +function searchMatrix(matrix: number[][], target: number): boolean { + let m = matrix.length, n = matrix[0].length; + let i = m - 1, j = 0; + while (i >= 0 && j < n) { + let cur = matrix[i][j]; + if (cur == target) return true; + if (cur > target) { + --i; + } else { + ++j; + } + } + return false; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +}; +``` + +### **Go** + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + i, j := m-1, 0 + for i >= 0 && j < n { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0241.leetcode241 Different Ways to Add Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0241.leetcode241 Different Ways to Add Parentheses-zh.md" new file mode 100644 index 00000000..ec3a4fb5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0241.leetcode241 Different Ways to Add Parentheses-zh.md" @@ -0,0 +1,59 @@ +# [241. 为运算表达式设计优先级](https://leetcode-cn.com/problems/different-ways-to-add-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0241.Different%20Ways%20to%20Add%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +- 以及 * 。

    + +

    示例 1:

    + +
    输入: "2-1-1"
    +输出: [0, 2]
    +解释: 
    +((2-1)-1) = 0 
    +(2-(1-1)) = 2
    + +

    示例 2:

    + +
    输入: "2*3-4*5"
    +输出: [-34, -14, -10, -10, 10]
    +解释: 
    +(2*(3-(4*5))) = -34 
    +((2*3)-(4*5)) = -14 
    +((2*(3-4))*5) = -10 
    +(2*((3-4)*5)) = -10 
    +(((2*3)-4)*5) = 10
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0242.leetcode242 Valid Anagram-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0242.leetcode242 Valid Anagram-zh.md" new file mode 100644 index 00000000..2465c6b6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0242.leetcode242 Valid Anagram-zh.md" @@ -0,0 +1,149 @@ +# [242. 有效的字母异位词](https://leetcode-cn.com/problems/valid-anagram) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0242.Valid%20Anagram/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 st ,编写一个函数来判断 t 是否是 s 的字母异位词。

    + +

    示例 1:

    + +
    输入: s = "anagram", t = "nagaram"
    +输出: true
    +
    + +

    示例 2:

    + +
    输入: s = "rat", t = "car"
    +输出: false
    + +

    说明:
    +你可以假设字符串只包含小写字母。

    + +

    进阶:
    +如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

    + + +## 解法 + + + +哈希表解决。 + + + +### **Python3** + + + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + n = len(s) + chars = [0] * 26 + for i in range(n): + chars[ord(s[i]) - ord('a')] += 1 + chars[ord(t[i]) - ord('a')] -= 1 + for i in range(26): + if chars[i] != 0: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isAnagram(String s, String t) { + int n; + if ((n = s.length()) != t.length()) { + return false; + } + int[] chars = new int[26]; + for (int i = 0; i < n; ++i) { + ++chars[s.charAt(i) - 'a']; + --chars[t.charAt(i) - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (chars[i] != 0) { + return false; + } + } + return true; + } +} +``` + +### **TypeScript** + +```ts +function isAnagram(s: string, t: string): boolean { + if (s.length != t.length) return false; + let record = new Array(26).fill(0); + let base = 'a'.charCodeAt(0); + for (let i = 0; i < s.length; ++i) { + ++record[s.charCodeAt(i) - base]; + --record[t.charCodeAt(i) - base]; + } + return record.every(v => v == 0); +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.size() != t.size()) { + return false; + } + vector chars(26, 0); + for (int i = 0, n = s.size(); i < n; ++i) { + ++chars[s[i] - 'a']; + --chars[t[i] - 'a']; + } + for (int i = 0; i < 26; ++i) { + if (chars[i] != 0) { + return false; + } + } + return true; + } +}; +``` + +### **Go** + +```go +func isAnagram(s string, t string) bool { + if len(s) != len(t) { + return false + } + var chars [26]int + for i := 0; i < len(s); i++ { + chars[s[i]-'a']++ + chars[t[i]-'a']-- + } + for i := 0; i < 26; i++ { + if chars[i] != 0 { + return false + } + } + return true +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0243.leetcode243 Shortest Word Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0243.leetcode243 Shortest Word Distance-zh.md" new file mode 100644 index 00000000..a1b6e2ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0243.leetcode243 Shortest Word Distance-zh.md" @@ -0,0 +1,82 @@ +# [243. 最短单词距离](https://leetcode-cn.com/problems/shortest-word-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0243.Shortest%20Word%20Distance/README_EN.md) + +## 题目描述 + + + +

    给定一个单词列表和两个单词 word1word2,返回列表中这两个单词之间的最短距离。

    + +

    示例:
    +假设 words = ["practice", "makes", "perfect", "coding", "makes"]

    + +
    输入: word1 = “coding”, word2 = “practice”
    +输出: 3
    +
    + +
    输入: word1 = "makes", word2 = "coding"
    +输出: 1
    +
    + +

    注意:
    +你可以假设 word1 不等于 word2, 并且 word1word2 都在列表里。

    + +## 解法 + + + +用两个指针 `i1`, `i2` 保存 `word1` 和 `word2` 最近出现的位置,然后每次计算距离 `Math.abs(i1 - i2)` 是否比此前的记录更小,是则更新最短距离。 + + + +### **Python3** + + + +```python +class Solution: + def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: + i1 = i2 = -1 + shortest_distance = len(wordsDict) + for i in range(len(wordsDict)): + if wordsDict[i] == word1: + i1 = i + elif wordsDict[i] == word2: + i2 = i + if i1 != -1 and i2 != -1: + shortest_distance = min(shortest_distance, abs(i1 - i2)) + return shortest_distance +``` + +### **Java** + + + +```java +class Solution { + public int shortestDistance(String[] wordsDict, String word1, String word2) { + int i1 = -1, i2 = -1; + int shortestDistance = wordsDict.length; + for (int i = 0; i < wordsDict.length; ++i) { + if (word1.equals(wordsDict[i])) { + i1 = i; + } else if (word2.equals(wordsDict[i])) { + i2 = i; + } + if (i1 != -1 && i2 != -1) { + shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2)); + } + } + return shortestDistance; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0244.leetcode244 Shortest Word Distance II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0244.leetcode244 Shortest Word Distance II-zh.md" new file mode 100644 index 00000000..a06e2623 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0244.leetcode244 Shortest Word Distance II-zh.md" @@ -0,0 +1,110 @@ +# [244. 最短单词距离 II](https://leetcode-cn.com/problems/shortest-word-distance-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0244.Shortest%20Word%20Distance%20II/README_EN.md) + +## 题目描述 + + + +

    请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次

    + +

    示例:
    +假设 words = ["practice", "makes", "perfect", "coding", "makes"]

    + +
    输入: word1 = “coding”, word2 = “practice”
    +输出: 3
    +
    + +
    输入: word1 = "makes", word2 = "coding"
    +输出: 1
    + +

    注意:
    +你可以假设 word1 不等于 word2, 并且 word1word2 都在列表里。

    + +## 解法 + + + + + +### **Python3** + + + +```python +class WordDistance: + + def __init__(self, wordsDict: List[str]): + self.words = {} + for i, word in enumerate(wordsDict): + indexes = self.words.get(word, []) + indexes.append(i) + self.words[word] = indexes + + def shortest(self, word1: str, word2: str) -> int: + idx1, idx2 = self.words[word1], self.words[word2] + i1 = i2 = 0 + shortest = float('inf') + while i1 < len(idx1) and i2 < len(idx2): + shortest = min(shortest, abs(idx1[i1] - idx2[i2])) + smaller = idx1[i1] < idx2[i2] + if smaller: + i1 += 1 + else: + i2 += 1 + return shortest + + +# Your WordDistance object will be instantiated and called as such: +# obj = WordDistance(wordsDict) +# param_1 = obj.shortest(word1,word2) +``` + +### **Java** + + + +```java +class WordDistance { + private Map> words; + + public WordDistance(String[] wordsDict) { + words = new HashMap<>(); + for (int i = 0; i < wordsDict.length; ++i) { + List indexes = words.getOrDefault(wordsDict[i], new ArrayList<>()); + indexes.add(i); + words.put(wordsDict[i], indexes); + } + } + + public int shortest(String word1, String word2) { + List idx1 = words.get(word1); + List idx2 = words.get(word2); + int i1 = 0, i2 = 0, shortest = Integer.MAX_VALUE; + while (i1 < idx1.size() && i2 < idx2.size()) { + shortest = Math.min(shortest, Math.abs(idx1.get(i1) - idx2.get(i2))); + boolean smaller = idx1.get(i1) < idx2.get(i2); + if (smaller) { + ++i1; + } else { + ++i2; + } + } + return shortest; + } +} + +/** + * Your WordDistance object will be instantiated and called as such: + * WordDistance obj = new WordDistance(wordsDict); + * int param_1 = obj.shortest(word1,word2); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0245.leetcode245 Shortest Word Distance III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0245.leetcode245 Shortest Word Distance III-zh.md" new file mode 100644 index 00000000..2f8ef761 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0245.leetcode245 Shortest Word Distance III-zh.md" @@ -0,0 +1,101 @@ +# [245. 最短单词距离 III](https://leetcode-cn.com/problems/shortest-word-distance-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0245.Shortest%20Word%20Distance%20III/README_EN.md) + +## 题目描述 + + + +

    给定一个单词列表和两个单词 word1word2,返回列表中这两个单词之间的最短距离。

    + +

    word1word2 是有可能相同的,并且它们将分别表示为列表中两个独立的单词。

    + +

    示例:
    +假设 words = ["practice", "makes", "perfect", "coding", "makes"].

    + +
    输入: word1 = “makes”, word2 = “coding”
    +输出: 1
    +
    + +
    输入: word1 = "makes", word2 = "makes"
    +输出: 3
    +
    + +

    注意:
    +你可以假设 word1word2 都在列表里。

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: + i1 = i2 = -1 + shortest_distance = len(wordsDict) + same = word1 == word2 + for i in range(len(wordsDict)): + if same: + if word1 == wordsDict[i]: + if i1 != -1: + shortest_distance = min(shortest_distance, i - i1) + i1 = i + else: + if word1 == wordsDict[i]: + i1 = i + if word2 == wordsDict[i]: + i2 = i + if i1 != -1 and i2 != -1: + shortest_distance = min(shortest_distance, abs(i1 - i2)) + return shortest_distance +``` + +### **Java** + + + +```java +class Solution { + public int shortestWordDistance(String[] wordsDict, String word1, String word2) { + int i1 = -1, i2 = -1; + int shortestDistance = wordsDict.length; + boolean same = word1.equals(word2); + for (int i = 0; i < wordsDict.length; ++i) { + if (same) { + if (word1.equals(wordsDict[i])) { + if (i1 != -1) { + shortestDistance = Math.min(shortestDistance, i - i1); + } + i1 = i; + } + } else { + if (word1.equals(wordsDict[i])) { + i1 = i; + } + if (word2.equals(wordsDict[i])) { + i2 = i; + } + if (i1 != -1 && i2 != -1) { + shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2)); + } + } + } + return shortestDistance; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0246.leetcode246 Strobogrammatic Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0246.leetcode246 Strobogrammatic Number-zh.md" new file mode 100644 index 00000000..145b52a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0246.leetcode246 Strobogrammatic Number-zh.md" @@ -0,0 +1,106 @@ +# [246. 中心对称数](https://leetcode-cn.com/problems/strobogrammatic-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0246.Strobogrammatic%20Number/README_EN.md) + +## 题目描述 + + + +

    中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。

    + +

    请写一个函数来判断该数字是否是中心对称数,其输入将会以一个字符串的形式来表达数字。

    + +

     

    + +

    示例 1:

    + +
    输入: num = "69"
    +输出: true
    +
    + +

    示例 2:

    + +
    输入: num = "88"
    +输出: true
    + +

    示例 3:

    + +
    输入: num = "962"
    +输出: false
    + +

    示例 4:

    + +
    输入:num = "1"
    +输出:true
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isStrobogrammatic(self, num: str) -> bool: + def match(a, b): + if a in {'0', '1', '8'}: + return a == b + if a == '6': + return b == '9' + if a == '9': + return b == '6' + return False + n = len(num) + i, j = 0, n - 1 + while i <= j: + if not match(num[i], num[j]): + return False + i += 1 + j -= 1 + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isStrobogrammatic(String num) { + int n = num.length(); + for (int i = 0, j = n - 1; i <= j; ++i, --j) { + if (!match(num.charAt(i), num.charAt(j))) return false; + } + return true; + } + + private boolean match(char a, char b) { + switch (a) { + case '0': + case '1': + case '8': + return a == b; + case '6': + return b == '9'; + case '9': + return b == '6'; + default: + return false; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0247.leetcode247 Strobogrammatic Number II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0247.leetcode247 Strobogrammatic Number II-zh.md" new file mode 100644 index 00000000..f20710d1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0247.leetcode247 Strobogrammatic Number II-zh.md" @@ -0,0 +1,48 @@ +# [247. 中心对称数 II](https://leetcode-cn.com/problems/strobogrammatic-number-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0247.Strobogrammatic%20Number%20II/README_EN.md) + +## 题目描述 + + + +

    中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。

    + +

    找到所有长度为 n 的中心对称数。

    + +

    示例 :

    + +
    输入:  n = 2
    +输出: ["11","69","88","96"]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0248.leetcode248 Strobogrammatic Number III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0248.leetcode248 Strobogrammatic Number III-zh.md" new file mode 100644 index 00000000..bc97182d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0248.leetcode248 Strobogrammatic Number III-zh.md" @@ -0,0 +1,51 @@ +# [248. 中心对称数 III](https://leetcode-cn.com/problems/strobogrammatic-number-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0248.Strobogrammatic%20Number%20III/README_EN.md) + +## 题目描述 + + + +

    中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。

    + +

    写一个函数来计算范围在 [low, high] 之间中心对称数的个数。

    + +

    示例:

    + +
    输入: low = "50", high = "100"
    +输出: 3 
    +解释: 69,88 和 96 是三个在该范围内的中心对称数
    + +

    注意:
    +由于范围可能很大,所以 low 和 high 都用字符串表示。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0249.leetcode249 Group Shifted Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0249.leetcode249 Group Shifted Strings-zh.md" new file mode 100644 index 00000000..11d641d2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0249.leetcode249 Group Shifted Strings-zh.md" @@ -0,0 +1,58 @@ +# [249. 移位字符串分组](https://leetcode-cn.com/problems/group-shifted-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0249.Group%20Shifted%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,对该字符串可以进行 “移位” 的操作,也就是将字符串中每个字母都变为其在字母表中后续的字母,比如:"abc" -> "bcd"。这样,我们可以持续进行 “移位” 操作,从而生成如下移位序列:

    + +
    "abc" -> "bcd" -> ... -> "xyz"
    + +

    给定一个包含仅小写字母字符串的列表,将该列表中所有满足 “移位” 操作规律的组合进行分组并返回。

    + +

     

    + +

    示例:

    + +
    输入:["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
    +输出:
    +[
    +  ["abc","bcd","xyz"],
    +  ["az","ba"],
    +  ["acef"],
    +  ["a","z"]
    +]
    +解释:可以认为字母表首尾相接,所以 'z' 的后续为 'a',所以 ["az","ba"] 也满足 “移位” 操作规律。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0250.leetcode250 Count Univalue Subtrees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0250.leetcode250 Count Univalue Subtrees-zh.md" new file mode 100644 index 00000000..dc956a45 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0250.leetcode250 Count Univalue Subtrees-zh.md" @@ -0,0 +1,55 @@ +# [250. 统计同值子树](https://leetcode-cn.com/problems/count-univalue-subtrees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0250.Count%20Univalue%20Subtrees/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,统计该二叉树数值相同的子树个数。

    + +

    同值子树是指该子树的所有节点都拥有相同的数值。

    + +

    示例:

    + +
    输入: root = [5,1,5,5,5,null,5]
    +
    +              5
    +             / \
    +            1   5
    +           / \   \
    +          5   5   5
    +
    +输出: 4
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0251.leetcode251 Flatten 2D Vector-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0251.leetcode251 Flatten 2D Vector-zh.md" new file mode 100644 index 00000000..c9bea4c9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0251.leetcode251 Flatten 2D Vector-zh.md" @@ -0,0 +1,89 @@ +# [251. 展开二维向量](https://leetcode-cn.com/problems/flatten-2d-vector) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0251.Flatten%202D%20Vector/README_EN.md) + +## 题目描述 + + + +

    请设计并实现一个能够展开二维向量的迭代器。该迭代器需要支持 next 和 hasNext 两种操作。

    + +

     

    + +

    示例:

    + +
    +Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
    +
    +iterator.next(); // 返回 1
    +iterator.next(); // 返回 2
    +iterator.next(); // 返回 3
    +iterator.hasNext(); // 返回 true
    +iterator.hasNext(); // 返回 true
    +iterator.next(); // 返回 4
    +iterator.hasNext(); // 返回 false
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 请记得 重置 在 Vector2D 中声明的类变量(静态变量),因为类变量会 在多个测试用例中保持不变,影响判题准确。请 查阅 这里。
    2. +
    3. 你可以假定 next() 的调用总是合法的,即当 next() 被调用时,二维向量总是存在至少一个后续元素。
    4. +
    + +

     

    + +

    进阶:尝试在代码中仅使用 C++ 提供的迭代器Java 提供的迭代器

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Vector2D: + + def __init__(self, vec: List[List[int]]): + self.flatten = [] + for item in vec: + for e in item: + self.flatten.append(e) + self.cur = -1 + + def next(self) -> int: + self.cur += 1 + return self.flatten[self.cur] + + def hasNext(self) -> bool: + return self.cur < len(self.flatten) - 1 + + +# Your Vector2D object will be instantiated and called as such: +# obj = Vector2D(vec) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0252.leetcode252 Meeting Rooms-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0252.leetcode252 Meeting Rooms-zh.md" new file mode 100644 index 00000000..98ec6472 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0252.leetcode252 Meeting Rooms-zh.md" @@ -0,0 +1,80 @@ +# [252. 会议室](https://leetcode-cn.com/problems/meeting-rooms) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0252.Meeting%20Rooms/README_EN.md) + +## 题目描述 + + + +

    给定一个会议时间安排的数组 intervals ,每个会议时间都会包括开始和结束的时间 intervals[i] = [starti, endi] ,请你判断一个人是否能够参加这里面的全部会议。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[0,30],[5,10],[15,20]]
    +输出:false
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[7,10],[2,4]]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= intervals.length <= 104
    • +
    • intervals[i].length == 2
    • +
    • 0 <= starti < endi <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def canAttendMeetings(self, intervals: List[List[int]]) -> bool: + intervals.sort(key=lambda x: x[0]) + for i in range(len(intervals) - 1): + if intervals[i][1] > intervals[i + 1][0]: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean canAttendMeetings(int[][] intervals) { + Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); + for (int i = 0, n = intervals.length; i < n - 1; ++i) { + if (intervals[i][1] > intervals[i + 1][0]) return false; + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0253.leetcode253 Meeting Rooms II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0253.leetcode253 Meeting Rooms II-zh.md" new file mode 100644 index 00000000..8ec2c916 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0253.leetcode253 Meeting Rooms II-zh.md" @@ -0,0 +1,65 @@ +# [253. 会议室 II](https://leetcode-cn.com/problems/meeting-rooms-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0253.Meeting%20Rooms%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个会议时间安排的数组 intervals ,每个会议时间都会包括开始和结束的时间 intervals[i] = [starti, endi] ,为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[0,30],[5,10],[15,20]]
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[7,10],[2,4]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= intervals.length <= 104
    • +
    • 0 <= starti < endi <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0254.leetcode254 Factor Combinations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0254.leetcode254 Factor Combinations-zh.md" new file mode 100644 index 00000000..a4bd943f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0254.leetcode254 Factor Combinations-zh.md" @@ -0,0 +1,89 @@ +# [254. 因子的组合](https://leetcode-cn.com/problems/factor-combinations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0254.Factor%20Combinations/README_EN.md) + +## 题目描述 + + + +

    整数可以被看作是其因子的乘积。

    + +

    例如:

    + +
    8 = 2 x 2 x 2;
    +  = 2 x 4.
    + +

    请实现一个函数,该函数接收一个整数 n 并返回该整数所有的因子组合。

    + +

    注意:

    + +
      +
    1. 你可以假定 n 为永远为正数。
    2. +
    3. 因子必须大于 1 并且小于 n
    4. +
    + +

    示例 1:

    + +
    输入: 1
    +输出: []
    +
    + +

    示例 2:

    + +
    输入: 37
    +输出: []
    + +

    示例 3:

    + +
    输入: 12
    +输出:
    +[
    +  [2, 6],
    +  [2, 2, 3],
    +  [3, 4]
    +]
    + +

    示例 4:

    + +
    输入: 32
    +输出:
    +[
    +  [2, 16],
    +  [2, 2, 8],
    +  [2, 2, 2, 4],
    +  [2, 2, 2, 2, 2],
    +  [2, 4, 4],
    +  [4, 8]
    +]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0255.leetcode255 Verify Preorder Sequence in Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0255.leetcode255 Verify Preorder Sequence in Binary Search Tree-zh.md" new file mode 100644 index 00000000..793b93a9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0255.leetcode255 Verify Preorder Sequence in Binary Search Tree-zh.md" @@ -0,0 +1,64 @@ +# [255. 验证前序遍历序列二叉搜索树](https://leetcode-cn.com/problems/verify-preorder-sequence-in-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0255.Verify%20Preorder%20Sequence%20in%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组,你需要验证它是否是一个二叉搜索树正确的先序遍历序列。

    + +

    你可以假定该序列中的数都是不相同的。

    + +

    参考以下这颗二叉搜索树:

    + +
         5
    +    / \
    +   2   6
    +  / \
    + 1   3
    + +

    示例 1:

    + +
    输入: [5,2,6,1,3]
    +输出: false
    + +

    示例 2:

    + +
    输入: [5,2,1,3,6]
    +输出: true
    + +

    进阶挑战:

    + +

    您能否使用恒定的空间复杂度来完成此题?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0256.leetcode256 Paint House-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0256.leetcode256 Paint House-zh.md" new file mode 100644 index 00000000..158615e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0256.leetcode256 Paint House-zh.md" @@ -0,0 +1,56 @@ +# [256. 粉刷房子](https://leetcode-cn.com/problems/paint-house) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0256.Paint%20House/README_EN.md) + +## 题目描述 + + + +

    假如有一排房子,共 n 个,每个房子可以被粉刷成红色、蓝色或者绿色这三种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。

    + +

    当然,因为市场上不同颜色油漆的价格不同,所以房子粉刷成不同颜色的花费成本也是不同的。每个房子粉刷成不同颜色的花费是以一个 n x 3 的矩阵来表示的。

    + +

    例如,costs[0][0] 表示第 0 号房子粉刷成红色的成本花费;costs[1][2] 表示第 1 号房子粉刷成绿色的花费,以此类推。请你计算出粉刷完所有房子最少的花费成本。

    + +

    注意:

    + +

    所有花费均为正整数。

    + +

    示例:

    + +
    输入: [[17,2,17],[16,16,5],[14,3,19]]
    +输出: 10
    +解释: 将 0 号房子粉刷成蓝色,1 号房子粉刷成绿色,2 号房子粉刷成蓝色。最少花费: 2 + 5 + 3 = 10。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0257.leetcode257 Binary Tree Paths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0257.leetcode257 Binary Tree Paths-zh.md" new file mode 100644 index 00000000..a8118219 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0257.leetcode257 Binary Tree Paths-zh.md" @@ -0,0 +1,148 @@ +# [257. 二叉树的所有路径](https://leetcode-cn.com/problems/binary-tree-paths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0257.Binary%20Tree%20Paths/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,返回所有从根节点到叶子节点的路径。

    + +

    说明: 叶子节点是指没有子节点的节点。

    + +

    示例:

    + +
    输入:
    +
    +   1
    + /   \
    +2     3
    + \
    +  5
    +
    +输出: ["1->2->5", "1->3"]
    +
    +解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
    + + +## 解法 + + + +深度优先搜索+路径记录。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def binaryTreePaths(self, root: TreeNode) -> List[str]: + def dfs(root): + if root is None: + return + path.append(str(root.val)) + if root.left is None and root.right is None: + res.append("->".join(path)) + dfs(root.left) + dfs(root.right) + path.pop() + res = [] + path = [] + dfs(root) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + private List res; + private List path; + + public List binaryTreePaths(TreeNode root) { + if (root == null) return Collections.emptyList(); + res = new ArrayList<>(); + path = new ArrayList<>(); + dfs(root); + return res; + } + + private void dfs(TreeNode root) { + if (root == null) return; + path.add(String.valueOf(root.val)); + if (root.left == null && root.right == null) { + res.add(String.join("->", path)); + } + dfs(root.left); + dfs(root.right); + path.remove(path.size() - 1); + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function binaryTreePaths(root: TreeNode | null): string[] { + let ans = []; + let pre = ''; + dfs(root, pre, ans); + return ans; +}; + +function dfs(root: TreeNode | null, pre: string, ans: string[]): void { + if (root == null) return; + let val = String(root.val); + pre = pre.length > 0 ? `${pre}->${val}` : pre + val; + // 叶子节点 + if (root.left == null && root.right == null) { + ans.push(pre); + return; + } + dfs(root.left, pre, ans); + dfs(root.right, pre, ans); +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0258.leetcode258 Add Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0258.leetcode258 Add Digits-zh.md" new file mode 100644 index 00000000..8b27b799 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0258.leetcode258 Add Digits-zh.md" @@ -0,0 +1,82 @@ +# [258. 各位相加](https://leetcode-cn.com/problems/add-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0258.Add%20Digits/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

    + +

    示例:

    + +
    输入: 38
    +输出: 2 
    +解释: 各位相加的过程为3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
    +
    + +

    进阶:
    +你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

    + + +## 解法 + + + +题目要求的数叫做“数根”,我们把 1~30 的数根列出来: + +``` +原数: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 +数根: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 +``` + +可以看到,数根 9 个为一组,循环出现。我们可以得出下面的规律: + +- n = 0:数根是 0 +- n 是 9 的倍数:数根是 9 +- n 不是 9 的倍数:数根是 n % 9 + +将上面的规律用式子:`(n - 1) % 9 + 1` 统一表达。 + + + +### **Python3** + + + +```python +class Solution: + def addDigits(self, num: int) -> int: + return 0 if num == 0 else (num - 1) % 9 + 1 +``` + +### **Java** + + + +```java +class Solution { + public int addDigits(int num) { + return (num - 1) % 9 + 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int addDigits(int num) { + return (num - 1) % 9 + 1; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0259.leetcode259 3Sum Smaller-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0259.leetcode259 3Sum Smaller-zh.md" new file mode 100644 index 00000000..e9409733 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0259.leetcode259 3Sum Smaller-zh.md" @@ -0,0 +1,123 @@ +# [259. 较小的三数之和](https://leetcode-cn.com/problems/3sum-smaller) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0259.3Sum%20Smaller/README_EN.md) + +## 题目描述 + + + +

    给定一个长度为 n 的整数数组和一个目标值 target,寻找能够使条件 nums[i] + nums[j] + nums[k] < target 成立的三元组  i, j, k 个数(0 <= i < j < k < n)。

    + +

    示例:

    + +
    输入: nums = [-2,0,1,3], target = 2
    +输出: 2 
    +解释: 因为一共有两个三元组满足累加和小于 2:
    +     [-2,0,1]
    +     [-2,0,3]
    +
    + +

    进阶:是否能在 O(n2) 的时间复杂度内解决?

    + + +## 解法 + + + +双指针解决。 + + + +### **Python3** + + + +```python +class Solution: + def threeSumSmaller(self, nums: List[int], target: int) -> int: + def threeSumSmaller(nums, start, end, target): + count = 0 + while start < end: + if nums[start] + nums[end] < target: + count += (end - start) + start += 1 + else: + end -= 1 + return count + + nums.sort() + n, count = len(nums), 0 + for i in range(n - 2): + count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]) + return count +``` + +### **Java** + + + +```java +class Solution { + public int threeSumSmaller(int[] nums, int target) { + Arrays.sort(nums); + int n = nums.length; + int count = 0; + for (int i = 0; i < n - 2; ++i) { + count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]); + } + return count; + } + + private int threeSumSmaller(int[] nums, int start, int end, int target) { + int count = 0; + while (start < end) { + if (nums[start] + nums[end] < target) { + count += (end - start); + ++start; + } else { + --end; + } + } + return count; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumSmaller = function (nums, target) { + let len = nums.length; + if (len < 3) return 0; + nums.sort((a, b) => a - b) + let res = 0; + for (let i = 0; i < len - 2; i++) { + let left = i + 1, right = len - 1; + if (nums[i] + nums[left] + nums[i + 2] >= target) break; + while (left < right) { + if (nums[i] + nums[left] + nums[right] < target) { + res += (right - left); + left++; + continue; + } else { + right--; + continue; + } + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0260.leetcode260 Single Number III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0260.leetcode260 Single Number III-zh.md" new file mode 100644 index 00000000..153ebd0e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0260.leetcode260 Single Number III-zh.md" @@ -0,0 +1,105 @@ +# [260. 只出现一次的数字 III](https://leetcode-cn.com/problems/single-number-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0260.Single%20Number%20III/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。

    + +

     

    + +

    进阶:你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,1,3,2,5]
    +输出:[3,5]
    +解释:[5, 3] 也是有效的答案。
    +
    + +

    示例 2:

    + +
    +输入:nums = [-1,0]
    +输出:[-1,0]
    +
    + +

    示例 3:

    + +
    +输入:nums = [0,1]
    +输出:[1,0]
    +
    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 3 * 104
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    • 除两个只出现一次的整数外,nums 中的其他数字都出现两次
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + eor = 0 + for num in nums: + eor ^= num + # 提取最右边的 1 + diff = eor & (~eor + 1) + a = 0 + for num in nums: + if (num & diff) == 0: + a ^= num + b = eor ^ a + return [a, b] +``` + +### **Java** + + + +```java +class Solution { + public int[] singleNumber(int[] nums) { + int eor = 0; + for (int num : nums) { + eor ^= num; + } + // 提取最右的 1 + int diff = eor & (~eor + 1); + int a = 0; + for (int num : nums) { + if ((num & diff) == 0) { + a ^= num; + } + } + int b = eor ^ a; + return new int[]{a, b}; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0261.leetcode261 Graph Valid Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0261.leetcode261 Graph Valid Tree-zh.md" new file mode 100644 index 00000000..e105d9ef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0261.leetcode261 Graph Valid Tree-zh.md" @@ -0,0 +1,52 @@ +# [261. 以图判树](https://leetcode-cn.com/problems/graph-valid-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0261.Graph%20Valid%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定从 0n-1 标号的 n 个结点,和一个无向边列表(每条边以结点对来表示),请编写一个函数用来判断这些边是否能够形成一个合法有效的树结构。

    + +

    示例 1:

    + +
    输入: n = 5, 边列表 edges = [[0,1], [0,2], [0,3], [1,4]]
    +输出: true
    + +

    示例 2:

    + +
    输入: n = 5, 边列表 edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
    +输出: false
    + +

    注意:你可以假定边列表 edges 中不会出现重复的边。由于所有的边是无向边,边 [0,1] 和边 [1,0] 是相同的,因此不会同时出现在边列表 edges 中。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0262.leetcode262 Trips and Users-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0262.leetcode262 Trips and Users-zh.md" new file mode 100644 index 00000000..9be2276f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0262.leetcode262 Trips and Users-zh.md" @@ -0,0 +1,133 @@ +# [262. 行程和用户](https://leetcode-cn.com/problems/trips-and-users) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0262.Trips%20and%20Users/README_EN.md) + +## 题目描述 + + + +表:Trips +
    +
    +
    ++-------------+----------+
    +| Column Name | Type     |
    ++-------------+----------+
    +| Id          | int      |
    +| Client_Id   | int      |
    +| Driver_Id   | int      |
    +| City_Id     | int      |
    +| Status      | enum     |
    +| Request_at  | date     |     
    ++-------------+----------+
    +Id 是这张表的主键。
    +这张表中存所有出租车的行程信息。每段行程有唯一 Id ,其中 Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外键。
    +Status 是一个表示行程状态的枚举类型,枚举成员为(‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’) 。
    +
    + +

     

    + +
    +
    +

    表:Users

    +
    +
    + +
    ++-------------+----------+
    +| Column Name | Type     |
    ++-------------+----------+
    +| Users_Id    | int      |
    +| Banned      | enum     |
    +| Role        | enum     |
    ++-------------+----------+
    +Users_Id 是这张表的主键。
    +这张表中存所有用户,每个用户都有一个唯一的 Users_Id ,Role 是一个表示用户身份的枚举类型,枚举成员为 (‘client’, ‘driver’, ‘partner’) 。
    +Banned 是一个表示用户是否被禁止的枚举类型,枚举成员为 (‘Yes’, ‘No’) 。
    +
    + +

     

    + +

    写一段 SQL 语句查出 "2013-10-01" 至 "2013-10-03" 期间非禁止用户(乘客和司机都必须未被禁止)的取消率。非禁止用户即 Banned 为 No 的用户,禁止用户即 Banned 为 Yes 的用户。

    + +

    取消率 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数)。

    + +

    返回结果表中的数据可以按任意顺序组织。其中取消率 Cancellation Rate 需要四舍五入保留 两位小数

    + +

     

    + +

    查询结果格式如下例所示:

    + +
    +Trips 表:
    ++----+-----------+-----------+---------+---------------------+------------+
    +| Id | Client_Id | Driver_Id | City_Id | Status              | Request_at |
    ++----+-----------+-----------+---------+---------------------+------------+
    +| 1  | 1         | 10        | 1       | completed           | 2013-10-01 |
    +| 2  | 2         | 11        | 1       | cancelled_by_driver | 2013-10-01 |
    +| 3  | 3         | 12        | 6       | completed           | 2013-10-01 |
    +| 4  | 4         | 13        | 6       | cancelled_by_client | 2013-10-01 |
    +| 5  | 1         | 10        | 1       | completed           | 2013-10-02 |
    +| 6  | 2         | 11        | 6       | completed           | 2013-10-02 |
    +| 7  | 3         | 12        | 6       | completed           | 2013-10-02 |
    +| 8  | 2         | 12        | 12      | completed           | 2013-10-03 |
    +| 9  | 3         | 10        | 12      | completed           | 2013-10-03 |
    +| 10 | 4         | 13        | 12      | cancelled_by_driver | 2013-10-03 |
    ++----+-----------+-----------+---------+---------------------+------------+
    +
    +Users 表:
    ++----------+--------+--------+
    +| Users_Id | Banned | Role   |
    ++----------+--------+--------+
    +| 1        | No     | client |
    +| 2        | Yes    | client |
    +| 3        | No     | client |
    +| 4        | No     | client |
    +| 10       | No     | driver |
    +| 11       | No     | driver |
    +| 12       | No     | driver |
    +| 13       | No     | driver |
    ++----------+--------+--------+
    +
    +Result 表:
    ++------------+-------------------+
    +| Day        | Cancellation Rate |
    ++------------+-------------------+
    +| 2013-10-01 | 0.33              |
    +| 2013-10-02 | 0.00              |
    +| 2013-10-03 | 0.50              |
    ++------------+-------------------+
    +
    +2013-10-01:
    +  - 共有 4 条请求,其中 2 条取消。
    +  - 然而,Id=2 的请求是由禁止用户(User_Id=2)发出的,所以计算时应当忽略它。
    +  - 因此,总共有 3 条非禁止请求参与计算,其中 1 条取消。
    +  - 取消率为 (1 / 3) = 0.33
    +2013-10-02:
    +  - 共有 3 条请求,其中 0 条取消。
    +  - 然而,Id=6 的请求是由禁止用户发出的,所以计算时应当忽略它。
    +  - 因此,总共有 2 条非禁止请求参与计算,其中 0 条取消。
    +  - 取消率为 (0 / 2) = 0.00
    +2013-10-03:
    +  - 共有 3 条请求,其中 1 条取消。
    +  - 然而,Id=8 的请求是由禁止用户发出的,所以计算时应当忽略它。
    +  - 因此,总共有 2 条非禁止请求参与计算,其中 1 条取消。
    +  - 取消率为 (1 / 2) = 0.50
    +
    +
    +
    + + +## 解法 + + + + + +### **SQL** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0263.leetcode263 ugly-number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0263.leetcode263 ugly-number-zh.md" new file mode 100644 index 00000000..ea3d8ca8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0263.leetcode263 ugly-number-zh.md" @@ -0,0 +1,50 @@ +### [263. 丑数](https://leetcode-cn.com/problems/ugly-number/) + +**难度** 简单 + + + +给你一个整数 `n` ,请你判断 `n` 是否为 **丑数** 。如果是,返回 `true` ;否则,返回 `false` 。 + +**丑数** 就是只包含质因数 `2`、`3` 和/或 `5` 的正整数。 + + + +**示例 1:** + +``` +输入:n = 6 +输出:true +解释:6 = 2 × 3 +``` + +**示例 2:** + +``` +输入:n = 8 +输出:true +解释:8 = 2 × 2 × 2 +``` + +**示例 3:** + +``` +输入:n = 14 +输出:false +解释:14 不是丑数,因为它包含了另外一个质因数 7 。 +``` + +**示例 4:** + +``` +输入:n = 1 +输出:true +解释:1 通常被视为丑数。 +``` + + + +**提示:** + +- `-2^31 <= n <= 2^31 - 1` + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0264.leetcode264 Ugly Number II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0264.leetcode264 Ugly Number II-zh.md" new file mode 100644 index 00000000..31ca009e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0264.leetcode264 Ugly Number II-zh.md" @@ -0,0 +1,213 @@ +# [264. 丑数 II](https://leetcode-cn.com/problems/ugly-number-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0264.Ugly%20Number%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n ,请你找出并返回第 n丑数

    + +

    丑数 就是只包含质因数 23 和/或 5 的正整数。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 10
    +输出:12
    +解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
    +
    + +

    示例 2:

    + +
    +输入:n = 1
    +输出:1
    +解释:1 通常被视为丑数。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1690
    • +
    + + +## 解法 + + + +动态规划法。 + +定义数组 dp,`dp[i - 1]` 表示第 i 个丑数,那么第 n 个丑数就是 `dp[n - 1]`。最小的丑数是 1,所以 `dp[0] = 1`。 + +定义 3 个指针 p2,p3,p5,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针的值都指向 0。 + +当 `i∈[1,n)`,`dp[i] = min(dp[p2] * 2, dp[p3] * 3, dp[p5] * 5)`,然后分别比较 `dp[i]` 与 `dp[p2] * 2`、`dp[p3] * 3`、`dp[p5] * 5` 是否相等,若是,则对应的指针加 1。 + +最后返回 `dp[n - 1]` 即可。 + + + +### **Python3** + + + +```python +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] +``` + +### **Java** + + + +```java +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {number} + */ +var nthUglyNumber = function (n) { + let dp = [1]; + let p2 = 0, + p3 = 0, + p5 = 0; + for (let i = 1; i < n; ++i) { + const next2 = dp[p2] * 2, + next3 = dp[p3] * 3, + next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + dp.push(dp[i]); + } + return dp[n - 1]; +}; +``` + +### **Go** + +```go +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int NthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) + { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.Min(next2, Math.Min(next3, next5)); + if (dp[i] == next2) + { + ++p2; + } + if (dp[i] == next3) + { + ++p3; + } + if (dp[i] == next5) + { + ++p5; + } + } + return dp[n - 1]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0265.leetcode265 Paint House II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0265.leetcode265 Paint House II-zh.md" new file mode 100644 index 00000000..fded0d0f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0265.leetcode265 Paint House II-zh.md" @@ -0,0 +1,59 @@ +# [265. 粉刷房子 II](https://leetcode-cn.com/problems/paint-house-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0265.Paint%20House%20II/README_EN.md) + +## 题目描述 + + + +

    假如有一排房子,共 n 个,每个房子可以被粉刷成 k 种颜色中的一种,你需要粉刷所有的房子并且使其相邻的两个房子颜色不能相同。

    + +

    当然,因为市场上不同颜色油漆的价格不同,所以房子粉刷成不同颜色的花费成本也是不同的。每个房子粉刷成不同颜色的花费是以一个 n x k 的矩阵来表示的。

    + +

    例如,costs[0][0] 表示第 0 号房子粉刷成 0 号颜色的成本花费;costs[1][2] 表示第 1 号房子粉刷成 2 号颜色的成本花费,以此类推。请你计算出粉刷完所有房子最少的花费成本。

    + +

    注意:

    + +

    所有花费均为正整数。

    + +

    示例:

    + +
    输入: [[1,5,3],[2,9,4]]
    +输出: 5
    +解释: 将 0 号房子粉刷成 0 号颜色,1 号房子粉刷成 2 号颜色。最少花费: 1 + 4 = 5; 
    +     或者将 0 号房子粉刷成 2 号颜色,1 号房子粉刷成 0 号颜色。最少花费: 3 + 2 = 5. 
    +
    + +

    进阶:
    +您能否在 O(nk) 的时间复杂度下解决此问题?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0266.leetcode266 Palindrome Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0266.leetcode266 Palindrome Permutation-zh.md" new file mode 100644 index 00000000..a2793e3c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0266.leetcode266 Palindrome Permutation-zh.md" @@ -0,0 +1,81 @@ +# [266. 回文排列](https://leetcode-cn.com/problems/palindrome-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0266.Palindrome%20Permutation/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,判断该字符串中是否可以通过重新排列组合,形成一个回文字符串。

    + +

    示例 1:

    + +
    输入: "code"
    +输出: false
    + +

    示例 2:

    + +
    输入: "aab"
    +输出: true
    + +

    示例 3:

    + +
    输入: "carerac"
    +输出: true
    + + +## 解法 + + + +利用 HashMap(字典表)统计每个字符出现的频率,至多有一个字符出现奇数次数即可。 + + + +### **Python3** + + + +```python +class Solution: + def canPermutePalindrome(self, s: str) -> bool: + mapper = {} + for ch in s: + mapper[ch] = mapper.get(ch, 0) + 1 + cnt = 0 + for _, v in mapper.items(): + if v % 2 != 0: + cnt += 1 + return cnt <= 1 +``` + +### **Java** + + + +```java +class Solution { + public boolean canPermutePalindrome(String s) { + Map map = new HashMap<>(); + for (int i = 0, n = s.length(); i < n; ++i) { + char ch = s.charAt(i); + map.put(ch, map.getOrDefault(ch, 0) + 1); + } + int cnt = 0; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() % 2 != 0) { + ++cnt; + } + } + return cnt <= 1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0267.leetcode267 Palindrome Permutation II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0267.leetcode267 Palindrome Permutation II-zh.md" new file mode 100644 index 00000000..77b771cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0267.leetcode267 Palindrome Permutation II-zh.md" @@ -0,0 +1,52 @@ +# [267. 回文排列 II](https://leetcode-cn.com/problems/palindrome-permutation-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0267.Palindrome%20Permutation%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s ,返回其通过重新排列组合后所有可能的回文字符串,并去除重复的组合。

    + +

    如不能形成任何回文排列时,则返回一个空列表。

    + +

    示例 1:

    + +
    输入: "aabb"
    +输出: ["abba", "baab"]
    + +

    示例 2:

    + +
    输入: "abc"
    +输出: []
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0268.leetcode268 Missing Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0268.leetcode268 Missing Number-zh.md" new file mode 100644 index 00000000..40ea9f0b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0268.leetcode268 Missing Number-zh.md" @@ -0,0 +1,122 @@ +# [268. 丢失的数字](https://leetcode-cn.com/problems/missing-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0268.Missing%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。

    + +

     

    + +

    进阶:

    + +
      +
    • 你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3,0,1]
    +输出:2
    +解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。
    + +

    示例 2:

    + +
    +输入:nums = [0,1]
    +输出:2
    +解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。
    + +

    示例 3:

    + +
    +输入:nums = [9,6,4,2,3,5,7,0,1]
    +输出:8
    +解释:n = 9,因为有 9 个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。
    + +

    示例 4:

    + +
    +输入:nums = [0]
    +输出:1
    +解释:n = 1,因为有 1 个数字,所以所有的数字都在范围 [0,1] 内。1 是丢失的数字,因为它没有出现在 nums 中。
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 104
    • +
    • 0 <= nums[i] <= n
    • +
    • nums 中的所有数字都 独一无二
    • +
    + + +## 解法 + + + +异或求解。两个相同的数异或的结果为 0。 + +也可以用数学求解。求出 `[0..n]` 的和,减去数组中所有数的和,就得到了缺失的数字。 + + + +### **Python3** + + + +```python +class Solution: + def missingNumber(self, nums: List[int]) -> int: + res = len(nums) + for i, v in enumerate(nums): + res ^= (i ^ v) + return res +``` + +### **Java** + + + +- 异或 + +```java +class Solution { + public int missingNumber(int[] nums) { + int res = nums.length; + for (int i = 0, n = res; i < n; ++i) { + res ^= (i ^ nums[i]); + } + return res; + } +} +``` + +- 数学 + +```java +class Solution { + public int missingNumber(int[] nums) { + int res = nums.length; + for (int i = 0, n = res; i < n; ++i) { + res += (i - nums[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0269.leetcode269 Alien Dictionary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0269.leetcode269 Alien Dictionary-zh.md" new file mode 100644 index 00000000..1fab46ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0269.leetcode269 Alien Dictionary-zh.md" @@ -0,0 +1,85 @@ +# [269. 火星词典](https://leetcode-cn.com/problems/alien-dictionary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0269.Alien%20Dictionary/README_EN.md) + +## 题目描述 + + + +

    现有一种使用英语字母的火星语言,这门语言的字母顺序与英语顺序不同。

    + +

    给你一个字符串列表 words ,作为这门语言的词典,words 中的字符串已经 按这门新语言的字母顺序进行了排序

    + +

    请你根据该词典还原出此语言中已知的字母顺序,并 按字母递增顺序 排列。若不存在合法字母顺序,返回 "" 。若存在多种可能的合法字母顺序,返回其中 任意一种 顺序即可。

    + +

    字符串 s 字典顺序小于 字符串 t 有两种情况:

    + +
      +
    • 在第一个不同字母处,如果 s 中的字母在这门外星语言的字母顺序中位于 t 中字母之前,那么 s 的字典顺序小于 t
    • +
    • 如果前面 min(s.length, t.length) 字母都相同,那么 s.length < t.length 时,s 的字典顺序也小于 t
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["wrt","wrf","er","ett","rftt"]
    +输出:"wertf"
    +
    + +

    示例 2:

    + +
    +输入:words = ["z","x"]
    +输出:"zx"
    +
    + +

    示例 3:

    + +
    +输入:words = ["z","x","z"]
    +输出:""
    +解释:不存在合法字母顺序,因此返回 "" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 100
    • +
    • 1 <= words[i].length <= 100
    • +
    • words[i] 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0270.leetcode270 Closest Binary Search Tree Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0270.leetcode270 Closest Binary Search Tree Value-zh.md" new file mode 100644 index 00000000..075c5a61 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0270.leetcode270 Closest Binary Search Tree Value-zh.md" @@ -0,0 +1,216 @@ +# [270. 最接近的二叉搜索树值](https://leetcode-cn.com/problems/closest-binary-search-tree-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/README_EN.md) + +## 题目描述 + + + +

    给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的数值。

    + +

    注意:

    + +
      +
    • 给定的目标值 target 是一个浮点数
    • +
    • 题目保证在该二叉搜索树中只会存在一个最接近目标值的数
    • +
    + +

    示例:

    + +
    输入: root = [4,2,5,1,3],目标值 target = 3.714286
    +
    +    4
    +   / \
    +  2   5
    + / \
    +1   3
    +
    +输出: 4
    +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def closestValue(self, root: TreeNode, target: float) -> int: + res, min_diff = root.val, float('inf') + while root: + val = abs(root.val - target) + if min_diff > val: + min_diff = val + res = root.val + if root.val > target: + root = root.left + else: + root = root.right + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int closestValue(TreeNode root, double target) { + int res = root.val; + double minDiff = Double.MAX_VALUE; + while (root != null) { + double val = Math.abs(root.val - target); + if (minDiff > val) { + minDiff = val; + res = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} target + * @return {number} + */ +var closestValue = function(root, target) { + let res = root.val; + let minDiff = Math.abs(root.val - target); + while (root) { + const val = Math.abs(root.val - target); + if (minDiff > val) { + minDiff = val; + res = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return res; +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int closestValue(TreeNode* root, double target) { + int res = root->val; + double minDiff = abs(root->val - target); + while (root != nullptr) { + double val = abs(root->val - target); + if (minDiff > val) { + minDiff = val; + res = root->val; + } + if (root->val > target) { + root = root->left; + } else { + root = root->right; + } + } + return res; + } +}; +``` + +### **Go** + +```go +import "math" + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func closestValue(root *TreeNode, target float64) int { + res := root.Val + minDiff := math.Abs(float64(root.Val) - float64(target)) + for root != nil { + val := math.Abs(float64(root.Val) - float64(target)) + if minDiff > val { + minDiff = val + res = root.Val + } + if float64(root.Val) > target { + root = root.Left + } else { + root = root.Right + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0271.leetcode271 Encode and Decode Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0271.leetcode271 Encode and Decode Strings-zh.md" new file mode 100644 index 00000000..4a489f57 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0271.leetcode271 Encode and Decode Strings-zh.md" @@ -0,0 +1,77 @@ +# [271. 字符串的编码与解码](https://leetcode-cn.com/problems/encode-and-decode-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0271.Encode%20and%20Decode%20Strings/README_EN.md) + +## 题目描述 + + + +

    请你设计一个算法,可以将一个 字符串列表 编码成为一个 字符串。这个编码后的字符串是可以通过网络进行高效传送的,并且可以在接收端被解码回原来的字符串列表。

    + +

    1 号机(发送方)有如下函数:

    + +
    string encode(vector<string> strs) {
    +  // ... your code
    +  return encoded_string;
    +}
    + +

    2 号机(接收方)有如下函数:

    + +
    vector<string> decode(string s) {
    +  //... your code
    +  return strs;
    +}
    +
    + +

    1 号机(发送方)执行:

    + +
    string encoded_string = encode(strs);
    +
    + +

    2 号机(接收方)执行:

    + +
    vector<string> strs2 = decode(encoded_string);
    +
    + +

    此时,2 号机(接收方)的 strs2 需要和 1 号机(发送方)的 strs 相同。

    + +

    请你来实现这个 encode 和 decode 方法。

    + +

    注意:

    + +
      +
    • 因为字符串可能会包含 256 个合法 ascii 字符中的任何字符,所以您的算法必须要能够处理任何可能会出现的字符。
    • +
    • 请勿使用 “类成员”、“全局变量” 或 “静态变量” 来存储这些状态,您的编码和解码算法应该是非状态依赖的。
    • +
    • 请不要依赖任何方法库,例如 eval 又或者是 serialize 之类的方法。本题的宗旨是需要您自己实现 “编码” 和 “解码” 算法。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0272.leetcode272 Closest Binary Search Tree Value II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0272.leetcode272 Closest Binary Search Tree Value II-zh.md" new file mode 100644 index 00000000..2ec57383 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0272.leetcode272 Closest Binary Search Tree Value II-zh.md" @@ -0,0 +1,63 @@ +# [272. 最接近的二叉搜索树值 II](https://leetcode-cn.com/problems/closest-binary-search-tree-value-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0272.Closest%20Binary%20Search%20Tree%20Value%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的 k 个值。

    + +

    注意:

    + +
      +
    • 给定的目标值 target 是一个浮点数
    • +
    • 你可以默认 k 值永远是有效的,即 k ≤ 总结点数
    • +
    • 题目保证该二叉搜索树中只会存在一种 k 个值集合最接近目标值
    • +
    + +

    示例:

    + +
    输入: root = [4,2,5,1,3],目标值 = 3.714286,且 k = 2
    +
    +    4
    +   / \
    +  2   5
    + / \
    +1   3
    +
    +输出: [4,3]
    + +

    拓展:
    +假设该二叉搜索树是平衡的,请问您是否能在小于 O(n)(n 为总结点数)的时间复杂度内解决该问题呢?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0273.leetcode273 Integer to English Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0273.leetcode273 Integer to English Words-zh.md" new file mode 100644 index 00000000..9d41d0a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0273.leetcode273 Integer to English Words-zh.md" @@ -0,0 +1,78 @@ +# [273. 整数转换英文表示](https://leetcode-cn.com/problems/integer-to-english-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0273.Integer%20to%20English%20Words/README_EN.md) + +## 题目描述 + + + +

    将非负整数 num 转换为其对应的英文表示。

    + +

     

    + +

    示例 1:

    + +
    +输入:num = 123
    +输出:"One Hundred Twenty Three"
    +
    + +

    示例 2:

    + +
    +输入:num = 12345
    +输出:"Twelve Thousand Three Hundred Forty Five"
    +
    + +

    示例 3:

    + +
    +输入:num = 1234567
    +输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
    +
    + +

    示例 4:

    + +
    +输入:num = 1234567891
    +输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= num <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0274.leetcode274 H-Index-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0274.leetcode274 H-Index-zh.md" new file mode 100644 index 00000000..79083dac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0274.leetcode274 H-Index-zh.md" @@ -0,0 +1,151 @@ +# [274. H 指数](https://leetcode-cn.com/problems/h-index) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0274.H-Index/README_EN.md) + +## 题目描述 + + + +

    给定一位研究者论文被引用次数的数组(被引用次数是非负整数)。编写一个方法,计算出研究者的 指数。

    + +

    h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 N - h 篇论文每篇被引用次数 不超过 h 次。

    + +

    例如:某人的 h 指数是 20,这表示他已发表的论文中,每篇被引用了至少 20 次的论文总共有 20 篇。

    + +

     

    + +

    示例:

    + +
    +输入:citations = [3,0,6,1,5]
    +输出:3
    +解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 3, 0, 6, 1, 5 次。
    +     由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用 不多于 3 次,所以她的 h 指数是 3
    + +

     

    + +

    提示:如果 h 有多种可能的值,h 指数是其中最大的那个。

    + + +## 解法 + + + +最简单的解法就是排序之后再判断,但是因为 `H` 不可能大于论文的总数 `n`,所以可以用计数排序进行优化。 + + + +### **Python3** + + + +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + cnt = [0 for i in range(n + 1)] + for c in citations: + if c <= n: + cnt[c] += 1 + else: + cnt[n] += 1 + sum = 0 + for i in range(n, -1, -1): + sum += cnt[i] + if sum >= i: + return i + return 0 +``` + +### **Java** + + + +```java +class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int[] cnt = new int[n + 1]; + for (int c : citations) { + if (c <= n) { + ++cnt[c]; + } else { + ++cnt[n]; + } + } + int sum = 0; + for (int i = n; i >= 0; --i) { + sum += cnt[i]; + if (sum >= i) { + return i; + } + } + return 0; + } +} +``` + +### **TypeScript** + +```ts +function hIndex(citations: number[]): number { + let n = citations.length; + let cnt = new Array(n + 1).fill(0); + for (let c of citations) { + if ( c <= n) { + ++cnt[c]; + } else { + ++cnt[n]; + } + } + let sum = 0; + for (let i = n; i > -1; --i) { + sum += cnt[i]; + if (sum >= i) { + return i; + } + } + return 0; +}; +``` + +### **Go** + +利用二分查找,定位符合条件的最大值 + +```go +func hIndex(citations []int) int { + n := len(citations) + left, right := 0, n + for left+1 < right { + mid := int(uint(left+right) >> 1) + if check(citations, mid) { + left = mid + } else { + right = mid + } + } + if check(citations, right) { + return right + } + return left +} + +func check(citations []int, mid int) bool { + cnt := 0 + for _, citation := range citations { + if citation >= mid { + cnt++ + } + } + return cnt >= mid +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0275.leetcode275 H-Index II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0275.leetcode275 H-Index II-zh.md" new file mode 100644 index 00000000..b2ca0a64 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0275.leetcode275 H-Index II-zh.md" @@ -0,0 +1,131 @@ +# [275. H 指数 II](https://leetcode-cn.com/problems/h-index-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0275.H-Index%20II/README_EN.md) + +## 题目描述 + + + +

    给定一位研究者论文被引用次数的数组(被引用次数是非负整数),数组已经按照 升序排列 。编写一个方法,计算出研究者的 h 指数。

    + +

    h 指数的定义: “h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。(其余的 N - h 篇论文每篇被引用次数不多于 h 次。)"

    + +

     

    + +

    示例:

    + +
    输入: citations = [0,1,3,5,6]
    +输出: 3 
    +解释: 给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 0, 1, 3, 5, 6 次。
    +     由于研究者有 3 篇论文每篇至少被引用了 3 次,其余两篇论文每篇被引用不多于 3 次,所以她的 h 指数是 3
    + +

     

    + +

    说明:

    + +

    如果 h 有多有种可能的值 ,h 指数是其中最大的那个。

    + +

     

    + +

    进阶:

    + +
      +
    • 这是 H 指数 的延伸题目,本题中的 citations 数组是保证有序的。
    • +
    • 你可以优化你的算法到对数时间复杂度吗?
    • +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + left, right = 0, n + while left < right: + mid = (left + right) >> 1 + if citations[mid] >= n - mid: + right = mid + else: + left = mid + 1 + return n - left +``` + +### **Java** + + + +```java +class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (citations[mid] >= n - mid) { + right = mid; + } else { + left = mid + 1; + } + } + return n - left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int hIndex(vector& citations) { + int n = citations.size(); + int left = 0, right = n; + while (left < right) { + int mid = left + right >> 1; + if (citations[mid] >= n - mid) { + right = mid; + } else { + left = mid + 1; + } + } + return n - left; + } +}; +``` + +### **Go** + +```go +func hIndex(citations []int) int { + n := len(citations) + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if citations[mid] >= n-mid { + right = mid + } else { + left = mid + 1 + } + } + return n - left +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0276.leetcode276 Paint Fence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0276.leetcode276 Paint Fence-zh.md" new file mode 100644 index 00000000..5b9829fb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0276.leetcode276 Paint Fence-zh.md" @@ -0,0 +1,81 @@ +# [276. 栅栏涂色](https://leetcode-cn.com/problems/paint-fence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0276.Paint%20Fence/README_EN.md) + +## 题目描述 + + + +

    k 种颜色的涂料和一个包含 n 个栅栏柱的栅栏,请你按下述规则为栅栏设计涂色方案:

    + +
      +
    • 每个栅栏柱可以用其中 一种 颜色进行上色。
    • +
    • 相邻的栅栏柱 最多连续两个 颜色相同。
    • +
    + +

    给你两个整数 kn ,返回所有有效的涂色 方案数

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, k = 2
    +输出:6
    +解释:所有的可能涂色方案如上图所示。注意,全涂红或者全涂绿的方案属于无效方案,因为相邻的栅栏柱 最多连续两个 颜色相同。
    +
    + +

    示例 2:

    + +
    +输入:n = 1, k = 1
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:n = 7, k = 2
    +输出:42
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 50
    • +
    • 1 <= k <= 105
    • +
    • 题目数据保证:对于输入的 nk ,其答案在范围 [0, 231 - 1]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0277.leetcode277 Find the Celebrity-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0277.leetcode277 Find the Celebrity-zh.md" new file mode 100644 index 00000000..3c85dc80 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0277.leetcode277 Find the Celebrity-zh.md" @@ -0,0 +1,95 @@ +# [277. 搜寻名人](https://leetcode-cn.com/problems/find-the-celebrity) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0277.Find%20the%20Celebrity/README_EN.md) + +## 题目描述 + + + +

    假设你是一个专业的狗仔,参加了一个 n 人派对,其中每个人被从 0 到 n - 1 标号。在这个派对人群当中可能存在一位 “名人”。所谓 “名人” 的定义是:其他所有 n - 1 个人都认识他/她,而他/她并不认识其他任何人。

    + +

    现在你想要确认这个 “名人” 是谁,或者确定这里没有 “名人”。而你唯一能做的就是问诸如 “A 你好呀,请问你认不认识 B呀?” 的问题,以确定 A 是否认识 B。你需要在(渐近意义上)尽可能少的问题内来确定这位 “名人” 是谁(或者确定这里没有 “名人”)。

    + +

    在本题中,你可以使用辅助函数 bool knows(a, b) 获取到 A 是否认识 B。请你来实现一个函数 int findCelebrity(n)

    + +

    派对最多只会有一个 “名人” 参加。若 “名人” 存在,请返回他/她的编号;若 “名人” 不存在,请返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入: graph = [
    +  [1,1,0],
    +  [0,1,0],
    +  [1,1,1]
    +]
    +输出: 1
    +解释: 有编号分别为 0、1 和 2 的三个人。graph[i][j] = 1 代表编号为 i 的人认识编号为 j 的人,而 graph[i][j] = 0 则代表编号为 i 的人不认识编号为 j 的人。“名人” 是编号 1 的人,因为 0 和 2 均认识他/她,但 1 不认识任何人。
    +
    + +

    示例 2:

    + +

    + +
    +输入: graph = [
    +  [1,0,1],
    +  [1,1,0],
    +  [0,1,1]
    +]
    +输出: -1
    +解释: 没有 “名人”
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == graph.length
    • +
    • n == graph[i].length
    • +
    • 2 <= n <= 100
    • +
    • graph[i][j]01.
    • +
    • graph[i][i] == 1
    • +
    + +

     

    + +

    进阶:如果允许调用 API knows 的最大次数为 3 * n ,你可以设计一个不超过最大调用次数的解决方案吗?

    + +
      +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0278.leetcode278 First Bad Version-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0278.leetcode278 First Bad Version-zh.md" new file mode 100644 index 00000000..c3ff6a8d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0278.leetcode278 First Bad Version-zh.md" @@ -0,0 +1,176 @@ +# [278. 第一个错误的版本](https://leetcode-cn.com/problems/first-bad-version) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0278.First%20Bad%20Version/README_EN.md) + +## 题目描述 + + + +

    你是产品经理,目前正在带领一个团队开发新的产品。不幸的是,你的产品的最新版本没有通过质量检测。由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的。

    + +

    假设你有 n 个版本 [1, 2, ..., n],你想找出导致之后所有版本出错的第一个错误的版本。

    + +

    你可以通过调用 bool isBadVersion(version) 接口来判断版本号 version 是否在单元测试中出错。实现一个函数来查找第一个错误的版本。你应该尽量减少对调用 API 的次数。

    + +

    示例:

    + +
    给定 n = 5,并且 version = 4 是第一个错误的版本。
    +
    +调用 isBadVersion(3) -> false
    +调用 isBadVersion(5) -> true
    +调用 isBadVersion(4) -> true
    +
    +所以,4 是第一个错误的版本。 
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return an integer +# def isBadVersion(version): + +class Solution: + def firstBadVersion(self, n): + """ + :type n: int + :rtype: int + """ + left, right = 1, n + while left < right: + mid = (left + right) >> 1 + if isBadVersion(mid): + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +/* The isBadVersion API is defined in the parent class VersionControl. + boolean isBadVersion(int version); */ + +public class Solution extends VersionControl { + public int firstBadVersion(int n) { + int left = 1, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +// The API isBadVersion is defined for you. +// bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **JavaScript** + +```js +/** + * Definition for isBadVersion() + * + * @param {integer} version number + * @return {boolean} whether the version is bad + * isBadVersion = function(version) { + * ... + * }; + */ + +/** + * @param {function} isBadVersion() + * @return {function} + */ +var solution = function(isBadVersion) { + /** + * @param {integer} n Total versions + * @return {integer} The first bad version + */ + return function(n) { + let left = 1; + let right = n; + while (left < right) { + const mid = (left + right) >>> 1; + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; +}; +``` + +### **Go** + +```go +/** + * Forward declaration of isBadVersion API. + * @param version your guess about first bad version + * @return true if current version is bad + * false if current version is good + * func isBadVersion(version int) bool; + */ + +func firstBadVersion(n int) int { + left, right := 1, n + for left < right { + mid := (left + right) >> 1 + if isBadVersion(mid) { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0279.leetcode279 Perfect Squares-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0279.leetcode279 Perfect Squares-zh.md" new file mode 100644 index 00000000..d86a0cdb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0279.leetcode279 Perfect Squares-zh.md" @@ -0,0 +1,136 @@ +# [279. 完全平方数](https://leetcode-cn.com/problems/perfect-squares) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0279.Perfect%20Squares/README_EN.md) + +## 题目描述 + + + +

    给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

    + +

    给你一个整数 n ,返回和为 n 的完全平方数的 最少数量

    + +

    完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,14916 都是完全平方数,而 311 不是。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 12
    +输出:3
    +解释:12 = 4 + 4 + 4
    + +

    示例 2:

    + +
    +输入:n = 13
    +输出:2
    +解释:13 = 4 + 9
    +  + +

    提示:

    + +
      +
    • 1 <= n <= 104
    • +
    + + +## 解法 + + + +动态规划,定义 `dp[i]` 表示和为 `i` 的完全平方数的最少数量。 + + + +### **Python3** + + + +```python +class Solution: + def numSquares(self, n: int) -> int: + dp = [0 for i in range(n + 1)] + for i in range(1, n + 1): + j, mi = 1, 0x3f3f3f3f + while j * j <= i: + mi = min(mi, dp[i - j * j]) + j += 1 + dp[i] = mi + 1 + return dp[n] +``` + +### **Java** + + + +```java +class Solution { + public int numSquares(int n) { + List ans = new ArrayList<>(); + ans.add(0); + while (ans.size() <= n) { + int m = ans.size(), val = Integer.MAX_VALUE; + for (int i = 1; i * i <= m; i++) { + val = Math.min(val, ans.get(m - i * i) + 1); + } + ans.add(val); + } + return ans.get(n); + } +} +``` + +### **TypeScript** + +```ts +function numSquares(n: number): number { + let dp = new Array(n + 1).fill(0); + for (let i = 1; i <= n; ++i) { + let min = Infinity; + for (let j = 1; j * j <= i; ++j) { + min = Math.min(min, dp[i - j * j]); + } + dp[i] = min + 1; + } + return dp.pop(); +}; +``` + +### **Go** + +```go +/* + * @lc app=leetcode.cn id=279 lang=golang + * 动态规划的思路,状态转移方程:dp[n] = min(dp[n-1*1]+1, dp[n-2*2]+1, ..., dp[n-k*k]+1), ( 0< k*k <=n ) + */ +func numSquares(n int) int { + if n <= 0 { + return 0 + } + dp := make([]int, n+1) // 多申请了一份整形,使代码更容易理解, dp[n] 就是 n 的完全平方数的求解 + for i := 1; i <= n; i++ { + dp[i] = i // 初始值 dp[n] 的最大值的解,也是最容易求的解 + for j := 0; j*j <= i; j++ { + dp[i] = minInt(dp[i-j*j]+1, dp[i]) + } + } + return dp[n] +} + +func minInt(x, y int) int { + if x < y { + return x + } + return y +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0280.leetcode280 Wiggle Sort-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0280.leetcode280 Wiggle Sort-zh.md" new file mode 100644 index 00000000..7913b5be --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0280.leetcode280 Wiggle Sort-zh.md" @@ -0,0 +1,93 @@ +# [280. 摆动排序](https://leetcode-cn.com/problems/wiggle-sort) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0280.Wiggle%20Sort/README_EN.md) + +## 题目描述 + + + +

    给你一个无序的数组 nums, 将该数字 原地 重排后使得 nums[0] <= nums[1] >= nums[2] <= nums[3]...

    + +

    示例:

    + +
    输入: nums = [3,5,2,1,6,4]
    +输出: 一个可能的解答是 [3,5,1,6,2,4]
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def wiggleSort(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + for i in range(1, len(nums)): + if (i % 2 == 1 and nums[i] < nums[i - 1]) or (i % 2 == 0 and nums[i] > nums[i - 1]): + nums[i], nums[i - 1] = nums[i - 1], nums[i] +``` + +### **Java** + + + +```java +class Solution { + public void wiggleSort(int[] nums) { + for (int i = 1; i < nums.length; ++i) { + if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { + swap(nums, i, i - 1); + } + } + } + + private void swap(int[] nums, int i, int j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + void wiggleSort(vector& nums) { + for (int i = 1; i < nums.size(); ++i) { + if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { + swap(nums[i], nums[i - 1]); + } + } + } +}; +``` + +### **Go** + +```go +func wiggleSort(nums []int) { + for i := 1; i < len(nums); i++ { + if (i%2 == 1 && nums[i] < nums[i-1]) || (i%2 == 0 && nums[i] > nums[i-1]) { + nums[i], nums[i-1] = nums[i-1], nums[i] + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0281.leetcode281 Zigzag Iterator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0281.leetcode281 Zigzag Iterator-zh.md" new file mode 100644 index 00000000..3c3fb759 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0281.leetcode281 Zigzag Iterator-zh.md" @@ -0,0 +1,131 @@ +# [281. 锯齿迭代器](https://leetcode-cn.com/problems/zigzag-iterator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0281.Zigzag%20Iterator/README_EN.md) + +## 题目描述 + + + +

    给出两个一维的向量,请你实现一个迭代器,交替返回它们中间的元素。

    + +

    示例:

    + +
    输入:
    +v1 = [1,2]
    +v2 = [3,4,5,6] 
    +
    +输出: [1,3,2,4,5,6]
    +
    +解析: 通过连续调用 next 函数直到 hasNext 函数返回 false,next 函数返回值的次序应依次为: [1,3,2,4,5,6]。
    + +

    拓展:假如给你 k 个一维向量呢?你的代码在这种情况下的扩展性又会如何呢?

    + +

    拓展声明:
    + “锯齿” 顺序对于 k > 2 的情况定义可能会有些歧义。所以,假如你觉得 “锯齿” 这个表述不妥,也可以认为这是一种 “循环”。例如:

    + +
    输入:
    +[1,2,3]
    +[4,5,6,7]
    +[8,9]
    +
    +输出: [1,4,8,2,5,9,3,6,7].
    +
    + +## 解法 + + + +定义 vectors 列表保存输入的所有一维向量,indexes 表示 vectors 列表每一项当前所遍历到的下标位置,cur 表示当前遍历到的 vector 列表,而 size 表示 vectors 列表元素个数。具体实现参考以下代码实现。 + + + +### **Python3** + + + +```python +class ZigzagIterator: + def __init__(self, v1: List[int], v2: List[int]): + self.cur = 0 + self.size = 2 + self.indexes = [0] * self.size + self.vectors = [v1, v2] + + def next(self) -> int: + vector = self.vectors[self.cur] + index = self.indexes[self.cur] + res = vector[index] + self.indexes[self.cur] = index + 1 + self.cur = (self.cur + 1) % self.size + return res + + def hasNext(self) -> bool: + start = self.cur + while self.indexes[self.cur] == len(self.vectors[self.cur]): + self.cur = (self.cur + 1) % self.size + if self.cur == start: + return False + return True + + +# Your ZigzagIterator object will be instantiated and called as such: +# i, v = ZigzagIterator(v1, v2), [] +# while i.hasNext(): v.append(i.next()) +``` + +### **Java** + + + +```java +public class ZigzagIterator { + private int cur; + private int size; + private List indexes = new ArrayList<>(); + private List> vectors = new ArrayList<>(); + + public ZigzagIterator(List v1, List v2) { + cur = 0; + size = 2; + indexes.add(0); + indexes.add(0); + vectors.add(v1); + vectors.add(v2); + } + + public int next() { + List vector = vectors.get(cur); + int index = indexes.get(cur); + int res = vector.get(index); + indexes.set(cur, index + 1); + cur = (cur + 1) % size; + return res; + } + + public boolean hasNext() { + int start = cur; + while (indexes.get(cur) == vectors.get(cur).size()) { + cur = (cur + 1) % size; + if (start == cur) { + return false; + } + } + return true; + } +} + +/** + * Your ZigzagIterator object will be instantiated and called as such: + * ZigzagIterator i = new ZigzagIterator(v1, v2); + * while (i.hasNext()) v[f()] = i.next(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0282.leetcode282 Expression Add Operators-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0282.leetcode282 Expression Add Operators-zh.md" new file mode 100644 index 00000000..92b90cfc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0282.leetcode282 Expression Add Operators-zh.md" @@ -0,0 +1,83 @@ +# [282. 给表达式添加运算符](https://leetcode-cn.com/problems/expression-add-operators) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0282.Expression%20Add%20Operators/README_EN.md) + +## 题目描述 + + + +

    给定一个仅包含数字 0-9 的字符串和一个目标值,在数字之间添加 二元 运算符(不是一元)+- 或 * ,返回所有能够得到目标值的表达式。

    + +

     

    + +

    示例 1:

    + +
    +输入: num = "123", target = 6
    +输出: ["1+2+3", "1*2*3"] 
    +
    + +

    示例 2:

    + +
    +输入: num = "232", target = 8
    +输出: ["2*3+2", "2+3*2"]
    + +

    示例 3:

    + +
    +输入: num = "105", target = 5
    +输出: ["1*0+5","10-5"]
    + +

    示例 4:

    + +
    +输入: num = "00", target = 0
    +输出: ["0+0", "0-0", "0*0"]
    +
    + +

    示例 5:

    + +
    +输入: num = "3456237490", target = 9191
    +输出: []
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= num.length <= 10
    • +
    • num 仅含数字
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0283.leetcode283 Move Zeroes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0283.leetcode283 Move Zeroes-zh.md" new file mode 100644 index 00000000..8a46200b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0283.leetcode283 Move Zeroes-zh.md" @@ -0,0 +1,106 @@ +# [283. 移动零](https://leetcode-cn.com/problems/move-zeroes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0283.Move%20Zeroes/README_EN.md) + +## 题目描述 + + + +

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

    + +

    示例:

    + +
    输入: [0,1,0,3,12]
    +输出: [1,3,12,0,0]
    + +

    说明:

    + +
      +
    1. 必须在原数组上操作,不能拷贝额外的数组。
    2. +
    3. 尽量减少操作次数。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + if not nums: + return + n = len(nums) + zero_count = 0 + for i in range(n): + if nums[i] == 0: + zero_count += 1 + else: + nums[i - zero_count] = nums[i] + while zero_count > 0: + nums[n - zero_count] = 0 + zero_count -= 1 +``` + +### **Java** + + + +```java +class Solution { + public void moveZeroes(int[] nums) { + int n; + if (nums == null || (n = nums.length) < 1) { + return; + } + int zeroCount = 0; + for (int i = 0; i < n; ++i) { + if (nums[i] == 0) { + ++zeroCount; + } else { + nums[i - zeroCount] = nums[i]; + } + } + while (zeroCount > 0) { + nums[n - zeroCount--] = 0; + } + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function (nums) { + if (!nums.length) return nums; + let j = 0; + for (i = 0; i < nums.length; i++) { + if (nums[i]) { + if (i > j) [nums[i], nums[j]] = [nums[j], nums[i]]; + j++; + } + } + return nums; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0284.leetcode284 Peeking Iterator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0284.leetcode284 Peeking Iterator-zh.md" new file mode 100644 index 00000000..f0e126fd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0284.leetcode284 Peeking Iterator-zh.md" @@ -0,0 +1,152 @@ +# [284. 顶端迭代器](https://leetcode-cn.com/problems/peeking-iterator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0284.Peeking%20Iterator/README_EN.md) + +## 题目描述 + + + +

    给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。

    + +

    示例:

    + +
    假设迭代器被初始化为列表 [1,2,3]。
    +
    +调用 next() 返回 1,得到列表中的第一个元素。
    +现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
    +最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false。
    +
    + +

    进阶:你将如何拓展你的设计?使之变得通用化,从而适应所有的类型,而不只是整数型?

    + +## 解法 + + + + + +### **Python3** + + + +```python +# Below is the interface for Iterator, which is already defined for you. +# +# class Iterator: +# def __init__(self, nums): +# """ +# Initializes an iterator object to the beginning of a list. +# :type nums: List[int] +# """ +# +# def hasNext(self): +# """ +# Returns true if the iteration has more elements. +# :rtype: bool +# """ +# +# def next(self): +# """ +# Returns the next element in the iteration. +# :rtype: int +# """ + +class PeekingIterator: + def __init__(self, iterator): + """ + Initialize your data structure here. + :type iterator: Iterator + """ + self.iterator = iterator + self.has_peeked = False + self.peeked_element = None + + def peek(self): + """ + Returns the next element in the iteration without advancing the iterator. + :rtype: int + """ + if not self.has_peeked: + self.peeked_element = self.iterator.next() + self.has_peeked = True + return self.peeked_element + + def next(self): + """ + :rtype: int + """ + if not self.has_peeked: + return self.iterator.next() + result = self.peeked_element + self.has_peeked = False + self.peeked_element = None + return result + + def hasNext(self): + """ + :rtype: bool + """ + return self.has_peeked or self.iterator.hasNext() + + +# Your PeekingIterator object will be instantiated and called as such: +# iter = PeekingIterator(Iterator(nums)) +# while iter.hasNext(): +# val = iter.peek() # Get the next element but not advance the iterator. +# iter.next() # Should return the same value as [val]. +``` + +### **Java** + + + +```java +// Java Iterator interface reference: +// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html + +class PeekingIterator implements Iterator { + private Iterator iterator; + private boolean hasPeeked; + private Integer peekedElement; + + public PeekingIterator(Iterator iterator) { + // initialize any member here. + this.iterator = iterator; + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + if (!hasPeeked) { + peekedElement = iterator.next(); + hasPeeked = true; + } + return peekedElement; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + if (!hasPeeked) { + return iterator.next(); + } + Integer result = peekedElement; + hasPeeked = false; + peekedElement = null; + return result; + } + + @Override + public boolean hasNext() { + return hasPeeked || iterator.hasNext(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0285.leetcode285 Inorder Successor in BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0285.leetcode285 Inorder Successor in BST-zh.md" new file mode 100644 index 00000000..72c2104b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0285.leetcode285 Inorder Successor in BST-zh.md" @@ -0,0 +1,120 @@ +# [285. 二叉搜索树中的中序后继](https://leetcode-cn.com/problems/inorder-successor-in-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0285.Inorder%20Successor%20in%20BST/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉搜索树和其中的一个节点 p ,找到该节点在树中的中序后继。如果节点没有中序后继,请返回 null

    + +

    节点 p 的后继是值比 p.val 大的节点中键值最小的节点。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [2,1,3], p = 1
    +输出:2
    +解释:这里 1 的中序后继是 2。请注意 p 和返回值都应是 TreeNode 类型。
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [5,3,6,2,4,null,null,1], p = 6
    +输出:null
    +解释:因为给出的节点没有中序后继,所以答案就返回 null 了。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在范围 [1, 104] 内。
    • +
    • -105 <= Node.val <= 105
    • +
    • 树中各节点的值均保证唯一。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @return {TreeNode} + */ +var inorderSuccessor = function (root, p) { + function findMin(root) { + if (!root) { + return null; + } + while (root.left) { + root = root.left; + } + return root; + } + if (!root) { + return null; + } + let successor = null; + while (root) { + if (root.val > p.val) { + successor = root; + root = root.left; + } else if (root.val < p.val) { + root = root.right; + } else { + if (root.right) { + successor = findMin(root.right); + } + break; + } + } + return successor; +}; +``` + + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0286.leetcode286 Walls and Gates-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0286.leetcode286 Walls and Gates-zh.md" new file mode 100644 index 00000000..dcc8cce1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0286.leetcode286 Walls and Gates-zh.md" @@ -0,0 +1,89 @@ +# [286. 墙与门](https://leetcode-cn.com/problems/walls-and-gates) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0286.Walls%20and%20Gates/README_EN.md) + +## 题目描述 + + + +

    你被给定一个 m × n 的二维网格 rooms ,网格中有以下三种可能的初始化值:

    + +
      +
    1. -1 表示墙或是障碍物
    2. +
    3. 0 表示一扇门
    4. +
    5. INF 无限表示一个空的房间。然后,我们用 231 - 1 = 2147483647 代表 INF。你可以认为通往门的距离总是小于 2147483647 的。
    6. +
    + +

    你要给每个空房间位上填上该房间到 最近门的距离 ,如果无法到达门,则填 INF 即可。

    + +

     

    + +

    示例 1:

    + +
    +输入:rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
    +输出:[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
    +
    + +

    示例 2:

    + +
    +输入:rooms = [[-1]]
    +输出:[[-1]]
    +
    + +

    示例 3:

    + +
    +输入:rooms = [[2147483647]]
    +输出:[[2147483647]]
    +
    + +

    示例 4:

    + +
    +输入:rooms = [[0]]
    +输出:[[0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == rooms.length
    • +
    • n == rooms[i].length
    • +
    • 1 <= m, n <= 250
    • +
    • rooms[i][j]-10231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0287.leetcode287 Find the Duplicate Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0287.leetcode287 Find the Duplicate Number-zh.md" new file mode 100644 index 00000000..18afdec6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0287.leetcode287 Find the Duplicate Number-zh.md" @@ -0,0 +1,146 @@ +# [287. 寻找重复数](https://leetcode-cn.com/problems/find-the-duplicate-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0287.Find%20the%20Duplicate%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个包含 n + 1 个整数的数组 nums ,其数字都在 1n 之间(包括 1n),可知至少存在一个重复的整数。

    + +

    假设 nums 只有 一个重复的整数 ,找出 这个重复的数

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,4,2,2]
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,1,3,4,2]
    +输出:3
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,1]
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:nums = [1,1,2]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 3 * 104
    • +
    • nums.length == n + 1
    • +
    • 1 <= nums[i] <= n
    • +
    • nums只有一个整数 出现 两次或多次 ,其余整数均只出现 一次
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 如何证明 nums 中至少存在一个重复的数字?
    • +
    • 你可以在不修改数组 nums 的情况下解决这个问题吗?
    • +
    • 你可以只用常量级 O(1) 的额外空间解决这个问题吗?
    • +
    • 你可以设计一个时间复杂度小于 O(n2) 的解决方案吗?
    • +
    + + +## 解法 + + + +二分法。 + +如果值范围在 `[1, mid]` 的数小于等于 mid,说明此范围内没有重复的数,否则说明有重复数。 + + + +### **Python3** + + + +```python +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + while l < r: + mid = (l + r) >> 1 + cnt = 0 + for e in nums: + if e <= mid: + cnt += 1 + if cnt <= mid: + l = mid + 1 + else: + r = mid + return l +``` + +### **Java** + + + +```java +class Solution { + public int findDuplicate(int[] nums) { + int l = 1, r = nums.length - 1; + while (l < r) { + int mid = (l + r) >>> 1; + int cnt = 0; + for (int e : nums) { + if (e <= mid) ++cnt; + } + if (cnt <= mid) l = mid + 1; + else r = mid; + } + return l; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findDuplicate(vector& nums) { + int l = 0, r = nums.size() - 1; + while (l < r) { + int mid = l + ((r - l) >> 1); + int cnt = 0; + for (auto e : nums) { + if (e <= mid) ++cnt; + } + if (cnt <= mid) l = mid + 1; + else r = mid; + } + return l; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0288.leetcode288 Unique Word Abbreviation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0288.leetcode288 Unique Word Abbreviation-zh.md" new file mode 100644 index 00000000..bd2c8f7e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0288.leetcode288 Unique Word Abbreviation-zh.md" @@ -0,0 +1,154 @@ +# [288. 单词的唯一缩写](https://leetcode-cn.com/problems/unique-word-abbreviation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0288.Unique%20Word%20Abbreviation/README_EN.md) + +## 题目描述 + + + +

    单词的 缩写 需要遵循 <起始字母><中间字母数><结尾字母> 这样的格式。如果单词只有两个字符,那么它就是它自身的 缩写

    + +

    以下是一些单词缩写的范例:

    + +
      +
    • dog --> d1g 因为第一个字母 'd' 和最后一个字母 'g' 之间有 1 个字母
    • +
    • internationalization --> i18n 因为第一个字母 'i' 和最后一个字母 'n' 之间有 18 个字母
    • +
    • it --> it 单词只有两个字符,它就是它自身的 缩写
    • +
    + +

     

    + +

    实现 ValidWordAbbr 类:

    + +
      +
    • ValidWordAbbr(String[] dictionary) 使用单词字典 dictionary 初始化对象
    • +
    • boolean isUnique(string word) 如果满足下述任意一个条件,返回 true ;否则,返回 false : +
        +
      • 字典 dictionary 中没有任何其他单词的 缩写 与该单词 word缩写 相同。
      • +
      • 字典 dictionary 中的所有 缩写 与该单词 word缩写 相同的单词都与 word 相同
      • +
      +
    • +
    + +

     

    + +

    示例:

    + +
    +输入
    +["ValidWordAbbr", "isUnique", "isUnique", "isUnique", "isUnique"]
    +[[["deer", "door", "cake", "card"]], ["dear"], ["cart"], ["cane"], ["make"]]
    +输出
    +[null, false, true, false, true]
    +
    +解释
    +ValidWordAbbr validWordAbbr = new ValidWordAbbr(["deer", "door", "cake", "card"]);
    +validWordAbbr.isUnique("dear"); // 返回 false,字典中的 "deer" 与输入 "dear" 的缩写都是 "d2r",但这两个单词不相同
    +validWordAbbr.isUnique("cart"); // 返回 true,字典中不存在缩写为 "c2t" 的单词
    +validWordAbbr.isUnique("cane"); // 返回 false,字典中的 "cake" 与输入 "cane" 的缩写都是 "c2e",但这两个单词不相同
    +validWordAbbr.isUnique("make"); // 返回 true,字典中不存在缩写为 "m2e" 的单词
    +validWordAbbr.isUnique("cake"); // 返回 true,因为 "cake" 已经存在于字典中,并且字典中没有其他缩写为 "c2e" 的单词
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= dictionary.length <= 3 * 104
    • +
    • 1 <= dictionary[i].length <= 20
    • +
    • dictionary[i] 由小写英文字母组成
    • +
    • 1 <= word <= 20
    • +
    • word 由小写英文字母组成
    • +
    • 最多调用 5000isUnique
    • +
    + +## 解法 + + + +哈希表实现,其中 key 存放单词缩写,value 存放单词缩写所对应的所有单词的集合。 + + + +### **Python3** + + + +```python +class ValidWordAbbr: + + def __init__(self, dictionary: List[str]): + self.words = {} + for word in dictionary: + abbr = self._word_abbr(word) + vals = self.words.get(abbr, set()) + vals.add(word) + self.words[abbr] = vals + + def isUnique(self, word: str) -> bool: + abbr = self._word_abbr(word) + vals = self.words.get(abbr) + return vals is None or (len(vals) == 1 and word in vals) + + def _word_abbr(self, word: str) -> str: + n = len(word) + if n < 3: + return word + return f'{word[0]}{n - 2}{word[n - 1]}' + + +# Your ValidWordAbbr object will be instantiated and called as such: +# obj = ValidWordAbbr(dictionary) +# param_1 = obj.isUnique(word) +``` + +### **Java** + + + +```java +class ValidWordAbbr { + private Map> words; + + public ValidWordAbbr(String[] dictionary) { + words = new HashMap<>(); + for (String word : dictionary) { + String abbr = wordAbbr(word); + Set vals = words.getOrDefault(abbr, new HashSet<>()); + vals.add(word); + words.put(abbr, vals); + } + } + + public boolean isUnique(String word) { + String abbr = wordAbbr(word); + Set vals = words.get(abbr); + return vals == null || (vals.size() == 1 && vals.contains(word)); + } + + private String wordAbbr(String word) { + int n = word.length(); + if (n < 3) { + return word; + } + StringBuilder sb = new StringBuilder(); + sb.append(word.charAt(0)).append(n - 2).append(word.charAt(n - 1)); + return sb.toString(); + } +} + +/** + * Your ValidWordAbbr object will be instantiated and called as such: + * ValidWordAbbr obj = new ValidWordAbbr(dictionary); + * boolean param_1 = obj.isUnique(word); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0289.leetcode289 Game of Life-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0289.leetcode289 Game of Life-zh.md" new file mode 100644 index 00000000..3b54c430 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0289.leetcode289 Game of Life-zh.md" @@ -0,0 +1,87 @@ +# [289. 生命游戏](https://leetcode-cn.com/problems/game-of-life) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0289.Game%20of%20Life/README_EN.md) + +## 题目描述 + + + +

    根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。

    + +

    给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:

    + +
      +
    1. 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
    2. +
    3. 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
    4. +
    5. 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
    6. +
    7. 如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
    8. +
    + +

    下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。给你 m x n 网格面板 board 的当前状态,返回下一个状态。

    + +

     

    + +

    示例 1:

    + +
    +输入:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
    +输出:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
    +
    + +

    示例 2:

    + +
    +输入:board = [[1,1],[1,0]]
    +输出:[[1,1],[1,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == board.length
    • +
    • n == board[i].length
    • +
    • 1 <= m, n <= 25
    • +
    • board[i][j]01
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以使用原地算法解决本题吗?请注意,面板上所有格子需要同时被更新:你不能先更新某些格子,然后使用它们的更新后的值再更新其他格子。
    • +
    • 本题中,我们使用二维数组来表示面板。原则上,面板是无限的,但当活细胞侵占了面板边界时会造成问题。你将如何解决这些问题?
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0290.leetcode290 Word Pattern-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0290.leetcode290 Word Pattern-zh.md" new file mode 100644 index 00000000..341dcb06 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0290.leetcode290 Word Pattern-zh.md" @@ -0,0 +1,101 @@ +# [290. 单词规律](https://leetcode-cn.com/problems/word-pattern) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0290.Word%20Pattern/README_EN.md) + +## 题目描述 + + + +

    给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。

    + +

    这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

    + +

    示例1:

    + +
    输入: pattern = "abba", str = "dog cat cat dog"
    +输出: true
    + +

    示例 2:

    + +
    输入:pattern = "abba", str = "dog cat cat fish"
    +输出: false
    + +

    示例 3:

    + +
    输入: pattern = "aaaa", str = "dog cat cat dog"
    +输出: false
    + +

    示例 4:

    + +
    输入: pattern = "abba", str = "dog dog dog dog"
    +输出: false
    + +

    说明:
    +你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。    

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + ch2str, str2ch = {}, {} + ss = s.split(' ') + n = len(pattern) + if n != len(ss): + return False + for i in range(n): + if ch2str.get(pattern[i]) is not None and ch2str.get(pattern[i]) != ss[i]: + return False + if str2ch.get(ss[i]) is not None and str2ch.get(ss[i]) != pattern[i]: + return False + ch2str[pattern[i]] = ss[i] + str2ch[ss[i]] = pattern[i] + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean wordPattern(String pattern, String s) { + Map ch2str = new HashMap<>(); + Map str2ch = new HashMap<>(); + String[] ss = s.split(" "); + int n = pattern.length(); + if (n != ss.length) { + return false; + } + for (int i = 0; i < n; ++i) { + char ch = pattern.charAt(i); + if (ch2str.containsKey(ch) && !ch2str.get(ch).equals(ss[i])) { + return false; + } + if (str2ch.containsKey(ss[i]) && !str2ch.get(ss[i]).equals(ch)) { + return false; + } + ch2str.put(ch, ss[i]); + str2ch.put(ss[i], ch); + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0291.leetcode291 Word Pattern II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0291.leetcode291 Word Pattern II-zh.md" new file mode 100644 index 00000000..0b25c8a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0291.leetcode291 Word Pattern II-zh.md" @@ -0,0 +1,90 @@ +# [291. 单词规律 II](https://leetcode-cn.com/problems/word-pattern-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0291.Word%20Pattern%20II/README_EN.md) + +## 题目描述 + + + +

    给你一种规律 pattern 和一个字符串 str,请你判断 str 是否遵循其相同的规律。

    + +

    这里我们指的是 完全遵循,例如 pattern 里的每个字母和字符串 str 中每个 非空 单词之间,存在着 双射 的对应规律。双射 意味着映射双方一一对应,不会存在两个字符映射到同一个字符串,也不会存在一个字符分别映射到两个不同的字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:pattern = "abab", s = "redblueredblue"
    +输出:true
    +解释:一种可能的映射如下:
    +'a' -> "red"
    +'b' -> "blue"
    + +

    示例 2:

    + +
    +输入:pattern = "aaaa", s = "asdasdasdasd"
    +输出:true
    +解释:一种可能的映射如下:
    +'a' -> "asd"
    +
    + +

    示例 3:

    + +
    +输入:pattern = "abab", s = "asdasdasdasd"
    +输出:true
    +解释:一种可能的映射如下:
    +'a' -> "a"
    +'b' -> "sdasd"
    +注意 'a' 和 'b' 不能同时映射到 "asd",因为这里的映射是一种双射。
    +
    + +

    示例 4:

    + +
    +输入:pattern = "aabb", s = "xyzabcxzyabc"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= pattern.length <= 20
    • +
    • 0 <= s.length <= 50
    • +
    • patterns 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0292.leetcode292 Nim Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0292.leetcode292 Nim Game-zh.md" new file mode 100644 index 00000000..a07131af --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0292.leetcode292 Nim Game-zh.md" @@ -0,0 +1,82 @@ +# [292. Nim 游戏](https://leetcode-cn.com/problems/nim-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0292.Nim%20Game/README_EN.md) + +## 题目描述 + + + +

    你和你的朋友,两个人一起玩 Nim 游戏

    + +
      +
    • 桌子上有一堆石头。
    • +
    • 你们轮流进行自己的回合,你作为先手。
    • +
    • 每一回合,轮到的人拿掉 1 - 3 块石头。
    • +
    • 拿掉最后一块石头的人就是获胜者。
    • +
    + +

    假设你们每一步都是最优解。请编写一个函数,来判断你是否可以在给定石头数量为 n 的情况下赢得游戏。如果可以赢,返回 true;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 4
    +输出:false 
    +解释:如果堆中有 4 块石头,那么你永远不会赢得比赛;
    +     因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
    +
    + +

    示例 2:

    + +
    +输入:n = 1
    +输出:true
    +
    + +

    示例 3:

    + +
    +输入:n = 2
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0293.leetcode293 Flip Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0293.leetcode293 Flip Game-zh.md" new file mode 100644 index 00000000..c7617247 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0293.leetcode293 Flip Game-zh.md" @@ -0,0 +1,92 @@ +# [293. 翻转游戏](https://leetcode-cn.com/problems/flip-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0293.Flip%20Game/README_EN.md) + +## 题目描述 + + + +

    你和朋友玩一个叫做「翻转游戏」的游戏。游戏规则如下:

    + +

    给你一个字符串 currentState ,其中只含 '+''-' 。你和朋友轮流将 连续 的两个 "++" 反转成 "--" 。当一方无法进行有效的翻转时便意味着游戏结束,则另一方获胜。

    + +

    计算并返回 一次有效操作 后,字符串 currentState 所有的可能状态,返回结果可以按 任意顺序 排列。如果不存在可能的有效操作,请返回一个空列表 []

    + +

     

    + +

    示例 1:

    + +
    +输入:currentState = "++++"
    +输出:["--++","+--+","++--"]
    +
    + +

    示例 2:

    + +
    +输入:currentState = "+"
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= currentState.length <= 500
    • +
    • currentState[i] 不是 '+' 就是 '-'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def generatePossibleNextMoves(self, s: str) -> List[str]: + if not s or len(s) < 2: + return [] + n = len(s) + res = [] + for i in range(n - 1): + if s[i] == '+' and s[i + 1] == '+': + res.append(s[:i] + "--" + s[i + 2:]) + return res +``` + +### **Java** + + + +```java +class Solution { + public List generatePossibleNextMoves(String s) { + int n; + if (s == null || (n = s.length()) < 2) return Collections.emptyList(); + List res = new ArrayList<>(); + for (int i = 0; i < n - 1; ++i) { + if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') { + StringBuilder sb = new StringBuilder(s); + sb.replace(i, i + 2, "--"); + res.add(sb.toString()); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0294.leetcode294 Flip Game II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0294.leetcode294 Flip Game II-zh.md" new file mode 100644 index 00000000..a40de846 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0294.leetcode294 Flip Game II-zh.md" @@ -0,0 +1,72 @@ +# [294. 翻转游戏 II](https://leetcode-cn.com/problems/flip-game-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0294.Flip%20Game%20II/README_EN.md) + +## 题目描述 + + + +

    你和朋友玩一个叫做「翻转游戏」的游戏。游戏规则如下:

    + +

    给你一个字符串 currentState ,其中只含 '+''-' 。你和朋友轮流将 连续 的两个 "++" 反转成 "--" 。当一方无法进行有效的翻转时便意味着游戏结束,则另一方获胜。

    + +

    请你写出一个函数来判定起始玩家 是否存在必胜的方案 :如果存在,返回 true ;否则,返回 false

    +  + +

    示例 1:

    + +
    +输入:currentState = "++++"
    +输出:true
    +解释:起始玩家可将中间的 "++" 翻转变为 "+--+" 从而得胜。
    + +

    示例 2:

    + +
    +输入:currentState = "+"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= currentState.length <= 60
    • +
    • currentState[i] 不是 '+' 就是 '-'
    • +
    + +

     

    + +

    进阶:请推导你算法的时间复杂度。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0295.leetcode295 Find Median from Data Stream-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0295.leetcode295 Find Median from Data Stream-zh.md" new file mode 100644 index 00000000..e85bff54 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0295.leetcode295 Find Median from Data Stream-zh.md" @@ -0,0 +1,126 @@ +# [295. 数据流的中位数](https://leetcode-cn.com/problems/find-median-from-data-stream) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0295.Find%20Median%20from%20Data%20Stream/README_EN.md) + +## 题目描述 + + + +

    中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。

    + +

    例如,

    + +

    [2,3,4] 的中位数是 3

    + +

    [2,3] 的中位数是 (2 + 3) / 2 = 2.5

    + +

    设计一个支持以下两种操作的数据结构:

    + +
      +
    • void addNum(int num) - 从数据流中添加一个整数到数据结构中。
    • +
    • double findMedian() - 返回目前所有元素的中位数。
    • +
    + +

    示例:

    + +
    addNum(1)
    +addNum(2)
    +findMedian() -> 1.5
    +addNum(3) 
    +findMedian() -> 2
    + +

    进阶:

    + +
      +
    1. 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
    2. +
    3. 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
    4. +
    + +## 解法 + + + +- 创建大根堆、小根堆,其中:大根堆存放较小的一半元素,小根堆存放较大的一半元素。 +- 添加元素时,先放入小根堆,然后将小根堆对顶元素弹出并放入大根堆(使得大根堆个数多 1);若大小根堆元素个数差超过 1,则将大根堆元素弹出放入小根堆。 +- 取中位数时,若大根堆元素较多,取大根堆堆顶,否则取两堆顶元素和的平均值。 + + + +### **Python3** + + + +```python +class MedianFinder: + + def __init__(self): + """ + initialize your data structure here. + """ + self.min_heap = [] + self.max_heap = [] + + def addNum(self, num: int) -> None: + heapq.heappush(self.min_heap, num) + heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap)) + if len(self.max_heap) - len(self.min_heap) > 1: + heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap)) + + def findMedian(self) -> float: + if len(self.max_heap) > len(self.min_heap): + return -self.max_heap[0] + return (self.min_heap[0] - self.max_heap[0]) / 2 + + +# Your MedianFinder object will be instantiated and called as such: +# obj = MedianFinder() +# obj.addNum(num) +# param_2 = obj.findMedian() +``` + +### **Java** + + + +```java +class MedianFinder { + private PriorityQueue minHeap; + private PriorityQueue maxHeap; + + /** initialize your data structure here. */ + public MedianFinder() { + minHeap = new PriorityQueue<>(); + maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + } + + public void addNum(int num) { + minHeap.offer(num); + maxHeap.offer(minHeap.poll()); + if (maxHeap.size() - minHeap.size() > 1) { + minHeap.offer(maxHeap.poll()); + } + } + + public double findMedian() { + if (maxHeap.size() > minHeap.size()) { + return maxHeap.peek(); + } + return (minHeap.peek() + maxHeap.peek()) * 1.0 / 2; + } +} + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder obj = new MedianFinder(); + * obj.addNum(num); + * double param_2 = obj.findMedian(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0296.leetcode296 Best Meeting Point-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0296.leetcode296 Best Meeting Point-zh.md" new file mode 100644 index 00000000..b65a0636 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0296.leetcode296 Best Meeting Point-zh.md" @@ -0,0 +1,59 @@ +# [296. 最佳的碰头地点](https://leetcode-cn.com/problems/best-meeting-point) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0296.Best%20Meeting%20Point/README_EN.md) + +## 题目描述 + + + +

    有一队人(两人或以上)想要在一个地方碰面,他们希望能够最小化他们的总行走距离。

    + +

    给你一个 2D 网格,其中各个格子内的值要么是 0,要么是 1。

    + +

    1 表示某个人的家所处的位置。这里,我们将使用 曼哈顿距离 来计算,其中 distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|

    + +

    示例:

    + +
    输入: 
    +
    +1 - 0 - 0 - 0 - 1
    +|   |   |   |   |
    +0 - 0 - 0 - 0 - 0
    +|   |   |   |   |
    +0 - 0 - 1 - 0 - 0
    +
    +输出: 6 
    +
    +解析: 给定的三个人分别住在(0,0)(0,4) (2,2):
    +     (0,2) 是一个最佳的碰面点,其总行走距离为 2 + 2 + 2 = 6,最小,因此返回 6。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0297.leetcode297 Serialize and Deserialize Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0297.leetcode297 Serialize and Deserialize Binary Tree-zh.md" new file mode 100644 index 00000000..e0bdd901 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0297.leetcode297 Serialize and Deserialize Binary Tree-zh.md" @@ -0,0 +1,83 @@ +# [297. 二叉树的序列化与反序列化](https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0297.Serialize%20and%20Deserialize%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。

    + +

    请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。

    + +

    提示: 输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2,3,null,null,4,5]
    +输出:[1,2,3,null,null,4,5]
    +
    + +

    示例 2:

    + +
    +输入:root = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:root = [1]
    +输出:[1]
    +
    + +

    示例 4:

    + +
    +输入:root = [1,2]
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中结点数在范围 [0, 104]
    • +
    • -1000 <= Node.val <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0298.leetcode298 Binary Tree Longest Consecutive Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0298.leetcode298 Binary Tree Longest Consecutive Sequence-zh.md" new file mode 100644 index 00000000..8679c0a0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0298.leetcode298 Binary Tree Longest Consecutive Sequence-zh.md" @@ -0,0 +1,76 @@ +# [298. 二叉树最长连续序列](https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0298.Binary%20Tree%20Longest%20Consecutive%20Sequence/README_EN.md) + +## 题目描述 + + + +

    给你一棵指定的二叉树,请你计算它最长连续序列路径的长度。

    + +

    该路径,可以是从某个初始结点到树中任意结点,通过「父 - 子」关系连接而产生的任意路径。

    + +

    这个最长连续的路径,必须从父结点到子结点,反过来是不可以的。

    + +

    示例 1:

    + +
    输入:
    +
    +   1
    +    \
    +     3
    +    / \
    +   2   4
    +        \
    +         5
    +
    +输出: 3
    +
    +解析: 当中,最长连续序列是 3-4-5,所以返回结果为 3
    + +

    示例 2:

    + +
    输入:
    +
    +   2
    +    \
    +     3
    +    / 
    +   2    
    +  / 
    + 1
    +
    +输出: 2 
    +
    +解析: 当中,最长连续序列是 2-3。注意,不是 3-2-1,所以返回 2。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0299.leetcode299 Bulls and Cows-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0299.leetcode299 Bulls and Cows-zh.md" new file mode 100644 index 00000000..02f9bac7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0299.leetcode299 Bulls and Cows-zh.md" @@ -0,0 +1,108 @@ +# [299. 猜数字游戏](https://leetcode-cn.com/problems/bulls-and-cows) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0200-0299/0299.Bulls%20and%20Cows/README_EN.md) + +## 题目描述 + + + +

    你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下:

    + +
      +
    1. 你写出一个秘密数字,并请朋友猜这个数字是多少。
    2. +
    3. 朋友每猜测一次,你就会给他一个提示,告诉他的猜测数字中有多少位属于数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位属于数字猜对了但是位置不对(称为“Cows”, 奶牛)。
    4. +
    5. 朋友根据提示继续猜,直到猜出秘密数字。
    6. +
    + +

    请写出一个根据秘密数字和朋友的猜测数返回提示的函数,返回字符串的格式为 xAyBxy 都是数字,A 表示公牛,用 B 表示奶牛。

    + +
      +
    • xA 表示有 x 位数字出现在秘密数字中,且位置都与秘密数字一致。
    • +
    • yB 表示有 y 位数字出现在秘密数字中,但位置与秘密数字不一致。
    • +
    + +

    请注意秘密数字和朋友的猜测数都可能含有重复数字,每位数字只能统计一次。

    + +

     

    + +

    示例 1:

    + +
    输入: secret = "1807", guess = "7810"
    +输出: "1A3B"
    +解释: 1 公牛和 3 奶牛。公牛是 8,奶牛是 0, 1 和 7
    + +

    示例 2:

    + +
    输入: secret = "1123", guess = "0111"
    +输出: "1A1B"
    +解释: 朋友猜测数中的第一个 1 是公牛,第二个或第三个 1 可被视为奶牛。
    + +

     

    + +

    说明: 你可以假设秘密数字和朋友的猜测数都只包含数字,并且它们的长度永远相等。

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def getHint(self, secret: str, guess: str) -> str: + a_cnt = b_cnt = 0 + nums1 = dict() + nums2 = dict() + for i in range(len(secret)): + if secret[i] == guess[i]: + a_cnt += 1 + else: + nums1[secret[i]] = nums1.get(secret[i], 0) + 1 + nums2[guess[i]] = nums2.get(guess[i], 0) + 1 + for i, v in nums1.items(): + if i in nums2: + b_cnt += min(v, nums2[i]) + return f'{a_cnt}A{b_cnt}B' +``` + +### **Java** + + + +```java +class Solution { + public String getHint(String secret, String guess) { + int aCnt = 0, bCnt = 0; + Map nums1 = new HashMap<>(); + Map nums2 = new HashMap<>(); + for (int i = 0; i < secret.length(); ++i) { + if (secret.charAt(i) == guess.charAt(i)) { + ++aCnt; + } else { + nums1.put(secret.charAt(i), nums1.getOrDefault(secret.charAt(i), 0) + 1); + nums2.put(guess.charAt(i), nums2.getOrDefault(guess.charAt(i), 0) + 1); + } + } + + for (Map.Entry entry : nums1.entrySet()) { + if (nums2.containsKey(entry.getKey())) { + bCnt += Math.min(entry.getValue(), nums2.get(entry.getKey())); + } + } + return String.format("%dA%dB", aCnt, bCnt); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0300.leetcode300 Longest Increasing Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0300.leetcode300 Longest Increasing Subsequence-zh.md" new file mode 100644 index 00000000..67dad52a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0300.leetcode300 Longest Increasing Subsequence-zh.md" @@ -0,0 +1,119 @@ +# [300. 最长递增子序列](https://leetcode-cn.com/problems/longest-increasing-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0300.Longest%20Increasing%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。

    + +

    子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。

    +  + +

    示例 1:

    + +
    +输入:nums = [10,9,2,5,3,7,101,18]
    +输出:4
    +解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [0,1,0,3,2,3]
    +输出:4
    +
    + +

    示例 3:

    + +
    +输入:nums = [7,7,7,7,7,7,7]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 2500
    • +
    • -104 <= nums[i] <= 104
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以设计时间复杂度为 O(n2) 的解决方案吗?
    • +
    • 你能将算法的时间复杂度降低到 O(n log(n)) 吗?
    • +
    + + +## 解法 + + + +动态规划求解。 + +定义 `dp[i]` 为以 `nums[i]` 结尾的最长子序列的长度。即题目求的是 `dp[i]` (`i ∈[0, n-1]`)的最大值。 + +状态转移方程为: + +`dp[i] = max(dp[j]) + 1`,其中 `0≤j + +### **Python3** + + + +```python +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + n = len(nums) + if n < 2: + return n + dp = [1] * n + res = 1 + for i in range(1, n): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + res = max(res, dp[i]) + return res +``` + +### **Java** + + + +```java +class Solution { + public int lengthOfLIS(int[] nums) { + int n = nums.length; + int[] dp = new int[n]; + Arrays.fill(dp, 1); + int res = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + res = Math.max(res, dp[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0301.leetcode301 Remove Invalid Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0301.leetcode301 Remove Invalid Parentheses-zh.md" new file mode 100644 index 00000000..b2b30384 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0301.leetcode301 Remove Invalid Parentheses-zh.md" @@ -0,0 +1,97 @@ +# [301. 删除无效的括号](https://leetcode-cn.com/problems/remove-invalid-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0301.Remove%20Invalid%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。

    + +

    返回所有可能的结果。答案可以按 任意顺序 返回。

    + +

     

    + +

    示例 1:

    + +
    +输入: "()())()"
    +输出: ["()()()", "(())()"]
    +
    + +

    示例 2:

    + +
    +输入: "(a)())()"
    +输出: ["(a)()()", "(a())()"]
    +
    + +

    示例 3:

    + +
    +输入: ")("
    +输出: [""]
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "()())()"
    +输出:["(())()","()()()"]
    +
    + +

    示例 2:

    + +
    +输入:s = "(a)())()"
    +输出:["(a())()","(a)()()"]
    +
    + +

    示例 3:

    + +
    +输入:s = ")("
    +输出:[""]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 25
    • +
    • s 由小写英文字母以及括号 '('')' 组成
    • +
    • s 中至多含 20 个括号
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0302.leetcode302 Smallest Rectangle Enclosing Black Pixels-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0302.leetcode302 Smallest Rectangle Enclosing Black Pixels-zh.md" new file mode 100644 index 00000000..0aa93829 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0302.leetcode302 Smallest Rectangle Enclosing Black Pixels-zh.md" @@ -0,0 +1,63 @@ +# [302. 包含全部黑色像素的最小矩形](https://leetcode-cn.com/problems/smallest-rectangle-enclosing-black-pixels) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0302.Smallest%20Rectangle%20Enclosing%20Black%20Pixels/README_EN.md) + +## 题目描述 + + + +

    图片在计算机处理中往往是使用二维矩阵来表示的。

    + +

    假设,这里我们用的是一张黑白的图片,那么 0 代表白色像素,1 代表黑色像素。

    + +

    其中黑色的像素他们相互连接,也就是说,图片中只会有一片连在一块儿的黑色像素(像素点是水平或竖直方向连接的)。

    + +

    那么,给出某一个黑色像素点 (x, y) 的位置,你是否可以找出包含全部黑色像素的最小矩形(与坐标轴对齐)的面积呢?

    + +

    + +

    示例:

    + +
    输入:
    +[
    +  "0010",
    +  "0110",
    +  "0100"
    +]
    +和 x = 0, y = 2
    +
    +输出: 6
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0303.leetcode303 Range Sum Query - Immutable-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0303.leetcode303 Range Sum Query - Immutable-zh.md" new file mode 100644 index 00000000..ea82c74a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0303.leetcode303 Range Sum Query - Immutable-zh.md" @@ -0,0 +1,116 @@ +# [303. 区域和检索 - 数组不可变](https://leetcode-cn.com/problems/range-sum-query-immutable) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0303.Range%20Sum%20Query%20-%20Immutable/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组  nums,求出数组从索引 i 到 ji ≤ j)范围内元素的总和,包含 i两点。

    + +
    +
    +

    实现 NumArray 类:

    + +
      +
    • NumArray(int[] nums) 使用数组 nums 初始化对象
    • +
    • int sumRange(int i, int j) 返回数组 nums 从索引 i 到 ji ≤ j)范围内元素的总和,包含 i两点(也就是 sum(nums[i], nums[i + 1], ... , nums[j])
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["NumArray", "sumRange", "sumRange", "sumRange"]
    +[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
    +输出:
    +[null, 1, -1, -3]
    +
    +解释:
    +NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
    +numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
    +numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) 
    +numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 104
    • +
    • -105 <= nums[i] <= 105
    • +
    • 0 <= i <= j < nums.length
    • +
    • 最多调用 104sumRange 方法
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class NumArray: + + def __init__(self, nums: List[int]): + n = len(nums) + self.sums = [0] * (n + 1) + for i in range(n): + self.sums[i + 1] = nums[i] + self.sums[i] + + + def sumRange(self, i: int, j: int) -> int: + return self.sums[j + 1] - self.sums[i] + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# param_1 = obj.sumRange(i,j) +``` + +### **Java** + + + +```java +class NumArray { + + private int[] sums; + + public NumArray(int[] nums) { + int n = nums.length; + sums = new int[n + 1]; + for (int i = 0; i < n; ++i) { + sums[i + 1] = nums[i] + sums[i]; + } + } + + public int sumRange(int i, int j) { + return sums[j + 1] - sums[i]; + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * int param_1 = obj.sumRange(i,j); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0304.leetcode304 Range Sum Query 2D - Immutable-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0304.leetcode304 Range Sum Query 2D - Immutable-zh.md" new file mode 100644 index 00000000..137bbabf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0304.leetcode304 Range Sum Query 2D - Immutable-zh.md" @@ -0,0 +1,171 @@ +# [304. 二维区域和检索 - 矩阵不可变](https://leetcode-cn.com/problems/range-sum-query-2d-immutable) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0304.Range%20Sum%20Query%202D%20-%20Immutable/README_EN.md) + +## 题目描述 + + + +

    给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)

    + +

    Range Sum Query 2D
    +上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。

    + +

     

    + +

    示例:

    + +
    +给定 matrix = [
    +  [3, 0, 1, 4, 2],
    +  [5, 6, 3, 2, 1],
    +  [1, 2, 0, 1, 5],
    +  [4, 1, 0, 1, 7],
    +  [1, 0, 3, 0, 5]
    +]
    +
    +sumRegion(2, 1, 4, 3) -> 8
    +sumRegion(1, 1, 2, 2) -> 11
    +sumRegion(1, 2, 2, 4) -> 12
    +
    + +

     

    + +

    提示:

    + +
      +
    • 你可以假设矩阵不可变。
    • +
    • 会多次调用 sumRegion 方法
    • +
    • 你可以假设 row1 ≤ row2 且 col1 ≤ col2
    • +
    + + +## 解法 + + + +动态规划-二维前缀和。 + + + +### **Python3** + + + +```python +class NumMatrix: + + def __init__(self, matrix: List[List[int]]): + m, n = len(matrix), len(matrix[0]) + self.pre = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + self.pre[i][j] = self.pre[i - 1][j] + self.pre[i][j - 1] - self.pre[i - 1][j - 1] + matrix[i - 1][j - 1] + + def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: + return self.pre[row2 + 1][col2 + 1] - self.pre[row2 + 1][col1] - self.pre[row1][col2 + 1] + self.pre[row1][col1] + + +# Your NumMatrix object will be instantiated and called as such: +# obj = NumMatrix(matrix) +# param_1 = obj.sumRegion(row1,col1,row2,col2) +``` + +### **Java** + + + +```java +class NumMatrix { + private int[][] pre; + + public NumMatrix(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + pre = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + return pre[row2 + 1][col2 + 1] - pre[row2 + 1][col1] - pre[row1][col2 + 1] + pre[row1][col1]; + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * int param_1 = obj.sumRegion(row1,col1,row2,col2); + */ +``` + +### **C++** + +```cpp +class NumMatrix { +public: + vector> pre; + + NumMatrix(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + pre.resize(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return pre[row2 + 1][col2 + 1] - pre[row2 + 1][col1] - pre[row1][col2 + 1] + pre[row1][col1]; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * int param_1 = obj->sumRegion(row1,col1,row2,col2); + */ +``` + +### **C++** + +```cpp +type NumMatrix struct { + pre [][]int +} + +func Constructor(matrix [][]int) NumMatrix { + m, n := len(matrix), len(matrix[0]) + pre := make([][]int, m+1) + for i := 0; i < m+1; i++ { + pre[i] = make([]int, n+1) + } + for i := 1; i < m+1; i++ { + for j := 1; j < n+1; j++ { + pre[i][j] = pre[i-1][j] + pre[i][j-1] + -pre[i-1][j-1] + matrix[i-1][j-1] + } + } + return NumMatrix{pre} +} + +func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { + return this.pre[row2+1][col2+1] - this.pre[row2+1][col1] - this.pre[row1][col2+1] + this.pre[row1][col1] +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * obj := Constructor(matrix); + * param_1 := obj.SumRegion(row1,col1,row2,col2); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0305.leetcode305 Number of Islands II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0305.leetcode305 Number of Islands II-zh.md" new file mode 100644 index 00000000..8e9e7b7a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0305.leetcode305 Number of Islands II-zh.md" @@ -0,0 +1,95 @@ +# [305. 岛屿数量 II](https://leetcode-cn.com/problems/number-of-islands-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0305.Number%20of%20Islands%20II/README_EN.md) + +## 题目描述 + + + +

    假设你设计一个游戏,用一个 m 行 n 列的 2D 网格来存储你的游戏地图。

    + +

    起始的时候,每个格子的地形都被默认标记为「水」。我们可以通过使用 addLand 进行操作,将位置 (row, col) 的「水」变成「陆地」。

    + +

    你将会被给定一个列表,来记录所有需要被操作的位置,然后你需要返回计算出来 每次 addLand 操作后岛屿的数量

    + +

    注意:一个岛的定义是被「水」包围的「陆地」,通过水平方向或者垂直方向上相邻的陆地连接而成。你可以假设地图网格的四边均被无边无际的「水」所包围。

    + +

    请仔细阅读下方示例与解析,更加深入了解岛屿的判定。

    + +

    示例:

    + +
    输入: m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]
    +输出: [1,1,2,3]
    +
    + +

    解析:

    + +

    起初,二维网格 grid 被全部注入「水」。(0 代表「水」,1 代表「陆地」)

    + +
    0 0 0
    +0 0 0
    +0 0 0
    +
    + +

    操作 #1:addLand(0, 0) 将 grid[0][0] 的水变为陆地。

    + +
    1 0 0
    +0 0 0   Number of islands = 1
    +0 0 0
    +
    + +

    操作 #2:addLand(0, 1) 将 grid[0][1] 的水变为陆地。

    + +
    1 1 0
    +0 0 0   岛屿的数量为 1
    +0 0 0
    +
    + +

    操作 #3:addLand(1, 2) 将 grid[1][2] 的水变为陆地。

    + +
    1 1 0
    +0 0 1   岛屿的数量为 2
    +0 0 0
    +
    + +

    操作 #4:addLand(2, 1) 将 grid[2][1] 的水变为陆地。

    + +
    1 1 0
    +0 0 1   岛屿的数量为 3
    +0 1 0
    +
    + +

    拓展:

    + +

    你是否能在 O(k log mn) 的时间复杂度程度内完成每次的计算?(k 表示 positions 的长度)

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0306.leetcode306 Additive Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0306.leetcode306 Additive Number-zh.md" new file mode 100644 index 00000000..1ff84a24 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0306.leetcode306 Additive Number-zh.md" @@ -0,0 +1,62 @@ +# [306. 累加数](https://leetcode-cn.com/problems/additive-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0306.Additive%20Number/README_EN.md) + +## 题目描述 + + + +

    累加数是一个字符串,组成它的数字可以形成累加序列。

    + +

    一个有效的累加序列必须至少包含 3 个数。除了最开始的两个数以外,字符串中的其他数都等于它之前两个数相加的和。

    + +

    给定一个只包含数字 '0'-'9' 的字符串,编写一个算法来判断给定输入是否是累加数。

    + +

    说明: 累加序列里的数不会以 0 开头,所以不会出现 1, 2, 03 或者 1, 02, 3 的情况。

    + +

    示例 1:

    + +
    输入: "112358"
    +输出: true 
    +解释: 累加序列为: 1, 1, 2, 3, 5, 8 。1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
    +
    + +

    示例 2:

    + +
    输入: "199100199"
    +输出: true 
    +解释: 累加序列为: 1, 99, 100, 199。1 + 99 = 100, 99 + 100 = 199
    + +

    进阶:
    +你如何处理一个溢出的过大的整数输入?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0307.leetcode307 Range Sum Query - Mutable-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0307.leetcode307 Range Sum Query - Mutable-zh.md" new file mode 100644 index 00000000..d06b0626 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0307.leetcode307 Range Sum Query - Mutable-zh.md" @@ -0,0 +1,83 @@ +# [307. 区域和检索 - 数组可修改](https://leetcode-cn.com/problems/range-sum-query-mutable) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0307.Range%20Sum%20Query%20-%20Mutable/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums ,请你完成两类查询,其中一类查询要求更新数组下标对应的值,另一类查询要求返回数组中某个范围内元素的总和。

    + +

    实现 NumArray 类:

    + +
    +
    +
      +
    • NumArray(int[] nums) 用整数数组 nums 初始化对象
    • +
    • void update(int index, int val)nums[index] 的值更新为 val
    • +
    • int sumRange(int left, int right) 返回子数组 nums[left, right] 的总和(即,nums[left] + nums[left + 1], ..., nums[right]
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["NumArray", "sumRange", "update", "sumRange"]
    +[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
    +输出:
    +[null, 9, null, 8]
    +
    +解释:
    +NumArray numArray = new NumArray([1, 3, 5]);
    +numArray.sumRange(0, 2); // 返回 9 ,sum([1,3,5]) = 9
    +numArray.update(1, 2);   // nums = [1,2,5]
    +numArray.sumRange(0, 2); // 返回 8 ,sum([1,2,5]) = 8
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 3 * 104
    • +
    • -100 <= nums[i] <= 100
    • +
    • 0 <= index < nums.length
    • +
    • -100 <= val <= 100
    • +
    • 0 <= left <= right < nums.length
    • +
    • 最多调用 3 * 104updatesumRange 方法
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0308.leetcode308 Range Sum Query 2D - Mutable-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0308.leetcode308 Range Sum Query 2D - Mutable-zh.md" new file mode 100644 index 00000000..02599137 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0308.leetcode308 Range Sum Query 2D - Mutable-zh.md" @@ -0,0 +1,70 @@ +# [308. 二维区域和检索 - 可变](https://leetcode-cn.com/problems/range-sum-query-2d-mutable) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0308.Range%20Sum%20Query%202D%20-%20Mutable/README_EN.md) + +## 题目描述 + + + +

    给你一个 2D 矩阵 matrix,请计算出从左上角 (row1, col1) 到右下角 (row2, col2) 组成的矩形中所有元素的和。

    + +

    Range Sum Query 2D
    +上述粉色矩形框内的,该矩形由左上角 (row1, col1) = (2, 1) 和右下角 (row2, col2) = (4, 3) 确定。其中,所包括的元素总和 sum = 8

    + +

    示例:

    + +
    给定 matrix = [
    +  [3, 0, 1, 4, 2],
    +  [5, 6, 3, 2, 1],
    +  [1, 2, 0, 1, 5],
    +  [4, 1, 0, 1, 7],
    +  [1, 0, 3, 0, 5]
    +]
    +
    +sumRegion(2, 1, 4, 3) -> 8
    +update(3, 2, 2)
    +sumRegion(2, 1, 4, 3) -> 10
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 矩阵 matrix 的值只能通过 update 函数来进行修改
    2. +
    3. 你可以默认 update 函数和 sumRegion 函数的调用次数是均匀分布的
    4. +
    5. 你可以默认 row1 ≤ row2,col1 ≤ col2
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0309.leetcode309 Best Time to Buy and Sell Stock with Cooldown-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0309.leetcode309 Best Time to Buy and Sell Stock with Cooldown-zh.md" new file mode 100644 index 00000000..190f1430 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0309.leetcode309 Best Time to Buy and Sell Stock with Cooldown-zh.md" @@ -0,0 +1,127 @@ +# [309. 最佳买卖股票时机含冷冻期](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0309.Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Cooldown/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​

    + +

    设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

    + +
      +
    • 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
    • +
    • 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
    • +
    + +

    示例:

    + +
    输入: [1,2,3,0,2]
    +输出: 3 
    +解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
    + +## 解法 + + + +动态规划法。 + +设 f1 表示当天买入股票后的最大利润,f2 表示当天卖出股票后的最大利润,f3 表示当天空仓后的最大利润。 + +初始第 1 天结束时,`f1 = -prices[0]`,`f2 = 0`,`f3 = 0`。 + +从第 2 天开始,当天结束时: + +- 若买入,则说明前一天空仓,然后今天买入,`f1 = max(f1, f3 - prices[i])`。 +- 若卖出,则只能是之前某一天买入,然后今天卖出,`f2 = max(f2, f1 + prices[i])`。 +- 若空仓,则只能是之前某一天卖出后,然后今天保持空仓,`f3 = max(f3, f2)`。 + +最后返回 f2 即可。 + + + +### **Python3** + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + # 买入,卖出,继续空仓 + f1, f2, f3 = -prices[0], 0, 0 + for price in prices[1:]: + pf1, pf2, pf3 = f1, f2, f3 + f1 = max(pf1, pf3 - price) + f2 = max(pf2, pf1 + price) + f3 = max(pf3, pf2) + return f2 +``` + +### **Java** + + + +```java +class Solution { + public int maxProfit(int[] prices) { + // 买入,卖出,继续空仓 + int f1 = -prices[0], f2 = 0, f3 = 0; + for (int i = 1; i < prices.length; ++i) { + int pf1 = f1, pf2 = f2, pf3 = f3; + f1 = Math.max(pf1, pf3 - prices[i]); + f2 = Math.max(pf2, pf1 + prices[i]); + f3 = Math.max(pf3, pf2); + } + return f2; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f1 = -prices[0], f2 = 0, f3 = 0; + for (int i = 1; i < prices.size(); ++i) { + int pf1 = f1, pf2 = f2, pf3 = f3; + f1 = max(pf1, pf3 - prices[i]); + f2 = max(pf2, pf1 + prices[i]); + f3 = max(pf3, pf2); + } + return f2; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int) int { + f1, f2, f3 := -prices[0], 0, 0 + for i := 1; i < len(prices); i++ { + pf1, pf2, pf3 := f1, f2, f3 + f1 = max(pf1, pf3-prices[i]) + f2 = max(pf2, pf1+prices[i]) + f3 = max(pf3, pf2) + } + return f2 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0310.leetcode310 Minimum Height Trees0310.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0310.leetcode310 Minimum Height Trees0310.md" new file mode 100644 index 00000000..53621892 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0310.leetcode310 Minimum Height Trees0310.md" @@ -0,0 +1,93 @@ +# [310. 最小高度树](https://leetcode-cn.com/problems/minimum-height-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0310.Minimum%20Height%20Trees/README_EN.md) + +## 题目描述 + + + +

    树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。

    + +

    给你一棵包含 n 个节点的树,标记为 0 到 n - 1 。给定数字 n 和一个有 n - 1 条无向边的 edges 列表(每一个边都是一对标签),其中 edges[i] = [ai, bi] 表示树中节点 aibi 之间存在一条无向边。

    + +

    可选择树中任何一个节点作为根。当选择节点 x 作为根节点时,设结果树的高度为 h 。在所有可能的树中,具有最小高度的树(即,min(h))被称为 最小高度树

    + +

    请你找到所有的 最小高度树 并按 任意顺序 返回它们的根节点标签列表。

    +树的 高度 是指根节点和叶子节点之间最长向下路径上边的数量。 + +

     

    + +

    示例 1:

    + +
    +输入:n = 4, edges = [[1,0],[1,2],[1,3]]
    +输出:[1]
    +解释:如图所示,当根是标签为 1 的节点时,树的高度是 1 ,这是唯一的最小高度树。
    + +

    示例 2:

    + +
    +输入:n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
    +输出:[3,4]
    +
    + +

    示例 3:

    + +
    +输入:n = 1, edges = []
    +输出:[0]
    +
    + +

    示例 4:

    + +
    +输入:n = 2, edges = [[0,1]]
    +输出:[0,1]
    +
    + +

     

    + +
      +
    + +

    提示:

    + +
      +
    • 1 <= n <= 2 * 104
    • +
    • edges.length == n - 1
    • +
    • 0 <= ai, bi < n
    • +
    • ai != bi
    • +
    • 所有 (ai, bi) 互不相同
    • +
    • 给定的输入 保证 是一棵树,并且 不会有重复的边
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0311.leetcode311 Sparse Matrix Multiplication0311.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0311.leetcode311 Sparse Matrix Multiplication0311.md" new file mode 100644 index 00000000..fdb5a30f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0311.leetcode311 Sparse Matrix Multiplication0311.md" @@ -0,0 +1,66 @@ +# [311. 稀疏矩阵的乘法](https://leetcode-cn.com/problems/sparse-matrix-multiplication) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0311.Sparse%20Matrix%20Multiplication/README_EN.md) + +## 题目描述 + + + +

    给你两个 稀疏矩阵 A 和 B,请你返回 AB 的结果。你可以默认 的列数等于 的行数。

    + +

    请仔细阅读下面的示例。

    + +

     

    + +

    示例:

    + +
    输入:
    +
    +A = [
    +  [ 1, 0, 0],
    +  [-1, 0, 3]
    +]
    +
    +B = [
    +  [ 7, 0, 0 ],
    +  [ 0, 0, 0 ],
    +  [ 0, 0, 1 ]
    +]
    +
    +输出:
    +
    +     |  1 0 0 |   | 7 0 0 |   |  7 0 0 |
    +AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
    +                  | 0 0 1 |
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0312.leetcode312 Burst Balloons-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0312.leetcode312 Burst Balloons-zh.md" new file mode 100644 index 00000000..1de49284 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0312.leetcode312 Burst Balloons-zh.md" @@ -0,0 +1,71 @@ +# [312. 戳气球](https://leetcode-cn.com/problems/burst-balloons) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0312.Burst%20Balloons/README_EN.md) + +## 题目描述 + + + +

    n 个气球,编号为0n - 1,每个气球上都标有一个数字,这些数字存在数组 nums 中。

    + +

    现在要求你戳破所有的气球。戳破第 i 个气球,你可以获得 nums[i - 1] * nums[i] * nums[i + 1] 枚硬币。 这里的 i - 1i + 1 代表和 i 相邻的两个气球的序号。如果 i - 1i + 1 超出了数组的边界,那么就当它是一个数字为 1 的气球。

    + +

    求所能获得硬币的最大数量。

    + +

     

    +示例 1: + +
    +输入:nums = [3,1,5,8]
    +输出:167
    +解释:
    +nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
    +coins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167
    + +

    示例 2:

    + +
    +输入:nums = [1,5]
    +输出:10
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 500
    • +
    • 0 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0313.leetcode313 Super Ugly Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0313.leetcode313 Super Ugly Number-zh.md" new file mode 100644 index 00000000..e14db4d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0313.leetcode313 Super Ugly Number-zh.md" @@ -0,0 +1,57 @@ +# [313. 超级丑数](https://leetcode-cn.com/problems/super-ugly-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0313.Super%20Ugly%20Number/README_EN.md) + +## 题目描述 + + + +

    编写一段程序来查找第 n 个超级丑数。

    + +

    超级丑数是指其所有质因数都是长度为 k 的质数列表 primes 中的正整数。

    + +

    示例:

    + +
    输入: n = 12, primes = [2,7,13,19]
    +输出: 32 
    +解释: 给定长度为 4 的质数列表 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26,28,32] 。
    + +

    说明:

    + +
      +
    • 1 是任何给定 primes 的超级丑数。
    • +
    •  给定 primes 中的数字以升序排列。
    • +
    • 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000 。
    • +
    • 第 n 个超级丑数确保在 32 位有符整数范围内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0314.leetcode314 Binary Tree Vertical Order Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0314.leetcode314 Binary Tree Vertical Order Traversal-zh.md" new file mode 100644 index 00000000..1170d2e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0314.leetcode314 Binary Tree Vertical Order Traversal-zh.md" @@ -0,0 +1,148 @@ +# [314. 二叉树的垂直遍历](https://leetcode-cn.com/problems/binary-tree-vertical-order-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0314.Binary%20Tree%20Vertical%20Order%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给你一个二叉树的根结点,返回其结点按 垂直方向(从上到下,逐列)遍历的结果。

    + +

    如果两个结点在同一行和列,那么顺序则为 从左到右

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,9,20,null,null,15,7]
    +输出:[[9],[3,15],[20],[7]]
    +
    + +

    示例 2:

    + +
    +输入:root = [3,9,8,4,0,1,7]
    +输出:[[4],[9],[3,0,1],[8],[7]]
    +
    + +

    示例 3:

    + +
    +输入:root = [3,9,8,4,0,1,7,null,null,null,2,5]
    +输出:[[4],[9,5],[3,0,1],[8,2],[7]]
    +
    + +

    示例 4:

    + +
    +输入:root = []
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中结点的数目在范围 [0, 100]
    • +
    • -100 <= Node.val <= 100
    • +
    + +## 解法 + + + +“BFS 层次遍历”实现。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def verticalOrder(self, root: TreeNode) -> List[List[int]]: + if root is None: + return [] + q = collections.deque([(root, 0)]) + offset_vals = collections.defaultdict(list) + while q: + node, offset = q.popleft() + offset_vals[offset].append(node.val) + if node.left: + q.append((node.left, offset - 1)) + if node.right: + q.append((node.right, offset + 1)) + res = [] + for _, vals in sorted(offset_vals.items(), key=lambda x: x[0]): + res.append(vals) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> verticalOrder(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Map> offsetVals = new TreeMap<>(); + Map nodeOffsets = new HashMap<>(); + Deque q = new ArrayDeque<>(); + q.offer(root); + nodeOffsets.put(root, 0); + + while (!q.isEmpty()) { + TreeNode node = q.poll(); + int offset = nodeOffsets.get(node); + if (!offsetVals.containsKey(offset)) { + offsetVals.put(offset, new ArrayList<>()); + } + offsetVals.get(offset).add(node.val); + if (node.left != null) { + q.offer(node.left); + nodeOffsets.put(node.left, offset - 1); + } + if (node.right != null) { + q.offer(node.right); + nodeOffsets.put(node.right, offset + 1); + } + } + return new ArrayList<>(offsetVals.values()); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0315.leetcode315 Count of Smaller Numbers After Self-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0315.leetcode315 Count of Smaller Numbers After Self-zh.md" new file mode 100644 index 00000000..0ea0de18 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0315.leetcode315 Count of Smaller Numbers After Self-zh.md" @@ -0,0 +1,62 @@ +# [315. 计算右侧小于当前元素的个数](https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0315.Count%20of%20Smaller%20Numbers%20After%20Self/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是  nums[i] 右侧小于 nums[i] 的元素的数量。

    + +

     

    + +

    示例:

    + +
    输入:nums = [5,2,6,1]
    +输出:[2,1,1,0] 
    +解释:
    +5 的右侧有 2 个更小的元素 (2 和 1)
    +2 的右侧仅有 1 个更小的元素 (1)
    +6 的右侧有 1 个更小的元素 (1)
    +1 的右侧有 0 个更小的元素
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 10^5
    • +
    • -10^4 <= nums[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0316.leetcode316 Remove Duplicate Letters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0316.leetcode316 Remove Duplicate Letters-zh.md" new file mode 100644 index 00000000..ebd70491 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0316.leetcode316 Remove Duplicate Letters-zh.md" @@ -0,0 +1,66 @@ +# [316. 去除重复字母](https://leetcode-cn.com/problems/remove-duplicate-letters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0316.Remove%20Duplicate%20Letters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。

    + +

    注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "bcabc"
    +输出"abc"
    +
    + +

    示例 2:

    + +
    +输入:s = "cbacdcbc"
    +输出:"acdb"
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0317.leetcode317 Shortest Distance from All Buildings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0317.leetcode317 Shortest Distance from All Buildings-zh.md" new file mode 100644 index 00000000..6634a302 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0317.leetcode317 Shortest Distance from All Buildings-zh.md" @@ -0,0 +1,79 @@ +# [317. 离建筑物最近的距离](https://leetcode-cn.com/problems/shortest-distance-from-all-buildings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0317.Shortest%20Distance%20from%20All%20Buildings/README_EN.md) + +## 题目描述 + + + +

    你是个房地产开发商,想要选择一片空地 建一栋大楼。你想把这栋大楼够造在一个距离周边设施都比较方便的地方,通过调研,你希望从它出发能在 最短的距离和 内抵达周边全部的建筑物。请你计算出这个最佳的选址到周边全部建筑物的 最短距离和

    + +

     

    + +

    提示:

    + +

    你只能通过向上、下、左、右四个方向上移动。

    + +

    给你一个由 0、1 和 2 组成的二维网格,其中:

    + +
      +
    • 0 代表你可以自由通过和选择建造的空地
    • +
    • 1 代表你无法通行的建筑物
    • +
    • 2 代表你无法通行的障碍物
    • +
    + +

     

    + +

    示例:

    + +
    输入:[[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
    +
    +1 - 0 - 2 - 0 - 1
    +|   |   |   |   |
    +0 - 0 - 0 - 0 - 0
    +|   |   |   |   |
    +0 - 0 - 1 - 0 - 0
    +输出:7 
    +解析:
    +给定三个建筑物 (0,0)、(0,4) 和 (2,2) 以及一个位于 (0,2) 的障碍物。
    +由于总距离之和 3+3+1=7 最优,所以位置 (1,2) 是符合要求的最优地点,故返回7。
    +
    + +

     

    + +

    注意:

    + +
      +
    • 题目数据保证至少存在一栋建筑物,如果无法按照上述规则返回建房地点,则请你返回 -1。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0318.leetcode318 Maximum Product of Word Lengths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0318.leetcode318 Maximum Product of Word Lengths-zh.md" new file mode 100644 index 00000000..60da43e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0318.leetcode318 Maximum Product of Word Lengths-zh.md" @@ -0,0 +1,58 @@ +# [318. 最大单词长度乘积](https://leetcode-cn.com/problems/maximum-product-of-word-lengths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0318.Maximum%20Product%20of%20Word%20Lengths/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。

    + +

    示例 1:

    + +
    输入: ["abcw","baz","foo","bar","xtfn","abcdef"]
    +输出: 16 
    +解释: 这两个单词为 "abcw", "xtfn"
    + +

    示例 2:

    + +
    输入: ["a","ab","abc","d","cd","bcd","abcd"]
    +输出: 4 
    +解释: 这两个单词为 "ab", "cd"
    + +

    示例 3:

    + +
    输入: ["a","aa","aaa","aaaa"]
    +输出: 0 
    +解释: 不存在这样的两个单词。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0319.leetcode319 Bulb Switcher-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0319.leetcode319 Bulb Switcher-zh.md" new file mode 100644 index 00000000..4957ea9d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0319.leetcode319 Bulb Switcher-zh.md" @@ -0,0 +1,92 @@ +# [319. 灯泡开关](https://leetcode-cn.com/problems/bulb-switcher) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0319.Bulb%20Switcher/README_EN.md) + +## 题目描述 + + + +

    初始时有 n 个灯泡处于关闭状态。

    + +

    对某个灯泡切换开关意味着:如果灯泡状态为关闭,那该灯泡就会被开启;而灯泡状态为开启,那该灯泡就会被关闭。

    + +

    第 1 轮,每个灯泡切换一次开关。即,打开所有的灯泡。

    + +

    第 2 轮,每两个灯泡切换一次开关。 即,每两个灯泡关闭一个。

    + +

    第 3 轮,每三个灯泡切换一次开关。

    + +

    第 i 轮,每 i 个灯泡切换一次开关。 而第 n 轮,你只切换最后一个灯泡的开关。

    + +

    找出 n 轮后有多少个亮着的灯泡。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 3
    +输出:1 
    +解释:
    +初始时, 灯泡状态 [关闭, 关闭, 关闭].
    +第一轮后, 灯泡状态 [开启, 开启, 开启].
    +第二轮后, 灯泡状态 [开启, 关闭, 开启].
    +第三轮后, 灯泡状态 [开启, 关闭, 关闭]. 
    +
    +你应该返回 1,因为只有一个灯泡还亮着。
    +
    + +

    示例 2:

    + +
    +输入:n = 0
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:n = 1
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0320.leetcode320 Generalized Abbreviation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0320.leetcode320 Generalized Abbreviation-zh.md" new file mode 100644 index 00000000..f5950aa5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0320.leetcode320 Generalized Abbreviation-zh.md" @@ -0,0 +1,51 @@ +# [320. 列举单词的全部缩写](https://leetcode-cn.com/problems/generalized-abbreviation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0320.Generalized%20Abbreviation/README_EN.md) + +## 题目描述 + + + +

    请你写出一个能够举单词全部缩写的函数。

    + +

    注意:输出的顺序并不重要。

    + +

    示例:

    + +
    输入: "word"
    +输出:
    +["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0321.leetcode321 Create Maximum Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0321.leetcode321 Create Maximum Number-zh.md" new file mode 100644 index 00000000..9ab275c4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0321.leetcode321 Create Maximum Number-zh.md" @@ -0,0 +1,71 @@ +# [321. 拼接最大数](https://leetcode-cn.com/problems/create-maximum-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0321.Create%20Maximum%20Number/README_EN.md) + +## 题目描述 + + + +

    给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。

    + +

    求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。

    + +

    说明: 请尽可能地优化你算法的时间和空间复杂度。

    + +

    示例 1:

    + +
    输入:
    +nums1 = [3, 4, 6, 5]
    +nums2 = [9, 1, 2, 5, 8, 3]
    +k = 5
    +输出:
    +[9, 8, 6, 5, 3]
    + +

    示例 2:

    + +
    输入:
    +nums1 = [6, 7]
    +nums2 = [6, 0, 4]
    +k = 5
    +输出:
    +[6, 7, 6, 0, 4]
    + +

    示例 3:

    + +
    输入:
    +nums1 = [3, 9]
    +nums2 = [8, 9]
    +k = 3
    +输出:
    +[9, 8, 9]
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0322.leetcode322 Coin Change-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0322.leetcode322 Coin Change-zh.md" new file mode 100644 index 00000000..9599743e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0322.leetcode322 Coin Change-zh.md" @@ -0,0 +1,141 @@ +# [322. 零钱兑换](https://leetcode-cn.com/problems/coin-change) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0322.Coin%20Change/README_EN.md) + +## 题目描述 + + + +

    给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1

    + +

    你可以认为每种硬币的数量是无限的。

    + +

     

    + +

    示例 1:

    + +
    +输入:coins = [1, 2, 5], amount = 11
    +输出:3
    +解释:11 = 5 + 5 + 1
    + +

    示例 2:

    + +
    +输入:coins = [2], amount = 3
    +输出:-1
    + +

    示例 3:

    + +
    +输入:coins = [1], amount = 0
    +输出:0
    +
    + +

    示例 4:

    + +
    +输入:coins = [1], amount = 1
    +输出:1
    +
    + +

    示例 5:

    + +
    +输入:coins = [1], amount = 2
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= coins.length <= 12
    • +
    • 1 <= coins[i] <= 231 - 1
    • +
    • 0 <= amount <= 104
    • +
    + + +## 解法 + + + +类似完全背包的思路,硬币数量不限,求凑成总金额所需的最少的硬币个数。 + + + +### **Python3** + + + +```python +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + for coin in coins: + for j in range(coin, amount + 1): + dp[j] = min(dp[j], dp[j - coin] + 1) + return -1 if dp[amount] > amount else dp[amount] +``` + +### **Java** + + + +```java +class Solution { + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount + 1]; + Arrays.fill(dp, amount + 1); + dp[0] = 0; + for (int coin : coins) { + for (int j = coin; j <= amount; j++) { + dp[j] = Math.min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function (coins, amount) { + let dp = Array(amount + 1).fill(amount + 1); + dp[0] = 0; + for (const coin of coins) { + for (let j = coin; j <= amount; ++j) { + dp[j] = Math.min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); + dp[0] = 0; + for (auto coin : coins) { + for (int j = coin; j <= amount; ++j) { + dp[j] = min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } +}; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0323.leetcode323 Number of Connected Components in an Undirected Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0323.leetcode323 Number of Connected Components in an Undirected Graph-zh.md" new file mode 100644 index 00000000..30f0d4b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0323.leetcode323 Number of Connected Components in an Undirected Graph-zh.md" @@ -0,0 +1,65 @@ +# [323. 无向图中连通分量的数目](https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/README_EN.md) + +## 题目描述 + + + +

    给定编号从 0n-1n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连通分量的数目。

    + +

    示例 1:

    + +
    输入: n = 5edges = [[0, 1], [1, 2], [3, 4]]
    +
    +     0          3
    +     |          |
    +     1 --- 2    4 
    +
    +输出: 2
    +
    + +

    示例 2:

    + +
    输入: n = 5edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
    +
    +     0           4
    +     |           |
    +     1 --- 2 --- 3
    +
    +输出:  1
    +
    + +

    注意:
    +你可以假设在 edges 中不会出现重复的边。而且由于所以的边都是无向边,[0, 1][1, 0]  相同,所以它们不会同时在 edges 中出现。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0324.leetcode324 Wiggle Sort II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0324.leetcode324 Wiggle Sort II-zh.md" new file mode 100644 index 00000000..27dd418a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0324.leetcode324 Wiggle Sort II-zh.md" @@ -0,0 +1,73 @@ +# [324. 摆动排序 II](https://leetcode-cn.com/problems/wiggle-sort-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0324.Wiggle%20Sort%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]... 的顺序。

    + +

    你可以假设所有输入数组都可以得到满足题目要求的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,5,1,1,6,4]
    +输出:[1,6,1,5,1,4]
    +解释:[1,4,1,5,1,6] 同样是符合题目要求的结果,可以被判题程序接受。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,3,2,2,3,1]
    +输出:[2,3,1,3,1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 0 <= nums[i] <= 5000
    • +
    • 题目数据保证,对于给定的输入 nums ,总能产生满足题目要求的结果
    • +
    + +

     

    + +

    进阶:你能用 O(n) 时间复杂度和 / 或原地 O(1) 额外空间来实现吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0325.leetcode325 Maximum Size Subarray Sum Equals k-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0325.leetcode325 Maximum Size Subarray Sum Equals k-zh.md" new file mode 100644 index 00000000..dccf5ed0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0325.leetcode325 Maximum Size Subarray Sum Equals k-zh.md" @@ -0,0 +1,59 @@ +# [325. 和等于 k 的最长子数组长度](https://leetcode-cn.com/problems/maximum-size-subarray-sum-equals-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0325.Maximum%20Size%20Subarray%20Sum%20Equals%20k/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 nums 和一个目标值 k,找到和等于 k 的最长子数组长度。如果不存在任意一个符合要求的子数组,则返回 0。

    + +

    注意:
    nums 数组的总和是一定在 32 位有符号整数范围之内的。

    + +

    示例 1:

    + +
    输入: nums = [1, -1, 5, -2, 3], k = 3
    +输出: 4 
    +解释: 子数组 [1, -1, 5, -2] 和等于 3,且长度最长。
    +
    + +

    示例 2:

    + +
    输入: nums = [-2, -1, 2, 1], k = 1
    +输出: 2 
    +解释: 子数组 [-1, 2] 和等于 1,且长度最长。
    + +

    进阶:
    +你能使时间复杂度在 O(n) 内完成此题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0326.leetcode326 Power of Three-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0326.leetcode326 Power of Three-zh.md" new file mode 100644 index 00000000..0e937984 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0326.leetcode326 Power of Three-zh.md" @@ -0,0 +1,88 @@ +# [326. 3的幂](https://leetcode-cn.com/problems/power-of-three) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0326.Power%20of%20Three/README_EN.md) + +## 题目描述 + + + +

    给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false

    + +

    整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3x

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 27
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:n = 0
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:n = 9
    +输出:true
    +
    + +

    示例 4:

    + +
    +输入:n = 45
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • -231 <= n <= 231 - 1
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你能不使用循环或者递归来完成本题吗?
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0327.leetcode327 Count of Range Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0327.leetcode327 Count of Range Sum-zh.md" new file mode 100644 index 00000000..93253291 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0327.leetcode327 Count of Range Sum-zh.md" @@ -0,0 +1,72 @@ +# [327. 区间和的个数](https://leetcode-cn.com/problems/count-of-range-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0327.Count%20of%20Range%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums 。区间和 S(i, j) 表示在 nums 中,位置从 i 到 j 的元素之和,包含 i 和 j (ij)。

    + +

    请你以下标 i0 <= i <= nums.length )为起点,元素个数逐次递增,计算子数组内的元素和。

    + +

    当元素和落在范围 [lower, upper] (包含 lower 和 upper)之内时,记录子数组当前最末元素下标 j ,记作 有效 区间和 S(i, j)

    + +

    求数组中,值位于范围 [lower, upper] (包含 lower 和 upper)之内的 有效 区间和的个数。

    + +

     

    + +

    注意:
    +最直观的算法复杂度是 O(n2) ,请在此基础上优化你的算法。

    + +

     

    + +

    示例:

    + +
    +输入:nums = [-2,5,-1], lower = -2, upper = 2,
    +输出:3 
    +解释:
    +下标 i = 0 时,子数组 [-2]、[-2,5]、[-2,5,-1],对应元素和分别为 -2、3、2 ;其中 -2 和 2 落在范围 [lower = -2, upper = 2] 之间,因此记录有效区间和 S(0,0),S(0,2) 。
    +下标 i = 1 时,子数组 [5]、[5,-1] ,元素和 5、4 ;没有满足题意的有效区间和。
    +下标 i = 2 时,子数组 [-1] ,元素和 -1 ;记录有效区间和 S(2,2) 。
    +故,共有 3 个有效区间和。
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0328.leetcode328 Odd Even Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0328.leetcode328 Odd Even Linked List-zh.md" new file mode 100644 index 00000000..de1d4f01 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0328.leetcode328 Odd Even Linked List-zh.md" @@ -0,0 +1,193 @@ +# [328. 奇偶链表](https://leetcode-cn.com/problems/odd-even-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0328.Odd%20Even%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

    + +

    请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。

    + +

    示例 1:

    + +
    输入: 1->2->3->4->5->NULL
    +输出: 1->3->5->2->4->NULL
    +
    + +

    示例 2:

    + +
    输入: 2->1->3->5->6->4->7->NULL 
    +输出: 2->3->6->7->1->5->4->NULL
    + +

    说明:

    + +
      +
    • 应当保持奇数节点和偶数节点的相对顺序。
    • +
    • 链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def oddEvenList(self, head: ListNode) -> ListNode: + if head is None: + return head + odd, even = head, head.next + even_head = even + while even and even.next: + odd.next = even.next + odd = odd.next + even.next = odd.next + even = even.next + odd.next = even_head + return head +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode oddEvenList(ListNode head) { + if (head == null) { + return head; + } + ListNode odd = head, even = head.next; + ListNode evenHead = even; + while (even != null && even.next != null) { + odd.next = even.next; + odd = odd.next; + even.next = odd.next; + even = even.next; + } + odd.next = evenHead; + return head; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function oddEvenList(head: ListNode | null): ListNode | null { + if (head == null) return head; + let odd: ListNode = head, even: ListNode = head.next; + let evenHead = even; + while (even != null && even.next != null) { + odd.next = even.next; + odd = odd.next; + even.next = odd.next; + even = even.next; + } + odd.next = evenHead; + return head; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + if (!head) { + return head; + } + ListNode *odd = head, *even = head->next; + ListNode *evenHead = even; + while (even && even->next) { + odd->next = even->next; + odd = odd->next; + even->next = odd->next; + even = even->next; + } + odd->next = evenHead; + return head; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func oddEvenList(head *ListNode) *ListNode { + if head == nil { + return head + } + odd, even := head, head.Next + evenHead := even + for even != nil && even.Next != nil { + odd.Next = even.Next + odd = odd.Next + even.Next = odd.Next + even = even.Next + } + odd.Next = evenHead + return head +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0329.leetcode329 Longest Increasing Path in a Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0329.leetcode329 Longest Increasing Path in a Matrix-zh.md" new file mode 100644 index 00000000..10f4c8c2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0329.leetcode329 Longest Increasing Path in a Matrix-zh.md" @@ -0,0 +1,77 @@ +# [329. 矩阵中的最长递增路径](https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0329.Longest%20Increasing%20Path%20in%20a%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给定一个 m x n 整数矩阵 matrix ,找出其中 最长递增路径 的长度。

    + +

    对于每个单元格,你可以往上,下,左,右四个方向移动。 你 不能对角线 方向上移动或移动到 边界外(即不允许环绕)。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[9,9,4],[6,6,8],[2,1,1]]
    +输出:4 
    +解释:最长递增路径为 [1, 2, 6, 9]
    + +

    示例 2:

    + +
    +输入:matrix = [[3,4,5],[3,2,6],[2,2,1]]
    +输出:4 
    +解释:最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
    +
    + +

    示例 3:

    + +
    +输入:matrix = [[1]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • 0 <= matrix[i][j] <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0330.leetcode330 Patching Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0330.leetcode330 Patching Array-zh.md" new file mode 100644 index 00000000..84721a59 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0330.leetcode330 Patching Array-zh.md" @@ -0,0 +1,63 @@ +# [330. 按要求补齐数组](https://leetcode-cn.com/problems/patching-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0330.Patching%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。

    + +

    示例 1:

    + +
    输入: nums = [1,3], n = 6
    +输出: 1 
    +解释:
    +根据 nums 里现有的组合 [1], [3], [1,3],可以得出 1, 3, 4。
    +现在如果我们将 2 添加到 nums 中, 组合变为: [1], [2], [3], [1,3], [2,3], [1,2,3]。
    +其和可以表示数字 1, 2, 3, 4, 5, 6,能够覆盖 [1, 6] 区间里所有的数。
    +所以我们最少需要添加一个数字。
    + +

    示例 2:

    + +
    输入: nums = [1,5,10], n = 20
    +输出: 2
    +解释: 我们需要添加 [2, 4]。
    +
    + +

    示例 3:

    + +
    输入: nums = [1,2,2], n = 5
    +输出: 0
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0331.leetcode331 Verify Preorder Serialization of a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0331.leetcode331 Verify Preorder Serialization of a Binary Tree-zh.md" new file mode 100644 index 00000000..a865efb0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0331.leetcode331 Verify Preorder Serialization of a Binary Tree-zh.md" @@ -0,0 +1,73 @@ +# [331. 验证二叉树的前序序列化](https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0331.Verify%20Preorder%20Serialization%20of%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录下这个节点的值。如果它是一个空节点,我们可以使用一个标记值记录,例如 #

    + +
         _9_
    +    /   \
    +   3     2
    +  / \   / \
    + 4   1  #  6
    +/ \ / \   / \
    +# # # #   # #
    +
    + +

    例如,上面的二叉树可以被序列化为字符串 "9,3,4,#,#,1,#,#,2,#,6,#,#",其中 # 代表一个空节点。

    + +

    给定一串以逗号分隔的序列,验证它是否是正确的二叉树的前序序列化。编写一个在不重构树的条件下的可行算法。

    + +

    每个以逗号分隔的字符或为一个整数或为一个表示 null 指针的 '#'

    + +

    你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3"

    + +

    示例 1:

    + +
    输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
    +输出: true
    + +

    示例 2:

    + +
    输入: "1,#"
    +输出: false
    +
    + +

    示例 3:

    + +
    输入: "9,#,#,1"
    +输出: false
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0332.leetcode332 Reconstruct Itinerary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0332.leetcode332 Reconstruct Itinerary-zh.md" new file mode 100644 index 00000000..d3dfd0b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0332.leetcode332 Reconstruct Itinerary-zh.md" @@ -0,0 +1,67 @@ +# [332. 重新安排行程](https://leetcode-cn.com/problems/reconstruct-itinerary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0332.Reconstruct%20Itinerary/README_EN.md) + +## 题目描述 + + + +

    给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。

    + +

     

    + +

    提示:

    + +
      +
    1. 如果存在多种有效的行程,请你按字符自然排序返回最小的行程组合。例如,行程 ["JFK", "LGA"]["JFK", "LGB"] 相比就更小,排序更靠前
    2. +
    3. 所有的机场都用三个大写字母表示(机场代码)。
    4. +
    5. 假定所有机票至少存在一种合理的行程。
    6. +
    7. 所有的机票必须都用一次 且 只能用一次。
    8. +
    + +

     

    + +

    示例 1:

    + +
    +输入:[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
    +输出:["JFK", "MUC", "LHR", "SFO", "SJC"]
    +
    + +

    示例 2:

    + +
    +输入:[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
    +输出:["JFK","ATL","JFK","SFO","ATL","SFO"]
    +解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"]。但是它自然排序更大更靠后。
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0333.leetcode333 Largest BST Subtree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0333.leetcode333 Largest BST Subtree-zh.md" new file mode 100644 index 00000000..5fd7173e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0333.leetcode333 Largest BST Subtree-zh.md" @@ -0,0 +1,90 @@ +# [333. 最大 BST 子树](https://leetcode-cn.com/problems/largest-bst-subtree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0333.Largest%20BST%20Subtree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,找到其中最大的二叉搜索树(BST)子树,并返回该子树的大小。其中,最大指的是子树节点数最多的。

    + +

    二叉搜索树(BST)中的所有节点都具备以下属性:

    + +
      +
    • +

      左子树的值小于其父(根)节点的值。

      +
    • +
    • +

      右子树的值大于其父(根)节点的值。

      +
    • +
    + +

    注意:

    + +
      +
    • 子树必须包含其所有后代。
    • +
    + +

    进阶:

    + +
      +
    • 你能想出 O(n) 时间复杂度的解法吗?
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [10,5,15,1,8,null,7]
    +输出:3
    +解释:本例中最大的 BST 子树是高亮显示的子树。返回值是子树的大小,即 3 。
    + +

    示例 2:

    + +
    +输入:root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树上节点数目的范围是 [0, 104]
    • +
    • -104 <= Node.val <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0334.leetcode334 Increasing Triplet Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0334.leetcode334 Increasing Triplet Subsequence-zh.md" new file mode 100644 index 00000000..75ed958b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0334.leetcode334 Increasing Triplet Subsequence-zh.md" @@ -0,0 +1,80 @@ +# [334. 递增的三元子序列](https://leetcode-cn.com/problems/increasing-triplet-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0334.Increasing%20Triplet%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。

    + +

    如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,4,5]
    +输出:true
    +解释:任何 i < j < k 的三元组都满足题意
    +
    + +

    示例 2:

    + +
    +输入:nums = [5,4,3,2,1]
    +输出:false
    +解释:不存在满足题意的三元组
    + +

    示例 3:

    + +
    +输入:nums = [2,1,5,0,4,6]
    +输出:true
    +解释:三元组 (3, 4, 5) 满足题意,因为 nums[3] == 0 < nums[4] == 4 < nums[5] == 6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    + +

     

    + +

    进阶:你能实现时间复杂度为 O(n) ,空间复杂度为 O(1) 的解决方案吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0335.leetcode335 Self Crossing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0335.leetcode335 Self Crossing-zh.md" new file mode 100644 index 00000000..17109ead --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0335.leetcode335 Self Crossing-zh.md" @@ -0,0 +1,77 @@ +# [335. 路径交叉](https://leetcode-cn.com/problems/self-crossing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0335.Self%20Crossing/README_EN.md) + +## 题目描述 + + + +

    给定一个含有 n 个正数的数组 x。从点 (0,0) 开始,先向北移动 x[0] 米,然后向西移动 x[1] 米,向南移动 x[2] 米,向东移动 x[3] 米,持续移动。也就是说,每次移动后你的方位会发生逆时针变化。

    + +

    编写一个 O(1) 空间复杂度的一趟扫描算法,判断你所经过的路径是否相交。

    + +

     

    + +

    示例 1:

    + +
    ┌───┐
    +│   │
    +└───┼──>
    +    │
    +
    +输入: [2,1,1,2]
    +输出: true 
    +
    + +

    示例 2:

    + +
    ┌──────┐
    +│      │
    +│
    +│
    +└────────────>
    +
    +输入: [1,2,3,4]
    +输出: false 
    +
    + +

    示例 3:

    + +
    ┌───┐
    +│   │
    +└───┼>
    +
    +输入: [1,1,1,1]
    +输出: true 
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0336.leetcode336 Palindrome Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0336.leetcode336 Palindrome Pairs-zh.md" new file mode 100644 index 00000000..11e7a6b5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0336.leetcode336 Palindrome Pairs-zh.md" @@ -0,0 +1,73 @@ +# [336. 回文对](https://leetcode-cn.com/problems/palindrome-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0336.Palindrome%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给定一组 互不相同 的单词, 找出所有 不同 的索引对 (i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。

    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["abcd","dcba","lls","s","sssll"]
    +输出:[[0,1],[1,0],[3,2],[2,4]] 
    +解释:可拼接成的回文串为 ["dcbaabcd","abcddcba","slls","llssssll"]
    +
    + +

    示例 2:

    + +
    +输入:words = ["bat","tab","cat"]
    +输出:[[0,1],[1,0]] 
    +解释:可拼接成的回文串为 ["battab","tabbat"]
    + +

    示例 3:

    + +
    +输入:words = ["a",""]
    +输出:[[0,1],[1,0]]
    +
    +  + +

    提示:

    + +
      +
    • 1 <= words.length <= 5000
    • +
    • 0 <= words[i].length <= 300
    • +
    • words[i] 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0337.leetcode337 House Robber III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0337.leetcode337 House Robber III-zh.md" new file mode 100644 index 00000000..4ccc5f19 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0337.leetcode337 House Robber III-zh.md" @@ -0,0 +1,69 @@ +# [337. 打家劫舍 III](https://leetcode-cn.com/problems/house-robber-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0337.House%20Robber%20III/README_EN.md) + +## 题目描述 + + + +

    在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。

    + +

    计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。

    + +

    示例 1:

    + +
    输入: [3,2,3,null,3,null,1]
    +
    +     3
    +    / \
    +   2   3
    +    \   \ 
    +     3   1
    +
    +输出: 7 
    +解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
    + +

    示例 2:

    + +
    输入: [3,4,5,1,3,null,1]
    +
    +     3
    +    / \
    +   4   5
    +  / \   \ 
    + 1   3   1
    +
    +输出: 9
    +解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0338.leetcode338 Counting Bits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0338.leetcode338 Counting Bits-zh.md" new file mode 100644 index 00000000..588dd9ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0338.leetcode338 Counting Bits-zh.md" @@ -0,0 +1,58 @@ +# [338. 比特位计数](https://leetcode-cn.com/problems/counting-bits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0338.Counting%20Bits/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 ,计算其二进制数中的 1 的数目并将它们作为数组返回。

    + +

    示例 1:

    + +
    输入: 2
    +输出: [0,1,1]
    + +

    示例 2:

    + +
    输入: 5
    +输出: [0,1,1,2,1,2]
    + +

    进阶:

    + +
      +
    • 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
    • +
    • 要求算法的空间复杂度为O(n)
    • +
    • 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0339.leetcode339 Nested List Weight Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0339.leetcode339 Nested List Weight Sum-zh.md" new file mode 100644 index 00000000..7d2bcbc1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0339.leetcode339 Nested List Weight Sum-zh.md" @@ -0,0 +1,237 @@ +# [339. 嵌套列表权重和](https://leetcode-cn.com/problems/nested-list-weight-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0339.Nested%20List%20Weight%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个嵌套的整数列表 nestedList ,每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。

    + +

    整数的 深度 是其在列表内部的嵌套层数。例如,嵌套列表 [1,[2,2],[[3],2],1] 中每个整数的值就是其深度。

    + +

    请返回该列表按深度加权后所有整数的总和。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:nestedList = [[1,1],2,[1,1]]
    +输出:10 
    +解释:因为列表中有四个深度为 2 的 1 ,和一个深度为 1 的 2。
    + +

    示例 2:

    + +
    +输入:nestedList = [1,[4,[6]]]
    +输出:27 
    +解释:一个深度为 1 的 1,一个深度为 2 的 4,一个深度为 3 的 6。所以,1 + 4*2 + 6*3 = 27。
    + +

    示例 3:

    + +
    +输入:nestedList = [0]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nestedList.length <= 50
    • +
    • 嵌套列表中整数的值在范围 [-100, 100]
    • +
    • 任何整数的最大 深度 都小于或等于 50
    • +
    + +## 解法 + + + +DFS 实现。 + + + +### **Python3** + + + +```python +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger: +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ +class Solution: + def depthSum(self, nestedList: List[NestedInteger]) -> int: + def dfs(nestedList, depth): + depth_sum = 0 + for item in nestedList: + if item.isInteger(): + depth_sum += item.getInteger() * depth + else: + depth_sum += dfs(item.getList(), depth + 1) + return depth_sum + return dfs(nestedList, 1) +``` + +### **Java** + + + +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public int depthSum(List nestedList) { + return dfs(nestedList, 1); + } + + private int dfs(List nestedList, int depth) { + int depthSum = 0; + for (NestedInteger item : nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth + 1); + } + } + return depthSum; + } +} +``` + +### **JavaScript** + +```js +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * function NestedInteger() { + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * @return {boolean} + * this.isInteger = function() { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * @return {integer} + * this.getInteger = function() { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * @return {void} + * this.setInteger = function(value) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * @return {void} + * this.add = function(elem) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, if it holds a nested list + * Return null if this NestedInteger holds a single integer + * @return {NestedInteger[]} + * this.getList = function() { + * ... + * }; + * }; + */ +/** + * @param {NestedInteger[]} nestedList + * @return {number} + */ +var depthSum = function (nestedList) { + const dfs = (nestedList, depth) => { + let depthSum = 0; + for (const item of nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth + 1); + } + } + return depthSum; + }; + return dfs(nestedList, 1); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0340.leetcode340 Longest Substring with At Most K Distinct Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0340.leetcode340 Longest Substring with At Most K Distinct Characters-zh.md" new file mode 100644 index 00000000..df3c0370 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0340.leetcode340 Longest Substring with At Most K Distinct Characters-zh.md" @@ -0,0 +1,53 @@ +# [340. 至多包含 K 个不同字符的最长子串](https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0340.Longest%20Substring%20with%20At%20Most%20K%20Distinct%20Characters/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T

    + +

    示例 1:

    + +
    输入: s = "eceba", k = 2
    +输出: 3
    +解释:  T 为 "ece",所以长度为 3。
    + +

    示例 2:

    + +
    输入: s = "aa", k = 1
    +输出: 2
    +解释: 则 T 为 "aa",所以长度为 2。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0341.leetcode341 Flatten Nested List Iterator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0341.leetcode341 Flatten Nested List Iterator-zh.md" new file mode 100644 index 00000000..1258d03b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0341.leetcode341 Flatten Nested List Iterator-zh.md" @@ -0,0 +1,156 @@ +# [341. 扁平化嵌套列表迭代器](https://leetcode-cn.com/problems/flatten-nested-list-iterator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0341.Flatten%20Nested%20List%20Iterator/README_EN.md) + +## 题目描述 + + + +

    给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。

    + +

    列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。

    + +

     

    + +

    示例 1:

    + +
    输入: [[1,1],2,[1,1]]
    +输出: [1,1,2,1,1]
    +解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]
    + +

    示例 2:

    + +
    输入: [1,[4,[6]]]
    +输出: [1,4,6]
    +解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger: +# def isInteger(self) -> bool: +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# """ +# +# def getInteger(self) -> int: +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# """ +# +# def getList(self) -> [NestedInteger]: +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# """ + +class NestedIterator: + def __init__(self, nestedList: [NestedInteger]): + def dfs(nestedList): + for e in nestedList: + if e.isInteger(): + self.vals.append(e.getInteger()) + else: + dfs(e.getList()) + + self.vals = [] + dfs(nestedList) + self.cur = 0 + + def next(self) -> int: + res = self.vals[self.cur] + self.cur += 1 + return res + + def hasNext(self) -> bool: + return self.cur < len(self.vals) + +# Your NestedIterator object will be instantiated and called as such: +# i, v = NestedIterator(nestedList), [] +# while i.hasNext(): v.append(i.next()) +``` + +### **Java** + + + +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return null if this NestedInteger holds a single integer + * public List getList(); + * } + */ +public class NestedIterator implements Iterator { + + private List vals; + + private Iterator cur; + + public NestedIterator(List nestedList) { + vals = new ArrayList<>(); + dfs(nestedList); + cur = vals.iterator(); + } + + @Override + public Integer next() { + return cur.next(); + } + + @Override + public boolean hasNext() { + return cur.hasNext(); + } + + private void dfs(List nestedList) { + for (NestedInteger e : nestedList) { + if (e.isInteger()) { + vals.add(e.getInteger()); + } else { + dfs(e.getList()); + } + } + } +} + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i = new NestedIterator(nestedList); + * while (i.hasNext()) v[f()] = i.next(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0342.leetcode342 Power of Four-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0342.leetcode342 Power of Four-zh.md" new file mode 100644 index 00000000..5f0e781b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0342.leetcode342 Power of Four-zh.md" @@ -0,0 +1,126 @@ +# [342. 4的幂](https://leetcode-cn.com/problems/power-of-four) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0342.Power%20of%20Four/README_EN.md) + +## 题目描述 + + + +

    给定一个整数,写一个函数来判断它是否是 4 的幂次方。如果是,返回 true ;否则,返回 false

    + +

    整数 n 是 4 的幂次方需满足:存在整数 x 使得 n == 4x

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 16
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:n = 5
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:n = 1
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • -231 <= n <= 231 - 1
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你能不使用循环或者递归来完成本题吗?
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 and (n & 0xaaaaaaaa) == 0 +``` + +### **Java** + + + +```java +class Solution { + public boolean isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function(n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; +}; +``` + +### **Go** + +```go +func isPowerOfFour(n int) bool { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0 +} +``` + +### **TypeScript** + +```ts +function isPowerOfFour(n: number): boolean { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0343.leetcode343 Integer Break-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0343.leetcode343 Integer Break-zh.md" new file mode 100644 index 00000000..173f3c51 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0343.leetcode343 Integer Break-zh.md" @@ -0,0 +1,54 @@ +# [343. 整数拆分](https://leetcode-cn.com/problems/integer-break) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0343.Integer%20Break/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

    + +

    示例 1:

    + +
    输入: 2
    +输出: 1
    +解释: 2 = 1 + 1, 1 × 1 = 1。
    + +

    示例 2:

    + +
    输入: 10
    +输出: 36
    +解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
    + +

    说明: 你可以假设 不小于 2 且不大于 58。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0344.leetcode344 Reverse String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0344.leetcode344 Reverse String-zh.md" new file mode 100644 index 00000000..acdb8eb2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0344.leetcode344 Reverse String-zh.md" @@ -0,0 +1,75 @@ +# [344. 反转字符串](https://leetcode-cn.com/problems/reverse-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0344.Reverse%20String/README_EN.md) + +## 题目描述 + + + +

    编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

    + +

    不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

    + +

    你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

    + +

     

    + +

    示例 1:

    + +
    输入:["h","e","l","l","o"]
    +输出:["o","l","l","e","h"]
    +
    + +

    示例 2:

    + +
    输入:["H","a","n","n","a","h"]
    +输出:["h","a","n","n","a","H"]
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + s[:] = s[::-1] +``` + +### **Java** + + + +```java +class Solution { + public void reverseString(char[] s) { + int n; + if (s == null || (n = s.length) < 2) return; + int i = 0, j = n - 1; + while (i < j) { + char t = s[i]; + s[i] = s[j]; + s[j] = t; + ++i; + --j; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0345.leetcode345 Reverse Vowels of a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0345.leetcode345 Reverse Vowels of a String-zh.md" new file mode 100644 index 00000000..b8fac287 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0345.leetcode345 Reverse Vowels of a String-zh.md" @@ -0,0 +1,102 @@ +# [345. 反转字符串中的元音字母](https://leetcode-cn.com/problems/reverse-vowels-of-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0345.Reverse%20Vowels%20of%20a%20String/README_EN.md) + +## 题目描述 + + + +

    编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

    + +

     

    + +

    示例 1:

    + +
    输入:"hello"
    +输出:"holle"
    +
    + +

    示例 2:

    + +
    输入:"leetcode"
    +输出:"leotcede"
    + +

     

    + +

    提示:

    + +
      +
    • 元音字母不包含字母 "y" 。
    • +
    + + +## 解法 + + + +将字符串转为字符数组(或列表),定义双指针 i、j,分别指向数组(列表)头部和尾部,当 i、j 指向的字符均为元音字母时,进行交换。 + +依次遍历,当 `i >= j` 时,遍历结束。将字符数组(列表)转为字符串返回即可。 + + + +### **Python3** + + + +```python +class Solution: + def reverseVowels(self, s: str) -> str: + vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} + i, j = 0, len(s) - 1 + chars = list(s) + while i < j: + if chars[i] not in vowels: + i += 1 + continue + if chars[j] not in vowels: + j -= 1 + continue + chars[i], chars[j] = chars[j], chars[i] + i += 1 + j -= 1 + return ''.join(chars) +``` + +### **Java** + + + +```java +class Solution { + public String reverseVowels(String s) { + Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); + int i = 0, j = s.length() - 1; + char[] chars = s.toCharArray(); + while (i < j) { + if (!vowels.contains(chars[i])) { + ++i; + continue; + } + if (!vowels.contains(chars[j])) { + --j; + continue; + } + char t = chars[i]; + chars[i] = chars[j]; + chars[j] = t; + ++i; + --j; + } + return new String(chars); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0346.leetcode346 Moving Average from Data Stream-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0346.leetcode346 Moving Average from Data Stream-zh.md" new file mode 100644 index 00000000..58b67a01 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0346.leetcode346 Moving Average from Data Stream-zh.md" @@ -0,0 +1,125 @@ +# [346. 数据流中的移动平均值](https://leetcode-cn.com/problems/moving-average-from-data-stream) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0346.Moving%20Average%20from%20Data%20Stream/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算其所有整数的移动平均值。

    + +

    实现 MovingAverage 类:

    + +
      +
    • MovingAverage(int size) 用窗口大小 size 初始化对象。
    • +
    • double next(int val) 计算并返回数据流中最后 size 个值的移动平均值。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["MovingAverage", "next", "next", "next", "next"]
    +[[3], [1], [10], [3], [5]]
    +输出:
    +[null, 1.0, 5.5, 4.66667, 6.0]
    +
    +解释:
    +MovingAverage movingAverage = new MovingAverage(3);
    +movingAverage.next(1); // 返回 1.0 = 1 / 1
    +movingAverage.next(10); // 返回 5.5 = (1 + 10) / 2
    +movingAverage.next(3); // 返回 4.66667 = (1 + 10 + 3) / 3
    +movingAverage.next(5); // 返回 6.0 = (10 + 3 + 5) / 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= size <= 1000
    • +
    • -105 <= val <= 105
    • +
    • 最多调用 next 方法 104
    • +
    + +## 解法 + + + +“循环数组”实现。 + + + +### **Python3** + + + +```python +class MovingAverage: + + def __init__(self, size: int): + """ + Initialize your data structure here. + """ + self.size = size + self.data = [0] * size + self.count = 0 + self.s = 0 + + def next(self, val: int) -> float: + idx = self.count % self.size + old_val = self.data[idx] + self.data[idx] = val + self.s += (val - old_val) + self.count += 1 + return self.s / min(self.size, self.count) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) +``` + +### **Java** + + + +```java +class MovingAverage { + private int size; + private int[] data; + private int count; + private int s; + + /** Initialize your data structure here. */ + public MovingAverage(int size) { + this.size = size; + this.data = new int[size]; + } + + public double next(int val) { + int idx = count % size; + int oldVal = data[idx]; + data[idx] = val; + s += (val - oldVal); + ++count; + return s * 1.0 / Math.min(size, count); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0347.leetcode347 Top K Frequent Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0347.leetcode347 Top K Frequent Elements-zh.md" new file mode 100644 index 00000000..6a331638 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0347.leetcode347 Top K Frequent Elements-zh.md" @@ -0,0 +1,114 @@ +# [347. 前 K 个高频元素](https://leetcode-cn.com/problems/top-k-frequent-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0347.Top%20K%20Frequent%20Elements/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

    + +

     

    + +

    示例 1:

    + +
    +输入: nums = [1,1,1,2,2,3], k = 2
    +输出: [1,2]
    +
    + +

    示例 2:

    + +
    +输入: nums = [1], k = 1
    +输出: [1]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • k 的取值范围是 [1, 数组中不相同的元素的个数]
    • +
    • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
    • +
    + +

     

    + +

    进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。

    + + +## 解法 + + + +“桶排序”实现。 + + + +### **Python3** + + + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + counter = collections.Counter(nums) + buckets = [[] for _ in range(len(nums) + 1)] + for num, freq in counter.items(): + buckets[freq].append(num) + i, res = len(nums), [] + while k > 0 and i >= 0: + if buckets[i]: + for num in buckets[i]: + if k <= 0: + break + res.append(num) + k -= 1 + i -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map counter = new HashMap<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + List[] buckets = new List[nums.length + 1]; + for (Map.Entry entry : counter.entrySet()) { + int num = entry.getKey(); + int freq = entry.getValue(); + if (buckets[freq] == null) { + buckets[freq] = new ArrayList<>(); + } + buckets[freq].add(num); + } + int[] res = new int[k]; + for (int i = nums.length; i >= 0 && k > 0; --i) { + if (buckets[i] != null) { + for (int num : buckets[i]) { + if (k <= 0) { + break; + } + res[--k] = num; + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0348.leetcode348 Design Tic-Tac-Toe0348.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0348.leetcode348 Design Tic-Tac-Toe0348.md" new file mode 100644 index 00000000..fd1aa553 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0348.leetcode348 Design Tic-Tac-Toe0348.md" @@ -0,0 +1,170 @@ +# [348. 设计井字棋](https://leetcode-cn.com/problems/design-tic-tac-toe) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0348.Design%20Tic-Tac-Toe/README_EN.md) + +## 题目描述 + + + +

    请在 n × n 的棋盘上,实现一个判定井字棋(Tic-Tac-Toe)胜负的神器,判断每一次玩家落子后,是否有胜出的玩家。

    + +

    在这个井字棋游戏中,会有 2 名玩家,他们将轮流在棋盘上放置自己的棋子。

    + +

    在实现这个判定器的过程中,你可以假设以下这些规则一定成立:

    + +

          1. 每一步棋都是在棋盘内的,并且只能被放置在一个空的格子里;

    + +

          2. 一旦游戏中有一名玩家胜出的话,游戏将不能再继续;

    + +

          3. 一个玩家如果在同一行、同一列或者同一斜对角线上都放置了自己的棋子,那么他便获得胜利。

    + +

    示例:

    + +
    给定棋盘边长 n = 3, 玩家 1 的棋子符号是 "X",玩家 2 的棋子符号是 "O"。
    +
    +TicTacToe toe = new TicTacToe(3);
    +
    +toe.move(0, 0, 1); -> 函数返回 0 (此时,暂时没有玩家赢得这场对决)
    +|X| | |
    +| | | |    // 玩家 1 在 (0, 0) 落子。
    +| | | |
    +
    +toe.move(0, 2, 2); -> 函数返回 0 (暂时没有玩家赢得本场比赛)
    +|X| |O|
    +| | | |    // 玩家 2 在 (0, 2) 落子。
    +| | | |
    +
    +toe.move(2, 2, 1); -> 函数返回 0 (暂时没有玩家赢得比赛)
    +|X| |O|
    +| | | |    // 玩家 1 在 (2, 2) 落子。
    +| | |X|
    +
    +toe.move(1, 1, 2); -> 函数返回 0 (暂没有玩家赢得比赛)
    +|X| |O|
    +| |O| |    // 玩家 2 在 (1, 1) 落子。
    +| | |X|
    +
    +toe.move(2, 0, 1); -> 函数返回 0 (暂无玩家赢得比赛)
    +|X| |O|
    +| |O| |    // 玩家 1 在 (2, 0) 落子。
    +|X| |X|
    +
    +toe.move(1, 0, 2); -> 函数返回 0 (没有玩家赢得比赛)
    +|X| |O|
    +|O|O| |    // 玩家 2 在 (1, 0) 落子.
    +|X| |X|
    +
    +toe.move(2, 1, 1); -> 函数返回 1 (此时,玩家 1 赢得了该场比赛)
    +|X| |O|
    +|O|O| |    // 玩家 1 在 (2, 1) 落子。
    +|X|X|X|
    +
    + +

     

    + +

    进阶:
    +您有没有可能将每一步的 move() 操作优化到比 O(n2) 更快吗?

    + +## 解法 + + + +思路同[1275. 找出井字棋的获胜者](solution/1200-1299/1275.Find%20Winner%20on%20a%20Tic%20Tac%20Toe%20Game/README)。 + + + +### **Python3** + + + +```python +class TicTacToe: + + def __init__(self, n: int): + """ + Initialize your data structure here. + """ + self.n = n + self.counter = [[0] * ((n << 1) + 2) for _ in range(2)] + + def move(self, row: int, col: int, player: int) -> int: + """ + Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. + """ + n = self.n + self.counter[player - 1][row] += 1 + self.counter[player - 1][col + n] += 1 + if row == col: + self.counter[player - 1][n << 1] += 1 + if row + col == n - 1: + self.counter[player - 1][(n << 1) + 1] += 1 + if self.counter[player - 1][row] == n or self.counter[player - 1][col + n] == n or self.counter[player - 1][n << 1] == n or self.counter[player - 1][(n << 1) + 1] == n: + return player + return 0 + + +# Your TicTacToe object will be instantiated and called as such: +# obj = TicTacToe(n) +# param_1 = obj.move(row,col,player) +``` + +### **Java** + + + +```java +class TicTacToe { + private int n; + private int[][] counter; + + /** Initialize your data structure here. */ + public TicTacToe(int n) { + counter = new int[2][(n << 1) + 2]; + this.n = n; + } + + /** Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. */ + public int move(int row, int col, int player) { + counter[player - 1][row] += 1; + counter[player - 1][col + n] += 1; + if (row == col) { + counter[player - 1][n << 1] += 1; + } + if (row + col == n - 1) { + counter[player - 1][(n << 1) + 1] += 1; + } + if (counter[player - 1][row] == n || counter[player - 1][col + n] == n || counter[player - 1][n << 1] == n || counter[player - 1][(n << 1) + 1] == n) { + return player; + } + return 0; + } +} + +/** + * Your TicTacToe object will be instantiated and called as such: + * TicTacToe obj = new TicTacToe(n); + * int param_1 = obj.move(row,col,player); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0349.leetcode349 Intersection of Two Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0349.leetcode349 Intersection of Two Arrays-zh.md" new file mode 100644 index 00000000..deea4e4f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0349.leetcode349 Intersection of Two Arrays-zh.md" @@ -0,0 +1,113 @@ +# [349. 两个数组的交集](https://leetcode-cn.com/problems/intersection-of-two-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0349.Intersection%20of%20Two%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给定两个数组,编写一个函数来计算它们的交集。

    + +

     

    + +

    示例 1:

    + +
    输入:nums1 = [1,2,2,1], nums2 = [2,2]
    +输出:[2]
    +
    + +

    示例 2:

    + +
    输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    +输出:[9,4]
    + +

     

    + +

    说明:

    + +
      +
    • 输出结果中的每个元素一定是唯一的。
    • +
    • 我们可以不考虑输出结果的顺序。
    • +
    + + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + s = set(nums1) + res = set() + for num in nums2: + if num in s: + res.add(num) + return list(res) +``` + +### **Java** + + + +```java +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + Set s = new HashSet<>(); + for (int num : nums1) { + s.add(num); + } + Set res = new HashSet<>(); + for (int num : nums2) { + if (s.contains(num)) { + res.add(num); + } + } + int[] output = new int[res.size()]; + int i = 0; + for (int num : res) { + output[i++] = num; + } + return output; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function(nums1, nums2) { + const s = new Set(); + for (const num of nums1) { + s.add(num); + } + let res = new Set(); + for (const num of nums2) { + if (s.has(num)) { + res.add(num); + } + } + return [...res]; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0350.leetcode350 Intersection of Two Arrays II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0350.leetcode350 Intersection of Two Arrays II-zh.md" new file mode 100644 index 00000000..e6a9360e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0350.leetcode350 Intersection of Two Arrays II-zh.md" @@ -0,0 +1,125 @@ +# [350. 两个数组的交集 II](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0350.Intersection%20of%20Two%20Arrays%20II/README_EN.md) + +## 题目描述 + + + +

    给定两个数组,编写一个函数来计算它们的交集。

    + +

     

    + +

    示例 1:

    + +
    输入:nums1 = [1,2,2,1], nums2 = [2,2]
    +输出:[2,2]
    +
    + +

    示例 2:

    + +
    输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    +输出:[4,9]
    + +

     

    + +

    说明:

    + +
      +
    • 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
    • +
    • 我们可以不考虑输出结果的顺序。
    • +
    + +

    进阶

    + +
      +
    • 如果给定的数组已经排好序呢?你将如何优化你的算法?
    • +
    • 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
    • +
    • 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
    • +
    + + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +class Solution: + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + counter = collections.Counter(nums1) + res = [] + for num in nums2: + if counter[num] > 0: + res.append(num) + counter[num] -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] intersect(int[] nums1, int[] nums2) { + Map counter = new HashMap<>(); + for (int num : nums1) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + List intersection = new ArrayList<>(); + for (int num : nums2) { + int val = counter.getOrDefault(num, 0); + if (val > 0) { + intersection.add(num); + counter.put(num, val - 1); + } + } + int i = 0; + int[] res = new int[intersection.size()]; + for (int num : intersection) { + res[i++] = num; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function(nums1, nums2) { + const counter = {}; + for (const num of nums1) { + counter[num] = (counter[num] || 0) + 1; + } + let res = []; + for (const num of nums2) { + if (counter[num] > 0) { + res.push(num); + counter[num] -= 1; + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0351.leetcode351 Android Unlock Patterns-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0351.leetcode351 Android Unlock Patterns-zh.md" new file mode 100644 index 00000000..fe639a78 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0351.leetcode351 Android Unlock Patterns-zh.md" @@ -0,0 +1,87 @@ +# [351. 安卓系统手势解锁](https://leetcode-cn.com/problems/android-unlock-patterns) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0351.Android%20Unlock%20Patterns/README_EN.md) + +## 题目描述 + + + +

    我们都知道安卓有个手势解锁的界面,是一个 3 x 3 的点所绘制出来的网格。用户可以设置一个 “解锁模式” ,通过连接特定序列中的点,形成一系列彼此连接的线段,每个线段的端点都是序列中两个连续的点。如果满足以下两个条件,则 k 点序列是有效的解锁模式:

    + +
      +
    • 解锁模式中的所有点 互不相同
    • +
    • 假如模式中两个连续点的线段需要经过其他点,那么要经过的点必须事先出现在序列中(已经经过),不能跨过任何还未被经过的点。
    • +
    + +

     

    + +

    以下是一些有效和无效解锁模式的示例:

    + +

    +  + +
      +
    • 无效手势:[4,1,3,6] ,连接点 1 和点 3 时经过了未被连接过的 2 号点。
    • +
    • 无效手势:[4,1,9,2] ,连接点 1 和点 9 时经过了未被连接过的 5 号点。
    • +
    • 有效手势:[2,4,1,3,6] ,连接点 1 和点 3 是有效的,因为虽然它经过了点 2 ,但是点 2 在该手势中之前已经被连过了。
    • +
    • 有效手势:[6,5,4,1,9,2] ,连接点 1 和点 9 是有效的,因为虽然它经过了按键 5 ,但是点 5 在该手势中之前已经被连过了。
    • +
    + +

    给你两个整数,分别为 ​​mn ,那么请你统计一下有多少种 不同且有效的解锁模式 ,是 至少 需要经过 m 个点,但是 不超过 n 个点的。

    + +

    两个解锁模式 不同 需满足:经过的点不同或者经过点的顺序不同。

    + +

     

    + +

    示例 1:

    + +
    +输入:m = 1, n = 1
    +输出:9
    +
    + +

    示例 2:

    + +
    +输入:m = 1, n = 2
    +输出:65
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m, n <= 9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0352.leetcode352 Data Stream as Disjoint Intervals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0352.leetcode352 Data Stream as Disjoint Intervals-zh.md" new file mode 100644 index 00000000..c2ed1cce --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0352.leetcode352 Data Stream as Disjoint Intervals-zh.md" @@ -0,0 +1,57 @@ +# [352. 将数据流变为多个不相交区间](https://leetcode-cn.com/problems/data-stream-as-disjoint-intervals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0352.Data%20Stream%20as%20Disjoint%20Intervals/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数的数据流输入 a1,a2,…,an,…,将到目前为止看到的数字总结为不相交的区间列表。

    + +

    例如,假设数据流中的整数为 1,3,7,2,6,…,每次的总结为:

    + +
    [1, 1]
    +[1, 1], [3, 3]
    +[1, 1], [3, 3], [7, 7]
    +[1, 3], [7, 7]
    +[1, 3], [6, 7]
    +
    + +

     

    + +

    进阶:
    +如果有很多合并,并且与数据流的大小相比,不相交区间的数量很小,该怎么办?

    + +

    提示:
    +特别感谢 @yunhong 提供了本问题和其测试用例。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0353.leetcode353 Design Snake Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0353.leetcode353 Design Snake Game-zh.md" new file mode 100644 index 00000000..1b708bc5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0353.leetcode353 Design Snake Game-zh.md" @@ -0,0 +1,92 @@ +# [353. 贪吃蛇](https://leetcode-cn.com/problems/design-snake-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0353.Design%20Snake%20Game/README_EN.md) + +## 题目描述 + + + +

    请你设计一个 贪吃蛇游戏,该游戏将会在一个 屏幕尺寸 = 宽度 x 高度 的屏幕上运行。如果你不熟悉这个游戏,可以 点击这里 在线试玩。

    + +

    起初时,蛇在左上角的 (0, 0) 位置,身体长度为 1 个单位。

    + +

    你将会被给出一个数组形式的食物位置序列 food ,其中 food[i] = (ri, ci) 。当蛇吃到食物时,身子的长度会增加 1 个单位,得分也会 +1

    + +

    食物不会同时出现,会按列表的顺序逐一显示在屏幕上。比方讲,第一个食物被蛇吃掉后,第二个食物才会出现。

    + +

    当一个食物在屏幕上出现时,保证 不会 出现在被蛇身体占据的格子里。

    + +

    如果蛇越界(与边界相撞)或者头与 移动后 的身体相撞(即,身长为 4 的蛇无法与自己相撞),游戏结束。

    + +

    实现 SnakeGame 类:

    + +
      +
    • SnakeGame(int width, int height, int[][] food) 初始化对象,屏幕大小为 height x width ,食物位置序列为 food
    • +
    • int move(String direction) 返回蛇在方向 direction 上移动后的得分。如果游戏结束,返回 -1
    • +
    +  + +

    示例 1:

    + +
    +输入:
    +["SnakeGame", "move", "move", "move", "move", "move", "move"]
    +[[3, 2, [[1, 2], [0, 1]]], ["R"], ["D"], ["R"], ["U"], ["L"], ["U"]]
    +输出:
    +[null, 0, 0, 1, 1, 2, -1]
    +
    +解释:
    +SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]);
    +snakeGame.move("R"); // 返回 0
    +snakeGame.move("D"); // 返回 0
    +snakeGame.move("R"); // 返回 1 ,蛇吃掉了第一个食物,同时第二个食物出现在 (0, 1)
    +snakeGame.move("U"); // 返回 1
    +snakeGame.move("L"); // 返回 2 ,蛇吃掉了第二个食物,没有出现更多食物
    +snakeGame.move("U"); // 返回 -1 ,蛇与边界相撞,游戏结束
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= width, height <= 104
    • +
    • 1 <= food.length <= 50
    • +
    • food[i].length == 2
    • +
    • 0 <= ri < height
    • +
    • 0 <= ci < width
    • +
    • direction.length == 1
    • +
    • direction is 'U', 'D', 'L', or 'R'.
    • +
    • 最多调用 104move 方法
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0354.leetcode354 Russian Doll Envelopes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0354.leetcode354 Russian Doll Envelopes-zh.md" new file mode 100644 index 00000000..b234cebc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0354.leetcode354 Russian Doll Envelopes-zh.md" @@ -0,0 +1,109 @@ +# [354. 俄罗斯套娃信封问题](https://leetcode-cn.com/problems/russian-doll-envelopes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0354.Russian%20Doll%20Envelopes/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。

    + +

    当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

    + +

    请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

    + +

    注意:不允许旋转信封。

    +  + +

    示例 1:

    + +
    +输入:envelopes = [[5,4],[6,4],[6,7],[2,3]]
    +输出:3
    +解释:最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
    + +

    示例 2:

    + +
    +输入:envelopes = [[1,1],[1,1],[1,1]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= envelopes.length <= 5000
    • +
    • envelopes[i].length == 2
    • +
    • 1 <= wi, hi <= 104
    • +
    + + +## 解法 + + + +排序 + [最长递增子序列](/solution/0300-0399/0300.Longest%20Increasing%20Subsequence/README.md)。 + +按 w 进行升序排序,若 w 相同则按 h 降序排序。然后问题转换为求 h 数组的最长递增子序列长度。 + + + +### **Python3** + + + +```python +class Solution: + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: + if not envelopes: + return 0 + envelopes.sort(key=lambda x: (x[0], -x[1])) + nums = [x[1] for x in envelopes] + n = len(nums) + dp = [1] * n + res = 1 + for i in range(1, n): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + res = max(res, dp[i]) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxEnvelopes(int[][] envelopes) { + int n; + if (envelopes == null || (n = envelopes.length) == 0) return 0; + Arrays.sort(envelopes, (a, b) -> { + return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]; + }); + int[] dp = new int[n]; + Arrays.fill(dp, 1); + int res = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (envelopes[j][1] < envelopes[i][1]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + res = Math.max(res, dp[i]); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0355.leetcode355 Design Twitter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0355.leetcode355 Design Twitter-zh.md" new file mode 100644 index 00000000..7be8734c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0355.leetcode355 Design Twitter-zh.md" @@ -0,0 +1,193 @@ +# [355. 设计推特](https://leetcode-cn.com/problems/design-twitter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0355.Design%20Twitter/README_EN.md) + +## 题目描述 + + + +

    设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文。你的设计需要支持以下的几个功能:

    + +
      +
    1. postTweet(userId, tweetId): 创建一条新的推文
    2. +
    3. getNewsFeed(userId): 检索最近的十条推文。每个推文都必须是由此用户关注的人或者是用户自己发出的。推文必须按照时间顺序由最近的开始排序。
    4. +
    5. follow(followerId, followeeId): 关注一个用户
    6. +
    7. unfollow(followerId, followeeId): 取消关注一个用户
    8. +
    + +

    示例:

    + +
    +Twitter twitter = new Twitter();
    +
    +// 用户1发送了一条新推文 (用户id = 1, 推文id = 5).
    +twitter.postTweet(1, 5);
    +
    +// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
    +twitter.getNewsFeed(1);
    +
    +// 用户1关注了用户2.
    +twitter.follow(1, 2);
    +
    +// 用户2发送了一个新推文 (推文id = 6).
    +twitter.postTweet(2, 6);
    +
    +// 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5].
    +// 推文id6应当在推文id5之前,因为它是在5之后发送的.
    +twitter.getNewsFeed(1);
    +
    +// 用户1取消关注了用户2.
    +twitter.unfollow(1, 2);
    +
    +// 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文.
    +// 因为用户1已经不再关注用户2.
    +twitter.getNewsFeed(1);
    +
    + +## 解法 + + + +“哈希表 + 堆”实现。 + + + +### **Python3** + + + +```python +class Twitter: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.user_tweets = collections.defaultdict(list) + self.user_following = collections.defaultdict(set) + self.tweets = collections.defaultdict() + self.time = 0 + + def postTweet(self, userId: int, tweetId: int) -> None: + """ + Compose a new tweet. + """ + self.time += 1 + self.user_tweets[userId].append(tweetId) + self.tweets[tweetId] = self.time + + def getNewsFeed(self, userId: int) -> List[int]: + """ + Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. + """ + following = self.user_following[userId] + users = set(following) + users.add(userId) + tweets = [self.user_tweets[u][::-1][:10] for u in users] + tweets = sum(tweets, []) + return heapq.nlargest(10, tweets, key=lambda tweet: self.tweets[tweet]) + + def follow(self, followerId: int, followeeId: int) -> None: + """ + Follower follows a followee. If the operation is invalid, it should be a no-op. + """ + self.user_following[followerId].add(followeeId) + + def unfollow(self, followerId: int, followeeId: int) -> None: + """ + Follower unfollows a followee. If the operation is invalid, it should be a no-op. + """ + following = self.user_following[followerId] + if followeeId in following: + following.remove(followeeId) + + + +# Your Twitter object will be instantiated and called as such: +# obj = Twitter() +# obj.postTweet(userId,tweetId) +# param_2 = obj.getNewsFeed(userId) +# obj.follow(followerId,followeeId) +# obj.unfollow(followerId,followeeId) +``` + +### **Java** + + + +```java +class Twitter { + private Map> userTweets; + private Map> userFollowing; + private Map tweets; + private int time; + + /** Initialize your data structure here. */ + public Twitter() { + userTweets = new HashMap<>(); + userFollowing = new HashMap<>(); + tweets = new HashMap<>(); + time = 0; + } + + /** Compose a new tweet. */ + public void postTweet(int userId, int tweetId) { + List userTweet = userTweets.getOrDefault(userId, new ArrayList<>()); + userTweet.add(tweetId); + userTweets.put(userId, userTweet); + tweets.put(tweetId, ++time); + } + + /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ + public List getNewsFeed(int userId) { + Set following = userFollowing.getOrDefault(userId, new HashSet<>()); + Set users = new HashSet<>(following); + users.add(userId); + PriorityQueue pq = new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a))); + for (Integer u : users) { + List userTweet = userTweets.get(u); + if (userTweet != null && !userTweet.isEmpty()) { + for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) { + pq.offer(userTweet.get(i)); + } + } + } + List res = new ArrayList<>(); + while (!pq.isEmpty() && res.size() < 10) { + res.add(pq.poll()); + } + return res; + } + + /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ + public void follow(int followerId, int followeeId) { + Set following = userFollowing.getOrDefault(followerId, new HashSet<>()); + following.add(followeeId); + userFollowing.put(followerId, following); + } + + /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ + public void unfollow(int followerId, int followeeId) { + Set following = userFollowing.getOrDefault(followerId, new HashSet<>()); + following.remove(followeeId); + userFollowing.put(followerId, following); + } +} + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter obj = new Twitter(); + * obj.postTweet(userId,tweetId); + * List param_2 = obj.getNewsFeed(userId); + * obj.follow(followerId,followeeId); + * obj.unfollow(followerId,followeeId); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0356.leetcode356 Line Reflection-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0356.leetcode356 Line Reflection-zh.md" new file mode 100644 index 00000000..29889ecb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0356.leetcode356 Line Reflection-zh.md" @@ -0,0 +1,105 @@ +# [356. 直线镜像](https://leetcode-cn.com/problems/line-reflection) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0356.Line%20Reflection/README_EN.md) + +## 题目描述 + + + +

    在一个二维平面空间中,给你 n 个点的坐标。问,是否能找出一条平行于 y 轴的直线,让这些点关于这条直线成镜像排布?

    + +

    注意:题目数据中可能有重复的点。

    + +

     

    + +

    进阶:你能找到比 O(n2) 更优的解法吗?

    + +

     

    + +

    示例 1:

    + +
    +输入:points = [[1,1],[-1,1]]
    +输出:true
    +解释:可以找出 x = 0 这条线。
    +
    + +

    示例 2:

    + +
    +输入:points = [[1,1],[-1,-1]]
    +输出:false
    +解释:无法找出这样一条线。
    + +

     

    + +

    提示:

    + +
      +
    • n == points.length
    • +
    • 1 <= n <= 10^4
    • +
    • -10^8 <= points[i][j] <= 10^8
    • +
    + +## 解法 + + + +先找出所有点中的最小、最大的 x 坐标 `minX` 和 `maxX`。若存在满足条件的直线,则直线 `x = (minX + maxX) / 2`。(或者说:`s = minX + maxX`) + +遍历每个点 `point(x, y)`,若 `(s - x, y)` 不在点集里,说明不满足条件,直接返回 false。遍历结束返回 true。 + + + +### **Python3** + + + +```python +class Solution: + def isReflected(self, points: List[List[int]]) -> bool: + min_x, max_x = float('inf'), float('-inf') + point_set = set() + for x, y in points: + min_x = min(min_x, x) + max_x = max(max_x, x) + point_set.add((x, y)) + s = min_x + max_x + for x, y in points: + if (s - x, y) not in point_set: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isReflected(int[][] points) { + int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; + Set pointSet = new HashSet<>(); + for (int[] point : points) { + minX = Math.min(minX, point[0]); + maxX = Math.max(maxX, point[0]); + pointSet.add(point[0] + "." + point[1]); + } + long s = minX + maxX; + for (int[] point : points) { + if (!pointSet.contains((s - point[0]) + "." + point[1])) { + return false; + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0357.leetcode357 Count Numbers with Unique Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0357.leetcode357 Count Numbers with Unique Digits-zh.md" new file mode 100644 index 00000000..58b7e556 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0357.leetcode357 Count Numbers with Unique Digits-zh.md" @@ -0,0 +1,47 @@ +# [357. 计算各个位数不同的数字个数](https://leetcode-cn.com/problems/count-numbers-with-unique-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0357.Count%20Numbers%20with%20Unique%20Digits/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数 n,计算各位数字都不同的数字 x 的个数,其中 0 ≤ x < 10

    + +

    示例:

    + +
    输入: 2
    +输出: 91 
    +解释: 答案应为除去 11,22,33,44,55,66,77,88,99 外,在 [0,100) 区间内的所有数字。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0358.leetcode358 Rearrange String k Distance Apart-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0358.leetcode358 Rearrange String k Distance Apart-zh.md" new file mode 100644 index 00000000..6cc21354 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0358.leetcode358 Rearrange String k Distance Apart-zh.md" @@ -0,0 +1,63 @@ +# [358. K 距离间隔重排字符串](https://leetcode-cn.com/problems/rearrange-string-k-distance-apart) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0358.Rearrange%20String%20k%20Distance%20Apart/README_EN.md) + +## 题目描述 + + + +

    给你一个非空的字符串 s 和一个整数 k,你要将这个字符串中的字母进行重新排列,使得重排后的字符串中相同字母的位置间隔距离至少为 k

    + +

    所有输入的字符串都由小写字母组成,如果找不到距离至少为 k 的重排结果,请返回一个空字符串 ""

    + +

    示例 1:

    + +
    输入: s = "aabbcc", k = 3
    +输出: "abcabc" 
    +解释: 相同的字母在新的字符串中间隔至少 3 个单位距离。
    +
    + +

    示例 2:

    + +
    输入: s = "aaabc", k = 3
    +输出: "" 
    +解释: 没有办法找到可能的重排结果。
    +
    + +

    示例 3:

    + +
    输入: s = "aaadbbcc", k = 2
    +输出: "abacabcd"
    +解释: 相同的字母在新的字符串中间隔至少 2 个单位距离。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0359.leetcode359 Logger Rate Limiter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0359.leetcode359 Logger Rate Limiter-zh.md" new file mode 100644 index 00000000..7d4c890d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0359.leetcode359 Logger Rate Limiter-zh.md" @@ -0,0 +1,165 @@ +# [359. 日志速率限制器](https://leetcode-cn.com/problems/logger-rate-limiter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0359.Logger%20Rate%20Limiter/README_EN.md) + +## 题目描述 + + + +

    请你设计一个日志系统,可以流式接收消息以及它的时间戳。每条 不重复 的消息最多只能每 10 秒打印一次。也就是说,如果在时间戳 t 打印某条消息,那么相同内容的消息直到时间戳变为 t + 10 之前都不会被打印。

    + +

    所有消息都按时间顺序发送。多条消息可能到达同一时间戳。

    + +

    实现 Logger 类:

    + +
      +
    • Logger() 初始化 logger 对象
    • +
    • bool shouldPrintMessage(int timestamp, string message) 如果这条消息 message 在给定的时间戳 timestamp 应该被打印出来,则返回 true ,否则请返回 false
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]
    +[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
    +输出:
    +[null, true, true, false, false, false, true]
    +
    +解释:
    +Logger logger = new Logger();
    +logger.shouldPrintMessage(1, "foo");  // 返回 true ,下一次 "foo" 可以打印的时间戳是 1 + 10 = 11
    +logger.shouldPrintMessage(2, "bar");  // 返回 true ,下一次 "bar" 可以打印的时间戳是 2 + 10 = 12
    +logger.shouldPrintMessage(3, "foo");  // 3 < 11 ,返回 false
    +logger.shouldPrintMessage(8, "bar");  // 8 < 12 ,返回 false
    +logger.shouldPrintMessage(10, "foo"); // 10 < 11 ,返回 false
    +logger.shouldPrintMessage(11, "foo"); // 11 >= 11 ,返回 true ,下一次 "foo" 可以打印的时间戳是 11 + 10 = 21
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= timestamp <= 109
    • +
    • 每个 timestamp 都将按非递减顺序(时间顺序)传递
    • +
    • 1 <= message.length <= 30
    • +
    • 最多调用 104shouldPrintMessage 方法
    • +
    + +## 解法 + + + +哈希表实现。 + + + +### **Python3** + + + +```python +class Logger: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.limiter = {} + + def shouldPrintMessage(self, timestamp: int, message: str) -> bool: + """ + Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. + """ + t = self.limiter.get(message, 0) + if t > timestamp: + return False + self.limiter[message] = timestamp + 10 + return True + + +# Your Logger object will be instantiated and called as such: +# obj = Logger() +# param_1 = obj.shouldPrintMessage(timestamp,message) +``` + +### **Java** + + + +```java +class Logger { + + private Map limiter; + + /** Initialize your data structure here. */ + public Logger() { + limiter = new HashMap<>(); + } + + /** Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. */ + public boolean shouldPrintMessage(int timestamp, String message) { + int t = limiter.getOrDefault(message, 0); + if (t > timestamp) { + return false; + } + limiter.put(message, timestamp + 10); + return true; + } +} + +/** + * Your Logger object will be instantiated and called as such: + * Logger obj = new Logger(); + * boolean param_1 = obj.shouldPrintMessage(timestamp,message); + */ +``` + +### **JavaScript** + +```js +/** + * Initialize your data structure here. + */ +var Logger = function () { + this.limiter = {}; +}; + +/** + * Returns true if the message should be printed in the given timestamp, otherwise returns false. + If this method returns false, the message will not be printed. + The timestamp is in seconds granularity. + * @param {number} timestamp + * @param {string} message + * @return {boolean} + */ +Logger.prototype.shouldPrintMessage = function (timestamp, message) { + const t = this.limiter[message] || 0; + if (t > timestamp) { + return false; + } + this.limiter[message] = timestamp + 10; + return true; +}; + +/** + * Your Logger object will be instantiated and called as such: + * var obj = new Logger() + * var param_1 = obj.shouldPrintMessage(timestamp,message) + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0360.leetcode360 Sort Transformed Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0360.leetcode360 Sort Transformed Array-zh.md" new file mode 100644 index 00000000..5e50ae92 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0360.leetcode360 Sort Transformed Array-zh.md" @@ -0,0 +1,54 @@ +# [360. 有序转化数组](https://leetcode-cn.com/problems/sort-transformed-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0360.Sort%20Transformed%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个已经 排好序 的整数数组 nums 和整数 a、b、c。对于数组中的每一个数 x,计算函数值 f(x) = ax2 + bx + c,请将函数值产生的数组返回。

    + +

    要注意,返回的这个数组必须按照 升序排列,并且我们所期望的解法时间复杂度为 O(n)

    + +

    示例 1:

    + +
    输入: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
    +输出: [3,9,15,33]
    +
    + +

    示例 2:

    + +
    输入: nums = [-4,-2,2,4], a = -1, b = 3, c = 5
    +输出: [-23,-5,1,7]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0361.leetcode361 Bomb Enemy-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0361.leetcode361 Bomb Enemy-zh.md" new file mode 100644 index 00000000..c9e359b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0361.leetcode361 Bomb Enemy-zh.md" @@ -0,0 +1,67 @@ +# [361. 轰炸敌人](https://leetcode-cn.com/problems/bomb-enemy) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0361.Bomb%20Enemy/README_EN.md) + +## 题目描述 + + + +

    想象一下炸弹人游戏,在你面前有一个二维的网格来表示地图,网格中的格子分别被以下三种符号占据:

    + +
      +
    • 'W' 表示一堵墙
    • +
    • 'E' 表示一个敌人
    • +
    • '0'(数字 0)表示一个空位
    • +
    + +

    + +

    请你计算一个炸弹最多能炸多少敌人。

    + +

    由于炸弹的威力不足以穿透墙体,炸弹只能炸到同一行和同一列没被墙体挡住的敌人。

    + +

    注意:你只能把炸弹放在一个空的格子里

    + +

    示例:

    + +
    输入: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
    +输出: 3 
    +解释: 对于如下网格
    +
    +0 E 0 0 
    +E 0 W E 
    +0 E 0 0
    +
    +假如在位置 (1,1) 放置炸弹的话,可以炸到 3 个敌人
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0362.leetcode362 Design Hit Counter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0362.leetcode362 Design Hit Counter-zh.md" new file mode 100644 index 00000000..7c6bc6e1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0362.leetcode362 Design Hit Counter-zh.md" @@ -0,0 +1,135 @@ +# [362. 敲击计数器](https://leetcode-cn.com/problems/design-hit-counter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0362.Design%20Hit%20Counter/README_EN.md) + +## 题目描述 + + + +

    设计一个敲击计数器,使它可以统计在过去5分钟内被敲击次数。

    + +

    每个函数会接收一个时间戳参数(以秒为单位),你可以假设最早的时间戳从1开始,且都是按照时间顺序对系统进行调用(即时间戳是单调递增)。

    + +

    在同一时刻有可能会有多次敲击。

    + +

    示例:

    + +
    HitCounter counter = new HitCounter();
    +
    +// 在时刻 1 敲击一次。
    +counter.hit(1);
    +
    +// 在时刻 2 敲击一次。
    +counter.hit(2);
    +
    +// 在时刻 3 敲击一次。
    +counter.hit(3);
    +
    +// 在时刻 4 统计过去 5 分钟内的敲击次数, 函数返回 3 。
    +counter.getHits(4);
    +
    +// 在时刻 300 敲击一次。
    +counter.hit(300);
    +
    +// 在时刻 300 统计过去 5 分钟内的敲击次数,函数返回 4 。
    +counter.getHits(300);
    +
    +// 在时刻 301 统计过去 5 分钟内的敲击次数,函数返回 3 。
    +counter.getHits(301); 
    +
    + +

    进阶:

    + +

    如果每秒的敲击次数是一个很大的数字,你的计数器可以应对吗?

    + +## 解法 + + + +用哈希表作为计数器实现。 + + + +### **Python3** + + + +```python +class HitCounter: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.counter = collections.Counter() + + def hit(self, timestamp: int) -> None: + """ + Record a hit. + @param timestamp - The current timestamp (in seconds granularity). + """ + self.counter[timestamp] += 1 + + + def getHits(self, timestamp: int) -> int: + """ + Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). + """ + return sum([v for t, v in self.counter.items() if t + 300 > timestamp]) + + +# Your HitCounter object will be instantiated and called as such: +# obj = HitCounter() +# obj.hit(timestamp) +# param_2 = obj.getHits(timestamp) +``` + +### **Java** + + + +```java +class HitCounter { + + private Map counter; + + /** Initialize your data structure here. */ + public HitCounter() { + counter = new HashMap<>(); + } + + /** Record a hit. + @param timestamp - The current timestamp (in seconds granularity). */ + public void hit(int timestamp) { + counter.put(timestamp, counter.getOrDefault(timestamp, 0) + 1); + } + + /** Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). */ + public int getHits(int timestamp) { + int hits = 0; + for (Map.Entry entry : counter.entrySet()) { + if (entry.getKey() + 300 > timestamp) { + hits += entry.getValue(); + } + } + return hits; + } +} + +/** + * Your HitCounter object will be instantiated and called as such: + * HitCounter obj = new HitCounter(); + * obj.hit(timestamp); + * int param_2 = obj.getHits(timestamp); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0363.leetcode363 Max Sum of Rectangle No Larger Than K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0363.leetcode363 Max Sum of Rectangle No Larger Than K-zh.md" new file mode 100644 index 00000000..9fba91de --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0363.leetcode363 Max Sum of Rectangle No Larger Than K-zh.md" @@ -0,0 +1,75 @@ +# [363. 矩形区域不超过 K 的最大数值和](https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0363.Max%20Sum%20of%20Rectangle%20No%20Larger%20Than%20K/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的矩阵 matrix 和一个整数 k ,找出并返回矩阵内部矩形区域的不超过 k 的最大数值和。

    + +

    题目数据保证总会存在一个数值和不超过 k 的矩形区域。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,0,1],[0,-2,3]], k = 2
    +输出:2
    +解释:蓝色边框圈出来的矩形区域 [[0, 1], [-2, 3]] 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[2,2,-1]], k = 3
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • -100 <= matrix[i][j] <= 100
    • +
    • -105 <= k <= 105
    • +
    + +

     

    + +

    进阶:如果行数远大于列数,该如何设计解决方案?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0364.leetcode364 Nested List Weight Sum II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0364.leetcode364 Nested List Weight Sum II-zh.md" new file mode 100644 index 00000000..6bedd35c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0364.leetcode364 Nested List Weight Sum II-zh.md" @@ -0,0 +1,251 @@ +# [364. 加权嵌套序列和 II](https://leetcode-cn.com/problems/nested-list-weight-sum-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0364.Nested%20List%20Weight%20Sum%20II/README_EN.md) + +## 题目描述 + + + +

    给一个嵌套整数序列,请你返回每个数字在序列中的加权和,它们的权重由它们的深度决定。

    + +

    序列中的每一个元素要么是一个整数,要么是一个序列(这个序列中的每个元素也同样是整数或序列)。

    + +

    前一个问题 不同的是,前一题的权重按照从根到叶逐一增加,而本题的权重从叶到根逐一增加。

    + +

    也就是说,在本题中,叶子的权重为1,而根拥有最大的权重。

    + +

    示例 1:

    + +
    输入: [[1,1],2,[1,1]]
    +输出: 8 
    +解释: 四个 1 在深度为 1 的位置, 一个 2 在深度为 2 的位置。
    +
    + +

    示例 2:

    + +
    输入: [1,[4,[6]]]
    +输出: 17 
    +解释: 一个 1 在深度为 3 的位置, 一个 4 在深度为 2 的位置,一个 6 在深度为 1 的位置。 1*3 + 4*2 + 6*1 = 17。
    +
    + +## 解法 + + + +先求序列的最大深度 `depth`,然后利用 DFS 累加求和。 + + + +### **Python3** + + + +```python +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger: +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ +class Solution: + def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: + def max_depth(nestedList): + depth = 1 + for item in nestedList: + if item.isInteger(): + continue + depth = max(depth, max_depth(item.getList()) + 1) + return depth + + def dfs(nestedList, max_depth): + depth_sum = 0 + for item in nestedList: + if item.isInteger(): + depth_sum += item.getInteger() * max_depth + else: + depth_sum += dfs(item.getList(), max_depth - 1) + return depth_sum + + depth = max_depth(nestedList) + return dfs(nestedList, depth) +``` + +### **Java** + + + +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public int depthSumInverse(List nestedList) { + int depth = maxDepth(nestedList); + return dfs(nestedList, depth); + } + + private int maxDepth(List nestedList) { + int depth = 1; + for (NestedInteger item : nestedList) { + if (item.isInteger()) { + continue; + } + depth = Math.max(depth, 1 + maxDepth(item.getList())); + } + return depth; + } + + private int dfs(List nestedList, int depth) { + int depthSum = 0; + for (NestedInteger item : nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth - 1); + } + } + return depthSum; + } +} +``` + +### **JavaScript** + +```js +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * function NestedInteger() { + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * @return {boolean} + * this.isInteger = function() { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * @return {integer} + * this.getInteger = function() { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * @return {void} + * this.setInteger = function(value) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * @return {void} + * this.add = function(elem) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, if it holds a nested list + * Return null if this NestedInteger holds a single integer + * @return {NestedInteger[]} + * this.getList = function() { + * ... + * }; + * }; + */ +/** + * @param {NestedInteger[]} nestedList + * @return {number} + */ +var depthSumInverse = function (nestedList) { + const maxDepth = (nestedList) => { + let depth = 1; + for (const item of nestedList) { + if (item.isInteger()) { + continue; + } + depth = Math.max(depth, 1 + maxDepth(item.getList())); + } + return depth; + }; + const dfs = (nestedList, depth) => { + let depthSum = 0; + for (const item of nestedList) { + if (item.isInteger()) { + depthSum += item.getInteger() * depth; + } else { + depthSum += dfs(item.getList(), depth - 1); + } + } + return depthSum; + }; + const depth = maxDepth(nestedList); + return dfs(nestedList, depth); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0365.leetcode365 Water and Jug Problem-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0365.leetcode365 Water and Jug Problem-zh.md" new file mode 100644 index 00000000..7e93259a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0365.leetcode365 Water and Jug Problem-zh.md" @@ -0,0 +1,62 @@ +# [365. 水壶问题](https://leetcode-cn.com/problems/water-and-jug-problem) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0365.Water%20and%20Jug%20Problem/README_EN.md) + +## 题目描述 + + + +

    有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?

    + +

    如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。

    + +

    你允许:

    + +
      +
    • 装满任意一个水壶
    • +
    • 清空任意一个水壶
    • +
    • 从一个水壶向另外一个水壶倒水,直到装满或者倒空
    • +
    + +

    示例 1: (From the famous "Die Hard" example)

    + +
    输入: x = 3, y = 5, z = 4
    +输出: True
    +
    + +

    示例 2:

    + +
    输入: x = 2, y = 6, z = 5
    +输出: False
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0366.leetcode366 Find Leaves of Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0366.leetcode366 Find Leaves of Binary Tree-zh.md" new file mode 100644 index 00000000..99e15183 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0366.leetcode366 Find Leaves of Binary Tree-zh.md" @@ -0,0 +1,85 @@ +# [366. 寻找二叉树的叶子节点](https://leetcode-cn.com/problems/find-leaves-of-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0366.Find%20Leaves%20of%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树,请按以下要求的顺序收集它的全部节点:

    + +
      +
    1. 依次从左到右,每次收集并删除所有的叶子节点
    2. +
    3. 重复如上过程直到整棵树为空
    4. +
    + +

     

    + +

    示例:

    + +
    输入: [1,2,3,4,5]
    +  
    +          1
    +         / \
    +        2   3
    +       / \     
    +      4   5    
    +
    +输出: [[4,5,3],[2],[1]]
    +
    + +

     

    + +

    解释:

    + +

    1. 删除叶子节点 [4,5,3] ,得到如下树结构:

    + +
              1
    +         / 
    +        2          
    +
    + +

     

    + +

    2. 现在删去叶子节点 [2] ,得到如下树结构:

    + +
              1          
    +
    + +

     

    + +

    3. 现在删去叶子节点 [1] ,得到空树:

    + +
              []         
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0367.leetcode367 Valid Perfect Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0367.leetcode367 Valid Perfect Square-zh.md" new file mode 100644 index 00000000..aa0d4321 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0367.leetcode367 Valid Perfect Square-zh.md" @@ -0,0 +1,126 @@ +# [367. 有效的完全平方数](https://leetcode-cn.com/problems/valid-perfect-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0367.Valid%20Perfect%20Square/README_EN.md) + +## 题目描述 + + + +

    给定一个 正整数 num ,编写一个函数,如果 num 是一个完全平方数,则返回 true ,否则返回 false

    + +

    进阶:不要 使用任何内置的库函数,如  sqrt

    + +

     

    + +

    示例 1:

    + +
    +输入:num = 16
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:num = 14
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num <= 2^31 - 1
    • +
    + +## 解法 + + + +二分法。 + + + +### **Python3** + + + +```python +class Solution: + def isPerfectSquare(self, num: int) -> bool: + left, right = 1, num + while left < right: + mid = left + ((right - left) >> 1) + if num // mid <= mid: + right = mid + else: + left = mid + 1 + return left * left == num +``` + +### **Java** + + + +```java +class Solution { + public boolean isPerfectSquare(int num) { + int left = 1, right = num; + while (left < right) { + int mid = (left + right) >>> 1; + if (num / mid <= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return left * left == num; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isPerfectSquare(int num) { + long left = 1, right = num; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (num / mid <= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return left * left == num; + } +}; +``` + +### **Go** + +```go +func isPerfectSquare(num int) bool { + left, right := 1, num + for left < right { + mid := left + (right-left)>>1 + if num/mid <= mid { + right = mid + } else { + left = mid + 1 + } + } + return left*left == num +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0368.leetcode368 Largest Divisible Subset-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0368.leetcode368 Largest Divisible Subset-zh.md" new file mode 100644 index 00000000..fad64a2c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0368.leetcode368 Largest Divisible Subset-zh.md" @@ -0,0 +1,73 @@ +# [368. 最大整除子集](https://leetcode-cn.com/problems/largest-divisible-subset) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0368.Largest%20Divisible%20Subset/README_EN.md) + +## 题目描述 + + + +给你一个由 无重复 正整数组成的集合 nums ,请你找出并返回其中最大的整除子集 answer ,子集中每一元素对 (answer[i], answer[j]) 都应当满足: +
      +
    • answer[i] % answer[j] == 0 ,或
    • +
    • answer[j] % answer[i] == 0
    • +
    + +

    如果存在多个有效解子集,返回其中任何一个均可。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3]
    +输出:[1,2]
    +解释:[1,3] 也会被视为正确答案。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,4,8]
    +输出:[1,2,4,8]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 2 * 109
    • +
    • nums 中的所有整数 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0369.leetcode369 Plus One Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0369.leetcode369 Plus One Linked List-zh.md" new file mode 100644 index 00000000..7b15ef27 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0369.leetcode369 Plus One Linked List-zh.md" @@ -0,0 +1,99 @@ +# [369. 给单链表加一](https://leetcode-cn.com/problems/plus-one-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0369.Plus%20One%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    用一个 非空 单链表来表示一个非负整数,然后将这个整数加一。

    + +

    你可以假设这个整数除了 0 本身,没有任何前导的 0。

    + +

    这个整数的各个数位按照 高位在链表头部低位在链表尾部 的顺序排列。

    + +

    示例:

    + +
    输入: [1,2,3]
    +输出: [1,2,4]
    +
    + +## 解法 + + + +找出链表最右一个 `val ≠ 9` 的节点 target,将 target 值加 1。然后将 target 之后的所有节点值置为 0。 + +若遇到如 `9 -> 9 -> 9` 的链表,就找不到 target 了,因此,我们可以定义一个虚拟头节点 dummy,初始值为 0。刚开始将 target 指向 dummy,这样就确保链表一定存在一个 `val ≠ 9` 的节点了。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def plusOne(self, head: ListNode) -> ListNode: + dummy = ListNode(val=0, next=head) + target = dummy + while head: + if head.val != 9: + target = head + head = head.next + target.val += 1 + target = target.next + while target: + target.val = 0 + target = target.next + return dummy if dummy.val else dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode plusOne(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode target = dummy; + while (head != null) { + if (head.val != 9) { + target = head; + } + head = head.next; + } + target.val += 1; + target = target.next; + while (target != null) { + target.val = 0; + target = target.next; + } + return dummy.val == 1 ? dummy : dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0370.leetcode370 Range Addition0370.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0370.leetcode370 Range Addition0370.md" new file mode 100644 index 00000000..e44052fe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0370.leetcode370 Range Addition0370.md" @@ -0,0 +1,65 @@ +# [370. 区间加法](https://leetcode-cn.com/problems/range-addition) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0370.Range%20Addition/README_EN.md) + +## 题目描述 + + + +

    假设你有一个长度为 n 的数组,初始情况下所有的数字均为 0,你将会被给出 k​​​​​​ 个更新的操作。

    + +

    其中,每个操作会被表示为一个三元组:[startIndex, endIndex, inc],你需要将子数组 A[startIndex ... endIndex](包括 startIndex 和 endIndex)增加 inc

    + +

    请你返回 k 次操作后的数组。

    + +

    示例:

    + +
    输入: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
    +输出: [-2,0,3,5,3]
    +
    + +

    解释:

    + +
    初始状态:
    +[0,0,0,0,0]
    +
    +进行了操作 [1,3,2] 后的状态:
    +[0,2,2,2,0]
    +
    +进行了操作 [2,4,3] 后的状态:
    +[0,2,5,5,3]
    +
    +进行了操作 [0,2,-2] 后的状态:
    +[-2,0,3,5,3]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0371.leetcode371 Sum of Two Integers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0371.leetcode371 Sum of Two Integers-zh.md" new file mode 100644 index 00000000..0aaba10d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0371.leetcode371 Sum of Two Integers-zh.md" @@ -0,0 +1,51 @@ +# [371. 两整数之和](https://leetcode-cn.com/problems/sum-of-two-integers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0371.Sum%20of%20Two%20Integers/README_EN.md) + +## 题目描述 + + + +

    不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。

    + +

    示例 1:

    + +
    输入: a = 1, b = 2
    +输出: 3
    +
    + +

    示例 2:

    + +
    输入: a = -2, b = 3
    +输出: 1
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0372.leetcode372 Super Pow-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0372.leetcode372 Super Pow-zh.md" new file mode 100644 index 00000000..6a31855e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0372.leetcode372 Super Pow-zh.md" @@ -0,0 +1,81 @@ +# [372. 超级次方](https://leetcode-cn.com/problems/super-pow) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0372.Super%20Pow/README_EN.md) + +## 题目描述 + + + +

    你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。

    + +

     

    + +

    示例 1:

    + +
    +输入:a = 2, b = [3]
    +输出:8
    +
    + +

    示例 2:

    + +
    +输入:a = 2, b = [1,0]
    +输出:1024
    +
    + +

    示例 3:

    + +
    +输入:a = 1, b = [4,3,3,8,5,2]
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:a = 2147483647, b = [2,0,0]
    +输出:1198
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= a <= 231 - 1
    • +
    • 1 <= b.length <= 2000
    • +
    • 0 <= b[i] <= 9
    • +
    • b 不含前导 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0373.leetcode373 Find K Pairs with Smallest Sums-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0373.leetcode373 Find K Pairs with Smallest Sums-zh.md" new file mode 100644 index 00000000..8b93bca9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0373.leetcode373 Find K Pairs with Smallest Sums-zh.md" @@ -0,0 +1,67 @@ +# [373. 查找和最小的K对数字](https://leetcode-cn.com/problems/find-k-pairs-with-smallest-sums) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0373.Find%20K%20Pairs%20with%20Smallest%20Sums/README_EN.md) + +## 题目描述 + + + +

    给定两个以升序排列的整形数组 nums1nums2, 以及一个整数 k

    + +

    定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2

    + +

    找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)

    + +

    示例 1:

    + +
    输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
    +输出: [1,2],[1,4],[1,6]
    +解释: 返回序列中的前 3 对数:
    +     [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
    +
    + +

    示例 2:

    + +
    输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
    +输出: [1,1],[1,1]
    +解释: 返回序列中的前 2 对数:
    +     [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
    +
    + +

    示例 3:

    + +
    输入: nums1 = [1,2], nums2 = [3], k = 3 
    +输出: [1,3],[2,3]
    +解释: 也可能序列中所有的数对都被返回:[1,3],[2,3]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0374.leetcode374 Guess Number Higher or Lower-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0374.leetcode374 Guess Number Higher or Lower-zh.md" new file mode 100644 index 00000000..ec8146af --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0374.leetcode374 Guess Number Higher or Lower-zh.md" @@ -0,0 +1,217 @@ +# [374. 猜数字大小](https://leetcode-cn.com/problems/guess-number-higher-or-lower) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0374.Guess%20Number%20Higher%20or%20Lower/README_EN.md) + +## 题目描述 + + + +

    猜数字游戏的规则如下:

    + +
      +
    • 每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
    • +
    • 如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。
    • +
    + +

    你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-11 或 0):

    + +
      +
    • -1:我选出的数字比你猜的数字小 pick < num
    • +
    • 1:我选出的数字比你猜的数字大 pick > num
    • +
    • 0:我选出的数字和你猜的数字一样。恭喜!你猜对了!pick == num
    • +
    + +

    返回我选出的数字。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 10, pick = 6
    +输出:6
    +
    + +

    示例 2:

    + +
    +输入:n = 1, pick = 1
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:n = 2, pick = 1
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:n = 2, pick = 2
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    • 1 <= pick <= n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +# def guess(num: int) -> int: + +class Solution: + def guessNumber(self, n: int) -> int: + left, right = 1, n + while left < right: + mid = (left + right) >> 1 + if guess(mid) <= 0: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * int guess(int num); + */ + +public class Solution extends GuessGame { + public int guessNumber(int n) { + int left = 1, right = n; + while (left < right) { + int mid = (left + right) >>> 1; + if (guess(mid) <= 0) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * int guess(int num); + */ + +class Solution { +public: + int guessNumber(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (guess(mid) <= 0) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * func guess(num int) int; + */ + +func guessNumber(n int) int { + left, right := 1, n + for left < right { + mid := (left + right) >> 1 + if guess(mid) <= 0 { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **C#** + +```cs +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * int guess(int num); + */ + +public class Solution : GuessGame { + public int GuessNumber(int n) { + int left = 1, right = n; + while (left < right) + { + int mid = left + ((right - left) >> 1); + if (guess(mid) <= 0) + { + right = mid; + } + else + { + left = mid + 1; + } + } + return left; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0375.leetcode375 Guess Number Higher or Lower II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0375.leetcode375 Guess Number Higher or Lower II-zh.md" new file mode 100644 index 00000000..fdf8d6e1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0375.leetcode375 Guess Number Higher or Lower II-zh.md" @@ -0,0 +1,61 @@ +# [375. 猜数字大小 II](https://leetcode-cn.com/problems/guess-number-higher-or-lower-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0375.Guess%20Number%20Higher%20or%20Lower%20II/README_EN.md) + +## 题目描述 + + + +

    我们正在玩一个猜数游戏,游戏规则如下:

    + +

    我从 n 之间选择一个数字,你来猜我选了哪个数字。

    + +

    每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。

    + +

    然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。

    + +

    示例:

    + +
    n = 10, 我选择了8.
    +
    +第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。
    +第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。
    +第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。
    +
    +游戏结束。8 就是我选的数字。
    +
    +你最终要支付 5 + 7 + 9 = 21 块钱。
    +
    + +

    给定 n ≥ 1,计算你至少需要拥有多少现金才能确保你能赢得这个游戏。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0376.leetcode376 Wiggle Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0376.leetcode376 Wiggle Subsequence-zh.md" new file mode 100644 index 00000000..054cbd36 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0376.leetcode376 Wiggle Subsequence-zh.md" @@ -0,0 +1,65 @@ +# [376. 摆动序列](https://leetcode-cn.com/problems/wiggle-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0376.Wiggle%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。

    + +

    例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。

    + +

    给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。

    + +

    示例 1:

    + +
    输入: [1,7,4,9,2,5]
    +输出: 6 
    +解释: 整个序列均为摆动序列。
    +
    + +

    示例 2:

    + +
    输入: [1,17,5,10,13,15,10,5,16,8]
    +输出: 7
    +解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。
    + +

    示例 3:

    + +
    输入: [1,2,3,4,5,6,7,8,9]
    +输出: 2
    + +

    进阶:
    +你能否用 O(n) 时间复杂度完成此题?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0377.leetcode377 Combination Sum IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0377.leetcode377 Combination Sum IV-zh.md" new file mode 100644 index 00000000..ab06a9e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0377.leetcode377 Combination Sum IV-zh.md" @@ -0,0 +1,106 @@ +# [377. 组合总和 Ⅳ](https://leetcode-cn.com/problems/combination-sum-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0377.Combination%20Sum%20IV/README_EN.md) + +## 题目描述 + + + +

    给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。

    + +

    题目数据保证答案符合 32 位整数范围。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3], target = 4
    +输出:7
    +解释:
    +所有可能的组合为:
    +(1, 1, 1, 1)
    +(1, 1, 2)
    +(1, 2, 1)
    +(1, 3)
    +(2, 1, 1)
    +(2, 2)
    +(3, 1)
    +请注意,顺序不同的序列被视作不同的组合。
    +
    + +

    示例 2:

    + +
    +输入:nums = [9], target = 3
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 200
    • +
    • 1 <= nums[i] <= 1000
    • +
    • nums 中的所有元素 互不相同
    • +
    • 1 <= target <= 1000
    • +
    + +

     

    + +

    进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件?

    + + +## 解法 + + + +简单动态规划,`dp[i]` 表示总和为 `i` 的元素组合的个数。 + + + +### **Python3** + + + +```python +class Solution: + def combinationSum4(self, nums: List[int], target: int) -> int: + dp = [0 for i in range(target + 1)] + dp[0] = 1 + for i in range(1, target + 1): + for num in nums: + if i - num >= 0: + dp[i] += dp[i - num] + return dp[target] +``` + +### **Java** + + + +```java +class Solution { + public int combinationSum4(int[] nums, int target) { + int[] dp = new int[target + 1]; + dp[0] = 1; + for (int i = 1; i <= target; i++) { + for (int num : nums) { + if (i - num >= 0) { + dp[i] += dp[i - num]; + } + } + } + return dp[target]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0378.leetcode378 Kth Smallest Element in a Sorted Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0378.leetcode378 Kth Smallest Element in a Sorted Matrix-zh.md" new file mode 100644 index 00000000..2f6f2a62 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0378.leetcode378 Kth Smallest Element in a Sorted Matrix-zh.md" @@ -0,0 +1,189 @@ +# [378. 有序矩阵中第 K 小的元素](https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0378.Kth%20Smallest%20Element%20in%20a%20Sorted%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
    +请注意,它是 排序后 的第 k 小元素,而不是第 k不同 的元素。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
    +输出:13
    +解释:矩阵中的元素为 [1,5,9,10,11,12,13,13,15],第 8 小元素是 13
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[-5]], k = 1
    +输出:-5
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= n <= 300
    • +
    • -109 <= matrix[i][j] <= 109
    • +
    • 题目数据 保证 matrix 中的所有行和列都按 非递减顺序 排列
    • +
    • 1 <= k <= n2
    • +
    + +## 解法 + + + +二分法。 + + + +### **Python3** + + + +```python +class Solution: + def kthSmallest(self, matrix: List[List[int]], k: int) -> int: + def check(matrix, mid, k, n): + count = 0 + i, j = n - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] <= mid: + count += (i + 1) + j += 1 + else: + i -= 1 + return count >= k + + n = len(matrix) + left, right = matrix[0][0], matrix[n - 1][n - 1] + while left < right: + mid = (left + right) >> 1 + if check(matrix, mid, k, n): + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int kthSmallest(int[][] matrix, int k) { + int n = matrix.length; + int left = matrix[0][0], right = matrix[n - 1][n - 1]; + while (left < right) { + int mid = (left + right) >>> 1; + if (check(matrix, mid, k, n)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean check(int[][] matrix, int mid, int k, int n) { + int count = 0; + int i = n - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] <= mid) { + count += (i + 1); + ++j; + } else { + --i; + } + } + return count >= k; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int kthSmallest(vector>& matrix, int k) { + int n = matrix.size(); + int left = matrix[0][0], right = matrix[n - 1][n - 1]; + while (left < right) { + int mid = left + right >> 1; + if (check(matrix, mid, k, n)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + +private: + bool check(vector>& matrix, int mid, int k, int n) { + int count = 0; + int i = n - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] <= mid) { + count += (i + 1); + ++j; + } else { + --i; + } + } + return count >= k; + } +}; +``` + +### **Go** + +```go +func kthSmallest(matrix [][]int, k int) int { + n := len(matrix) + left, right := matrix[0][0], matrix[n-1][n-1] + for left < right { + mid := (left + right) >> 1 + if check(matrix, mid, k, n) { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func check(matrix [][]int, mid, k, n int) bool { + count := 0 + i, j := n-1, 0 + for i >= 0 && j < n { + if matrix[i][j] <= mid { + count += (i + 1) + j++ + } else { + i-- + } + } + return count >= k +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0379.leetcode379 Design Phone Directory-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0379.leetcode379 Design Phone Directory-zh.md" new file mode 100644 index 00000000..5b787e24 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0379.leetcode379 Design Phone Directory-zh.md" @@ -0,0 +1,161 @@ +# [379. 电话目录管理系统](https://leetcode-cn.com/problems/design-phone-directory) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0379.Design%20Phone%20Directory/README_EN.md) + +## 题目描述 + + + +

    设计一个电话目录管理系统,让它支持以下功能:

    + +
      +
    1. get: 分配给用户一个未被使用的电话号码,获取失败请返回 -1
    2. +
    3. check: 检查指定的电话号码是否被使用
    4. +
    5. release: 释放掉一个电话号码,使其能够重新被分配
    6. +
    + +

     

    + +

    示例:

    + +
    // 初始化电话目录,包括 3 个电话号码:0,1 和 2。
    +PhoneDirectory directory = new PhoneDirectory(3);
    +
    +// 可以返回任意未分配的号码,这里我们假设它返回 0。
    +directory.get();
    +
    +// 假设,函数返回 1。
    +directory.get();
    +
    +// 号码 2 未分配,所以返回为 true。
    +directory.check(2);
    +
    +// 返回 2,分配后,只剩一个号码未被分配。
    +directory.get();
    +
    +// 此时,号码 2 已经被分配,所以返回 false。
    +directory.check(2);
    +
    +// 释放号码 2,将该号码变回未分配状态。
    +directory.release(2);
    +
    +// 号码 2 现在是未分配状态,所以返回 true。
    +directory.check(2);
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= maxNumbers <= 10^4
    • +
    • 0 <= number < maxNumbers
    • +
    • 调用方法的总数处于区间 [0 - 20000] 之内
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class PhoneDirectory: + + def __init__(self, maxNumbers: int): + """ + Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. + """ + self.provided = [False] * maxNumbers + + def get(self) -> int: + """ + Provide a number which is not assigned to anyone. + @return - Return an available number. Return -1 if none is available. + """ + for i in range(len(self.provided)): + if not self.provided[i]: + self.provided[i] = True + return i + return -1 + + def check(self, number: int) -> bool: + """ + Check if a number is available or not. + """ + return not self.provided[number] + + def release(self, number: int) -> None: + """ + Recycle or release a number. + """ + self.provided[number] = False + + +# Your PhoneDirectory object will be instantiated and called as such: +# obj = PhoneDirectory(maxNumbers) +# param_1 = obj.get() +# param_2 = obj.check(number) +# obj.release(number) +``` + +### **Java** + + + +```java +class PhoneDirectory { + + private boolean[] provided; + + /** Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ + public PhoneDirectory(int maxNumbers) { + provided = new boolean[maxNumbers]; + } + + /** Provide a number which is not assigned to anyone. + @return - Return an available number. Return -1 if none is available. */ + public int get() { + for (int i = 0; i < provided.length; ++i) { + if (!provided[i]) { + provided[i] = true; + return i; + } + } + return -1; + } + + /** Check if a number is available or not. */ + public boolean check(int number) { + return !provided[number]; + } + + /** Recycle or release a number. */ + public void release(int number) { + provided[number] = false; + } +} + +/** + * Your PhoneDirectory object will be instantiated and called as such: + * PhoneDirectory obj = new PhoneDirectory(maxNumbers); + * int param_1 = obj.get(); + * boolean param_2 = obj.check(number); + * obj.release(number); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0380.leetcode380 Insert Delete GetRandom O(1)-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0380.leetcode380 Insert Delete GetRandom O(1)-zh.md" new file mode 100644 index 00000000..0d251304 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0380.leetcode380 Insert Delete GetRandom O(1)-zh.md" @@ -0,0 +1,172 @@ +# [380. 常数时间插入、删除和获取随机元素](https://leetcode-cn.com/problems/insert-delete-getrandom-o1) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0380.Insert%20Delete%20GetRandom%20O%281%29/README_EN.md) + +## 题目描述 + + + +

    设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。

    + +
      +
    1. insert(val):当元素 val 不存在时,向集合中插入该项。
    2. +
    3. remove(val):元素 val 存在时,从集合中移除该项。
    4. +
    5. getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
    6. +
    + +

    示例 :

    + +
    +// 初始化一个空的集合。
    +RandomizedSet randomSet = new RandomizedSet();
    +
    +// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
    +randomSet.insert(1);
    +
    +// 返回 false ,表示集合中不存在 2 。
    +randomSet.remove(2);
    +
    +// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
    +randomSet.insert(2);
    +
    +// getRandom 应随机返回 1 或 2 。
    +randomSet.getRandom();
    +
    +// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
    +randomSet.remove(1);
    +
    +// 2 已在集合中,所以返回 false 。
    +randomSet.insert(2);
    +
    +// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
    +randomSet.getRandom();
    +
    + +## 解法 + + + +“哈希表 + 动态列表”实现。 + +哈希表存放每个元素的值和对应的下标,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。 + +注意,在 `remove()` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。 + + + +### **Python3** + + + +```python +class RandomizedSet: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.m = {} + self.l = [] + + def insert(self, val: int) -> bool: + """ + Inserts a value to the set. Returns true if the set did not already contain the specified element. + """ + if val in self.m: + return False + self.m[val] = len(self.l) + self.l.append(val) + return True + + def remove(self, val: int) -> bool: + """ + Removes a value from the set. Returns true if the set contained the specified element. + """ + if val not in self.m: + return False + idx = self.m[val] + last_idx = len(self.l) - 1 + self.m[self.l[last_idx]] = idx + self.m.pop(val) + self.l[idx] = self.l[last_idx] + self.l.pop() + return True + + def getRandom(self) -> int: + """ + Get a random element from the set. + """ + return random.choice(self.l) + + +# Your RandomizedSet object will be instantiated and called as such: +# obj = RandomizedSet() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() +``` + +### **Java** + + + +```java +class RandomizedSet { + private Map m; + private List l; + private Random rnd; + + /** Initialize your data structure here. */ + public RandomizedSet() { + m = new HashMap<>(); + l = new ArrayList<>(); + rnd = new Random(); + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + public boolean insert(int val) { + if (m.containsKey(val)) { + return false; + } + m.put(val, l.size()); + l.add(val); + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + public boolean remove(int val) { + if (!m.containsKey(val)) { + return false; + } + int idx = m.get(val); + int lastIdx = l.size() - 1; + m.put(l.get(lastIdx), idx); + m.remove(val); + l.set(idx, l.get(lastIdx)); + l.remove(lastIdx); + return true; + } + + /** Get a random element from the set. */ + public int getRandom() { + int idx = rnd.nextInt(l.size()); + return l.get(idx); + } +} + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0381.leetcode381 Insert Delete GetRandom O(1) - Duplicates allowed-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0381.leetcode381 Insert Delete GetRandom O(1) - Duplicates allowed-zh.md" new file mode 100644 index 00000000..c4bc47a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0381.leetcode381 Insert Delete GetRandom O(1) - Duplicates allowed-zh.md" @@ -0,0 +1,187 @@ +# [381. O(1) 时间插入、删除和获取随机元素 - 允许重复](https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0381.Insert%20Delete%20GetRandom%20O%281%29%20-%20Duplicates%20allowed/README_EN.md) + +## 题目描述 + + + +

    设计一个支持在平均 时间复杂度 O(1) , 执行以下操作的数据结构。

    + +

    注意: 允许出现重复元素。

    + +
      +
    1. insert(val):向集合中插入元素 val。
    2. +
    3. remove(val):当 val 存在时,从集合中移除一个 val。
    4. +
    5. getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。
    6. +
    + +

    示例:

    + +
    // 初始化一个空的集合。
    +RandomizedCollection collection = new RandomizedCollection();
    +
    +// 向集合中插入 1 。返回 true 表示集合不包含 1 。
    +collection.insert(1);
    +
    +// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
    +collection.insert(1);
    +
    +// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
    +collection.insert(2);
    +
    +// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
    +collection.getRandom();
    +
    +// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
    +collection.remove(1);
    +
    +// getRandom 应有相同概率返回 1 和 2 。
    +collection.getRandom();
    +
    + +## 解法 + + + +“哈希表 + 动态列表”实现。 + +哈希表存放每个元素的值和对应的下标集合,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。 + +注意,在 `remove()` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。 + + + +### **Python3** + + + +```python +class RandomizedCollection: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.m = {} + self.l = [] + + def insert(self, val: int) -> bool: + """ + Inserts a value to the collection. Returns true if the collection did not already contain the specified element. + """ + idx_set = self.m.get(val, set()) + idx_set.add(len(self.l)) + self.m[val] = idx_set + self.l.append(val) + return len(idx_set) == 1 + + def remove(self, val: int) -> bool: + """ + Removes a value from the collection. Returns true if the collection contained the specified element. + """ + if val not in self.m: + return False + idx_set = self.m[val] + idx = list(idx_set)[0] + last_idx = len(self.l) - 1 + self.l[idx] = self.l[last_idx] + idx_set.remove(idx) + + last_idx_set = self.m[self.l[last_idx]] + if last_idx in last_idx_set: + last_idx_set.remove(last_idx) + if idx < last_idx: + last_idx_set.add(idx) + if not idx_set: + self.m.pop(val) + self.l.pop() + return True + + def getRandom(self) -> int: + """ + Get a random element from the collection. + """ + return -1 if len(self.l) == 0 else random.choice(self.l) + + + +# Your RandomizedCollection object will be instantiated and called as such: +# obj = RandomizedCollection() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() +``` + +### **Java** + + + +```java +class RandomizedCollection { + private Map> m; + private List l; + private Random rnd; + + /** Initialize your data structure here. */ + public RandomizedCollection() { + m = new HashMap<>(); + l = new ArrayList<>(); + rnd = new Random(); + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + public boolean insert(int val) { + Set idxSet = m.getOrDefault(val, new HashSet<>()); + idxSet.add(l.size()); + m.put(val, idxSet); + l.add(val); + return idxSet.size() == 1; + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + public boolean remove(int val) { + if (!m.containsKey(val)) { + return false; + } + Set idxSet = m.get(val); + int idx = idxSet.iterator().next(); + int lastIdx = l.size() - 1; + l.set(idx, l.get(lastIdx)); + idxSet.remove(idx); + + Set lastIdxSet = m.get(l.get(lastIdx)); + lastIdxSet.remove(lastIdx); + if (idx < lastIdx) { + lastIdxSet.add(idx); + } + if (idxSet.isEmpty()) { + m.remove(val); + } + l.remove(lastIdx); + return true; + } + + /** Get a random element from the collection. */ + public int getRandom() { + int size = l.size(); + return size == 0 ? -1 : l.get(rnd.nextInt(size)); + } +} + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * RandomizedCollection obj = new RandomizedCollection(); + * boolean param_1 = obj.insert(val); + * boolean param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0382.leetcode382 Linked List Random Node-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0382.leetcode382 Linked List Random Node-zh.md" new file mode 100644 index 00000000..117f6770 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0382.leetcode382 Linked List Random Node-zh.md" @@ -0,0 +1,56 @@ +# [382. 链表随机节点](https://leetcode-cn.com/problems/linked-list-random-node) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0382.Linked%20List%20Random%20Node/README_EN.md) + +## 题目描述 + + + +

    给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样

    + +

    进阶:
    +如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?

    + +

    示例:

    + +
    +// 初始化一个单链表 [1,2,3].
    +ListNode head = new ListNode(1);
    +head.next = new ListNode(2);
    +head.next.next = new ListNode(3);
    +Solution solution = new Solution(head);
    +
    +// getRandom()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
    +solution.getRandom();
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0383.leetcode383 Ransom Note-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0383.leetcode383 Ransom Note-zh.md" new file mode 100644 index 00000000..3410fa35 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0383.leetcode383 Ransom Note-zh.md" @@ -0,0 +1,98 @@ +# [383. 赎金信](https://leetcode-cn.com/problems/ransom-note) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0383.Ransom%20Note/README_EN.md) + +## 题目描述 + + + +

    给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false

    + +

    (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

    + +

     

    + +

    示例 1:

    + +
    +输入:ransomNote = "a", magazine = "b"
    +输出:false
    +
    + +

    示例 2:

    + +
    +输入:ransomNote = "aa", magazine = "ab"
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:ransomNote = "aa", magazine = "aab"
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 你可以假设两个字符串均只含有小写字母。
    • +
    + + +## 解法 + + + +用一个数组或字典 chars 存放 magazine 中每个字母出现的次数。遍历 ransomNote 中每个字母,判断 chars 是否包含即可。 + + + +### **Python3** + + + +```python +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + chars = {} + for i in magazine: + chars[i] = chars.get(i, 0) + 1 + for i in ransomNote: + if not chars.get(i): + return False + chars[i] -= 1 + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + int[] chars = new int[26]; + for (int i = 0, n = magazine.length(); i < n; ++i) { + int idx = magazine.charAt(i) - 'a'; + ++chars[idx]; + } + for (int i = 0, n = ransomNote.length(); i < n; ++i) { + int idx = ransomNote.charAt(i) - 'a'; + if (chars[idx] == 0) return false; + --chars[idx]; + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0384.leetcode384 Shuffle an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0384.leetcode384 Shuffle an Array-zh.md" new file mode 100644 index 00000000..4b303710 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0384.leetcode384 Shuffle an Array-zh.md" @@ -0,0 +1,77 @@ +# [384. 打乱数组](https://leetcode-cn.com/problems/shuffle-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0384.Shuffle%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。

    + +

    实现 Solution class:

    + +
      +
    • Solution(int[] nums) 使用整数数组 nums 初始化对象
    • +
    • int[] reset() 重设数组到它的初始状态并返回
    • +
    • int[] shuffle() 返回数组随机打乱后的结果
    • +
    + +

     

    + +

    示例:

    + +
    +输入
    +["Solution", "shuffle", "reset", "shuffle"]
    +[[[1, 2, 3]], [], [], []]
    +输出
    +[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
    +
    +解释
    +Solution solution = new Solution([1, 2, 3]);
    +solution.shuffle();    // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]
    +solution.reset();      // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
    +solution.shuffle();    // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [1, 3, 2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 200
    • +
    • -106 <= nums[i] <= 106
    • +
    • nums 中的所有元素都是 唯一的
    • +
    • 最多可以调用 5 * 104resetshuffle
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0385.leetcode385 Mini Parser-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0385.leetcode385 Mini Parser-zh.md" new file mode 100644 index 00000000..107a8b55 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0385.leetcode385 Mini Parser-zh.md" @@ -0,0 +1,72 @@ +# [385. 迷你语法分析器](https://leetcode-cn.com/problems/mini-parser) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0385.Mini%20Parser/README_EN.md) + +## 题目描述 + + + +

    给定一个用字符串表示的整数的嵌套列表,实现一个解析它的语法分析器。

    + +

    列表中的每个元素只可能是整数或整数嵌套列表

    + +

    提示:你可以假定这些字符串都是格式良好的:

    + +
      +
    • 字符串非空
    • +
    • 字符串不包含空格
    • +
    • 字符串只包含数字0-9[-,]
    • +
    + +

     

    + +

    示例 1:

    + +
    给定 s = "324",
    +
    +你应该返回一个 NestedInteger 对象,其中只包含整数值 324。
    +
    + +

    示例 2:

    + +
    给定 s = "[123,[456,[789]]]",
    +
    +返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表:
    +
    +1. 一个 integer 包含值 123
    +2. 一个包含两个元素的嵌套列表:
    +    i.  一个 integer 包含值 456
    +    ii. 一个包含一个元素的嵌套列表
    +         a. 一个 integer 包含值 789
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0386.leetcode386 Lexicographical Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0386.leetcode386 Lexicographical Numbers-zh.md" new file mode 100644 index 00000000..71431e1e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0386.leetcode386 Lexicographical Numbers-zh.md" @@ -0,0 +1,46 @@ +# [386. 字典序排数](https://leetcode-cn.com/problems/lexicographical-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0386.Lexicographical%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给定一个整数 n, 返回从 到 的字典顺序。

    + +

    例如,

    + +

    给定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。

    + +

    请尽可能的优化算法的时间复杂度和空间复杂度。 输入的数据 小于等于 5,000,000。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0387.leetcode387 First Unique Character in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0387.leetcode387 First Unique Character in a String-zh.md" new file mode 100644 index 00000000..25bbccda --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0387.leetcode387 First Unique Character in a String-zh.md" @@ -0,0 +1,81 @@ +# [387. 字符串中的第一个唯一字符](https://leetcode-cn.com/problems/first-unique-character-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0387.First%20Unique%20Character%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

    + +

     

    + +

    示例:

    + +
    s = "leetcode"
    +返回 0
    +
    +s = "loveleetcode"
    +返回 2
    +
    + +

     

    + +

    提示:你可以假定该字符串只包含小写字母。

    + + +## 解法 + + + +遍历字符串,用一个 map 或者字典存放字符串中每个字符出现的次数。然后再次遍历字符串,取出对应字符出现的次数,若次数为 1,直接返回当前字符串的下标。遍历结束,返回 -1。 + + + +### **Python3** + + + +```python +class Solution: + def firstUniqChar(self, s: str) -> int: + chars = {} + for ch in s: + ch = ord(ch) + chars[ch] = chars.get(ch, 0) + 1 + for i, ch in enumerate(s): + ch = ord(ch) + if chars[ch] == 1: + return i + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int firstUniqChar(String s) { + Map chars = new HashMap<>(26); + int n = s.length(); + for (int i = 0; i < n; ++i) { + char ch = s.charAt(i); + chars.put(ch, chars.getOrDefault(ch, 0) + 1); + } + for (int i = 0; i < n; ++i) { + char ch = s.charAt(i); + if (chars.get(ch) == 1) return i; + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0388.leetcode388 Longest Absolute File Path-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0388.leetcode388 Longest Absolute File Path-zh.md" new file mode 100644 index 00000000..492c9f7c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0388.leetcode388 Longest Absolute File Path-zh.md" @@ -0,0 +1,108 @@ +# [388. 文件的最长绝对路径](https://leetcode-cn.com/problems/longest-absolute-file-path) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0388.Longest%20Absolute%20File%20Path/README_EN.md) + +## 题目描述 + + + +

    假设文件系统如下图所示:

    + +

    + +

    这里将 dir 作为根目录中的唯一目录。dir 包含两个子目录 subdir1subdir2subdir1 包含文件 file1.ext 和子目录 subsubdir1subdir2 包含子目录 subsubdir2,该子目录下包含文件 file2.ext

    + +

    在文本格式中,如下所示(⟶表示制表符):

    + +
    +dir
    +⟶ subdir1
    +⟶ ⟶ file1.ext
    +⟶ ⟶ subsubdir1
    +⟶ subdir2
    +⟶ ⟶ subsubdir2
    +⟶ ⟶ ⟶ file2.ext
    +
    + +

    如果是代码表示,上面的文件系统可以写为 "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"'\n''\t' 分别是换行符和制表符。

    + +

    文件系统中的每个文件和文件夹都有一个唯一的 绝对路径 ,即必须打开才能到达文件/目录所在位置的目录顺序,所有路径用 '/' 连接。上面例子中,指向 file2.ext 的绝对路径是 "dir/subdir2/subsubdir2/file2.ext" 。每个目录名由字母、数字和/或空格组成,每个文件名遵循 name.extension 的格式,其中名称和扩展名由字母、数字和/或空格组成。

    + +

    给定一个以上述格式表示文件系统的字符串 input ,返回文件系统中 指向文件的最长绝对路径 的长度。 如果系统中没有文件,返回 0

    + +

     

    + +

    示例 1:

    + +
    +输入:input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
    +输出:20
    +解释:只有一个文件,绝对路径为 "dir/subdir2/file.ext" ,路径长度 20
    +路径 "dir/subdir1" 不含任何文件
    +
    + +

    示例 2:

    + +
    +输入:input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
    +输出:32
    +解释:存在两个文件:
    +"dir/subdir1/file1.ext" ,路径长度 21
    +"dir/subdir2/subsubdir2/file2.ext" ,路径长度 32
    +返回 32 ,因为这是最长的路径
    + +

    示例 3:

    + +
    +输入:input = "a"
    +输出:0
    +解释:不存在任何文件
    + +

    示例 4:

    + +
    +输入:input = "file1.txt\nfile2.txt\nlongfile.txt"
    +输出:12
    +解释:根目录下有 3 个文件。
    +因为根目录中任何东西的绝对路径只是名称本身,所以答案是 "longfile.txt" ,路径长度为 12
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= input.length <= 104
    • +
    • input 可能包含小写或大写的英文字母,一个换行符 '\n',一个指表符 '\t',一个点 '.',一个空格 ' ',和数字。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0389.leetcode389 Find the Difference-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0389.leetcode389 Find the Difference-zh.md" new file mode 100644 index 00000000..b384ef15 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0389.leetcode389 Find the Difference-zh.md" @@ -0,0 +1,105 @@ +# [389. 找不同](https://leetcode-cn.com/problems/find-the-difference) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0389.Find%20the%20Difference/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 st,它们只包含小写字母。

    + +

    字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

    + +

    请找出在 t 中被添加的字母。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "abcd", t = "abcde"
    +输出:"e"
    +解释:'e' 是那个被添加的字母。
    +
    + +

    示例 2:

    + +
    输入:s = "", t = "y"
    +输出:"y"
    +
    + +

    示例 3:

    + +
    输入:s = "a", t = "aa"
    +输出:"a"
    +
    + +

    示例 4:

    + +
    输入:s = "ae", t = "aea"
    +输出:"a"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 1000
    • +
    • t.length == s.length + 1
    • +
    • st 只包含小写字母
    • +
    + +## 解法 + + + +计数器实现。 + + + +### **Python3** + + + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + counter = collections.Counter(s) + for c in t: + if counter[c] <= 0: + return c + counter[c] -= 1 + return None +``` + +### **Java** + + + +```java +class Solution { + public char findTheDifference(String s, String t) { + int[] counter = new int[26]; + for (int i = 0; i < s.length(); ++i) { + int index = s.charAt(i) - 'a'; + ++counter[index]; + } + for (int i = 0; i < t.length(); ++i) { + int index = t.charAt(i) - 'a'; + if (counter[index] <= 0) { + return t.charAt(i); + } + --counter[index]; + } + return ' '; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0390.leetcode390 Elimination Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0390.leetcode390 Elimination Game-zh.md" new file mode 100644 index 00000000..97c1653e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0390.leetcode390 Elimination Game-zh.md" @@ -0,0 +1,57 @@ +# [390. 消除游戏](https://leetcode-cn.com/problems/elimination-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0390.Elimination%20Game/README_EN.md) + +## 题目描述 + + + +

    给定一个从1 到 n 排序的整数列表。
    +首先,从左到右,从第一个数字开始,每隔一个数字进行删除,直到列表的末尾。
    +第二步,在剩下的数字中,从右到左,从倒数第一个数字开始,每隔一个数字进行删除,直到列表开头。
    +我们不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。
    +返回长度为 n 的列表中,最后剩下的数字。

    + +

    示例:

    + +
    +输入:
    +n = 9,
    +1 2 3 4 5 6 7 8 9
    +2 4 6 8
    +2 6
    +6
    +
    +输出:
    +6
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0391.leetcode391 Perfect Rectangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0391.leetcode391 Perfect Rectangle-zh.md" new file mode 100644 index 00000000..1c759f69 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0391.leetcode391 Perfect Rectangle-zh.md" @@ -0,0 +1,105 @@ +# [391. 完美矩形](https://leetcode-cn.com/problems/perfect-rectangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0391.Perfect%20Rectangle/README_EN.md) + +## 题目描述 + + + +

    我们有 N 个与坐标轴对齐的矩形, 其中 N > 0, 判断它们是否能精确地覆盖一个矩形区域。

    + +

    每个矩形用左下角的点和右上角的点的坐标来表示。例如, 一个单位正方形可以表示为 [1,1,2,2]。 ( 左下角的点的坐标为 (1, 1) 以及右上角的点的坐标为 (2, 2) )。

    + +

    + +

    示例 1:

    + +
    rectangles = [
    +  [1,1,3,3],
    +  [3,1,4,2],
    +  [3,2,4,4],
    +  [1,3,2,4],
    +  [2,3,3,4]
    +]
    +
    +返回 true。5个矩形一起可以精确地覆盖一个矩形区域。
    +
    + +

     

    + +

    + +

    示例 2:

    + +
    rectangles = [
    +  [1,1,2,3],
    +  [1,3,2,4],
    +  [3,1,4,2],
    +  [3,2,4,4]
    +]
    +
    +返回 false。两个矩形之间有间隔,无法覆盖成一个矩形。
    +
    + +

     

    + +

    + +

    示例 3:

    + +
    rectangles = [
    +  [1,1,3,3],
    +  [3,1,4,2],
    +  [1,3,2,4],
    +  [3,2,4,4]
    +]
    +
    +返回 false。图形顶端留有间隔,无法覆盖成一个矩形。
    +
    + +

     

    + +

    + +

    示例 4:

    + +
    rectangles = [
    +  [1,1,3,3],
    +  [3,1,4,2],
    +  [1,3,2,4],
    +  [2,2,4,4]
    +]
    +
    +返回 false。因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0392.leetcode392 Is Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0392.leetcode392 Is Subsequence-zh.md" new file mode 100644 index 00000000..cc7ecfa7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0392.leetcode392 Is Subsequence-zh.md" @@ -0,0 +1,117 @@ +# [392. 判断子序列](https://leetcode-cn.com/problems/is-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0392.Is%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定字符串 st ,判断 s 是否为 t 的子序列。

    + +

    字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace""abcde"的一个子序列,而"aec"不是)。

    + +

    进阶:

    + +

    如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

    + +

    致谢:

    + +

    特别感谢 @pbrother 添加此问题并且创建所有测试用例。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abc", t = "ahbgdc"
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:s = "axc", t = "ahbgdc"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 100
    • +
    • 0 <= t.length <= 10^4
    • +
    • 两个字符串都只由小写字符组成。
    • +
    + + +## 解法 + + + +双指针遍历即可。 + + + +### **Python3** + + + +```python +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + m, n = len(s), len(t) + i = j = 0 + while i < m and j < n: + if s[i] == t[j]: + i += 1 + j += 1 + return i == m +``` + +### **Java** + + + +```java +class Solution { + public boolean isSubsequence(String s, String t) { + int m = s.length(), n = t.length(); + int i = 0, j = 0; + while (i < m && j < n) { + if (s.charAt(i) == t.charAt(j)) { + ++i; + } + ++j; + } + return i == m; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isSubsequence(string s, string t) { + int m = s.size(), n = t.size(); + int i = 0, j = 0; + while (i < m && j < n) { + if (s[i] == t[j]) { + ++i; + } + ++j; + } + return i == m; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0393.leetcode393 UTF-8 Validation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0393.leetcode393 UTF-8 Validation-zh.md" new file mode 100644 index 00000000..06245bdd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0393.leetcode393 UTF-8 Validation-zh.md" @@ -0,0 +1,82 @@ +# [393. UTF-8 编码验证](https://leetcode-cn.com/problems/utf-8-validation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0393.UTF-8%20Validation/README_EN.md) + +## 题目描述 + + + +

    UTF-8 中的一个字符可能的长度为 1 到 4 字节,遵循以下的规则:

    + +
      +
    1. 对于 1 字节的字符,字节的第一位设为 0 ,后面 7 位为这个符号的 unicode 码。
    2. +
    3. 对于 n 字节的字符 (n > 1),第一个字节的前 n 位都设为1,第 n+1 位设为 0 ,后面字节的前两位一律设为 10 。剩下的没有提及的二进制位,全部为这个符号的 unicode 码。
    4. +
    + +

    这是 UTF-8 编码的工作方式:

    + +
    +   Char. number range  |        UTF-8 octet sequence
    +      (hexadecimal)    |              (binary)
    +   --------------------+---------------------------------------------
    +   0000 0000-0000 007F | 0xxxxxxx
    +   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
    +   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
    +   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    +
    + +

    给定一个表示数据的整数数组,返回它是否为有效的 utf-8 编码。

    + +

    注意:
    +输入是整数数组。只有每个整数的 最低 8 个有效位 用来存储数据。这意味着每个整数只表示 1 字节的数据。

    + +

    示例 1:

    + +
    +data = [197, 130, 1], 表示 8 位的序列: 11000101 10000010 00000001.
    +
    +返回 true 。
    +这是有效的 utf-8 编码,为一个2字节字符,跟着一个1字节字符。
    +
    + +

    示例 2:

    + +
    +data = [235, 140, 4], 表示 8 位的序列: 11101011 10001100 00000100.
    +
    +返回 false 。
    +前 3 位都是 1 ,第 4 位为 0 表示它是一个3字节字符。
    +下一个字节是开头为 10 的延续字节,这是正确的。
    +但第二个延续字节不以 10 开头,所以是不符合规则的。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0394.leetcode394 Decode String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0394.leetcode394 Decode String-zh.md" new file mode 100644 index 00000000..a3ec32cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0394.leetcode394 Decode String-zh.md" @@ -0,0 +1,72 @@ +# [394. 字符串解码](https://leetcode-cn.com/problems/decode-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0394.Decode%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个经过编码的字符串,返回它解码后的字符串。

    + +

    编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

    + +

    你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

    + +

    此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "3[a]2[bc]"
    +输出:"aaabcbc"
    +
    + +

    示例 2:

    + +
    输入:s = "3[a2[c]]"
    +输出:"accaccacc"
    +
    + +

    示例 3:

    + +
    输入:s = "2[abc]3[cd]ef"
    +输出:"abcabccdcdcdef"
    +
    + +

    示例 4:

    + +
    输入:s = "abc3[cd]xyz"
    +输出:"abccdcdcdxyz"
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0395.leetcode395 Longest Substring with At Least K Repeating Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0395.leetcode395 Longest Substring with At Least K Repeating Characters-zh.md" new file mode 100644 index 00000000..e56846b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0395.leetcode395 Longest Substring with At Least K Repeating Characters-zh.md" @@ -0,0 +1,67 @@ +# [395. 至少有 K 个重复字符的最长子串](https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0395.Longest%20Substring%20with%20At%20Least%20K%20Repeating%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个整数 k ,请你找出 s 中的最长子串, 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aaabb", k = 3
    +输出:3
    +解释:最长子串为 "aaa" ,其中 'a' 重复了 3 次。
    +
    + +

    示例 2:

    + +
    +输入:s = "ababbc", k = 2
    +输出:5
    +解释:最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s 仅由小写英文字母组成
    • +
    • 1 <= k <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0396.leetcode396 Rotate Function-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0396.leetcode396 Rotate Function-zh.md" new file mode 100644 index 00000000..61ec7890 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0396.leetcode396 Rotate Function-zh.md" @@ -0,0 +1,62 @@ +# [396. 旋转函数](https://leetcode-cn.com/problems/rotate-function) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0396.Rotate%20Function/README_EN.md) + +## 题目描述 + + + +

    给定一个长度为 n 的整数数组 A 。

    + +

    假设 Bk 是数组 A 顺时针旋转 k 个位置后的数组,我们定义 A 的“旋转函数” F 为:

    + +

    F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]

    + +

    计算F(0), F(1), ..., F(n-1)中的最大值。

    + +

    注意:
    +可以认为 n 的值小于 105

    + +

    示例:

    + +
    +A = [4, 3, 2, 6]
    +
    +F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
    +F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
    +F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
    +F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
    +
    +所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0397.leetcode397 Integer Replacement-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0397.leetcode397 Integer Replacement-zh.md" new file mode 100644 index 00000000..2f0e9cd1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0397.leetcode397 Integer Replacement-zh.md" @@ -0,0 +1,81 @@ +# [397. 整数替换](https://leetcode-cn.com/problems/integer-replacement) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0397.Integer%20Replacement/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 n ,你可以做如下操作:

    + +
      +
    1. 如果 n 是偶数,则用 n / 2替换 n
    2. +
    3. 如果 n 是奇数,则可以用 n + 1n - 1替换 n
    4. +
    + +

    n 变为 1 所需的最小替换次数是多少?

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 8
    +输出:3
    +解释:8 -> 4 -> 2 -> 1
    +
    + +

    示例 2:

    + +
    +输入:n = 7
    +输出:4
    +解释:7 -> 8 -> 4 -> 2 -> 1
    +或 7 -> 6 -> 3 -> 2 -> 1
    +
    + +

    示例 3:

    + +
    +输入:n = 4
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0398.leetcode398 Random Pick Index-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0398.leetcode398 Random Pick Index-zh.md" new file mode 100644 index 00000000..beb32ceb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0398.leetcode398 Random Pick Index-zh.md" @@ -0,0 +1,56 @@ +# [398. 随机数索引](https://leetcode-cn.com/problems/random-pick-index) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0398.Random%20Pick%20Index/README_EN.md) + +## 题目描述 + + + +

    给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

    + +

    注意:
    +数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。

    + +

    示例:

    + +
    +int[] nums = new int[] {1,2,3,3,3};
    +Solution solution = new Solution(nums);
    +
    +// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
    +solution.pick(3);
    +
    +// pick(1) 应该返回 0。因为只有nums[0]等于1。
    +solution.pick(1);
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0399.leetcode399 Evaluate Division-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0399.leetcode399 Evaluate Division-zh.md" new file mode 100644 index 00000000..2269886e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0399.leetcode399 Evaluate Division-zh.md" @@ -0,0 +1,89 @@ +# [399. 除法求值](https://leetcode-cn.com/problems/evaluate-division) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0300-0399/0399.Evaluate%20Division/README_EN.md) + +## 题目描述 + + + +

    给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi]values[i] 共同表示等式 Ai / Bi = values[i] 。每个 AiBi 是一个表示单个变量的字符串。

    + +

    另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。

    + +

    返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。如果问题中出现了给定的已知条件中没有出现的字符串,也需要用 -1.0 替代这个答案。

    + +

    注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
    +输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000]
    +解释:
    +条件:a / b = 2.0, b / c = 3.0
    +问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
    +结果:[6.0, 0.5, -1.0, 1.0, -1.0 ]
    +
    + +

    示例 2:

    + +
    +输入:equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
    +输出:[3.75000,0.40000,5.00000,0.20000]
    +
    + +

    示例 3:

    + +
    +输入:equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
    +输出:[0.50000,2.00000,-1.00000,-1.00000]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= equations.length <= 20
    • +
    • equations[i].length == 2
    • +
    • 1 <= Ai.length, Bi.length <= 5
    • +
    • values.length == equations.length
    • +
    • 0.0 < values[i] <= 20.0
    • +
    • 1 <= queries.length <= 20
    • +
    • queries[i].length == 2
    • +
    • 1 <= Cj.length, Dj.length <= 5
    • +
    • Ai, Bi, Cj, Dj 由小写英文字母与数字组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0400.leetcode400 Nth Digit-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0400.leetcode400 Nth Digit-zh.md" new file mode 100644 index 00000000..66d99e64 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode1-400/0400.leetcode400 Nth Digit-zh.md" @@ -0,0 +1,61 @@ +# [400. 第 N 位数字](https://leetcode-cn.com/problems/nth-digit) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0400.Nth%20Digit/README_EN.md) + +## 题目描述 + + + +

    在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 位数字。

    + +

     

    + +

    注意:n 是正数且在 32 位整数范围内(n < 231)。

    + +

     

    + +

    示例 1:

    + +
    +输入:3
    +输出:3
    +
    + +

    示例 2:

    + +
    +输入:11
    +输出:0
    +解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0401.leetcode401 Binary Watch-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0401.leetcode401 Binary Watch-zh.md" new file mode 100644 index 00000000..83d279eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0401.leetcode401 Binary Watch-zh.md" @@ -0,0 +1,87 @@ +# [401. 二进制手表](https://leetcode-cn.com/problems/binary-watch) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0401.Binary%20Watch/README_EN.md) + +## 题目描述 + + + +

    二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)

    + +

    每个 LED 代表一个 0 或 1,最低位在右侧。

    + +

    + +

    (图源:WikiMedia - Binary clock samui moon.jpg ,许可协议:Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)

    + +

    例如,上面的二进制手表读取 “3:25”。

    + +

    给定一个非负整数 代表当前 LED 亮着的数量,返回所有可能的时间。

    + +

     

    + +

    示例:

    + +
    +输入: n = 1
    +返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
    + +

     

    + +

    提示:

    + +
      +
    • 输出的顺序没有要求。
    • +
    • 小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
    • +
    • 分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。
    • +
    • 超过表示范围(小时 0-11,分钟 0-59)的数据将会被舍弃,也就是说不会出现 "13:00", "0:61" 等时间。
    • +
    + + +## 解法 + + + +题目可转换为求 i(`i∈[0,12)`) 和 j(`j∈[0,60)`) 所有可能的组合。 + +合法组合需要满足的条件是:i 的二进制形式中 1 的个数加上 j 的二进制形式中 1 的个数,结果等于 num。 + + + +### **Python3** + + + +```python +class Solution: + def readBinaryWatch(self, num: int) -> List[str]: + return ['{:d}:{:02d}'.format(i, j) for i in range(12) for j in range(60) if (bin(i) + bin(j)).count('1') == num] +``` + +### **Java** + + + +```java +class Solution { + public List readBinaryWatch(int num) { + List res = new ArrayList<>(); + for (int i = 0; i < 12; ++i) { + for (int j = 0; j < 60; ++j) { + if (Integer.bitCount(i) + Integer.bitCount(j) == num) { + res.add(String.format("%d:%02d", i, j)); + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0402.leetcode402 Remove K Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0402.leetcode402 Remove K Digits-zh.md" new file mode 100644 index 00000000..774df524 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0402.leetcode402 Remove K Digits-zh.md" @@ -0,0 +1,71 @@ +# [402. 移掉K位数字](https://leetcode-cn.com/problems/remove-k-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0402.Remove%20K%20Digits/README_EN.md) + +## 题目描述 + + + +

    给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。

    + +

    注意:

    + +
      +
    • num 的长度小于 10002 且 ≥ k。
    • +
    • num 不会包含任何前导零。
    • +
    + +

    示例 1 :

    + +
    +输入: num = "1432219", k = 3
    +输出: "1219"
    +解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。
    +
    + +

    示例 2 :

    + +
    +输入: num = "10200", k = 1
    +输出: "200"
    +解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。
    +
    + +

    示例 3 :

    + +
    +输入: num = "10", k = 2
    +输出: "0"
    +解释: 从原数字移除所有的数字,剩余为空就是0。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0403.leetcode403 Frog Jump-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0403.leetcode403 Frog Jump-zh.md" new file mode 100644 index 00000000..43a201ce --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0403.leetcode403 Frog Jump-zh.md" @@ -0,0 +1,107 @@ +# [403. 青蛙过河](https://leetcode-cn.com/problems/frog-jump) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0403.Frog%20Jump/README_EN.md) + +## 题目描述 + + + +

    一只青蛙想要过河。 假定河流被等分为若干个单元格,并且在每一个单元格内都有可能放有一块石子(也有可能没有)。 青蛙可以跳上石子,但是不可以跳入水中。

    + +

    给你石子的位置列表 stones(用单元格序号 升序 表示), 请判定青蛙能否成功过河(即能否在最后一步跳至最后一块石子上)。

    + +

    开始时, 青蛙默认已站在第一块石子上,并可以假定它第一步只能跳跃一个单位(即只能从单元格 1 跳至单元格 2 )。

    + +

    如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1k 或 k + 1 个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。

    + +

     

    + +

    示例 1:

    + +
    +输入:stones = [0,1,3,5,6,8,12,17]
    +输出:true
    +解释:青蛙可以成功过河,按照如下方案跳跃:跳 1 个单位到第 2 块石子, 然后跳 2 个单位到第 3 块石子, 接着 跳 2 个单位到第 4 块石子, 然后跳 3 个单位到第 6 块石子, 跳 4 个单位到第 7 块石子, 最后,跳 5 个单位到第 8 个石子(即最后一块石子)。
    + +

    示例 2:

    + +
    +输入:stones = [0,1,2,3,4,8,9,11]
    +输出:false
    +解释:这是因为第 5 和第 6 个石子之间的间距太大,没有可选的方案供青蛙跳跃过去。
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= stones.length <= 2000
    • +
    • 0 <= stones[i] <= 231 - 1
    • +
    • stones[0] == 0
    • +
    + +## 解法 + + + +动态规划,用 `dp[i][k]` 表示最后一次跳跃为 `k` 个单位时,能否到达 `i` ,定义 base case 为 `dp[0][0] = True`(起点在下标 0)。 + +因为 “青蛙上一步跳跃了 `k` 个单位,那么它接下来的跳跃距离只能选择为 `k - 1`、`k` 或 `k + 1` 个单位”,所以 `dp[j][k - 1], dp[j][k], dp[j][k + 1]` 中有任一为真,即可从 `j` 跳跃到 `i`。 + + + +### **Python3** + + + +```python +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + dp = [[False] * n for i in range(n)] + dp[0][0] = True + for i in range(1, n): + for j in range(i): + k = stones[i] - stones[j]; + if k > j + 1: + continue + dp[i][k] = dp[j][k - 1] or dp[j][k] or dp[j][k + 1] + if i == n - 1 and dp[i][k]: + return True + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean canCross(int[] stones) { + int n = stones.length; + boolean[][] dp = new boolean[n][n]; + dp[0][0] = true; + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + int k = stones[i] - stones[j]; + if (k > j + 1) { + continue; + } + dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; + if (i == n - 1 && dp[i][k]) { + return true; + } + } + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0404.leetcode404 Sum of Left Leaves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0404.leetcode404 Sum of Left Leaves-zh.md" new file mode 100644 index 00000000..9578e827 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0404.leetcode404 Sum of Left Leaves-zh.md" @@ -0,0 +1,91 @@ +# [404. 左叶子之和](https://leetcode-cn.com/problems/sum-of-left-leaves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0404.Sum%20of%20Left%20Leaves/README_EN.md) + +## 题目描述 + + + +

    计算给定二叉树的所有左叶子之和。

    + +

    示例:

    + +
    +    3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    +
    +在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def sumOfLeftLeaves(self, root: TreeNode) -> int: + if root is None: + return 0 + res = 0 + if root.left and root.left.left is None and root.left.right is None: + res += root.left.val + res += self.sumOfLeftLeaves(root.left) + res += self.sumOfLeftLeaves(root.right) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) { + return 0; + } + int res = 0; + if (root.left != null && root.left.left == null && root.left.right == null) { + res += root.left.val; + } + res += sumOfLeftLeaves(root.left); + res += sumOfLeftLeaves(root.right); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0405.leetcode405 Convert a Number to Hexadecimal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0405.leetcode405 Convert a Number to Hexadecimal-zh.md" new file mode 100644 index 00000000..abbf7c92 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0405.leetcode405 Convert a Number to Hexadecimal-zh.md" @@ -0,0 +1,69 @@ +# [405. 数字转换为十六进制数](https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0405.Convert%20a%20Number%20to%20Hexadecimal/README_EN.md) + +## 题目描述 + + + +

    给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。

    + +

    注意:

    + +
      +
    1. 十六进制中所有字母(a-f)都必须是小写。
    2. +
    3. 十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。 
    4. +
    5. 给定的数确保在32位有符号整数范围内。
    6. +
    7. 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
    8. +
    + +

    示例 1:

    + +
    +输入:
    +26
    +
    +输出:
    +"1a"
    +
    + +

    示例 2:

    + +
    +输入:
    +-1
    +
    +输出:
    +"ffffffff"
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0406.leetcode406 Queue Reconstruction by Height-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0406.leetcode406 Queue Reconstruction by Height-zh.md" new file mode 100644 index 00000000..04df580a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0406.leetcode406 Queue Reconstruction by Height-zh.md" @@ -0,0 +1,80 @@ +# [406. 根据身高重建队列](https://leetcode-cn.com/problems/queue-reconstruction-by-height) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0406.Queue%20Reconstruction%20by%20Height/README_EN.md) + +## 题目描述 + + + +

    假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 i 个人的身高为 hi ,前面 正好ki 个身高大于或等于 hi 的人。

    + +

    请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
    +输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
    +解释:
    +编号为 0 的人身高为 5 ,没有身高更高或者相同的人排在他前面。
    +编号为 1 的人身高为 7 ,没有身高更高或者相同的人排在他前面。
    +编号为 2 的人身高为 5 ,有 2 个身高更高或者相同的人排在他前面,即编号为 0 和 1 的人。
    +编号为 3 的人身高为 6 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。
    +编号为 4 的人身高为 4 ,有 4 个身高更高或者相同的人排在他前面,即编号为 0、1、2、3 的人。
    +编号为 5 的人身高为 7 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。
    +因此 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 是重新构造后的队列。
    +
    + +

    示例 2:

    + +
    +输入:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
    +输出:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= people.length <= 2000
    • +
    • 0 <= hi <= 106
    • +
    • 0 <= ki < people.length
    • +
    • 题目数据确保队列可以被重建
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0407.leetcode407 Trapping Rain Water II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0407.leetcode407 Trapping Rain Water II-zh.md" new file mode 100644 index 00000000..852063af --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0407.leetcode407 Trapping Rain Water II-zh.md" @@ -0,0 +1,73 @@ +# [407. 接雨水 II](https://leetcode-cn.com/problems/trapping-rain-water-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0407.Trapping%20Rain%20Water%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。

    + +

     

    + +

    示例:

    + +
    给出如下 3x6 的高度图:
    +[
    +  [1,4,3,1,3,2],
    +  [3,2,1,3,2,4],
    +  [2,3,3,2,3,1]
    +]
    +
    +返回 4 。
    +
    + +

    + +

    如上图所示,这是下雨前的高度图[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] 的状态。

    + +

     

    + +

    + +

    下雨后,雨水将会被存储在这些方块中。总的接雨水量是4。

    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m, n <= 110
    • +
    • 0 <= heightMap[i][j] <= 20000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0408.leetcode408 Valid Word Abbreviation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0408.leetcode408 Valid Word Abbreviation-zh.md" new file mode 100644 index 00000000..39f23e2a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0408.leetcode408 Valid Word Abbreviation-zh.md" @@ -0,0 +1,67 @@ +# [408. 有效单词缩写](https://leetcode-cn.com/problems/valid-word-abbreviation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0408.Valid%20Word%20Abbreviation/README_EN.md) + +## 题目描述 + + + +

    给一个 非空 字符串 s 和一个单词缩写 abbr ,判断这个缩写是否可以是给定单词的缩写。

    + +

    字符串 "word" 的所有有效缩写为:

    + +
    ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
    + +

    注意单词 "word" 的所有有效缩写仅包含以上这些。任何其他的字符串都不是 "word" 的有效缩写。

    + +

    注意:
    +假设字符串 s 仅包含小写字母且 abbr 只包含小写字母和数字。

    + +

    示例 1:

    + +
    给定 s = "internationalization", abbr = "i12iz4n":
    +
    +函数返回 true.
    +
    + +

     

    + +

    示例 2:

    + +
    给定 s = "apple", abbr = "a2e":
    +
    +函数返回 false.
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0409.leetcode409 Longest Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0409.leetcode409 Longest Palindrome-zh.md" new file mode 100644 index 00000000..703770bf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0409.leetcode409 Longest Palindrome-zh.md" @@ -0,0 +1,79 @@ +# [409. 最长回文串](https://leetcode-cn.com/problems/longest-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0409.Longest%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

    + +

    在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。

    + +

    注意:
    +假设字符串的长度不会超过 1010。

    + +

    示例 1:

    + +
    +输入:
    +"abccccdd"
    +
    +输出:
    +7
    +
    +解释:
    +我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def longestPalindrome(self, s: str) -> int: + res = [0] * 128 + for ch in s: + res[ord(ch)] += 1 + odd_cnt, n = 0, len(s) + for e in res: + odd_cnt += (e % 2) + return n if odd_cnt == 0 else n - odd_cnt + 1 +``` + +### **Java** + + + +```java +class Solution { + public int longestPalindrome(String s) { + int[] res = new int[128]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + res[s.charAt(i)]++; + } + int oddCnt = 0; + for (int e : res) { + oddCnt += (e % 2); + } + return oddCnt == 0 ? n : n - oddCnt + 1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0410.leetcode410 Split Array Largest Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0410.leetcode410 Split Array Largest Sum-zh.md" new file mode 100644 index 00000000..5420514b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0410.leetcode410 Split Array Largest Sum-zh.md" @@ -0,0 +1,77 @@ +# [410. 分割数组的最大值](https://leetcode-cn.com/problems/split-array-largest-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0410.Split%20Array%20Largest%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组 nums 和一个整数 m ,你需要将这个数组分成 m 个非空的连续子数组。

    + +

    设计一个算法使得这 m 个子数组各自和的最大值最小。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [7,2,5,10,8], m = 2
    +输出:18
    +解释:
    +一共有四种方法将 nums 分割为 2 个子数组。 其中最好的方式是将其分为 [7,2,5] 和 [10,8] 。
    +因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,4,5], m = 2
    +输出:9
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,4,4], m = 3
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 0 <= nums[i] <= 106
    • +
    • 1 <= m <= min(50, nums.length)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0411.leetcode411 Minimum Unique Word Abbreviation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0411.leetcode411 Minimum Unique Word Abbreviation-zh.md" new file mode 100644 index 00000000..68297bfb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0411.leetcode411 Minimum Unique Word Abbreviation-zh.md" @@ -0,0 +1,93 @@ +# [411. 最短独占单词缩写](https://leetcode-cn.com/problems/minimum-unique-word-abbreviation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0411.Minimum%20Unique%20Word%20Abbreviation/README_EN.md) + +## 题目描述 + + + +

    通过将任意数量的 不相邻 子字符串替换为它们的长度,可以完成对字符串的 缩写 。 例如,像 "substitution" 这样的字符串可以缩写为(但不限于):

    + +
      +
    • "s10n" ("s ubstitutio n")
    • +
    • "sub4u4" ("sub stit u tion")
    • +
    • "12" ("substitution")
    • +
    • "su3i1u2on" ("su bst i t u ti on")
    • +
    • "substitution" (不替换子字符串)
    • +
    + +

    注意:"s55n" ("s ubsti tutio n") 不是 "substitution" 的有效缩写形式,因为它试图替换两个相邻的子字符串。

    + +

    缩写的 长度 是未被替换的字母数加上被替换的字符串数。例如,缩写 "s10n" 的长度为 32 个字母 + 1 个子字符串),而 "su3i1u2on" 的长度为 96 个字母 + 3 子字符串)。

    + +

    给你一个目标字符串 target 和一个字符串数组 dictionary 作为字典,为 target 找出并返回一个 最短 长度的缩写字符串,同时这个缩写字符串 不是 字典 dictionary 中其他字符串的缩写形式。如果有多个有效答案,可以返回其中任意一个。

    + +

     

    + +

    示例 1:

    + +
    +输入:target = "apple", dictionary = ["blade"]
    +输出:"a4"
    +解释:"apple" 的最短缩写形式为 "5" ,但这也是 "blade" 的缩写形式之一。
    +下一组最短缩写是 "a4" 和 "4e" ,其中 "4e" 也是 "blade" 的缩写形式之一,而 "a4" 不是。
    +因此,返回 "a4" 。
    +
    + +

    示例 2:

    + +
    +输入:target = "apple", dictionary = ["blade","plain","amber"]
    +输出:"1p3"
    +解释:"5" 同时是 "apple" 和字典中所有单词的缩写形式。
    +"a4" 同时是 "apple" 和 "amber" 的缩写形式。
    +"4e" 同时是 "apple" 和 "blade" 的缩写形式。
    +"1p3"、"2p2" 和 "3l1" 是 "apple" 的下一组最短缩写形式。
    +因为它们不是字典中其他单词的缩写形式,返回其中任意一个都是正确的。
    +
    + +

     

    + +

    提示:

    + +
      +
    • target.length == m
    • +
    • dictionary.length == n
    • +
    • 1 <= m <= 21
    • +
    • 0 <= n <= 1000
    • +
    • 1 <= dictionary[i] <= 100
    • +
    • 如果 n > 0 ,那么 log2(n) + m <= 21
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0412.leetcode412 Fizz Buzz-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0412.leetcode412 Fizz Buzz-zh.md" new file mode 100644 index 00000000..4755f9b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0412.leetcode412 Fizz Buzz-zh.md" @@ -0,0 +1,70 @@ +# [412. Fizz Buzz](https://leetcode-cn.com/problems/fizz-buzz) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0412.Fizz%20Buzz/README_EN.md) + +## 题目描述 + + + +

    写一个程序,输出从 1 到 n 数字的字符串表示。

    + +

    1. 如果 是3的倍数,输出“Fizz”;

    + +

    2. 如果 是5的倍数,输出“Buzz”;

    + +

    3.如果 同时是3和5的倍数,输出 “FizzBuzz”。

    + +

    示例:

    + +
    n = 15,
    +
    +返回:
    +[
    +    "1",
    +    "2",
    +    "Fizz",
    +    "4",
    +    "Buzz",
    +    "Fizz",
    +    "7",
    +    "8",
    +    "Fizz",
    +    "Buzz",
    +    "11",
    +    "Fizz",
    +    "13",
    +    "14",
    +    "FizzBuzz"
    +]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0413.leetcode413 Arithmetic Slices-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0413.leetcode413 Arithmetic Slices-zh.md" new file mode 100644 index 00000000..f4b542ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0413.leetcode413 Arithmetic Slices-zh.md" @@ -0,0 +1,142 @@ +# [413. 等差数列划分](https://leetcode-cn.com/problems/arithmetic-slices) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0413.Arithmetic%20Slices/README_EN.md) + +## 题目描述 + + + +

    如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。

    + +

    例如,以下数列为等差数列:

    + +
    +1, 3, 5, 7, 9
    +7, 7, 7, 7
    +3, -1, -5, -9
    + +

    以下数列不是等差数列。

    + +
    +1, 1, 2, 5, 7
    + +

     

    + +

    数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。

    + +

    如果满足以下条件,则称子数组(P, Q)为等差数组:

    + +

    元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。

    + +

    函数要返回数组 A 中所有为等差数组的子数组个数。

    + +

     

    + +

    示例:

    + +
    +A = [1, 2, 3, 4]
    +
    +返回: 3, A 中有三个子等差数组: [1, 2, 3], [2, 3, 4] 以及自身 [1, 2, 3, 4]。
    +
    + +## 解法 + + + +动态规划法。 + +设 `dp[i]` 表示以 i 结尾的数组构成的等差数列的个数。 + +如果 `nums[i] + nums[i - 2] ≠ nums[i - 1] * 2`,说明以 i 结尾的数组无法构成等差数列,`dp[i] = 0`;否则 `dp[i] = 1 + dp[i - 1]`。 + +结果返回 dp 数组所有元素之和即可。 + + + +### **Python3** + + + +```python +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + n = len(nums) + dp = [0] * n + for i in range(2, n): + if nums[i] + nums[i - 2] == (nums[i - 1] << 1): + dp[i] = 1 + dp[i - 1] + return sum(dp) +``` + +### **Java** + + + +```java +class Solution { + public int numberOfArithmeticSlices(int[] nums) { + int n = nums.length; + int[] dp = new int[n]; + for (int i = 2; i < n; ++i) { + if (nums[i] + nums[i - 2] == (nums[i - 1] << 1)) { + dp[i] = 1 + dp[i - 1]; + } + } + int res = 0; + for (int e : dp) { + res += e; + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + int n = nums.size(); + vector dp(n, 0); + for (int i = 2; i < n; ++i) { + if (nums[i] + nums[i - 2] == (nums[i - 1] * 2)) { + dp[i] = 1 + dp[i - 1]; + } + } + int res = 0; + for (auto e : dp) { + res += e; + } + return res; + } +}; +``` + +### **Go** + +```go +func numberOfArithmeticSlices(nums []int) int { + n := len(nums) + dp := make([]int, n) + for i := 2; i < n; i++ { + if nums[i]-nums[i-1] == nums[i-1]-nums[i-2] { + dp[i] = 1 + dp[i-1] + } + } + res := 0 + for _, e := range dp { + res += e + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0414.leetcode414 Third Maximum Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0414.leetcode414 Third Maximum Number-zh.md" new file mode 100644 index 00000000..cd48421a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0414.leetcode414 Third Maximum Number-zh.md" @@ -0,0 +1,163 @@ +# [414. 第三大的数](https://leetcode-cn.com/problems/third-maximum-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0414.Third%20Maximum%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

    + +

     

    + +

    示例 1:

    + +
    +输入:[3, 2, 1]
    +输出:1
    +解释:第三大的数是 1 。
    + +

    示例 2:

    + +
    +输入:[1, 2]
    +输出:2
    +解释:第三大的数不存在, 所以返回最大的数 2 。
    +
    + +

    示例 3:

    + +
    +输入:[2, 2, 3, 1]
    +输出:1
    +解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
    +此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -231 <= nums[i] <= 231 - 1
    • +
    + +

     

    + +

    进阶:你能设计一个时间复杂度 O(n) 的解决方案吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def thirdMax(self, nums: List[int]) -> int: + m1 = m2 = m3 = float('-inf') + for num in nums: + if num == m1 or num == m2 or num == m3: + continue + if num > m1: + m3, m2, m1 = m2, m1, num + elif num > m2: + m3, m2 = m2, num + elif num > m3: + m3 = num + return m1 if m3 == float('-inf') else m3 +``` + +### **Java** + + + +```java +class Solution { + public int thirdMax(int[] nums) { + long m1 = Long.MIN_VALUE; + long m2 = Long.MIN_VALUE; + long m3 = Long.MIN_VALUE; + for (int num : nums) { + if (num == m1 || num == m2 || num == m3) { + continue; + } + if (num > m1) { + m3 = m2; + m2 = m1; + m1 = num; + } else if (num > m2) { + m3 = m2; + m2 = num; + } else if (num > m3) { + m3 = num; + } + } + return (int) (m3 == Long.MIN_VALUE ? m1 : m3); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int thirdMax(vector& nums) { + long m1 = LONG_MIN, m2 = LONG_MIN, m3 = LONG_MIN; + for (int& num : nums) { + if (num == m1 || num == m2 || num == m3) continue; + if (num > m1) { + m3 = m2; + m2 = m1; + m1 = num; + } else if (num > m2) { + m3 = m2; + m2 = num; + } else if (num > m3) { + m3 = num; + } + } + return (int) (m3 == LONG_MIN ? m1 : m3); + } +}; +``` + +### **Go** + +```go +import "math" + +func thirdMax(nums []int) int { + m1, m2, m3 := math.MinInt64, math.MinInt64, math.MinInt64 + for _, num := range nums { + if num == m1 || num == m2 || num == m3 { + continue + } + if num > m1 { + m3, m2, m1 = m2, m1, num + } else if num > m2 { + m3, m2 = m2, num + } else if num > m3 { + m3 = num + } + } + if m3 == math.MinInt64 { + return m1 + } + return m3 +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0415.leetcode415 Add Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0415.leetcode415 Add Strings-zh.md" new file mode 100644 index 00000000..4fbe5738 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0415.leetcode415 Add Strings-zh.md" @@ -0,0 +1,73 @@ +# [415. 字符串相加](https://leetcode-cn.com/problems/add-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0415.Add%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串形式的非负整数 num1num2 ,计算它们的和。

    + +

     

    + +

    提示:

    + +
      +
    1. num1num2 的长度都小于 5100
    2. +
    3. num1num2 都只包含数字 0-9
    4. +
    5. num1num2 都不包含任何前导零
    6. +
    7. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + n1, n2 = len(num1) - 1, len(num2) - 1 + carry = 0 + res = [] + while n1 >= 0 or n2 >= 0 or carry > 0: + carry += (0 if n1 < 0 else int(num1[n1])) + (0 if n2 < 0 else int(num2[n2])) + res.append(str(carry % 10)) + carry //= 10 + n1, n2 = n1 - 1, n2 - 1 + return ''.join(res[::-1]) +``` + +### **Java** + + + +```java +class Solution { + public String addStrings(String num1, String num2) { + int n1 = num1.length() - 1, n2 = num2.length() - 1; + int carry = 0; + StringBuilder sb = new StringBuilder(); + while (n1 >= 0 || n2 >= 0 || carry > 0) { + carry += (n1 < 0 ? 0 : num1.charAt(n1--) - '0') + (n2 < 0 ? 0 : num2.charAt(n2--) - '0'); + sb.append(carry % 10); + carry /= 10; + } + return sb.reverse().toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0416.leetcode416 Partition Equal Subset Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0416.leetcode416 Partition Equal Subset Sum-zh.md" new file mode 100644 index 00000000..1e867fe4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0416.leetcode416 Partition Equal Subset Sum-zh.md" @@ -0,0 +1,66 @@ +# [416. 分割等和子集](https://leetcode-cn.com/problems/partition-equal-subset-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0416.Partition%20Equal%20Subset%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个 只包含正整数 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,5,11,5]
    +输出:true
    +解释:数组可以分割成 [1, 5, 5] 和 [11] 。
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,5]
    +输出:false
    +解释:数组不能分割成两个元素和相等的子集。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 200
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0417.leetcode417 Pacific Atlantic Water Flow-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0417.leetcode417 Pacific Atlantic Water Flow-zh.md" new file mode 100644 index 00000000..85cefe81 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0417.leetcode417 Pacific Atlantic Water Flow-zh.md" @@ -0,0 +1,77 @@ +# [417. 太平洋大西洋水流问题](https://leetcode-cn.com/problems/pacific-atlantic-water-flow) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0417.Pacific%20Atlantic%20Water%20Flow/README_EN.md) + +## 题目描述 + + + +

    给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。

    + +

    规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。

    + +

    请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。

    + +

     

    + +

    提示:

    + +
      +
    1. 输出坐标的顺序不重要
    2. +
    3. mn 都小于150
    4. +
    + +

     

    + +

    示例:

    + +

     

    + +
    +给定下面的 5x5 矩阵:
    +
    +  太平洋 ~   ~   ~   ~   ~ 
    +       ~  1   2   2   3  (5) *
    +       ~  3   2   3  (4) (4) *
    +       ~  2   4  (5)  3   1  *
    +       ~ (6) (7)  1   4   5  *
    +       ~ (5)  1   1   2   4  *
    +          *   *   *   *   * 大西洋
    +
    +返回:
    +
    +[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上图中带括号的单元).
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0418.leetcode418 Sentence Screen Fitting-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0418.leetcode418 Sentence Screen Fitting-zh.md" new file mode 100644 index 00000000..ca8f5bd3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0418.leetcode418 Sentence Screen Fitting-zh.md" @@ -0,0 +1,107 @@ +# [418. 屏幕可显示句子的数量](https://leetcode-cn.com/problems/sentence-screen-fitting) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0418.Sentence%20Screen%20Fitting/README_EN.md) + +## 题目描述 + + + +

    给你一个 rows x cols 的屏幕和一个用 非空 的单词列表组成的句子,请你计算出给定句子可以在屏幕上完整显示的次数。

    + +

    注意:

    + +
      +
    1. 一个单词不能拆分成两行。
    2. +
    3. 单词在句子中的顺序必须保持不变。
    4. +
    5. 在一行中 的两个连续单词必须用一个空格符分隔。
    6. +
    7. 句子中的单词总量不会超过 100。
    8. +
    9. 每个单词的长度大于 0 且不会超过 10。
    10. +
    11. 1 ≤ rows, cols ≤ 20,000.
    12. +
    + +

     

    + +

    示例 1:

    + +
    输入:
    +rows = 2, cols = 8, 句子 sentence = ["hello", "world"]
    +
    +输出:
    +1
    +
    +解释:
    +hello---
    +world---
    +
    +字符 '-' 表示屏幕上的一个空白位置。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +rows = 3, cols = 6, 句子 sentence = ["a", "bcd", "e"]
    +
    +输出:
    +2
    +
    +解释:
    +a-bcd- 
    +e-a---
    +bcd-e-
    +
    +字符 '-' 表示屏幕上的一个空白位置。
    +
    + +

     

    + +

    示例 3:

    + +
    输入:
    +rows = 4, cols = 5, 句子 sentence = ["I", "had", "apple", "pie"]
    +
    +输出:
    +1
    +
    +解释:
    +I-had
    +apple
    +pie-I
    +had--
    +
    +字符 '-' 表示屏幕上的一个空白位置。
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0419.leetcode419 Battleships in a Board-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0419.leetcode419 Battleships in a Board-zh.md" new file mode 100644 index 00000000..477c86ed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0419.leetcode419 Battleships in a Board-zh.md" @@ -0,0 +1,70 @@ +# [419. 甲板上的战舰](https://leetcode-cn.com/problems/battleships-in-a-board) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0419.Battleships%20in%20a%20Board/README_EN.md) + +## 题目描述 + + + +

    给定一个二维的甲板, 请计算其中有多少艘战舰。 战舰用 'X'表示,空位用 '.'表示。 你需要遵守以下规则:

    + +
      +
    • 给你一个有效的甲板,仅由战舰或者空位组成。
    • +
    • 战舰只能水平或者垂直放置。换句话说,战舰只能由 1xN (1 行, N 列)组成,或者 Nx1 (N 行, 1 列)组成,其中N可以是任意大小。
    • +
    • 两艘战舰之间至少有一个水平或垂直的空位分隔 - 即没有相邻的战舰。
    • +
    + +

    示例 :

    + +
    +X..X
    +...X
    +...X
    +
    + +

    在上面的甲板中有2艘战舰。

    + +

    无效样例 :

    + +
    +...X
    +XXXX
    +...X
    +
    + +

    你不会收到这样的无效甲板 - 因为战舰之间至少会有一个空位将它们分开。

    + +

    进阶:

    + +

    你可以用一次扫描算法,只使用O(1)额外空间,并且不修改甲板的值来解决这个问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0420.leetcode420 Strong Password Checker-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0420.leetcode420 Strong Password Checker-zh.md" new file mode 100644 index 00000000..8e1154cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0420.leetcode420 Strong Password Checker-zh.md" @@ -0,0 +1,50 @@ +# [420. 强密码检验器](https://leetcode-cn.com/problems/strong-password-checker) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0420.Strong%20Password%20Checker/README_EN.md) + +## 题目描述 + + + +

    一个强密码应满足以下所有条件:

    + +
      +
    1. 由至少6个,至多20个字符组成。
    2. +
    3. 至少包含一个小写字母,一个大写字母,和一个数字。
    4. +
    5. 同一字符不能连续出现三次 (比如 "...aaa..." 是不允许的, 但是 "...aa...a..." 是可以的)。
    6. +
    + +

    编写函数 strongPasswordChecker(s),s 代表输入字符串,如果 s 已经符合强密码条件,则返回0;否则返回要将 s 修改为满足强密码条件的字符串所需要进行修改的最小步数。

    + +

    插入、删除、替换任一字符都算作一次修改。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0421.leetcode421 Maximum XOR of Two Numbers in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0421.leetcode421 Maximum XOR of Two Numbers in an Array-zh.md" new file mode 100644 index 00000000..932c7b3e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0421.leetcode421 Maximum XOR of Two Numbers in an Array-zh.md" @@ -0,0 +1,54 @@ +# [421. 数组中两个数的最大异或值](https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0421.Maximum%20XOR%20of%20Two%20Numbers%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个非空数组,数组中元素为 a0, a1, a2, … , an-1,其中 0 ≤ ai < 231 

    + +

    找到 ai 和a最大的异或 (XOR) 运算结果,其中0 ≤ i,  j <

    + +

    你能在O(n)的时间解决这个问题吗?

    + +

    示例:

    + +
    +输入: [3, 10, 5, 25, 2, 8]
    +
    +输出: 28
    +
    +解释: 最大的结果是 5 ^ 25 = 28.
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0422.leetcode422 Valid Word Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0422.leetcode422 Valid Word Square-zh.md" new file mode 100644 index 00000000..8d62f002 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0422.leetcode422 Valid Word Square-zh.md" @@ -0,0 +1,121 @@ +# [422. 有效的单词方块](https://leetcode-cn.com/problems/valid-word-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0422.Valid%20Word%20Square/README_EN.md) + +## 题目描述 + + + +

    给你一个单词序列,判断其是否形成了一个有效的单词方块。

    + +

    有效的单词方块是指此由单词序列组成的文字方块的 第 k 行 和 第 k 列 (0 ≤ k < max(行数, 列数)) 所显示的字符串完全相同。

    + +

    注意:

    + +
      +
    1. 给定的单词数大于等于 1 且不超过 500。
    2. +
    3. 单词长度大于等于 1 且不超过 500。
    4. +
    5. 每个单词只包含小写英文字母 a-z
    6. +
    + +

     

    + +

    示例 1:

    + +
    输入:
    +[
    +  "abcd",
    +  "bnrt",
    +  "crmy",
    +  "dtye"
    +]
    +
    +输出:
    +true
    +
    +解释:
    +第 1 行和第 1 列都是 "abcd"。
    +第 2 行和第 2 列都是 "bnrt"。
    +第 3 行和第 3 列都是 "crmy"。
    +第 4 行和第 4 列都是 "dtye"。
    +
    +因此,这是一个有效的单词方块。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +[
    +  "abcd",
    +  "bnrt",
    +  "crm",
    +  "dt"
    +]
    +
    +输出:
    +true
    +
    +解释:
    +第 1 行和第 1 列都是 "abcd"。
    +第 2 行和第 2 列都是 "bnrt"。
    +第 3 行和第 3 列都是 "crm"。
    +第 4 行和第 4 列都是 "dt"。
    +
    +因此,这是一个有效的单词方块。
    +
    + +

     

    + +

    示例 3:

    + +
    输入:
    +[
    +  "ball",
    +  "area",
    +  "read",
    +  "lady"
    +]
    +
    +输出:
    +false
    +
    +解释:
    +第 3 行是 "read" ,然而第 3 列是 "lead"。
    +
    +因此,这 不是 一个有效的单词方块。
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0423.leetcode423 Reconstruct Original Digits from English-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0423.leetcode423 Reconstruct Original Digits from English-zh.md" new file mode 100644 index 00000000..56d2778c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0423.leetcode423 Reconstruct Original Digits from English-zh.md" @@ -0,0 +1,64 @@ +# [423. 从英文中重建数字](https://leetcode-cn.com/problems/reconstruct-original-digits-from-english) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0423.Reconstruct%20Original%20Digits%20from%20English/README_EN.md) + +## 题目描述 + + + +

    给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字0-9。按升序输出原始的数字。

    + +

    注意:

    + +
      +
    1. 输入只包含小写英文字母。
    2. +
    3. 输入保证合法并可以转换为原始的数字,这意味着像 "abc" 或 "zerone" 的输入是不允许的。
    4. +
    5. 输入字符串的长度小于 50,000。
    6. +
    + +

    示例 1:

    + +
    +输入: "owoztneoer"
    +
    +输出: "012" (zeroonetwo)
    +
    + +

    示例 2:

    + +
    +输入: "fviefuro"
    +
    +输出: "45" (fourfive)
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0424.leetcode424 Longest Repeating Character Replacement-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0424.leetcode424 Longest Repeating Character Replacement-zh.md" new file mode 100644 index 00000000..0e2d27d2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0424.leetcode424 Longest Repeating Character Replacement-zh.md" @@ -0,0 +1,62 @@ +# [424. 替换后的最长重复字符](https://leetcode-cn.com/problems/longest-repeating-character-replacement) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0424.Longest%20Repeating%20Character%20Replacement/README_EN.md) + +## 题目描述 + + + +

    给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 次。在执行上述操作后,找到包含重复字母的最长子串的长度。

    + +

    注意:字符串长度 和 k 不会超过 104

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "ABAB", k = 2
    +输出:4
    +解释:用两个'A'替换为两个'B',反之亦然。
    +
    + +

    示例 2:

    + +
    +输入:s = "AABABBA", k = 1
    +输出:4
    +解释:
    +将中间的一个'A'替换为'B',字符串变为 "AABBBBA"。
    +子串 "BBBB" 有最长重复字母, 答案为 4。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0425.leetcode425 Word Squares10425.leetcode425 Word Squares-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0425.leetcode425 Word Squares10425.leetcode425 Word Squares-zh.md" new file mode 100644 index 00000000..1274469f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0425.leetcode425 Word Squares10425.leetcode425 Word Squares-zh.md" @@ -0,0 +1,111 @@ +# [425. 单词方块](https://leetcode-cn.com/problems/word-squares) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0425.Word%20Squares/README_EN.md) + +## 题目描述 + + + +

    给定一个单词集合 (没有重复),找出其中所有的 单词方块 

    + +

    一个单词序列形成了一个有效的单词方块的意思是指从第 k 行和第 k 列 (0 ≤ k < max(行数, 列数)) 来看都是相同的字符串。

    + +

    例如,单词序列 ["ball","area","lead","lady"] 形成了一个单词方块,因为每个单词从水平方向看和从竖直方向看都是相同的。

    + +
    b a l l
    +a r e a
    +l e a d
    +l a d y
    +
    + +

    注意:

    + +
      +
    1. 单词个数大于等于 1 且不超过 500。
    2. +
    3. 所有的单词长度都相同。
    4. +
    5. 单词长度大于等于 1 且不超过 5。
    6. +
    7. 每个单词只包含小写英文字母 a-z
    8. +
    + +

     

    + +

    示例 1:

    + +
    输入:
    +["area","lead","wall","lady","ball"]
    +
    +输出:
    +[
    +  [ "wall",
    +    "area",
    +    "lead",
    +    "lady"
    +  ],
    +  [ "ball",
    +    "area",
    +    "lead",
    +    "lady"
    +  ]
    +]
    +
    +解释:
    +输出包含两个单词方块,输出的顺序不重要,只需要保证每个单词方块内的单词顺序正确即可。 
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +["abat","baba","atan","atal"]
    +
    +输出:
    +[
    +  [ "baba",
    +    "abat",
    +    "baba",
    +    "atan"
    +  ],
    +  [ "baba",
    +    "abat",
    +    "baba",
    +    "atal"
    +  ]
    +]
    +
    +解释:
    +输出包含两个单词方块,输出的顺序不重要,只需要保证每个单词方块内的单词顺序正确即可。 
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0426.leetcode426 Convert Binary Search Tree to Sorted Doubly Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0426.leetcode426 Convert Binary Search Tree to Sorted Doubly Linked List-zh.md" new file mode 100644 index 00000000..0bf77f37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0426.leetcode426 Convert Binary Search Tree to Sorted Doubly Linked List-zh.md" @@ -0,0 +1,198 @@ +# [426. 将二叉搜索树转化为排序的双向链表](https://leetcode-cn.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    将一个 二叉搜索树 就地转化为一个 已排序的双向循环链表

    + +

    对于双向循环列表,你可以将左右孩子指针作为双向循环链表的前驱和后继指针,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。

    + +

    特别地,我们希望可以 就地 完成转换操作。当转化完成以后,树中节点的左指针需要指向前驱,树中节点的右指针需要指向后继。还需要返回链表中最小元素的指针。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [4,2,5,1,3] 
    +
    +
    +输出:[1,2,3,4,5]
    +
    +解释:下图显示了转化后的二叉搜索树,实线表示后继关系,虚线表示前驱关系。
    +
    +
    + +

    示例 2:

    + +
    +输入:root = [2,1,3]
    +输出:[1,2,3]
    +
    + +

    示例 3:

    + +
    +输入:root = []
    +输出:[]
    +解释:输入是空树,所以输出也是空链表。
    +
    + +

    示例 4:

    + +
    +输入:root = [1]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • -1000 <= Node.val <= 1000
    • +
    • Node.left.val < Node.val < Node.right.val
    • +
    • Node.val 的所有值都是独一无二的
    • +
    • 0 <= Number of Nodes <= 2000
    • +
    + + +## 解法 + + + +- 排序链表:二叉搜索树中序遍历得到有序序列 +- 循环链表:头节点指向链表尾节点,尾节点指向链表头节点 +- 双向链表:`pre.right = cur`、`cur.left = pre`、`pre = cur` + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val, left=None, right=None): + self.val = val + self.left = left + self.right = right +""" +class Solution: + def treeToDoublyList(self, root: 'Node') -> 'Node': + def dfs(cur): + if cur is None: + return + dfs(cur.left) + if self.pre is None: + self.head = cur + else: + self.pre.right = cur + cur.left = self.pre + self.pre = cur + dfs(cur.right) + if root is None: + return None + self.head = self.pre = None + dfs(root) + self.head.left = self.pre + self.pre.right = self.head + return self.head +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val,Node _left,Node _right) { + val = _val; + left = _left; + right = _right; + } +}; +*/ + +class Solution { + private Node head; + private Node pre; + + public Node treeToDoublyList(Node root) { + if (root == null) return null; + dfs(root); + head.left = pre; + pre.right = head; + return head; + } + + private void dfs(Node cur) { + if (cur == null) return; + dfs(cur.left); + if (pre == null) head = cur; + else pre.right = cur; + cur.left = pre; + pre = cur; + dfs(cur.right); + } +} +``` + +### **JavaScript** + +```js +/** + * // Definition for a Node. + * function Node(val,left,right) { + * this.val = val; + * this.left = left; + * this.right = right; + * }; + */ +/** + * @param {Node} root + * @return {Node} + */ +var treeToDoublyList = function (root) { + function dfs(cur) { + if (!cur) return; + dfs(cur.left); + if (!pre) head = cur; + else pre.right = cur; + cur.left = pre; + pre = cur; + dfs(cur.right); + } + if (!root) return null; + let head, pre; + dfs(root); + head.left = pre; + pre.right = head; + return head; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0427.leetcode427 Construct Quad Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0427.leetcode427 Construct Quad Tree-zh.md" new file mode 100644 index 00000000..79148bc0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0427.leetcode427 Construct Quad Tree-zh.md" @@ -0,0 +1,133 @@ +# [427. 建立四叉树](https://leetcode-cn.com/problems/construct-quad-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0427.Construct%20Quad%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一个 n * n 矩阵 grid ,矩阵由若干 01 组成。请你用四叉树表示该矩阵 grid

    + +

    你需要返回能表示矩阵的 四叉树 的根结点。

    + +

    注意,当 isLeafFalse 时,你可以把 True 或者 False 赋值给节点,两种值都会被判题机制 接受

    + +

    四叉树数据结构中,每个内部节点只有四个子节点。此外,每个节点都有两个属性:

    + +
      +
    • val:储存叶子结点所代表的区域的值。1 对应 True,0 对应 False
    • +
    • isLeaf: 当这个节点是一个叶子结点时为 True,如果它有 4 个子节点则为 False
    • +
    + +
    class Node {
    +    public boolean val;
    +    public boolean isLeaf;
    +    public Node topLeft;
    +    public Node topRight;
    +    public Node bottomLeft;
    +    public Node bottomRight;
    +}
    + +

    我们可以按以下步骤为二维区域构建四叉树:

    + +
      +
    1. 如果当前网格的值相同(即,全为 0 或者全为 1),将 isLeaf 设为 True ,将 val 设为网格相应的值,并将四个子节点都设为 Null 然后停止。
    2. +
    3. 如果当前网格的值不同,将 isLeaf 设为 False, 将 val 设为任意值,然后如下图所示,将当前网格划分为四个子网格。
    4. +
    5. 使用适当的子网格递归每个子节点。
    6. +
    + +

    + +

    如果你想了解更多关于四叉树的内容,可以参考 wiki

    + +

    四叉树格式:

    + +

    输出为使用层序遍历后四叉树的序列化形式,其中 null 表示路径终止符,其下面不存在节点。

    + +

    它与二叉树的序列化非常相似。唯一的区别是节点以列表形式表示 [isLeaf, val]

    + +

    如果 isLeaf 或者 val 的值为 True ,则表示它在列表 [isLeaf, val] 中的值为 1 ;如果 isLeaf 或者 val 的值为 False ,则表示值为 0

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[0,1],[1,0]]
    +输出:[[0,1],[1,0],[1,1],[1,1],[1,0]]
    +解释:此示例的解释如下:
    +请注意,在下面四叉树的图示中,0 表示 false,1 表示 True 。
    +
    +
    + +

    示例 2:

    + +

    + +
    输入:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
    +输出:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
    +解释:网格中的所有值都不相同。我们将网格划分为四个子网格。
    +topLeft,bottomLeft 和 bottomRight 均具有相同的值。
    +topRight 具有不同的值,因此我们将其再分为 4 个子网格,这样每个子网格都具有相同的值。
    +解释如下图所示:
    +
    +
    + +

    示例 3:

    + +
    输入:grid = [[1,1],[1,1]]
    +输出:[[1,1]]
    +
    + +

    示例 4:

    + +
    输入:grid = [[0]]
    +输出:[[1,0]]
    +
    + +

    示例 5:

    + +
    输入:grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
    +输出:[[0,1],[1,1],[1,0],[1,0],[1,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. n == grid.length == grid[i].length
    2. +
    3. n == 2^x 其中 0 <= x <= 6
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0428.leetcode428 Serialize and Deserialize N-ary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0428.leetcode428 Serialize and Deserialize N-ary Tree-zh.md" new file mode 100644 index 00000000..4b1ef732 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0428.leetcode428 Serialize and Deserialize N-ary Tree-zh.md" @@ -0,0 +1,71 @@ +# [428. 序列化和反序列化 N 叉树](https://leetcode-cn.com/problems/serialize-and-deserialize-n-ary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0428.Serialize%20and%20Deserialize%20N-ary%20Tree/README_EN.md) + +## 题目描述 + + + +

    序列化是指将一个数据结构转化为位序列的过程,因此可以将其存储在文件中或内存缓冲区中,以便稍后在相同或不同的计算机环境中恢复结构。

    + +

    设计一个序列化和反序列化 N 叉树的算法。一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有根树。序列化 / 反序列化算法的算法实现没有限制。你只需要保证 N 叉树可以被序列化为一个字符串并且该字符串可以被反序列化成原树结构即可。

    + +

    例如,你需要序列化下面的 3-叉 树。

    + +

     

    + +

    + +

     

    + +

    为 [1 [3[5 6] 2 4]]。你不需要以这种形式完成,你可以自己创造和实现不同的方法。

    + +

    或者,您可以遵循 LeetCode 的层序遍历序列化格式,其中每组孩子节点由空值分隔。

    + +

    + +

    例如,上面的树可以序列化为 [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

    + +

    你不一定要遵循以上建议的格式,有很多不同的格式,所以请发挥创造力,想出不同的方法来完成本题。

    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目的范围是 [0, 104].
    • +
    • 0 <= Node.val <= 104
    • +
    • N 叉树的高度小于等于 1000
    • +
    • 不要使用类成员 / 全局变量 / 静态变量来存储状态。你的序列化和反序列化算法应是无状态的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0429.leetcode429 N-ary Tree Level Order Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0429.leetcode429 N-ary Tree Level Order Traversal-zh.md" new file mode 100644 index 00000000..94e8bfed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0429.leetcode429 N-ary Tree Level Order Traversal-zh.md" @@ -0,0 +1,161 @@ +# [429. N 叉树的层序遍历](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0429.N-ary%20Tree%20Level%20Order%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

    + +

    树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,null,3,2,4,null,5,6]
    +输出:[[1],[3,2,4],[5,6]]
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树的高度不会超过 1000
    • +
    • 树的节点总数在 [0, 10^4] 之间
    • +
    + + +## 解法 + + + +“BFS 层次遍历实现”。 + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + if root is None: + return [] + q = collections.deque([root]) + res = [] + while q: + n = len(q) + t = [] + for _ in range(n): + node = q.popleft() + t.append(node.val) + if node.children: + q.extend(node.children) + res.append(t) + return res +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + public List> levelOrder(Node root) { + if (root == null) { + return Collections.emptyList(); + } + Deque q = new ArrayDeque<>(); + List> res = new ArrayList<>(); + q.offer(root); + while (!q.isEmpty()) { + List t = new ArrayList<>(); + for (int i = 0, n = q.size(); i < n; ++i) { + Node node = q.poll(); + t.add(node.val); + if (node.children != null) { + q.addAll(node.children); + } + } + res.add(t); + } + return res; + } +} +``` + +也可以使用 DFS: + +```java +class Solution { + public List> levelOrder(Node root) { + List> res = new ArrayList<>(); + dfs(root, 0, res); + return res; + } + + private void dfs(Node root, int level, List> res) { + if (root == null) { + return; + } + if (res.size() <= level) { + res.add(new ArrayList<>()); + } + res.get(level++).add(root.val); + for (Node child : root.children) { + dfs(child, level, res); + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0430.leetcode430 Flatten a Multilevel Doubly Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0430.leetcode430 Flatten a Multilevel Doubly Linked List-zh.md" new file mode 100644 index 00000000..ba5e49ab --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0430.leetcode430 Flatten a Multilevel Doubly Linked List-zh.md" @@ -0,0 +1,178 @@ +# [430. 扁平化多级双向链表](https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0430.Flatten%20a%20Multilevel%20Doubly%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    多级双向链表中,除了指向下一个节点和前一个节点指针之外,它还有一个子链表指针,可能指向单独的双向链表。这些子列表也可能会有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。

    + +

    给你位于列表第一级的头节点,请你扁平化列表,使所有结点出现在单级双链表中。

    + +

     

    + +

    示例 1:

    + +
    输入:head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
    +输出:[1,2,3,7,8,11,12,9,10,4,5,6]
    +解释:
    +
    +输入的多级列表如下图所示:
    +
    +
    +
    +扁平化后的链表如下图:
    +
    +
    +
    + +

    示例 2:

    + +
    输入:head = [1,2,null,3]
    +输出:[1,3,2]
    +解释:
    +
    +输入的多级列表如下图所示:
    +
    +  1---2---NULL
    +  |
    +  3---NULL
    +
    + +

    示例 3:

    + +
    输入:head = []
    +输出:[]
    +
    + +

     

    + +

    如何表示测试用例中的多级链表?

    + +

    示例 1 为例:

    + +
     1---2---3---4---5---6--NULL
    +         |
    +         7---8---9---10--NULL
    +             |
    +             11--12--NULL
    + +

    序列化其中的每一级之后:

    + +
    [1,2,3,4,5,6,null]
    +[7,8,9,10,null]
    +[11,12,null]
    +
    + +

    为了将每一级都序列化到一起,我们需要每一级中添加值为 null 的元素,以表示没有节点连接到上一级的上级节点。

    + +
    [1,2,3,4,5,6,null]
    +[null,null,7,8,9,10,null]
    +[null,11,12,null]
    +
    + +

    合并所有序列化结果,并去除末尾的 null 。

    + +
    [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
    + +

     

    + +

    提示:

    + +
      +
    • 节点数目不超过 1000
    • +
    • 1 <= Node.val <= 10^5
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val, prev, next, child): + self.val = val + self.prev = prev + self.next = next + self.child = child +""" + +class Solution: + def flatten(self, head: 'Node') -> 'Node': + def preorder(pre, cur): + if cur is None: + return pre + cur.prev = pre + pre.next = cur + + t = cur.next + tail = preorder(cur, cur.child) + cur.child = None + return preorder(tail, t) + + if head is None: + return None + dummy = Node(0, None, head, None) + preorder(dummy, head) + dummy.next.prev = None + return dummy.next +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node prev; + public Node next; + public Node child; +}; +*/ + +class Solution { + public Node flatten(Node head) { + if (head == null) { + return null; + } + Node dummy = new Node(); + dummy.next = head; + preorder(dummy, head); + dummy.next.prev = null; + return dummy.next; + } + + private Node preorder(Node pre, Node cur) { + if (cur == null) { + return pre; + } + cur.prev = pre; + pre.next = cur; + + Node t = cur.next; + Node tail = preorder(cur, cur.child); + cur.child = null; + return preorder(tail, t); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0431.leetcode431 Encode N-ary Tree to Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0431.leetcode431 Encode N-ary Tree to Binary Tree-zh.md" new file mode 100644 index 00000000..b3d9fe36 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0431.leetcode431 Encode N-ary Tree to Binary Tree-zh.md" @@ -0,0 +1,57 @@ +# [431. 将 N 叉树编码为二叉树](https://leetcode-cn.com/problems/encode-n-ary-tree-to-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0431.Encode%20N-ary%20Tree%20to%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    设计一个算法,可以将 N 叉树编码为二叉树,并能将该二叉树解码为原 N 叉树。一个 N 叉树是指每个节点都有不超过 N 个孩子节点的有根树。类似地,一个二叉树是指每个节点都有不超过 2 个孩子节点的有根树。你的编码 / 解码的算法的实现没有限制,你只需要保证一个 N 叉树可以编码为二叉树且该二叉树可以解码回原始 N 叉树即可。

    + +

    例如,你可以将下面的 3-叉 树以该种方式编码:

    + +

     

    + +

    + +

     

    + +

    注意,上面的方法仅仅是一个例子,可能可行也可能不可行。你没有必要遵循这种形式转化,你可以自己创造和实现不同的方法。

    + +

    注意:

    + +
      +
    1. N 的范围在 [1, 1000]
    2. +
    3. 不要使用类成员 / 全局变量 / 静态变量来存储状态。你的编码和解码算法应是无状态的。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0432.leetcode432 All O`one Data Structure-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0432.leetcode432 All O`one Data Structure-zh.md" new file mode 100644 index 00000000..5cfa3736 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0432.leetcode432 All O`one Data Structure-zh.md" @@ -0,0 +1,53 @@ +# [432. 全 O(1) 的数据结构](https://leetcode-cn.com/problems/all-oone-data-structure) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0432.All%20O%60one%20Data%20Structure/README_EN.md) + +## 题目描述 + + + +

    请你实现一个数据结构支持以下操作:

    + +
      +
    1. Inc(key) - 插入一个新的值为 1 的 key。或者使一个存在的 key 增加一,保证 key 不为空字符串。
    2. +
    3. Dec(key) - 如果这个 key 的值是 1,那么把他从数据结构中移除掉。否则使一个存在的 key 值减一。如果这个 key 不存在,这个函数不做任何事情。key 保证不为空字符串。
    4. +
    5. GetMaxKey() - 返回 key 中值最大的任意一个。如果没有元素存在,返回一个空字符串""
    6. +
    7. GetMinKey() - 返回 key 中值最小的任意一个。如果没有元素存在,返回一个空字符串""
    8. +
    + +

     

    + +

    挑战:

    + +

    你能够以 O(1) 的时间复杂度实现所有操作吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0433.leetcode433 Minimum Genetic Mutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0433.leetcode433 Minimum Genetic Mutation-zh.md" new file mode 100644 index 00000000..66eeb40c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0433.leetcode433 Minimum Genetic Mutation-zh.md" @@ -0,0 +1,88 @@ +# [433. 最小基因变化](https://leetcode-cn.com/problems/minimum-genetic-mutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0433.Minimum%20Genetic%20Mutation/README_EN.md) + +## 题目描述 + + + +

    一条基因序列由一个带有8个字符的字符串表示,其中每个字符都属于 "A", "C", "G", "T"中的任意一个。

    + +

    假设我们要调查一个基因序列的变化。一次基因变化意味着这个基因序列中的一个字符发生了变化。

    + +

    例如,基因序列由"AACCGGTT" 变化至 "AACCGGTA" 即发生了一次基因变化。

    + +

    与此同时,每一次基因变化的结果,都需要是一个合法的基因串,即该结果属于一个基因库。

    + +

    现在给定3个参数 — start, end, bank,分别代表起始基因序列,目标基因序列及基因库,请找出能够使起始基因序列变化为目标基因序列所需的最少变化次数。如果无法实现目标变化,请返回 -1。

    + +

    注意:

    + +
      +
    1. 起始基因序列默认是合法的,但是它并不一定会出现在基因库中。
    2. +
    3. 如果一个起始基因序列需要多次变化,那么它每一次变化之后的基因序列都必须是合法的。
    4. +
    5. 假定起始基因序列与目标基因序列是不一样的。
    6. +
    + +

     

    + +

    示例 1:

    + +
    +start: "AACCGGTT"
    +end:   "AACCGGTA"
    +bank: ["AACCGGTA"]
    +
    +返回值: 1
    +
    + +

    示例 2:

    + +
    +start: "AACCGGTT"
    +end:   "AAACGGTA"
    +bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
    +
    +返回值: 2
    +
    + +

    示例 3:

    + +
    +start: "AAAAACCC"
    +end:   "AACCCCCC"
    +bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
    +
    +返回值: 3
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0434.leetcode434 Number of Segments in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0434.leetcode434 Number of Segments in a String-zh.md" new file mode 100644 index 00000000..bedb30d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0434.leetcode434 Number of Segments in a String-zh.md" @@ -0,0 +1,49 @@ +# [434. 字符串中的单词数](https://leetcode-cn.com/problems/number-of-segments-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0434.Number%20of%20Segments%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

    + +

    请注意,你可以假定字符串里不包括任何不可打印的字符。

    + +

    示例:

    + +
    输入: "Hello, my name is John"
    +输出: 5
    +解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0435.leetcode435 Non-overlapping Intervals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0435.leetcode435 Non-overlapping Intervals-zh.md" new file mode 100644 index 00000000..7a92f2f0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0435.leetcode435 Non-overlapping Intervals-zh.md" @@ -0,0 +1,77 @@ +# [435. 无重叠区间](https://leetcode-cn.com/problems/non-overlapping-intervals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0435.Non-overlapping%20Intervals/README_EN.md) + +## 题目描述 + + + +

    给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。

    + +

    注意:

    + +
      +
    1. 可以认为区间的终点总是大于它的起点。
    2. +
    3. 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。
    4. +
    + +

    示例 1:

    + +
    +输入: [ [1,2], [2,3], [3,4], [1,3] ]
    +
    +输出: 1
    +
    +解释: 移除 [1,3] 后,剩下的区间没有重叠。
    +
    + +

    示例 2:

    + +
    +输入: [ [1,2], [1,2], [1,2] ]
    +
    +输出: 2
    +
    +解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
    +
    + +

    示例 3:

    + +
    +输入: [ [1,2], [2,3] ]
    +
    +输出: 0
    +
    +解释: 你不需要移除任何区间,因为它们已经是无重叠的了。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0436.leetcode436 Find Right Interval-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0436.leetcode436 Find Right Interval-zh.md" new file mode 100644 index 00000000..acfc5222 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0436.leetcode436 Find Right Interval-zh.md" @@ -0,0 +1,83 @@ +# [436. 寻找右区间](https://leetcode-cn.com/problems/find-right-interval) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0436.Find%20Right%20Interval/README_EN.md) + +## 题目描述 + + + +

    给你一个区间数组 intervals ,其中 intervals[i] = [starti, endi] ,且每个 starti不同

    + +

    区间 i右侧区间 可以记作区间 j ,并满足 startj >= endi ,且 startj 最小化

    + +

    返回一个由每个区间 i右侧区间 的最小起始位置组成的数组。如果某个区间 i 不存在对应的 右侧区间 ,则下标 i 处的值设为 -1

    +  + +

    示例 1:

    + +
    +输入:intervals = [[1,2]]
    +输出:[-1]
    +解释:集合中只有一个区间,所以输出-1。
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[3,4],[2,3],[1,2]]
    +输出:[-1, 0, 1]
    +解释:对于 [3,4] ,没有满足条件的“右侧”区间。
    +对于 [2,3] ,区间[3,4]具有最小的“右”起点;
    +对于 [1,2] ,区间[2,3]具有最小的“右”起点。
    +
    + +

    示例 3:

    + +
    +输入:intervals = [[1,4],[2,3],[3,4]]
    +输出:[-1, 2, -1]
    +解释:对于区间 [1,4] 和 [3,4] ,没有满足条件的“右侧”区间。
    +对于 [2,3] ,区间 [3,4] 有最小的“右”起点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= intervals.length <= 2 * 104
    • +
    • intervals[i].length == 2
    • +
    • -106 <= starti <= endi <= 106
    • +
    • 每个间隔的起点都 不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0437.leetcode437 Path Sum III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0437.leetcode437 Path Sum III-zh.md" new file mode 100644 index 00000000..0ac5e6a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0437.leetcode437 Path Sum III-zh.md" @@ -0,0 +1,65 @@ +# [437. 路径总和 III](https://leetcode-cn.com/problems/path-sum-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0437.Path%20Sum%20III/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,它的每个结点都存放着一个整数值。

    + +

    找出路径和等于给定数值的路径总数。

    + +

    路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

    + +

    二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

    + +

    示例:

    + +
    root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
    +
    +      10
    +     /  \
    +    5   -3
    +   / \    \
    +  3   2   11
    + / \   \
    +3  -2   1
    +
    +返回 3。和等于 8 的路径有:
    +
    +1.  5 -> 3
    +2.  5 -> 2 -> 1
    +3.  -3 -> 11
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0438.leetcode438 Find All Anagrams in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0438.leetcode438 Find All Anagrams in a String-zh.md" new file mode 100644 index 00000000..b987472a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0438.leetcode438 Find All Anagrams in a String-zh.md" @@ -0,0 +1,148 @@ +# [438. 找到字符串中所有字母异位词](https://leetcode-cn.com/problems/find-all-anagrams-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0438.Find%20All%20Anagrams%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 和一个非空字符串 p,找到 中所有是 的字母异位词的子串,返回这些子串的起始索引。

    + +

    字符串只包含小写英文字母,并且字符串 的长度都不超过 20100。

    + +

    说明:

    + +
      +
    • 字母异位词指字母相同,但排列不同的字符串。
    • +
    • 不考虑答案输出的顺序。
    • +
    + +

    示例 1:

    + +
    +输入:
    +s: "cbaebabacd" p: "abc"
    +
    +输出:
    +[0, 6]
    +
    +解释:
    +起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
    +起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
    +
    + +

     示例 2:

    + +
    +输入:
    +s: "abab" p: "ab"
    +
    +输出:
    +[0, 1, 2]
    +
    +解释:
    +起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
    +起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
    +起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
    +
    + +## 解法 + + + +“双指针 + 滑动窗口”求解。定义滑动窗口的左右两个指针 left、right,right 一步步往右走遍历 s 字符串,当 right 指针遍历到的字符加入 t 后超过 counter 的字符数量时,将滑动窗口左侧字符不断弹出,也就是 left 指针不断右移,直到符合要求为止。 + +若滑动窗口长度等于字符串 p 的长度时,这时的 s 子字符串就是 p 的异位词。 + + + +### **Python3** + + + +```python +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + counter = collections.Counter(p) + res = [] + left = right = 0 + t = collections.Counter() + while right < len(s): + t[s[right]] += 1 + while t[s[right]] > counter[s[right]]: + t[s[left]] -= 1 + left += 1 + if right - left == len(p) - 1: + res.append(left) + right += 1 + return res +``` + +### **Java** + + + +“暴力”求解。利用哈希表 counter 统计字符串 p 中每个字符出现的次数。然后遍历字符串 s,判断子串 `s[i, i + p)` 中每个字符出现的次数是否与 counter 相同。若是,则将当前下标 i 添加到结果列表中。时间复杂度 `O(s.length * p.length)`。 + +```java +class Solution { + public List findAnagrams(String s, String p) { + int[] counter = new int[26]; + for (int i = 0; i < p.length(); ++i) { + ++counter[p.charAt(i) - 'a']; + } + List res = new ArrayList<>(); + for (int i = 0; i <= s.length() - p.length(); ++i) { + int[] t = Arrays.copyOf(counter, counter.length); + boolean find = true; + for (int j = i; j < i + p.length(); ++j) { + if (--t[s.charAt(j) - 'a'] < 0) { + find = false; + break; + } + } + if (find) { + res.add(i); + } + } + return res; + } +} +``` + +“双指针 + 滑动窗口”求解。 + +```java +class Solution { + public List findAnagrams(String s, String p) { + int[] counter = new int[26]; + for (int i = 0; i < p.length(); ++i) { + ++counter[p.charAt(i) - 'a']; + } + List res = new ArrayList<>(); + int left = 0, right = 0; + int[] t = new int[26]; + while (right < s.length()) { + int i = s.charAt(right) - 'a'; + ++t[i]; + while (t[i] > counter[i]) { + --t[s.charAt(left) - 'a']; + ++left; + } + if (right - left == p.length() - 1) { + res.add(left); + } + ++right; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0439.leetcode439 Ternary Expression Parser-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0439.leetcode439 Ternary Expression Parser-zh.md" new file mode 100644 index 00000000..483266b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0439.leetcode439 Ternary Expression Parser-zh.md" @@ -0,0 +1,93 @@ +# [439. 三元表达式解析器](https://leetcode-cn.com/problems/ternary-expression-parser) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0439.Ternary%20Expression%20Parser/README_EN.md) + +## 题目描述 + + + +

    给定一个以字符串表示的任意嵌套的三元表达式,计算表达式的值。你可以假定给定的表达式始终都是有效的并且只包含数字 0-9, ?, :, T 和 F (T 和 F 分别表示真和假)。

    + +

    注意:

    + +
      +
    1. 给定的字符串长度 ≤ 10000。
    2. +
    3. 所包含的数字都只有一位数。
    4. +
    5. 条件表达式从右至左结合(和大多数程序设计语言类似)。
    6. +
    7. 条件是 T 和 F其一,即条件永远不会是数字。
    8. +
    9. 表达式的结果是数字 0-9, T 或者 F
    10. +
    + +

     

    + +

    示例 1:

    + +
    输入: "T?2:3"
    +
    +输出: "2"
    +
    +解释: 如果条件为真,结果为 2;否则,结果为 3。
    +
    + +

     

    + +

    示例 2:

    + +
    输入: "F?1:T?4:5"
    +
    +输出: "4"
    +
    +解释: 条件表达式自右向左结合。使用括号的话,相当于:
    +
    +             "(F ? 1 : (T ? 4 : 5))"                   "(F ? 1 : (T ? 4 : 5))"
    +          -> "(F ? 1 : 4)"                 或者     -> "(T ? 4 : 5)"
    +          -> "4"                                    -> "4"
    +
    + +

     

    + +

    示例 3:

    + +
    输入: "T?T?F:5:3"
    +
    +输出: "F"
    +
    +解释: 条件表达式自右向左结合。使用括号的话,相当于:
    +
    +             "(T ? (T ? F : 5) : 3)"                   "(T ? (T ? F : 5) : 3)"
    +          -> "(T ? F : 3)"                 或者       -> "(T ? F : 5)"
    +          -> "F"                                     -> "F"
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0440.leetcode440 K-th Smallest in Lexicographical Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0440.leetcode440 K-th Smallest in Lexicographical Order-zh.md" new file mode 100644 index 00000000..5942b0f8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0440.leetcode440 K-th Smallest in Lexicographical Order-zh.md" @@ -0,0 +1,55 @@ +# [440. 字典序的第K小数字](https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0440.K-th%20Smallest%20in%20Lexicographical%20Order/README_EN.md) + +## 题目描述 + + + +

    给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。

    + +

    注意:1 ≤ k ≤ n ≤ 109

    + +

    示例 :

    + +
    +输入:
    +n: 13   k: 2
    +
    +输出:
    +10
    +
    +解释:
    +字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0441.leetcode441 Arranging Coins-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0441.leetcode441 Arranging Coins-zh.md" new file mode 100644 index 00000000..5a9fad93 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0441.leetcode441 Arranging Coins-zh.md" @@ -0,0 +1,83 @@ +# [441. 排列硬币](https://leetcode-cn.com/problems/arranging-coins) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0441.Arranging%20Coins/README_EN.md) + +## 题目描述 + + + +

    你总共有 枚硬币,你需要将它们摆成一个阶梯形状,第 行就必须正好有 枚硬币。

    + +

    给定一个数字 n,找出可形成完整阶梯行的总行数。

    + +

    是一个非负整数,并且在32位有符号整型的范围内。

    + +

    示例 1:

    + +
    +n = 5
    +
    +硬币可排列成以下几行:
    +¤
    +¤ ¤
    +¤ ¤
    +
    +因为第三行不完整,所以返回2.
    +
    + +

    示例 2:

    + +
    +n = 8
    +
    +硬币可排列成以下几行:
    +¤
    +¤ ¤
    +¤ ¤ ¤
    +¤ ¤
    +
    +因为第四行不完整,所以返回3.
    +
    + + +## 解法 + + + +`(1 + x) * x / 2 <= n`,求解 x。 + +`(x + 1/2)² <= 2n + 1/4`,即 `x <= sqrt(2n + 1/4) - 1/2`。 + +由于 2n 可能溢出,故转换为 `x <= sqrt(2) * sqrt(n + 1/8) - 1/2`。 + + + +### **Python3** + + + +```python +class Solution: + def arrangeCoins(self, n: int) -> int: + return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5) +``` + +### **Java** + + + +```java +class Solution { + public int arrangeCoins(int n) { + return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0442.leetcode442 Find All Duplicates in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0442.leetcode442 Find All Duplicates in an Array-zh.md" new file mode 100644 index 00000000..e55b727a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0442.leetcode442 Find All Duplicates in an Array-zh.md" @@ -0,0 +1,54 @@ +# [442. 数组中重复的数据](https://leetcode-cn.com/problems/find-all-duplicates-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0442.Find%20All%20Duplicates%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 a,其中1 ≤ a[i] ≤ nn为数组长度), 其中有些元素出现两次而其他元素出现一次

    + +

    找到所有出现两次的元素。

    + +

    你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

    + +

    示例:

    + +
    +输入:
    +[4,3,2,7,8,2,3,1]
    +
    +输出:
    +[2,3]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0443.leetcode443 String Compression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0443.leetcode443 String Compression-zh.md" new file mode 100644 index 00000000..8a941195 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0443.leetcode443 String Compression-zh.md" @@ -0,0 +1,99 @@ +# [443. 压缩字符串](https://leetcode-cn.com/problems/string-compression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0443.String%20Compression/README_EN.md) + +## 题目描述 + + + +

    给定一组字符,使用原地算法将其压缩。

    + +

    压缩后的长度必须始终小于或等于原数组长度。

    + +

    数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。

    + +

    在完成原地修改输入数组后,返回数组的新长度。

    + +

     

    + +

    进阶:
    +你能否仅使用O(1) 空间解决问题?

    + +

     

    + +

    示例 1:

    + +
    输入:
    +["a","a","b","b","c","c","c"]
    +
    +输出:
    +返回 6 ,输入数组的前 6 个字符应该是:["a","2","b","2","c","3"]
    +
    +说明:
    +"aa" 被 "a2" 替代。"bb" 被 "b2" 替代。"ccc" 被 "c3" 替代。
    +
    + +

    示例 2:

    + +
    输入:
    +["a"]
    +
    +输出:
    +返回 1 ,输入数组的前 1 个字符应该是:["a"]
    +
    +解释:
    +没有任何字符串被替代。
    +
    + +

    示例 3:

    + +
    输入:
    +["a","b","b","b","b","b","b","b","b","b","b","b","b"]
    +
    +输出:
    +返回 4 ,输入数组的前4个字符应该是:["a","b","1","2"]。
    +
    +解释:
    +由于字符 "a" 不重复,所以不会被压缩。"bbbbbbbbbbbb" 被 “b12” 替代。
    +注意每个数字在数组中都有它自己的位置。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 所有字符都有一个ASCII值在[35, 126]区间内。
    • +
    • 1 <= len(chars) <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0444.leetcode444 Sequence Reconstruction-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0444.leetcode444 Sequence Reconstruction-zh.md" new file mode 100644 index 00000000..96030fed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0444.leetcode444 Sequence Reconstruction-zh.md" @@ -0,0 +1,91 @@ +# [444. 序列重建](https://leetcode-cn.com/problems/sequence-reconstruction) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0444.Sequence%20Reconstruction/README_EN.md) + +## 题目描述 + + + +

    验证原始的序列 org 是否可以从序列集 seqs 中唯一地重建。序列 org 是 1 到 n 整数的排列,其中 1 ≤ n ≤ 104。重建是指在序列集 seqs 中构建最短的公共超序列。(即使得所有  seqs 中的序列都是该最短序列的子序列)。确定是否只可以从 seqs 重建唯一的序列,且该序列就是 org

    + +

    示例 1:

    + +
    输入:
    +org: [1,2,3], seqs: [[1,2],[1,3]]
    +
    +输出:
    +false
    +
    +解释:
    +[1,2,3] 不是可以被重建的唯一的序列,因为 [1,3,2] 也是一个合法的序列。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +org: [1,2,3], seqs: [[1,2]]
    +
    +输出:
    +false
    +
    +解释:
    +可以重建的序列只有 [1,2]。
    +
    + +

     

    + +

    示例 3:

    + +
    输入:
    +org: [1,2,3], seqs: [[1,2],[1,3],[2,3]]
    +
    +输出:
    +true
    +
    +解释:
    +序列 [1,2], [1,3] 和 [2,3] 可以被唯一地重建为原始的序列 [1,2,3]。
    +
    + +

     

    + +

    示例 4:

    + +
    输入:
    +org: [4,1,5,2,6,3], seqs: [[5,2,6,3],[4,1,5,2]]
    +
    +输出:
    +true
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0445.leetcode445 Add Two Numbers II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0445.leetcode445 Add Two Numbers II-zh.md" new file mode 100644 index 00000000..a259b80d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0445.leetcode445 Add Two Numbers II-zh.md" @@ -0,0 +1,111 @@ +# [445. 两数相加 II](https://leetcode-cn.com/problems/add-two-numbers-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0445.Add%20Two%20Numbers%20II/README_EN.md) + +## 题目描述 + + + +

    给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

    + +

    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

    + +

     

    + +

    进阶:

    + +

    如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

    + +

     

    + +

    示例:

    + +
    输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
    +输出:7 -> 8 -> 0 -> 7
    +
    + + +## 解法 + + + +利用栈将数字逆序。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + s1, s2 = [], [] + while l1: + s1.append(l1.val) + l1 = l1.next + while l2: + s2.append(l2.val) + l2 = l2.next + carry, dummy = 0, ListNode(-1) + while s1 or s2 or carry: + carry += (0 if not s1 else s1.pop()) + (0 if not s2 else s2.pop()) + # 创建结点,利用头插法将结点插入链表 + node = ListNode(carry % 10) + node.next = dummy.next + dummy.next = node + carry //= 10 + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + Deque s1 = new ArrayDeque<>(); + Deque s2 = new ArrayDeque<>(); + for (; l1 != null; l1 = l1.next) { + s1.push(l1.val); + } + for (; l2 != null; l2 = l2.next) { + s2.push(l2.val); + } + int carry = 0; + ListNode dummy = new ListNode(-1); + while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) { + carry += (s1.isEmpty() ? 0 : s1.pop()) + (s2.isEmpty() ? 0 : s2.pop()); + // 创建结点,利用头插法将结点插入链表 + ListNode node = new ListNode(carry % 10); + node.next = dummy.next; + dummy.next = node; + carry /= 10; + } + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0446.leetcode446 Arithmetic Slices II - Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0446.leetcode446 Arithmetic Slices II - Subsequence-zh.md" new file mode 100644 index 00000000..fa5ae2b5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0446.leetcode446 Arithmetic Slices II - Subsequence-zh.md" @@ -0,0 +1,86 @@ +# [446. 等差数列划分 II - 子序列](https://leetcode-cn.com/problems/arithmetic-slices-ii-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0446.Arithmetic%20Slices%20II%20-%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。

    + +

    例如,以下数列为等差数列:

    + +
    +1, 3, 5, 7, 9
    +7, 7, 7, 7
    +3, -1, -5, -9
    + +

    以下数列不是等差数列。

    + +
    +1, 1, 2, 5, 7
    + +

     

    + +

    数组 A 包含 N 个数,且索引从 0 开始。该数组子序列将划分为整数序列 (P0, P1, ..., Pk),满足 0 ≤ P0 < P1 < ... < Pk < N。

    + +

     

    + +

    如果序列 A[P0],A[P1],...,A[Pk-1],A[Pk] 是等差的,那么数组 A 的子序列 (P0,P1,…,PK) 称为等差序列。值得注意的是,这意味着 k ≥ 2。

    + +

    函数要返回数组 A 中所有等差子序列的个数。

    + +

    输入包含 N 个整数。每个整数都在 -231 和 231-1 之间,另外 0 ≤ N ≤ 1000。保证输出小于 231-1。

    + +

     

    + +

    示例:

    + +
    +输入:[2, 4, 6, 8, 10]
    +
    +输出:7
    +
    +解释:
    +所有的等差子序列为:
    +[2,4,6]
    +[4,6,8]
    +[6,8,10]
    +[2,4,6,8]
    +[4,6,8,10]
    +[2,4,6,8,10]
    +[2,6,10]
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0447.leetcode447 Number of Boomerangs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0447.leetcode447 Number of Boomerangs-zh.md" new file mode 100644 index 00000000..94d68ccf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0447.leetcode447 Number of Boomerangs-zh.md" @@ -0,0 +1,120 @@ +# [447. 回旋镖的数量](https://leetcode-cn.com/problems/number-of-boomerangs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0447.Number%20of%20Boomerangs/README_EN.md) + +## 题目描述 + + + +

    给定平面上 n 互不相同 的点 points ,其中 points[i] = [xi, yi]回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。

    + +

    返回平面上所有回旋镖的数量。

    +  + +

    示例 1:

    + +
    +输入:points = [[0,0],[1,0],[2,0]]
    +输出:2
    +解释:两个回旋镖为 [[1,0],[0,0],[2,0]][[1,0],[2,0],[0,0]]
    +
    + +

    示例 2:

    + +
    +输入:points = [[1,1],[2,2],[3,3]]
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:points = [[1,1]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == points.length
    • +
    • 1 <= n <= 500
    • +
    • points[i].length == 2
    • +
    • -104 <= xi, yi <= 104
    • +
    • 所有点都 互不相同
    • +
    + +## 解法 + + + +计数器实现。 + +对于每个点,计算其他点到该点的距离,然后按照距离进行分组计数。对每个组中的点进行两两排列组合(A n 取 2,即 `n * (n - 1))`)计数即可。 + + + +### **Python3** + + + +```python +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + n = len(points) + if n < 3: + return 0 + number = 0 + for i in range(n): + distance_counter = collections.Counter() + for j in range(n): + if i == j: + continue + x1, y1 = points[i][0], points[i][1] + x2, y2 = points[j][0], points[j][1] + distance = (x1 - x2) ** 2 + (y1 - y2) ** 2 + distance_counter[distance] += 1 + number += sum([val * (val - 1) for val in distance_counter.values()]) + return number +``` + +### **Java** + + + +```java +class Solution { + public int numberOfBoomerangs(int[][] points) { + int n = points.length; + if (n < 3) { + return 0; + } + int number = 0; + for (int i = 0; i < n; ++i) { + Map distanceCounter = new HashMap<>(); + for (int j = 0; j < n; ++j) { + if (i == j) { + continue; + } + int x1 = points[i][0], y1 = points[i][1]; + int x2 = points[j][0], y2 = points[j][1]; + int distance = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + distanceCounter.put(distance, distanceCounter.getOrDefault(distance, 0) + 1); + } + for (int val : distanceCounter.values()) { + number += val * (val - 1); + } + } + return number; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0448.leetcode448 Find All Numbers Disappeared in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0448.leetcode448 Find All Numbers Disappeared in an Array-zh.md" new file mode 100644 index 00000000..e1b149ee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0448.leetcode448 Find All Numbers Disappeared in an Array-zh.md" @@ -0,0 +1,85 @@ +# [448. 找到所有数组中消失的数字](https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0448.Find%20All%20Numbers%20Disappeared%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

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

    + +

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

    + +

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

    + +

    示例:

    + +
    +输入:
    +[4,3,2,7,8,2,3,1]
    +
    +输出:
    +[5,6]
    +
    + + +## 解法 + + + +- 遍历输入数组的每个元素一次。 +- 把 `|nums[i]|-1` 索引位置的元素标记为负数。即 `nums[|nums[i]|-1]` \* -1。 +- 然后遍历数组,若当前数组元素 `nums[i]` 为负数,说明我们在数组中存在数字 `i+1`。否则,说明数组不存在数字 `i+1`,添加到结果列表中。 + + + +### **Python3** + + + +```python +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for num in nums: + index = abs(num) - 1 + if nums[index] > 0: + nums[index] *= -1 + res = [] + for i, v in enumerate(nums): + if v > 0: + res.append(i + 1) + return res +``` + +### **Java** + + + +```java +class Solution { + public List findDisappearedNumbers(int[] nums) { + int n = nums.length; + for (int i = 0; i < n; ++i) { + int index = Math.abs(nums[i]) - 1; + if (nums[index] > 0) { + nums[index] *= -1; + } + } + List res = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (nums[i] > 0) { + res.add(i + 1); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0449.leetcode449 Serialize and Deserialize BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0449.leetcode449 Serialize and Deserialize BST-zh.md" new file mode 100644 index 00000000..ff41a5e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0449.leetcode449 Serialize and Deserialize BST-zh.md" @@ -0,0 +1,74 @@ +# [449. 序列化和反序列化二叉搜索树](https://leetcode-cn.com/problems/serialize-and-deserialize-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0449.Serialize%20and%20Deserialize%20BST/README_EN.md) + +## 题目描述 + + + +

    序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。

    + +

    设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。

    + +

    编码的字符串应尽可能紧凑。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [2,1,3]
    +输出:[2,1,3]
    +
    + +

    示例 2:

    + +
    +输入:root = []
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数范围是 [0, 104]
    • +
    • 0 <= Node.val <= 104
    • +
    • 题目数据 保证 输入的树是一棵二叉搜索树。
    • +
    + +

     

    + +

    注意:不要使用类成员/全局/静态变量来存储状态。 你的序列化和反序列化算法应该是无状态的。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0450.leetcode450 Delete Node in a BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0450.leetcode450 Delete Node in a BST-zh.md" new file mode 100644 index 00000000..c53f319b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0450.leetcode450 Delete Node in a BST-zh.md" @@ -0,0 +1,80 @@ +# [450. 删除二叉搜索树中的节点](https://leetcode-cn.com/problems/delete-node-in-a-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0450.Delete%20Node%20in%20a%20BST/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。

    + +

    一般来说,删除节点可分为两个步骤:

    + +
      +
    1. 首先找到需要删除的节点;
    2. +
    3. 如果找到了,删除它。
    4. +
    + +

    说明: 要求算法时间复杂度为 O(h),h 为树的高度。

    + +

    示例:

    + +
    +root = [5,3,6,2,4,null,7]
    +key = 3
    +
    +    5
    +   / \
    +  3   6
    + / \   \
    +2   4   7
    +
    +给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。
    +
    +一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。
    +
    +    5
    +   / \
    +  4   6
    + /     \
    +2       7
    +
    +另一个正确答案是 [5,2,6,null,4,null,7]。
    +
    +    5
    +   / \
    +  2   6
    +   \   \
    +    4   7
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0451.leetcode451 Sort Characters By Frequency-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0451.leetcode451 Sort Characters By Frequency-zh.md" new file mode 100644 index 00000000..167a126e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0451.leetcode451 Sort Characters By Frequency-zh.md" @@ -0,0 +1,149 @@ +# [451. 根据字符出现频率排序](https://leetcode-cn.com/problems/sort-characters-by-frequency) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0451.Sort%20Characters%20By%20Frequency/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

    + +

    示例 1:

    + +
    +输入:
    +"tree"
    +
    +输出:
    +"eert"
    +
    +解释:
    +'e'出现两次,'r'和't'都只出现一次。
    +因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
    +
    + +

    示例 2:

    + +
    +输入:
    +"cccaaa"
    +
    +输出:
    +"cccaaa"
    +
    +解释:
    +'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
    +注意"cacaca"是不正确的,因为相同的字母必须放在一起。
    +
    + +

    示例 3:

    + +
    +输入:
    +"Aabb"
    +
    +输出:
    +"bbAa"
    +
    +解释:
    +此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
    +注意'A'和'a'被认为是两种不同的字符。
    +
    + +## 解法 + + + +“计数器 + 桶”实现。其中,计数器统计字符串中每个字符出现的次数。而对于桶,第 i 个位置存放出现次数为 i 的所有字符。 + + + +### **Python3** + + + +```python +class Solution: + def frequencySort(self, s: str) -> str: + counter = collections.Counter(s) + buckets = collections.defaultdict(list) + for c, freq in counter.items(): + buckets[freq].append(c) + res = [] + for i in range(len(s), -1, -1): + if buckets[i]: + for c in buckets[i]: + res.append(c * i) + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String frequencySort(String s) { + Map counter = new HashMap<>(); + for (char c : s.toCharArray()) { + counter.put(c, counter.getOrDefault(c, 0) + 1); + } + List[] buckets = new List[s.length() + 1]; + for (Map.Entry entry : counter.entrySet()) { + char c = entry.getKey(); + int freq = entry.getValue(); + if (buckets[freq] == null) { + buckets[freq] = new ArrayList<>(); + } + buckets[freq].add(c); + } + StringBuilder sb = new StringBuilder(); + for (int i = s.length(); i >= 0; --i) { + if (buckets[i] != null) { + for (char c : buckets[i]) { + for (int j = 0; j < i; ++j) { + sb.append(c); + } + } + } + } + return sb.toString(); + } +} +``` + +### **Go** + +用结构体排序进行模拟 + +```go +type pair struct { + b byte + cnt int +} + +func frequencySort(s string) string { + freq := make(map[byte]int) + for _, r := range s { + freq[byte(r)]++ + } + a := make([]pair, 0) + for k, v := range freq { + a = append(a, pair{b: k, cnt: v}) + } + sort.Slice(a, func(i, j int) bool { return a[i].cnt > a[j].cnt }) + var sb strings.Builder + for _, p := range a { + sb.Write(bytes.Repeat([]byte{p.b}, p.cnt)) + } + return sb.String() +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0452.leetcode452 Minimum Number of Arrows to Burst Balloons-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0452.leetcode452 Minimum Number of Arrows to Burst Balloons-zh.md" new file mode 100644 index 00000000..ef2220aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0452.leetcode452 Minimum Number of Arrows to Burst Balloons-zh.md" @@ -0,0 +1,90 @@ +# [452. 用最少数量的箭引爆气球](https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0452.Minimum%20Number%20of%20Arrows%20to%20Burst%20Balloons/README_EN.md) + +## 题目描述 + + + +

    在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以纵坐标并不重要,因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。

    + +

    一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstartxend 且满足  xstart ≤ x ≤ xend则该气球会被引爆可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

    + +

    给你一个数组 points ,其中 points [i] = [xstart,xend] ,返回引爆所有气球所必须射出的最小弓箭数。

    +  + +

    示例 1:

    + +
    +输入:points = [[10,16],[2,8],[1,6],[7,12]]
    +输出:2
    +解释:对于该样例,x = 6 可以射爆 [2,8],[1,6] 两个气球,以及 x = 11 射爆另外两个气球
    + +

    示例 2:

    + +
    +输入:points = [[1,2],[3,4],[5,6],[7,8]]
    +输出:4
    +
    + +

    示例 3:

    + +
    +输入:points = [[1,2],[2,3],[3,4],[4,5]]
    +输出:2
    +
    + +

    示例 4:

    + +
    +输入:points = [[1,2]]
    +输出:1
    +
    + +

    示例 5:

    + +
    +输入:points = [[2,3],[2,3]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= points.length <= 104
    • +
    • points[i].length == 2
    • +
    • -231 <= xstart < xend <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0453.leetcode453 Minimum Moves to Equal Array Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0453.leetcode453 Minimum Moves to Equal Array Elements-zh.md" new file mode 100644 index 00000000..49cd4d41 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0453.leetcode453 Minimum Moves to Equal Array Elements-zh.md" @@ -0,0 +1,54 @@ +# [453. 最小操作次数使数组元素相等](https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0453.Minimum%20Moves%20to%20Equal%20Array%20Elements/README_EN.md) + +## 题目描述 + + + +

    给定一个长度为 n非空 整数数组,每次操作将会使 n - 1 个元素增加 1。找出让数组所有元素相等的最小操作次数。

    + +

     

    + +

    示例:

    + +
    +输入:
    +[1,2,3]
    +输出:
    +3
    +解释:
    +只需要3次操作(注意每次操作会增加两个元素的值):
    +[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0454.leetcode454 4Sum II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0454.leetcode454 4Sum II-zh.md" new file mode 100644 index 00000000..8fa5a417 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0454.leetcode454 4Sum II-zh.md" @@ -0,0 +1,60 @@ +# [454. 四数相加 II](https://leetcode-cn.com/problems/4sum-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0454.4Sum%20II/README_EN.md) + +## 题目描述 + + + +

    给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0

    + +

    为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。

    + +

    例如:

    + +
    +输入:
    +A = [ 1, 2]
    +B = [-2,-1]
    +C = [-1, 2]
    +D = [ 0, 2]
    +
    +输出:
    +2
    +
    +解释:
    +两个元组如下:
    +1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
    +2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0455.leetcode455 Assign Cookies-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0455.leetcode455 Assign Cookies-zh.md" new file mode 100644 index 00000000..5a7bddd0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0455.leetcode455 Assign Cookies-zh.md" @@ -0,0 +1,100 @@ +# [455. 分发饼干](https://leetcode-cn.com/problems/assign-cookies) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0455.Assign%20Cookies/README_EN.md) + +## 题目描述 + + + +

    假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。

    + +

    对每个孩子 i,都有一个胃口值 g[i]这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

    +  + +

    示例 1:

    + +
    +输入: g = [1,2,3], s = [1,1]
    +输出: 1
    +解释: 
    +你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
    +虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
    +所以你应该输出1。
    +
    + +

    示例 2:

    + +
    +输入: g = [1,2], s = [1,2,3]
    +输出: 2
    +解释: 
    +你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
    +你拥有的饼干数量和尺寸都足以让所有孩子满足。
    +所以你应该输出2.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= g.length <= 3 * 104
    • +
    • 0 <= s.length <= 3 * 104
    • +
    • 1 <= g[i], s[j] <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **JavaScript** + +```js +/** + * @param {number[]} g + * @param {number[]} s + * @return {number} + */ +var findContentChildren = function (g, s) { + let len1 = g.length, len2 = s.length; + if (len2 === 0) return 0; + g.sort((a, b) => a - b); + s.sort((a, b) => a - b); + let i = 0, j = 0; + while (i < len1 && j < len2) { + while (s[j] < g[i]) j++; + if (s[j] >= g[i]) { + i++; + j++; + } else break; + } + return i; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0456.leetcode456 132 Pattern-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0456.leetcode456 132 Pattern-zh.md" new file mode 100644 index 00000000..27989a3a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0456.leetcode456 132 Pattern-zh.md" @@ -0,0 +1,109 @@ +# [456. 132 模式](https://leetcode-cn.com/problems/132-pattern) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0456.132%20Pattern/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,数组中共有 n 个整数。132 模式的子序列 由三个整数 nums[i]nums[j]nums[k] 组成,并同时满足:i < j < knums[i] < nums[k] < nums[j]

    + +

    如果 nums 中存在 132 模式的子序列 ,返回 true ;否则,返回 false

    + +

     

    + +

    进阶:很容易想到时间复杂度为 O(n^2) 的解决方案,你可以设计一个时间复杂度为 O(n logn)O(n) 的解决方案吗?

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,4]
    +输出:false
    +解释:序列中不存在 132 模式的子序列。
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,1,4,2]
    +输出:true
    +解释:序列中有 1 个 132 模式的子序列: [1, 4, 2] 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [-1,3,2,0]
    +输出:true
    +解释:序列中有 3 个 132 模式的的子序列:[-1, 3, 2]、[-1, 3, 0] 和 [-1, 2, 0] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 104
    • +
    • -109 <= nums[i] <= 109
    • +
    + + +## 解法 + + + +单调栈实现。 + + + +### **Python3** + + + +```python +class Solution: + def find132pattern(self, nums: List[int]) -> bool: + ak = float('-inf') + stack = [] + for num in nums[::-1]: + if num < ak: + return True + while stack and num > stack[-1]: + ak = stack.pop() + stack.append(num) + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean find132pattern(int[] nums) { + int ak = Integer.MIN_VALUE; + Deque stack = new ArrayDeque<>(); + for (int i = nums.length - 1; i >= 0; --i) { + if (nums[i] < ak) { + return true; + } + while (!stack.isEmpty() && nums[i] > stack.peek()) { + ak = stack.pop(); + } + stack.push(nums[i]); + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0457.leetcode457 Circular Array Loop-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0457.leetcode457 Circular Array Loop-zh.md" new file mode 100644 index 00000000..0904819f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0457.leetcode457 Circular Array Loop-zh.md" @@ -0,0 +1,97 @@ +# [457. 环形数组是否存在循环](https://leetcode-cn.com/problems/circular-array-loop) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0457.Circular%20Array%20Loop/README_EN.md) + +## 题目描述 + + + +

    存在一个不含 0 环形 数组 nums ,每个 nums[i] 都表示位于下标 i 的角色应该向前或向后移动的下标个数:

    + +
      +
    • 如果 nums[i] 是正数,向前 移动 nums[i]
    • +
    • 如果 nums[i] 是负数,向后 移动 nums[i]
    • +
    + +

    因为数组是 环形 的,所以可以假设从最后一个元素向前移动一步会到达第一个元素,而第一个元素向后移动一步会到达最后一个元素。

    + +

    数组中的 循环 由长度为 k 的下标序列 seq

    + +
      +
    • 遵循上述移动规则将导致重复下标序列 seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
    • +
    • 所有 nums[seq[j]] 应当不是 全正 就是 全负
    • +
    • k > 1
    • +
    + +

    如果 nums 中存在循环,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,-1,1,2,2]
    +输出:true
    +解释:存在循环,按下标 0 -> 2 -> 3 -> 0 。循环长度为 3 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [-1,2]
    +输出:false
    +解释:按下标 1 -> 1 -> 1 ... 的运动无法构成循环,因为循环的长度为 1 。根据定义,循环的长度必须大于 1 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [-2,1,-1,-2,-2]
    +输出:false
    +解释:按下标 1 -> 2 -> 1 -> ... 的运动无法构成循环,因为 nums[1] 是正数,而 nums[2] 是负数。
    +所有 nums[seq[j]] 应当不是全正就是全负。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5000
    • +
    • -1000 <= nums[i] <= 1000
    • +
    • nums[i] != 0
    • +
    + +

     

    + +

    进阶:你能设计一个时间复杂度为 O(n) 且额外空间复杂度为 O(1) 的算法吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0458.leetcode458 Poor Pigs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0458.leetcode458 Poor Pigs-zh.md" new file mode 100644 index 00000000..6e491919 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0458.leetcode458 Poor Pigs-zh.md" @@ -0,0 +1,84 @@ +# [458. 可怜的小猪](https://leetcode-cn.com/problems/poor-pigs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0458.Poor%20Pigs/README_EN.md) + +## 题目描述 + + + +

    buckets 桶液体,其中 正好 有一桶含有毒药,其余装的都是水。它们从外观看起来都一样。为了弄清楚哪只水桶含有毒药,你可以喂一些猪喝,通过观察猪是否会死进行判断。不幸的是,你只有 minutesToTest 分钟时间来确定哪桶液体是有毒的。

    + +

    喂猪的规则如下:

    + +
      +
    1. 选择若干活猪进行喂养
    2. +
    3. 可以允许小猪同时饮用任意数量的桶中的水,并且该过程不需要时间。
    4. +
    5. 小猪喝完水后,必须有 minutesToDie 分钟的冷却时间。在这段时间里,你只能观察,而不允许继续喂猪。
    6. +
    7. 过了 minutesToDie 分钟后,所有喝到毒药的猪都会死去,其他所有猪都会活下来。
    8. +
    9. 重复这一过程,直到时间用完。
    10. +
    + +

    给你桶的数目 bucketsminutesToDieminutesToTest ,返回在规定时间内判断哪个桶有毒所需的 最小 猪数。

    + +

     

    + +

    示例 1:

    + +
    +输入:buckets = 1000, minutesToDie = 15, minutesToTest = 60
    +输出:5
    +
    + +

    示例 2:

    + +
    +输入:buckets = 4, minutesToDie = 15, minutesToTest = 15
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:buckets = 4, minutesToDie = 15, minutesToTest = 30
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= buckets <= 1000
    • +
    • 1 <= minutesToDie <= minutesToTest <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0459.leetcode459 Repeated Substring Pattern-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0459.leetcode459 Repeated Substring Pattern-zh.md" new file mode 100644 index 00000000..acef8ee5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0459.leetcode459 Repeated Substring Pattern-zh.md" @@ -0,0 +1,68 @@ +# [459. 重复的子字符串](https://leetcode-cn.com/problems/repeated-substring-pattern) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0459.Repeated%20Substring%20Pattern/README_EN.md) + +## 题目描述 + + + +

    给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。

    + +

    示例 1:

    + +
    +输入: "abab"
    +
    +输出: True
    +
    +解释: 可由子字符串 "ab" 重复两次构成。
    +
    + +

    示例 2:

    + +
    +输入: "aba"
    +
    +输出: False
    +
    + +

    示例 3:

    + +
    +输入: "abcabcabcabc"
    +
    +输出: True
    +
    +解释: 可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。)
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0460.leetcode460 LFU Cache-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0460.leetcode460 LFU Cache-zh.md" new file mode 100644 index 00000000..4a47478c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0460.leetcode460 LFU Cache-zh.md" @@ -0,0 +1,99 @@ +# [460. LFU 缓存](https://leetcode-cn.com/problems/lfu-cache) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0460.LFU%20Cache/README_EN.md) + +## 题目描述 + + + +

    请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。

    + +

    实现 LFUCache 类:

    + +
      +
    • LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象
    • +
    • int get(int key) - 如果键存在于缓存中,则获取键的值,否则返回 -1。
    • +
    • void put(int key, int value) - 如果键已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近最久未使用 的键。
    • +
    + +

    注意「项的使用次数」就是自插入该项以来对其调用 getput 函数的次数之和。使用次数会在对应项被移除后置为 0 。

    + +

    为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。

    + +

    当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 getput 操作,使用计数器的值将会递增。

    + +

     

    + +

    示例:

    + +
    +输入:
    +["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
    +[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
    +输出:
    +[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
    +
    +解释:
    +// cnt(x) = 键 x 的使用计数
    +// cache=[] 将显示最后一次使用的顺序(最左边的元素是最近的)
    +LFUCache lFUCache = new LFUCache(2);
    +lFUCache.put(1, 1);   // cache=[1,_], cnt(1)=1
    +lFUCache.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1
    +lFUCache.get(1);      // 返回 1
    +                      // cache=[1,2], cnt(2)=1, cnt(1)=2
    +lFUCache.put(3, 3);   // 去除键 2 ,因为 cnt(2)=1 ,使用计数最小
    +                      // cache=[3,1], cnt(3)=1, cnt(1)=2
    +lFUCache.get(2);      // 返回 -1(未找到)
    +lFUCache.get(3);      // 返回 3
    +                      // cache=[3,1], cnt(3)=2, cnt(1)=2
    +lFUCache.put(4, 4);   // 去除键 1 ,1 和 3 的 cnt 相同,但 1 最久未使用
    +                      // cache=[4,3], cnt(4)=1, cnt(3)=2
    +lFUCache.get(1);      // 返回 -1(未找到)
    +lFUCache.get(3);      // 返回 3
    +                      // cache=[3,4], cnt(4)=1, cnt(3)=3
    +lFUCache.get(4);      // 返回 4
    +                      // cache=[3,4], cnt(4)=2, cnt(3)=3
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= capacity, key, value <= 104
    • +
    • 最多调用 105getput 方法
    • +
    + +

     

    + +

    进阶:你可以为这两种操作设计时间复杂度为 O(1) 的实现吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0461.leetcode461 Hamming Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0461.leetcode461 Hamming Distance-zh.md" new file mode 100644 index 00000000..1259b8a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0461.leetcode461 Hamming Distance-zh.md" @@ -0,0 +1,112 @@ +# [461. 汉明距离](https://leetcode-cn.com/problems/hamming-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0461.Hamming%20Distance/README_EN.md) + +## 题目描述 + + + +

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

    + +

    给出两个整数 xy,计算它们之间的汉明距离。

    + +

    注意:
    +0 ≤ x, y < 231.

    + +

    示例:

    + +
    +输入: x = 1, y = 4
    +
    +输出: 2
    +
    +解释:
    +1   (0 0 0 1)
    +4   (0 1 0 0)
    +       ↑   ↑
    +
    +上面的箭头指出了对应二进制位不同的位置。
    +
    + + +## 解法 + + + +利用异或运算的规律找出不同的位 + +- 0 ^ 0 = 0 +- 1 ^ 1 = 0 +- 0 ^ 1 = 1 +- 1 ^ 0 = 1 + + + +### **Python3** + + + +```python +class Solution: + def hammingDistance(self, x: int, y: int) -> int: + num, count = x ^ y, 0 + while num != 0: + num &= num - 1 + count += 1 + return count +``` + +### **Java** + + + +```java +class Solution { + public int hammingDistance(int x, int y) { + int num = x ^ y; + int count = 0; + while (num != 0) { + num &= num - 1; + count++; + } + return count; + } +} +``` + +或者利用库函数 `Integer.bitCount()` + +```java +class Solution { + public int hammingDistance(int x, int y) { + return Integer.bitCount(x ^ y); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @param {number} y + * @return {number} + */ +var hammingDistance = function(x, y) { + let distance = x ^ y; + let count = 0; + while (distance != 0) { + count++; + distance &= (distance - 1); + } + return count; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0462.leetcode462 Minimum Moves to Equal Array Elements II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0462.leetcode462 Minimum Moves to Equal Array Elements II-zh.md" new file mode 100644 index 00000000..c4fd01a8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0462.leetcode462 Minimum Moves to Equal Array Elements II-zh.md" @@ -0,0 +1,55 @@ +# [462. 最少移动次数使数组元素相等 II](https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1。 您可以假设数组的长度最多为10000。

    + +

    例如:

    + +
    +输入:
    +[1,2,3]
    +
    +输出:
    +2
    +
    +说明:
    +只有两个动作是必要的(记得每一步仅可使其中一个元素加1或减1): 
    +
    +[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0463.leetcode463 Island Perimeter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0463.leetcode463 Island Perimeter-zh.md" new file mode 100644 index 00000000..95f3d668 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0463.leetcode463 Island Perimeter-zh.md" @@ -0,0 +1,113 @@ +# [463. 岛屿的周长](https://leetcode-cn.com/problems/island-perimeter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0463.Island%20Perimeter/README_EN.md) + +## 题目描述 + + + +

    给定一个 row x col 的二维网格地图 grid ,其中:grid[i][j] = 1 表示陆地, grid[i][j] = 0 表示水域。

    + +

    网格中的格子 水平和垂直 方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。

    + +

    岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
    +输出:16
    +解释:它的周长是上面图片中的 16 个黄色的边
    + +

    示例 2:

    + +
    +输入:grid = [[1]]
    +输出:4
    +
    + +

    示例 3:

    + +
    +输入:grid = [[1,0]]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • row == grid.length
    • +
    • col == grid[i].length
    • +
    • 1 <= row, col <= 100
    • +
    • grid[i][j]01
    • +
    + + +## 解法 + + + +遍历二维数组 + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **TypeScript** + +```ts +function islandPerimeter(grid: number[][]): number { + let m = grid.length, n = grid[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + let top = 0, left = 0; + if (i > 0) { + top = grid[i - 1][j]; + } + if (j > 0) { + left = grid[i][j - 1]; + } + let cur = grid[i][j]; + if (cur != top) ++ans; + if (cur != left) ++ans; + } + } + // 最后一行, 最后一列 + for (let i = 0; i < m; ++i) { + if (grid[i][n - 1] == 1) ++ans; + } + for (let j = 0; j < n; ++j) { + if (grid[m - 1][j] == 1) ++ans; + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0464.leetcode464 Can I Win-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0464.leetcode464 Can I Win-zh.md" new file mode 100644 index 00000000..9e08dac1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0464.leetcode464 Can I Win-zh.md" @@ -0,0 +1,65 @@ +# [464. 我能赢吗](https://leetcode-cn.com/problems/can-i-win) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0464.Can%20I%20Win/README_EN.md) + +## 题目描述 + + + +

    在 "100 game" 这个游戏中,两名玩家轮流选择从 1 到 10 的任意整数,累计整数和,先使得累计整数和达到或超过 100 的玩家,即为胜者。

    + +

    如果我们将游戏规则改为 “玩家不能重复使用整数” 呢?

    + +

    例如,两个玩家可以轮流从公共整数池中抽取从 1 到 15 的整数(不放回),直到累计整数和 >= 100。

    + +

    给定一个整数 maxChoosableInteger (整数池中可选择的最大数)和另一个整数 desiredTotal(累计和),判断先出手的玩家是否能稳赢(假设两位玩家游戏时都表现最佳)?

    + +

    你可以假设 maxChoosableInteger 不会大于 20, desiredTotal 不会大于 300。

    + +

    示例:

    + +
    输入:
    +maxChoosableInteger = 10
    +desiredTotal = 11
    +
    +输出:
    +false
    +
    +解释:
    +无论第一个玩家选择哪个整数,他都会失败。
    +第一个玩家可以选择从 1 到 10 的整数。
    +如果第一个玩家选择 1,那么第二个玩家只能选择从 2 到 10 的整数。
    +第二个玩家可以通过选择整数 10(那么累积和为 11 >= desiredTotal),从而取得胜利.
    +同样地,第一个玩家选择任意其他整数,第二个玩家都会赢。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0465.leetcode465 Optimal Account Balancing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0465.leetcode465 Optimal Account Balancing-zh.md" new file mode 100644 index 00000000..ae7833a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0465.leetcode465 Optimal Account Balancing-zh.md" @@ -0,0 +1,87 @@ +# [465. 最优账单平衡](https://leetcode-cn.com/problems/optimal-account-balancing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0465.Optimal%20Account%20Balancing/README_EN.md) + +## 题目描述 + + + +

    一群朋友在度假期间会相互借钱。比如说,小爱同学支付了小新同学的午餐共计 10 美元。如果小明同学支付了小爱同学的出租车钱共计 5 美元。我们可以用一个三元组 (x, y, z) 表示一次交易,表示 x 借给 y 共计 z 美元。用 0, 1, 2 表示小爱同学、小新同学和小明同学(0, 1, 2 为人的标号),上述交易可以表示为 [[0, 1, 10], [2, 0, 5]]

    + +

    给定一群人之间的交易信息列表,计算能够还清所有债务的最小次数。

    + +

    注意:

    + +
      +
    1. 一次交易会以三元组 (x, y, z) 表示,并有 x ≠ y 且 z > 0
    2. +
    3. 人的标号可能不是按顺序的,例如标号可能为 0, 1, 2 也可能为 0, 2, 6。
    4. +
    + +

     

    + +

    示例 1:

    + +
    输入:
    +[[0,1,10], [2,0,5]]
    +
    +输出:
    +2
    +
    +解释:
    +人 #0 给人 #1 共计 10 美元。
    +人 #2 给人 #0 共计 5 美元。
    +
    +需要两次交易。一种方式是人 #1 分别给人 #0 和人 #2 各 5 美元。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +[[0,1,10], [1,0,1], [1,2,5], [2,0,5]]
    +
    +输出:
    +1
    +
    +解释:
    +人 #0 给人 #1 共计 10 美元。Person #0 gave person #1 $10.
    +人 #1 给人 #0 共计 1 美元。Person #1 gave person #0 $1.
    +人 #1 给人 #2 共计 5 美元。Person #1 gave person #2 $5.
    +人 #2 给人 #0 共计 5 美元。Person #2 gave person #0 $5.
    +
    +因此,人 #1 需要给人 #0 共计 4 美元,所有的债务即可还清。
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0466.leetcode466 Count The Repetitions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0466.leetcode466 Count The Repetitions-zh.md" new file mode 100644 index 00000000..d8534385 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0466.leetcode466 Count The Repetitions-zh.md" @@ -0,0 +1,58 @@ +# [466. 统计重复个数](https://leetcode-cn.com/problems/count-the-repetitions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0466.Count%20The%20Repetitions/README_EN.md) + +## 题目描述 + + + +

    由 n 个连接的字符串 s 组成字符串 S,记作 S = [s,n]。例如,["abc",3]=“abcabcabc”。

    + +

    如果我们可以从 s2 中删除某些字符使其变为 s1,则称字符串 s1 可以从字符串 s2 获得。例如,根据定义,"abc" 可以从 “abdbec” 获得,但不能从 “acbbe” 获得。

    + +

    现在给你两个非空字符串 s1 和 s2(每个最多 100 个字符长)和两个整数 0 ≤ n1 ≤ 10和 1 ≤ n2 ≤ 106。现在考虑字符串 S1 和 S2,其中 S1=[s1,n1] 、S2=[s2,n2]

    + +

    请你找出一个可以满足使[S2,M]S1 获得的最大整数 M 。

    + +

     

    + +

    示例:

    + +
    输入:
    +s1 ="acb",n1 = 4
    +s2 ="ab",n2 = 2
    +
    +返回:
    +2
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0467.leetcode467 Unique Substrings in Wraparound String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0467.leetcode467 Unique Substrings in Wraparound String-zh.md" new file mode 100644 index 00000000..46bb64db --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0467.leetcode467 Unique Substrings in Wraparound String-zh.md" @@ -0,0 +1,76 @@ +# [467. 环绕字符串中唯一的子字符串](https://leetcode-cn.com/problems/unique-substrings-in-wraparound-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0467.Unique%20Substrings%20in%20Wraparound%20String/README_EN.md) + +## 题目描述 + + + +

    把字符串 s 看作是“abcdefghijklmnopqrstuvwxyz”的无限环绕字符串,所以 s 看起来是这样的:"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". 

    + +

    现在我们有了另一个字符串 p 。你需要的是找出 s 中有多少个唯一的 p 的非空子串,尤其是当你的输入是字符串 p ,你需要输出字符串 sp 的不同的非空子串的数目。 

    + +

    注意: p 仅由小写的英文字母组成,p 的大小可能超过 10000。

    + +

     

    + +

    示例 1:

    + +
    +输入: "a"
    +输出: 1
    +解释: 字符串 S 中只有一个"a"子字符。
    +
    + +

     

    + +

    示例 2:

    + +
    +输入: "cac"
    +输出: 2
    +解释: 字符串 S 中的字符串“cac”只有两个子串“a”、“c”。.
    +
    + +

     

    + +

    示例 3:

    + +
    +输入: "zab"
    +输出: 6
    +解释: 在字符串 S 中有六个子串“z”、“a”、“b”、“za”、“ab”、“zab”。.
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0468.leetcode468 Validate IP Address-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0468.leetcode468 Validate IP Address-zh.md" new file mode 100644 index 00000000..3b46f7ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0468.leetcode468 Validate IP Address-zh.md" @@ -0,0 +1,99 @@ +# [468. 验证IP地址](https://leetcode-cn.com/problems/validate-ip-address) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0468.Validate%20IP%20Address/README_EN.md) + +## 题目描述 + + + +

    编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。

    + +
      +
    • 如果是有效的 IPv4 地址,返回 "IPv4"
    • +
    • 如果是有效的 IPv6 地址,返回 "IPv6"
    • +
    • 如果不是上述类型的 IP 地址,返回 "Neither"
    • +
    + +

    IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1

    + +

    同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。

    + +

    IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。

    + +

    然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。

    + +

    同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。

    + +

     

    + +

    示例 1:

    + +
    输入:IP = "172.16.254.1"
    +输出:"IPv4"
    +解释:有效的 IPv4 地址,返回 "IPv4"
    +
    + +

    示例 2:

    + +
    输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
    +输出:"IPv6"
    +解释:有效的 IPv6 地址,返回 "IPv6"
    +
    + +

    示例 3:

    + +
    输入:IP = "256.256.256.256"
    +输出:"Neither"
    +解释:既不是 IPv4 地址,又不是 IPv6 地址
    +
    + +

    示例 4:

    + +
    输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:"
    +输出:"Neither"
    +
    + +

    示例 5:

    + +
    输入:IP = "1e1.4.5.6"
    +输出:"Neither"
    +
    + +

     

    + +

    提示:

    + +
      +
    • IP 仅由英文字母,数字,字符 '.'':' 组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0469.leetcode469 Convex Polygon-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0469.leetcode469 Convex Polygon-zh.md" new file mode 100644 index 00000000..a9316b8d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0469.leetcode469 Convex Polygon-zh.md" @@ -0,0 +1,68 @@ +# [469. 凸多边形](https://leetcode-cn.com/problems/convex-polygon) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0469.Convex%20Polygon/README_EN.md) + +## 题目描述 + + + +

    给定一个按顺序连接的多边形的顶点,判断该多边形是否为凸多边形。(凸多边形的定义)

    + +

    注:

    + +
      +
    1. 顶点个数至少为 3 个且不超过 10,000。
    2. +
    3. 坐标范围为 -10,000 到 10,000。
    4. +
    5. 你可以假定给定的点形成的多边形均为简单多边形(简单多边形的定义)。换句话说,保证每个顶点处恰好是两条边的汇合点,并且这些边 互不相交 
    6. +
    + +

     

    + +

    示例 1:

    + +
    [[0,0],[0,1],[1,1],[1,0]]
    +
    +输出: True
    +
    +解释:
    +
    + +

    示例 2:

    + +
    [[0,0],[0,10],[10,10],[10,0],[5,5]]
    +
    +输出: False
    +
    +解释:
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0470.leetcode470 Implement Rand10() Using Rand7()-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0470.leetcode470 Implement Rand10() Using Rand7()-zh.md" new file mode 100644 index 00000000..c872a6a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0470.leetcode470 Implement Rand10() Using Rand7()-zh.md" @@ -0,0 +1,86 @@ +# [470. 用 Rand7() 实现 Rand10()](https://leetcode-cn.com/problems/implement-rand10-using-rand7) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0470.Implement%20Rand10%28%29%20Using%20Rand7%28%29/README_EN.md) + +## 题目描述 + + + +

    已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。

    + +

    不要使用系统的 Math.random() 方法。

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    +输入: 1
    +输出: [7]
    +
    + +

    示例 2:

    + +
    +输入: 2
    +输出: [8,4]
    +
    + +

    示例 3:

    + +
    +输入: 3
    +输出: [8,1,10]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. rand7 已定义。
    2. +
    3. 传入参数: n 表示 rand10 的调用次数。
    4. +
    + +

     

    + +

    进阶:

    + +
      +
    1. rand7()调用次数的 期望值 是多少 ?
    2. +
    3. 你能否尽量少调用 rand7() ?
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0471.leetcode471 Encode String with Shortest Length-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0471.leetcode471 Encode String with Shortest Length-zh.md" new file mode 100644 index 00000000..53a5a3df --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0471.leetcode471 Encode String with Shortest Length-zh.md" @@ -0,0 +1,100 @@ +# [471. 编码最短长度的字符串](https://leetcode-cn.com/problems/encode-string-with-shortest-length) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0471.Encode%20String%20with%20Shortest%20Length/README_EN.md) + +## 题目描述 + + + +

    给定一个 非空 字符串,将其编码为具有最短长度的字符串。

    + +

    编码规则是:k[encoded_string],其中在方括号 encoded_string 中的内容重复 k 次。

    + +

    注:

    + +
      +
    • k 为正整数
    • +
    • 如果编码的过程不能使字符串缩短,则不要对其进行编码。如果有多种编码方式,返回 任意一种 即可
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aaa"
    +输出:"aaa"
    +解释:无法将其编码为更短的字符串,因此不进行编码。
    +
    + +

    示例 2:

    + +
    +输入:s = "aaaaa"
    +输出:"5[a]"
    +解释:"5[a]" 比 "aaaaa" 短 1 个字符。
    +
    + +

    示例 3:

    + +
    +输入:s = "aaaaaaaaaa"
    +输出:"10[a]"
    +解释:"a9[a]" 或 "9[a]a" 都是合法的编码,和 "10[a]" 一样长度都为 5。
    +
    + +

    示例 4:

    + +
    +输入:s = "aabcaabcd"
    +输出:"2[aabc]d"
    +解释:"aabc" 出现两次,因此一种答案可以是 "2[aabc]d"。
    +
    + +

    示例 5:

    + +
    +输入:s = "abbbabbbcabbbabbbc"
    +输出:"2[2[abbb]c]"
    +解释:"abbbabbbc" 出现两次,但是 "abbbabbbc" 可以编码为 "2[abbb]c",因此一种答案可以是 "2[2[abbb]c]"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 150
    • +
    • s 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0472.leetcode472 Concatenated Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0472.leetcode472 Concatenated Words-zh.md" new file mode 100644 index 00000000..2ad159c1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0472.leetcode472 Concatenated Words-zh.md" @@ -0,0 +1,71 @@ +# [472. 连接词](https://leetcode-cn.com/problems/concatenated-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0472.Concatenated%20Words/README_EN.md) + +## 题目描述 + + + +

    给定一个 不含重复 单词的字符串数组 words ,编写一个程序,返回 words 中的所有 连接词

    + +

    连接词 的定义为:一个字符串完全是由至少两个给定数组中的单词组成的。

    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
    +输出:["catsdogcats","dogcatsdog","ratcatdogcat"]
    +解释:"catsdogcats"由"cats", "dog" 和 "cats"组成; 
    +     "dogcatsdog"由"dog", "cats"和"dog"组成; 
    +     "ratcatdogcat"由"rat", "cat", "dog"和"cat"组成。
    +
    + +

    示例 2:

    + +
    +输入:words = ["cat","dog","catdog"]
    +输出:["catdog"]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 104
    • +
    • 0 <= words[i].length <= 1000
    • +
    • words[i] 仅由小写字母组成
    • +
    • 0 <= sum(words[i].length) <= 6 * 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0473.leetcode473 Matchsticks to Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0473.leetcode473 Matchsticks to Square-zh.md" new file mode 100644 index 00000000..d25233b8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0473.leetcode473 Matchsticks to Square-zh.md" @@ -0,0 +1,67 @@ +# [473. 火柴拼正方形](https://leetcode-cn.com/problems/matchsticks-to-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0473.Matchsticks%20to%20Square/README_EN.md) + +## 题目描述 + + + +

    还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能折断火柴,可以把火柴连接起来,并且每根火柴都要用到。

    + +

    输入为小女孩拥有火柴的数目,每根火柴用其长度表示。输出即为是否能用所有的火柴拼成正方形。

    + +

    示例 1:

    + +
    +输入: [1,1,2,2,2]
    +输出: true
    +
    +解释: 能拼成一个边长为2的正方形,每边两根火柴。
    +
    + +

    示例 2:

    + +
    +输入: [3,3,3,3,4]
    +输出: false
    +
    +解释: 不能用所有火柴拼成一个正方形。
    +
    + +

    注意:

    + +
      +
    1. 给定的火柴长度和在 0 到 10^9之间。
    2. +
    3. 火柴数组的长度不超过15。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0474.leetcode474 Ones and Zeroes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0474.leetcode474 Ones and Zeroes-zh.md" new file mode 100644 index 00000000..77a141cc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0474.leetcode474 Ones and Zeroes-zh.md" @@ -0,0 +1,76 @@ +# [474. 一和零](https://leetcode-cn.com/problems/ones-and-zeroes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0474.Ones%20and%20Zeroes/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串数组 strs 和两个整数 mn

    + +
    +

    请你找出并返回 strs 的最大子集的大小,该子集中 最多m0n1

    + +

    如果 x 的所有元素也是 y 的元素,集合 x 是集合 y子集

    +
    + +

     

    + +

    示例 1:

    + +
    +输入:strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
    +输出:4
    +解释:最多有 5 个 0 和 3 个 1 的最大子集是 {"10","0001","1","0"} ,因此答案是 4 。
    +其他满足题意但较小的子集包括 {"0001","1"} 和 {"10","1","0"} 。{"111001"} 不满足题意,因为它含 4 个 1 ,大于 n 的值 3 。
    +
    + +

    示例 2:

    + +
    +输入:strs = ["10", "0", "1"], m = 1, n = 1
    +输出:2
    +解释:最大的子集是 {"0", "1"} ,所以答案是 2 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= strs.length <= 600
    • +
    • 1 <= strs[i].length <= 100
    • +
    • strs[i] 仅由 '0' 和 '1' 组成
    • +
    • 1 <= m, n <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0475.leetcode475 Heaters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0475.leetcode475 Heaters-zh.md" new file mode 100644 index 00000000..63a99962 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0475.leetcode475 Heaters-zh.md" @@ -0,0 +1,80 @@ +# [475. 供暖器](https://leetcode-cn.com/problems/heaters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0475.Heaters/README_EN.md) + +## 题目描述 + + + +

    冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。

    + +

    在加热器的加热半径范围内的每个房屋都可以获得供暖。

    + +

    现在,给出位于一条水平线上的房屋 houses 和供暖器 heaters 的位置,请你找出并返回可以覆盖所有房屋的最小加热半径。

    + +

    说明:所有供暖器都遵循你的半径标准,加热的半径也一样。

    + +

     

    + +

    示例 1:

    + +
    +输入: houses = [1,2,3], heaters = [2]
    +输出: 1
    +解释: 仅在位置2上有一个供暖器。如果我们将加热半径设为1,那么所有房屋就都能得到供暖。
    +
    + +

    示例 2:

    + +
    +输入: houses = [1,2,3,4], heaters = [1,4]
    +输出: 1
    +解释: 在位置1, 4上有两个供暖器。我们需要将加热半径设为1,这样所有房屋就都能得到供暖。
    +
    + +

    示例 3:

    + +
    +输入:houses = [1,5], heaters = [2]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= houses.length, heaters.length <= 3 * 104
    • +
    • 1 <= houses[i], heaters[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0476.leetcode476 Number Complement-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0476.leetcode476 Number Complement-zh.md" new file mode 100644 index 00000000..2a4c0e40 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0476.leetcode476 Number Complement-zh.md" @@ -0,0 +1,72 @@ +# [476. 数字的补数](https://leetcode-cn.com/problems/number-complement) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0476.Number%20Complement/README_EN.md) + +## 题目描述 + + + +

    给你一个 整数 num ,输出它的补数。补数是对该数的二进制表示取反。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:num = 5
    +输出:2
    +解释:5 的二进制表示为 101(没有前导零位),其补数为 010。所以你需要输出 2 。
    +
    + +

    示例 2:

    + +
    +输入:num = 1
    +输出:0
    +解释:1 的二进制表示为 1(没有前导零位),其补数为 0。所以你需要输出 0 。
    +
    + +

     

    + +

    提示:

    + + + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0477.leetcode477 Total Hamming Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0477.leetcode477 Total Hamming Distance-zh.md" new file mode 100644 index 00000000..8d372092 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0477.leetcode477 Total Hamming Distance-zh.md" @@ -0,0 +1,61 @@ +# [477. 汉明距离总和](https://leetcode-cn.com/problems/total-hamming-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0477.Total%20Hamming%20Distance/README_EN.md) + +## 题目描述 + + + +

    两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。

    + +

    计算一个数组中,任意两个数之间汉明距离的总和。

    + +

    示例:

    + +
    +输入: 4, 14, 2
    +
    +输出: 6
    +
    +解释: 在二进制表示中,4表示为0100,14表示为1110,2表示为0010。(这样表示是为了体现后四位之间关系)
    +所以答案为:
    +HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
    +
    + +

    注意:

    + +
      +
    1. 数组中元素的范围为从 0到 10^9
    2. +
    3. 数组的长度不超过 10^4
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0478.leetcode478 Generate Random Point in a Circle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0478.leetcode478 Generate Random Point in a Circle-zh.md" new file mode 100644 index 00000000..8fd0f565 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0478.leetcode478 Generate Random Point in a Circle-zh.md" @@ -0,0 +1,70 @@ +# [478. 在圆内随机生成点](https://leetcode-cn.com/problems/generate-random-point-in-a-circle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0478.Generate%20Random%20Point%20in%20a%20Circle/README_EN.md) + +## 题目描述 + + + +

    给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。

    + +

    说明:

    + +
      +
    1. 输入值和输出值都将是浮点数
    2. +
    3. 圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。
    4. +
    5. 圆周上的点也认为是在圆中。
    6. +
    7. randPoint 返回一个包含随机点的x坐标和y坐标的大小为2的数组。
    8. +
    + +

    示例 1:

    + +
    +输入: 
    +["Solution","randPoint","randPoint","randPoint"]
    +[[1,0,0],[],[],[]]
    +输出: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]
    +
    + +

    示例 2:

    + +
    +输入: 
    +["Solution","randPoint","randPoint","randPoint"]
    +[[10,5,-7.5],[],[],[]]
    +输出: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]
    + +

    输入语法说明:

    + +

    输入是两个列表:调用成员函数名和调用的参数。Solution 的构造函数有三个参数,圆的半径、圆心的 x 坐标、圆心的 y 坐标。randPoint 没有参数。输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0479.leetcode479 Largest Palindrome Product-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0479.leetcode479 Largest Palindrome Product-zh.md" new file mode 100644 index 00000000..be2c0379 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0479.leetcode479 Largest Palindrome Product-zh.md" @@ -0,0 +1,54 @@ +# [479. 最大回文数乘积](https://leetcode-cn.com/problems/largest-palindrome-product) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0479.Largest%20Palindrome%20Product/README_EN.md) + +## 题目描述 + + + +

    你需要找到由两个 n 位数的乘积组成的最大回文数。

    + +

    由于结果会很大,你只需返回最大回文数 mod 1337得到的结果。

    + +

    示例:

    + +

    输入: 2

    + +

    输出: 987

    + +

    解释: 99 x 91 = 9009, 9009 % 1337 = 987

    + +

    说明:

    + +

    n 的取值范围为 [1,8]。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0480.leetcode480 Sliding Window Median-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0480.leetcode480 Sliding Window Median-zh.md" new file mode 100644 index 00000000..1fdec863 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0480.leetcode480 Sliding Window Median-zh.md" @@ -0,0 +1,77 @@ +# [480. 滑动窗口中位数](https://leetcode-cn.com/problems/sliding-window-median) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0480.Sliding%20Window%20Median/README_EN.md) + +## 题目描述 + + + +

    中位数是有序序列最中间的那个数。如果序列的长度是偶数,则没有最中间的数;此时中位数是最中间的两个数的平均数。

    + +

    例如:

    + +
      +
    • [2,3,4],中位数是 3
    • +
    • [2,3],中位数是 (2 + 3) / 2 = 2.5
    • +
    + +

    给你一个数组 nums,有一个长度为 k 的窗口从最左端滑动到最右端。窗口中有 k 个数,每次窗口向右移动 1 位。你的任务是找出每次窗口移动后得到的新窗口中元素的中位数,并输出由它们组成的数组。

    + +

     

    + +

    示例:

    + +

    给出 nums = [1,3,-1,-3,5,3,6,7],以及 k = 3。

    + +
    +窗口位置                      中位数
    +---------------               -----
    +[1  3  -1] -3  5  3  6  7       1
    + 1 [3  -1  -3] 5  3  6  7      -1
    + 1  3 [-1  -3  5] 3  6  7      -1
    + 1  3  -1 [-3  5  3] 6  7       3
    + 1  3  -1  -3 [5  3  6] 7       5
    + 1  3  -1  -3  5 [3  6  7]      6
    +
    + +

     因此,返回该滑动窗口的中位数数组 [1,-1,-1,3,5,6]

    + +

     

    + +

    提示:

    + +
      +
    • 你可以假设 k 始终有效,即:k 始终小于等于输入的非空数组的元素个数。
    • +
    • 与真实值误差在 10 ^ -5 以内的答案将被视作正确答案。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0481.leetcode481 Magical String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0481.leetcode481 Magical String-zh.md" new file mode 100644 index 00000000..31bcc776 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0481.leetcode481 Magical String-zh.md" @@ -0,0 +1,67 @@ +# [481. 神奇字符串](https://leetcode-cn.com/problems/magical-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0481.Magical%20String/README_EN.md) + +## 题目描述 + + + +

    神奇的字符串 只包含 '1' 和 '2',并遵守以下规则:

    + +

    字符串 S 是神奇的,因为串联字符 '1' 和 '2' 的连续出现次数会生成字符串 S 本身。

    + +

    字符串 的前几个元素如下:S = “1221121221221121122 ......”

    + +

    如果我们将 S 中连续的 1 和 2 进行分组,它将变成:

    + +

    1 22 11 2 1 22 1 22 11 2 11 22 ......

    + +

    并且每个组中 '1' 或 '2' 的出现次数分别是:

    + +

    1 2 2 1 1 2 1 2 2 1 2 2 ......

    + +

    你可以看到上面的出现次数就是 S 本身。

    + +

    给定一个整数 N 作为输入,返回神奇字符串 中前 N 个数字中的 '1' 的数目。

    + +

    注意:N 不会超过 100,000。

    + +

    示例:

    + +
    输入:6
    +输出:3
    +解释:神奇字符串 S 的前 6 个元素是 “12211”,它包含三个 1,因此返回 3。
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0482.leetcode482 License Key Formatting-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0482.leetcode482 License Key Formatting-zh.md" new file mode 100644 index 00000000..24f3d124 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0482.leetcode482 License Key Formatting-zh.md" @@ -0,0 +1,73 @@ +# [482. 密钥格式化](https://leetcode-cn.com/problems/license-key-formatting) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0482.License%20Key%20Formatting/README_EN.md) + +## 题目描述 + + + +

    有一个密钥字符串 S ,只包含字母,数字以及 '-'(破折号)。其中, N 个 '-' 将字符串分成了 N+1 组。

    + +

    给你一个数字 K,请你重新格式化字符串,使每个分组恰好包含 K 个字符。特别地,第一个分组包含的字符个数必须小于等于 K,但至少要包含 1 个字符。两个分组之间需要用 '-'(破折号)隔开,并且将所有的小写字母转换为大写字母。

    + +

    给定非空字符串 S 和数字 K,按照上面描述的规则进行格式化。

    + +

     

    + +

    示例 1:

    + +
    输入:S = "5F3Z-2e-9-w", K = 4
    +输出:"5F3Z-2E9W"
    +解释:字符串 S 被分成了两个部分,每部分 4 个字符;
    +     注意,两个额外的破折号需要删掉。
    +
    + +

    示例 2:

    + +
    输入:S = "2-5g-3-J", K = 2
    +输出:"2-5G-3J"
    +解释:字符串 S 被分成了 3 个部分,按照前面的规则描述,第一部分的字符可以少于给定的数量,其余部分皆为 2 个字符。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. S 的长度可能很长,请按需分配大小。K 为正整数。
    2. +
    3. S 只包含字母数字(a-z,A-Z,0-9)以及破折号'-'
    4. +
    5. S 非空
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0483.leetcode483 Smallest Good Base-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0483.leetcode483 Smallest Good Base-zh.md" new file mode 100644 index 00000000..9df1f7dd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0483.leetcode483 Smallest Good Base-zh.md" @@ -0,0 +1,79 @@ +# [483. 最小好进制](https://leetcode-cn.com/problems/smallest-good-base) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0483.Smallest%20Good%20Base/README_EN.md) + +## 题目描述 + + + +

    对于给定的整数 n, 如果n的k(k>=2)进制数的所有数位全为1,则称 k(k>=2)是 n 的一个好进制

    + +

    以字符串的形式给出 n, 以字符串的形式返回 n 的最小好进制。

    + +

     

    + +

    示例 1:

    + +
    +输入:"13"
    +输出:"3"
    +解释:13 的 3 进制是 111。
    +
    + +

    示例 2:

    + +
    +输入:"4681"
    +输出:"8"
    +解释:4681 的 8 进制是 11111。
    +
    + +

    示例 3:

    + +
    +输入:"1000000000000000000"
    +输出:"999999999999999999"
    +解释:1000000000000000000 的 999999999999999999 进制是 11。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. n的取值范围是 [3, 10^18]。
    2. +
    3. 输入总是有效且没有前导 0。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0484.leetcode484 Find Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0484.leetcode484 Find Permutation-zh.md" new file mode 100644 index 00000000..5e725cc4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0484.leetcode484 Find Permutation-zh.md" @@ -0,0 +1,70 @@ +# [484. 寻找排列](https://leetcode-cn.com/problems/find-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0484.Find%20Permutation/README_EN.md) + +## 题目描述 + + + +

    现在给定一个只由字符 'D' 和 'I' 组成的 秘密签名。'D' 表示两个数字间的递减关系,'I' 表示两个数字间的递增关系。并且 秘密签名 是由一个特定的整数数组生成的,该数组唯一地包含 1 到 n 中所有不同的数字(秘密签名的长度加 1 等于 n)。例如,秘密签名 "DI" 可以由数组 [2,1,3] 或 [3,1,2] 生成,但是不能由数组 [3,2,4] 或 [2,1,3,4] 生成,因为它们都不是合法的能代表 "DI" 秘密签名 的特定串。

    + +

    现在你的任务是找到具有最小字典序的 [1, 2, ... n] 的排列,使其能代表输入的 秘密签名

    + +

    示例 1:

    + +
    输入: "I"
    +输出: [1,2]
    +解释: [1,2] 是唯一合法的可以生成秘密签名 "I" 的特定串,数字 1 和 2 构成递增关系。
    +
    + +

     

    + +

    示例 2:

    + +
    输入: "DI"
    +输出: [2,1,3]
    +解释: [2,1,3] 和 [3,1,2] 可以生成秘密签名 "DI",
    +但是由于我们要找字典序最小的排列,因此你需要输出 [2,1,3]。
    +
    + +

     

    + +

    注:

    + +
      +
    • 输出字符串只会包含字符 'D' 和 'I'。
    • +
    • 输入字符串的长度是一个正整数且不会超过 10,000。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0485.leetcode485 Max Consecutive Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0485.leetcode485 Max Consecutive Ones-zh.md" new file mode 100644 index 00000000..59773082 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0485.leetcode485 Max Consecutive Ones-zh.md" @@ -0,0 +1,103 @@ +# [485. 最大连续 1 的个数](https://leetcode-cn.com/problems/max-consecutive-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0485.Max%20Consecutive%20Ones/README_EN.md) + +## 题目描述 + + + +

    给定一个二进制数组, 计算其中最大连续 1 的个数。

    + +

     

    + +

    示例:

    + +
    +输入:[1,1,0,1,1,1]
    +输出:3
    +解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 输入的数组只包含 01
    • +
    • 输入数组的长度是正整数,且不超过 10,000。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + res = t = 0 + for num in nums: + if num == 1: + t += 1 + else: + res = max(res, t) + t = 0 + return max(res, t) +``` + +### **Java** + + + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int res = 0, t = 0; + for (int num : nums) { + if (num == 1) { + ++t; + } else { + res = Math.max(res, t); + t = 0; + } + } + return Math.max(res, t); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function (nums) { + let res = 0, + t = 0; + for (let num of nums) { + if (num == 1) { + ++t; + } else { + res = Math.max(res, t); + t = 0; + } + } + return Math.max(res, t); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0486.leetcode486 Predict the Winner-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0486.leetcode486 Predict the Winner-zh.md" new file mode 100644 index 00000000..fd816714 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0486.leetcode486 Predict the Winner-zh.md" @@ -0,0 +1,72 @@ +# [486. 预测赢家](https://leetcode-cn.com/problems/predict-the-winner) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0486.Predict%20the%20Winner/README_EN.md) + +## 题目描述 + + + +

    给定一个表示分数的非负整数数组。 玩家 1 从数组任意一端拿取一个分数,随后玩家 2 继续从剩余数组任意一端拿取分数,然后玩家 1 拿,…… 。每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。

    + +

    给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。

    + +

     

    + +

    示例 1:

    + +
    输入:[1, 5, 2]
    +输出:False
    +解释:一开始,玩家1可以从1和2中进行选择。
    +如果他选择 2(或者 1 ),那么玩家 2 可以从 1(或者 2 )和 5 中进行选择。如果玩家 2 选择了 5 ,那么玩家 1 则只剩下 1(或者 2 )可选。
    +所以,玩家 1 的最终分数为 1 + 2 = 3,而玩家 2 为 5 。
    +因此,玩家 1 永远不会成为赢家,返回 False 。
    +
    + +

    示例 2:

    + +
    输入:[1, 5, 233, 7]
    +输出:True
    +解释:玩家 1 一开始选择 1 。然后玩家 2 必须从 5 和 7 中进行选择。无论玩家 2 选择了哪个,玩家 1 都可以选择 233 。
    +     最终,玩家 1(234 分)比玩家 2(12 分)获得更多的分数,所以返回 True,表示玩家 1 可以成为赢家。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= 给定的数组长度 <= 20.
    • +
    • 数组里所有分数都为非负数且不会大于 10000000 。
    • +
    • 如果最终两个玩家的分数相等,那么玩家 1 仍为赢家。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0487.leetcode487 Max Consecutive Ones II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0487.leetcode487 Max Consecutive Ones II-zh.md" new file mode 100644 index 00000000..3c56a82c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0487.leetcode487 Max Consecutive Ones II-zh.md" @@ -0,0 +1,147 @@ +# [487. 最大连续1的个数 II](https://leetcode-cn.com/problems/max-consecutive-ones-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0487.Max%20Consecutive%20Ones%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个二进制数组,你可以最多将 1 个 0 翻转为 1,找出其中最大连续 1 的个数。

    + +

    示例 1:

    + +
    输入:[1,0,1,1,0]
    +输出:4
    +解释:翻转第一个 0 可以得到最长的连续 1。
    +     当翻转以后,最大连续 1 的个数为 4。
    +
    + +

     

    + +

    注:

    + +
      +
    • 输入数组只包含 0 和 1.
    • +
    • 输入数组的长度为正整数,且不超过 10,000
    • +
    + +

     

    + +

    进阶:
    +如果输入的数字是作为 无限流 逐个输入如何处理?换句话说,内存不能存储下所有从流中输入的数字。您可以有效地解决吗?

    + + +## 解法 + + + +用 `prefix[i]` 数组表示以 i 结尾往前累计的最大连续 1 的个数,`suffix[i]` 数组表示以 i 开头往后累计的最大连续 1 的个数。 + +遍历 `nums` 数组每个为 0 的位置,则位置 i 的最大连续 1 的个数为 `1 + prefix[i-1] + suffix[i+1]`。 + +当然,如果 `nums` 数组没有 0,即所有元素都是 1,那么结果即为 `nums` 数组的长度。 + + + +### **Python3** + + + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + n = len(nums) + prefix = [0] * n + suffix = [0] * n + res = 0 + for i in range(n): + if i == 0: + prefix[i] = nums[i] + else: + prefix[i] = 0 if nums[i] == 0 else prefix[i - 1] + 1 + res = max(res, prefix[i]) + + for i in range(n - 1, -1, -1): + if i == n - 1: + suffix[i] = nums[i] + else: + suffix[i] = 0 if nums[i] == 0 else suffix[i + 1] + 1 + + for i in range(n): + if nums[i] == 0: + t = 1 + if i > 0: + t += prefix[i - 1] + if i < n - 1: + t += suffix[i + 1] + res = max(res, t) + return res +``` + +### **Java** + + + +- 双指针,时间复杂度 O(n²),空间复杂度 O(1) + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int n = nums.length; + int res = 0; + for (int i = 0; i < n; ++i) { + int cnt = 1; + int j = i; + while (j < n && (cnt > 0 || nums[j] == 1)) { + if (nums[j] == 0) --cnt; + ++j; + } + res = Math.max(res, j - i); + } + return res; + } +} +``` + +- 辅助数组,时间复杂度 O(n),空间复杂度 O(n) + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int n = nums.length; + + int[] prefix = new int[n]; + int[] suffix = new int[n]; + + int res = 0; + for (int i = 0; i < n; ++i) { + if (i == 0) prefix[0] = nums[0]; + else prefix[i] = nums[i] == 0 ? 0 : prefix[i - 1] + 1; + res = Math.max(res, prefix[i]); + } + + for (int i = n - 1; i >= 0; --i) { + if (i == n - 1) suffix[n - 1] = nums[n - 1]; + else suffix[i] = nums[i] == 0 ? 0 : suffix[i + 1] + 1; + } + + for (int i = 0; i < n; ++i) { + if (nums[i] == 0) { + int t = 1; + if (i > 0) t += prefix[i - 1]; + if (i < n - 1) t += suffix[i + 1]; + res = Math.max(res, t); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0488.leetcode488 Zuma Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0488.leetcode488 Zuma Game-zh.md" new file mode 100644 index 00000000..51f4e145 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0488.leetcode488 Zuma Game-zh.md" @@ -0,0 +1,89 @@ +# [488. 祖玛游戏](https://leetcode-cn.com/problems/zuma-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0488.Zuma%20Game/README_EN.md) + +## 题目描述 + + + +

    回忆一下祖玛游戏。现在桌上有一串球,颜色有红色(R),黄色(Y),蓝色(B),绿色(G),还有白色(W)。 现在你手里也有几个球。

    + +

    每一次,你可以从手里的球选一个,然后把这个球插入到一串球中的某个位置上(包括最左端,最右端)。接着,如果有出现三个或者三个以上颜色相同的球相连的话,就把它们移除掉。重复这一步骤直到桌上所有的球都被移除。

    + +

    找到插入并可以移除掉桌上所有球所需的最少的球数。如果不能移除桌上所有的球,输出 -1 。

    + +

     

    + +

    示例 1:

    + +
    +输入:board = "WRRBBW", hand = "RB"
    +输出:-1
    +解释:WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
    +
    + +

    示例 2:

    + +
    +输入:board = "WWRRBBWW", hand = "WRBRW"
    +输出:2
    +解释:WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty
    +
    + +

    示例 3:

    + +
    +输入:board = "G", hand = "GGGGG"
    +输出:2
    +解释:G -> G[G] -> GG[G] -> empty 
    +
    + +

    示例 4:

    + +
    +输入:board = "RBYYBBRRB", hand = "YRBGB"
    +输出:3
    +解释:RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty 
    +
    + +

     

    + +

    提示:

    + +
      +
    • 你可以假设桌上一开始的球中,不会有三个及三个以上颜色相同且连着的球。
    • +
    • 1 <= board.length <= 16
    • +
    • 1 <= hand.length <= 5
    • +
    • 输入的两个字符串均为非空字符串,且只包含字符 'R','Y','B','G','W'。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0489.leetcode489 Robot Room Cleaner-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0489.leetcode489 Robot Room Cleaner-zh.md" new file mode 100644 index 00000000..b3167344 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0489.leetcode489 Robot Room Cleaner-zh.md" @@ -0,0 +1,89 @@ +# [489. 扫地机器人](https://leetcode-cn.com/problems/robot-room-cleaner) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0489.Robot%20Room%20Cleaner/README_EN.md) + +## 题目描述 + + + +

    房间(用格栅表示)中有一个扫地机器人。格栅中的每一个格子有空和障碍物两种可能。

    + +

    扫地机器人提供4个API,可以向前进,向左转或者向右转。每次转弯90度。

    + +

    当扫地机器人试图进入障碍物格子时,它的碰撞传感器会探测出障碍物,使它停留在原地。

    + +

    请利用提供的4个API编写让机器人清理整个房间的算法。

    + +
    interface Robot {
    +  // 若下一个方格为空,则返回true,并移动至该方格
    +  // 若下一个方格为障碍物,则返回false,并停留在原地
    +  boolean move();
    +
    +  // 在调用turnLeft/turnRight后机器人会停留在原位置
    +  // 每次转弯90度
    +  void turnLeft();
    +  void turnRight();
    +
    +  // 清理所在方格
    +  void clean();
    +}
    +
    + +

    示例:

    + +
    输入:
    +room = [
    +  [1,1,1,1,1,0,1,1],
    +  [1,1,1,1,1,0,1,1],
    +  [1,0,1,1,1,1,1,1],
    +  [0,0,0,1,0,0,0,0],
    +  [1,1,1,1,1,1,1,1]
    +],
    +row = 1,
    +col = 3
    +
    +解析:
    +房间格栅用0或1填充。0表示障碍物,1表示可以通过。
    +机器人从row=1,col=3的初始位置出发。在左上角的一行以下,三列以右。
    +
    + +

    注意:

    + +
      +
    1. 输入只用于初始化房间和机器人的位置。你需要“盲解”这个问题。换而言之,你必须在对房间和机器人位置一无所知的情况下,只使用4个给出的API解决问题。 
    2. +
    3. 扫地机器人的初始位置一定是空地。
    4. +
    5. 扫地机器人的初始方向向上。
    6. +
    7. 所有可抵达的格子都是相连的,亦即所有标记为1的格子机器人都可以抵达。
    8. +
    9. 可以假定格栅的四周都被墙包围。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0490.leetcode490 The Maze-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0490.leetcode490 The Maze-zh.md" new file mode 100644 index 00000000..645db84f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0490.leetcode490 The Maze-zh.md" @@ -0,0 +1,153 @@ +# [490. 迷宫](https://leetcode-cn.com/problems/the-maze) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0490.The%20Maze/README_EN.md) + +## 题目描述 + + + +由空地(用 0 表示)和墙(用 1 表示)组成的迷宫 maze 中有一个球。球可以途经空地向 上、下、左、右 四个方向滚动,且在遇到墙壁前不会停止滚动。当球停下时,可以选择向下一个方向滚动。 +
    +
    +
    +

    给你一个大小为 m x n 的迷宫 maze ,以及球的初始位置 start 和目的地 destination ,其中 start = [startrow, startcol]destination = [destinationrow, destinationcol] 。请你判断球能否在目的地停下:如果可以,返回 true ;否则,返回 false

    + +

    你可以 假定迷宫的边缘都是墙壁(参考示例)。

    + +

     

    + +

    示例 1:

    + +
    +输入:maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
    +输出:true
    +解释:一种可能的路径是 : 左 -> 下 -> 左 -> 下 -> 右 -> 下 -> 右。
    +
    + +

    示例 2:

    + +
    +输入:maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
    +输出:false
    +解释:不存在能够使球停在目的地的路径。注意,球可以经过目的地,但无法在那里停驻。
    +
    + +

    示例 3:

    + +
    +输入:maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == maze.length
    • +
    • n == maze[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • maze[i][j] is 0 or 1.
    • +
    • start.length == 2
    • +
    • destination.length == 2
    • +
    • 0 <= startrow, destinationrow <= m
    • +
    • 0 <= startcol, destinationcol <= n
    • +
    • 球和目的地都在空地上,且初始时它们不在同一位置
    • +
    • 迷宫 至少包括 2 块空地
    • +
    +
    +
    +
    + + +## 解法 + + + +深度优先搜索或广度优先搜索实现。 + + + +### **Python3** + + + +深度优先搜索。 + +```python +class Solution: + def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: + def dfs(maze, start, destination): + if visited[start[0]][start[1]]: + return False + if start[0] == destination[0] and start[1] == destination[1]: + return True + visited[start[0]][start[1]] = True + l, r, u, d = start[1] - 1, start[1] + 1, start[0] - 1, start[0] + 1 + while l >= 0 and maze[start[0]][l] == 0: + l -= 1 + if dfs(maze, [start[0], l + 1], destination): + return True + while r < len(maze[0]) and maze[start[0]][r] == 0: + r += 1 + if dfs(maze, [start[0], r - 1], destination): + return True + while u >= 0 and maze[u][start[1]] == 0: + u -= 1 + if dfs(maze, [u + 1, start[1]], destination): + return True + while d < len(maze) and maze[d][start[1]] == 0: + d += 1 + if dfs(maze, [d - 1, start[1]], destination): + return True + return False + + visited = [[False for _ in maze[0]] for _ in maze] + return dfs(maze, start, destination) +``` + +### **Java** + + + +```java +class Solution { + private boolean[][] visited; + + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + int m = maze.length, n = maze[0].length; + visited = new boolean[m][n]; + return dfs(maze, start, destination); + } + + private boolean dfs(int[][] maze, int[] start, int[] destination) { + if (visited[start[0]][start[1]]) return false; + if (start[0] == destination[0] && start[1] == destination[1]) return true; + visited[start[0]][start[1]] = true; + + int l = start[1] - 1, r = start[1] + 1, u = start[0] - 1, d = start[0] + 1; + + while (l >= 0 && maze[start[0]][l] == 0) --l; + if (dfs(maze, new int[]{start[0], l + 1}, destination)) return true; + + while (r < maze[0].length && maze[start[0]][r] == 0) ++r; + if (dfs(maze, new int[]{start[0], r - 1}, destination)) return true; + + while (u >= 0 && maze[u][start[1]] == 0) --u; + if (dfs(maze, new int[]{u + 1, start[1]}, destination)) return true; + + while (d < maze.length && maze[d][start[1]] == 0) ++d; + if (dfs(maze, new int[]{d - 1, start[1]}, destination)) return true; + + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0491.leetcode491 Increasing Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0491.leetcode491 Increasing Subsequences-zh.md" new file mode 100644 index 00000000..9f155acb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0491.leetcode491 Increasing Subsequences-zh.md" @@ -0,0 +1,58 @@ +# [491. 递增子序列](https://leetcode-cn.com/problems/increasing-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0491.Increasing%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是 2 。

    + +

     

    + +

    示例:

    + +
    +输入:[4, 6, 7, 7]
    +输出:[[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
    + +

     

    + +

    提示:

    + +
      +
    • 给定数组的长度不会超过15。
    • +
    • 数组中的整数范围是 [-100,100]。
    • +
    • 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0492.leetcode492 Construct the Rectangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0492.leetcode492 Construct the Rectangle-zh.md" new file mode 100644 index 00000000..b95c3a8e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0492.leetcode492 Construct the Rectangle-zh.md" @@ -0,0 +1,90 @@ +# [492. 构造矩形](https://leetcode-cn.com/problems/construct-the-rectangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0492.Construct%20the%20Rectangle/README_EN.md) + +## 题目描述 + + + +

    作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:

    + +
    +1. 你设计的矩形页面必须等于给定的目标面积。
    +
    +2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。
    +
    +3. 长度 L 和宽度 W 之间的差距应当尽可能小。
    +
    + +

    你需要按顺序输出你设计的页面的长度 L 和宽度 W。

    + +

    示例:

    + +
    +输入: 4
    +输出: [2, 2]
    +解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。
    +但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。
    +
    + +

    说明:

    + +
      +
    1. 给定的面积不大于 10,000,000 且为正整数。
    2. +
    3. 你设计的页面的长度和宽度必须都是正整数。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def constructRectangle(self, area: int) -> List[int]: + sr = int(math.sqrt(area)) + l = w = sr + while l <= area and w >= 1: + s = l * w + if s == area: + break + if s > area: + w -= 1 + else: + l += 1 + return [l, w] +``` + +### **Java** + + + +```java +class Solution { + public int[] constructRectangle(int area) { + int sr = (int) Math.sqrt(area); + int l = sr, w = sr; + while (l <= area && w >= 1) { + int s = l * w; + if (s == area) break; + if (s > area) --w; + else ++l; + } + return new int[]{l, w}; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0493.leetcode493 Reverse Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0493.leetcode493 Reverse Pairs-zh.md" new file mode 100644 index 00000000..09e524d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0493.leetcode493 Reverse Pairs-zh.md" @@ -0,0 +1,63 @@ +# [493. 翻转对](https://leetcode-cn.com/problems/reverse-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0493.Reverse%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 nums ,如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对

    + +

    你需要返回给定数组中的重要翻转对的数量。

    + +

    示例 1:

    + +
    +输入: [1,3,2,3,1]
    +输出: 2
    +
    + +

    示例 2:

    + +
    +输入: [2,4,3,5,1]
    +输出: 3
    +
    + +

    注意:

    + +
      +
    1. 给定数组的长度不会超过50000
    2. +
    3. 输入数组中的所有数字都在32位整数的表示范围内。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0494.leetcode494 Target Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0494.leetcode494 Target Sum-zh.md" new file mode 100644 index 00000000..7a51a511 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0494.leetcode494 Target Sum-zh.md" @@ -0,0 +1,132 @@ +# [494. 目标和](https://leetcode-cn.com/problems/target-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0494.Target%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。

    + +

    返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

    + +

     

    + +

    示例:

    + +
    输入:nums: [1, 1, 1, 1, 1], S: 3
    +输出:5
    +解释:
    +
    +-1+1+1+1+1 = 3
    ++1-1+1+1+1 = 3
    ++1+1-1+1+1 = 3
    ++1+1+1-1+1 = 3
    ++1+1+1+1-1 = 3
    +
    +一共有5种方法让最终目标和为3。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 数组非空,且长度不会超过 20 。
    • +
    • 初始的数组的和不会超过 1000 。
    • +
    • 保证返回的最终结果能被 32 位整数存下。
    • +
    + + +## 解法 + + + +类似背包问题,只不过下标可能会出现负数,需要特殊处理。 + + + +### **Python3** + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + if target < -1000 or target > 1000: + return 0 + n = len(nums) + dp = [[0] * 2001 for i in range(n)] + dp[0][nums[0] + 1000] += 1 + dp[0][-nums[0] + 1000] += 1 + for i in range(1, n): + for j in range(-1000, 1001): + if dp[i - 1][j + 1000] > 0: + dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000] + dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000] + return dp[n - 1][target + 1000] +``` + +### **Java** + + + +```java +class Solution { + public int findTargetSumWays(int[] nums, int target) { + if (target < -1000 || target > 1000) { + return 0; + } + + int n = nums.length; + int[][] dp = new int[n][2001]; + + dp[0][nums[0] + 1000] += 1; + dp[0][-nums[0] + 1000] += 1; + + for (int i = 1; i < n; i++) { + for (int j = -1000; j <= 1000; j++) { + if (dp[i - 1][j + 1000] > 0) { + dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000]; + dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000]; + } + } + } + return dp[n - 1][target + 1000]; + } +} +``` + +### **Go** + + + +```go +func findTargetSumWays(nums []int, target int) int { + if target < -1000 || target > 1000 { + return 0 + } + n := len(nums) + dp := make([][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([]int, 2001) + } + dp[0][nums[0]+1000] += 1 + dp[0][-nums[0]+1000] += 1 + for i := 1; i < n; i++ { + for j := -1000; j <= 1000; j++ { + if dp[i-1][j+1000] > 0 { + dp[i][j+nums[i]+1000] += dp[i-1][j+1000] + dp[i][j-nums[i]+1000] += dp[i-1][j+1000] + } + } + } + return dp[n-1][target+1000] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0495.leetcode495 Teemo Attacking-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0495.leetcode495 Teemo Attacking-zh.md" new file mode 100644 index 00000000..e94829ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0495.leetcode495 Teemo Attacking-zh.md" @@ -0,0 +1,72 @@ +# [495. 提莫攻击](https://leetcode-cn.com/problems/teemo-attacking) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0495.Teemo%20Attacking/README_EN.md) + +## 题目描述 + + + +

    在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄,他的攻击可以让敌方英雄艾希(编者注:寒冰射手)进入中毒状态。现在,给出提莫对艾希的攻击时间序列和提莫攻击的中毒持续时间,你需要输出艾希的中毒状态总时长。

    + +

    你可以认为提莫在给定的时间点进行攻击,并立即使艾希处于中毒状态。

    + +

     

    + +

    示例1:

    + +
    输入: [1,4], 2
    +输出: 4
    +原因: 第 1 秒初,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒末结束。
    +第 4 秒初,提莫再次攻击艾希,使得艾希获得另外 2 秒中毒时间。
    +所以最终输出 4 秒。
    +
    + +

    示例2:

    + +
    输入: [1,2], 2
    +输出: 3
    +原因: 第 1 秒初,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒末结束。
    +但是第 2 秒初,提莫再次攻击了已经处于中毒状态的艾希。
    +由于中毒状态不可叠加,提莫在第 2 秒初的这次攻击会在第 3 秒末结束。
    +所以最终输出 3 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 你可以假定时间序列数组的总长度不超过 10000。
    2. +
    3. 你可以假定提莫攻击时间序列中的数字和提莫攻击的中毒持续时间都是非负整数,并且不超过 10,000,000。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0496.leetcode496 Next Greater Element I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0496.leetcode496 Next Greater Element I-zh.md" new file mode 100644 index 00000000..c67dffa8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0496.leetcode496 Next Greater Element I-zh.md" @@ -0,0 +1,130 @@ +# [496. 下一个更大元素 I](https://leetcode-cn.com/problems/next-greater-element-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0496.Next%20Greater%20Element%20I/README_EN.md) + +## 题目描述 + + + +

    给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。

    + +

    请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。

    + +

    nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1

    + +

     

    + +

    示例 1:

    + +
    +输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
    +输出: [-1,3,-1]
    +解释:
    +    对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。
    +    对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。
    +    对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
    + +

    示例 2:

    + +
    +输入: nums1 = [2,4], nums2 = [1,2,3,4].
    +输出: [3,-1]
    +解释:
    +    对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。
    +    对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length <= nums2.length <= 1000
    • +
    • 0 <= nums1[i], nums2[i] <= 104
    • +
    • nums1nums2中所有整数 互不相同
    • +
    • nums1 中的所有整数同样出现在 nums2
    • +
    + +

     

    + +

    进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?

    + + +## 解法 + + + +先对将 nums2 中的每一个元素,求出其下一个更大的元素。随后对于将这些答案放入哈希映射(HashMap)中,再遍历数组 nums1,并直接找出答案。对于 nums2,可以使用单调栈来解决这个问题。 + + + +### **Python3** + + + +```python +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + mapper = {} + for num in nums2: + while stack and stack[-1] < num: + mapper[stack.pop()] = num + stack.append(num) + return [mapper.get(num, -1) for num in nums1] +``` + +### **Java** + + + +```java +class Solution { + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + Deque stack = new ArrayDeque<>(); + Map map = new HashMap<>(); + for (int num : nums2) { + while (!stack.isEmpty() && stack.peek() < num) { + map.put(stack.pop(), num); + } + stack.push(num); + } + int n = nums1.length; + int[] res = new int[n]; + for (int i = 0; i < n; ++i) { + res[i] = map.getOrDefault(nums1[i], -1); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function(nums1, nums2) { + let stack = []; + let nextGreater = {}; + for (let num of nums2) { + while (stack.length > 0 && stack[stack.length - 1] < num) { + nextGreater[stack.pop()] = num; + } + stack.push(num); + } + let res = nums1.map(d => nextGreater[d] || -1); + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0497.leetcode497 Random Point in Non-overlapping Rectangles-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0497.leetcode497 Random Point in Non-overlapping Rectangles-zh.md" new file mode 100644 index 00000000..456665c1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0497.leetcode497 Random Point in Non-overlapping Rectangles-zh.md" @@ -0,0 +1,81 @@ +# [497. 非重叠矩形中的随机点](https://leetcode-cn.com/problems/random-point-in-non-overlapping-rectangles) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0497.Random%20Point%20in%20Non-overlapping%20Rectangles/README_EN.md) + +## 题目描述 + + + +

    给定一个非重叠轴对齐矩形的列表 rects,写一个函数 pick 随机均匀地选取矩形覆盖的空间中的整数点。

    + +

    提示:

    + +
      +
    1. 整数点是具有整数坐标的点。
    2. +
    3. 矩形周边上的点包含在矩形覆盖的空间中。
    4. +
    5. i 个矩形 rects [i] = [x1,y1,x2,y2],其中 [x1,y1] 是左下角的整数坐标,[x2,y2] 是右上角的整数坐标。
    6. +
    7. 每个矩形的长度和宽度不超过 2000。
    8. +
    9. 1 <= rects.length <= 100
    10. +
    11. pick 以整数坐标数组 [p_x, p_y] 的形式返回一个点。
    12. +
    13. pick 最多被调用10000次。
    14. +
    + +

     

    + +

    示例 1:

    + +
    +输入: 
    +["Solution","pick","pick","pick"]
    +[[[[1,1,5,5]]],[],[],[]]
    +输出: 
    +[null,[4,1],[4,1],[3,3]]
    +
    + +

    示例 2:

    + +
    +输入: 
    +["Solution","pick","pick","pick","pick","pick"]
    +[[[[-2,-2,-1,-1],[1,0,3,0]]],[],[],[],[],[]]
    +输出: 
    +[null,[-1,-2],[2,0],[-2,-1],[3,0],[-2,-2]]
    + +

     

    + +

    输入语法的说明:

    + +

    输入是两个列表:调用的子例程及其参数。Solution 的构造函数有一个参数,即矩形数组 rectspick 没有参数。参数总是用列表包装的,即使没有也是如此。

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0498.leetcode498 Diagonal Traverse-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0498.leetcode498 Diagonal Traverse-zh.md" new file mode 100644 index 00000000..9a696586 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0498.leetcode498 Diagonal Traverse-zh.md" @@ -0,0 +1,65 @@ +# [498. 对角线遍历](https://leetcode-cn.com/problems/diagonal-traverse) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0498.Diagonal%20Traverse/README_EN.md) + +## 题目描述 + + + +

    给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。

    + +

     

    + +

    示例:

    + +
    输入:
    +[
    + [ 1, 2, 3 ],
    + [ 4, 5, 6 ],
    + [ 7, 8, 9 ]
    +]
    +
    +输出:  [1,2,4,7,5,3,6,8,9]
    +
    +解释:
    +
    +
    + +

     

    + +

    说明:

    + +
      +
    1. 给定矩阵中的元素总数不会超过 100000 。
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0499.leetcode499 The Maze III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0499.leetcode499 The Maze III-zh.md" new file mode 100644 index 00000000..ac989184 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0499.leetcode499 The Maze III-zh.md" @@ -0,0 +1,98 @@ +# [499. 迷宫 III](https://leetcode-cn.com/problems/the-maze-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0400-0499/0499.The%20Maze%20III/README_EN.md) + +## 题目描述 + + + +

    由空地和墙组成的迷宫中有一个。球可以向上(u)下(d)左(l)右(r)四个方向滚动,但在遇到墙壁前不会停止滚动。当球停下时,可以选择下一个方向。迷宫中还有一个,当球运动经过洞时,就会掉进洞里。

    + +

    给定球的起始位置,目的地迷宫,找出让球以最短距离掉进洞里的路径。 距离的定义是球从起始位置(不包括)到目的地(包括)经过的空地个数。通过'u', 'd', 'l' 和 'r'输出球的移动方向。 由于可能有多条最短路径, 请输出字典序最小的路径如果球无法进入洞,输出"impossible"。

    + +

    迷宫由一个0和1的二维数组表示。 1表示墙壁,0表示空地。你可以假定迷宫的边缘都是墙壁。起始位置和目的地的坐标通过行号和列号给出。

    + +

     

    + +

    示例1:

    + +
    输入 1: 迷宫由以下二维数组表示
    +
    +0 0 0 0 0
    +1 1 0 0 1
    +0 0 0 0 0
    +0 1 0 0 1
    +0 1 0 0 0
    +
    +输入 2: 球的初始位置 (rowBall, colBall) = (4, 3)
    +输入 3: 洞的位置 (rowHole, colHole) = (0, 1)
    +
    +输出: "lul"
    +
    +解析: 有两条让球进洞的最短路径。
    +第一条路径是 左 -> 上 -> 左, 记为 "lul".
    +第二条路径是 上 -> 左, 记为 'ul'.
    +两条路径都具有最短距离6, 但'l' < 'u',故第一条路径字典序更小。因此输出"lul"。
    +
    +
    + +

    示例 2:

    + +
    输入 1: 迷宫由以下二维数组表示
    +
    +0 0 0 0 0
    +1 1 0 0 1
    +0 0 0 0 0
    +0 1 0 0 1
    +0 1 0 0 0
    +
    +输入 2: 球的初始位置 (rowBall, colBall) = (4, 3)
    +输入 3: 洞的位置 (rowHole, colHole) = (3, 0)
    +
    +输出: "impossible"
    +
    +示例: 球无法到达洞。
    +
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 迷宫中只有一个球和一个目的地。
    2. +
    3. 球和洞都在空地上,且初始时它们不在同一位置。
    4. +
    5. 给定的迷宫不包括边界 (如图中的红色矩形), 但你可以假设迷宫的边缘都是墙壁。
    6. +
    7. 迷宫至少包括2块空地,行数和列数均不超过30。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0500.leetcode500 Keyboard Row-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0500.leetcode500 Keyboard Row-zh.md" new file mode 100644 index 00000000..2dc410b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0500.leetcode500 Keyboard Row-zh.md" @@ -0,0 +1,130 @@ +# [500. 键盘行](https://leetcode-cn.com/problems/keyboard-row) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0500.Keyboard%20Row/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。

    + +

    美式键盘 中:

    + +
      +
    • 第一行由字符 "qwertyuiop" 组成。
    • +
    • 第二行由字符 "asdfghjkl" 组成。
    • +
    • 第三行由字符 "zxcvbnm" 组成。
    • +
    + +

    American keyboard

    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["Hello","Alaska","Dad","Peace"]
    +输出:["Alaska","Dad"]
    +
    + +

    示例 2:

    + +
    +输入:words = ["omk"]
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:words = ["adsdf","sfd"]
    +输出:["adsdf","sfd"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 20
    • +
    • 1 <= words[i].length <= 100
    • +
    • words[i] 由英文字母(小写和大写字母)组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +用三个集合存储键盘每一行字母。 + +遍历单词列表 `words`,判断每个单词 `word` 转 set 后是否被以上三个集合其中之一包含,若是,将单词添加到结果数组。 + +```python +class Solution: + def findWords(self, words: List[str]) -> List[str]: + s1 = set('qwertyuiop') + s2 = set('asdfghjkl') + s3 = set('zxcvbnm') + res = [] + for word in words: + t = set(word.lower()) + if t <= s1 or t <= s2 or t <= s3: + # 利用 python set 比较 + res.append(word) + return res +``` + +### **Java** + + + +用三个字符串存储键盘每一行字母。 + +遍历单词列表 `words`,对于每个单词 `word`: + +1. 分别设置三个计数器,存储当前单词在对应键盘字符串的字母个数; +2. 遍历 `word` 中的每个字母,如果在对应的键盘字符串中,则对应的计数器加 1; +3. 单词遍历结束后,判断是否存在一个计数器值与 `word` 长度相同。如果有,说明该单词所有字母都在同一个键盘字符串中,将单词添加到结果数组。 + +```java +class Solution { + public String[] findWords(String[] words) { + String s1 = "qwertyuiopQWERTYUIOP"; + String s2 = "asdfghjklASDFGHJKL"; + String s3 = "zxcvbnmZXCVBNM"; + List res = new ArrayList<>(); + for (String word : words) { + int n1 = 0, n2 = 0, n3 = 0; + int n = word.length(); + for (int i = 0; i < n; ++i) { + if (s1.contains(String.valueOf(word.charAt(i)))) { + ++n1; + } else if (s2.contains(String.valueOf(word.charAt(i)))) { + ++n2; + } else { + ++n3; + } + } + if (n1 == n || n2 == n || n3 == n) { + res.add(word); + } + } + return res.toArray(new String[0]); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0501.leetcode501 Find Mode in Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0501.leetcode501 Find Mode in Binary Search Tree-zh.md" new file mode 100644 index 00000000..a9481ab2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0501.leetcode501 Find Mode in Binary Search Tree-zh.md" @@ -0,0 +1,64 @@ +# [501. 二叉搜索树中的众数](https://leetcode-cn.com/problems/find-mode-in-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0501.Find%20Mode%20in%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

    + +

    假定 BST 有如下定义:

    + +
      +
    • 结点左子树中所含结点的值小于等于当前结点的值
    • +
    • 结点右子树中所含结点的值大于等于当前结点的值
    • +
    • 左子树和右子树都是二叉搜索树
    • +
    + +

    例如:
    +给定 BST [1,null,2,2],

    + +
       1
    +    \
    +     2
    +    /
    +   2
    +
    + +

    返回[2].

    + +

    提示:如果众数超过1个,不需考虑输出顺序

    + +

    进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0502.leetcode502 IPO-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0502.leetcode502 IPO-zh.md" new file mode 100644 index 00000000..5e377774 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0502.leetcode502 IPO-zh.md" @@ -0,0 +1,69 @@ +# [502. IPO](https://leetcode-cn.com/problems/ipo) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0502.IPO/README_EN.md) + +## 题目描述 + + + +

    假设 力扣(LeetCode)即将开始其 IPO。为了以更高的价格将股票卖给风险投资公司,力扣 希望在 IPO 之前开展一些项目以增加其资本。 由于资源有限,它只能在 IPO 之前完成最多 k 个不同的项目。帮助 力扣 设计完成最多 k 个不同项目后得到最大总资本的方式。

    + +

    给定若干个项目。对于每个项目 i,它都有一个纯利润 Pi,并且需要最小的资本 Ci 来启动相应的项目。最初,你有 W 资本。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。

    + +

    总而言之,从给定项目中选择最多 k 个不同项目的列表,以最大化最终资本,并输出最终可获得的最多资本。

    + +

     

    + +

    示例:

    + +
    +输入:k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].
    +输出:4
    +解释:
    +由于你的初始资本为 0,你仅可以从 0 号项目开始。
    +在完成后,你将获得 1 的利润,你的总资本将变为 1。
    +此时你可以选择开始 1 号或 2 号项目。
    +由于你最多可以选择两个项目,所以你需要完成 2 号项目以获得最大的资本。
    +因此,输出最后最大化的资本,为 0 + 1 + 3 = 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 假设所有输入数字都是非负整数。
    • +
    • 表示利润和资本的数组的长度不超过 50000。
    • +
    • 答案保证在 32 位有符号整数范围内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0503.leetcode503 Next Greater Element II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0503.leetcode503 Next Greater Element II-zh.md" new file mode 100644 index 00000000..faa5f3f0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0503.leetcode503 Next Greater Element II-zh.md" @@ -0,0 +1,98 @@ +# [503. 下一个更大元素 II](https://leetcode-cn.com/problems/next-greater-element-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0503.Next%20Greater%20Element%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。

    + +

    示例 1:

    + +
    +输入: [1,2,1]
    +输出: [2,-1,2]
    +解释: 第一个 1 的下一个更大的数是 2;
    +数字 2 找不到下一个更大的数; 
    +第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
    +
    + +

    注意: 输入数组的长度不会超过 10000。

    + +## 解法 + + + +“单调栈 + 循环数组”实现。 + + + +### **Python3** + + + +```python +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + stack = [] + n = len(nums) + res = [-1] * n + for i in range(n << 1): + while stack and nums[stack[-1]] < nums[i % n]: + res[stack.pop()] = nums[i % n] + stack.append(i % n) + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] nextGreaterElements(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + Arrays.fill(res, -1); + Deque stack = new ArrayDeque<>(); + for (int i = 0; i < (n << 1); ++i) { + while (!stack.isEmpty() && nums[stack.peek()] < nums[i % n]) { + res[stack.pop()] = nums[i % n]; + } + stack.push(i % n); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ + var nextGreaterElements = function(nums) { + let n = nums.length; + let stack = []; + let res = new Array(n).fill(-1); + for (let i = 0; i < 2 * n; i++) { + let cur = nums[i % n]; + while (stack.length > 0 && nums[stack[stack.length - 1]] < cur) { + res[stack.pop()] = cur; + } + stack.push(i % n); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0504.leetcode504 Base 7-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0504.leetcode504 Base 7-zh.md" new file mode 100644 index 00000000..769cae43 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0504.leetcode504 Base 7-zh.md" @@ -0,0 +1,56 @@ +# [504. 七进制数](https://leetcode-cn.com/problems/base-7) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0504.Base%207/README_EN.md) + +## 题目描述 + + + +

    给定一个整数,将其转化为7进制,并以字符串形式输出。

    + +

    示例 1:

    + +
    +输入: 100
    +输出: "202"
    +
    + +

    示例 2:

    + +
    +输入: -7
    +输出: "-10"
    +
    + +

    注意: 输入范围是 [-1e7, 1e7] 。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0505.leetcode505 The Maze II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0505.leetcode505 The Maze II-zh.md" new file mode 100644 index 00000000..7af9ce54 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0505.leetcode505 The Maze II-zh.md" @@ -0,0 +1,96 @@ +# [505. 迷宫 II](https://leetcode-cn.com/problems/the-maze-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0505.The%20Maze%20II/README_EN.md) + +## 题目描述 + + + +

    由空地和墙组成的迷宫中有一个。球可以向上下左右四个方向滚动,但在遇到墙壁前不会停止滚动。当球停下时,可以选择下一个方向。

    + +

    给定球的起始位置,目的地迷宫,找出让球停在目的地的最短距离。距离的定义是球从起始位置(不包括)到目的地(包括)经过的空地个数。如果球无法停在目的地,返回 -1。

    + +

    迷宫由一个0和1的二维数组表示。 1表示墙壁,0表示空地。你可以假定迷宫的边缘都是墙壁。起始位置和目的地的坐标通过行号和列号给出。

    + +

     

    + +

    示例 1:

    + +
    输入 1: 迷宫由以下二维数组表示
    +
    +0 0 1 0 0
    +0 0 0 0 0
    +0 0 0 1 0
    +1 1 0 1 1
    +0 0 0 0 0
    +
    +输入 2: 起始位置坐标 (rowStart, colStart) = (0, 4)
    +输入 3: 目的地坐标 (rowDest, colDest) = (4, 4)
    +
    +输出: 12
    +
    +解析: 一条最短路径 : left -> down -> left -> down -> right -> down -> right。
    +             总距离为 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12。
    +
    +
    + +

    示例 2:

    + +
    输入 1: 迷宫由以下二维数组表示
    +
    +0 0 1 0 0
    +0 0 0 0 0
    +0 0 0 1 0
    +1 1 0 1 1
    +0 0 0 0 0
    +
    +输入 2: 起始位置坐标 (rowStart, colStart) = (0, 4)
    +输入 3: 目的地坐标 (rowDest, colDest) = (3, 2)
    +
    +输出: -1
    +
    +解析: 没有能够使球停在目的地的路径。
    +
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 迷宫中只有一个球和一个目的地。
    2. +
    3. 球和目的地都在空地上,且初始时它们不在同一位置。
    4. +
    5. 给定的迷宫不包括边界 (如图中的红色矩形), 但你可以假设迷宫的边缘都是墙壁。
    6. +
    7. 迷宫至少包括2块空地,行数和列数均不超过100。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0506.leetcode506 Relative Ranks-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0506.leetcode506 Relative Ranks-zh.md" new file mode 100644 index 00000000..a914371d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0506.leetcode506 Relative Ranks-zh.md" @@ -0,0 +1,57 @@ +# [506. 相对名次](https://leetcode-cn.com/problems/relative-ranks) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0506.Relative%20Ranks/README_EN.md) + +## 题目描述 + + + +

    给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”("Gold Medal", "Silver Medal", "Bronze Medal")。

    + +

    (注:分数越高的选手,排名越靠前。)

    + +

    示例 1:

    + +
    +输入: [5, 4, 3, 2, 1]
    +输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
    +解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
    +余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
    + +

    提示:

    + +
      +
    1. N 是一个正整数并且不会超过 10000。
    2. +
    3. 所有运动员的成绩都不相同。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0507.leetcode507 Perfect Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0507.leetcode507 Perfect Number-zh.md" new file mode 100644 index 00000000..dd184b1e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0507.leetcode507 Perfect Number-zh.md" @@ -0,0 +1,83 @@ +# [507. 完美数](https://leetcode-cn.com/problems/perfect-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0507.Perfect%20Number/README_EN.md) + +## 题目描述 + + + +

    对于一个 正整数,如果它和除了它自身以外的所有 正因子 之和相等,我们称它为 「完美数」。

    + +

    给定一个 整数 n, 如果是完美数,返回 true,否则返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:28
    +输出:True
    +解释:28 = 1 + 2 + 4 + 7 + 14
    +1, 2, 4, 7, 和 14 是 28 的所有正因子。
    + +

    示例 2:

    + +
    输入:num = 6
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:num = 496
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:num = 8128
    +输出:true
    +
    + +

    示例 5:

    + +
    输入:num = 2
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num <= 108
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0508.leetcode508 Most Frequent Subtree Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0508.leetcode508 Most Frequent Subtree Sum-zh.md" new file mode 100644 index 00000000..db2e609f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0508.leetcode508 Most Frequent Subtree Sum-zh.md" @@ -0,0 +1,68 @@ +# [508. 出现次数最多的子树元素和](https://leetcode-cn.com/problems/most-frequent-subtree-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0508.Most%20Frequent%20Subtree%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个二叉树的根结点,请你找出出现次数最多的子树元素和。一个结点的「子树元素和」定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。

    + +

    你需要返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)。

    + +

     

    + +

    示例 1:
    +输入:

    + +
      5
    + /  \
    +2   -3
    +
    + +

    返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。

    + +

    示例 2:
    +输入:

    + +
      5
    + /  \
    +2   -5
    +
    + +

    返回 [2],只有 2 出现两次,-5 只出现 1 次。

    + +

     

    + +

    提示: 假设任意子树元素和均可以用 32 位有符号整数表示。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0509.leetcode509 Fibonacci Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0509.leetcode509 Fibonacci Number-zh.md" new file mode 100644 index 00000000..778b7066 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0509.leetcode509 Fibonacci Number-zh.md" @@ -0,0 +1,145 @@ +# [509. 斐波那契数](https://leetcode-cn.com/problems/fibonacci-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0509.Fibonacci%20Number/README_EN.md) + +## 题目描述 + + + +

    斐波那契数,通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 01 开始,后面的每一项数字都是前面两项数字的和。也就是:

    + +
    +F(0) = 0,F(1) = 1
    +F(n) = F(n - 1) + F(n - 2),其中 n > 1
    +
    + +

    给你 n ,请计算 F(n)

    + +

     

    + +

    示例 1:

    + +
    +输入:2
    +输出:1
    +解释:F(2) = F(1) + F(0) = 1 + 0 = 1
    +
    + +

    示例 2:

    + +
    +输入:3
    +输出:2
    +解释:F(3) = F(2) + F(1) = 1 + 1 = 2
    +
    + +

    示例 3:

    + +
    +输入:4
    +输出:3
    +解释:F(4) = F(3) + F(2) = 2 + 1 = 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 30
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def fib(self, n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return a +``` + +### **Java** + + + +```java +class Solution { + public int fib(int n) { + int a = 0, b = 1; + while (n-- > 0) { + int c = a + b; + a = b; + b = c; + } + return a; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int fib(int n) { + int a = 0, b = 1; + while (n--) { + int c = a + b; + a = b; + b = c; + } + return a; + } +}; +``` + +### **Go** + +```go +func fib(n int) int { + a, b := 0, 1 + for i := 0; i < n; i++ { + a, b = b, a+b + } + return a +} +``` + +### **JavaScript** + + +```js +/** + * @param {number} n + * @return {number} + */ +var fib = function(n) { + let a = 0; + let b = 1; + while (n--) { + const c = a + b; + a = b; + b = c; + } + return a; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0510.leetcode510 Inorder Successor in BST II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0510.leetcode510 Inorder Successor in BST II-zh.md" new file mode 100644 index 00000000..71a1567f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0510.leetcode510 Inorder Successor in BST II-zh.md" @@ -0,0 +1,113 @@ +# [510. 二叉搜索树中的中序后继 II](https://leetcode-cn.com/problems/inorder-successor-in-bst-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0510.Inorder%20Successor%20in%20BST%20II/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉搜索树和其中的一个节点 node ,找到该节点在树中的中序后继。如果节点没有中序后继,请返回 null

    + +

    一个节点 node 的中序后继是键值比 node.val 大所有的节点中键值最小的那个。

    + +

    你可以直接访问结点,但无法直接访问树。每个节点都会有其父节点的引用。节点 Node 定义如下:

    + +
    +class Node {
    +    public int val;
    +    public Node left;
    +    public Node right;
    +    public Node parent;
    +}
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:tree = [2,1,3], node = 1
    +输出:2
    +解析:1 的中序后继结点是 2 。注意节点和返回值都是 Node 类型的。
    +
    + +

    示例 2:

    + +

    + +
    +输入:tree = [5,3,6,2,4,null,null,1], node = 6
    +输出:null
    +解析:该结点没有中序后继,因此返回 null 。
    +
    + +

    示例 3:

    + +

    + +
    +输入:tree = [15,6,18,3,7,17,20,2,4,null,13,null,null,null,null,null,null,null,null,9], node = 15
    +输出:17
    +
    + +

    示例 4:

    + +

    + +
    +输入:tree = [15,6,18,3,7,17,20,2,4,null,13,null,null,null,null,null,null,null,null,9], node = 13
    +输出:15
    +
    + +

    示例 5:

    + +
    +输入:tree = [0], node = 0
    +输出:null
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在范围 [1, 104] 内。
    • +
    • -105 <= Node.val <= 105
    • +
    • 树中各结点的值均保证唯一。
    • +
    + +

     

    + +

    进阶:你能否在不访问任何结点的值的情况下解决问题?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0511.leetcode511 Game Play Analysis I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0511.leetcode511 Game Play Analysis I-zh.md" new file mode 100644 index 00000000..ea693564 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0511.leetcode511 Game Play Analysis I-zh.md" @@ -0,0 +1,66 @@ +# [511. 游戏玩法分析 I](https://leetcode-cn.com/problems/game-play-analysis-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0511.Game%20Play%20Analysis%20I/README_EN.md) + +## 题目描述 + + + +

    活动表 Activity

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| player_id    | int     |
    +| device_id    | int     |
    +| event_date   | date    |
    +| games_played | int     |
    ++--------------+---------+
    +表的主键是 (player_id, event_date)。
    +这张表展示了一些游戏玩家在游戏平台上的行为活动。
    +每行数据记录了一名玩家在退出平台之前,当天使用同一台设备登录平台后打开的游戏的数目(可能是 0 个)。
    +
    + +

     

    + +

    写一条 SQL 查询语句获取每位玩家 第一次登陆平台的日期

    + +

    查询结果的格式如下所示:

    + +
    +Activity 表:
    ++-----------+-----------+------------+--------------+
    +| player_id | device_id | event_date | games_played |
    ++-----------+-----------+------------+--------------+
    +| 1         | 2         | 2016-03-01 | 5            |
    +| 1         | 2         | 2016-05-02 | 6            |
    +| 2         | 3         | 2017-06-25 | 1            |
    +| 3         | 1         | 2016-03-02 | 0            |
    +| 3         | 4         | 2018-07-03 | 5            |
    ++-----------+-----------+------------+--------------+
    +
    +Result 表:
    ++-----------+-------------+
    +| player_id | first_login |
    ++-----------+-------------+
    +| 1         | 2016-03-01  |
    +| 2         | 2017-06-25  |
    +| 3         | 2016-03-02  |
    ++-----------+-------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0512.leetcode512 Game Play Analysis II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0512.leetcode512 Game Play Analysis II-zh.md" new file mode 100644 index 00000000..23cc6d79 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0512.leetcode512 Game Play Analysis II-zh.md" @@ -0,0 +1,63 @@ +# [512. 游戏玩法分析 II](https://leetcode-cn.com/problems/game-play-analysis-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0512.Game%20Play%20Analysis%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Activity

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| player_id    | int     |
    +| device_id    | int     |
    +| event_date   | date    |
    +| games_played | int     |
    ++--------------+---------+
    +(player_id, event_date) 是这个表的两个主键
    +这个表显示的是某些游戏玩家的游戏活动情况
    +每一行是在某天使用某个设备登出之前登录并玩多个游戏(可能为0)的玩家的记录
    +
    + +

    请编写一个 SQL 查询,描述每一个玩家首次登陆的设备名称

    + +

    查询结果格式在以下示例中:

    + +
    +Activity table:
    ++-----------+-----------+------------+--------------+
    +| player_id | device_id | event_date | games_played |
    ++-----------+-----------+------------+--------------+
    +| 1         | 2         | 2016-03-01 | 5            |
    +| 1         | 2         | 2016-05-02 | 6            |
    +| 2         | 3         | 2017-06-25 | 1            |
    +| 3         | 1         | 2016-03-02 | 0            |
    +| 3         | 4         | 2018-07-03 | 5            |
    ++-----------+-----------+------------+--------------+
    +
    +Result table:
    ++-----------+-----------+
    +| player_id | device_id |
    ++-----------+-----------+
    +| 1         | 2         |
    +| 2         | 3         |
    +| 3         | 1         |
    ++-----------+-----------+
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0513.leetcode513 Find Bottom Left Tree Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0513.leetcode513 Find Bottom Left Tree Value-zh.md" new file mode 100644 index 00000000..b9ea2ab2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0513.leetcode513 Find Bottom Left Tree Value-zh.md" @@ -0,0 +1,130 @@ +# [513. 找树左下角的值](https://leetcode-cn.com/problems/find-bottom-left-tree-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0513.Find%20Bottom%20Left%20Tree%20Value/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,在树的最后一行找到最左边的值。

    + +

    示例 1:

    + +
    +输入:
    +
    +    2
    +   / \
    +  1   3
    +
    +输出:
    +1
    +
    + +

     

    + +

    示例 2:

    + +
    +输入:
    +
    +        1
    +       / \
    +      2   3
    +     /   / \
    +    4   5   6
    +       /
    +      7
    +
    +输出:
    +7
    +
    + +

     

    + +

    注意: 您可以假设树(即给定的根节点)不为 NULL

    + +## 解法 + + + +“BFS 层次遍历”实现。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findBottomLeftValue(self, root: TreeNode) -> int: + res = 0 + q = collections.deque([root]) + while q: + res = q[0].val + n = len(q) + for _ in range(n): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int findBottomLeftValue(TreeNode root) { + Deque q = new ArrayDeque<>(); + q.offer(root); + int res = 0; + while (!q.isEmpty()) { + res = q.peek().val; + for (int i = 0, n = q.size(); i < n; ++i) { + TreeNode node = q.poll(); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0514.leetcode514 Freedom Trail-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0514.leetcode514 Freedom Trail-zh.md" new file mode 100644 index 00000000..ae712f95 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0514.leetcode514 Freedom Trail-zh.md" @@ -0,0 +1,76 @@ +# [514. 自由之路](https://leetcode-cn.com/problems/freedom-trail) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0514.Freedom%20Trail/README_EN.md) + +## 题目描述 + + + +

    电子游戏“辐射4”中,任务“通向自由”要求玩家到达名为“Freedom Trail Ring”的金属表盘,并使用表盘拼写特定关键词才能开门。

    + +

    给定一个字符串 ring,表示刻在外环上的编码;给定另一个字符串 key,表示需要拼写的关键词。您需要算出能够拼写关键词中所有字符的最少步数。

    + +

    最初,ring 的第一个字符与12:00方向对齐。您需要顺时针或逆时针旋转 ring 以使 key 的一个字符在 12:00 方向对齐,然后按下中心按钮,以此逐个拼写完 key 中的所有字符。

    + +

    旋转 ring 拼出 key 字符 key[i] 的阶段中:

    + +
      +
    1. 您可以将 ring 顺时针或逆时针旋转一个位置,计为1步。旋转的最终目的是将字符串 ring 的一个字符与 12:00 方向对齐,并且这个字符必须等于字符 key[i] 。
    2. +
    3. 如果字符 key[i] 已经对齐到12:00方向,您需要按下中心按钮进行拼写,这也将算作 1 步。按完之后,您可以开始拼写 key 的下一个字符(下一阶段), 直至完成所有拼写。
    4. +
    + +

    示例:

    + +

     

    + +
    +  + +
    +输入: ring = "godding", key = "gd"
    +输出: 4
    +解释:
    + 对于 key 的第一个字符 'g',已经在正确的位置, 我们只需要1步来拼写这个字符。 
    + 对于 key 的第二个字符 'd',我们需要逆时针旋转 ring "godding" 2步使它变成 "ddinggo"。
    + 当然, 我们还需要1步进行拼写。
    + 因此最终的输出是 4。
    +
    + +

    提示:

    + +
      +
    1. ring 和 key 的字符串长度取值范围均为 1 至 100;
    2. +
    3. 两个字符串中都只有小写字符,并且均可能存在重复字符;
    4. +
    5. 字符串 key 一定可以由字符串 ring 旋转拼出。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0515.leetcode515 Find Largest Value in Each Tree Row-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0515.leetcode515 Find Largest Value in Each Tree Row-zh.md" new file mode 100644 index 00000000..940b5c85 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0515.leetcode515 Find Largest Value in Each Tree Row-zh.md" @@ -0,0 +1,117 @@ +# [515. 在每个树行中找最大值](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0515.Find%20Largest%20Value%20in%20Each%20Tree%20Row/README_EN.md) + +## 题目描述 + + + +

    您需要在二叉树的每一行中找到最大的值。

    + +

    示例:

    + +
    +输入: 
    +
    +          1
    +         / \
    +        3   2
    +       / \   \  
    +      5   3   9 
    +
    +输出: [1, 3, 9]
    +
    + +## 解法 + + + +“BFS 层次遍历”实现。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: TreeNode) -> List[int]: + if root is None: + return [] + q = collections.deque([root]) + res = [] + while q: + n = len(q) + t = float('-inf') + for _ in range(n): + node = q.popleft() + t = max(t, node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + res.append(t) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List largestValues(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + Deque q = new ArrayDeque<>(); + q.offer(root); + List res = new ArrayList<>(); + while (!q.isEmpty()) { + int t = Integer.MIN_VALUE; + for (int i = 0, n = q.size(); i < n; ++i) { + TreeNode node = q.poll(); + t = Math.max(t, node.val); + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + res.add(t); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0516.leetcode516 Longest Palindromic Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0516.leetcode516 Longest Palindromic Subsequence-zh.md" new file mode 100644 index 00000000..0a324859 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0516.leetcode516 Longest Palindromic Subsequence-zh.md" @@ -0,0 +1,77 @@ +# [516. 最长回文子序列](https://leetcode-cn.com/problems/longest-palindromic-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0516.Longest%20Palindromic%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s ,找到其中最长的回文子序列,并返回该序列的长度。可以假设 s 的最大长度为 1000

    + +

     

    + +

    示例 1:
    +输入:

    + +
    "bbbab"
    +
    + +

    输出:

    + +
    4
    +
    + +

    一个可能的最长回文子序列为 "bbbb"。

    + +

    示例 2:
    +输入:

    + +
    "cbbd"
    +
    + +

    输出:

    + +
    2
    +
    + +

    一个可能的最长回文子序列为 "bb"。

    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 只包含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0517.leetcode517 Super Washing Machines-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0517.leetcode517 Super Washing Machines-zh.md" new file mode 100644 index 00000000..86dea3b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0517.leetcode517 Super Washing Machines-zh.md" @@ -0,0 +1,90 @@ +# [517. 超级洗衣机](https://leetcode-cn.com/problems/super-washing-machines) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0517.Super%20Washing%20Machines/README_EN.md) + +## 题目描述 + + + +

    假设有 台超级洗衣机放在同一排上。开始的时候,每台洗衣机内可能有一定量的衣服,也可能是空的。

    + +

    每一步操作中,你可以选择任意 m (1 ≤ m ≤ n) 台洗衣机,与此同时将每台洗衣机的一件衣服送到相邻的一台洗衣机。

    + +

    给定一个非负整数数组代表从左至右每台洗衣机中的衣物数量,请给出能让所有洗衣机中剩下的衣物的数量相等的最少的操作步数。如果不能使每台洗衣机中衣物的数量相等,则返回 -1。

    + +

     

    + +

    示例 1:

    + +
    输入: [1,0,5]
    +
    +输出: 3
    +
    +解释: 
    +第一步:    1     0 <-- 5    =>    1     1     4
    +第二步:    1 <-- 1 <-- 4    =>    2     1     3    
    +第三步:    2     1 <-- 3    =>    2     2     2   
    +
    + +

    示例 2:

    + +
    输入: [0,3,0]
    +
    +输出: 2
    +
    +解释: 
    +第一步:    0 <-- 3     0    =>    1     2     0    
    +第二步:    1     2 --> 0    =>    1     1     1     
    +
    + +

    示例 3:

    + +
    输入: [0,2,0]
    +
    +输出: -1
    +
    +解释: 
    +不可能让所有三个洗衣机同时剩下相同数量的衣物。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. n 的范围是 [1, 10000]。
    2. +
    3. 在每台超级洗衣机中,衣物数量的范围是 [0, 1e5]。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0518.leetcode518 Coin Change 2-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0518.leetcode518 Coin Change 2-zh.md" new file mode 100644 index 00000000..091bd8c8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0518.leetcode518 Coin Change 2-zh.md" @@ -0,0 +1,132 @@ +# [518. 零钱兑换 II](https://leetcode-cn.com/problems/coin-change-2) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0518.Coin%20Change%202/README_EN.md) + +## 题目描述 + + + +

    给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。 

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入: amount = 5, coins = [1, 2, 5]
    +输出: 4
    +解释: 有四种方式可以凑成总金额:
    +5=5
    +5=2+2+1
    +5=2+1+1+1
    +5=1+1+1+1+1
    +
    + +

    示例 2:

    + +
    输入: amount = 3, coins = [2]
    +输出: 0
    +解释: 只用面额2的硬币不能凑成总金额3。
    +
    + +

    示例 3:

    + +
    输入: amount = 10, coins = [10]
    +输出: 1
    +
    + +

     

    + +

    注意:

    + +

    你可以假设:

    + +
      +
    • 0 <= amount (总金额) <= 5000
    • +
    • 1 <= coin (硬币面额) <= 5000
    • +
    • 硬币种类不超过 500 种
    • +
    • 结果符合 32 位符号整数
    • +
    + + +## 解法 + + + +完全背包问题 + + + +### **Python3** + + + +```python +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + dp = [0 for i in range(amount + 1)] + dp[0] = 1 + for coin in coins: + for j in range(coin, amount + 1): + dp[j] += dp[j - coin] + return dp[amount] +``` + +### **Java** + + + +```java +class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; + for (int coin : coins) { + for (int j = coin; j <= amount; j++) { + dp[j] += dp[j - coin]; + } + } + return dp[amount]; + } +} +``` + +### **TypeScript** + +```ts +function change(amount: number, coins: number[]): number { + let dp = new Array(amount + 1).fill(0); + dp[0] = 1; + for (let coin of coins) { + for (let i = coin; i <= amount; ++i) { + dp[i] += dp[i - coin]; + } + } + return dp.pop(); +}; +``` + +### **Go** + +```go +func change(amount int, coins []int) int { + dp := make([]int, amount+1) + dp[0] = 1 + for _, coin := range coins { + for j := coin; j <= amount; j++ { + dp[j] += dp[j-coin] + } + } + return dp[amount] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0519.leetcode519 Random Flip Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0519.leetcode519 Random Flip Matrix-zh.md" new file mode 100644 index 00000000..b397e1b4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0519.leetcode519 Random Flip Matrix-zh.md" @@ -0,0 +1,68 @@ +# [519. 随机翻转矩阵](https://leetcode-cn.com/problems/random-flip-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0519.Random%20Flip%20Matrix/README_EN.md) + +## 题目描述 + + + +

    题中给出一个 n_rowsn_cols 列的二维矩阵,且所有值被初始化为 0。要求编写一个 flip 函数,均匀随机的将矩阵中的 0 变为 1,并返回该值的位置下标 [row_id,col_id];同样编写一个 reset 函数,将所有的值都重新置为 0。尽量最少调用随机函数 Math.random(),并且优化时间和空间复杂度。

    + +

    注意:

    + +
      +
    1. 1 <= n_rows, n_cols <= 10000
    2. +
    3. 0 <= row.id < n_rows 并且 0 <= col.id < n_cols
    4. +
    5. 当矩阵中没有值为 0 时,不可以调用 flip 函数
    6. +
    7. 调用 flip 和 reset 函数的次数加起来不会超过 1000 次
    8. +
    + +

    示例 1:

    + +
    输入: 
    +["Solution","flip","flip","flip","flip"]
    +[[2,3],[],[],[],[]]
    +输出: [null,[0,1],[1,2],[1,0],[1,1]]
    +
    + +

    示例 2:

    + +
    输入: 
    +["Solution","flip","flip","reset","flip"]
    +[[1,2],[],[],[],[]]
    +输出: [null,[0,0],[0,1],null,[0,0]]
    + +

    输入语法解释:

    + +

    输入包含两个列表:被调用的子程序和他们的参数。Solution 的构造函数有两个参数,分别为 n_rowsn_colsflip 和 reset 没有参数,参数总会以列表形式给出,哪怕该列表为空

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0520.leetcode520 Detect Capital-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0520.leetcode520 Detect Capital-zh.md" new file mode 100644 index 00000000..aaf10668 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0520.leetcode520 Detect Capital-zh.md" @@ -0,0 +1,66 @@ +# [520. 检测大写字母](https://leetcode-cn.com/problems/detect-capital) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0520.Detect%20Capital/README_EN.md) + +## 题目描述 + + + +

    给定一个单词,你需要判断单词的大写使用是否正确。

    + +

    我们定义,在以下情况时,单词的大写用法是正确的:

    + +
      +
    1. 全部字母都是大写,比如"USA"。
    2. +
    3. 单词中所有字母都不是大写,比如"leetcode"。
    4. +
    5. 如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。
    6. +
    + +

    否则,我们定义这个单词没有正确使用大写字母。

    + +

    示例 1:

    + +
    +输入: "USA"
    +输出: True
    +
    + +

    示例 2:

    + +
    +输入: "FlaG"
    +输出: False
    +
    + +

    注意: 输入是由大写和小写拉丁字母组成的非空单词。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0521.leetcode521 Longest Uncommon Subsequence I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0521.leetcode521 Longest Uncommon Subsequence I-zh.md" new file mode 100644 index 00000000..b56a2a59 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0521.leetcode521 Longest Uncommon Subsequence I-zh.md" @@ -0,0 +1,75 @@ +# [521. 最长特殊序列 Ⅰ](https://leetcode-cn.com/problems/longest-uncommon-subsequence-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0521.Longest%20Uncommon%20Subsequence%20I/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串,请你从这两个字符串中找出最长的特殊序列。

    + +

    「最长特殊序列」定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。

    + +

    子序列 可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。

    + +

    输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。

    + +

     

    + +

    示例 1:

    + +
    输入: "aba", "cdc"
    +输出: 3
    +解释: 最长特殊序列可为 "aba" (或 "cdc"),两者均为自身的子序列且不是对方的子序列。
    + +

    示例 2:

    + +
    输入:a = "aaa", b = "bbb"
    +输出:3
    +
    + +

    示例 3:

    + +
    输入:a = "aaa", b = "aaa"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 两个字符串长度均处于区间 [1 - 100]
    2. +
    3. 字符串中的字符仅含有 'a'~'z'
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0522.leetcode522 Longest Uncommon Subsequence II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0522.leetcode522 Longest Uncommon Subsequence II-zh.md" new file mode 100644 index 00000000..71cac1b3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0522.leetcode522 Longest Uncommon Subsequence II-zh.md" @@ -0,0 +1,63 @@ +# [522. 最长特殊序列 II](https://leetcode-cn.com/problems/longest-uncommon-subsequence-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0522.Longest%20Uncommon%20Subsequence%20II/README_EN.md) + +## 题目描述 + + + +

    给定字符串列表,你需要从它们中找出最长的特殊序列。最长特殊序列定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。

    + +

    子序列可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。

    + +

    输入将是一个字符串列表,输出是最长特殊序列的长度。如果最长特殊序列不存在,返回 -1 。

    + +

     

    + +

    示例:

    + +
    输入: "aba", "cdc", "eae"
    +输出: 3
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 所有给定的字符串长度不会超过 10 。
    2. +
    3. 给定字符串列表的长度将在 [2, 50 ] 之间。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0523.leetcode523 Continuous Subarray Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0523.leetcode523 Continuous Subarray Sum-zh.md" new file mode 100644 index 00000000..de3fda40 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0523.leetcode523 Continuous Subarray Sum-zh.md" @@ -0,0 +1,67 @@ +# [523. 连续的子数组和](https://leetcode-cn.com/problems/continuous-subarray-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0523.Continuous%20Subarray%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个包含 非负数 的数组和一个目标 整数 k ,编写一个函数来判断该数组是否含有连续的子数组,其大小至少为 2,且总和为 k 的倍数,即总和为 n * k ,其中 n 也是一个整数

    + +

     

    + +

    示例 1:

    + +
    +输入:[23,2,4,6,7], k = 6
    +输出:True
    +解释:[2,4] 是一个大小为 2 的子数组,并且和为 6。
    +
    + +

    示例 2:

    + +
    +输入:[23,2,6,4,7], k = 6
    +输出:True
    +解释:[23,2,6,4,7]是大小为 5 的子数组,并且和为 42。
    +
    + +

     

    + +

    说明:

    + +
      +
    • 数组的长度不会超过 10,000
    • +
    • 你可以认为所有数字总和在 32 位有符号整数范围内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0524.leetcode524 Longest Word in Dictionary through Deleting-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0524.leetcode524 Longest Word in Dictionary through Deleting-zh.md" new file mode 100644 index 00000000..25d3031f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0524.leetcode524 Longest Word in Dictionary through Deleting-zh.md" @@ -0,0 +1,68 @@ +# [524. 通过删除字母匹配到字典里最长单词](https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0524.Longest%20Word%20in%20Dictionary%20through%20Deleting/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。

    + +

    示例 1:

    + +
    +输入:
    +s = "abpcplea", d = ["ale","apple","monkey","plea"]
    +
    +输出: 
    +"apple"
    +
    + +

    示例 2:

    + +
    +输入:
    +s = "abpcplea", d = ["a","b","c"]
    +
    +输出: 
    +"a"
    +
    + +

    说明:

    + +
      +
    1. 所有输入的字符串只包含小写字母。
    2. +
    3. 字典的大小不会超过 1000。
    4. +
    5. 所有输入的字符串长度不会超过 1000。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0525.leetcode525 Contiguous Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0525.leetcode525 Contiguous Array-zh.md" new file mode 100644 index 00000000..f3a8e13d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0525.leetcode525 Contiguous Array-zh.md" @@ -0,0 +1,58 @@ +# [525. 连续数组](https://leetcode-cn.com/problems/contiguous-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0525.Contiguous%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组(的长度)。

    + +

     

    + +

    示例 1:

    + +
    输入: [0,1]
    +输出: 2
    +说明: [0, 1] 是具有相同数量0和1的最长连续子数组。
    + +

    示例 2:

    + +
    输入: [0,1,0]
    +输出: 2
    +说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。
    + +

     

    + +

    注意: 给定的二进制数组的长度不会超过50000。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0526.leetcode526 Beautiful Arrangement-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0526.leetcode526 Beautiful Arrangement-zh.md" new file mode 100644 index 00000000..7974b702 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0526.leetcode526 Beautiful Arrangement-zh.md" @@ -0,0 +1,69 @@ +# [526. 优美的排列](https://leetcode-cn.com/problems/beautiful-arrangement) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0526.Beautiful%20Arrangement/README_EN.md) + +## 题目描述 + + + +

    假设有从 1 到 N 的 个整数,如果从这 个数字中成功构造出一个数组,使得数组的第 i 位 (1 <= i <= N) 满足如下两个条件中的一个,我们就称这个数组为一个优美的排列。条件:

    + +
      +
    1. 第 位的数字能被 整除
    2. +
    3. i 能被第 i 位上的数字整除
    4. +
    + +

    现在给定一个整数 N,请问可以构造多少个优美的排列?

    + +

    示例1:

    + +
    +输入: 2
    +输出: 2
    +解释: 
    +
    +第 1 个优美的排列是 [1, 2]:
    +  第 1 个位置(i=1)上的数字是1,1能被 i(i=1)整除
    +  第 2 个位置(i=2)上的数字是2,2能被 i(i=2)整除
    +
    +第 2 个优美的排列是 [2, 1]:
    +  第 1 个位置(i=1)上的数字是2,2能被 i(i=1)整除
    +  第 2 个位置(i=2)上的数字是1,i(i=2)能被 1 整除
    +
    + +

    说明:

    + +
      +
    1. N 是一个正整数,并且不会超过15。
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0527.leetcode527 Word Abbreviation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0527.leetcode527 Word Abbreviation-zh.md" new file mode 100644 index 00000000..e057a643 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0527.leetcode527 Word Abbreviation-zh.md" @@ -0,0 +1,63 @@ +# [527. 单词缩写](https://leetcode-cn.com/problems/word-abbreviation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0527.Word%20Abbreviation/README_EN.md) + +## 题目描述 + + + +

    给定一个由n个不重复非空字符串组成的数组,你需要按照以下规则为每个单词生成最小的缩写

    + +
      +
    1. 初始缩写由起始字母+省略字母的数量+结尾字母组成。
    2. +
    3. 若存在冲突,亦即多于一个单词有同样的缩写,则使用更长的前缀代替首字母,直到从单词到缩写的映射唯一。换而言之,最终的缩写必须只能映射到一个单词。
    4. +
    5. 若缩写并不比原单词更短,则保留原样。
    6. +
    + +

    示例:

    + +
    输入: ["like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"]
    +输出: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]
    +
    + +

     

    + +

    注意:

    + +
      +
    1. n和每个单词的长度均不超过 400。
    2. +
    3. 每个单词的长度大于 1。
    4. +
    5. 单词只由英文小写字母组成。
    6. +
    7. 返回的答案需要和原数组保持同一顺序。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0528.leetcode528 Random Pick with Weight-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0528.leetcode528 Random Pick with Weight-zh.md" new file mode 100644 index 00000000..e0311e60 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0528.leetcode528 Random Pick with Weight-zh.md" @@ -0,0 +1,95 @@ +# [528. 按权重随机选择](https://leetcode-cn.com/problems/random-pick-with-weight) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0528.Random%20Pick%20with%20Weight/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数数组 w ,其中 w[i] 代表下标 i 的权重(下标从 0 开始),请写一个函数 pickIndex ,它可以随机地获取下标 i,选取下标 i 的概率与 w[i] 成正比。

    + +
      +
    + +

    例如,对于 w = [1, 3],挑选下标 0 的概率为 1 / (1 + 3) = 0.25 (即,25%),而选取下标 1 的概率为 3 / (1 + 3) = 0.75(即,75%)。

    + +

    也就是说,选取下标 i 的概率为 w[i] / sum(w)

    + +

     

    + +

    示例 1:

    + +
    输入:
    +["Solution","pickIndex"]
    +[[[1]],[]]
    +输出:
    +[null,0]
    +解释:
    +Solution solution = new Solution([1]);
    +solution.pickIndex(); // 返回 0,因为数组中只有一个元素,所以唯一的选择是返回下标 0。
    + +

    示例 2:

    + +
    输入:
    +["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
    +[[[1,3]],[],[],[],[],[]]
    +输出:
    +[null,1,1,1,1,0]
    +解释:
    +Solution solution = new Solution([1, 3]);
    +solution.pickIndex(); // 返回 1,返回下标 1,返回该下标概率为 3/4 。
    +solution.pickIndex(); // 返回 1
    +solution.pickIndex(); // 返回 1
    +solution.pickIndex(); // 返回 1
    +solution.pickIndex(); // 返回 0,返回下标 0,返回该下标概率为 1/4 。
    +
    +由于这是一个随机问题,允许多个答案,因此下列输出都可以被认为是正确的:
    +[null,1,1,1,1,0]
    +[null,1,1,1,1,1]
    +[null,1,1,1,0,0]
    +[null,1,1,1,0,1]
    +[null,1,0,1,0,0]
    +......
    +诸若此类。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= w.length <= 10000
    • +
    • 1 <= w[i] <= 10^5
    • +
    • pickIndex 将被调用不超过 10000 次
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0529.leetcode529 Minesweeper-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0529.leetcode529 Minesweeper-zh.md" new file mode 100644 index 00000000..e16c8b2c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0529.leetcode529 Minesweeper-zh.md" @@ -0,0 +1,108 @@ +# [529. 扫雷游戏](https://leetcode-cn.com/problems/minesweeper) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0529.Minesweeper/README_EN.md) + +## 题目描述 + + + +

    让我们一起来玩扫雷游戏!

    + +

    给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。

    + +

    现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:

    + +
      +
    1. 如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'
    2. +
    3. 如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的未挖出方块都应该被递归地揭露。
    4. +
    5. 如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。
    6. +
    7. 如果在此次点击中,若无更多方块可被揭露,则返回面板。
    8. +
    + +

     

    + +

    示例 1:

    + +
    输入: 
    +
    +[['E', 'E', 'E', 'E', 'E'],
    + ['E', 'E', 'M', 'E', 'E'],
    + ['E', 'E', 'E', 'E', 'E'],
    + ['E', 'E', 'E', 'E', 'E']]
    +
    +Click : [3,0]
    +
    +输出: 
    +
    +[['B', '1', 'E', '1', 'B'],
    + ['B', '1', 'M', '1', 'B'],
    + ['B', '1', '1', '1', 'B'],
    + ['B', 'B', 'B', 'B', 'B']]
    +
    +解释:
    +
    +
    + +

    示例 2:

    + +
    输入: 
    +
    +[['B', '1', 'E', '1', 'B'],
    + ['B', '1', 'M', '1', 'B'],
    + ['B', '1', '1', '1', 'B'],
    + ['B', 'B', 'B', 'B', 'B']]
    +
    +Click : [1,2]
    +
    +输出: 
    +
    +[['B', '1', 'E', '1', 'B'],
    + ['B', '1', 'X', '1', 'B'],
    + ['B', '1', '1', '1', 'B'],
    + ['B', 'B', 'B', 'B', 'B']]
    +
    +解释:
    +
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 输入矩阵的宽和高的范围为 [1,50]。
    2. +
    3. 点击的位置只能是未被挖出的方块 ('M' 或者 'E'),这也意味着面板至少包含一个可点击的方块。
    4. +
    5. 输入面板不会是游戏结束的状态(即有地雷已被挖出)。
    6. +
    7. 简单起见,未提及的规则在这个问题中可被忽略。例如,当游戏结束时你不需要挖出所有地雷,考虑所有你可能赢得游戏或标记方块的情况。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0530.leetcode530 Minimum Absolute Difference in BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0530.leetcode530 Minimum Absolute Difference in BST-zh.md" new file mode 100644 index 00000000..077f6091 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0530.leetcode530 Minimum Absolute Difference in BST-zh.md" @@ -0,0 +1,143 @@ +# [530. 二叉搜索树的最小绝对差](https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0530.Minimum%20Absolute%20Difference%20in%20BST/README_EN.md) + +## 题目描述 + + + +

    给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

    + +

     

    + +

    示例:

    + +
    输入:
    +
    +   1
    +    \
    +     3
    +    /
    +   2
    +
    +输出:
    +1
    +
    +解释:
    +最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
    +
    + +

     

    + +

    提示:

    + + + + +## 解法 + + + +中序遍历二叉搜索树,获取当前节点与上个节点的差值的最小值即可。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def getMinimumDifference(self, root: TreeNode) -> int: + def inorder(root): + if not root: + return + inorder(root.left) + if self.pre is not None: + self.min_diff = min(self.min_diff, abs(root.val - self.pre)) + self.pre = root.val + inorder(root.right) + + self.pre = None + self.min_diff = 10 ** 5 + inorder(root) + return self.min_diff +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + + private int minDiff = Integer.MAX_VALUE; + private Integer pre; + + public int getMinimumDifference(TreeNode root) { + inorder(root); + return minDiff; + } + + private void inorder(TreeNode root) { + if (root == null) return; + inorder(root.left); + if (pre != null) minDiff = Math.min(minDiff, Math.abs(root.val - pre)); + pre = root.val; + inorder(root.right); + } +} +``` + +### **Go** + +```go +var res int +var preNode *TreeNode +func getMinimumDifference(root *TreeNode) int { + res = int(^uint(0) >> 1) + preNode = nil + helper(root) + return res +} + +func helper(root *TreeNode) { + if root == nil { + return + } + helper(root.Left) + if preNode != nil { + res = getMinInt(res, root.Val - preNode.Val) + } + preNode = root + helper(root.Right) +} + +func getMinInt(a,b int) int { + if a < b { + return a + } + return b +} +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0531.leetcode531 Lonely Pixel I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0531.leetcode531 Lonely Pixel I-zh.md" new file mode 100644 index 00000000..c3421b92 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0531.leetcode531 Lonely Pixel I-zh.md" @@ -0,0 +1,65 @@ +# [531. 孤独像素 I](https://leetcode-cn.com/problems/lonely-pixel-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0531.Lonely%20Pixel%20I/README_EN.md) + +## 题目描述 + + + +

    给定一幅黑白像素组成的图像, 计算黑色孤独像素的数量。

    + +

    图像由一个由‘B’和‘W’组成二维字符数组表示, ‘B’和‘W’分别代表黑色像素和白色像素。

    + +

    黑色孤独像素指的是在同一行和同一列不存在其他黑色像素的黑色像素。

    + +

    示例:

    + +
    输入: 
    +[['W', 'W', 'B'],
    + ['W', 'B', 'W'],
    + ['B', 'W', 'W']]
    +
    +输出: 3
    +解析: 全部三个'B'都是黑色孤独像素。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 输入二维数组行和列的范围是 [1,500]。
    2. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0532.leetcode532 K-diff Pairs in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0532.leetcode532 K-diff Pairs in an Array-zh.md" new file mode 100644 index 00000000..efe4b5b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0532.leetcode532 K-diff Pairs in an Array-zh.md" @@ -0,0 +1,102 @@ +# [532. 数组中的 k-diff 数对](https://leetcode-cn.com/problems/k-diff-pairs-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0532.K-diff%20Pairs%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组和一个整数 k,你需要在数组里找到不同的 k-diff 数对,并返回不同的 k-diff 数对 的数目。

    + +

    这里将 k-diff 数对定义为一个整数对 (nums[i], nums[j]),并满足下述全部条件:

    + +
      +
    • 0 <= i, j < nums.length
    • +
    • i != j
    • +
    • |nums[i] - nums[j]| == k
    • +
    + +

    注意|val| 表示 val 的绝对值。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3, 1, 4, 1, 5], k = 2
    +输出:2
    +解释:数组中有两个 2-diff 数对, (1, 3) 和 (3, 5)。
    +尽管数组中有两个1,但我们只应返回不同的数对的数量。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1, 2, 3, 4, 5], k = 1
    +输出:4
    +解释:数组中有四个 1-diff 数对, (1, 2), (2, 3), (3, 4) 和 (4, 5)。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1, 3, 1, 5, 4], k = 0
    +输出:1
    +解释:数组中只有一个 0-diff 数对,(1, 1)。
    +
    + +

    示例 4:

    + +
    +输入:nums = [1,2,4,4,3,3,0,9,2,3], k = 3
    +输出:2
    +
    + +

    示例 5:

    + +
    +输入:nums = [-1,-2,-3], k = 1
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -107 <= nums[i] <= 107
    • +
    • 0 <= k <= 107
    • +
    • (nums[i], nums[j])(nums[j], nums[i]) 算同一个数对
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0533.leetcode533 Lonely Pixel II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0533.leetcode533 Lonely Pixel II-zh.md" new file mode 100644 index 00000000..74403c7e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0533.leetcode533 Lonely Pixel II-zh.md" @@ -0,0 +1,81 @@ +# [533. 孤独像素 II](https://leetcode-cn.com/problems/lonely-pixel-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0533.Lonely%20Pixel%20II/README_EN.md) + +## 题目描述 + + + +

    给定一幅由黑色像素和白色像素组成的图像, 与一个正整数N, 找到位于某行 R 和某列 C 中且符合下列规则的黑色像素的数量:

    + +
      +
    1. 行R 和列C都恰好包括N个黑色像素。
    2. +
    3. 列C中所有黑色像素所在的行必须和行R完全相同。
    4. +
    + +

    图像由一个由‘B’和‘W’组成二维字符数组表示, ‘B’和‘W’分别代表黑色像素和白色像素。

    + +

    示例:

    + +
    输入:                                            
    +[['W', 'B', 'W', 'B', 'B', 'W'],    
    + ['W', 'B', 'W', 'B', 'B', 'W'],    
    + ['W', 'B', 'W', 'B', 'B', 'W'],    
    + ['W', 'W', 'B', 'W', 'B', 'W']] 
    +
    +N = 3
    +输出: 6
    +解析: 所有粗体的'B'都是我们所求的像素(第1列和第3列的所有'B').
    +        0    1    2    3    4    5         列号                                          
    +0    [['W', 'B', 'W', 'B', 'B', 'W'],    
    +1     ['W', 'B', 'W', 'B', 'B', 'W'],    
    +2     ['W', 'B', 'W', 'B', 'B', 'W'],    
    +3     ['W', 'W', 'B', 'W', 'B', 'W']]    
    +行号
    +
    +以R = 0行和C = 1列的'B'为例:
    +规则 1,R = 0行和C = 1列都恰好有N = 3个黑色像素. 
    +规则 2,在C = 1列的黑色像素分别位于0,1和2行。它们都和R = 0行完全相同。
    +
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 输入二维数组行和列的范围是 [1,200]。
    2. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0534.leetcode534 Game Play Analysis III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0534.leetcode534 Game Play Analysis III-zh.md" new file mode 100644 index 00000000..a83f1546 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0534.leetcode534 Game Play Analysis III-zh.md" @@ -0,0 +1,71 @@ +# [534. 游戏玩法分析 III](https://leetcode-cn.com/problems/game-play-analysis-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0534.Game%20Play%20Analysis%20III/README_EN.md) + +## 题目描述 + + + +

    Table: Activity

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| player_id    | int     |
    +| device_id    | int     |
    +| event_date   | date    |
    +| games_played | int     |
    ++--------------+---------+
    +(player_id,event_date)是此表的主键。
    +这张表显示了某些游戏的玩家的活动情况。
    +每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0 )。
    +
    + +

     

    + +

    编写一个 SQL 查询,同时报告每组玩家和日期,以及玩家到目前为止玩了多少游戏。也就是说,在此日期之前玩家所玩的游戏总数。详细情况请查看示例。

    + +

    查询结果格式如下所示:

    + +
    +Activity table:
    ++-----------+-----------+------------+--------------+
    +| player_id | device_id | event_date | games_played |
    ++-----------+-----------+------------+--------------+
    +| 1         | 2         | 2016-03-01 | 5            |
    +| 1         | 2         | 2016-05-02 | 6            |
    +| 1         | 3         | 2017-06-25 | 1            |
    +| 3         | 1         | 2016-03-02 | 0            |
    +| 3         | 4         | 2018-07-03 | 5            |
    ++-----------+-----------+------------+--------------+
    +
    +Result table:
    ++-----------+------------+---------------------+
    +| player_id | event_date | games_played_so_far |
    ++-----------+------------+---------------------+
    +| 1         | 2016-03-01 | 5                   |
    +| 1         | 2016-05-02 | 11                  |
    +| 1         | 2017-06-25 | 12                  |
    +| 3         | 2016-03-02 | 0                   |
    +| 3         | 2018-07-03 | 5                   |
    ++-----------+------------+---------------------+
    +对于 ID 为 1 的玩家,2016-05-02 共玩了 5+6=11 个游戏,2017-06-25 共玩了 5+6+1=12 个游戏。
    +对于 ID 为 3 的玩家,2018-07-03 共玩了 0+5=5 个游戏。
    +请注意,对于每个玩家,我们只关心玩家的登录日期。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0535.leetcode535 Encode and Decode TinyURL-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0535.leetcode535 Encode and Decode TinyURL-zh.md" new file mode 100644 index 00000000..736f992e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0535.leetcode535 Encode and Decode TinyURL-zh.md" @@ -0,0 +1,86 @@ +# [535. TinyURL 的加密与解密](https://leetcode-cn.com/problems/encode-and-decode-tinyurl) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0535.Encode%20and%20Decode%20TinyURL/README_EN.md) + +## 题目描述 + + + +

    TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk.

    + +

    要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。

    + +## 解法 + + + +哈希表实现。 + + + +### **Python3** + + + +```python +class Codec: + def __init__(self): + self.code_url = {} + self.count = 0 + self.prefix_url = 'http://tinyurl.com/' + + def encode(self, longUrl: str) -> str: + """Encodes a URL to a shortened URL. + """ + self.count += 1 + code = str(hex(self.count))[2:] + self.code_url[code] = longUrl + return self.prefix_url + code + + def decode(self, shortUrl: str) -> str: + """Decodes a shortened URL to its original URL. + """ + code = shortUrl.replace(self.prefix_url, '') + return self.code_url[code] + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(url)) +``` + +### **Java** + + + +```java +public class Codec { + private Map code2Url = new HashMap<>(); + private int count = 0; + private static final String prefixUrl = "http://tinyurl.com/"; + + // Encodes a URL to a shortened URL. + public String encode(String longUrl) { + String code = Integer.toHexString(++count); + code2Url.put(code, longUrl); + return prefixUrl + code; + } + + // Decodes a shortened URL to its original URL. + public String decode(String shortUrl) { + String code = shortUrl.replace(prefixUrl, ""); + return code2Url.get(code); + } +} + +// Your Codec object will be instantiated and called as such: +// Codec codec = new Codec(); +// codec.decode(codec.encode(url)); +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0536.leetcode536 Construct Binary Tree from String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0536.leetcode536 Construct Binary Tree from String-zh.md" new file mode 100644 index 00000000..b319a1e8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0536.leetcode536 Construct Binary Tree from String-zh.md" @@ -0,0 +1,69 @@ +# [536. 从字符串生成二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0536.Construct%20Binary%20Tree%20from%20String/README_EN.md) + +## 题目描述 + + + +

    你需要从一个包括括号和整数的字符串构建一棵二叉树。

    + +

    输入的字符串代表一棵二叉树。它包括整数和随后的 0 ,1 或 2 对括号。整数代表根的值,一对括号内表示同样结构的子树。

    + +

    若存在左子结点,则从左子结点开始构建。

    + +

     

    + +

    示例:

    + +
    输入:"4(2(3)(1))(6(5))"
    +输出:返回代表下列二叉树的根节点:
    +
    +       4
    +     /   \
    +    2     6
    +   / \   / 
    +  3   1 5   
    +
    + +

     

    + +

    提示:

    + +
      +
    • 输入字符串中只包含 '(', ')', '-' 和 '0' ~ '9' 
    • +
    • 空树由 "" 而非"()"表示。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0537.leetcode537 Complex Number Multiplication-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0537.leetcode537 Complex Number Multiplication-zh.md" new file mode 100644 index 00000000..475b4704 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0537.leetcode537 Complex Number Multiplication-zh.md" @@ -0,0 +1,65 @@ +# [537. 复数乘法](https://leetcode-cn.com/problems/complex-number-multiplication) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0537.Complex%20Number%20Multiplication/README_EN.md) + +## 题目描述 + + + +

    给定两个表示复数的字符串。

    + +

    返回表示它们乘积的字符串。注意,根据定义 i2 = -1 。

    + +

    示例 1:

    + +
    +输入: "1+1i", "1+1i"
    +输出: "0+2i"
    +解释: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要将它转换为 0+2i 的形式。
    +
    + +

    示例 2:

    + +
    +输入: "1+-1i", "1+-1i"
    +输出: "0+-2i"
    +解释: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要将它转换为 0+-2i 的形式。 
    +
    + +

    注意:

    + +
      +
    1. 输入字符串不包含额外的空格。
    2. +
    3. 输入字符串将以 a+bi 的形式给出,其中整数 ab 的范围均在 [-100, 100] 之间。输出也应当符合这种形式
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0538.leetcode538 Convert BST to Greater Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0538.leetcode538 Convert BST to Greater Tree-zh.md" new file mode 100644 index 00000000..1a7197f0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0538.leetcode538 Convert BST to Greater Tree-zh.md" @@ -0,0 +1,89 @@ +# [538. 把二叉搜索树转换为累加树](https://leetcode-cn.com/problems/convert-bst-to-greater-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0538.Convert%20BST%20to%20Greater%20Tree/README_EN.md) + +## 题目描述 + + + +

    给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

    + +

    提醒一下,二叉搜索树满足下列约束条件:

    + +
      +
    • 节点的左子树仅包含键 小于 节点键的节点。
    • +
    • 节点的右子树仅包含键 大于 节点键的节点。
    • +
    • 左右子树也必须是二叉搜索树。
    • +
    + +

    注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
    +输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
    +
    + +

    示例 2:

    + +
    输入:root = [0,null,1]
    +输出:[1,null,1]
    +
    + +

    示例 3:

    + +
    输入:root = [1,0,2]
    +输出:[3,3,2]
    +
    + +

    示例 4:

    + +
    输入:root = [3,2,4,1]
    +输出:[7,9,4,10]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数介于 0 和 104 之间。
    • +
    • 每个节点的值介于 -104 和 104 之间。
    • +
    • 树中的所有值 互不相同
    • +
    • 给定的树为二叉搜索树。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0539.leetcode539 Minimum Time Difference-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0539.leetcode539 Minimum Time Difference-zh.md" new file mode 100644 index 00000000..70a2d42a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0539.leetcode539 Minimum Time Difference-zh.md" @@ -0,0 +1,65 @@ +# [539. 最小时间差](https://leetcode-cn.com/problems/minimum-time-difference) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0539.Minimum%20Time%20Difference/README_EN.md) + +## 题目描述 + + + +

    给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。

    + +

     

    + +

    示例 1:

    + +
    +输入:timePoints = ["23:59","00:00"]
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:timePoints = ["00:00","23:59","00:00"]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= timePoints <= 2 * 104
    • +
    • timePoints[i] 格式为 "HH:MM"
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0540.leetcode540 Single Element in a Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0540.leetcode540 Single Element in a Sorted Array-zh.md" new file mode 100644 index 00000000..890d396b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0540.leetcode540 Single Element in a Sorted Array-zh.md" @@ -0,0 +1,123 @@ +# [540. 有序数组中的单一元素](https://leetcode-cn.com/problems/single-element-in-a-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0540.Single%20Element%20in%20a%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。

    + +

    示例 1:

    + +
    +输入: [1,1,2,3,3,4,4,8,8]
    +输出: 2
    +
    + +

    示例 2:

    + +
    +输入: [3,3,7,7,10,11,11]
    +输出: 10
    +
    + +

    注意: 您的方案应该在 O(log n)时间复杂度和 O(1)空间复杂度中运行。

    + + +## 解法 + + + +二分法 + + + +### **Python3** + + + +```python +class Solution: + def singleNonDuplicate(self, nums: List[int]) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if (mid & 1) == 1: + mid -= 1 + if nums[mid] == nums[mid + 1]: + left = mid + 2 + else: + right = mid + return nums[left] +``` + +### **Java** + + + +```java +class Solution { + public int singleNonDuplicate(int[] nums) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >>> 1; + if ((mid & 1) == 1) { + --mid; + } + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } + return nums[left]; + } +} +``` + +### **TypeScript** + +```ts +function singleNonDuplicate(nums: number[]): number { + let left = 0, right = nums.length - 1; + while (left < right) { + let mid = (left + right) >> 1; + if ((mid & 1) == 1) --mid; + if (nums[mid] == nums[mid + 1]) { + left = mid + 2; + } else { + right = mid; + } + } + return nums[left]; +}; +``` + +### **Go** + +```go +func singleNonDuplicate(nums []int) int { + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if (mid & 1) == 1 { + mid-- + } + if nums[mid] == nums[mid+1] { + left = mid + 2 + } else { + right = mid + } + } + return nums[left] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0541.leetcode541 Reverse String II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0541.leetcode541 Reverse String II-zh.md" new file mode 100644 index 00000000..5552d796 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0541.leetcode541 Reverse String II-zh.md" @@ -0,0 +1,62 @@ +# [541. 反转字符串 II](https://leetcode-cn.com/problems/reverse-string-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0541.Reverse%20String%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。

    + +
      +
    • 如果剩余字符少于 k 个,则将剩余字符全部反转。
    • +
    • 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
    • +
    + +

     

    + +

    示例:

    + +
    输入: s = "abcdefg", k = 2
    +输出: "bacdfeg"
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 该字符串只包含小写英文字母。
    2. +
    3. 给定字符串的长度和 k[1, 10000] 范围内。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0542.leetcode542 01 Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0542.leetcode542 01 Matrix-zh.md" new file mode 100644 index 00000000..1d065562 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0542.leetcode542 01 Matrix-zh.md" @@ -0,0 +1,82 @@ +# [542. 01 矩阵](https://leetcode-cn.com/problems/01-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0542.01%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

    + +

    两个相邻元素间的距离为 1 。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +[[0,0,0],
    + [0,1,0],
    + [0,0,0]]
    +
    +输出:
    +[[0,0,0],
    + [0,1,0],
    + [0,0,0]]
    +
    + +

    示例 2:

    + +
    +输入:
    +[[0,0,0],
    + [0,1,0],
    + [1,1,1]]
    +
    +输出:
    +[[0,0,0],
    + [0,1,0],
    + [1,2,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定矩阵的元素个数不超过 10000。
    • +
    • 给定矩阵中至少有一个元素是 0。
    • +
    • 矩阵中的元素只在四个方向上相邻: 上、下、左、右。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0543.leetcode543 Diameter of Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0543.leetcode543 Diameter of Binary Tree-zh.md" new file mode 100644 index 00000000..bbd33deb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0543.leetcode543 Diameter of Binary Tree-zh.md" @@ -0,0 +1,58 @@ +# [543. 二叉树的直径](https://leetcode-cn.com/problems/diameter-of-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0543.Diameter%20of%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

    + +

     

    + +

    示例 :
    +给定二叉树

    + +
              1
    +         / \
    +        2   3
    +       / \     
    +      4   5    
    +
    + +

    返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

    + +

     

    + +

    注意:两结点之间的路径长度是以它们之间边的数目表示。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0544.leetcode544 Output Contest Matches-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0544.leetcode544 Output Contest Matches-zh.md" new file mode 100644 index 00000000..f5e80d38 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0544.leetcode544 Output Contest Matches-zh.md" @@ -0,0 +1,85 @@ +# [544. 输出比赛匹配对](https://leetcode-cn.com/problems/output-contest-matches) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0544.Output%20Contest%20Matches/README_EN.md) + +## 题目描述 + + + +

    在 NBA 季后赛中,我们总是安排较强的队伍对战较弱的队伍,例如用排名第 1 的队伍和第 n 的队伍对决,这是一个可以让比赛更加有趣的好策略。现在,给你 支队伍,你需要以字符串格式输出它们的 最终 比赛配对。

    + +

    n 支队伍按从 1 到 n 的正整数格式给出,分别代表它们的初始排名(排名 1 最强,排名 n 最弱)。我们用括号('(', ')')和逗号(',')来表示匹配对——括号('(', ')')表示匹配,逗号(',')来用于分割。 在每一轮的匹配过程中,你都需要遵循将强队与弱队配对的原则。

    + +

     

    + +

    示例 1:

    + +
    输入: 2
    +输出: (1,2)
    +解析: 
    +初始地,我们有队1和队2两支队伍,按照1,2排列。
    +因此 用 '(', ')' 和 ','来将队1和队2进行配对,得到最终答案。
    +
    + +

    示例 2:

    + +
    输入: 4
    +输出: ((1,4),(2,3))
    +解析: 
    +在第一轮,我们将队伍1和4配对,2和3配对,以满足将强队和弱队搭配的效果。得到(1,4),(2,3).
    +在第二轮,(1,4) 和 (2,3) 的赢家需要进行比赛以确定最终赢家,因此需要再在外面加一层括号。
    +于是最终答案是((1,4),(2,3))。
    +
    + +

    示例 3:

    + +
    输入: 8
    +输出: (((1,8),(4,5)),((2,7),(3,6)))
    +解析: 
    +第一轮: (1,8),(2,7),(3,6),(4,5)
    +第二轮: ((1,8),(4,5)),((2,7),(3,6))
    +第三轮 (((1,8),(4,5)),((2,7),(3,6)))
    +由于第三轮会决出最终胜者,故输出答案为(((1,8),(4,5)),((2,7),(3,6)))。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 的范围是 [2, 212].
    2. +
    3. 保证 n 可以写成 2k 的形式,其中 k 是正整数。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0545.leetcode545 Boundary of Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0545.leetcode545 Boundary of Binary Tree-zh.md" new file mode 100644 index 00000000..51a9b1a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0545.leetcode545 Boundary of Binary Tree-zh.md" @@ -0,0 +1,214 @@ +# [545. 二叉树的边界](https://leetcode-cn.com/problems/boundary-of-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0545.Boundary%20of%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    二叉树的 边界 是由 根节点 左边界 、按从左到右顺序的 叶节点逆序的右边界 ,按顺序依次连接组成。

    + +

    左边界 是满足下述定义的节点集合:

    + +
      +
    • 根节点的左子节点在左边界中。如果根节点不含左子节点,那么左边界就为
    • +
    • 如果一个节点在左边界中,并且该节点有左子节点,那么它的左子节点也在左边界中。
    • +
    • 如果一个节点在左边界中,并且该节点 不含 左子节点,那么它的右子节点就在左边界中。
    • +
    • 最左侧的叶节点 不在 左边界中。
    • +
    + +

    右边界 定义方式与 左边界 相同,只是将左替换成右。即,右边界是根节点右子树的右侧部分;叶节点 不是 右边界的组成部分;如果根节点不含右子节点,那么右边界为

    + +

    叶节点 是没有任何子节点的节点。对于此问题,根节点 不是 叶节点。

    + +

    给你一棵二叉树的根节点 root ,按顺序返回组成二叉树 边界 的这些值。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,null,2,3,4]
    +输出:[1,3,4,2]
    +解释:
    +- 左边界为空,因为二叉树不含左子节点。
    +- 右边界是 [2] 。从根节点的右子节点开始的路径为 2 -> 4 ,但 4 是叶节点,所以右边界只有 2 。
    +- 叶节点从左到右是 [3,4] 。
    +按题目要求依序连接得到结果 [1] + [] + [3,4] + [2] = [1,3,4,2] 。
    + +

    示例 2:

    + +
    +输入:root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
    +输出:[1,2,4,7,8,9,10,6,3]
    +解释:
    +- 左边界为 [2] 。从根节点的左子节点开始的路径为 2 -> 4 ,但 4 是叶节点,所以左边界只有 2 。
    +- 右边界是 [3,6] ,逆序为 [6,3] 。从根节点的右子节点开始的路径为 3 -> 6 -> 10 ,但 10 是叶节点。
    +- 叶节点从左到右是 [4,7,8,9,10]
    +按题目要求依序连接得到结果 [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3] 。
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在范围 [1, 104]
    • +
    • -1000 <= Node.val <= 1000
    • +
    + +## 解法 + + + +分别求根节点、左边界、叶子节点、右边界,依次放入结果数组 res 中。 + +注意,求右边界的时候,需要逆序结果,这时可以用栈实现。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]: + self.res = [] + if not root: + return self.res + # root + if not self.is_leaf(root): + self.res.append(root.val) + + # left boundary + t = root.left + while t: + if not self.is_leaf(t): + self.res.append(t.val) + t = t.left if t.left else t.right + + # leaves + self.add_leaves(root) + + # right boundary(reverse order) + s = [] + t = root.right + while t: + if not self.is_leaf(t): + s.append(t.val) + t = t.right if t.right else t.left + while s: + self.res.append(s.pop()) + + # output + return self.res + + def add_leaves(self, root): + if self.is_leaf(root): + self.res.append(root.val) + return + if root.left: + self.add_leaves(root.left) + if root.right: + self.add_leaves(root.right) + + def is_leaf(self, node) -> bool: + return node and node.left is None and node.right is None + +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List res; + + public List boundaryOfBinaryTree(TreeNode root) { + if (root == null) { + return Collections.emptyList(); + } + res = new ArrayList<>(); + + // root + if (!isLeaf(root)) { + res.add(root.val); + } + + // left boundary + TreeNode t = root.left; + while (t != null) { + if (!isLeaf(t)) { + res.add(t.val); + } + t = t.left == null ? t.right : t.left; + } + + // leaves + addLeaves(root); + + // right boundary(reverse order) + Deque s = new ArrayDeque<>(); + t = root.right; + while (t != null) { + if (!isLeaf(t)) { + s.offer(t.val); + } + t = t.right == null ? t.left : t.right; + } + while (!s.isEmpty()) { + res.add(s.pollLast()); + } + + // output + return res; + } + + private void addLeaves(TreeNode root) { + if (isLeaf(root)) { + res.add(root.val); + return; + } + if (root.left != null) { + addLeaves(root.left); + } + if (root.right != null) { + addLeaves(root.right); + } + } + + private boolean isLeaf(TreeNode node) { + return node != null && node.left == null && node.right == null; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0546.leetcode546 Remove Boxes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0546.leetcode546 Remove Boxes-zh.md" new file mode 100644 index 00000000..5c2eed06 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0546.leetcode546 Remove Boxes-zh.md" @@ -0,0 +1,82 @@ +# [546. 移除盒子](https://leetcode-cn.com/problems/remove-boxes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0546.Remove%20Boxes/README_EN.md) + +## 题目描述 + + + +

    给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。

    + +

    你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。每一轮你可以移除具有相同颜色的连续 k 个盒子(k >= 1),这样一轮之后你将得到 k * k 个积分。

    + +

    当你将所有盒子都去掉之后,求你能获得的最大积分和。

    + +

     

    + +

    示例 1:

    + +
    +输入:boxes = [1,3,2,2,2,3,4,3,1]
    +输出:23
    +解释:
    +[1, 3, 2, 2, 2, 3, 4, 3, 1] 
    +----> [1, 3, 3, 4, 3, 1] (3*3=9 分) 
    +----> [1, 3, 3, 3, 1] (1*1=1 分) 
    +----> [1, 1] (3*3=9 分) 
    +----> [] (2*2=4 分)
    +
    + +

    示例 2:

    + +
    +输入:boxes = [1,1,1]
    +输出:9
    +
    + +

    示例 3:

    + +
    +输入:boxes = [1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= boxes.length <= 100
    • +
    • 1 <= boxes[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0547.leetcode547 Number of Provinces-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0547.leetcode547 Number of Provinces-zh.md" new file mode 100644 index 00000000..70d0ad24 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0547.leetcode547 Number of Provinces-zh.md" @@ -0,0 +1,118 @@ +# [547. 省份数量](https://leetcode-cn.com/problems/number-of-provinces) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0547.Number%20of%20Provinces/README_EN.md) + +## 题目描述 + + + +
    +
    +

    n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。

    + +

    省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。

    + +

    给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。

    + +

    返回矩阵中 省份 的数量。

    + +

     

    + +

    示例 1:

    + +
    +输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]]
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 200
    • +
    • n == isConnected.length
    • +
    • n == isConnected[i].length
    • +
    • isConnected[i][j]10
    • +
    • isConnected[i][i] == 1
    • +
    • isConnected[i][j] == isConnected[j][i]
    • +
    +
    +
    + + +## 解法 + + + +深度优先搜索。判断学生与学生之间是否属于同一个连通分量,最后连通分量的总数即为结果。 + + + +### **Python3** + + + +```python +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def dfs(i): + for j in range(n): + if not visited[j] and isConnected[i][j] == 1: + visited[j] = True + dfs(j) + + n = len(isConnected) + visited = [False] * n + num = 0 + for i in range(n): + if not visited[i]: + dfs(i) + num += 1 + return num +``` + +### **Java** + + + +```java +class Solution { + public int findCircleNum(int[][] isConnected) { + int n = isConnected.length; + boolean[] visited = new boolean[n]; + int num = 0; + for (int i = 0; i < n; ++i) { + if (!visited[i]) { + dfs(isConnected, visited, i, n); + ++num; + } + } + return num; + } + + private void dfs(int[][] isConnected, boolean[] visited, int i, int n) { + for (int j = 0; j < n; ++j) { + if (!visited[j] && isConnected[i][j] == 1) { + visited[j] = true; + dfs(isConnected, visited, j, n); + } + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0548.leetcode548 Split Array with Equal Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0548.leetcode548 Split Array with Equal Sum-zh.md" new file mode 100644 index 00000000..e3d716e2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0548.leetcode548 Split Array with Equal Sum-zh.md" @@ -0,0 +1,70 @@ +# [548. 将数组分割成和相等的子数组](https://leetcode-cn.com/problems/split-array-with-equal-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0548.Split%20Array%20with%20Equal%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个有 n 个整数的数组,你需要找到满足以下条件的三元组 (i, j, k) :

    + +
      +
    1. 0 < i, i + 1 < j, j + 1 < k < n - 1
    2. +
    3. 子数组 (0, i - 1),(i + 1, j - 1),(j + 1, k - 1),(k + 1, n - 1) 的和应该相等。
    4. +
    + +

    这里我们定义子数组 (L, R) 表示原数组从索引为L的元素开始至索引为R的元素。

    + +

     

    + +

    示例:

    + +
    输入: [1,2,1,2,1,2,1]
    +输出: True
    +解释:
    +i = 1, j = 3, k = 5. 
    +sum(0, i - 1) = sum(0, 0) = 1
    +sum(i + 1, j - 1) = sum(2, 2) = 1
    +sum(j + 1, k - 1) = sum(4, 4) = 1
    +sum(k + 1, n - 1) = sum(6, 6) = 1
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 1 <= n <= 2000。
    2. +
    3. 给定数组中的元素会在 [-1,000,000, 1,000,000] 范围内。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0549.leetcode549 Binary Tree Longest Consecutive Sequence II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0549.leetcode549 Binary Tree Longest Consecutive Sequence II-zh.md" new file mode 100644 index 00000000..6425f0cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0549.leetcode549 Binary Tree Longest Consecutive Sequence II-zh.md" @@ -0,0 +1,68 @@ +# [549. 二叉树中最长的连续序列](https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0549.Binary%20Tree%20Longest%20Consecutive%20Sequence%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,你需要找出二叉树中最长的连续序列路径的长度。

    + +

    请注意,该路径可以是递增的或者是递减。例如,[1,2,3,4] 和 [4,3,2,1] 都被认为是合法的,而路径 [1,2,4,3] 则不合法。另一方面,路径可以是 子-父-子 顺序,并不一定是 父-子 顺序。

    + +

    示例 1:

    + +
    输入:
    +        1
    +       / \
    +      2   3
    +输出: 2
    +解释: 最长的连续路径是 [1, 2] 或者 [2, 1]。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +        2
    +       / \
    +      1   3
    +输出: 3
    +解释: 最长的连续路径是 [1, 2, 3] 或者 [3, 2, 1]。
    +
    + +

     

    + +

    注意: 树上所有节点的值都在 [-1e7, 1e7] 范围内。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0550.leetcode550 Game Play Analysis IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0550.leetcode550 Game Play Analysis IV-zh.md" new file mode 100644 index 00000000..1b243c6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0550.leetcode550 Game Play Analysis IV-zh.md" @@ -0,0 +1,63 @@ +# [550. 游戏玩法分析 IV](https://leetcode-cn.com/problems/game-play-analysis-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0550.Game%20Play%20Analysis%20IV/README_EN.md) + +## 题目描述 + + + +

    Table: Activity

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| player_id    | int     |
    +| device_id    | int     |
    +| event_date   | date    |
    +| games_played | int     |
    ++--------------+---------+
    +(player_id,event_date)是此表的主键。
    +这张表显示了某些游戏的玩家的活动情况。
    +每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0)。
    +
    + +

     

    + +

    编写一个 SQL 查询,报告在首次登录的第二天再次登录的玩家的比率,四舍五入到小数点后两位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。

    + +

    查询结果格式如下所示:

    + +
    Activity table:
    ++-----------+-----------+------------+--------------+
    +| player_id | device_id | event_date | games_played |
    ++-----------+-----------+------------+--------------+
    +| 1         | 2         | 2016-03-01 | 5            |
    +| 1         | 2         | 2016-03-02 | 6            |
    +| 2         | 3         | 2017-06-25 | 1            |
    +| 3         | 1         | 2016-03-02 | 0            |
    +| 3         | 4         | 2018-07-03 | 5            |
    ++-----------+-----------+------------+--------------+
    +
    +Result table:
    ++-----------+
    +| fraction  |
    ++-----------+
    +| 0.33      |
    ++-----------+
    +只有 ID 为 1 的玩家在第一天登录后才重新登录,所以答案是 1/3 = 0.33
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0551.leetcode551 Student Attendance Record I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0551.leetcode551 Student Attendance Record I-zh.md" new file mode 100644 index 00000000..82c83f7d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0551.leetcode551 Student Attendance Record I-zh.md" @@ -0,0 +1,69 @@ +# [551. 学生出勤记录 I](https://leetcode-cn.com/problems/student-attendance-record-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0551.Student%20Attendance%20Record%20I/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:

    + +
      +
    1. 'A' : Absent,缺勤
    2. +
    3. 'L' : Late,迟到
    4. +
    5. 'P' : Present,到场
    6. +
    + +

    如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。

    + +

    你需要根据这个学生的出勤记录判断他是否会被奖赏。

    + +

    示例 1:

    + +
    输入: "PPALLP"
    +输出: True
    +
    + +

    示例 2:

    + +
    输入: "PPALLL"
    +输出: False
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def checkRecord(self, s: str) -> bool: + return s.count('A') <= 1 and 'LLL' not in s +``` + +### **Java** + + + +```java +class Solution { + public boolean checkRecord(String s) { + int i = s.indexOf("A"); + return (i == -1 || s.lastIndexOf("A") == i) && !s.contains("LLL"); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0552.leetcode552 Student Attendance Record II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0552.leetcode552 Student Attendance Record II-zh.md" new file mode 100644 index 00000000..b90479b8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0552.leetcode552 Student Attendance Record II-zh.md" @@ -0,0 +1,62 @@ +# [552. 学生出勤记录 II](https://leetcode-cn.com/problems/student-attendance-record-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0552.Student%20Attendance%20Record%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 n,返回长度为 n 的所有可被视为可奖励的出勤记录的数量。 答案可能非常大,你只需返回结果mod 109 + 7的值。

    + +

    学生出勤记录是只包含以下三个字符的字符串:

    + +
      +
    1. 'A' : Absent,缺勤
    2. +
    3. 'L' : Late,迟到
    4. +
    5. 'P' : Present,到场
    6. +
    + +

    如果记录不包含多于一个'A'(缺勤)超过两个连续的'L'(迟到),则该记录被视为可奖励的。

    + +

    示例 1:

    + +
    +输入: n = 2
    +输出: 8 
    +解释:
    +有8个长度为2的记录将被视为可奖励:
    +"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
    +只有"AA"不会被视为可奖励,因为缺勤次数超过一次。
    + +

    注意:n 的值不会超过100000。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0553.leetcode553 Optimal Division-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0553.leetcode553 Optimal Division-zh.md" new file mode 100644 index 00000000..75907319 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0553.leetcode553 Optimal Division-zh.md" @@ -0,0 +1,67 @@ +# [553. 最优除法](https://leetcode-cn.com/problems/optimal-division) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0553.Optimal%20Division/README_EN.md) + +## 题目描述 + + + +

    给定一组正整数,相邻的整数之间将会进行浮点除法操作。例如, [2,3,4] -> 2 / 3 / 4 。

    + +

    但是,你可以在任意位置添加任意数目的括号,来改变算数的优先级。你需要找出怎么添加括号,才能得到最大的结果,并且返回相应的字符串格式的表达式。你的表达式不应该含有冗余的括号。

    + +

    示例:

    + +
    +输入: [1000,100,10,2]
    +输出: "1000/(100/10/2)"
    +解释:
    +1000/(100/10/2) = 1000/((100/10)/2) = 200
    +但是,以下加粗的括号 "1000/((100/10)/2)" 是冗余的,
    +因为他们并不影响操作的优先级,所以你需要返回 "1000/(100/10/2)"。
    +
    +其他用例:
    +1000/(100/10)/2 = 50
    +1000/(100/(10/2)) = 50
    +1000/100/10/2 = 0.5
    +1000/100/(10/2) = 2
    +
    + +

    说明:

    + +
      +
    1. 输入数组的长度在 [1, 10] 之间。
    2. +
    3. 数组中每个元素的大小都在 [2, 1000] 之间。
    4. +
    5. 每个测试用例只有一个最优除法解。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0554.leetcode554 Brick Wall-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0554.leetcode554 Brick Wall-zh.md" new file mode 100644 index 00000000..2169b956 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0554.leetcode554 Brick Wall-zh.md" @@ -0,0 +1,142 @@ +# [554. 砖墙](https://leetcode-cn.com/problems/brick-wall) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0554.Brick%20Wall/README_EN.md) + +## 题目描述 + + + +

    你的面前有一堵矩形的、由多行砖块组成的砖墙。 这些砖块高度相同但是宽度不同。你现在要画一条自顶向下的、穿过最少砖块的垂线。

    + +

    砖墙由行的列表表示。 每一行都是一个代表从左至右每块砖的宽度的整数列表。

    + +

    如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你需要找出怎样画才能使这条线穿过的砖块数量最少,并且返回穿过的砖块数量。

    + +

    你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。

    + +

     

    + +

    示例:

    + +
    输入: [[1,2,2,1],
    +      [3,1,2],
    +      [1,3,2],
    +      [2,4],
    +      [3,1,2],
    +      [1,3,1,1]]
    +
    +输出: 2
    +
    +解释: 
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 每一行砖块的宽度之和应该相等,并且不能超过 INT_MAX。
    2. +
    3. 每一行砖块的数量在 [1,10,000] 范围内, 墙的高度在 [1,10,000] 范围内, 总的砖块数量不超过 20,000。
    4. +
    + +## 解法 + + + +题目可以理解为,让垂线尽可能多地穿过砖块边缘,用哈希表处理不同位置的砖块边缘出现的频次(不包括两个垂直边缘),最终的答案就是总行数减去最大频数。 + + + +### **Python3** + + + +```python +class Solution: + def leastBricks(self, wall: List[List[int]]) -> int: + cnt = collections.defaultdict(int) + for row in wall: + width = 0 + for brick in row[:-1]: + width += brick + cnt[width] += 1 + if not cnt: + return len(wall) + return len(wall) - cnt[max(cnt, key=cnt.get)] +``` + +### **Java** + + + +```java +class Solution { + public int leastBricks(List> wall) { + Map cnt = new HashMap<>(); + for (List row : wall) { + int width = 0; + for (int i = 0, n = row.size() - 1; i < n; i++) { + width += row.get(i); + cnt.merge(width, 1, Integer::sum); + } + } + int max = cnt.values().stream().max(Comparator.naturalOrder()).orElse(0); + return wall.size() - max; + } +} +``` + +### **Go** + +```go +func leastBricks(wall [][]int) int { + cnt := make(map[int]int) + for _, row := range wall { + width := 0 + for _, brick := range row[:len(row)-1] { + width += brick + cnt[width]++ + } + } + max := 0 + for _, v := range cnt { + if v > max { + max = v + } + } + return len(wall) - max +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} wall + * @return {number} + */ +var leastBricks = function (wall) { + const cnt = new Map(); + for (const row of wall) { + let width = 0; + for (let i = 0, n = row.length - 1; i < n; ++i) { + width += row[i]; + cnt.set(width, (cnt.get(width) || 0) + 1); + } + } + let max = 0; + for (const v of cnt.values()) { + max = Math.max(max, v); + } + return wall.length - max; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0555.leetcode555 Split Concatenated Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0555.leetcode555 Split Concatenated Strings-zh.md" new file mode 100644 index 00000000..4a751bf9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0555.leetcode555 Split Concatenated Strings-zh.md" @@ -0,0 +1,70 @@ +# [555. 分割连接字符串](https://leetcode-cn.com/problems/split-concatenated-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0555.Split%20Concatenated%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串列表,你可以将这些字符串连接成一个循环字符串,对于每个字符串,你可以选择是否翻转它。在所有可能的循环字符串中,你需要分割循环字符串(这将使循环字符串变成一个常规的字符串),然后找到字典序最大的字符串。

    + +

    具体来说,要找到字典序最大的字符串,你需要经历两个阶段:

    + +
      +
    1. 将所有字符串连接成一个循环字符串,你可以选择是否翻转某些字符串,并按照给定的顺序连接它们。
    2. +
    3. 在循环字符串的某个位置分割它,这将使循环字符串从分割点变成一个常规的字符串。
    4. +
    + +

    你的工作是在所有可能的常规字符串中找到字典序最大的一个。

    + +

    示例:

    + +
    输入: "abc", "xyz"
    +输出: "zyxcba"
    +解释: 你可以得到循环字符串 "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-",
    +其中 '-' 代表循环状态。 
    +答案字符串来自第四个循环字符串, 
    +你可以从中间字符 'a' 分割开然后得到 "zyxcba"。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 输入字符串只包含小写字母。
    2. +
    3. 所有字符串的总长度不会超过 1,000。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0556.leetcode556 Next Greater Element III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0556.leetcode556 Next Greater Element III-zh.md" new file mode 100644 index 00000000..5e37e414 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0556.leetcode556 Next Greater Element III-zh.md" @@ -0,0 +1,66 @@ +# [556. 下一个更大元素 III](https://leetcode-cn.com/problems/next-greater-element-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0556.Next%20Greater%20Element%20III/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数 n ,请你找出符合条件的最小整数,其由重新排列 n 中存在的每位数字组成,并且其值大于 n 。如果不存在这样的正整数,则返回 -1

    + +

    注意 ,返回的整数应当是一个 32 位整数 ,如果存在满足题意的答案,但不是 32 位整数 ,同样返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 12
    +输出:21
    +
    + +

    示例 2:

    + +
    +输入:n = 21
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0557.leetcode557 Reverse Words in a String III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0557.leetcode557 Reverse Words in a String III-zh.md" new file mode 100644 index 00000000..ca0ee5eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0557.leetcode557 Reverse Words in a String III-zh.md" @@ -0,0 +1,56 @@ +# [557. 反转字符串中的单词 III](https://leetcode-cn.com/problems/reverse-words-in-a-string-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0557.Reverse%20Words%20in%20a%20String%20III/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

    + +

     

    + +

    示例:

    + +
    输入:"Let's take LeetCode contest"
    +输出:"s'teL ekat edoCteeL tsetnoc"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0558.leetcode558 Logical OR of Two Binary Grids Represented as Quad-Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0558.leetcode558 Logical OR of Two Binary Grids Represented as Quad-Trees-zh.md" new file mode 100644 index 00000000..ec14deb6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0558.leetcode558 Logical OR of Two Binary Grids Represented as Quad-Trees-zh.md" @@ -0,0 +1,142 @@ +# [558. 四叉树交集](https://leetcode-cn.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0558.Logical%20OR%20of%20Two%20Binary%20Grids%20Represented%20as%20Quad-Trees/README_EN.md) + +## 题目描述 + + + +

    二进制矩阵中的所有元素不是 0 就是 1

    + +

    给你两个四叉树,quadTree1quadTree2。其中 quadTree1 表示一个 n * n 二进制矩阵,而 quadTree2 表示另一个 n * n 二进制矩阵。

    + +

    请你返回一个表示 n * n 二进制矩阵的四叉树,它是 quadTree1quadTree2 所表示的两个二进制矩阵进行 按位逻辑或运算 的结果。

    + +

    注意,当 isLeafFalse 时,你可以把 True 或者 False 赋值给节点,两种值都会被判题机制 接受

    + +

    四叉树数据结构中,每个内部节点只有四个子节点。此外,每个节点都有两个属性:

    + +
      +
    • val:储存叶子结点所代表的区域的值。1 对应 True,0 对应 False
    • +
    • isLeaf: 当这个节点是一个叶子结点时为 True,如果它有 4 个子节点则为 False
    • +
    + +
    +class Node {
    +    public boolean val;
    +    public boolean isLeaf;
    +    public Node topLeft;
    +    public Node topRight;
    +    public Node bottomLeft;
    +    public Node bottomRight;
    +}
    + +

    我们可以按以下步骤为二维区域构建四叉树:

    + +
      +
    1. 如果当前网格的值相同(即,全为 0 或者全为 1),将 isLeaf 设为 True ,将 val 设为网格相应的值,并将四个子节点都设为 Null 然后停止。
    2. +
    3. 如果当前网格的值不同,将 isLeaf 设为 False, 将 val 设为任意值,然后如下图所示,将当前网格划分为四个子网格。
    4. +
    5. 使用适当的子网格递归每个子节点。
    6. +
    + +

    + +

    如果你想了解更多关于四叉树的内容,可以参考 wiki

    + +

    四叉树格式:

    + +

    输出为使用层序遍历后四叉树的序列化形式,其中 null 表示路径终止符,其下面不存在节点。

    + +

    它与二叉树的序列化非常相似。唯一的区别是节点以列表形式表示 [isLeaf, val]

    + +

    如果 isLeaf 或者 val 的值为 True ,则表示它在列表 [isLeaf, val] 中的值为 1 ;如果 isLeaf 或者 val 的值为 False ,则表示值为 0

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
    +, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
    +输出:[[0,0],[1,1],[1,1],[1,1],[1,0]]
    +解释:quadTree1 和 quadTree2 如上所示。由四叉树所表示的二进制矩阵也已经给出。
    +如果我们对这两个矩阵进行按位逻辑或运算,则可以得到下面的二进制矩阵,由一个作为结果的四叉树表示。
    +注意,我们展示的二进制矩阵仅仅是为了更好地说明题意,你无需构造二进制矩阵来获得结果四叉树。
    +
    +
    + +

    示例 2:

    + +
    +输入:quadTree1 = [[1,0]]
    +, quadTree2 = [[1,0]]
    +输出:[[1,0]]
    +解释:两个数所表示的矩阵大小都为 1*1,值全为 0 
    +结果矩阵大小为 1*1,值全为 0 。
    +
    + +

    示例 3:

    + +
    +输入:quadTree1 = [[0,0],[1,0],[1,0],[1,1],[1,1]]
    +, quadTree2 = [[0,0],[1,1],[1,1],[1,0],[1,1]]
    +输出:[[1,1]]
    +
    + +

    示例 4:

    + +
    +输入:quadTree1 = [[0,0],[1,1],[1,0],[1,1],[1,1]]
    +, quadTree2 = [[0,0],[1,1],[0,1],[1,1],[1,1],null,null,null,null,[1,1],[1,0],[1,0],[1,1]]
    +输出:[[0,0],[1,1],[0,1],[1,1],[1,1],null,null,null,null,[1,1],[1,0],[1,0],[1,1]]
    +
    + +

    示例 5:

    + +
    +输入:quadTree1 = [[0,1],[1,0],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
    +, quadTree2 = [[0,1],[0,1],[1,0],[1,1],[1,0],[1,0],[1,0],[1,1],[1,1]]
    +输出:[[0,0],[0,1],[0,1],[1,1],[1,0],[1,0],[1,0],[1,1],[1,1],[1,0],[1,0],[1,1],[1,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • quadTree1quadTree2 都是符合题目要求的四叉树,每个都代表一个 n * n 的矩阵。
    • +
    • n == 2^x ,其中 0 <= x <= 9.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0559.leetcode559 Maximum Depth of N-ary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0559.leetcode559 Maximum Depth of N-ary Tree-zh.md" new file mode 100644 index 00000000..740062ad --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0559.leetcode559 Maximum Depth of N-ary Tree-zh.md" @@ -0,0 +1,117 @@ +# [559. N 叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0559.Maximum%20Depth%20of%20N-ary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个 N 叉树,找到其最大深度。

    + +

    最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

    + +

    N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,null,3,2,4,null,5,6]
    +输出:3
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树的深度不会超过 1000
    • +
    • 树的节点数目位于 [0, 104] 之间。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def maxDepth(self, root: 'Node') -> int: + if not root: + return 0 + max_depth = 1 + for child in root.children: + max_depth = max(max_depth, 1 + self.maxDepth(child)) + return max_depth +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + public int maxDepth(Node root) { + if (root == null) { + return 0; + } + int maxDepth = 1; + for (Node child : root.children) { + maxDepth = Math.max(maxDepth, 1 + maxDepth(child)); + } + return maxDepth; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0560.leetcode560 Subarray Sum Equals K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0560.leetcode560 Subarray Sum Equals K-zh.md" new file mode 100644 index 00000000..c06502b5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0560.leetcode560 Subarray Sum Equals K-zh.md" @@ -0,0 +1,54 @@ +# [560. 和为K的子数组](https://leetcode-cn.com/problems/subarray-sum-equals-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0560.Subarray%20Sum%20Equals%20K/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组和一个整数 k,你需要找到该数组中和为 的连续的子数组的个数。

    + +

    示例 1 :

    + +
    +输入:nums = [1,1,1], k = 2
    +输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
    +
    + +

    说明 :

    + +
      +
    1. 数组的长度为 [1, 20,000]。
    2. +
    3. 数组中元素的范围是 [-1000, 1000] ,且整数 的范围是 [-1e7, 1e7]。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0561.leetcode561 Array Partition I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0561.leetcode561 Array Partition I-zh.md" new file mode 100644 index 00000000..68c910cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0561.leetcode561 Array Partition I-zh.md" @@ -0,0 +1,103 @@ +# [561. 数组拆分 I](https://leetcode-cn.com/problems/array-partition-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0561.Array%20Partition%20I/README_EN.md) + +## 题目描述 + + + +

    给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从 1 到 nmin(ai, bi) 总和最大。

    + +

    返回该 最大总和

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,4,3,2]
    +输出:4
    +解释:所有可能的分法(忽略元素顺序)为:
    +1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
    +2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
    +3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
    +所以最大总和为 4
    + +

    示例 2:

    + +
    +输入:nums = [6,2,6,5,1,2]
    +输出:9
    +解释:最优的分法为 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 104
    • +
    • nums.length == 2 * n
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## 解法 + + + +先排序,然后求相邻的两个元素的最小值,得到的总和即为结果。 + + + +### **Python3** + + + +```python +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + return sum(sorted(nums)[::2]) +``` + +### **Java** + + + +```java +class Solution { + public int arrayPairSum(int[] nums) { + Arrays.sort(nums); + int res = 0; + for (int i = 0, n = nums.length; i < n; i += 2) { + res += nums[i]; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var arrayPairSum = function (nums) { + nums.sort((a, b) => a - b); + let res = 0; + for (let i = 0, n = nums.length; i < n; i += 2) { + res += nums[i]; + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0562.leetcode562 Longest Line of Consecutive One in Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0562.leetcode562 Longest Line of Consecutive One in Matrix-zh.md" new file mode 100644 index 00000000..b3a4ac4d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0562.leetcode562 Longest Line of Consecutive One in Matrix-zh.md" @@ -0,0 +1,51 @@ +# [562. 矩阵中最长的连续1线段](https://leetcode-cn.com/problems/longest-line-of-consecutive-one-in-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0562.Longest%20Line%20of%20Consecutive%20One%20in%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给定一个01矩阵 M,找到矩阵中最长的连续1线段。这条线段可以是水平的、垂直的、对角线的或者反对角线的。

    + +

    示例:

    + +
    输入:
    +[[0,1,1,0],
    + [0,1,1,0],
    + [0,0,0,1]]
    +输出: 3
    +
    + +

    提示: 给定矩阵中的元素数量不会超过 10,000。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0563.leetcode563 Binary Tree Tilt-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0563.leetcode563 Binary Tree Tilt-zh.md" new file mode 100644 index 00000000..6be3d0b2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0563.leetcode563 Binary Tree Tilt-zh.md" @@ -0,0 +1,89 @@ +# [563. 二叉树的坡度](https://leetcode-cn.com/problems/binary-tree-tilt) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0563.Binary%20Tree%20Tilt/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,计算 整个树 的坡度 。

    + +

    一个树的 节点的坡度 定义即为,该节点左子树的节点之和和右子树节点之和的 差的绝对值 。如果没有左子树的话,左子树的节点之和为 0 ;没有右子树的话也是一样。空结点的坡度是 0 。

    + +

    整个树 的坡度就是其所有节点的坡度之和。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2,3]
    +输出:1
    +解释:
    +节点 2 的坡度:|0-0| = 0(没有子节点)
    +节点 3 的坡度:|0-0| = 0(没有子节点)
    +节点 1 的坡度:|2-3| = 1(左子树就是左子节点,所以和是 2 ;右子树就是右子节点,所以和是 3 )
    +坡度总和:0 + 0 + 1 = 1
    +
    + +

    示例 2:

    + +
    +输入:root = [4,2,9,3,5,null,7]
    +输出:15
    +解释:
    +节点 3 的坡度:|0-0| = 0(没有子节点)
    +节点 5 的坡度:|0-0| = 0(没有子节点)
    +节点 7 的坡度:|0-0| = 0(没有子节点)
    +节点 2 的坡度:|3-5| = 2(左子树就是左子节点,所以和是 3 ;右子树就是右子节点,所以和是 5 )
    +节点 9 的坡度:|0-7| = 7(没有左子树,所以和是 0 ;右子树正好是右子节点,所以和是 7 )
    +节点 4 的坡度:|(3+5+2)-(9+7)| = |10-16| = 6(左子树值为 3、5 和 2 ,和是 10 ;右子树值为 9 和 7 ,和是 16 )
    +坡度总和:0 + 0 + 0 + 2 + 7 + 6 = 15
    +
    + +

    示例 3:

    + +
    +输入:root = [21,7,14,1,1,2,2,3,3]
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目的范围在 [0, 104]
    • +
    • -1000 <= Node.val <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0564.leetcode564 Find the Closest Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0564.leetcode564 Find the Closest Palindrome-zh.md" new file mode 100644 index 00000000..06936f2c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0564.leetcode564 Find the Closest Palindrome-zh.md" @@ -0,0 +1,56 @@ +# [564. 寻找最近的回文数](https://leetcode-cn.com/problems/find-the-closest-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0564.Find%20the%20Closest%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给定一个整数 n ,你需要找到与它最近的回文数(不包括自身)。

    + +

    “最近的”定义为两个整数差的绝对值最小。

    + +

    示例 1:

    + +
    +输入: "123"
    +输出: "121"
    +
    + +

    注意:

    + +
      +
    1. n 是由字符串表示的正整数,其长度不超过18。
    2. +
    3. 如果有多个结果,返回最小的那个。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0565.leetcode565 Array Nesting-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0565.leetcode565 Array Nesting-zh.md" new file mode 100644 index 00000000..6f03ebc1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0565.leetcode565 Array Nesting-zh.md" @@ -0,0 +1,65 @@ +# [565. 数组嵌套](https://leetcode-cn.com/problems/array-nesting) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0565.Array%20Nesting/README_EN.md) + +## 题目描述 + + + +

    索引从0开始长度为N的数组A,包含0N - 1的所有整数。找到最大的集合S并返回其大小,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], ... }且遵守以下的规则。

    + +

    假设选择索引为i的元素A[i]S的第一个元素,S的下一个元素应该是A[A[i]],之后是A[A[A[i]]]... 以此类推,不断添加直到S出现重复的元素。

    + +

     

    + +

    示例 1:

    + +
    输入: A = [5,4,0,3,1,6,2]
    +输出: 4
    +解释: 
    +A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
    +
    +其中一种最长的 S[K]:
    +S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
    +
    + +

     

    + +

    提示:

    + +
      +
    1. N[1, 20,000]之间的整数。
    2. +
    3. A中不含有重复的元素。
    4. +
    5. A中的元素大小在[0, N-1]之间。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0566.leetcode566 Reshape the Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0566.leetcode566 Reshape the Matrix-zh.md" new file mode 100644 index 00000000..f81df0fa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0566.leetcode566 Reshape the Matrix-zh.md" @@ -0,0 +1,118 @@ +# [566. 重塑矩阵](https://leetcode-cn.com/problems/reshape-the-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0566.Reshape%20the%20Matrix/README_EN.md) + +## 题目描述 + + + +

    在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。

    + +

    给出一个由二维数组表示的矩阵,以及两个正整数rc,分别表示想要的重构的矩阵的行数和列数。

    + +

    重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。

    + +

    如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

    + +

    示例 1:

    + +
    +输入: 
    +nums = 
    +[[1,2],
    + [3,4]]
    +r = 1, c = 4
    +输出: 
    +[[1,2,3,4]]
    +解释:
    +行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
    +
    + +

    示例 2:

    + +
    +输入: 
    +nums = 
    +[[1,2],
    + [3,4]]
    +r = 2, c = 4
    +输出: 
    +[[1,2],
    + [3,4]]
    +解释:
    +没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
    +
    + +

    注意:

    + +
      +
    1. 给定矩阵的宽和高范围在 [1, 100]。
    2. +
    3. 给定的 r 和 c 都是正数。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: + m, n = len(nums), len(nums[0]) + if m * n != r * c: + return nums + res = [[0] * c for _ in range(r)] + for x in range(m * n): + res[x // c][x % c] = nums[x // n][x % n] + return res +``` + +### **Java** + + + +```java +class Solution { + public int[][] matrixReshape(int[][] nums, int r, int c) { + int m = nums.length, n = nums[0].length; + if (m * n != r * c) return nums; + int[][] res = new int[r][c]; + for (int i = 0; i < m * n; ++i) { + res[i / c][i % c] = nums[i / n][i % n]; + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function matrixReshape(mat: number[][], r: number, c: number): number[][] { + let m = mat.length, n = mat[0].length; + if (m * n != r * c) return mat; + let ans = Array.from({length: r}, v => new Array(c).fill(0)); + let k = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + ans[Math.floor(k / c)][k % c] = mat[i][j]; + ++k; + } + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0567.leetcode567 Permutation in String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0567.leetcode567 Permutation in String-zh.md" new file mode 100644 index 00000000..7b38eb67 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0567.leetcode567 Permutation in String-zh.md" @@ -0,0 +1,68 @@ +# [567. 字符串的排列](https://leetcode-cn.com/problems/permutation-in-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0567.Permutation%20in%20String/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。

    + +

    换句话说,第一个字符串的排列之一是第二个字符串的 子串

    + +

     

    + +

    示例 1:

    + +
    +输入: s1 = "ab" s2 = "eidbaooo"
    +输出: True
    +解释: s2 包含 s1 的排列之一 ("ba").
    +
    + +

    示例 2:

    + +
    +输入: s1= "ab" s2 = "eidboaoo"
    +输出: False
    +
    + +

     

    + +

    提示:

    + +
      +
    • 输入的字符串只包含小写字母
    • +
    • 两个字符串的长度都在 [1, 10,000] 之间
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0568.leetcode568 Maximum Vacation Days-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0568.leetcode568 Maximum Vacation Days-zh.md" new file mode 100644 index 00000000..57f18531 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0568.leetcode568 Maximum Vacation Days-zh.md" @@ -0,0 +1,109 @@ +# [568. 最大休假天数](https://leetcode-cn.com/problems/maximum-vacation-days) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0568.Maximum%20Vacation%20Days/README_EN.md) + +## 题目描述 + + + +

    力扣想让一个最优秀的员工在 N 个城市间旅行来收集算法问题。 但只工作不玩耍,聪明的孩子也会变傻,所以您可以在某些特定的城市和星期休假。您的工作就是安排旅行使得最大化你可以休假的天数,但是您需要遵守一些规则和限制。

    + +

    规则和限制:

    + +
      +
    1. 您只能在 N 个城市之间旅行,用 0 到 N-1 的索引表示。一开始,您在索引为0的城市,并且那天是星期一
    2. +
    3. 这些城市通过航班相连。这些航班用 N*N 矩阵 flights(不一定是对称的)表示,flights[i][j] 代表城市i到城市j的航空状态。如果没有城市i到城市j的航班,flights[i][j] = 0;否则,flights[i][j] = 1。同时,对于所有的i,flights[i][i] = 0。
    4. +
    5. 您总共有 K 周(每周7天)的时间旅行。您每天最多只能乘坐一次航班,并且只能在每周的星期一上午乘坐航班。由于飞行时间很短,我们不考虑飞行时间的影响。
    6. +
    7. 对于每个城市,不同的星期您休假天数是不同的,给定一个 N*K 矩阵 days 代表这种限制,days[i][j] 代表您在第j个星期在城市i能休假的最长天数。
    8. +
    + +

    给定 flights 矩阵和 days 矩阵,您需要输出 K 周内可以休假的最长天数。

    + +

    示例 1:

    + +
    输入:flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
    +输出: 12
    +解释: 
    +Ans = 6 + 3 + 3 = 12. 
    +
    +最好的策略之一:
    +第一个星期 : 星期一从城市0飞到城市1,玩6天,工作1天。 
    +(虽然你是从城市0开始,但因为是星期一,我们也可以飞到其他城市。) 
    +第二个星期 : 星期一从城市1飞到城市2,玩3天,工作4天。
    +第三个星期 : 呆在城市2,玩3天,工作4天。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:flights = [[0,0,0],[0,0,0],[0,0,0]], days = [[1,1,1],[7,7,7],[7,7,7]]
    +输出: 3
    +解释: 
    +Ans = 1 + 1 + 1 = 3. 
    +
    +由于没有航班可以让您飞到其他城市,你必须在城市0呆整整3个星期。 
    +对于每一个星期,你只有一天时间玩,剩下六天都要工作。 
    +所以最大休假天数为3.
    +
    + +

     

    + +

    示例 3:

    + +
    输入:flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[7,0,0],[0,7,0],[0,0,7]]
    +输出: 21
    +解释:
    +Ans = 7 + 7 + 7 = 21
    +
    +最好的策略之一是:
    +第一个星期 : 呆在城市0,玩7天。 
    +第二个星期 : 星期一从城市0飞到城市1,玩7天。
    +第三个星期 : 星期一从城市1飞到城市2,玩7天。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. N 和 K 都是正整数,在 [1, 100] 范围内。
    2. +
    3. 矩阵 flights 的所有值都是 [0, 1] 范围内的整数。
    4. +
    5. 矩阵 days 的所有值都是 [0, 7] 范围内的整数。
    6. +
    7. 超过休假天数您仍可以呆在那个城市,但是在额外的日子您需要 工作 ,这些日子不会算做休假日。
    8. +
    9. 如果您从城市A飞往城市B并在当天休假日,这个休假会被算作是城市B的休假日。
    10. +
    11. 我们不考虑飞行时间对计算休假日的影响。
    12. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0569.leetcode569 Median Employee Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0569.leetcode569 Median Employee Salary-zh.md" new file mode 100644 index 00000000..771b6715 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0569.leetcode569 Median Employee Salary-zh.md" @@ -0,0 +1,60 @@ +# [569. 员工薪水中位数](https://leetcode-cn.com/problems/median-employee-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0569.Median%20Employee%20Salary/README_EN.md) + +## 题目描述 + + + +

    Employee 表包含所有员工。Employee 表有三列:员工Id,公司名和薪水。

    + +
    +-----+------------+--------+
    +|Id   | Company    | Salary |
    ++-----+------------+--------+
    +|1    | A          | 2341   |
    +|2    | A          | 341    |
    +|3    | A          | 15     |
    +|4    | A          | 15314  |
    +|5    | A          | 451    |
    +|6    | A          | 513    |
    +|7    | B          | 15     |
    +|8    | B          | 13     |
    +|9    | B          | 1154   |
    +|10   | B          | 1345   |
    +|11   | B          | 1221   |
    +|12   | B          | 234    |
    +|13   | C          | 2345   |
    +|14   | C          | 2645   |
    +|15   | C          | 2645   |
    +|16   | C          | 2652   |
    +|17   | C          | 65     |
    ++-----+------------+--------+
    +
    + +

    请编写SQL查询来查找每个公司的薪水中位数。挑战点:你是否可以在不使用任何内置的SQL函数的情况下解决此问题。

    + +
    +-----+------------+--------+
    +|Id   | Company    | Salary |
    ++-----+------------+--------+
    +|5    | A          | 451    |
    +|6    | A          | 513    |
    +|12   | B          | 234    |
    +|9    | B          | 1154   |
    +|14   | C          | 2645   |
    ++-----+------------+--------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0570.leetcode570 Managers with at Least 5 Direct Reports-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0570.leetcode570 Managers with at Least 5 Direct Reports-zh.md" new file mode 100644 index 00000000..6c27e386 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0570.leetcode570 Managers with at Least 5 Direct Reports-zh.md" @@ -0,0 +1,49 @@ +# [570. 至少有5名直接下属的经理](https://leetcode-cn.com/problems/managers-with-at-least-5-direct-reports) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0570.Managers%20with%20at%20Least%205%20Direct%20Reports/README_EN.md) + +## 题目描述 + + + +

    Employee 表包含所有员工和他们的经理。每个员工都有一个 Id,并且还有一列是经理的 Id。

    + +
    +------+----------+-----------+----------+
    +|Id    |Name 	  |Department |ManagerId |
    ++------+----------+-----------+----------+
    +|101   |John 	  |A 	      |null      |
    +|102   |Dan 	  |A 	      |101       |
    +|103   |James 	  |A 	      |101       |
    +|104   |Amy 	  |A 	      |101       |
    +|105   |Anne 	  |A 	      |101       |
    +|106   |Ron 	  |B 	      |101       |
    ++------+----------+-----------+----------+
    +
    + +

    给定 Employee 表,请编写一个SQL查询来查找至少有5名直接下属的经理。对于上表,您的SQL查询应该返回:

    + +
    +-------+
    +| Name  |
    ++-------+
    +| John  |
    ++-------+
    +
    + +

    注意:
    +没有人是自己的下属。

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0571.leetcode571 Find Median Given Frequency of Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0571.leetcode571 Find Median Given Frequency of Numbers-zh.md" new file mode 100644 index 00000000..3b97c473 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0571.leetcode571 Find Median Given Frequency of Numbers-zh.md" @@ -0,0 +1,61 @@ +# [571. 给定数字的频率查询中位数](https://leetcode-cn.com/problems/find-median-given-frequency-of-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0571.Find%20Median%20Given%20Frequency%20of%20Numbers/README_EN.md) + +## 题目描述 + + + +

    Numbers 表保存数字的值及其频率。

    + +
    +----------+-------------+
    +|  Number  |  Frequency  |
    ++----------+-------------|
    +|  0       |  7          |
    +|  1       |  1          |
    +|  2       |  3          |
    +|  3       |  1          |
    ++----------+-------------+
    +
    + +

    在此表中,数字为 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3,所以中位数是 (0 + 0) / 2 = 0

    + +
    +--------+
    +| median |
    ++--------|
    +| 0.0000 |
    ++--------+
    +
    + +

    请编写一个查询来查找所有数字的中位数并将结果命名为 median

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0572.leetcode572 Subtree of Another Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0572.leetcode572 Subtree of Another Tree-zh.md" new file mode 100644 index 00000000..966ae4e9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0572.leetcode572 Subtree of Another Tree-zh.md" @@ -0,0 +1,84 @@ +# [572. 另一个树的子树](https://leetcode-cn.com/problems/subtree-of-another-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0572.Subtree%20of%20Another%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定两个非空二叉树 st,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。

    + +

    示例 1:
    +给定的树 s:

    + +
    +     3
    +    / \
    +   4   5
    +  / \
    + 1   2
    +
    + +

    给定的树 t:

    + +
    +   4 
    +  / \
    + 1   2
    +
    + +

    返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。

    + +

    示例 2:
    +给定的树 s:

    + +
    +     3
    +    / \
    +   4   5
    +  / \
    + 1   2
    +    /
    +   0
    +
    + +

    给定的树 t:

    + +
    +   4
    +  / \
    + 1   2
    +
    + +

    返回 false

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0573.leetcode573 Squirrel Simulation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0573.leetcode573 Squirrel Simulation-zh.md" new file mode 100644 index 00000000..10f868b8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0573.leetcode573 Squirrel Simulation-zh.md" @@ -0,0 +1,63 @@ +# [573. 松鼠模拟](https://leetcode-cn.com/problems/squirrel-simulation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0573.Squirrel%20Simulation/README_EN.md) + +## 题目描述 + + + +

    现在有一棵树,一只松鼠和一些坚果。位置由二维网格的单元格表示。你的目标是找到松鼠收集所有坚果的最小路程,且坚果是一颗接一颗地被放在树下。松鼠一次最多只能携带一颗坚果,松鼠可以向上,向下,向左和向右四个方向移动到相邻的单元格。移动次数表示路程。

    + +

    输入 1:

    + +
    输入: 
    +高度 : 5
    +宽度 : 7
    +树的位置 : [2,2]
    +松鼠 : [4,4]
    +坚果 : [[3,0], [2,5]]
    +输出: 12
    +解释:
    +​​​​​
    +
    + +

    注意:

    + +
      +
    1. 所有给定的位置不会重叠。
    2. +
    3. 松鼠一次最多只能携带一颗坚果。
    4. +
    5. 给定的坚果位置没有顺序。
    6. +
    7. 高度和宽度是正整数。 3 <= 高度 * 宽度 <= 10,000。
    8. +
    9. 给定的网格至少包含一颗坚果,唯一的一棵树和一只松鼠。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0574.leetcode574 Winning Candidate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0574.leetcode574 Winning Candidate-zh.md" new file mode 100644 index 00000000..81c7e3c5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0574.leetcode574 Winning Candidate-zh.md" @@ -0,0 +1,68 @@ +# [574. 当选者](https://leetcode-cn.com/problems/winning-candidate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0574.Winning%20Candidate/README_EN.md) + +## 题目描述 + + + +

    表: Candidate

    + +
    +-----+---------+
    +| id  | Name    |
    ++-----+---------+
    +| 1   | A       |
    +| 2   | B       |
    +| 3   | C       |
    +| 4   | D       |
    +| 5   | E       |
    ++-----+---------+  
    +
    + +

    表: Vote

    + +
    +-----+--------------+
    +| id  | CandidateId  |
    ++-----+--------------+
    +| 1   |     2        |
    +| 2   |     4        |
    +| 3   |     3        |
    +| 4   |     2        |
    +| 5   |     5        |
    ++-----+--------------+
    +id 是自动递增的主键,
    +CandidateId 是 Candidate 表中的 id.
    +
    + +

    请编写 sql 语句来找到当选者的名字,上面的例子将返回当选者 B.

    + +
    +------+
    +| Name |
    ++------+
    +| B    |
    ++------+
    +
    + +

    注意:

    + +
      +
    1. 你可以假设没有平局,换言之,最多只有一位当选者。
    2. +
    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0575.leetcode575 Distribute Candies-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0575.leetcode575 Distribute Candies-zh.md" new file mode 100644 index 00000000..6204ca2e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0575.leetcode575 Distribute Candies-zh.md" @@ -0,0 +1,67 @@ +# [575. 分糖果](https://leetcode-cn.com/problems/distribute-candies) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0575.Distribute%20Candies/README_EN.md) + +## 题目描述 + + + +

    给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。

    + +

    示例 1:

    + +
    +输入: candies = [1,1,2,2,3,3]
    +输出: 3
    +解析: 一共有三种种类的糖果,每一种都有两个。
    +     最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。
    +
    + +

    示例 2 :

    + +
    +输入: candies = [1,1,2,3]
    +输出: 2
    +解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。
    +
    + +

    注意:

    + +
      +
    1. 数组的长度为[2, 10,000],并且确定为偶数。
    2. +
    3. 数组中数字的大小在范围[-100,000, 100,000]内。 +
        +
      +
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0576.leetcode576 Out of Boundary Paths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0576.leetcode576 Out of Boundary Paths-zh.md" new file mode 100644 index 00000000..82e915e8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0576.leetcode576 Out of Boundary Paths-zh.md" @@ -0,0 +1,91 @@ +# [576. 出界的路径数](https://leetcode-cn.com/problems/out-of-boundary-paths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0576.Out%20of%20Boundary%20Paths/README_EN.md) + +## 题目描述 + + + +

    给定一个 m × n 的网格和一个球。球的起始坐标为 (i,j) ,你可以将球移到相邻的单元格内,或者往上、下、左、右四个方向上移动使球穿过网格边界。但是,你最多可以移动 次。找出可以将球移出边界的路径数量。答案可能非常大,返回 结果 mod 109 + 7 的值。

    + + + +

     

    + + + +

    示例 1:

    + + + +
    输入: m = 2, n = 2, N = 2, i = 0, j = 0
    +
    +输出: 6
    +
    +解释:
    +
    +
    +
    +
    + + + +

    示例 2:

    + + + +
    输入: m = 1, n = 3, N = 3, i = 0, j = 1
    +
    +输出: 12
    +
    +解释:
    +
    +
    +
    +
    + + + +

     

    + + + +

    说明:

    + + + +
      +
    1. 球一旦出界,就不能再被移动回网格内。
    2. +
    3. 网格的长度和高度在 [1,50] 的范围内。
    4. +
    5. N 在 [0,50] 的范围内。
    6. +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0577.leetcode577 Employee Bonus-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0577.leetcode577 Employee Bonus-zh.md" new file mode 100644 index 00000000..d3a84a8f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0577.leetcode577 Employee Bonus-zh.md" @@ -0,0 +1,59 @@ +# [577. 员工奖金](https://leetcode-cn.com/problems/employee-bonus) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0577.Employee%20Bonus/README_EN.md) + +## 题目描述 + + + +

    选出所有 bonus < 1000 的员工的 name 及其 bonus。

    + +

    Employee 表单

    + +
    +-------+--------+-----------+--------+
    +| empId |  name  | supervisor| salary |
    ++-------+--------+-----------+--------+
    +|   1   | John   |  3        | 1000   |
    +|   2   | Dan    |  3        | 2000   |
    +|   3   | Brad   |  null     | 4000   |
    +|   4   | Thomas |  3        | 4000   |
    ++-------+--------+-----------+--------+
    +empId 是这张表单的主关键字
    +
    + +

    Bonus 表单

    + +
    +-------+-------+
    +| empId | bonus |
    ++-------+-------+
    +| 2     | 500   |
    +| 4     | 2000  |
    ++-------+-------+
    +empId 是这张表单的主关键字
    +
    + +

    输出示例:

    + +
    +-------+-------+
    +| name  | bonus |
    ++-------+-------+
    +| John  | null  |
    +| Dan   | 500   |
    +| Brad  | null  |
    ++-------+-------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0578.leetcode578 Get Highest Answer Rate Question-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0578.leetcode578 Get Highest Answer Rate Question-zh.md" new file mode 100644 index 00000000..d5add80d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0578.leetcode578 Get Highest Answer Rate Question-zh.md" @@ -0,0 +1,55 @@ +# [578. 查询回答率最高的问题](https://leetcode-cn.com/problems/get-highest-answer-rate-question) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0578.Get%20Highest%20Answer%20Rate%20Question/README_EN.md) + +## 题目描述 + + + +

    survey_log 表中获得回答率最高的问题,survey_log 表包含这些列:id, action, question_id, answer_id, q_num, timestamp

    + +

    id 表示用户 id;action 有以下几种值:"show","answer","skip";当 action 值为 "answer" 时 answer_id 非空,而 action 值为 "show" 或者 "skip" 时 answer_id 为空;q_num 表示当前会话中问题的编号。

    + +

    请编写 SQL 查询来找到具有最高回答率的问题。

    + +

     

    + +

    示例:

    + +
    输入:
    ++------+-----------+--------------+------------+-----------+------------+
    +| id   | action    | question_id  | answer_id  | q_num     | timestamp  |
    ++------+-----------+--------------+------------+-----------+------------+
    +| 5    | show      | 285          | null       | 1         | 123        |
    +| 5    | answer    | 285          | 124124     | 1         | 124        |
    +| 5    | show      | 369          | null       | 2         | 125        |
    +| 5    | skip      | 369          | null       | 2         | 126        |
    ++------+-----------+--------------+------------+-----------+------------+
    +输出:
    ++-------------+
    +| survey_log  |
    ++-------------+
    +|    285      |
    ++-------------+
    +解释:
    +问题 285 的回答率为 1/1,而问题 369 回答率为 0/1,因此输出 285 。
    +
    + +

     

    + +

    提示:回答率最高的含义是:同一问题编号中回答数占显示数的比例最高。

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0579.leetcode579 Find Cumulative Salary of an Employee-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0579.leetcode579 Find Cumulative Salary of an Employee-zh.md" new file mode 100644 index 00000000..428c83db --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0579.leetcode579 Find Cumulative Salary of an Employee-zh.md" @@ -0,0 +1,95 @@ +# [579. 查询员工的累计薪水](https://leetcode-cn.com/problems/find-cumulative-salary-of-an-employee) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0579.Find%20Cumulative%20Salary%20of%20an%20Employee/README_EN.md) + +## 题目描述 + + + +

    Employee 表保存了一年内的薪水信息。

    + +

    请你编写 SQL 语句,对于每个员工,查询他除最近一个月(即最大月)之外,剩下每个月的近三个月的累计薪水(不足三个月也要计算)。

    + +

    结果请按 Id 升序,然后按 Month 降序显示。

    + +

     

    + +

    示例:
    +输入:

    + +
    +| Id | Month | Salary |
    +|----|-------|--------|
    +| 1  | 1     | 20     |
    +| 2  | 1     | 20     |
    +| 1  | 2     | 30     |
    +| 2  | 2     | 30     |
    +| 3  | 2     | 40     |
    +| 1  | 3     | 40     |
    +| 3  | 3     | 60     |
    +| 1  | 4     | 60     |
    +| 3  | 4     | 70     |
    +
    + +

    输出:

    + +
    +| Id | Month | Salary |
    +|----|-------|--------|
    +| 1  | 3     | 90     |
    +| 1  | 2     | 50     |
    +| 1  | 1     | 20     |
    +| 2  | 1     | 20     |
    +| 3  | 3     | 100    |
    +| 3  | 2     | 40     |
    +
    + +

     

    + +

    解释:

    + +

    员工 '1' 除去最近一个月(月份 '4'),有三个月的薪水记录:月份 '3' 薪水为 40,月份 '2' 薪水为 30,月份 '1' 薪水为 20。

    + +

    所以近 3 个月的薪水累计分别为 (40 + 30 + 20) = 90,(30 + 20) = 50 和 20。

    + +
    +| Id | Month | Salary |
    +|----|-------|--------|
    +| 1  | 3     | 90     |
    +| 1  | 2     | 50     |
    +| 1  | 1     | 20     |
    +
    + +

    员工 '2' 除去最近的一个月(月份 '2')的话,只有月份 '1' 这一个月的薪水记录。

    + +
    +| Id | Month | Salary |
    +|----|-------|--------|
    +| 2  | 1     | 20     |
    +
    + +

    员工 '3' 除去最近一个月(月份 '4')后有两个月,分别为:月份 '3' 薪水为 60 和 月份 '2' 薪水为 40。所以各月的累计情况如下:

    + +
    +| Id | Month | Salary |
    +|----|-------|--------|
    +| 3  | 3     | 100    |
    +| 3  | 2     | 40     |
    +
    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0580.leetcode580 Count Student Number in Departments-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0580.leetcode580 Count Student Number in Departments-zh.md" new file mode 100644 index 00000000..034f0ca9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0580.leetcode580 Count Student Number in Departments-zh.md" @@ -0,0 +1,78 @@ +# [580. 统计各专业学生人数](https://leetcode-cn.com/problems/count-student-number-in-departments) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0580.Count%20Student%20Number%20in%20Departments/README_EN.md) + +## 题目描述 + + + +

    一所大学有 2 个数据表,分别是 student 和 department ,这两个表保存着每个专业的学生数据和院系数据。

    + +

    写一个查询语句,查询 department 表中每个专业的学生人数 (即使没有学生的专业也需列出)。

    + +

    将你的查询结果按照学生人数降序排列。 如果有两个或两个以上专业有相同的学生数目,将这些部门按照部门名字的字典序从小到大排列。

    + +

    student 表格如下:

    + +
    | Column Name  | Type      |
    +|--------------|-----------|
    +| student_id   | Integer   |
    +| student_name | String    |
    +| gender       | Character |
    +| dept_id      | Integer   |
    +
    + +

    其中, student_id 是学生的学号, student_name 是学生的姓名, gender 是学生的性别, dept_id 是学生所属专业的专业编号。

    + +

    department 表格如下:

    + +
    | Column Name | Type    |
    +|-------------|---------|
    +| dept_id     | Integer |
    +| dept_name   | String  |
    +
    + +

    dept_id 是专业编号, dept_name 是专业名字。

    + +

    这里是一个示例输入:
    +student 表格:

    + +
    | student_id | student_name | gender | dept_id |
    +|------------|--------------|--------|---------|
    +| 1          | Jack         | M      | 1       |
    +| 2          | Jane         | F      | 1       |
    +| 3          | Mark         | M      | 2       |
    +
    + +

    department 表格:

    + +
    | dept_id | dept_name   |
    +|---------|-------------|
    +| 1       | Engineering |
    +| 2       | Science     |
    +| 3       | Law         |
    +
    + +

    示例输出为:

    + +
    | dept_name   | student_number |
    +|-------------|----------------|
    +| Engineering | 2              |
    +| Science     | 1              |
    +| Law         | 0              |
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0581.leetcode581 Shortest Unsorted Continuous Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0581.leetcode581 Shortest Unsorted Continuous Subarray-zh.md" new file mode 100644 index 00000000..bf5a2232 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0581.leetcode581 Shortest Unsorted Continuous Subarray-zh.md" @@ -0,0 +1,83 @@ +# [581. 最短无序连续子数组](https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0581.Shortest%20Unsorted%20Continuous%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

    + +

    请你找出符合题意的 最短 子数组,并输出它的长度。

    + +

     

    + +
    +
    +

    示例 1:

    + +
    +输入:nums = [2,6,4,8,10,9,15]
    +输出:5
    +解释:你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,4]
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:nums = [1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -105 <= nums[i] <= 105
    • +
    + +

     

    + +

    进阶:你可以设计一个时间复杂度为 O(n) 的解决方案吗?

    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0582.leetcode582 Kill Process-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0582.leetcode582 Kill Process-zh.md" new file mode 100644 index 00000000..2dddf3f4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0582.leetcode582 Kill Process-zh.md" @@ -0,0 +1,77 @@ +# [582. 杀掉进程](https://leetcode-cn.com/problems/kill-process) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0582.Kill%20Process/README_EN.md) + +## 题目描述 + + + +

    系统中存在 n 个进程,形成一个有根树结构。给你两个整数数组 pidppid ,其中 pid[i] 是第 i 个进程的 ID ,ppid[i] 是第 i 个进程的父进程 ID 。

    + +

    每一个进程只有 一个父进程 ,但是可能会有 一个或者多个子进程 。只有一个进程的 ppid[i] = 0 ,意味着这个进程 没有父进程

    + +

    当一个进程 被杀掉 的时候,它所有的子进程和后代进程都要被杀掉。

    + +

    给你一个整数 kill 表示要杀掉​​进程的 ID ,返回杀掉该进程后的所有进程 ID 的列表。可以按 任意顺序 返回答案。

    +  + +

    示例 1:

    + +
    +输入:pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
    +输出:[5,10]
    +解释:涂为红色的进程是应该被杀掉的进程。
    +
    + +

    示例 2:

    + +
    +输入:pid = [1], ppid = [0], kill = 1
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == pid.length
    • +
    • n == ppid.length
    • +
    • 1 <= n <= 5 * 104
    • +
    • 1 <= pid[i] <= 5 * 104
    • +
    • 0 <= ppid[i] <= 5 * 104
    • +
    • 仅有一个进程没有父进程
    • +
    • pid 中的所有值 互不相同
    • +
    • 题目数据保证 killpid
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0583.leetcode583 Delete Operation for Two Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0583.leetcode583 Delete Operation for Two Strings-zh.md" new file mode 100644 index 00000000..2ace8f56 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0583.leetcode583 Delete Operation for Two Strings-zh.md" @@ -0,0 +1,58 @@ +# [583. 两个字符串的删除操作](https://leetcode-cn.com/problems/delete-operation-for-two-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0583.Delete%20Operation%20for%20Two%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。

    + +

     

    + +

    示例:

    + +
    输入: "sea", "eat"
    +输出: 2
    +解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 给定单词的长度不超过500。
    2. +
    3. 给定单词中的字符只含有小写字母。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0584.leetcode584 Find Customer Referee-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0584.leetcode584 Find Customer Referee-zh.md" new file mode 100644 index 00000000..93877428 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0584.leetcode584 Find Customer Referee-zh.md" @@ -0,0 +1,52 @@ +# [584. 寻找用户推荐人](https://leetcode-cn.com/problems/find-customer-referee) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0584.Find%20Customer%20Referee/README_EN.md) + +## 题目描述 + + + +

    给定表 customer ,里面保存了所有客户信息和他们的推荐人。

    + +
    ++------+------+-----------+
    +| id   | name | referee_id|
    ++------+------+-----------+
    +|    1 | Will |      NULL |
    +|    2 | Jane |      NULL |
    +|    3 | Alex |         2 |
    +|    4 | Bill |      NULL |
    +|    5 | Zack |         1 |
    +|    6 | Mark |         2 |
    ++------+------+-----------+
    +
    + +

    写一个查询语句,返回一个客户列表,列表中客户的推荐人的编号都 不是 2。

    + +

    对于上面的示例数据,结果为:

    + +
    ++------+
    +| name |
    ++------+
    +| Will |
    +| Jane |
    +| Bill |
    +| Zack |
    ++------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0585.leetcode585 Investments in 2016-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0585.leetcode585 Investments in 2016-zh.md" new file mode 100644 index 00000000..78d560d3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0585.leetcode585 Investments in 2016-zh.md" @@ -0,0 +1,73 @@ +# [585. 2016年的投资](https://leetcode-cn.com/problems/investments-in-2016) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0585.Investments%20in%202016/README_EN.md) + +## 题目描述 + + + +

    写一个查询语句,将 2016 年 (TIV_2016) 所有成功投资的金额加起来,保留 2 位小数。

    + +

    对于一个投保人,他在 2016 年成功投资的条件是:

    + +
      +
    1. 他在 2015 年的投保额 (TIV_2015) 至少跟一个其他投保人在 2015 年的投保额相同。
    2. +
    3. 他所在的城市必须与其他投保人都不同(也就是说维度和经度不能跟其他任何一个投保人完全相同)。
    4. +
    + +

    输入格式:
    +表 insurance 格式如下:

    + +
    | Column Name | Type          |
    +|-------------|---------------|
    +| PID         | INTEGER(11)   |
    +| TIV_2015    | NUMERIC(15,2) |
    +| TIV_2016    | NUMERIC(15,2) |
    +| LAT         | NUMERIC(5,2)  |
    +| LON         | NUMERIC(5,2)  |
    +
    + +

    PID 字段是投保人的投保编号, TIV_2015 是该投保人在2015年的总投保金额, TIV_2016 是该投保人在2016年的投保金额, LAT 是投保人所在城市的维度, LON 是投保人所在城市的经度。

    + +

    样例输入

    + +
    | PID | TIV_2015 | TIV_2016 | LAT | LON |
    +|-----|----------|----------|-----|-----|
    +| 1   | 10       | 5        | 10  | 10  |
    +| 2   | 20       | 20       | 20  | 20  |
    +| 3   | 10       | 30       | 20  | 20  |
    +| 4   | 10       | 40       | 40  | 40  |
    +
    + +

    样例输出

    + +
    | TIV_2016 |
    +|----------|
    +| 45.00    |
    +
    + +

    解释

    + +
    就如最后一个投保人,第一个投保人同时满足两个条件:
    +1. 他在 2015 年的投保金额 TIV_2015 为 '10' ,与第三个和第四个投保人在 2015 年的投保金额相同。
    +2. 他所在城市的经纬度是独一无二的。
    +
    +第二个投保人两个条件都不满足。他在 2015 年的投资 TIV_2015 与其他任何投保人都不相同。
    +且他所在城市的经纬度与第三个投保人相同。基于同样的原因,第三个投保人投资失败。
    +
    +所以返回的结果是第一个投保人和最后一个投保人的 TIV_2016 之和,结果是 45 。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0586.leetcode586 Customer Placing the Largest Number of Orders-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0586.leetcode586 Customer Placing the Largest Number of Orders-zh.md" new file mode 100644 index 00000000..a2acf924 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0586.leetcode586 Customer Placing the Largest Number of Orders-zh.md" @@ -0,0 +1,64 @@ +# [586. 订单最多的客户](https://leetcode-cn.com/problems/customer-placing-the-largest-number-of-orders) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0586.Customer%20Placing%20the%20Largest%20Number%20of%20Orders/README_EN.md) + +## 题目描述 + + + +

    在表 orders 中找到订单数最多客户对应的 customer_number 。

    + +

    数据保证订单数最多的顾客恰好只有一位。

    + +

    表 orders 定义如下:

    + +
    | Column            | Type      |
    +|-------------------|-----------|
    +| order_number (PK) | int       |
    +| customer_number   | int       |
    +| order_date        | date      |
    +| required_date     | date      |
    +| shipped_date      | date      |
    +| status            | char(15)  |
    +| comment           | char(200) |
    +
    + +

    样例输入

    + +
    | order_number | customer_number | order_date | required_date | shipped_date | status | comment |
    +|--------------|-----------------|------------|---------------|--------------|--------|---------|
    +| 1            | 1               | 2017-04-09 | 2017-04-13    | 2017-04-12   | Closed |         |
    +| 2            | 2               | 2017-04-15 | 2017-04-20    | 2017-04-18   | Closed |         |
    +| 3            | 3               | 2017-04-16 | 2017-04-25    | 2017-04-20   | Closed |         |
    +| 4            | 3               | 2017-04-18 | 2017-04-28    | 2017-04-25   | Closed |         |
    +
    + +

    样例输出

    + +
    | customer_number |
    +|-----------------|
    +| 3               |
    +
    + +

    解释

    + +
    customer_number 为 '3' 的顾客有两个订单,比顾客 '1' 或者 '2' 都要多,因为他们只有一个订单
    +所以结果是该顾客的 customer_number ,也就是 3 。
    +
    + +

    进阶: 如果有多位顾客订单数并列最多,你能找到他们所有的 customer_number 吗?

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0587.leetcode587 Erect the Fence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0587.leetcode587 Erect the Fence-zh.md" new file mode 100644 index 00000000..df70b940 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0587.leetcode587 Erect the Fence-zh.md" @@ -0,0 +1,95 @@ +# [587. 安装栅栏](https://leetcode-cn.com/problems/erect-the-fence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0587.Erect%20the%20Fence/README_EN.md) + +## 题目描述 + + + +

    在一个二维的花园中,有一些用 (x, y) 坐标表示的树。由于安装费用十分昂贵,你的任务是先用最短的绳子围起所有的树。只有当所有的树都被绳子包围时,花园才能围好栅栏。你需要找到正好位于栅栏边界上的树的坐标。

    + + + +

     

    + + + +

    示例 1:

    + + + +
    输入: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
    +
    +输出: [[1,1],[2,0],[4,2],[3,3],[2,4]]
    +
    +解释:
    +
    +
    +
    +
    + + + +

    示例 2:

    + + + +
    输入: [[1,2],[2,2],[4,2]]
    +
    +输出: [[1,2],[2,2],[4,2]]
    +
    +解释:
    +
    +
    +
    +即使树都在一条直线上,你也需要先用绳子包围它们。
    +
    +
    + + + +

     

    + + + +

    注意:

    + + + +
      +
    1. 所有的树应当被围在一起。你不能剪断绳子来包围树或者把树分成一组以上。
    2. +
    3. 输入的整数在 0 到 100 之间。
    4. +
    5. 花园至少有一棵树。
    6. +
    7. 所有树的坐标都是不同的。
    8. +
    9. 输入的点没有顺序。输出顺序也没有要求。
    10. +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0588.leetcode588 Design In-Memory File System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0588.leetcode588 Design In-Memory File System-zh.md" new file mode 100644 index 00000000..d022de2a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0588.leetcode588 Design In-Memory File System-zh.md" @@ -0,0 +1,73 @@ +# [588. 设计内存文件系统](https://leetcode-cn.com/problems/design-in-memory-file-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0588.Design%20In-Memory%20File%20System/README_EN.md) + +## 题目描述 + + + +

    设计一个内存文件系统,模拟以下功能:

    + +

    ls: 以字符串的格式输入一个路径。如果它是一个文件的路径,那么函数返回一个列表,仅包含这个文件的名字。如果它是一个文件夹的的路径,那么返回该 文件夹内 的所有文件和子文件夹的名字。你的返回结果(包括文件和子文件夹)应该按字典序排列。

    + +

    mkdir:输入一个当前不存在的 文件夹路径 ,你需要根据路径名创建一个新的文件夹。如果有上层文件夹路径不存在,那么你也应该将它们全部创建。这个函数的返回类型为 void 。

    + +

    addContentToFile: 输入字符串形式的 文件路径 和 文件内容 。如果文件不存在,你需要创建包含给定文件内容的文件。如果文件已经存在,那么你需要将给定的文件内容 追加 在原本内容的后面。这个函数的返回类型为 void 。

    + +

    readContentFromFile: 输入 文件路径 ,以字符串形式返回该文件的 内容 。

    + +

     

    + +

    示例:

    + +
    输入: 
    +["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"]
    +[[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]]
    +
    +输出:
    +[null,[],null,null,["a"],"hello"]
    +
    +解释:
    +filesystem
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 你可以假定所有文件和文件夹的路径都是绝对路径,除非是根目录 / 自身,其他路径都是以 / 开头且 以 / 结束。
    2. +
    3. 你可以假定所有操作的参数都是有效的,即用户不会获取不存在文件的内容,或者获取不存在文件夹和文件的列表。
    4. +
    5. 你可以假定所有文件夹名字和文件名字都只包含小写字母,且同一文件夹下不会有相同名字的文件夹或文件。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0589.leetcode589 N-ary Tree Preorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0589.leetcode589 N-ary Tree Preorder Traversal-zh.md" new file mode 100644 index 00000000..c43b3873 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0589.leetcode589 N-ary Tree Preorder Traversal-zh.md" @@ -0,0 +1,98 @@ +# [589. N 叉树的前序遍历](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0589.N-ary%20Tree%20Preorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给定一个 N 叉树,返回其节点值的 前序遍历

    + +

    N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

    + +
    +
    +

     

    + +

    进阶:

    + +

    递归法很简单,你可以使用迭代法完成此题吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,null,3,2,4,null,5,6]
    +输出:[1,3,5,6,2,4]
    +
    +示例 2: + +

    + +
    +输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]
    +
    + +

     

    + +

    提示:

    + +
      +
    • N 叉树的高度小于或等于 1000
    • +
    • 节点总数在范围 [0, 10^4]
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def preorder(self, root: 'Node') -> List[int]: + if not root: + return [] + def PO(root): + res.append(root.val) + for i in root.children: + PO(i) + res=[] + PO(root) + return res +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0590.leetcode590 N-ary Tree Postorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0590.leetcode590 N-ary Tree Postorder Traversal-zh.md" new file mode 100644 index 00000000..02c057ef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0590.leetcode590 N-ary Tree Postorder Traversal-zh.md" @@ -0,0 +1,102 @@ +# [590. N 叉树的后序遍历](https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0590.N-ary%20Tree%20Postorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给定一个 N 叉树,返回其节点值的 后序遍历

    + +

    N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

    + +
    +
    +

     

    + +

    进阶:

    + +

    递归法很简单,你可以使用迭代法完成此题吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,null,3,2,4,null,5,6]
    +输出:[5,6,3,2,4,1]
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • N 叉树的高度小于或等于 1000
    • +
    • 节点总数在范围 [0, 10^4]
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" +class Solution: + def postorder(self, root: 'Node') -> List[int]: + if not root: + return [] + def PO(root): + if root==None: + return res + else: + for i in root.children: + PO(i) + res.append(i.val) + res=[] + PO(root) + res.append(root.val) + return res +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0591.leetcode591 Tag Validator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0591.leetcode591 Tag Validator-zh.md" new file mode 100644 index 00000000..1addb8ab --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0591.leetcode591 Tag Validator-zh.md" @@ -0,0 +1,123 @@ +# [591. 标签验证器](https://leetcode-cn.com/problems/tag-validator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0591.Tag%20Validator/README_EN.md) + +## 题目描述 + + + +

    给定一个表示代码片段的字符串,你需要实现一个验证器来解析这段代码,并返回它是否合法。合法的代码片段需要遵守以下的所有规则:

    + +
      +
    1. 代码必须被合法的闭合标签包围。否则,代码是无效的。
    2. +
    3. 闭合标签(不一定合法)要严格符合格式:<TAG_NAME>TAG_CONTENT</TAG_NAME>。其中,<TAG_NAME>是起始标签,</TAG_NAME>是结束标签。起始和结束标签中的 TAG_NAME 应当相同。当且仅当 TAG_NAME 和 TAG_CONTENT 都是合法的,闭合标签才是合法的
    4. +
    5. 合法的 TAG_NAME 仅含有大写字母,长度在范围 [1,9] 之间。否则,该 TAG_NAME 是不合法的
    6. +
    7. 合法的 TAG_CONTENT 可以包含其他合法的闭合标签cdata (请参考规则7)和任意字符(注意参考规则1)除了不匹配的<、不匹配的起始和结束标签、不匹配的或带有不合法 TAG_NAME 的闭合标签。否则,TAG_CONTENT 是不合法的
    8. +
    9. 一个起始标签,如果没有具有相同 TAG_NAME 的结束标签与之匹配,是不合法的。反之亦然。不过,你也需要考虑标签嵌套的问题。
    10. +
    11. 一个<,如果你找不到一个后续的>与之匹配,是不合法的。并且当你找到一个<</时,所有直到下一个>的前的字符,都应当被解析为 TAG_NAME(不一定合法)。
    12. +
    13. cdata 有如下格式:<![CDATA[CDATA_CONTENT]]>CDATA_CONTENT 的范围被定义成 <![CDATA[ 和后续的第一个 ]]>之间的字符。
    14. +
    15. CDATA_CONTENT 可以包含任意字符。cdata 的功能是阻止验证器解析CDATA_CONTENT,所以即使其中有一些字符可以被解析为标签(无论合法还是不合法),也应该将它们视为常规字符
    16. +
    + +

    合法代码的例子:

    + +
    +输入: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"
    +
    +输出: True
    +
    +解释: 
    +
    +代码被包含在了闭合的标签内: <DIV> 和 </DIV> 。
    +
    +TAG_NAME 是合法的,TAG_CONTENT 包含了一些字符和 cdata 。 
    +
    +即使 CDATA_CONTENT 含有不匹配的起始标签和不合法的 TAG_NAME,它应该被视为普通的文本,而不是标签。
    +
    +所以 TAG_CONTENT 是合法的,因此代码是合法的。最终返回True。
    +
    +
    +输入: "<DIV>>>  ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"
    +
    +输出: True
    +
    +解释:
    +
    +我们首先将代码分割为: start_tag|tag_content|end_tag 。
    +
    +start_tag -> "<DIV>"
    +
    +end_tag -> "</DIV>"
    +
    +tag_content 也可被分割为: text1|cdata|text2 。
    +
    +text1 -> ">>  ![cdata[]] "
    +
    +cdata -> "<![CDATA[<div>]>]]>" ,其中 CDATA_CONTENT 为 "<div>]>"
    +
    +text2 -> "]]>>]"
    +
    +
    +start_tag "<DIV>>>" 的原因参照规则 6 。
    +cdata "<![CDATA[<div>]>]]>]]>" 的原因参照规则 7 。
    +
    + +

    不合法代码的例子:

    + +
    +输入: "<A>  <B> </A>   </B>"
    +输出: False
    +解释: 不合法。如果 "<A>" 是闭合的,那么 "<B>" 一定是不匹配的,反之亦然。
    +
    +输入: "<DIV>  div tag is not closed  <DIV>"
    +输出: False
    +
    +输入: "<DIV>  unmatched <  </DIV>"
    +输出: False
    +
    +输入: "<DIV> closed tags with invalid tag name  <b>123</b> </DIV>"
    +输出: False
    +
    +输入: "<DIV> unmatched tags with invalid tag name  </1234567890> and <CDATA[[]]>  </DIV>"
    +输出: False
    +
    +输入: "<DIV>  unmatched start tag <B>  and unmatched end tag </C>  </DIV>"
    +输出: False
    +
    + +

    注意:

    + +
      +
    1. 为简明起见,你可以假设输入的代码(包括提到的任意字符)只包含数字, 字母, '<','>','/','!','[',']'' '
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0592.leetcode592 Fraction Addition and Subtraction-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0592.leetcode592 Fraction Addition and Subtraction-zh.md" new file mode 100644 index 00000000..eaa474f4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0592.leetcode592 Fraction Addition and Subtraction-zh.md" @@ -0,0 +1,78 @@ +# [592. 分数加减运算](https://leetcode-cn.com/problems/fraction-addition-and-subtraction) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0592.Fraction%20Addition%20and%20Subtraction/README_EN.md) + +## 题目描述 + + + +

    给定一个表示分数加减运算表达式的字符串,你需要返回一个字符串形式的计算结果。 这个结果应该是不可约分的分数,即最简分数。 如果最终结果是一个整数,例如 2,你需要将它转换成分数形式,其分母为 1。所以在上述例子中, 2 应该被转换为 2/1

    + +

    示例 1:

    + +
    +输入:"-1/2+1/2"
    +输出: "0/1"
    +
    + +

     示例 2:

    + +
    +输入:"-1/2+1/2+1/3"
    +输出: "1/3"
    +
    + +

    示例 3:

    + +
    +输入:"1/3-1/2"
    +输出: "-1/6"
    +
    + +

    示例 4:

    + +
    +输入:"5/3+1/3"
    +输出: "2/1"
    +
    + +

    说明:

    + +
      +
    1. 输入和输出字符串只包含 '0' 到 '9' 的数字,以及 '/', '+' 和 '-'。 
    2. +
    3. 输入和输出分数格式均为 ±分子/分母。如果输入的第一个分数或者输出的分数是正数,则 '+' 会被省略掉。
    4. +
    5. 输入只包含合法的最简分数,每个分数的分子分母的范围是  [1,10]。 如果分母是1,意味着这个分数实际上是一个整数。
    6. +
    7. 输入的分数个数范围是 [1,10]。
    8. +
    9. 最终结果的分子与分母保证是 32 位整数范围内的有效整数。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0593.leetcode593 Valid Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0593.leetcode593 Valid Square-zh.md" new file mode 100644 index 00000000..54c7fe25 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0593.leetcode593 Valid Square-zh.md" @@ -0,0 +1,59 @@ +# [593. 有效的正方形](https://leetcode-cn.com/problems/valid-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0593.Valid%20Square/README_EN.md) + +## 题目描述 + + + +

    给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。

    + +

    一个点的坐标(x,y)由一个有两个整数的整数数组表示。

    + +

    示例:

    + +
    +输入: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
    +输出: True
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 所有输入整数都在 [-10000,10000] 范围内。
    2. +
    3. 一个有效的正方形有四个等长的正长和四个等角(90度角)。
    4. +
    5. 输入点没有顺序。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0594.leetcode594 Longest Harmonious Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0594.leetcode594 Longest Harmonious Subsequence-zh.md" new file mode 100644 index 00000000..6bf6e788 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0594.leetcode594 Longest Harmonious Subsequence-zh.md" @@ -0,0 +1,77 @@ +# [594. 最长和谐子序列](https://leetcode-cn.com/problems/longest-harmonious-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0594.Longest%20Harmonious%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1

    + +

    现在,给你一个整数数组 nums ,请你在所有可能的子序列中找到最长的和谐子序列的长度。

    + +

    数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,2,2,5,2,3,7]
    +输出:5
    +解释:最长的和谐子序列是 [3,2,2,2,3]
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,4]
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,1,1,1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 2 * 104
    • +
    • -109 <= nums[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0595.leetcode595 Big Countries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0595.leetcode595 Big Countries-zh.md" new file mode 100644 index 00000000..e5a2bb93 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0595.leetcode595 Big Countries-zh.md" @@ -0,0 +1,56 @@ +# [595. 大的国家](https://leetcode-cn.com/problems/big-countries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0595.Big%20Countries/README_EN.md) + +## 题目描述 + + + +

    这里有张 World

    + +
    ++-----------------+------------+------------+--------------+---------------+
    +| name            | continent  | area       | population   | gdp           |
    ++-----------------+------------+------------+--------------+---------------+
    +| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
    +| Albania         | Europe     | 28748      | 2831741      | 12960000      |
    +| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
    +| Andorra         | Europe     | 468        | 78115        | 3712000       |
    +| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
    ++-----------------+------------+------------+--------------+---------------+
    +
    + +

    如果一个国家的面积超过 300 万平方公里,或者人口超过 2500 万,那么这个国家就是大国家。

    + +

    编写一个 SQL 查询,输出表中所有大国家的名称、人口和面积。

    + +

    例如,根据上表,我们应该输出:

    + +
    ++--------------+-------------+--------------+
    +| name         | population  | area         |
    ++--------------+-------------+--------------+
    +| Afghanistan  | 25500100    | 652230       |
    +| Algeria      | 37100000    | 2381741      |
    ++--------------+-------------+--------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +``` +SELECT name, + population, + area +FROM World +WHERE area>3000000 + OR population>25000000 +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0596.leetcode596 Classes More Than 5 Students-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0596.leetcode596 Classes More Than 5 Students-zh.md" new file mode 100644 index 00000000..c8236048 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0596.leetcode596 Classes More Than 5 Students-zh.md" @@ -0,0 +1,67 @@ +# [596. 超过5名学生的课](https://leetcode-cn.com/problems/classes-more-than-5-students) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0596.Classes%20More%20Than%205%20Students/README_EN.md) + +## 题目描述 + + + +

    有一个courses 表 ,有: student (学生) class (课程)

    + +

    请列出所有超过或等于5名学生的课。

    + +

    例如,表:

    + +
    +---------+------------+
    +| student | class      |
    ++---------+------------+
    +| A       | Math       |
    +| B       | English    |
    +| C       | Math       |
    +| D       | Biology    |
    +| E       | Math       |
    +| F       | Computer   |
    +| G       | Math       |
    +| H       | Math       |
    +| I       | Math       |
    ++---------+------------+
    +
    + +

    应该输出:

    + +
    +---------+
    +| class   |
    ++---------+
    +| Math    |
    ++---------+
    +
    + +

     

    + +

    提示:

    + +
      +
    • 学生在每个课中不应被重复计算。
    • +
    + + +## 解法 + + + + + +### **SQL** + +``` +select + c.class +from + (select distinct courses.student, courses.class from courses) c +group by + c.class +having + count(c.class)>=5 +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0597.leetcode597 Friend Requests I Overall Acceptance Rate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0597.leetcode597 Friend Requests I Overall Acceptance Rate-zh.md" new file mode 100644 index 00000000..75dd28f2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0597.leetcode597 Friend Requests I Overall Acceptance Rate-zh.md" @@ -0,0 +1,109 @@ +# [597. 好友申请 I:总体通过率](https://leetcode-cn.com/problems/friend-requests-i-overall-acceptance-rate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0597.Friend%20Requests%20I%20Overall%20Acceptance%20Rate/README_EN.md) + +## 题目描述 + + + +

    在 Facebook 或者 Twitter 这样的社交应用中,人们经常会发好友申请也会收到其他人的好友申请。

    + +

     

    + +

    表:FriendRequest

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| sender_id      | int     |
    +| send_to_id     | int     |
    +| request_date   | date    |
    ++----------------+---------+
    +此表没有主键,它可能包含重复项。
    +该表包含发送请求的用户的 ID ,接受请求的用户的 ID 以及请求的日期。
    +
    + +

    表:RequestAccepted

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| requester_id   | int     |
    +| accepter_id    | int     |
    +| accept_date    | date    |
    ++----------------+---------+
    +此表没有主键,它可能包含重复项。
    +该表包含发送请求的用户的 ID ,接受请求的用户的 ID 以及请求通过的日期。
    + +

     

    + +

    写一个查询语句,求出好友申请的通过率,用 2 位小数表示。通过率由接受好友申请的数目除以申请总数。

    + +

    提示:

    + +
      +
    • 通过的好友申请不一定都在表 friend_request 中。你只需要统计总的被通过的申请数(不管它们在不在表 FriendRequest 中),并将它除以申请总数,得到通过率
    • +
    • 一个好友申请发送者有可能会给接受者发几条好友申请,也有可能一个好友申请会被通过好几次。这种情况下,重复的好友申请只统计一次。
    • +
    • 如果一个好友申请都没有,通过率为 0.00 。
    • +
    + +

     

    + +

    查询结果应该如下例所示:

    + +
    +FriendRequest 表:
    ++-----------+------------+--------------+
    +| sender_id | send_to_id | request_date |
    ++-----------+------------+--------------+
    +| 1         | 2          | 2016/06/01   |
    +| 1         | 3          | 2016/06/01   |
    +| 1         | 4          | 2016/06/01   |
    +| 2         | 3          | 2016/06/02   |
    +| 3         | 4          | 2016/06/09   |
    ++-----------+------------+--------------+
    +
    +RequestAccepted 表:
    ++--------------+-------------+-------------+
    +| requester_id | accepter_id | accept_date |
    ++--------------+-------------+-------------+
    +| 1            | 2           | 2016/06/03  |
    +| 1            | 3           | 2016/06/08  |
    +| 2            | 3           | 2016/06/08  |
    +| 3            | 4           | 2016/06/09  |
    +| 3            | 4           | 2016/06/10  |
    ++--------------+-------------+-------------+
    +
    +Result 表:
    ++-------------+
    +| accept_rate |
    ++-------------+
    +| 0.8         |
    ++-------------+
    +总共有 5 个请求,有 4 个不同的通过请求,所以通过率是 0.80
    + +

     

    + +

    进阶:

    + +
      +
    • 你能写一个查询语句得到每个月的通过率吗?
    • +
    • 你能求出每一天的累计通过率吗?
    • +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0598.leetcode598 Range Addition II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0598.leetcode598 Range Addition II-zh.md" new file mode 100644 index 00000000..a6a8a78c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0598.leetcode598 Range Addition II-zh.md" @@ -0,0 +1,78 @@ +# [598. 范围求和 II](https://leetcode-cn.com/problems/range-addition-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0598.Range%20Addition%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个初始元素全部为 0,大小为 m*n 的矩阵 以及在 上的一系列更新操作。

    + +

    操作用二维数组表示,其中的每个操作用一个含有两个正整数 ab 的数组表示,含义是将所有符合 0 <= i < a 以及 0 <= j < b 的元素 M[i][j] 的值都增加 1

    + +

    在执行给定的一系列操作后,你需要返回矩阵中含有最大整数的元素个数。

    + +

    示例 1:

    + +
    +输入: 
    +m = 3, n = 3
    +operations = [[2,2],[3,3]]
    +输出: 4
    +解释: 
    +初始状态, M = 
    +[[0, 0, 0],
    + [0, 0, 0],
    + [0, 0, 0]]
    +
    +执行完操作 [2,2] 后, M = 
    +[[1, 1, 0],
    + [1, 1, 0],
    + [0, 0, 0]]
    +
    +执行完操作 [3,3] 后, M = 
    +[[2, 2, 1],
    + [2, 2, 1],
    + [1, 1, 1]]
    +
    +M 中最大的整数是 2, 而且 M 中有4个值为2的元素。因此返回 4。
    +
    + +

    注意:

    + +
      +
    1. m 和 n 的范围是 [1,40000]。
    2. +
    3. a 的范围是 [1,m],b 的范围是 [1,n]。
    4. +
    5. 操作数目不超过 10000。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0599.leetcode599 Minimum Index Sum of Two Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0599.leetcode599 Minimum Index Sum of Two Lists-zh.md" new file mode 100644 index 00000000..1fc0e67f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0599.leetcode599 Minimum Index Sum of Two Lists-zh.md" @@ -0,0 +1,69 @@ +# [599. 两个列表的最小索引总和](https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0500-0599/0599.Minimum%20Index%20Sum%20of%20Two%20Lists/README_EN.md) + +## 题目描述 + + + +

    假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。

    + +

    你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。

    + +

    示例 1:

    + +
    输入:
    +["Shogun", "Tapioca Express", "Burger King", "KFC"]
    +["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
    +输出: ["Shogun"]
    +解释: 他们唯一共同喜爱的餐厅是“Shogun”。
    +
    + +

    示例 2:

    + +
    输入:
    +["Shogun", "Tapioca Express", "Burger King", "KFC"]
    +["KFC", "Shogun", "Burger King"]
    +输出: ["Shogun"]
    +解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。
    +
    + +

    提示:

    + +
      +
    1. 两个列表的长度范围都在 [1, 1000]内。
    2. +
    3. 两个列表中的字符串的长度将在[1,30]的范围内。
    4. +
    5. 下标从0开始,到列表的长度减1。
    6. +
    7. 两个列表都没有重复的元素。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0600.leetcode600 Non-negative Integers without Consecutive Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0600.leetcode600 Non-negative Integers without Consecutive Ones-zh.md" new file mode 100644 index 00000000..3924c376 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0600.leetcode600 Non-negative Integers without Consecutive Ones-zh.md" @@ -0,0 +1,56 @@ +# [600. 不含连续1的非负整数](https://leetcode-cn.com/problems/non-negative-integers-without-consecutive-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0600.Non-negative%20Integers%20without%20Consecutive%20Ones/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 n,找出小于或等于 n 的非负整数中,其二进制表示不包含 连续的1 的个数。

    + +

    示例 1:

    + +
    输入: 5
    +输出: 5
    +解释: 
    +下面是带有相应二进制表示的非负整数<= 5:
    +0 : 0
    +1 : 1
    +2 : 10
    +3 : 11
    +4 : 100
    +5 : 101
    +其中,只有整数3违反规则(有两个连续的1),其他5个满足规则。
    + +

    说明: 1 <= n <= 109

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0601.leetcode601 Human Traffic of Stadium-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0601.leetcode601 Human Traffic of Stadium-zh.md" new file mode 100644 index 00000000..46f3cff6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0601.leetcode601 Human Traffic of Stadium-zh.md" @@ -0,0 +1,93 @@ +# [601. 体育馆的人流量](https://leetcode-cn.com/problems/human-traffic-of-stadium) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0601.Human%20Traffic%20of%20Stadium/README_EN.md) + +## 题目描述 + + + +表:Stadium +
    +
    +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| visit_date    | date    |
    +| people        | int     |
    ++---------------+---------+
    +visit_date 是表的主键
    +每日人流量信息被记录在这三列信息中:序号 (id)、日期 (visit_date)、 人流量 (people)
    +每天只有一行记录,日期随着 id 的增加而增加
    +
    + +

     

    + +

    编写一个 SQL 查询以找出每行的人数大于或等于 100id 连续的三行或更多行记录。

    + +

    返回按 visit_date 升序排列的结果表。

    + +

    查询结果格式如下所示。

    + +
    +Stadium table:
    ++------+------------+-----------+
    +| id   | visit_date | people    |
    ++------+------------+-----------+
    +| 1    | 2017-01-01 | 10        |
    +| 2    | 2017-01-02 | 109       |
    +| 3    | 2017-01-03 | 150       |
    +| 4    | 2017-01-04 | 99        |
    +| 5    | 2017-01-05 | 145       |
    +| 6    | 2017-01-06 | 1455      |
    +| 7    | 2017-01-07 | 199       |
    +| 8    | 2017-01-09 | 188       |
    ++------+------------+-----------+
    +
    +Result table:
    ++------+------------+-----------+
    +| id   | visit_date | people    |
    ++------+------------+-----------+
    +| 5    | 2017-01-05 | 145       |
    +| 6    | 2017-01-06 | 1455      |
    +| 7    | 2017-01-07 | 199       |
    +| 8    | 2017-01-09 | 188       |
    ++------+------------+-----------+
    +id 为 5、6、7、8 的四行 id 连续,并且每行都有 >= 100 的人数记录。
    +请注意,即使第 7 行和第 8 行的 visit_date 不是连续的,输出也应当包含第 8 行,因为我们只需要考虑 id 连续的记录。
    +不输出 id 为 2 和 3 的行,因为至少需要三条 id 连续的记录。
    +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0602.leetcode602 Friend Requests II Who Has the Most Friends-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0602.leetcode602 Friend Requests II Who Has the Most Friends-zh.md" new file mode 100644 index 00000000..a2172ac0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0602.leetcode602 Friend Requests II Who Has the Most Friends-zh.md" @@ -0,0 +1,64 @@ +# [602. 好友申请 II :谁有最多的好友](https://leetcode-cn.com/problems/friend-requests-ii-who-has-the-most-friends) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0602.Friend%20Requests%20II%20Who%20Has%20the%20Most%20Friends/README_EN.md) + +## 题目描述 + + + +

    在 Facebook 或者 Twitter 这样的社交应用中,人们经常会发好友申请也会收到其他人的好友申请。

    + +

     

    + +

    表 request_accepted 存储了所有好友申请通过的数据记录,其中, requester_id 和 accepter_id 都是用户的编号。

    + +

     

    + +
    | requester_id | accepter_id | accept_date|
    +|--------------|-------------|------------|
    +| 1            | 2           | 2016_06-03 |
    +| 1            | 3           | 2016-06-08 |
    +| 2            | 3           | 2016-06-08 |
    +| 3            | 4           | 2016-06-09 |
    +
    + +

    写一个查询语句,求出谁拥有最多的好友和他拥有的好友数目。对于上面的样例数据,结果为:

    + +
    | id | num |
    +|----|-----|
    +| 3  | 3   |
    +
    + +

    注意:

    + +
      +
    • 保证拥有最多好友数目的只有 1 个人。
    • +
    • 好友申请只会被接受一次,所以不会有 requester_id 和 accepter_id 值都相同的重复记录。
    • +
    + +

     

    + +

    解释:

    + +

    编号为 '3' 的人是编号为 '1','2' 和 '4' 的好友,所以他总共有 3 个好友,比其他人都多。

    + +

     

    + +

    进阶:

    + +

    在真实世界里,可能会有多个人拥有好友数相同且最多,你能找到所有这些人吗?

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0603.leetcode603 Consecutive Available Seats-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0603.leetcode603 Consecutive Available Seats-zh.md" new file mode 100644 index 00000000..3bc7592d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0603.leetcode603 Consecutive Available Seats-zh.md" @@ -0,0 +1,55 @@ +# [603. 连续空余座位](https://leetcode-cn.com/problems/consecutive-available-seats) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0603.Consecutive%20Available%20Seats/README_EN.md) + +## 题目描述 + + + +

    几个朋友来到电影院的售票处,准备预约连续空余座位。

    + +

    你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?

    + +
    | seat_id | free |
    +|---------|------|
    +| 1       | 1    |
    +| 2       | 0    |
    +| 3       | 1    |
    +| 4       | 1    |
    +| 5       | 1    |
    +
    + +

     

    + +

    对于如上样例,你的查询语句应该返回如下结果。

    + +

     

    + +
    | seat_id |
    +|---------|
    +| 3       |
    +| 4       |
    +| 5       |
    +
    + +

    注意:

    + +
      +
    • seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。
    • +
    • 连续空余座位的定义是大于等于 2 个连续空余的座位。
    • +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0604.leetcode604 Design Compressed String Iterator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0604.leetcode604 Design Compressed String Iterator-zh.md" new file mode 100644 index 00000000..3f22d08c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0604.leetcode604 Design Compressed String Iterator-zh.md" @@ -0,0 +1,68 @@ +# [604. 迭代压缩字符串](https://leetcode-cn.com/problems/design-compressed-string-iterator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0604.Design%20Compressed%20String%20Iterator/README_EN.md) + +## 题目描述 + + + +

    对于一个压缩字符串,设计一个数据结构,它支持如下两种操作: next 和 hasNext

    + +

    给定的压缩字符串格式为:每个字母后面紧跟一个正整数,这个整数表示该字母在解压后的字符串里连续出现的次数。

    + +

    next() - 如果压缩字符串仍然有字母未被解压,则返回下一个字母,否则返回一个空格。
    +hasNext() - 判断是否还有字母仍然没被解压。

    + +

    注意:

    + +

    请记得将你的类在 StringIterator 中 初始化 ,因为静态变量或类变量在多组测试数据中不会被自动清空。更多细节请访问 这里 。

    + +

    示例:

    + +
    StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1");
    +
    +iterator.next(); // 返回 'L'
    +iterator.next(); // 返回 'e'
    +iterator.next(); // 返回 'e'
    +iterator.next(); // 返回 't'
    +iterator.next(); // 返回 'C'
    +iterator.next(); // 返回 'o'
    +iterator.next(); // 返回 'd'
    +iterator.hasNext(); // 返回 true
    +iterator.next(); // 返回 'e'
    +iterator.hasNext(); // 返回 false
    +iterator.next(); // 返回 ' '
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0605.leetcode605 Can Place Flowers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0605.leetcode605 Can Place Flowers-zh.md" new file mode 100644 index 00000000..64bb5256 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0605.leetcode605 Can Place Flowers-zh.md" @@ -0,0 +1,69 @@ +# [605. 种花问题](https://leetcode-cn.com/problems/can-place-flowers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0605.Can%20Place%20Flowers/README_EN.md) + +## 题目描述 + + + +

    假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。

    + +

    给你一个整数数组  flowerbed 表示花坛,由若干 01 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数 n ,能否在不打破种植规则的情况下种入 n 朵花?能则返回 true ,不能则返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:flowerbed = [1,0,0,0,1], n = 1
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:flowerbed = [1,0,0,0,1], n = 2
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= flowerbed.length <= 2 * 104
    • +
    • flowerbed[i]01
    • +
    • flowerbed 中不存在相邻的两朵花
    • +
    • 0 <= n <= flowerbed.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0606.leetcode606 Construct String from Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0606.leetcode606 Construct String from Binary Tree-zh.md" new file mode 100644 index 00000000..a5b79fb9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0606.leetcode606 Construct String from Binary Tree-zh.md" @@ -0,0 +1,75 @@ +# [606. 根据二叉树创建字符串](https://leetcode-cn.com/problems/construct-string-from-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0606.Construct%20String%20from%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

    + +

    空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

    + +

    示例 1:

    + +
    +输入: 二叉树: [1,2,3,4]
    +       1
    +     /   \
    +    2     3
    +   /    
    +  4     
    +
    +输出: "1(2(4))(3)"
    +
    +解释: 原本将是“1(2(4)())(3())”,
    +在你省略所有不必要的空括号对之后,
    +它将是“1(2(4))(3)”。
    +
    + +

    示例 2:

    + +
    +输入: 二叉树: [1,2,3,null,4]
    +       1
    +     /   \
    +    2     3
    +     \  
    +      4 
    +
    +输出: "1(2()(4))(3)"
    +
    +解释: 和第一个示例相似,
    +除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0607.leetcode607 Sales Person10607.leetcode607 Sales Person-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0607.leetcode607 Sales Person10607.leetcode607 Sales Person-zh.md" new file mode 100644 index 00000000..2cd8e800 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0607.leetcode607 Sales Person10607.leetcode607 Sales Person-zh.md" @@ -0,0 +1,99 @@ +# [607. 销售员](https://leetcode-cn.com/problems/sales-person) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0607.Sales%20Person/README_EN.md) + +## 题目描述 + + + +

    描述

    + +

    给定 3 个表: salesperson, company, orders
    +输出所有表 salesperson 中,没有向公司 'RED' 销售任何东西的销售员。

    + +

    示例:
    +输入

    + +

    表: salesperson

    + +
    +----------+------+--------+-----------------+-----------+
    +| sales_id | name | salary | commission_rate | hire_date |
    ++----------+------+--------+-----------------+-----------+
    +|   1      | John | 100000 |     6           | 4/1/2006  |
    +|   2      | Amy  | 120000 |     5           | 5/1/2010  |
    +|   3      | Mark | 65000  |     12          | 12/25/2008|
    +|   4      | Pam  | 25000  |     25          | 1/1/2005  |
    +|   5      | Alex | 50000  |     10          | 2/3/2007  |
    ++----------+------+--------+-----------------+-----------+
    +
    + +

    表 salesperson 存储了所有销售员的信息。每个销售员都有一个销售员编号 sales_id 和他的名字 name 

    + +

    表: company

    + +
    +---------+--------+------------+
    +| com_id  |  name  |    city    |
    ++---------+--------+------------+
    +|   1     |  RED   |   Boston   |
    +|   2     | ORANGE |   New York |
    +|   3     | YELLOW |   Boston   |
    +|   4     | GREEN  |   Austin   |
    ++---------+--------+------------+
    +
    + +

    表 company 存储了所有公司的信息。每个公司都有一个公司编号 com_id 和它的名字 name 。

    + +

    表: orders

    + +
    +----------+------------+---------+----------+--------+
    +| order_id | order_date | com_id  | sales_id | amount |
    ++----------+------------+---------+----------+--------+
    +| 1        |   1/1/2014 |    3    |    4     | 100000 |
    +| 2        |   2/1/2014 |    4    |    5     | 5000   |
    +| 3        |   3/1/2014 |    1    |    1     | 50000  |
    +| 4        |   4/1/2014 |    1    |    4     | 25000  |
    ++----------+----------+---------+----------+--------+
    +
    + +

    表 orders 存储了所有的销售数据,包括销售员编号 sales_id 和公司编号 com_id 。

    + +

    输出

    + +
    +------+
    +| name | 
    ++------+
    +| Amy  | 
    +| Mark | 
    +| Alex |
    ++------+
    +
    + +

    解释

    + +

    根据表 orders 中的订单 '3' 和 '4' ,容易看出只有 'John' 和 'Pam' 两个销售员曾经向公司 'RED' 销售过。

    + +

    所以我们需要输出表 salesperson 中所有其他人的名字。

    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT name +FROM salesperson +WHERE sales_id +NOT IN ( + SELECT s.sales_id FROM orders o + INNER JOIN salesperson s ON o.sales_id = s.sales_id + INNER JOIN company c ON o.com_id = c.com_id + WHERE c.name = 'RED' +); +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0608.leetcode608 Tree Node-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0608.leetcode608 Tree Node-zh.md" new file mode 100644 index 00000000..bb4be826 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0608.leetcode608 Tree Node-zh.md" @@ -0,0 +1,85 @@ +# [608. 树节点](https://leetcode-cn.com/problems/tree-node) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0608.Tree%20Node/README_EN.md) + +## 题目描述 + + + +

    给定一个表 treeid 是树节点的编号, p_id 是它父节点的 id 。

    + +
    +----+------+
    +| id | p_id |
    ++----+------+
    +| 1  | null |
    +| 2  | 1    |
    +| 3  | 1    |
    +| 4  | 2    |
    +| 5  | 2    |
    ++----+------+
    + +

    树中每个节点属于以下三种类型之一:

    + +
      +
    • 叶子:如果这个节点没有任何孩子节点。
    • +
    • 根:如果这个节点是整棵树的根,即没有父节点。
    • +
    • 内部节点:如果这个节点既不是叶子节点也不是根节点。
    • +
    + +

     

    + +

    写一个查询语句,输出所有节点的编号和节点的类型,并将结果按照节点编号排序。上面样例的结果为:

    + +

     

    + +
    +----+------+
    +| id | Type |
    ++----+------+
    +| 1  | Root |
    +| 2  | Inner|
    +| 3  | Leaf |
    +| 4  | Leaf |
    +| 5  | Leaf |
    ++----+------+
    +
    + +

     

    + +

    解释

    + +
      +
    • 节点 '1' 是根节点,因为它的父节点是 NULL ,同时它有孩子节点 '2' 和 '3' 。
    • +
    • 节点 '2' 是内部节点,因为它有父节点 '1' ,也有孩子节点 '4' 和 '5' 。
    • +
    • 节点 '3', '4' 和 '5' 都是叶子节点,因为它们都有父节点同时没有孩子节点。
    • +
    • 样例中树的形态如下: +

       

      + +
      			  1
      +			/   \
      +                      2       3
      +                    /   \
      +                  4       5
      +
      + +

       

      +
    • +
    + +

    注意

    + +

    如果树中只有一个节点,你只需要输出它的根属性。

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0609.leetcode609 Find Duplicate File in System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0609.leetcode609 Find Duplicate File in System-zh.md" new file mode 100644 index 00000000..c13d8553 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0609.leetcode609 Find Duplicate File in System-zh.md" @@ -0,0 +1,82 @@ +# [609. 在系统中查找重复文件](https://leetcode-cn.com/problems/find-duplicate-file-in-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0609.Find%20Duplicate%20File%20in%20System/README_EN.md) + +## 题目描述 + + + +

    给定一个目录信息列表,包括目录路径,以及该目录中的所有包含内容的文件,您需要找到文件系统中的所有重复文件组的路径。一组重复的文件至少包括二个具有完全相同内容的文件。

    + +

    输入列表中的单个目录信息字符串的格式如下:

    + +

    "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

    + +

    这意味着有 n 个文件(f1.txtf2.txt ... fn.txt 的内容分别是 f1_contentf2_content ... fn_content)在目录 root/d1/d2/.../dm 下。注意:n>=1 且 m>=0。如果 m=0,则表示该目录是根目录。

    + +

    输出是重复文件路径组的列表。对于每个组,它包含具有相同内容的文件的所有文件路径。文件路径是具有下列格式的字符串:

    + +

    "directory_path/file_name.txt"

    + +

    示例 1:

    + +
    输入:
    +["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"]
    +输出:  
    +[["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
    +
    + +

     

    + +

    注:

    + +
      +
    1. 最终输出不需要顺序。
    2. +
    3. 您可以假设目录名、文件名和文件内容只有字母和数字,并且文件内容的长度在 [1,50] 的范围内。
    4. +
    5. 给定的文件数量在 [1,20000] 个范围内。
    6. +
    7. 您可以假设在同一目录中没有任何文件或目录共享相同的名称。
    8. +
    9. 您可以假设每个给定的目录信息代表一个唯一的目录。目录路径和文件信息用一个空格分隔。
    10. +
    + +

     

    + +

    超越竞赛的后续行动:

    + +
      +
    1. 假设您有一个真正的文件系统,您将如何搜索文件?广度搜索还是宽度搜索?
    2. +
    3. 如果文件内容非常大(GB级别),您将如何修改您的解决方案?
    4. +
    5. 如果每次只能读取 1 kb 的文件,您将如何修改解决方案?
    6. +
    7. 修改后的解决方案的时间复杂度是多少?其中最耗时的部分和消耗内存的部分是什么?如何优化?
    8. +
    9. 如何确保您发现的重复文件不是误报?
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0610.leetcode610 Triangle Judgement-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0610.leetcode610 Triangle Judgement-zh.md" new file mode 100644 index 00000000..64e1c006 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0610.leetcode610 Triangle Judgement-zh.md" @@ -0,0 +1,46 @@ +# [610. 判断三角形](https://leetcode-cn.com/problems/triangle-judgement) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0610.Triangle%20Judgement/README_EN.md) + +## 题目描述 + + + +

    一个小学生 Tim 的作业是判断三条线段是否能形成一个三角形。

    + +

    然而,这个作业非常繁重,因为有几百组线段需要判断。

    + +

    假设表 triangle 保存了所有三条线段的长度 x、y、z ,请你帮 Tim 写一个查询语句,来判断每组 x、y、z 是否可以组成一个三角形?

    + +

     

    + +
    +| x  | y  | z  |
    +|----|----|----|
    +| 13 | 15 | 30 |
    +| 10 | 20 | 15 |
    +
    + +

    对于如上样例数据,你的查询语句应该返回如下结果:

    + +
    +| x  | y  | z  | triangle |
    +|----|----|----|----------|
    +| 13 | 15 | 30 | No       |
    +| 10 | 20 | 15 | Yes      |
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0611.leetcode611 Valid Triangle Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0611.leetcode611 Valid Triangle Number-zh.md" new file mode 100644 index 00000000..1485f399 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0611.leetcode611 Valid Triangle Number-zh.md" @@ -0,0 +1,59 @@ +# [611. 有效三角形的个数](https://leetcode-cn.com/problems/valid-triangle-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0611.Valid%20Triangle%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个包含非负整数的数组,你的任务是统计其中可以组成三角形三条边的三元组个数。

    + +

    示例 1:

    + +
    +输入: [2,2,3,4]
    +输出: 3
    +解释:
    +有效的组合是: 
    +2,3,4 (使用第一个 2)
    +2,3,4 (使用第二个 2)
    +2,2,3
    +
    + +

    注意:

    + +
      +
    1. 数组长度不超过1000。
    2. +
    3. 数组里整数的范围为 [0, 1000]。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0612.leetcode612 Shortest Distance in a Plane-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0612.leetcode612 Shortest Distance in a Plane-zh.md" new file mode 100644 index 00000000..51c3e055 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0612.leetcode612 Shortest Distance in a Plane-zh.md" @@ -0,0 +1,54 @@ +# [612. 平面上的最近距离](https://leetcode-cn.com/problems/shortest-distance-in-a-plane) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0612.Shortest%20Distance%20in%20a%20Plane/README_EN.md) + +## 题目描述 + + + +

    表 point_2d 保存了所有点(多于 2 个点)的坐标 (x,y) ,这些点在平面上两两不重合。

    + +

     

    + +

    写一个查询语句找到两点之间的最近距离,保留 2 位小数。

    + +

     

    + +
    | x  | y  |
    +|----|----|
    +| -1 | -1 |
    +| 0  | 0  |
    +| -1 | -2 |
    +
    + +

     

    + +

    最近距离在点 (-1,-1) 和(-1,2) 之间,距离为 1.00 。所以输出应该为:

    + +

     

    + +
    | shortest |
    +|----------|
    +| 1.00     |
    +
    + +

     

    + +

    注意:任意点之间的最远距离小于 10000 。

    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0613.leetcode613 Shortest Distance in a Line-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0613.leetcode613 Shortest Distance in a Line-zh.md" new file mode 100644 index 00000000..08a93202 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0613.leetcode613 Shortest Distance in a Line-zh.md" @@ -0,0 +1,58 @@ +# [613. 直线上的最近距离](https://leetcode-cn.com/problems/shortest-distance-in-a-line) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0613.Shortest%20Distance%20in%20a%20Line/README_EN.md) + +## 题目描述 + + + +

    表 point 保存了一些点在 x 轴上的坐标,这些坐标都是整数。

    + +

     

    + +

    写一个查询语句,找到这些点中最近两个点之间的距离。

    + +

     

    + +
    | x   |
    +|-----|
    +| -1  |
    +| 0   |
    +| 2   |
    +
    + +

     

    + +

    最近距离显然是 '1' ,是点 '-1' 和 '0' 之间的距离。所以输出应该如下:

    + +

     

    + +
    | shortest|
    +|---------|
    +| 1       |
    +
    + +

     

    + +

    注意:每个点都与其他点坐标不同,表 table 不会有重复坐标出现。

    + +

     

    + +

    进阶:如果这些点在 x 轴上从左到右都有一个编号,输出结果时需要输出最近点对的编号呢?

    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0614.leetcode614 Second Degree Follower-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0614.leetcode614 Second Degree Follower-zh.md" new file mode 100644 index 00000000..3e316c54 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0614.leetcode614 Second Degree Follower-zh.md" @@ -0,0 +1,63 @@ +# [614. 二级关注者](https://leetcode-cn.com/problems/second-degree-follower) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0614.Second%20Degree%20Follower/README_EN.md) + +## 题目描述 + + + +

    在 facebook 中,表 follow 会有 2 个字段: followee, follower ,分别表示被关注者和关注者。

    + +

    请写一个 sql 查询语句,对每一个关注者,查询关注他的关注者的数目。

    + +

    比方说:

    + +
    +-------------+------------+
    +| followee    | follower   |
    ++-------------+------------+
    +|     A       |     B      |
    +|     B       |     C      |
    +|     B       |     D      |
    +|     D       |     E      |
    ++-------------+------------+
    +
    + +

    应该输出:

    + +
    +-------------+------------+
    +| follower    | num        |
    ++-------------+------------+
    +|     B       |  2         |
    +|     D       |  1         |
    ++-------------+------------+
    +
    + +

    解释:

    + +

    B 和 D 都在在 follower 字段中出现,作为被关注者,B 被 C 和 D 关注,D 被 E 关注。A 不在 follower 字段内,所以A不在输出列表中。

    + +

     

    + +

    注意:

    + +
      +
    • 被关注者永远不会被他 / 她自己关注。
    • +
    • 将结果按照字典序返回。
    • +
    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0615.leetcode615 Average Salary Departments VS Company-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0615.leetcode615 Average Salary Departments VS Company-zh.md" new file mode 100644 index 00000000..d870f219 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0615.leetcode615 Average Salary Departments VS Company-zh.md" @@ -0,0 +1,87 @@ +# [615. 平均工资:部门与公司比较](https://leetcode-cn.com/problems/average-salary-departments-vs-company) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0615.Average%20Salary%20Departments%20VS%20Company/README_EN.md) + +## 题目描述 + + + +

    给如下两个表,写一个查询语句,求出在每一个工资发放日,每个部门的平均工资与公司的平均工资的比较结果 (高 / 低 / 相同)。

    + +

     

    + +

    表: salary

    + +
    | id | employee_id | amount | pay_date   |
    +|----|-------------|--------|------------|
    +| 1  | 1           | 9000   | 2017-03-31 |
    +| 2  | 2           | 6000   | 2017-03-31 |
    +| 3  | 3           | 10000  | 2017-03-31 |
    +| 4  | 1           | 7000   | 2017-02-28 |
    +| 5  | 2           | 6000   | 2017-02-28 |
    +| 6  | 3           | 8000   | 2017-02-28 |
    +
    + +

     

    + +

    employee_id 字段是表 employee 中 employee_id 字段的外键。

    + +

     

    + +
    | employee_id | department_id |
    +|-------------|---------------|
    +| 1           | 1             |
    +| 2           | 2             |
    +| 3           | 2             |
    +
    + +

     

    + +

    对于如上样例数据,结果为:

    + +

     

    + +
    | pay_month | department_id | comparison  |
    +|-----------|---------------|-------------|
    +| 2017-03   | 1             | higher      |
    +| 2017-03   | 2             | lower       |
    +| 2017-02   | 1             | same        |
    +| 2017-02   | 2             | same        |
    +
    + +

     

    + +

    解释

    + +

     

    + +

    在三月,公司的平均工资是 (9000+6000+10000)/3 = 8333.33...

    + +

     

    + +

    由于部门 '1' 里只有一个 employee_id 为 '1' 的员工,所以部门 '1' 的平均工资就是此人的工资 9000 。因为 9000 > 8333.33 ,所以比较结果是 'higher'。

    + +

     

    + +

    第二个部门的平均工资为 employee_id 为 '2' 和 '3' 两个人的平均工资,为 (6000+10000)/2=8000 。因为 8000 < 8333.33 ,所以比较结果是 'lower' 。

    + +

     

    + +

    在二月用同样的公式求平均工资并比较,比较结果为 'same' ,因为部门 '1' 和部门 '2' 的平均工资与公司的平均工资相同,都是 7000 。

    + +

     

    + + +## 解法 + + + + + +### **SQL** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0616.leetcode616 Add Bold Tag in String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0616.leetcode616 Add Bold Tag in String-zh.md" new file mode 100644 index 00000000..b1361a26 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0616.leetcode616 Add Bold Tag in String-zh.md" @@ -0,0 +1,79 @@ +# [616. 给字符串添加加粗标签](https://leetcode-cn.com/problems/add-bold-tag-in-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0616.Add%20Bold%20Tag%20in%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个字符串列表 dict ,你需要将在字符串列表中出现过的 s 的子串添加加粗闭合标签  和  。

    + +

    如果两个子串有重叠部分,你需要把它们一起用一个闭合标签包围起来。同理,如果两个子字符串连续被加粗,那么你也需要把它们合起来用一个加粗标签包围。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +s = "abcxyz123"
    +dict = ["abc","123"]
    +输出:
    +"abcxyz123"
    +
    + +

    示例 2:

    + +
    +输入:
    +s = "aaabbcc"
    +dict = ["aaa","aab","bc"]
    +输出:
    +"aaabbcc"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定的 dict 中不会有重复的字符串,且字符串数目不会超过 100
    • +
    • 输入中的所有字符串长度都在范围 [1,1000] 内。
    • +
    + +

     

    + +

    注:此题与「758 - 字符串中的加粗单词」相同 - https://leetcode-cn.com/problems/bold-words-in-string

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0617.leetcode617 Merge Two Binary Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0617.leetcode617 Merge Two Binary Trees-zh.md" new file mode 100644 index 00000000..f97d1e12 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0617.leetcode617 Merge Two Binary Trees-zh.md" @@ -0,0 +1,183 @@ +# [617. 合并二叉树](https://leetcode-cn.com/problems/merge-two-binary-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0617.Merge%20Two%20Binary%20Trees/README_EN.md) + +## 题目描述 + + + +

    给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。

    + +

    你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。

    + +

    示例 1:

    + +
    +输入: 
    +	Tree 1                     Tree 2                  
    +          1                         2                             
    +         / \                       / \                            
    +        3   2                     1   3                        
    +       /                           \   \                      
    +      5                             4   7                  
    +输出: 
    +合并后的树:
    +	     3
    +	    / \
    +	   4   5
    +	  / \   \ 
    +	 5   4   7
    +
    + +

    注意: 合并必须从两个树的根节点开始。

    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: + if root1 is None: + return root2 + if root2 is None: + return root1 + node = TreeNode(root1.val + root2.val) + node.left = self.mergeTrees(root1.left, root2.left) + node.right = self.mergeTrees(root1.right, root2.right) + return node +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + TreeNode node = new TreeNode(root1.val + root2.val); + node.left = mergeTrees(root1.left, root2.left); + node.right = mergeTrees(root1.right, root2.right); + return node; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + + function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { + if (root1 == null && root2 == null) return null; + if (root1 == null) return root2; + if (root2 == null) return root1; + let left = mergeTrees(root1.left, root2.left); + let right = mergeTrees(root1.right, root2.right); + return new TreeNode(root1.val + root2.val, left, right); +}; +``` + +### **C++** + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { + if (root1 == nullptr) { + return root2; + } + if (root2 == nullptr) { + return root1; + } + TreeNode *node = new TreeNode(root1->val + root2->val); + node->left = mergeTrees(root1->left, root2->left); + node->right = mergeTrees(root1->right, root2->right); + return node; + } +}; +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode { + if root1 == nil { + return root2 + } + if root2 == nil { + return root1 + } + node := &TreeNode{Val: root1.Val + root2.Val} + node.Left = mergeTrees(root1.Left, root2.Left) + node.Right = mergeTrees(root1.Right, root2.Right) + return node +} +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0618.leetcode618 Students Report By Geography-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0618.leetcode618 Students Report By Geography-zh.md" new file mode 100644 index 00000000..c637ee98 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0618.leetcode618 Students Report By Geography-zh.md" @@ -0,0 +1,58 @@ +# [618. 学生地理信息报告](https://leetcode-cn.com/problems/students-report-by-geography) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0618.Students%20Report%20By%20Geography/README_EN.md) + +## 题目描述 + + + +

    一所美国大学有来自亚洲、欧洲和美洲的学生,他们的地理信息存放在如下 student 表中。

    + +

     

    + +
    +| name   | continent |
    +|--------|-----------|
    +| Jack   | America   |
    +| Pascal | Europe    |
    +| Xi     | Asia      |
    +| Jane   | America   |
    +
    + +

     

    + +

    写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。

    + +

     

    + +

    对于样例输入,它的对应输出是:

    + +

     

    + +
    +| America | Asia | Europe |
    +|---------|------|--------|
    +| Jack    | Xi   | Pascal |
    +| Jane    |      |        |
    +
    + +

     

    + +

    进阶:如果不能确定哪个大洲的学生数最多,你可以写出一个查询去生成上述学生报告吗?

    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0619.leetcode619 Biggest Single Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0619.leetcode619 Biggest Single Number-zh.md" new file mode 100644 index 00000000..b6400842 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0619.leetcode619 Biggest Single Number-zh.md" @@ -0,0 +1,53 @@ +# [619. 只出现一次的最大数字](https://leetcode-cn.com/problems/biggest-single-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0619.Biggest%20Single%20Number/README_EN.md) + +## 题目描述 + + + +

    表 my_numbers 的 num 字段包含很多数字,其中包括很多重复的数字。

    + +

    你能写一个 SQL 查询语句,找到只出现过一次的数字中,最大的一个数字吗?

    + +
    +---+
    +|num|
    ++---+
    +| 8 |
    +| 8 |
    +| 3 |
    +| 3 |
    +| 1 |
    +| 4 |
    +| 5 |
    +| 6 | 
    +
    + +

    对于上面给出的样例数据,你的查询语句应该返回如下结果:

    + +
    +---+
    +|num|
    ++---+
    +| 6 |
    +
    + +

    注意:

    + +

    如果没有只出现一次的数字,输出 null 。

    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0620.leetcode620 Not Boring Movies-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0620.leetcode620 Not Boring Movies-zh.md" new file mode 100644 index 00000000..07a58700 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0620.leetcode620 Not Boring Movies-zh.md" @@ -0,0 +1,59 @@ +# [620. 有趣的电影](https://leetcode-cn.com/problems/not-boring-movies) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0620.Not%20Boring%20Movies/README_EN.md) + +## 题目描述 + + + +

    某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。

    + +

    作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

    + +

     

    + +

    例如,下表 cinema:

    + +
    ++---------+-----------+--------------+-----------+
    +|   id    | movie     |  description |  rating   |
    ++---------+-----------+--------------+-----------+
    +|   1     | War       |   great 3D   |   8.9     |
    +|   2     | Science   |   fiction    |   8.5     |
    +|   3     | irish     |   boring     |   6.2     |
    +|   4     | Ice song  |   Fantacy    |   8.6     |
    +|   5     | House card|   Interesting|   9.1     |
    ++---------+-----------+--------------+-----------+
    +
    + +

    对于上面的例子,则正确的输出是为:

    + +
    ++---------+-----------+--------------+-----------+
    +|   id    | movie     |  description |  rating   |
    ++---------+-----------+--------------+-----------+
    +|   5     | House card|   Interesting|   9.1     |
    +|   1     | War       |   great 3D   |   8.9     |
    ++---------+-----------+--------------+-----------+
    +
    + +

     

    + + +## 解法 + + + + + +### **SQL** + +``` +SELECT * +FROM cinema +WHERE description NOT LIKE '%boring%' + AND mod(id,2)=1 +ORDER BY rating desc; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0621.leetcode621 Task Scheduler-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0621.leetcode621 Task Scheduler-zh.md" new file mode 100644 index 00000000..138f7acd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0621.leetcode621 Task Scheduler-zh.md" @@ -0,0 +1,86 @@ +# [621. 任务调度器](https://leetcode-cn.com/problems/task-scheduler) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0621.Task%20Scheduler/README_EN.md) + +## 题目描述 + + + +

    给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表。其中每个字母表示一种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。在任何一个单位时间,CPU 可以完成一个任务,或者处于待命状态。

    + +

    然而,两个 相同种类 的任务之间必须有长度为整数 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。

    + +

    你需要计算完成所有任务所需要的 最短时间

    + +

     

    + +

    示例 1:

    + +
    +输入:tasks = ["A","A","A","B","B","B"], n = 2
    +输出:8
    +解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B
    +     在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。 
    + +

    示例 2:

    + +
    +输入:tasks = ["A","A","A","B","B","B"], n = 0
    +输出:6
    +解释:在这种情况下,任何大小为 6 的排列都可以满足要求,因为 n = 0
    +["A","A","A","B","B","B"]
    +["A","B","A","B","A","B"]
    +["B","B","B","A","A","A"]
    +...
    +诸如此类
    +
    + +

    示例 3:

    + +
    +输入:tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
    +输出:16
    +解释:一种可能的解决方案是:
    +     A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> (待命) -> (待命) -> A -> (待命) -> (待命) -> A
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= task.length <= 104
    • +
    • tasks[i] 是大写英文字母
    • +
    • n 的取值范围为 [0, 100]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0622.leetcode622 Design Circular Queue-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0622.leetcode622 Design Circular Queue-zh.md" new file mode 100644 index 00000000..e4b57606 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0622.leetcode622 Design Circular Queue-zh.md" @@ -0,0 +1,192 @@ +# [622. 设计循环队列](https://leetcode-cn.com/problems/design-circular-queue) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0622.Design%20Circular%20Queue/README_EN.md) + +## 题目描述 + + + +

    设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。

    + +

    循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。

    + +

    你的实现应该支持如下操作:

    + +
      +
    • MyCircularQueue(k): 构造器,设置队列长度为 k 。
    • +
    • Front: 从队首获取元素。如果队列为空,返回 -1 。
    • +
    • Rear: 获取队尾元素。如果队列为空,返回 -1 。
    • +
    • enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
    • +
    • deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
    • +
    • isEmpty(): 检查循环队列是否为空。
    • +
    • isFull(): 检查循环队列是否已满。
    • +
    + +

     

    + +

    示例:

    + +
    MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
    +circularQueue.enQueue(1);  // 返回 true
    +circularQueue.enQueue(2);  // 返回 true
    +circularQueue.enQueue(3);  // 返回 true
    +circularQueue.enQueue(4);  // 返回 false,队列已满
    +circularQueue.Rear();  // 返回 3
    +circularQueue.isFull();  // 返回 true
    +circularQueue.deQueue();  // 返回 true
    +circularQueue.enQueue(4);  // 返回 true
    +circularQueue.Rear();  // 返回 4
    + +

     

    + +

    提示:

    + +
      +
    • 所有的值都在 0 至 1000 的范围内;
    • +
    • 操作数将在 1 至 1000 的范围内;
    • +
    • 请不要使用内置的队列库。
    • +
    + + +## 解法 + + + +“循环数组”实现。 + + + +### **Python3** + + + +```python +class MyCircularQueue: + + def __init__(self, k: int): + self.q = [0] * k + self.front = 0 + self.size = 0 + self.capacity = k + + def enQueue(self, value: int) -> bool: + if self.isFull(): + return False + idx = (self.front + self.size) % self.capacity + self.q[idx] = value + self.size += 1 + return True + + def deQueue(self) -> bool: + if self.isEmpty(): + return False + self.front = (self.front + 1) % self.capacity + self.size -= 1 + return True + + def Front(self) -> int: + if self.isEmpty(): + return -1 + return self.q[self.front] + + def Rear(self) -> int: + if self.isEmpty(): + return -1 + idx = (self.front + self.size - 1) % self.capacity + return self.q[idx] + + def isEmpty(self) -> bool: + return self.size == 0 + + def isFull(self) -> bool: + return self.size == self.capacity + + +# Your MyCircularQueue object will be instantiated and called as such: +# obj = MyCircularQueue(k) +# param_1 = obj.enQueue(value) +# param_2 = obj.deQueue() +# param_3 = obj.Front() +# param_4 = obj.Rear() +# param_5 = obj.isEmpty() +# param_6 = obj.isFull() +``` + +### **Java** + + + +```java +class MyCircularQueue { + private int[] q; + private int front; + private int size; + private int capacity; + + public MyCircularQueue(int k) { + q = new int[k]; + capacity = k; + } + + public boolean enQueue(int value) { + if (isFull()) { + return false; + } + int idx = (front + size) % capacity; + q[idx] = value; + ++size; + return true; + } + + public boolean deQueue() { + if (isEmpty()) { + return false; + } + front = (front + 1) % capacity; + --size; + return true; + } + + public int Front() { + if (isEmpty()) { + return -1; + } + return q[front]; + } + + public int Rear() { + if (isEmpty()) { + return -1; + } + int idx = (front + size - 1) % capacity; + return q[idx]; + } + + public boolean isEmpty() { + return size == 0; + } + + public boolean isFull() { + return size == capacity; + } +} + +/** + * Your MyCircularQueue object will be instantiated and called as such: + * MyCircularQueue obj = new MyCircularQueue(k); + * boolean param_1 = obj.enQueue(value); + * boolean param_2 = obj.deQueue(); + * int param_3 = obj.Front(); + * int param_4 = obj.Rear(); + * boolean param_5 = obj.isEmpty(); + * boolean param_6 = obj.isFull(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0623.leetcode623 Add One Row to Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0623.leetcode623 Add One Row to Tree-zh.md" new file mode 100644 index 00000000..aa4c81b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0623.leetcode623 Add One Row to Tree-zh.md" @@ -0,0 +1,104 @@ +# [623. 在二叉树中增加一行](https://leetcode-cn.com/problems/add-one-row-to-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0623.Add%20One%20Row%20to%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,根节点为第1层,深度为 1。在其第 d 层追加一行值为 v 的节点。

    + +

    添加规则:给定一个深度值 d (正整数),针对深度为 d-1 层的每一非空节点 N,为 N 创建两个值为 v 的左子树和右子树。

    + +

    将 N 原先的左子树,连接为新节点 v 的左子树;将 N 原先的右子树,连接为新节点 v 的右子树。

    + +

    如果 d 的值为 1,深度 d - 1 不存在,则创建一个新的根节点 v,原先的整棵树将作为 v 的左子树。

    + +

    示例 1:

    + +
    +输入: 
    +二叉树如下所示:
    +       4
    +     /   \
    +    2     6
    +   / \   / 
    +  3   1 5   
    +
    +v = 1
    +
    +d = 2
    +
    +输出: 
    +       4
    +      / \
    +     1   1
    +    /     \
    +   2       6
    +  / \     / 
    + 3   1   5   
    +
    +
    + +

    示例 2:

    + +
    +输入: 
    +二叉树如下所示:
    +      4
    +     /   
    +    2    
    +   / \   
    +  3   1    
    +
    +v = 1
    +
    +d = 3
    +
    +输出: 
    +      4
    +     /   
    +    2
    +   / \    
    +  1   1
    + /     \  
    +3       1
    +
    + +

    注意:

    + +
      +
    1. 输入的深度值 d 的范围是:[1,二叉树最大深度 + 1]。
    2. +
    3. 输入的二叉树至少有一个节点。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0624.leetcode624 Maximum Distance in Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0624.leetcode624 Maximum Distance in Arrays-zh.md" new file mode 100644 index 00000000..5a616f19 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0624.leetcode624 Maximum Distance in Arrays-zh.md" @@ -0,0 +1,63 @@ +# [624. 数组列表中的最大距离](https://leetcode-cn.com/problems/maximum-distance-in-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0624.Maximum%20Distance%20in%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给定 m 个数组,每个数组都已经按照升序排好序了。现在你需要从两个不同的数组中选择两个整数(每个数组选一个)并且计算它们的距离。两个整数 a 和 b 之间的距离定义为它们差的绝对值 |a-b| 。你的任务就是去找到最大距离

    + +

    示例 1:

    + +
    输入: 
    +[[1,2,3],
    + [4,5],
    + [1,2,3]]
    +输出: 4
    +解释:
    +一种得到答案 4 的方法是从第一个数组或者第三个数组中选择 1,同时从第二个数组中选择 5 。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 每个给定数组至少会有 1 个数字。列表中至少有两个非空数组。
    2. +
    3. 所有 m 个数组中的数字总数目在范围 [2, 10000] 内。
    4. +
    5. m 个数组中所有整数的范围在 [-10000, 10000] 内。
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0625.leetcode625 Minimum Factorization-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0625.leetcode625 Minimum Factorization-zh.md" new file mode 100644 index 00000000..d50e637a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0625.leetcode625 Minimum Factorization-zh.md" @@ -0,0 +1,70 @@ +# [625. 最小因式分解](https://leetcode-cn.com/problems/minimum-factorization) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0625.Minimum%20Factorization/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 a,找出最小的正整数 b 使得 b 的所有数位相乘恰好等于 a

    + +

    如果不存在这样的结果或者结果不是 32 位有符号整数,返回 0。

    + +

     

    + +

    样例 1

    + +

    输入:

    + +
    48 
    +
    + +

    输出:

    + +
    68
    + +

     

    + +

    样例 2

    + +

    输入:

    + +
    15
    +
    + +

    输出:

    + +
    35
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0626.leetcode626 Exchange Seats-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0626.leetcode626 Exchange Seats-zh.md" new file mode 100644 index 00000000..197e85d4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0626.leetcode626 Exchange Seats-zh.md" @@ -0,0 +1,69 @@ +# [626. 换座位](https://leetcode-cn.com/problems/exchange-seats) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0626.Exchange%20Seats/README_EN.md) + +## 题目描述 + + + +

    小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

    + +

    其中纵列的 id 是连续递增的

    + +

    小美想改变相邻俩学生的座位。

    + +

    你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

    + +

     

    + +

    示例:

    + +
    ++---------+---------+
    +|    id   | student |
    ++---------+---------+
    +|    1    | Abbot   |
    +|    2    | Doris   |
    +|    3    | Emerson |
    +|    4    | Green   |
    +|    5    | Jeames  |
    ++---------+---------+
    +
    + +

    假如数据输入的是上表,则输出结果如下:

    + +
    ++---------+---------+
    +|    id   | student |
    ++---------+---------+
    +|    1    | Doris   |
    +|    2    | Abbot   |
    +|    3    | Green   |
    +|    4    | Emerson |
    +|    5    | Jeames  |
    ++---------+---------+
    + +

    注意:

    + +

    如果学生人数是奇数,则不需要改变最后一个同学的座位。

    + + +## 解法 + + + + + +### **SQL** + +``` +SELECT + s1.id, COALESCE(s2.student, s1.student) AS student +FROM + seat s1 + LEFT JOIN + seat s2 ON (s1.id+1)^1-1 = s2.id +ORDER BY s1.id; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0627.leetcode627 Swap Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0627.leetcode627 Swap Salary-zh.md" new file mode 100644 index 00000000..e62660e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0627.leetcode627 Swap Salary-zh.md" @@ -0,0 +1,51 @@ +# [627. 变更性别](https://leetcode-cn.com/problems/swap-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0627.Swap%20Salary/README_EN.md) + +## 题目描述 + + + +

    给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。

    + +

    注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。

    + +

    例如:

    + +
    | id | name | sex | salary |
    +|----|------|-----|--------|
    +| 1  | A    | m   | 2500   |
    +| 2  | B    | f   | 1500   |
    +| 3  | C    | m   | 5500   |
    +| 4  | D    | f   | 500    |
    +
    + +

    运行你所编写的更新语句之后,将会得到以下表:

    + +
    | id | name | sex | salary |
    +|----|------|-----|--------|
    +| 1  | A    | f   | 2500   |
    +| 2  | B    | m   | 1500   |
    +| 3  | C    | f   | 5500   |
    +| 4  | D    | m   | 500    |
    +
    + + +## 解法 + + + + + +### **SQL** + +``` +UPDATE salary +SET + sex = CASE sex + WHEN 'm' THEN 'f' + ELSE 'm' + END; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0628.leetcode628 Maximum Product of Three Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0628.leetcode628 Maximum Product of Three Numbers-zh.md" new file mode 100644 index 00000000..378a8a6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0628.leetcode628 Maximum Product of Three Numbers-zh.md" @@ -0,0 +1,88 @@ +# [628. 三个数的最大乘积](https://leetcode-cn.com/problems/maximum-product-of-three-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0628.Maximum%20Product%20of%20Three%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你一个整型数组 nums ,在数组中找出由三个数组成的最大乘积,并输出这个乘积。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3]
    +输出:6
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,4]
    +输出:24
    +
    + +

    示例 3:

    + +
    +输入:nums = [-1,-2,-3]
    +输出:-6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= nums.length <= 104
    • +
    • -1000 <= nums[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + n = len(nums) + nums.sort() + # 全负 0 1 n-1 + # 全正 n-1 n-2 n-3 + # 有正有负 max([0 1 n-1], [n-1 n-2 n-3]) + return max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]) +``` + +### **Java** + + + +```java +class Solution { + public int maximumProduct(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + // 全负 0 1 n-1 + // 全正 n-1 n-2 n-3 + // 有正有负 max([0 1 n-1], [n-1 n-2 n-3]) + return Math.max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0629.leetcode629 K Inverse Pairs Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0629.leetcode629 K Inverse Pairs Array-zh.md" new file mode 100644 index 00000000..3710d0d4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0629.leetcode629 K Inverse Pairs Array-zh.md" @@ -0,0 +1,68 @@ +# [629. K个逆序对数组](https://leetcode-cn.com/problems/k-inverse-pairs-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0629.K%20Inverse%20Pairs%20Array/README_EN.md) + +## 题目描述 + + + +

    给出两个整数 n 和 k,找出所有包含从 1 到 n 的数字,且恰好拥有 k 个逆序对的不同的数组的个数。

    + +

    逆序对的定义如下:对于数组的第i个和第 j个元素,如果满i < j且 a[i] > a[j],则其为一个逆序对;否则不是。

    + +

    由于答案可能很大,只需要返回 答案 mod 109 + 7 的值。

    + +

    示例 1:

    + +
    +输入: n = 3, k = 0
    +输出: 1
    +解释: 
    +只有数组 [1,2,3] 包含了从1到3的整数并且正好拥有 0 个逆序对。
    +
    + +

    示例 2:

    + +
    +输入: n = 3, k = 1
    +输出: 2
    +解释: 
    +数组 [1,3,2] 和 [2,1,3] 都有 1 个逆序对。
    +
    + +

    说明:

    + +
      +
    1.  n 的范围是 [1, 1000] 并且 k 的范围是 [0, 1000]。
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0630.leetcode630 Course Schedule III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0630.leetcode630 Course Schedule III-zh.md" new file mode 100644 index 00000000..808150c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0630.leetcode630 Course Schedule III-zh.md" @@ -0,0 +1,67 @@ +# [630. 课程表 III](https://leetcode-cn.com/problems/course-schedule-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0630.Course%20Schedule%20III/README_EN.md) + +## 题目描述 + + + +

    这里有 n 门不同的在线课程,他们按从 1n 编号。每一门课程有一定的持续上课时间(课程时间)t 以及关闭时间第 d 天。一门课要持续学习 t 天直到第 d 天时要完成,你将会从第 1 天开始。

    + +

    给出 n 个在线课程用 (t, d) 对表示。你的任务是找出最多可以修几门课。

    + +

     

    + +

    示例:

    + +
    +输入: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
    +输出: 3
    +解释: 
    +这里一共有 4 门课程, 但是你最多可以修 3 门:
    +首先, 修第一门课时, 它要耗费 100 天,你会在第 100 天完成, 在第 101 天准备下门课。
    +第二, 修第三门课时, 它会耗费 1000 天,所以你将在第 1100 天的时候完成它, 以及在第 1101 天开始准备下门课程。
    +第三, 修第二门课时, 它会耗时 200 天,所以你将会在第 1300 天时完成它。
    +第四门课现在不能修,因为你将会在第 3300 天完成它,这已经超出了关闭日期。
    + +

     

    + +

    提示:

    + +
      +
    1. 整数 1 <= d, t, n <= 10,000 。
    2. +
    3. 你不能同时修两门课程。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0631.leetcode631 Design Excel Sum Formula-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0631.leetcode631 Design Excel Sum Formula-zh.md" new file mode 100644 index 00000000..690410cb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0631.leetcode631 Design Excel Sum Formula-zh.md" @@ -0,0 +1,103 @@ +# [631. 设计 Excel 求和公式](https://leetcode-cn.com/problems/design-excel-sum-formula) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0631.Design%20Excel%20Sum%20Formula/README_EN.md) + +## 题目描述 + + + +

    你的任务是实现 Excel 的求和功能,具体的操作如下:

    + +

    Excel(int H, char W): 这是一个构造函数,输入表明了 Excel 的高度和宽度。H 是一个正整数,范围从 1 到 26,代表高度。W 是一个字符,范围从 'A' 到 'Z',宽度等于从 'A' 到 W 的字母个数。Excel 表格是一个高度 * 宽度的二维整数数组,数组中元素初始化为 0。第一行下标从 1 开始,第一列下标从 'A' 开始。

    + +

     

    + +

    void Set(int row, char column, int val): 设置 C(row, column) 中的值为 val。

    + +

     

    + +

    int Get(int row, char column): 返回 C(row, column) 中的值。

    + +

     

    + +

    int Sum(int row, char column, List of Strings : numbers): 这个函数会将计算的结果放入 C(row, column) 中,计算的结果等于在 numbers 中代表的所有元素之和,这个函数同时也会将这个结果返回。求和公式会一直计算更新结果直到这个公式被其他的值或者公式覆盖。

    + +

    numbers 是若干字符串的集合,每个字符串代表单个位置或一个区间。如果这个字符串表示单个位置,它的格式如下:ColRow,例如 "F7" 表示位置 (7, F) 。如果这个字符串表示一个区间,它的格式如下:ColRow1:ColRow2。区间就是左上角为 ColRow1 右下角为 ColRow2 的长方形。

    + +

     

    + +

    样例 1 :

    + +

     

    + +
    Excel(3,"C"); 
    +// 构造一个 3*3 的二维数组,初始化全是 0。
    +//   A B C
    +// 1 0 0 0
    +// 2 0 0 0
    +// 3 0 0 0
    +
    +Set(1, "A", 2);
    +// 设置 C(1,"A") 为 2。
    +//   A B C
    +// 1 2 0 0
    +// 2 0 0 0
    +// 3 0 0 0
    +
    +Sum(3, "C", ["A1", "A1:B2"]);
    +// 将 C(3,"C") 的值设为 C(1,"A") 单点,左上角为 C(1,"A") 右下角为 C(2,"B") 的长方形,所有元素之和。返回值 4。 
    +//   A B C
    +// 1 2 0 0
    +// 2 0 0 0
    +// 3 0 0 4
    +
    +Set(2, "B", 2);
    +// 将 C(2,"B") 设为 2。 注意 C(3, "C") 的值也同时改变。
    +//   A B C
    +// 1 2 0 0
    +// 2 0 2 0
    +// 3 0 0 6
    +
    + +

     

    + +

    注释 :

    + +
      +
    1. 你可以认为不会出现循环求和的定义,比如说: A1 = sum(B1) ,B1 = sum(A1)。
    2. +
    3. 测试数据中,字母表示用双引号。
    4. +
    5. 请记住清零 Excel 类中的变量,因为静态变量、类变量会在多组测试数据中保存之前结果。详情请看这里
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0632.leetcode632 Smallest Range Covering Elements from K Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0632.leetcode632 Smallest Range Covering Elements from K Lists-zh.md" new file mode 100644 index 00000000..d2d2f243 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0632.leetcode632 Smallest Range Covering Elements from K Lists-zh.md" @@ -0,0 +1,95 @@ +# [632. 最小区间](https://leetcode-cn.com/problems/smallest-range-covering-elements-from-k-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0632.Smallest%20Range%20Covering%20Elements%20from%20K%20Lists/README_EN.md) + +## 题目描述 + + + +

    你有 k 个 非递减排列 的整数列表。找到一个 最小 区间,使得 k 个列表中的每个列表至少有一个数包含在其中。

    + +

    我们定义如果 b-a < d-c 或者在 b-a == d-c 时 a < c,则区间 [a,b][c,d] 小。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
    +输出:[20,24]
    +解释: 
    +列表 1:[4, 10, 15, 24, 26],24 在区间 [20,24] 中。
    +列表 2:[0, 9, 12, 20],20 在区间 [20,24] 中。
    +列表 3:[5, 18, 22, 30],22 在区间 [20,24] 中。
    +
    + +

    示例 2:

    + +
    +输入:nums = [[1,2,3],[1,2,3],[1,2,3]]
    +输出:[1,1]
    +
    + +

    示例 3:

    + +
    +输入:nums = [[10,10],[11,11]]
    +输出:[10,11]
    +
    + +

    示例 4:

    + +
    +输入:nums = [[10],[11]]
    +输出:[10,11]
    +
    + +

    示例 5:

    + +
    +输入:nums = [[1],[2],[3],[4],[5],[6],[7]]
    +输出:[1,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums.length == k
    • +
    • 1 <= k <= 3500
    • +
    • 1 <= nums[i].length <= 50
    • +
    • -105 <= nums[i][j] <= 105
    • +
    • nums[i] 按非递减顺序排列
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0633.leetcode633 Sum of Square Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0633.leetcode633 Sum of Square Numbers-zh.md" new file mode 100644 index 00000000..519ea64d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0633.leetcode633 Sum of Square Numbers-zh.md" @@ -0,0 +1,166 @@ +# [633. 平方数之和](https://leetcode-cn.com/problems/sum-of-square-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0633.Sum%20of%20Square%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数 c ,你要判断是否存在两个整数 ab,使得 a2 + b2 = c

    + +

     

    + +

    示例 1:

    + +
    输入:c = 5
    +输出:true
    +解释:1 * 1 + 2 * 2 = 5
    +
    + +

    示例 2:

    + +
    输入:c = 3
    +输出:false
    +
    + +

    示例 3:

    + +
    输入:c = 4
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:c = 2
    +输出:true
    +
    + +

    示例 5:

    + +
    输入:c = 1
    +输出:true
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= c <= 231 - 1
    • +
    + +## 解法 + + + +![](https://cdn.jsdelivr.net/gh/yanglr/leetcode-ac@master/assets/0600-0699/0633.Sum%20of%20Square%20Numbers/images/table.png) + +上图为 a,b,c 之间的关系,这题其实就是在这张“表”里查找 c + +从表的右上角看,不难发现它类似一棵二叉查找树,所以只需从右上角开始,按照二叉查找树的规律进行搜索 + + + +### **Python3** + + + +```python +class Solution(object): + def judgeSquareSum(self, c): + i, j = 0, int(math.sqrt(c)) + while i <= j: + s = i * i + j * j + if s < c: + i += 1 + elif s > c: + j -= 1 + else: + return True + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean judgeSquareSum(int c) { + int i = 0, j = (int) Math.sqrt(c); + while (i <= j) { + int s = i * i + j * j; + if (s < c) { + ++i; + } else if (s > c) { + --j; + } else { + return true; + } + } + return false; + } +} +``` + +### **TypeScript** + +```ts +function judgeSquareSum(c: number): boolean { + let a = 0, b = Math.floor(Math.sqrt(c)); + while (a <= b) { + let sum = a ** 2 + b ** 2; + if (sum == c) return true; + if (sum < c) { + ++a; + } else { + --b; + } + } + return false; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool judgeSquareSum(int c) { + long i = 0, j = (long) sqrt(c); + while (i <= j) { + long s = i * i + j * j; + if (s < c) ++i; + else if (s > c) --j; + else return true; + } + return false; + } +}; +``` + +### **Go** + +```go +func judgeSquareSum(c int) bool { + i, j := 0, int(math.Sqrt(float64(c))) + for i <= j { + s := i*i + j*j + if s < c { + i++ + } else if s > c { + j-- + } else { + return true + } + } + return false +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0634.leetcode634 Find the Derangement of An Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0634.leetcode634 Find the Derangement of An Array-zh.md" new file mode 100644 index 00000000..78531e5d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0634.leetcode634 Find the Derangement of An Array-zh.md" @@ -0,0 +1,58 @@ +# [634. 寻找数组的错位排列](https://leetcode-cn.com/problems/find-the-derangement-of-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0634.Find%20the%20Derangement%20of%20An%20Array/README_EN.md) + +## 题目描述 + + + +

    在组合数学中,如果一个排列中所有元素都不在原先的位置上,那么这个排列就被称为错位排列。

    + +

    给定一个从 1 到 n 升序排列的数组,你可以计算出总共有多少个不同的错位排列吗?

    + +

    由于答案可能非常大,你只需要将答案对 109+7 取余输出即可。

    + +

     

    + +

    样例 1:

    + +
    输入: 3
    +输出: 2
    +解释: 原始的数组为 [1,2,3]。两个错位排列的数组为 [2,3,1] 和 [3,1,2]。
    +
    + +

     

    + +

    注释:
    +n 的范围是 [1, 106]。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0635.leetcode635 Design Log Storage System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0635.leetcode635 Design Log Storage System-zh.md" new file mode 100644 index 00000000..49691327 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0635.leetcode635 Design Log Storage System-zh.md" @@ -0,0 +1,87 @@ +# [635. 设计日志存储系统](https://leetcode-cn.com/problems/design-log-storage-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0635.Design%20Log%20Storage%20System/README_EN.md) + +## 题目描述 + + + +

    你将获得多条日志,每条日志都有唯一的 idtimestamptimestamp 是形如 Year:Month:Day:Hour:Minute:Second 的字符串,2017:01:01:23:59:59 ,所有值域都是零填充的十进制数。

    + +

    实现 LogSystem 类:

    + +
      +
    • LogSystem() 初始化 LogSystem 对象
    • +
    • void put(int id, string timestamp) 给定日志的 idtimestamp ,将这个日志存入你的存储系统中。
    • +
    • int[] retrieve(string start, string end, string granularity) 返回在给定时间区间 [start, end] (包含两端)内的所有日志的 idstartendtimestamp 的格式相同,granularity 表示考虑的时间粒度(例如,精确到 DayMinute 等)。例如 start = "2017:01:01:23:59:59"end = "2017:01:02:23:59:59"granularity = "Day" 意味着需要查找从 Jan. 1st 2017Jan. 2nd 2017 范围内的日志,可以忽略日志的 HourMinuteSecond
    • +
    +  + +

    示例:

    + +
    +输入:
    +["LogSystem", "put", "put", "put", "retrieve", "retrieve"]
    +[[], [1, "2017:01:01:23:59:59"], [2, "2017:01:01:22:59:59"], [3, "2016:01:01:00:00:00"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Year"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour"]]
    +输出:
    +[null, null, null, null, [3, 2, 1], [2, 1]]
    +
    +解释:
    +LogSystem logSystem = new LogSystem();
    +logSystem.put(1, "2017:01:01:23:59:59");
    +logSystem.put(2, "2017:01:01:22:59:59");
    +logSystem.put(3, "2016:01:01:00:00:00");
    +
    +// 返回 [3,2,1],返回从 2016 年到 2017 年所有的日志。
    +logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00", "Year");
    +
    +// 返回 [2,1],返回从 Jan. 1, 2016 01:XX:XX 到 Jan. 1, 2017 23:XX:XX 之间的所有日志
    +// 不返回日志 3 因为记录时间 Jan. 1, 2016 00:00:00 超过范围的起始时间
    +logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour");
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= id <= 500
    • +
    • 2000 <= Year <= 2017
    • +
    • 1 <= Month <= 12
    • +
    • 1 <= Day <= 31
    • +
    • 0 <= Hour <= 23
    • +
    • 0 <= Minute, Second <= 59
    • +
    • granularity 是这些值 ["Year", "Month", "Day", "Hour", "Minute", "Second"] 之一
    • +
    • 最多调用 500putretrieve
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0636.leetcode636 Exclusive Time of Functions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0636.leetcode636 Exclusive Time of Functions-zh.md" new file mode 100644 index 00000000..562eb128 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0636.leetcode636 Exclusive Time of Functions-zh.md" @@ -0,0 +1,73 @@ +# [636. 函数的独占时间](https://leetcode-cn.com/problems/exclusive-time-of-functions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0636.Exclusive%20Time%20of%20Functions/README_EN.md) + +## 题目描述 + + + +

    给出一个非抢占单线程CPU的 n 个函数运行日志,找到函数的独占时间。

    + +

    每个函数都有一个唯一的 Id,从 0 n-1,函数可能会递归调用或者被其他函数调用。

    + +

    日志是具有以下格式的字符串:function_id:start_or_end:timestamp。例如:"0:start:0" 表示函数 0 从 0 时刻开始运行。"0:end:0" 表示函数 0 在 0 时刻结束。

    + +

    函数的独占时间定义是在该方法中花费的时间,调用其他函数花费的时间不算该函数的独占时间。你需要根据函数的 Id 有序地返回每个函数的独占时间。

    + +

    示例 1:

    + +
    输入:
    +n = 2
    +logs = 
    +["0:start:0",
    + "1:start:2",
    + "1:end:5",
    + "0:end:6"]
    +输出:[3, 4]
    +说明:
    +函数 0 在时刻 0 开始,在执行了  2个时间单位结束于时刻 1。
    +现在函数 0 调用函数 1,函数 1 在时刻 2 开始,执行 4 个时间单位后结束于时刻 5。
    +函数 0 再次在时刻 6 开始执行,并在时刻 6 结束运行,从而执行了 1 个时间单位。
    +所以函数 0 总共的执行了 2 +1 =3 个时间单位,函数 1 总共执行了 4 个时间单位。
    +
    + +

    说明:

    + +
      +
    1. 输入的日志会根据时间戳排序,而不是根据日志Id排序。
    2. +
    3. 你的输出会根据函数Id排序,也就意味着你的输出数组中序号为 0 的元素相当于函数 0 的执行时间。
    4. +
    5. 两个函数不会在同时开始或结束。
    6. +
    7. 函数允许被递归调用,直到运行结束。
    8. +
    9. 1 <= n <= 100
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0637.leetcode637 Average of Levels in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0637.leetcode637 Average of Levels in Binary Tree-zh.md" new file mode 100644 index 00000000..ac3c9177 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0637.leetcode637 Average of Levels in Binary Tree-zh.md" @@ -0,0 +1,157 @@ +# [637. 二叉树的层平均值](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0637.Average%20of%20Levels%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:
    +    3
    +   / \
    +  9  20
    +    /  \
    +   15   7
    +输出:[3, 14.5, 11]
    +解释:
    +第 0 层的平均值是 3 ,  第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 节点值的范围在32位有符号整数范围内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def averageOfLevels(self, root: TreeNode) -> List[float]: + res = [] + q = collections.deque([root]) + while q: + n = len(q) + s = 0 + for _ in range(n): + node = q.popleft() + s += node.val + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + res.append(s / n) + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List averageOfLevels(TreeNode root) { + List res = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + double s = 0, n = q.size(); + for (int i = 0; i < n; ++i) { + TreeNode node = q.poll(); + s += node.val; + if (node.left != null) { + q.offer(node.left); + } + if (node.right != null) { + q.offer(node.right); + } + } + res.add(s / n); + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var averageOfLevels = function(root) { + let res = []; + let queue = [root]; + while (queue.length > 0) { + n = queue.length; + let sum = 0; + for (let i = 0; i < n; i++) { + let node = queue.shift(); + sum += node.val; + if (node.left) { + queue.push(node.left); + } + if (node.right) { + queue.push(node.right); + } + } + res.push(sum / n); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0638.leetcode638 Shopping Offers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0638.leetcode638 Shopping Offers-zh.md" new file mode 100644 index 00000000..7794ea4a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0638.leetcode638 Shopping Offers-zh.md" @@ -0,0 +1,77 @@ +# [638. 大礼包](https://leetcode-cn.com/problems/shopping-offers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0638.Shopping%20Offers/README_EN.md) + +## 题目描述 + + + +

    在LeetCode商店中, 有许多在售的物品。

    + +

    然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。

    + +

    现给定每个物品的价格,每个大礼包包含物品的清单,以及待购物品清单。请输出确切完成待购清单的最低花费。

    + +

    每个大礼包的由一个数组中的一组数据描述,最后一个数字代表大礼包的价格,其他数字分别表示内含的其他种类物品的数量。

    + +

    任意大礼包可无限次购买。

    + +

    示例 1:

    + +
    输入: [2,5], [[3,0,5],[1,2,10]], [3,2]
    +输出: 14
    +解释: 
    +有A和B两种物品,价格分别为¥2和¥5。
    +大礼包1,你可以以¥5的价格购买3A和0B。
    +大礼包2, 你可以以¥10的价格购买1A和2B。
    +你需要购买3个A和2个B, 所以你付了¥10购买了1A和2B(大礼包2),以及¥4购买2A。
    + +

    示例 2:

    + +
    输入: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
    +输出: 11
    +解释: 
    +A,B,C的价格分别为¥2,¥3,¥4.
    +你可以用¥4购买1A和1B,也可以用¥9购买2A,2B和1C。
    +你需要买1A,2B和1C,所以你付了¥4买了1A和1B(大礼包1),以及¥3购买1B, ¥4购买1C。
    +你不可以购买超出待购清单的物品,尽管购买大礼包2更加便宜。
    +
    + +

    说明:

    + +
      +
    1. 最多6种物品, 100种大礼包。
    2. +
    3. 每种物品,你最多只需要购买6个。
    4. +
    5. 你不可以购买超出待购清单的物品,即使更便宜。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0639.leetcode639 Decode Ways II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0639.leetcode639 Decode Ways II-zh.md" new file mode 100644 index 00000000..2783695f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0639.leetcode639 Decode Ways II-zh.md" @@ -0,0 +1,72 @@ +# [639. 解码方法 II](https://leetcode-cn.com/problems/decode-ways-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0639.Decode%20Ways%20II/README_EN.md) + +## 题目描述 + + + +

    一条包含字母 A-Z 的消息通过以下的方式进行了编码:

    + +
    'A' -> 1
    +'B' -> 2
    +...
    +'Z' -> 26
    +
    + +

    除了上述的条件以外,现在加密字符串可以包含字符 '*'了,字符'*'可以被当做1到9当中的任意一个数字。

    + +

    给定一条包含数字和字符'*'的加密信息,请确定解码方法的总数。

    + +

    同时,由于结果值可能会相当的大,所以你应当对109 + 7取模。(翻译者标注:此处取模主要是为了防止溢出)

    + +

    示例 1 :

    + +
    输入: "*"
    +输出: 9
    +解释: 加密的信息可以被解密为: "A", "B", "C", "D", "E", "F", "G", "H", "I".
    +
    + +

    示例 2 :

    + +
    输入: "1*"
    +输出: 9 + 9 = 18(翻译者标注:这里1*可以分解为1,* 或者当做1*来处理,所以结果是9+9=18)
    +
    + +

    说明 :

    + +
      +
    1. 输入的字符串长度范围是 [1, 105]。
    2. +
    3. 输入的字符串只会包含字符 '*' 和 数字'0' - '9'。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0640.leetcode640 Solve the Equation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0640.leetcode640 Solve the Equation-zh.md" new file mode 100644 index 00000000..5d96c3c5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0640.leetcode640 Solve the Equation-zh.md" @@ -0,0 +1,76 @@ +# [640. 求解方程](https://leetcode-cn.com/problems/solve-the-equation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0640.Solve%20the%20Equation/README_EN.md) + +## 题目描述 + + + +

    求解一个给定的方程,将x以字符串"x=#value"的形式返回。该方程仅包含'+',' - '操作,变量 x 和其对应系数。

    + +

    如果方程没有解,请返回“No solution”。

    + +

    如果方程有无限解,则返回“Infinite solutions”。

    + +

    如果方程中只有一个解,要保证返回值 x 是一个整数。

    + +

    示例 1:

    + +
    输入: "x+5-3+x=6+x-2"
    +输出: "x=2"
    +
    + +

    示例 2:

    + +
    输入: "x=x"
    +输出: "Infinite solutions"
    +
    + +

    示例 3:

    + +
    输入: "2x=x"
    +输出: "x=0"
    +
    + +

    示例 4:

    + +
    输入: "2x+3x-6x=x+2"
    +输出: "x=-1"
    +
    + +

    示例 5:

    + +
    输入: "x=x+2"
    +输出: "No solution"
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0641.leetcode641 Design Circular Deque-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0641.leetcode641 Design Circular Deque-zh.md" new file mode 100644 index 00000000..d8982547 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0641.leetcode641 Design Circular Deque-zh.md" @@ -0,0 +1,264 @@ +# [641. 设计循环双端队列](https://leetcode-cn.com/problems/design-circular-deque) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0641.Design%20Circular%20Deque/README_EN.md) + +## 题目描述 + + + +

    设计实现双端队列。
    +你的实现需要支持以下操作:

    + +
      +
    • MyCircularDeque(k):构造函数,双端队列的大小为k。
    • +
    • insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
    • +
    • insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
    • +
    • deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
    • +
    • deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
    • +
    • getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
    • +
    • getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
    • +
    • isEmpty():检查双端队列是否为空。
    • +
    • isFull():检查双端队列是否满了。
    • +
    + +

    示例:

    + +
    MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3
    +circularDeque.insertLast(1);			        // 返回 true
    +circularDeque.insertLast(2);			        // 返回 true
    +circularDeque.insertFront(3);			        // 返回 true
    +circularDeque.insertFront(4);			        // 已经满了,返回 false
    +circularDeque.getRear();  				// 返回 2
    +circularDeque.isFull();				        // 返回 true
    +circularDeque.deleteLast();			        // 返回 true
    +circularDeque.insertFront(4);			        // 返回 true
    +circularDeque.getFront();				// 返回 4
    + 
    + +

     

    + +

    提示:

    + +
      +
    • 所有值的范围为 [1, 1000]
    • +
    • 操作次数的范围为 [1, 1000]
    • +
    • 请不要使用内置的双端队列库。
    • +
    + +## 解法 + + + +“循环数组”实现。 + + + +### **Python3** + + + +```python +class MyCircularDeque: + + def __init__(self, k: int): + """ + Initialize your data structure here. Set the size of the deque to be k. + """ + self.q = [0] * k + self.front = 0 + self.size = 0 + self.capacity = k + + def insertFront(self, value: int) -> bool: + """ + Adds an item at the front of Deque. Return true if the operation is successful. + """ + if self.isFull(): + return False + if not self.isEmpty(): + self.front = (self.front - 1 + self.capacity) % self.capacity + self.q[self.front] = value + self.size += 1 + return True + + def insertLast(self, value: int) -> bool: + """ + Adds an item at the rear of Deque. Return true if the operation is successful. + """ + if self.isFull(): + return False + idx = (self.front + self.size) % self.capacity + self.q[idx] = value + self.size += 1 + return True + + def deleteFront(self) -> bool: + """ + Deletes an item from the front of Deque. Return true if the operation is successful. + """ + if self.isEmpty(): + return False + self.front = (self.front + 1) % self.capacity + self.size -= 1 + return True + + def deleteLast(self) -> bool: + """ + Deletes an item from the rear of Deque. Return true if the operation is successful. + """ + if self.isEmpty(): + return False + self.size -= 1 + return True + + def getFront(self) -> int: + """ + Get the front item from the deque. + """ + if self.isEmpty(): + return -1 + return self.q[self.front] + + def getRear(self) -> int: + """ + Get the last item from the deque. + """ + if self.isEmpty(): + return -1 + idx = (self.front + self.size - 1) % self.capacity + return self.q[idx] + + def isEmpty(self) -> bool: + """ + Checks whether the circular deque is empty or not. + """ + return self.size == 0 + + def isFull(self) -> bool: + """ + Checks whether the circular deque is full or not. + """ + return self.size == self.capacity + + +# Your MyCircularDeque object will be instantiated and called as such: +# obj = MyCircularDeque(k) +# param_1 = obj.insertFront(value) +# param_2 = obj.insertLast(value) +# param_3 = obj.deleteFront() +# param_4 = obj.deleteLast() +# param_5 = obj.getFront() +# param_6 = obj.getRear() +# param_7 = obj.isEmpty() +# param_8 = obj.isFull() +``` + +### **Java** + + + +```java +class MyCircularDeque { + private int[] q; + private int front; + private int size; + private int capacity; + + /** Initialize your data structure here. Set the size of the deque to be k. */ + public MyCircularDeque(int k) { + q = new int[k]; + capacity = k; + } + + /** Adds an item at the front of Deque. Return true if the operation is successful. */ + public boolean insertFront(int value) { + if (isFull()) { + return false; + } + if (!isEmpty()) { + front = (front - 1 + capacity) % capacity; + } + q[front] = value; + ++size; + return true; + } + + /** Adds an item at the rear of Deque. Return true if the operation is successful. */ + public boolean insertLast(int value) { + if (isFull()) { + return false; + } + int idx = (front + size) % capacity; + q[idx] = value; + ++size; + return true; + } + + /** Deletes an item from the front of Deque. Return true if the operation is successful. */ + public boolean deleteFront() { + if (isEmpty()) { + return false; + } + front = (front + 1) % capacity; + --size; + return true; + } + + /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ + public boolean deleteLast() { + if (isEmpty()) { + return false; + } + --size; + return true; + } + + /** Get the front item from the deque. */ + public int getFront() { + if (isEmpty()) { + return -1; + } + return q[front]; + } + + /** Get the last item from the deque. */ + public int getRear() { + if (isEmpty()) { + return -1; + } + int idx = (front + size - 1) % capacity; + return q[idx]; + } + + /** Checks whether the circular deque is empty or not. */ + public boolean isEmpty() { + return size == 0; + } + + /** Checks whether the circular deque is full or not. */ + public boolean isFull() { + return size == capacity; + } +} + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * MyCircularDeque obj = new MyCircularDeque(k); + * boolean param_1 = obj.insertFront(value); + * boolean param_2 = obj.insertLast(value); + * boolean param_3 = obj.deleteFront(); + * boolean param_4 = obj.deleteLast(); + * int param_5 = obj.getFront(); + * int param_6 = obj.getRear(); + * boolean param_7 = obj.isEmpty(); + * boolean param_8 = obj.isFull(); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0642.leetcode642 Design Search Autocomplete System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0642.leetcode642 Design Search Autocomplete System-zh.md" new file mode 100644 index 00000000..a98e6af9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0642.leetcode642 Design Search Autocomplete System-zh.md" @@ -0,0 +1,103 @@ +# [642. 设计搜索自动补全系统](https://leetcode-cn.com/problems/design-search-autocomplete-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0642.Design%20Search%20Autocomplete%20System/README_EN.md) + +## 题目描述 + + + +

    为搜索引擎设计一个搜索自动补全系统。用户会输入一条语句(最少包含一个字母,以特殊字符 '#' 结尾)。除 '#' 以外用户输入的每个字符,返回历史中热度前三并以当前输入部分为前缀的句子。下面是详细规则:

    + +
      +
    1. 一条句子的热度定义为历史上用户输入这个句子的总次数。
    2. +
    3. 返回前三的句子需要按照热度从高到低排序(第一个是最热门的)。如果有多条热度相同的句子,请按照 ASCII 码的顺序输出(ASCII 码越小排名越前)。
    4. +
    5. 如果满足条件的句子个数少于 3,将它们全部输出。
    6. +
    7. 如果输入了特殊字符,意味着句子结束了,请返回一个空集合。
    8. +
    + +

    你的工作是实现以下功能:

    + +

    构造函数:

    + +

    AutocompleteSystem(String[] sentences, int[] times): 这是构造函数,输入的是历史数据。 Sentences 是之前输入过的所有句子,Times 是每条句子输入的次数,你的系统需要记录这些历史信息。

    + +

    现在,用户输入一条新的句子,下面的函数会提供用户输入的下一个字符:

    + +

    List<String> input(char c): 其中 c 是用户输入的下一个字符。字符只会是小写英文字母('a' 'z' ),空格(' ')和特殊字符('#')。输出历史热度前三的具有相同前缀的句子。

    + +

     

    + +

    样例 :
    +操作 : AutocompleteSystem(["i love you", "island","ironman", "i love leetcode"], [5,3,2,2])
    +系统记录下所有的句子和出现的次数:
    +"i love you" : 5 次
    +"island" : 3 次
    +"ironman" : 2 次
    +"i love leetcode" : 2 次
    +现在,用户开始新的键入:

    + +


    +输入 : input('i')
    +输出 : ["i love you", "island","i love leetcode"]
    +解释 :
    +有四个句子含有前缀 "i"。其中 "ironman" 和 "i love leetcode" 有相同的热度,由于 ' ' 的 ASCII 码是 32 而 'r' 的 ASCII 码是 114,所以 "i love leetcode" 在 "ironman" 前面。同时我们只输出前三的句子,所以 "ironman" 被舍弃。
    +
    +输入 : input(' ')
    +输出 : ["i love you","i love leetcode"]
    +解释:
    +只有两个句子含有前缀 "i "
    +
    +输入 : input('a')
    +输出 : []
    +解释 :
    +没有句子有前缀 "i a"
    +
    +输入 : input('#')
    +输出 : []
    +解释 :

    + +

    用户输入结束,"i a" 被存到系统中,后面的输入被认为是下一次搜索。

    + +

     

    + +

    注释 :

    + +
      +
    1. 输入的句子以字母开头,以 '#' 结尾,两个字母之间最多只会出现一个空格。
    2. +
    3. 即将搜索的句子总数不会超过 100。每条句子的长度(包括已经搜索的和即将搜索的)也不会超过 100。
    4. +
    5. 即使只有一个字母,输出的时候请使用双引号而不是单引号。
    6. +
    7. 请记住清零 AutocompleteSystem 类中的变量,因为静态变量、类变量会在多组测试数据中保存之前结果。详情请看这里
    8. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0643.leetcode643 Maximum Average Subarray I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0643.leetcode643 Maximum Average Subarray I-zh.md" new file mode 100644 index 00000000..f1067778 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0643.leetcode643 Maximum Average Subarray I-zh.md" @@ -0,0 +1,101 @@ +# [643. 子数组最大平均数 I](https://leetcode-cn.com/problems/maximum-average-subarray-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0643.Maximum%20Average%20Subarray%20I/README_EN.md) + +## 题目描述 + + + +

    给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。

    + +

     

    + +

    示例:

    + +
    +输入:[1,12,-5,-6,50,3], k = 4
    +输出:12.75
    +解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= n <= 30,000。
    • +
    • 所给数据范围 [-10,000,10,000]。
    • +
    + + +## 解法 + + + +滑动窗口。 + + + +### **Python3** + + + +```python +class Solution: + def findMaxAverage(self, nums: List[int], k: int) -> float: + s = sum(nums[:k]) + ans = s + for i in range(k, len(nums)): + s += (nums[i] - nums[i - k]) + ans = max(ans, s) + return ans / k +``` + +### **Java** + + + +```java +class Solution { + public double findMaxAverage(int[] nums, int k) { + int s = 0; + for (int i = 0; i < k; ++i) { + s += nums[i]; + } + int ans = s; + for (int i = k; i < nums.length; ++i) { + s += (nums[i] - nums[i - k]); + ans = Math.max(ans, s); + } + return ans * 1.0 / k; + } +} +``` + +### **TypeScript** + +```ts +function findMaxAverage(nums: number[], k: number): number { + let n = nums.length; + let ans = 0; + let sum = 0; + // 前k + for (let i = 0; i < k; i++) { + sum += nums[i]; + } + ans = sum; + for (let i = k; i < n; i++) { + sum += (nums[i] - nums[i - k]); + ans = Math.max(ans, sum); + } + return ans / k; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0644.leetcode644 Maximum Average Subarray II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0644.leetcode644 Maximum Average Subarray II-zh.md" new file mode 100644 index 00000000..6b4eb173 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0644.leetcode644 Maximum Average Subarray II-zh.md" @@ -0,0 +1,74 @@ +# [644. 子数组最大平均数 II](https://leetcode-cn.com/problems/maximum-average-subarray-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0644.Maximum%20Average%20Subarray%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个包含 n 个整数的数组 nums ,和一个整数 k

    + +

    请你找出 长度大于等于 k 且含最大平均值的连续子数组。并输出这个最大平均值。任何计算误差小于 10-5 的结果都将被视为正确答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,12,-5,-6,50,3], k = 4
    +输出:12.75000
    +解释:
    +- 当长度为 4 的时候,连续子数组平均值分别为 [0.5, 12.75, 10.5] ,其中最大平均值是 12.75 。
    +- 当长度为 5 的时候,连续子数组平均值分别为 [10.4, 10.8] ,其中最大平均值是 10.8 。
    +- 当长度为 6 的时候,连续子数组平均值分别为 [9.16667] ,其中最大平均值是 9.16667 。
    +当取长度为 4 的子数组(即,子数组 [12, -5, -6, 50])的时候,可以得到最大的连续子数组平均值 12.75 ,所以返回 12.75 。
    +根据题目要求,无需考虑长度小于 4 的子数组。
    +
    + +

    示例 2:

    + +
    +输入:nums = [5], k = 1
    +输出:5.00000
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= k <= n <= 104
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0645.leetcode645 Set Mismatch-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0645.leetcode645 Set Mismatch-zh.md" new file mode 100644 index 00000000..a9595548 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0645.leetcode645 Set Mismatch-zh.md" @@ -0,0 +1,230 @@ +# [645. 错误的集合](https://leetcode-cn.com/problems/set-mismatch) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0645.Set%20Mismatch/README_EN.md) + +## 题目描述 + + + +

    集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复

    + +

    给定一个数组 nums 代表了集合 S 发生错误后的结果。

    + +

    请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,2,4]
    +输出:[2,3]
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,1]
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 104
    • +
    • 1 <= nums[i] <= 104
    • +
    + +## 解法 + + + +异或运算求解。 + +首先明确,两个相同的数异或之后的结果为 0。对该数组所有元素以及 `i∈[1, n]` 所有数字进行异或运算,结果就是**两个只出现一次的数字异或的结果**,即 `eor = a ^ b`。 + +找出这个结果 eor 中最后一个二进制位为 1 而其余位为 0 的数,即 `eor & (~eor + 1)`,之后遍历数组所有元素以及 `i∈[1, n]` 所有数字,二进制位为 0 的元素异或到 a。 + +遍历结束后 `b = eor ^ a`,返回结果即可。 + + + +### **Python3** + + + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + eor, n = 0, len(nums) + for i in range(1, n + 1): + eor ^= (i ^ nums[i - 1]) + diff = eor & (~eor + 1) + a = 0 + for i in range(1, n + 1): + if (nums[i - 1] & diff) == 0: + a ^= nums[i - 1] + if (i & diff) == 0: + a ^= i + b = eor ^ a + for num in nums: + if a == num: + return [a, b] + return [b, a] +``` + +### **Java** + + + +```java +class Solution { + public int[] findErrorNums(int[] nums) { + int eor = 0; + for (int i = 1; i <= nums.length; ++i) { + eor ^= (i ^ nums[i - 1]); + } + int diff = eor & (~eor + 1); + int a = 0; + for (int i = 1; i <= nums.length; ++i) { + if ((nums[i - 1] & diff) == 0) { + a ^= nums[i - 1]; + } + if ((i & diff) == 0) { + a ^= i; + } + } + int b = eor ^ a; + for (int num : nums) { + if (a == num) { + return new int[]{a, b}; + } + } + return new int[]{b, a}; + } +} +``` + +### **TypeScript** + +```ts +function findErrorNums(nums: number[]): number[] { + let xor = 0; + for (let i = 0; i < nums.length; ++i) { + xor ^= ((i + 1) ^ nums[i]); + } + + let divide = 1; + while ((xor & divide) == 0) { + divide <<= 1; + } + + let ans1 = 0, ans2 = 0; + for (let i = 0; i < nums.length; ++i) { + let cur = nums[i]; + if (divide & cur) { + ans1 ^= cur; + } else { + ans2 ^= cur; + } + + let idx = i + 1; + if (divide & idx) { + ans1 ^= idx; + } else { + ans2 ^= idx; + } + } + return nums.includes(ans1) ? [ans1, ans2] : [ans2, ans1]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int eor = 0, n = nums.size(); + for (int i = 1; i <= n; ++i) { + eor ^= (i ^ nums[i - 1]); + } + int diff = eor & (~eor + 1); + int a = 0; + for (int i = 1; i <= n; ++i) { + if ((nums[i - 1] & diff) == 0) { + a ^= nums[i - 1]; + } + if ((i & diff) == 0) { + a ^= i; + } + } + int b = eor ^ a; + for (int num : nums) { + if (a == num) { + return {a, b}; + } + } + return {b, a}; + } +}; +``` + +### **Go** + +把每个数都放到它应该在的位置,最后出现“异常”的就是重复的数和丢失的数。 + +```go +func findErrorNums(nums []int) []int { + n := len(nums) + for i := 0; i < n; i++ { + for nums[i] != i+1 && nums[nums[i]-1] != nums[i] { + nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] + } + } + for i := 0; i < n; i++ { + if nums[i] != i+1 { + return []int{nums[i], i + 1} + } + } + return []int{-1, -1} +} +``` + +也可以使用位运算。 + +```go +func findErrorNums(nums []int) []int { + eor, n := 0, len(nums) + for i := 1; i <= n; i++ { + eor ^= (i ^ nums[i-1]) + } + diff := eor & (-eor) + a := 0 + for i := 1; i <= n; i++ { + if (nums[i-1] & diff) == 0 { + a ^= nums[i-1] + } + if (i & diff) == 0 { + a ^= i + } + } + b := eor ^ a + for _, num := range nums { + if a == num { + return []int{a, b} + } + } + return []int{b, a} +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0646.leetcode646 Maximum Length of Pair Chain-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0646.leetcode646 Maximum Length of Pair Chain-zh.md" new file mode 100644 index 00000000..f328605d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0646.leetcode646 Maximum Length of Pair Chain-zh.md" @@ -0,0 +1,62 @@ +# [646. 最长数对链](https://leetcode-cn.com/problems/maximum-length-of-pair-chain) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0646.Maximum%20Length%20of%20Pair%20Chain/README_EN.md) + +## 题目描述 + + + +

    给出 n 个数对。 在每一个数对中,第一个数字总是比第二个数字小。

    + +

    现在,我们定义一种跟随关系,当且仅当 b < c 时,数对(c, d) 才可以跟在 (a, b) 后面。我们用这种形式来构造一个数对链。

    + +

    给定一个数对集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。

    + +

     

    + +

    示例:

    + +
    +输入:[[1,2], [2,3], [3,4]]
    +输出:2
    +解释:最长的数对链是 [1,2] -> [3,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给出数对的个数在 [1, 1000] 范围内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0647.leetcode647 Palindromic Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0647.leetcode647 Palindromic Substrings-zh.md" new file mode 100644 index 00000000..6d0cbb59 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0647.leetcode647 Palindromic Substrings-zh.md" @@ -0,0 +1,65 @@ +# [647. 回文子串](https://leetcode-cn.com/problems/palindromic-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0647.Palindromic%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

    + +

    具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

    + +

     

    + +

    示例 1:

    + +
    输入:"abc"
    +输出:3
    +解释:三个回文子串: "a", "b", "c"
    +
    + +

    示例 2:

    + +
    输入:"aaa"
    +输出:6
    +解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
    + +

     

    + +

    提示:

    + +
      +
    • 输入的字符串长度不会超过 1000 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0648.leetcode648 Replace Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0648.leetcode648 Replace Words-zh.md" new file mode 100644 index 00000000..01999a4b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0648.leetcode648 Replace Words-zh.md" @@ -0,0 +1,92 @@ +# [648. 单词替换](https://leetcode-cn.com/problems/replace-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0648.Replace%20Words/README_EN.md) + +## 题目描述 + + + +

    在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。

    + +

    现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。

    + +

    你需要输出替换之后的句子。

    + +

     

    + +

    示例 1:

    + +
    输入:dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
    +输出:"the cat was rat by the bat"
    +
    + +

    示例 2:

    + +
    输入:dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
    +输出:"a a b c"
    +
    + +

    示例 3:

    + +
    输入:dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
    +输出:"a a a a a a a a bbb baba a"
    +
    + +

    示例 4:

    + +
    输入:dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
    +输出:"the cat was rat by the bat"
    +
    + +

    示例 5:

    + +
    输入:dictionary = ["ac","ab"], sentence = "it is abnormal that this solution is accepted"
    +输出:"it is ab that this solution is ac"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= dictionary.length <= 1000
    • +
    • 1 <= dictionary[i].length <= 100
    • +
    • dictionary[i] 仅由小写字母组成。
    • +
    • 1 <= sentence.length <= 10^6
    • +
    • sentence 仅由小写字母和空格组成。
    • +
    • sentence 中单词的总量在范围 [1, 1000] 内。
    • +
    • sentence 中每个单词的长度在范围 [1, 1000] 内。
    • +
    • sentence 中单词之间由一个空格隔开。
    • +
    • sentence 没有前导或尾随空格。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0649.leetcode649 Dota2 Senate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0649.leetcode649 Dota2 Senate-zh.md" new file mode 100644 index 00000000..1195383f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0649.leetcode649 Dota2 Senate-zh.md" @@ -0,0 +1,95 @@ +# [649. Dota2 参议院](https://leetcode-cn.com/problems/dota2-senate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0649.Dota2%20Senate/README_EN.md) + +## 题目描述 + + + +

    Dota2 的世界里有两个阵营:Radiant(天辉)和 Dire(夜魇)

    + +

    Dota2 参议院由来自两派的参议员组成。现在参议院希望对一个 Dota2 游戏里的改变作出决定。他们以一个基于轮为过程的投票进行。在每一轮中,每一位参议员都可以行使两项权利中的项:

    + +
      +
    1. +

      禁止一名参议员的权利

      + +

      参议员可以让另一位参议员在这一轮和随后的几轮中丧失所有的权利

      +
    2. +
    3. +

      宣布胜利

      +
    4. +
    + +

              如果参议员发现有权利投票的参议员都是同一个阵营的,他可以宣布胜利并决定在游戏中的有关变化。

    + +

     

    + +

    给定一个字符串代表每个参议员的阵营。字母 “R” 和 “D” 分别代表了 Radiant(天辉)和 Dire(夜魇)。然后,如果有 n 个参议员,给定字符串的大小将是 n

    + +

    以轮为基础的过程从给定顺序的第一个参议员开始到最后一个参议员结束。这一过程将持续到投票结束。所有失去权利的参议员将在过程中被跳过。

    + +

    假设每一位参议员都足够聪明,会为自己的政党做出最好的策略,你需要预测哪一方最终会宣布胜利并在 Dota2 游戏中决定改变。输出应该是 Radiant 或 Dire

    + +

     

    + +

    示例 1:

    + +
    +输入:"RD"
    +输出:"Radiant"
    +解释:第一个参议员来自 Radiant 阵营并且他可以使用第一项权利让第二个参议员失去权力,因此第二个参议员将被跳过因为他没有任何权利。然后在第二轮的时候,第一个参议员可以宣布胜利,因为他是唯一一个有投票权的人
    +
    + +

    示例 2:

    + +
    +输入:"RDD"
    +输出:"Dire"
    +解释:
    +第一轮中,第一个来自 Radiant 阵营的参议员可以使用第一项权利禁止第二个参议员的权利
    +第二个来自 Dire 阵营的参议员会被跳过因为他的权利被禁止
    +第三个来自 Dire 阵营的参议员可以使用他的第一项权利禁止第一个参议员的权利
    +因此在第二轮只剩下第三个参议员拥有投票的权利,于是他可以宣布胜利
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定字符串的长度在 [1, 10,000] 之间.
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0650.leetcode650 2 Keys Keyboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0650.leetcode650 2 Keys Keyboard-zh.md" new file mode 100644 index 00000000..d79e62a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0650.leetcode650 2 Keys Keyboard-zh.md" @@ -0,0 +1,65 @@ +# [650. 只有两个键的键盘](https://leetcode-cn.com/problems/2-keys-keyboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0650.2%20Keys%20Keyboard/README_EN.md) + +## 题目描述 + + + +

    最初在一个记事本上只有一个字符 'A'。你每次可以对这个记事本进行两种操作:

    + +
      +
    1. Copy All (复制全部) : 你可以复制这个记事本中的所有字符(部分的复制是不允许的)。
    2. +
    3. Paste (粘贴) : 你可以粘贴你上一次复制的字符。
    4. +
    + +

    给定一个数字 n 。你需要使用最少的操作次数,在记事本中打印出恰好 n 个 'A'。输出能够打印出 n 个 'A' 的最少操作次数。

    + +

    示例 1:

    + +
    +输入: 3
    +输出: 3
    +解释:
    +最初, 我们只有一个字符 'A'。
    +第 1 步, 我们使用 Copy All 操作。
    +第 2 步, 我们使用 Paste 操作来获得 'AA'。
    +第 3 步, 我们使用 Paste 操作来获得 'AAA'。
    +
    + +

    说明:

    + +
      +
    1. n 的取值范围是 [1, 1000] 。
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0651.leetcode651 4 Keys Keyboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0651.leetcode651 4 Keys Keyboard-zh.md" new file mode 100644 index 00000000..396479f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0651.leetcode651 4 Keys Keyboard-zh.md" @@ -0,0 +1,81 @@ +# [651. 4键键盘](https://leetcode-cn.com/problems/4-keys-keyboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0651.4%20Keys%20Keyboard/README_EN.md) + +## 题目描述 + + + +

    假设你有一个特殊的键盘包含下面的按键:

    + +

    Key 1: (A):在屏幕上打印一个 'A'。

    + +

    Key 2: (Ctrl-A):选中整个屏幕。

    + +

    Key 3: (Ctrl-C):复制选中区域到缓冲区。

    + +

    Key 4: (Ctrl-V):将缓冲区内容输出到上次输入的结束位置,并显示在屏幕上。

    + +

    现在,你只可以按键 N 次(使用上述四种按键),请问屏幕上最多可以显示几个 'A'呢?

    + +

    样例 1:

    + +
    输入: N = 3
    +输出: 3
    +解释: 
    +我们最多可以在屏幕上显示三个'A'通过如下顺序按键:
    +A, A, A
    +
    + +

     

    + +

    样例 2:

    + +
    输入: N = 7
    +输出: 9
    +解释: 
    +我们最多可以在屏幕上显示九个'A'通过如下顺序按键:
    +A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
    +
    + +

     

    + +

    注释:

    + +
      +
    1. 1 <= N <= 50
    2. +
    3. 结果不会超过 32 位有符号整数范围。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0652.leetcode652 Find Duplicate Subtrees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0652.leetcode652 Find Duplicate Subtrees-zh.md" new file mode 100644 index 00000000..a7c3ca0b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0652.leetcode652 Find Duplicate Subtrees-zh.md" @@ -0,0 +1,67 @@ +# [652. 寻找重复的子树](https://leetcode-cn.com/problems/find-duplicate-subtrees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0652.Find%20Duplicate%20Subtrees/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。

    + +

    两棵树重复是指它们具有相同的结构以及相同的结点值。

    + +

    示例 1:

    + +
            1
    +       / \
    +      2   3
    +     /   / \
    +    4   2   4
    +       /
    +      4
    +
    + +

    下面是两个重复的子树:

    + +
          2
    +     /
    +    4
    +
    + +

    + +
        4
    +
    + +

    因此,你需要以列表的形式返回上述重复子树的根结点。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0653.leetcode653 Two Sum IV - Input is a BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0653.leetcode653 Two Sum IV - Input is a BST-zh.md" new file mode 100644 index 00000000..0e9f08f7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0653.leetcode653 Two Sum IV - Input is a BST-zh.md" @@ -0,0 +1,74 @@ +# [653. 两数之和 IV - 输入 BST](https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0653.Two%20Sum%20IV%20-%20Input%20is%20a%20BST/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。

    + +

    案例 1:

    + +
    +输入: 
    +    5
    +   / \
    +  3   6
    + / \   \
    +2   4   7
    +
    +Target = 9
    +
    +输出: True
    +
    + +

     

    + +

    案例 2:

    + +
    +输入: 
    +    5
    +   / \
    +  3   6
    + / \   \
    +2   4   7
    +
    +Target = 28
    +
    +输出: False
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0654.leetcode654 Maximum Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0654.leetcode654 Maximum Binary Tree-zh.md" new file mode 100644 index 00000000..d18962c7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0654.leetcode654 Maximum Binary Tree-zh.md" @@ -0,0 +1,84 @@ +# [654. 最大二叉树](https://leetcode-cn.com/problems/maximum-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0654.Maximum%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的 最大二叉树 定义如下:

    + +
      +
    1. 二叉树的根是数组 nums 中的最大元素。
    2. +
    3. 左子树是通过数组中 最大值左边部分 递归构造出的最大二叉树。
    4. +
    5. 右子树是通过数组中 最大值右边部分 递归构造出的最大二叉树。
    6. +
    + +

    返回有给定数组 nums 构建的 最大二叉树

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3,2,1,6,0,5]
    +输出:[6,3,5,null,2,0,null,null,1]
    +解释:递归调用如下所示:
    +- [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。
    +    - [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。
    +        - 空数组,无子节点。
    +        - [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。
    +            - 空数组,无子节点。
    +            - 只有一个元素,所以子节点是一个值为 1 的节点。
    +    - [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。
    +        - 只有一个元素,所以子节点是一个值为 0 的节点。
    +        - 空数组,无子节点。
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,2,1]
    +输出:[3,null,2,null,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 0 <= nums[i] <= 1000
    • +
    • nums 中的所有整数 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0655.leetcode655 Print Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0655.leetcode655 Print Binary Tree-zh.md" new file mode 100644 index 00000000..1594ba02 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0655.leetcode655 Print Binary Tree-zh.md" @@ -0,0 +1,95 @@ +# [655. 输出二叉树](https://leetcode-cn.com/problems/print-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0655.Print%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    在一个 m*n 的二维字符串数组中输出二叉树,并遵守以下规则:

    + +
      +
    1. 行数 m 应当等于给定二叉树的高度。
    2. +
    3. 列数 n 应当总是奇数。
    4. +
    5. 根节点的值(以字符串格式给出)应当放在可放置的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分)。你应该将左子树输出在左下部分,右子树输出在右下部分。左下和右下部分应当有相同的大小。即使一个子树为空而另一个非空,你不需要为空的子树输出任何东西,但仍需要为另一个子树留出足够的空间。然而,如果两个子树都为空则不需要为它们留出任何空间。
    6. +
    7. 每个未使用的空间应包含一个空的字符串""
    8. +
    9. 使用相同的规则输出子树。
    10. +
    + +

    示例 1:

    + +
    +输入:
    +     1
    +    /
    +   2
    +输出:
    +[["", "1", ""],
    + ["2", "", ""]]
    +
    + +

    示例 2:

    + +
    +输入:
    +     1
    +    / \
    +   2   3
    +    \
    +     4
    +输出:
    +[["", "", "", "1", "", "", ""],
    + ["", "2", "", "", "", "3", ""],
    + ["", "", "4", "", "", "", ""]]
    +
    + +

    示例 3:

    + +
    +输入:
    +      1
    +     / \
    +    2   5
    +   / 
    +  3 
    + / 
    +4 
    +输出:
    +[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
    + ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
    + ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
    + ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]
    +
    + +

    注意: 二叉树的高度在范围 [1, 10] 中。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0656.leetcode656 Coin Path-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0656.leetcode656 Coin Path-zh.md" new file mode 100644 index 00000000..bfa4a1c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0656.leetcode656 Coin Path-zh.md" @@ -0,0 +1,75 @@ +# [656. 金币路径](https://leetcode-cn.com/problems/coin-path) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0656.Coin%20Path/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 A(下标从 1 开始)包含 N 个整数:A1,A2,……,AN 和一个整数 B。你可以从数组 A 中的任何一个位置(下标为 i)跳到下标 i+1i+2,……,i+B 的任意一个可以跳到的位置上。如果你在下标为 i 的位置上,你需要支付 Ai 个金币。如果 Ai 是 -1,意味着下标为 i 的位置是不可以跳到的。

    + +

    现在,你希望花费最少的金币从数组 A1 位置跳到 N 位置,你需要输出花费最少的路径,依次输出所有经过的下标(从 1 到 N)。

    + +

    如果有多种花费最少的方案,输出字典顺序最小的路径。

    + +

    如果无法到达 N 位置,请返回一个空数组。

    + +

     

    + +

    样例 1 :

    + +
    输入: [1,2,4,-1,2], 2
    +输出: [1,3,5]
    +
    + +

     

    + +

    样例 2 :

    + +
    输入: [1,2,4,-1,2], 1
    +输出: []
    +
    + +

     

    + +

    注释 :

    + +
      +
    1. 路径 Pa1,Pa2,……,Pa是字典序小于 Pb1,Pb2,……,Pb的,当且仅当第一个 Pai 和 Pbi 不同的 i 满足 Pai < Pbi,如果不存在这样的 i 那么满足 n < m
    2. +
    3. A1 >= 0。 A2, ..., AN (如果存在) 的范围是 [-1, 100]。
    4. +
    5. A 数组的长度范围 [1, 1000].
    6. +
    7. B 的范围 [1, 100].
    8. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0657.leetcode657 Robot Return to Origin-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0657.leetcode657 Robot Return to Origin-zh.md" new file mode 100644 index 00000000..beb0b8ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0657.leetcode657 Robot Return to Origin-zh.md" @@ -0,0 +1,82 @@ +# [657. 机器人能否返回原点](https://leetcode-cn.com/problems/robot-return-to-origin) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0657.Robot%20Return%20to%20Origin/README_EN.md) + +## 题目描述 + + + +

    在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束

    + +

    移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。

    + +

    注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。

    + +

     

    + +

    示例 1:

    + +
    输入: "UD"
    +输出: true
    +解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
    + +

    示例 2:

    + +
    输入: "LL"
    +输出: false
    +解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def judgeCircle(self, moves: str) -> bool: + x = y = 0 + for c in moves: + if c == 'R': + x += 1 + elif c == 'L': + x -= 1 + elif c == 'U': + y += 1 + elif c == 'D': + y -= 1 + return x == 0 and y == 0 +``` + +### **Java** + + + +```java +class Solution { + public boolean judgeCircle(String moves) { + int x = 0, y = 0; + for (int i = 0; i < moves.length(); ++i) { + char c = moves.charAt(i); + if (c == 'R') ++x; + else if (c == 'L') --x; + else if (c == 'U') ++y; + else if (c == 'D') --y; + } + return x == 0 && y == 0; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0658.leetcode658 Find K Closest Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0658.leetcode658 Find K Closest Elements-zh.md" new file mode 100644 index 00000000..99a1eabe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0658.leetcode658 Find K Closest Elements-zh.md" @@ -0,0 +1,73 @@ +# [658. 找到 K 个最接近的元素](https://leetcode-cn.com/problems/find-k-closest-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0658.Find%20K%20Closest%20Elements/README_EN.md) + +## 题目描述 + + + +

    给定一个排序好的数组 arr ,两个整数 kx ,从数组中找到最靠近 x(两数之差最小)的 k 个数。返回的结果必须要是按升序排好的。

    + +

    整数 a 比整数 b 更接近 x 需要满足:

    + +
      +
    • |a - x| < |b - x| 或者
    • +
    • |a - x| == |b - x|a < b
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [1,2,3,4,5], k = 4, x = 3
    +输出:[1,2,3,4]
    +
    + +

    示例 2:

    + +
    +输入:arr = [1,2,3,4,5], k = 4, x = -1
    +输出:[1,2,3,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= arr.length
    • +
    • 1 <= arr.length <= 104
    • +
    • 数组里的每个元素与 x 的绝对值不超过 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0659.leetcode659 Split Array into Consecutive Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0659.leetcode659 Split Array into Consecutive Subsequences-zh.md" new file mode 100644 index 00000000..262dfac2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0659.leetcode659 Split Array into Consecutive Subsequences-zh.md" @@ -0,0 +1,81 @@ +# [659. 分割数组为连续子序列](https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0659.Split%20Array%20into%20Consecutive%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给你一个按升序排序的整数数组 num(可能包含重复数字),请你将它们分割成一个或多个长度至少为 3 的子序列,其中每个子序列都由连续整数组成。

    + +

    如果可以完成上述分割,则返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入: [1,2,3,3,4,5]
    +输出: True
    +解释:
    +你可以分割出这样两个连续子序列 : 
    +1, 2, 3
    +3, 4, 5
    +
    + +

    示例 2:

    + +
    +输入: [1,2,3,3,4,4,5,5]
    +输出: True
    +解释:
    +你可以分割出这样两个连续子序列 : 
    +1, 2, 3, 4, 5
    +3, 4, 5
    +
    + +

    示例 3:

    + +
    +输入: [1,2,3,4,4,5]
    +输出: False
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0660.leetcode660 Remove 910660.leetcode660 Remove 9-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0660.leetcode660 Remove 910660.leetcode660 Remove 9-zh.md" new file mode 100644 index 00000000..8649b1ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0660.leetcode660 Remove 910660.leetcode660 Remove 9-zh.md" @@ -0,0 +1,56 @@ +# [660. 移除 9](https://leetcode-cn.com/problems/remove-9) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0660.Remove%209/README_EN.md) + +## 题目描述 + + + +

    从 1 开始,移除所有包含数字 9 的所有整数,例如 9,19,29,……

    + +

    这样就获得了一个新的整数数列:1,2,3,4,5,6,7,8,10,11,……

    + +

    给定正整数 n,请你返回新数列中第 n 个数字是多少。1 是新数列中的第一个数字。

    + +

     

    + +

    样例 1:

    + +
    输入: 9
    +输出: 10
    +
    + +

     

    + +

    注释 :n 不会超过 9 x 10^8

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0661.leetcode661 Image Smoother-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0661.leetcode661 Image Smoother-zh.md" new file mode 100644 index 00000000..71aa922c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0661.leetcode661 Image Smoother-zh.md" @@ -0,0 +1,64 @@ +# [661. 图片平滑器](https://leetcode-cn.com/problems/image-smoother) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0661.Image%20Smoother/README_EN.md) + +## 题目描述 + + + +

    包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

    + +

    示例 1:

    + +
    +输入:
    +[[1,1,1],
    + [1,0,1],
    + [1,1,1]]
    +输出:
    +[[0, 0, 0],
    + [0, 0, 0],
    + [0, 0, 0]]
    +解释:
    +对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
    +对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
    +对于点 (1,1): 平均(8/9) = 平均(0.88888889) = 0
    +
    + +

    注意:

    + +
      +
    1. 给定矩阵中的整数范围为 [0, 255]。
    2. +
    3. 矩阵的长和宽的范围均为 [1, 150]。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0662.leetcode662 Maximum Width of Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0662.leetcode662 Maximum Width of Binary Tree-zh.md" new file mode 100644 index 00000000..a774bb53 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0662.leetcode662 Maximum Width of Binary Tree-zh.md" @@ -0,0 +1,105 @@ +# [662. 二叉树最大宽度](https://leetcode-cn.com/problems/maximum-width-of-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0662.Maximum%20Width%20of%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。

    + +

    每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。

    + +

    示例 1:

    + +
    +输入: 
    +
    +           1
    +         /   \
    +        3     2
    +       / \     \  
    +      5   3     9 
    +
    +输出: 4
    +解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
    +
    + +

    示例 2:

    + +
    +输入: 
    +
    +          1
    +         /  
    +        3    
    +       / \       
    +      5   3     
    +
    +输出: 2
    +解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。
    +
    + +

    示例 3:

    + +
    +输入: 
    +
    +          1
    +         / \
    +        3   2 
    +       /        
    +      5      
    +
    +输出: 2
    +解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。
    +
    + +

    示例 4:

    + +
    +输入: 
    +
    +          1
    +         / \
    +        3   2
    +       /     \  
    +      5       9 
    +     /         \
    +    6           7
    +输出: 8
    +解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。
    +
    + +

    注意: 答案在32位有符号整数的表示范围内。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0663.leetcode663 Equal Tree Partition-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0663.leetcode663 Equal Tree Partition-zh.md" new file mode 100644 index 00000000..b7e759b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0663.leetcode663 Equal Tree Partition-zh.md" @@ -0,0 +1,90 @@ +# [663. 均匀树划分](https://leetcode-cn.com/problems/equal-tree-partition) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0663.Equal%20Tree%20Partition/README_EN.md) + +## 题目描述 + + + +

    给定一棵有 n 个结点的二叉树,你的任务是检查是否可以通过去掉树上的一条边将树分成两棵,且这两棵树结点之和相等。

    + +

    样例 1:

    + +
    输入:     
    +    5
    +   / \
    +  10 10
    +    /  \
    +   2   3
    +
    +输出: True
    +解释: 
    +    5
    +   / 
    +  10
    +      
    +和: 15
    +
    +   10
    +  /  \
    + 2    3
    +
    +和: 15
    +
    + +

     

    + +

    样例 2:

    + +
    输入:     
    +    1
    +   / \
    +  2  10
    +    /  \
    +   2   20
    +
    +输出: False
    +解释: 无法通过移除一条树边将这棵树划分成结点之和相等的两棵子树。
    +
    + +

     

    + +

    注释 :

    + +
      +
    1. 树上结点的权值范围 [-100000, 100000]。
    2. +
    3. 1 <= n <= 10000
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0664.leetcode664 Strange Printer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0664.leetcode664 Strange Printer-zh.md" new file mode 100644 index 00000000..42a6f0f8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0664.leetcode664 Strange Printer-zh.md" @@ -0,0 +1,64 @@ +# [664. 奇怪的打印机](https://leetcode-cn.com/problems/strange-printer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0664.Strange%20Printer/README_EN.md) + +## 题目描述 + + + +

    有台奇怪的打印机有以下两个特殊要求:

    + +
      +
    1. 打印机每次只能打印同一个字符序列。
    2. +
    3. 每次可以在任意起始和结束位置打印新字符,并且会覆盖掉原来已有的字符。
    4. +
    + +

    给定一个只包含小写英文字母的字符串,你的任务是计算这个打印机打印它需要的最少次数。

    + +

    示例 1:

    + +
    +输入: "aaabbb"
    +输出: 2
    +解释: 首先打印 "aaa" 然后打印 "bbb"。
    +
    + +

    示例 2:

    + +
    +输入: "aba"
    +输出: 2
    +解释: 首先打印 "aaa" 然后在第二个位置打印 "b" 覆盖掉原来的字符 'a'。
    + +

    提示: 输入字符串的长度不会超过 100。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0665.leetcode665 Non-decreasing Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0665.leetcode665 Non-decreasing Array-zh.md" new file mode 100644 index 00000000..a8f72eee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0665.leetcode665 Non-decreasing Array-zh.md" @@ -0,0 +1,69 @@ +# [665. 非递减数列](https://leetcode-cn.com/problems/non-decreasing-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0665.Non-decreasing%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。

    + +

    我们是这样定义一个非递减数列的: 对于数组中任意的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]

    + +

     

    + +

    示例 1:

    + +
    +输入: nums = [4,2,3]
    +输出: true
    +解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。
    +
    + +

    示例 2:

    + +
    +输入: nums = [4,2,1]
    +输出: false
    +解释: 你不能在只改变一个元素的情况下将其变为非递减数列。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10 ^ 4
    • +
    • - 10 ^ 5 <= nums[i] <= 10 ^ 5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0666.leetcode666 Path Sum IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0666.leetcode666 Path Sum IV-zh.md" new file mode 100644 index 00000000..73a1ec0e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0666.leetcode666 Path Sum IV-zh.md" @@ -0,0 +1,82 @@ +# [666. 路径总和 IV](https://leetcode-cn.com/problems/path-sum-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0666.Path%20Sum%20IV/README_EN.md) + +## 题目描述 + + + +

    对于一棵深度小于 5 的树,可以用一组三位十进制整数来表示。

    + +

    对于每个整数:

    + +
      +
    1. 百位上的数字表示这个节点的深度 D1 <= D <= 4
    2. +
    3. 十位上的数字表示这个节点在当前层所在的位置 P1 <= P <= 8。位置编号与一棵满二叉树的位置编号相同。
    4. +
    5. 个位上的数字表示这个节点的权值 V0 <= V <= 9
    6. +
    + +

    给定一个包含三位整数的升序数组,表示一棵深度小于 5 的二叉树,请你返回从根到所有叶子结点的路径之和。

    + +

     

    + +

    示例 1:

    + +
    +输入: [113, 215, 221]
    +输出: 12
    +解释: 
    +这棵树形状如下:
    +    3
    +   / \
    +  5   1
    +
    +路径和 = (3 + 5) + (3 + 1) = 12.
    +
    + +

    示例 2:

    + +
    +输入: [113, 221]
    +输出: 4
    +解释: 
    +这棵树形状如下: 
    +    3
    +     \
    +      1
    +
    +路径和 = (3 + 1) = 4.
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0667.leetcode667 Beautiful Arrangement II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0667.leetcode667 Beautiful Arrangement II-zh.md" new file mode 100644 index 00000000..36c5091a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0667.leetcode667 Beautiful Arrangement II-zh.md" @@ -0,0 +1,72 @@ +# [667. 优美的排列 II](https://leetcode-cn.com/problems/beautiful-arrangement-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0667.Beautiful%20Arrangement%20II/README_EN.md) + +## 题目描述 + + + +

    给定两个整数 n 和 k,你需要实现一个数组,这个数组包含从 1 到 n 的 n 个不同整数,同时满足以下条件:

    + +

    ① 如果这个数组是 [a1, a2, a3, ... , an] ,那么数组 [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 中应该有且仅有 k 个不同整数;.

    + +

    ② 如果存在多种答案,你只需实现并返回其中任意一种.

    + +

    示例 1:

    + +
    +输入: n = 3, k = 1
    +输出: [1, 2, 3]
    +解释: [1, 2, 3] 包含 3 个范围在 1-3 的不同整数, 并且 [1, 1] 中有且仅有 1 个不同整数 : 1
    +
    + +

     

    + +

    示例 2:

    + +
    +输入: n = 3, k = 2
    +输出: [1, 3, 2]
    +解释: [1, 3, 2] 包含 3 个范围在 1-3 的不同整数, 并且 [2, 1] 中有且仅有 2 个不同整数: 1 和 2
    +
    + +

     

    + +

    提示:

    + +
      +
    1.  n 和 k 满足条件 1 <= k < n <= 104.
    2. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0668.leetcode668 Kth Smallest Number in Multiplication Table-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0668.leetcode668 Kth Smallest Number in Multiplication Table-zh.md" new file mode 100644 index 00000000..15b67661 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0668.leetcode668 Kth Smallest Number in Multiplication Table-zh.md" @@ -0,0 +1,76 @@ +# [668. 乘法表中第k小的数](https://leetcode-cn.com/problems/kth-smallest-number-in-multiplication-table) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0668.Kth%20Smallest%20Number%20in%20Multiplication%20Table/README_EN.md) + +## 题目描述 + + + +

    几乎每一个人都用 乘法表。但是你能在乘法表中快速找到第k小的数字吗?

    + +

    给定高度m 、宽度n 的一张 m * n的乘法表,以及正整数k,你需要返回表中第k 小的数字。

    + +

    例 1:

    + +
    +输入: m = 3, n = 3, k = 5
    +输出: 3
    +解释: 
    +乘法表:
    +1	2	3
    +2	4	6
    +3	6	9
    +
    +第5小的数字是 3 (1, 2, 2, 3, 3).
    +
    + +

    例 2:

    + +
    +输入: m = 2, n = 3, k = 6
    +输出: 6
    +解释: 
    +乘法表:
    +1	2	3
    +2	4	6
    +
    +第6小的数字是 6 (1, 2, 2, 3, 4, 6).
    +
    + +

    注意:

    + +
      +
    1. m 和 n 的范围在 [1, 30000] 之间。
    2. +
    3. k 的范围在 [1, m * n] 之间。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0669.leetcode669 Trim a Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0669.leetcode669 Trim a Binary Search Tree-zh.md" new file mode 100644 index 00000000..f85dd7ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0669.leetcode669 Trim a Binary Search Tree-zh.md" @@ -0,0 +1,91 @@ +# [669. 修剪二叉搜索树](https://leetcode-cn.com/problems/trim-a-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0669.Trim%20a%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树不应该改变保留在树中的元素的相对结构(即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在唯一的答案。

    + +

    所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,0,2], low = 1, high = 2
    +输出:[1,null,2]
    +
    + +

    示例 2:

    + +
    +输入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
    +输出:[3,2,null,1]
    +
    + +

    示例 3:

    + +
    +输入:root = [1], low = 1, high = 2
    +输出:[1]
    +
    + +

    示例 4:

    + +
    +输入:root = [1,null,2], low = 1, high = 3
    +输出:[1,null,2]
    +
    + +

    示例 5:

    + +
    +输入:root = [1,null,2], low = 2, high = 4
    +输出:[2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数在范围 [1, 104]
    • +
    • 0 <= Node.val <= 104
    • +
    • 树中每个节点的值都是唯一的
    • +
    • 题目数据保证输入是一棵有效的二叉搜索树
    • +
    • 0 <= low <= high <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0670.leetcode670 Maximum Swap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0670.leetcode670 Maximum Swap-zh.md" new file mode 100644 index 00000000..bcd87d68 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0670.leetcode670 Maximum Swap-zh.md" @@ -0,0 +1,62 @@ +# [670. 最大交换](https://leetcode-cn.com/problems/maximum-swap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0670.Maximum%20Swap/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数,你至多可以交换一次数字中的任意两位。返回你能得到的最大值。

    + +

    示例 1 :

    + +
    +输入: 2736
    +输出: 7236
    +解释: 交换数字2和数字7。
    +
    + +

    示例 2 :

    + +
    +输入: 9973
    +输出: 9973
    +解释: 不需要交换。
    +
    + +

    注意:

    + +
      +
    1. 给定数字的范围是 [0, 108]
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0671.leetcode671 Second Minimum Node In a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0671.leetcode671 Second Minimum Node In a Binary Tree-zh.md" new file mode 100644 index 00000000..bc95e905 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0671.leetcode671 Second Minimum Node In a Binary Tree-zh.md" @@ -0,0 +1,123 @@ +# [671. 二叉树中第二小的节点](https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0671.Second%20Minimum%20Node%20In%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么该节点的值等于两个子节点中较小的一个。

    + +

    更正式地说,root.val = min(root.left.val, root.right.val) 总成立。

    + +

    给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [2,2,5,null,null,5,7]
    +输出:5
    +解释:最小的值是 2 ,第二小的值是 5 。
    +
    + +

    示例 2:

    + +
    +输入:root = [2,2,2]
    +输出:-1
    +解释:最小的值是 2, 但是不存在第二小的值。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [1, 25]
    • +
    • 1 <= Node.val <= 231 - 1
    • +
    • 对于树中每个节点 root.val == min(root.left.val, root.right.val)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findSecondMinimumValue(self, root: TreeNode) -> int: + def traverse(root, val): + if root is None: + return + traverse(root.left, val) + traverse(root.right, val) + if root.val > val: + self.res = root.val if self.res == -1 else min(self.res, root.val) + + self.res = -1 + traverse(root, root.val) + return self.res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int res; + public int findSecondMinimumValue(TreeNode root) { + res = -1; + traverse(root, root.val); + return res; + } + + private void traverse(TreeNode root, int min) { + if (root == null) { + return; + } + traverse(root.left, min); + traverse(root.right, min); + if (root.val > min) { + res = res == -1 ? root.val : Math.min(res, root.val); + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0672.leetcode672 Bulb Switcher II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0672.leetcode672 Bulb Switcher II-zh.md" new file mode 100644 index 00000000..d83b1d37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0672.leetcode672 Bulb Switcher II-zh.md" @@ -0,0 +1,72 @@ +# [672. 灯泡开关 Ⅱ](https://leetcode-cn.com/problems/bulb-switcher-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0672.Bulb%20Switcher%20II/README_EN.md) + +## 题目描述 + + + +

    现有一个房间,墙上挂有 n 只已经打开的灯泡和 4 个按钮。在进行了 m 次未知操作后,你需要返回这 n 只灯泡可能有多少种不同的状态。

    + +

    假设这 n 只灯泡被编号为 [1, 2, 3 ..., n],这 4 个按钮的功能如下:

    + +
      +
    1. 将所有灯泡的状态反转(即开变为关,关变为开)
    2. +
    3. 将编号为偶数的灯泡的状态反转
    4. +
    5. 将编号为奇数的灯泡的状态反转
    6. +
    7. 将编号为 3k+1 的灯泡的状态反转(k = 0, 1, 2, ...)
    8. +
    + +

    示例 1:

    + +
    输入: n = 1, m = 1.
    +输出: 2
    +说明: 状态为: [开], [关]
    +
    + +

    示例 2:

    + +
    输入: n = 2, m = 1.
    +输出: 3
    +说明: 状态为: [开, 关], [关, 开], [关, 关]
    +
    + +

    示例 3:

    + +
    输入: n = 3, m = 1.
    +输出: 4
    +说明: 状态为: [关, 开, 关], [开, 关, 开], [关, 关, 关], [关, 开, 开].
    +
    + +

    注意: n 和 m 都属于 [0, 1000].

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0673.leetcode673 Number of Longest Increasing Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0673.leetcode673 Number of Longest Increasing Subsequence-zh.md" new file mode 100644 index 00000000..387e8312 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0673.leetcode673 Number of Longest Increasing Subsequence-zh.md" @@ -0,0 +1,58 @@ +# [673. 最长递增子序列的个数](https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0673.Number%20of%20Longest%20Increasing%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定一个未排序的整数数组,找到最长递增子序列的个数。

    + +

    示例 1:

    + +
    +输入: [1,3,5,4,7]
    +输出: 2
    +解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
    +
    + +

    示例 2:

    + +
    +输入: [2,2,2,2,2]
    +输出: 5
    +解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。
    +
    + +

    注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0674.leetcode674 Longest Continuous Increasing Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0674.leetcode674 Longest Continuous Increasing Subsequence-zh.md" new file mode 100644 index 00000000..46a97a89 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0674.leetcode674 Longest Continuous Increasing Subsequence-zh.md" @@ -0,0 +1,96 @@ +# [674. 最长连续递增序列](https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0674.Longest%20Continuous%20Increasing%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。

    + +

    连续递增的子序列 可以由两个下标 lrl < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,5,4,7]
    +输出:3
    +解释:最长连续递增序列是 [1,3,5], 长度为3。
    +尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,2,2,2,2]
    +输出:1
    +解释:最长连续递增序列是 [2], 长度为1。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= nums.length <= 104
    • +
    • -109 <= nums[i] <= 109
    • +
    + + +## 解法 + + + +设 f(i) 表示将数组第 i 项作为最长连续递增子序列的最后一项时,子序列的长度。 + +那么,当 `nums[i - 1] < nums[i]`,即 `f(i) = f(i - 1)` + 1,否则 `f(i) = 1`。问题转换为求 f(i) (`i ∈ [0 ,n - 1]`) 的最大值。 + +由于 f(i) 只与前一项 f(i - 1) 有关联,故不需要用一个数组存储。 + + + +### **Python3** + + + +```python +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + n = len(nums) + if n < 2: + return n + res = f = 1 + for i in range(1, n): + f = 1 + (f if nums[i - 1] < nums[i] else 0) + res = max(res, f) + return res +``` + +### **Java** + + + +```java +class Solution { + public int findLengthOfLCIS(int[] nums) { + int n; + if ((n = nums.length) < 2) return n; + int res = 1, f = 1; + for (int i = 1; i < n; ++i) { + f = 1 + (nums[i - 1] < nums[i] ? f : 0); + res = Math.max(res, f); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0675.leetcode675 Cut Off Trees for Golf Event-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0675.leetcode675 Cut Off Trees for Golf Event-zh.md" new file mode 100644 index 00000000..41d30aa0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0675.leetcode675 Cut Off Trees for Golf Event-zh.md" @@ -0,0 +1,91 @@ +# [675. 为高尔夫比赛砍树](https://leetcode-cn.com/problems/cut-off-trees-for-golf-event) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0675.Cut%20Off%20Trees%20for%20Golf%20Event/README_EN.md) + +## 题目描述 + + + +

    你被请来给一个要举办高尔夫比赛的树林砍树。树林由一个 m x n 的矩阵表示, 在这个矩阵中:

    + +
      +
    • 0 表示障碍,无法触碰
    • +
    • 1 表示地面,可以行走
    • +
    • 比 1 大的数 表示有树的单元格,可以行走,数值表示树的高度
    • +
    + +

    每一步,你都可以向上、下、左、右四个方向之一移动一个单位,如果你站的地方有一棵树,那么你可以决定是否要砍倒它。

    + +

    你需要按照树的高度从低向高砍掉所有的树,每砍过一颗树,该单元格的值变为 1(即变为地面)。

    + +

    你将从 (0, 0) 点开始工作,返回你砍完所有树需要走的最小步数。 如果你无法砍完所有的树,返回 -1

    + +

    可以保证的是,没有两棵树的高度是相同的,并且你至少需要砍倒一棵树。

    + +

     

    + +

    示例 1:

    + +
    +输入:forest = [[1,2,3],[0,0,4],[7,6,5]]
    +输出:6
    +解释:沿着上面的路径,你可以用 6 步,按从最矮到最高的顺序砍掉这些树。
    + +

    示例 2:

    + +
    +输入:forest = [[1,2,3],[0,0,0],[7,6,5]]
    +输出:-1
    +解释:由于中间一行被障碍阻塞,无法访问最下面一行中的树。
    +
    + +

    示例 3:

    + +
    +输入:forest = [[2,3,4],[0,0,5],[8,7,6]]
    +输出:6
    +解释:可以按与示例 1 相同的路径来砍掉所有的树。
    +(0,0) 位置的树,可以直接砍去,不用算步数。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == forest.length
    • +
    • n == forest[i].length
    • +
    • 1 <= m, n <= 50
    • +
    • 0 <= forest[i][j] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0676.leetcode676 Implement Magic Dictionary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0676.leetcode676 Implement Magic Dictionary-zh.md" new file mode 100644 index 00000000..363914f5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0676.leetcode676 Implement Magic Dictionary-zh.md" @@ -0,0 +1,89 @@ +# [676. 实现一个魔法字典](https://leetcode-cn.com/problems/implement-magic-dictionary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0676.Implement%20Magic%20Dictionary/README_EN.md) + +## 题目描述 + + + +

    设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

    + +

    实现 MagicDictionary 类:

    + +
      +
    • MagicDictionary() 初始化对象
    • +
    • void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
    • +
    • bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false
    • +
    + +

     

    + +
    +
    +
    +

    示例:

    + +
    +输入
    +["MagicDictionary", "buildDict", "search", "search", "search", "search"]
    +[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
    +输出
    +[null, null, false, true, false, false]
    +
    +解释
    +MagicDictionary magicDictionary = new MagicDictionary();
    +magicDictionary.buildDict(["hello", "leetcode"]);
    +magicDictionary.search("hello"); // 返回 False
    +magicDictionary.search("hhllo"); // 将第二个 'h' 替换为 'e' 可以匹配 "hello" ,所以返回 True
    +magicDictionary.search("hell"); // 返回 False
    +magicDictionary.search("leetcoded"); // 返回 False
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= dictionary.length <= 100
    • +
    • 1 <= dictionary[i].length <= 100
    • +
    • dictionary[i] 仅由小写英文字母组成
    • +
    • dictionary 中的所有字符串 互不相同
    • +
    • 1 <= searchWord.length <= 100
    • +
    • searchWord 仅由小写英文字母组成
    • +
    • buildDict 仅在 search 之前调用一次
    • +
    • 最多调用 100search
    • +
    +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0677.leetcode677 Map Sum Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0677.leetcode677 Map Sum Pairs-zh.md" new file mode 100644 index 00000000..6d6eafd6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0677.leetcode677 Map Sum Pairs-zh.md" @@ -0,0 +1,76 @@ +# [677. 键值映射](https://leetcode-cn.com/problems/map-sum-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0677.Map%20Sum%20Pairs/README_EN.md) + +## 题目描述 + + + +

    实现一个 MapSum 类,支持两个方法,insert 和 sum

    + +
      +
    • MapSum() 初始化 MapSum 对象
    • +
    • void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
    • +
    • int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["MapSum", "insert", "sum", "insert", "sum"]
    +[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
    +输出:
    +[null, null, 3, null, 5]
    +
    +解释:
    +MapSum mapSum = new MapSum();
    +mapSum.insert("apple", 3);  
    +mapSum.sum("ap");           // return 3 (apple = 3)
    +mapSum.insert("app", 2);    
    +mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= key.length, prefix.length <= 50
    • +
    • keyprefix 仅由小写英文字母组成
    • +
    • 1 <= val <= 1000
    • +
    • 最多调用 50insertsum
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0678.leetcode678 valid parenthesis string.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0678.leetcode678 valid parenthesis string.md" new file mode 100644 index 00000000..c5d063ef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0678.leetcode678 valid parenthesis string.md" @@ -0,0 +1,40 @@ +### [678. 有效的括号字符串](https://leetcode-cn.com/problems/valid-parenthesis-string/) + +**难度** 中等 + + + +给定一个只包含三种字符的字符串:`( `,`)` 和 `*`,写一个函数来检验这个字符串是否为有效字符串。有效字符串具有如下规则: + +1. 任何左括号 `(` 必须有相应的右括号 `)`。 +2. 任何右括号 `)` 必须有相应的左括号 `(` 。 +3. 左括号 `(` 必须在对应的右括号之前 `)`。 +4. `*` 可以被视为单个右括号 `)` ,或单个左括号 `(` ,或一个空字符串。 +5. 一个空字符串也被视为有效字符串。 + +**示例 1:** + +``` +输入: "()" +输出: True +``` + +**示例 2:** + +``` +输入: "(*)" +输出: True +``` + +**示例 3:** + +``` +输入: "(*))" +输出: True +``` + + + +**注意:** + +1. 字符串大小将在 [1,100] 范围内。 \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0679.leetcode679 24 Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0679.leetcode679 24 Game-zh.md" new file mode 100644 index 00000000..ccc5247f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0679.leetcode679 24 Game-zh.md" @@ -0,0 +1,61 @@ +# [679. 24 点游戏](https://leetcode-cn.com/problems/24-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0679.24%20Game/README_EN.md) + +## 题目描述 + + + +

    你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 */+-() 的运算得到 24。

    + +

    示例 1:

    + +
    输入: [4, 1, 8, 7]
    +输出: True
    +解释: (8-4) * (7-1) = 24
    +
    + +

    示例 2:

    + +
    输入: [1, 2, 1, 2]
    +输出: False
    +
    + +

    注意:

    + +
      +
    1. 除法运算符 / 表示实数除法,而不是整数除法。例如 4 / (1 - 2/3) = 12 。
    2. +
    3. 每个运算符对两个数进行运算。特别是我们不能用 - 作为一元运算符。例如,[1, 1, 1, 1] 作为输入时,表达式 -1 - 1 - 1 - 1 是不允许的。
    4. +
    5. 你不能将数字连接在一起。例如,输入为 [1, 2, 1, 2] 时,不能写成 12 + 12 。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0680.leetcode680 Valid Palindrome II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0680.leetcode680 Valid Palindrome II-zh.md" new file mode 100644 index 00000000..1d3ce196 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0680.leetcode680 Valid Palindrome II-zh.md" @@ -0,0 +1,117 @@ +# [680. 验证回文字符串 Ⅱ](https://leetcode-cn.com/problems/valid-palindrome-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0680.Valid%20Palindrome%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非空字符串 s最多删除一个字符。判断是否能成为回文字符串。

    + +

    示例 1:

    + +
    +输入: "aba"
    +输出: True
    +
    + +

    示例 2:

    + +
    +输入: "abca"
    +输出: True
    +解释: 你可以删除c字符。
    +
    + +

    注意:

    + +
      +
    1. 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。
    2. +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def validPalindrome(self, s: str) -> bool: + def isPalindrome(s): + i, j = 0, len(s) - 1 + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True + + i, j = 0, len(s) - 1 + while i < j: + if s[i] != s[j]: + return isPalindrome(s[i: j]) or isPalindrome(s[i + 1: j + 1]) + i += 1 + j -= 1 + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean validPalindrome(String s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalindrome(s.substring(i, j)) || isPalindrome(s.substring(i + 1, j + 1)); + } + } + return true; + } + + private boolean isPalindrome(String s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; + } +} +``` + +### **TypeScript** + +```ts +function validPalindrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalinddrome(s.slice(i, j)) || isPalinddrome(s.slice(i + 1, j + 1)); + } + } + return true; +}; + +function isPalinddrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0681.leetcode681 Next Closest Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0681.leetcode681 Next Closest Time-zh.md" new file mode 100644 index 00000000..b4cf4dd8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0681.leetcode681 Next Closest Time-zh.md" @@ -0,0 +1,62 @@ +# [681. 最近时刻](https://leetcode-cn.com/problems/next-closest-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0681.Next%20Closest%20Time/README_EN.md) + +## 题目描述 + + + +

    给定一个形如 “HH:MM” 表示的时刻,利用当前出现过的数字构造下一个距离当前时间最近的时刻。每个出现数字都可以被无限次使用。

    + +

    你可以认为给定的字符串一定是合法的。例如,“01:34” 和 “12:09” 是合法的,“1:34” 和 “12:9” 是不合法的。

    + +

     

    + +

    样例 1:

    + +
    输入: "19:34"
    +输出: "19:39"
    +解释: 利用数字 1, 9, 3, 4 构造出来的最近时刻是 19:39,是 5 分钟之后。结果不是 19:33 因为这个时刻是 23 小时 59 分钟之后。
    +
    + +

     

    + +

    样例 2:

    + +
    输入: "23:59"
    +输出: "22:22"
    +解释: 利用数字 2, 3, 5, 9 构造出来的最近时刻是 22:22。 答案一定是第二天的某一时刻,所以选择可构造的最小时刻。
    +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0682.leetcode682 Baseball Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0682.leetcode682 Baseball Game-zh.md" new file mode 100644 index 00000000..446d6d00 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0682.leetcode682 Baseball Game-zh.md" @@ -0,0 +1,139 @@ +# [682. 棒球比赛](https://leetcode-cn.com/problems/baseball-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0682.Baseball%20Game/README_EN.md) + +## 题目描述 + + + +

    你现在是一场采用特殊赛制棒球比赛的记录员。这场比赛由若干回合组成,过去几回合的得分可能会影响以后几回合的得分。

    + +

    比赛开始时,记录是空白的。你会得到一个记录操作的字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则:

    + +
      +
    1. 整数 x - 表示本回合新获得分数 x
    2. +
    3. "+" - 表示本回合新获得的得分是前两次得分的总和。题目数据保证记录此操作时前面总是存在两个有效的分数。
    4. +
    5. "D" - 表示本回合新获得的得分是前一次得分的两倍。题目数据保证记录此操作时前面总是存在一个有效的分数。
    6. +
    7. "C" - 表示前一次得分无效,将其从记录中移除。题目数据保证记录此操作时前面总是存在一个有效的分数。
    8. +
    + +

    请你返回记录中所有得分的总和。

    + +

     

    + +

    示例 1:

    + +
    +输入:ops = ["5","2","C","D","+"]
    +输出:30
    +解释:
    +"5" - 记录加 5 ,记录现在是 [5]
    +"2" - 记录加 2 ,记录现在是 [5, 2]
    +"C" - 使前一次得分的记录无效并将其移除,记录现在是 [5].
    +"D" - 记录加 2 * 5 = 10 ,记录现在是 [5, 10].
    +"+" - 记录加 5 + 10 = 15 ,记录现在是 [5, 10, 15].
    +所有得分的总和 5 + 10 + 15 = 30
    +
    + +

    示例 2:

    + +
    +输入:ops = ["5","-2","4","C","D","9","+","+"]
    +输出:27
    +解释:
    +"5" - 记录加 5 ,记录现在是 [5]
    +"-2" - 记录加 -2 ,记录现在是 [5, -2]
    +"4" - 记录加 4 ,记录现在是 [5, -2, 4]
    +"C" - 使前一次得分的记录无效并将其移除,记录现在是 [5, -2]
    +"D" - 记录加 2 * -2 = -4 ,记录现在是 [5, -2, -4]
    +"9" - 记录加 9 ,记录现在是 [5, -2, -4, 9]
    +"+" - 记录加 -4 + 9 = 5 ,记录现在是 [5, -2, -4, 9, 5]
    +"+" - 记录加 9 + 5 = 14 ,记录现在是 [5, -2, -4, 9, 5, 14]
    +所有得分的总和 5 + -2 + -4 + 9 + 5 + 14 = 27
    +
    + +

    示例 3:

    + +
    +输入:ops = ["1"]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= ops.length <= 1000
    • +
    • ops[i]"C""D""+",或者一个表示整数的字符串。整数范围是 [-3 * 104, 3 * 104]
    • +
    • 对于 "+" 操作,题目数据保证记录此操作时前面总是存在两个有效的分数
    • +
    • 对于 "C""D" 操作,题目数据保证记录此操作时前面总是存在一个有效的分数
    • +
    + + +## 解法 + + + +栈实现。 + + + +### **Python3** + + + +```python +class Solution: + def calPoints(self, ops: List[str]) -> int: + stack = [] + for op in ops: + if op == 'C': + stack.pop() + elif op == 'D': + stack.append(stack[-1] << 1) + elif op == '+': + stack.append(stack[-1] + stack[-2]) + else: + stack.append(int(op)) + return sum(stack) +``` + +### **Java** + + + +```java +class Solution { + public int calPoints(String[] ops) { + Deque stack = new ArrayDeque<>(); + for (String op : ops) { + if ("C".equals(op)) { + stack.pop(); + } else if ("D".equals(op)) { + stack.push(stack.peek() << 1); + } else if ("+".equals(op)) { + Integer a = stack.pop(); + Integer b = stack.peek(); + stack.push(a); + stack.push(a + b); + } else { + stack.push(Integer.valueOf(op)); + } + } + int res = 0; + for (Integer score : stack) { + res += score; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0683.leetcode683 K Empty Slots-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0683.leetcode683 K Empty Slots-zh.md" new file mode 100644 index 00000000..f89e6092 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0683.leetcode683 K Empty Slots-zh.md" @@ -0,0 +1,82 @@ +# [683. K 个关闭的灯泡](https://leetcode-cn.com/problems/k-empty-slots) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0683.K%20Empty%20Slots/README_EN.md) + +## 题目描述 + + + +

    N 个灯泡排成一行,编号从 1N 。最初,所有灯泡都关闭。每天只打开一个灯泡,直到 N 天后所有灯泡都打开。

    + +

    给你一个长度为 N 的灯泡数组 blubs ,其中 bulls[i] = x 意味着在第 (i+1) 天,我们会把在位置 x 的灯泡打开,其中 i 从 0 开始x 从 1 开始

    + +

    给你一个整数 K ,请你输出在第几天恰好有两个打开的灯泡,使得它们中间 正好 有 K 个灯泡且这些灯泡 全部是关闭的

    + +

    如果不存在这种情况,返回 -1 。如果有多天都出现这种情况,请返回 最小的天数

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +bulbs: [1,3,2]
    +K: 1
    +输出:2
    +解释:
    +第一天 bulbs[0] = 1,打开第一个灯泡 [1,0,0]
    +第二天 bulbs[1] = 3,打开第三个灯泡 [1,0,1]
    +第三天 bulbs[2] = 2,打开第二个灯泡 [1,1,1]
    +返回2,因为在第二天,两个打开的灯泡之间恰好有一个关闭的灯泡。
    +
    + +

    示例 2:

    + +
    +输入:
    +bulbs: [1,2,3]
    +k: 1
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 20000
    • +
    • 1 <= bulbs[i] <= N
    • +
    • bulbs 是一个由从 1N 的数字构成的排列
    • +
    • 0 <= K <= 20000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0684.leetcode684 Redundant Connection-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0684.leetcode684 Redundant Connection-zh.md" new file mode 100644 index 00000000..f0d901e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0684.leetcode684 Redundant Connection-zh.md" @@ -0,0 +1,76 @@ +# [684. 冗余连接](https://leetcode-cn.com/problems/redundant-connection) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0684.Redundant%20Connection/README_EN.md) + +## 题目描述 + + + +

    在本问题中, 树指的是一个连通且无环的无向图。

    + +

    输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。

    + +

    结果图是一个以组成的二维数组。每一个的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v无向图的边。

    + +

    返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v

    + +

    示例 1:

    + +
    输入: [[1,2], [1,3], [2,3]]
    +输出: [2,3]
    +解释: 给定的无向图为:
    +  1
    + / \
    +2 - 3
    +
    + +

    示例 2:

    + +
    输入: [[1,2], [2,3], [3,4], [1,4], [1,5]]
    +输出: [1,4]
    +解释: 给定的无向图为:
    +5 - 1 - 2
    +    |   |
    +    4 - 3
    +
    + +

    注意:

    + +
      +
    • 输入的二维数组大小在 3 到 1000。
    • +
    • 二维数组中的整数在1到N之间,其中N是输入数组的大小。
    • +
    + +

    更新(2017-09-26):
    +我们已经重新检查了问题描述及测试用例,明确图是无向 图。对于有向图详见冗余连接II对于造成任何不便,我们深感歉意。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0685.leetcode685 Redundant Connection II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0685.leetcode685 Redundant Connection II-zh.md" new file mode 100644 index 00000000..7c7b4eff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0685.leetcode685 Redundant Connection II-zh.md" @@ -0,0 +1,73 @@ +# [685. 冗余连接 II](https://leetcode-cn.com/problems/redundant-connection-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0685.Redundant%20Connection%20II/README_EN.md) + +## 题目描述 + + + +

    在本问题中,有根树指满足以下条件的 有向 图。该树只有一个根节点,所有其他节点都是该根节点的后继。该树除了根节点之外的每一个节点都有且只有一个父节点,而根节点没有父节点。

    + +

    输入一个有向图,该图由一个有着 n 个节点(节点值不重复,从 1n)的树及一条附加的有向边构成。附加的边包含在 1n 中的两个不同顶点间,这条附加的边不属于树中已存在的边。

    + +

    结果图是一个以边组成的二维数组 edges 。 每个元素是一对 [ui, vi],用以表示 有向 图中连接顶点 ui 和顶点 vi 的边,其中 uivi 的一个父节点。

    + +

    返回一条能删除的边,使得剩下的图是有 n 个节点的有根树。若有多个答案,返回最后出现在给定二维数组的答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:edges = [[1,2],[1,3],[2,3]]
    +输出:[2,3]
    +
    + +

    示例 2:

    + +
    +输入:edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
    +输出:[4,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == edges.length
    • +
    • 3 <= n <= 1000
    • +
    • edges[i].length == 2
    • +
    • 1 <= ui, vi <= n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0686.leetcode686 Repeated String Match-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0686.leetcode686 Repeated String Match-zh.md" new file mode 100644 index 00000000..03e804db --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0686.leetcode686 Repeated String Match-zh.md" @@ -0,0 +1,79 @@ +# [686. 重复叠加字符串匹配](https://leetcode-cn.com/problems/repeated-string-match) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0686.Repeated%20String%20Match/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 ab,寻找重复叠加字符串 a 的最小次数,使得字符串 b 成为叠加后的字符串 a 的子串,如果不存在则返回 -1

    + +

    注意:字符串 "abc" 重复叠加 0 次是 "",重复叠加 1 次是 "abc",重复叠加 2 次是 "abcabc"

    + +

     

    + +

    示例 1:

    + +
    输入:a = "abcd", b = "cdabcdab"
    +输出:3
    +解释:a 重复叠加三遍后为 "abcdabcdabcd", 此时 b 是其子串。
    +
    + +

    示例 2:

    + +
    输入:a = "a", b = "aa"
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:a = "a", b = "a"
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:a = "abc", b = "wxyz"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= a.length <= 104
    • +
    • 1 <= b.length <= 104
    • +
    • ab 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0687.leetcode687 Longest Univalue Path-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0687.leetcode687 Longest Univalue Path-zh.md" new file mode 100644 index 00000000..d129519b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0687.leetcode687 Longest Univalue Path-zh.md" @@ -0,0 +1,80 @@ +# [687. 最长同值路径](https://leetcode-cn.com/problems/longest-univalue-path) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0687.Longest%20Univalue%20Path/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

    + +

    注意:两个节点之间的路径长度由它们之间的边数表示。

    + +

    示例 1:

    + +

    输入:

    + +
    +              5
    +             / \
    +            4   5
    +           / \   \
    +          1   1   5
    +
    + +

    输出:

    + +
    +2
    +
    + +

    示例 2:

    + +

    输入:

    + +
    +              1
    +             / \
    +            4   5
    +           / \   \
    +          4   4   5
    +
    + +

    输出:

    + +
    +2
    +
    + +

    注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0688.leetcode688 Knight Probability in Chessboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0688.leetcode688 Knight Probability in Chessboard-zh.md" new file mode 100644 index 00000000..2d284632 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0688.leetcode688 Knight Probability in Chessboard-zh.md" @@ -0,0 +1,76 @@ +# [688. “马”在棋盘上的概率](https://leetcode-cn.com/problems/knight-probability-in-chessboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0688.Knight%20Probability%20in%20Chessboard/README_EN.md) + +## 题目描述 + + + +

    已知一个 NxN 的国际象棋棋盘,棋盘的行号和列号都是从 0 开始。即最左上角的格子记为 (0, 0),最右下角的记为 (N-1, N-1)。 

    + +

    现有一个 “马”(也译作 “骑士”)位于 (r, c) ,并打算进行 K 次移动。 

    + +

    如下图所示,国际象棋的 “马” 每一步先沿水平或垂直方向移动 2 个格子,然后向与之相垂直的方向再移动 1 个格子,共有 8 个可选的位置。

    + +

     

    + +

    + +

     

    + +

    现在 “马” 每一步都从可选的位置(包括棋盘外部的)中独立随机地选择一个进行移动,直到移动了 K 次或跳到了棋盘外面。

    + +

    求移动结束后,“马” 仍留在棋盘上的概率。

    + +

     

    + +

    示例:

    + +
    输入: 3, 2, 0, 0
    +输出: 0.0625
    +解释: 
    +输入的数据依次为 N, K, r, c
    +第 1 步时,有且只有 2 种走法令 “马” 可以留在棋盘上(跳到(1,2)或(2,1))。对于以上的两种情况,各自在第2步均有且只有2种走法令 “马” 仍然留在棋盘上。
    +所以 “马” 在结束后仍在棋盘上的概率为 0.0625。
    +
    + +

     

    + +

    注意:

    + +
      +
    • N 的取值范围为 [1, 25]
    • +
    • K 的取值范围为 [0, 100]
    • +
    • 开始时,“马” 总是位于棋盘上
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0689.leetcode689 Maximum Sum of 3 Non-Overlapping Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0689.leetcode689 Maximum Sum of 3 Non-Overlapping Subarrays-zh.md" new file mode 100644 index 00000000..5b7398f2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0689.leetcode689 Maximum Sum of 3 Non-Overlapping Subarrays-zh.md" @@ -0,0 +1,61 @@ +# [689. 三个无重叠子数组的最大和](https://leetcode-cn.com/problems/maximum-sum-of-3-non-overlapping-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0689.Maximum%20Sum%20of%203%20Non-Overlapping%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    给定数组 nums 由正整数组成,找到三个互不重叠的子数组的最大和。

    + +

    每个子数组的长度为k,我们要使这3*k个项的和最大化。

    + +

    返回每个区间起始索引的列表(索引从 0 开始)。如果有多个结果,返回字典序最小的一个。

    + +

    示例:

    + +
    +输入: [1,2,1,2,6,7,5,1], 2
    +输出: [0, 3, 5]
    +解释: 子数组 [1, 2], [2, 6], [7, 5] 对应的起始索引为 [0, 3, 5]。
    +我们也可以取 [2, 1], 但是结果 [1, 3, 5] 在字典序上更大。
    +
    + +

    注意:

    + +
      +
    • nums.length的范围在[1, 20000]之间。
    • +
    • nums[i]的范围在[1, 65535]之间。
    • +
    • k的范围在[1, floor(nums.length / 3)]之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0690.leetcode690 Employee Importance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0690.leetcode690 Employee Importance-zh.md" new file mode 100644 index 00000000..4369f0e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0690.leetcode690 Employee Importance-zh.md" @@ -0,0 +1,147 @@ +# [690. 员工的重要性](https://leetcode-cn.com/problems/employee-importance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0690.Employee%20Importance/README_EN.md) + +## 题目描述 + + + +

    给定一个保存员工信息的数据结构,它包含了员工 唯一的 id 重要度 直系下属的 id

    + +

    比如,员工 1 是员工 2 的领导,员工 2 是员工 3 的领导。他们相应的重要度为 15 , 10 , 5 。那么员工 1 的数据结构是 [1, 15, [2]] ,员工 2的 数据结构是 [2, 10, [3]] ,员工 3 的数据结构是 [3, 5, []] 。注意虽然员工 3 也是员工 1 的一个下属,但是由于 并不是直系 下属,因此没有体现在员工 1 的数据结构中。

    + +

    现在输入一个公司的所有员工信息,以及单个员工 id ,返回这个员工和他所有下属的重要度之和。

    + +

     

    + +

    示例:

    + +
    +输入:[[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
    +输出:11
    +解释:
    +员工 1 自身的重要度是 5 ,他有两个直系下属 2 和 3 ,而且 2 和 3 的重要度均为 3 。因此员工 1 的总重要度是 5 + 3 + 3 = 11 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 一个员工最多有一个 直系 领导,但是可以有多个 直系 下属
    • +
    • 员工数量不超过 2000 。
    • +
    + +## 解法 + + + +“所有下属” 包括了 “下属的下属”,先用哈希表存储员工 id 和员工之间的映射关系,然后再递归求解即可(也能用 BFS 实现) + + + +### **Python3** + + + +```python +""" +# Definition for Employee. +class Employee: + def __init__(self, id: int, importance: int, subordinates: List[int]): + self.id = id + self.importance = importance + self.subordinates = subordinates +""" + +class Solution: + def getImportance(self, employees: List['Employee'], id: int) -> int: + m = {emp.id: emp for emp in employees} + + def dfs(id: int) -> int: + emp = m[id] + s = emp.importance + for sub in emp.subordinates: + s += dfs(sub) + return s + + return dfs(id) +``` + +### **Java** + + + +```java +/* +// Definition for Employee. +class Employee { + public int id; + public int importance; + public List subordinates; +}; +*/ + +class Solution { + + private final Map map = new HashMap<>(); + + public int getImportance(List employees, int id) { + for (Employee employee : employees) { + map.put(employee.id, employee); + } + return dfs(id); + } + + private int dfs(int id) { + Employee employee = map.get(id); + int sum = employee.importance; + for (Integer subordinate : employee.subordinates) { + sum += dfs(subordinate); + } + return sum; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for Employee. + * function Employee(id, importance, subordinates) { + * this.id = id; + * this.importance = importance; + * this.subordinates = subordinates; + * } + */ + +/** + * @param {Employee[]} employees + * @param {number} id + * @return {number} + */ +var GetImportance = function (employees, id) { + const map = new Map(); + for (const employee of employees) { + map.set(employee.id, employee); + } + const dfs = (id) => { + const employee = map.get(id); + let sum = employee.importance; + for (const subId of employee.subordinates) { + sum += dfs(subId); + } + return sum; + }; + return dfs(id); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0691.leetcode691 Stickers to Spell Word-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0691.leetcode691 Stickers to Spell Word-zh.md" new file mode 100644 index 00000000..08265bb6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0691.leetcode691 Stickers to Spell Word-zh.md" @@ -0,0 +1,98 @@ +# [691. 贴纸拼词](https://leetcode-cn.com/problems/stickers-to-spell-word) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0691.Stickers%20to%20Spell%20Word/README_EN.md) + +## 题目描述 + + + +

    我们给出了 N 种不同类型的贴纸。每个贴纸上都有一个小写的英文单词。

    + +

    你希望从自己的贴纸集合中裁剪单个字母并重新排列它们,从而拼写出给定的目标字符串 target

    + +

    如果你愿意的话,你可以不止一次地使用每一张贴纸,而且每一张贴纸的数量都是无限的。

    + +

    拼出目标 target 所需的最小贴纸数量是多少?如果任务不可能,则返回 -1。

    + +

     

    + +

    示例 1:

    + +

    输入:

    + +
    ["with", "example", "science"], "thehat"
    +
    + +

    输出:

    + +
    3
    +
    + +

    解释:

    + +
    我们可以使用 2 个 "with" 贴纸,和 1 个 "example" 贴纸。
    +把贴纸上的字母剪下来并重新排列后,就可以形成目标 “thehat“ 了。
    +此外,这是形成目标字符串所需的最小贴纸数量。
    +
    + +

    示例 2:

    + +

    输入:

    + +
    ["notice", "possible"], "basicbasic"
    +
    + +

    输出:

    + +
    -1
    +
    + +

    解释:

    + +
    我们不能通过剪切给定贴纸的字母来形成目标“basicbasic”。
    +
    + +

     

    + +

    提示:

    + +
      +
    • stickers 长度范围是 [1, 50]
    • +
    • stickers 由小写英文单词组成(不带撇号)。
    • +
    • target 的长度在 [1, 15] 范围内,由小写字母组成。
    • +
    • 在所有的测试案例中,所有的单词都是从 1000 个最常见的美国英语单词中随机选取的,目标是两个随机单词的串联。
    • +
    • 时间限制可能比平时更具挑战性。预计 50 个贴纸的测试案例平均可在35ms内解决。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0692.leetcode692 Top K Frequent Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0692.leetcode692 Top K Frequent Words-zh.md" new file mode 100644 index 00000000..4e09f306 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0692.leetcode692 Top K Frequent Words-zh.md" @@ -0,0 +1,107 @@ +# [692. 前 K 个高频单词](https://leetcode-cn.com/problems/top-k-frequent-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0692.Top%20K%20Frequent%20Words/README_EN.md) + +## 题目描述 + + + +

    给一非空的单词列表,返回前 个出现次数最多的单词。

    + +

    返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。

    + +

    示例 1:

    + +
    +输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
    +输出: ["i", "love"]
    +解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
    +    注意,按字母顺序 "i" 在 "love" 之前。
    +
    + +

     

    + +

    示例 2:

    + +
    +输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
    +输出: ["the", "is", "sunny", "day"]
    +解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
    +    出现次数依次为 4, 3, 2 和 1 次。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. 假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
    2. +
    3. 输入的单词均由小写字母组成。
    4. +
    + +

     

    + +

    扩展练习:

    + +
      +
    1. 尝试以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。
    2. +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def topKFrequent(self, words: List[str], k: int) -> List[str]: + counter = collections.Counter(words) + res = sorted(counter, key=lambda word: (-counter[word], word)) + return res[:k] +``` + +### **Java** + + + +```java +class Solution { + public List topKFrequent(String[] words, int k) { + Map counter = new HashMap<>(); + for (String word : words) { + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> { + if (counter.get(a).equals(counter.get(b))) { + return b.compareTo(a); + } + return counter.get(a) - counter.get(b); + }); + for (String word : counter.keySet()) { + minHeap.offer(word); + if (minHeap.size() > k) { + minHeap.poll(); + } + } + List res = new ArrayList<>(); + while (!minHeap.isEmpty()) { + res.add(minHeap.poll()); + } + Collections.reverse(res); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0693.leetcode693 Binary Number with Alternating Bits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0693.leetcode693 Binary Number with Alternating Bits-zh.md" new file mode 100644 index 00000000..eb117621 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0693.leetcode693 Binary Number with Alternating Bits-zh.md" @@ -0,0 +1,109 @@ +# [693. 交替位二进制数](https://leetcode-cn.com/problems/binary-number-with-alternating-bits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0693.Binary%20Number%20with%20Alternating%20Bits/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数,检查它的二进制表示是否总是 0、1 交替出现:换句话说,就是二进制表示中相邻两位的数字永不相同。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 5
    +输出:true
    +解释:5 的二进制表示是:101
    +
    + +

    示例 2:

    + +
    +输入:n = 7
    +输出:false
    +解释:7 的二进制表示是:111.
    + +

    示例 3:

    + +
    +输入:n = 11
    +输出:false
    +解释:11 的二进制表示是:1011.
    + +

    示例 4:

    + +
    +输入:n = 10
    +输出:true
    +解释:10 的二进制表示是:1010.
    + +

    示例 5:

    + +
    +输入:n = 3
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 231 - 1
    • +
    + +## 解法 + + + +假设 01 交替出现,那么我们可以通过错位异或将尾部全部转为 1,加 1 可以得到 2 的幂次的一个数 n(n 中只有一个位是 1),接着利用 `n & (n - 1)` 可以消除最后一位的 1。 + +此时判断是否为 0,若是,说明假设成立,是 01 交替串。 + + + +### **Python3** + + + +```python +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + n = (n ^ (n >> 1)) + 1 + return (n & (n - 1)) == 0 +``` + +### **Java** + + + +```java +class Solution { + public boolean hasAlternatingBits(int n) { + n = (n ^ (n >> 1)) + 1; + return (n & (n - 1)) == 0; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & ((long) n + 1)) == 0; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0694.leetcode694 Number of Distinct Islands-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0694.leetcode694 Number of Distinct Islands-zh.md" new file mode 100644 index 00000000..dc5b602e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0694.leetcode694 Number of Distinct Islands-zh.md" @@ -0,0 +1,81 @@ +# [694. 不同岛屿的数量](https://leetcode-cn.com/problems/number-of-distinct-islands) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0694.Number%20of%20Distinct%20Islands/README_EN.md) + +## 题目描述 + + + +

    给定一个非空 01 二维数组表示的网格,一个岛屿由四连通(上、下、左、右四个方向)的 1 组成,你可以认为网格的四周被海水包围。

    + +

    请你计算这个网格中共有多少个形状不同的岛屿。两个岛屿被认为是相同的,当且仅当一个岛屿可以通过平移变换(不可以旋转、翻转)和另一个岛屿重合。

    + +

     

    + +

    示例 1:

    + +
    11000
    +11000
    +00011
    +00011
    +
    + +

    给定上图,返回结果 1

    + +

    示例 2:

    + +
    11011
    +10000
    +00001
    +11011
    + +

    给定上图,返回结果 3
    +
    +注意:

    + +
    11
    +1
    +
    + +

    + +
     1
    +11
    +
    + +

    是不同的岛屿,因为我们不考虑旋转、翻转操作。

    + +

     

    + +

    提示:二维数组每维的大小都不会超过 50 。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0695.leetcode695 Max Area of Island-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0695.leetcode695 Max Area of Island-zh.md" new file mode 100644 index 00000000..282ee53c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0695.leetcode695 Max Area of Island-zh.md" @@ -0,0 +1,177 @@ +# [695. 岛屿的最大面积](https://leetcode-cn.com/problems/max-area-of-island) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0695.Max%20Area%20of%20Island/README_EN.md) + +## 题目描述 + + + +

    给定一个包含了一些 01 的非空二维数组 grid

    + +

    一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。

    + +

    找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。)

    + +

     

    + +

    示例 1:

    + +
    [[0,0,1,0,0,0,0,1,0,0,0,0,0],
    + [0,0,0,0,0,0,0,1,1,1,0,0,0],
    + [0,1,1,0,1,0,0,0,0,0,0,0,0],
    + [0,1,0,0,1,1,0,0,1,0,1,0,0],
    + [0,1,0,0,1,1,0,0,1,1,1,0,0],
    + [0,0,0,0,0,0,0,0,0,0,1,0,0],
    + [0,0,0,0,0,0,0,1,1,1,0,0,0],
    + [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    +
    + +

    对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1

    + +

    示例 2:

    + +
    [[0,0,0,0,0,0,0,0]]
    + +

    对于上面这个给定的矩阵, 返回 0

    + +

     

    + +

    注意: 给定的矩阵grid 的长度和宽度都不超过 50。

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + def dfs(grid, i, j, m, n): + if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0: + return 0 + grid[i][j] = 0 + res = 1 + for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + res += dfs(grid, i + x, j + y, m, n) + return res + + m, n = len(grid), len(grid[0]) + res = 0 + for i in range(m): + for j in range(n): + t = dfs(grid, i, j, m, n) + res = max(res, t) + return res +``` + +### **Java** + + + +```java +class Solution { + private int[][] directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + + public int maxAreaOfIsland(int[][] grid) { + int m = grid.length, n = grid[0].length; + int res = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int t = dfs(grid, i, j, m, n); + res = Math.max(res, t); + } + } + return res; + } + + private int dfs(int[][] grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + int res = 1; + for (int[] direction : directions) { + res += dfs(grid, i + direction[0], j + direction[1], m, n); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function maxAreaOfIsland(grid: number[][]): number { + let m = grid.length, n = grid[0].length; + let res = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + res = Math.max(dfs(grid, i, j), res); + } + } + } + return res; +}; + +function dfs(grid: number[][], i: number, j: number): number { + let m = grid.length, n = grid[0].length; + if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + let res = 1; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + res += dfs(grid, i + dx, j + dy); + } + return res; +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int res = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int t = dfs(grid, i, j, m, n); + res = max(res, t); + } + } + return res; + } +private: + vector> directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + + int dfs(vector>& grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + int res = 1; + for (auto direction : directions) { + res += dfs(grid, i + direction[0], j + direction[1], m, n); + } + return res; + } + +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0696.leetcode696 Count Binary Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0696.leetcode696 Count Binary Substrings-zh.md" new file mode 100644 index 00000000..5affcaee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0696.leetcode696 Count Binary Substrings-zh.md" @@ -0,0 +1,73 @@ +# [696. 计数二进制子串](https://leetcode-cn.com/problems/count-binary-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0696.Count%20Binary%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s,计算具有相同数量 0 和 1 的非空(连续)子字符串的数量,并且这些子字符串中的所有 0 和所有 1 都是连续的。

    + +

    重复出现的子串要计算它们出现的次数。

    + +

     

    + +

    示例 1 :

    + +
    +输入: "00110011"
    +输出: 6
    +解释: 有6个子串具有相同数量的连续1和0:“0011”,“01”,“1100”,“10”,“0011” 和 “01”。
    +
    +请注意,一些重复出现的子串要计算它们出现的次数。
    +
    +另外,“00110011”不是有效的子串,因为所有的0(和1)没有组合在一起。
    +
    + +

    示例 2 :

    + +
    +输入: "10101"
    +输出: 4
    +解释: 有4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续1和0。
    +
    + +

     

    + +

    提示:

    + +
      +
    • s.length 在1到50,000之间。
    • +
    • s 只包含“0”或“1”字符。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0697.leetcode697 Degree of an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0697.leetcode697 Degree of an Array-zh.md" new file mode 100644 index 00000000..d30afcb3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0697.leetcode697 Degree of an Array-zh.md" @@ -0,0 +1,118 @@ +# [697. 数组的度](https://leetcode-cn.com/problems/degree-of-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0697.Degree%20of%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。

    + +

    你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。

    + +

     

    + +

    示例 1:

    + +
    +输入:[1, 2, 2, 3, 1]
    +输出:2
    +解释:
    +输入数组的度是2,因为元素1和2的出现频数最大,均为2.
    +连续子数组里面拥有相同度的有如下所示:
    +[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
    +最短连续子数组[2, 2]的长度为2,所以返回2.
    +
    + +

    示例 2:

    + +
    +输入:[1,2,2,3,1,4,2]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums.length 在1到 50,000 区间范围内。
    • +
    • nums[i] 是一个在 0 到 49,999 范围内的整数。
    • +
    + + +## 解法 + + + +遍历数组,用哈希表记录数组每个元素出现的次数,以及首次、末次出现的位置。然后遍历哈希表,获取元素出现次数最多(可能有多个)且首末位置差最小的数。 + + + +### **Python3** + + + +```python +class Solution: + def findShortestSubArray(self, nums: List[int]) -> int: + mapper = {} + for i, v in enumerate(nums): + if v in mapper: + arr = mapper[v] + arr[0] += 1 + arr[2] = i + else: + arr = [1, i, i] + mapper[v] = arr + max_degree = min_len = 0 + for arr in mapper.values(): + if max_degree < arr[0]: + max_degree = arr[0] + min_len = arr[2] - arr[1] + 1 + elif max_degree == arr[0]: + min_len = min(min_len, arr[2] - arr[1] + 1) + return min_len +``` + +### **Java** + + + +```java +class Solution { + public int findShortestSubArray(int[] nums) { + Map mapper = new HashMap<>(); + for (int i = 0, n = nums.length; i < n; ++i) { + if (mapper.containsKey(nums[i])) { + int[] arr = mapper.get(nums[i]); + ++arr[0]; + arr[2] = i; + } else { + int[] arr = new int[]{1, i, i}; + mapper.put(nums[i], arr); + } + } + + int maxDegree = 0, minLen = 0; + for (Map.Entry entry : mapper.entrySet()) { + int[] arr = entry.getValue(); + if (maxDegree < arr[0]) { + maxDegree = arr[0]; + minLen = arr[2] - arr[1] + 1; + } else if (maxDegree == arr[0]) { + minLen = Math.min(minLen, arr[2] - arr[1] + 1); + } + } + return minLen; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0698.leetcode698 Partition to K Equal Sum Subsets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0698.leetcode698 Partition to K Equal Sum Subsets-zh.md" new file mode 100644 index 00000000..01eac9f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0698.leetcode698 Partition to K Equal Sum Subsets-zh.md" @@ -0,0 +1,55 @@ +# [698. 划分为k个相等的子集](https://leetcode-cn.com/problems/partition-to-k-equal-sum-subsets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0698.Partition%20to%20K%20Equal%20Sum%20Subsets/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组  nums 和一个正整数 k,找出是否有可能把这个数组分成 k 个非空子集,其总和都相等。

    + +

    示例 1:

    + +
    输入: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
    +输出: True
    +说明: 有可能将其分成 4 个子集(5),(1,4),(2,3),(2,3)等于总和。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= len(nums) <= 16
    • +
    • 0 < nums[i] < 10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0699.leetcode699 Falling Squares-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0699.leetcode699 Falling Squares-zh.md" new file mode 100644 index 00000000..766b0fa8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0699.leetcode699 Falling Squares-zh.md" @@ -0,0 +1,109 @@ +# [699. 掉落的方块](https://leetcode-cn.com/problems/falling-squares) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0600-0699/0699.Falling%20Squares/README_EN.md) + +## 题目描述 + + + +

    在无限长的数轴(即 x 轴)上,我们根据给定的顺序放置对应的正方形方块。

    + +

    i 个掉落的方块(positions[i] = (left, side_length))是正方形,其中 left 表示该方块最左边的点位置(positions[i][0]),side_length 表示该方块的边长(positions[i][1])。

    + +

    每个方块的底部边缘平行于数轴(即 x 轴),并且从一个比目前所有的落地方块更高的高度掉落而下。在上一个方块结束掉落,并保持静止后,才开始掉落新方块。

    + +

    方块的底边具有非常大的粘性,并将保持固定在它们所接触的任何长度表面上(无论是数轴还是其他方块)。邻接掉落的边不会过早地粘合在一起,因为只有底边才具有粘性。

    + +

     

    + +

    返回一个堆叠高度列表 ans 。每一个堆叠高度 ans[i] 表示在通过 positions[0], positions[1], ..., positions[i] 表示的方块掉落结束后,目前所有已经落稳的方块堆叠的最高高度。

    + +

     

    + +

     

    + +

    示例 1:

    + +
    输入: [[1, 2], [2, 3], [6, 1]]
    +输出: [2, 5, 5]
    +解释:
    +
    +第一个方块 positions[0] = [1, 2] 掉落:
    +_aa
    +_aa
    +-------
    +方块最大高度为 2 。
    +
    +第二个方块 positions[1] = [2, 3] 掉落:
    +__aaa
    +__aaa
    +__aaa
    +_aa__
    +_aa__
    +--------------
    +方块最大高度为5。
    +大的方块保持在较小的方块的顶部,不论它的重心在哪里,因为方块的底部边缘有非常大的粘性。
    +
    +第三个方块 positions[1] = [6, 1] 掉落:
    +__aaa
    +__aaa
    +__aaa
    +_aa
    +_aa___a
    +-------------- 
    +方块最大高度为5。
    +
    +因此,我们返回结果[2, 5, 5]。
    +
    + +

     

    + +

    示例 2:

    + +
    输入: [[100, 100], [200, 100]]
    +输出: [100, 100]
    +解释: 相邻的方块不会过早地卡住,只有它们的底部边缘才能粘在表面上。
    +
    + +

     

    + +

    注意:

    + +
      +
    • 1 <= positions.length <= 1000.
    • +
    • 1 <= positions[i][0] <= 10^8.
    • +
    • 1 <= positions[i][1] <= 10^6.
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0700.leetcode700 Search in a Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0700.leetcode700 Search in a Binary Search Tree-zh.md" new file mode 100644 index 00000000..f9913741 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0700.leetcode700 Search in a Binary Search Tree-zh.md" @@ -0,0 +1,64 @@ +# [700. 二叉搜索树中的搜索](https://leetcode-cn.com/problems/search-in-a-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0700.Search%20in%20a%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。

    + +

    例如,

    + +
    +给定二叉搜索树:
    +
    +        4
    +       / \
    +      2   7
    +     / \
    +    1   3
    +
    +和值: 2
    +
    + +

    你应该返回如下子树:

    + +
    +      2     
    +     / \   
    +    1   3
    +
    + +

    在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0701.leetcode701 Insert into a Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0701.leetcode701 Insert into a Binary Search Tree-zh.md" new file mode 100644 index 00000000..ca99e713 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0701.leetcode701 Insert into a Binary Search Tree-zh.md" @@ -0,0 +1,80 @@ +# [701. 二叉搜索树中的插入操作](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0701.Insert%20into%20a%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。

    + +

    注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [4,2,7,1,3], val = 5
    +输出:[4,2,7,1,3,5]
    +解释:另一个满足题目要求可以通过的树是:
    +
    +
    + +

    示例 2:

    + +
    +输入:root = [40,20,60,10,30,50,70], val = 25
    +输出:[40,20,60,10,30,50,70,null,null,25]
    +
    + +

    示例 3:

    + +
    +输入:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
    +输出:[4,2,7,1,3,5]
    +
    + +

     

    + +

     

    + +

    提示:

    + +
      +
    • 给定的树上的节点数介于 010^4 之间
    • +
    • 每个节点都有一个唯一整数值,取值范围从 010^8
    • +
    • -10^8 <= val <= 10^8
    • +
    • 新值和原始二叉搜索树中的任意节点值都不同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0702.leetcode702 Search in a Sorted Array of Unknown Size-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0702.leetcode702 Search in a Sorted Array of Unknown Size-zh.md" new file mode 100644 index 00000000..35f96b70 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0702.leetcode702 Search in a Sorted Array of Unknown Size-zh.md" @@ -0,0 +1,167 @@ +# [702. 搜索长度未知的有序数组](https://leetcode-cn.com/problems/search-in-a-sorted-array-of-unknown-size) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0702.Search%20in%20a%20Sorted%20Array%20of%20Unknown%20Size/README_EN.md) + +## 题目描述 + + + +

    给定一个升序整数数组,写一个函数搜索 nums 中数字 target。如果 target 存在,返回它的下标,否则返回 -1注意,这个数组的大小是未知的。你只可以通过 ArrayReader 接口访问这个数组,ArrayReader.get(k) 返回数组中第 k 个元素(下标从 0 开始)。

    + +

    你可以认为数组中所有的整数都小于 10000。如果你访问数组越界,ArrayReader.get 会返回 2147483647

    + +

     

    + +

    样例 1:

    + +
    输入: array = [-1,0,3,5,9,12], target = 9
    +输出: 4
    +解释: 9 存在在 nums 中,下标为 4
    +
    + +

    样例 2:

    + +
    输入: array = [-1,0,3,5,9,12], target = 2
    +输出: -1
    +解释: 2 不在数组中所以返回 -1
    + +

     

    + +

    注释 :

    + +
      +
    1. 你可以认为数组中所有元素的值互不相同。
    2. +
    3. 数组元素的值域是 [-9999, 9999]
    4. +
    + +## 解法 + + + +二分法。 + + + +### **Python3** + + + +```python +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class ArrayReader: +# def get(self, index: int) -> int: + +class Solution: + def search(self, reader, target): + """ + :type reader: ArrayReader + :type target: int + :rtype: int + """ + left, right = 0, 20000 + while left < right: + mid = (left + right) >> 1 + if reader.get(mid) >= target: + right = mid + else: + left = mid + 1 + return left if reader.get(left) == target else -1 +``` + +### **Java** + + + +```java +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * public int get(int index) {} + * } + */ + +class Solution { + public int search(ArrayReader reader, int target) { + int left = 0, right = 20000; + while (left < right) { + int mid = left + right >> 1; + if (reader.get(mid) >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return reader.get(left) == target ? left : -1; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * int get(int index); + * }; + */ + +class Solution { +public: + int search(const ArrayReader& reader, int target) { + int left = 0, right = 20000; + while (left < right) { + int mid = left + right >> 1; + if (reader.get(mid) >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return reader.get(left) == target ? left : -1; + } +}; +``` + +### **Go** + +```go +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * type ArrayReader struct { + * } + * + * func (this *ArrayReader) get(index int) int {} + */ + +func search(reader ArrayReader, target int) int { + left, right := 0, 20000 + for left < right { + mid := (left + right) >> 1 + if reader.get(mid) >= target { + right = mid + } else { + left = mid + 1 + } + } + if reader.get(left) == target { + return left + } + return -1 +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0703.leetcode703 Kth Largest Element in a Stream-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0703.leetcode703 Kth Largest Element in a Stream-zh.md" new file mode 100644 index 00000000..7d2f42e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0703.leetcode703 Kth Largest Element in a Stream-zh.md" @@ -0,0 +1,122 @@ +# [703. 数据流中的第 K 大元素](https://leetcode-cn.com/problems/kth-largest-element-in-a-stream) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0703.Kth%20Largest%20Element%20in%20a%20Stream/README_EN.md) + +## 题目描述 + + + +

    设计一个找到数据流中第 k 大元素的类(class)。注意是排序后的第 k 大元素,不是第 k 个不同的元素。

    + +

    请实现 KthLargest 类:

    + +
      +
    • KthLargest(int k, int[] nums) 使用整数 k 和整数流 nums 初始化对象。
    • +
    • int add(int val)val 插入数据流 nums 后,返回当前数据流中第 k 大的元素。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["KthLargest", "add", "add", "add", "add", "add"]
    +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
    +输出:
    +[null, 4, 5, 5, 8, 8]
    +
    +解释:
    +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
    +kthLargest.add(3);   // return 4
    +kthLargest.add(5);   // return 5
    +kthLargest.add(10);  // return 5
    +kthLargest.add(9);   // return 8
    +kthLargest.add(4);   // return 8
    +
    + +

     

    +提示: + +
      +
    • 1 <= k <= 104
    • +
    • 0 <= nums.length <= 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • -104 <= val <= 104
    • +
    • 最多调用 add 方法 104
    • +
    • 题目数据保证,在查找第 k 大元素时,数组中至少有 k 个元素
    • +
    + +## 解法 + + + +小根堆存放最大的 k 个元素,那么堆顶就是第 k 大的元素。 + + + +### **Python3** + + + +```python +class KthLargest: + + def __init__(self, k: int, nums: List[int]): + self.q = [] + self.size = k + for num in nums: + self.add(num) + + def add(self, val: int) -> int: + heapq.heappush(self.q, val) + if len(self.q) > self.size: + heapq.heappop(self.q) + return self.q[0] + + +# Your KthLargest object will be instantiated and called as such: +# obj = KthLargest(k, nums) +# param_1 = obj.add(val) +``` + +### **Java** + + + +```java +class KthLargest { + private PriorityQueue q; + private int size; + + public KthLargest(int k, int[] nums) { + q = new PriorityQueue<>(k); + size = k; + for (int num : nums) { + add(num); + } + } + + public int add(int val) { + q.offer(val); + if (q.size() > size) { + q.poll(); + } + return q.peek(); + } +} + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest obj = new KthLargest(k, nums); + * int param_1 = obj.add(val); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0704.leetcode704 Binary Search-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0704.leetcode704 Binary Search-zh.md" new file mode 100644 index 00000000..66e8adde --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0704.leetcode704 Binary Search-zh.md" @@ -0,0 +1,127 @@ +# [704. 二分查找](https://leetcode-cn.com/problems/binary-search) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0704.Binary%20Search/README_EN.md) + +## 题目描述 + + + +

    给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target  ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1

    + +


    +示例 1:

    + +
    输入: nums = [-1,0,3,5,9,12], target = 9
    +输出: 4
    +解释: 9 出现在 nums 中并且下标为 4
    +
    + +

    示例 2:

    + +
    输入: nums = [-1,0,3,5,9,12], target = 2
    +输出: -1
    +解释: 2 不存在 nums 中因此返回 -1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 你可以假设 nums 中的所有元素是不重复的。
    2. +
    3. n 将在 [1, 10000]之间。
    4. +
    5. nums 的每个元素都将在 [-9999, 9999]之间。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def search(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + return left if nums[left] == target else -1 +``` + +### **Java** + + + +```java +class Solution { + public int search(int[] nums, int target) { + int left = 0, right = nums.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; + } +}; +``` + +### **Go** + +```go +func search(nums []int, target int) int { + left, right := 0, len(nums)-1 + for left < right { + mid := (left + right) >> 1 + if nums[mid] >= target { + right = mid + } else { + left = mid + 1 + } + } + if nums[left] == target { + return left + } + return -1 +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0705.leetcode705 Design HashSet-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0705.leetcode705 Design HashSet-zh.md" new file mode 100644 index 00000000..bf9e7251 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0705.leetcode705 Design HashSet-zh.md" @@ -0,0 +1,199 @@ +# [705. 设计哈希集合](https://leetcode-cn.com/problems/design-hashset) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0705.Design%20HashSet/README_EN.md) + +## 题目描述 + + + +

    不使用任何内建的哈希表库设计一个哈希集合(HashSet)。

    + +

    实现 MyHashSet 类:

    + +
      +
    • void add(key) 向哈希集合中插入值 key
    • +
    • bool contains(key) 返回哈希集合中是否存在这个值 key
    • +
    • void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
    • +
    +  + +

    示例:

    + +
    +输入:
    +["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
    +[[], [1], [2], [1], [3], [2], [2], [2], [2]]
    +输出:
    +[null, null, null, true, false, null, true, null, false]
    +
    +解释:
    +MyHashSet myHashSet = new MyHashSet();
    +myHashSet.add(1);      // set = [1]
    +myHashSet.add(2);      // set = [1, 2]
    +myHashSet.contains(1); // 返回 True
    +myHashSet.contains(3); // 返回 False ,(未找到)
    +myHashSet.add(2);      // set = [1, 2]
    +myHashSet.contains(2); // 返回 True
    +myHashSet.remove(2);   // set = [1]
    +myHashSet.contains(2); // 返回 False ,(已移除)
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= key <= 106
    • +
    • 最多调用 104addremovecontains
    • +
    + +

     

    + +

    进阶:你可以不使用内建的哈希集合库解决此问题吗?

    + + +## 解法 + + + +数组实现。 + + + +### **Python3** + + + +```python +class MyHashSet: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.data = [False] * 1000001 + + def add(self, key: int) -> None: + self.data[key] = True + + def remove(self, key: int) -> None: + self.data[key] = False + + def contains(self, key: int) -> bool: + """ + Returns true if this set contains the specified element + """ + return self.data[key] + + + +# Your MyHashSet object will be instantiated and called as such: +# obj = MyHashSet() +# obj.add(key) +# obj.remove(key) +# param_3 = obj.contains(key) +``` + +### **Java** + + + +- 可以一次性开辟一个大的数组,存放所有元素。 + +```java +class MyHashSet { + + private boolean[] data; + + /** Initialize your data structure here. */ + public MyHashSet() { + data = new boolean[1000001]; + } + + public void add(int key) { + data[key] = true; + } + + public void remove(int key) { + data[key] = false; + } + + /** Returns true if this set contains the specified element */ + public boolean contains(int key) { + return data[key]; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ +``` + +- 也可以开辟一个大小为 `SIZE` 的数组,数组的每个位置是一个链表。 + +```java +class MyHashSet { + + private static final int SIZE = 1000; + private LinkedList[] data; + + /** Initialize your data structure here. */ + public MyHashSet() { + data = new LinkedList[SIZE]; + Arrays.fill(data, new LinkedList()); + } + + public void add(int key) { + int index = hash(key); + Iterator iterator = data[index].iterator(); + while (iterator.hasNext()) { + Integer e = iterator.next(); + if (e == key) return; + } + data[index].addFirst(key); + } + + public void remove(int key) { + int index = hash(key); + ListIterator iterator = data[index].listIterator(); + while (iterator.hasNext()) { + Integer e = iterator.next(); + if (e == key) iterator.remove(); + } + } + + /** Returns true if this set contains the specified element */ + public boolean contains(int key) { + int index = hash(key); + Iterator iterator = data[index].iterator(); + while (iterator.hasNext()) { + Integer e = iterator.next(); + if (e == key) return true; + } + return false; + } + + private int hash(int key) { + return key % SIZE; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0706.leetcode706 Design HashMap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0706.leetcode706 Design HashMap-zh.md" new file mode 100644 index 00000000..720ff106 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0706.leetcode706 Design HashMap-zh.md" @@ -0,0 +1,151 @@ +# [706. 设计哈希映射](https://leetcode-cn.com/problems/design-hashmap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0706.Design%20HashMap/README_EN.md) + +## 题目描述 + + + +

    不使用任何内建的哈希表库设计一个哈希映射(HashMap)。

    + +

    实现 MyHashMap 类:

    + +
      +
    • MyHashMap() 用空映射初始化对象
    • +
    • void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中,则更新其对应的值 value
    • +
    • int get(int key) 返回特定的 key 所映射的 value ;如果映射中不包含 key 的映射,返回 -1
    • +
    • void remove(key) 如果映射中存在 key 的映射,则移除 key 和它所对应的 value
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
    +[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
    +输出:
    +[null, null, null, 1, -1, null, 1, null, -1]
    +
    +解释:
    +MyHashMap myHashMap = new MyHashMap();
    +myHashMap.put(1, 1); // myHashMap 现在为 [[1,1]]
    +myHashMap.put(2, 2); // myHashMap 现在为 [[1,1], [2,2]]
    +myHashMap.get(1);    // 返回 1 ,myHashMap 现在为 [[1,1], [2,2]]
    +myHashMap.get(3);    // 返回 -1(未找到),myHashMap 现在为 [[1,1], [2,2]]
    +myHashMap.put(2, 1); // myHashMap 现在为 [[1,1], [2,1]](更新已有的值)
    +myHashMap.get(2);    // 返回 1 ,myHashMap 现在为 [[1,1], [2,1]]
    +myHashMap.remove(2); // 删除键为 2 的数据,myHashMap 现在为 [[1,1]]
    +myHashMap.get(2);    // 返回 -1(未找到),myHashMap 现在为 [[1,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= key, value <= 106
    • +
    • 最多调用 104putgetremove 方法
    • +
    + +

     

    + +

    进阶:你能否不使用内置的 HashMap 库解决此问题?

    + + +## 解法 + + + +数组实现。 + + + +### **Python3** + + + +```python +class MyHashMap: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.data = [-1] * 1000001 + + def put(self, key: int, value: int) -> None: + """ + value will always be non-negative. + """ + self.data[key] = value + + def get(self, key: int) -> int: + """ + Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key + """ + return self.data[key] + + def remove(self, key: int) -> None: + """ + Removes the mapping of the specified value key if this map contains a mapping for the key + """ + self.data[key] = -1 + + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key) +``` + +### **Java** + + + +```java +class MyHashMap { + + private int[] data; + + /** Initialize your data structure here. */ + public MyHashMap() { + data = new int[1000001]; + Arrays.fill(data, -1); + } + + /** value will always be non-negative. */ + public void put(int key, int value) { + data[key] = value; + } + + /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ + public int get(int key) { + return data[key]; + } + + /** Removes the mapping of the specified value key if this map contains a mapping for the key */ + public void remove(int key) { + data[key] = -1; + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap obj = new MyHashMap(); + * obj.put(key,value); + * int param_2 = obj.get(key); + * obj.remove(key); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0707.leetcode707 Design Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0707.leetcode707 Design Linked List-zh.md" new file mode 100644 index 00000000..d94259ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0707.leetcode707 Design Linked List-zh.md" @@ -0,0 +1,235 @@ +# [707. 设计链表](https://leetcode-cn.com/problems/design-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0707.Design%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 nextval 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

    + +

    在链表类中实现这些功能:

    + +
      +
    • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1
    • +
    • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
    • +
    • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
    • +
    • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val  的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
    • +
    • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
    • +
    + +

     

    + +

    示例:

    + +
    MyLinkedList linkedList = new MyLinkedList();
    +linkedList.addAtHead(1);
    +linkedList.addAtTail(3);
    +linkedList.addAtIndex(1,2);   //链表变为1-> 2-> 3
    +linkedList.get(1);            //返回2
    +linkedList.deleteAtIndex(1);  //现在链表是1-> 3
    +linkedList.get(1);            //返回3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 所有val值都在 [1, 1000] 之内。
    • +
    • 操作次数将在  [1, 1000] 之内。
    • +
    • 请不要使用内置的 LinkedList 库。
    • +
    + + +## 解法 + + + +定义虚拟头结点 dummy,count 记录当前链表结点个数。 + + + +### **Python3** + + + +```python +class ListNode: + + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class MyLinkedList: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.dummy = ListNode() + self.count = 0 + + + def get(self, index: int) -> int: + """ + Get the value of the index-th node in the linked list. If the index is invalid, return -1. + """ + if index < 0 or index >= self.count: + return -1 + cur = self.dummy.next + for _ in range(index): + cur = cur.next + return cur.val + + + def addAtHead(self, val: int) -> None: + """ + Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. + """ + self.addAtIndex(0, val) + + + def addAtTail(self, val: int) -> None: + """ + Append a node of value val to the last element of the linked list. + """ + self.addAtIndex(self.count, val) + + + def addAtIndex(self, index: int, val: int) -> None: + """ + Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. + """ + if index > self.count: + return + pre = self.dummy + for _ in range(index): + pre = pre.next + pre.next = ListNode(val, pre.next) + self.count += 1 + + + def deleteAtIndex(self, index: int) -> None: + """ + Delete the index-th node in the linked list, if the index is valid. + """ + if index < 0 or index >= self.count: + return + pre = self.dummy + for _ in range(index): + pre = pre.next + t = pre.next + pre.next = t.next + t.next = None + self.count -= 1 + + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) +``` + +### **Java** + + + +```java +class MyLinkedList { + + private class ListNode { + int val; + ListNode next; + ListNode(int val) { + this(val, null); + } + ListNode(int val, ListNode next) { + this.val = val; + this.next = next; + } + } + + private ListNode dummy; + private int count; + + /** Initialize your data structure here. */ + public MyLinkedList() { + dummy = new ListNode(0); + count = 0; + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + public int get(int index) { + if (index < 0 || index >= count) { + return -1; + } + ListNode cur = dummy.next; + while (index-- > 0) { + cur = cur.next; + } + return cur.val; + } + + /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ + public void addAtHead(int val) { + addAtIndex(0, val); + } + + /** Append a node of value val to the last element of the linked list. */ + public void addAtTail(int val) { + addAtIndex(count, val); + } + + /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ + public void addAtIndex(int index, int val) { + if (index > count) { + return; + } + ListNode pre = dummy; + while (index-- > 0) { + pre = pre.next; + } + pre.next = new ListNode(val, pre.next); + ++count; + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + public void deleteAtIndex(int index) { + if (index < 0 || index >= count) { + return; + } + ListNode pre = dummy; + while (index-- > 0) { + pre = pre.next; + } + ListNode t = pre.next; + pre.next = t.next; + t.next = null; + --count; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList obj = new MyLinkedList(); + * int param_1 = obj.get(index); + * obj.addAtHead(val); + * obj.addAtTail(val); + * obj.addAtIndex(index,val); + * obj.deleteAtIndex(index); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0708.leetcode708 Insert into a Sorted Circular Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0708.leetcode708 Insert into a Sorted Circular Linked List-zh.md" new file mode 100644 index 00000000..bfbb2833 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0708.leetcode708 Insert into a Sorted Circular Linked List-zh.md" @@ -0,0 +1,147 @@ +# [708. 循环有序列表的插入](https://leetcode-cn.com/problems/insert-into-a-sorted-circular-linked-list) + +[English Version](https://cdn.jsdelivr.net/gh/yanglr/leetcode-ac@master/assets/0700-0799/0708.Insert%20into%20a%20Sorted%20Circular%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给定循环升序列表中的一个点,写一个函数向这个列表中插入一个新元素 insertVal ,使这个列表仍然是循环升序的。

    + +

    给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。

    + +

    如果有多个满足条件的插入位置,你可以选择任意一个位置插入新的值,插入后整个列表仍然保持有序。

    + +

    如果列表为空(给定的节点是 null),你需要创建一个循环有序列表并返回这个节点。否则。请返回原先给定的节点。

    + +

     

    + +

    示例 1:

    +
    +  +
    +输入:head = [3,4,1], insertVal = 2
    +输出:[3,4,1,2]
    +解释:在上图中,有一个包含三个元素的循环有序列表,你获得值为 3 的节点的指针,我们需要向表中插入元素 2 。新插入的节点应该在 1 和 3 之间,插入之后,整个列表如上图所示,最后返回节点 3 。
    +
    +
    +
    + +

    示例 2:

    + +
    +输入:head = [], insertVal = 1
    +输出:[1]
    +解释:列表为空(给定的节点是 null),创建一个循环有序列表并返回这个节点。
    +
    + +

    示例 3:

    + +
    +输入:head = [1], insertVal = 0
    +输出:[1,0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= Number of Nodes <= 5 * 10^4
    • +
    • -10^6 <= Node.val <= 10^6
    • +
    • -10^6 <= insertVal <= 10^6
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, next=None): + self.val = val + self.next = next +""" + +class Solution: + def insert(self, head: 'Node', insertVal: int) -> 'Node': + node = Node(val=insertVal) + if head is None: + node.next = node + return node + pre, cur = head, head.next + while 1: + if pre.val <= insertVal <= cur.val or (pre.val > cur.val and (insertVal >= pre.val or insertVal <= cur.val)): + break + pre, cur = cur, cur.next + if pre == head: + break + pre.next = node + node.next = cur + return head +``` + +### **Java** + + + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _next) { + val = _val; + next = _next; + } +}; +*/ + +class Solution { + public Node insert(Node head, int insertVal) { + Node node = new Node(insertVal); + if (head == null) { + node.next = node; + return node; + } + Node pre = head, cur = head.next; + while (true) { + if ((pre.val <= insertVal && insertVal <= cur.val) || (pre.val > cur.val && (insertVal >= pre.val || cur.val >= insertVal))) { + break; + } + pre = cur; + cur = cur.next; + if (pre == head) { + break; + } + } + pre.next = node; + node.next = cur; + return head; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0709.leetcode709 To Lower Case-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0709.leetcode709 To Lower Case-zh.md" new file mode 100644 index 00000000..e30327ec --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0709.leetcode709 To Lower Case-zh.md" @@ -0,0 +1,85 @@ +# [709. 转换成小写字母](https://leetcode-cn.com/problems/to-lower-case) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0709.To%20Lower%20Case/README_EN.md) + +## 题目描述 + + + +

    实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入: "Hello"
    +输出: "hello"
    + +

    示例 2:

    + +
    +输入: "here"
    +输出: "here"
    + +

    示例 3:

    + +
    +输入: "LOVELY"
    +输出: "lovely"
    +
    + + +## 解法 + + + +遍历字符串,遇到大写的字符,转小写。 + + + +### **Python3** + + + +```python +class Solution: + def toLowerCase(self, str: str) -> str: + if not str: + return str + n = len(str) + res = [] + for i in range(n): + c = ord(str[i]) + if c >= 65 and c <= 90: + c += 32 + res.append(chr(c)) + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String toLowerCase(String str) { + int n; + if (str == null || (n = str.length()) == 0) return str; + char[] chars = str.toCharArray(); + for (int i = 0; i < chars.length; ++i) { + boolean isUpper = chars[i] >= 'A' && chars[i] <= 'Z'; + if (isUpper) chars[i] += 32; + } + return new String(chars); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0710.leetcode710 Random Pick with Blacklist-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0710.leetcode710 Random Pick with Blacklist-zh.md" new file mode 100644 index 00000000..cc986ff7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0710.leetcode710 Random Pick with Blacklist-zh.md" @@ -0,0 +1,90 @@ +# [710. 黑名单中的随机数](https://leetcode-cn.com/problems/random-pick-with-blacklist) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0710.Random%20Pick%20with%20Blacklist/README_EN.md) + +## 题目描述 + + + +

    给定一个包含 [0,n ) 中独特的整数的黑名单 B,写一个函数从 [ 0,n ) 中返回一个不在 B 中的随机整数。

    + +

    对它进行优化使其尽量少调用系统方法 Math.random()

    + +

    提示:

    + +
      +
    1. 1 <= N <= 1000000000
    2. +
    3. 0 <= B.length < min(100000, N)
    4. +
    5. [0, N) 不包含 N,详细参见 interval notation 。
    6. +
    + +

    示例 1:

    + +
    +输入: 
    +["Solution","pick","pick","pick"]
    +[[1,[]],[],[],[]]
    +输出: [null,0,0,0]
    +
    + +

    示例 2:

    + +
    +输入: 
    +["Solution","pick","pick","pick"]
    +[[2,[]],[],[],[]]
    +输出: [null,1,1,1]
    +
    + +

    示例 3:

    + +
    +输入: 
    +["Solution","pick","pick","pick"]
    +[[3,[1]],[],[],[]]
    +Output: [null,0,0,2]
    +
    + +

    示例 4:

    + +
    +输入: 
    +["Solution","pick","pick","pick"]
    +[[4,[2]],[],[],[]]
    +输出: [null,1,3,1]
    +
    + +

    输入语法说明:

    + +

    输入是两个列表:调用成员函数名和调用的参数。Solution的构造函数有两个参数,N 和黑名单 Bpick 没有参数,输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0711.leetcode711 Number of Distinct Islands II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0711.leetcode711 Number of Distinct Islands II-zh.md" new file mode 100644 index 00000000..fd9cbd8c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0711.leetcode711 Number of Distinct Islands II-zh.md" @@ -0,0 +1,108 @@ +# [711. 不同岛屿的数量 II](https://leetcode-cn.com/problems/number-of-distinct-islands-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0711.Number%20of%20Distinct%20Islands%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非空01二维数组表示的网格,一个岛屿由四连通(上、下、左、右四个方向)的 1 组成,你可以认为网格的四周被海水包围。

    + +

    请你计算这个网格中共有多少个形状不同的岛屿。如果两个岛屿的形状相同,或者通过旋转(顺时针旋转 90°,180°,270°)、翻转(左右翻转、上下翻转)后形状相同,那么就认为这两个岛屿是相同的。

    + +

     

    + +

    样例 1:

    + +
    11000
    +10000
    +00001
    +00011
    +
    + +

    给定上图,返回结果 1
    +
    +注意 :

    + +
    11
    +1
    +
    + +

    + +
     1
    +11
    + +

    是相同的岛屿。因为我们通过 180° 旋转第一个岛屿,两个岛屿的形状相同。

    + +

     

    + +

    样例 2:

    + +
    11100
    +10001
    +01001
    +01110
    + +

    给定上图,返回结果 2
    +
    +下面是两个不同的岛屿:

    + +
    111
    +1
    + +

    + +
    1
    +1
    +
    + +

     

    + +

    注意 :

    + +
    111
    +1
    + +

    + +
    1
    +111
    +
    + +

    相同的岛屿。因为我们通过上下翻转第一个岛屿,两个岛屿的形状相同。

    + +

     

    + +

    注释 :  二维数组每维的大小都不会超过50。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0712.leetcode712 Minimum ASCII Delete Sum for Two Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0712.leetcode712 Minimum ASCII Delete Sum for Two Strings-zh.md" new file mode 100644 index 00000000..fe5d93d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0712.leetcode712 Minimum ASCII Delete Sum for Two Strings-zh.md" @@ -0,0 +1,68 @@ +# [712. 两个字符串的最小ASCII删除和](https://leetcode-cn.com/problems/minimum-ascii-delete-sum-for-two-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0712.Minimum%20ASCII%20Delete%20Sum%20for%20Two%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串s1, s2,找到使两个字符串相等所需删除字符的ASCII值的最小和。

    + +

    示例 1:

    + +
    +输入: s1 = "sea", s2 = "eat"
    +输出: 231
    +解释: 在 "sea" 中删除 "s" 并将 "s" 的值(115)加入总和。
    +在 "eat" 中删除 "t" 并将 116 加入总和。
    +结束时,两个字符串相等,115 + 116 = 231 就是符合条件的最小和。
    +
    + +

    示例 2:

    + +
    +输入: s1 = "delete", s2 = "leet"
    +输出: 403
    +解释: 在 "delete" 中删除 "dee" 字符串变成 "let",
    +将 100[d]+101[e]+101[e] 加入总和。在 "leet" 中删除 "e" 将 101[e] 加入总和。
    +结束时,两个字符串都等于 "let",结果即为 100+101+101+101 = 403 。
    +如果改为将两个字符串转换为 "lee" 或 "eet",我们会得到 433 或 417 的结果,比答案更大。
    +
    + +

    注意:

    + +
      +
    • 0 < s1.length, s2.length <= 1000
    • +
    • 所有字符串中的字符ASCII值在[97, 122]之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0713.leetcode713 Subarray Product Less Than K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0713.leetcode713 Subarray Product Less Than K-zh.md" new file mode 100644 index 00000000..6a428fb0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0713.leetcode713 Subarray Product Less Than K-zh.md" @@ -0,0 +1,59 @@ +# [713. 乘积小于K的子数组](https://leetcode-cn.com/problems/subarray-product-less-than-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0713.Subarray%20Product%20Less%20Than%20K/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数数组 nums

    + +

    找出该数组内乘积小于 k 的连续的子数组的个数。

    + +

    示例 1:

    + +
    +输入: nums = [10,5,2,6], k = 100
    +输出: 8
    +解释: 8个乘积小于100的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。
    +需要注意的是 [10,5,2] 并不是乘积小于100的子数组。
    +
    + +

    说明:

    + +
      +
    • 0 < nums.length <= 50000
    • +
    • 0 < nums[i] < 1000
    • +
    • 0 <= k < 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0714.leetcode714 Best Time to Buy and Sell Stock with Transaction Fee-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0714.leetcode714 Best Time to Buy and Sell Stock with Transaction Fee-zh.md" new file mode 100644 index 00000000..a9bfe915 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0714.leetcode714 Best Time to Buy and Sell Stock with Transaction Fee-zh.md" @@ -0,0 +1,129 @@ +# [714. 买卖股票的最佳时机含手续费](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0714.Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

    + +

    你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

    + +

    返回获得利润的最大值。

    + +

    注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

    + +

    示例 1:

    + +
    输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
    +输出: 8
    +解释: 能够达到的最大利润:  
    +在此处买入 prices[0] = 1
    +在此处卖出 prices[3] = 8
    +在此处买入 prices[4] = 4
    +在此处卖出 prices[5] = 9
    +总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
    + +

    注意:

    + +
      +
    • 0 < prices.length <= 50000.
    • +
    • 0 < prices[i] < 50000.
    • +
    • 0 <= fee < 50000.
    • +
    + +## 解法 + + + +动态规划法。 + +设 f1 表示当天持有股票的最大利润,f2 表示当天没持有股票的最大利润。 + +初始第 1 天结束时,`f1 = -prices[0]`,`f2 = 0`。 + +从第 2 天开始,当天结束时: + +- 若持有,则可能是前一天持有,今天继续持有;也可能前一天没持有,今天买入,`f1 = max(f1, f2 - price)`。 +- 若没持有,则可能是前一天持有,今天卖出;也可能是前一天没没有,今天继续没持有,`f2 = max(f2, f1 + price - fee)`。 + +最后返回 f2 即可。 + + + +### **Python3** + + + +```python +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + # 持有,没持有 + f1, f2 = -prices[0], 0 + for price in prices[1:]: + f1 = max(f1, f2 - price) + f2 = max(f2, f1 + price - fee) + return f2 +``` + +### **Java** + + + +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, f2 - prices[i]); + f2 = Math.max(f2, f1 + prices[i] - fee); + } + return f2; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int f1 = -prices[0], f2 = 0; + for (int i = 1; i < prices.size(); ++i) { + f1 = max(f1, f2 - prices[i]); + f2 = max(f2, f1 + prices[i] - fee); + } + return f2; + } +}; +``` + +### **Go** + +```go +func maxProfit(prices []int, fee int) int { + f1, f2 := -prices[0], 0 + for i := 1; i < len(prices); i++ { + f1 = max(f1, f2-prices[i]) + f2 = max(f2, f1+prices[i]-fee) + } + return f2 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0715.leetcode715 Range Module-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0715.leetcode715 Range Module-zh.md" new file mode 100644 index 00000000..73fdcaa9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0715.leetcode715 Range Module-zh.md" @@ -0,0 +1,71 @@ +# [715. Range 模块](https://leetcode-cn.com/problems/range-module) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0715.Range%20Module/README_EN.md) + +## 题目描述 + + + +

    Range 模块是跟踪数字范围的模块。你的任务是以一种有效的方式设计和实现以下接口。

    + +
      +
    • addRange(int left, int right) 添加半开区间 [left, right),跟踪该区间中的每个实数。添加与当前跟踪的数字部分重叠的区间时,应当添加在区间 [left, right) 中尚未跟踪的任何数字到该区间中。
    • +
    • queryRange(int left, int right) 只有在当前正在跟踪区间 [left, right) 中的每一个实数时,才返回 true。
    • +
    • removeRange(int left, int right) 停止跟踪区间 [left, right) 中当前正在跟踪的每个实数。
    • +
    + +

     

    + +

    示例:

    + +
    addRange(10, 20): null
    +removeRange(14, 16): null
    +queryRange(10, 14): true (区间 [10, 14) 中的每个数都正在被跟踪)
    +queryRange(13, 15): false (未跟踪区间 [13, 15) 中像 14, 14.03, 14.17 这样的数字)
    +queryRange(16, 17): true (尽管执行了删除操作,区间 [16, 17) 中的数字 16 仍然会被跟踪)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 半开区间 [left, right) 表示所有满足 left <= x < right 的实数。
    • +
    • 对 addRange, queryRange, removeRange 的所有调用中 0 < left < right < 10^9
    • +
    • 在单个测试用例中,对 addRange 的调用总数不超过 1000 次。
    • +
    • 在单个测试用例中,对  queryRange 的调用总数不超过 5000 次。
    • +
    • 在单个测试用例中,对 removeRange 的调用总数不超过 1000 次。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0716.leetcode716 Max Stack-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0716.leetcode716 Max Stack-zh.md" new file mode 100644 index 00000000..47954a2f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0716.leetcode716 Max Stack-zh.md" @@ -0,0 +1,93 @@ +# [716. 最大栈](https://leetcode-cn.com/problems/max-stack) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0716.Max%20Stack/README_EN.md) + +## 题目描述 + + + +

    设计一个最大栈数据结构,既支持栈操作,又支持查找栈中最大元素。

    + +

    实现 MaxStack 类:

    + +
      +
    • MaxStack() 初始化栈对象
    • +
    • void push(int x) 将元素 x 压入栈中。
    • +
    • int pop() 移除栈顶元素并返回这个元素。
    • +
    • int top() 返回栈顶元素,无需移除。
    • +
    • int peekMax() 检索并返回栈中最大元素,无需移除。
    • +
    • int popMax() 检索并返回栈中最大元素,并将其移除。如果有多个最大元素,只要移除 最靠近栈顶 的那个。
    • +
    + +

     

    + +

    示例:

    + +
    +输入
    +["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"]
    +[[], [5], [1], [5], [], [], [], [], [], []]
    +输出
    +[null, null, null, null, 5, 5, 1, 5, 1, 5]
    +
    +解释
    +MaxStack stk = new MaxStack();
    +stk.push(5);   // [5] - 5 既是栈顶元素,也是最大元素
    +stk.push(1);   // [5, 1] - 栈顶元素是 1,最大元素是 5
    +stk.push(5);   // [5, 1, 5] - 5 既是栈顶元素,也是最大元素
    +stk.top();     // 返回 5,[5, 1, 5] - 栈没有改变
    +stk.popMax();  // 返回 5,[5, 1] - 栈发生改变,栈顶元素不再是最大元素
    +stk.top();     // 返回 1,[5, 1] - 栈没有改变
    +stk.peekMax(); // 返回 5,[5, 1] - 栈没有改变
    +stk.pop();     // 返回 1,[5] - 此操作后,5 既是栈顶元素,也是最大元素
    +stk.top();     // 返回 5,[5] - 栈没有改变
    +
    + +

     

    + +

    提示:

    + +
      +
    • -107 <= x <= 107
    • +
    • 最多调用 104 次 pushpoptoppeekMax 和 popMax
    • +
    • 调用 poptoppeekMax 或 popMax 时,栈中 至少存在一个元素
    • +
    + +

     

    + +

    进阶: 

    + +
      +
    • 试着设计解决方案:调用 top 方法的时间复杂度为 O(1) ,调用其他方法的时间复杂度为 O(logn) 。 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0717.leetcode717 1-bit and 2-bit Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0717.leetcode717 1-bit and 2-bit Characters-zh.md" new file mode 100644 index 00000000..2e788433 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0717.leetcode717 1-bit and 2-bit Characters-zh.md" @@ -0,0 +1,69 @@ +# [717. 1比特与2比特字符](https://leetcode-cn.com/problems/1-bit-and-2-bit-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0717.1-bit%20and%202-bit%20Characters/README_EN.md) + +## 题目描述 + + + +

    有两种特殊字符。第一种字符可以用一比特0来表示。第二种字符可以用两比特(10 或 11)来表示。

    + +

    现给一个由若干比特组成的字符串。问最后一个字符是否必定为一个一比特字符。给定的字符串总是由0结束。

    + +

    示例 1:

    + +
    +输入: 
    +bits = [1, 0, 0]
    +输出: True
    +解释: 
    +唯一的编码方式是一个两比特字符和一个一比特字符。所以最后一个字符是一比特字符。
    +
    + +

    示例 2:

    + +
    +输入: 
    +bits = [1, 1, 1, 0]
    +输出: False
    +解释: 
    +唯一的编码方式是两比特字符和两比特字符。所以最后一个字符不是一比特字符。
    +
    + +

    注意:

    + +
      +
    • 1 <= len(bits) <= 1000.
    • +
    • bits[i] 总是0 或 1.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0718.leetcode718 Maximum Length of Repeated Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0718.leetcode718 Maximum Length of Repeated Subarray-zh.md" new file mode 100644 index 00000000..ab69f654 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0718.leetcode718 Maximum Length of Repeated Subarray-zh.md" @@ -0,0 +1,61 @@ +# [718. 最长重复子数组](https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0718.Maximum%20Length%20of%20Repeated%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。

    + +

     

    + +

    示例:

    + +
    输入:
    +A: [1,2,3,2,1]
    +B: [3,2,1,4,7]
    +输出:3
    +解释:
    +长度最长的公共子数组是 [3, 2, 1] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= len(A), len(B) <= 1000
    • +
    • 0 <= A[i], B[i] < 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0719.leetcode719 Find K-th Smallest Pair Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0719.leetcode719 Find K-th Smallest Pair Distance-zh.md" new file mode 100644 index 00000000..ff1e973e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0719.leetcode719 Find K-th Smallest Pair Distance-zh.md" @@ -0,0 +1,63 @@ +# [719. 找出第 k 小的距离对](https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0719.Find%20K-th%20Smallest%20Pair%20Distance/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。

    + +

    示例 1:

    + +
    +输入:
    +nums = [1,3,1]
    +k = 1
    +输出:0 
    +解释:
    +所有数对如下:
    +(1,3) -> 2
    +(1,1) -> 0
    +(3,1) -> 2
    +因此第 1 个最小距离的数对是 (1,1),它们之间的距离为 0。
    +
    + +

    提示:

    + +
      +
    1. 2 <= len(nums) <= 10000.
    2. +
    3. 0 <= nums[i] < 1000000.
    4. +
    5. 1 <= k <= len(nums) * (len(nums) - 1) / 2.
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0720.leetcode720 Longest Word in Dictionary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0720.leetcode720 Longest Word in Dictionary-zh.md" new file mode 100644 index 00000000..ce1f9ea0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0720.leetcode720 Longest Word in Dictionary-zh.md" @@ -0,0 +1,72 @@ +# [720. 词典中最长的单词](https://leetcode-cn.com/problems/longest-word-in-dictionary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0720.Longest%20Word%20in%20Dictionary/README_EN.md) + +## 题目描述 + + + +

    给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

    + +

    若无答案,则返回空字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:
    +words = ["w","wo","wor","worl", "world"]
    +输出:"world"
    +解释: 
    +单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。
    +
    + +

    示例 2:

    + +
    输入:
    +words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
    +输出:"apple"
    +解释:
    +"apply"和"apple"都能由词典中的单词组成。但是"apple"的字典序小于"apply"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 所有输入的字符串都只包含小写字母。
    • +
    • words数组长度范围为[1,1000]
    • +
    • words[i]的长度范围为[1,30]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0721.leetcode721 Accounts Merge-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0721.leetcode721 Accounts Merge-zh.md" new file mode 100644 index 00000000..d9444873 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0721.leetcode721 Accounts Merge-zh.md" @@ -0,0 +1,70 @@ +# [721. 账户合并](https://leetcode-cn.com/problems/accounts-merge) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0721.Accounts%20Merge/README_EN.md) + +## 题目描述 + + + +

    给定一个列表 accounts,每个元素 accounts[i] 是一个字符串列表,其中第一个元素 accounts[i][0] 是 名称 (name),其余元素是 emails 表示该账户的邮箱地址。

    + +

    现在,我们想合并这些账户。如果两个账户都有一些共同的邮箱地址,则两个账户必定属于同一个人。请注意,即使两个账户具有相同的名称,它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的账户,但其所有账户都具有相同的名称。

    + +

    合并账户后,按以下格式返回账户:每个账户的第一个元素是名称,其余元素是按字符 ASCII 顺序排列的邮箱地址。账户本身可以以任意顺序返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
    +输出:
    +[["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
    +解释:
    +第一个和第三个 John 是同一个人,因为他们有共同的邮箱地址 "johnsmith@mail.com"。 
    +第二个 John 和 Mary 是不同的人,因为他们的邮箱地址没有被其他帐户使用。
    +可以以任何顺序返回这些列表,例如答案 [['Mary','mary@mail.com'],['John','johnnybravo@mail.com'],
    +['John','john00@mail.com','john_newyork@mail.com','johnsmith@mail.com']] 也是正确的。
    +
    + +

     

    + +

    提示:

    + +
      +
    • accounts的长度将在[1,1000]的范围内。
    • +
    • accounts[i]的长度将在[1,10]的范围内。
    • +
    • accounts[i][j]的长度将在[1,30]的范围内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0722.leetcode722 Remove Comments-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0722.leetcode722 Remove Comments-zh.md" new file mode 100644 index 00000000..ffb5026b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0722.leetcode722 Remove Comments-zh.md" @@ -0,0 +1,109 @@ +# [722. 删除注释](https://leetcode-cn.com/problems/remove-comments) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0722.Remove%20Comments/README_EN.md) + +## 题目描述 + + + +

    给一个 C++ 程序,删除程序中的注释。这个程序source是一个数组,其中source[i]表示第i行源码。 这表示每行源码由\n分隔。

    + +

    在 C++ 中有两种注释风格,行内注释和块注释。

    + +

    字符串// 表示行注释,表示//和其右侧的其余字符应该被忽略。

    + +

    字符串/* 表示一个块注释,它表示直到*/的下一个(非重叠)出现的所有字符都应该被忽略。(阅读顺序为从左到右)非重叠是指,字符串/*/并没有结束块注释,因为注释的结尾与开头相重叠。

    + +

    第一个有效注释优先于其他注释:如果字符串//出现在块注释中会被忽略。 同样,如果字符串/*出现在行或块注释中也会被忽略。

    + +

    如果一行在删除注释之后变为空字符串,那么不要输出该行。即,答案列表中的每个字符串都是非空的。

    + +

    样例中没有控制字符,单引号或双引号字符。比如,source = "string s = "/* Not a comment. */";" 不会出现在测试样例里。(此外,没有其他内容(如定义或宏)会干扰注释。)

    + +

    我们保证每一个块注释最终都会被闭合, 所以在行或块注释之外的/*总是开始新的注释。

    + +

    最后,隐式换行符可以通过块注释删除。 有关详细信息,请参阅下面的示例。

    + +

    从源代码中删除注释后,需要以相同的格式返回源代码。

    + +

    示例 1:

    + +
    +输入: 
    +source = ["/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"]
    +
    +示例代码可以编排成这样:
    +/*Test program */
    +int main()
    +{ 
    +  // variable declaration 
    +int a, b, c;
    +/* This is a test
    +   multiline  
    +   comment for 
    +   testing */
    +a = b + c;
    +}
    +
    +输出: ["int main()","{ ","  ","int a, b, c;","a = b + c;","}"]
    +
    +编排后:
    +int main()
    +{ 
    +  
    +int a, b, c;
    +a = b + c;
    +}
    +
    +解释: 
    +第 1 行和第 6-9 行的字符串 /* 表示块注释。第 4 行的字符串 // 表示行注释。
    +
    + +

    示例 2:

    + +
    +输入: 
    +source = ["a/*comment", "line", "more_comment*/b"]
    +输出: ["ab"]
    +解释: 原始的 source 字符串是 "a/*comment\nline\nmore_comment*/b", 其中我们用粗体显示了换行符。删除注释后,隐含的换行符被删除,留下字符串 "ab" 用换行符分隔成数组时就是 ["ab"].
    +
    + +

    注意:

    + +
      +
    • source的长度范围为[1, 100].
    • +
    • source[i]的长度范围为[0, 80].
    • +
    • 每个块注释都会被闭合。
    • +
    • 给定的源码中不会有单引号、双引号或其他控制字符。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0723.leetcode723 Candy Crush-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0723.leetcode723 Candy Crush-zh.md" new file mode 100644 index 00000000..3c6158f5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0723.leetcode723 Candy Crush-zh.md" @@ -0,0 +1,76 @@ +# [723. 粉碎糖果](https://leetcode-cn.com/problems/candy-crush) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0723.Candy%20Crush/README_EN.md) + +## 题目描述 + + + +

    这个问题是实现一个简单的消除算法。

    + +

    给定一个二维整数数组 board 代表糖果所在的方格,不同的正整数 board[i][j] 代表不同种类的糖果,如果 board[i][j] = 0 代表 (i, j) 这个位置是空的。给定的方格是玩家移动后的游戏状态,现在需要你根据以下规则粉碎糖果,使得整个方格处于稳定状态并最终输出。

    + +
      +
    1. 如果有三个及以上水平或者垂直相连的同种糖果,同一时间将它们粉碎,即将这些位置变成空的。
    2. +
    3. 在同时粉碎掉这些糖果之后,如果有一个空的位置上方还有糖果,那么上方的糖果就会下落直到碰到下方的糖果或者底部,这些糖果都是同时下落,也不会有新的糖果从顶部出现并落下来。
    4. +
    5. 通过前两步的操作,可能又会出现可以粉碎的糖果,请继续重复前面的操作。
    6. +
    7. 当不存在可以粉碎的糖果,也就是状态稳定之后,请输出最终的状态。
    8. +
    + +

    你需要模拟上述规则并使整个方格达到稳定状态,并输出。

    + +

     

    + +

    样例 :

    + +
    输入:
    +board = 
    +[[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]]
    +
    +输出:
    +[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
    +
    +解释: 
    +
    +
    + +

     

    + +

    注释 :

    + +
      +
    1. board 数组的行数区间是 [3, 50]。
    2. +
    3. board[i] 数组的长度区间(即 board 数组的列数区间)是 [3, 50]。
    4. +
    5. 每个 board[i][j] 初始整数范围是 [1, 2000]。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0724.leetcode724 Find Pivot Index-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0724.leetcode724 Find Pivot Index-zh.md" new file mode 100644 index 00000000..755123eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0724.leetcode724 Find Pivot Index-zh.md" @@ -0,0 +1,111 @@ +# [724. 寻找数组的中心下标](https://leetcode-cn.com/problems/find-pivot-index) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0724.Find%20Pivot%20Index/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,请编写一个能够返回数组 “中心下标” 的方法。

    + +

    数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。

    + +

    如果数组不存在中心下标,返回 -1 。如果数组有多个中心下标,应该返回最靠近左边的那一个。

    + +

    注意:中心下标可能出现在数组的两端。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1, 7, 3, 6, 5, 6]
    +输出:3
    +解释:
    +中心下标是 3 。
    +左侧数之和 (1 + 7 + 3 = 11),
    +右侧数之和 (5 + 6 = 11) ,二者相等。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1, 2, 3]
    +输出:-1
    +解释:
    +数组中不存在满足此条件的中心下标。
    + +

    示例 3:

    + +
    +输入:nums = [2, 1, -1]
    +输出:0
    +解释:
    +中心下标是 0 。
    +下标 0 左侧不存在元素,视作和为 0 ;
    +右侧数之和为 1 + (-1) = 0 ,二者相等。
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums 的长度范围为 [0, 10000]
    • +
    • 任何一个 nums[i] 将会是一个范围在 [-1000, 1000]的整数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def pivotIndex(self, nums: List[int]) -> int: + sums = sum(nums) + pre_sum = 0 + for i, v in enumerate(nums): + if (pre_sum << 1) == sums - v: + return i + pre_sum += v + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int pivotIndex(int[] nums) { + int sums = 0; + for (int e : nums) { + sums += e; + } + int preSum = 0; + for (int i = 0; i < nums.length; ++i) { + // preSum == sums - nums[i] - preSum + if (preSum << 1 == sums - nums[i]) { + return i; + } + preSum += nums[i]; + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0725.leetcode725 Split Linked List in Parts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0725.leetcode725 Split Linked List in Parts-zh.md" new file mode 100644 index 00000000..4c463801 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0725.leetcode725 Split Linked List in Parts-zh.md" @@ -0,0 +1,149 @@ +# [725. 分隔链表](https://leetcode-cn.com/problems/split-linked-list-in-parts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0725.Split%20Linked%20List%20in%20Parts/README_EN.md) + +## 题目描述 + + + +

    给定一个头结点为 root 的链表, 编写一个函数以将链表分隔为 k 个连续的部分。

    + +

    每部分的长度应该尽可能的相等: 任意两部分的长度差距不能超过 1,也就是说可能有些部分为 null。

    + +

    这k个部分应该按照在链表中出现的顺序进行输出,并且排在前面的部分的长度应该大于或等于后面的长度。

    + +

    返回一个符合上述规则的链表的列表。

    + +

    举例: 1->2->3->4, k = 5 // 5 结果 [ [1], [2], [3], [4], null ]

    + +

    示例 1:

    + +
    +输入: 
    +root = [1, 2, 3], k = 5
    +输出: [[1],[2],[3],[],[]]
    +解释:
    +输入输出各部分都应该是链表,而不是数组。
    +例如, 输入的结点 root 的 val= 1, root.next.val = 2, \root.next.next.val = 3, 且 root.next.next.next = null。
    +第一个输出 output[0] 是 output[0].val = 1, output[0].next = null。
    +最后一个元素 output[4] 为 null, 它代表了最后一个部分为空链表。
    +
    + +

    示例 2:

    + +
    +输入: 
    +root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
    +输出: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
    +解释:
    +输入被分成了几个连续的部分,并且每部分的长度相差不超过1.前面部分的长度大于等于后面部分的长度。
    +
    + +

     

    + +

    提示:

    + +
      +
    • root 的长度范围: [0, 1000].
    • +
    • 输入的每个节点的大小范围:[0, 999].
    • +
    • k 的取值范围: [1, 50].
    • +
    + +

     

    + + +## 解法 + + + +先遍历链表,统计结点总个数。 + +接着将链表拆分,`width` 表示每一部分至少含有的结点个数,而 `remainder` 表示前 `remainder` 部分,每一部分多出一个数。 + +然后遍历链表,依次拆出每一部分,添加到结果数组 `res` 即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: + n, cur = 0, root + while cur: + n += 1 + cur = cur.next + cur = root + width, remainder = divmod(n, k) + res = [None for _ in range(k)] + for i in range(k): + head = cur + for j in range(width + (i < remainder) - 1): + if cur: + cur = cur.next + if cur: + cur.next, cur = None, cur.next + res[i] = head + return res +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode[] splitListToParts(ListNode root, int k) { + int n = 0; + ListNode cur = root; + while (cur != null) { + ++n; + cur = cur.next; + } + // width 表示每一部分至少含有的结点个数 + // remainder 表示前 remainder 部分,每一部分多出一个数 + int width = n / k, remainder = n % k; + ListNode[] res = new ListNode[k]; + cur = root; + for (int i = 0; i < k; ++i) { + ListNode head = cur; + for (int j = 0; j < width + ((i < remainder) ? 1 : 0) - 1; ++j) { + if (cur != null) { + cur = cur.next; + } + } + if (cur != null) { + ListNode t = cur.next; + cur.next = null; + cur = t; + } + res[i] = head; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0726.leetcode726 Number of Atoms-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0726.leetcode726 Number of Atoms-zh.md" new file mode 100644 index 00000000..a45b3467 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0726.leetcode726 Number of Atoms-zh.md" @@ -0,0 +1,88 @@ +# [726. 原子的数量](https://leetcode-cn.com/problems/number-of-atoms) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0726.Number%20of%20Atoms/README_EN.md) + +## 题目描述 + + + +

    给定一个化学式formula(作为字符串),返回每种原子的数量。

    + +

    原子总是以一个大写字母开始,接着跟随0个或任意个小写字母,表示原子的名字。

    + +

    如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。例如,H2O 和 H2O2 是可行的,但 H1O2 这个表达是不可行的。

    + +

    两个化学式连在一起是新的化学式。例如 H2O2He3Mg4 也是化学式。

    + +

    一个括号中的化学式和数字(可选择性添加)也是化学式。例如 (H2O2) 和 (H2O2)3 是化学式。

    + +

    给定一个化学式,输出所有原子的数量。格式为:第一个(按字典序)原子的名子,跟着它的数量(如果数量大于 1),然后是第二个原子的名字(按字典序),跟着它的数量(如果数量大于 1),以此类推。

    + +

    示例 1:

    + +
    +输入: 
    +formula = "H2O"
    +输出: "H2O"
    +解释: 
    +原子的数量是 {'H': 2, 'O': 1}。
    +
    + +

    示例 2:

    + +
    +输入: 
    +formula = "Mg(OH)2"
    +输出: "H2MgO2"
    +解释: 
    +原子的数量是 {'H': 2, 'Mg': 1, 'O': 2}。
    +
    + +

    示例 3:

    + +
    +输入: 
    +formula = "K4(ON(SO3)2)2"
    +输出: "K4N2O14S4"
    +解释: 
    +原子的数量是 {'K': 4, 'N': 2, 'O': 14, 'S': 4}。
    +
    + +

    注意:

    + +
      +
    • 所有原子的第一个字母为大写,剩余字母都是小写。
    • +
    • formula的长度在[1, 1000]之间。
    • +
    • formula只包含字母、数字和圆括号,并且题目中给定的是合法的化学式。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0727.leetcode727 Minimum Window Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0727.leetcode727 Minimum Window Subsequence-zh.md" new file mode 100644 index 00000000..dbd482c4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0727.leetcode727 Minimum Window Subsequence-zh.md" @@ -0,0 +1,63 @@ +# [727. 最小窗口子序列](https://leetcode-cn.com/problems/minimum-window-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0727.Minimum%20Window%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定字符串 S and T,找出 S 中最短的(连续)子串 W ,使得 TW子序列

    + +

    如果 S 中没有窗口可以包含 T 中的所有字符,返回空字符串 ""。如果有不止一个最短长度的窗口,返回开始位置最靠左的那个。

    + +

    示例 1:

    + +
    输入:
    +S = "abcdebdde", T = "bde"
    +输出:"bcde"
    +解释:
    +"bcde" 是答案,因为它在相同长度的字符串 "bdde" 出现之前。
    +"deb" 不是一个更短的答案,因为在窗口中必须按顺序出现 T 中的元素。
    + +

     

    + +

    注:

    + +
      +
    • 所有输入的字符串都只包含小写字母。All the strings in the input will only contain lowercase letters.
    • +
    • S 长度的范围为 [1, 20000]
    • +
    • T 长度的范围为 [1, 100]
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0728.leetcode728 Self Dividing Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0728.leetcode728 Self Dividing Numbers-zh.md" new file mode 100644 index 00000000..62b2cd72 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0728.leetcode728 Self Dividing Numbers-zh.md" @@ -0,0 +1,60 @@ +# [728. 自除数](https://leetcode-cn.com/problems/self-dividing-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0728.Self%20Dividing%20Numbers/README_EN.md) + +## 题目描述 + + + +

    自除数 是指可以被它包含的每一位数除尽的数。

    + +

    例如,128 是一个自除数,因为 128 % 1 == 0128 % 2 == 0128 % 8 == 0

    + +

    还有,自除数不允许包含 0 。

    + +

    给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。

    + +

    示例 1:

    + +
    +输入: 
    +上边界left = 1, 下边界right = 22
    +输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
    +
    + +

    注意:

    + +
      +
    • 每个输入参数的边界满足 1 <= left <= right <= 10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0729.leetcode729 My Calendar I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0729.leetcode729 My Calendar I-zh.md" new file mode 100644 index 00000000..e664f919 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0729.leetcode729 My Calendar I-zh.md" @@ -0,0 +1,67 @@ +# [729. 我的日程安排表 I](https://leetcode-cn.com/problems/my-calendar-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0729.My%20Calendar%20I/README_EN.md) + +## 题目描述 + + + +

    实现一个 MyCalendar 类来存放你的日程安排。如果要添加的时间内没有其他安排,则可以存储这个新的日程安排。

    + +

    MyCalendar 有一个 book(int start, int end)方法。它意味着在 start 到 end 时间内增加一个日程安排,注意,这里的时间是半开区间,即 [start, end), 实数 x 的范围为,  start <= x < end

    + +

    当两个日程安排有一些时间上的交叉时(例如两个日程安排都在同一时间内),就会产生重复预订。

    + +

    每次调用 MyCalendar.book方法时,如果可以将日程安排成功添加到日历中而不会导致重复预订,返回 true。否则,返回 false 并且不要将该日程安排添加到日历中。

    + +

    请按照以下步骤调用 MyCalendar 类: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)

    + +

    示例 1:

    + +
    +MyCalendar();
    +MyCalendar.book(10, 20); // returns true
    +MyCalendar.book(15, 25); // returns false
    +MyCalendar.book(20, 30); // returns true
    +解释: 
    +第一个日程安排可以添加到日历中.  第二个日程安排不能添加到日历中,因为时间 15 已经被第一个日程安排预定了。
    +第三个日程安排可以添加到日历中,因为第一个日程安排并不包含时间 20 。
    +
    + +

    说明:

    + +
      +
    • 每个测试用例,调用 MyCalendar.book 函数最多不超过 1000次。
    • +
    • 调用函数 MyCalendar.book(start, end)时, start 和 end 的取值范围为 [0, 10^9]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0730.leetcode730 Count Different Palindromic Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0730.leetcode730 Count Different Palindromic Subsequences-zh.md" new file mode 100644 index 00000000..2e15e9e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0730.leetcode730 Count Different Palindromic Subsequences-zh.md" @@ -0,0 +1,78 @@ +# [730. 统计不同回文子序列](https://leetcode-cn.com/problems/count-different-palindromic-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0730.Count%20Different%20Palindromic%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 S,找出 S 中不同的非空回文子序列个数,并返回该数字与 10^9 + 7 的模。

    + +

    通过从 S 中删除 0 个或多个字符来获得子序列。

    + +

    如果一个字符序列与它反转后的字符序列一致,那么它是回文字符序列。

    + +

    如果对于某个  iA_i != B_i,那么 A_1, A_2, ... 和 B_1, B_2, ... 这两个字符序列是不同的。

    + +

     

    + +

    示例 1:

    + +
    输入:
    +S = 'bccb'
    +输出:6
    +解释:
    +6 个不同的非空回文子字符序列分别为:'b', 'c', 'bb', 'cc', 'bcb', 'bccb'。
    +注意:'bcb' 虽然出现两次但仅计数一次。
    +
    + +

    示例 2:

    + +
    输入:
    +S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
    +输出:104860361
    +解释:
    +共有 3104860382 个不同的非空回文子序列,对 10^9 + 7 取模为 104860361。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 字符串 S 的长度将在[1, 1000]范围内。
    • +
    • 每个字符 S[i] 将会是集合 {'a', 'b', 'c', 'd'} 中的某一个。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0731.leetcode731 My Calendar II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0731.leetcode731 My Calendar II-zh.md" new file mode 100644 index 00000000..3e12ab54 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0731.leetcode731 My Calendar II-zh.md" @@ -0,0 +1,76 @@ +# [731. 我的日程安排表 II](https://leetcode-cn.com/problems/my-calendar-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0731.My%20Calendar%20II/README_EN.md) + +## 题目描述 + + + +

    实现一个 MyCalendar 类来存放你的日程安排。如果要添加的时间内不会导致三重预订时,则可以存储这个新的日程安排。

    + +

    MyCalendar 有一个 book(int start, int end)方法。它意味着在 startend 时间内增加一个日程安排,注意,这里的时间是半开区间,即 [start, end), 实数 x 的范围为,  start <= x < end

    + +

    当三个日程安排有一些时间上的交叉时(例如三个日程安排都在同一时间内),就会产生三重预订。

    + +

    每次调用 MyCalendar.book方法时,如果可以将日程安排成功添加到日历中而不会导致三重预订,返回 true。否则,返回 false 并且不要将该日程安排添加到日历中。

    + +

    请按照以下步骤调用MyCalendar 类: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)

    + +

     

    + +

    示例:

    + +
    MyCalendar();
    +MyCalendar.book(10, 20); // returns true
    +MyCalendar.book(50, 60); // returns true
    +MyCalendar.book(10, 40); // returns true
    +MyCalendar.book(5, 15); // returns false
    +MyCalendar.book(5, 10); // returns true
    +MyCalendar.book(25, 55); // returns true
    +解释: 
    +前两个日程安排可以添加至日历中。 第三个日程安排会导致双重预订,但可以添加至日历中。
    +第四个日程安排活动(5,15)不能添加至日历中,因为它会导致三重预订。
    +第五个日程安排(5,10)可以添加至日历中,因为它未使用已经双重预订的时间10。
    +第六个日程安排(25,55)可以添加至日历中,因为时间 [25,40] 将和第三个日程安排双重预订;
    +时间 [40,50] 将单独预订,时间 [50,55)将和第二个日程安排双重预订。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每个测试用例,调用 MyCalendar.book 函数最多不超过 1000次。
    • +
    • 调用函数 MyCalendar.book(start, end)时, start 和 end 的取值范围为 [0, 10^9]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0732.leetcode732 My Calendar III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0732.leetcode732 My Calendar III-zh.md" new file mode 100644 index 00000000..8a6580b4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0732.leetcode732 My Calendar III-zh.md" @@ -0,0 +1,79 @@ +# [732. 我的日程安排表 III](https://leetcode-cn.com/problems/my-calendar-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0732.My%20Calendar%20III/README_EN.md) + +## 题目描述 + + + +

    k 个日程安排有一些时间上的交叉时(例如 k 个日程安排都在同一时间内),就会产生 k 次预订。

    + +

    给你一些日程安排 [start, end) ,请你在每个日程安排添加后,返回一个整数 k ,表示所有先前日程安排会产生的最大 k 次预订。

    + +

    实现一个 MyCalendarThree 类来存放你的日程安排,你可以一直添加新的日程安排。

    + +
      +
    • MyCalendarThree() 初始化对象。
    • +
    • int book(int start, int end) 返回一个整数 k ,表示日历中存在的 k 次预订的最大值。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["MyCalendarThree", "book", "book", "book", "book", "book", "book"]
    +[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
    +输出:
    +[null, 1, 1, 2, 3, 3, 3]
    +
    +解释:
    +MyCalendarThree myCalendarThree = new MyCalendarThree();
    +myCalendarThree.book(10, 20); // 返回 1 ,第一个日程安排可以预订并且不存在相交,所以最大 k 次预订是 1 次预订。
    +myCalendarThree.book(50, 60); // 返回 1 ,第二个日程安排可以预订并且不存在相交,所以最大 k 次预订是 1 次预订。
    +myCalendarThree.book(10, 40); // 返回 2 ,第三个日程安排 [10, 40) 与第一个日程安排相交,所以最大 k 次预订是 2 次预订。
    +myCalendarThree.book(5, 15); // 返回 3 ,剩下的日程安排的最大 k 次预订是 3 次预订。
    +myCalendarThree.book(5, 10); // 返回 3
    +myCalendarThree.book(25, 55); // 返回 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= start < end <= 109
    • +
    • 每个测试用例,调用 book 函数最多不超过 400
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0733.leetcode733 Flood Fill-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0733.leetcode733 Flood Fill-zh.md" new file mode 100644 index 00000000..eace83a0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0733.leetcode733 Flood Fill-zh.md" @@ -0,0 +1,68 @@ +# [733. 图像渲染](https://leetcode-cn.com/problems/flood-fill) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0733.Flood%20Fill/README_EN.md) + +## 题目描述 + + + +

    有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。

    + +

    给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。

    + +

    为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。

    + +

    最后返回经过上色渲染后的图像。

    + +

    示例 1:

    + +
    +输入: 
    +image = [[1,1,1],[1,1,0],[1,0,1]]
    +sr = 1, sc = 1, newColor = 2
    +输出: [[2,2,2],[2,2,0],[2,0,1]]
    +解析: 
    +在图像的正中间,(坐标(sr,sc)=(1,1)),
    +在路径上所有符合条件的像素点的颜色都被更改成2。
    +注意,右下角的像素没有更改为2,
    +因为它不是在上下左右四个方向上与初始点相连的像素点。
    +
    + +

    注意:

    + +
      +
    • image 和 image[0] 的长度在范围 [1, 50] 内。
    • +
    • 给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length
    • +
    • image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0734.leetcode734 Sentence Similarity-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0734.leetcode734 Sentence Similarity-zh.md" new file mode 100644 index 00000000..1f44664b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0734.leetcode734 Sentence Similarity-zh.md" @@ -0,0 +1,90 @@ +# [734. 句子相似性](https://leetcode-cn.com/problems/sentence-similarity) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0734.Sentence%20Similarity/README_EN.md) + +## 题目描述 + + + +

    给定两个句子 words1, words2 (每个用字符串数组表示),和一个相似单词对的列表 pairs ,判断是否两个句子是相似的。

    + +

    例如,当相似单词对是 pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]的时候,"great acting skills" 和 "fine drama talent" 是相似的。

    + +

    注意相似关系是不具有传递性的。例如,如果 "great" 和 "fine" 是相似的,"fine" 和 "good" 是相似的,但是 "great" 和 "good" 未必是相似的。

    + +

    但是,相似关系是具有对称性的。例如,"great" 和 "fine" 是相似的相当于 "fine" 和 "great" 是相似的。

    + +

    而且,一个单词总是与其自身相似。例如,句子 words1 = ["great"], words2 = ["great"], pairs = [] 是相似的,尽管没有输入特定的相似单词对。

    + +

    最后,句子只会在具有相同单词个数的前提下才会相似。所以一个句子 words1 = ["great"] 永远不可能和句子 words2 = ["doubleplus","good"] 相似。

    + +

     

    + +

    注:

    + +
      +
    • words1 and words2 的长度不会超过 1000
    • +
    • pairs 的长度不会超过 2000
    • +
    • 每个pairs[i] 的长度为 2
    • +
    • 每个 words[i] 和 pairs[i][j] 的长度范围为 [1, 20]
    • +
    + +

     

    + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +class Solution: + def areSentencesSimilar(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool: + if len(sentence1) != len(sentence2): + return False + pairs = {(word1, word2) for word1, word2 in similarPairs} + for i in range(len(sentence1)): + similar = (sentence1[i], sentence2[i]) in pairs or (sentence2[i], sentence1[i]) in pairs or sentence1[i] == sentence2[i] + if not similar: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean areSentencesSimilar(String[] sentence1, String[] sentence2, List> similarPairs) { + if (sentence1.length != sentence2.length) { + return false; + } + Set pairs = new HashSet<>(); + for (List pair : similarPairs) { + pairs.add(pair.get(0) + "." + pair.get(1)); + } + for (int i = 0; i < sentence1.length; ++i) { + boolean similar = pairs.contains(sentence1[i] + "." + sentence2[i]) || pairs.contains(sentence2[i] + "." + sentence1[i]) || sentence1[i].equals(sentence2[i]); + if (!similar) { + return false; + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0735.leetcode735 Asteroid Collision-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0735.leetcode735 Asteroid Collision-zh.md" new file mode 100644 index 00000000..97bafd66 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0735.leetcode735 Asteroid Collision-zh.md" @@ -0,0 +1,84 @@ +# [735. 行星碰撞](https://leetcode-cn.com/problems/asteroid-collision) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0735.Asteroid%20Collision/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 asteroids,表示在同一行的行星。

    + +

    对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动)。每一颗行星以相同的速度移动。

    + +

    找出碰撞后剩下的所有行星。碰撞规则:两个行星相互碰撞,较小的行星会爆炸。如果两颗行星大小相同,则两颗行星都会爆炸。两颗移动方向相同的行星,永远不会发生碰撞。

    + +

     

    + +

    示例 1:

    + +
    +输入:asteroids = [5,10,-5]
    +输出:[5,10]
    +解释:10 和 -5 碰撞后只剩下 10 。 5 和 10 永远不会发生碰撞。
    + +

    示例 2:

    + +
    +输入:asteroids = [8,-8]
    +输出:[]
    +解释:8 和 -8 碰撞后,两者都发生爆炸。
    + +

    示例 3:

    + +
    +输入:asteroids = [10,2,-5]
    +输出:[10]
    +解释:2 和 -5 发生碰撞后剩下 -5 。10 和 -5 发生碰撞后剩下 10 。
    + +

    示例 4:

    + +
    +输入:asteroids = [-2,-1,1,2]
    +输出:[-2,-1,1,2]
    +解释-2 和 -1 向左移动,而 1 和 2 向右移动。 由于移动方向相同的行星不会发生碰撞,所以最终没有行星发生碰撞。 
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= asteroids.length <= 104
    • +
    • -1000 <= asteroids[i] <= 1000
    • +
    • asteroids[i] != 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0736.leetcode736 Parse Lisp Expression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0736.leetcode736 Parse Lisp Expression-zh.md" new file mode 100644 index 00000000..14748034 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0736.leetcode736 Parse Lisp Expression-zh.md" @@ -0,0 +1,104 @@ +# [736. Lisp 语法解析](https://leetcode-cn.com/problems/parse-lisp-expression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0736.Parse%20Lisp%20Expression/README_EN.md) + +## 题目描述 + + + +

    给定一个类似 Lisp 语句的表达式 expression,求出其计算结果。

    + +

    表达式语法如下所示:

    + +
      +
    • 表达式可以为整数,let 语法,add 语法,mult 语法,或赋值的变量。表达式的结果总是一个整数。
    • +
    • (整数可以是正整数、负整数、0)
    • +
    • let 语法表示为 (let v1 e1 v2 e2 ... vn en expr), 其中 let语法总是以字符串 "let"来表示,接下来会跟随一个或多个交替变量或表达式,也就是说,第一个变量 v1被分配为表达式 e1 的值,第二个变量 v2 被分配为表达式 e2 的值,以此类推;最终 let 语法的值为 expr表达式的值。
    • +
    • add 语法表示为 (add e1 e2),其中 add 语法总是以字符串 "add"来表示,该语法总是有两个表达式e1e2, 该语法的最终结果是 e1 表达式的值与 e2 表达式的值之
    • +
    • mult 语法表示为 (mult e1 e2) ,其中 mult 语法总是以字符串"mult"表示, 该语法总是有两个表达式 e1e2,该语法的最终结果是 e1 表达式的值与 e2 表达式的值之
    • +
    • 在该题目中,变量的命名以小写字符开始,之后跟随0个或多个小写字符或数字。为了方便,"add","let","mult"会被定义为"关键字",不会在表达式的变量命名中出现。
    • +
    • 最后,要说一下作用域的概念。计算变量名所对应的表达式时,在计算上下文中,首先检查最内层作用域(按括号计),然后按顺序依次检查外部作用域。我们将保证每一个测试的表达式都是合法的。有关作用域的更多详细信息,请参阅示例。
    • +
    + +

     

    + +

    示例:

    + +
    输入: (add 1 2)
    +输出: 3
    +
    +输入: (mult 3 (add 2 3))
    +输出: 15
    +
    +输入: (let x 2 (mult x 5))
    +输出: 10
    +
    +输入: (let x 2 (mult x (let x 3 y 4 (add x y))))
    +输出: 14
    +解释: 
    +表达式 (add x y), 在获取 x 值时, 我们应当由最内层依次向外计算, 首先遇到了 x=3, 所以此处的 x 值是 3.
    +
    +
    +输入: (let x 3 x 2 x)
    +输出: 2
    +解释: let 语句中的赋值运算按顺序处理即可
    +
    +输入: (let x 1 y 2 x (add x y) (add x y))
    +输出: 5
    +解释: 
    +第一个 (add x y) 计算结果是 3,并且将此值赋给了 x 。
    +第二个 (add x y) 计算结果就是 3+2 = 5 。
    +
    +输入: (let x 2 (add (let x 3 (let x 4 x)) x))
    +输出: 6
    +解释: 
    +(let x 4 x) 中的 x 的作用域仅在()之内。所以最终做加法操作时,x 的值是 2 。
    +
    +输入: (let a1 3 b2 (add a1 1) b2) 
    +输出: 4
    +解释: 
    +变量命名时可以在第一个小写字母后跟随数字.
    +
    + +

     

    + +

    注意:

    + +
      +
    • 我们给定的 expression 表达式都是格式化后的:表达式前后没有多余的空格,表达式的不同部分(关键字、变量、表达式)之间仅使用一个空格分割,并且在相邻括号之间也没有空格。我们给定的表达式均为合法的且最终结果为整数。
    • +
    • 我们给定的表达式长度最多为 2000 (表达式也不会为空,因为那不是一个合法的表达式)。
    • +
    • 最终的结果和中间的计算结果都将是一个 32 位整数。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0737.leetcode737 Sentence Similarity II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0737.leetcode737 Sentence Similarity II-zh.md" new file mode 100644 index 00000000..b68894f9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0737.leetcode737 Sentence Similarity II-zh.md" @@ -0,0 +1,59 @@ +# [737. 句子相似性 II](https://leetcode-cn.com/problems/sentence-similarity-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0737.Sentence%20Similarity%20II/README_EN.md) + +## 题目描述 + + + +

    给定两个句子 words1, words2 (每个用字符串数组表示),和一个相似单词对的列表 pairs ,判断是否两个句子是相似的。

    + +

    例如,当相似单词对是 pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]的时候,words1 = ["great", "acting", "skills"] 和 words2 = ["fine", "drama", "talent"] 是相似的。

    + +

    注意相似关系是 具有 传递性的。例如,如果 "great" 和 "fine" 是相似的,"fine" 和 "good" 是相似的,则 "great" 和 "good" 是相似的

    + +

    而且,相似关系是具有对称性的。例如,"great" 和 "fine" 是相似的相当于 "fine" 和 "great" 是相似的。

    + +

    并且,一个单词总是与其自身相似。例如,句子 words1 = ["great"], words2 = ["great"], pairs = [] 是相似的,尽管没有输入特定的相似单词对。

    + +

    最后,句子只会在具有相同单词个数的前提下才会相似。所以一个句子 words1 = ["great"] 永远不可能和句子 words2 = ["doubleplus","good"] 相似。

    + +

    注:

    + +
      +
    • words1 and words2 的长度不会超过 1000
    • +
    • pairs 的长度不会超过 2000
    • +
    • 每个pairs[i] 的长度为 2
    • +
    • 每个 words[i] 和 pairs[i][j] 的长度范围为 [1, 20]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0738.leetcode738 Monotone Increasing Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0738.leetcode738 Monotone Increasing Digits-zh.md" new file mode 100644 index 00000000..0605a78d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0738.leetcode738 Monotone Increasing Digits-zh.md" @@ -0,0 +1,62 @@ +# [738. 单调递增的数字](https://leetcode-cn.com/problems/monotone-increasing-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0738.Monotone%20Increasing%20Digits/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。

    + +

    (当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。)

    + +

    示例 1:

    + +
    输入: N = 10
    +输出: 9
    +
    + +

    示例 2:

    + +
    输入: N = 1234
    +输出: 1234
    +
    + +

    示例 3:

    + +
    输入: N = 332
    +输出: 299
    +
    + +

    说明: N 是在 [0, 10^9] 范围内的一个整数。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0739.leetcode739 Daily Temperatures-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0739.leetcode739 Daily Temperatures-zh.md" new file mode 100644 index 00000000..c9e76596 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0739.leetcode739 Daily Temperatures-zh.md" @@ -0,0 +1,120 @@ +# [739. 每日温度](https://leetcode-cn.com/problems/daily-temperatures) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0739.Daily%20Temperatures/README_EN.md) + +## 题目描述 + + + +

    请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。

    + +

    例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

    + +

    提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

    + + +## 解法 + + + +栈实现,栈存放 T 中元素的的下标 i,结果用数组 res 存储。 + +遍历 T,遍历到 `T[i]` 时: + +- 若栈不为空,并且栈顶元素小于 `T[i]` 时,弹出栈顶元素 j,并且 `res[j]` 赋值为 `i - j`。 +- 然后将 i 压入栈中。 + +最后返回结果数组 res 即可。 + + + +### **Python3** + + + +```python +class Solution: + def dailyTemperatures(self, T: List[int]) -> List[int]: + n = len(T) + res = [0 for _ in range(n)] + s = [] + for i in range(n): + while s and T[s[-1]] < T[i]: + j = s.pop() + res[j] = i - j + s.append(i) + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] dailyTemperatures(int[] T) { + int n = T.length; + int[] res = new int[n]; + Deque s = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + while (!s.isEmpty() && T[s.peek()] < T[i]) { + int j = s.pop(); + res[j] = i - j; + } + s.push(i); + } + return res; + } +} +``` + +### **C++** + + + +```cpp +class Solution { +public: + vector dailyTemperatures(vector& T) { + int n = T.size(); + vector ans(n); + stack s; + for(int i = 0; i < n; ++i) { + while(!s.empty() && T[s.top()] < T[i]) { + int pre = s.top(); + s.pop(); + ans[pre] = i - pre; + } + s.push(i); + } + return ans; + } +}; +``` + +### **Go** + +```go +func dailyTemperatures(T []int) []int { + n := len(T) + res := make([]int, n) + stack := make([]int, 0) + for i, v := range T { + for len(stack) != 0 && T[stack[len(stack)-1]] < v { + j := stack[len(stack)-1] + stack = stack[:len(stack)-1] + res[j] = i - j + } + stack = append(stack, i) + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0740.leetcode740 Delete and Earn-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0740.leetcode740 Delete and Earn-zh.md" new file mode 100644 index 00000000..a88b5db2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0740.leetcode740 Delete and Earn-zh.md" @@ -0,0 +1,182 @@ +# [740. 删除与获得点数](https://leetcode-cn.com/problems/delete-and-earn) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0740.Delete%20and%20Earn/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums ,你可以对它进行一些操作。

    + +

    每次操作中,选择任意一个 nums[i] ,删除它并获得 nums[i] 的点数。之后,你必须删除每个等于 nums[i] - 1 或 nums[i] + 1 的元素。

    + +

    开始你拥有 0 个点数。返回你能通过这些操作获得的最大点数。

    + +

    示例 1:

    + +
    +输入: nums = [3, 4, 2]
    +输出: 6
    +解释:
    +删除 4 来获得 4 个点数,因此 3 也被删除。
    +之后,删除 2 来获得 2 个点数。总共获得 6 个点数。
    +
    + +

    示例 2:

    + +
    +输入: nums = [2, 2, 3, 3, 3, 4]
    +输出: 9
    +解释:
    +删除 3 来获得 3 个点数,接着要删除两个 2 和 4 。
    +之后,再次删除 3 获得 3 个点数,再次删除 3 获得 3 个点数。
    +总共获得 9 个点数。
    +
    + +

    注意:

    + +
      +
    • nums的长度最大为20000
    • +
    • 每个整数nums[i]的大小都在[1, 10000]范围内。
    • +
    + + +## 解法 + + + +核心思路: **一个数字要么不选,要么全选** + +首先计算出每个数字的总和 sums,并维护两个 dp 数组:select 和 nonSelect + +- `sums[i]` 代表值为 i 的元素总和 +- `select[i]` 代表如果选数字 i,从 0 处理到 i 的最大和 +- `nonSelect[i]` 代表如果不选数字 i,从 0 处理到 i 的最大和 + +那么我们有以下逻辑: + +- 如果选 i,那么 i-1 肯定不能选; +- 如果不选 i,那么 i-1 选不选都可以,因此我们选择其中较大的选法 + +```java +select[i] = nonSelect[i-1] + sums[i]; +nonSelect[i] = Math.max(select[i-1], nonSelect[i-1]); +``` + + + +### **Python3** + + + +```python +class Solution: + def deleteAndEarn(self, nums: List[int]) -> int: + mx = float('-inf') + for num in nums: + mx = max(mx, num) + total = [0] * (mx + 1) + for num in nums: + total[num] += num + first = total[0] + second = max(total[0], total[1]) + for i in range(2, mx + 1): + cur = max(first + total[i], second) + first = second + second = cur + return second +``` + +### **Java** + + + +```java +class Solution { + public int deleteAndEarn(int[] nums) { + if (nums.length == 0) { + return 0; + } + + int[] sums = new int[10010]; + int[] select = new int[10010]; + int[] nonSelect = new int[10010]; + + int maxV = 0; + for (int x : nums) { + sums[x] += x; + maxV = Math.max(maxV, x); + } + + for (int i = 1; i <= maxV; i++) { + select[i] = nonSelect[i - 1] + sums[i]; + nonSelect[i] = Math.max(select[i - 1], nonSelect[i - 1]); + } + return Math.max(select[maxV], nonSelect[maxV]); + } +} +``` + +### **Go** + +```go +func deleteAndEarn(nums []int) int { + + max := func(x, y int) int { + if x > y { + return x + } + return y + } + + mx := math.MinInt32 + for _, num := range nums { + mx = max(mx, num) + } + total := make([]int, mx+1) + for _, num := range nums { + total[num] += num + } + first := total[0] + second := max(total[0], total[1]) + for i := 2; i <= mx; i++ { + cur := max(first+total[i], second) + first = second + second = cur + } + return second +} +``` + +### **C++** + +```cpp +class Solution { +public: + int deleteAndEarn(vector& nums) { + vector vals(10010); + for (int& num : nums) { + vals[num] += num; + } + return rob(vals); + } + + int rob(vector& nums) { + int a = 0, b = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0741.leetcode741 Cherry Pickup-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0741.leetcode741 Cherry Pickup-zh.md" new file mode 100644 index 00000000..741bc75c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0741.leetcode741 Cherry Pickup-zh.md" @@ -0,0 +1,78 @@ +# [741. 摘樱桃](https://leetcode-cn.com/problems/cherry-pickup) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0741.Cherry%20Pickup/README_EN.md) + +## 题目描述 + + + +

    一个N x N的网格(grid) 代表了一块樱桃地,每个格子由以下三种数字的一种来表示:

    + +
      +
    • 0 表示这个格子是空的,所以你可以穿过它。
    • +
    • 1 表示这个格子里装着一个樱桃,你可以摘到樱桃然后穿过它。
    • +
    • -1 表示这个格子里有荆棘,挡着你的路。
    • +
    + +

    你的任务是在遵守下列规则的情况下,尽可能的摘到最多樱桃:

    + +
      +
    • 从位置 (0, 0) 出发,最后到达 (N-1, N-1) ,只能向下或向右走,并且只能穿越有效的格子(即只可以穿过值为0或者1的格子);
    • +
    • 当到达 (N-1, N-1) 后,你要继续走,直到返回到 (0, 0) ,只能向上或向左走,并且只能穿越有效的格子;
    • +
    • 当你经过一个格子且这个格子包含一个樱桃时,你将摘到樱桃并且这个格子会变成空的(值变为0);
    • +
    • 如果在 (0, 0) 和 (N-1, N-1) 之间不存在一条可经过的路径,则没有任何一个樱桃能被摘到。
    • +
    + +

    示例 1:

    + +
    +输入: grid =
    +[[0, 1, -1],
    + [1, 0, -1],
    + [1, 1,  1]]
    +输出: 5
    +解释: 
    +玩家从(0,0)点出发,经过了向下走,向下走,向右走,向右走,到达了点(2, 2)。
    +在这趟单程中,总共摘到了4颗樱桃,矩阵变成了[[0,1,-1],[0,0,-1],[0,0,0]]。
    +接着,这名玩家向左走,向上走,向上走,向左走,返回了起始点,又摘到了1颗樱桃。
    +在旅程中,总共摘到了5颗樱桃,这是可以摘到的最大值了。
    +
    + +

    说明:

    + +
      +
    • grid 是一个 N * N 的二维数组,N的取值范围是1 <= N <= 50
    • +
    • 每一个 grid[i][j] 都是集合 {-1, 0, 1}其中的一个数。
    • +
    • 可以保证起点 grid[0][0] 和终点 grid[N-1][N-1] 的值都不会是 -1。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0742.leetcode742 Closest Leaf in a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0742.leetcode742 Closest Leaf in a Binary Tree-zh.md" new file mode 100644 index 00000000..23033a3b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0742.leetcode742 Closest Leaf in a Binary Tree-zh.md" @@ -0,0 +1,102 @@ +# [742. 二叉树最近的叶节点](https://leetcode-cn.com/problems/closest-leaf-in-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0742.Closest%20Leaf%20in%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个 每个结点的值互不相同 的二叉树,和一个目标值 k,找出树中与目标值 k 最近的叶结点。 

    + +

    这里,与叶结点 最近 表示在二叉树中到达该叶节点需要行进的边数与到达其它叶结点相比最少。而且,当一个结点没有孩子结点时称其为叶结点。

    + +

    在下面的例子中,输入的树以逐行的平铺形式表示。实际上的有根树 root 将以TreeNode对象的形式给出。

    + +

    示例 1:

    + +
    输入:
    +root = [1, 3, 2], k = 1
    +二叉树图示:
    +          1
    +         / \
    +        3   2
    +
    +输出: 2 (或 3)
    +
    +解释: 2 和 3 都是距离目标 1 最近的叶节点。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +root = [1], k = 1
    +输出:1
    +
    +解释: 最近的叶节点是根结点自身。
    +
    + +

     

    + +

    示例 3:

    + +
    输入:
    +root = [1,2,3,4,null,null,null,5,null,6], k = 2
    +二叉树图示:
    +             1
    +            / \
    +           2   3
    +          /
    +         4
    +        /
    +       5
    +      /
    +     6
    +
    +输出:3
    +解释: 值为 3(而不是值为 6)的叶节点是距离结点 2 的最近结点。
    +
    + +

     

    + +

    注:

    + +
      +
    1. root 表示的二叉树最少有 1 个结点且最多有 1000 个结点。
    2. +
    3. 每个结点都有一个唯一的 node.val ,范围为 [1, 1000]
    4. +
    5. 给定的二叉树中有某个结点使得 node.val == k
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0743.leetcode743 Network Delay Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0743.leetcode743 Network Delay Time-zh.md" new file mode 100644 index 00000000..ea0a7540 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0743.leetcode743 Network Delay Time-zh.md" @@ -0,0 +1,83 @@ +# [743. 网络延迟时间](https://leetcode-cn.com/problems/network-delay-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0743.Network%20Delay%20Time/README_EN.md) + +## 题目描述 + + + +

    n 个网络节点,标记为 1 到 n

    + +

    给你一个列表 times,表示信号经过 有向 边的传递时间。 times[i] = (ui, vi, wi),其中 ui 是源节点,vi 是目标节点, wi 是一个信号从源节点传递到目标节点的时间。

    + +

    现在,从某个节点 K 发出一个信号。需要多久才能使所有节点都收到信号?如果不能使所有节点收到信号,返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:times = [[1,2,1]], n = 2, k = 1
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:times = [[1,2,1]], n = 2, k = 2
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= n <= 100
    • +
    • 1 <= times.length <= 6000
    • +
    • times[i].length == 3
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 0 <= wi <= 100
    • +
    • 所有 (ui, vi) 对都 互不相同(即,不含重复边)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0744.leetcode744 Find Smallest Letter Greater Than Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0744.leetcode744 Find Smallest Letter Greater Than Target-zh.md" new file mode 100644 index 00000000..a4155028 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0744.leetcode744 Find Smallest Letter Greater Than Target-zh.md" @@ -0,0 +1,167 @@ +# [744. 寻找比目标字母大的最小字母](https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0744.Find%20Smallest%20Letter%20Greater%20Than%20Target/README_EN.md) + +## 题目描述 + + + +

    给你一个排序后的字符列表 letters ,列表中只包含小写英文字母。另给出一个目标字母 target,请你寻找在这一有序列表里比目标字母大的最小字母。

    + +

    在比较时,字母是依序循环出现的。举个例子:

    + +
      +
    • 如果目标字母 target = 'z' 并且字符列表为 letters = ['a', 'b'],则答案返回 'a'
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +letters = ["c", "f", "j"]
    +target = "a"
    +输出: "c"
    +
    +输入:
    +letters = ["c", "f", "j"]
    +target = "c"
    +输出: "f"
    +
    +输入:
    +letters = ["c", "f", "j"]
    +target = "d"
    +输出: "f"
    +
    +输入:
    +letters = ["c", "f", "j"]
    +target = "g"
    +输出: "j"
    +
    +输入:
    +letters = ["c", "f", "j"]
    +target = "j"
    +输出: "c"
    +
    +输入:
    +letters = ["c", "f", "j"]
    +target = "k"
    +输出: "c"
    +
    + +

     

    + +

    提示:

    + +
      +
    1. letters长度范围在[2, 10000]区间内。
    2. +
    3. letters 仅由小写字母组成,最少包含两个不同的字母。
    4. +
    5. 目标字母target 是一个小写字母。
    6. +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def nextGreatestLetter(self, letters: List[str], target: str) -> str: + left, right = 0, len(letters) + while left < right: + mid = (left + right) >> 1 + if ord(letters[mid]) > ord(target): + right = mid + else: + left = mid + 1 + return letters[left % len(letters)] +``` + +### **Java** + + + +```java +class Solution { + public char nextGreatestLetter(char[] letters, char target) { + int left = 0, right = letters.length; + while (left < right) { + int mid = (left + right) >> 1; + if (letters[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % letters.length]; + } +} +``` + +### **TypeScript** + +```ts +function nextGreatestLetter(letters: string[], target: string): string { + let left = 0, right = letters.length; + let x = target.charCodeAt(0); + while (left < right) { + let mid = (left + right) >> 1; + if (x < letters[mid].charCodeAt(0)) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % letters.length]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + char nextGreatestLetter(vector& letters, char target) { + int left = 0, right = letters.size(); + while (left < right) { + int mid = left + right >> 1; + if (letters[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % letters.size()]; + } +}; +``` + +### **Go** + +```go +func nextGreatestLetter(letters []byte, target byte) byte { + left, right := 0, len(letters) + for left < right { + mid := (left + right) >> 1 + if letters[mid] > target { + right = mid + } else { + left = mid + 1 + } + } + return letters[left%len(letters)] +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0745.leetcode745 Prefix and Suffix Search-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0745.leetcode745 Prefix and Suffix Search-zh.md" new file mode 100644 index 00000000..4e659eef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0745.leetcode745 Prefix and Suffix Search-zh.md" @@ -0,0 +1,61 @@ +# [745. 前缀和后缀搜索](https://leetcode-cn.com/problems/prefix-and-suffix-search) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0745.Prefix%20and%20Suffix%20Search/README_EN.md) + +## 题目描述 + + + +

    给定多个 wordswords[i] 的权重为 i 。

    + +

    设计一个类 WordFilter 实现函数WordFilter.f(String prefix, String suffix)。这个函数将返回具有前缀 prefix 和后缀suffix 的词的最大权重。如果没有这样的词,返回 -1。

    + +

    例子:

    + +
    +输入:
    +WordFilter(["apple"])
    +WordFilter.f("a", "e") // 返回 0
    +WordFilter.f("b", "") // 返回 -1
    +
    + +

    注意:

    + +
      +
    1. words的长度在[1, 15000]之间。
    2. +
    3. 对于每个测试用例,最多会有words.length次对WordFilter.f的调用。
    4. +
    5. words[i]的长度在[1, 10]之间。
    6. +
    7. prefix, suffix的长度在[0, 10]之前。
    8. +
    9. words[i]prefix, suffix只包含小写字母。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0746.leetcode746 Min Cost Climbing Stairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0746.leetcode746 Min Cost Climbing Stairs-zh.md" new file mode 100644 index 00000000..dab4de20 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0746.leetcode746 Min Cost Climbing Stairs-zh.md" @@ -0,0 +1,134 @@ +# [746. 使用最小花费爬楼梯](https://leetcode-cn.com/problems/min-cost-climbing-stairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0746.Min%20Cost%20Climbing%20Stairs/README_EN.md) + +## 题目描述 + + + +

    数组的每个下标作为一个阶梯,第 i 个阶梯对应着一个非负数的体力花费值 cost[i](下标从 0 开始)。

    + +

    每当你爬上一个阶梯你都要花费对应的体力值,一旦支付了相应的体力值,你就可以选择向上爬一个阶梯或者爬两个阶梯。

    + +

    请你找出达到楼层顶部的最低花费。在开始时,你可以选择从下标为 0 或 1 的元素作为初始阶梯。

    + +

     

    + +

    示例 1:

    + +
    +输入:cost = [10, 15, 20]
    +输出:15
    +解释:最低花费是从 cost[1] 开始,然后走两步即可到阶梯顶,一共花费 15 。
    +
    + +

     示例 2:

    + +
    +输入:cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
    +输出:6
    +解释:最低花费方式是从 cost[0] 开始,逐个经过那些 1 ,跳过 cost[3] ,一共花费 6 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • cost 的长度范围是 [2, 1000]
    • +
    • cost[i] 将会是一个整型数据,范围为 [0, 999]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + a = b = 0 + for i in range(1, len(cost)): + a, b = b, min(a + cost[i - 1], b + cost[i]) + return b +``` + +### **Java** + + + +```java +class Solution { + public int minCostClimbingStairs(int[] cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.length; ++i) { + int c = Math.min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; + } + return b; + } +} +``` + +### **TypeScript** + +```ts +function minCostClimbingStairs(cost: number[]): number { + let a = 0, b = 0; + for (let i = 1; i < cost.length; ++i) { + [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + } + return b; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.size(); ++i) { + int c = min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; + } + return b; + } +}; +``` + +### **Go** + +```go +func minCostClimbingStairs(cost []int) int { + a, b := 0, 0 + for i := 1; i < len(cost); i++ { + a, b = b, min(a+cost[i-1], b+cost[i]) + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0747.leetcode747 Largest Number At Least Twice of Others-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0747.leetcode747 Largest Number At Least Twice of Others-zh.md" new file mode 100644 index 00000000..eecf8fff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0747.leetcode747 Largest Number At Least Twice of Others-zh.md" @@ -0,0 +1,70 @@ +# [747. 至少是其他数字两倍的最大数](https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0747.Largest%20Number%20At%20Least%20Twice%20of%20Others/README_EN.md) + +## 题目描述 + + + +

    在一个给定的数组nums中,总是存在一个最大元素 。

    + +

    查找数组中的最大元素是否至少是数组中每个其他数字的两倍。

    + +

    如果是,则返回最大元素的索引,否则返回-1。

    + +

    示例 1:

    + +
    输入: nums = [3, 6, 1, 0]
    +输出: 1
    +解释: 6是最大的整数, 对于数组中的其他整数,
    +6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.
    +
    + +

     

    + +

    示例 2:

    + +
    输入: nums = [1, 2, 3, 4]
    +输出: -1
    +解释: 4没有超过3的两倍大, 所以我们返回 -1.
    +
    + +

     

    + +

    提示:

    + +
      +
    1. nums 的长度范围在[1, 50].
    2. +
    3. 每个 nums[i] 的整数范围在 [0, 100].
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0748.leetcode748 Shortest Completing Word-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0748.leetcode748 Shortest Completing Word-zh.md" new file mode 100644 index 00000000..46ad7df0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0748.leetcode748 Shortest Completing Word-zh.md" @@ -0,0 +1,104 @@ +# [748. 最短补全词](https://leetcode-cn.com/problems/shortest-completing-word) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0748.Shortest%20Completing%20Word/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串牌照 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中的 最短补全词

    + +

    如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为 补全词 。在所有完整词中,最短的单词我们称之为 最短补全词

    + +

    单词在匹配牌照中的字母时要:

    + +
      +
    • 忽略牌照中的数字和空格。
    • +
    • 不区分大小写,比如牌照中的 "P" 依然可以匹配单词中的 "p" 字母。
    • +
    • 如果某个字母在牌照中出现不止一次,那么该字母在补全词中的出现次数应当一致或者更多。
    • +
    + +

    例如:licensePlate = "aBc 12c",那么它由字母 'a''b' (忽略大写)和两个 'c' 。可能的 补全词"abccdef""caaacab" 以及 "cbca"

    + +

    题目数据保证一定存在一个最短补全词。当有多个单词都符合最短补全词的匹配条件时取单词列表中最靠前的一个。

    + +

     

    + +

    示例 1:

    + +
    输入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
    +输出:"steps"
    +说明:最短补全词应该包括 "s"、"p"、"s" 以及 "t"。在匹配过程中我们忽略牌照中的大小写。
    +"step" 包含 "t"、"p",但只包含一个 "s",所以它不符合条件。
    +"steps" 包含 "t"、"p" 和两个 "s"。
    +"stripe" 缺一个 "s"。
    +"stepple" 缺一个 "s"。
    +因此,"steps" 是唯一一个包含所有字母的单词,也是本样例的答案。
    + +

    示例 2:

    + +
    输入:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
    +输出:"pest"
    +说明:存在 3 个包含字母 "s" 且有着最短长度的补全词,"pest"、"stew"、和 "show" 三者长度相同,但我们返回最先出现的补全词 "pest" 。
    +
    + +

    示例 3:

    + +
    输入:licensePlate = "Ah71752", words = ["suggest","letter","of","husband","easy","education","drug","prevent","writer","old"]
    +输出:"husband"
    +
    + +

    示例 4:

    + +
    输入:licensePlate = "OgEu755", words = ["enough","these","play","wide","wonder","box","arrive","money","tax","thus"]
    +输出:"enough"
    +
    + +

    示例 5:

    + +
    输入:licensePlate = "iMSlpe4", words = ["claim","consumer","student","camera","public","never","wonder","simple","thought","use"]
    +输出:"simple"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= licensePlate.length <= 7
    • +
    • licensePlate 由数字、大小写字母或空格 ' ' 组成
    • +
    • 1 <= words.length <= 1000
    • +
    • 1 <= words[i].length <= 15
    • +
    • words[i] 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0749.leetcode749 Contain Virus-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0749.leetcode749 Contain Virus-zh.md" new file mode 100644 index 00000000..7885b9d0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0749.leetcode749 Contain Virus-zh.md" @@ -0,0 +1,102 @@ +# [749. 隔离病毒](https://leetcode-cn.com/problems/contain-virus) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0749.Contain%20Virus/README_EN.md) + +## 题目描述 + + + +

    病毒扩散得很快,现在你的任务是尽可能地通过安装防火墙来隔离病毒。

    + +

    假设世界由二维矩阵组成,0 表示该区域未感染病毒,而 1 表示该区域已感染病毒。可以在任意 2 个四方向相邻单元之间的共享边界上安装一个防火墙(并且只有一个防火墙)。

    + +

    每天晚上,病毒会从被感染区域向相邻未感染区域扩散,除非被防火墙隔离。现由于资源有限,每天你只能安装一系列防火墙来隔离其中一个被病毒感染的区域(一个区域或连续的一片区域),且该感染区域对未感染区域的威胁最大且保证唯一。

    + +

    你需要努力使得最后有部分区域不被病毒感染,如果可以成功,那么返回需要使用的防火墙个数; 如果无法实现,则返回在世界被病毒全部感染时已安装的防火墙个数。

    + +

     

    + +

    示例 1:

    + +
    输入: grid = 
    +[[0,1,0,0,0,0,0,1],
    + [0,1,0,0,0,0,0,1],
    + [0,0,0,0,0,0,0,1],
    + [0,0,0,0,0,0,0,0]]
    +输出: 10
    +说明:
    +一共有两块被病毒感染的区域: 从左往右第一块需要 5 个防火墙,同时若该区域不隔离,晚上将感染 5 个未感染区域(即被威胁的未感染区域个数为 5);
    +第二块需要 4 个防火墙,同理被威胁的未感染区域个数是 4。因此,第一天先隔离左边的感染区域,经过一晚后,病毒传播后世界如下:
    +[[0,1,0,0,0,0,1,1],
    + [0,1,0,0,0,0,1,1],
    + [0,0,0,0,0,0,1,1],
    + [0,0,0,0,0,0,0,1]]
    +第二题,只剩下一块未隔离的被感染的连续区域,此时需要安装 5 个防火墙,且安装完毕后病毒隔离任务完成。
    +
    + +

    示例 2:

    + +
    输入: grid = 
    +[[1,1,1],
    + [1,0,1],
    + [1,1,1]]
    +输出: 4
    +说明: 
    +此时只需要安装 4 面防火墙,就有一小区域可以幸存,不被病毒感染。
    +注意不需要在世界边界建立防火墙。
    + +

     

    + +

    示例 3:

    + +
    输入: grid = 
    +[[1,1,1,0,0,0,0,0,0],
    + [1,0,1,0,1,1,1,1,1],
    + [1,1,1,0,0,0,0,0,0]]
    +输出: 13
    +说明: 
    +在隔离右边感染区域后,隔离左边病毒区域只需要 2 个防火墙了。
    +
    + +

     

    + +

    说明:

    + +
      +
    1. grid 的行数和列数范围是 [1, 50]。
    2. +
    3.  grid[i][j] 只包含 0 或 1 。
    4. +
    5. 题目保证每次选取感染区域进行隔离时,一定存在唯一一个对未感染区域的威胁最大的区域。
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0750.leetcode750 Number Of Corner Rectangles-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0750.leetcode750 Number Of Corner Rectangles-zh.md" new file mode 100644 index 00000000..535874e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0750.leetcode750 Number Of Corner Rectangles-zh.md" @@ -0,0 +1,85 @@ +# [750. 角矩形的数量](https://leetcode-cn.com/problems/number-of-corner-rectangles) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0750.Number%20Of%20Corner%20Rectangles/README_EN.md) + +## 题目描述 + + + +

    给定一个只包含 0 和 1 的网格,找出其中角矩形的数量。

    + +

    一个「角矩形」是由四个不同的在网格上的 1 形成的轴对称的矩形。注意只有角的位置才需要为 1。并且,4 个 1 需要是不同的。

    + +

     

    + +

    示例 1:

    + +
    输入:grid = 
    +[[1, 0, 0, 1, 0],
    + [0, 0, 1, 0, 1],
    + [0, 0, 0, 1, 0],
    + [1, 0, 1, 0, 1]]
    +输出:1
    +解释:只有一个角矩形,角的位置为 grid[1][2], grid[1][4], grid[3][2], grid[3][4]。
    +
    + +

    示例 2:

    + +
    输入:grid = 
    +[[1, 1, 1],
    + [1, 1, 1],
    + [1, 1, 1]]
    +输出:9
    +解释:这里有 4 个 2x2 的矩形,4 个 2x3 和 3x2 的矩形和 1 个 3x3 的矩形。
    +
    + +

    示例 3:

    + +
    输入:grid = 
    +[[1, 1, 1, 1]]
    +输出:0
    +解释:矩形必须有 4 个不同的角。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 网格 grid 中行和列的数目范围为 [1, 200]
    2. +
    3. 每个网格 grid[i][j] 中的值不是 0 就是 1
    4. +
    5. 网格中 1 的个数不会超过 6000
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0751.leetcode751 IP to CIDR-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0751.leetcode751 IP to CIDR-zh.md" new file mode 100644 index 00000000..b5850618 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0751.leetcode751 IP to CIDR-zh.md" @@ -0,0 +1,90 @@ +# [751. IP 到 CIDR](https://leetcode-cn.com/problems/ip-to-cidr) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0751.IP%20to%20CIDR/README_EN.md) + +## 题目描述 + + + +

    给定一个起始 IP 地址 ip 和一个我们需要包含的 IP 的数量 n,返回用列表(最小可能的长度)表示的 CIDR块的范围。 

    + +

    CIDR 块是包含 IP 的字符串,后接斜杠和固定长度。例如:“123.45.67.89/20”。固定长度 “20” 表示在特定的范围中公共前缀位的长度。

    + +

    示例 1:

    + +
    输入:ip = "255.0.0.7", n = 10
    +输出:["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"]
    +解释:
    +转换为二进制时,初始IP地址如下所示(为清晰起见添加了空格):
    +255.0.0.7 -> 11111111 00000000 00000000 00000111
    +地址 "255.0.0.7/32" 表示与给定地址有相同的 32 位前缀的所有地址,
    +在这里只有这一个地址。
    +
    +地址 "255.0.0.8/29" 表示与给定地址有相同的 29 位前缀的所有地址:
    +255.0.0.8 -> 11111111 00000000 00000000 00001000
    +有相同的 29 位前缀的地址如下:
    +11111111 00000000 00000000 00001000
    +11111111 00000000 00000000 00001001
    +11111111 00000000 00000000 00001010
    +11111111 00000000 00000000 00001011
    +11111111 00000000 00000000 00001100
    +11111111 00000000 00000000 00001101
    +11111111 00000000 00000000 00001110
    +11111111 00000000 00000000 00001111
    +
    +地址 "255.0.0.16/32" 表示与给定地址有相同的 32 位前缀的所有地址,
    +这里只有 11111111 00000000 00000000 00010000。
    +
    +总之,答案指定了从 255.0.0.7 开始的 10 个 IP 的范围。
    +
    +有一些其他的表示方法,例如:
    +["255.0.0.7/32","255.0.0.8/30", "255.0.0.12/30", "255.0.0.16/32"],
    +但是我们的答案是最短可能的答案。
    +
    +另外请注意以 "255.0.0.7/30" 开始的表示不正确,
    +因为其包括了 255.0.0.4 = 11111111 00000000 00000000 00000100 这样的地址,
    +超出了需要表示的范围。
    +
    + +

     

    + +

    注:

    + +
      +
    1. ip 是有效的 IPv4 地址。
    2. +
    3. 每一个隐含地址 ip + x (其中 x < n) 都是有效的 IPv4 地址。
    4. +
    5. n 为整数,范围为 [1, 1000]
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0752.leetcode752 Open the Lock-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0752.leetcode752 Open the Lock-zh.md" new file mode 100644 index 00000000..864af0a0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0752.leetcode752 Open the Lock-zh.md" @@ -0,0 +1,94 @@ +# [752. 打开转盘锁](https://leetcode-cn.com/problems/open-the-lock) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0752.Open%20the%20Lock/README_EN.md) + +## 题目描述 + + + +

    你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转:例如把 '9' 变为  '0''0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。

    + +

    锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。

    + +

    列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。

    + +

    字符串 target 代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1。

    + +

     

    + +

    示例 1:

    + +
    +输入:deadends = ["0201","0101","0102","1212","2002"], target = "0202"
    +输出:6
    +解释:
    +可能的移动序列为 "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202"。
    +注意 "0000" -> "0001" -> "0002" -> "0102" -> "0202" 这样的序列是不能解锁的,
    +因为当拨动到 "0102" 时这个锁就会被锁定。
    +
    + +

    示例 2:

    + +
    +输入: deadends = ["8888"], target = "0009"
    +输出:1
    +解释:
    +把最后一位反向旋转一次即可 "0000" -> "0009"。
    +
    + +

    示例 3:

    + +
    +输入: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
    +输出:-1
    +解释:
    +无法旋转到目标数字且不被锁定。
    +
    + +

    示例 4:

    + +
    +输入: deadends = ["0000"], target = "8888"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 死亡列表 deadends 的长度范围为 [1, 500]
    2. +
    3. 目标数字 target 不会在 deadends 之中。
    4. +
    5. 每个 deadendstarget 中的字符串的数字会在 10,000 个可能的情况 '0000''9999' 中产生。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0753.leetcode753 Cracking the Safe-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0753.leetcode753 Cracking the Safe-zh.md" new file mode 100644 index 00000000..c2ac0c58 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0753.leetcode753 Cracking the Safe-zh.md" @@ -0,0 +1,76 @@ +# [753. 破解保险箱](https://leetcode-cn.com/problems/cracking-the-safe) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0753.Cracking%20the%20Safe/README_EN.md) + +## 题目描述 + + + +

    有一个需要密码才能打开的保险箱。密码是 n 位数, 密码的每一位是 k 位序列 0, 1, ..., k-1 中的一个 。

    + +

    你可以随意输入密码,保险箱会自动记住最后 n 位输入,如果匹配,则能够打开保险箱。

    + +

    举个例子,假设密码是 "345",你可以输入 "012345" 来打开它,只是你输入了 6 个字符.

    + +

    请返回一个能打开保险箱的最短字符串。

    + +

     

    + +

    示例1:

    + +
    输入: n = 1, k = 2
    +输出: "01"
    +说明: "10"也可以打开保险箱。
    +
    + +

     

    + +

    示例2:

    + +
    输入: n = 2, k = 2
    +输出: "00110"
    +说明: "01100", "10011", "11001" 也能打开保险箱。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. n 的范围是 [1, 4]
    2. +
    3. k 的范围是 [1, 10]
    4. +
    5. k^n 最大可能为 4096
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0754.leetcode754 Reach a Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0754.leetcode754 Reach a Number-zh.md" new file mode 100644 index 00000000..b810e343 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0754.leetcode754 Reach a Number-zh.md" @@ -0,0 +1,71 @@ +# [754. 到达终点数字](https://leetcode-cn.com/problems/reach-a-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0754.Reach%20a%20Number/README_EN.md) + +## 题目描述 + + + +

    在一根无限长的数轴上,你站在0的位置。终点在target的位置。

    + +

    每次你可以选择向左或向右移动。第 n 次移动(从 1 开始),可以走 n 步。

    + +

    返回到达终点需要的最小移动次数。

    + +

    示例 1:

    + +
    +输入: target = 3
    +输出: 2
    +解释:
    +第一次移动,从 0 到 1 。
    +第二次移动,从 1 到 3 。
    +
    + +

    示例 2:

    + +
    +输入: target = 2
    +输出: 3
    +解释:
    +第一次移动,从 0 到 1 。
    +第二次移动,从 1 到 -1 。
    +第三次移动,从 -1 到 2 。
    +
    + +

    注意:

    + +
      +
    • target是在[-10^9, 10^9]范围中的非零整数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0755.leetcode755 Pour Water-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0755.leetcode755 Pour Water-zh.md" new file mode 100644 index 00000000..0b3d3f07 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0755.leetcode755 Pour Water-zh.md" @@ -0,0 +1,176 @@ +# [755. 倒水](https://leetcode-cn.com/problems/pour-water) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0755.Pour%20Water/README_EN.md) + +## 题目描述 + + + +

    给出一个地形高度图, heights[i] 表示该索引处的高度。每个索引的宽度为 1。在 V 个单位的水落在索引 K 处以后,每个索引位置有多少水?

    + +

    水最先会在索引 K 处下降并且落在该索引位置的最高地形或水面之上。然后按如下方式流动:

    + +
      +
    • 如果液滴最终可以通过向左流动而下降,则向左流动。
    • +
    • 否则,如果液滴最终可以通过向右流动而下降,则向右流动。
    • +
    • 否则,在当前的位置上升。
    • +
    • 这里,“最终下降” 的意思是液滴如果按此方向移动的话,最终可以下降到一个较低的水平。而且,“水平”的意思是当前列的地形的高度加上水的高度。 +

       

      + +

      我们可以假定在数组两侧的边界外有无限高的地形。而且,不能有部分水在多于 1 个的网格块上均匀分布 - 每个单位的水必须要位于一个块中。

      +
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:heights = [2,1,1,2,1,2,2], V = 4, K = 3
    +输出:[2,2,2,3,2,2,2]
    +解释:
    +#       #
    +#       #
    +##  # ###
    +#########
    + 0123456    <- 索引
    +
    +第一个水滴降落在索引 K = 3 上:
    +
    +#       #
    +#   w   #
    +##  # ###
    +#########
    + 0123456    
    +
    +当向左或向右移动时,水可以移动到相同或更低的高度。When moving left or right, the water can only move to the same level or a lower level.
    +(从水平上看,意思是该列的地形高度加上水的高度)
    +由于向左移动可以最终下落,因此向左移动。
    +(一个水滴 “下落” 的意思是可以相比之前可以进入更低的高度)
    +
    +#       #
    +#       #
    +## w# ###
    +#########
    + 0123456    
    +
    +由于向左移动不会使其降落,所以停在该位置上。下一个水滴下落:
    +
    +#       #
    +#   w   #
    +## w# ###
    +#########
    + 0123456  
    +
    +
    +由于新水滴向左移动可以最终下落,因此向左移动。
    +注意水滴仍然是优先选择向左移动,
    +尽管可以向右移动(而且向右移动可以下落更快)
    +
    +
    +#       #
    +#  w    #
    +## w# ###
    +#########
    + 0123456  
    +
    +#       #
    +#       #
    +##ww# ###
    +#########
    + 0123456  
    +
    +经过刚才的阶段后,第三个水滴下落。
    +由于向左移动不会最终下落,因此尝试向右移动。
    +由于向右移动可以最终下落,因此向右移动。
    +
    +
    +#       #
    +#   w   #
    +##ww# ###
    +#########
    + 0123456  
    +
    +#       #
    +#       #
    +##ww#w###
    +#########
    + 0123456  
    +
    +最终,第四个水滴下落。
    +由于向左移动不会最终下落,因此尝试向右移动。
    +由于向右移动不会最终下落,因此停在当前位置:
    +
    +#       #
    +#   w   #
    +##ww#w###
    +#########
    + 0123456  
    +
    +最终的答案为 [2,2,2,3,2,2,2]:
    +
    +    #    
    + ####### 
    + ####### 
    + 0123456 
    +
    + +

     

    + +

    示例 2:

    + +
    输入:heights = [1,2,3,4], V = 2, K = 2
    +输出:[2,3,3,4]
    +解释:
    +最后的水滴落在索引 1 位置,因为继续向左移动不会使其下降到更低的高度。
    +
    + +

     

    + +

    示例 3:

    + +
    输入:heights = [3,1,3], V = 5, K = 1
    +输出:[4,4,4]
    +
    + +

     

    + +

    注:

    + +

     

    + +
      +
    1. heights 的长度为 [1, 100] ,并且每个数的范围为[0, 99]
    2. +
    3. V 的范围 [0, 2000]
    4. +
    5. K 的范围 [0, heights.length - 1]
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0756.leetcode756 Pyramid Transition Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0756.leetcode756 Pyramid Transition Matrix-zh.md" new file mode 100644 index 00000000..9850ca2e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0756.leetcode756 Pyramid Transition Matrix-zh.md" @@ -0,0 +1,86 @@ +# [756. 金字塔转换矩阵](https://leetcode-cn.com/problems/pyramid-transition-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0756.Pyramid%20Transition%20Matrix/README_EN.md) + +## 题目描述 + + + +

    现在,我们用一些方块来堆砌一个金字塔。 每个方块用仅包含一个字母的字符串表示。

    + +

    使用三元组表示金字塔的堆砌规则如下:

    + +

    对于三元组 ABCC 为顶层方块,方块 AB 分别作为方块 C 下一层的的左、右子块。当且仅当 ABC 是被允许的三元组,我们才可以将其堆砌上。

    + +

    初始时,给定金字塔的基层 bottom,用一个字符串表示。一个允许的三元组列表 allowed,每个三元组用一个长度为 3 的字符串表示。

    + +

    如果可以由基层一直堆到塔尖就返回 true ,否则返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:bottom = "BCD", allowed = ["BCG", "CDE", "GEA", "FFF"]
    +输出:true
    +解释:
    +可以堆砌成这样的金字塔:
    +    A
    +   / \
    +  G   E
    + / \ / \
    +B   C   D
    +
    +因为符合 BCG、CDE 和 GEA 三种规则。
    +
    + +

    示例 2:

    + +
    +输入:bottom = "AABA", allowed = ["AAA", "AAB", "ABA", "ABB", "BAC"]
    +输出:false
    +解释:
    +无法一直堆到塔尖。
    +注意, 允许存在像 ABC 和 ABD 这样的三元组,其中 C != D。
    +
    + +

     

    + +

    提示:

    + +
      +
    • bottom 的长度范围在 [2, 8]
    • +
    • allowed 的长度范围在[0, 200]
    • +
    • 方块的标记字母范围为{'A', 'B', 'C', 'D', 'E', 'F', 'G'}
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0757.leetcode757 Set Intersection Size At Least Two-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0757.leetcode757 Set Intersection Size At Least Two-zh.md" new file mode 100644 index 00000000..95c1f331 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0757.leetcode757 Set Intersection Size At Least Two-zh.md" @@ -0,0 +1,69 @@ +# [757. 设置交集大小至少为2](https://leetcode-cn.com/problems/set-intersection-size-at-least-two) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0757.Set%20Intersection%20Size%20At%20Least%20Two/README_EN.md) + +## 题目描述 + + + +

    一个整数区间 [a, b]  ( a < b ) 代表着从 a 到 b 的所有连续整数,包括 a 和 b

    + +

    给你一组整数区间intervals,请找到一个最小的集合 S,使得 S 里的元素与区间intervals中的每一个整数区间都至少有2个元素相交。

    + +

    输出这个最小集合S的大小。

    + +

    示例 1:

    + +
    输入: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
    +输出: 3
    +解释:
    +考虑集合 S = {2, 3, 4}. S与intervals中的四个区间都有至少2个相交的元素。
    +且这是S最小的情况,故我们输出3。
    +
    + +

    示例 2:

    + +
    输入: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
    +输出: 5
    +解释:
    +最小的集合S = {1, 2, 3, 4, 5}.
    +
    + +

    注意:

    + +
      +
    1. intervals 的长度范围为[1, 3000]
    2. +
    3. intervals[i] 长度为 2,分别代表左、右边界。
    4. +
    5. intervals[i][j] 的值是 [0, 10^8]范围内的整数。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0758.leetcode758 Bold Words in String10758.leetcode758 Bold Words in String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0758.leetcode758 Bold Words in String10758.leetcode758 Bold Words in String-zh.md" new file mode 100644 index 00000000..c9a28555 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0758.leetcode758 Bold Words in String10758.leetcode758 Bold Words in String-zh.md" @@ -0,0 +1,61 @@ +# [758. 字符串中的加粗单词](https://leetcode-cn.com/problems/bold-words-in-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0758.Bold%20Words%20in%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个关键词集合 words 和一个字符串 S,将所有 S 中出现的关键词加粗。所有在标签 和  中的字母都会加粗。

    + +

    返回的字符串需要使用尽可能少的标签,当然标签应形成有效的组合。

    + +

    例如,给定 words = ["ab", "bc"] 和 S = "aabcd",需要返回 "aabcd"。注意返回 "aabcd" 会使用更多的标签,因此是错误的。

    + +

     

    + +

    提示:

    + +
      +
    • words 长度的范围为 [0, 50]
    • +
    • words[i] 长度的范围为 [1, 10]
    • +
    • S 长度的范围为 [0, 500]
    • +
    • 所有 words[i] 和 S 中的字符都为小写字母。
    • +
    + +

     

    + +

    注:此题与「616 - 给字符串添加加粗标签」相同 - https://leetcode-cn.com/problems/add-bold-tag-in-string/

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0759.leetcode759 Employee Free Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0759.leetcode759 Employee Free Time-zh.md" new file mode 100644 index 00000000..c94160c7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0759.leetcode759 Employee Free Time-zh.md" @@ -0,0 +1,81 @@ +# [759. 员工空闲时间](https://leetcode-cn.com/problems/employee-free-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0759.Employee%20Free%20Time/README_EN.md) + +## 题目描述 + + + +

    给定员工的 schedule 列表,表示每个员工的工作时间。

    + +

    每个员工都有一个非重叠的时间段  Intervals 列表,这些时间段已经排好序。

    + +

    返回表示 所有 员工的 共同,正数长度的空闲时间 的有限时间段的列表,同样需要排好序。

    + +

    示例 1:

    + +
    输入:schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
    +输出:[[3,4]]
    +解释:
    +共有 3 个员工,并且所有共同的
    +空间时间段是 [-inf, 1], [3, 4], [10, inf]。
    +我们去除所有包含 inf 的时间段,因为它们不是有限的时间段。
    +
    + +

     

    + +

    示例 2:

    + +
    输入:schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
    +输出:[[5,6],[7,9]]
    +
    + +

     

    + +

    (尽管我们用 [x, y] 的形式表示 Intervals ,内部的对象是 Intervals 而不是列表或数组。例如,schedule[0][0].start = 1, schedule[0][0].end = 2,并且 schedule[0][0][0] 是未定义的)

    + +

    而且,答案中不包含 [5, 5] ,因为长度为 0。

    + +

     

    + +

    注:

    + +
      +
    1. schedule 和 schedule[i] 为长度范围在 [1, 50]的列表。
    2. +
    3. 0 <= schedule[i].start < schedule[i].end <= 10^8
    4. +
    + +

    注:输入类型于 2019 年 4 月 15 日 改变。请重置为默认代码的定义以获取新方法。

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0760.leetcode760 Find Anagram Mappings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0760.leetcode760 Find Anagram Mappings-zh.md" new file mode 100644 index 00000000..03dab11c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0760.leetcode760 Find Anagram Mappings-zh.md" @@ -0,0 +1,91 @@ +# [760. 找出变位映射](https://leetcode-cn.com/problems/find-anagram-mappings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0760.Find%20Anagram%20Mappings/README_EN.md) + +## 题目描述 + + + +

    给定两个列表 Aand B,并且 BA 的变位(即 B 是由 A 中的元素随机排列后组成的新列表)。

    + +

    我们希望找出一个从 AB 的索引映射 P 。一个映射 P[i] = j 指的是列表 A 中的第 i 个元素出现于列表 B 中的第 j 个元素上。

    + +

    列表 AB 可能出现重复元素。如果有多于一种答案,输出任意一种。

    + +

    例如,给定

    + +
    A = [12, 28, 46, 32, 50]
    +B = [50, 12, 32, 46, 28]
    +
    + +

     

    + +

    需要返回

    + +
    [1, 4, 3, 2, 0]
    +
    + +

    P[0] = 1 ,因为 A 中的第 0 个元素出现于 B[1],而且 P[1] = 4 因为 A 中第 1 个元素出现于 B[4],以此类推。

    + +

     

    + +

    注:

    + +
      +
    1. A, B 有相同的长度,范围为 [1, 100]
    2. +
    3. A[i], B[i] 都是范围在 [0, 10^5] 的整数。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]: + mapper = collections.defaultdict(set) + for i, num in enumerate(nums2): + mapper[num].add(i) + return [mapper[num].pop() for num in nums1] +``` + +### **Java** + + + +```java +class Solution { + public int[] anagramMappings(int[] nums1, int[] nums2) { + Map> map = new HashMap<>(); + for (int i = 0; i < nums2.length; ++i) { + Set s = map.getOrDefault(nums2[i], new HashSet<>()); + s.add(i); + map.put(nums2[i], s); + } + int[] res = new int[nums1.length]; + for (int i = 0; i < nums1.length; ++i) { + int idx = map.get(nums1[i]).iterator().next(); + res[i] = idx; + map.get(nums1[i]).remove(idx); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0761.leetcode761 Special Binary String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0761.leetcode761 Special Binary String-zh.md" new file mode 100644 index 00000000..e937d586 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0761.leetcode761 Special Binary String-zh.md" @@ -0,0 +1,66 @@ +# [761. 特殊的二进制序列](https://leetcode-cn.com/problems/special-binary-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0761.Special%20Binary%20String/README_EN.md) + +## 题目描述 + + + +

    特殊的二进制序列是具有以下两个性质的二进制序列:

    + +
      +
    • 0 的数量与 1 的数量相等。
    • +
    • 二进制序列的每一个前缀码中 1 的数量要大于等于 0 的数量。
    • +
    + +

    给定一个特殊的二进制序列 S,以字符串形式表示。定义一个操作 为首先选择 S 的两个连续且非空的特殊的子串,然后将它们交换。(两个子串为连续的当且仅当第一个子串的最后一个字符恰好为第二个子串的第一个字符的前一个字符。)

    + +

    在任意次数的操作之后,交换后的字符串按照字典序排列的最大的结果是什么?

    + +

    示例 1:

    + +
    +输入: S = "11011000"
    +输出: "11100100"
    +解释:
    +将子串 "10" (在S[1]出现) 和 "1100" (在S[3]出现)进行交换。
    +这是在进行若干次操作后按字典序排列最大的结果。
    +
    + +

    说明:

    + +
      +
    1. S 的长度不超过 50
    2. +
    3. S 保证为一个满足上述定义的特殊 的二进制序列。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0762.leetcode762 Prime Number of Set Bits in Binary Representation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0762.leetcode762 Prime Number of Set Bits in Binary Representation-zh.md" new file mode 100644 index 00000000..d432eaf0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0762.leetcode762 Prime Number of Set Bits in Binary Representation-zh.md" @@ -0,0 +1,75 @@ +# [762. 二进制表示中质数个计算置位](https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0762.Prime%20Number%20of%20Set%20Bits%20in%20Binary%20Representation/README_EN.md) + +## 题目描述 + + + +

    给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。

    + +

    (注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)

    + +

    示例 1:

    + +
    +输入: L = 6, R = 10
    +输出: 4
    +解释:
    +6 -> 110 (2 个计算置位,2 是质数)
    +7 -> 111 (3 个计算置位,3 是质数)
    +9 -> 1001 (2 个计算置位,2 是质数)
    +10-> 1010 (2 个计算置位,2 是质数)
    +
    + +

    示例 2:

    + +
    +输入: L = 10, R = 15
    +输出: 5
    +解释:
    +10 -> 1010 (2 个计算置位, 2 是质数)
    +11 -> 1011 (3 个计算置位, 3 是质数)
    +12 -> 1100 (2 个计算置位, 2 是质数)
    +13 -> 1101 (3 个计算置位, 3 是质数)
    +14 -> 1110 (3 个计算置位, 3 是质数)
    +15 -> 1111 (4 个计算置位, 4 不是质数)
    +
    + +

    注意:

    + +
      +
    1. L, R 是 L <= R 且在 [1, 10^6] 中的整数。
    2. +
    3. R - L 的最大值为 10000。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0763.leetcode763 Partition Labels-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0763.leetcode763 Partition Labels-zh.md" new file mode 100644 index 00000000..1a59d3f4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0763.leetcode763 Partition Labels-zh.md" @@ -0,0 +1,62 @@ +# [763. 划分字母区间](https://leetcode-cn.com/problems/partition-labels) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0763.Partition%20Labels/README_EN.md) + +## 题目描述 + + + +

    字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。

    + +

     

    + +

    示例:

    + +
    +输入:S = "ababcbacadefegdehijhklij"
    +输出:[9,7,8]
    +解释:
    +划分结果为 "ababcbaca", "defegde", "hijhklij"。
    +每个字母最多出现在一个片段中。
    +像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
    +
    + +

     

    + +

    提示:

    + +
      +
    • S的长度在[1, 500]之间。
    • +
    • S只包含小写字母 'a''z'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0764.leetcode764 Largest Plus Sign-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0764.leetcode764 Largest Plus Sign-zh.md" new file mode 100644 index 00000000..afc317ef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0764.leetcode764 Largest Plus Sign-zh.md" @@ -0,0 +1,129 @@ +# [764. 最大加号标志](https://leetcode-cn.com/problems/largest-plus-sign) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0764.Largest%20Plus%20Sign/README_EN.md) + +## 题目描述 + + + +

    在一个大小在 (0, 0) 到 (N-1, N-1) 的2D网格 grid 中,除了在 mines 中给出的单元为 0,其他每个单元都是 1。网格中包含 1 的最大的轴对齐加号标志是多少阶?返回加号标志的阶数。如果未找到加号标志,则返回 0。

    + +

    一个 k" 阶由 1 组成的“轴对称”加号标志具有中心网格  grid[x][y] = 1 ,以及4个从中心向上、向下、向左、向右延伸,长度为 k-1,由 1 组成的臂。下面给出 k" 阶“轴对称”加号标志的示例。注意,只有加号标志的所有网格要求为 1,别的网格可能为 0 也可能为 1。

    + +

     

    + +

    k 阶轴对称加号标志示例:

    + +
    +阶 1:
    +000
    +010
    +000
    +
    +阶 2:
    +00000
    +00100
    +01110
    +00100
    +00000
    +
    +阶 3:
    +0000000
    +0001000
    +0001000
    +0111110
    +0001000
    +0001000
    +0000000
    +
    + +

     

    + +

    示例 1:

    + +
    +输入: N = 5, mines = [[4, 2]]
    +输出: 2
    +解释:
    +
    +11111
    +11111
    +11111
    +11111
    +11011
    +
    +在上面的网格中,最大加号标志的阶只能是2。一个标志已在图中标出。
    +
    + +

     

    + +

    示例 2:

    + +
    +输入: N = 2, mines = []
    +输出: 1
    +解释:
    +
    +11
    +11
    +
    +没有 2 阶加号标志,有 1 阶加号标志。
    +
    + +

     

    + +

    示例 3:

    + +
    +输入: N = 1, mines = [[0, 0]]
    +输出: 0
    +解释:
    +
    +0
    +
    +没有加号标志,返回 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 整数N 的范围: [1, 500].
    2. +
    3. mines 的最大长度为 5000.
    4. +
    5. mines[i] 是长度为2的由2个 [0, N-1] 中的数组成.
    6. +
    7. (另外,使用 C, C++, 或者 C# 编程将以稍小的时间限制进行​​判断.)
    8. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0765.leetcode765 Couples Holding Hands-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0765.leetcode765 Couples Holding Hands-zh.md" new file mode 100644 index 00000000..7f9c6917 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0765.leetcode765 Couples Holding Hands-zh.md" @@ -0,0 +1,67 @@ +# [765. 情侣牵手](https://leetcode-cn.com/problems/couples-holding-hands) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0765.Couples%20Holding%20Hands/README_EN.md) + +## 题目描述 + + + +

    N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手。 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起。 次交换可选择任意两人,让他们站起来交换座位。

    + +

    人和座位用 0 到 2N-1 的整数表示,情侣们按顺序编号,第一对是 (0, 1),第二对是 (2, 3),以此类推,最后一对是 (2N-2, 2N-1)

    + +

    这些情侣的初始座位  row[i] 是由最初始坐在第 i 个座位上的人决定的。

    + +

    示例 1:

    + +
    +输入: row = [0, 2, 1, 3]
    +输出: 1
    +解释: 我们只需要交换row[1]和row[2]的位置即可。
    +
    + +

    示例 2:

    + +
    +输入: row = [3, 2, 0, 1]
    +输出: 0
    +解释: 无需交换座位,所有的情侣都已经可以手牵手了。
    +
    + +

    说明:

    + +
      +
    1. len(row) 是偶数且数值在 [4, 60]范围内。
    2. +
    3. 可以保证row 是序列 0...len(row)-1 的一个全排列。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0766.leetcode766 Toeplitz Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0766.leetcode766 Toeplitz Matrix-zh.md" new file mode 100644 index 00000000..61d8baa5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0766.leetcode766 Toeplitz Matrix-zh.md" @@ -0,0 +1,104 @@ +# [766. 托普利茨矩阵](https://leetcode-cn.com/problems/toeplitz-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0766.Toeplitz%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的矩阵 matrix 。如果这个矩阵是托普利茨矩阵,返回 true ;否则,返回 false

    + +

    如果矩阵上每一条由左上到右下的对角线上的元素都相同,那么这个矩阵是 托普利茨矩阵

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
    +输出:true
    +解释:
    +在上述矩阵中, 其对角线为: 
    +"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。 
    +各条对角线上的所有元素均相同, 因此答案是 True 。
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[1,2],[2,2]]
    +输出:false
    +解释:
    +对角线 "[1, 2]" 上的元素不同。
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 20
    • +
    • 0 <= matrix[i][j] <= 99
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 如果矩阵存储在磁盘上,并且内存有限,以至于一次最多只能将矩阵的一行加载到内存中,该怎么办?
    • +
    • 如果矩阵太大,以至于一次只能将不完整的一行加载到内存中,该怎么办?
    • +
    + + +## 解法 + + + +遍历矩阵,若出现元素与其左上角的元素不等的情况,返回 `false`。 + + + +### **Python3** + + + +```python +class Solution: + def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: + m, n = len(matrix), len(matrix[0]) + for i in range(1, m): + for j in range(1, n): + if matrix[i][j] != matrix[i - 1][j - 1]: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isToeplitzMatrix(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + if (matrix[i][j] != matrix[i - 1][j - 1]) { + return false; + } + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0767.leetcode767 Reorganize String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0767.leetcode767 Reorganize String-zh.md" new file mode 100644 index 00000000..49ad6d31 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0767.leetcode767 Reorganize String-zh.md" @@ -0,0 +1,62 @@ +# [767. 重构字符串](https://leetcode-cn.com/problems/reorganize-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0767.Reorganize%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

    + +

    若可行,输出任意可行的结果。若不可行,返回空字符串。

    + +

    示例 1:

    + +
    +输入: S = "aab"
    +输出: "aba"
    +
    + +

    示例 2:

    + +
    +输入: S = "aaab"
    +输出: ""
    +
    + +

    注意:

    + +
      +
    • S 只包含小写字母并且长度在[1, 500]区间内。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0768.leetcode768 Max Chunks To Make Sorted II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0768.leetcode768 Max Chunks To Make Sorted II-zh.md" new file mode 100644 index 00000000..b5fc1ffa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0768.leetcode768 Max Chunks To Make Sorted II-zh.md" @@ -0,0 +1,71 @@ +# [768. 最多能完成排序的块 II](https://leetcode-cn.com/problems/max-chunks-to-make-sorted-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0768.Max%20Chunks%20To%20Make%20Sorted%20II/README_EN.md) + +## 题目描述 + + + +

    这个问题和“最多能完成排序的块”相似,但给定数组中的元素可以重复,输入数组最大长度为2000,其中的元素最大为10**8

    + +

    arr是一个可能包含重复元素的整数数组,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。

    + +

    我们最多能将数组分成多少块?

    + +

    示例 1:

    + +
    +输入: arr = [5,4,3,2,1]
    +输出: 1
    +解释:
    +将数组分成2块或者更多块,都无法得到所需的结果。
    +例如,分成 [5, 4], [3, 2, 1] 的结果是 [4, 5, 1, 2, 3],这不是有序的数组。 
    +
    + +

    示例 2:

    + +
    +输入: arr = [2,1,3,4,4]
    +输出: 4
    +解释:
    +我们可以把它分成两块,例如 [2, 1], [3, 4, 4]。
    +然而,分成 [2, 1], [3], [4], [4] 可以得到最多的块数。 
    +
    + +

    注意:

    + +
      +
    • arr的长度在[1, 2000]之间。
    • +
    • arr[i]的大小在[0, 10**8]之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0769.leetcode769 Max Chunks To Make Sorted-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0769.leetcode769 Max Chunks To Make Sorted-zh.md" new file mode 100644 index 00000000..e1e92566 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0769.leetcode769 Max Chunks To Make Sorted-zh.md" @@ -0,0 +1,67 @@ +# [769. 最多能完成排序的块](https://leetcode-cn.com/problems/max-chunks-to-make-sorted) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0769.Max%20Chunks%20To%20Make%20Sorted/README_EN.md) + +## 题目描述 + + + +

    数组arr[0, 1, ..., arr.length - 1]的一种排列,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。

    + +

    我们最多能将数组分成多少块?

    + +

    示例 1:

    + +
    输入: arr = [4,3,2,1,0]
    +输出: 1
    +解释:
    +将数组分成2块或者更多块,都无法得到所需的结果。
    +例如,分成 [4, 3], [2, 1, 0] 的结果是 [3, 4, 0, 1, 2],这不是有序的数组。
    +
    + +

    示例 2:

    + +
    输入: arr = [1,0,2,3,4]
    +输出: 4
    +解释:
    +我们可以把它分成两块,例如 [1, 0], [2, 3, 4]。
    +然而,分成 [1, 0], [2], [3], [4] 可以得到最多的块数。
    +
    + +

    注意:

    + +
      +
    • arr 的长度在 [1, 10] 之间。
    • +
    • arr[i][0, 1, ..., arr.length - 1]的一种排列。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0770.leetcode770 Basic Calculator IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0770.leetcode770 Basic Calculator IV-zh.md" new file mode 100644 index 00000000..4fd8d064 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0770.leetcode770 Basic Calculator IV-zh.md" @@ -0,0 +1,93 @@ +# [770. 基本计算器 IV](https://leetcode-cn.com/problems/basic-calculator-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0770.Basic%20Calculator%20IV/README_EN.md) + +## 题目描述 + + + +

    给定一个表达式 expression 如 expression = "e + 8 - a + 5" 和一个求值映射,如 {"e": 1}(给定的形式为 evalvars = ["e"] 和 evalints = [1]),返回表示简化表达式的标记列表,例如 ["-1*a","14"]

    + +
      +
    • 表达式交替使用块和符号,每个块和符号之间有一个空格。
    • +
    • 块要么是括号中的表达式,要么是变量,要么是非负整数。
    • +
    • 块是括号中的表达式,变量或非负整数。
    • +
    • 变量是一个由小写字母组成的字符串(不包括数字)。请注意,变量可以是多个字母,并注意变量从不具有像 "2x" 或 "-x" 这样的前导系数或一元运算符 。
    • +
    + +

    表达式按通常顺序进行求值:先是括号,然后求乘法,再计算加法和减法。例如,expression = "1 + 2 * 3" 的答案是 ["7"]

    + +

    输出格式如下:

    + +
      +
    • 对于系数非零的每个自变量项,我们按字典排序的顺序将自变量写在一个项中。例如,我们永远不会写像 “b*a*c” 这样的项,只写 “a*b*c”
    • +
    • 项的次数等于被乘的自变量的数目,并计算重复项。(例如,"a*a*b*c" 的次数为 4。)。我们先写出答案的最大次数项,用字典顺序打破关系,此时忽略词的前导系数。
    • +
    • 项的前导系数直接放在左边,用星号将它与变量分隔开(如果存在的话)。前导系数 1 仍然要打印出来。
    • +
    • 格式良好的一个示例答案是 ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] 。
    • +
    • 系数为 0 的项(包括常数项)不包括在内。例如,“0” 的表达式输出为 []。
    • +
    + +

     

    + +

    示例:

    + +
    输入:expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
    +输出:["-1*a","14"]
    +
    +输入:expression = "e - 8 + temperature - pressure",
    +evalvars = ["e", "temperature"], evalints = [1, 12]
    +输出:["-1*pressure","5"]
    +
    +输入:expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
    +输出:["1*e*e","-64"]
    +
    +输入:expression = "7 - 7", evalvars = [], evalints = []
    +输出:[]
    +
    +输入:expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
    +输出:["5*a*b*c"]
    +
    +输入:expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
    +evalvars = [], evalints = []
    +输出:["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. expression 的长度在 [1, 250] 范围内。
    2. +
    3. evalvars, evalints 在范围 [0, 100] 内,且长度相同。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0771.leetcode771 Jewels and Stones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0771.leetcode771 Jewels and Stones-zh.md" new file mode 100644 index 00000000..65ed9473 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0771.leetcode771 Jewels and Stones-zh.md" @@ -0,0 +1,96 @@ +# [771. 宝石与石头](https://leetcode-cn.com/problems/jewels-and-stones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0771.Jewels%20and%20Stones/README_EN.md) + +## 题目描述 + + + +

     给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。

    + +

    J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a""A"是不同类型的石头。

    + +

    示例 1:

    + +
    输入: J = "aA", S = "aAAbbbb"
    +输出: 3
    +
    + +

    示例 2:

    + +
    输入: J = "z", S = "ZZ"
    +输出: 0
    +
    + +

    注意:

    + +
      +
    • S 和 J 最多含有50个字母。
    • +
    •  J 中的字符不重复。
    • +
    + +## 解法 + + + +哈希表实现。 + + + +### **Python3** + + + +```python +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + jewel_set = {c for c in jewels} + return sum([1 for c in stones if c in jewel_set]) +``` + +### **Java** + + + +```java +class Solution { + public int numJewelsInStones(String jewels, String stones) { + Set jewelSet = new HashSet<>(); + for (char ch : jewels.toCharArray()) { + jewelSet.add(ch); + } + int res = 0; + for (char ch : stones.toCharArray()) { + res += (jewelSet.contains(ch) ? 1 : 0); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numJewelsInStones(string jewels, string stones) { + unordered_set jewelsSet; + for (int i = 0; i < jewels.length(); ++i) { + jewelsSet.insert(jewels[i]); + } + int res = 0; + for (int i = 0; i < stones.length(); ++i) { + res += jewelsSet.count(stones[i]); + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0772.leetcode772 Basic Calculator III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0772.leetcode772 Basic Calculator III-zh.md" new file mode 100644 index 00000000..58575ce0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0772.leetcode772 Basic Calculator III-zh.md" @@ -0,0 +1,95 @@ +# [772. 基本计算器 III](https://leetcode-cn.com/problems/basic-calculator-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0772.Basic%20Calculator%20III/README_EN.md) + +## 题目描述 + + + +

    实现一个基本的计算器来计算简单的表达式字符串。

    + +

    表达式字符串只包含非负整数,算符 +-*/ ,左括号 ( 和右括号 ) 。整数除法需要 向下截断

    + +

    你可以假定给定的表达式总是有效的。所有的中间结果的范围为 [-231, 231 - 1]

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "1+1"
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:s = "6-4/2"
    +输出:4
    +
    + +

    示例 3:

    + +
    +输入:s = "2*(5+5*2)/3+(6/2+8)"
    +输出:21
    +
    + +

    示例 4:

    + +
    +输入:s = "(2+6*3+5-(3*14/7+2)*5)+3"
    +输出:-12
    +
    + +

    示例 5:

    + +
    +输入:s = "0"
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s <= 104
    • +
    • s 由整数、'+''-''*''/''('')' 组成
    • +
    • s 是一个 有效的 表达式
    • +
    + +

     

    + +

    进阶:你可以在不使用内置库函数的情况下解决此问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0773.leetcode773 Sliding Puzzle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0773.leetcode773 Sliding Puzzle-zh.md" new file mode 100644 index 00000000..f6a01650 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0773.leetcode773 Sliding Puzzle-zh.md" @@ -0,0 +1,86 @@ +# [773. 滑动谜题](https://leetcode-cn.com/problems/sliding-puzzle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0773.Sliding%20Puzzle/README_EN.md) + +## 题目描述 + + + +

    在一个 2 x 3 的板上(board)有 5 块砖瓦,用数字 1~5 来表示, 以及一块空缺用 0 来表示.

    + +

    一次移动定义为选择 0 与一个相邻的数字(上下左右)进行交换.

    + +

    最终当板 board 的结果是 [[1,2,3],[4,5,0]] 谜板被解开。

    + +

    给出一个谜板的初始状态,返回最少可以通过多少次移动解开谜板,如果不能解开谜板,则返回 -1 。

    + +

    示例:

    + +
    +输入:board = [[1,2,3],[4,0,5]]
    +输出:1
    +解释:交换 0 和 5 ,1 步完成
    +
    + +
    +输入:board = [[1,2,3],[5,4,0]]
    +输出:-1
    +解释:没有办法完成谜板
    +
    + +
    +输入:board = [[4,1,2],[5,0,3]]
    +输出:5
    +解释:
    +最少完成谜板的最少移动次数是 5 ,
    +一种移动路径:
    +尚未移动: [[4,1,2],[5,0,3]]
    +移动 1 次: [[4,1,2],[0,5,3]]
    +移动 2 次: [[0,1,2],[4,5,3]]
    +移动 3 次: [[1,0,2],[4,5,3]]
    +移动 4 次: [[1,2,0],[4,5,3]]
    +移动 5 次: [[1,2,3],[4,5,0]]
    +
    + +
    +输入:board = [[3,2,4],[1,5,0]]
    +输出:14
    +
    + +

    提示:

    + +
      +
    • board 是一个如上所述的 2 x 3 的数组.
    • +
    • board[i][j] 是一个 [0, 1, 2, 3, 4, 5] 的排列.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0774.leetcode774 Minimize Max Distance to Gas Station-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0774.leetcode774 Minimize Max Distance to Gas Station-zh.md" new file mode 100644 index 00000000..f874413a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0774.leetcode774 Minimize Max Distance to Gas Station-zh.md" @@ -0,0 +1,72 @@ +# [774. 最小化去加油站的最大距离](https://leetcode-cn.com/problems/minimize-max-distance-to-gas-station) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0774.Minimize%20Max%20Distance%20to%20Gas%20Station/README_EN.md) + +## 题目描述 + + + +

    整数数组 stations 表示 水平数轴 上各个加油站的位置。给你一个整数 k

    + +

    请你在数轴上增设 k 个加油站,新增加油站可以位于 水平数轴 上的任意位置,而不必放在整数位置上。

    + +

    penalty() 是:增设 k 个新加油站后,相邻 两个加油站间的最大距离。

    +请你返回 penalty() 可能的最小值。与实际答案误差在 10-6 范围内的答案将被视作正确答案。 + +

     

    + +

    示例 1:

    + +
    +输入:stations = [1,2,3,4,5,6,7,8,9,10], k = 9
    +输出:0.50000
    +
    + +

    示例 2:

    + +
    +输入:stations = [23,24,36,39,46,56,57,65,84,98], k = 1
    +输出:14.00000
    +
    + +

     

    + +

    提示:

    + +
      +
    • 10 <= stations.length <= 2000
    • +
    • 0 <= stations[i] <= 108
    • +
    • stations严格递增 顺序排列
    • +
    • 1 <= k <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0775.leetcode775 Global and Local Inversions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0775.leetcode775 Global and Local Inversions-zh.md" new file mode 100644 index 00000000..63864b28 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0775.leetcode775 Global and Local Inversions-zh.md" @@ -0,0 +1,68 @@ +# [775. 全局倒置与局部倒置](https://leetcode-cn.com/problems/global-and-local-inversions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0775.Global%20and%20Local%20Inversions/README_EN.md) + +## 题目描述 + + + +

    数组 A 是 [0, 1, ..., N - 1] 的一种排列,N 是数组 A 的长度。全局倒置指的是 i,j 满足 0 <= i < j < N 并且 A[i] > A[j] ,局部倒置指的是 i 满足 0 <= i < N 并且 A[i] > A[i+1] 。

    + +

    当数组 A 中全局倒置的数量等于局部倒置的数量时,返回 true

    + +

     

    + +

    示例 1:

    + +
    +输入: A = [1,0,2]
    +输出: true
    +解释: 有 1 个全局倒置,和 1 个局部倒置。
    +
    + +

    示例 2:

    + +
    +输入: A = [1,2,0]
    +输出: false
    +解释: 有 2 个全局倒置,和 1 个局部倒置。
    +
    + +

    注意:

    + +
      +
    • A 是 [0, 1, ..., A.length - 1] 的一种排列
    • +
    • A 的长度在 [1, 5000]之间
    • +
    • 这个问题的时间限制已经减少了。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0776.leetcode776 Split BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0776.leetcode776 Split BST-zh.md" new file mode 100644 index 00000000..079c0b2d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0776.leetcode776 Split BST-zh.md" @@ -0,0 +1,81 @@ +# [776. 拆分二叉搜索树](https://leetcode-cn.com/problems/split-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0776.Split%20BST/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉搜索树(BST)、它的根结点 root 以及目标值 V

    + +

    请将该树按要求拆分为两个子树:其中一个子树结点的值都必须小于等于给定的目标值 V;另一个子树结点的值都必须大于目标值 V;树中并非一定要存在值为 V 的结点。

    + +

    除此之外,树中大部分结构都需要保留,也就是说原始树中父节点 P 的任意子节点 C,假如拆分后它们仍在同一个子树中,那么结点 P 应仍为 C 的父结点。

    + +

    你需要返回拆分后两个子树的根结点 TreeNode,顺序随意。

    + +

     

    + +

    示例:

    + +
    +输入:root = [4,2,6,1,3,5,7], V = 2
    +输出:[[2,1],[4,3,6,null,null,5,7]]
    +解释:
    +注意根结点 output[0] 和 output[1] 都是 TreeNode 对象,不是数组。
    +
    +给定的树 [4,2,6,1,3,5,7] 可化为如下示意图:
    +
    +          4
    +        /   \
    +      2      6
    +     / \    / \
    +    1   3  5   7
    +
    +输出的示意图如下:
    +
    +          4
    +        /   \
    +      3      6       和    2
    +            / \           /
    +           5   7         1
    + +

     

    + +

    提示:

    + +
      +
    1. 二叉搜索树节点个数不超过 50 
    2. +
    3. 二叉搜索树始终是有效的,并且每个节点的值都不相同
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0777.leetcode777 Swap Adjacent in LR String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0777.leetcode777 Swap Adjacent in LR String-zh.md" new file mode 100644 index 00000000..a54bcbbe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0777.leetcode777 Swap Adjacent in LR String-zh.md" @@ -0,0 +1,64 @@ +# [777. 在LR字符串中交换相邻字符](https://leetcode-cn.com/problems/swap-adjacent-in-lr-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0777.Swap%20Adjacent%20in%20LR%20String/README_EN.md) + +## 题目描述 + + + +

    在一个由 'L' , 'R''X' 三个字符组成的字符串(例如"RXXLRXRXL")中进行移动操作。一次移动操作指用一个"LX"替换一个"XL",或者用一个"XR"替换一个"RX"。现给定起始字符串start和结束字符串end,请编写代码,当且仅当存在一系列移动操作使得start可以转换成end时, 返回True

    + +

     

    + +

    示例 :

    + +
    输入: start = "RXXLRXRXL", end = "XRLXXRRLX"
    +输出: True
    +解释:
    +我们可以通过以下几步将start转换成end:
    +RXXLRXRXL ->
    +XRXLRXRXL ->
    +XRLXRXRXL ->
    +XRLXXRRXL ->
    +XRLXXRRLX
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= len(start) = len(end) <= 10000
    • +
    • startend中的字符串仅限于'L', 'R''X'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0778.leetcode778 Swim in Rising Water-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0778.leetcode778 Swim in Rising Water-zh.md" new file mode 100644 index 00000000..5d40deef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0778.leetcode778 Swim in Rising Water-zh.md" @@ -0,0 +1,132 @@ +# [778. 水位上升的泳池中游泳](https://leetcode-cn.com/problems/swim-in-rising-water) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0778.Swim%20in%20Rising%20Water/README_EN.md) + +## 题目描述 + + + +

    在一个 N x N 的坐标方格 grid 中,每一个方格的值 grid[i][j] 表示在位置 (i,j) 的平台高度。

    + +

    现在开始下雨了。当时间为 t 时,此时雨水导致水池中任意位置的水位为 t 。你可以从一个平台游向四周相邻的任意一个平台,但是前提是此时水位必须同时淹没这两个平台。假定你可以瞬间移动无限距离,也就是默认在方格内部游动是不耗时的。当然,在你游泳的时候你必须待在坐标方格里面。

    + +

    你从坐标方格的左上平台 (0,0) 出发。最少耗时多久你才能到达坐标方格的右下平台 (N-1, N-1)

    + +

     

    + +

    示例 1:

    + +
    +输入: [[0,2],[1,3]]
    +输出: 3
    +解释:
    +时间为0时,你位于坐标方格的位置为 (0, 0)。
    +此时你不能游向任意方向,因为四个相邻方向平台的高度都大于当前时间为 0 时的水位。
    +
    +等时间到达 3 时,你才可以游向平台 (1, 1). 因为此时的水位是 3,坐标方格中的平台没有比水位 3 更高的,所以你可以游向坐标方格中的任意位置
    +
    + +

    示例2:

    + +
    +输入: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
    +输出: 16
    +解释:
    + 0  1  2  3  4
    +24 23 22 21  5
    +12 13 14 15 16
    +11 17 18 19 20
    +10  9  8  7  6
    +
    +最终的路线用加粗进行了标记。
    +我们必须等到时间为 16,此时才能保证平台 (0, 0) 和 (4, 4) 是连通的
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= N <= 50.
    2. +
    3. grid[i][j][0, ..., N*N - 1] 的排列。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java +class Solution { + // x、y方向向量 + public static final int[] dx = {0, 0, 1, -1}; + public static final int[] dy = {1, -1, 0, 0}; + /** + * https://blog.csdn.net/fuxuemingzhu/article/details/82926674 + *

    + * 参考这篇文章的第二种解题方法做的 + *

    + * 通过优先级队列找寻局部最优解 最终的得到的结果就是全局最优解 + * + * @param grid + * @return + */ + // 以grid左上角为原点,横向为X轴,纵向为Y轴 + public int swimInWater(int[][] grid) { + // 定义一个优先级队列 按照h从小到大排列 + Queue>> queue = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); + queue.add(new Pair<>(grid[0][0], new Pair<>(0, 0))); + // 已经遍历过的点 + Set> visitSet = new HashSet<>(); + visitSet.add(new Pair<>(0, 0)); + + int res = 0; + int length = grid.length; + + while (!queue.isEmpty()) { + Pair> top = queue.poll(); + Integer x = top.getValue().getKey(); + Integer y = top.getValue().getValue(); + res = Math.max(res, top.getKey()); + // 2 <= N <= 50 这个范围内可以直接使用==进行Integer的比较 + if (x == top.getValue().getValue() && y == length - 1) { + break; + } + + for (int i = 0; i < 4; i++) { + int newY = y + dy[i]; + int newX = x + dx[i]; + if (newX < 0 || newY < 0 || newX >= length || newY >= length || visitSet.contains(new Pair<>(newX, newY))) { + // 直接忽略 + continue; + } + queue.add(new Pair<>(grid[newX][newY], new Pair<>(newX, newY))); + visitSet.add(new Pair<>(newX, newY)); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0779.leetcode779 K-th Symbol in Grammar-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0779.leetcode779 K-th Symbol in Grammar-zh.md" new file mode 100644 index 00000000..1924b5cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0779.leetcode779 K-th Symbol in Grammar-zh.md" @@ -0,0 +1,72 @@ +# [779. 第K个语法符号](https://leetcode-cn.com/problems/k-th-symbol-in-grammar) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0779.K-th%20Symbol%20in%20Grammar/README_EN.md) + +## 题目描述 + + + +

    在第一行我们写上一个 0。接下来的每一行,将前一行中的0替换为011替换为10

    + +

    给定行数 N 和序数 K,返回第 N 行中第 K个字符。(K从1开始)

    + +


    +例子:

    + +
    输入: N = 1, K = 1
    +输出: 0
    +
    +输入: N = 2, K = 1
    +输出: 0
    +
    +输入: N = 2, K = 2
    +输出: 1
    +
    +输入: N = 4, K = 5
    +输出: 1
    +
    +解释:
    +第一行: 0
    +第二行: 01
    +第三行: 0110
    +第四行: 01101001
    +
    + +


    +注意:

    + +
      +
    1. N 的范围 [1, 30].
    2. +
    3. K 的范围 [1, 2^(N-1)].
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0780.leetcode780 Reaching Points-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0780.leetcode780 Reaching Points-zh.md" new file mode 100644 index 00000000..59462474 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0780.leetcode780 Reaching Points-zh.md" @@ -0,0 +1,66 @@ +# [780. 到达终点](https://leetcode-cn.com/problems/reaching-points) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0780.Reaching%20Points/README_EN.md) + +## 题目描述 + + + +

    从点 (x, y) 可以转换到 (x, x+y)  或者 (x+y, y)

    + +

    给定一个起点 (sx, sy) 和一个终点 (tx, ty),如果通过一系列的转换可以从起点到达终点,则返回 True ,否则返回 False

    + +
    +示例:
    +输入: sx = 1, sy = 1, tx = 3, ty = 5
    +输出: True
    +解释:
    +可以通过以下一系列转换从起点转换到终点:
    +(1, 1) -> (1, 2)
    +(1, 2) -> (3, 2)
    +(3, 2) -> (3, 5)
    +
    +输入: sx = 1, sy = 1, tx = 2, ty = 2
    +输出: False
    +
    +输入: sx = 1, sy = 1, tx = 1, ty = 1
    +输出: True
    +
    +
    + +

    注意:

    + +
      +
    • sx, sy, tx, ty 是范围在 [1, 10^9] 的整数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0781.leetcode781 Rabbits in Forest-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0781.leetcode781 Rabbits in Forest-zh.md" new file mode 100644 index 00000000..0f5624d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0781.leetcode781 Rabbits in Forest-zh.md" @@ -0,0 +1,89 @@ +# [781. 森林中的兔子](https://leetcode-cn.com/problems/rabbits-in-forest) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0781.Rabbits%20in%20Forest/README_EN.md) + +## 题目描述 + + + +

    森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。

    + +

    返回森林中兔子的最少数量。

    + +
    +示例:
    +输入: answers = [1, 1, 2]
    +输出: 5
    +解释:
    +两只回答了 "1" 的兔子可能有相同的颜色,设为红色。
    +之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
    +设回答了 "2" 的兔子为蓝色。
    +此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
    +因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。
    +
    +输入: answers = [10, 10, 10]
    +输出: 11
    +
    +输入: answers = []
    +输出: 0
    +
    + +

    说明:

    + +
      +
    1. answers 的长度最大为1000
    2. +
    3. answers[i] 是在 [0, 999] 范围内的整数。
    4. +
    + + +## 解法 + + + +两只相同颜色的兔子看到的其他同色兔子数一定相同,若两只兔子看到的其它同色兔子数不同,那么这两只兔子颜色也不同。 + +因此,将 `answers` 中值相同的元素分为一组,对于每一组,计算出兔子的最少数量,然后将所有组的计算结果累加,就是最终的答案。 + +如果有 x 只兔子都回答 y,则至少有 `⌈x / (y + 1)⌉` 种不同的颜色,且每种颜色有 `y + 1` 只兔子。 + + + +### **Python3** + + + +```python +class Solution: + def numRabbits(self, answers: List[int]) -> int: + counter = collections.Counter(answers) + return sum([math.ceil(v / (k + 1)) * (k + 1) for k, v in counter.items()]) +``` + +### **Java** + + + +```java +class Solution { + public int numRabbits(int[] answers) { + Map counter = new HashMap<>(); + for (int e : answers) { + counter.put(e, counter.getOrDefault(e, 0) + 1); + } + int res = 0; + for (Map.Entry entry : counter.entrySet()) { + int answer = entry.getKey(), count = entry.getValue(); + res += (int) Math.ceil(count / ((answer + 1) * 1.0)) * (answer + 1); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0782.leetcode782 Transform to Chessboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0782.leetcode782 Transform to Chessboard-zh.md" new file mode 100644 index 00000000..b257515b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0782.leetcode782 Transform to Chessboard-zh.md" @@ -0,0 +1,82 @@ +# [782. 变为棋盘](https://leetcode-cn.com/problems/transform-to-chessboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0782.Transform%20to%20Chessboard/README_EN.md) + +## 题目描述 + + + +

    一个 N x N的 board 仅由 0 和 1 组成 。每次移动,你能任意交换两列或是两行的位置。

    + +

    输出将这个矩阵变为 “棋盘” 所需的最小移动次数。“棋盘” 是指任意一格的上下左右四个方向的值均与本身不同的矩阵。如果不存在可行的变换,输出 -1。

    + +
    示例:
    +输入: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
    +输出: 2
    +解释:
    +一种可行的变换方式如下,从左到右:
    +
    +0110     1010     1010
    +0110 --> 1010 --> 0101
    +1001     0101     1010
    +1001     0101     0101
    +
    +第一次移动交换了第一列和第二列。
    +第二次移动交换了第二行和第三行。
    +
    +
    +输入: board = [[0, 1], [1, 0]]
    +输出: 0
    +解释:
    +注意左上角的格值为0时也是合法的棋盘,如:
    +
    +01
    +10
    +
    +也是合法的棋盘.
    +
    +输入: board = [[1, 0], [1, 0]]
    +输出: -1
    +解释:
    +任意的变换都不能使这个输入变为合法的棋盘。
    +
    + +

     

    + +

    提示:

    + +
      +
    • board 是方阵,且行列数的范围是[2, 30]
    • +
    • board[i][j] 将只包含 0或 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0783.leetcode783 Minimum Distance Between BST Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0783.leetcode783 Minimum Distance Between BST Nodes-zh.md" new file mode 100644 index 00000000..c6284127 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0783.leetcode783 Minimum Distance Between BST Nodes-zh.md" @@ -0,0 +1,161 @@ +# [783. 二叉搜索树节点最小距离](https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0783.Minimum%20Distance%20Between%20BST%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值

    + +

    注意:本题与 530:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ 相同

    + +

     

    + +
    +
    +

    示例 1:

    + +
    +输入:root = [4,2,6,1,3]
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:root = [1,0,48,null,null,12,49]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [2, 100]
    • +
    • 0 <= Node.val <= 105
    • +
    • 差值是一个正数,其数值等于两值之差的绝对值
    • +
    +
    +
    + + +## 解法 + + + +中序遍历二叉搜索树,获取当前节点与上个节点的差值的最小值即可。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDiffInBST(self, root: TreeNode) -> int: + def inorder(root): + if not root: + return + inorder(root.left) + if self.pre is not None: + self.min_diff = min(self.min_diff, abs(root.val - self.pre)) + self.pre = root.val + inorder(root.right) + + self.pre = None + self.min_diff = 10 ** 5 + inorder(root) + return self.min_diff +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + + private int minDiff = Integer.MAX_VALUE; + private Integer pre; + + public int minDiffInBST(TreeNode root) { + inorder(root); + return minDiff; + } + + private void inorder(TreeNode root) { + if (root == null) return; + inorder(root.left); + if (pre != null) minDiff = Math.min(minDiff, Math.abs(root.val - pre)); + pre = root.val; + inorder(root.right); + } +} +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +var res int +var preNode *TreeNode +func minDiffInBST(root *TreeNode) int { + res = int(^uint(0) >> 1) + preNode = nil + helper(root) + return res +} + +func helper(root *TreeNode) { + if root == nil { + return + } + helper(root.Left) + if preNode != nil { + res = getMinInt(res, root.Val - preNode.Val) + } + preNode = root + helper(root.Right) +} + +func getMinInt(a,b int) int { + if a < b { + return a + } + return b +} +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0784.leetcode784 Letter Case Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0784.leetcode784 Letter Case Permutation-zh.md" new file mode 100644 index 00000000..853f3001 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0784.leetcode784 Letter Case Permutation-zh.md" @@ -0,0 +1,62 @@ +# [784. 字母大小写全排列](https://leetcode-cn.com/problems/letter-case-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0784.Letter%20Case%20Permutation/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。

    + +

     

    + +
    示例:
    +输入:S = "a1b2"
    +输出:["a1b2", "a1B2", "A1b2", "A1B2"]
    +
    +输入:S = "3z4"
    +输出:["3z4", "3Z4"]
    +
    +输入:S = "12345"
    +输出:["12345"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • S 的长度不超过12
    • +
    • S 仅由数字和字母组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0785.leetcode785 Is Graph Bipartite-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0785.leetcode785 Is Graph Bipartite-zh.md" new file mode 100644 index 00000000..d5bdd364 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0785.leetcode785 Is Graph Bipartite-zh.md" @@ -0,0 +1,80 @@ +# [785. 判断二分图](https://leetcode-cn.com/problems/is-graph-bipartite) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0785.Is%20Graph%20Bipartite/README_EN.md) + +## 题目描述 + + + +存在一个 无向图 ,图中有 n 个节点。其中每个节点都有一个介于 0n - 1 之间的唯一编号。给你一个二维数组 graph ,其中 graph[u] 是一个节点数组,由节点 u 的邻接节点组成。形式上,对于 graph[u] 中的每个 v ,都存在一条位于节点 u 和节点 v 之间的无向边。该无向图同时具有以下属性: +
      +
    • 不存在自环(graph[u] 不包含 u)。
    • +
    • 不存在平行边(graph[u] 不包含重复值)。
    • +
    • 如果 vgraph[u] 内,那么 u 也应该在 graph[v] 内(该图是无向图)
    • +
    • 这个图可能不是连通图,也就是说两个节点 uv 之间可能不存在一条连通彼此的路径。
    • +
    + +

    二分图 定义:如果能将一个图的节点集合分割成两个独立的子集 AB ,并使图中的每一条边的两个节点一个来自 A 集合,一个来自 B 集合,就将这个图称为 二分图

    + +

    如果图是二分图,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
    +输出:false
    +解释:不能将节点分割成两个独立的子集,以使每条边都连通一个子集中的一个节点与另一个子集中的一个节点。
    + +

    示例 2:

    + +
    +输入:graph = [[1,3],[0,2],[1,3],[0,2]]
    +输出:true
    +解释:可以将节点分成两组: {0, 2} 和 {1, 3} 。
    + +

     

    + +

    提示:

    + +
      +
    • graph.length == n
    • +
    • 1 <= n <= 100
    • +
    • 0 <= graph[u].length < n
    • +
    • 0 <= graph[u][i] <= n - 1
    • +
    • graph[u] 不会包含 u
    • +
    • graph[u] 的所有值 互不相同
    • +
    • 如果 graph[u] 包含 v,那么 graph[v] 也会包含 u
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0786.leetcode786 K-th Smallest Prime Fraction-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0786.leetcode786 K-th Smallest Prime Fraction-zh.md" new file mode 100644 index 00000000..4063fdd3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0786.leetcode786 K-th Smallest Prime Fraction-zh.md" @@ -0,0 +1,75 @@ +# [786. 第 K 个最小的素数分数](https://leetcode-cn.com/problems/k-th-smallest-prime-fraction) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0786.K-th%20Smallest%20Prime%20Fraction/README_EN.md) + +## 题目描述 + + + +

    给你一个按递增顺序排序的数组 arr 和一个整数 k 。数组 arr1 和若干 素数  组成,且其中所有整数互不相同。

    + +

    对于每对满足 0 < i < j < arr.lengthij ,可以得到分数 arr[i] / arr[j]

    + +

    那么第 k 个最小的分数是多少呢?  以长度为 2 的整数数组返回你的答案, 这里 answer[0] == arr[i] 且 answer[1] == arr[j]

    +  + +

    示例 1:

    + +
    +输入:arr = [1,2,3,5], k = 3
    +输出:[2,5]
    +解释:已构造好的分数,排序后如下所示: 
    +1/5, 1/3, 2/5, 1/2, 3/5, 2/3
    +很明显第三个最小的分数是 2/5
    +
    + +

    示例 2:

    + +
    +输入:arr = [1,7], k = 1
    +输出:[1,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 3 * 104
    • +
    • arr[0] == 1
    • +
    • arr[i] 是一个 素数i > 0
    • +
    • arr 中的所有数字 互不相同 ,且按 严格递增 排序
    • +
    • 1 <= k <= arr.length * (arr.length - 1) / 2
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0787.leetcode787 Cheapest Flights Within K Stops-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0787.leetcode787 Cheapest Flights Within K Stops-zh.md" new file mode 100644 index 00000000..715170d4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0787.leetcode787 Cheapest Flights Within K Stops-zh.md" @@ -0,0 +1,83 @@ +# [787. K 站中转内最便宜的航班](https://leetcode-cn.com/problems/cheapest-flights-within-k-stops) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0787.Cheapest%20Flights%20Within%20K%20Stops/README_EN.md) + +## 题目描述 + + + +

    n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v

    + +

    现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 srcdst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -1

    + +

     

    + +

    示例 1:

    + +
    +输入: 
    +n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
    +src = 0, dst = 2, k = 1
    +输出: 200
    +解释: 
    +城市航班图如下
    +
    +
    +从城市 0 到城市 2 在 1 站中转以内的最便宜价格是 200,如图中红色所示。
    + +

    示例 2:

    + +
    +输入: 
    +n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
    +src = 0, dst = 2, k = 0
    +输出: 500
    +解释: 
    +城市航班图如下
    +
    +
    +从城市 0 到城市 2 在 0 站中转以内的最便宜价格是 500,如图中蓝色所示。
    + +

     

    + +

    提示:

    + +
      +
    • n 范围是 [1, 100],城市标签从 0n - 1
    • +
    • 航班数量范围是 [0, n * (n - 1) / 2]
    • +
    • 每个航班的格式 (src, dst, price)
    • +
    • 每个航班的价格范围是 [1, 10000]
    • +
    • k 范围是 [0, n - 1]
    • +
    • 航班没有重复,且不存在自环
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0788.leetcode788 Rotated Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0788.leetcode788 Rotated Digits-zh.md" new file mode 100644 index 00000000..8ab81aa2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0788.leetcode788 Rotated Digits-zh.md" @@ -0,0 +1,63 @@ +# [788. 旋转数字](https://leetcode-cn.com/problems/rotated-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0788.Rotated%20Digits/README_EN.md) + +## 题目描述 + + + +

    我们称一个数 X 为好数, 如果它的每位数字逐个地被旋转 180 度后,我们仍可以得到一个有效的,且和 X 不同的数。要求每位数字都要被旋转。

    + +

    如果一个数的每位数字被旋转以后仍然还是一个数字, 则这个数是有效的。0, 1, 和 8 被旋转后仍然是它们自己;2 和 5 可以互相旋转成对方(在这种情况下,它们以不同的方向旋转,换句话说,2 和 5 互为镜像);6 和 9 同理,除了这些以外其他的数字旋转以后都不再是有效的数字。

    + +

    现在我们有一个正整数 N, 计算从 1 到 N 中有多少个数 X 是好数?

    + +

     

    + +

    示例:

    + +
    输入: 10
    +输出: 4
    +解释: 
    +在[1, 10]中有四个好数: 2, 5, 6, 9。
    +注意 1 和 10 不是好数, 因为他们在旋转之后不变。
    +
    + +

     

    + +

    提示:

    + +
      +
    • N 的取值范围是 [1, 10000]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0789.leetcode789 Escape The Ghosts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0789.leetcode789 Escape The Ghosts-zh.md" new file mode 100644 index 00000000..efda4a98 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0789.leetcode789 Escape The Ghosts-zh.md" @@ -0,0 +1,98 @@ +# [789. 逃脱阻碍者](https://leetcode-cn.com/problems/escape-the-ghosts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0789.Escape%20The%20Ghosts/README_EN.md) + +## 题目描述 + + + +

    你在进行一个简化版的吃豆人游戏。你从 [0, 0] 点开始出发,你的目的地是 target = [xtarget, ytarget] 。地图上有一些阻碍者,以数组 ghosts 给出,第 i 个阻碍者从 ghosts[i] = [xi, yi] 出发。所有输入均为 整数坐标

    + +

    每一回合,你和阻碍者们可以同时向东,西,南,北四个方向移动,每次可以移动到距离原位置 1 个单位 的新位置。当然,也可以选择 不动 。所有动作 同时 发生。

    + +

    如果你可以在任何阻碍者抓住你 之前 到达目的地(阻碍者可以采取任意行动方式),则被视为逃脱成功。如果你和阻碍者同时到达了一个位置(包括目的地)都不算是逃脱成功。

    + +

    只有在你有可能成功逃脱时,输出 true ;否则,输出 false

    +  + +

    示例 1:

    + +
    +输入:ghosts = [[1,0],[0,3]], target = [0,1]
    +输出:true
    +解释:你可以直接一步到达目的地 (0,1) ,在 (1, 0) 或者 (0, 3) 位置的阻碍者都不可能抓住你。 
    +
    + +

    示例 2:

    + +
    +输入:ghosts = [[1,0]], target = [2,0]
    +输出:false
    +解释:你需要走到位于 (2, 0) 的目的地,但是在 (1, 0) 的阻碍者位于你和目的地之间。 
    +
    + +

    示例 3:

    + +
    +输入:ghosts = [[2,0]], target = [1,0]
    +输出:false
    +解释:阻碍者可以和你同时达到目的地。 
    +
    + +

    示例 4:

    + +
    +输入:ghosts = [[5,0],[-10,-2],[0,-5],[-2,-2],[-7,1]], target = [7,7]
    +输出:false
    +
    + +

    示例 5:

    + +
    +输入:ghosts = [[-1,0],[0,1],[-1,0],[0,1],[-1,0]], target = [0,0]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= ghosts.length <= 100
    • +
    • ghosts[i].length == 2
    • +
    • -104 <= xi, yi <= 104
    • +
    • 同一位置可能有 多个阻碍者
    • +
    • target.length == 2
    • +
    • -104 <= xtarget, ytarget <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0790.leetcode790 Domino and Tromino Tiling-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0790.leetcode790 Domino and Tromino Tiling-zh.md" new file mode 100644 index 00000000..e5029d4f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0790.leetcode790 Domino and Tromino Tiling-zh.md" @@ -0,0 +1,68 @@ +# [790. 多米诺和托米诺平铺](https://leetcode-cn.com/problems/domino-and-tromino-tiling) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0790.Domino%20and%20Tromino%20Tiling/README_EN.md) + +## 题目描述 + + + +

    有两种形状的瓷砖:一种是 2x1 的多米诺形,另一种是形如 "L" 的托米诺形。两种形状都可以旋转。

    + +
    +XX  <- 多米诺
    +
    +XX  <- "L" 托米诺
    +X
    +
    + +

    给定 N 的值,有多少种方法可以平铺 2 x N 的面板?返回值 mod 10^9 + 7

    + +

    (平铺指的是每个正方形都必须有瓷砖覆盖。两个平铺不同,当且仅当面板上有四个方向上的相邻单元中的两个,使得恰好有一个平铺有一个瓷砖占据两个正方形。)

    + +
    +示例:
    +输入: 3
    +输出: 5
    +解释: 
    +下面列出了五种不同的方法,不同字母代表不同瓷砖:
    +XYZ XXZ XYY XXY XYY
    +XYZ YYZ XZZ XYY XXY
    + +

    提示:

    + +
      +
    • N  的范围是 [1, 1000]
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0791.leetcode791 Custom Sort String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0791.leetcode791 Custom Sort String-zh.md" new file mode 100644 index 00000000..5ef19080 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0791.leetcode791 Custom Sort String-zh.md" @@ -0,0 +1,63 @@ +# [791. 自定义字符串排序](https://leetcode-cn.com/problems/custom-sort-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0791.Custom%20Sort%20String/README_EN.md) + +## 题目描述 + + + +

    字符串ST 只包含小写字符。在S中,所有字符只会出现一次。

    + +

    S 已经根据某种规则进行了排序。我们要根据S中的字符顺序对T进行排序。更具体地说,如果Sxy之前出现,那么返回的字符串中x也应出现在y之前。

    + +

    返回任意一种符合条件的字符串T

    + +
    +示例:
    +输入:
    +S = "cba"
    +T = "abcd"
    +输出: "cbad"
    +解释: 
    +S中出现了字符 "a", "b", "c", 所以 "a", "b", "c" 的顺序应该是 "c", "b", "a". 
    +由于 "d" 没有在S中出现, 它可以放在T的任意位置. "dcba", "cdba", "cbda" 都是合法的输出。
    +
    + +

    注意:

    + +
      +
    • S的最大长度为26,其中没有重复的字符。
    • +
    • T的最大长度为200
    • +
    • ST只包含小写字符。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0792.leetcode792 Number of Matching Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0792.leetcode792 Number of Matching Subsequences-zh.md" new file mode 100644 index 00000000..73e42264 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0792.leetcode792 Number of Matching Subsequences-zh.md" @@ -0,0 +1,58 @@ +# [792. 匹配子序列的单词数](https://leetcode-cn.com/problems/number-of-matching-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0792.Number%20of%20Matching%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。

    + +
    +示例:
    +输入: 
    +S = "abcde"
    +words = ["a", "bb", "acd", "ace"]
    +输出: 3
    +解释: 有三个是 S 的子序列的单词: "a", "acd", "ace"。
    +
    + +

    注意:

    + +
      +
    • 所有在words和 S 里的单词都只由小写字母组成。
    • +
    • S 的长度在 [1, 50000]
    • +
    • words 的长度在 [1, 5000]
    • +
    • words[i]的长度在[1, 50]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0793.leetcode793 Preimage Size of Factorial Zeroes Function-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0793.leetcode793 Preimage Size of Factorial Zeroes Function-zh.md" new file mode 100644 index 00000000..8c98b6b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0793.leetcode793 Preimage Size of Factorial Zeroes Function-zh.md" @@ -0,0 +1,69 @@ +# [793. 阶乘函数后 K 个零](https://leetcode-cn.com/problems/preimage-size-of-factorial-zeroes-function) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0793.Preimage%20Size%20of%20Factorial%20Zeroes%20Function/README_EN.md) + +## 题目描述 + + + +

     f(x) 是 x! 末尾是 0 的数量。(回想一下 x! = 1 * 2 * 3 * ... * x,且 0! = 1

    + +

    例如, f(3) = 0 ,因为 3! = 6 的末尾没有 0 ;而 f(11) = 2 ,因为 11!= 39916800 末端有 2 个 0 。给定 K,找出多少个非负整数 x ,能满足 f(x) = K

    + +

     

    + +

    示例 1:

    + +
    +输入:K = 0
    +输出:5
    +解释:0!, 1!, 2!, 3!, and 4! 均符合 K = 0 的条件。
    +
    + +

    示例 2:

    + +
    +输入:K = 5
    +输出:0
    +解释:没有匹配到这样的 x!,符合 K = 5 的条件。
    + +

     

    + +

    提示:

    + +
      +
    • +

      K 是范围在 [0, 10^9] 的整数

      +
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0794.leetcode794 Valid Tic-Tac-Toe State-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0794.leetcode794 Valid Tic-Tac-Toe State-zh.md" new file mode 100644 index 00000000..b5e6a1aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0794.leetcode794 Valid Tic-Tac-Toe State-zh.md" @@ -0,0 +1,80 @@ +# [794. 有效的井字游戏](https://leetcode-cn.com/problems/valid-tic-tac-toe-state) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0794.Valid%20Tic-Tac-Toe%20State/README_EN.md) + +## 题目描述 + + + +

    用字符串数组作为井字游戏的游戏板 board。当且仅当在井字游戏过程中,玩家有可能将字符放置成游戏板所显示的状态时,才返回 true。

    + +

    该游戏板是一个 3 x 3 数组,由字符 " ""X" 和 "O" 组成。字符 " " 代表一个空位。

    + +

    以下是井字游戏的规则:

    + +
      +
    • 玩家轮流将字符放入空位(" ")中。
    • +
    • 第一个玩家总是放字符 “X”,且第二个玩家总是放字符 “O”。
    • +
    • “X” 和 “O” 只允许放置在空位中,不允许对已放有字符的位置进行填充。
    • +
    • 当有 3 个相同(且非空)的字符填充任何行、列或对角线时,游戏结束。
    • +
    • 当所有位置非空时,也算为游戏结束。
    • +
    • 如果游戏结束,玩家不允许再放置字符。
    • +
    + +
    +示例 1:
    +输入: board = ["O  ", "   ", "   "]
    +输出: false
    +解释: 第一个玩家总是放置“X”。
    +
    +示例 2:
    +输入: board = ["XOX", " X ", "   "]
    +输出: false
    +解释: 玩家应该是轮流放置的。
    +
    +示例 3:
    +输入: board = ["XXX", "   ", "OOO"]
    +输出: false
    +
    +示例 4:
    +输入: board = ["XOX", "O O", "XOX"]
    +输出: true
    +
    + +

    说明:

    + +
      +
    • 游戏板 board 是长度为 3 的字符串数组,其中每个字符串 board[i] 的长度为 3。
    • +
    •  board[i][j] 是集合 {" ", "X", "O"} 中的一个字符。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0795.leetcode795 Number of Subarrays with Bounded Maximum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0795.leetcode795 Number of Subarrays with Bounded Maximum-zh.md" new file mode 100644 index 00000000..8bd3f032 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0795.leetcode795 Number of Subarrays with Bounded Maximum-zh.md" @@ -0,0 +1,58 @@ +# [795. 区间子数组个数](https://leetcode-cn.com/problems/number-of-subarrays-with-bounded-maximum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0795.Number%20of%20Subarrays%20with%20Bounded%20Maximum/README_EN.md) + +## 题目描述 + + + +

    给定一个元素都是正整数的数组A ,正整数 L 以及 R (L <= R)。

    + +

    求连续、非空且其中最大元素满足大于等于L 小于等于R的子数组个数。

    + +
    例如 :
    +输入: 
    +A = [2, 1, 4, 3]
    +L = 2
    +R = 3
    +输出: 3
    +解释: 满足条件的子数组: [2], [2, 1], [3].
    +
    + +

    注意:

    + +
      +
    • L, R  和 A[i] 都是整数,范围在 [0, 10^9]
    • +
    • 数组 A 的长度范围在[1, 50000]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0796.leetcode796 Rotate String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0796.leetcode796 Rotate String-zh.md" new file mode 100644 index 00000000..e6e80b91 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0796.leetcode796 Rotate String-zh.md" @@ -0,0 +1,57 @@ +# [796. 旋转字符串](https://leetcode-cn.com/problems/rotate-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0796.Rotate%20String/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串, A 和 B

    + +

    A 的旋转操作就是将 A 最左边的字符移动到最右边。 例如, 若 A = 'abcde',在移动一次之后结果就是'bcdea' 。如果在若干次旋转操作之后,A 能变成B,那么返回True

    + +
    +示例 1:
    +输入: A = 'abcde', B = 'cdeab'
    +输出: true
    +
    +示例 2:
    +输入: A = 'abcde', B = 'abced'
    +输出: false
    + +

    注意:

    + +
      +
    • A 和 B 长度不超过 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0797.leetcode797 All Paths From Source to Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0797.leetcode797 All Paths From Source to Target-zh.md" new file mode 100644 index 00000000..8b7b3b52 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0797.leetcode797 All Paths From Source to Target-zh.md" @@ -0,0 +1,88 @@ +# [797. 所有可能的路径](https://leetcode-cn.com/problems/all-paths-from-source-to-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0797.All%20Paths%20From%20Source%20to%20Target/README_EN.md) + +## 题目描述 + + + +

    给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)

    + +

    二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a )空就是没有下一个结点了。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:graph = [[1,2],[3],[3],[]]
    +输出:[[0,1,3],[0,2,3]]
    +解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
    +
    + +

    示例 2:

    + +

    + +
    输入:graph = [[4,3,1],[3,2,4],[3],[4],[]]
    +输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
    +
    + +

    示例 3:

    + +
    输入:graph = [[1],[]]
    +输出:[[0,1]]
    +
    + +

    示例 4:

    + +
    输入:graph = [[1,2,3],[2],[3],[]]
    +输出:[[0,1,2,3],[0,2,3],[0,3]]
    +
    + +

    示例 5:

    + +
    输入:graph = [[1,3],[2],[3],[]]
    +输出:[[0,1,2,3],[0,3]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 结点的数量会在范围 [2, 15] 内。
    • +
    • 你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0798.leetcode798 Smallest Rotation with Highest Score-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0798.leetcode798 Smallest Rotation with Highest Score-zh.md" new file mode 100644 index 00000000..3e417caf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0798.leetcode798 Smallest Rotation with Highest Score-zh.md" @@ -0,0 +1,77 @@ +# [798. 得分最高的最小轮调](https://leetcode-cn.com/problems/smallest-rotation-with-highest-score) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0798.Smallest%20Rotation%20with%20Highest%20Score/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 A,我们可以将它按一个非负整数 K 进行轮调,这样可以使数组变为 A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1] 的形式。此后,任何值小于或等于其索引的项都可以记作一分。

    + +

    例如,如果数组为 [2, 4, 1, 3, 0],我们按 K = 2 进行轮调后,它将变成 [1, 3, 0, 2, 4]。这将记作 3 分,因为 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]。

    + +

    在所有可能的轮调中,返回我们所能得到的最高分数对应的轮调索引 K。如果有多个答案,返回满足条件的最小的索引 K。

    + +

     

    + +

    示例 1:

    + +
    输入:[2, 3, 1, 4, 0]
    +输出:3
    +解释:
    +下面列出了每个 K 的得分:
    +K = 0,  A = [2,3,1,4,0],    score 2
    +K = 1,  A = [3,1,4,0,2],    score 3
    +K = 2,  A = [1,4,0,2,3],    score 3
    +K = 3,  A = [4,0,2,3,1],    score 4
    +K = 4,  A = [0,2,3,1,4],    score 3
    +所以我们应当选择 K = 3,得分最高。
    + +

    示例 2:

    + +
    输入:[1, 3, 0, 2, 4]
    +输出:0
    +解释:
    +A 无论怎么变化总是有 3 分。
    +所以我们将选择最小的 K,即 0。
    +
    + +

     

    + +

    提示:

    + +
      +
    • A 的长度最大为 20000
    • +
    • A[i] 的取值范围是 [0, A.length]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0799.leetcode799 Champagne Tower-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0799.leetcode799 Champagne Tower-zh.md" new file mode 100644 index 00000000..b44d901f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0799.leetcode799 Champagne Tower-zh.md" @@ -0,0 +1,69 @@ +# [799. 香槟塔](https://leetcode-cn.com/problems/champagne-tower) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0700-0799/0799.Champagne%20Tower/README_EN.md) + +## 题目描述 + + + +

    我们把玻璃杯摆成金字塔的形状,其中第一层有1个玻璃杯,第二层有2个,依次类推到第100层,每个玻璃杯(250ml)将盛有香槟。

    + +

    从顶层的第一个玻璃杯开始倾倒一些香槟,当顶层的杯子满了,任何溢出的香槟都会立刻等流量的流向左右两侧的玻璃杯。当左右两边的杯子也满了,就会等流量的流向它们左右两边的杯子,依次类推。(当最底层的玻璃杯满了,香槟会流到地板上)

    + +

    例如,在倾倒一杯香槟后,最顶层的玻璃杯满了。倾倒了两杯香槟后,第二层的两个玻璃杯各自盛放一半的香槟。在倒三杯香槟后,第二层的香槟满了 - 此时总共有三个满的玻璃杯。在倒第四杯后,第三层中间的玻璃杯盛放了一半的香槟,他两边的玻璃杯各自盛放了四分之一的香槟,如下图所示。

    + +

    + +

    现在当倾倒了非负整数杯香槟后,返回第 i 行 j 个玻璃杯所盛放的香槟占玻璃杯容积的比例(i 和 j都从0开始)。

    + +

     

    + +
    +示例 1:
    +输入: poured(倾倒香槟总杯数) = 1, query_glass(杯子的位置数) = 1, query_row(行数) = 1
    +输出: 0.0
    +解释: 我们在顶层(下标是(0,0))倒了一杯香槟后,没有溢出,因此所有在顶层以下的玻璃杯都是空的。
    +
    +示例 2:
    +输入: poured(倾倒香槟总杯数) = 2, query_glass(杯子的位置数) = 1, query_row(行数) = 1
    +输出: 0.5
    +解释: 我们在顶层(下标是(0,0)倒了两杯香槟后,有一杯量的香槟将从顶层溢出,位于(1,0)的玻璃杯和(1,1)的玻璃杯平分了这一杯香槟,所以每个玻璃杯有一半的香槟。
    +
    + +

    注意:

    + +
      +
    • poured 的范围[0, 10 ^ 9]
    • +
    • query_glass 和query_row 的范围 [0, 99]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0800.leetcode800 Similar RGB Color-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0800.leetcode800 Similar RGB Color-zh.md" new file mode 100644 index 00000000..99ab6a3b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0800.leetcode800 Similar RGB Color-zh.md" @@ -0,0 +1,63 @@ +# [800. 相似 RGB 颜色](https://leetcode-cn.com/problems/similar-rgb-color) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0800.Similar%20RGB%20Color/README_EN.md) + +## 题目描述 + + + +

    RGB 颜色用十六进制来表示的话,每个大写字母都代表了某个从 0 到 f 的 16 进制数。

    + +

    RGB 颜色 "#AABBCC" 可以简写成 "#ABC" 。例如,"#15c" 其实是 "#1155cc" 的简写。

    + +

    现在,假如我们分别定义两个颜色 "#ABCDEF" 和 "#UVWXYZ",则他们的相似度可以通过这个表达式 -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2 来计算。

    + +

    那么给定颜色 "#ABCDEF",请你返回一个与 #ABCDEF 最相似的 7 个字符代表的颜色,并且它是可以被简写形式表达的。(比如,可以表示成类似 "#XYZ" 的形式)

    + +
    示例 1:
    +输入:color = "#09f166"
    +输出:"#11ee66"
    +解释: 
    +因为相似度计算得出 -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73
    +这已经是所有可以简写的颜色中最相似的了
    +
    + +

    注意:

    + +
      +
    • color 是一个长度为 7 的字符串
    • +
    • color 是一个有效的 RGB 颜色:对于仍和 i > 0color[i] 都是一个在 0 到 f 范围的 16 进制数
    • +
    • 假如答案具有相同的(最大)相似度的话,都是可以被接受的
    • +
    • 所有输入、输出都必须使用小写字母,并且输出为 7 个字符
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0801.leetcode801 Minimum Swaps To Make Sequences Increasing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0801.leetcode801 Minimum Swaps To Make Sequences Increasing-zh.md" new file mode 100644 index 00000000..bfec3034 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0801.leetcode801 Minimum Swaps To Make Sequences Increasing-zh.md" @@ -0,0 +1,62 @@ +# [801. 使序列递增的最小交换次数](https://leetcode-cn.com/problems/minimum-swaps-to-make-sequences-increasing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0801.Minimum%20Swaps%20To%20Make%20Sequences%20Increasing/README_EN.md) + +## 题目描述 + + + +

    我们有两个长度相等且不为空的整型数组 A 和 B 。

    + +

    我们可以交换 A[i] 和 B[i] 的元素。注意这两个元素在各自的序列中应该处于相同的位置。

    + +

    在交换过一些元素之后,数组 A 和 B 都应该是严格递增的(数组严格递增的条件仅为A[0] < A[1] < A[2] < ... < A[A.length - 1])。

    + +

    给定数组 A 和 B ,请返回使得两个数组均保持严格递增状态的最小交换次数。假设给定的输入总是有效的。

    + +
    +示例:
    +输入: A = [1,3,5,4], B = [1,2,3,7]
    +输出: 1
    +解释: 
    +交换 A[3] 和 B[3] 后,两个数组如下:
    +A = [1, 3, 5, 7] , B = [1, 2, 3, 4]
    +两个数组均为严格递增的。
    + +

    注意:

    + +
      +
    • A, B 两个数组的长度总是相等的,且长度的范围为 [1, 1000]
    • +
    • A[i], B[i] 均为 [0, 2000]区间内的整数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0802.leetcode802 Find Eventual Safe States-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0802.leetcode802 Find Eventual Safe States-zh.md" new file mode 100644 index 00000000..8590e7fd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0802.leetcode802 Find Eventual Safe States-zh.md" @@ -0,0 +1,80 @@ +# [802. 找到最终的安全状态](https://leetcode-cn.com/problems/find-eventual-safe-states) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0802.Find%20Eventual%20Safe%20States/README_EN.md) + +## 题目描述 + + + +

    在有向图中,从某个节点和每个转向处开始出发,沿着图的有向边走。如果到达的节点是终点(即它没有连出的有向边),则停止。

    + +

    如果从起始节点出发,最后必然能走到终点,就认为起始节点是 最终安全 的。更具体地说,对于最终安全的起始节点而言,存在一个自然数 k无论选择沿哪条有向边行走 ,走了不到 k 步后必能停止在一个终点上。

    + +

    返回一个由图中所有最终安全的起始节点组成的数组作为答案。答案数组中的元素应当按 升序 排列。

    + +

    该有向图有 n 个节点,按 0n - 1 编号,其中 n 是 graph 的节点数。图以下述形式给出:graph[i] 是编号 j 节点的一个列表,满足 (i, j) 是图的一条有向边。

    + +

     

    + +
    +
    +

    示例 1:

    +Illustration of graph +
    +输入:graph = [[1,2],[2,3],[5],[0],[5],[],[]]
    +输出:[2,4,5,6]
    +解释:示意图如上。
    +
    + +

    示例 2:

    + +
    +输入:graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
    +输出:[4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == graph.length
    • +
    • 1 <= n <= 104
    • +
    • 0 <= graph[i].legnth <= n
    • +
    • graph[i] 按严格递增顺序排列。
    • +
    • 图中可能包含自环。
    • +
    • 图中边的数目在范围 [1, 4 * 104] 内。
    • +
    +
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0803.leetcode803 Bricks Falling When Hit-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0803.leetcode803 Bricks Falling When Hit-zh.md" new file mode 100644 index 00000000..91ed9cf4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0803.leetcode803 Bricks Falling When Hit-zh.md" @@ -0,0 +1,108 @@ +# [803. 打砖块](https://leetcode-cn.com/problems/bricks-falling-when-hit) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0803.Bricks%20Falling%20When%20Hit/README_EN.md) + +## 题目描述 + + + +

    有一个 m x n 的二元网格,其中 1 表示砖块,0 表示空白。砖块 稳定(不会掉落)的前提是:

    + +
      +
    • 一块砖直接连接到网格的顶部,或者
    • +
    • 至少有一块相邻(4 个方向之一)砖块 稳定 不会掉落时
    • +
    + +

    给你一个数组 hits ,这是需要依次消除砖块的位置。每当消除 hits[i] = (rowi, coli) 位置上的砖块时,对应位置的砖块(若存在)会消失,然后其他的砖块可能因为这一消除操作而掉落。一旦砖块掉落,它会立即从网格中消失(即,它不会落在其他稳定的砖块上)。

    + +

    返回一个数组 result ,其中 result[i] 表示第 i 次消除操作对应掉落的砖块数目。

    + +

    注意,消除可能指向是没有砖块的空白位置,如果发生这种情况,则没有砖块掉落。

    + +

     

    + +

    示例 1:

    + +
    +输入:grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
    +输出:[2]
    +解释:
    +网格开始为:
    +[[1,0,0,0],
    + [1,1,1,0]]
    +消除 (1,0) 处加粗的砖块,得到网格:
    +[[1,0,0,0]
    + [0,1,1,0]]
    +两个加粗的砖不再稳定,因为它们不再与顶部相连,也不再与另一个稳定的砖相邻,因此它们将掉落。得到网格:
    +[[1,0,0,0],
    + [0,0,0,0]]
    +因此,结果为 [2] 。
    +
    + +

    示例 2:

    + +
    +输入:grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
    +输出:[0,0]
    +解释:
    +网格开始为:
    +[[1,0,0,0],
    + [1,1,0,0]]
    +消除 (1,1) 处加粗的砖块,得到网格:
    +[[1,0,0,0],
    + [1,0,0,0]]
    +剩下的砖都很稳定,所以不会掉落。网格保持不变:
    +[[1,0,0,0], 
    + [1,0,0,0]]
    +接下来消除 (1,0) 处加粗的砖块,得到网格:
    +[[1,0,0,0],
    + [0,0,0,0]]
    +剩下的砖块仍然是稳定的,所以不会有砖块掉落。
    +因此,结果为 [0,0] 。
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • grid[i][j]01
    • +
    • 1 <= hits.length <= 4 * 104
    • +
    • hits[i].length == 2
    • +
    • 0 <= x<= m - 1
    • +
    • 0 <= yi <= n - 1
    • +
    • 所有 (xi, yi) 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0804.leetcode804 Unique Morse Code Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0804.leetcode804 Unique Morse Code Words-zh.md" new file mode 100644 index 00000000..1278d849 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0804.leetcode804 Unique Morse Code Words-zh.md" @@ -0,0 +1,71 @@ +# [804. 唯一摩尔斯密码词](https://leetcode-cn.com/problems/unique-morse-code-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0804.Unique%20Morse%20Code%20Words/README_EN.md) + +## 题目描述 + + + +

    国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。

    + +

    为了方便,所有26个英文字母对应摩尔斯密码表如下:

    + +
    [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    + +

    给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + ".-" + "-..." 字符串的结合)。我们将这样一个连接过程称作单词翻译。

    + +

    返回我们可以获得所有词不同单词翻译的数量。

    + +
    例如:
    +输入: words = ["gin", "zen", "gig", "msg"]
    +输出: 2
    +解释: 
    +各单词翻译如下:
    +"gin" -> "--...-."
    +"zen" -> "--...-."
    +"gig" -> "--...--."
    +"msg" -> "--...--."
    +
    +共有 2 种不同翻译, "--...-." 和 "--...--.".
    +
    + +

     

    + +

    注意:

    + +
      +
    • 单词列表words 的长度不会超过 100
    • +
    • 每个单词 words[i]的长度范围为 [1, 12]
    • +
    • 每个单词 words[i]只包含小写字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0805.leetcode805 Split Array With Same Average-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0805.leetcode805 Split Array With Same Average-zh.md" new file mode 100644 index 00000000..114e3200 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0805.leetcode805 Split Array With Same Average-zh.md" @@ -0,0 +1,57 @@ +# [805. 数组的均值分割](https://leetcode-cn.com/problems/split-array-with-same-average) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0805.Split%20Array%20With%20Same%20Average/README_EN.md) + +## 题目描述 + + + +

    给定的整数数组 A ,我们要将 A数组 中的每个元素移动到 B数组 或者 C数组中。(B数组和C数组在开始的时候都为空)

    + +

    返回true ,当且仅当在我们的完成这样的移动后,可使得B数组的平均值和C数组的平均值相等,并且B数组和C数组都不为空。

    + +
    +示例:
    +输入: 
    +[1,2,3,4,5,6,7,8]
    +输出: true
    +解释: 我们可以将数组分割为 [1,4,5,8] 和 [2,3,6,7], 他们的平均值都是4.5。
    +
    + +

    注意:

    + +
      +
    • A 数组的长度范围为 [1, 30].
    • +
    • A[i] 的数据范围为 [0, 10000].
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0806.leetcode806 Number of Lines To Write String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0806.leetcode806 Number of Lines To Write String-zh.md" new file mode 100644 index 00000000..72f1b056 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0806.leetcode806 Number of Lines To Write String-zh.md" @@ -0,0 +1,76 @@ +# [806. 写字符串需要的行数](https://leetcode-cn.com/problems/number-of-lines-to-write-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0806.Number%20of%20Lines%20To%20Write%20String/README_EN.md) + +## 题目描述 + + + +

    我们要把给定的字符串 S 从左到右写到每一行上,每一行的最大宽度为100个单位,如果我们在写某个字母的时候会使这行超过了100 个单位,那么我们应该把这个字母写到下一行。我们给定了一个数组 widths ,这个数组 widths[0] 代表 'a' 需要的单位, widths[1] 代表 'b' 需要的单位,..., widths[25] 代表 'z' 需要的单位。

    + +

    现在回答两个问题:至少多少行能放下S,以及最后一行使用的宽度是多少个单位?将你的答案作为长度为2的整数列表返回。

    + +
    +示例 1:
    +输入: 
    +widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
    +S = "abcdefghijklmnopqrstuvwxyz"
    +输出: [3, 60]
    +解释: 
    +所有的字符拥有相同的占用单位10。所以书写所有的26个字母,
    +我们需要2个整行和占用60个单位的一行。
    +
    + +
    +示例 2:
    +输入: 
    +widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
    +S = "bbbcccdddaaa"
    +输出: [2, 4]
    +解释: 
    +除去字母'a'所有的字符都是相同的单位10,并且字符串 "bbbcccdddaa" 将会覆盖 9 * 10 + 2 * 4 = 98 个单位.
    +最后一个字母 'a' 将会被写到第二行,因为第一行只剩下2个单位了。
    +所以,这个答案是2行,第二行有4个单位宽度。
    +
    + +

     

    + +

    注:

    + +
      +
    • 字符串 S 的长度在 [1, 1000] 的范围。
    • +
    • S 只包含小写字母。
    • +
    • widths 是长度为 26的数组。
    • +
    • widths[i] 值的范围在 [2, 10]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0807.leetcode807 Max Increase to Keep City Skyline-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0807.leetcode807 Max Increase to Keep City Skyline-zh.md" new file mode 100644 index 00000000..af826081 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0807.leetcode807 Max Increase to Keep City Skyline-zh.md" @@ -0,0 +1,74 @@ +# [807. 保持城市天际线](https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0807.Max%20Increase%20to%20Keep%20City%20Skyline/README_EN.md) + +## 题目描述 + + + +

    在二维数组grid中,grid[i][j]代表位于某处的建筑物的高度。 我们被允许增加任何数量(不同建筑物的数量可能不同)的建筑物的高度。 高度 0 也被认为是建筑物。

    + +

    最后,从新数组的所有四个方向(即顶部,底部,左侧和右侧)观看的“天际线”必须与原始数组的天际线相同。 城市的天际线是从远处观看时,由所有建筑物形成的矩形的外部轮廓。 请看下面的例子。

    + +

    建筑物高度可以增加的最大总和是多少?

    + +
    +例子:
    +输入: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
    +输出: 35
    +解释: 
    +The grid is:
    +[ [3, 0, 8, 4], 
    +  [2, 4, 5, 7],
    +  [9, 2, 6, 3],
    +  [0, 3, 1, 0] ]
    +
    +从数组竖直方向(即顶部,底部)看“天际线”是:[9, 4, 8, 7]
    +从水平水平方向(即左侧,右侧)看“天际线”是:[8, 7, 9, 3]
    +
    +在不影响天际线的情况下对建筑物进行增高后,新数组如下:
    +
    +gridNew = [ [8, 4, 8, 7],
    +            [7, 4, 7, 7],
    +            [9, 4, 8, 7],
    +            [3, 3, 3, 3] ]
    +
    + +

    说明:

    + +
      +
    • 1 < grid.length = grid[0].length <= 50
    • +
    •  grid[i][j] 的高度范围是: [0, 100]
    • +
    • 一座建筑物占据一个grid[i][j]:换言之,它们是 1 x 1 x grid[i][j] 的长方体。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0808.leetcode808 Soup Servings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0808.leetcode808 Soup Servings-zh.md" new file mode 100644 index 00000000..a5c9862e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0808.leetcode808 Soup Servings-zh.md" @@ -0,0 +1,71 @@ +# [808. 分汤](https://leetcode-cn.com/problems/soup-servings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0808.Soup%20Servings/README_EN.md) + +## 题目描述 + + + +

    有 A 和 B 两种类型的汤。一开始每种类型的汤有 N 毫升。有四种分配操作:

    + +
      +
    1. 提供 100ml 的汤A 和 0ml 的汤B。
    2. +
    3. 提供 75ml 的汤A 和 25ml 的汤B。
    4. +
    5. 提供 50ml 的汤A 和 50ml 的汤B。
    6. +
    7. 提供 25ml 的汤A 和 75ml 的汤B。
    8. +
    + +

    当我们把汤分配给某人之后,汤就没有了。每个回合,我们将从四种概率同为0.25的操作中进行分配选择。如果汤的剩余量不足以完成某次操作,我们将尽可能分配。当两种类型的汤都分配完时,停止操作。

    + +

    注意不存在先分配100 ml汤B的操作。

    + +

    需要返回的值: 汤A先分配完的概率 + 汤A和汤B同时分配完的概率 / 2。

    + +
    +示例:
    +输入: N = 50
    +输出: 0.625
    +解释:
    +如果我们选择前两个操作A将首先变为空。对于第三个操作,A和B会同时变为空。对于第四个操作,B将首先变为空。
    +所以A变为空的总概率加上A和B同时变为空的概率的一半是 0.25 *(1 + 1 + 0.5 + 0)= 0.625。
    +
    + +

    注释:

    + +
      +
    • 0 <= N <= 10^9
    • +
    • +

      返回值在 10^-6 的范围将被认为是正确的。

      +
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0809.leetcode809 Expressive Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0809.leetcode809 Expressive Words-zh.md" new file mode 100644 index 00000000..253b71cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0809.leetcode809 Expressive Words-zh.md" @@ -0,0 +1,71 @@ +# [809. 情感丰富的文字](https://leetcode-cn.com/problems/expressive-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0809.Expressive%20Words/README_EN.md) + +## 题目描述 + + + +

    有时候人们会用重复写一些字母来表示额外的感受,比如 "hello" -> "heeellooo", "hi" -> "hiii"。我们将相邻字母都相同的一串字符定义为相同字母组,例如:"h", "eee", "ll", "ooo"。

    + +

    对于一个给定的字符串 S ,如果另一个单词能够通过将一些字母组扩张从而使其和 S 相同,我们将这个单词定义为可扩张的(stretchy)。扩张操作定义如下:选择一个字母组(包含字母 c ),然后往其中添加相同的字母 c 使其长度达到 3 或以上。

    + +

    例如,以 "hello" 为例,我们可以对字母组 "o" 扩张得到 "hellooo",但是无法以同样的方法得到 "helloo" 因为字母组 "oo" 长度小于 3。此外,我们可以进行另一种扩张 "ll" -> "lllll" 以获得 "helllllooo"。如果 S = "helllllooo",那么查询词 "hello" 是可扩张的,因为可以对它执行这两种扩张操作使得 query = "hello" -> "hellooo" -> "helllllooo" = S

    + +

    输入一组查询单词,输出其中可扩张的单词数量。

    + +

     

    + +

    示例:

    + +
    +输入: 
    +S = "heeellooo"
    +words = ["hello", "hi", "helo"]
    +输出:1
    +解释:
    +我们能通过扩张 "hello" 的 "e" 和 "o" 来得到 "heeellooo"。
    +我们不能通过扩张 "helo" 来得到 "heeellooo" 因为 "ll" 的长度小于 3 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= len(S) <= 100
    • +
    • 0 <= len(words) <= 100
    • +
    • 0 <= len(words[i]) <= 100
    • +
    • S 和所有在 words 中的单词都只由小写字母组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0810.leetcode810 Chalkboard XOR Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0810.leetcode810 Chalkboard XOR Game-zh.md" new file mode 100644 index 00000000..1115b1c9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0810.leetcode810 Chalkboard XOR Game-zh.md" @@ -0,0 +1,66 @@ +# [810. 黑板异或游戏](https://leetcode-cn.com/problems/chalkboard-xor-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0810.Chalkboard%20XOR%20Game/README_EN.md) + +## 题目描述 + + + +

    黑板上写着一个非负整数数组 nums[i] 。Alice 和 Bob 轮流从黑板上擦掉一个数字,Alice 先手。如果擦除一个数字后,剩余的所有数字按位异或运算得出的结果等于 0 的话,当前玩家游戏失败。 (另外,如果只剩一个数字,按位异或运算得到它本身;如果无数字剩余,按位异或运算结果为 0。)

    + +

    换种说法就是,轮到某个玩家时,如果当前黑板上所有数字按位异或运算结果等于 0,这个玩家获胜。

    + +

    假设两个玩家每步都使用最优解,当且仅当 Alice 获胜时返回 true

    + +

     

    + +

    示例:

    + +
    +输入: nums = [1, 1, 2]
    +输出: false
    +解释: 
    +Alice 有两个选择: 擦掉数字 1 或 2。
    +如果擦掉 1, 数组变成 [1, 2]。剩余数字按位异或得到 1 XOR 2 = 3。那么 Bob 可以擦掉任意数字,因为 Alice 会成为擦掉最后一个数字的人,她总是会输。
    +如果 Alice 擦掉 2,那么数组变成[1, 1]。剩余数字按位异或得到 1 XOR 1 = 0。Alice 仍然会输掉游戏。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 1000
    • +
    • 0 <= nums[i] <= 2^16
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0811.leetcode811 Subdomain Visit Count-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0811.leetcode811 Subdomain Visit Count-zh.md" new file mode 100644 index 00000000..ca4121b1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0811.leetcode811 Subdomain Visit Count-zh.md" @@ -0,0 +1,103 @@ +# [811. 子域名访问计数](https://leetcode-cn.com/problems/subdomain-visit-count) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0811.Subdomain%20Visit%20Count/README_EN.md) + +## 题目描述 + + + +

    一个网站域名,如"discuss.leetcode.com",包含了多个子域名。作为顶级域名,常用的有"com",下一级则有"leetcode.com",最低的一级为"discuss.leetcode.com"。当我们访问域名"discuss.leetcode.com"时,也同时访问了其父域名"leetcode.com"以及顶级域名 "com"。

    + +

    给定一个带访问次数和域名的组合,要求分别计算每个域名被访问的次数。其格式为访问次数+空格+地址,例如:"9001 discuss.leetcode.com"。

    + +

    接下来会给出一组访问次数和域名组合的列表cpdomains 。要求解析出所有域名的访问次数,输出格式和输入格式相同,不限定先后顺序。

    + +
    +示例 1:
    +输入: 
    +["9001 discuss.leetcode.com"]
    +输出: 
    +["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
    +说明: 
    +例子中仅包含一个网站域名:"discuss.leetcode.com"。按照前文假设,子域名"leetcode.com"和"com"都会被访问,所以它们都被访问了9001次。
    +
    + +
    +示例 2
    +输入: 
    +["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
    +输出: 
    +["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
    +说明: 
    +按照假设,会访问"google.mail.com" 900次,"yahoo.com" 50次,"intel.mail.com" 1次,"wiki.org" 5次。
    +而对于父域名,会访问"mail.com" 900+1 = 901次,"com" 900 + 50 + 1 = 951次,和 "org" 5 次。
    +
    + +

    注意事项:

    + +
      +
    •  cpdomains 的长度小于 100
    • +
    • 每个域名的长度小于100
    • +
    • 每个域名地址包含一个或两个"."符号。
    • +
    • 输入中任意一个域名的访问次数都小于10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def subdomainVisits(self, cpdomains: List[str]) -> List[str]: + domains = collections.Counter() + for item in cpdomains: + count, domain = item.split() + count = int(count) + subs = domain.split('.') + for i in range(len(subs)): + key = '.'.join(subs[i:]) + domains[key] += count + return [f'{cnt} {domain}' for domain, cnt in domains.items()] +``` + +### **Java** + + + +```java +class Solution { + public List subdomainVisits(String[] cpdomains) { + Map domains = new HashMap<>(); + for (String domain : cpdomains) { + String[] t = domain.split(" "); + int count = Integer.parseInt(t[0]); + String[] subs = t[1].split("\\."); + String cur = ""; + for (int i = subs.length - 1; i >= 0; --i) { + cur = subs[i] + (i == subs.length - 1 ? "" : ".") + cur; + domains.put(cur, domains.getOrDefault(cur, 0) + count); + } + } + List res = new ArrayList<>(); + domains.forEach((domain, count) -> { + res.add(count + " " + domain); + }); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0812.leetcode812 Largest Triangle Area-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0812.leetcode812 Largest Triangle Area-zh.md" new file mode 100644 index 00000000..42148f9b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0812.leetcode812 Largest Triangle Area-zh.md" @@ -0,0 +1,59 @@ +# [812. 最大三角形面积](https://leetcode-cn.com/problems/largest-triangle-area) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0812.Largest%20Triangle%20Area/README_EN.md) + +## 题目描述 + + + +

    给定包含多个点的集合,从其中取三个点组成三角形,返回能组成的最大三角形的面积。

    + +
    +示例:
    +输入: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
    +输出: 2
    +解释: 
    +这五个点如下图所示。组成的橙色三角形是最大的,面积为2。
    +
    + +

    + +

    注意:

    + +
      +
    • 3 <= points.length <= 50.
    • +
    • 不存在重复的点。
    • +
    •  -50 <= points[i][j] <= 50.
    • +
    • 结果误差值在 10^-6 以内都认为是正确答案。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0813.leetcode813 Largest Sum of Averages-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0813.leetcode813 Largest Sum of Averages-zh.md" new file mode 100644 index 00000000..23ebeb7c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0813.leetcode813 Largest Sum of Averages-zh.md" @@ -0,0 +1,63 @@ +# [813. 最大平均值和的分组](https://leetcode-cn.com/problems/largest-sum-of-averages) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0813.Largest%20Sum%20of%20Averages/README_EN.md) + +## 题目描述 + + + +

    我们将给定的数组 A 分成 K 个相邻的非空子数组 ,我们的分数由每个子数组内的平均值的总和构成。计算我们所能得到的最大分数是多少。

    + +

    注意我们必须使用 A 数组中的每一个数进行分组,并且分数不一定需要是整数。

    + +
    +示例:
    +输入: 
    +A = [9,1,2,3,9]
    +K = 3
    +输出: 20
    +解释: 
    +A 的最优分组是[9], [1, 2, 3], [9]. 得到的分数是 9 + (1 + 2 + 3) / 3 + 9 = 20.
    +我们也可以把 A 分成[9, 1], [2], [3, 9].
    +这样的分组得到的分数为 5 + 2 + 6 = 13, 但不是最大值.
    +
    + +

    说明:

    + +
      +
    • 1 <= A.length <= 100.
    • +
    • 1 <= A[i] <= 10000.
    • +
    • 1 <= K <= A.length.
    • +
    • 答案误差在 10^-6 内被视为是正确的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0814.leetcode814 Binary Tree Pruning-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0814.leetcode814 Binary Tree Pruning-zh.md" new file mode 100644 index 00000000..5309d053 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0814.leetcode814 Binary Tree Pruning-zh.md" @@ -0,0 +1,81 @@ +# [814. 二叉树剪枝](https://leetcode-cn.com/problems/binary-tree-pruning) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0814.Binary%20Tree%20Pruning/README_EN.md) + +## 题目描述 + + + +

    给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。

    + +

    返回移除了所有不包含 1 的子树的原二叉树。

    + +

    ( 节点 X 的子树为 X 本身,以及所有 X 的后代。)

    + +
    +示例1:
    +输入: [1,null,0,0,1]
    +输出: [1,null,0,null,1]
    + 
    +解释: 
    +只有红色节点满足条件“所有不包含 1 的子树”。
    +右图为返回的答案。
    +
    +
    +
    + +
    +示例2:
    +输入: [1,0,1,0,0,0,1]
    +输出: [1,null,1,null,1]
    +
    +
    +
    +
    + +
    +示例3:
    +输入: [1,1,0,1,1,0,1,0]
    +输出: [1,1,0,1,1,null,1]
    +
    +
    +
    +
    + +

    说明:

    + +
      +
    • 给定的二叉树最多有 100 个节点。
    • +
    • 每个节点的值只会为 0 或 1 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0815.leetcode815 Bus Routes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0815.leetcode815 Bus Routes-zh.md" new file mode 100644 index 00000000..13b562fb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0815.leetcode815 Bus Routes-zh.md" @@ -0,0 +1,78 @@ +# [815. 公交路线](https://leetcode-cn.com/problems/bus-routes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0815.Bus%20Routes/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 routes ,表示一系列公交线路,其中每个 routes[i] 表示一条公交线路,第 i 辆公交车将会在上面循环行驶。

    + +
      +
    • 例如,路线 routes[0] = [1, 5, 7] 表示第 0 辆公交车会一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... 这样的车站路线行驶。
    • +
    + +

    现在从 source 车站出发(初始时不在公交车上),要前往 target 车站。 期间仅可乘坐公交车。

    + +

    求出 最少乘坐的公交车数量 。如果不可能到达终点车站,返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:routes = [[1,2,7],[3,6,7]], source = 1, target = 6
    +输出:2
    +解释:最优策略是先乘坐第一辆公交车到达车站 7 , 然后换乘第二辆公交车到车站 6 。 
    +
    + +

    示例 2:

    + +
    +输入:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= routes.length <= 500.
    • +
    • 1 <= routes[i].length <= 105
    • +
    • routes[i] 中的所有值 互不相同
    • +
    • sum(routes[i].length) <= 105
    • +
    • 0 <= routes[i][j] < 106
    • +
    • 0 <= source, target < 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0816.leetcode816 Ambiguous Coordinates-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0816.leetcode816 Ambiguous Coordinates-zh.md" new file mode 100644 index 00000000..afeec2f8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0816.leetcode816 Ambiguous Coordinates-zh.md" @@ -0,0 +1,85 @@ +# [816. 模糊坐标](https://leetcode-cn.com/problems/ambiguous-coordinates) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0816.Ambiguous%20Coordinates/README_EN.md) + +## 题目描述 + + + +

    我们有一些二维坐标,如 "(1, 3)" 或 "(2, 0.5)",然后我们移除所有逗号,小数点和空格,得到一个字符串S。返回所有可能的原始字符串到一个列表中。

    + +

    原始的坐标表示法不会存在多余的零,所以不会出现类似于"00", "0.0", "0.00", "1.0", "001", "00.01"或一些其他更小的数来表示坐标。此外,一个小数点前至少存在一个数,所以也不会出现“.1”形式的数字。

    + +

    最后返回的列表可以是任意顺序的。而且注意返回的两个数字中间(逗号之后)都有一个空格。

    + +

     

    + +
    +示例 1:
    +输入: "(123)"
    +输出: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]
    +
    + +
    +示例 2:
    +输入: "(00011)"
    +输出:  ["(0.001, 1)", "(0, 0.011)"]
    +解释: 
    +0.0, 00, 0001 或 00.01 是不被允许的。
    +
    + +
    +示例 3:
    +输入: "(0123)"
    +输出: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"]
    +
    + +
    +示例 4:
    +输入: "(100)"
    +输出: [(10, 0)]
    +解释: 
    +1.0 是不被允许的。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 4 <= S.length <= 12.
    • +
    • S[0] = "(", S[S.length - 1] = ")", 且字符串 S 中的其他元素都是数字。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0817.leetcode817 Linked List Components-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0817.leetcode817 Linked List Components-zh.md" new file mode 100644 index 00000000..d3d6a3dd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0817.leetcode817 Linked List Components-zh.md" @@ -0,0 +1,131 @@ +# [817. 链表组件](https://leetcode-cn.com/problems/linked-list-components) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0817.Linked%20List%20Components/README_EN.md) + +## 题目描述 + + + +

    给定链表头结点 head,该链表上的每个结点都有一个 唯一的整型值

    + +

    同时给定列表 G,该列表是上述链表中整型值的一个子集。

    + +

    返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。

    + +

     

    + +

    示例 1:

    + +
    输入: 
    +head: 0->1->2->3
    +G = [0, 1, 3]
    +输出: 2
    +解释: 
    +链表中,0 和 1 是相连接的,且 G 中不包含 2,所以 [0, 1] 是 G 的一个组件,同理 [3] 也是一个组件,故返回 2。
    + +

    示例 2:

    + +
    输入: 
    +head: 0->1->2->3->4
    +G = [0, 3, 1, 4]
    +输出: 2
    +解释: 
    +链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1] 和 [3, 4] 是两个组件,故返回 2。
    + +

     

    + +

    提示:

    + +
      +
    • 如果 N 是给定链表 head 的长度,1 <= N <= 10000
    • +
    • 链表中每个结点的值所在范围为 [0, N - 1]
    • +
    • 1 <= G.length <= 10000
    • +
    • G 是链表中所有结点的值的一个子集.
    • +
    + +## 解法 + + + +定义 pre 表示是否可加 1,初始为 true。 + +遍历链表各个结点: + +- 若当前结点值在 nums 中,并且当前为可加 1 的状态,则 `res++`,并且将 pre 状态置为 false; +- 若当前结点值不在 nums 中,则将 pre 置为 true,表示可加 1。 + +最后返回 res 即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def numComponents(self, head: ListNode, nums: List[int]) -> int: + s = set(nums) + res, pre = 0, True + while head: + if head.val in s: + if pre: + res += 1 + pre = False + else: + pre = True + head = head.next + return res +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int numComponents(ListNode head, int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + s.add(num); + } + int res = 0; + boolean pre = true; + while (head != null) { + if (s.contains(head.val)) { + if (pre) { + ++res; + pre = false; + } + } else { + pre = true; + } + head = head.next; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0818.leetcode818 Race Car-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0818.leetcode818 Race Car-zh.md" new file mode 100644 index 00000000..de237d4d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0818.leetcode818 Race Car-zh.md" @@ -0,0 +1,74 @@ +# [818. 赛车](https://leetcode-cn.com/problems/race-car) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0818.Race%20Car/README_EN.md) + +## 题目描述 + + + +

    你的赛车起始停留在位置 0,速度为 +1,正行驶在一个无限长的数轴上。(车也可以向负数方向行驶。)

    + +

    你的车会根据一系列由 A(加速)和 R(倒车)组成的指令进行自动驾驶 。

    + +

    当车得到指令 "A" 时, 将会做出以下操作: position += speed, speed *= 2

    + +

    当车得到指令 "R" 时, 将会做出以下操作:如果当前速度是正数,则将车速调整为 speed = -1 ;否则将车速调整为 speed = 1。  (当前所处位置不变。)

    + +

    例如,当得到一系列指令 "AAR" 后, 你的车将会走过位置 0->1->3->3,并且速度变化为 1->2->4->-1。

    + +

    现在给定一个目标位置,请给出能够到达目标位置的最短指令列表的长度

    + +
    示例 1:
    +输入: 
    +target = 3
    +输出: 2
    +解释: 
    +最短指令列表为 "AA"
    +位置变化为 0->1->3
    +
    + +
    示例 2:
    +输入: 
    +target = 6
    +输出: 5
    +解释: 
    +最短指令列表为 "AAARA"
    +位置变化为 0->1->3->7->7->6
    +
    + +

    说明:

    + +
      +
    • 1 <= target(目标位置) <= 10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0819.leetcode819 Most Common Word-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0819.leetcode819 Most Common Word-zh.md" new file mode 100644 index 00000000..e95eaf3f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0819.leetcode819 Most Common Word-zh.md" @@ -0,0 +1,108 @@ +# [819. 最常见的单词](https://leetcode-cn.com/problems/most-common-word) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0819.Most%20Common%20Word/README_EN.md) + +## 题目描述 + + + +

    给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。

    + +

    题目保证至少有一个词不在禁用列表中,而且答案唯一。

    + +

    禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。

    + +

     

    + +

    示例:

    + +
    输入: 
    +paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
    +banned = ["hit"]
    +输出: "ball"
    +解释: 
    +"hit" 出现了3次,但它是一个禁用的单词。
    +"ball" 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。 
    +注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 "ball,"), 
    +"hit"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= 段落长度 <= 1000
    • +
    • 0 <= 禁用单词个数 <= 100
    • +
    • 1 <= 禁用单词长度 <= 10
    • +
    • 答案是唯一的, 且都是小写字母 (即使在 paragraph 里是大写的,即使是一些特定的名词,答案都是小写的。)
    • +
    • paragraph 只包含字母、空格和下列标点符号!?',;.
    • +
    • 不存在没有连字符或者带有连字符的单词。
    • +
    • 单词里只包含字母,不会出现省略号或者其他标点符号。
    • +
    + +## 解法 + + + +“正则 + 计数器”实现。 + + + +### **Python3** + + + +```python +class Solution: + def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: + paragraph = collections.Counter(re.findall('[a-z]+', paragraph.lower())) + banned_words = set(banned) + for word, _ in paragraph.most_common(): + if word not in banned_words: + return word +``` + +### **Java** + + + +```java +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class Solution { + public String mostCommonWord(String paragraph, String[] banned) { + Set bannedWords = new HashSet<>(); + for (String word : banned) { + bannedWords.add(word); + } + Map counter = new HashMap<>(); + Matcher matcher = Pattern.compile("[a-z]+").matcher(paragraph.toLowerCase()); + while (matcher.find()) { + String word = matcher.group(); + if (bannedWords.contains(word)) { + continue; + } + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + int max = Integer.MIN_VALUE; + String res = null; + for (Map.Entry entry : counter.entrySet()) { + if (entry.getValue() > max) { + max = entry.getValue(); + res = entry.getKey(); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0820.leetcode820 Short Encoding of Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0820.leetcode820 Short Encoding of Words-zh.md" new file mode 100644 index 00000000..7421a0e4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0820.leetcode820 Short Encoding of Words-zh.md" @@ -0,0 +1,79 @@ +# [820. 单词的压缩编码](https://leetcode-cn.com/problems/short-encoding-of-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0820.Short%20Encoding%20of%20Words/README_EN.md) + +## 题目描述 + + + +

    单词数组 words有效编码 由任意助记字符串 s 和下标数组 indices 组成,且满足:

    + +
      +
    • words.length == indices.length
    • +
    • 助记字符串 s'#' 字符结尾
    • +
    • 对于每个下标 indices[i]s 的一个从 indices[i] 开始、到下一个 '#' 字符结束(但不包括 '#')的 子字符串 恰好与 words[i] 相等
    • +
    + +

    给你一个单词数组 words ,返回成功对 words 进行编码的最小助记字符串 s 的长度 。

    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["time", "me", "bell"]
    +输出:10
    +解释:一组有效编码为 s = "time#bell#" 和 indices = [0, 2, 5] 。
    +words[0] = "time" ,s 开始于 indices[0] = 0 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
    +words[1] = "me" ,s 开始于 indices[1] = 2 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
    +words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
    +
    + +

    示例 2:

    + +
    +输入:words = ["t"]
    +输出:2
    +解释:一组有效编码为 s = "t#" 和 indices = [0] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 2000
    • +
    • 1 <= words[i].length <= 7
    • +
    • words[i] 仅由小写字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0821.leetcode821 Shortest Distance to a Character-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0821.leetcode821 Shortest Distance to a Character-zh.md" new file mode 100644 index 00000000..d1653c75 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0821.leetcode821 Shortest Distance to a Character-zh.md" @@ -0,0 +1,74 @@ +# [821. 字符的最短距离](https://leetcode-cn.com/problems/shortest-distance-to-a-character) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0821.Shortest%20Distance%20to%20a%20Character/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个字符 c ,且 cs 中出现过的字符。

    + +

    返回一个整数数组 answer ,其中 answer.length == s.lengthanswer[i]s 中从下标 i 到离它 最近 的字符 c距离

    + +

    两个下标 ij 之间的 距离abs(i - j) ,其中 abs 是绝对值函数。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "loveleetcode", c = "e"
    +输出:[3,2,1,0,1,0,0,1,2,2,1,0]
    +解释:字符 'e' 出现在下标 3、5、6 和 11 处(下标从 0 开始计数)。
    +距下标 0 最近的 'e' 出现在下标 3 ,所以距离为 abs(0 - 3) = 3 。
    +距下标 1 最近的 'e' 出现在下标 3 ,所以距离为 abs(1 - 3) = 3 。
    +对于下标 4 ,出现在下标 3 和下标 5 处的 'e' 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1 。
    +距下标 8 最近的 'e' 出现在下标 6 ,所以距离为 abs(8 - 6) = 2 。
    +
    + +

    示例 2:

    + +
    +输入:s = "aaab", c = "b"
    +输出:[3,2,1,0]
    +
    + +

     

    +提示: + +
      +
    • 1 <= s.length <= 104
    • +
    • s[i]c 均为小写英文字母
    • +
    • 题目数据保证 cs 中至少出现一次
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0822.leetcode822 Card Flipping Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0822.leetcode822 Card Flipping Game-zh.md" new file mode 100644 index 00000000..48280afb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0822.leetcode822 Card Flipping Game-zh.md" @@ -0,0 +1,68 @@ +# [822. 翻转卡片游戏](https://leetcode-cn.com/problems/card-flipping-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0822.Card%20Flipping%20Game/README_EN.md) + +## 题目描述 + + + +

    在桌子上有 N 张卡片,每张卡片的正面和背面都写着一个正数(正面与背面上的数有可能不一样)。

    + +

    我们可以先翻转任意张卡片,然后选择其中一张卡片。

    + +

    如果选中的那张卡片背面的数字 X 与任意一张卡片的正面的数字都不同,那么这个数字是我们想要的数字。

    + +

    哪个数是这些想要的数字中最小的数(找到这些数中的最小值)呢?如果没有一个数字符合要求的,输出 0。

    + +

    其中, fronts[i] 和 backs[i] 分别代表第 i 张卡片的正面和背面的数字。

    + +

    如果我们通过翻转卡片来交换正面与背面上的数,那么当初在正面的数就变成背面的数,背面的数就变成正面的数。

    + +

    示例:

    + +
    +输入:fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
    +输出:2
    +解释:假设我们翻转第二张卡片,那么在正面的数变成了 [1,3,4,4,7] , 背面的数变成了 [1,2,4,1,3]。
    +接着我们选择第二张卡片,因为现在该卡片的背面的数是 2,2 与任意卡片上正面的数都不同,所以 2 就是我们想要的数字。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= fronts.length == backs.length <= 1000
    2. +
    3. 1 <= fronts[i] <= 2000
    4. +
    5. 1 <= backs[i] <= 2000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0823.leetcode823 Binary Trees With Factors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0823.leetcode823 Binary Trees With Factors-zh.md" new file mode 100644 index 00000000..3742ebe2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0823.leetcode823 Binary Trees With Factors-zh.md" @@ -0,0 +1,71 @@ +# [823. 带因子的二叉树](https://leetcode-cn.com/problems/binary-trees-with-factors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0823.Binary%20Trees%20With%20Factors/README_EN.md) + +## 题目描述 + + + +

    给出一个含有不重复整数元素的数组,每个整数均大于 1。

    + +

    我们用这些整数来构建二叉树,每个整数可以使用任意次数。

    + +

    其中:每个非叶结点的值应等于它的两个子结点的值的乘积。

    + +

    满足条件的二叉树一共有多少个?返回的结果应模除 10 ** 9 + 7

    + +

     

    + +

    示例 1:

    + +
    +输入: A = [2, 4]
    +输出: 3
    +解释: 我们可以得到这些二叉树: [2], [4], [4, 2, 2]
    + +

    示例 2:

    + +
    +输入: A = [2, 4, 5, 10]
    +输出: 7
    +解释: 我们可以得到这些二叉树: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 1000.
    2. +
    3. 2 <= A[i] <= 10 ^ 9.
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0824.leetcode824 Goat Latin-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0824.leetcode824 Goat Latin-zh.md" new file mode 100644 index 00000000..66f6247b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0824.leetcode824 Goat Latin-zh.md" @@ -0,0 +1,78 @@ +# [824. 山羊拉丁文](https://leetcode-cn.com/problems/goat-latin) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0824.Goat%20Latin/README_EN.md) + +## 题目描述 + + + +

    给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。

    + +

    我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。

    + +

    山羊拉丁文的规则如下:

    + +
      +
    • 如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"
      + 例如,单词"apple"变为"applema"
    • +
      +
    • 如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"
      + 例如,单词"goat"变为"oatgma"
    • +
      +
    • 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从1开始。
      + 例如,在第一个单词后添加"a",在第二个单词后添加"aa",以此类推。
    • +
    + +

    返回将 S 转换为山羊拉丁文后的句子。

    + +

    示例 1:

    + +
    +输入: "I speak Goat Latin"
    +输出: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
    +
    + +

    示例 2:

    + +
    +输入: "The quick brown fox jumped over the lazy dog"
    +输出: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
    +
    + +

    说明:

    + +
      +
    • S 中仅包含大小写字母和空格。单词间有且仅有一个空格。
    • +
    • 1 <= S.length <= 150
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0825.leetcode825 Friends Of Appropriate Ages-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0825.leetcode825 Friends Of Appropriate Ages-zh.md" new file mode 100644 index 00000000..305efea8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0825.leetcode825 Friends Of Appropriate Ages-zh.md" @@ -0,0 +1,88 @@ +# [825. 适龄的朋友](https://leetcode-cn.com/problems/friends-of-appropriate-ages) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0825.Friends%20Of%20Appropriate%20Ages/README_EN.md) + +## 题目描述 + + + +

    人们会互相发送好友请求,现在给定一个包含有他们年龄的数组,ages[i] 表示第 i 个人的年龄。

    + +

    当满足以下任一条件时,A 不能给 B(A、B不为同一人)发送好友请求:

    + +
      +
    • age[B] <= 0.5 * age[A] + 7
    • +
    • age[B] > age[A]
    • +
    • age[B] > 100 && age[A] < 100
    • +
    + +

    否则,A 可以给 B 发送好友请求。

    + +

    注意如果 A 向 B 发出了请求,不等于 B 也一定会向 A 发出请求。而且,人们不会给自己发送好友请求。 

    + +

    求总共会发出多少份好友请求?

    + +

     

    + +

    示例 1:

    + +
    +输入:[16,16]
    +输出:2
    +解释:二人可以互发好友申请。
    +
    + +

    示例 2:

    + +
    +输入:[16,17,18]
    +输出:2
    +解释:好友请求可产生于 17 -> 16, 18 -> 17.
    + +

    示例 3:

    + +
    +输入:[20,30,100,110,120]
    +输出:3
    +解释:好友请求可产生于 110 -> 100, 120 -> 110, 120 -> 100.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= ages.length <= 20000
    • +
    • 1 <= ages[i] <= 120
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0826.leetcode826 Most Profit Assigning Work-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0826.leetcode826 Most Profit Assigning Work-zh.md" new file mode 100644 index 00000000..81ad120f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0826.leetcode826 Most Profit Assigning Work-zh.md" @@ -0,0 +1,66 @@ +# [826. 安排工作以达到最大收益](https://leetcode-cn.com/problems/most-profit-assigning-work) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0826.Most%20Profit%20Assigning%20Work/README_EN.md) + +## 题目描述 + + + +

    有一些工作:difficulty[i] 表示第 i 个工作的难度,profit[i] 表示第 i 个工作的收益。

    + +

    现在我们有一些工人。worker[i] 是第 i 个工人的能力,即该工人只能完成难度小于等于 worker[i] 的工作。

    + +

    每一个工人都最多只能安排一个工作,但是一个工作可以完成多次。

    + +

    举个例子,如果 3 个工人都尝试完成一份报酬为 1 的同样工作,那么总收益为 $3。如果一个工人不能完成任何工作,他的收益为 $0 。

    + +

    我们能得到的最大收益是多少?

    + +

     

    + +

    示例:

    + +
    输入: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
    +输出: 100 
    +解释: 工人被分配的工作难度是 [4,4,6,6] ,分别获得 [20,20,30,30] 的收益。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= difficulty.length = profit.length <= 10000
    • +
    • 1 <= worker.length <= 10000
    • +
    • difficulty[i], profit[i], worker[i]  的范围是 [1, 10^5]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0827.leetcode827 Making A Large Island-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0827.leetcode827 Making A Large Island-zh.md" new file mode 100644 index 00000000..8027dbef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0827.leetcode827 Making A Large Island-zh.md" @@ -0,0 +1,71 @@ +# [827. 最大人工岛](https://leetcode-cn.com/problems/making-a-large-island) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0827.Making%20A%20Large%20Island/README_EN.md) + +## 题目描述 + + + +

    在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地。

    + +

    进行填海之后,地图上最大的岛屿面积是多少?(上、下、左、右四个方向相连的 1 可形成岛屿)

    + +

    示例 1:

    + +
    +输入: [[1, 0], [0, 1]]
    +输出: 3
    +解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。
    +
    + +

    示例 2:

    + +
    +输入: [[1, 1], [1, 0]]
    +输出: 4
    +解释: 将一格0变成1,岛屿的面积扩大为 4。
    + +

    示例 3:

    + +
    +输入: [[1, 1], [1, 1]]
    +输出: 4
    +解释: 没有0可以让我们变成1,面积依然为 4。
    + +

    说明:

    + +
      +
    • 1 <= grid.length = grid[0].length <= 50
    • +
    • 0 <= grid[i][j] <= 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0828.leetcode828 Count Unique Characters of All Substrings of a Given String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0828.leetcode828 Count Unique Characters of All Substrings of a Given String-zh.md" new file mode 100644 index 00000000..7fbde317 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0828.leetcode828 Count Unique Characters of All Substrings of a Given String-zh.md" @@ -0,0 +1,82 @@ +# [828. 统计子串中的唯一字符](https://leetcode-cn.com/problems/count-unique-characters-of-all-substrings-of-a-given-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0828.Count%20Unique%20Characters%20of%20All%20Substrings%20of%20a%20Given%20String/README_EN.md) + +## 题目描述 + + + +

    我们定义了一个函数 countUniqueChars(s) 来统计字符串 s 中的唯一字符,并返回唯一字符的个数。

    + +

    例如:s = "LEETCODE" ,则其中 "L", "T","C","O","D" 都是唯一字符,因为它们只出现一次,所以 countUniqueChars(s) = 5

    + +

    本题将会给你一个字符串 s ,我们需要返回 countUniqueChars(t) 的总和,其中 ts 的子字符串。注意,某些子字符串可能是重复的,但你统计时也必须算上这些重复的子字符串(也就是说,你必须统计 s 的所有子字符串中的唯一字符)。

    + +

    由于答案可能非常大,请将结果 mod 10 ^ 9 + 7 后再返回。

    + +

     

    + +

    示例 1:

    + +
    +输入: s = "ABC"
    +输出: 10
    +解释: 所有可能的子串为:"A","B","C","AB","BC" 和 "ABC"。
    +     其中,每一个子串都由独特字符构成。
    +     所以其长度总和为:1 + 1 + 1 + 2 + 2 + 3 = 10
    +
    + +

    示例 2:

    + +
    +输入: s = "ABA"
    +输出: 8
    +解释: 了 countUniqueChars("ABA") = 1 之外,其余与示例 1 相同。
    +
    + +

    示例 3:

    + +
    +输入:s = "LEETCODE"
    +输出:92
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 10^4
    • +
    • s 只包含大写英文字符
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0829.leetcode829 Consecutive Numbers Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0829.leetcode829 Consecutive Numbers Sum-zh.md" new file mode 100644 index 00000000..90cfb14d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0829.leetcode829 Consecutive Numbers Sum-zh.md" @@ -0,0 +1,63 @@ +# [829. 连续整数求和](https://leetcode-cn.com/problems/consecutive-numbers-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0829.Consecutive%20Numbers%20Sum/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N?

    + +

    例 1:

    + +
    +输入: 5
    +输出: 2
    +解释: 5 = 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。
    + +

    示例 2:

    + +
    +输入: 9
    +输出: 3
    +解释: 9 = 9 = 4 + 5 = 2 + 3 + 4
    + +

    示例 3:

    + +
    +输入: 15
    +输出: 4
    +解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
    + +

    说明: 1 <= N <= 10 ^ 9

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0830.leetcode830 Positions of Large Groups-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0830.leetcode830 Positions of Large Groups-zh.md" new file mode 100644 index 00000000..aa8916ed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0830.leetcode830 Positions of Large Groups-zh.md" @@ -0,0 +1,88 @@ +# [830. 较大分组的位置](https://leetcode-cn.com/problems/positions-of-large-groups) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0830.Positions%20of%20Large%20Groups/README_EN.md) + +## 题目描述 + + + +

    在一个由小写字母构成的字符串 s 中,包含由一些连续的相同字符所构成的分组。

    + +

    例如,在字符串 s = "abbxxxxzyy" 中,就含有 "a", "bb", "xxxx", "z""yy" 这样的一些分组。

    + +

    分组可以用区间 [start, end] 表示,其中 startend 分别表示该分组的起始和终止位置的下标。上例中的 "xxxx" 分组用区间表示为 [3,6]

    + +

    我们称所有包含大于或等于三个连续字符的分组为 较大分组

    + +

    找到每一个 较大分组 的区间,按起始位置下标递增顺序排序后,返回结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abbxxxxzzy"
    +输出:[[3,6]]
    +解释"xxxx" 是一个起始于 3 且终止于 6 的较大分组。
    +
    + +

    示例 2:

    + +
    +输入:s = "abc"
    +输出:[]
    +解释:"a","b" 和 "c" 均不是符合要求的较大分组。
    +
    + +

    示例 3:

    + +
    +输入:s = "abcdddeeeeaabbbcd"
    +输出:[[3,5],[6,9],[12,14]]
    +解释:较大分组为 "ddd", "eeee" 和 "bbb"
    + +

    示例 4:

    + +
    +输入:s = "aba"
    +输出:[]
    +
    +  + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 仅含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0831.leetcode831 Masking Personal Information-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0831.leetcode831 Masking Personal Information-zh.md" new file mode 100644 index 00000000..62b8868e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0831.leetcode831 Masking Personal Information-zh.md" @@ -0,0 +1,118 @@ +# [831. 隐藏个人信息](https://leetcode-cn.com/problems/masking-personal-information) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0831.Masking%20Personal%20Information/README_EN.md) + +## 题目描述 + + + +

    给你一条个人信息字符串 S,它可能是一个 邮箱地址 ,也可能是一串 电话号码

    + +

    我们将隐藏它的隐私信息,通过如下规则:

    + +

     

    + +

    1. 电子邮箱

    + +

    定义名称 name 是长度大于等于 2 (length ≥ 2),并且只包含小写字母 a-z 和大写字母 A-Z 的字符串。

    + +

    电子邮箱地址由名称 name 开头,紧接着是符号 '@',后面接着一个名称 name,再接着一个点号 '.',然后是一个名称 name

    + +

    电子邮箱地址确定为有效的,并且格式是 "name1@name2.name3"

    + +

    为了隐藏电子邮箱,所有的名称 name 必须被转换成小写的,并且第一个名称 name 的第一个字母和最后一个字母的中间的所有字母由 5 个 '*' 代替。

    + +

     

    + +

    2. 电话号码

    + +

    电话号码是一串包括数字 0-9,以及 {'+', '-', '(', ')', ' '} 这几个字符的字符串。你可以假设电话号码包含 10 到 13 个数字。

    + +

    电话号码的最后 10 个数字组成本地号码,在这之前的数字组成国际号码。注意,国际号码是可选的。我们只暴露最后 4 个数字并隐藏所有其他数字。

    + +

    本地号码是有格式的,并且如 "***-***-1111" 这样显示,这里的 1 表示暴露的数字。

    + +

    为了隐藏有国际号码的电话号码,像 "+111 111 111 1111",我们以 "+***-***-***-1111" 的格式来显示。在本地号码前面的 '+' 号和第一个 '-' 号仅当电话号码中包含国际号码时存在。例如,一个 12 位的电话号码应当以 "+**-" 开头进行显示。

    + +

    注意:像 "(",")"," " 这样的不相干的字符以及不符合上述格式的额外的减号或者加号都应当被删除。

    + +

     

    + +

    最后,将提供的信息正确隐藏后返回。

    + +

     

    + +

    示例 1:

    + +
    输入: "LeetCode@LeetCode.com"
    +输出: "l*****e@leetcode.com"
    +解释: 
    +所有的名称转换成小写, 第一个名称的第一个字符和最后一个字符中间由 5 个星号代替。
    +因此,"leetcode" -> "l*****e"。
    +
    + +

    示例 2:

    + +
    输入: "AB@qq.com"
    +输出: "a*****b@qq.com"
    +解释: 
    +第一个名称"ab"的第一个字符和最后一个字符的中间必须有 5 个星号
    +因此,"ab" -> "a*****b"。
    +
    + +

    示例 3:

    + +
    输入: "1(234)567-890"
    +输出: "***-***-7890"
    +解释: 
    +10 个数字的电话号码,那意味着所有的数字都是本地号码。
    +
    + +

    示例 4:

    + +
    输入: "86-(10)12345678"
    +输出: "+**-***-***-5678"
    +解释: 
    +12 位数字,2 个数字是国际号码另外 10 个数字是本地号码 。
    +
    + +

     

    + +

    注意:

    + +
      +
    1. S.length <= 40
    2. +
    3. 邮箱的长度至少是 8。
    4. +
    5. 电话号码的长度至少是 10。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0832.leetcode832 Flipping an Image-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0832.leetcode832 Flipping an Image-zh.md" new file mode 100644 index 00000000..9be34854 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0832.leetcode832 Flipping an Image-zh.md" @@ -0,0 +1,131 @@ +# [832. 翻转图像](https://leetcode-cn.com/problems/flipping-an-image) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0832.Flipping%20an%20Image/README_EN.md) + +## 题目描述 + + + +

    给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。

    + +

    水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]

    + +

    反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]

    + +

     

    + +

    示例 1:

    + +
    +输入:[[1,1,0],[1,0,1],[0,0,0]]
    +输出:[[1,0,0],[0,1,0],[1,1,1]]
    +解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
    +     然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
    +
    + +

    示例 2:

    + +
    +输入:[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
    +输出:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
    +解释:首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
    +     然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= A.length = A[0].length <= 20
    • +
    • 0 <= A[i][j] <= 1
    • +
    + + +## 解法 + + + +遍历矩阵每一行,利用双指针 p, q 进行水平交换翻转,顺便反转图像(1 变 0,0 变 1:`1 ^ 1` = 0,`0 ^ 1` = 1)。 + + + +### **Python3** + + + +```python +class Solution: + def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: + m, n = len(A), len(A[0]) + for i in range(m): + p, q = 0, n - 1 + while p < q: + t = A[i][p] ^ 1 + A[i][p] = A[i][q] ^ 1 + A[i][q] = t + p += 1 + q -= 1 + if p == q: + A[i][p] ^= 1 + return A +``` + +### **Java** + + + +```java +class Solution { + public int[][] flipAndInvertImage(int[][] A) { + int m = A.length, n = A[0].length; + for (int i = 0; i < m; ++i) { + int p = 0, q = n - 1; + while (p < q) { + int t = A[i][p] ^ 1; + A[i][p] = A[i][q] ^ 1; + A[i][q] = t; + ++p; + --q; + } + if (p == q) { + A[i][p] ^= 1; + } + } + return A; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> flipAndInvertImage(vector>& A) { + int m = A.size(), n = A[0].size(); + for (int i = 0; i < m; ++i) { + int p = 0, q = n - 1; + while (p < q) { + int t = A[i][p] ^ 1; + A[i][p] = A[i][q] ^ 1; + A[i][q] = t; + ++p; + --q; + } + if (p == q) { + A[i][p] ^= 1; + } + } + return A; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0833.leetcode833 Find And Replace in String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0833.leetcode833 Find And Replace in String-zh.md" new file mode 100644 index 00000000..9c7a19e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0833.leetcode833 Find And Replace in String-zh.md" @@ -0,0 +1,87 @@ +# [833. 字符串中的查找与替换](https://leetcode-cn.com/problems/find-and-replace-in-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0833.Find%20And%20Replace%20in%20String/README_EN.md) + +## 题目描述 + + + +

    某个字符串 S 需要执行一些替换操作,用新的字母组替换原有的字母组(不一定大小相同)。

    + +

    每个替换操作具有 3 个参数:起始索引 i,源字 x 和目标字 y。规则是:如果 x原始字符串 S 中的位置 i 开始,那么就用 y 替换出现的 x。如果没有,则什么都不做。

    + +

    举个例子,如果 S = “abcd” 并且替换操作 i = 2,x = “cd”,y = “ffff”,那么因为 “cd” 从原始字符串 S 中的位置 2 开始,所以用 “ffff” 替换它。

    + +

    再来看 S = “abcd” 上的另一个例子,如果一个替换操作 i = 0,x = “ab”,y = “eee”,以及另一个替换操作 i = 2,x = “ec”,y = “ffff”,那么第二个操作将不会执行,因为原始字符串中 S[2] = 'c',与 x[0] = 'e' 不匹配。

    + +

    所有这些操作同时发生。保证在替换时不会有任何重叠: S = "abc", indexes = [0, 1], sources = ["ab","bc"] 不是有效的测试用例。

    + +

     

    + +

    示例 1:

    + +
    +输入:S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
    +输出:"eeebffff"
    +解释:
    +"a" 从 S 中的索引 0 开始,所以它被替换为 "eee"。
    +"cd" 从 S 中的索引 2 开始,所以它被替换为 "ffff"。
    +
    + +

    示例 2:

    + +
    +输入:S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
    +输出:"eeecd"
    +解释:
    +"ab" 从 S 中的索引 0 开始,所以它被替换为 "eee"。
    +"ec" 没有从原始的 S 中的索引 2 开始,所以它没有被替换。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= S.length <= 1000
    • +
    • S 仅由小写英文字母组成
    • +
    • 0 <= indexes.length <= 100
    • +
    • 0 <= indexes[i] < S.length
    • +
    • sources.length == indexes.length
    • +
    • targets.length == indexes.length
    • +
    • 1 <= sources[i].length, targets[i].length <= 50
    • +
    • sources[i]targets[i] 仅由小写英文字母组成
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0834.leetcode834 Sum of Distances in Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0834.leetcode834 Sum of Distances in Tree-zh.md" new file mode 100644 index 00000000..874cf26a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0834.leetcode834 Sum of Distances in Tree-zh.md" @@ -0,0 +1,63 @@ +# [834. 树中距离之和](https://leetcode-cn.com/problems/sum-of-distances-in-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0834.Sum%20of%20Distances%20in%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个无向、连通的树。树中有 N 个标记为 0...N-1 的节点以及 N-1 条边 。

    + +

    i 条边连接节点 edges[i][0]edges[i][1] 。

    + +

    返回一个表示节点 i 与其他所有节点距离之和的列表 ans

    + +

    示例 1:

    + +
    +输入: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
    +输出: [8,12,6,10,10,10]
    +解释: 
    +如下为给定的树的示意图:
    +  0
    + / \
    +1   2
    +   /|\
    +  3 4 5
    +
    +我们可以计算出 dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) 
    +也就是 1 + 1 + 2 + 2 + 2 = 8。 因此,answer[0] = 8,以此类推。
    +
    + +

    说明: 1 <= N <= 10000

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0835.leetcode835 Image Overlap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0835.leetcode835 Image Overlap-zh.md" new file mode 100644 index 00000000..e3dc66f4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0835.leetcode835 Image Overlap-zh.md" @@ -0,0 +1,64 @@ +# [835. 图像重叠](https://leetcode-cn.com/problems/image-overlap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0835.Image%20Overlap/README_EN.md) + +## 题目描述 + + + +

    给出两个图像 AB ,AB 为大小相同的二维正方形矩阵。(并且为二进制矩阵,只包含0和1)。

    + +

    我们转换其中一个图像,向左,右,上,或下滑动任何数量的单位,并把它放在另一个图像的上面。之后,该转换的重叠是指两个图像都具有 1 的位置的数目。

    + +

    (请注意,转换不包括向任何方向旋转。)

    + +

    最大可能的重叠是什么?

    + +

    示例 1:

    + +
    输入:A = [[1,1,0],
    +          [0,1,0],
    +          [0,1,0]]
    +     B = [[0,0,0],
    +          [0,1,1],
    +          [0,0,1]]
    +输出:3
    +解释: 将 A 向右移动一个单位,然后向下移动一个单位。
    + +

    注意: 

    + +
      +
    1. 1 <= A.length = A[0].length = B.length = B[0].length <= 30
    2. +
    3. 0 <= A[i][j], B[i][j] <= 1
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0836.leetcode836 Rectangle Overlap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0836.leetcode836 Rectangle Overlap-zh.md" new file mode 100644 index 00000000..4548c5d0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0836.leetcode836 Rectangle Overlap-zh.md" @@ -0,0 +1,79 @@ +# [836. 矩形重叠](https://leetcode-cn.com/problems/rectangle-overlap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0836.Rectangle%20Overlap/README_EN.md) + +## 题目描述 + + + +

    矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。矩形的上下边平行于 x 轴,左右边平行于 y 轴。

    + +

    如果相交的面积为 ,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。

    + +

    给出两个矩形 rec1rec2 。如果它们重叠,返回 true;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:rec1 = [0,0,1,1], rec2 = [2,2,3,3]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • rect1.length == 4
    • +
    • rect2.length == 4
    • +
    • -109 <= rec1[i], rec2[i] <= 109
    • +
    • rec1[0] <= rec1[2]rec1[1] <= rec1[3]
    • +
    • rec2[0] <= rec2[2]rec2[1] <= rec2[3]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0837.leetcode837 New 21 Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0837.leetcode837 New 21 Game-zh.md" new file mode 100644 index 00000000..0d48e3e1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0837.leetcode837 New 21 Game-zh.md" @@ -0,0 +1,75 @@ +# [837. 新21点](https://leetcode-cn.com/problems/new-21-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0837.New%2021%20Game/README_EN.md) + +## 题目描述 + + + +

    爱丽丝参与一个大致基于纸牌游戏 “21点” 规则的游戏,描述如下:

    + +

    爱丽丝以 0 分开始,并在她的得分少于 K 分时抽取数字。 抽取时,她从 [1, W] 的范围中随机获得一个整数作为分数进行累计,其中 W 是整数。 每次抽取都是独立的,其结果具有相同的概率。

    + +

    当爱丽丝获得不少于 K 分时,她就停止抽取数字。 爱丽丝的分数不超过 N 的概率是多少?

    + +

     

    + +

    示例 1

    + +
    输入:N = 10, K = 1, W = 10
    +输出:1.00000
    +说明:爱丽丝得到一张卡,然后停止。
    + +

    示例 2

    + +
    输入:N = 6, K = 1, W = 10
    +输出:0.60000
    +说明:爱丽丝得到一张卡,然后停止。
    +在 W = 10 的 6 种可能下,她的得分不超过 N = 6 分。
    + +

    示例 3

    + +
    输入:N = 21, K = 17, W = 10
    +输出:0.73278
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= K <= N <= 10000
    2. +
    3. 1 <= W <= 10000
    4. +
    5. 如果答案与正确答案的误差不超过 10^-5,则该答案将被视为正确答案通过。
    6. +
    7. 此问题的判断限制时间已经减少。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0838.leetcode838 Push Dominoes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0838.leetcode838 Push Dominoes-zh.md" new file mode 100644 index 00000000..e6a8a620 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0838.leetcode838 Push Dominoes-zh.md" @@ -0,0 +1,74 @@ +# [838. 推多米诺](https://leetcode-cn.com/problems/push-dominoes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0838.Push%20Dominoes/README_EN.md) + +## 题目描述 + + + +

    一行中有 N 张多米诺骨牌,我们将每张多米诺骨牌垂直竖立。

    + +

    在开始时,我们同时把一些多米诺骨牌向左或向右推。

    + +

    + +

    每过一秒,倒向左边的多米诺骨牌会推动其左侧相邻的多米诺骨牌。

    + +

    同样地,倒向右边的多米诺骨牌也会推动竖立在其右侧的相邻多米诺骨牌。

    + +

    如果同时有多米诺骨牌落在一张垂直竖立的多米诺骨牌的两边,由于受力平衡, 该骨牌仍然保持不变。

    + +

    就这个问题而言,我们会认为正在下降的多米诺骨牌不会对其它正在下降或已经下降的多米诺骨牌施加额外的力。

    + +

    给定表示初始状态的字符串 "S" 。如果第 i 张多米诺骨牌被推向左边,则 S[i] = 'L';如果第 i 张多米诺骨牌被推向右边,则 S[i] = 'R';如果第 i 张多米诺骨牌没有被推动,则 S[i] = '.'

    + +

    返回表示最终状态的字符串。

    + +

    示例 1

    + +
    输入:".L.R...LR..L.."
    +输出:"LL.RR.LLRRLL.."
    + +

    示例 2

    + +
    输入:"RR.L"
    +输出:"RR.L"
    +说明:第一张多米诺骨牌没有给第二张施加额外的力。
    + +

    提示:

    + +
      +
    1. 0 <= N <= 10^5
    2. +
    3. 表示多米诺骨牌状态的字符串只含有 'L''R'; 以及 '.';
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0839.leetcode839 Similar String Groups-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0839.leetcode839 Similar String Groups-zh.md" new file mode 100644 index 00000000..d5c891e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0839.leetcode839 Similar String Groups-zh.md" @@ -0,0 +1,79 @@ +# [839. 相似字符串组](https://leetcode-cn.com/problems/similar-string-groups) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0839.Similar%20String%20Groups/README_EN.md) + +## 题目描述 + + + +

    如果交换字符串 X 中的两个不同位置的字母,使得它和字符串 Y 相等,那么称 XY 两个字符串相似。如果这两个字符串本身是相等的,那它们也是相似的。

    + +

    例如,"tars""rats" 是相似的 (交换 02 的位置); "rats""arts" 也是相似的,但是 "star" 不与 "tars""rats",或 "arts" 相似。

    + +

    总之,它们通过相似性形成了两个关联组:{"tars", "rats", "arts"}{"star"}。注意,"tars""arts" 是在同一组中,即使它们并不相似。形式上,对每个组而言,要确定一个单词在组中,只需要这个词和该组中至少一个单词相似。

    + +

    给你一个字符串列表 strs。列表中的每个字符串都是 strs 中其它所有字符串的一个字母异位词。请问 strs 中有多少个相似字符串组?

    + +

     

    + +

    示例 1:

    + +
    +输入:strs = ["tars","rats","arts","star"]
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:strs = ["omv","ovm"]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= strs.length <= 300
    • +
    • 1 <= strs[i].length <= 300
    • +
    • strs[i] 只包含小写字母。
    • +
    • strs 中的所有单词都具有相同的长度,且是彼此的字母异位词。
    • +
    + +

     

    + +

    备注:

    + +

          字母异位词(anagram),一种把某个字符串的字母的位置(顺序)加以改换所形成的新词。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0840.leetcode840 Magic Squares In Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0840.leetcode840 Magic Squares In Grid-zh.md" new file mode 100644 index 00000000..3d19c83b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0840.leetcode840 Magic Squares In Grid-zh.md" @@ -0,0 +1,72 @@ +# [840. 矩阵中的幻方](https://leetcode-cn.com/problems/magic-squares-in-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0840.Magic%20Squares%20In%20Grid/README_EN.md) + +## 题目描述 + + + +

    3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。

    + +

    给定一个由整数组成的 grid,其中有多少个 3 × 3 的 “幻方” 子矩阵?(每个子矩阵都是连续的)。

    + +

     

    + +

    示例:

    + +
    输入: [[4,3,8,4],
    +      [9,5,1,9],
    +      [2,7,6,2]]
    +输出: 1
    +解释: 
    +下面的子矩阵是一个 3 x 3 的幻方:
    +438
    +951
    +276
    +
    +而这一个不是:
    +384
    +519
    +762
    +
    +总的来说,在本示例所给定的矩阵中只有一个 3 x 3 的幻方子矩阵。
    +
    + +

    提示:

    + +
      +
    1. 1 <= grid.length <= 10
    2. +
    3. 1 <= grid[0].length <= 10
    4. +
    5. 0 <= grid[i][j] <= 15
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0841.leetcode841 Keys and Rooms-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0841.leetcode841 Keys and Rooms-zh.md" new file mode 100644 index 00000000..c44d09c2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0841.leetcode841 Keys and Rooms-zh.md" @@ -0,0 +1,78 @@ +# [841. 钥匙和房间](https://leetcode-cn.com/problems/keys-and-rooms) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0841.Keys%20and%20Rooms/README_EN.md) + +## 题目描述 + + + +

    N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。

    + +

    在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j][0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。

    + +

    最初,除 0 号房间外的其余所有房间都被锁住。

    + +

    你可以自由地在房间之间来回走动。

    + +

    如果能进入每个房间返回 true,否则返回 false

    + +
      +
    + +

    示例 1:

    + +
    输入: [[1],[2],[3],[]]
    +输出: true
    +解释:  
    +我们从 0 号房间开始,拿到钥匙 1。
    +之后我们去 1 号房间,拿到钥匙 2。
    +然后我们去 2 号房间,拿到钥匙 3。
    +最后我们去了 3 号房间。
    +由于我们能够进入每个房间,我们返回 true。
    +
    + +

    示例 2:

    + +
    输入:[[1,3],[3,0,1],[2],[0]]
    +输出:false
    +解释:我们不能进入 2 号房间。
    +
    + +

    提示:

    + +
      +
    1. 1 <= rooms.length <= 1000
    2. +
    3. 0 <= rooms[i].length <= 1000
    4. +
    5. 所有房间中的钥匙数量总计不超过 3000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0842.leetcode842 Split Array into Fibonacci Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0842.leetcode842 Split Array into Fibonacci Sequence-zh.md" new file mode 100644 index 00000000..b8b17966 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0842.leetcode842 Split Array into Fibonacci Sequence-zh.md" @@ -0,0 +1,96 @@ +# [842. 将数组拆分成斐波那契序列](https://leetcode-cn.com/problems/split-array-into-fibonacci-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0842.Split%20Array%20into%20Fibonacci%20Sequence/README_EN.md) + +## 题目描述 + + + +

    给定一个数字字符串 S,比如 S = "123456579",我们可以将它分成斐波那契式的序列 [123, 456, 579]

    + +

    形式上,斐波那契式序列是一个非负整数列表 F,且满足:

    + +
      +
    • 0 <= F[i] <= 2^31 - 1,(也就是说,每个整数都符合 32 位有符号整数类型);
    • +
    • F.length >= 3
    • +
    • 对于所有的0 <= i < F.length - 2,都有 F[i] + F[i+1] = F[i+2] 成立。
    • +
    + +

    另外,请注意,将字符串拆分成小块时,每个块的数字一定不要以零开头,除非这个块是数字 0 本身。

    + +

    返回从 S 拆分出来的任意一组斐波那契式的序列块,如果不能拆分则返回 []

    + +

     

    + +

    示例 1:

    + +
    输入:"123456579"
    +输出:[123,456,579]
    +
    + +

    示例 2:

    + +
    输入: "11235813"
    +输出: [1,1,2,3,5,8,13]
    +
    + +

    示例 3:

    + +
    输入: "112358130"
    +输出: []
    +解释: 这项任务无法完成。
    +
    + +

    示例 4:

    + +
    输入:"0123"
    +输出:[]
    +解释:每个块的数字不能以零开头,因此 "01","2","3" 不是有效答案。
    +
    + +

    示例 5:

    + +
    输入: "1101111"
    +输出: [110, 1, 111]
    +解释: 输出 [11,0,11,11] 也同样被接受。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 200
    2. +
    3. 字符串 S 中只含有数字。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0843.leetcode843 Guess the Word-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0843.leetcode843 Guess the Word-zh.md" new file mode 100644 index 00000000..01cacdc4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0843.leetcode843 Guess the Word-zh.md" @@ -0,0 +1,66 @@ +# [843. 猜猜这个单词](https://leetcode-cn.com/problems/guess-the-word) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0843.Guess%20the%20Word/README_EN.md) + +## 题目描述 + + + +

    这个问题是 LeetCode 平台新增的交互式问题

    + +

    我们给出了一个由一些独特的单词组成的单词列表,每个单词都是 6 个字母长,并且这个列表中的一个单词将被选作秘密

    + +

    你可以调用 master.guess(word) 来猜单词。你所猜的单词应当是存在于原列表并且由 6 个小写字母组成的类型字符串

    + +

    此函数将会返回一个整型数字,表示你的猜测与秘密单词的准确匹配(值和位置同时匹配)的数目。此外,如果你的猜测不在给定的单词列表中,它将返回 -1

    + +

    对于每个测试用例,你有 10 次机会来猜出这个单词。当所有调用都结束时,如果您对 master.guess 的调用不超过 10 次,并且至少有一次猜到秘密,那么您将通过该测试用例。

    + +

    除了下面示例给出的测试用例外,还会有 5 个额外的测试用例,每个单词列表中将会有 100 个单词。这些测试用例中的每个单词的字母都是从 'a''z' 中随机选取的,并且保证给定单词列表中的每个单词都是唯一的。

    + +
    示例 1:
    +输入: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"]
    +
    +解释:
    +
    +master.guess("aaaaaa") 返回 -1, 因为 "aaaaaa" 不在 wordlist 中.
    +master.guess("acckzz") 返回 6, 因为 "acckzz" 就是秘密,6个字母完全匹配。
    +master.guess("ccbazz") 返回 3, 因为 "ccbazz" 有 3 个匹配项。
    +master.guess("eiowzz") 返回 2, 因为 "eiowzz" 有 2 个匹配项。
    +master.guess("abcczz") 返回 4, 因为 "abcczz" 有 4 个匹配项。
    +
    +我们调用了 5 次master.guess,其中一次猜到了秘密,所以我们通过了这个测试用例。
    +
    + +

    提示:任何试图绕过评判的解决方案都将导致比赛资格被取消。

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0844.leetcode844 Backspace String Compare-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0844.leetcode844 Backspace String Compare-zh.md" new file mode 100644 index 00000000..098d0d3a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0844.leetcode844 Backspace String Compare-zh.md" @@ -0,0 +1,95 @@ +# [844. 比较含退格的字符串](https://leetcode-cn.com/problems/backspace-string-compare) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0844.Backspace%20String%20Compare/README_EN.md) + +## 题目描述 + + + +

    给定 ST 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。

    + +

    注意:如果对空文本输入退格字符,文本继续为空。

    + +

     

    + +

    示例 1:

    + +
    +输入:S = "ab#c", T = "ad#c"
    +输出:true
    +解释:S 和 T 都会变成 “ac”。
    +
    + +

    示例 2:

    + +
    +输入:S = "ab##", T = "c#d#"
    +输出:true
    +解释:S 和 T 都会变成 “”。
    +
    + +

    示例 3:

    + +
    +输入:S = "a##c", T = "#a#c"
    +输出:true
    +解释:S 和 T 都会变成 “c”。
    +
    + +

    示例 4:

    + +
    +输入:S = "a#c", T = "b"
    +输出:false
    +解释:S 会变成 “c”,但 T 仍然是 “b”。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= S.length <= 200
    • +
    • 1 <= T.length <= 200
    • +
    • ST 只含有小写字母以及字符 '#'
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以用 O(N) 的时间复杂度和 O(1) 的空间复杂度解决该问题吗?
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0845.leetcode845 Longest Mountain in Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0845.leetcode845 Longest Mountain in Array-zh.md" new file mode 100644 index 00000000..20c1018e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0845.leetcode845 Longest Mountain in Array-zh.md" @@ -0,0 +1,76 @@ +# [845. 数组中的最长山脉](https://leetcode-cn.com/problems/longest-mountain-in-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0845.Longest%20Mountain%20in%20Array/README_EN.md) + +## 题目描述 + + + +

    我们把数组 A 中符合下列属性的任意连续子数组 B 称为 “山脉”

    + +
      +
    • B.length >= 3
    • +
    • 存在 0 < i < B.length - 1 使得 B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
    • +
    + +

    (注意:B 可以是 A 的任意子数组,包括整个数组 A。)

    + +

    给出一个整数数组 A,返回最长 “山脉” 的长度。

    + +

    如果不含有 “山脉” 则返回 0

    + +

     

    + +

    示例 1:

    + +
    输入:[2,1,4,7,3,2,5]
    +输出:5
    +解释:最长的 “山脉” 是 [1,4,7,3,2],长度为 5。
    +
    + +

    示例 2:

    + +
    输入:[2,2,2]
    +输出:0
    +解释:不含 “山脉”。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= A.length <= 10000
    2. +
    3. 0 <= A[i] <= 10000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0846.leetcode846 Hand of Straights-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0846.leetcode846 Hand of Straights-zh.md" new file mode 100644 index 00000000..191f6c2e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0846.leetcode846 Hand of Straights-zh.md" @@ -0,0 +1,77 @@ +# [846. 一手顺子](https://leetcode-cn.com/problems/hand-of-straights) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0846.Hand%20of%20Straights/README_EN.md) + +## 题目描述 + + + +

    爱丽丝有一手(hand)由整数数组给定的牌。 

    + +

    现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。

    + +

    如果她可以完成分组就返回 true,否则返回 false

    + +

     

    + +

    注意:此题目与 1296 重复:https://leetcode-cn.com/problems/divide-array-in-sets-of-k-consecutive-numbers/

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:hand = [1,2,3,6,2,3,4,7,8], W = 3
    +输出:true
    +解释:爱丽丝的手牌可以被重新排列为 [1,2,3],[2,3,4],[6,7,8]
    + +

    示例 2:

    + +
    +输入:hand = [1,2,3,4,5], W = 4
    +输出:false
    +解释:爱丽丝的手牌无法被重新排列成几个大小为 4 的组。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= hand.length <= 10000
    • +
    • 0 <= hand[i] <= 10^9
    • +
    • 1 <= W <= hand.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0847.leetcode847 Shortest Path Visiting All Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0847.leetcode847 Shortest Path Visiting All Nodes-zh.md" new file mode 100644 index 00000000..a4d3f953 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0847.leetcode847 Shortest Path Visiting All Nodes-zh.md" @@ -0,0 +1,71 @@ +# [847. 访问所有节点的最短路径](https://leetcode-cn.com/problems/shortest-path-visiting-all-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0847.Shortest%20Path%20Visiting%20All%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给出 graph 为有 N 个节点(编号为 0, 1, 2, ..., N-1)的无向连通图。 

    + +

    graph.length = N,且只有节点 i 和 j 连通时,j != i 在列表 graph[i] 中恰好出现一次。

    + +

    返回能够访问所有节点的最短路径的长度。你可以在任一节点开始和停止,也可以多次重访节点,并且可以重用边。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:[[1,2,3],[0],[0],[0]]
    +输出:4
    +解释:一个可能的路径为 [1,0,2,0,3]
    + +

    示例 2:

    + +
    输入:[[1],[0,2,4],[1,3,4],[2],[1,2]]
    +输出:4
    +解释:一个可能的路径为 [0,1,4,2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= graph.length <= 12
    2. +
    3. 0 <= graph[i].length < graph.length
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0848.leetcode848 Shifting Letters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0848.leetcode848 Shifting Letters-zh.md" new file mode 100644 index 00000000..660965e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0848.leetcode848 Shifting Letters-zh.md" @@ -0,0 +1,66 @@ +# [848. 字母移位](https://leetcode-cn.com/problems/shifting-letters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0848.Shifting%20Letters/README_EN.md) + +## 题目描述 + + + +

    有一个由小写字母组成的字符串 S,和一个整数数组 shifts

    + +

    我们将字母表中的下一个字母称为原字母的 移位(由于字母表是环绕的, 'z' 将会变成 'a')。

    + +

    例如·,shift('a') = 'b', shift('t') = 'u',, 以及 shift('z') = 'a'

    + +

    对于每个 shifts[i] = x , 我们会将 S 中的前 i+1 个字母移位 x 次。

    + +

    返回将所有这些移位都应用到 S 后最终得到的字符串。

    + +

    示例:

    + +
    输入:S = "abc", shifts = [3,5,9]
    +输出:"rpl"
    +解释: 
    +我们以 "abc" 开始。
    +将 S 中的第 1 个字母移位 3 次后,我们得到 "dbc"。
    +再将 S 中的前 2 个字母移位 5 次后,我们得到 "igc"。
    +最后将 S 中的这 3 个字母移位 9 次后,我们得到答案 "rpl"。
    +
    + +

    提示:

    + +
      +
    1. 1 <= S.length = shifts.length <= 20000
    2. +
    3. 0 <= shifts[i] <= 10 ^ 9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0849.leetcode849 Maximize Distance to Closest Person-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0849.leetcode849 Maximize Distance to Closest Person-zh.md" new file mode 100644 index 00000000..38473e6a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0849.leetcode849 Maximize Distance to Closest Person-zh.md" @@ -0,0 +1,87 @@ +# [849. 到最近的人的最大距离](https://leetcode-cn.com/problems/maximize-distance-to-closest-person) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0849.Maximize%20Distance%20to%20Closest%20Person/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 seats 表示一排座位,其中 seats[i] = 1 代表有人坐在第 i 个座位上,seats[i] = 0 代表座位 i 上是空的(下标从 0 开始)。

    + +

    至少有一个空座位,且至少有一人已经坐在座位上。

    + +

    亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。

    + +

    返回他到离他最近的人的最大距离。

    + +

     

    + +

    示例 1:

    + +
    +输入:seats = [1,0,0,0,1,0,1]
    +输出:2
    +解释:
    +如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。
    +如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。
    +因此,他到离他最近的人的最大距离是 2 。 
    +
    + +

    示例 2:

    + +
    +输入:seats = [1,0,0,0]
    +输出:3
    +解释:
    +如果亚历克斯坐在最后一个座位上,他离最近的人有 3 个座位远。
    +这是可能的最大距离,所以答案是 3 。
    +
    + +

    示例 3:

    + +
    +输入:seats = [0,1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= seats.length <= 2 * 104
    • +
    • seats[i]01
    • +
    • 至少有一个 空座位
    • +
    • 至少有一个 座位上有人
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0850.leetcode850 Rectangle Area II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0850.leetcode850 Rectangle Area II-zh.md" new file mode 100644 index 00000000..89fa255c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0850.leetcode850 Rectangle Area II-zh.md" @@ -0,0 +1,67 @@ +# [850. 矩形面积 II](https://leetcode-cn.com/problems/rectangle-area-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0850.Rectangle%20Area%20II/README_EN.md) + +## 题目描述 + + + +

    我们给出了一个(轴对齐的)矩形列表 rectangles 。 对于 rectangle[i] = [x1, y1, x2, y2],其中(x1,y1)是矩形 i 左下角的坐标,(x2,y2)是该矩形右上角的坐标。

    + +

    找出平面中所有矩形叠加覆盖后的总面积。 由于答案可能太大,请返回它对 10 ^ 9 + 7 取模的结果

    + +

    + +

    示例 1:

    + +
    输入:[[0,0,2,2],[1,0,2,3],[1,0,3,1]]
    +输出:6
    +解释:如图所示。
    +
    + +

    示例 2:

    + +
    输入:[[0,0,1000000000,1000000000]]
    +输出:49
    +解释:答案是 10^18 对 (10^9 + 7) 取模的结果, 即 (10^9)^2 → (-7)^2 = 49 。
    +
    + +

    提示:

    + +
      +
    • 1 <= rectangles.length <= 200
    • +
    • rectanges[i].length = 4
    • +
    • 0 <= rectangles[i][j] <= 10^9
    • +
    • 矩形叠加覆盖后的总面积不会超越 2^63 - 1 ,这意味着可以用一个 64 位有符号整数来保存面积结果。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0851.leetcode851 Loud and Rich-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0851.leetcode851 Loud and Rich-zh.md" new file mode 100644 index 00000000..4572d9c9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0851.leetcode851 Loud and Rich-zh.md" @@ -0,0 +1,77 @@ +# [851. 喧闹和富有](https://leetcode-cn.com/problems/loud-and-rich) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0851.Loud%20and%20Rich/README_EN.md) + +## 题目描述 + + + +

    在一组 N 个人(编号为 0, 1, 2, ..., N-1)中,每个人都有不同数目的钱,以及不同程度的安静(quietness)。

    + +

    为了方便起见,我们将编号为 x 的人简称为 "person x "。

    + +

    如果能够肯定 person x 比 person y 更有钱的话,我们会说 richer[i] = [x, y] 。注意 richer 可能只是有效观察的一个子集。

    + +

    另外,如果 person x 的安静程度为 q ,我们会说 quiet[x] = q 。

    + +

    现在,返回答案 answer ,其中 answer[x] = y 的前提是,在所有拥有的钱不少于 person x 的人中,person y 是最安静的人(也就是安静值 quiet[y] 最小的人)。

    + +

    示例:

    + +
    输入:richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
    +输出:[5,5,2,5,4,5,6,7]
    +解释: 
    +answer[0] = 5,
    +person 5 比 person 3 有更多的钱,person 3 比 person 1 有更多的钱,person 1 比 person 0 有更多的钱。
    +唯一较为安静(有较低的安静值 quiet[x])的人是 person 7,
    +但是目前还不清楚他是否比 person 0 更有钱。
    +
    +answer[7] = 7,
    +在所有拥有的钱肯定不少于 person 7 的人中(这可能包括 person 3,4,5,6 以及 7),
    +最安静(有较低安静值 quiet[x])的人是 person 7。
    +
    +其他的答案也可以用类似的推理来解释。
    +
    + +

    提示:

    + +
      +
    1. 1 <= quiet.length = N <= 500
    2. +
    3. 0 <= quiet[i] < N,所有 quiet[i] 都不相同。
    4. +
    5. 0 <= richer.length <= N * (N-1) / 2
    6. +
    7. 0 <= richer[i][j] < N
    8. +
    9. richer[i][0] != richer[i][1]
    10. +
    11. richer[i] 都是不同的。
    12. +
    13. 对 richer 的观察在逻辑上是一致的。
    14. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0852.leetcode852 Peak Index in a Mountain Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0852.leetcode852 Peak Index in a Mountain Array-zh.md" new file mode 100644 index 00000000..208d67ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0852.leetcode852 Peak Index in a Mountain Array-zh.md" @@ -0,0 +1,188 @@ +# [852. 山脉数组的峰顶索引](https://leetcode-cn.com/problems/peak-index-in-a-mountain-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0852.Peak%20Index%20in%20a%20Mountain%20Array/README_EN.md) + +## 题目描述 + + + +符合下列属性的数组 arr 称为 山脉数组 : +
      +
    • arr.length >= 3
    • +
    • 存在 i0 < i < arr.length - 1)使得: +
        +
      • arr[0] < arr[1] < ... arr[i-1] < arr[i]
      • +
      • arr[i] > arr[i+1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

    给你由整数组成的山脉数组 arr ,返回任何满足 arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 的下标 i

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [0,1,0]
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:arr = [0,2,1,0]
    +输出:1
    +
    + +

    示例 3:

    + +
    +输入:arr = [0,10,5,2]
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:arr = [3,4,5,1]
    +输出:2
    +
    + +

    示例 5:

    + +
    +输入:arr = [24,69,100,99,79,78,67,36,26,19]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= arr.length <= 104
    • +
    • 0 <= arr[i] <= 106
    • +
    • 题目数据保证 arr 是一个山脉数组
    • +
    + +

     

    + +

    进阶:很容易想到时间复杂度 O(n) 的解决方案,你可以设计一个 O(log(n)) 的解决方案吗?

    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def peakIndexInMountainArray(self, arr: List[int]) -> int: + n = len(arr) + left, right = 1, n - 2 + while left < right: + mid = (left + right) // 2 + if arr[mid] < arr[mid + 1]: + left = mid + 1 + else: + right = mid + return right +``` + +### **Java** + + + +```java +class Solution { + public int peakIndexInMountainArray(int[] arr) { + int n = arr.length; + int left = 1, right = n - 2; + while (left < right) { + int mid = left + (right - left) / 2; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } +} +``` + +### **Go** + +```go +func peakIndexInMountainArray(arr []int) int { + n := len(arr) + left, right := 1, n-2 + for left < right { + mid := left + (right-left)/2 + if arr[mid] < arr[mid+1] { + left = mid + 1 + } else { + right = mid + } + } + return right +} +``` + +### **C++** + +```cpp +class Solution { +public: + int peakIndexInMountainArray(vector& arr) { + int left = 1, right = arr.size() - 2; + while (left < right) { + int mid = left + right >> 1; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @return {number} + */ +var peakIndexInMountainArray = function(arr) { + let left = 1; + let right = arr.length - 2; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0853.leetcode853 Car Fleet-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0853.leetcode853 Car Fleet-zh.md" new file mode 100644 index 00000000..acfc2f37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0853.leetcode853 Car Fleet-zh.md" @@ -0,0 +1,78 @@ +# [853. 车队](https://leetcode-cn.com/problems/car-fleet) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0853.Car%20Fleet/README_EN.md) + +## 题目描述 + + + +

    N  辆车沿着一条车道驶向位于 target 英里之外的共同目的地。

    + +

    每辆车 i 以恒定的速度 speed[i] (英里/小时),从初始位置 position[i] (英里) 沿车道驶向目的地。

    + +

    一辆车永远不会超过前面的另一辆车,但它可以追上去,并与前车以相同的速度紧接着行驶。

    + +

    此时,我们会忽略这两辆车之间的距离,也就是说,它们被假定处于相同的位置。

    + +

    车队 是一些由行驶在相同位置、具有相同速度的车组成的非空集合。注意,一辆车也可以是一个车队。

    + +

    即便一辆车在目的地才赶上了一个车队,它们仍然会被视作是同一个车队。

    + +

     

    + +

    会有多少车队到达目的地?

    + +

     

    + +

    示例:

    + +
    输入:target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
    +输出:3
    +解释:
    +从 10 和 8 开始的车会组成一个车队,它们在 12 处相遇。
    +从 0 处开始的车无法追上其它车,所以它自己就是一个车队。
    +从 5 和 3 开始的车会组成一个车队,它们在 6 处相遇。
    +请注意,在到达目的地之前没有其它车会遇到这些车队,所以答案是 3。
    +
    + +


    +提示:

    + +
      +
    1. 0 <= N <= 10 ^ 4
    2. +
    3. 0 < target <= 10 ^ 6
    4. +
    5. 0 < speed[i] <= 10 ^ 6
    6. +
    7. 0 <= position[i] < target
    8. +
    9. 所有车的初始位置各不相同。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0854.leetcode854 K-Similar Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0854.leetcode854 K-Similar Strings-zh.md" new file mode 100644 index 00000000..ade58e57 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0854.leetcode854 K-Similar Strings-zh.md" @@ -0,0 +1,76 @@ +# [854. 相似度为 K 的字符串](https://leetcode-cn.com/problems/k-similar-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0854.K-Similar%20Strings/README_EN.md) + +## 题目描述 + + + +

    如果可以通过将 A 中的两个小写字母精确地交换位置 K 次得到与 B 相等的字符串,我们称字符串 A 和 B 的相似度为 KK 为非负整数)。

    + +

    给定两个字母异位词 A 和 B ,返回 AB 的相似度 K 的最小值。

    + +

     

    + +

    示例 1:

    + +
    输入:A = "ab", B = "ba"
    +输出:1
    +
    + +

    示例 2:

    + +
    输入:A = "abc", B = "bca"
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:A = "abac", B = "baca"
    +输出:2
    +
    + +

    示例 4:

    + +
    输入:A = "aabc", B = "abca"
    +输出:2
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length == B.length <= 20
    2. +
    3. A 和 B 只包含集合 {'a', 'b', 'c', 'd', 'e', 'f'} 中的小写字母。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0855.leetcode855 Exam Room-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0855.leetcode855 Exam Room-zh.md" new file mode 100644 index 00000000..3e8a9405 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0855.leetcode855 Exam Room-zh.md" @@ -0,0 +1,70 @@ +# [855. 考场就座](https://leetcode-cn.com/problems/exam-room) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0855.Exam%20Room/README_EN.md) + +## 题目描述 + + + +

    在考场里,一排有 N 个座位,分别编号为 0, 1, 2, ..., N-1 。

    + +

    当学生进入考场后,他必须坐在能够使他与离他最近的人之间的距离达到最大化的座位上。如果有多个这样的座位,他会坐在编号最小的座位上。(另外,如果考场里没有人,那么学生就坐在 0 号座位上。)

    + +

    返回 ExamRoom(int N) 类,它有两个公开的函数:其中,函数 ExamRoom.seat() 会返回一个 int (整型数据),代表学生坐的位置;函数 ExamRoom.leave(int p) 代表坐在座位 p 上的学生现在离开了考场。每次调用 ExamRoom.leave(p) 时都保证有学生坐在座位 p 上。

    + +

     

    + +

    示例:

    + +
    输入:["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]
    +输出:[null,0,9,4,2,null,5]
    +解释:
    +ExamRoom(10) -> null
    +seat() -> 0,没有人在考场里,那么学生坐在 0 号座位上。
    +seat() -> 9,学生最后坐在 9 号座位上。
    +seat() -> 4,学生最后坐在 4 号座位上。
    +seat() -> 2,学生最后坐在 2 号座位上。
    +leave(4) -> null
    +seat() -> 5,学生最后坐在 5 号座位上。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10^9
    2. +
    3. 在所有的测试样例中 ExamRoom.seat() 和 ExamRoom.leave() 最多被调用 10^4 次。
    4. +
    5. 保证在调用 ExamRoom.leave(p) 时有学生正坐在座位 p 上。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0856.leetcode856 Score of Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0856.leetcode856 Score of Parentheses-zh.md" new file mode 100644 index 00000000..45615643 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0856.leetcode856 Score of Parentheses-zh.md" @@ -0,0 +1,81 @@ +# [856. 括号的分数](https://leetcode-cn.com/problems/score-of-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0856.Score%20of%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:

    + +
      +
    • () 得 1 分。
    • +
    • AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
    • +
    • (A) 得 2 * A 分,其中 A 是平衡括号字符串。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入: "()"
    +输出: 1
    +
    + +

    示例 2:

    + +
    输入: "(())"
    +输出: 2
    +
    + +

    示例 3:

    + +
    输入: "()()"
    +输出: 2
    +
    + +

    示例 4:

    + +
    输入: "(()(()))"
    +输出: 6
    +
    + +

     

    + +

    提示:

    + +
      +
    1. S 是平衡括号字符串,且只含有 ( 和 ) 。
    2. +
    3. 2 <= S.length <= 50
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0857.leetcode857 Minimum Cost to Hire K Workers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0857.leetcode857 Minimum Cost to Hire K Workers-zh.md" new file mode 100644 index 00000000..21e704ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0857.leetcode857 Minimum Cost to Hire K Workers-zh.md" @@ -0,0 +1,77 @@ +# [857. 雇佣 K 名工人的最低成本](https://leetcode-cn.com/problems/minimum-cost-to-hire-k-workers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0857.Minimum%20Cost%20to%20Hire%20K%20Workers/README_EN.md) + +## 题目描述 + + + +

    N 名工人。 第 i 名工人的工作质量为 quality[i] ,其最低期望工资为 wage[i] 。

    + +

    现在我们想雇佣 K 名工人组成一个工资组。在雇佣 一组 K 名工人时,我们必须按照下述规则向他们支付工资:

    + +
      +
    1. 对工资组中的每名工人,应当按其工作质量与同组其他工人的工作质量的比例来支付工资。
    2. +
    3. 工资组中的每名工人至少应当得到他们的最低期望工资。
    4. +
    + +

    返回组成一个满足上述条件的工资组至少需要多少钱。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入: quality = [10,20,5], wage = [70,50,30], K = 2
    +输出: 105.00000
    +解释: 我们向 0 号工人支付 70,向 2 号工人支付 35。
    + +

    示例 2:

    + +
    输入: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
    +输出: 30.66667
    +解释: 我们向 0 号工人支付 4,向 2 号和 3 号分别支付 13.33333。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= K <= N <= 10000,其中 N = quality.length = wage.length
    2. +
    3. 1 <= quality[i] <= 10000
    4. +
    5. 1 <= wage[i] <= 10000
    6. +
    7. 与正确答案误差在 10^-5 之内的答案将被视为正确的。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0858.leetcode858 Mirror Reflection-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0858.leetcode858 Mirror Reflection-zh.md" new file mode 100644 index 00000000..7aba56f0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0858.leetcode858 Mirror Reflection-zh.md" @@ -0,0 +1,63 @@ +# [858. 镜面反射](https://leetcode-cn.com/problems/mirror-reflection) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0858.Mirror%20Reflection/README_EN.md) + +## 题目描述 + + + +

    有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角以外,每个角落都放有一个接受器,编号为 0, 1,以及 2

    + +

    正方形房间的墙壁长度为 p,一束激光从西南角射出,首先会与东墙相遇,入射点到接收器 0 的距离为 q

    + +

    返回光线最先遇到的接收器的编号(保证光线最终会遇到一个接收器)。

    + +

     

    + +

    示例:

    + +
    +输入: p = 2, q = 1
    +输出: 2
    +解释: 这条光线在第一次被反射回左边的墙时就遇到了接收器 2 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= p <= 1000
    • +
    • 0 <= q <= p
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0859.leetcode859 Buddy Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0859.leetcode859 Buddy Strings-zh.md" new file mode 100644 index 00000000..2db98015 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0859.leetcode859 Buddy Strings-zh.md" @@ -0,0 +1,90 @@ +# [859. 亲密字符串](https://leetcode-cn.com/problems/buddy-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0859.Buddy%20Strings/README_EN.md) + +## 题目描述 + + + +

    给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false

    + +

    交换字母的定义是取两个下标 ij (下标从 0 开始),只要 i!=j 就交换 A[i]A[j] 处的字符。例如,在 "abcd" 中交换下标 0 和下标 2 的元素可以生成 "cbad"

    + +

     

    + +

    示例 1:

    + +
    +输入: A = "ab", B = "ba"
    +输出: true
    +解释: 你可以交换 A[0] = 'a' 和 A[1] = 'b' 生成 "ba",此时 A 和 B 相等。
    + +

    示例 2:

    + +
    +输入: A = "ab", B = "ab"
    +输出: false
    +解释: 你只能交换 A[0] = 'a' 和 A[1] = 'b' 生成 "ba",此时 A 和 B 不相等。
    +
    + +

    示例 3:

    + +
    +输入: A = "aa", B = "aa"
    +输出: true
    +解释: 你可以交换 A[0] = 'a' 和 A[1] = 'a' 生成 "aa",此时 A 和 B 相等。
    + +

    示例 4:

    + +
    +输入: A = "aaaaaaabc", B = "aaaaaaacb"
    +输出: true
    +
    + +

    示例 5:

    + +
    +输入: A = "", B = "aa"
    +输出: false
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= A.length <= 20000
    2. +
    3. 0 <= B.length <= 20000
    4. +
    5. A 和 B 仅由小写字母构成。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0860.leetcode860 Lemonade Change-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0860.leetcode860 Lemonade Change-zh.md" new file mode 100644 index 00000000..aed426ed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0860.leetcode860 Lemonade Change-zh.md" @@ -0,0 +1,91 @@ +# [860. 柠檬水找零](https://leetcode-cn.com/problems/lemonade-change) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0860.Lemonade%20Change/README_EN.md) + +## 题目描述 + + + +

    在柠檬水摊上,每一杯柠檬水的售价为 5 美元。

    + +

    顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。

    + +

    每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。

    + +

    注意,一开始你手头没有任何零钱。

    + +

    如果你能给每位顾客正确找零,返回 true ,否则返回 false 。

    + +

    示例 1:

    + +
    输入:[5,5,5,10,20]
    +输出:true
    +解释:
    +前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
    +第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
    +第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。
    +由于所有客户都得到了正确的找零,所以我们输出 true。
    +
    + +

    示例 2:

    + +
    输入:[5,5,10]
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:[10,10]
    +输出:false
    +
    + +

    示例 4:

    + +
    输入:[5,5,10,10,20]
    +输出:false
    +解释:
    +前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。
    +对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。
    +对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。
    +由于不是每位顾客都得到了正确的找零,所以答案是 false。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= bills.length <= 10000
    • +
    • bills[i] 不是 5 就是 10 或是 20 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0861.leetcode861 Score After Flipping Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0861.leetcode861 Score After Flipping Matrix-zh.md" new file mode 100644 index 00000000..3956f3b9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0861.leetcode861 Score After Flipping Matrix-zh.md" @@ -0,0 +1,69 @@ +# [861. 翻转矩阵后的得分](https://leetcode-cn.com/problems/score-after-flipping-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0861.Score%20After%20Flipping%20Matrix/README_EN.md) + +## 题目描述 + + + +

    有一个二维矩阵 A 其中每个元素的值为 0 或 1 。

    + +

    移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0

    + +

    在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。

    + +

    返回尽可能高的分数。

    + +

     

    + +
      +
    + +

    示例:

    + +
    输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]]
    +输出:39
    +解释:
    +转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
    +0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 20
    2. +
    3. 1 <= A[0].length <= 20
    4. +
    5. A[i][j] 是 0 或 1
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0862.leetcode862 Shortest Subarray with Sum at Least K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0862.leetcode862 Shortest Subarray with Sum at Least K-zh.md" new file mode 100644 index 00000000..2f4a4f5d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0862.leetcode862 Shortest Subarray with Sum at Least K-zh.md" @@ -0,0 +1,75 @@ +# [862. 和至少为 K 的最短子数组](https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0862.Shortest%20Subarray%20with%20Sum%20at%20Least%20K/README_EN.md) + +## 题目描述 + + + +

    返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K

    + +

    如果没有和至少为 K 的非空子数组,返回 -1 。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:A = [1], K = 1
    +输出:1
    +
    + +

    示例 2:

    + +
    输入:A = [1,2], K = 4
    +输出:-1
    +
    + +

    示例 3:

    + +
    输入:A = [2,-1,2], K = 3
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. -10 ^ 5 <= A[i] <= 10 ^ 5
    4. +
    5. 1 <= K <= 10 ^ 9
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0863.leetcode863 All Nodes Distance K in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0863.leetcode863 All Nodes Distance K in Binary Tree-zh.md" new file mode 100644 index 00000000..3c00196f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0863.leetcode863 All Nodes Distance K in Binary Tree-zh.md" @@ -0,0 +1,72 @@ +# [863. 二叉树中所有距离为 K 的结点](https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0863.All%20Nodes%20Distance%20K%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树(具有根结点 root), 一个目标结点 target ,和一个整数值 K

    + +

    返回到目标结点 target 距离为 K 的所有结点的值的列表。 答案可以以任何顺序返回。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
    +输出:[7,4,1]
    +解释:
    +所求结点为与目标结点(值为 5)距离为 2 的结点,
    +值分别为 7,4,以及 1
    +
    +
    +
    +注意,输入的 "root" 和 "target" 实际上是树上的结点。
    +上面的输入仅仅是对这些对象进行了序列化描述。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 给定的树是非空的。
    2. +
    3. 树上的每个结点都具有唯一的值 0 <= node.val <= 500 。
    4. +
    5. 目标结点 target 是树上的结点。
    6. +
    7. 0 <= K <= 1000.
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0864.leetcode864 Shortest Path to Get All Keys-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0864.leetcode864 Shortest Path to Get All Keys-zh.md" new file mode 100644 index 00000000..32cea145 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0864.leetcode864 Shortest Path to Get All Keys-zh.md" @@ -0,0 +1,71 @@ +# [864. 获取所有钥匙的最短路径](https://leetcode-cn.com/problems/shortest-path-to-get-all-keys) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0864.Shortest%20Path%20to%20Get%20All%20Keys/README_EN.md) + +## 题目描述 + + + +

    给定一个二维网格 grid。 "." 代表一个空房间, "#" 代表一堵墙, "@" 是起点,("a""b", ...)代表钥匙,("A""B", ...)代表锁。

    + +

    我们从起点开始出发,一次移动是指向四个基本方向之一行走一个单位空间。我们不能在网格外面行走,也无法穿过一堵墙。如果途经一个钥匙,我们就把它捡起来。除非我们手里有对应的钥匙,否则无法通过锁。

    + +

    假设 K 为钥匙/锁的个数,且满足 1 <= K <= 6,字母表中的前 K 个字母在网格中都有自己对应的一个小写和一个大写字母。换言之,每个锁有唯一对应的钥匙,每个钥匙也有唯一对应的锁。另外,代表钥匙和锁的字母互为大小写并按字母顺序排列。

    + +

    返回获取所有钥匙所需要的移动的最少次数。如果无法获取所有钥匙,返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    输入:["@.a.#","###.#","b.A.B"]
    +输出:8
    +
    + +

    示例 2:

    + +
    输入:["@..aA","..B#.","....b"]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= grid.length <= 30
    2. +
    3. 1 <= grid[0].length <= 30
    4. +
    5. grid[i][j] 只含有 '.''#''@''a'-'f' 以及 'A'-'F'
    6. +
    7. 钥匙的数目范围是 [1, 6],每个钥匙都对应一个不同的字母,正好打开一个对应的锁。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0865.leetcode865 Smallest Subtree with all the Deepest Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0865.leetcode865 Smallest Subtree with all the Deepest Nodes-zh.md" new file mode 100644 index 00000000..5307606a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0865.leetcode865 Smallest Subtree with all the Deepest Nodes-zh.md" @@ -0,0 +1,89 @@ +# [865. 具有所有最深节点的最小子树](https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0865.Smallest%20Subtree%20with%20all%20the%20Deepest%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给定一个根为 root 的二叉树,每个节点的深度是 该节点到根的最短距离

    + +

    如果一个节点在 整个树 的任意节点之间具有最大的深度,则该节点是 最深的

    + +

    一个节点的 子树 是该节点加上它的所有后代的集合。

    + +

    返回能满足 以该节点为根的子树中包含所有最深的节点 这一条件的具有最大深度的节点。

    + +

     

    + +

    注意:本题与力扣 1123 重复:https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves/

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4]
    +输出:[2,7,4]
    +解释:
    +我们返回值为 2 的节点,在图中用黄色标记。
    +在图中用蓝色标记的是树的最深的节点。
    +注意,节点 5、3 和 2 包含树中最深的节点,但节点 2 的子树最小,因此我们返回它。
    +
    + +

    示例 2:

    + +
    +输入:root = [1]
    +输出:[1]
    +解释:根节点是树中最深的节点。
    + +

    示例 3:

    + +
    +输入:root = [0,1,3,null,2]
    +输出:[2]
    +解释:树中最深的节点为 2 ,有效子树为节点 2、1 和 0 的子树,但节点 2 的子树最小。
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数量介于 1 和 500 之间。
    • +
    • 0 <= Node.val <= 500
    • +
    • 每个节点的值都是独一无二的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0866.leetcode866 Prime Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0866.leetcode866 Prime Palindrome-zh.md" new file mode 100644 index 00000000..6b217b1a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0866.leetcode866 Prime Palindrome-zh.md" @@ -0,0 +1,80 @@ +# [866. 回文素数](https://leetcode-cn.com/problems/prime-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0866.Prime%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    求出大于或等于 N 的最小回文素数。

    + +

    回顾一下,如果一个数大于 1,且其因数只有 1 和它自身,那么这个数是素数

    + +

    例如,2,3,5,7,11 以及 13 是素数。

    + +

    回顾一下,如果一个数从左往右读与从右往左读是一样的,那么这个数是回文数。

    + +

    例如,12321 是回文数。

    + +

     

    + +

    示例 1:

    + +
    输入:6
    +输出:7
    +
    + +

    示例 2:

    + +
    输入:8
    +输出:11
    +
    + +

    示例 3:

    + +
    输入:13
    +输出:101
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 10^8
    • +
    • 答案肯定存在,且小于 2 * 10^8
    • +
    + +

     

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0867.leetcode867 Transpose Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0867.leetcode867 Transpose Matrix-zh.md" new file mode 100644 index 00000000..41d0c40c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0867.leetcode867 Transpose Matrix-zh.md" @@ -0,0 +1,111 @@ +# [867. 转置矩阵](https://leetcode-cn.com/problems/transpose-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0867.Transpose%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 matrix, 返回 matrix转置矩阵

    + +

    矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

    + +

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    +输出:[[1,4,7],[2,5,8],[3,6,9]]
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[1,2,3],[4,5,6]]
    +输出:[[1,4],[2,5],[3,6]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 1000
    • +
    • 1 <= m * n <= 105
    • +
    • -109 <= matrix[i][j] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def transpose(self, matrix: List[List[int]]) -> List[List[int]]: + m, n = len(matrix), len(matrix[0]) + res = [[0] * m for _ in range(n)] + for i in range(n): + for j in range(m): + res[i][j] = matrix[j][i] + return res +``` + +### **Java** + + + +```java +class Solution { + public int[][] transpose(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[][] res = new int[n][m]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < m; ++j) { + res[i][j] = matrix[j][i]; + } + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} matrix + * @return {number[][]} + */ +var transpose = function (matrix) { + const m = matrix.length, + n = matrix[0].length; + let res = []; + for (let i = 0; i < n; ++i) { + res[i] = []; + for (let j = 0; j < m; ++j) { + res[i][j] = matrix[j][i]; + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0868.leetcode868 Binary Gap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0868.leetcode868 Binary Gap-zh.md" new file mode 100644 index 00000000..c22b5616 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0868.leetcode868 Binary Gap-zh.md" @@ -0,0 +1,103 @@ +# [868. 二进制间距](https://leetcode-cn.com/problems/binary-gap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0868.Binary%20Gap/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 n,找到并返回 n 的二进制表示中两个 相邻 1 之间的 最长距离 。如果不存在两个相邻的 1,返回 0

    + +

    如果只有 0 将两个 1 分隔开(可能不存在 0 ),则认为这两个 1 彼此 相邻 。两个 1 之间的距离是它们的二进制表示中位置的绝对差。例如,"1001" 中的两个 1 的距离为 3 。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:n = 22
    +输出:2
    +解释:
    +22 的二进制是 "10110" 。
    +在 22 的二进制表示中,有三个 1,组成两对相邻的 1 。
    +第一对相邻的 1 中,两个 1 之间的距离为 2 。
    +第二对相邻的 1 中,两个 1 之间的距离为 1 。
    +答案取两个距离之中最大的,也就是 2 。
    +
    + +

    示例 2:

    + +
    +输入:n = 5
    +输出:2
    +解释:
    +5 的二进制是 "101" 。
    +
    + +

    示例 3:

    + +
    +输入:n = 6
    +输出:1
    +解释:
    +6 的二进制是 "110" 。
    +
    + +

    示例 4:

    + +
    +输入:n = 8
    +输出:0
    +解释:
    +8 的二进制是 "1000" 。
    +在 8 的二进制表示中没有相邻的两个 1,所以返回 0 。
    +
    + +

    示例 5:

    + +
    +输入:n = 1
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0869.leetcode869 Reordered Power of 2-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0869.leetcode869 Reordered Power of 2-zh.md" new file mode 100644 index 00000000..bc0d2532 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0869.leetcode869 Reordered Power of 2-zh.md" @@ -0,0 +1,85 @@ +# [869. 重新排序得到 2 的幂](https://leetcode-cn.com/problems/reordered-power-of-2) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0869.Reordered%20Power%20of%202/README_EN.md) + +## 题目描述 + + + +

    给定正整数 N ,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。

    + +

    如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:1
    +输出:true
    +
    + +

    示例 2:

    + +
    输入:10
    +输出:false
    +
    + +

    示例 3:

    + +
    输入:16
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:24
    +输出:false
    +
    + +

    示例 5:

    + +
    输入:46
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10^9
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0870.leetcode870 Advantage Shuffle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0870.leetcode870 Advantage Shuffle-zh.md" new file mode 100644 index 00000000..d5bdd19d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0870.leetcode870 Advantage Shuffle-zh.md" @@ -0,0 +1,66 @@ +# [870. 优势洗牌](https://leetcode-cn.com/problems/advantage-shuffle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0870.Advantage%20Shuffle/README_EN.md) + +## 题目描述 + + + +

    给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。

    + +

    返回 A 的任意排列,使其相对于 B 的优势最大化。

    + +

     

    + +

    示例 1:

    + +
    输入:A = [2,7,11,15], B = [1,10,4,11]
    +输出:[2,11,7,15]
    +
    + +

    示例 2:

    + +
    输入:A = [12,24,8,32], B = [13,25,32,11]
    +输出:[24,32,8,12]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length = B.length <= 10000
    2. +
    3. 0 <= A[i] <= 10^9
    4. +
    5. 0 <= B[i] <= 10^9
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0871.leetcode871 Minimum Number of Refueling Stops-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0871.leetcode871 Minimum Number of Refueling Stops-zh.md" new file mode 100644 index 00000000..07311c0d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0871.leetcode871 Minimum Number of Refueling Stops-zh.md" @@ -0,0 +1,88 @@ +# [871. 最低加油次数](https://leetcode-cn.com/problems/minimum-number-of-refueling-stops) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0871.Minimum%20Number%20of%20Refueling%20Stops/README_EN.md) + +## 题目描述 + + + +

    汽车从起点出发驶向目的地,该目的地位于出发位置东面 target 英里处。

    + +

    沿途有加油站,每个 station[i] 代表一个加油站,它位于出发位置东面 station[i][0] 英里处,并且有 station[i][1] 升汽油。

    + +

    假设汽车油箱的容量是无限的,其中最初有 startFuel 升燃料。它每行驶 1 英里就会用掉 1 升汽油。

    + +

    当汽车到达加油站时,它可能停下来加油,将所有汽油从加油站转移到汽车中。

    + +

    为了到达目的地,汽车所必要的最低加油次数是多少?如果无法到达目的地,则返回 -1

    + +

    注意:如果汽车到达加油站时剩余燃料为 0,它仍然可以在那里加油。如果汽车到达目的地时剩余燃料为 0,仍然认为它已经到达目的地。

    + +

     

    + +

    示例 1:

    + +
    输入:target = 1, startFuel = 1, stations = []
    +输出:0
    +解释:我们可以在不加油的情况下到达目的地。
    +
    + +

    示例 2:

    + +
    输入:target = 100, startFuel = 1, stations = [[10,100]]
    +输出:-1
    +解释:我们无法抵达目的地,甚至无法到达第一个加油站。
    +
    + +

    示例 3:

    + +
    输入:target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
    +输出:2
    +解释:
    +我们出发时有 10 升燃料。
    +我们开车来到距起点 10 英里处的加油站,消耗 10 升燃料。将汽油从 0 升加到 60 升。
    +然后,我们从 10 英里处的加油站开到 60 英里处的加油站(消耗 50 升燃料),
    +并将汽油从 10 升加到 50 升。然后我们开车抵达目的地。
    +我们沿途在1两个加油站停靠,所以返回 2 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= target, startFuel, stations[i][1] <= 10^9
    2. +
    3. 0 <= stations.length <= 500
    4. +
    5. 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0872.leetcode872 Leaf-Similar Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0872.leetcode872 Leaf-Similar Trees-zh.md" new file mode 100644 index 00000000..3eec31eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0872.leetcode872 Leaf-Similar Trees-zh.md" @@ -0,0 +1,175 @@ +# [872. 叶子相似的树](https://leetcode-cn.com/problems/leaf-similar-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0872.Leaf-Similar%20Trees/README_EN.md) + +## 题目描述 + + + +

    请考虑一棵二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列

    + +

    + +

    举个例子,如上图所示,给定一棵叶值序列为 (6, 7, 4, 9, 8) 的树。

    + +

    如果有两棵二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。

    + +

    如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
    +输出:true
    +
    + +

    示例 2:

    + +
    输入:root1 = [1], root2 = [1]
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:root1 = [1], root2 = [2]
    +输出:false
    +
    + +

    示例 4:

    + +
    输入:root1 = [1,2], root2 = [2,2]
    +输出:true
    +
    + +

    示例 5:

    + +

    + +
    输入:root1 = [1,2,3], root2 = [1,3,2]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定的两棵树可能会有 1 到 200 个结点。
    • +
    • 给定的两棵树上的值介于 0200 之间。
    • +
    + + +## 解法 + + + +深度优先搜索。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: + def dfs(root, leaves): + if root is None: + return + if root.left is None and root.right is None: + leaves.append(root.val) + return + dfs(root.left, leaves) + dfs(root.right, leaves) + l1, l2 = [], [] + dfs(root1, l1) + dfs(root2, l2) + return l1 == l2 +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + List l1 = new ArrayList<>(); + List l2 = new ArrayList<>(); + dfs(root1, l1); + dfs(root2, l2); + return l1.equals(l2); + } + + private void dfs(TreeNode root, List leaves) { + if (root == null) return; + if (root.left == null && root.right == null) { + leaves.add(root.val); + return; + } + dfs(root.left, leaves); + dfs(root.right, leaves); + } +} +``` + +### **Go** + +```go +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + var l1, l2 []int + if root1 != nil { + dfs(root1, &l1) + } + if root2 != nil { + dfs(root2, &l2) + } + return reflect.DeepEqual(l1, l2) +} + +func dfs(root *TreeNode, leaves *[]int) { + if root.Left == nil && root.Right == nil { + *leaves = append(*leaves, root.Val) + } else { + if root.Left != nil { + dfs(root.Left, leaves) + } + if root.Right != nil { + dfs(root.Right, leaves) + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0873.leetcode873 Length of Longest Fibonacci Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0873.leetcode873 Length of Longest Fibonacci Subsequence-zh.md" new file mode 100644 index 00000000..a4e331ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0873.leetcode873 Length of Longest Fibonacci Subsequence-zh.md" @@ -0,0 +1,81 @@ +# [873. 最长的斐波那契子序列的长度](https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0873.Length%20of%20Longest%20Fibonacci%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    如果序列 X_1, X_2, ..., X_n 满足下列条件,就说它是 斐波那契式 的:

    + +
      +
    • n >= 3
    • +
    • 对于所有 i + 2 <= n,都有 X_i + X_{i+1} = X_{i+2}
    • +
    + +

    给定一个严格递增的正整数数组形成序列,找到 A 中最长的斐波那契式的子序列的长度。如果一个不存在,返回  0 。

    + +

    (回想一下,子序列是从原序列 A 中派生出来的,它从 A 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8] 是 [3, 4, 5, 6, 7, 8] 的一个子序列)

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入: [1,2,3,4,5,6,7,8]
    +输出: 5
    +解释:
    +最长的斐波那契式子序列为:[1,2,3,5,8] 。
    +
    + +

    示例 2:

    + +
    输入: [1,3,7,11,12,14,18]
    +输出: 3
    +解释:
    +最长的斐波那契式子序列有:
    +[1,11,12],[3,11,14] 以及 [7,11,18] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= A.length <= 1000
    • +
    • 1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
    • +
    • (对于以 Java,C,C++,以及 C# 的提交,时间限制被减少了 50%)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0874.leetcode874 Walking Robot Simulation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0874.leetcode874 Walking Robot Simulation-zh.md" new file mode 100644 index 00000000..76bc55c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0874.leetcode874 Walking Robot Simulation-zh.md" @@ -0,0 +1,112 @@ +# [874. 模拟行走机器人](https://leetcode-cn.com/problems/walking-robot-simulation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0874.Walking%20Robot%20Simulation/README_EN.md) + +## 题目描述 + + + +

    机器人在一个无限大小的 XY 网格平面上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令 commands

    + +
      +
    • -2 :向左转 90
    • +
    • -1 :向右转 90
    • +
    • 1 <= x <= 9 :向前移动 x 个单位长度
    • +
    + +

    在网格上有一些格子被视为障碍物 obstacles 。第 i 个障碍物位于网格点  obstacles[i] = (xi, yi)

    + +

    机器人无法走到障碍物上,它将会停留在障碍物的前一个网格方块上,但仍然可以继续尝试进行该路线的其余部分。

    + +

    返回从原点到机器人所有经过的路径点(坐标为整数)的最大欧式距离的平方。(即,如果距离为 5 ,则返回 25

    + +
    +
    +
    +
    +
     
    +
    + +
    +

    注意:

    + +
      +
    • 北表示 +Y 方向。
    • +
    • 东表示 +X 方向。
    • +
    • 南表示 -Y 方向。
    • +
    • 西表示 -X 方向。
    • +
    +
    +
    +
    +
    + +

     

    + +

    示例 1:

    + +
    +输入:commands = [4,-1,3], obstacles = []
    +输出:25
    +解释:
    +机器人开始位于 (0, 0):
    +1. 向北移动 4 个单位,到达 (0, 4)
    +2. 右转
    +3. 向东移动 3 个单位,到达 (3, 4)
    +距离原点最远的是 (3, 4) ,距离为 32 + 42 = 25
    + +

    示例 2:

    + +
    +输入:commands = [4,-1,4,-2,4], obstacles = [[2,4]]
    +输出:65
    +解释:机器人开始位于 (0, 0):
    +1. 向北移动 4 个单位,到达 (0, 4)
    +2. 右转
    +3. 向东移动 1 个单位,然后被位于 (2, 4) 的障碍物阻挡,机器人停在 (1, 4)
    +4. 左转
    +5. 向北走 4 个单位,到达 (1, 8)
    +距离原点最远的是 (1, 8) ,距离为 12 + 82 = 65
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= commands.length <= 104
    • +
    • commands[i] is one of the values in the list [-2,-1,1,2,3,4,5,6,7,8,9].
    • +
    • 0 <= obstacles.length <= 104
    • +
    • -3 * 104 <= xi, yi <= 3 * 104
    • +
    • 答案保证小于 231
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0875.leetcode875 Koko Eating Bananas-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0875.leetcode875 Koko Eating Bananas-zh.md" new file mode 100644 index 00000000..1a6160da --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0875.leetcode875 Koko Eating Bananas-zh.md" @@ -0,0 +1,200 @@ +# [875. 爱吃香蕉的珂珂](https://leetcode-cn.com/problems/koko-eating-bananas) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0875.Koko%20Eating%20Bananas/README_EN.md) + +## 题目描述 + + + +

    珂珂喜欢吃香蕉。这里有 N 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 H 小时后回来。

    + +

    珂珂可以决定她吃香蕉的速度 K (单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 K 根。如果这堆香蕉少于 K 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。  

    + +

    珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。

    + +

    返回她可以在 H 小时内吃掉所有香蕉的最小速度 KK 为整数)。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入: piles = [3,6,7,11], H = 8
    +输出: 4
    +
    + +

    示例 2:

    + +
    输入: piles = [30,11,23,4,20], H = 5
    +输出: 30
    +
    + +

    示例 3:

    + +
    输入: piles = [30,11,23,4,20], H = 6
    +输出: 23
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= piles.length <= 10^4
    • +
    • piles.length <= H <= 10^9
    • +
    • 1 <= piles[i] <= 10^9
    • +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: + left, right = 1, max(piles) + while left < right: + mid = (left + right) >> 1 + s = sum([(pile + mid - 1) // mid for pile in piles]) + if s <= h: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int minEatingSpeed(int[] piles, int h) { + int mx = 0; + for (int pile : piles) { + mx = Math.max(mx, pile); + } + int left = 1, right = mx; + while (left < right) { + int mid = (left + right) >>> 1; + int s = 0; + for (int pile : piles) { + s += (pile + mid - 1) / mid; + } + if (s <= h) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + int mx = 0; + for (auto pile : piles) { + mx = max(mx, pile); + } + int left = 1, right = mx; + while (left < right) { + int mid = left + right >> 1; + int s = 0; + for (auto pile : piles) { + s += (pile + mid - 1) / mid; + } + if (s <= h) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func minEatingSpeed(piles []int, h int) int { + mx := 0 + for _, pile := range piles { + mx = max(mx, pile) + } + left, right := 1, mx + for left < right { + mid := (left + right) >> 1 + s := 0 + for _, pile := range piles { + s += (pile + mid - 1) / mid + } + if s <= h { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **C#** + +```cs +public class Solution { + public int MinEatingSpeed(int[] piles, int h) { + int left = 1, right = piles.Max(); + while (left < right) + { + int mid = (left + right) >> 1; + int s = 0; + foreach (int pile in piles) + { + s += (pile + mid - 1) / mid; + } + if (s <= h) + { + right = mid; + } + else + { + left = mid + 1; + } + } + return left; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0876.leetcode876 Middle of the Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0876.leetcode876 Middle of the Linked List-zh.md" new file mode 100644 index 00000000..2ed58787 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0876.leetcode876 Middle of the Linked List-zh.md" @@ -0,0 +1,170 @@ +# [876. 链表的中间结点](https://leetcode-cn.com/problems/middle-of-the-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0876.Middle%20of%20the%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给定一个头结点为 head 的非空单链表,返回链表的中间结点。

    + +

    如果有两个中间结点,则返回第二个中间结点。

    + +

     

    + +

    示例 1:

    + +
    +输入:[1,2,3,4,5]
    +输出:此列表中的结点 3 (序列化形式:[3,4,5])
    +返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
    +注意,我们返回了一个 ListNode 类型的对象 ans,这样:
    +ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
    +
    + +

    示例 2:

    + +
    +输入:[1,2,3,4,5,6]
    +输出:此列表中的结点 4 (序列化形式:[4,5,6])
    +由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定链表的结点数介于 1 和 100 之间。
    • +
    + +## 解法 + + + +“快慢指针”实现。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def middleNode(self, head: ListNode) -> ListNode: + slow = fast = head + while fast and fast.next: + slow, fast = slow.next, fast.next.next + return slow +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode middleNode(ListNode head) { + ListNode slow = head, fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } +} +``` + +### **TypeScript** + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function middleNode(head: ListNode | null): ListNode | null { + let fast = head, slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + return slow; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* middleNode(ListNode* head) { + ListNode *slow = head, *fast = head; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + return slow; + } +}; +``` + +### **Go** + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func middleNode(head *ListNode) *ListNode { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + return slow +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0877.leetcode877 Stone Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0877.leetcode877 Stone Game-zh.md" new file mode 100644 index 00000000..3b7d0f30 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0877.leetcode877 Stone Game-zh.md" @@ -0,0 +1,71 @@ +# [877. 石子游戏](https://leetcode-cn.com/problems/stone-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0877.Stone%20Game/README_EN.md) + +## 题目描述 + + + +

    亚历克斯和李用几堆石子在做游戏。偶数堆石子排成一行,每堆都有正整数颗石子 piles[i] 。

    + +

    游戏以谁手中的石子最多来决出胜负。石子的总数是奇数,所以没有平局。

    + +

    亚历克斯和李轮流进行,亚历克斯先开始。 每回合,玩家从行的开始或结束处取走整堆石头。 这种情况一直持续到没有更多的石子堆为止,此时手中石子最多的玩家获胜。

    + +

    假设亚历克斯和李都发挥出最佳水平,当亚历克斯赢得比赛时返回 true ,当李赢得比赛时返回 false 。

    + +

     

    + +

    示例:

    + +
    输入:[5,3,4,5]
    +输出:true
    +解释:
    +亚历克斯先开始,只能拿前 5 颗或后 5 颗石子 。
    +假设他取了前 5 颗,这一行就变成了 [3,4,5] 。
    +如果李拿走前 3 颗,那么剩下的是 [4,5],亚历克斯拿走后 5 颗赢得 10 分。
    +如果李拿走后 5 颗,那么剩下的是 [3,4],亚历克斯拿走后 4 颗赢得 9 分。
    +这表明,取前 5 颗石子对亚历克斯来说是一个胜利的举动,所以我们返回 true 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= piles.length <= 500
    2. +
    3. piles.length 是偶数。
    4. +
    5. 1 <= piles[i] <= 500
    6. +
    7. sum(piles) 是奇数。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0878.leetcode878 Nth Magical Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0878.leetcode878 Nth Magical Number-zh.md" new file mode 100644 index 00000000..437eb80e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0878.leetcode878 Nth Magical Number-zh.md" @@ -0,0 +1,81 @@ +# [878. 第 N 个神奇数字](https://leetcode-cn.com/problems/nth-magical-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0878.Nth%20Magical%20Number/README_EN.md) + +## 题目描述 + + + +

    如果正整数可以被 A 或 B 整除,那么它是神奇的。

    + +

    返回第 N 个神奇数字。由于答案可能非常大,返回它模 10^9 + 7 的结果

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:N = 1, A = 2, B = 3
    +输出:2
    +
    + +

    示例 2:

    + +
    输入:N = 4, A = 2, B = 3
    +输出:6
    +
    + +

    示例 3:

    + +
    输入:N = 5, A = 2, B = 4
    +输出:10
    +
    + +

    示例 4:

    + +
    输入:N = 3, A = 6, B = 4
    +输出:8
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10^9
    2. +
    3. 2 <= A <= 40000
    4. +
    5. 2 <= B <= 40000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0879.leetcode879 Profitable Schemes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0879.leetcode879 Profitable Schemes-zh.md" new file mode 100644 index 00000000..9892857b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0879.leetcode879 Profitable Schemes-zh.md" @@ -0,0 +1,81 @@ +# [879. 盈利计划](https://leetcode-cn.com/problems/profitable-schemes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0879.Profitable%20Schemes/README_EN.md) + +## 题目描述 + + + +

    集团里有 n 名员工,他们可以完成各种各样的工作创造利润。

    + +

    第 i 种工作会产生 profit[i] 的利润,它要求 group[i] 名成员共同参与。如果成员参与了其中一项工作,就不能参与另一项工作。

    + +

    工作的任何至少产生 minProfit 利润的子集称为盈利计划。并且工作的成员总数最多为 n

    + +

    有多少种计划可以选择?因为答案很大,所以 返回结果模 10^9 + 7 的值

    + +
    +
    +

     

    + +

    示例 1:

    + +
    +输入:n = 5, minProfit = 3, group = [2,2], profit = [2,3]
    +输出:2
    +解释:至少产生 3 的利润,该集团可以完成工作 0 和工作 1 ,或仅完成工作 1 。
    +总的来说,有两种计划。
    + +

    示例 2:

    + +
    +输入:n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
    +输出:7
    +解释:至少产生 5 的利润,只要完成其中一种工作就行,所以该集团可以完成任何工作。
    +有 7 种可能的计划:(0),(1),(2),(0,1),(0,2),(1,2),以及 (0,1,2) 。
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 100
    • +
    • 0 <= minProfit <= 100
    • +
    • 1 <= group.length <= 100
    • +
    • 1 <= group[i] <= 100
    • +
    • profit.length == group.length
    • +
    • 0 <= profit[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0880.leetcode880 Decoded String at Index-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0880.leetcode880 Decoded String at Index-zh.md" new file mode 100644 index 00000000..9ed072aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0880.leetcode880 Decoded String at Index-zh.md" @@ -0,0 +1,87 @@ +# [880. 索引处的解码字符串](https://leetcode-cn.com/problems/decoded-string-at-index) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0880.Decoded%20String%20at%20Index/README_EN.md) + +## 题目描述 + + + +

    给定一个编码字符串 S。请你找出 解码字符串 并将其写入磁带。解码时,从编码字符串中 每次读取一个字符 ,并采取以下步骤:

    + +
      +
    • 如果所读的字符是字母,则将该字母写在磁带上。
    • +
    • 如果所读的字符是数字(例如 d),则整个当前磁带总共会被重复写 d-1 次。
    • +
    + +

    现在,对于给定的编码字符串 S 和索引 K,查找并返回解码字符串中的第 K 个字母。

    + +

     

    + +

    示例 1:

    + +
    输入:S = "leet2code3", K = 10
    +输出:"o"
    +解释:
    +解码后的字符串为 "leetleetcodeleetleetcodeleetleetcode"。
    +字符串中的第 10 个字母是 "o"。
    +
    + +

    示例 2:

    + +
    输入:S = "ha22", K = 5
    +输出:"h"
    +解释:
    +解码后的字符串为 "hahahaha"。第 5 个字母是 "h"。
    +
    + +

    示例 3:

    + +
    输入:S = "a2345678999999999999999", K = 1
    +输出:"a"
    +解释:
    +解码后的字符串为 "a" 重复 8301530446056247680 次。第 1 个字母是 "a"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= S.length <= 100
    • +
    • S 只包含小写字母与数字 29
    • +
    • S 以字母开头。
    • +
    • 1 <= K <= 10^9
    • +
    • 题目保证 K 小于或等于解码字符串的长度。
    • +
    • 解码后的字符串保证少于 2^63 个字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0881.leetcode881 Boats to Save People-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0881.leetcode881 Boats to Save People-zh.md" new file mode 100644 index 00000000..6d954437 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0881.leetcode881 Boats to Save People-zh.md" @@ -0,0 +1,98 @@ +# [881. 救生艇](https://leetcode-cn.com/problems/boats-to-save-people) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0881.Boats%20to%20Save%20People/README_EN.md) + +## 题目描述 + + + +

    第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit

    + +

    每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit

    + +

    返回载到每一个人所需的最小船数。(保证每个人都能被船载)。

    + +

     

    + +

    示例 1:

    + +
    输入:people = [1,2], limit = 3
    +输出:1
    +解释:1 艘船载 (1, 2)
    +
    + +

    示例 2:

    + +
    输入:people = [3,2,2,1], limit = 3
    +输出:3
    +解释:3 艘船分别载 (1, 2), (2) 和 (3)
    +
    + +

    示例 3:

    + +
    输入:people = [3,5,3,4], limit = 5
    +输出:4
    +解释:4 艘船分别载 (3), (3), (4), (5)
    + +

    提示:

    + +
      +
    • 1 <= people.length <= 50000
    • +
    • 1 <= people[i] <= limit <= 30000
    • +
    + + +## 解法 + + + +“排序 + 双指针”实现。 + + + +### **Python3** + + + +```python +class Solution: + def numRescueBoats(self, people: List[int], limit: int) -> int: + people.sort() + num, i, j = 0, 0, len(people) - 1 + while i <= j: + if people[i] + people[j] <= limit: + i += 1 + j -= 1 + num += 1 + return num +``` + +### **Java** + + + +```java +class Solution { + public int numRescueBoats(int[] people, int limit) { + Arrays.sort(people); + int num = 0; + int i = 0, j = people.length - 1; + while (i <= j) { + if (people[i] + people[j] <= limit) { + ++i; + } + --j; + ++num; + } + return num; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0882.leetcode882 Reachable Nodes In Subdivided Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0882.leetcode882 Reachable Nodes In Subdivided Graph-zh.md" new file mode 100644 index 00000000..5a5eb1f5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0882.leetcode882 Reachable Nodes In Subdivided Graph-zh.md" @@ -0,0 +1,88 @@ +# [882. 细分图中的可到达结点](https://leetcode-cn.com/problems/reachable-nodes-in-subdivided-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0882.Reachable%20Nodes%20In%20Subdivided%20Graph/README_EN.md) + +## 题目描述 + + + +

    给你一个无向图(原始图),图中有 n 个节点,编号从 0n - 1 。你决定将图中的每条边细分为一条节点链,每条边之间的新节点数各不相同。

    + +

    图用由边组成的二维数组 edges 表示,其中 edges[i] = [ui, vi, cnti] 表示原始图中节点 ui 和 vi 之间存在一条边,cnti 是将边细分后的新节点总数。注意,cnti == 0 表示边不可细分。

    + +

    要细分边 [ui, vi] ,需要将其替换为 (cnti + 1) 条新边,和 cnti 个新节点。新节点为 x1, x2, ..., xcnti ,新边为 [ui, x1], [x1, x2], [x2, x3], ..., [xcnti+1, xcnti], [xcnti, vi]

    + +

    现在得到一个新的 细分图 ,请你计算从节点 0 出发,可以到达多少个节点?节点 是否可以到达的判断条件 为:如果节点间距离是 maxMoves 或更少,则视为可以到达;否则,不可到达。

    + +

    给你原始图和 maxMoves ,返回新的细分图中从节点 0 出发 可到达的节点数

    + +

     

    + +

    示例 1:

    + +
    +输入:edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
    +输出:13
    +解释:边的细分情况如上图所示。
    +可以到达的节点已经用黄色标注出来。
    +
    + +

    示例 2:

    + +
    +输入:edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
    +输出:23
    +
    + +

    示例 3:

    + +
    +输入:edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
    +输出:1
    +解释:节点 0 与图的其余部分没有连通,所以只有节点 0 可以到达。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= edges.length <= min(n * (n - 1) / 2, 104)
    • +
    • edges[i].length == 3
    • +
    • 0 <= ui < vi < n
    • +
    • 图中 不存在平行边
    • +
    • 0 <= cnti <= 104
    • +
    • 0 <= maxMoves <= 109
    • +
    • 1 <= n <= 3000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0883.leetcode883 Projection Area of 3D Shapes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0883.leetcode883 Projection Area of 3D Shapes-zh.md" new file mode 100644 index 00000000..dff24e49 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0883.leetcode883 Projection Area of 3D Shapes-zh.md" @@ -0,0 +1,106 @@ +# [883. 三维形体投影面积](https://leetcode-cn.com/problems/projection-area-of-3d-shapes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0883.Projection%20Area%20of%203D%20Shapes/README_EN.md) + +## 题目描述 + + + +

    在 N * N 的网格中,我们放置了一些与 x,y,z 三轴对齐的 1 * 1 * 1 立方体。

    + +

    每个值 v = grid[i][j] 表示 v 个正方体叠放在单元格 (i, j) 上。

    + +

    现在,我们查看这些立方体在 xy、yz 和 zx 平面上的投影

    + +

    投影就像影子,将三维形体映射到一个二维平面上。

    + +

    在这里,从顶部、前面和侧面看立方体时,我们会看到“影子”。

    + +

    返回所有三个投影的总面积。

    + +

     

    + +
      +
    + +
      +
    + +
      +
    + +
      +
    + +

    示例 1:

    + +
    输入:[[2]]
    +输出:5
    +
    + +

    示例 2:

    + +
    输入:[[1,2],[3,4]]
    +输出:17
    +解释:
    +这里有该形体在三个轴对齐平面上的三个投影(“阴影部分”)。
    +
    +
    + +

    示例 3:

    + +
    输入:[[1,0],[0,2]]
    +输出:8
    +
    + +

    示例 4:

    + +
    输入:[[1,1,1],[1,0,1],[1,1,1]]
    +输出:14
    +
    + +

    示例 5:

    + +
    输入:[[2,2,2],[2,1,2],[2,2,2]]
    +输出:21
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length = grid[0].length <= 50
    • +
    • 0 <= grid[i][j] <= 50
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0884.leetcode884 Uncommon Words from Two Sentences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0884.leetcode884 Uncommon Words from Two Sentences-zh.md" new file mode 100644 index 00000000..d90b2e71 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0884.leetcode884 Uncommon Words from Two Sentences-zh.md" @@ -0,0 +1,73 @@ +# [884. 两句话中的不常见单词](https://leetcode-cn.com/problems/uncommon-words-from-two-sentences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0884.Uncommon%20Words%20from%20Two%20Sentences/README_EN.md) + +## 题目描述 + + + +

    给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

    + +

    如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的

    + +

    返回所有不常用单词的列表。

    + +

    您可以按任何顺序返回列表。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:A = "this apple is sweet", B = "this apple is sour"
    +输出:["sweet","sour"]
    +
    + +

    示例 2:

    + +
    输入:A = "apple apple", B = "banana"
    +输出:["banana"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= A.length <= 200
    2. +
    3. 0 <= B.length <= 200
    4. +
    5. A 和 B 都只包含空格和小写字母。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0885.leetcode885 Spiral Matrix III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0885.leetcode885 Spiral Matrix III-zh.md" new file mode 100644 index 00000000..423e7dff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0885.leetcode885 Spiral Matrix III-zh.md" @@ -0,0 +1,81 @@ +# [885. 螺旋矩阵 III](https://leetcode-cn.com/problems/spiral-matrix-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0885.Spiral%20Matrix%20III/README_EN.md) + +## 题目描述 + + + +

    在 R 行 C 列的矩阵上,我们从 (r0, c0) 面朝东面开始

    + +

    这里,网格的西北角位于第一行第一列,网格的东南角位于最后一行最后一列。

    + +

    现在,我们以顺时针按螺旋状行走,访问此网格中的每个位置。

    + +

    每当我们移动到网格的边界之外时,我们会继续在网格之外行走(但稍后可能会返回到网格边界)。

    + +

    最终,我们到过网格的所有 R * C 个空间。

    + +

    按照访问顺序返回表示网格位置的坐标列表。

    + +

     

    + +

    示例 1:

    + +
    输入:R = 1, C = 4, r0 = 0, c0 = 0
    +输出:[[0,0],[0,1],[0,2],[0,3]]
    +
    +
    +
    + +

     

    + +

    示例 2:

    + +
    输入:R = 5, C = 6, r0 = 1, c0 = 4
    +输出:[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
    +
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= R <= 100
    2. +
    3. 1 <= C <= 100
    4. +
    5. 0 <= r0 < R
    6. +
    7. 0 <= c0 < C
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0886.leetcode886 Possible Bipartition-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0886.leetcode886 Possible Bipartition-zh.md" new file mode 100644 index 00000000..f9599da3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0886.leetcode886 Possible Bipartition-zh.md" @@ -0,0 +1,86 @@ +# [886. 可能的二分法](https://leetcode-cn.com/problems/possible-bipartition) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0886.Possible%20Bipartition/README_EN.md) + +## 题目描述 + + + +

    给定一组 N 人(编号为 1, 2, ..., N), 我们想把每个人分进任意大小的两组。

    + +

    每个人都可能不喜欢其他人,那么他们不应该属于同一组。

    + +

    形式上,如果 dislikes[i] = [a, b],表示不允许将编号为 ab 的人归入同一组。

    + +

    当可以用这种方法将所有人分进两组时,返回 true;否则返回 false

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:N = 4, dislikes = [[1,2],[1,3],[2,4]]
    +输出:true
    +解释:group1 [1,4], group2 [2,3]
    +
    + +

    示例 2:

    + +
    +输入:N = 3, dislikes = [[1,2],[1,3],[2,3]]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 2000
    • +
    • 0 <= dislikes.length <= 10000
    • +
    • dislikes[i].length == 2
    • +
    • 1 <= dislikes[i][j] <= N
    • +
    • dislikes[i][0] < dislikes[i][1]
    • +
    • 对于 dislikes[i] == dislikes[j] 不存在 i != j
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0887.leetcode887 Super Egg Drop-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0887.leetcode887 Super Egg Drop-zh.md" new file mode 100644 index 00000000..0ddb6f1f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0887.leetcode887 Super Egg Drop-zh.md" @@ -0,0 +1,82 @@ +# [887. 鸡蛋掉落](https://leetcode-cn.com/problems/super-egg-drop) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0887.Super%20Egg%20Drop/README_EN.md) + +## 题目描述 + + + +

    给你 k 枚相同的鸡蛋,并可以使用一栋从第 1 层到第 n 层共有 n 层楼的建筑。

    + +

    已知存在楼层 f ,满足 0 <= f <= n ,任何从 高于 f 的楼层落下的鸡蛋都会碎,从 f 楼层或比它低的楼层落下的鸡蛋都不会破。

    + +

    每次操作,你可以取一枚没有碎的鸡蛋并把它从任一楼层 x 扔下(满足 1 <= x <= n)。如果鸡蛋碎了,你就不能再次使用它。如果某枚鸡蛋扔下后没有摔碎,则可以在之后的操作中 重复使用 这枚鸡蛋。

    + +

    请你计算并返回要确定 f 确切的值最小操作次数 是多少?

    +  + +

    示例 1:

    + +
    +输入:k = 1, n = 2
    +输出:2
    +解释:
    +鸡蛋从 1 楼掉落。如果它碎了,肯定能得出 f = 0 。 
    +否则,鸡蛋从 2 楼掉落。如果它碎了,肯定能得出 f = 1 。 
    +如果它没碎,那么肯定能得出 f = 2 。 
    +因此,在最坏的情况下我们需要移动 2 次以确定 f 是多少。 
    +
    + +

    示例 2:

    + +
    +输入:k = 2, n = 6
    +输出:3
    +
    + +

    示例 3:

    + +
    +输入:k = 3, n = 14
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= 100
    • +
    • 1 <= n <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0888.leetcode888 Fair Candy Swap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0888.leetcode888 Fair Candy Swap-zh.md" new file mode 100644 index 00000000..1d39c26f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0888.leetcode888 Fair Candy Swap-zh.md" @@ -0,0 +1,141 @@ +# [888. 公平的糖果棒交换](https://leetcode-cn.com/problems/fair-candy-swap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0888.Fair%20Candy%20Swap/README_EN.md) + +## 题目描述 + + + +

    爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。

    + +

    因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)

    + +

    返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。

    + +

    如果有多个答案,你可以返回其中任何一个。保证答案存在。

    + +

     

    + +

    示例 1:

    + +
    +输入:A = [1,1], B = [2,2]
    +输出:[1,2]
    +
    + +

    示例 2:

    + +
    +输入:A = [1,2], B = [2,3]
    +输出:[1,2]
    +
    + +

    示例 3:

    + +
    +输入:A = [2], B = [1,3]
    +输出:[2,3]
    +
    + +

    示例 4:

    + +
    +输入:A = [1,2,5], B = [2,4]
    +输出:[5,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= A.length <= 10000
    • +
    • 1 <= B.length <= 10000
    • +
    • 1 <= A[i] <= 100000
    • +
    • 1 <= B[i] <= 100000
    • +
    • 保证爱丽丝与鲍勃的糖果总量不同。
    • +
    • 答案肯定存在。
    • +
    + + +## 解法 + + + +哈希表实现。 + + + +### **Python3** + + + +```python +class Solution: + def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]: + diff = (sum(aliceSizes) - sum(bobSizes)) >> 1 + s = set(bobSizes) + for a in aliceSizes: + target = a - diff + if target in s: + return [a, target] +``` + +### **Java** + + + +```java +class Solution { + public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { + int s1 = 0, s2 = 0; + Set s = new HashSet<>(); + for (int a : aliceSizes) { + s1 += a; + } + for (int b : bobSizes) { + s.add(b); + s2 += b; + } + int diff = (s1 - s2) >> 1; + for (int a : aliceSizes) { + int target = a - diff; + if (s.contains(target)) { + return new int[]{a, target}; + } + } + return null; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector fairCandySwap(vector& aliceSizes, vector& bobSizes) { + int s1 = accumulate(aliceSizes.begin(), aliceSizes.end(), 0); + int s2 = accumulate(bobSizes.begin(), bobSizes.end(), 0); + int diff = (s1 - s2) >> 1; + unordered_set s(bobSizes.begin(), bobSizes.end()); + vector ans; + for (int& a : aliceSizes) { + int target = a - diff; + if (s.count(target)) { + ans = vector{a, target}; + break; + } + } + return ans; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0889.leetcode889 Construct Binary Tree from Preorder and Postorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0889.leetcode889 Construct Binary Tree from Preorder and Postorder Traversal-zh.md" new file mode 100644 index 00000000..b527e128 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0889.leetcode889 Construct Binary Tree from Preorder and Postorder Traversal-zh.md" @@ -0,0 +1,60 @@ +# [889. 根据前序和后序遍历构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0889.Construct%20Binary%20Tree%20from%20Preorder%20and%20Postorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    返回与给定的前序和后序遍历匹配的任何二叉树。

    + +

     pre 和 post 遍历中的值是不同的正整数。

    + +

     

    + +

    示例:

    + +
    输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
    +输出:[1,2,3,4,5,6,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= pre.length == post.length <= 30
    • +
    • pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
    • +
    • 每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0890.leetcode890 Find and Replace Pattern-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0890.leetcode890 Find and Replace Pattern-zh.md" new file mode 100644 index 00000000..0d019327 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0890.leetcode890 Find and Replace Pattern-zh.md" @@ -0,0 +1,68 @@ +# [890. 查找和替换模式](https://leetcode-cn.com/problems/find-and-replace-pattern) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0890.Find%20and%20Replace%20Pattern/README_EN.md) + +## 题目描述 + + + +

    你有一个单词列表 words 和一个模式  pattern,你想知道 words 中的哪些单词与模式匹配。

    + +

    如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。

    + +

    (回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)

    + +

    返回 words 中与给定模式匹配的单词列表。

    + +

    你可以按任何顺序返回答案。

    + +

     

    + +

    示例:

    + +
    输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
    +输出:["mee","aqq"]
    +解释:
    +"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
    +"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。
    +因为 a 和 b 映射到同一个字母。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 50
    • +
    • 1 <= pattern.length = words[i].length <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0891.leetcode891 Sum of Subsequence Widths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0891.leetcode891 Sum of Subsequence Widths-zh.md" new file mode 100644 index 00000000..516f091d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0891.leetcode891 Sum of Subsequence Widths-zh.md" @@ -0,0 +1,67 @@ +# [891. 子序列宽度之和](https://leetcode-cn.com/problems/sum-of-subsequence-widths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0891.Sum%20of%20Subsequence%20Widths/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A ,考虑 A 的所有非空子序列。

    + +

    对于任意序列 S ,设 S 的宽度是 S 的最大元素和最小元素的差。

    + +

    返回 A 的所有子序列的宽度之和。

    + +

    由于答案可能非常大,请返回答案模 10^9+7

    + +

     

    + +

    示例:

    + +
    输入:[2,1,3]
    +输出:6
    +解释:
    +子序列为 [1],[2],[3],[2,1],[2,3],[1,3],[2,1,3] 。
    +相应的宽度是 0,0,0,1,1,2,2 。
    +这些宽度之和是 6 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= A.length <= 20000
    • +
    • 1 <= A[i] <= 20000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0892.leetcode892 Surface Area of 3D Shapes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0892.leetcode892 Surface Area of 3D Shapes-zh.md" new file mode 100644 index 00000000..5cba859e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0892.leetcode892 Surface Area of 3D Shapes-zh.md" @@ -0,0 +1,99 @@ +# [892. 三维形体的表面积](https://leetcode-cn.com/problems/surface-area-of-3d-shapes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0892.Surface%20Area%20of%203D%20Shapes/README_EN.md) + +## 题目描述 + + + +

    给你一个 n * n 的网格 grid ,上面放置着一些 1 x 1 x 1 的正方体。

    + +

    每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。

    + +

    放置好正方体后,任何直接相邻的正方体都会互相粘在一起,形成一些不规则的三维形体。

    + +

    请你返回最终这些形体的总表面积。

    + +

    注意:每个形体的底面也需要计入表面积中。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:grid = [[2]]
    +输出:10
    +
    + +

    示例 2:

    + +
    +输入:grid = [[1,2],[3,4]]
    +输出:34
    +
    + +

    示例 3:

    + +
    +输入:grid = [[1,0],[0,2]]
    +输出:16
    +
    + +

    示例 4:

    + +
    +输入:grid = [[1,1,1],[1,0,1],[1,1,1]]
    +输出:32
    +
    + +

    示例 5:

    + +
    +输入:grid = [[2,2,2],[2,1,2],[2,2,2]]
    +输出:46
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 50
    • +
    • 0 <= grid[i][j] <= 50
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0893.leetcode893 Groups of Special-Equivalent Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0893.leetcode893 Groups of Special-Equivalent Strings-zh.md" new file mode 100644 index 00000000..22725de5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0893.leetcode893 Groups of Special-Equivalent Strings-zh.md" @@ -0,0 +1,87 @@ +# [893. 特殊等价字符串组](https://leetcode-cn.com/problems/groups-of-special-equivalent-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0893.Groups%20of%20Special-Equivalent%20Strings/README_EN.md) + +## 题目描述 + + + +

    你将得到一个字符串数组 A

    + +

    每次移动都可以交换 S 的任意两个偶数下标的字符或任意两个奇数下标的字符。

    + +

    如果经过任意次数的移动,S == T,那么两个字符串 ST特殊等价 的。

    + +

    例如,S = "zzxy"T = "xyzz" 是一对特殊等价字符串,因为可以先交换 S[0]S[2],然后交换 S[1]S[3],使得 "zzxy" -> "xzzy" -> "xyzz"

    + +

    现在规定,A 一组特殊等价字符串 就是 A 的一个同时满足下述条件的非空子集:

    + +
      +
    1. 该组中的每一对字符串都是 特殊等价
    2. +
    3. 该组字符串已经涵盖了该类别中的所有特殊等价字符串,容量达到理论上的最大值(也就是说,如果一个字符串不在该组中,那么这个字符串就 不会 与该组内任何字符串特殊等价)
    4. +
    + +

    返回 A 中特殊等价字符串组的数量。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
    +输出:3
    +解释:
    +其中一组为 ["abcd", "cdab", "cbad"],因为它们是成对的特殊等价字符串,且没有其他字符串与这些字符串特殊等价。
    +另外两组分别是 ["xyzz", "zzxy"] 和 ["zzyx"]。特别需要注意的是,"zzxy" 不与 "zzyx" 特殊等价。
    +
    + +

    示例 2:

    + +
    输入:["abc","acb","bac","bca","cab","cba"]
    +输出:3
    +解释:3 组 ["abc","cba"],["acb","bca"],["bac","cab"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= A.length <= 1000
    • +
    • 1 <= A[i].length <= 20
    • +
    • 所有 A[i] 都具有相同的长度。
    • +
    • 所有 A[i] 都只由小写字母组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0894.leetcode894 All Possible Full Binary Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0894.leetcode894 All Possible Full Binary Trees-zh.md" new file mode 100644 index 00000000..ab0db296 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0894.leetcode894 All Possible Full Binary Trees-zh.md" @@ -0,0 +1,64 @@ +# [894. 所有可能的满二叉树](https://leetcode-cn.com/problems/all-possible-full-binary-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0894.All%20Possible%20Full%20Binary%20Trees/README_EN.md) + +## 题目描述 + + + +

    满二叉树是一类二叉树,其中每个结点恰好有 0 或 2 个子结点。

    + +

    返回包含 N 个结点的所有可能满二叉树的列表。 答案的每个元素都是一个可能树的根结点。

    + +

    答案中每个树的每个结点必须node.val=0

    + +

    你可以按任何顺序返回树的最终列表。

    + +

     

    + +

    示例:

    + +
    输入:7
    +输出:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
    +解释:
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0895.leetcode895 Maximum Frequency Stack-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0895.leetcode895 Maximum Frequency Stack-zh.md" new file mode 100644 index 00000000..503ffc01 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0895.leetcode895 Maximum Frequency Stack-zh.md" @@ -0,0 +1,89 @@ +# [895. 最大频率栈](https://leetcode-cn.com/problems/maximum-frequency-stack) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0895.Maximum%20Frequency%20Stack/README_EN.md) + +## 题目描述 + + + +

    实现 FreqStack,模拟类似栈的数据结构的操作的一个类。

    + +

    FreqStack 有两个函数:

    + +
      +
    • push(int x),将整数 x 推入栈中。
    • +
    • pop(),它移除并返回栈中出现最频繁的元素。 +
        +
      • 如果最频繁的元素不只一个,则移除并返回最接近栈顶的元素。
      • +
      +
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],
    +[[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
    +输出:[null,null,null,null,null,null,null,5,7,5,4]
    +解释:
    +执行六次 .push 操作后,栈自底向上为 [5,7,5,7,4,5]。然后:
    +
    +pop() -> 返回 5,因为 5 是出现频率最高的。
    +栈变成 [5,7,5,7,4]。
    +
    +pop() -> 返回 7,因为 5 和 7 都是频率最高的,但 7 最接近栈顶。
    +栈变成 [5,7,5,4]。
    +
    +pop() -> 返回 5 。
    +栈变成 [5,7,4]。
    +
    +pop() -> 返回 4 。
    +栈变成 [5,7]。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 对 FreqStack.push(int x) 的调用中 0 <= x <= 10^9
    • +
    • 如果栈的元素数目为零,则保证不会调用  FreqStack.pop()
    • +
    • 单个测试样例中,对 FreqStack.push 的总调用次数不会超过 10000
    • +
    • 单个测试样例中,对 FreqStack.pop 的总调用次数不会超过 10000
    • +
    • 所有测试样例中,对 FreqStack.push 和 FreqStack.pop 的总调用次数不会超过 150000
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0896.leetcode896 Monotonic Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0896.leetcode896 Monotonic Array-zh.md" new file mode 100644 index 00000000..b940eb69 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0896.leetcode896 Monotonic Array-zh.md" @@ -0,0 +1,115 @@ +# [896. 单调数列](https://leetcode-cn.com/problems/monotonic-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0896.Monotonic%20Array/README_EN.md) + +## 题目描述 + + + +

    如果数组是单调递增或单调递减的,那么它是单调的

    + +

    如果对于所有 i <= jA[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= jA[i]> = A[j],那么数组 A 是单调递减的。

    + +

    当给定的数组 A 是单调数组时返回 true,否则返回 false

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:[1,2,2,3]
    +输出:true
    +
    + +

    示例 2:

    + +
    输入:[6,5,4,4]
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:[1,3,2]
    +输出:false
    +
    + +

    示例 4:

    + +
    输入:[1,2,4,5]
    +输出:true
    +
    + +

    示例 5:

    + +
    输入:[1,1,1]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. -100000 <= A[i] <= 100000
    4. +
    + + +## 解法 + + + +遍历数组: + +- 出现递减,将 `increase` 置为 `false`; +- 出现递增,将 `decrease` 置为 `false`; +- 既非递增也非递减,提前返回 `false`; +- 遍历结束,若出现递增或递减,返回 `true`。 + + + +### **Python3** + + + +```python +class Solution: + def isMonotonic(self, A: List[int]) -> bool: + increase = decrease = True + for i in range(1, len(A)): + if not increase and not decrease: + return False + if A[i] < A[i - 1]: + increase = False + elif A[i] > A[i - 1]: + decrease = False + return increase or decrease +``` + +### **Java** + + + +```java +class Solution { + public boolean isMonotonic(int[] A) { + boolean increase = true, decrease = true; + for (int i = 1, n = A.length; i < n; ++i) { + if (!increase && !decrease) return false; + if (A[i] < A[i - 1]) decrease = false; + else if (A[i] > A[i - 1]) increase = false; + } + return increase || decrease; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0897.leetcode897 Increasing Order Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0897.leetcode897 Increasing Order Search Tree-zh.md" new file mode 100644 index 00000000..86d962c1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0897.leetcode897 Increasing Order Search Tree-zh.md" @@ -0,0 +1,121 @@ +# [897. 递增顺序搜索树](https://leetcode-cn.com/problems/increasing-order-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0897.Increasing%20Order%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
    +输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
    +
    + +

    示例 2:

    + +
    +输入:root = [5,1,7]
    +输出:[1,null,5,null,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数的取值范围是 [1, 100]
    • +
    • 0 <= Node.val <= 1000
    • +
    + + +## 解法 + + + +递归将左子树、右子树转换为左、右链表 left 和 right。然后将左链表 left 的最后一个结点的 right 指针指向 root,root 的 right 指针指向右链表 right,并将 root 的 left 指针值为空。 + +同[面试题 17.12. BiNode](/lcci/17.12.BiNode/README.md)。 + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def increasingBST(self, root: TreeNode) -> TreeNode: + if root is None: + return None + left = self.increasingBST(root.left) + right = self.increasingBST(root.right) + if left is None: + root.right = right + return root + res = left + while left and left.right: + left = left.right + left.right = root + root.right = right + root.left = None + return res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode increasingBST(TreeNode root) { + if (root == null) return null; + TreeNode left = increasingBST(root.left); + TreeNode right = increasingBST(root.right); + if (left == null) { + root.right = right; + return root; + } + TreeNode res = left; + while (left != null && left.right != null) left = left.right; + left.right = root; + root.right = right; + root.left = null; + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0898.leetcode898 Bitwise ORs of Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0898.leetcode898 Bitwise ORs of Subarrays-zh.md" new file mode 100644 index 00000000..9abd7e8c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0898.leetcode898 Bitwise ORs of Subarrays-zh.md" @@ -0,0 +1,81 @@ +# [898. 子数组按位或操作](https://leetcode-cn.com/problems/bitwise-ors-of-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0898.Bitwise%20ORs%20of%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    我们有一个非负整数数组 A

    + +

    对于每个(连续的)子数组 B = [A[i], A[i+1], ..., A[j]] ( i <= j),我们对 B 中的每个元素进行按位或操作,获得结果 A[i] | A[i+1] | ... | A[j]

    + +

    返回可能结果的数量。 (多次出现的结果在最终答案中仅计算一次。)

    + +

     

    + +

    示例 1:

    + +
    输入:[0]
    +输出:1
    +解释:
    +只有一个可能的结果 0 。
    +
    + +

    示例 2:

    + +
    输入:[1,1,2]
    +输出:3
    +解释:
    +可能的子数组为 [1],[1],[2],[1, 1],[1, 2],[1, 1, 2]。
    +产生的结果为 1,1,2,1,3,3 。
    +有三个唯一值,所以答案是 3 。
    +
    + +

    示例 3:

    + +
    输入:[1,2,4]
    +输出:6
    +解释:
    +可能的结果是 1,2,3,4,6,以及 7 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. 0 <= A[i] <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0899.leetcode899 Orderly Queue-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0899.leetcode899 Orderly Queue-zh.md" new file mode 100644 index 00000000..607410ec --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0899.leetcode899 Orderly Queue-zh.md" @@ -0,0 +1,73 @@ +# [899. 有序队列](https://leetcode-cn.com/problems/orderly-queue) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0800-0899/0899.Orderly%20Queue/README_EN.md) + +## 题目描述 + + + +

    给出了一个由小写字母组成的字符串 S。然后,我们可以进行任意次数的移动

    + +

    在每次移动中,我们选择前 K 个字母中的一个(从左侧开始),将其从原位置移除,并放置在字符串的末尾。

    + +

    返回我们在任意次数的移动之后可以拥有的按字典顺序排列的最小字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:S = "cba", K = 1
    +输出:"acb"
    +解释:
    +在第一步中,我们将第一个字符(“c”)移动到最后,获得字符串 “bac”。
    +在第二步中,我们将第一个字符(“b”)移动到最后,获得最终结果 “acb”。
    +
    + +

    示例 2:

    + +
    输入:S = "baaca", K = 3
    +输出:"aaabc"
    +解释:
    +在第一步中,我们将第一个字符(“b”)移动到最后,获得字符串 “aacab”。
    +在第二步中,我们将第三个字符(“c”)移动到最后,获得最终结果 “aaabc”。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= K <= S.length <= 1000
    2. +
    3. S 只由小写字母组成。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0900.leetcode900 RLE Iterator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0900.leetcode900 RLE Iterator-zh.md" new file mode 100644 index 00000000..62321b97 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0900.leetcode900 RLE Iterator-zh.md" @@ -0,0 +1,79 @@ +# [900. RLE 迭代器](https://leetcode-cn.com/problems/rle-iterator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0900.RLE%20Iterator/README_EN.md) + +## 题目描述 + + + +

    编写一个遍历游程编码序列的迭代器。

    + +

    迭代器由 RLEIterator(int[] A) 初始化,其中 A 是某个序列的游程编码。更具体地,对于所有偶数 iA[i] 告诉我们在序列中重复非负整数值 A[i + 1] 的次数。

    + +

    迭代器支持一个函数:next(int n),它耗尽接下来的  n 个元素(n >= 1)并返回以这种方式耗去的最后一个元素。如果没有剩余的元素可供耗尽,则  next 返回 -1

    + +

    例如,我们以 A = [3,8,0,9,2,5] 开始,这是序列 [8,8,8,5,5] 的游程编码。这是因为该序列可以读作 “三个八,零个九,两个五”。

    + +

     

    + +

    示例:

    + +
    输入:["RLEIterator","next","next","next","next"], [[[3,8,0,9,2,5]],[2],[1],[1],[2]]
    +输出:[null,8,8,5,-1]
    +解释:
    +RLEIterator 由 RLEIterator([3,8,0,9,2,5]) 初始化。
    +这映射到序列 [8,8,8,5,5]。
    +然后调用 RLEIterator.next 4次。
    +
    +.next(2) 耗去序列的 2 个项,返回 8。现在剩下的序列是 [8, 5, 5]。
    +
    +.next(1) 耗去序列的 1 个项,返回 8。现在剩下的序列是 [5, 5]。
    +
    +.next(1) 耗去序列的 1 个项,返回 5。现在剩下的序列是 [5]。
    +
    +.next(2) 耗去序列的 2 个项,返回 -1。 这是由于第一个被耗去的项是 5,
    +但第二个项并不存在。由于最后一个要耗去的项不存在,我们返回 -1。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= A.length <= 1000
    2. +
    3. A.length 是偶数。
    4. +
    5. 0 <= A[i] <= 10^9
    6. +
    7. 每个测试用例最多调用 1000 次 RLEIterator.next(int n)
    8. +
    9. 每次调用 RLEIterator.next(int n) 都有 1 <= n <= 10^9 。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0901.leetcode901 Online Stock Span-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0901.leetcode901 Online Stock Span-zh.md" new file mode 100644 index 00000000..b66fe588 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0901.leetcode901 Online Stock Span-zh.md" @@ -0,0 +1,75 @@ +# [901. 股票价格跨度](https://leetcode-cn.com/problems/online-stock-span) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0901.Online%20Stock%20Span/README_EN.md) + +## 题目描述 + + + +

    编写一个 StockSpanner 类,它收集某些股票的每日报价,并返回该股票当日价格的跨度。

    + +

    今天股票价格的跨度被定义为股票价格小于或等于今天价格的最大连续日数(从今天开始往回数,包括今天)。

    + +

    例如,如果未来7天股票的价格是 [100, 80, 60, 70, 60, 75, 85],那么股票跨度将是 [1, 1, 1, 2, 1, 4, 6]

    + +

     

    + +

    示例:

    + +
    输入:["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
    +输出:[null,1,1,1,2,1,4,6]
    +解释:
    +首先,初始化 S = StockSpanner(),然后:
    +S.next(100) 被调用并返回 1,
    +S.next(80) 被调用并返回 1,
    +S.next(60) 被调用并返回 1,
    +S.next(70) 被调用并返回 2,
    +S.next(60) 被调用并返回 1,
    +S.next(75) 被调用并返回 4,
    +S.next(85) 被调用并返回 6。
    +
    +注意 (例如) S.next(75) 返回 4,因为截至今天的最后 4 个价格
    +(包括今天的价格 75) 小于或等于今天的价格。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 调用 StockSpanner.next(int price) 时,将有 1 <= price <= 10^5
    2. +
    3. 每个测试用例最多可以调用  10000StockSpanner.next
    4. +
    5. 在所有测试用例中,最多调用 150000 次 StockSpanner.next
    6. +
    7. 此问题的总时间限制减少了 50%。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0902.leetcode902 Numbers At Most N Given Digit Set-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0902.leetcode902 Numbers At Most N Given Digit Set-zh.md" new file mode 100644 index 00000000..f6a6361f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0902.leetcode902 Numbers At Most N Given Digit Set-zh.md" @@ -0,0 +1,74 @@ +# [902. 最大为 N 的数字组合](https://leetcode-cn.com/problems/numbers-at-most-n-given-digit-set) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0902.Numbers%20At%20Most%20N%20Given%20Digit%20Set/README_EN.md) + +## 题目描述 + + + +

    我们有一组排序的数字 D,它是  {'1','2','3','4','5','6','7','8','9'} 的非空子集。(请注意,'0' 不包括在内。)

    + +

    现在,我们用这些数字进行组合写数字,想用多少次就用多少次。例如 D = {'1','3','5'},我们可以写出像 '13', '551', '1351315' 这样的数字。

    + +

    返回可以用 D 中的数字写出的小于或等于 N 的正整数的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:D = ["1","3","5","7"], N = 100
    +输出:20
    +解释:
    +可写出的 20 个数字是:
    +1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
    +
    + +

    示例 2:

    + +
    输入:D = ["1","4","9"], N = 1000000000
    +输出:29523
    +解释:
    +我们可以写 3 个一位数字,9 个两位数字,27 个三位数字,
    +81 个四位数字,243 个五位数字,729 个六位数字,
    +2187 个七位数字,6561 个八位数字和 19683 个九位数字。
    +总共,可以使用D中的数字写出 29523 个整数。
    + +

     

    + +

    提示:

    + +
      +
    1. D 是按排序顺序的数字 '1'-'9' 的子集。
    2. +
    3. 1 <= N <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0903.leetcode903 Valid Permutations for DI Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0903.leetcode903 Valid Permutations for DI Sequence-zh.md" new file mode 100644 index 00000000..68969d68 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0903.leetcode903 Valid Permutations for DI Sequence-zh.md" @@ -0,0 +1,74 @@ +# [903. DI 序列的有效排列](https://leetcode-cn.com/problems/valid-permutations-for-di-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0903.Valid%20Permutations%20for%20DI%20Sequence/README_EN.md) + +## 题目描述 + + + +

    我们给出 S,一个源于 {'D', 'I'} 的长度为 n 的字符串 。(这些字母代表 “减少” 和 “增加”。)
    +有效排列 是对整数 {0, 1, ..., n} 的一个排列 P[0], P[1], ..., P[n],使得对所有的 i

    + +
      +
    • 如果 S[i] == 'D',那么 P[i] > P[i+1],以及;
    • +
    • 如果 S[i] == 'I',那么 P[i] < P[i+1]
    • +
    + +

    有多少个有效排列?因为答案可能很大,所以请返回你的答案模 10^9 + 7.

    + +

     

    + +

    示例:

    + +
    输入:"DID"
    +输出:5
    +解释:
    +(0, 1, 2, 3) 的五个有效排列是:
    +(1, 0, 3, 2)
    +(2, 0, 3, 1)
    +(2, 1, 3, 0)
    +(3, 0, 2, 1)
    +(3, 1, 2, 0)
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 200
    2. +
    3. S 仅由集合 {'D', 'I'} 中的字符组成。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0904.leetcode904 Fruit Into Baskets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0904.leetcode904 Fruit Into Baskets-zh.md" new file mode 100644 index 00000000..6b31090f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0904.leetcode904 Fruit Into Baskets-zh.md" @@ -0,0 +1,125 @@ +# [904. 水果成篮](https://leetcode-cn.com/problems/fruit-into-baskets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0904.Fruit%20Into%20Baskets/README_EN.md) + +## 题目描述 + + + +

    在一排树中,第 i 棵树产生 tree[i] 型的水果。
    +你可以从你选择的任何树开始,然后重复执行以下步骤:

    + +
      +
    1. 把这棵树上的水果放进你的篮子里。如果你做不到,就停下来。
    2. +
    3. 移动到当前树右侧的下一棵树。如果右边没有树,就停下来。
    4. +
    + +

    请注意,在选择一颗树后,你没有任何选择:你必须执行步骤 1,然后执行步骤 2,然后返回步骤 1,然后执行步骤 2,依此类推,直至停止。

    + +

    你有两个篮子,每个篮子可以携带任何数量的水果,但你希望每个篮子只携带一种类型的水果。

    + +

    用这个程序你能收集的水果树的最大总量是多少?

    + +

     

    + +

    示例 1:

    + +
    输入:[1,2,1]
    +输出:3
    +解释:我们可以收集 [1,2,1]。
    +
    + +

    示例 2:

    + +
    输入:[0,1,2,2]
    +输出:3
    +解释:我们可以收集 [1,2,2]
    +如果我们从第一棵树开始,我们将只能收集到 [0, 1]。
    +
    + +

    示例 3:

    + +
    输入:[1,2,3,2,2]
    +输出:4
    +解释:我们可以收集 [2,3,2,2]
    +如果我们从第一棵树开始,我们将只能收集到 [1, 2]。
    +
    + +

    示例 4:

    + +
    输入:[3,3,3,1,2,1,1,2,3,3,4]
    +输出:5
    +解释:我们可以收集 [1,2,1,1,2]
    +如果我们从第一棵树或第八棵树开始,我们将只能收集到 4 棵水果树。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= tree.length <= 40000
    • +
    • 0 <= tree[i] < tree.length
    • +
    + + +## 解法 + + + +“计数器 + 滑动窗口”实现。 + + + +### **Python3** + + + +```python +class Solution: + def totalFruit(self, tree: List[int]) -> int: + counter = collections.Counter() + i = res = 0 + for j, type in enumerate(tree): + counter[type] += 1 + while len(counter) > 2: + counter[tree[i]] -= 1 + if counter[tree[i]] == 0: + counter.pop(tree[i]) + i += 1 + res = max(res, j - i + 1) + return res +``` + +### **Java** + + + +```java +class Solution { + public int totalFruit(int[] tree) { + Map counter = new HashMap<>(); + int i = 0, res = 0; + for (int j = 0; j < tree.length; ++j) { + counter.put(tree[j], counter.getOrDefault(tree[j], 0) + 1); + while (counter.size() > 2) { + counter.put(tree[i], counter.get(tree[i]) - 1); + if (counter.get(tree[i]) == 0) { + counter.remove(tree[i]); + } + ++i; + } + res = Math.max(res, j - i + 1); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0905.leetcode905 Sort Array By Parity-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0905.leetcode905 Sort Array By Parity-zh.md" new file mode 100644 index 00000000..a8992904 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0905.leetcode905 Sort Array By Parity-zh.md" @@ -0,0 +1,116 @@ +# [905. 按奇偶排序数组](https://leetcode-cn.com/problems/sort-array-by-parity) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0905.Sort%20Array%20By%20Parity/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。

    + +

    你可以返回满足此条件的任何数组作为答案。

    + +

     

    + +

    示例:

    + +
    输入:[3,1,2,4]
    +输出:[2,4,3,1]
    +输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 5000
    2. +
    3. 0 <= A[i] <= 5000
    4. +
    + +## 解法 + + + +双指针原地交换数组元素。 + + + +### **Python3** + + + +```python +class Solution: + def sortArrayByParity(self, A: List[int]) -> List[int]: + i, j = 0, len(A) - 1 + while i < j: + if (A[i] & 1) > (A[j] & 1): + A[i], A[j] = A[j], A[i] + if A[i] & 1 == 0: + i += 1 + if A[j] & 1 == 1: + j -= 1 + return A +``` + +### **Java** + + + +```java +class Solution { + public int[] sortArrayByParity(int[] A) { + int i = 0, j = A.length - 1; + while (i < j) { + if ((A[i] & 1) > (A[j] & 1)) { + int t = A[i]; + A[i] = A[j]; + A[j] = t; + } + if ((A[i] & 1) == 0) { + ++i; + } + if ((A[j] & 1) == 1) { + --j; + } + } + return A; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} A + * @return {number[]} + */ +var sortArrayByParity = function (A) { + let i = 0; + let j = A.length - 1; + while (i < j) { + if ((A[i] & 1) > (A[j] & 1)) { + const t = A[i]; + A[i] = A[j]; + A[j] = t; + } + if ((A[i] & 1) == 0) { + ++i; + } + if ((A[j] & 1) == 1) { + --j; + } + } + return A; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0906.leetcode906 Super Palindromes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0906.leetcode906 Super Palindromes-zh.md" new file mode 100644 index 00000000..b7cc9f34 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0906.leetcode906 Super Palindromes-zh.md" @@ -0,0 +1,65 @@ +# [906. 超级回文数](https://leetcode-cn.com/problems/super-palindromes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0906.Super%20Palindromes/README_EN.md) + +## 题目描述 + + + +

    如果一个正整数自身是回文数,而且它也是一个回文数的平方,那么我们称这个数为超级回文数。

    + +

    现在,给定两个正整数 L 和 R (以字符串形式表示),返回包含在范围 [L, R] 中的超级回文数的数目。

    + +

     

    + +

    示例:

    + +
    输入:L = "4", R = "1000"
    +输出:4
    +解释:
    +4,9,121,以及 484 是超级回文数。
    +注意 676 不是一个超级回文数: 26 * 26 = 676,但是 26 不是回文数。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= len(L) <= 18
    2. +
    3. 1 <= len(R) <= 18
    4. +
    5. L 和 R 是表示 [1, 10^18) 范围的整数的字符串。
    6. +
    7. int(L) <= int(R)
    8. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0907.leetcode907 Sum of Subarray Minimums-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0907.leetcode907 Sum of Subarray Minimums-zh.md" new file mode 100644 index 00000000..b63dde82 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0907.leetcode907 Sum of Subarray Minimums-zh.md" @@ -0,0 +1,71 @@ +# [907. 子数组的最小值之和](https://leetcode-cn.com/problems/sum-of-subarray-minimums) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 arr,找到 min(b) 的总和,其中 b 的范围为 arr 的每个(连续)子数组。

    + +

    由于答案可能很大,因此 返回答案模 10^9 + 7

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [3,1,2,4]
    +输出:17
    +解释:
    +子数组为 [3],[1],[2],[4],[3,1],[1,2],[2,4],[3,1,2],[1,2,4],[3,1,2,4]。 
    +最小值为 3,1,2,4,1,1,2,1,1,1,和为 17。
    + +

    示例 2:

    + +
    +输入:arr = [11,81,94,43,3]
    +输出:444
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 3 * 104
    • +
    • 1 <= arr[i] <= 3 * 104
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0908.leetcode908 Smallest Range I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0908.leetcode908 Smallest Range I-zh.md" new file mode 100644 index 00000000..11dff9e1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0908.leetcode908 Smallest Range I-zh.md" @@ -0,0 +1,78 @@ +# [908. 最小差值 I](https://leetcode-cn.com/problems/smallest-range-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0908.Smallest%20Range%20I/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 A,请你给数组中的每个元素 A[i] 都加上一个任意数字 x-K <= x <= K),从而得到一个新数组 B

    + +

    返回数组 B 的最大值和最小值之间可能存在的最小差值。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:A = [1], K = 0
    +输出:0
    +解释:B = [1]
    +
    + +

    示例 2:

    + +
    输入:A = [0,10], K = 2
    +输出:6
    +解释:B = [2,8]
    +
    + +

    示例 3:

    + +
    输入:A = [1,3,6], K = 3
    +输出:0
    +解释:B = [3,3,3] 或 B = [4,4,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. 0 <= A[i] <= 10000
    4. +
    5. 0 <= K <= 10000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0909.leetcode909 Snakes and Ladders-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0909.leetcode909 Snakes and Ladders-zh.md" new file mode 100644 index 00000000..3105449e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0909.leetcode909 Snakes and Ladders-zh.md" @@ -0,0 +1,97 @@ +# [909. 蛇梯棋](https://leetcode-cn.com/problems/snakes-and-ladders) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0909.Snakes%20and%20Ladders/README_EN.md) + +## 题目描述 + + + +

    N x N 的棋盘 board 上,按从 1N*N 的数字给方格编号,编号 从左下角开始,每一行交替方向。

    + +

    例如,一块 6 x 6 大小的棋盘,编号如下:

    + +
    
    +
    + +

    rc 列的棋盘,按前述方法编号,棋盘格中可能存在 “蛇” 或 “梯子”;如果 board[r][c] != -1,那个蛇或梯子的目的地将会是 board[r][c]

    + +

    玩家从棋盘上的方格 1 (总是在最后一行、第一列)开始出发。

    + +

    每一回合,玩家需要从当前方格 x 开始出发,按下述要求前进:

    + +
      +
    • 选定目标方格:选择从编号 x+1x+2x+3x+4x+5,或者 x+6 的方格中选出一个目标方格 s ,目标方格的编号 <= N*N。 + +
        +
      • 该选择模拟了掷骰子的情景,无论棋盘大小如何,你的目的地范围也只能处于区间 [x+1, x+6] 之间。
      • +
      +
    • +
    • 传送玩家:如果目标方格 S 处存在蛇或梯子,那么玩家会传送到蛇或梯子的目的地。否则,玩家传送到目标方格 S。 
    • +
    + +

    注意,玩家在每回合的前进过程中最多只能爬过蛇或梯子一次:就算目的地是另一条蛇或梯子的起点,你也不会继续移动。

    + +

    返回达到方格 N*N 所需的最少移动次数,如果不可能,则返回 -1

    + +

     

    + +

    示例:

    + +
    输入:[
    +[-1,-1,-1,-1,-1,-1],
    +[-1,-1,-1,-1,-1,-1],
    +[-1,-1,-1,-1,-1,-1],
    +[-1,35,-1,-1,13,-1],
    +[-1,-1,-1,-1,-1,-1],
    +[-1,15,-1,-1,-1,-1]]
    +输出:4
    +解释:
    +首先,从方格 1 [第 5 行,第 0 列] 开始。
    +你决定移动到方格 2,并必须爬过梯子移动到到方格 15。
    +然后你决定移动到方格 17 [第 3 行,第 5 列],必须爬过蛇到方格 13。
    +然后你决定移动到方格 14,且必须通过梯子移动到方格 35。
    +然后你决定移动到方格 36, 游戏结束。
    +可以证明你需要至少 4 次移动才能到达第 N*N 个方格,所以答案是 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= board.length = board[0].length <= 20
    • +
    • board[i][j] 介于 1 和 N*N 之间或者等于 -1
    • +
    • 编号为 1 的方格上没有蛇或梯子。
    • +
    • 编号为 N*N 的方格上没有蛇或梯子。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0910.leetcode910 Smallest Range II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0910.leetcode910 Smallest Range II-zh.md" new file mode 100644 index 00000000..4ee7bfad --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0910.leetcode910 Smallest Range II-zh.md" @@ -0,0 +1,83 @@ +# [910. 最小差值 II](https://leetcode-cn.com/problems/smallest-range-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0910.Smallest%20Range%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 A,对于每个整数 A[i],可以选择 x = -K 或是 x = KK 总是非负整数),并将 x 加到 A[i] 中。

    + +

    在此过程之后,得到数组 B

    + +

    返回 B 的最大值和 B 的最小值之间可能存在的最小差值。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:A = [1], K = 0
    +输出:0
    +解释:B = [1]
    +
    + +

    示例 2:

    + +
    +输入:A = [0,10], K = 2
    +输出:6
    +解释:B = [2,8]
    +
    + +

    示例 3:

    + +
    +输入:A = [1,3,6], K = 3
    +输出:3
    +解释:B = [4,6,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= A.length <= 10000
    • +
    • 0 <= A[i] <= 10000
    • +
    • 0 <= K <= 10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0911.leetcode911 Online Election-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0911.leetcode911 Online Election-zh.md" new file mode 100644 index 00000000..298f888b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0911.leetcode911 Online Election-zh.md" @@ -0,0 +1,67 @@ +# [911. 在线选举](https://leetcode-cn.com/problems/online-election) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0911.Online%20Election/README_EN.md) + +## 题目描述 + + + +

    在选举中,第 i 张票是在时间为 times[i] 时投给 persons[i] 的。

    + +

    现在,我们想要实现下面的查询函数: TopVotedCandidate.q(int t) 将返回在 t 时刻主导选举的候选人的编号。

    + +

    在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。

    + +

    示例:

    + +
    输入:["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]
    +输出:[null,0,1,1,0,0,1]
    +解释:
    +时间为 3,票数分布情况是 [0],编号为 0 的候选人领先。
    +时间为 12,票数分布情况是 [0,1,1],编号为 1 的候选人领先。
    +时间为 25,票数分布情况是 [0,1,1,0,0,1],编号为 1 的候选人领先(因为最近的投票结果是平局)。
    +在时间 15、24 和 8 处继续执行 3 个查询。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= persons.length = times.length <= 5000
    2. +
    3. 0 <= persons[i] <= persons.length
    4. +
    5. times 是严格递增的数组,所有元素都在 [0, 10^9] 范围中。
    6. +
    7. 每个测试用例最多调用 10000 次 TopVotedCandidate.q
    8. +
    9. TopVotedCandidate.q(int t) 被调用时总是满足 t >= times[0]
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0912.leetcode912 Sort an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0912.leetcode912 Sort an Array-zh.md" new file mode 100644 index 00000000..0b9b3baf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0912.leetcode912 Sort an Array-zh.md" @@ -0,0 +1,66 @@ +# [912. 排序数组](https://leetcode-cn.com/problems/sort-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0912.Sort%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,请你将该数组升序排列。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:nums = [5,2,3,1]
    +输出:[1,2,3,5]
    +
    + +

    示例 2:

    + +
    输入:nums = [5,1,1,2,0,0]
    +输出:[0,0,1,1,2,5]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= nums.length <= 50000
    2. +
    3. -50000 <= nums[i] <= 50000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0913.leetcode913 Cat and Mouse-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0913.leetcode913 Cat and Mouse-zh.md" new file mode 100644 index 00000000..0b6db3e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0913.leetcode913 Cat and Mouse-zh.md" @@ -0,0 +1,85 @@ +# [913. 猫和老鼠](https://leetcode-cn.com/problems/cat-and-mouse) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0913.Cat%20and%20Mouse/README_EN.md) + +## 题目描述 + + + +

    两个玩家分别扮演猫(Cat)和老鼠(Mouse)在无向图上进行游戏,他们轮流行动。

    + +

    该图按下述规则给出:graph[a] 是所有结点 b 的列表,使得 ab 是图的一条边。

    + +

    老鼠从结点 1 开始并率先出发,猫从结点 2 开始且随后出发,在结点 0 处有一个洞。

    + +

    在每个玩家的回合中,他们必须沿着与他们所在位置相吻合的图的一条边移动。例如,如果老鼠位于结点 1,那么它只能移动到 graph[1] 中的(任何)结点去。

    + +

    此外,猫无法移动到洞(结点 0)里。

    + +

    然后,游戏在出现以下三种情形之一时结束:

    + +
      +
    • 如果猫和老鼠占据相同的结点,猫获胜。
    • +
    • 如果老鼠躲入洞里,老鼠获胜。
    • +
    • 如果某一位置重复出现(即,玩家们的位置和移动顺序都与上一个回合相同),游戏平局。
    • +
    + +

    给定 graph,并假设两个玩家都以最佳状态参与游戏,如果老鼠获胜,则返回 1;如果猫获胜,则返回 2;如果平局,则返回 0

    + +

     

    + +
      +
    + +

    示例:

    + +
    输入:[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
    +输出:0
    +解释:
    +4---3---1
    +|   |
    +2---5
    + \ /
    +  0
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= graph.length <= 200
    2. +
    3. 保证 graph[1] 非空。
    4. +
    5. 保证 graph[2] 包含非零元素。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0914.leetcode914 X of a Kind in a Deck of Cards-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0914.leetcode914 X of a Kind in a Deck of Cards-zh.md" new file mode 100644 index 00000000..98f29493 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0914.leetcode914 X of a Kind in a Deck of Cards-zh.md" @@ -0,0 +1,96 @@ +# [914. 卡牌分组](https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0914.X%20of%20a%20Kind%20in%20a%20Deck%20of%20Cards/README_EN.md) + +## 题目描述 + + + +

    给定一副牌,每张牌上都写着一个整数。

    + +

    此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:

    + +
      +
    • 每组都有 X 张牌。
    • +
    • 组内所有的牌上都写着相同的整数。
    • +
    + +

    仅当你可选的 X >= 2 时返回 true

    + +

     

    + +

    示例 1:

    + +
    输入:[1,2,3,4,4,3,2,1]
    +输出:true
    +解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]
    +
    + +

    示例 2:

    + +
    输入:[1,1,1,2,2,2,3,3]
    +输出:false
    +解释:没有满足要求的分组。
    +
    + +

    示例 3:

    + +
    输入:[1]
    +输出:false
    +解释:没有满足要求的分组。
    +
    + +

    示例 4:

    + +
    输入:[1,1]
    +输出:true
    +解释:可行的分组是 [1,1]
    +
    + +

    示例 5:

    + +
    输入:[1,1,2,2,2,2]
    +输出:true
    +解释:可行的分组是 [1,1],[2,2],[2,2]
    +
    + +


    +提示:

    + +
      +
    1. 1 <= deck.length <= 10000
    2. +
    3. 0 <= deck[i] < 10000
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0915.leetcode915 Partition Array into Disjoint Intervals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0915.leetcode915 Partition Array into Disjoint Intervals-zh.md" new file mode 100644 index 00000000..01057753 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0915.leetcode915 Partition Array into Disjoint Intervals-zh.md" @@ -0,0 +1,78 @@ +# [915. 分割数组](https://leetcode-cn.com/problems/partition-array-into-disjoint-intervals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0915.Partition%20Array%20into%20Disjoint%20Intervals/README_EN.md) + +## 题目描述 + + + +

    给定一个数组 A,将其划分为两个连续子数组 left 和 right, 使得:

    + +
      +
    • left 中的每个元素都小于或等于 right 中的每个元素。
    • +
    • left 和 right 都是非空的。
    • +
    • left 的长度要尽可能小。
    • +
    + +

    在完成这样的分组后返回 left 的长度。可以保证存在这样的划分方法。

    + +

     

    + +

    示例 1:

    + +
    +输入:[5,0,3,8,6]
    +输出:3
    +解释:left = [5,0,3],right = [8,6]
    +
    + +

    示例 2:

    + +
    +输入:[1,1,1,0,6,12]
    +输出:4
    +解释:left = [1,1,1,0],right = [6,12]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= A.length <= 30000
    2. +
    3. 0 <= A[i] <= 10^6
    4. +
    5. 可以保证至少有一种方法能够按题目所描述的那样对 A 进行划分。
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0916.leetcode916 Word Subsets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0916.leetcode916 Word Subsets-zh.md" new file mode 100644 index 00000000..941514df --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0916.leetcode916 Word Subsets-zh.md" @@ -0,0 +1,92 @@ +# [916. 单词子集](https://leetcode-cn.com/problems/word-subsets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0916.Word%20Subsets/README_EN.md) + +## 题目描述 + + + +

    我们给出两个单词数组 A 和 B。每个单词都是一串小写字母。

    + +

    现在,如果 b 中的每个字母都出现在 a 中,包括重复出现的字母,那么称单词 b 是单词 a 的子集。 例如,“wrr” 是 “warrior” 的子集,但不是 “world” 的子集。

    + +

    如果对 B 中的每一个单词 bb 都是 a 的子集,那么我们称 A 中的单词 a通用的

    + +

    你可以按任意顺序以列表形式返回 A 中所有的通用单词。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
    +输出:["facebook","google","leetcode"]
    +
    + +

    示例 2:

    + +
    输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
    +输出:["apple","google","leetcode"]
    +
    + +

    示例 3:

    + +
    输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
    +输出:["facebook","google"]
    +
    + +

    示例 4:

    + +
    输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
    +输出:["google","leetcode"]
    +
    + +

    示例 5:

    + +
    输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
    +输出:["facebook","leetcode"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length, B.length <= 10000
    2. +
    3. 1 <= A[i].length, B[i].length <= 10
    4. +
    5. A[i] 和 B[i] 只由小写字母组成。
    6. +
    7. A[i] 中所有的单词都是独一无二的,也就是说不存在 i != j 使得 A[i] == A[j]
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0917.leetcode917 Reverse Only Letters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0917.leetcode917 Reverse Only Letters-zh.md" new file mode 100644 index 00000000..0451067f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0917.leetcode917 Reverse Only Letters-zh.md" @@ -0,0 +1,73 @@ +# [917. 仅仅反转字母](https://leetcode-cn.com/problems/reverse-only-letters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0917.Reverse%20Only%20Letters/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:"ab-cd"
    +输出:"dc-ba"
    +
    + +

    示例 2:

    + +
    输入:"a-bC-dEf-ghIj"
    +输出:"j-Ih-gfE-dCba"
    +
    + +

    示例 3:

    + +
    输入:"Test1ng-Leet=code-Q!"
    +输出:"Qedo1ct-eeLg=ntse-T!"
    +
    + +

     

    + +

    提示:

    + +
      +
    1. S.length <= 100
    2. +
    3. 33 <= S[i].ASCIIcode <= 122 
    4. +
    5. S 中不包含 \ or "
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0918.leetcode918 Maximum Sum Circular Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0918.leetcode918 Maximum Sum Circular Subarray-zh.md" new file mode 100644 index 00000000..da6ec1bc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0918.leetcode918 Maximum Sum Circular Subarray-zh.md" @@ -0,0 +1,190 @@ +# [918. 环形子数组的最大和](https://leetcode-cn.com/problems/maximum-sum-circular-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0918.Maximum%20Sum%20Circular%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给定一个由整数数组 A 表示的环形数组 C,求 C 的非空子数组的最大可能和。

    + +

    在此处,环形数组意味着数组的末端将会与开头相连呈环状。(形式上,当0 <= i < A.length 时 C[i] = A[i],且当 i >= 0 时 C[i+A.length] = C[i]

    + +

    此外,子数组最多只能包含固定缓冲区 A 中的每个元素一次。(形式上,对于子数组 C[i], C[i+1], ..., C[j],不存在 i <= k1, k2 <= j 其中 k1 % A.length = k2 % A.length

    + +

     

    + +

    示例 1:

    + +
    输入:[1,-2,3,-2]
    +输出:3
    +解释:从子数组 [3] 得到最大和 3
    +
    + +

    示例 2:

    + +
    输入:[5,-3,5]
    +输出:10
    +解释:从子数组 [5,5] 得到最大和 5 + 5 = 10
    +
    + +

    示例 3:

    + +
    输入:[3,-1,2,-1]
    +输出:4
    +解释:从子数组 [2,-1,3] 得到最大和 2 + (-1) + 3 = 4
    +
    + +

    示例 4:

    + +
    输入:[3,-2,2,-3]
    +输出:3
    +解释:从子数组 [3] 和 [3,-2,2] 都可以得到最大和 3
    +
    + +

    示例 5:

    + +
    输入:[-2,-3,-1]
    +输出:-1
    +解释:从子数组 [-1] 得到最大和 -1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. -30000 <= A[i] <= 30000
    2. +
    3. 1 <= A.length <= 30000
    4. +
    + +## 解法 + + + +环形子数组的最大和,可分为两种情况:无环最大和、有环最大和。求其较大值即可。 + +无环最大和 s1 的求解可参考:[53. 最大子序和](/solution/0000-0099/0053.Maximum%20Subarray/README.md)。 + +对于有环最大和,我们可以转换为求最小子序和 s2,然后用 sum 减去最小子序和,得到有环的最大和。 + +注意:若数组所有元素均不大于 0,直接返回无环最大和 s1 即可。 + + + +### **Python3** + + + +```python +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + s1 = s2 = f1 = f2 = nums[0] + for num in nums[1:]: + f1 = num + max(f1, 0) + f2 = num + min(f2, 0) + s1 = max(s1, f1) + s2 = min(s2, f2) + return s1 if s1 <= 0 else max(s1, sum(nums) - s2) +``` + +### **Java** + + + +```java +class Solution { + public int maxSubarraySumCircular(int[] nums) { + int s1 = nums[0], s2 = nums[0], f1 = nums[0], f2 = nums[0], total = nums[0]; + for (int i = 1; i < nums.length; ++i) { + total += nums[i]; + f1 = nums[i] + Math.max(f1, 0); + f2 = nums[i] + Math.min(f2, 0); + s1 = Math.max(s1, f1); + s2 = Math.min(s2, f2); + } + return s1 > 0 ? Math.max(s1, total - s2) : s1; + } +} +``` + +### **TypeScript** + +```ts +function maxSubarraySumCircular(nums: number[]): number { + let pre1 = nums[0], pre2 = nums[0]; + let ans1 = nums[0], ans2 = nums[0]; + let sum = nums[0]; + + for (let i = 1; i < nums.length; ++i) { + let cur = nums[i]; + sum += cur; + pre1 = Math.max(pre1 + cur, cur); + ans1 = Math.max(pre1, ans1); + + pre2 = Math.min(pre2 + cur, cur); + ans2 = Math.min(pre2, ans2); + } + return ans1 > 0 ? Math.max(ans1, sum - ans2) : ans1; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + int s1 = nums[0], s2 = nums[0], f1 = nums[0], f2 = nums[0], total = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + total += nums[i]; + f1 = nums[i] + max(f1, 0); + f2 = nums[i] + min(f2, 0); + s1 = max(s1, f1); + s2 = min(s2, f2); + } + return s1 > 0 ? max(s1, total - s2) : s1; + } +}; +``` + +### **Go** + +```go +func maxSubarraySumCircular(nums []int) int { + s1, s2, f1, f2, total := nums[0], nums[0], nums[0], nums[0], nums[0] + for i := 1; i < len(nums); i++ { + total += nums[i] + f1 = nums[i] + max(f1, 0) + f2 = nums[i] + min(f2, 0) + s1 = max(s1, f1) + s2 = min(s2, f2) + } + if s1 <= 0 { + return s1 + } + return max(s1, total-s2) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0919.leetcode919 Complete Binary Tree Inserter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0919.leetcode919 Complete Binary Tree Inserter-zh.md" new file mode 100644 index 00000000..a4b78d6d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0919.leetcode919 Complete Binary Tree Inserter-zh.md" @@ -0,0 +1,75 @@ +# [919. 完全二叉树插入器](https://leetcode-cn.com/problems/complete-binary-tree-inserter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0919.Complete%20Binary%20Tree%20Inserter/README_EN.md) + +## 题目描述 + + + +

    完全二叉树是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。

    + +

    设计一个用完全二叉树初始化的数据结构 CBTInserter,它支持以下几种操作:

    + +
      +
    • CBTInserter(TreeNode root) 使用头节点为 root 的给定树初始化该数据结构;
    • +
    • CBTInserter.insert(int v)  向树中插入一个新节点,节点类型为 TreeNode,值为 v 。使树保持完全二叉树的状态,并返回插入的新节点的父节点的值
    • +
    • CBTInserter.get_root() 将返回树的头节点。
    • +
    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
    +输出:[null,1,[1,2]]
    +
    + +

    示例 2:

    + +
    输入:inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
    +输出:[null,3,4,[1,2,3,4,5,6,7,8]]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 最初给定的树是完全二叉树,且包含 1 到 1000 个节点。
    2. +
    3. 每个测试用例最多调用 CBTInserter.insert  操作 10000 次。
    4. +
    5. 给定节点或插入节点的每个值都在 0 到 5000 之间。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0920.leetcode920 Number of Music Playlists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0920.leetcode920 Number of Music Playlists-zh.md" new file mode 100644 index 00000000..283bdd63 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0920.leetcode920 Number of Music Playlists-zh.md" @@ -0,0 +1,78 @@ +# [920. 播放列表的数量](https://leetcode-cn.com/problems/number-of-music-playlists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0920.Number%20of%20Music%20Playlists/README_EN.md) + +## 题目描述 + + + +

    你的音乐播放器里有 N 首不同的歌,在旅途中,你的旅伴想要听 L 首歌(不一定不同,即,允许歌曲重复)。请你为她按如下规则创建一个播放列表:

    + +
      +
    • 每首歌至少播放一次。
    • +
    • 一首歌只有在其他 K 首歌播放完之后才能再次播放。
    • +
    + +

    返回可以满足要求的播放列表的数量。由于答案可能非常大,请返回它模 10^9 + 7 的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:N = 3, L = 3, K = 1
    +输出:6
    +解释:有 6 种可能的播放列表。[1, 2, 3],[1, 3, 2],[2, 1, 3],[2, 3, 1],[3, 1, 2],[3, 2, 1].
    +
    + +

    示例 2:

    + +
    输入:N = 2, L = 3, K = 0
    +输出:6
    +解释:有 6 种可能的播放列表。[1, 1, 2],[1, 2, 1],[2, 1, 1],[2, 2, 1],[2, 1, 2],[1, 2, 2]
    +
    + +

    示例 3:

    + +
    输入:N = 2, L = 3, K = 1
    +输出:2
    +解释:有 2 种可能的播放列表。[1, 2, 1],[2, 1, 2]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= K < N <= L <= 100
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0921.leetcode921 Minimum Add to Make Parentheses Valid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0921.leetcode921 Minimum Add to Make Parentheses Valid-zh.md" new file mode 100644 index 00000000..1f484a63 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0921.leetcode921 Minimum Add to Make Parentheses Valid-zh.md" @@ -0,0 +1,86 @@ +# [921. 使括号有效的最少添加](https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0921.Minimum%20Add%20to%20Make%20Parentheses%20Valid/README_EN.md) + +## 题目描述 + + + +

    给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。

    + +

    从形式上讲,只有满足下面几点之一,括号字符串才是有效的:

    + +
      +
    • 它是一个空字符串,或者
    • +
    • 它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
    • +
    • 它可以被写作 (A),其中 A 是有效字符串。
    • +
    + +

    给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。

    + +

     

    + +

    示例 1:

    + +
    输入:"())"
    +输出:1
    +
    + +

    示例 2:

    + +
    输入:"((("
    +输出:3
    +
    + +

    示例 3:

    + +
    输入:"()"
    +输出:0
    +
    + +

    示例 4:

    + +
    输入:"()))(("
    +输出:4
    + +

     

    + +

    提示:

    + +
      +
    1. S.length <= 1000
    2. +
    3. S 只包含 '(' 和 ')' 字符。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0922.leetcode922 Sort Array By Parity II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0922.leetcode922 Sort Array By Parity II-zh.md" new file mode 100644 index 00000000..7acc2c9a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0922.leetcode922 Sort Array By Parity II-zh.md" @@ -0,0 +1,65 @@ +# [922. 按奇偶排序数组 II](https://leetcode-cn.com/problems/sort-array-by-parity-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0922.Sort%20Array%20By%20Parity%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。

    + +

    对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

    + +

    你可以返回任何满足上述条件的数组作为答案。

    + +

     

    + +

    示例:

    + +
    输入:[4,2,5,7]
    +输出:[4,5,2,7]
    +解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= A.length <= 20000
    2. +
    3. A.length % 2 == 0
    4. +
    5. 0 <= A[i] <= 1000
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0923.leetcode923 3Sum With Multiplicity-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0923.leetcode923 3Sum With Multiplicity-zh.md" new file mode 100644 index 00000000..bcba2628 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0923.leetcode923 3Sum With Multiplicity-zh.md" @@ -0,0 +1,76 @@ +# [923. 三数之和的多种可能](https://leetcode-cn.com/problems/3sum-with-multiplicity) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0923.3Sum%20With%20Multiplicity/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,以及一个整数 target 作为目标值,返回满足 i < j < k 且 A[i] + A[j] + A[k] == target 的元组 i, j, k 的数量。

    + +

    由于结果会非常大,请返回 结果除以 10^9 + 7 的余数

    + +

     

    + +

    示例 1:

    + +
    输入:A = [1,1,2,2,3,3,4,4,5,5], target = 8
    +输出:20
    +解释:
    +按值枚举(A[i],A[j],A[k]):
    +(1, 2, 5) 出现 8 次;
    +(1, 3, 4) 出现 8 次;
    +(2, 2, 4) 出现 2 次;
    +(2, 3, 3) 出现 2 次。
    +
    + +

    示例 2:

    + +
    输入:A = [1,1,2,2,2,2], target = 5
    +输出:12
    +解释:
    +A[i] = 1,A[j] = A[k] = 2 出现 12 次:
    +我们从 [1,1] 中选择一个 1,有 2 种情况,
    +从 [2,2,2,2] 中选出两个 2,有 6 种情况。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= A.length <= 3000
    2. +
    3. 0 <= A[i] <= 100
    4. +
    5. 0 <= target <= 300
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0924.leetcode924 Minimize Malware Spread-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0924.leetcode924 Minimize Malware Spread-zh.md" new file mode 100644 index 00000000..42eac415 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0924.leetcode924 Minimize Malware Spread-zh.md" @@ -0,0 +1,83 @@ +# [924. 尽量减少恶意软件的传播](https://leetcode-cn.com/problems/minimize-malware-spread) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0924.Minimize%20Malware%20Spread/README_EN.md) + +## 题目描述 + + + +

    在节点网络中,只有当 graph[i][j] = 1 时,每个节点 i 能够直接连接到另一个节点 j

    + +

    一些节点 initial 最初被恶意软件感染。只要两个节点直接连接,且其中至少一个节点受到恶意软件的感染,那么两个节点都将被恶意软件感染。这种恶意软件的传播将继续,直到没有更多的节点可以被这种方式感染。

    + +

    假设 M(initial) 是在恶意软件停止传播之后,整个网络中感染恶意软件的最终节点数。

    + +

    我们可以从初始列表中删除一个节点。如果移除这一节点将最小化 M(initial), 则返回该节点。如果有多个节点满足条件,就返回索引最小的节点。

    + +

    请注意,如果某个节点已从受感染节点的列表 initial 中删除,它以后可能仍然因恶意软件传播而受到感染。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
    +输出:0
    +
    + +

    示例 2:

    + +
    输入:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
    +输出:0
    +
    + +

    示例 3:

    + +
    输入:graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 < graph.length = graph[0].length <= 300
    • +
    • 0 <= graph[i][j] == graph[j][i] <= 1
    • +
    • graph[i][i] == 1
    • +
    • 1 <= initial.length < graph.length
    • +
    • 0 <= initial[i] < graph.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0925.leetcode925 Long Pressed Name-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0925.leetcode925 Long Pressed Name-zh.md" new file mode 100644 index 00000000..bc5896a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0925.leetcode925 Long Pressed Name-zh.md" @@ -0,0 +1,85 @@ +# [925. 长按键入](https://leetcode-cn.com/problems/long-pressed-name) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0925.Long%20Pressed%20Name/README_EN.md) + +## 题目描述 + + + +

    你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。

    + +

    你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True

    + +

     

    + +

    示例 1:

    + +
    输入:name = "alex", typed = "aaleex"
    +输出:true
    +解释:'alex' 中的 'a' 和 'e' 被长按。
    +
    + +

    示例 2:

    + +
    输入:name = "saeed", typed = "ssaaedd"
    +输出:false
    +解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。
    +
    + +

    示例 3:

    + +
    输入:name = "leelee", typed = "lleeelee"
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:name = "laiden", typed = "laiden"
    +输出:true
    +解释:长按名字中的字符并不是必要的。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. name.length <= 1000
    2. +
    3. typed.length <= 1000
    4. +
    5. name 和 typed 的字符都是小写字母。
    6. +
    + +

     

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0926.leetcode926 Flip String to Monotone Increasing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0926.leetcode926 Flip String to Monotone Increasing-zh.md" new file mode 100644 index 00000000..54dbbadd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0926.leetcode926 Flip String to Monotone Increasing-zh.md" @@ -0,0 +1,76 @@ +# [926. 将字符串翻转到单调递增](https://leetcode-cn.com/problems/flip-string-to-monotone-increasing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0926.Flip%20String%20to%20Monotone%20Increasing/README_EN.md) + +## 题目描述 + + + +

    如果一个由 '0''1' 组成的字符串,是以一些 '0'(可能没有 '0')后面跟着一些 '1'(也可能没有 '1')的形式组成的,那么该字符串是单调递增的。

    + +

    我们给出一个由字符 '0''1' 组成的字符串 S,我们可以将任何 '0' 翻转为 '1' 或者将 '1' 翻转为 '0'

    + +

    返回使 S 单调递增的最小翻转次数。

    + +

     

    + +

    示例 1:

    + +
    输入:"00110"
    +输出:1
    +解释:我们翻转最后一位得到 00111.
    +
    + +

    示例 2:

    + +
    输入:"010110"
    +输出:2
    +解释:我们翻转得到 011111,或者是 000111。
    +
    + +

    示例 3:

    + +
    输入:"00011000"
    +输出:2
    +解释:我们翻转得到 00000000。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 20000
    2. +
    3. S 中只包含字符 '0' 和 '1'
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0927.leetcode927 Three Equal Parts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0927.leetcode927 Three Equal Parts-zh.md" new file mode 100644 index 00000000..02b845f5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0927.leetcode927 Three Equal Parts-zh.md" @@ -0,0 +1,77 @@ +# [927. 三等分](https://leetcode-cn.com/problems/three-equal-parts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0927.Three%20Equal%20Parts/README_EN.md) + +## 题目描述 + + + +

    给定一个由 01 组成的数组 A,将数组分成 3 个非空的部分,使得所有这些部分表示相同的二进制值。

    + +

    如果可以做到,请返回任何 [i, j],其中 i+1 < j,这样一来:

    + +
      +
    • A[0], A[1], ..., A[i] 组成第一部分;
    • +
    • A[i+1], A[i+2], ..., A[j-1] 作为第二部分;
    • +
    • A[j], A[j+1], ..., A[A.length - 1] 是第三部分。
    • +
    • 这三个部分所表示的二进制值相等。
    • +
    + +

    如果无法做到,就返回 [-1, -1]

    + +

    注意,在考虑每个部分所表示的二进制时,应当将其看作一个整体。例如,[1,1,0] 表示十进制中的 6,而不会是 3。此外,前导零也是被允许的,所以 [0,1,1] 和 [1,1] 表示相同的值。

    + +

     

    + +

    示例 1:

    + +
    输入:[1,0,1,0,1]
    +输出:[0,3]
    +
    + +

    示例 2:

    + +
    输出:[1,1,0,1,1]
    +输出:[-1,-1]
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= A.length <= 30000
    2. +
    3. A[i] == 0 或 A[i] == 1
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0928.leetcode928 Minimize Malware Spread II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0928.leetcode928 Minimize Malware Spread II-zh.md" new file mode 100644 index 00000000..90f39db0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0928.leetcode928 Minimize Malware Spread II-zh.md" @@ -0,0 +1,83 @@ +# [928. 尽量减少恶意软件的传播 II](https://leetcode-cn.com/problems/minimize-malware-spread-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0928.Minimize%20Malware%20Spread%20II/README_EN.md) + +## 题目描述 + + + +

    (这个问题与 尽量减少恶意软件的传播 是一样的,不同之处用粗体表示。)

    + +

    在节点网络中,只有当 graph[i][j] = 1 时,每个节点 i 能够直接连接到另一个节点 j

    + +

    一些节点 initial 最初被恶意软件感染。只要两个节点直接连接,且其中至少一个节点受到恶意软件的感染,那么两个节点都将被恶意软件感染。这种恶意软件的传播将继续,直到没有更多的节点可以被这种方式感染。

    + +

    假设 M(initial) 是在恶意软件停止传播之后,整个网络中感染恶意软件的最终节点数。

    + +

    我们可以从初始列表中删除一个节点,并完全移除该节点以及从该节点到任何其他节点的任何连接。如果移除这一节点将最小化 M(initial), 则返回该节点。如果有多个节点满足条件,就返回索引最小的节点。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输出:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
    +输入:0
    +
    + +

    示例 2:

    + +
    输入:graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
    +输出:1
    +
    + +

    示例 3:

    + +
    输入:graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 < graph.length = graph[0].length <= 300
    2. +
    3. 0 <= graph[i][j] == graph[j][i] <= 1
    4. +
    5. graph[i][i] = 1
    6. +
    7. 1 <= initial.length < graph.length
    8. +
    9. 0 <= initial[i] < graph.length
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0929.leetcode929 Unique Email Addresses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0929.leetcode929 Unique Email Addresses-zh.md" new file mode 100644 index 00000000..713a47a0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0929.leetcode929 Unique Email Addresses-zh.md" @@ -0,0 +1,71 @@ +# [929. 独特的电子邮件地址](https://leetcode-cn.com/problems/unique-email-addresses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0929.Unique%20Email%20Addresses/README_EN.md) + +## 题目描述 + + + +

    每封电子邮件都由一个本地名称和一个域名组成,以 @ 符号分隔。

    + +

    例如,在 alice@leetcode.com中, alice 是本地名称,而 leetcode.com 是域名。

    + +

    除了小写字母,这些电子邮件还可能包含 '.''+'

    + +

    如果在电子邮件地址的本地名称部分中的某些字符之间添加句点('.'),则发往那里的邮件将会转发到本地名称中没有点的同一地址。例如,"alice.z@leetcode.com”“alicez@leetcode.com” 会转发到同一电子邮件地址。 (请注意,此规则不适用于域名。)

    + +

    如果在本地名称中添加加号('+'),则会忽略第一个加号后面的所有内容。这允许过滤某些电子邮件,例如 m.y+name@email.com 将转发到 my@email.com。 (同样,此规则不适用于域名。)

    + +

    可以同时使用这两个规则。

    + +

    给定电子邮件列表 emails,我们会向列表中的每个地址发送一封电子邮件。实际收到邮件的不同地址有多少?

    + +

     

    + +

    示例:

    + +
    输入:["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
    +输出:2
    +解释:实际收到邮件的是 "testemail@leetcode.com" 和 "testemail@lee.tcode.com"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= emails[i].length <= 100
    • +
    • 1 <= emails.length <= 100
    • +
    • 每封 emails[i] 都包含有且仅有一个 '@' 字符。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0930.leetcode930 Binary Subarrays With Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0930.leetcode930 Binary Subarrays With Sum-zh.md" new file mode 100644 index 00000000..673d5734 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0930.leetcode930 Binary Subarrays With Sum-zh.md" @@ -0,0 +1,64 @@ +# [930. 和相同的二元子数组](https://leetcode-cn.com/problems/binary-subarrays-with-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0930.Binary%20Subarrays%20With%20Sum/README_EN.md) + +## 题目描述 + + + +

    在由若干 0 和 1  组成的数组 A 中,有多少个和为 S 的非空子数组。

    + +

     

    + +

    示例:

    + +
    输入:A = [1,0,1,0,1], S = 2
    +输出:4
    +解释:
    +如下面黑体所示,有 4 个满足题目要求的子数组:
    +[1,0,1,0,1]
    +[1,0,1,0,1]
    +[1,0,1,0,1]
    +[1,0,1,0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. A.length <= 30000
    2. +
    3. 0 <= S <= A.length
    4. +
    5. A[i] 为 0 或 1
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0931.leetcode931 Minimum Falling Path Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0931.leetcode931 Minimum Falling Path Sum-zh.md" new file mode 100644 index 00000000..7039a650 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0931.leetcode931 Minimum Falling Path Sum-zh.md" @@ -0,0 +1,168 @@ +# [931. 下降路径最小和](https://leetcode-cn.com/problems/minimum-falling-path-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0931.Minimum%20Falling%20Path%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个 n x n 方形 整数数组 matrix ,请你找出并返回通过 matrix下降路径 最小和

    + +

    下降路径 可以从第一行中的任何元素开始,并从每一行中选择一个元素。在下一行选择的元素和当前行所选元素最多相隔一列(即位于正下方或者沿对角线向左或者向右的第一个元素)。具体来说,位置 (row, col) 的下一个元素应当是 (row + 1, col - 1)(row + 1, col) 或者 (row + 1, col + 1)

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[2,1,3],[6,5,4],[7,8,9]]
    +输出:13
    +解释:下面是两条和最小的下降路径,用加粗标注:
    +[[2,1,3],      [[2,1,3],
    + [6,5,4],       [6,5,4],
    + [7,8,9]]       [7,8,9]]
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[-19,57],[-40,-5]]
    +输出:-59
    +解释:下面是一条和最小的下降路径,用加粗标注:
    +[[-19,57],
    + [-40,-5]]
    +
    + +

    示例 3:

    + +
    +输入:matrix = [[-48]]
    +输出:-48
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= n <= 100
    • +
    • -100 <= matrix[i][j] <= 100
    • +
    + + +## 解法 + + + +动态规划。 + + + +### **Python3** + + + +```python +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + n = len(matrix) + for i in range(1, n): + for j in range(n): + mi = matrix[i - 1][j] + if j > 0: + mi = min(mi, matrix[i - 1][j - 1]) + if j < n - 1: + mi = min(mi, matrix[i - 1][j + 1]) + matrix[i][j] += mi + return min(matrix[n - 1]) +``` + +### **Java** + + + +```java +class Solution { + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int mi = matrix[i - 1][j]; + if (j > 0) { + mi = Math.min(mi, matrix[i - 1][j - 1]); + } + if (j < n - 1) { + mi = Math.min(mi, matrix[i - 1][j + 1]); + } + matrix[i][j] += mi; + } + } + int res = Integer.MAX_VALUE; + for (int j = 0; j < n; ++j) { + res = Math.min(res, matrix[n - 1][j]); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minFallingPathSum(vector>& matrix) { + int n = matrix.size(); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int mi = matrix[i - 1][j]; + if (j > 0) mi = min(mi, matrix[i - 1][j - 1]); + if (j < n - 1) mi = min(mi, matrix[i - 1][j + 1]); + matrix[i][j] += mi; + } + } + int res = INT_MAX; + for (int j = 0; j < n; ++j) { + res = min(res, matrix[n - 1][j]); + } + return res; + } +}; +``` + +### **Go** + +```go +func minFallingPathSum(matrix [][]int) int { + n := len(matrix) + for i := 1; i < n; i++ { + for j := 0; j < n; j++ { + mi := matrix[i - 1][j] + if j > 0 && mi > matrix[i - 1][j - 1] { + mi = matrix[i - 1][j - 1] + } + if j < n - 1 && mi > matrix[i - 1][j + 1] { + mi = matrix[i - 1][j + 1] + } + matrix[i][j] += mi + } + } + res := 10000 + for j := 0; j < n; j++ { + if res > matrix[n - 1][j] { + res = matrix[n - 1][j] + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0932.leetcode932 Beautiful Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0932.leetcode932 Beautiful Array-zh.md" new file mode 100644 index 00000000..2c4e2d65 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0932.leetcode932 Beautiful Array-zh.md" @@ -0,0 +1,71 @@ +# [932. 漂亮数组](https://leetcode-cn.com/problems/beautiful-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0932.Beautiful%20Array/README_EN.md) + +## 题目描述 + + + +

    对于某些固定的 N,如果数组 A 是整数 1, 2, ..., N 组成的排列,使得:

    + +

    对于每个 i < j,都不存在 k 满足 i < k < j 使得 A[k] * 2 = A[i] + A[j]

    + +

    那么数组 A 是漂亮数组。

    + +

     

    + +

    给定 N,返回任意漂亮数组 A(保证存在一个)。

    + +

     

    + +

    示例 1:

    + +
    输入:4
    +输出:[2,1,4,3]
    +
    + +

    示例 2:

    + +
    输入:5
    +输出:[3,1,2,5,4]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 1000
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0933.leetcode933 Number of Recent Calls-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0933.leetcode933 Number of Recent Calls-zh.md" new file mode 100644 index 00000000..a0c5ba40 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0933.leetcode933 Number of Recent Calls-zh.md" @@ -0,0 +1,142 @@ +# [933. 最近的请求次数](https://leetcode-cn.com/problems/number-of-recent-calls) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0933.Number%20of%20Recent%20Calls/README_EN.md) + +## 题目描述 + + + +

    写一个 RecentCounter 类来计算特定时间范围内最近的请求。

    + +

    请你实现 RecentCounter 类:

    + +
      +
    • RecentCounter() 初始化计数器,请求数为 0 。
    • +
    • int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。
    • +
    + +

    保证 每次对 ping 的调用都使用比之前更大的 t 值。

    + +

     

    + +

    示例:

    + +
    +输入:
    +["RecentCounter", "ping", "ping", "ping", "ping"]
    +[[], [1], [100], [3001], [3002]]
    +输出:
    +[null, 1, 2, 3, 3]
    +
    +解释:
    +RecentCounter recentCounter = new RecentCounter();
    +recentCounter.ping(1);     // requests = [1],范围是 [-2999,1],返回 1
    +recentCounter.ping(100);   // requests = [1, 100],范围是 [-2900,100],返回 2
    +recentCounter.ping(3001);  // requests = [1, 100, 3001],范围是 [1,3001],返回 3
    +recentCounter.ping(3002);  // requests = [1, 100, 3001, 3002],范围是 [2,3002],返回 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= t <= 109
    • +
    • 保证每次对 ping 调用所使用的 t 值都 严格递增
    • +
    • 至多调用 ping 方法 104
    • +
    + +## 解法 + + + +在第 1、100、3001、3002 这四个时间点分别进行了 ping 请求, 在 3001 秒的时候, 它前面的 3000 秒指的是区间 `[1,3001]`, 所以一共是有 `1、100、3001` 三个请求, t = 3002 的前 3000 秒指的是区间 `[2,3002]`, 所以有 `100、3001、3002` 三次请求。 + +可以用队列实现。每次将 t 进入队尾,同时从队头开始依次移除小于 `t-3000` 的元素。然后返回队列的大小 `q.size()` 即可。 + + + +### **Python3** + + + +```python +class RecentCounter: + + def __init__(self): + self.q = collections.deque() + + def ping(self, t: int) -> int: + self.q.append(t) + while self.q[0] < t - 3000: + self.q.popleft() + return len(self.q) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) +``` + +### **Java** + + + +```java +class RecentCounter { + + private Deque q; + + public RecentCounter() { + q = new ArrayDeque<>(); + } + + public int ping(int t) { + q.offerLast(t); + while (q.peekFirst() < t - 3000) { + q.pollFirst(); + } + return q.size(); + } +} + +/** + * Your RecentCounter object will be instantiated and called as such: + * RecentCounter obj = new RecentCounter(); + * int param_1 = obj.ping(t); + */ +``` + +### **JavaScript** + +```js +var RecentCounter = function () { + this.q = []; +}; + +/** + * @param {number} t + * @return {number} + */ +RecentCounter.prototype.ping = function (t) { + this.q.push(t); + while (this.q[0] < t - 3000) { + this.q.shift(); + } + return this.q.length; +}; + +/** + * Your RecentCounter object will be instantiated and called as such: + * var obj = new RecentCounter() + * var param_1 = obj.ping(t) + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0934.leetcode934 Shortest Bridge-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0934.leetcode934 Shortest Bridge-zh.md" new file mode 100644 index 00000000..51ed9e8a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0934.leetcode934 Shortest Bridge-zh.md" @@ -0,0 +1,75 @@ +# [934. 最短的桥](https://leetcode-cn.com/problems/shortest-bridge) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0934.Shortest%20Bridge/README_EN.md) + +## 题目描述 + + + +

    在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)

    + +

    现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。

    + +

    返回必须翻转的 0 的最小数目。(可以保证答案至少是 1 。)

    + +

     

    + +

    示例 1:

    + +
    +输入:A = [[0,1],[1,0]]
    +输出:1
    +
    + +

    示例 2:

    + +
    +输入:A = [[0,1,0],[0,0,0],[0,0,1]]
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
    +输出:1
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= A.length == A[0].length <= 100
    • +
    • A[i][j] == 0A[i][j] == 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0935.leetcode935 Knight Dialer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0935.leetcode935 Knight Dialer-zh.md" new file mode 100644 index 00000000..a8009870 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0935.leetcode935 Knight Dialer-zh.md" @@ -0,0 +1,82 @@ +# [935. 骑士拨号器](https://leetcode-cn.com/problems/knight-dialer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0935.Knight%20Dialer/README_EN.md) + +## 题目描述 + + + +

    国际象棋中的骑士可以按下图所示进行移动:

    + +

     .           

    + +


    +这一次,我们将 “骑士” 放在电话拨号盘的任意数字键(如上图所示)上,接下来,骑士将会跳 N-1 步。每一步必须是从一个数字键跳到另一个数字键。

    + +

    每当它落在一个键上(包括骑士的初始位置),都会拨出键所对应的数字,总共按下 N 位数字。

    + +

    你能用这种方式拨出多少个不同的号码?

    + +

    因为答案可能很大,所以输出答案模 10^9 + 7

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:1
    +输出:10
    +
    + +

    示例 2:

    + +
    输入:2
    +输出:20
    +
    + +

    示例 3:

    + +
    输入:3
    +输出:46
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 5000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0936.leetcode936 Stamping The Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0936.leetcode936 Stamping The Sequence-zh.md" new file mode 100644 index 00000000..1b9a3226 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0936.leetcode936 Stamping The Sequence-zh.md" @@ -0,0 +1,76 @@ +# [936. 戳印序列](https://leetcode-cn.com/problems/stamping-the-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0936.Stamping%20The%20Sequence/README_EN.md) + +## 题目描述 + + + +

    你想要用小写字母组成一个目标字符串 target。 

    + +

    开始的时候,序列由 target.length 个 '?' 记号组成。而你有一个小写字母印章 stamp

    + +

    在每个回合,你可以将印章放在序列上,并将序列中的每个字母替换为印章上的相应字母。你最多可以进行 10 * target.length  个回合。

    + +

    举个例子,如果初始序列为 "?????",而你的印章 stamp 是 "abc",那么在第一回合,你可以得到 "abc??"、"?abc?"、"??abc"。(请注意,印章必须完全包含在序列的边界内才能盖下去。)

    + +

    如果可以印出序列,那么返回一个数组,该数组由每个回合中被印下的最左边字母的索引组成。如果不能印出序列,就返回一个空数组。

    + +

    例如,如果序列是 "ababc",印章是 "abc",那么我们就可以返回与操作 "?????" -> "abc??" -> "ababc" 相对应的答案 [0, 2]

    + +

    另外,如果可以印出序列,那么需要保证可以在 10 * target.length 个回合内完成。任何超过此数字的答案将不被接受。

    + +

     

    + +

    示例 1:

    + +
    输入:stamp = "abc", target = "ababc"
    +输出:[0,2]
    +([1,0,2] 以及其他一些可能的结果也将作为答案被接受)
    +
    + +

    示例 2:

    + +
    输入:stamp = "abca", target = "aabcaca"
    +输出:[3,0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= stamp.length <= target.length <= 1000
    2. +
    3. stamp 和 target 只包含小写字母。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0937.leetcode937 Reorder Data in Log Files-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0937.leetcode937 Reorder Data in Log Files-zh.md" new file mode 100644 index 00000000..cb897902 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0937.leetcode937 Reorder Data in Log Files-zh.md" @@ -0,0 +1,87 @@ +# [937. 重新排列日志文件](https://leetcode-cn.com/problems/reorder-data-in-log-files) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0937.Reorder%20Data%20in%20Log%20Files/README_EN.md) + +## 题目描述 + + + +

    给你一个日志数组 logs。每条日志都是以空格分隔的字串,其第一个字为字母与数字混合的 标识符

    + +

    有两种不同类型的日志:

    + +
      +
    • 字母日志:除标识符之外,所有字均由小写字母组成
    • +
    • 数字日志:除标识符之外,所有字均由数字组成
    • +
    + +

    请按下述规则将日志重新排序:

    + +
      +
    • 所有 字母日志 都排在 数字日志 之前。
    • +
    • 字母日志 在内容不同时,忽略标识符后,按内容字母顺序排序;在内容相同时,按标识符排序。
    • +
    • 数字日志 应该保留原来的相对顺序。
    • +
    + +

    返回日志的最终顺序。

    + +

     

    + +

    示例 1:

    + +
    +输入:logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
    +输出:["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
    +解释:
    +字母日志的内容都不同,所以顺序为 "art can", "art zero", "own kit dig" 。
    +数字日志保留原来的相对顺序 "dig1 8 1 5 1", "dig2 3 6" 。
    +
    + +

    示例 2:

    + +
    +输入:logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
    +输出:["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= logs.length <= 100
    • +
    • 3 <= logs[i].length <= 100
    • +
    • logs[i] 中,字与字之间都用 单个 空格分隔
    • +
    • 题目数据保证 logs[i] 都有一个标识符,并且在标识符之后至少存在一个字
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0938.leetcode938 Range Sum of BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0938.leetcode938 Range Sum of BST-zh.md" new file mode 100644 index 00000000..e2607cf2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0938.leetcode938 Range Sum of BST-zh.md" @@ -0,0 +1,67 @@ +# [938. 二叉搜索树的范围和](https://leetcode-cn.com/problems/range-sum-of-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0938.Range%20Sum%20of%20BST/README_EN.md) + +## 题目描述 + + + +

    给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
    +输出:32
    +
    + +

    示例 2:

    + +
    +输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
    +输出:23
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [1, 2 * 104]
    • +
    • 1 <= Node.val <= 105
    • +
    • 1 <= low <= high <= 105
    • +
    • 所有 Node.val 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0939.leetcode939 Minimum Area Rectangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0939.leetcode939 Minimum Area Rectangle-zh.md" new file mode 100644 index 00000000..3d75293e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0939.leetcode939 Minimum Area Rectangle-zh.md" @@ -0,0 +1,67 @@ +# [939. 最小面积矩形](https://leetcode-cn.com/problems/minimum-area-rectangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0939.Minimum%20Area%20Rectangle/README_EN.md) + +## 题目描述 + + + +

    给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。

    + +

    如果没有任何矩形,就返回 0。

    + +

     

    + +

    示例 1:

    + +
    输入:[[1,1],[1,3],[3,1],[3,3],[2,2]]
    +输出:4
    +
    + +

    示例 2:

    + +
    输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= points.length <= 500
    2. +
    3. 0 <= points[i][0] <= 40000
    4. +
    5. 0 <= points[i][1] <= 40000
    6. +
    7. 所有的点都是不同的。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0940.leetcode940 Distinct Subsequences II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0940.leetcode940 Distinct Subsequences II-zh.md" new file mode 100644 index 00000000..cb56dbc5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0940.leetcode940 Distinct Subsequences II-zh.md" @@ -0,0 +1,80 @@ +# [940. 不同的子序列 II](https://leetcode-cn.com/problems/distinct-subsequences-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0940.Distinct%20Subsequences%20II/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 S,计算 S 的不同非空子序列的个数。

    + +

    因为结果可能很大,所以返回答案模 10^9 + 7.

    + +

     

    + +

    示例 1:

    + +
    输入:"abc"
    +输出:7
    +解释:7 个不同的子序列分别是 "a", "b", "c", "ab", "ac", "bc", 以及 "abc"。
    +
    + +

    示例 2:

    + +
    输入:"aba"
    +输出:6
    +解释:6 个不同的子序列分别是 "a", "b", "ab", "ba", "aa" 以及 "aba"。
    +
    + +

    示例 3:

    + +
    输入:"aaa"
    +输出:3
    +解释:3 个不同的子序列分别是 "a", "aa" 以及 "aaa"。
    +
    + +

     

    + +

     

    + +

    提示:

    + +
      +
    1. S 只包含小写字母。
    2. +
    3. 1 <= S.length <= 2000
    4. +
    + +

     

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0941.leetcode941 Valid Mountain Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0941.leetcode941 Valid Mountain Array-zh.md" new file mode 100644 index 00000000..1e648e2f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0941.leetcode941 Valid Mountain Array-zh.md" @@ -0,0 +1,87 @@ +# [941. 有效的山脉数组](https://leetcode-cn.com/problems/valid-mountain-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0941.Valid%20Mountain%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 arr,如果它是有效的山脉数组就返回 true,否则返回 false

    + +

    让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:

    + +
      +
    • arr.length >= 3
    • +
    • 在 0 < i < arr.length - 1 条件下,存在 i 使得: +
        +
      • arr[0] < arr[1] < ... arr[i-1] < arr[i]
      • +
      • arr[i] > arr[i+1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

     

    + +

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [2,1]
    +输出:false
    +
    + +

    示例 2:

    + +
    +输入:arr = [3,5,5]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:arr = [0,3,2,1]
    +输出:true
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 0 <= arr[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0942.leetcode942 DI String Match-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0942.leetcode942 DI String Match-zh.md" new file mode 100644 index 00000000..dc2433e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0942.leetcode942 DI String Match-zh.md" @@ -0,0 +1,75 @@ +# [942. 增减字符串匹配](https://leetcode-cn.com/problems/di-string-match) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0942.DI%20String%20Match/README_EN.md) + +## 题目描述 + + + +

    给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length

    + +

    返回 [0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N-1,都有:

    + +
      +
    • 如果 S[i] == "I",那么 A[i] < A[i+1]
    • +
    • 如果 S[i] == "D",那么 A[i] > A[i+1]
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:"IDID"
    +输出:[0,4,1,3,2]
    +
    + +

    示例 2:

    + +
    输入:"III"
    +输出:[0,1,2,3]
    +
    + +

    示例 3:

    + +
    输入:"DDI"
    +输出:[3,2,0,1]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= S.length <= 10000
    • +
    • S 只包含字符 "I" 或 "D"
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0943.leetcode943 Find the Shortest Superstring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0943.leetcode943 Find the Shortest Superstring-zh.md" new file mode 100644 index 00000000..c52aad22 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0943.leetcode943 Find the Shortest Superstring-zh.md" @@ -0,0 +1,68 @@ +# [943. 最短超级串](https://leetcode-cn.com/problems/find-the-shortest-superstring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0943.Find%20the%20Shortest%20Superstring/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串数组 words,找到以 words 中每个字符串作为子字符串的最短字符串。如果有多个有效最短字符串满足题目条件,返回其中 任意一个 即可。

    + +

    我们可以假设 words 中没有字符串是 words 中另一个字符串的子字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["alex","loves","leetcode"]
    +输出:"alexlovesleetcode"
    +解释:"alex","loves","leetcode" 的所有排列都会被接受。
    + +

    示例 2:

    + +
    +输入:words = ["catg","ctaagt","gcta","ttca","atgcatc"]
    +输出:"gctaagttcatgcatc"
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 12
    • +
    • 1 <= words[i].length <= 20
    • +
    • words[i] 由小写英文字母组成
    • +
    • words 中的所有字符串 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0944.leetcode944 Delete Columns to Make Sorted-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0944.leetcode944 Delete Columns to Make Sorted-zh.md" new file mode 100644 index 00000000..29c70ef7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0944.leetcode944 Delete Columns to Make Sorted-zh.md" @@ -0,0 +1,99 @@ +# [944. 删列造序](https://leetcode-cn.com/problems/delete-columns-to-make-sorted) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0944.Delete%20Columns%20to%20Make%20Sorted/README_EN.md) + +## 题目描述 + + + +

    给你由 n 个小写字母字符串组成的数组 strs,其中每个字符串长度相等。

    + +

    这些字符串可以每个一行,排成一个网格。例如,strs = ["abc", "bce", "cae"] 可以排列为:

    + +
    +abc
    +bce
    +cae
    + +

    你需要找出并删除 不是按字典序升序排列的 列。在上面的例子(下标从 0 开始)中,列 0('a', 'b', 'c')和列 2('c', 'e', 'e')都是按升序排列的,而列 1('b', 'c', 'a')不是,所以要删除列 1 。

    + +

    返回你需要删除的列数。

    + +

     

    + +

    示例 1:

    + +
    +输入:strs = ["cba","daf","ghi"]
    +输出:1
    +解释:网格示意如下:
    +  cba
    +  daf
    +  ghi
    +列 0 和列 2 按升序排列,但列 1 不是,所以只需要删除列 1 。
    +
    + +

    示例 2:

    + +
    +输入:strs = ["a","b"]
    +输出:0
    +解释:网格示意如下:
    +  a
    +  b
    +只有列 0 这一列,且已经按升序排列,所以不用删除任何列。
    +
    + +

    示例 3:

    + +
    +输入:strs = ["zyx","wvu","tsr"]
    +输出:3
    +解释:网格示意如下:
    +  zyx
    +  wvu
    +  tsr
    +所有 3 列都是非升序排列的,所以都要删除。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == strs.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= strs[i].length <= 1000
    • +
    • strs[i] 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0945.leetcode945 Minimum Increment to Make Array Unique-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0945.leetcode945 Minimum Increment to Make Array Unique-zh.md" new file mode 100644 index 00000000..b21ba22f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0945.leetcode945 Minimum Increment to Make Array Unique-zh.md" @@ -0,0 +1,63 @@ +# [945. 使数组唯一的最小增量](https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0945.Minimum%20Increment%20to%20Make%20Array%20Unique/README_EN.md) + +## 题目描述 + + + +

    给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1

    + +

    返回使 A 中的每个值都是唯一的最少操作次数。

    + +

    示例 1:

    + +
    输入:[1,2,2]
    +输出:1
    +解释:经过一次 move 操作,数组将变为 [1, 2, 3]。
    + +

    示例 2:

    + +
    输入:[3,2,1,2,1,7]
    +输出:6
    +解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。
    +可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。
    +
    + +

    提示:

    + +
      +
    1. 0 <= A.length <= 40000
    2. +
    3. 0 <= A[i] < 40000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0946.leetcode946 Validate Stack Sequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0946.leetcode946 Validate Stack Sequences-zh.md" new file mode 100644 index 00000000..64bf11a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0946.leetcode946 Validate Stack Sequences-zh.md" @@ -0,0 +1,68 @@ +# [946. 验证栈序列](https://leetcode-cn.com/problems/validate-stack-sequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0946.Validate%20Stack%20Sequences/README_EN.md) + +## 题目描述 + + + +

    给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

    + +

     

    + +

    示例 1:

    + +
    输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    +输出:true
    +解释:我们可以按以下顺序执行:
    +push(1), push(2), push(3), push(4), pop() -> 4,
    +push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
    +
    + +

    示例 2:

    + +
    输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
    +输出:false
    +解释:1 不能在 2 之前弹出。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= pushed.length == popped.length <= 1000
    2. +
    3. 0 <= pushed[i], popped[i] < 1000
    4. +
    5. pushed 是 popped 的排列。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0947.leetcode947 Most Stones Removed with Same Row or Column-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0947.leetcode947 Most Stones Removed with Same Row or Column-zh.md" new file mode 100644 index 00000000..1ddd8189 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0947.leetcode947 Most Stones Removed with Same Row or Column-zh.md" @@ -0,0 +1,87 @@ +# [947. 移除最多的同行或同列石头](https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0947.Most%20Stones%20Removed%20with%20Same%20Row%20or%20Column/README_EN.md) + +## 题目描述 + + + +

    n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。

    + +

    如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。

    + +

    给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。

    + +

     

    + +

    示例 1:

    + +
    +输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
    +输出:5
    +解释:一种移除 5 块石头的方法如下所示:
    +1. 移除石头 [2,2] ,因为它和 [2,1] 同行。
    +2. 移除石头 [2,1] ,因为它和 [0,1] 同列。
    +3. 移除石头 [1,2] ,因为它和 [1,0] 同行。
    +4. 移除石头 [1,0] ,因为它和 [0,0] 同列。
    +5. 移除石头 [0,1] ,因为它和 [0,0] 同行。
    +石头 [0,0] 不能移除,因为它没有与另一块石头同行/列。
    + +

    示例 2:

    + +
    +输入:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
    +输出:3
    +解释:一种移除 3 块石头的方法如下所示:
    +1. 移除石头 [2,2] ,因为它和 [2,0] 同行。
    +2. 移除石头 [2,0] ,因为它和 [0,0] 同列。
    +3. 移除石头 [0,2] ,因为它和 [0,0] 同行。
    +石头 [0,0] 和 [1,1] 不能移除,因为它们没有与另一块石头同行/列。
    + +

    示例 3:

    + +
    +输入:stones = [[0,0]]
    +输出:0
    +解释:[0,0] 是平面上唯一一块石头,所以不可以移除它。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= stones.length <= 1000
    • +
    • 0 <= xi, yi <= 104
    • +
    • 不会有两块石头放在同一个坐标点上
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0948.leetcode948 Bag of Tokens-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0948.leetcode948 Bag of Tokens-zh.md" new file mode 100644 index 00000000..0e85f906 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0948.leetcode948 Bag of Tokens-zh.md" @@ -0,0 +1,90 @@ +# [948. 令牌放置](https://leetcode-cn.com/problems/bag-of-tokens) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0948.Bag%20of%20Tokens/README_EN.md) + +## 题目描述 + + + +

    你的初始 能量 为 P,初始 分数 为 0,只有一包令牌 tokens 。其中 tokens[i] 是第 i 个令牌的值(下标从 0 开始)。

    + +

    令牌可能的两种使用方法如下:

    + +
      +
    • 如果你至少有 token[i] 点 能量 ,可以将令牌 i 置为正面朝上,失去 token[i] 点 能量 ,并得到 1 
    • +
    • 如果我们至少有 1 ,可以将令牌 i 置为反面朝上,获得 token[i]能量 ,并失去 1 
    • +
    + +

    每个令牌 最多 只能使用一次,使用 顺序不限不需 使用所有令牌。

    + +

    在使用任意数量的令牌后,返回我们可以得到的最大 分数

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:tokens = [100], P = 50
    +输出:0
    +解释:无法使用唯一的令牌,因为能量和分数都太少了。
    + +

    示例 2:

    + +
    +输入:tokens = [100,200], P = 150
    +输出:1
    +解释:令牌 0 正面朝上,能量变为 50,分数变为 1 。不必使用令牌 1 ,因为你无法使用它来提高分数。
    + +

    示例 3:

    + +
    +输入:tokens = [100,200,300,400], P = 200
    +输出:2
    +解释:按下面顺序使用令牌可以得到 2 分:
    +1. 令牌 0 正面朝上,能量变为 100 ,分数变为 1
    +2. 令牌 3 正面朝下,能量变为 500 ,分数变为 0
    +3. 令牌 1 正面朝上,能量变为 300 ,分数变为 1
    +4. 令牌 2 正面朝上,能量变为 0 ,分数变为 2
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= tokens.length <= 1000
    • +
    • 0 <= tokens[i], P < 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0949.leetcode949 Largest Time for Given Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0949.leetcode949 Largest Time for Given Digits-zh.md" new file mode 100644 index 00000000..474427ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0949.leetcode949 Largest Time for Given Digits-zh.md" @@ -0,0 +1,85 @@ +# [949. 给定数字能组成的最大时间](https://leetcode-cn.com/problems/largest-time-for-given-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0949.Largest%20Time%20for%20Given%20Digits/README_EN.md) + +## 题目描述 + + + +

    给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间。

    + +

    24 小时格式为 "HH:MM" ,其中 HH0023 之间,MM0059 之间。最小的 24 小时制时间是 00:00 ,而最大的是 23:59 。从 00:00 (午夜)开始算起,过得越久,时间越大。

    + +

    以长度为 5 的字符串,按 "HH:MM" 格式返回答案。如果不能确定有效时间,则返回空字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [1,2,3,4]
    +输出:"23:41"
    +解释:有效的 24 小时制时间是 "12:34","12:43","13:24","13:42","14:23","14:32","21:34","21:43","23:14" 和 "23:41" 。这些时间中,"23:41" 是最大时间。
    +
    + +

    示例 2:

    + +
    +输入:arr = [5,5,5,5]
    +输出:""
    +解释:不存在有效的 24 小时制时间,因为 "55:55" 无效。
    +
    + +

    示例 3:

    + +
    +输入:arr = [0,0,0,0]
    +输出:"00:00"
    +
    + +

    示例 4:

    + +
    +输入:arr = [0,0,1,0]
    +输出:"10:00"
    +
    + +

     

    + +

    提示:

    + +
      +
    • arr.length == 4
    • +
    • 0 <= arr[i] <= 9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0950.leetcode950 Reveal Cards In Increasing Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0950.leetcode950 Reveal Cards In Increasing Order-zh.md" new file mode 100644 index 00000000..74a666d0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0950.leetcode950 Reveal Cards In Increasing Order-zh.md" @@ -0,0 +1,83 @@ +# [950. 按递增顺序显示卡牌](https://leetcode-cn.com/problems/reveal-cards-in-increasing-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0950.Reveal%20Cards%20In%20Increasing%20Order/README_EN.md) + +## 题目描述 + + + +

    牌组中的每张卡牌都对应有一个唯一的整数。你可以按你想要的顺序对这套卡片进行排序。

    + +

    最初,这些卡牌在牌组里是正面朝下的(即,未显示状态)。

    + +

    现在,重复执行以下步骤,直到显示所有卡牌为止:

    + +
      +
    1. 从牌组顶部抽一张牌,显示它,然后将其从牌组中移出。
    2. +
    3. 如果牌组中仍有牌,则将下一张处于牌组顶部的牌放在牌组的底部。
    4. +
    5. 如果仍有未显示的牌,那么返回步骤 1。否则,停止行动。
    6. +
    + +

    返回能以递增顺序显示卡牌的牌组顺序。

    + +

    答案中的第一张牌被认为处于牌堆顶部。

    + +

     

    + +

    示例:

    + +
    输入:[17,13,11,2,3,5,7]
    +输出:[2,13,3,11,5,17,7]
    +解释:
    +我们得到的牌组顺序为 [17,13,11,2,3,5,7](这个顺序不重要),然后将其重新排序。
    +重新排序后,牌组以 [2,13,3,11,5,17,7] 开始,其中 2 位于牌组的顶部。
    +我们显示 2,然后将 13 移到底部。牌组现在是 [3,11,5,17,7,13]。
    +我们显示 3,并将 11 移到底部。牌组现在是 [5,17,7,13,11]。
    +我们显示 5,然后将 17 移到底部。牌组现在是 [7,13,11,17]。
    +我们显示 7,并将 13 移到底部。牌组现在是 [11,17,13]。
    +我们显示 11,然后将 17 移到底部。牌组现在是 [13,17]。
    +我们展示 13,然后将 17 移到底部。牌组现在是 [17]。
    +我们显示 17。
    +由于所有卡片都是按递增顺序排列显示的,所以答案是正确的。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 1000
    2. +
    3. 1 <= A[i] <= 10^6
    4. +
    5. 对于所有的 i != jA[i] != A[j]
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0951.leetcode951 Flip Equivalent Binary Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0951.leetcode951 Flip Equivalent Binary Trees-zh.md" new file mode 100644 index 00000000..d4e4bef9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0951.leetcode951 Flip Equivalent Binary Trees-zh.md" @@ -0,0 +1,65 @@ +# [951. 翻转等价二叉树](https://leetcode-cn.com/problems/flip-equivalent-binary-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0951.Flip%20Equivalent%20Binary%20Trees/README_EN.md) + +## 题目描述 + + + +

    我们可以为二叉树 T 定义一个翻转操作,如下所示:选择任意节点,然后交换它的左子树和右子树。

    + +

    只要经过一定次数的翻转操作后,能使 X 等于 Y,我们就称二叉树 X 翻转等价于二叉树 Y。

    + +

    编写一个判断两个二叉树是否是翻转等价的函数。这些树由根节点 root1root2 给出。

    + +

     

    + +

    示例:

    + +
    输入:root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
    +输出:true
    +解释:我们翻转值为 1,3 以及 5 的三个节点。
    +Flipped Trees Diagram
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 每棵树最多有 100 个节点。
    2. +
    3. 每棵树中的每个值都是唯一的、在 [0, 99] 范围内的整数。
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0952.leetcode952 Largest Component Size by Common Factor-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0952.leetcode952 Largest Component Size by Common Factor-zh.md" new file mode 100644 index 00000000..8f994b23 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0952.leetcode952 Largest Component Size by Common Factor-zh.md" @@ -0,0 +1,85 @@ +# [952. 按公因数计算最大组件大小](https://leetcode-cn.com/problems/largest-component-size-by-common-factor) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0952.Largest%20Component%20Size%20by%20Common%20Factor/README_EN.md) + +## 题目描述 + + + +

    给定一个由不同正整数的组成的非空数组 A,考虑下面的图:

    + +
      +
    • 有 A.length 个节点,按从 A[0] 到 A[A.length - 1] 标记;
    • +
    • 只有当 A[i]A[j] 共用一个大于 1 的公因数时,A[i] 和 A[j] 之间才有一条边。
    • +
    + +

    返回图中最大连通组件的大小。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:[4,6,15,35]
    +输出:4
    +
    +
    + +

    示例 2:

    + +
    +输入:[20,50,9,63]
    +输出:2
    +
    +
    + +

    示例 3:

    + +
    +输入:[2,3,6,7,4,12,21,39]
    +输出:8
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 20000
    2. +
    3. 1 <= A[i] <= 100000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0953.leetcode953 Verifying an Alien Dictionary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0953.leetcode953 Verifying an Alien Dictionary-zh.md" new file mode 100644 index 00000000..103c818e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0953.leetcode953 Verifying an Alien Dictionary-zh.md" @@ -0,0 +1,115 @@ +# [953. 验证外星语词典](https://leetcode-cn.com/problems/verifying-an-alien-dictionary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0953.Verifying%20an%20Alien%20Dictionary/README_EN.md) + +## 题目描述 + + + +

    某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。

    + +

    给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
    +输出:true
    +解释:在该语言的字母表中,'h' 位于 'l' 之前,所以单词序列是按字典序排列的。
    + +

    示例 2:

    + +
    输入:words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
    +输出:false
    +解释:在该语言的字母表中,'d' 位于 'l' 之后,那么 words[0] > words[1],因此单词序列不是按字典序排列的。
    + +

    示例 3:

    + +
    输入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
    +输出:false
    +解释:当前三个字符 "app" 匹配时,第二个字符串相对短一些,然后根据词典编纂规则 "apple" > "app",因为 'l' > '∅',其中 '∅' 是空白字符,定义为比任何其他字符都小(更多信息)。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= words.length <= 100
    2. +
    3. 1 <= words[i].length <= 20
    4. +
    5. order.length == 26
    6. +
    7. 在 words[i] 和 order 中的所有字符都是英文小写字母。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isAlienSorted(self, words: List[str], order: str) -> bool: + index = {v: k for k, v in enumerate(order)} + for i in range(len(words) - 1): + word1, word2 = words[i], words[i + 1] + len1, len2 = len(word1), len(word2) + flag = True + for j in range(min(len1, len2)): + diff = index[word1[j]] - index[word2[j]] + if diff > 0: + # 说明不是按字典序排序,直接返回False + return False + if diff < 0: + # 说明当前两单词是按字典序排序,无需再往下进行循环比较 + flag = False + break + if flag and len1 > len2: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean isAlienSorted(String[] words, String order) { + int[] index = new int[26]; + for (int i = 0; i < 26; ++i) { + index[order.charAt(i) - 'a'] = i; + } + for (int i = 0, m = words.length; i < m - 1; ++i) { + String word1 = words[i]; + String word2 = words[i + 1]; + int len1 = word1.length(); + int len2 = word2.length(); + boolean flag = true; + for (int j = 0, n = Math.min(len1, len2); j < n && flag; ++j) { + int diff = index[word1.charAt(j) - 'a'] - index[word2.charAt(j) - 'a']; + // 说明不是按字典序排序,直接返回False + if (diff > 0) return false; + // 说明当前两单词是按字典序排序,无需再往下进行循环比较 + if (diff < 0) flag = false; + } + if (flag && len1 > len2) return false; + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0954.leetcode954 Array of Doubled Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0954.leetcode954 Array of Doubled Pairs-zh.md" new file mode 100644 index 00000000..1aefb3b6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0954.leetcode954 Array of Doubled Pairs-zh.md" @@ -0,0 +1,81 @@ +# [954. 二倍数对数组](https://leetcode-cn.com/problems/array-of-doubled-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0954.Array%20of%20Doubled%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给定一个长度为偶数的整数数组 arr,只有对 arr 进行重组后可以满足 “对于每个 0 <= i < len(arr) / 2,都有 arr[2 * i + 1] = 2 * arr[2 * i]” 时,返回 true;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [3,1,3,6]
    +输出:false
    +
    + +

    示例 2:

    + +
    +输入:arr = [2,1,2,6]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:arr = [4,-2,2,-4]
    +输出:true
    +解释:可以用 [-2,-4] 和 [2,4] 这两组组成 [-2,-4,2,4] 或是 [2,4,-2,-4]
    +
    + +

    示例 4:

    + +
    +输入:arr = [1,2,4,16,8,4]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= arr.length <= 3 * 104
    • +
    • arr.length 是偶数
    • +
    • -105 <= arr[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0955.leetcode955 Delete Columns to Make Sorted II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0955.leetcode955 Delete Columns to Make Sorted II-zh.md" new file mode 100644 index 00000000..0c792aa3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0955.leetcode955 Delete Columns to Make Sorted II-zh.md" @@ -0,0 +1,93 @@ +# [955. 删列造序 II](https://leetcode-cn.com/problems/delete-columns-to-make-sorted-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0955.Delete%20Columns%20to%20Make%20Sorted%20II/README_EN.md) + +## 题目描述 + + + +

    给定由 n 个字符串组成的数组 strs,其中每个字符串长度相等。

    + +

    选取一个删除索引序列,对于 strs 中的每个字符串,删除对应每个索引处的字符。

    + +

    比如,有 strs = ["abcdef", "uvwxyz"],删除索引序列 {0, 2, 3},删除后 strs["bef", "vyz"]

    + +

    假设,我们选择了一组删除索引 answer,那么在执行删除操作之后,最终得到的数组的元素是按 字典序strs[0] <= strs[1] <= strs[2] ... <= strs[n - 1])排列的,然后请你返回 answer.length 的最小可能值。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:strs = ["ca","bb","ac"]
    +输出:1
    +解释: 
    +删除第一列后,strs = ["a", "b", "c"]。
    +现在 strs 中元素是按字典排列的 (即,strs[0] <= strs[1] <= strs[2])。
    +我们至少需要进行 1 次删除,因为最初 strs 不是按字典序排列的,所以答案是 1。
    +
    + +

    示例 2:

    + +
    +输入:strs = ["xc","yb","za"]
    +输出:0
    +解释:
    +strs 的列已经是按字典序排列了,所以我们不需要删除任何东西。
    +注意 strs 的行不需要按字典序排列。
    +也就是说,strs[0][0] <= strs[0][1] <= ... 不一定成立。
    +
    + +

    示例 3:

    + +
    +输入:strs = ["zyx","wvu","tsr"]
    +输出:3
    +解释:
    +我们必须删掉每一列。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == strs.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= strs[i].length <= 100
    • +
    • strs[i] 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0956.leetcode956 Tallest Billboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0956.leetcode956 Tallest Billboard-zh.md" new file mode 100644 index 00000000..a82e99ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0956.leetcode956 Tallest Billboard-zh.md" @@ -0,0 +1,75 @@ +# [956. 最高的广告牌](https://leetcode-cn.com/problems/tallest-billboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0956.Tallest%20Billboard/README_EN.md) + +## 题目描述 + + + +

    你正在安装一个广告牌,并希望它高度最大。这块广告牌将有两个钢制支架,两边各一个。每个钢支架的高度必须相等。

    + +

    你有一堆可以焊接在一起的钢筋 rods。举个例子,如果钢筋的长度为 1、2 和 3,则可以将它们焊接在一起形成长度为 6 的支架。

    + +

    返回广告牌的最大可能安装高度。如果没法安装广告牌,请返回 0。

    + +

     

    + +

    示例 1:

    + +
    输入:[1,2,3,6]
    +输出:6
    +解释:我们有两个不相交的子集 {1,2,3} 和 {6},它们具有相同的和 sum = 6。
    +
    + +

    示例 2:

    + +
    输入:[1,2,3,4,5,6]
    +输出:10
    +解释:我们有两个不相交的子集 {2,3,5} 和 {4,6},它们具有相同的和 sum = 10。
    + +

    示例 3:

    + +
    输入:[1,2]
    +输出:0
    +解释:没法安装广告牌,所以返回 0。
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= rods.length <= 20
    2. +
    3. 1 <= rods[i] <= 1000
    4. +
    5. 钢筋的长度总和最多为 5000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0957.leetcode957 Prison Cells After N Days-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0957.leetcode957 Prison Cells After N Days-zh.md" new file mode 100644 index 00000000..eed295d3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0957.leetcode957 Prison Cells After N Days-zh.md" @@ -0,0 +1,91 @@ +# [957. N 天后的牢房](https://leetcode-cn.com/problems/prison-cells-after-n-days) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0957.Prison%20Cells%20After%20N%20Days/README_EN.md) + +## 题目描述 + + + +

    8 间牢房排成一排,每间牢房不是有人住就是空着。

    + +

    每天,无论牢房是被占用或空置,都会根据以下规则进行更改:

    + +
      +
    • 如果一间牢房的两个相邻的房间都被占用或都是空的,那么该牢房就会被占用。
    • +
    • 否则,它就会被空置。
    • +
    + +

    (请注意,由于监狱中的牢房排成一行,所以行中的第一个和最后一个房间无法有两个相邻的房间。)

    + +

    我们用以下方式描述监狱的当前状态:如果第 i 间牢房被占用,则 cell[i]==1,否则 cell[i]==0

    + +

    根据监狱的初始状态,在 N 天后返回监狱的状况(和上述 N 种变化)。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:cells = [0,1,0,1,1,0,0,1], N = 7
    +输出:[0,0,1,1,0,0,0,0]
    +解释:
    +下表概述了监狱每天的状况:
    +Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
    +Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
    +Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
    +Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
    +Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
    +Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
    +Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
    +Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
    +
    +
    + +

    示例 2:

    + +
    输入:cells = [1,0,0,1,0,0,1,0], N = 1000000000
    +输出:[0,0,1,1,1,1,1,0]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. cells.length == 8
    2. +
    3. cells[i] 的值为 01 
    4. +
    5. 1 <= N <= 10^9
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0958.leetcode958 Check Completeness of a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0958.leetcode958 Check Completeness of a Binary Tree-zh.md" new file mode 100644 index 00000000..121c2caa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0958.leetcode958 Check Completeness of a Binary Tree-zh.md" @@ -0,0 +1,72 @@ +# [958. 二叉树的完全性检验](https://leetcode-cn.com/problems/check-completeness-of-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0958.Check%20Completeness%20of%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,确定它是否是一个完全二叉树

    + +

    百度百科中对完全二叉树的定义如下:

    + +

    若设二叉树的深度为 h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。(注:第 h 层可能包含 1~ 2h 个节点。)

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[1,2,3,4,5,6]
    +输出:true
    +解释:最后一层前的每一层都是满的(即,结点值为 {1} 和 {2,3} 的两层),且最后一层中的所有结点({4,5,6})都尽可能地向左。
    +
    + +

    示例 2:

    + +

    + +
    输入:[1,2,3,4,5,null,7]
    +输出:false
    +解释:值为 7 的结点没有尽可能靠向左侧。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 树中将会有 1 到 100 个结点。
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0959.leetcode959 Regions Cut By Slashes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0959.leetcode959 Regions Cut By Slashes-zh.md" new file mode 100644 index 00000000..9bbd648c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0959.leetcode959 Regions Cut By Slashes-zh.md" @@ -0,0 +1,116 @@ +# [959. 由斜杠划分区域](https://leetcode-cn.com/problems/regions-cut-by-slashes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0959.Regions%20Cut%20By%20Slashes/README_EN.md) + +## 题目描述 + + + +

    在由 1 x 1 方格组成的 N x N 网格 grid 中,每个 1 x 1 方块由 /\ 或空格构成。这些字符会将方块划分为一些共边的区域。

    + +

    (请注意,反斜杠字符是转义的,因此 \"\\" 表示。)。

    + +

    返回区域的数目。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:
    +[
    +  " /",
    +  "/ "
    +]
    +输出:2
    +解释:2x2 网格如下:
    +
    + +

    示例 2:

    + +
    输入:
    +[
    +  " /",
    +  "  "
    +]
    +输出:1
    +解释:2x2 网格如下:
    +
    + +

    示例 3:

    + +
    输入:
    +[
    +  "\\/",
    +  "/\\"
    +]
    +输出:4
    +解释:(回想一下,因为 \ 字符是转义的,所以 "\\/" 表示 \/,而 "/\\" 表示 /\。)
    +2x2 网格如下:
    +
    + +

    示例 4:

    + +
    输入:
    +[
    +  "/\\",
    +  "\\/"
    +]
    +输出:5
    +解释:(回想一下,因为 \ 字符是转义的,所以 "/\\" 表示 /\,而 "\\/" 表示 \/。)
    +2x2 网格如下:
    +
    + +

    示例 5:

    + +
    输入:
    +[
    +  "//",
    +  "/ "
    +]
    +输出:3
    +解释:2x2 网格如下:
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= grid.length == grid[0].length <= 30
    2. +
    3. grid[i][j] 是 '/''\'、或 ' '
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0960.leetcode960 Delete Columns to Make Sorted III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0960.leetcode960 Delete Columns to Make Sorted III-zh.md" new file mode 100644 index 00000000..81966254 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0960.leetcode960 Delete Columns to Make Sorted III-zh.md" @@ -0,0 +1,85 @@ +# [960. 删列造序 III](https://leetcode-cn.com/problems/delete-columns-to-make-sorted-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0960.Delete%20Columns%20to%20Make%20Sorted%20III/README_EN.md) + +## 题目描述 + + + +

    给定由 N 个小写字母字符串组成的数组 A,其中每个字符串长度相等。

    + +

    选取一个删除索引序列,对于 A 中的每个字符串,删除对应每个索引处的字符。

    + +

    比如,有 A = ["babca","bbazb"],删除索引序列 {0, 1, 4},删除后 A 为["bc","az"]

    + +

    假设,我们选择了一组删除索引 D,那么在执行删除操作之后,最终得到的数组的行中的每个元素都是按字典序排列的。

    + +

    清楚起见,A[0] 是按字典序排列的(即,A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1]),A[1] 是按字典序排列的(即,A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1]),依此类推。

    + +

    请你返回 D.length 的最小可能值。

    + +

     

    + +

    示例 1:

    + +
    输入:["babca","bbazb"]
    +输出:3
    +解释:
    +删除 0、1 和 4 这三列后,最终得到的数组是 A = ["bc", "az"]。
    +这两行是分别按字典序排列的(即,A[0][0] <= A[0][1] 且 A[1][0] <= A[1][1])。
    +注意,A[0] > A[1] —— 数组 A 不一定是按字典序排列的。
    +
    + +

    示例 2:

    + +
    输入:["edcba"]
    +输出:4
    +解释:如果删除的列少于 4 列,则剩下的行都不会按字典序排列。
    +
    + +

    示例 3:

    + +
    输入:["ghi","def","abc"]
    +输出:0
    +解释:所有行都已按字典序排列。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 100
    2. +
    3. 1 <= A[i].length <= 100
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0961.leetcode961 N-Repeated Element in Size 2N Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0961.leetcode961 N-Repeated Element in Size 2N Array-zh.md" new file mode 100644 index 00000000..fb06ddea --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0961.leetcode961 N-Repeated Element in Size 2N Array-zh.md" @@ -0,0 +1,136 @@ +# [961. 重复 N 次的元素](https://leetcode-cn.com/problems/n-repeated-element-in-size-2n-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0961.N-Repeated%20Element%20in%20Size%202N%20Array/README_EN.md) + +## 题目描述 + + + +

    在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。

    + +

    返回重复了 N 次的那个元素。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:[1,2,3,3]
    +输出:3
    +
    + +

    示例 2:

    + +
    +输入:[2,1,2,5,3,2]
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:[5,1,5,2,5,3,5,4]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 4 <= A.length <= 10000
    • +
    • 0 <= A[i] < 10000
    • +
    • A.length 为偶数
    • +
    + + +## 解法 + + + +长度为 `2N`,共 `N+1` 个不同元素,其中一个元素出现 `N` 次,说明其它元素各不相同。 + +遍历数组,只要出现重复元素,它就是我们要找的重复 `N` 次的元素。 + + + +### **Python3** + + + +```python +class Solution: + def repeatedNTimes(self, nums: List[int]) -> int: + s = set() + for num in nums: + if num in s: + return num + s.add(num) +``` + +### **Java** + + + +```java +class Solution { + public int repeatedNTimes(int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + if (s.contains(num)) { + return num; + } + s.add(num); + } + return -1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int repeatedNTimes(vector& nums) { + unordered_set s; + for (auto &num : nums) { + if (s.find(num) != s.end()) { + return num; + } + s.insert(num); + } + return -1; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var repeatedNTimes = function(nums) { + const s = new Set(); + for (const num of nums) { + if (s.has(num)) { + return num; + } + s.add(num); + } + return -1; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0962.leetcode962 Maximum Width Ramp-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0962.leetcode962 Maximum Width Ramp-zh.md" new file mode 100644 index 00000000..7661cc93 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0962.leetcode962 Maximum Width Ramp-zh.md" @@ -0,0 +1,71 @@ +# [962. 最大宽度坡](https://leetcode-cn.com/problems/maximum-width-ramp) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0962.Maximum%20Width%20Ramp/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A是元组 (i, j),其中  i < j 且 A[i] <= A[j]。这样的坡的宽度为 j - i

    + +

    找出 A 中的坡的最大宽度,如果不存在,返回 0 。

    + +

     

    + +

    示例 1:

    + +
    输入:[6,0,8,2,1,5]
    +输出:4
    +解释:
    +最大宽度的坡为 (i, j) = (1, 5): A[1] = 0 且 A[5] = 5.
    +
    + +

    示例 2:

    + +
    输入:[9,8,1,0,1,9,4,0,4,1]
    +输出:7
    +解释:
    +最大宽度的坡为 (i, j) = (2, 9): A[2] = 1 且 A[9] = 1.
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= A.length <= 50000
    2. +
    3. 0 <= A[i] <= 50000
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0963.leetcode963 Minimum Area Rectangle II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0963.leetcode963 Minimum Area Rectangle II-zh.md" new file mode 100644 index 00000000..44046ea4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0963.leetcode963 Minimum Area Rectangle II-zh.md" @@ -0,0 +1,91 @@ +# [963. 最小面积矩形 II](https://leetcode-cn.com/problems/minimum-area-rectangle-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0963.Minimum%20Area%20Rectangle%20II/README_EN.md) + +## 题目描述 + + + +

    给定在 xy 平面上的一组点,确定由这些点组成的任何矩形的最小面积,其中矩形的边不一定平行于 x 轴和 y 轴。

    + +

    如果没有任何矩形,就返回 0。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[[1,2],[2,1],[1,0],[0,1]]
    +输出:2.00000
    +解释:最小面积的矩形出现在 [1,2],[2,1],[1,0],[0,1] 处,面积为 2。
    + +

    示例 2:

    + +

    + +
    输入:[[0,1],[2,1],[1,1],[1,0],[2,0]]
    +输出:1.00000
    +解释:最小面积的矩形出现在 [1,0],[1,1],[2,1],[2,0] 处,面积为 1。
    +
    + +

    示例 3:

    + +

    + +
    输入:[[0,3],[1,2],[3,1],[1,3],[2,1]]
    +输出:0
    +解释:没法从这些点中组成任何矩形。
    +
    + +

    示例 4:

    + +

    + +
    输入:[[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
    +输出:2.00000
    +解释:最小面积的矩形出现在 [2,1],[2,3],[3,3],[3,1] 处,面积为 2。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= points.length <= 50
    2. +
    3. 0 <= points[i][0] <= 40000
    4. +
    5. 0 <= points[i][1] <= 40000
    6. +
    7. 所有的点都是不同的。
    8. +
    9. 与真实值误差不超过 10^-5 的答案将视为正确结果。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0964.leetcode964 Least Operators to Express Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0964.leetcode964 Least Operators to Express Number-zh.md" new file mode 100644 index 00000000..b745dc91 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0964.leetcode964 Least Operators to Express Number-zh.md" @@ -0,0 +1,84 @@ +# [964. 表示数字的最少运算符](https://leetcode-cn.com/problems/least-operators-to-express-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0964.Least%20Operators%20to%20Express%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数 x,我们将会写出一个形如 x (op1) x (op2) x (op3) x ... 的表达式,其中每个运算符 op1op2,… 可以是加、减、乘、除(+-*,或是 /)之一。例如,对于 x = 3,我们可以写出表达式 3 * 3 / 3 + 3 - 3,该式的值为 3 。

    + +

    在写这样的表达式时,我们需要遵守下面的惯例:

    + +
      +
    1. 除运算符(/)返回有理数。
    2. +
    3. 任何地方都没有括号。
    4. +
    5. 我们使用通常的操作顺序:乘法和除法发生在加法和减法之前。
    6. +
    7. 不允许使用一元否定运算符(-)。例如,“x - x” 是一个有效的表达式,因为它只使用减法,但是 “-x + x” 不是,因为它使用了否定运算符。 
    8. +
    + +

    我们希望编写一个能使表达式等于给定的目标值 target 且运算符最少的表达式。返回所用运算符的最少数量。

    + +

     

    + +

    示例 1:

    + +
    输入:x = 3, target = 19
    +输出:5
    +解释:3 * 3 + 3 * 3 + 3 / 3 。表达式包含 5 个运算符。
    +
    + +

    示例 2:

    + +
    输入:x = 5, target = 501
    +输出:8
    +解释:5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5 。表达式包含 8 个运算符。
    +
    + +

    示例 3:

    + +
    输入:x = 100, target = 100000000
    +输出:3
    +解释:100 * 100 * 100 * 100 。表达式包含 3 个运算符。
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= x <= 100
    • +
    • 1 <= target <= 2 * 10^8
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0965.leetcode965 Univalued Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0965.leetcode965 Univalued Binary Tree-zh.md" new file mode 100644 index 00000000..e4683a60 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0965.leetcode965 Univalued Binary Tree-zh.md" @@ -0,0 +1,69 @@ +# [965. 单值二叉树](https://leetcode-cn.com/problems/univalued-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0965.Univalued%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。

    + +

    只有给定的树是单值二叉树时,才返回 true;否则返回 false

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[1,1,1,1,1,null,1]
    +输出:true
    +
    + +

    示例 2:

    + +

    + +
    输入:[2,2,2,5,2]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 给定树的节点数范围是 [1, 100]
    2. +
    3. 每个节点的值都是整数,范围为 [0, 99] 。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0966.leetcode966 Vowel Spellchecker-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0966.leetcode966 Vowel Spellchecker-zh.md" new file mode 100644 index 00000000..b6d369f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0966.leetcode966 Vowel Spellchecker-zh.md" @@ -0,0 +1,90 @@ +# [966. 元音拼写检查器](https://leetcode-cn.com/problems/vowel-spellchecker) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0966.Vowel%20Spellchecker/README_EN.md) + +## 题目描述 + + + +

    在给定单词列表 wordlist 的情况下,我们希望实现一个拼写检查器,将查询单词转换为正确的单词。

    + +

    对于给定的查询单词 query,拼写检查器将会处理两类拼写错误:

    + +
      +
    • 大小写:如果查询匹配单词列表中的某个单词(不区分大小写),则返回的正确单词与单词列表中的大小写相同。 + +
        +
      • 例如:wordlist = ["yellow"], query = "YellOw": correct = "yellow"
      • +
      • 例如:wordlist = ["Yellow"], query = "yellow": correct = "Yellow"
      • +
      • 例如:wordlist = ["yellow"], query = "yellow": correct = "yellow"
      • +
      +
    • +
    • 元音错误:如果在将查询单词中的元音(‘a’、‘e’、‘i’、‘o’、‘u’)分别替换为任何元音后,能与单词列表中的单词匹配(不区分大小写),则返回的正确单词与单词列表中的匹配项大小写相同。 +
        +
      • 例如:wordlist = ["YellOw"], query = "yollow": correct = "YellOw"
      • +
      • 例如:wordlist = ["YellOw"], query = "yeellow": correct = "" (无匹配项)
      • +
      • 例如:wordlist = ["YellOw"], query = "yllw": correct = "" (无匹配项)
      • +
      +
    • +
    + +

    此外,拼写检查器还按照以下优先级规则操作:

    + +
      +
    • 当查询完全匹配单词列表中的某个单词(区分大小写)时,应返回相同的单词。
    • +
    • 当查询匹配到大小写问题的单词时,您应该返回单词列表中的第一个这样的匹配项。
    • +
    • 当查询匹配到元音错误的单词时,您应该返回单词列表中的第一个这样的匹配项。
    • +
    • 如果该查询在单词列表中没有匹配项,则应返回空字符串。
    • +
    + +

    给出一些查询 queries,返回一个单词列表 answer,其中 answer[i] 是由查询 query = queries[i] 得到的正确单词。

    + +

     

    + +

    示例:

    + +
    输入:wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
    +输出:["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= wordlist.length <= 5000
    2. +
    3. 1 <= queries.length <= 5000
    4. +
    5. 1 <= wordlist[i].length <= 7
    6. +
    7. 1 <= queries[i].length <= 7
    8. +
    9. wordlist 和 queries 中的所有字符串仅由英文字母组成。
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0967.leetcode967 Numbers With Same Consecutive Differences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0967.leetcode967 Numbers With Same Consecutive Differences-zh.md" new file mode 100644 index 00000000..7e6743a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0967.leetcode967 Numbers With Same Consecutive Differences-zh.md" @@ -0,0 +1,83 @@ +# [967. 连续差相同的数字](https://leetcode-cn.com/problems/numbers-with-same-consecutive-differences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0967.Numbers%20With%20Same%20Consecutive%20Differences/README_EN.md) + +## 题目描述 + + + +

    返回所有长度为 n 且满足其每两个连续位上的数字之间的差的绝对值为 k 非负整数

    + +

    请注意,除了 数字 0 本身之外,答案中的每个数字都 不能 有前导零。例如,01 有一个前导零,所以是无效的;但 0 是有效的。

    + +

    你可以按 任何顺序 返回答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, k = 7
    +输出:[181,292,707,818,929]
    +解释:注意,070 不是一个有效的数字,因为它有前导零。
    +
    + +

    示例 2:

    + +
    +输入:n = 2, k = 1
    +输出:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
    + +

    示例 3:

    + +
    +输入:n = 2, k = 0
    +输出:[11,22,33,44,55,66,77,88,99]
    +
    + +

    示例 4:

    + +
    +输入:n = 2, k = 2
    +输出:[13,20,24,31,35,42,46,53,57,64,68,75,79,86,97]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 9
    • +
    • 0 <= k <= 9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0968.leetcode968 Binary Tree Cameras-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0968.leetcode968 Binary Tree Cameras-zh.md" new file mode 100644 index 00000000..f6ad3aac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0968.leetcode968 Binary Tree Cameras-zh.md" @@ -0,0 +1,110 @@ +# [968. 监控二叉树](https://leetcode-cn.com/problems/binary-tree-cameras) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0968.Binary%20Tree%20Cameras/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,我们在树的节点上安装摄像头。

    + +

    节点上的每个摄影头都可以监视其父对象、自身及其直接子对象。

    + +

    计算监控树的所有节点所需的最小摄像头数量。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[0,0,null,0,0]
    +输出:1
    +解释:如图所示,一台摄像头足以监控所有节点。
    +
    + +

    示例 2:

    + +

    + +
    输入:[0,0,null,0,null,0,null,null,0]
    +输出:2
    +解释:需要至少两个摄像头来监视树的所有节点。 上图显示了摄像头放置的有效位置之一。
    +
    + +


    +提示:

    + +
      +
    1. 给定树的节点数的范围是 [1, 1000]
    2. +
    3. 每个节点的值都是 0。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **Go** + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +var res int +func minCameraCover(root *TreeNode) int { + res = 0 + //三种状态,后序遍历 + if root == nil { + return 0 + } + if dfs(root) == 0 { + res++ + } + return res +} +//0:待覆盖,1:已覆盖,2:安装 + +func dfs(root *TreeNode) int { + if root == nil { + return 1 + } + l := dfs(root.Left) + r := dfs(root.Right) + //左右子节点存在待覆盖状态,当前节点要安装 + if l == 0 || r == 0 { + res++ + return 2 + } else if l == 1 && r == 1 { //左右节点均为已覆盖,则当前节点为待覆盖 + return 0 + } + //除上述情况外,左右子节点中至少有一个安装了监控,当前节点为已覆盖 + return 1 +} +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0969.leetcode969 Pancake Sorting-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0969.leetcode969 Pancake Sorting-zh.md" new file mode 100644 index 00000000..0ca7d33c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0969.leetcode969 Pancake Sorting-zh.md" @@ -0,0 +1,87 @@ +# [969. 煎饼排序](https://leetcode-cn.com/problems/pancake-sorting) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0969.Pancake%20Sorting/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,请使用 煎饼翻转 完成对数组的排序。

    + +

    一次煎饼翻转的执行过程如下:

    + +
      +
    • 选择一个整数 k1 <= k <= arr.length
    • +
    • 反转子数组 arr[0...k-1]下标从 0 开始
    • +
    + +

    例如,arr = [3,2,1,4] ,选择 k = 3 进行一次煎饼翻转,反转子数组 [3,2,1] ,得到 arr = [1,2,3,4]

    + +

    以数组形式返回能使 arr 有序的煎饼翻转操作所对应的 k 值序列。任何将数组排序且翻转次数在 10 * arr.length 范围内的有效答案都将被判断为正确。

    + +

     

    + +

    示例 1:

    + +
    +输入:[3,2,4,1]
    +输出:[4,2,4,3]
    +解释:
    +我们执行 4 次煎饼翻转,k 值分别为 4,2,4,和 3。
    +初始状态 arr = [3, 2, 4, 1]
    +第一次翻转后(k = 4):arr = [1, 4, 2, 3]
    +第二次翻转后(k = 2):arr = [4, 1, 2, 3]
    +第三次翻转后(k = 4):arr = [3, 2, 1, 4]
    +第四次翻转后(k = 3):arr = [1, 2, 3, 4],此时已完成排序。 
    +
    + +

    示例 2:

    + +
    +输入:[1,2,3]
    +输出:[]
    +解释:
    +输入已经排序,因此不需要翻转任何内容。
    +请注意,其他可能的答案,如 [3,3] ,也将被判断为正确。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= arr.length
    • +
    • arr 中的所有整数互不相同(即,arr 是从 1arr.length 整数的一个排列)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0970.leetcode970 Powerful Integers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0970.leetcode970 Powerful Integers-zh.md" new file mode 100644 index 00000000..9fcb9012 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0970.leetcode970 Powerful Integers-zh.md" @@ -0,0 +1,132 @@ +# [970. 强整数](https://leetcode-cn.com/problems/powerful-integers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0970.Powerful%20Integers/README_EN.md) + +## 题目描述 + + + +

    给定两个正整数 xy,如果某一整数等于 x^i + y^j,其中整数 i >= 0 且 j >= 0,那么我们认为该整数是一个强整数

    + +

    返回值小于或等于 bound 的所有强整数组成的列表。

    + +

    你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。

    + +

     

    + +

    示例 1:

    + +
    输入:x = 2, y = 3, bound = 10
    +输出:[2,3,4,5,7,9,10]
    +解释: 
    +2 = 2^0 + 3^0
    +3 = 2^1 + 3^0
    +4 = 2^0 + 3^1
    +5 = 2^1 + 3^1
    +7 = 2^2 + 3^1
    +9 = 2^3 + 3^0
    +10 = 2^0 + 3^2
    +
    + +

    示例 2:

    + +
    输入:x = 3, y = 5, bound = 15
    +输出:[2,4,6,8,10,14]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= x <= 100
    • +
    • 1 <= y <= 100
    • +
    • 0 <= bound <= 10^6
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: + s = set() + i = 1 + while i < bound: + j = 1 + while j < bound: + if i + j <= bound: + s.add(i + j) + if y == 1: + break + j *= y + if x == 1: + break + i *= x + return list(s) +``` + +### **Java** + + + +```java +class Solution { + public List powerfulIntegers(int x, int y, int bound) { + Set s = new HashSet<>(); + for (int i = 1; i < bound; i *= x) { + for (int j = 1; j < bound; j *= y) { + if (i + j <= bound) { + s.add(i + j); + } + if (y == 1) { + break; + } + } + if (x == 1) { + break; + } + } + return new ArrayList<>(s); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} x + * @param {number} y + * @param {number} bound + * @return {number[]} + */ +var powerfulIntegers = function(x, y, bound) { + let res = new Set(); + for (let i = 1; i < bound; i *= x) { + for (let j = 1; j < bound; j *= y) { + if ((i + j) <= bound) { + res.add(i + j); + } + if (y == 1) break; + } + if (x == 1) break; + } + return [...res]; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0971.leetcode971 Flip Binary Tree To Match Preorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0971.leetcode971 Flip Binary Tree To Match Preorder Traversal-zh.md" new file mode 100644 index 00000000..63a06565 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0971.leetcode971 Flip Binary Tree To Match Preorder Traversal-zh.md" @@ -0,0 +1,86 @@ +# [971. 翻转二叉树以匹配先序遍历](https://leetcode-cn.com/problems/flip-binary-tree-to-match-preorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0971.Flip%20Binary%20Tree%20To%20Match%20Preorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树的根节点 root ,树中有 n 个节点,每个节点都有一个不同于其他节点且处于 1n 之间的值。

    + +

    另给你一个由 n 个值组成的行程序列 voyage ,表示 预期 的二叉树 先序遍历 结果。

    + +

    通过交换节点的左右子树,可以 翻转 该二叉树中的任意节点。例,翻转节点 1 的效果如下:

    + +

    请翻转 最少 的树中节点,使二叉树的 先序遍历 与预期的遍历行程 voyage 相匹配 。 

    + +

    如果可以,则返回 翻转的 所有节点的值的列表。你可以按任何顺序返回答案。如果不能,则返回列表 [-1]

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,2], voyage = [2,1]
    +输出:[-1]
    +解释:翻转节点无法令先序遍历匹配预期行程。
    +
    + +

    示例 2:

    + +
    +输入:root = [1,2,3], voyage = [1,3,2]
    +输出:[1]
    +解释:交换节点 2 和 3 来翻转节点 1 ,先序遍历可以匹配预期行程。
    + +

    示例 3:

    + +
    +输入:root = [1,2,3], voyage = [1,2,3]
    +输出:[]
    +解释:先序遍历已经匹配预期行程,所以不需要翻转节点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数目为 n
    • +
    • n == voyage.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= Node.val, voyage[i] <= n
    • +
    • 树中的所有值 互不相同
    • +
    • voyage 中的所有值 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0972.leetcode972 Equal Rational Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0972.leetcode972 Equal Rational Numbers-zh.md" new file mode 100644 index 00000000..fd90cf17 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0972.leetcode972 Equal Rational Numbers-zh.md" @@ -0,0 +1,89 @@ +# [972. 相等的有理数](https://leetcode-cn.com/problems/equal-rational-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0972.Equal%20Rational%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 ST,每个字符串代表一个非负有理数,只有当它们表示相同的数字时才返回 true;否则,返回 false。字符串中可以使用括号来表示有理数的重复部分。

    + +

    通常,有理数最多可以用三个部分来表示:整数部分 <IntegerPart>小数非重复部分 <NonRepeatingPart> 和小数重复部分 <(><RepeatingPart><)>。数字可以用以下三种方法之一来表示:

    + +
      +
    • <IntegerPart>(例:0,12,123)
    • +
    • <IntegerPart><.><NonRepeatingPart> (例:0.5,2.12,2.0001)
    • +
    • <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>(例:0.1(6),0.9(9),0.00(1212))
    • +
    + +

    十进制展开的重复部分通常在一对圆括号内表示。例如:

    + +

    1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)

    + +

    0.1(6) 或 0.1666(6) 或 0.166(66) 都是 1 / 6 的正确表示形式。

    + +

     

    + +

    示例 1:

    + +
    输入:S = "0.(52)", T = "0.5(25)"
    +输出:true
    +解释:因为 "0.(52)" 代表 0.52525252...,而 "0.5(25)" 代表 0.52525252525.....,则这两个字符串表示相同的数字。
    +
    + +

    示例 2:

    + +
    输入:S = "0.1666(6)", T = "0.166(66)"
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:S = "0.9(9)", T = "1."
    +输出:true
    +解释:
    +"0.9(9)" 代表 0.999999999... 永远重复,等于 1 。[有关说明,请参阅此链接]
    +"1." 表示数字 1,其格式正确:(IntegerPart) = "1" 且 (NonRepeatingPart) = "" 。
    + +

     

    + +

    提示:

    + +
      +
    1. 每个部分仅由数字组成。
    2. +
    3. 整数部分 <IntegerPart> 不会以 2 个或更多的零开头。(对每个部分的数字没有其他限制)。
    4. +
    5. 1 <= <IntegerPart>.length <= 4
    6. +
    7. 0 <= <NonRepeatingPart>.length <= 4
    8. +
    9. 1 <= <RepeatingPart>.length <= 4
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0973.leetcode973 K Closest Points to Origin-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0973.leetcode973 K Closest Points to Origin-zh.md" new file mode 100644 index 00000000..d31668b2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0973.leetcode973 K Closest Points to Origin-zh.md" @@ -0,0 +1,74 @@ +# [973. 最接近原点的 K 个点](https://leetcode-cn.com/problems/k-closest-points-to-origin) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0973.K%20Closest%20Points%20to%20Origin/README_EN.md) + +## 题目描述 + + + +

    我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。

    + +

    (这里,平面上两点之间的距离是欧几里德距离。)

    + +

    你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。

    + +

     

    + +

    示例 1:

    + +
    输入:points = [[1,3],[-2,2]], K = 1
    +输出:[[-2,2]]
    +解释: 
    +(1, 3) 和原点之间的距离为 sqrt(10),
    +(-2, 2) 和原点之间的距离为 sqrt(8),
    +由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。
    +我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]。
    +
    + +

    示例 2:

    + +
    输入:points = [[3,3],[5,-1],[-2,4]], K = 2
    +输出:[[3,3],[-2,4]]
    +(答案 [[-2,4],[3,3]] 也会被接受。)
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= K <= points.length <= 10000
    2. +
    3. -10000 < points[i][0] < 10000
    4. +
    5. -10000 < points[i][1] < 10000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0974.leetcode974 Subarray Sums Divisible by K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0974.leetcode974 Subarray Sums Divisible by K-zh.md" new file mode 100644 index 00000000..9aae01d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0974.leetcode974 Subarray Sums Divisible by K-zh.md" @@ -0,0 +1,61 @@ +# [974. 和可被 K 整除的子数组](https://leetcode-cn.com/problems/subarray-sums-divisible-by-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0974.Subarray%20Sums%20Divisible%20by%20K/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。

    + +

     

    + +

    示例:

    + +
    输入:A = [4,5,0,-2,-3,1], K = 5
    +输出:7
    +解释:
    +有 7 个子数组满足其元素之和可被 K = 5 整除:
    +[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 30000
    2. +
    3. -10000 <= A[i] <= 10000
    4. +
    5. 2 <= K <= 10000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0975.leetcode975 Odd Even Jump-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0975.leetcode975 Odd Even Jump-zh.md" new file mode 100644 index 00000000..a89dc6ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0975.leetcode975 Odd Even Jump-zh.md" @@ -0,0 +1,106 @@ +# [975. 奇偶跳](https://leetcode-cn.com/problems/odd-even-jump) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0975.Odd%20Even%20Jump/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,你可以从某一起始索引出发,跳跃一定次数。在你跳跃的过程中,第 1、3、5... 次跳跃称为奇数跳跃,而第 2、4、6... 次跳跃称为偶数跳跃。

    + +

    你可以按以下方式从索引 i 向后跳转到索引 j(其中 i < j):

    + +
      +
    • 在进行奇数跳跃时(如,第 1,3,5... 次跳跃),你将会跳到索引 j,使得 A[i] <= A[j]A[j] 是可能的最小值。如果存在多个这样的索引 j,你只能跳到满足要求的最小索引 j 上。
    • +
    • 在进行偶数跳跃时(如,第 2,4,6... 次跳跃),你将会跳到索引 j,使得 A[i] >= A[j]A[j] 是可能的最大值。如果存在多个这样的索引 j,你只能跳到满足要求的最小索引 j 上。
    • +
    • (对于某些索引 i,可能无法进行合乎要求的跳跃。)
    • +
    + +

    如果从某一索引开始跳跃一定次数(可能是 0 次或多次),就可以到达数组的末尾(索引 A.length - 1),那么该索引就会被认为是好的起始索引。

    + +

    返回好的起始索引的数量。

    + +

     

    + +

    示例 1:

    + +
    输入:[10,13,12,14,15]
    +输出:2
    +解释: 
    +从起始索引 i = 0 出发,我们可以跳到 i = 2,(因为 A[2] 是 A[1],A[2],A[3],A[4] 中大于或等于 A[0] 的最小值),然后我们就无法继续跳下去了。
    +从起始索引 i = 1 和 i = 2 出发,我们可以跳到 i = 3,然后我们就无法继续跳下去了。
    +从起始索引 i = 3 出发,我们可以跳到 i = 4,到达数组末尾。
    +从起始索引 i = 4 出发,我们已经到达数组末尾。
    +总之,我们可以从 2 个不同的起始索引(i = 3, i = 4)出发,通过一定数量的跳跃到达数组末尾。
    +
    + +

    示例 2:

    + +
    输入:[2,3,1,1,4]
    +输出:3
    +解释:
    +从起始索引 i=0 出发,我们依次可以跳到 i = 1,i = 2,i = 3:
    +
    +在我们的第一次跳跃(奇数)中,我们先跳到 i = 1,因为 A[1] 是(A[1],A[2],A[3],A[4])中大于或等于 A[0] 的最小值。
    +
    +在我们的第二次跳跃(偶数)中,我们从 i = 1 跳到 i = 2,因为 A[2] 是(A[2],A[3],A[4])中小于或等于 A[1] 的最大值。A[3] 也是最大的值,但 2 是一个较小的索引,所以我们只能跳到 i = 2,而不能跳到 i = 3。
    +
    +在我们的第三次跳跃(奇数)中,我们从 i = 2 跳到 i = 3,因为 A[3] 是(A[3],A[4])中大于或等于 A[2] 的最小值。
    +
    +我们不能从 i = 3 跳到 i = 4,所以起始索引 i = 0 不是好的起始索引。
    +
    +类似地,我们可以推断:
    +从起始索引 i = 1 出发, 我们跳到 i = 4,这样我们就到达数组末尾。
    +从起始索引 i = 2 出发, 我们跳到 i = 3,然后我们就不能再跳了。
    +从起始索引 i = 3 出发, 我们跳到 i = 4,这样我们就到达数组末尾。
    +从起始索引 i = 4 出发,我们已经到达数组末尾。
    +总之,我们可以从 3 个不同的起始索引(i = 1, i = 3, i = 4)出发,通过一定数量的跳跃到达数组末尾。
    +
    + +

    示例 3:

    + +
    输入:[5,1,3,4,2]
    +输出:3
    +解释: 
    +我们可以从起始索引 1,2,4 出发到达数组末尾。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 20000
    2. +
    3. 0 <= A[i] < 100000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0976.leetcode976 Largest Perimeter Triangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0976.leetcode976 Largest Perimeter Triangle-zh.md" new file mode 100644 index 00000000..f78dde84 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0976.leetcode976 Largest Perimeter Triangle-zh.md" @@ -0,0 +1,80 @@ +# [976. 三角形的最大周长](https://leetcode-cn.com/problems/largest-perimeter-triangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0976.Largest%20Perimeter%20Triangle/README_EN.md) + +## 题目描述 + + + +

    给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。

    + +

    如果不能形成任何面积不为零的三角形,返回 0

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:[2,1,2]
    +输出:5
    +
    + +

    示例 2:

    + +
    输入:[1,2,1]
    +输出:0
    +
    + +

    示例 3:

    + +
    输入:[3,2,3,4]
    +输出:10
    +
    + +

    示例 4:

    + +
    输入:[3,6,2,3]
    +输出:8
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= A.length <= 10000
    2. +
    3. 1 <= A[i] <= 10^6
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0977.leetcode977 Squares of a Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0977.leetcode977 Squares of a Sorted Array-zh.md" new file mode 100644 index 00000000..3ef4f0e2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0977.leetcode977 Squares of a Sorted Array-zh.md" @@ -0,0 +1,171 @@ +# [977. 有序数组的平方](https://leetcode-cn.com/problems/squares-of-a-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0977.Squares%20of%20a%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [-4,-1,0,3,10]
    +输出:[0,1,9,16,100]
    +解释:平方后,数组变为 [16,1,0,9,100]
    +排序后,数组变为 [0,1,9,16,100]
    + +

    示例 2:

    + +
    +输入:nums = [-7,-3,2,3,11]
    +输出:[4,9,9,49,121]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 104
    • +
    • -104 <= nums[i] <= 104
    • +
    • nums 已按 非递减顺序 排序
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 请你设计时间复杂度为 O(n) 的算法解决本问题
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + res = [0] * n + i, j, k = 0, n - 1, n - 1 + while i <= j: + if nums[i] * nums[i] > nums[j] * nums[j]: + res[k] = nums[i] * nums[i] + i += 1 + else: + res[k] = nums[j] * nums[j] + j -= 1 + k -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] sortedSquares(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + for (int i = 0, j = n - 1, k = n - 1; i <= j;) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector sortedSquares(vector& nums) { + int n = nums.size(); + vector res(n); + for (int i = 0, j = n - 1, k = n - 1; i <= j;) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; + } +}; +``` + +### **Go** + +```go +func sortedSquares(nums []int) []int { + n := len(nums) + res := make([]int, n) + for i, j, k := 0, n-1, n-1; i <= j; { + if nums[i]*nums[i] > nums[j]*nums[j] { + res[k] = nums[i] * nums[i] + i++ + } else { + res[k] = nums[j] * nums[j] + j-- + } + k-- + } + return res +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortedSquares = function(nums) { + const n = nums.length; + const res = new Array(n); + for (let i = 0, j = n - 1, k = n - 1; i <= j;) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0978.leetcode978 Longest Turbulent Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0978.leetcode978 Longest Turbulent Subarray-zh.md" new file mode 100644 index 00000000..7ded0851 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0978.leetcode978 Longest Turbulent Subarray-zh.md" @@ -0,0 +1,79 @@ +# [978. 最长湍流子数组](https://leetcode-cn.com/problems/longest-turbulent-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0978.Longest%20Turbulent%20Subarray/README_EN.md) + +## 题目描述 + + + +

    A 的子数组 A[i], A[i+1], ..., A[j] 满足下列条件时,我们称其为湍流子数组

    + +
      +
    • 若 i <= k < j,当 k 为奇数时, A[k] > A[k+1],且当 k 为偶数时,A[k] < A[k+1]
    • +
    • 若 i <= k < j,当 k 为偶数时,A[k] > A[k+1] ,且当 k 为奇数时, A[k] < A[k+1]
    • +
    + +

    也就是说,如果比较符号在子数组中的每个相邻元素对之间翻转,则该子数组是湍流子数组。

    + +

    返回 A 的最大湍流子数组的长度

    + +

     

    + +

    示例 1:

    + +
    输入:[9,4,2,10,7,8,8,1,9]
    +输出:5
    +解释:(A[1] > A[2] < A[3] > A[4] < A[5])
    +
    + +

    示例 2:

    + +
    输入:[4,8,12,16]
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:[100]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 40000
    2. +
    3. 0 <= A[i] <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0979.leetcode979 Distribute Coins in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0979.leetcode979 Distribute Coins in Binary Tree-zh.md" new file mode 100644 index 00000000..2b57a607 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0979.leetcode979 Distribute Coins in Binary Tree-zh.md" @@ -0,0 +1,89 @@ +# [979. 在二叉树中分配硬币](https://leetcode-cn.com/problems/distribute-coins-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0979.Distribute%20Coins%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个有 N 个结点的二叉树的根结点 root,树中的每个结点上都对应有 node.val 枚硬币,并且总共有 N 枚硬币。

    + +

    在一次移动中,我们可以选择两个相邻的结点,然后将一枚硬币从其中一个结点移动到另一个结点。(移动可以是从父结点到子结点,或者从子结点移动到父结点。)。

    + +

    返回使每个结点上只有一枚硬币所需的移动次数。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[3,0,0]
    +输出:2
    +解释:从树的根结点开始,我们将一枚硬币移到它的左子结点上,一枚硬币移到它的右子结点上。
    +
    + +

    示例 2:

    + +

    + +
    输入:[0,3,0]
    +输出:3
    +解释:从根结点的左子结点开始,我们将两枚硬币移到根结点上 [移动两次]。然后,我们把一枚硬币从根结点移到右子结点上。
    +
    + +

    示例 3:

    + +

    + +
    输入:[1,0,2]
    +输出:2
    +
    + +

    示例 4:

    + +

    + +
    输入:[1,0,0,null,3]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1<= N <= 100
    2. +
    3. 0 <= node.val <= N
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0980.leetcode980 Unique Paths III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0980.leetcode980 Unique Paths III-zh.md" new file mode 100644 index 00000000..a8021a98 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0980.leetcode980 Unique Paths III-zh.md" @@ -0,0 +1,88 @@ +# [980. 不同路径 III](https://leetcode-cn.com/problems/unique-paths-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0980.Unique%20Paths%20III/README_EN.md) + +## 题目描述 + + + +

    在二维网格 grid 上,有 4 种类型的方格:

    + +
      +
    • 1 表示起始方格。且只有一个起始方格。
    • +
    • 2 表示结束方格,且只有一个结束方格。
    • +
    • 0 表示我们可以走过的空方格。
    • +
    • -1 表示我们无法跨越的障碍。
    • +
    + +

    返回在四个方向(上、下、左、右)上行走时,从起始方格到结束方格的不同路径的数目

    + +

    每一个无障碍方格都要通过一次,但是一条路径中不能重复通过同一个方格

    + +

     

    + +

    示例 1:

    + +
    输入:[[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
    +输出:2
    +解释:我们有以下两条路径:
    +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
    +2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
    + +

    示例 2:

    + +
    输入:[[1,0,0,0],[0,0,0,0],[0,0,0,2]]
    +输出:4
    +解释:我们有以下四条路径: 
    +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
    +2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
    +3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
    +4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
    + +

    示例 3:

    + +
    输入:[[0,1],[2,0]]
    +输出:0
    +解释:
    +没有一条路能完全穿过每一个空的方格一次。
    +请注意,起始和结束方格可以位于网格中的任意位置。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length * grid[0].length <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0981.leetcode981 Time Based Key-Value Store-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0981.leetcode981 Time Based Key-Value Store-zh.md" new file mode 100644 index 00000000..c752960d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0981.leetcode981 Time Based Key-Value Store-zh.md" @@ -0,0 +1,178 @@ +# [981. 基于时间的键值存储](https://leetcode-cn.com/problems/time-based-key-value-store) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0981.Time%20Based%20Key-Value%20Store/README_EN.md) + +## 题目描述 + + + +

    创建一个基于时间的键值存储类 TimeMap,它支持下面两个操作:

    + +

    1. set(string key, string value, int timestamp)

    + +
      +
    • 存储键 key、值 value,以及给定的时间戳 timestamp
    • +
    + +

    2. get(string key, int timestamp)

    + +
      +
    • 返回先前调用 set(key, value, timestamp_prev) 所存储的值,其中 timestamp_prev <= timestamp
    • +
    • 如果有多个这样的值,则返回对应最大的  timestamp_prev 的那个值。
    • +
    • 如果没有值,则返回空字符串("")。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
    +输出:[null,null,"bar","bar",null,"bar2","bar2"]
    +解释: 
    +TimeMap kv;  
    +kv.set("foo", "bar", 1); // 存储键 "foo" 和值 "bar" 以及时间戳 timestamp = 1  
    +kv.get("foo", 1);  // 输出 "bar"  
    +kv.get("foo", 3); // 输出 "bar" 因为在时间戳 3 和时间戳 2 处没有对应 "foo" 的值,所以唯一的值位于时间戳 1 处(即 "bar")  
    +kv.set("foo", "bar2", 4);  
    +kv.get("foo", 4); // 输出 "bar2"  
    +kv.get("foo", 5); // 输出 "bar2"  
    +
    +
    + +

    示例 2:

    + +
    输入:inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
    +输出:[null,null,null,"","high","high","low","low"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 所有的键/值字符串都是小写的。
    2. +
    3. 所有的键/值字符串长度都在 [1, 100] 范围内。
    4. +
    5. 所有 TimeMap.set 操作中的时间戳 timestamps 都是严格递增的。
    6. +
    7. 1 <= timestamp <= 10^7
    8. +
    9. TimeMap.set 和 TimeMap.get 函数在每个测试用例中将(组合)调用总计 120000 次。
    10. +
    + +## 解法 + + + +嵌套哈希表实现。 + + + +### **Python3** + + + +```python +class TimeMap: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.ktv = collections.defaultdict(list) + + def set(self, key: str, value: str, timestamp: int) -> None: + self.ktv[key].append((timestamp, value)) + + def get(self, key: str, timestamp: int) -> str: + if key not in self.ktv: + return '' + tv = self.ktv[key] + # #查找第一个大于timestamp的 + i = bisect.bisect_right(tv, (timestamp, chr(127))) + return tv[i - 1][1] if i else '' + + + +# Your TimeMap object will be instantiated and called as such: +# obj = TimeMap() +# obj.set(key,value,timestamp) +# param_2 = obj.get(key,timestamp) +``` + +### **Java** + + + +```java +class TimeMap { + private Map> ktv; + + /** Initialize your data structure here. */ + public TimeMap() { + ktv = new HashMap<>(); + } + + public void set(String key, String value, int timestamp) { + TreeMap tv = ktv.getOrDefault(key, new TreeMap<>()); + tv.put(timestamp, value); + ktv.put(key, tv); + } + + public String get(String key, int timestamp) { + if (!ktv.containsKey(key)) { + return ""; + } + TreeMap tv = ktv.get(key); + Integer t = tv.floorKey(timestamp); + return t == null ? "" : tv.get(t); + } +} + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap obj = new TimeMap(); + * obj.set(key,value,timestamp); + * String param_2 = obj.get(key,timestamp); + */ +``` + +### **Go** + +因为 timestamp 是一直增长的,所以可以用二分查找快速找到值 + +```go +type pair struct { + timestamp int + value string +} + +type TimeMap struct { + data map[string][]pair +} + +func Constructor() TimeMap { + return TimeMap{data: make(map[string][]pair)} +} + +func (m *TimeMap) Set(key string, value string, timestamp int) { + m.data[key] = append(m.data[key], pair{timestamp, value}) +} + +func (m *TimeMap) Get(key string, timestamp int) string { + pairs := m.data[key] + // sort.Search return the smallest index i in [0, n) at which f(i) is true + i := sort.Search(len(pairs), func(i int) bool { + return pairs[i].timestamp > timestamp + }) + if i > 0 { + return pairs[i-1].value + } + return "" +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0982.leetcode982 Triples with Bitwise AND Equal To Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0982.leetcode982 Triples with Bitwise AND Equal To Zero-zh.md" new file mode 100644 index 00000000..9ca99203 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0982.leetcode982 Triples with Bitwise AND Equal To Zero-zh.md" @@ -0,0 +1,77 @@ +# [982. 按位与为零的三元组](https://leetcode-cn.com/problems/triples-with-bitwise-and-equal-to-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0982.Triples%20with%20Bitwise%20AND%20Equal%20To%20Zero/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,找出索引为 (i, j, k) 的三元组,使得:

    + +
      +
    • 0 <= i < A.length
    • +
    • 0 <= j < A.length
    • +
    • 0 <= k < A.length
    • +
    • A[i] & A[j] & A[k] == 0,其中 & 表示按位与(AND)操作符。
    • +
    + +

     

    + +

    示例:

    + +
    输入:[2,1,3]
    +输出:12
    +解释:我们可以选出如下 i, j, k 三元组:
    +(i=0, j=0, k=1) : 2 & 2 & 1
    +(i=0, j=1, k=0) : 2 & 1 & 2
    +(i=0, j=1, k=1) : 2 & 1 & 1
    +(i=0, j=1, k=2) : 2 & 1 & 3
    +(i=0, j=2, k=1) : 2 & 3 & 1
    +(i=1, j=0, k=0) : 1 & 2 & 2
    +(i=1, j=0, k=1) : 1 & 2 & 1
    +(i=1, j=0, k=2) : 1 & 2 & 3
    +(i=1, j=1, k=0) : 1 & 1 & 2
    +(i=1, j=2, k=0) : 1 & 3 & 2
    +(i=2, j=0, k=1) : 3 & 2 & 1
    +(i=2, j=1, k=0) : 3 & 1 & 2
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 1000
    2. +
    3. 0 <= A[i] < 2^16
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0983.leetcode983 Minimum Cost For Tickets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0983.leetcode983 Minimum Cost For Tickets-zh.md" new file mode 100644 index 00000000..01b5982b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0983.leetcode983 Minimum Cost For Tickets-zh.md" @@ -0,0 +1,89 @@ +# [983. 最低票价](https://leetcode-cn.com/problems/minimum-cost-for-tickets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0983.Minimum%20Cost%20For%20Tickets/README_EN.md) + +## 题目描述 + + + +

    在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。

    + +

    火车票有三种不同的销售方式:

    + +
      +
    • 一张为期一天的通行证售价为 costs[0] 美元;
    • +
    • 一张为期七天的通行证售价为 costs[1] 美元;
    • +
    • 一张为期三十天的通行证售价为 costs[2] 美元。
    • +
    + +

    通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。

    + +

    返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。

    + +

     

    + +

    示例 1:

    + +
    输入:days = [1,4,6,7,8,20], costs = [2,7,15]
    +输出:11
    +解释: 
    +例如,这里有一种购买通行证的方法,可以让你完成你的旅行计划:
    +在第 1 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 1 天生效。
    +在第 3 天,你花了 costs[1] = $7 买了一张为期 7 天的通行证,它将在第 3, 4, ..., 9 天生效。
    +在第 20 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 20 天生效。
    +你总共花了 $11,并完成了你计划的每一天旅行。
    +
    + +

    示例 2:

    + +
    输入:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
    +输出:17
    +解释:
    +例如,这里有一种购买通行证的方法,可以让你完成你的旅行计划: 
    +在第 1 天,你花了 costs[2] = $15 买了一张为期 30 天的通行证,它将在第 1, 2, ..., 30 天生效。
    +在第 31 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 31 天生效。 
    +你总共花了 $17,并完成了你计划的每一天旅行。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= days.length <= 365
    2. +
    3. 1 <= days[i] <= 365
    4. +
    5. days 按顺序严格递增
    6. +
    7. costs.length == 3
    8. +
    9. 1 <= costs[i] <= 1000
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0984.leetcode984 String Without AAA or BBB-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0984.leetcode984 String Without AAA or BBB-zh.md" new file mode 100644 index 00000000..294a4da6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0984.leetcode984 String Without AAA or BBB-zh.md" @@ -0,0 +1,70 @@ +# [984. 不含 AAA 或 BBB 的字符串](https://leetcode-cn.com/problems/string-without-aaa-or-bbb) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0984.String%20Without%20AAA%20or%20BBB/README_EN.md) + +## 题目描述 + + + +

    给定两个整数 A 和 B,返回任意字符串 S,要求满足:

    + +
      +
    • S 的长度为 A + B,且正好包含 A 个 'a' 字母与 B 个 'b' 字母;
    • +
    • 子串 'aaa' 没有出现在 S 中;
    • +
    • 子串 'bbb' 没有出现在 S 中。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:A = 1, B = 2
    +输出:"abb"
    +解释:"abb", "bab" 和 "bba" 都是正确答案。
    +
    + +

    示例 2:

    + +
    输入:A = 4, B = 1
    +输出:"aabaa"
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= A <= 100
    2. +
    3. 0 <= B <= 100
    4. +
    5. 对于给定的 AB,保证存在满足要求的 S
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0985.leetcode985 Sum of Even Numbers After Queries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0985.leetcode985 Sum of Even Numbers After Queries-zh.md" new file mode 100644 index 00000000..836ca537 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0985.leetcode985 Sum of Even Numbers After Queries-zh.md" @@ -0,0 +1,72 @@ +# [985. 查询后的偶数和](https://leetcode-cn.com/problems/sum-of-even-numbers-after-queries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0985.Sum%20of%20Even%20Numbers%20After%20Queries/README_EN.md) + +## 题目描述 + + + +

    给出一个整数数组 A 和一个查询数组 queries

    + +

    对于第 i 次查询,有 val = queries[i][0], index = queries[i][1],我们会把 val 加到 A[index] 上。然后,第 i 次查询的答案是 A 中偶数值的和。

    + +

    (此处给定的 index = queries[i][1] 是从 0 开始的索引,每次查询都会永久修改数组 A。)

    + +

    返回所有查询的答案。你的答案应当以数组 answer 给出,answer[i] 为第 i 次查询的答案。

    + +

     

    + +

    示例:

    + +
    输入:A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
    +输出:[8,6,2,4]
    +解释:
    +开始时,数组为 [1,2,3,4]。
    +将 1 加到 A[0] 上之后,数组为 [2,2,3,4],偶数值之和为 2 + 2 + 4 = 8。
    +将 -3 加到 A[1] 上之后,数组为 [2,-1,3,4],偶数值之和为 2 + 4 = 6。
    +将 -4 加到 A[0] 上之后,数组为 [-2,-1,3,4],偶数值之和为 -2 + 4 = 2。
    +将 2 加到 A[3] 上之后,数组为 [-2,-1,3,6],偶数值之和为 -2 + 6 = 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. -10000 <= A[i] <= 10000
    4. +
    5. 1 <= queries.length <= 10000
    6. +
    7. -10000 <= queries[i][0] <= 10000
    8. +
    9. 0 <= queries[i][1] < A.length
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0986.leetcode986 Interval List Intersections-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0986.leetcode986 Interval List Intersections-zh.md" new file mode 100644 index 00000000..aa6e8074 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0986.leetcode986 Interval List Intersections-zh.md" @@ -0,0 +1,89 @@ +# [986. 区间列表的交集](https://leetcode-cn.com/problems/interval-list-intersections) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0986.Interval%20List%20Intersections/README_EN.md) + +## 题目描述 + + + +

    给定两个由一些 闭区间 组成的列表,firstListsecondList ,其中 firstList[i] = [starti, endi] 而 secondList[j] = [startj, endj] 。每个区间列表都是成对 不相交 的,并且 已经排序

    + +

    返回这 两个区间列表的交集

    + +

    形式上,闭区间 [a, b](其中 a <= b)表示实数 x 的集合,而 a <= x <= b

    + +

    两个闭区间的 交集 是一组实数,要么为空集,要么为闭区间。例如,[1, 3][2, 4] 的交集为 [2, 3]

    + +

     

    + +

    示例 1:

    + +
    +输入:firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
    +输出:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
    +
    + +

    示例 2:

    + +
    +输入:firstList = [[1,3],[5,9]], secondList = []
    +输出:[]
    +
    + +

    示例 3:

    + +
    +输入:firstList = [], secondList = [[4,8],[10,12]]
    +输出:[]
    +
    + +

    示例 4:

    + +
    +输入:firstList = [[1,7]], secondList = [[3,10]]
    +输出:[[3,7]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= firstList.length, secondList.length <= 1000
    • +
    • firstList.length + secondList.length >= 1
    • +
    • 0 <= starti < endi <= 109
    • +
    • endi < starti+1
    • +
    • 0 <= startj < endj <= 109
    • +
    • endj < startj+1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0987.leetcode987 Vertical Order Traversal of a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0987.leetcode987 Vertical Order Traversal of a Binary Tree-zh.md" new file mode 100644 index 00000000..1f033b46 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0987.leetcode987 Vertical Order Traversal of a Binary Tree-zh.md" @@ -0,0 +1,92 @@ +# [987. 二叉树的垂序遍历](https://leetcode-cn.com/problems/vertical-order-traversal-of-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0987.Vertical%20Order%20Traversal%20of%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你二叉树的根结点 root ,请你设计算法计算二叉树的 垂序遍历 序列。

    + +

    对位于 (row, col) 的每个结点而言,其左右子结点分别位于 (row + 1, col - 1) 和 (row + 1, col + 1) 。树的根结点位于 (0, 0)

    + +

    二叉树的 垂序遍历 从最左边的列开始直到最右边的列结束,按列索引每一列上的所有结点,形成一个按出现位置从上到下排序的有序列表。如果同行同列上有多个结点,则按结点的值从小到大进行排序。

    + +

    返回二叉树的 垂序遍历 序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,9,20,null,null,15,7]
    +输出:[[9],[3,15],[20],[7]]
    +解释:
    +列 -1 :只有结点 9 在此列中。
    +列  0 :只有结点 3 和 15 在此列中,按从上到下顺序。
    +列  1 :只有结点 20 在此列中。
    +列  2 :只有结点 7 在此列中。
    + +

    示例 2:

    + +
    +输入:root = [1,2,3,4,5,6,7]
    +输出:[[4],[2],[1,5,6],[3],[7]]
    +解释:
    +列 -2 :只有结点 4 在此列中。
    +列 -1 :只有结点 2 在此列中。
    +列  0 :结点 1 、5 和 6 都在此列中。
    +          1 在上面,所以它出现在前面。
    +          5 和 6 位置都是 (2, 0) ,所以按值从小到大排序,5 在 6 的前面。
    +列  1 :只有结点 3 在此列中。
    +列  2 :只有结点 7 在此列中。
    +
    + +

    示例 3:

    + +
    +输入:root = [1,2,3,4,6,5,7]
    +输出:[[4],[2],[1,5,6],[3],[7]]
    +解释:
    +这个示例实际上与示例 2 完全相同,只是结点 5 和 6 在树中的位置发生了交换。
    +因为 5 和 6 的位置仍然相同,所以答案保持不变,仍然按值从小到大排序。
    + +

     

    + +

    提示:

    + +
      +
    • 树中结点数目总数在范围 [1, 1000]
    • +
    • 0 <= Node.val <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0988.leetcode988 Smallest String Starting From Leaf-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0988.leetcode988 Smallest String Starting From Leaf-zh.md" new file mode 100644 index 00000000..b1c6cd81 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0988.leetcode988 Smallest String Starting From Leaf-zh.md" @@ -0,0 +1,82 @@ +# [988. 从叶结点开始的最小字符串](https://leetcode-cn.com/problems/smallest-string-starting-from-leaf) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0988.Smallest%20String%20Starting%20From%20Leaf/README_EN.md) + +## 题目描述 + + + +

    给定一颗根结点为 root 的二叉树,树中的每一个结点都有一个从 0 到 25 的值,分别代表字母 'a' 到 'z':值 0 代表 'a',值 1 代表 'b',依此类推。

    + +

    找出按字典序最小的字符串,该字符串从这棵树的一个叶结点开始,到根结点结束。

    + +

    (小贴士:字符串中任何较短的前缀在字典序上都是较小的:例如,在字典序上 "ab" 比 "aba" 要小。叶结点是指没有子结点的结点。)

    + +

     

    + +
      +
    + +

    示例 1:

    + +

    + +
    输入:[0,1,2,3,4,3,4]
    +输出:"dba"
    +
    + +

    示例 2:

    + +

    + +
    输入:[25,1,3,1,3,0,2]
    +输出:"adz"
    +
    + +

    示例 3:

    + +

    + +
    输入:[2,2,1,null,1,0,null,0]
    +输出:"abc"
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 给定树的结点数介于 1 和 8500 之间。
    2. +
    3. 树中的每个结点都有一个介于 0 和 25 之间的值。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0989.leetcode989 Add to Array-Form of Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0989.leetcode989 Add to Array-Form of Integer-zh.md" new file mode 100644 index 00000000..07eac0e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0989.leetcode989 Add to Array-Form of Integer-zh.md" @@ -0,0 +1,113 @@ +# [989. 数组形式的整数加法](https://leetcode-cn.com/problems/add-to-array-form-of-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0989.Add%20to%20Array-Form%20of%20Integer/README_EN.md) + +## 题目描述 + + + +

    对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]

    + +

    给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:A = [1,2,0,0], K = 34
    +输出:[1,2,3,4]
    +解释:1200 + 34 = 1234
    +
    + +

    示例 2:

    + +
    输入:A = [2,7,4], K = 181
    +输出:[4,5,5]
    +解释:274 + 181 = 455
    +
    + +

    示例 3:

    + +
    输入:A = [2,1,5], K = 806
    +输出:[1,0,2,1]
    +解释:215 + 806 = 1021
    +
    + +

    示例 4:

    + +
    输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1
    +输出:[1,0,0,0,0,0,0,0,0,0,0]
    +解释:9999999999 + 1 = 10000000000
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. 0 <= A[i] <= 9
    4. +
    5. 0 <= K <= 10000
    6. +
    7. 如果 A.length > 1,那么 A[0] != 0
    8. +
    + + +## 解法 + + + +数组从尾到头遍历,分别与 `K` 中的每一位相加,进位保存在 `carry` 中,不进位和则添加到结果列表中。最后逆序结果列表即可。 + + + +### **Python3** + + + +```python +class Solution: + def addToArrayForm(self, A: List[int], K: int) -> List[int]: + n = len(A) - 1 + carry, res = 0, [] + while n >= 0 or K != 0 or carry != 0: + carry += (0 if n < 0 else A[n]) + (K % 10) + res.append(carry % 10) + K //= 10 + carry //= 10 + n -= 1 + return res[::-1] +``` + +### **Java** + + + +```java +class Solution { + public List addToArrayForm(int[] A, int K) { + int n = A.length - 1; + List res = new ArrayList<>(); + int carry = 0; + while (n >= 0 || K != 0 || carry != 0) { + carry += (n < 0 ? 0 : A[n]) + (K % 10); + res.add(carry % 10); + K /= 10; + carry /= 10; + --n; + } + Collections.reverse(res); + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0990.leetcode990 Satisfiability of Equality Equations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0990.leetcode990 Satisfiability of Equality Equations-zh.md" new file mode 100644 index 00000000..8b1959a9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0990.leetcode990 Satisfiability of Equality Equations-zh.md" @@ -0,0 +1,91 @@ +# [990. 等式方程的可满足性](https://leetcode-cn.com/problems/satisfiability-of-equality-equations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0990.Satisfiability%20of%20Equality%20Equations/README_EN.md) + +## 题目描述 + + + +

    给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。

    + +

    只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。 

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:["a==b","b!=a"]
    +输出:false
    +解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
    +
    + +

    示例 2:

    + +
    输入:["b==a","a==b"]
    +输出:true
    +解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
    +
    + +

    示例 3:

    + +
    输入:["a==b","b==c","a==c"]
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:["a==b","b!=c","c==a"]
    +输出:false
    +
    + +

    示例 5:

    + +
    输入:["c==c","b==d","x!=z"]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= equations.length <= 500
    2. +
    3. equations[i].length == 4
    4. +
    5. equations[i][0] 和 equations[i][3] 是小写字母
    6. +
    7. equations[i][1] 要么是 '=',要么是 '!'
    8. +
    9. equations[i][2] 是 '='
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0991.leetcode991 Broken Calculator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0991.leetcode991 Broken Calculator-zh.md" new file mode 100644 index 00000000..cdfecea1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0991.leetcode991 Broken Calculator-zh.md" @@ -0,0 +1,88 @@ +# [991. 坏了的计算器](https://leetcode-cn.com/problems/broken-calculator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0991.Broken%20Calculator/README_EN.md) + +## 题目描述 + + + +

    在显示着数字的坏计算器上,我们可以执行以下两种操作:

    + +
      +
    • 双倍(Double):将显示屏上的数字乘 2;
    • +
    • 递减(Decrement):将显示屏上的数字减 1 。
    • +
    + +

    最初,计算器显示数字 X

    + +

    返回显示数字 Y 所需的最小操作数。

    + +

     

    + +

    示例 1:

    + +
    输入:X = 2, Y = 3
    +输出:2
    +解释:先进行双倍运算,然后再进行递减运算 {2 -> 4 -> 3}.
    +
    + +

    示例 2:

    + +
    输入:X = 5, Y = 8
    +输出:2
    +解释:先递减,再双倍 {5 -> 4 -> 8}.
    +
    + +

    示例 3:

    + +
    输入:X = 3, Y = 10
    +输出:3
    +解释:先双倍,然后递减,再双倍 {3 -> 6 -> 5 -> 10}.
    +
    + +

    示例 4:

    + +
    输入:X = 1024, Y = 1
    +输出:1023
    +解释:执行递减运算 1023 次
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= X <= 10^9
    2. +
    3. 1 <= Y <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0992.leetcode992 Subarrays with K Different Integers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0992.leetcode992 Subarrays with K Different Integers-zh.md" new file mode 100644 index 00000000..13b1edcd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0992.leetcode992 Subarrays with K Different Integers-zh.md" @@ -0,0 +1,72 @@ +# [992. K 个不同整数的子数组](https://leetcode-cn.com/problems/subarrays-with-k-different-integers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0992.Subarrays%20with%20K%20Different%20Integers/README_EN.md) + +## 题目描述 + + + +

    给定一个正整数数组 A,如果 A 的某个子数组中不同整数的个数恰好为 K,则称 A 的这个连续、不一定不同的子数组为好子数组

    + +

    (例如,[1,2,3,1,2] 中有 3 个不同的整数:12,以及 3。)

    + +

    返回 A 中好子数组的数目。

    + +

     

    + +

    示例 1:

    + +
    +输入:A = [1,2,1,2,3], K = 2
    +输出:7
    +解释:恰好由 2 个不同整数组成的子数组:[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
    +
    + +

    示例 2:

    + +
    +输入:A = [1,2,1,3,4], K = 3
    +输出:3
    +解释:恰好由 3 个不同整数组成的子数组:[1,2,1,3], [2,1,3], [1,3,4].
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 20000
    2. +
    3. 1 <= A[i] <= A.length
    4. +
    5. 1 <= K <= A.length
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0993.leetcode993 Cousins in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0993.leetcode993 Cousins in Binary Tree-zh.md" new file mode 100644 index 00000000..4e8825dc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0993.leetcode993 Cousins in Binary Tree-zh.md" @@ -0,0 +1,83 @@ +# [993. 二叉树的堂兄弟节点](https://leetcode-cn.com/problems/cousins-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0993.Cousins%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。

    + +

    如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点

    + +

    我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 xy

    + +

    只有与值 xy 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false

    + +

     

    + +

    示例 1:
    +

    + +
    +输入:root = [1,2,3,4], x = 4, y = 3
    +输出:false
    +
    + +

    示例 2:
    +

    + +
    +输入:root = [1,2,3,null,4,null,5], x = 5, y = 4
    +输出:true
    +
    + +

    示例 3:

    + +

    + +
    +输入:root = [1,2,3,null,4], x = 2, y = 3
    +输出:false
    + +

     

    + +

    提示:

    + +
      +
    • 二叉树的节点数介于 2 到 100 之间。
    • +
    • 每个节点的值都是唯一的、范围为 1 到 100 的整数。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0994.leetcode994 Rotting Oranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0994.leetcode994 Rotting Oranges-zh.md" new file mode 100644 index 00000000..6bfad3c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0994.leetcode994 Rotting Oranges-zh.md" @@ -0,0 +1,84 @@ +# [994. 腐烂的橘子](https://leetcode-cn.com/problems/rotting-oranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0994.Rotting%20Oranges/README_EN.md) + +## 题目描述 + + + +

    在给定的网格中,每个单元格可以有以下三个值之一:

    + +
      +
    • 值 0 代表空单元格;
    • +
    • 值 1 代表新鲜橘子;
    • +
    • 值 2 代表腐烂的橘子。
    • +
    + +

    每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。

    + +

    返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[[2,1,1],[1,1,0],[0,1,1]]
    +输出:4
    +
    + +

    示例 2:

    + +
    输入:[[2,1,1],[0,1,1],[1,0,1]]
    +输出:-1
    +解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个正向上。
    +
    + +

    示例 3:

    + +
    输入:[[0,2]]
    +输出:0
    +解释:因为 0 分钟时已经没有新鲜橘子了,所以答案就是 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= grid.length <= 10
    2. +
    3. 1 <= grid[0].length <= 10
    4. +
    5. grid[i][j] 仅为 01 或 2
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0995.leetcode995 Minimum Number of K Consecutive Bit Flips-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0995.leetcode995 Minimum Number of K Consecutive Bit Flips-zh.md" new file mode 100644 index 00000000..b14b7ef0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0995.leetcode995 Minimum Number of K Consecutive Bit Flips-zh.md" @@ -0,0 +1,80 @@ +# [995. K 连续位的最小翻转次数](https://leetcode-cn.com/problems/minimum-number-of-k-consecutive-bit-flips) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0995.Minimum%20Number%20of%20K%20Consecutive%20Bit%20Flips/README_EN.md) + +## 题目描述 + + + +

    在仅包含 01 的数组 A 中,一次 K 位翻转包括选择一个长度为 K 的(连续)子数组,同时将子数组中的每个 0 更改为 1,而每个 1 更改为 0

    + +

    返回所需的 K 位翻转的最小次数,以便数组没有值为 0 的元素。如果不可能,返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:A = [0,1,0], K = 1
    +输出:2
    +解释:先翻转 A[0],然后翻转 A[2]。
    +
    + +

    示例 2:

    + +
    +输入:A = [1,1,0], K = 2
    +输出:-1
    +解释:无论我们怎样翻转大小为 2 的子数组,我们都不能使数组变为 [1,1,1]。
    +
    + +

    示例 3:

    + +
    +输入:A = [0,0,0,1,0,1,1,0], K = 3
    +输出:3
    +解释:
    +翻转 A[0],A[1],A[2]: A变成 [1,1,1,1,0,1,1,0]
    +翻转 A[4],A[5],A[6]: A变成 [1,1,1,1,1,0,0,0]
    +翻转 A[5],A[6],A[7]: A变成 [1,1,1,1,1,1,1,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 30000
    2. +
    3. 1 <= K <= A.length
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0996.leetcode996 Number of Squareful Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0996.leetcode996 Number of Squareful Arrays-zh.md" new file mode 100644 index 00000000..529dcd7c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0996.leetcode996 Number of Squareful Arrays-zh.md" @@ -0,0 +1,67 @@ +# [996. 正方形数组的数目](https://leetcode-cn.com/problems/number-of-squareful-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0996.Number%20of%20Squareful%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给定一个非负整数数组 A,如果该数组每对相邻元素之和是一个完全平方数,则称这一数组为正方形数组。

    + +

    返回 A 的正方形排列的数目。两个排列 A1A2 不同的充要条件是存在某个索引 i,使得 A1[i] != A2[i]。

    + +

     

    + +

    示例 1:

    + +
    输入:[1,17,8]
    +输出:2
    +解释:
    +[1,8,17] 和 [17,8,1] 都是有效的排列。
    +
    + +

    示例 2:

    + +
    输入:[2,2,2]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 12
    2. +
    3. 0 <= A[i] <= 1e9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0997.leetcode997 Find the Town Judge-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0997.leetcode997 Find the Town Judge-zh.md" new file mode 100644 index 00000000..baad47a8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0997.leetcode997 Find the Town Judge-zh.md" @@ -0,0 +1,110 @@ +# [997. 找到小镇的法官](https://leetcode-cn.com/problems/find-the-town-judge) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0997.Find%20the%20Town%20Judge/README_EN.md) + +## 题目描述 + + + +

    在一个小镇里,按从 1N 标记了 N 个人。传言称,这些人中有一个是小镇上的秘密法官。

    + +

    如果小镇的法官真的存在,那么:

    + +
      +
    1. 小镇的法官不相信任何人。
    2. +
    3. 每个人(除了小镇法官外)都信任小镇的法官。
    4. +
    5. 只有一个人同时满足属性 1 和属性 2 。
    6. +
    + +

    给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示标记为 a 的人信任标记为 b 的人。

    + +

    如果小镇存在秘密法官并且可以确定他的身份,请返回该法官的标记。否则,返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:N = 2, trust = [[1,2]]
    +输出:2
    +
    + +

    示例 2:

    + +
    输入:N = 3, trust = [[1,3],[2,3]]
    +输出:3
    +
    + +

    示例 3:

    + +
    输入:N = 3, trust = [[1,3],[2,3],[3,1]]
    +输出:-1
    +
    + +

    示例 4:

    + +
    输入:N = 3, trust = [[1,2],[2,3]]
    +输出:-1
    +
    + +

    示例 5:

    + +
    输入:N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
    +输出:3
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 1000
    2. +
    3. trust.length <= 10000
    4. +
    5. trust[i] 是完全不同的
    6. +
    7. trust[i][0] != trust[i][1]
    8. +
    9. 1 <= trust[i][0], trust[i][1] <= N
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + if n == 1 and len(trust) == 0: + return 1 + dic = {} + values = set() + for i in trust: + values.add(i[0]) + if i[1] in dic: + dic[i[1]].append(i[0]) + else: dic[i[1]] = [i[0]] + + for key, value in dic.items(): + if len(dic[key]) == n-1 and key not in values: + return key + return -1 +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0998.leetcode998 Maximum Binary Tree II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0998.leetcode998 Maximum Binary Tree II-zh.md" new file mode 100644 index 00000000..9f00befc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0998.leetcode998 Maximum Binary Tree II-zh.md" @@ -0,0 +1,100 @@ +# [998. 最大二叉树 II](https://leetcode-cn.com/problems/maximum-binary-tree-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0998.Maximum%20Binary%20Tree%20II/README_EN.md) + +## 题目描述 + + + +

    最大树定义:一个树,其中每个节点的值都大于其子树中的任何其他值。

    + +

    给出最大树的根节点 root

    + +

    就像之前的问题那样,给定的树是从列表 Aroot = Construct(A))递归地使用下述 Construct(A) 例程构造的:

    + +
      +
    • 如果 A 为空,返回 null
    • +
    • 否则,令 A[i] 作为 A 的最大元素。创建一个值为 A[i] 的根节点 root
    • +
    • root 的左子树将被构建为 Construct([A[0], A[1], ..., A[i-1]])
    • +
    • root 的右子树将被构建为 Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
    • +
    • 返回 root
    • +
    + +

    请注意,我们没有直接给定 A,只有一个根节点 root = Construct(A).

    + +

    假设 BA 的副本,并在末尾附加值 val。题目数据保证 B 中的值是不同的。

    + +

    返回 Construct(B)

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [4,1,3,null,null,2], val = 5
    +输出:[5,4,null,1,3,null,null,2]
    +解释:A = [1,4,2,3], B = [1,4,2,3,5]
    +
    + +

    示例 2:
    +

    + +
    +输入:root = [5,2,4,null,1], val = 3
    +输出:[5,2,4,null,1,null,3]
    +解释:A = [2,1,5,4], B = [2,1,5,4,3]
    +
    + +

    示例 3:
    +

    + +
    +输入:root = [5,2,3,null,1], val = 4
    +输出:[5,2,4,null,1,3]
    +解释:A = [2,1,5,3], B = [2,1,5,3,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= B.length <= 100
    • +
    + +

     

    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0999.leetcode999 Available Captures for Rook-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0999.leetcode999 Available Captures for Rook-zh.md" new file mode 100644 index 00000000..3ad20ef2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/0999.leetcode999 Available Captures for Rook-zh.md" @@ -0,0 +1,138 @@ +# [999. 可以被一步捕获的棋子数](https://leetcode-cn.com/problems/available-captures-for-rook) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/0900-0999/0999.Available%20Captures%20for%20Rook/README_EN.md) + +## 题目描述 + + + +

    在一个 8 x 8 的棋盘上,有一个白色的车(Rook),用字符 'R' 表示。棋盘上还可能存在空方块,白色的象(Bishop)以及黑色的卒(pawn),分别用字符 '.''B''p' 表示。不难看出,大写字符表示的是白棋,小写字符表示的是黑棋。

    + +

    车按国际象棋中的规则移动。东,西,南,北四个基本方向任选其一,然后一直向选定的方向移动,直到满足下列四个条件之一:

    + +
      +
    • 棋手选择主动停下来。
    • +
    • 棋子因到达棋盘的边缘而停下。
    • +
    • 棋子移动到某一方格来捕获位于该方格上敌方(黑色)的卒,停在该方格内。
    • +
    • 车不能进入/越过已经放有其他友方棋子(白色的象)的方格,停在友方棋子前。
    • +
    + +

    你现在可以控制车移动一次,请你统计有多少敌方的卒处于你的捕获范围内(即,可以被一步捕获的棋子数)。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
    +输出:3
    +解释:
    +在本例中,车能够捕获所有的卒。
    +
    + +

    示例 2:

    + +

    + +
    输入:[[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
    +输出:0
    +解释:
    +象阻止了车捕获任何卒。
    +
    + +

    示例 3:

    + +

    + +
    输入:[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
    +输出:3
    +解释: 
    +车可以捕获位置 b5,d6 和 f5 的卒。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. board.length == board[i].length == 8
    2. +
    3. board[i][j] 可以是 'R''.''B' 或 'p'
    4. +
    5. 只有一个格子上存在 board[i][j] == 'R'
    6. +
    + + +## 解法 + + + +先找到 R 的位置,之后向“上、下、左、右”四个方向查找,累加结果。 + + + +### **Python3** + + + +```python +class Solution: + def numRookCaptures(self, board: List[List[str]]) -> int: + + def search(board, i, j, direction): + while i >= 0 and i < 8 and j >= 0 and j < 8: + if board[i][j] == 'B': return 0 + if board[i][j] == 'p': return 1 + i += direction[0] + j += direction[1] + return 0 + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + res = 0; + for i in range(8): + for j in range(8): + if board[i][j] == 'R': + for direction in directions: + res += search(board, i, j, direction) + return res +``` + +### **Java** + + + +```java +class Solution { + public int numRookCaptures(char[][] board) { + int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; + int res = 0; + for (int i = 0; i < 8; ++i) { + for (int j = 0; j < 8; ++j) { + if (board[i][j] == 'R') { + for (int[] direction : directions) { + res += search(board, i, j, direction); + } + return res; + } + } + } + return res; + } + + private int search(char[][] board, int i, int j, int[] direction) { + while (i >= 0 && i < 8 && j >= 0 && j < 8) { + if (board[i][j] == 'B') return 0; + if (board[i][j] == 'p') return 1; + i += direction[0]; + j += direction[1]; + } + return 0; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1000.leetcode1000 Minimum Cost to Merge Stones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1000.leetcode1000 Minimum Cost to Merge Stones-zh.md" new file mode 100644 index 00000000..a11c2e05 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1000.leetcode1000 Minimum Cost to Merge Stones-zh.md" @@ -0,0 +1,87 @@ +# [1000. 合并石头的最低成本](https://leetcode-cn.com/problems/minimum-cost-to-merge-stones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1000.Minimum%20Cost%20to%20Merge%20Stones/README_EN.md) + +## 题目描述 + + + +

    N 堆石头排成一排,第 i 堆中有 stones[i] 块石头。

    + +

    每次移动(move)需要将连续的 K 堆石头合并为一堆,而这个移动的成本为这 K 堆石头的总数。

    + +

    找出把所有石头合并成一堆的最低成本。如果不可能,返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:stones = [3,2,4,1], K = 2
    +输出:20
    +解释:
    +从 [3, 2, 4, 1] 开始。
    +合并 [3, 2],成本为 5,剩下 [5, 4, 1]。
    +合并 [4, 1],成本为 5,剩下 [5, 5]。
    +合并 [5, 5],成本为 10,剩下 [10]。
    +总成本 20,这是可能的最小值。
    +
    + +

    示例 2:

    + +
    输入:stones = [3,2,4,1], K = 3
    +输出:-1
    +解释:任何合并操作后,都会剩下 2 堆,我们无法再进行合并。所以这项任务是不可能完成的。.
    +
    + +

    示例 3:

    + +
    输入:stones = [3,5,1,2,6], K = 3
    +输出:25
    +解释:
    +从 [3, 5, 1, 2, 6] 开始。
    +合并 [5, 1, 2],成本为 8,剩下 [3, 8, 6]。
    +合并 [3, 8, 6],成本为 17,剩下 [17]。
    +总成本 25,这是可能的最小值。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= stones.length <= 30
    • +
    • 2 <= K <= 30
    • +
    • 1 <= stones[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1001.leetcode1001 Grid Illumination-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1001.leetcode1001 Grid Illumination-zh.md" new file mode 100644 index 00000000..2ef3569d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1001.leetcode1001 Grid Illumination-zh.md" @@ -0,0 +1,88 @@ +# [1001. 网格照明](https://leetcode-cn.com/problems/grid-illumination) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1001.Grid%20Illumination/README_EN.md) + +## 题目描述 + + + +

    在 N x N 的网格 grid 上,每个单元格都有一盏灯,最初灯都处于 关闭 状态。

    + +

    数组 lamps 表示打开的灯的位置。lamps[i] = [rowi, coli] 表示 打开 位于 grid[rowi][coli] 的第 i 盏灯 。每盏灯都照亮自身单元格以及同一行、同一列和两条对角线上的所有其他单元格。

    + +

    查询数组 queries 中,第 i 次查询 queries[i] = [rowi, coli],如果单元格 [rowi, coli] 是被照亮的,则查询结果为 1 ,否则为 0 。在第 i 次查询之后 [按照查询的顺序] ,关闭 位于单元格 grid[rowi][coli] 上或其相邻 8 个方向上(与单元格 grid[rowi][coli] 共享角或边)的任何灯。

    + +

    返回答案数组 ansanswer[i] 应等于第 i 次查询 queries[i] 的结果,1 表示照亮,0 表示未照亮。

    + +

     

    + +

    示例 1:

    + +
    +输入:N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
    +输出:[1,0]
    +解释:最初所有灯都是关闭的。在执行查询之前,打开位于 [0, 0] 和 [4, 4] 的灯。第 0 次查询检查 grid[1][1] 是否被照亮(蓝色方框)。该单元格被照亮,所以 ans[0] = 1 。然后,关闭红色方框中的所有灯。
    +
    +第 1 次查询检查 grid[1][0] 是否被照亮(蓝色方框)。该单元格没有被照亮,所以 ans[1] = 0 。然后,关闭红色矩形中的所有灯。
    +
    +
    + +

    示例 2:

    + +
    +输入:N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]
    +输出:[1,1]
    +
    + +

    示例 3:

    + +
    +输入:N = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]
    +输出:[1,1,0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 109
    • +
    • 0 <= lamps.length <= 20000
    • +
    • lamps[i].length == 2
    • +
    • 0 <= lamps[i][j] < N
    • +
    • 0 <= queries.length <= 20000
    • +
    • queries[i].length == 2
    • +
    • 0 <= queries[i][j] < N
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1002.leetcode1002 Find Common Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1002.leetcode1002 Find Common Characters-zh.md" new file mode 100644 index 00000000..de6125bc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1002.leetcode1002 Find Common Characters-zh.md" @@ -0,0 +1,105 @@ +# [1002. 查找常用字符](https://leetcode-cn.com/problems/find-common-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1002.Find%20Common%20Characters/README_EN.md) + +## 题目描述 + + + +

    给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

    + +

    你可以按任意顺序返回答案。

    + +

     

    + +

    示例 1:

    + +
    输入:["bella","label","roller"]
    +输出:["e","l","l"]
    +
    + +

    示例 2:

    + +
    输入:["cool","lock","cook"]
    +输出:["c","o"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 100
    2. +
    3. 1 <= A[i].length <= 100
    4. +
    5. A[i][j] 是小写字母
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **Go** + +```go +func commonChars(A []string) []string { + if len(A) == 0 { + return []string{} + } + res := make([]int, 26) + //以第一个字符串为基准,先统计出现次数 + for _, c := range A[0] { + res[c - 'a']++ + } + for i := 1; i < len(A); i++ { + tmp := make([]int, 26) + //统计后续每个字符串的字符出现次数 + for _, c := range A[i] { + tmp[c - 'a']++ + } + //比较,取小 + for j := 0; j < 26; j++ { + res[j] = getMin(res[j], tmp[j]) + } + } + //遍历res,取出字符转换为string数组元素 + result := make([]string,0) + for i := 0; i < len(res); i++ { + if res[i] > 0 { + for j := 0; j < res[i]; j++ { + result = append(result, string('a' + i)) + } + } + } + return result +} + +func getMin(a,b int) int { + if a > b{ + return b + } + return a +} + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1003.leetcode1003 Check If Word Is Valid After Substitutions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1003.leetcode1003 Check If Word Is Valid After Substitutions-zh.md" new file mode 100644 index 00000000..c86e9de9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1003.leetcode1003 Check If Word Is Valid After Substitutions-zh.md" @@ -0,0 +1,91 @@ +# [1003. 检查替换后的词是否有效](https://leetcode-cn.com/problems/check-if-word-is-valid-after-substitutions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1003.Check%20If%20Word%20Is%20Valid%20After%20Substitutions/README_EN.md) + +## 题目描述 + + + +给你一个字符串 s ,请你判断它是否 有效 。 +

    字符串 s 有效 需要满足:假设开始有一个空字符串 t = "" ,你可以执行 任意次 下述操作将 t 转换为 s

    + +
      +
    • 将字符串 "abc" 插入到 t 中的任意位置。形式上,t 变为 tleft + "abc" + tright,其中 t == tleft + tright 。注意,tlefttright 可能为
    • +
    + +

    如果字符串 s 有效,则返回 true;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aabcbc"
    +输出:true
    +解释:
    +"" -> "abc" -> "aabcbc"
    +因此,"aabcbc" 有效。
    + +

    示例 2:

    + +
    +输入:s = "abcabcababcc"
    +输出:true
    +解释:
    +"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
    +因此,"abcabcababcc" 有效。
    + +

    示例 3:

    + +
    +输入:s = "abccba"
    +输出:false
    +解释:执行操作无法得到 "abccba" 。
    + +

    示例 4:

    + +
    +输入:s = "cababc"
    +输出:false
    +解释:执行操作无法得到 "cababc" 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 2 * 104
    • +
    • s 由字母 'a''b''c' 组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1004.leetcode1004 Max Consecutive Ones III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1004.leetcode1004 Max Consecutive Ones III-zh.md" new file mode 100644 index 00000000..ff6dc9b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1004.leetcode1004 Max Consecutive Ones III-zh.md" @@ -0,0 +1,71 @@ +# [1004. 最大连续1的个数 III](https://leetcode-cn.com/problems/max-consecutive-ones-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1004.Max%20Consecutive%20Ones%20III/README_EN.md) + +## 题目描述 + + + +

    给定一个由若干 01 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。

    + +

    返回仅包含 1 的最长(连续)子数组的长度。

    + +

     

    + +

    示例 1:

    + +
    输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
    +输出:6
    +解释: 
    +[1,1,1,0,0,1,1,1,1,1,1]
    +粗体数字从 0 翻转到 1,最长的子数组长度为 6。
    + +

    示例 2:

    + +
    输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
    +输出:10
    +解释:
    +[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
    +粗体数字从 0 翻转到 1,最长的子数组长度为 10。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 20000
    2. +
    3. 0 <= K <= A.length
    4. +
    5. A[i] 为 0 或 1 
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1005.leetcode1005 Maximize Sum Of Array After K Negations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1005.leetcode1005 Maximize Sum Of Array After K Negations-zh.md" new file mode 100644 index 00000000..eb4d710f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1005.leetcode1005 Maximize Sum Of Array After K Negations-zh.md" @@ -0,0 +1,76 @@ +# [1005. K 次取反后最大化的数组和](https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1005.Maximize%20Sum%20Of%20Array%20After%20K%20Negations/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次。(我们可以多次选择同一个索引 i。)

    + +

    以这种方式修改数组后,返回数组可能的最大和。

    + +

     

    + +

    示例 1:

    + +
    输入:A = [4,2,3], K = 1
    +输出:5
    +解释:选择索引 (1,) ,然后 A 变为 [4,-2,3]。
    +
    + +

    示例 2:

    + +
    输入:A = [3,-1,0,2], K = 3
    +输出:6
    +解释:选择索引 (1, 2, 2) ,然后 A 变为 [3,1,0,2]。
    +
    + +

    示例 3:

    + +
    输入:A = [2,-3,-1,5,-4], K = 2
    +输出:13
    +解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 10000
    2. +
    3. 1 <= K <= 10000
    4. +
    5. -100 <= A[i] <= 100
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1006.leetcode1006 Clumsy Factorial-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1006.leetcode1006 Clumsy Factorial-zh.md" new file mode 100644 index 00000000..c6ad21a8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1006.leetcode1006 Clumsy Factorial-zh.md" @@ -0,0 +1,113 @@ +# [1006. 笨阶乘](https://leetcode-cn.com/problems/clumsy-factorial) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1006.Clumsy%20Factorial/README_EN.md) + +## 题目描述 + + + +

    通常,正整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

    + +

    相反,我们设计了一个笨阶乘 clumsy:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:乘法(*),除法(/),加法(+)和减法(-)。

    + +

    例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。然而,这些运算仍然使用通常的算术运算顺序:我们在任何加、减步骤之前执行所有的乘法和除法步骤,并且按从左到右处理乘法和除法步骤。

    + +

    另外,我们使用的除法是地板除法(floor division),所以 10 * 9 / 8 等于 11。这保证结果是一个整数。

    + +

    实现上面定义的笨函数:给定一个整数 N,它返回 N 的笨阶乘。

    + +

     

    + +

    示例 1:

    + +
    输入:4
    +输出:7
    +解释:7 = 4 * 3 / 2 + 1
    +
    + +

    示例 2:

    + +
    输入:10
    +输出:12
    +解释:12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10000
    2. +
    3. -2^31 <= answer <= 2^31 - 1  (答案保证符合 32 位整数。)
    4. +
    + + +## 解法 + + + +遇到 `*`、`/` 时计算后入栈,遇到 `+`、`-` 时直接入栈。最后累加栈中的元素即可。 + + + +### **Python3** + + + +```python +class Solution: + def clumsy(self, N: int) -> int: + op = 0 + s = [N] + for i in range(N - 1, 0, -1): + if op == 0: + s.append(s.pop() * i) + elif op == 1: + s.append(int(s.pop() / i)) + elif op == 2: + s.append(i) + else: + s.append(-i) + op = (op + 1) % 4 + return sum(s) +``` + +### **Java** + + + +```java +class Solution { + public int clumsy(int N) { + Deque s = new ArrayDeque<>(); + s.offerLast(N); + int op = 0; + for (int i = N - 1; i > 0; --i) { + if (op == 0) { + s.offerLast(s.pollLast() * i); + } else if (op == 1) { + s.offerLast(s.pollLast() / i); + } else if (op == 2) { + s.offerLast(i); + } else { + s.offerLast(-i); + } + op = (op + 1) % 4; + } + int res = 0; + while (!s.isEmpty()) { + res += s.pollLast(); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1007.leetcode1007 Minimum Domino Rotations For Equal Row-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1007.leetcode1007 Minimum Domino Rotations For Equal Row-zh.md" new file mode 100644 index 00000000..6ba20b61 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1007.leetcode1007 Minimum Domino Rotations For Equal Row-zh.md" @@ -0,0 +1,77 @@ +# [1007. 行相等的最少多米诺旋转](https://leetcode-cn.com/problems/minimum-domino-rotations-for-equal-row) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1007.Minimum%20Domino%20Rotations%20For%20Equal%20Row/README_EN.md) + +## 题目描述 + + + +

    在一排多米诺骨牌中,A[i]B[i] 分别代表第 i 个多米诺骨牌的上半部分和下半部分。(一个多米诺是两个从 1 到 6 的数字同列平铺形成的 —— 该平铺的每一半上都有一个数字。)

    + +

    我们可以旋转第 i 张多米诺,使得 A[i] 和 B[i] 的值交换。

    + +

    返回能使 A 中所有值或者 B 中所有值都相同的最小旋转次数。

    + +

    如果无法做到,返回 -1.

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
    +输出:2
    +解释:
    +图一表示:在我们旋转之前, A 和 B 给出的多米诺牌。
    +如果我们旋转第二个和第四个多米诺骨牌,我们可以使上面一行中的每个值都等于 2,如图二所示。
    +
    + +

    示例 2:

    + +
    输入:A = [3,5,1,2,3], B = [3,6,3,3,4]
    +输出:-1
    +解释:
    +在这种情况下,不可能旋转多米诺牌使一行的值相等。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A[i], B[i] <= 6
    2. +
    3. 2 <= A.length == B.length <= 20000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1008.leetcode1008 Construct Binary Search Tree from Preorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1008.leetcode1008 Construct Binary Search Tree from Preorder Traversal-zh.md" new file mode 100644 index 00000000..33827a12 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1008.leetcode1008 Construct Binary Search Tree from Preorder Traversal-zh.md" @@ -0,0 +1,64 @@ +# [1008. 前序遍历构造二叉搜索树](https://leetcode-cn.com/problems/construct-binary-search-tree-from-preorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1008.Construct%20Binary%20Search%20Tree%20from%20Preorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    返回与给定前序遍历 preorder 相匹配的二叉搜索树(binary search tree)的根结点。

    + +

    (回想一下,二叉搜索树是二叉树的一种,其每个节点都满足以下规则,对于 node.left 的任何后代,值总 < node.val,而 node.right 的任何后代,值总 > node.val。此外,前序遍历首先显示节点 node 的值,然后遍历 node.left,接着遍历 node.right。)

    + +

    题目保证,对于给定的测试用例,总能找到满足要求的二叉搜索树。

    + +

     

    + +

    示例:

    + +
    输入:[8,5,1,7,10,12]
    +输出:[8,5,10,1,7,null,12]
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= preorder.length <= 100
    • +
    • 1 <= preorder[i] <= 10^8
    • +
    • preorder 中的值互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1009.leetcode1009 Complement of Base 10 Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1009.leetcode1009 Complement of Base 10 Integer-zh.md" new file mode 100644 index 00000000..e22d4c46 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1009.leetcode1009 Complement of Base 10 Integer-zh.md" @@ -0,0 +1,80 @@ +# [1009. 十进制整数的反码](https://leetcode-cn.com/problems/complement-of-base-10-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1009.Complement%20of%20Base%2010%20Integer/README_EN.md) + +## 题目描述 + + + +

    每个非负整数 N 都有其二进制表示。例如, 5 可以被表示为二进制 "101"11 可以用二进制 "1011" 表示,依此类推。注意,除 N = 0 外,任何二进制表示中都不含前导零。

    + +

    二进制的反码表示是将每个 1 改为 0 且每个 0 变为 1。例如,二进制数 "101" 的二进制反码为 "010"

    + +

    给你一个十进制数 N,请你返回其二进制表示的反码所对应的十进制整数。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:5
    +输出:2
    +解释:5 的二进制表示为 "101",其二进制反码为 "010",也就是十进制中的 2 。
    +
    + +

    示例 2:

    + +
    输入:7
    +输出:0
    +解释:7 的二进制表示为 "111",其二进制反码为 "000",也就是十进制中的 0 。
    +
    + +

    示例 3:

    + +
    输入:10
    +输出:5
    +解释:10 的二进制表示为 "1010",其二进制反码为 "0101",也就是十进制中的 5 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= N < 10^9
    2. +
    3. 本题与 476:https://leetcode-cn.com/problems/number-complement/ 相同
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1010.leetcode1010 Pairs of Songs With Total Durations Divisible by 60-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1010.leetcode1010 Pairs of Songs With Total Durations Divisible by 60-zh.md" new file mode 100644 index 00000000..6a604895 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1010.leetcode1010 Pairs of Songs With Total Durations Divisible by 60-zh.md" @@ -0,0 +1,71 @@ +# [1010. 总持续时间可被 60 整除的歌曲](https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1010.Pairs%20of%20Songs%20With%20Total%20Durations%20Divisible%20by%2060/README_EN.md) + +## 题目描述 + + + +

    在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。

    + +

    返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字 ij 满足  i < j 且有 (time[i] + time[j]) % 60 == 0

    + +

     

    + +

    示例 1:

    + +
    输入:[30,20,150,100,40]
    +输出:3
    +解释:这三对的总持续时间可被 60 整数:
    +(time[0] = 30, time[2] = 150): 总持续时间 180
    +(time[1] = 20, time[3] = 100): 总持续时间 120
    +(time[1] = 20, time[4] = 40): 总持续时间 60
    +
    + +

    示例 2:

    + +
    输入:[60,60,60]
    +输出:3
    +解释:所有三对的总持续时间都是 120,可以被 60 整数。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= time.length <= 60000
    2. +
    3. 1 <= time[i] <= 500
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1011.leetcode1011 Capacity To Ship Packages Within D Days-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1011.leetcode1011 Capacity To Ship Packages Within D Days-zh.md" new file mode 100644 index 00000000..7d138b4a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1011.leetcode1011 Capacity To Ship Packages Within D Days-zh.md" @@ -0,0 +1,93 @@ +# [1011. 在 D 天内送达包裹的能力](https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1011.Capacity%20To%20Ship%20Packages%20Within%20D%20Days/README_EN.md) + +## 题目描述 + + + +

    传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。

    + +

    传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。

    + +

    返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。

    + +

     

    + +

    示例 1:

    + +
    输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
    +输出:15
    +解释:
    +船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
    +第 1 天:1, 2, 3, 4, 5
    +第 2 天:6, 7
    +第 3 天:8
    +第 4 天:9
    +第 5 天:10
    +
    +请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。 
    +
    + +

    示例 2:

    + +
    输入:weights = [3,2,2,4,1,4], D = 3
    +输出:6
    +解释:
    +船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示:
    +第 1 天:3, 2
    +第 2 天:2, 4
    +第 3 天:1, 4
    +
    + +

    示例 3:

    + +
    输入:weights = [1,2,3,1,1], D = 4
    +输出:3
    +解释:
    +第 1 天:1
    +第 2 天:2
    +第 3 天:3
    +第 4 天:1, 1
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= D <= weights.length <= 50000
    2. +
    3. 1 <= weights[i] <= 500
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1012.leetcode1012 Numbers With Repeated Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1012.leetcode1012 Numbers With Repeated Digits-zh.md" new file mode 100644 index 00000000..f374425f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1012.leetcode1012 Numbers With Repeated Digits-zh.md" @@ -0,0 +1,70 @@ +# [1012. 至少有 1 位重复的数字](https://leetcode-cn.com/problems/numbers-with-repeated-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1012.Numbers%20With%20Repeated%20Digits/README_EN.md) + +## 题目描述 + + + +

    给定正整数 N,返回小于等于 N 且具有至少 1 位重复数字的正整数的个数。

    + +

     

    + +

    示例 1:

    + +
    输入:20
    +输出:1
    +解释:具有至少 1 位重复数字的正数(<= 20)只有 11 。
    +
    + +

    示例 2:

    + +
    输入:100
    +输出:10
    +解释:具有至少 1 位重复数字的正数(<= 100)有 11,22,33,44,55,66,77,88,99 和 100 。
    +
    + +

    示例 3:

    + +
    输入:1000
    +输出:262
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10^9
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1013.leetcode1013 Partition Array Into Three Parts With Equal Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1013.leetcode1013 Partition Array Into Three Parts With Equal Sum-zh.md" new file mode 100644 index 00000000..e332fbb2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1013.leetcode1013 Partition Array Into Three Parts With Equal Sum-zh.md" @@ -0,0 +1,73 @@ +# [1013. 将数组分成和相等的三个部分](https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1013.Partition%20Array%20Into%20Three%20Parts%20With%20Equal%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 A,只有可以将其划分为三个和相等的非空部分时才返回 true,否则返回 false

    + +

    形式上,如果可以找出索引 i+1 < j 且满足 A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1] 就可以将数组三等分。

    + +

     

    + +

    示例 1:

    + +
    输入:[0,2,1,-6,6,-7,9,1,2,0,1]
    +输出:true
    +解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
    +
    + +

    示例 2:

    + +
    输入:[0,2,1,-6,6,7,9,-1,2,0,1]
    +输出:false
    +
    + +

    示例 3:

    + +
    输入:[3,3,6,5,-2,2,5,1,-9,4]
    +输出:true
    +解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= A.length <= 50000
    2. +
    3. -10^4 <= A[i] <= 10^4
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1014.leetcode1014 Best Sightseeing Pair-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1014.leetcode1014 Best Sightseeing Pair-zh.md" new file mode 100644 index 00000000..87698f9d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1014.leetcode1014 Best Sightseeing Pair-zh.md" @@ -0,0 +1,121 @@ +# [1014. 最佳观光组合](https://leetcode-cn.com/problems/best-sightseeing-pair) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1014.Best%20Sightseeing%20Pair/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 values,其中 values[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的 距离 为 j - i

    + +

    一对景点(i < j)组成的观光组合的得分为 values[i] + values[j] + i - j ,也就是景点的评分之和 减去 它们两者之间的距离。

    + +

    返回一对观光景点能取得的最高分。

    + +

     

    + +

    示例 1:

    + +
    +输入:values = [8,1,5,2,6]
    +输出:11
    +解释:i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
    +
    + +

    示例 2:

    + +
    +输入:values = [1,2]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= values.length <= 5 * 104
    • +
    • 1 <= values[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maxScoreSightseeingPair(self, values: List[int]) -> int: + res, mx = 0, values[0] + for i in range(1, len(values)): + res = max(res, values[i] - i + mx) + mx = max(mx, values[i] + i) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxScoreSightseeingPair(int[] values) { + int res = 0, mx = values[0]; + for (int i = 1; i < values.length; ++i) { + res = Math.max(res, values[i] - i + mx); + mx = Math.max(mx, values[i] + i); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxScoreSightseeingPair(vector& values) { + int res = 0, mx = values[0]; + for (int i = 1; i < values.size(); ++i) { + res = max(res, values[i] - i + mx); + mx = max(mx, values[i] + i); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxScoreSightseeingPair(values []int) int { + res, mx := 0, values[0] + for i := 1; i < len(values); i++ { + res = max(res, values[i]-i+mx) + mx = max(mx, values[i]+i) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1015.leetcode1015 Smallest Integer Divisible by K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1015.leetcode1015 Smallest Integer Divisible by K-zh.md" new file mode 100644 index 00000000..f7f2d3ab --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1015.leetcode1015 Smallest Integer Divisible by K-zh.md" @@ -0,0 +1,70 @@ +# [1015. 可被 K 整除的最小整数](https://leetcode-cn.com/problems/smallest-integer-divisible-by-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1015.Smallest%20Integer%20Divisible%20by%20K/README_EN.md) + +## 题目描述 + + + +

    给定正整数 K,你需要找出可以被 K 整除的、仅包含数字 1 的最小正整数 N。

    + +

    返回 N 的长度。如果不存在这样的 N,就返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:1
    +输出:1
    +解释:最小的答案是 N = 1,其长度为 1。
    + +

    示例 2:

    + +
    输入:2
    +输出:-1
    +解释:不存在可被 2 整除的正整数 N 。
    + +

    示例 3:

    + +
    输入:3
    +输出:3
    +解释:最小的答案是 N = 111,其长度为 3。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= K <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1016.leetcode1016 Binary String With Substrings Representing 1 To N-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1016.leetcode1016 Binary String With Substrings Representing 1 To N-zh.md" new file mode 100644 index 00000000..2b2a4e34 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1016.leetcode1016 Binary String With Substrings Representing 1 To N-zh.md" @@ -0,0 +1,63 @@ +# [1016. 子串能表示从 1 到 N 数字的二进制串](https://leetcode-cn.com/problems/binary-string-with-substrings-representing-1-to-n) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1016.Binary%20String%20With%20Substrings%20Representing%201%20To%20N/README_EN.md) + +## 题目描述 + + + +

    给定一个二进制字符串 S(一个仅由若干 '0' 和 '1' 构成的字符串)和一个正整数 N,如果对于从 1N 的每个整数 X,其二进制表示都是 S 的子串,就返回 true,否则返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:S = "0110", N = 3
    +输出:true
    +
    + +

    示例 2:

    + +
    输入:S = "0110", N = 4
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 1000
    2. +
    3. 1 <= N <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1017.leetcode1017 Convert to Base -2-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1017.leetcode1017 Convert to Base -2-zh.md" new file mode 100644 index 00000000..372985fe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1017.leetcode1017 Convert to Base -2-zh.md" @@ -0,0 +1,73 @@ +# [1017. 负二进制转换](https://leetcode-cn.com/problems/convert-to-base-2) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1017.Convert%20to%20Base%20-2/README_EN.md) + +## 题目描述 + + + +

    给出数字 N,返回由若干 "0" 和 "1"组成的字符串,该字符串为 N 的负二进制(base -2表示。

    + +

    除非字符串就是 "0",否则返回的字符串中不能含有前导零。

    + +

     

    + +

    示例 1:

    + +
    输入:2
    +输出:"110"
    +解释:(-2) ^ 2 + (-2) ^ 1 = 2
    +
    + +

    示例 2:

    + +
    输入:3
    +输出:"111"
    +解释:(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
    +
    + +

    示例 3:

    + +
    输入:4
    +输出:"100"
    +解释:(-2) ^ 2 = 4
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= N <= 10^9
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1018.leetcode1018 Binary Prefix Divisible By 5-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1018.leetcode1018 Binary Prefix Divisible By 5-zh.md" new file mode 100644 index 00000000..a2736652 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1018.leetcode1018 Binary Prefix Divisible By 5-zh.md" @@ -0,0 +1,79 @@ +# [1018. 可被 5 整除的二进制前缀](https://leetcode-cn.com/problems/binary-prefix-divisible-by-5) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1018.Binary%20Prefix%20Divisible%20By%205/README_EN.md) + +## 题目描述 + + + +

    给定由若干 0 和 1 组成的数组 A。我们定义 N_i:从 A[0] 到 A[i] 的第 i 个子数组被解释为一个二进制数(从最高有效位到最低有效位)。

    + +

    返回布尔值列表 answer,只有当 N_i 可以被 5 整除时,答案 answer[i] 为 true,否则为 false

    + +

     

    + +

    示例 1:

    + +
    输入:[0,1,1]
    +输出:[true,false,false]
    +解释:
    +输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为真。
    +
    + +

    示例 2:

    + +
    输入:[1,1,1]
    +输出:[false,false,false]
    +
    + +

    示例 3:

    + +
    输入:[0,1,1,1,1,1]
    +输出:[true,false,false,false,true,false]
    +
    + +

    示例 4:

    + +
    输入:[1,1,1,0,1]
    +输出:[false,false,false,false,false]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 30000
    2. +
    3. A[i] 为 0 或 1
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1019.leetcode1019 Next Greater Node In Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1019.leetcode1019 Next Greater Node In Linked List-zh.md" new file mode 100644 index 00000000..8ba1692f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1019.leetcode1019 Next Greater Node In Linked List-zh.md" @@ -0,0 +1,153 @@ +# [1019. 链表中的下一个更大节点](https://leetcode-cn.com/problems/next-greater-node-in-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1019.Next%20Greater%20Node%20In%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给出一个以头节点 head 作为第一个节点的链表。链表中的节点分别编号为:node_1, node_2, node_3, ...

    + +

    每个节点都可能有下一个更大值(next larger value):对于 node_i,如果其 next_larger(node_i) 是 node_j.val,那么就有 j > i 且  node_j.val > node_i.val,而 j 是可能的选项中最小的那个。如果不存在这样的 j,那么下一个更大值为 0 。

    + +

    返回整数答案数组 answer,其中 answer[i] = next_larger(node_{i+1}) 。

    + +

    注意:在下面的示例中,诸如 [2,1,5] 这样的输入(不是输出)是链表的序列化表示,其头节点的值为 2,第二个节点值为 1,第三个节点值为 5 。

    + +

     

    + +

    示例 1:

    + +
    输入:[2,1,5]
    +输出:[5,5,0]
    +
    + +

    示例 2:

    + +
    输入:[2,7,4,3,5]
    +输出:[7,0,5,5,0]
    +
    + +

    示例 3:

    + +
    输入:[1,7,5,1,9,2,5,1]
    +输出:[7,9,9,9,0,5,0,0]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 对于链表中的每个节点,1 <= node.val <= 10^9
    2. +
    3. 给定列表的长度在 [0, 10000] 范围内
    4. +
    + +## 解法 + + + +“单调栈”实现。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def nextLargerNodes(self, head: ListNode) -> List[int]: + nums = [] + while head: + nums.append(head.val) + head = head.next + s = [] + larger = [0] * len(nums) + for i, num in enumerate(nums): + while s and nums[s[-1]] < num: + larger[s.pop()] = num + s.append(i) + return larger +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public int[] nextLargerNodes(ListNode head) { + List nums = new ArrayList<>(); + while (head != null) { + nums.add(head.val); + head = head.next; + } + Deque s = new ArrayDeque<>(); + int[] larger = new int[nums.size()]; + for (int i = 0; i < nums.size(); ++i) { + while (!s.isEmpty() && nums.get(s.peek()) < nums.get(i)) { + larger[s.pop()] = nums.get(i); + } + s.push(i); + } + return larger; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var nextLargerNodes = function(head) { + let nums = []; + while (head != null) { + nums.push(head.val); + head = head.next; + } + const n = nums.length; + let larger = new Array(n).fill(0); + let stack = []; + for (let i = 0; i < n; i++) { + let num = nums[i]; + while (stack.length > 0 && nums[stack[stack.length - 1]] < num) { + larger[stack.pop()] = num; + } + stack.push(i); + } + return larger; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1020.leetcode1020 Number of Enclaves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1020.leetcode1020 Number of Enclaves-zh.md" new file mode 100644 index 00000000..c42c1795 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1020.leetcode1020 Number of Enclaves-zh.md" @@ -0,0 +1,71 @@ +# [1020. 飞地的数量](https://leetcode-cn.com/problems/number-of-enclaves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1020.Number%20of%20Enclaves/README_EN.md) + +## 题目描述 + + + +

    给出一个二维数组 A,每个单元格为 0(代表海)或 1(代表陆地)。

    + +

    移动是指在陆地上从一个地方走到另一个地方(朝四个方向之一)或离开网格的边界。

    + +

    返回网格中无法在任意次数的移动中离开网格边界的陆地单元格的数量。

    + +

     

    + +

    示例 1:

    + +
    输入:[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
    +输出:3
    +解释: 
    +有三个 1 被 0 包围。一个 1 没有被包围,因为它在边界上。
    + +

    示例 2:

    + +
    输入:[[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
    +输出:0
    +解释:
    +所有 1 都在边界上或可以到达边界。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 500
    2. +
    3. 1 <= A[i].length <= 500
    4. +
    5. 0 <= A[i][j] <= 1
    6. +
    7. 所有行的大小都相同
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1021.leetcode1021 Remove Outermost Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1021.leetcode1021 Remove Outermost Parentheses-zh.md" new file mode 100644 index 00000000..25c1da84 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1021.leetcode1021 Remove Outermost Parentheses-zh.md" @@ -0,0 +1,84 @@ +# [1021. 删除最外层的括号](https://leetcode-cn.com/problems/remove-outermost-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1021.Remove%20Outermost%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    有效括号字符串为空 ("")"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"""()""(())()" 和 "(()(()))" 都是有效的括号字符串。

    + +

    如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。

    + +

    给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。

    + +

    对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。

    + +

     

    + +

    示例 1:

    + +
    输入:"(()())(())"
    +输出:"()()()"
    +解释:
    +输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
    +删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
    + +

    示例 2:

    + +
    输入:"(()())(())(()(()))"
    +输出:"()()()()(())"
    +解释:
    +输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
    +删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
    +
    + +

    示例 3:

    + +
    输入:"()()"
    +输出:""
    +解释:
    +输入字符串为 "()()",原语化分解得到 "()" + "()",
    +删除每个部分中的最外层括号后得到 "" + "" = ""。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. S.length <= 10000
    2. +
    3. S[i] 为 "(" 或 ")"
    4. +
    5. S 是一个有效括号字符串
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1022.leetcode1022 Sum of Root To Leaf Binary Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1022.leetcode1022 Sum of Root To Leaf Binary Numbers-zh.md" new file mode 100644 index 00000000..e056cef0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1022.leetcode1022 Sum of Root To Leaf Binary Numbers-zh.md" @@ -0,0 +1,84 @@ +# [1022. 从根到叶的二进制数之和](https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1022.Sum%20of%20Root%20To%20Leaf%20Binary%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。

    + +

    对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

    + +

    返回这些数字之和。题目数据保证答案是一个 32 位 整数。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [1,0,1,0,1,0,1]
    +输出:22
    +解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
    +
    + +

    示例 2:

    + +
    +输入:root = [0]
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:root = [1]
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:root = [1,1]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的结点数介于 11000 之间。
    • +
    • Node.val01
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1023.leetcode1023 Camelcase Matching-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1023.leetcode1023 Camelcase Matching-zh.md" new file mode 100644 index 00000000..8b79afdf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1023.leetcode1023 Camelcase Matching-zh.md" @@ -0,0 +1,81 @@ +# [1023. 驼峰式匹配](https://leetcode-cn.com/problems/camelcase-matching) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1023.Camelcase%20Matching/README_EN.md) + +## 题目描述 + + + +

    如果我们可以将小写字母插入模式串 pattern 得到待查询项 query,那么待查询项与给定模式串匹配。(我们可以在任何位置插入每个字符,也可以插入 0 个字符。)

    + +

    给定待查询列表 queries,和模式串 pattern,返回由布尔值组成的答案列表 answer。只有在待查项 queries[i] 与模式串 pattern 匹配时, answer[i] 才为 true,否则为 false

    + +

     

    + +

    示例 1:

    + +
    输入:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
    +输出:[true,false,true,true,false]
    +示例:
    +"FooBar" 可以这样生成:"F" + "oo" + "B" + "ar"。
    +"FootBall" 可以这样生成:"F" + "oot" + "B" + "all".
    +"FrameBuffer" 可以这样生成:"F" + "rame" + "B" + "uffer".
    + +

    示例 2:

    + +
    输入:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
    +输出:[true,false,true,false,false]
    +解释:
    +"FooBar" 可以这样生成:"Fo" + "o" + "Ba" + "r".
    +"FootBall" 可以这样生成:"Fo" + "ot" + "Ba" + "ll".
    +
    + +

    示例 3:

    + +
    输出:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
    +输入:[false,true,false,false,false]
    +解释: 
    +"FooBarTest" 可以这样生成:"Fo" + "o" + "Ba" + "r" + "T" + "est".
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= queries.length <= 100
    2. +
    3. 1 <= queries[i].length <= 100
    4. +
    5. 1 <= pattern.length <= 100
    6. +
    7. 所有字符串都仅由大写和小写英文字母组成。
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1024.leetcode1024 Video Stitching-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1024.leetcode1024 Video Stitching-zh.md" new file mode 100644 index 00000000..eeb4b1cc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1024.leetcode1024 Video Stitching-zh.md" @@ -0,0 +1,95 @@ +# [1024. 视频拼接](https://leetcode-cn.com/problems/video-stitching) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1024.Video%20Stitching/README_EN.md) + +## 题目描述 + + + +

    你将会获得一系列视频片段,这些片段来自于一项持续时长为 T 秒的体育赛事。这些片段可能有所重叠,也可能长度不一。

    + +

    视频片段 clips[i] 都用区间进行表示:开始于 clips[i][0] 并于 clips[i][1] 结束。我们甚至可以对这些片段自由地再剪辑,例如片段 [0, 7] 可以剪切成 [0, 1] + [1, 3] + [3, 7] 三部分。

    + +

    我们需要将这些片段进行再剪辑,并将剪辑后的内容拼接成覆盖整个运动过程的片段([0, T])。返回所需片段的最小数目,如果无法完成该任务,则返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10
    +输出:3
    +解释:
    +我们选中 [0,2], [8,10], [1,9] 这三个片段。
    +然后,按下面的方案重制比赛片段:
    +将 [1,9] 再剪辑为 [1,2] + [2,8] + [8,9] 。
    +现在我们手上有 [0,2] + [2,8] + [8,10],而这些涵盖了整场比赛 [0, 10]。
    +
    + +

    示例 2:

    + +
    +输入:clips = [[0,1],[1,2]], T = 5
    +输出:-1
    +解释:
    +我们无法只用 [0,1] 和 [1,2] 覆盖 [0,5] 的整个过程。
    +
    + +

    示例 3:

    + +
    +输入:clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], T = 9
    +输出:3
    +解释: 
    +我们选取片段 [0,4], [4,7] 和 [6,9] 。
    +
    + +

    示例 4:

    + +
    +输入:clips = [[0,4],[2,8]], T = 5
    +输出:2
    +解释:
    +注意,你可能录制超过比赛结束时间的视频。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= clips.length <= 100
    • +
    • 0 <= clips[i][0] <= clips[i][1] <= 100
    • +
    • 0 <= T <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1025.leetcode1025 Divisor Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1025.leetcode1025 Divisor Game-zh.md" new file mode 100644 index 00000000..55a296a8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1025.leetcode1025 Divisor Game-zh.md" @@ -0,0 +1,78 @@ +# [1025. 除数博弈](https://leetcode-cn.com/problems/divisor-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1025.Divisor%20Game/README_EN.md) + +## 题目描述 + + + +

    爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。

    + +

    最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:

    + +
      +
    • 选出任一 x,满足 0 < x < N 且 N % x == 0 。
    • +
    • N - x 替换黑板上的数字 N
    • +
    + +

    如果玩家无法执行这些操作,就会输掉游戏。

    + +

    只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 False。假设两个玩家都以最佳状态参与游戏。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    输入:2
    +输出:true
    +解释:爱丽丝选择 1,鲍勃无法进行操作。
    +
    + +

    示例 2:

    + +
    输入:3
    +输出:false
    +解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 1000
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1026.leetcode1026 Maximum Difference Between Node and Ancestor-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1026.leetcode1026 Maximum Difference Between Node and Ancestor-zh.md" new file mode 100644 index 00000000..988c27c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1026.leetcode1026 Maximum Difference Between Node and Ancestor-zh.md" @@ -0,0 +1,76 @@ +# [1026. 节点与其祖先之间的最大差值](https://leetcode-cn.com/problems/maximum-difference-between-node-and-ancestor) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1026.Maximum%20Difference%20Between%20Node%20and%20Ancestor/README_EN.md) + +## 题目描述 + + + +

    给定二叉树的根节点 root,找出存在于 不同 节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。

    + +

    (如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [8,3,10,1,6,null,14,null,null,4,7,13]
    +输出:7
    +解释: 
    +我们有大量的节点与其祖先的差值,其中一些如下:
    +|8 - 3| = 5
    +|3 - 7| = 4
    +|8 - 1| = 7
    +|10 - 13| = 3
    +在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。
    +
    + +

    示例 2:

    + +
    +输入:root = [1,null,2,null,0,3]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数在 2 到 5000 之间。
    • +
    • 0 <= Node.val <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1027.leetcode1027 Longest Arithmetic Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1027.leetcode1027 Longest Arithmetic Subsequence-zh.md" new file mode 100644 index 00000000..80aecbcd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1027.leetcode1027 Longest Arithmetic Subsequence-zh.md" @@ -0,0 +1,77 @@ +# [1027. 最长等差数列](https://leetcode-cn.com/problems/longest-arithmetic-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1027.Longest%20Arithmetic%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,返回 A 中最长等差子序列的长度

    + +

    回想一下,A 的子序列是列表 A[i_1], A[i_2], ..., A[i_k] 其中 0 <= i_1 < i_2 < ... < i_k <= A.length - 1。并且如果 B[i+1] - B[i]0 <= i < B.length - 1) 的值都相同,那么序列 B 是等差的。

    + +

     

    + +

    示例 1:

    + +
    输入:[3,6,9,12]
    +输出:4
    +解释: 
    +整个数组是公差为 3 的等差数列。
    +
    + +

    示例 2:

    + +
    输入:[9,4,7,2,10]
    +输出:3
    +解释:
    +最长的等差子序列是 [4,7,10]。
    +
    + +

    示例 3:

    + +
    输入:[20,1,15,3,10,5,8]
    +输出:4
    +解释:
    +最长的等差子序列是 [20,15,10,5]。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= A.length <= 2000
    2. +
    3. 0 <= A[i] <= 10000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1028.leetcode1028 Recover a Tree From Preorder Traversal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1028.leetcode1028 Recover a Tree From Preorder Traversal-zh.md" new file mode 100644 index 00000000..a2862f6a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1028.leetcode1028 Recover a Tree From Preorder Traversal-zh.md" @@ -0,0 +1,81 @@ +# [1028. 从先序遍历还原二叉树](https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1028.Recover%20a%20Tree%20From%20Preorder%20Traversal/README_EN.md) + +## 题目描述 + + + +

    我们从二叉树的根节点 root 开始进行深度优先搜索。

    + +

    在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度),然后输出该节点的值。(如果节点的深度为 D,则其直接子节点的深度为 D + 1。根节点的深度为 0)。

    + +

    如果节点只有一个子节点,那么保证该子节点为左子节点。

    + +

    给出遍历输出 S,还原树并返回其根节点 root

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:"1-2--3--4-5--6--7"
    +输出:[1,2,5,3,4,6,7]
    +
    + +

    示例 2:

    + +

    + +
    输入:"1-2--3---4-5--6---7"
    +输出:[1,2,5,3,null,6,null,4,null,7]
    +
    + +

    示例 3:

    + +

    + +
    输入:"1-401--349---90--88"
    +输出:[1,401,null,349,88,90]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 原始树中的节点数介于 11000 之间。
    • +
    • 每个节点的值介于 110 ^ 9 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1029.leetcode1029 Two City Scheduling-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1029.leetcode1029 Two City Scheduling-zh.md" new file mode 100644 index 00000000..c49b039e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1029.leetcode1029 Two City Scheduling-zh.md" @@ -0,0 +1,67 @@ +# [1029. 两地调度](https://leetcode-cn.com/problems/two-city-scheduling) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1029.Two%20City%20Scheduling/README_EN.md) + +## 题目描述 + + + +

    公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]

    + +

    返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达

    + +

     

    + +

    示例:

    + +
    输入:[[10,20],[30,200],[400,50],[30,20]]
    +输出:110
    +解释:
    +第一个人去 A 市,费用为 10。
    +第二个人去 A 市,费用为 30。
    +第三个人去 B 市,费用为 50。
    +第四个人去 B 市,费用为 20。
    +
    +最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= costs.length <= 100
    2. +
    3. costs.length 为偶数
    4. +
    5. 1 <= costs[i][0], costs[i][1] <= 1000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1030.leetcode1030 Matrix Cells in Distance Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1030.leetcode1030 Matrix Cells in Distance Order-zh.md" new file mode 100644 index 00000000..690b1a63 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1030.leetcode1030 Matrix Cells in Distance Order-zh.md" @@ -0,0 +1,80 @@ +# [1030. 距离顺序排列矩阵单元格](https://leetcode-cn.com/problems/matrix-cells-in-distance-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1030.Matrix%20Cells%20in%20Distance%20Order/README_EN.md) + +## 题目描述 + + + +

    给出 RC 列的矩阵,其中的单元格的整数坐标为 (r, c),满足 0 <= r < R0 <= c < C

    + +

    另外,我们在该矩阵中给出了一个坐标为 (r0, c0) 的单元格。

    + +

    返回矩阵中的所有单元格的坐标,并按到 (r0, c0) 的距离从最小到最大的顺序排,其中,两单元格(r1, c1)(r2, c2) 之间的距离是曼哈顿距离,|r1 - r2| + |c1 - c2|。(你可以按任何满足此条件的顺序返回答案。)

    + +

     

    + +

    示例 1:

    + +
    输入:R = 1, C = 2, r0 = 0, c0 = 0
    +输出:[[0,0],[0,1]]
    +解释:从 (r0, c0) 到其他单元格的距离为:[0,1]
    +
    + +

    示例 2:

    + +
    输入:R = 2, C = 2, r0 = 0, c0 = 1
    +输出:[[0,1],[0,0],[1,1],[1,0]]
    +解释:从 (r0, c0) 到其他单元格的距离为:[0,1,1,2]
    +[[0,1],[1,1],[0,0],[1,0]] 也会被视作正确答案。
    +
    + +

    示例 3:

    + +
    输入:R = 2, C = 3, r0 = 1, c0 = 2
    +输出:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
    +解释:从 (r0, c0) 到其他单元格的距离为:[0,1,1,2,2,3]
    +其他满足题目要求的答案也会被视为正确,例如 [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= R <= 100
    2. +
    3. 1 <= C <= 100
    4. +
    5. 0 <= r0 < R
    6. +
    7. 0 <= c0 < C
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1031.leetcode1031 Maximum Sum of Two Non-Overlapping Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1031.leetcode1031 Maximum Sum of Two Non-Overlapping Subarrays-zh.md" new file mode 100644 index 00000000..9033b3d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1031.leetcode1031 Maximum Sum of Two Non-Overlapping Subarrays-zh.md" @@ -0,0 +1,82 @@ +# [1031. 两个非重叠子数组的最大和](https://leetcode-cn.com/problems/maximum-sum-of-two-non-overlapping-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1031.Maximum%20Sum%20of%20Two%20Non-Overlapping%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    给出非负整数数组 A ,返回两个非重叠(连续)子数组中元素的最大和,子数组的长度分别为 LM。(这里需要澄清的是,长为 L 的子数组可以出现在长为 M 的子数组之前或之后。)

    + +

    从形式上看,返回最大的 V,而 V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) 并满足下列条件之一:

    + +

     

    + +
      +
    • 0 <= i < i + L - 1 < j < j + M - 1 < A.length,
    • +
    • 0 <= j < j + M - 1 < i < i + L - 1 < A.length.
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
    +输出:20
    +解释:子数组的一种选择中,[9] 长度为 1,[6,5] 长度为 2。
    +
    + +

    示例 2:

    + +
    输入:A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
    +输出:29
    +解释:子数组的一种选择中,[3,8,1] 长度为 3,[8,9] 长度为 2。
    +
    + +

    示例 3:

    + +
    输入:A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
    +输出:31
    +解释:子数组的一种选择中,[5,6,0,9] 长度为 4,[0,3,8] 长度为 3。
    + +

     

    + +

    提示:

    + +
      +
    1. L >= 1
    2. +
    3. M >= 1
    4. +
    5. L + M <= A.length <= 1000
    6. +
    7. 0 <= A[i] <= 1000
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1032.leetcode1032 Stream of Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1032.leetcode1032 Stream of Characters-zh.md" new file mode 100644 index 00000000..1f5d69ce --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1032.leetcode1032 Stream of Characters-zh.md" @@ -0,0 +1,75 @@ +# [1032. 字符流](https://leetcode-cn.com/problems/stream-of-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1032.Stream%20of%20Characters/README_EN.md) + +## 题目描述 + + + +

    按下述要求实现 StreamChecker 类:

    + +
      +
    • StreamChecker(words):构造函数,用给定的字词初始化数据结构。
    • +
    • query(letter):如果存在某些 k >= 1,可以用查询的最后 k个字符(按从旧到新顺序,包括刚刚查询的字母)拼写出给定字词表中的某一字词时,返回 true。否则,返回 false
    • +
    + +

     

    + +

    示例:

    + +
    StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // 初始化字典
    +streamChecker.query('a');          // 返回 false
    +streamChecker.query('b');          // 返回 false
    +streamChecker.query('c');          // 返回 false
    +streamChecker.query('d');          // 返回 true,因为 'cd' 在字词表中
    +streamChecker.query('e');          // 返回 false
    +streamChecker.query('f');          // 返回 true,因为 'f' 在字词表中
    +streamChecker.query('g');          // 返回 false
    +streamChecker.query('h');          // 返回 false
    +streamChecker.query('i');          // 返回 false
    +streamChecker.query('j');          // 返回 false
    +streamChecker.query('k');          // 返回 false
    +streamChecker.query('l');          // 返回 true,因为 'kl' 在字词表中。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 2000
    • +
    • 1 <= words[i].length <= 2000
    • +
    • 字词只包含小写英文字母。
    • +
    • 待查项只包含小写英文字母。
    • +
    • 待查项最多 40000 个。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1033.leetcode1033 Moving Stones Until Consecutive-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1033.leetcode1033 Moving Stones Until Consecutive-zh.md" new file mode 100644 index 00000000..5a646002 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1033.leetcode1033 Moving Stones Until Consecutive-zh.md" @@ -0,0 +1,75 @@ +# [1033. 移动石子直到连续](https://leetcode-cn.com/problems/moving-stones-until-consecutive) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1033.Moving%20Stones%20Until%20Consecutive/README_EN.md) + +## 题目描述 + + + +

    三枚石子放置在数轴上,位置分别为 abc

    + +

    每一回合,你可以从两端之一拿起一枚石子(位置最大或最小),并将其放入两端之间的任一空闲位置。形式上,假设这三枚石子当前分别位于位置 x, y, zx < y < z。那么就可以从位置 x 或者是位置 z 拿起一枚石子,并将该石子移动到某一整数位置 k 处,其中 x < k < zk != y

    + +

    当你无法进行任何移动时,即,这些石子的位置连续时,游戏结束。

    + +

    要使游戏结束,你可以执行的最小和最大移动次数分别是多少? 以长度为 2 的数组形式返回答案:answer = [minimum_moves, maximum_moves]

    + +

     

    + +

    示例 1:

    + +
    +输入:a = 1, b = 2, c = 5
    +输出:[1, 2]
    +解释:将石子从 5 移动到 4 再移动到 3,或者我们可以直接将石子移动到 3。
    +
    + +

    示例 2:

    + +
    +输入:a = 4, b = 3, c = 2
    +输出:[0, 0]
    +解释:我们无法进行任何移动。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= a <= 100
    2. +
    3. 1 <= b <= 100
    4. +
    5. 1 <= c <= 100
    6. +
    7. a != b, b != c, c != a
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1034.leetcode1034 Coloring A Border-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1034.leetcode1034 Coloring A Border-zh.md" new file mode 100644 index 00000000..2a8d5c5e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1034.leetcode1034 Coloring A Border-zh.md" @@ -0,0 +1,80 @@ +# [1034. 边框着色](https://leetcode-cn.com/problems/coloring-a-border) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1034.Coloring%20A%20Border/README_EN.md) + +## 题目描述 + + + +

    给出一个二维整数网格 grid,网格中的每个值表示该位置处的网格块的颜色。

    + +

    只有当两个网格块的颜色相同,而且在四个方向中任意一个方向上相邻时,它们属于同一连通分量

    + +

    连通分量的边界是指连通分量中的所有与不在分量中的正方形相邻(四个方向上)的所有正方形,或者在网格的边界上(第一行/列或最后一行/列)的所有正方形。

    + +

    给出位于 (r0, c0) 的网格块和颜色 color,使用指定颜色 color 为所给网格块的连通分量的边界进行着色,并返回最终的网格 grid

    + +

     

    + +

    示例 1:

    + +
    输入:grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
    +输出:[[3, 3], [3, 2]]
    +
    + +

    示例 2:

    + +
    输入:grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
    +输出:[[1, 3, 3], [2, 3, 3]]
    +
    + +

    示例 3:

    + +
    输入:grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
    +输出:[[2, 2, 2], [2, 1, 2], [2, 2, 2]]
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= grid.length <= 50
    2. +
    3. 1 <= grid[0].length <= 50
    4. +
    5. 1 <= grid[i][j] <= 1000
    6. +
    7. 0 <= r0 < grid.length
    8. +
    9. 0 <= c0 < grid[0].length
    10. +
    11. 1 <= color <= 1000
    12. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1035.leetcode1035 Uncrossed Lines-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1035.leetcode1035 Uncrossed Lines-zh.md" new file mode 100644 index 00000000..84f781dc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1035.leetcode1035 Uncrossed Lines-zh.md" @@ -0,0 +1,129 @@ +# [1035. 不相交的线](https://leetcode-cn.com/problems/uncrossed-lines) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1035.Uncrossed%20Lines/README_EN.md) + +## 题目描述 + + + +

    我们在两条独立的水平线上按给定的顺序写下 A 和 B 中的整数。

    + +

    现在,我们可以绘制一些连接两个数字 A[i] 和 B[j] 的直线,只要 A[i] == B[j],且我们绘制的直线不与任何其他连线(非水平线)相交。

    + +

    以这种方法绘制线条,并返回我们可以绘制的最大连线数。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:A = [1,4,2], B = [1,2,4]
    +输出:2
    +解释:
    +我们可以画出两条不交叉的线,如上图所示。
    +我们无法画出第三条不相交的直线,因为从 A[1]=4 到 B[2]=4 的直线将与从 A[2]=2 到 B[1]=2 的直线相交。
    + +

    示例 2:

    + +
    输入:A = [2,5,1,2,5], B = [10,5,2,1,5,2]
    +输出:3
    +
    + +

    示例 3:

    + +
    输入:A = [1,3,7,1,7,5], B = [1,9,2,5,1]
    +输出:2
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 500
    2. +
    3. 1 <= B.length <= 500
    4. +
    5. 1 <= A[i], B[i] <= 2000
    6. +
    + +

     

    + + +## 解法 + + + +最长公共子序列问题 + + + +### **Python3** + + + +```python +class Solution: + def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: + m, n = len(nums1), len(nums2) + dp = [[0] * (n + 1) for i in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + if nums1[i - 1] == nums2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + 1 + else: + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + return dp[m][n] +``` + +### **Java** + + + +```java +class Solution { + public int maxUncrossedLines(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; + int[][] dp = new int[m + 1][n + 1]; + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (nums1[i - 1] == nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[m][n]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxUncrossedLines(vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + vector> dp(m + 1, vector(n + 1)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (nums1[i - 1] == nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[m][n]; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1036.leetcode1036 Escape a Large Maze-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1036.leetcode1036 Escape a Large Maze-zh.md" new file mode 100644 index 00000000..97596937 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1036.leetcode1036 Escape a Large Maze-zh.md" @@ -0,0 +1,81 @@ +# [1036. 逃离大迷宫](https://leetcode-cn.com/problems/escape-a-large-maze) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1036.Escape%20a%20Large%20Maze/README_EN.md) + +## 题目描述 + + + +

    在一个 106 x 106 的网格中,每个网格上方格的坐标为 (x, y)

    + +

    现在从源方格 source = [sx, sy] 开始出发,意图赶往目标方格 target = [tx, ty] 。数组 blocked 是封锁的方格列表,其中每个 blocked[i] = [xi, yi] 表示坐标为 (xi, yi) 的方格是禁止通行的。

    + +

    每次移动,都可以走到网格中在四个方向上相邻的方格,只要该方格 在给出的封锁列表 blocked 上。同时,不允许走出网格。

    + +

    只有在可以通过一系列的移动从源方格 source 到达目标方格 target 时才返回 true。否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
    +输出:false
    +解释:
    +从源方格无法到达目标方格,因为我们无法在网格中移动。
    +无法向北或者向东移动是因为方格禁止通行。
    +无法向南或者向西移动是因为不能走出网格。
    + +

    示例 2:

    + +
    +输入:blocked = [], source = [0,0], target = [999999,999999]
    +输出:true
    +解释:
    +因为没有方格被封锁,所以一定可以到达目标方格。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= blocked.length <= 200
    • +
    • blocked[i].length == 2
    • +
    • 0 <= xi, yi < 106
    • +
    • source.length == target.length == 2
    • +
    • 0 <= sx, sy, tx, ty < 106
    • +
    • source != target
    • +
    • 题目数据保证 sourcetarget 不在封锁列表内
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1037.leetcode1037 Valid Boomerang-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1037.leetcode1037 Valid Boomerang-zh.md" new file mode 100644 index 00000000..e67d35dc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1037.leetcode1037 Valid Boomerang-zh.md" @@ -0,0 +1,65 @@ +# [1037. 有效的回旋镖](https://leetcode-cn.com/problems/valid-boomerang) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1037.Valid%20Boomerang/README_EN.md) + +## 题目描述 + + + +

    回旋镖定义为一组三个点,这些点各不相同且在一条直线上。

    + +

    给出平面上三个点组成的列表,判断这些点是否可以构成回旋镖。

    + +

     

    + +

    示例 1:

    + +
    输入:[[1,1],[2,3],[3,2]]
    +输出:true
    +
    + +

    示例 2:

    + +
    输入:[[1,1],[2,2],[3,3]]
    +输出:false
    + +

     

    + +

    提示:

    + +
      +
    1. points.length == 3
    2. +
    3. points[i].length == 2
    4. +
    5. 0 <= points[i][j] <= 100
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1038.leetcode1038 Binary Search Tree to Greater Sum Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1038.leetcode1038 Binary Search Tree to Greater Sum Tree-zh.md" new file mode 100644 index 00000000..a0bd8d16 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1038.leetcode1038 Binary Search Tree to Greater Sum Tree-zh.md" @@ -0,0 +1,89 @@ +# [1038. 把二叉搜索树转换为累加树](https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1038.Binary%20Search%20Tree%20to%20Greater%20Sum%20Tree/README_EN.md) + +## 题目描述 + + + +

    给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

    + +

    提醒一下,二叉搜索树满足下列约束条件:

    + +
      +
    • 节点的左子树仅包含键 小于 节点键的节点。
    • +
    • 节点的右子树仅包含键 大于 节点键的节点。
    • +
    • 左右子树也必须是二叉搜索树。
    • +
    + +

    注意:该题目与 538: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/  相同

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
    +输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
    +
    + +

    示例 2:

    + +
    输入:root = [0,null,1]
    +输出:[1,null,1]
    +
    + +

    示例 3:

    + +
    输入:root = [1,0,2]
    +输出:[3,3,2]
    +
    + +

    示例 4:

    + +
    输入:root = [3,2,4,1]
    +输出:[7,9,4,10]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数介于 1100 之间。
    • +
    • 每个节点的值介于 0 和 100 之间。
    • +
    • 树中的所有值 互不相同
    • +
    • 给定的树为二叉搜索树。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1039.leetcode1039 Minimum Score Triangulation of Polygon-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1039.leetcode1039 Minimum Score Triangulation of Polygon-zh.md" new file mode 100644 index 00000000..d8133d34 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1039.leetcode1039 Minimum Score Triangulation of Polygon-zh.md" @@ -0,0 +1,80 @@ +# [1039. 多边形三角剖分的最低得分](https://leetcode-cn.com/problems/minimum-score-triangulation-of-polygon) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1039.Minimum%20Score%20Triangulation%20of%20Polygon/README_EN.md) + +## 题目描述 + + + +

    给定 N,想象一个凸 N 边多边形,其顶点按顺时针顺序依次标记为 A[0], A[i], ..., A[N-1]

    + +

    假设您将多边形剖分为 N-2 个三角形。对于每个三角形,该三角形的值是顶点标记的乘积,三角剖分的分数是进行三角剖分后所有 N-2 个三角形的值之和。

    + +

    返回多边形进行三角剖分后可以得到的最低分。

    + +
      +
    + +

    示例 1:

    + +
    输入:[1,2,3]
    +输出:6
    +解释:多边形已经三角化,唯一三角形的分数为 6。
    +
    + +

    示例 2:

    + +

    + +
    输入:[3,7,4,5]
    +输出:144
    +解释:有两种三角剖分,可能得分分别为:3*7*5 + 4*5*7 = 245,或 3*4*5 + 3*4*7 = 144。最低分数为 144。
    +
    + +

    示例 3:

    + +
    输入:[1,3,1,4,1,5]
    +输出:13
    +解释:最低分数三角剖分的得分情况为 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= A.length <= 50
    2. +
    3. 1 <= A[i] <= 100
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1040.leetcode1040 Moving Stones Until Consecutive II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1040.leetcode1040 Moving Stones Until Consecutive II-zh.md" new file mode 100644 index 00000000..cdd1a337 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1040.leetcode1040 Moving Stones Until Consecutive II-zh.md" @@ -0,0 +1,89 @@ +# [1040. 移动石子直到连续 II](https://leetcode-cn.com/problems/moving-stones-until-consecutive-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1040.Moving%20Stones%20Until%20Consecutive%20II/README_EN.md) + +## 题目描述 + + + +

    在一个长度 无限 的数轴上,第 i 颗石子的位置为 stones[i]。如果一颗石子的位置最小/最大,那么该石子被称作 端点石子

    + +

    每个回合,你可以将一颗端点石子拿起并移动到一个未占用的位置,使得该石子不再是一颗端点石子。

    + +

    值得注意的是,如果石子像 stones = [1,2,5] 这样,你将 无法 移动位于位置 5 的端点石子,因为无论将它移动到任何位置(例如 0 或 3),该石子都仍然会是端点石子。

    + +

    当你无法进行任何移动时,即,这些石子的位置连续时,游戏结束。

    + +

    要使游戏结束,你可以执行的最小和最大移动次数分别是多少? 以长度为 2 的数组形式返回答案:answer = [minimum_moves, maximum_moves]

    + +

     

    + +

    示例 1:

    + +
    +输入:[7,4,9]
    +输出:[1,2]
    +解释:
    +我们可以移动一次,4 -> 8,游戏结束。
    +或者,我们可以移动两次 9 -> 5,4 -> 6,游戏结束。
    +
    + +

    示例 2:

    + +
    +输入:[6,5,4,3,10]
    +输出:[2,3]
    +解释:
    +我们可以移动 3 -> 8,接着是 10 -> 7,游戏结束。
    +或者,我们可以移动 3 -> 7, 4 -> 8, 5 -> 9,游戏结束。
    +注意,我们无法进行 10 -> 2 这样的移动来结束游戏,因为这是不合要求的移动。
    +
    + +

    示例 3:

    + +
    +输入:[100,101,104,102,103]
    +输出:[0,0]
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= stones.length <= 10^4
    • +
    • 1 <= stones[i] <= 10^9
    • +
    • stones[i] 的值各不相同。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1041.leetcode1041 Robot Bounded In Circle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1041.leetcode1041 Robot Bounded In Circle-zh.md" new file mode 100644 index 00000000..c6f8b9a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1041.leetcode1041 Robot Bounded In Circle-zh.md" @@ -0,0 +1,85 @@ +# [1041. 困于环中的机器人](https://leetcode-cn.com/problems/robot-bounded-in-circle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1041.Robot%20Bounded%20In%20Circle/README_EN.md) + +## 题目描述 + + + +

    在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:

    + +
      +
    • "G":直走 1 个单位
    • +
    • "L":左转 90 度
    • +
    • "R":右转 90 度
    • +
    + +

    机器人按顺序执行指令 instructions,并一直重复它们。

    + +

    只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:"GGLLGG"
    +输出:true
    +解释:
    +机器人从 (0,0) 移动到 (0,2),转 180 度,然后回到 (0,0)。
    +重复这些指令,机器人将保持在以原点为中心,2 为半径的环中进行移动。
    +
    + +

    示例 2:

    + +
    输入:"GG"
    +输出:false
    +解释:
    +机器人无限向北移动。
    +
    + +

    示例 3:

    + +
    输入:"GL"
    +输出:true
    +解释:
    +机器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 进行移动。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= instructions.length <= 100
    2. +
    3. instructions[i] 在 {'G', 'L', 'R'} 中
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1042.leetcode1042 Flower Planting With No Adjacent-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1042.leetcode1042 Flower Planting With No Adjacent-zh.md" new file mode 100644 index 00000000..47968a19 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1042.leetcode1042 Flower Planting With No Adjacent-zh.md" @@ -0,0 +1,87 @@ +# [1042. 不邻接植花](https://leetcode-cn.com/problems/flower-planting-with-no-adjacent) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1042.Flower%20Planting%20With%20No%20Adjacent/README_EN.md) + +## 题目描述 + + + +

    n 个花园,按从 1 到 n 标记。另有数组 paths ,其中 paths[i] = [xi, yi] 描述了花园 xi 到花园 yi 的双向路径。在每个花园中,你打算种下四种花之一。

    + +

    另外,所有花园 最多 有 3 条路径可以进入或离开.

    + +

    你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同。

    + +

    以数组形式返回 任一 可行的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类。花的种类用  1、2、3、4 表示。保证存在答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, paths = [[1,2],[2,3],[3,1]]
    +输出:[1,2,3]
    +解释:
    +花园 1 和 2 花的种类不同。
    +花园 2 和 3 花的种类不同。
    +花园 3 和 1 花的种类不同。
    +因此,[1,2,3] 是一个满足题意的答案。其他满足题意的答案有 [1,2,4]、[1,4,2] 和 [3,2,1]
    +
    + +

    示例 2:

    + +
    +输入:n = 4, paths = [[1,2],[3,4]]
    +输出:[1,2,1,2]
    +
    + +

    示例 3:

    + +
    +输入:n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
    +输出:[1,2,3,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 104
    • +
    • 0 <= paths.length <= 2 * 104
    • +
    • paths[i].length == 2
    • +
    • 1 <= xi, yi <= n
    • +
    • xi != yi
    • +
    • 每个花园 最多 有 3 条路径可以进入或离开
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1043.leetcode1043 Partition Array for Maximum Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1043.leetcode1043 Partition Array for Maximum Sum-zh.md" new file mode 100644 index 00000000..ec254ee4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1043.leetcode1043 Partition Array for Maximum Sum-zh.md" @@ -0,0 +1,81 @@ +# [1043. 分隔数组以得到最大和](https://leetcode-cn.com/problems/partition-array-for-maximum-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1043.Partition%20Array%20for%20Maximum%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr,请你将该数组分隔为长度最多为 k 的一些(连续)子数组。分隔完成后,每个子数组的中的所有值都会变为该子数组中的最大值。

    + +

    返回将数组分隔变换后能够得到的元素最大和。

    + +

     

    + +

    注意,原数组和分隔后的数组对应顺序应当一致,也就是说,你只能选择分隔数组的位置而不能调整数组中的顺序。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [1,15,7,9,2,5,10], k = 3
    +输出:84
    +解释:
    +因为 k=3 可以分隔成 [1,15,7] [9] [2,5,10],结果为 [15,15,15,9,10,10,10],和为 84,是该数组所有分隔变换后元素总和最大的。
    +若是分隔成 [1] [15,7,9] [2,5,10],结果就是 [1, 15, 15, 15, 10, 10, 10] 但这种分隔方式的元素总和(76)小于上一种。 
    + +

    示例 2:

    + +
    +输入:arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
    +输出:83
    +
    + +

    示例 3:

    + +
    +输入:arr = [1], k = 1
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 500
    • +
    • 0 <= arr[i] <= 109
    • +
    • 1 <= k <= arr.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1044.leetcode1044 Longest Duplicate Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1044.leetcode1044 Longest Duplicate Substring-zh.md" new file mode 100644 index 00000000..308386e2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1044.leetcode1044 Longest Duplicate Substring-zh.md" @@ -0,0 +1,65 @@ +# [1044. 最长重复子串](https://leetcode-cn.com/problems/longest-duplicate-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1044.Longest%20Duplicate%20Substring/README_EN.md) + +## 题目描述 + + + +

    给出一个字符串 S,考虑其所有重复子串S 的连续子串,出现两次或多次,可能会有重叠)。

    + +

    返回任何具有最长可能长度的重复子串。(如果 S 不含重复子串,那么答案为 ""。)

    + +

     

    + +

    示例 1:

    + +
    输入:"banana"
    +输出:"ana"
    +
    + +

    示例 2:

    + +
    输入:"abcd"
    +输出:""
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 2 <= S.length <= 10^5
    2. +
    3. S 由小写英文字母组成。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1045.leetcode1045 Customers Who Bought All Products-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1045.leetcode1045 Customers Who Bought All Products-zh.md" new file mode 100644 index 00000000..a6a0b097 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1045.leetcode1045 Customers Who Bought All Products-zh.md" @@ -0,0 +1,91 @@ +# [1045. 买下所有产品的客户](https://leetcode-cn.com/problems/customers-who-bought-all-products) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1045.Customers%20Who%20Bought%20All%20Products/README_EN.md) + +## 题目描述 + + + +

    Customer 表:

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| customer_id | int     |
    +| product_key | int     |
    ++-------------+---------+
    +product_key 是 Customer 表的外键。
    +
    + +

    Product 表:

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_key | int     |
    ++-------------+---------+
    +product_key 是这张表的主键。
    +
    + +

     

    + +

    写一条 SQL 查询语句,从 Customer 表中查询购买了 Product 表中所有产品的客户的 id。

    + +

    示例:

    + +
    Customer 表:
    ++-------------+-------------+
    +| customer_id | product_key |
    ++-------------+-------------+
    +| 1           | 5           |
    +| 2           | 6           |
    +| 3           | 5           |
    +| 3           | 6           |
    +| 1           | 6           |
    ++-------------+-------------+
    +
    +Product 表:
    ++-------------+
    +| product_key |
    ++-------------+
    +| 5           |
    +| 6           |
    ++-------------+
    +
    +Result 表:
    ++-------------+
    +| customer_id |
    ++-------------+
    +| 1           |
    +| 3           |
    ++-------------+
    +购买了所有产品(5 和 6)的客户的 id 是 1 和 3 。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + customer_id +FROM + Customer +GROUP BY + customer_id +HAVING + COUNT(DISTINCT(product_key)) = ( + SELECT + COUNT(1) + FROM + Product + ); +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1046.leetcode1046 Last Stone Weight-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1046.leetcode1046 Last Stone Weight-zh.md" new file mode 100644 index 00000000..9ceec976 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1046.leetcode1046 Last Stone Weight-zh.md" @@ -0,0 +1,71 @@ +# [1046. 最后一块石头的重量](https://leetcode-cn.com/problems/last-stone-weight) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1046.Last%20Stone%20Weight/README_EN.md) + +## 题目描述 + + + +

    有一堆石头,每块石头的重量都是正整数。

    + +

    每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

    + +
      +
    • 如果 x == y,那么两块石头都会被完全粉碎;
    • +
    • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x
    • +
    + +

    最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0

    + +

     

    + +

    示例:

    + +
    +输入:[2,7,4,1,8,1]
    +输出:1
    +解释:
    +先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1],
    +再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1],
    +接着是 2 和 1,得到 1,所以数组转换为 [1,1,1],
    +最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= stones.length <= 30
    • +
    • 1 <= stones[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1047.leetcode1047 Remove All Adjacent Duplicates In String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1047.leetcode1047 Remove All Adjacent Duplicates In String-zh.md" new file mode 100644 index 00000000..e2ac7546 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1047.leetcode1047 Remove All Adjacent Duplicates In String-zh.md" @@ -0,0 +1,93 @@ +# [1047. 删除字符串中的所有相邻重复项](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1047.Remove%20All%20Adjacent%20Duplicates%20In%20String/README_EN.md) + +## 题目描述 + + + +

    给出由小写字母组成的字符串 S重复项删除操作会选择两个相邻且相同的字母,并删除它们。

    + +

    在 S 上反复执行重复项删除操作,直到无法继续删除。

    + +

    在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

    + +

     

    + +

    示例:

    + +
    输入:"abbaca"
    +输出:"ca"
    +解释:
    +例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 20000
    2. +
    3. S 仅由小写英文字母组成。
    4. +
    + + +## 解法 + + + +栈实现。 + +遍历字符串 S 中的每个字符 s,若栈为空或者栈顶值不等于字符 s,s 入栈,否则栈顶元素出栈。 + +最后返回栈中元素所组成的字符串。 + + + +### **Python3** + + + +```python +class Solution: + def removeDuplicates(self, S: str) -> str: + res = [] + for s in S: + if not res or res[-1] != s: + res.append(s) + else: + res.pop() + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String removeDuplicates(String S) { + StringBuilder sb = new StringBuilder(); + int top = -1; + for (int i = 0, n = S.length(); i < n; ++i) { + char s = S.charAt(i); + if (top == -1 || sb.charAt(top) != s) { + sb.append(s); + ++top; + } else { + sb.deleteCharAt(top); + --top; + } + } + return sb.toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1048.leetcode1048 Longest String Chain-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1048.leetcode1048 Longest String Chain-zh.md" new file mode 100644 index 00000000..d2559d35 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1048.leetcode1048 Longest String Chain-zh.md" @@ -0,0 +1,66 @@ +# [1048. 最长字符串链](https://leetcode-cn.com/problems/longest-string-chain) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1048.Longest%20String%20Chain/README_EN.md) + +## 题目描述 + + + +

    给出一个单词列表,其中每个单词都由小写英文字母组成。

    + +

    如果我们可以在 word1 的任何地方添加一个字母使其变成 word2,那么我们认为 word1 是 word2 的前身。例如,"abc" 是 "abac" 的前身。

    + +

    词链是单词 [word_1, word_2, ..., word_k] 组成的序列,k >= 1,其中 word_1 是 word_2 的前身,word_2 是 word_3 的前身,依此类推。

    + +

    从给定单词列表 words 中选择单词组成词链,返回词链的最长可能长度。

    + +

    示例:

    + +
    输入:["a","b","ba","bca","bda","bdca"]
    +输出:4
    +解释:最长单词链之一为 "a","ba","bda","bdca"。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= words.length <= 1000
    2. +
    3. 1 <= words[i].length <= 16
    4. +
    5. words[i] 仅由小写英文字母组成。
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1049.leetcode1049 Last Stone Weight II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1049.leetcode1049 Last Stone Weight II-zh.md" new file mode 100644 index 00000000..ac97d56b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1049.leetcode1049 Last Stone Weight II-zh.md" @@ -0,0 +1,130 @@ +# [1049. 最后一块石头的重量 II](https://leetcode-cn.com/problems/last-stone-weight-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1049.Last%20Stone%20Weight%20II/README_EN.md) + +## 题目描述 + + + +

    有一堆石头,每块石头的重量都是正整数。

    + +

    每一回合,从中选出任意两块石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

    + +
      +
    • 如果 x == y,那么两块石头都会被完全粉碎;
    • +
    • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x
    • +
    + +

    最后,最多只会剩下一块石头。返回此石头最小的可能重量。如果没有石头剩下,就返回 0

    + +

     

    + +

    示例:

    + +
    输入:[2,7,4,1,8,1]
    +输出:1
    +解释:
    +组合 2 和 4,得到 2,所以数组转化为 [2,7,1,8,1],
    +组合 7 和 8,得到 1,所以数组转化为 [2,1,1,1],
    +组合 2 和 1,得到 1,所以数组转化为 [1,1,1],
    +组合 1 和 1,得到 0,所以数组转化为 [1],这就是最优值。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= stones.length <= 30
    2. +
    3. 1 <= stones[i] <= 1000
    4. +
    + + +## 解法 + + + +**两个**石头的重量越接近,粉碎后的新重量就越小。同样的,**两堆**石头的重量越接近,它们粉碎后的新重量也越小。 + +所以本题可以转换为,计算容量为 `sum / 2` 的背包最多能装多少石头。 + + + +### **Python3** + + + +```python +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + s = sum(stones) + n = s // 2 + dp = [False for i in range(n + 1)] + dp[0] = True + for stone in stones: + for j in range(n, stone - 1, -1): + dp[j] = dp[j] or dp[j - stone] + for j in range(n, -1, -1): + if dp[j]: + return s - j - j +``` + +### **Java** + + + +```java +class Solution { + public int lastStoneWeightII(int[] stones) { + int sum = 0; + for (int stone : stones) { + sum += stone; + } + int n = sum / 2; + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int stone : stones) { + for (int j = n; j >= stone; j--) { + dp[j] = dp[j] || dp[j - stone]; + } + } + for (int j = n; ; j--) { + if (dp[j]) { + return sum - j - j; + } + } + } +} +``` + +### **Go** + +```go +func lastStoneWeightII(stones []int) int { + sum := 0 + for _, stone := range stones { + sum += stone + } + n := sum / 2 + dp := make([]bool, n+1) + dp[0] = true + for _, stone := range stones { + for j := n; j >= stone; j-- { + dp[j] = dp[j] || dp[j-stone] + } + } + for j := n; ; j-- { + if dp[j] { + return sum - j - j + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1050.leetcode1050 Actors and Directors Who Cooperated At Least Three Times-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1050.leetcode1050 Actors and Directors Who Cooperated At Least Three Times-zh.md" new file mode 100644 index 00000000..7d9121c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1050.leetcode1050 Actors and Directors Who Cooperated At Least Three Times-zh.md" @@ -0,0 +1,71 @@ +# [1050. 合作过至少三次的演员和导演](https://leetcode-cn.com/problems/actors-and-directors-who-cooperated-at-least-three-times) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1050.Actors%20and%20Directors%20Who%20Cooperated%20At%20Least%20Three%20Times/README_EN.md) + +## 题目描述 + + + +

    ActorDirector 表:

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| actor_id    | int     |
    +| director_id | int     |
    +| timestamp   | int     |
    ++-------------+---------+
    +timestamp 是这张表的主键.
    +
    + +

     

    + +

    写一条SQL查询语句获取合作过至少三次的演员和导演的 id 对 (actor_id, director_id)

    + +

    示例:

    + +
    +ActorDirector 表:
    ++-------------+-------------+-------------+
    +| actor_id    | director_id | timestamp   |
    ++-------------+-------------+-------------+
    +| 1           | 1           | 0           |
    +| 1           | 1           | 1           |
    +| 1           | 1           | 2           |
    +| 1           | 2           | 3           |
    +| 1           | 2           | 4           |
    +| 2           | 1           | 5           |
    +| 2           | 1           | 6           |
    ++-------------+-------------+-------------+
    +
    +Result 表:
    ++-------------+-------------+
    +| actor_id    | director_id |
    ++-------------+-------------+
    +| 1           | 1           |
    ++-------------+-------------+
    +唯一的 id 对是 (1, 1),他们恰好合作了 3 次。
    + + +## 解法 + + + +`GROUP BY` + `HAVING` 解决。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + actor_id, director_id +FROM + ActorDirector +GROUP BY actor_id, director_id +HAVING count(1) >= 3; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1051.leetcode1051 Height Checker-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1051.leetcode1051 Height Checker-zh.md" new file mode 100644 index 00000000..e540c5ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1051.leetcode1051 Height Checker-zh.md" @@ -0,0 +1,81 @@ +# [1051. 高度检查器](https://leetcode-cn.com/problems/height-checker) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1051.Height%20Checker/README_EN.md) + +## 题目描述 + + + +

    学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。

    + +

    请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。

    + +

    注意,当一组学生被选中时,他们之间可以以任何可能的方式重新排序,而未被选中的学生应该保持不动。

    + +

     

    + +

    示例:

    + +
    +输入:heights = [1,1,4,2,1,3]
    +输出:3 
    +解释:
    +当前数组:[1,1,4,2,1,3]
    +目标数组:[1,1,1,2,3,4]
    +在下标 2 处(从 0 开始计数)出现 4 vs 1 ,所以我们必须移动这名学生。
    +在下标 4 处(从 0 开始计数)出现 1 vs 3 ,所以我们必须移动这名学生。
    +在下标 5 处(从 0 开始计数)出现 3 vs 4 ,所以我们必须移动这名学生。
    + +

    示例 2:

    + +
    +输入:heights = [5,1,2,3,4]
    +输出:5
    +
    + +

    示例 3:

    + +
    +输入:heights = [1,2,3,4,5]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= heights.length <= 100
    • +
    • 1 <= heights[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1052.leetcode1052 Grumpy Bookstore Owner-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1052.leetcode1052 Grumpy Bookstore Owner-zh.md" new file mode 100644 index 00000000..8057890b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1052.leetcode1052 Grumpy Bookstore Owner-zh.md" @@ -0,0 +1,106 @@ +# [1052. 爱生气的书店老板](https://leetcode-cn.com/problems/grumpy-bookstore-owner) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1052.Grumpy%20Bookstore%20Owner/README_EN.md) + +## 题目描述 + + + +

    今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。

    + +

    在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。

    + +

    书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。

    + +

    请你返回这一天营业下来,最多有多少客户能够感到满意的数量。

    + +

    示例:

    + +
    输入:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
    +输出:16
    +解释:
    +书店老板在最后 3 分钟保持冷静。
    +感到满意的最大客户数量 = 1 + 1 + 1 + 1 + 7 + 5 = 16.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= X <= customers.length == grumpy.length <= 20000
    • +
    • 0 <= customers[i] <= 1000
    • +
    • 0 <= grumpy[i] <= 1
    • +
    + + +## 解法 + + + +- 用 `s` 累计不使用秘密技巧时,满意的顾客数; +- 用 `t` 计算大小为 `X` 的滑动窗口最多增加的满意的顾客数; +- 结果即为 `s+t`。 + + + +### **Python3** + + + +```python +class Solution: + def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int: + # 用s累计不使用秘密技巧时,满意的顾客数 + # 用t计算大小为X的滑动窗口最多增加的满意的顾客数 + # 结果即为s+t + s = t = 0 + win, n = 0, len(customers) + for i in range(n): + if grumpy[i] == 0: + s += customers[i] + else: + win += customers[i] + if i >= X and grumpy[i - X] == 1: + win -= customers[i - X] + # 求滑动窗口的最大值 + t = max(t, win) + return s + t +``` + +### **Java** + + + +```java +class Solution { + public int maxSatisfied(int[] customers, int[] grumpy, int X) { + // 用s累计不使用秘密技巧时,满意的顾客数 + // 用t计算大小为X的滑动窗口最多增加的满意的顾客数 + // 结果即为s+t + int s = 0, t = 0; + for (int i = 0, win = 0, n = customers.length; i < n; ++i) { + if (grumpy[i] == 0) { + s += customers[i]; + } else { + win += customers[i]; + } + if (i >= X && grumpy[i - X] == 1) { + win -= customers[i - X]; + } + // 求滑动窗口的最大值 + t = Math.max(t, win); + } + return s + t; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1053.leetcode1053 Previous Permutation With One Swap-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1053.leetcode1053 Previous Permutation With One Swap-zh.md" new file mode 100644 index 00000000..e86f3334 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1053.leetcode1053 Previous Permutation With One Swap-zh.md" @@ -0,0 +1,85 @@ +# [1053. 交换一次的先前排列](https://leetcode-cn.com/problems/previous-permutation-with-one-swap) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1053.Previous%20Permutation%20With%20One%20Swap/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数的数组 A(其中的元素不一定完全不同),请你返回可在 一次交换(交换两数字 A[i]A[j] 的位置)后得到的、按字典序排列小于 A 的最大可能排列。

    + +

    如果无法这么操作,就请返回原数组。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [3,2,1]
    +输出:[3,1,2]
    +解释:交换 2 和 1
    +
    + +

    示例 2:

    + +
    +输入:arr = [1,1,5]
    +输出:[1,1,5]
    +解释:已经是最小排列
    +
    + +

    示例 3:

    + +
    +输入:arr = [1,9,4,6,7]
    +输出:[1,7,4,6,9]
    +解释:交换 9 和 7
    +
    + +

    示例 4:

    + +
    +输入:arr = [3,1,1,3]
    +输出:[1,3,1,3]
    +解释:交换 1 和 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 1 <= arr[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1054.leetcode1054 Distant Barcodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1054.leetcode1054 Distant Barcodes-zh.md" new file mode 100644 index 00000000..d2e05454 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1054.leetcode1054 Distant Barcodes-zh.md" @@ -0,0 +1,66 @@ +# [1054. 距离相等的条形码](https://leetcode-cn.com/problems/distant-barcodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1054.Distant%20Barcodes/README_EN.md) + +## 题目描述 + + + +

    在一个仓库里,有一排条形码,其中第 i 个条形码为 barcodes[i]

    + +

    请你重新排列这些条形码,使其中两个相邻的条形码 不能 相等。 你可以返回任何满足该要求的答案,此题保证存在答案。

    + +

     

    + +

    示例 1:

    + +
    输入:[1,1,1,2,2,2]
    +输出:[2,1,2,1,2,1]
    +
    + +

    示例 2:

    + +
    输入:[1,1,1,1,2,2,3,3]
    +输出:[1,3,1,3,2,1,2,1]
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= barcodes.length <= 10000
    2. +
    3. 1 <= barcodes[i] <= 10000
    4. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1055.leetcode1055 Shortest Way to Form String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1055.leetcode1055 Shortest Way to Form String-zh.md" new file mode 100644 index 00000000..0cc17d5f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1055.leetcode1055 Shortest Way to Form String-zh.md" @@ -0,0 +1,74 @@ +# [1055. 形成字符串的最短路径](https://leetcode-cn.com/problems/shortest-way-to-form-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1055.Shortest%20Way%20to%20Form%20String/README_EN.md) + +## 题目描述 + + + +

    对于任何字符串,我们可以通过删除其中一些字符(也可能不删除)来构造该字符串的子序列。

    + +

    给定源字符串 source 和目标字符串 target,找出源字符串中能通过串联形成目标字符串的子序列的最小数量。如果无法通过串联源字符串中的子序列来构造目标字符串,则返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:source = "abc", target = "abcbc"
    +输出:2
    +解释:目标字符串 "abcbc" 可以由 "abc" 和 "bc" 形成,它们都是源字符串 "abc" 的子序列。
    +
    + +

    示例 2:

    + +
    输入:source = "abc", target = "acdbc"
    +输出:-1
    +解释:由于目标字符串中包含字符 "d",所以无法由源字符串的子序列构建目标字符串。
    +
    + +

    示例 3:

    + +
    输入:source = "xyz", target = "xzyxz"
    +输出:3
    +解释:目标字符串可以按如下方式构建: "xz" + "y" + "xz"。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. source 和 target 两个字符串都只包含 "a"-"z" 的英文小写字母。
    2. +
    3. source 和 target 两个字符串的长度介于 1 和 1000 之间。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1056.leetcode1056 Confusing Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1056.leetcode1056 Confusing Number-zh.md" new file mode 100644 index 00000000..dec539ce --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1056.leetcode1056 Confusing Number-zh.md" @@ -0,0 +1,99 @@ +# [1056. 易混淆数](https://leetcode-cn.com/problems/confusing-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1056.Confusing%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一个数字 N,当它满足以下条件的时候返回 true

    + +

    原数字旋转 180° 以后可以得到新的数字。

    + +

    如 0, 1, 6, 8, 9 旋转 180° 以后,得到了新的数字 0, 1, 9, 8, 6 。

    + +

    2, 3, 4, 5, 7 旋转 180° 后,得到的不是数字。

    + +

    易混淆数 (confusing number) 在旋转180°以后,可以得到和原来不同的数,且新数字的每一位都是有效的。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:6
    +输出:true
    +解释: 
    +把 6 旋转 180° 以后得到 9,9 是有效数字且 9!=6 。
    +
    + +

    示例 2:

    + +

    + +
    输入:89
    +输出:true
    +解释: 
    +把 89 旋转 180° 以后得到 68,86 是有效数字且 86!=89 。
    +
    + +

    示例 3:

    + +

    + +
    输入:11
    +输出:false
    +解释:
    +把 11 旋转 180° 以后得到 11,11 是有效数字但是值保持不变,所以 11 不是易混淆数字。 
    +
    + +

    示例 4:

    + +

    + +
    输入:25
    +输出:false
    +解释:
    +把 25 旋转 180° 以后得到的不是数字。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= N <= 10^9
    2. +
    3. 可以忽略掉旋转后得到的前导零,例如,如果我们旋转后得到 0008 那么该数字就是 8
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1057.leetcode1057 Campus Bikes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1057.leetcode1057 Campus Bikes-zh.md" new file mode 100644 index 00000000..f1971f1b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1057.leetcode1057 Campus Bikes-zh.md" @@ -0,0 +1,78 @@ +# [1057. 校园自行车分配](https://leetcode-cn.com/problems/campus-bikes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1057.Campus%20Bikes/README_EN.md) + +## 题目描述 + + + +

    在由 2D 网格表示的校园里有 n 位工人(worker)和 m 辆自行车(bike),n <= m。所有工人和自行车的位置都用网格上的 2D 坐标表示。

    + +

    我们需要为每位工人分配一辆自行车。在所有可用的自行车和工人中,我们选取彼此之间曼哈顿距离最短的工人自行车对  (worker, bike) ,并将其中的自行车分配給工人。如果有多个 (worker, bike) 对之间的曼哈顿距离相同,那么我们选择工人索引最小的那对。类似地,如果有多种不同的分配方法,则选择自行车索引最小的一对。不断重复这一过程,直到所有工人都分配到自行车为止。

    + +

    给定两点 p1 和 p2 之间的曼哈顿距离为 Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|

    + +

    返回长度为 n 的向量 ans,其中 a[i] 是第 i 位工人分配到的自行车的索引(从 0 开始)。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
    +输出:[1,0]
    +解释:
    +工人 1 分配到自行车 0,因为他们最接近且不存在冲突,工人 0 分配到自行车 1 。所以输出是 [1,0]。
    +
    + +

    示例 2:

    + +

    + +
    输入:workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
    +输出:[0,2,1]
    +解释:
    +工人 0 首先分配到自行车 0 。工人 1 和工人 2 与自行车 2 距离相同,因此工人 1 分配到自行车 2,工人 2 将分配到自行车 1 。因此输出为 [0,2,1]。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= workers[i][j], bikes[i][j] < 1000
    2. +
    3. 所有工人和自行车的位置都不相同。
    4. +
    5. 1 <= workers.length <= bikes.length <= 1000
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1058.leetcode1058 Minimize Rounding Error to Meet Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1058.leetcode1058 Minimize Rounding Error to Meet Target-zh.md" new file mode 100644 index 00000000..1109a690 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1058.leetcode1058 Minimize Rounding Error to Meet Target-zh.md" @@ -0,0 +1,69 @@ +# [1058. 最小化舍入误差以满足目标](https://leetcode-cn.com/problems/minimize-rounding-error-to-meet-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1058.Minimize%20Rounding%20Error%20to%20Meet%20Target/README_EN.md) + +## 题目描述 + + + +

    给定一系列价格 [p1,p2...,pn] 和一个目标 target,将每个价格 pi 舍入为 Roundi(pi) 以使得舍入数组 [Round1(p1),Round2(p2)...,Roundn(pn)] 之和达到给定的目标值 target。每次舍入操作 Roundi(pi) 可以是向下舍 Floor(pi) 也可以是向上入 Ceil(pi)

    + +

    如果舍入数组之和无论如何都无法达到目标值 target,就返回 -1。否则,以保留到小数点后三位的字符串格式返回最小的舍入误差,其定义为 Σ |Roundi(pi) - (pi)|( i 从 1 到 n )。

    + +

     

    + +

    示例 1:

    + +
    输入:prices = ["0.700","2.800","4.900"], target = 8
    +输出:"1.000"
    +解释: 
    +使用 Floor,Ceil 和 Ceil 操作得到 (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0 。
    +
    + +

    示例 2:

    + +
    输入:prices = ["1.500","2.500","3.500"], target = 10
    +输出:"-1"
    +解释:
    +达到目标是不可能的。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= prices.length <= 500
    2. +
    3. 表示价格的每个字符串 prices[i] 都代表一个介于 0 和 1000 之间的实数,并且正好有 3 个小数位。
    4. +
    5. target 介于 0 和 1000000 之间。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1059.leetcode1059 All Paths from Source Lead to Destination-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1059.leetcode1059 All Paths from Source Lead to Destination-zh.md" new file mode 100644 index 00000000..2c71c2fc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1059.leetcode1059 All Paths from Source Lead to Destination-zh.md" @@ -0,0 +1,108 @@ +# [1059. 从始点到终点的所有路径](https://leetcode-cn.com/problems/all-paths-from-source-lead-to-destination) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1059.All%20Paths%20from%20Source%20Lead%20to%20Destination/README_EN.md) + +## 题目描述 + + + +

    给定有向图的边 edges,以及该图的始点 source 和目标终点 destination,确定从始点 source 出发的所有路径是否最终结束于目标终点 destination,即:

    + +
      +
    • 从始点 source 到目标终点 destination 存在至少一条路径
    • +
    • 如果存在从始点 source 到没有出边的节点的路径,则该节点就是路径终点。
    • +
    • 从始点source到目标终点 destination 可能路径数是有限数字
    • +
    + +

    当从始点 source 出发的所有路径都可以到达目标终点 destination 时返回 true,否则返回 false

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
    +输出:false
    +说明:节点 1 和节点 2 都可以到达,但也会卡在那里。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3
    +输出:false
    +说明:有两种可能:在节点 3 处结束,或是在节点 1 和节点 2 之间无限循环。
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
    +输出:true
    +
    + +

    示例 4:

    + +

    + +
    输入:n = 3, edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2
    +输出:false
    +说明:从始点出发的所有路径都在目标终点结束,但存在无限多的路径,如 0-1-2,0-1-1-2,0-1-1-1-2,0-1-1-1-1-2 等。
    +
    + +

    示例 5:

    + +

    + +
    输入:n = 2, edges = [[0,1],[1,1]], source = 0, destination = 1
    +输出:false
    +说明:在目标节点上存在无限的自环。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 给定的图中可能带有自环和平行边。
    2. +
    3. 图中的节点数 n 介于 1 和 10000 之间。
    4. +
    5. 图中的边数在 0 到 10000 之间。
    6. +
    7. 0 <= edges.length <= 10000
    8. +
    9. edges[i].length == 2
    10. +
    11. 0 <= source <= n - 1
    12. +
    13. 0 <= destination <= n - 1
    14. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1060.leetcode1060 Missing Element in Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1060.leetcode1060 Missing Element in Sorted Array-zh.md" new file mode 100644 index 00000000..b2c282e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1060.leetcode1060 Missing Element in Sorted Array-zh.md" @@ -0,0 +1,83 @@ +# [1060. 有序数组中的缺失元素](https://leetcode-cn.com/problems/missing-element-in-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1060.Missing%20Element%20in%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    现有一个按 升序 排列的整数数组 nums ,其中每个数字都 互不相同

    + +

    给你一个整数 k ,请你找出并返回从数组最左边开始的第 k 个缺失数字。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [4,7,9,10], k = 1
    +输出:5
    +解释:第一个缺失数字为 5 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [4,7,9,10], k = 3
    +输出:8
    +解释:缺失数字有 [5,6,8,...],因此第三个缺失数字为 8 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,2,4], k = 3
    +输出:6
    +解释:缺失数字有 [3,5,6,7,...],因此第三个缺失数字为 6 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 1 <= nums[i] <= 107
    • +
    • nums升序 排列,其中所有元素 互不相同
    • +
    • 1 <= k <= 108
    • +
    + +

     

    + +

    进阶:你可以设计一个对数时间复杂度(即,O(log(n)))的解决方案吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1061.leetcode1061 Lexicographically Smallest Equivalent String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1061.leetcode1061 Lexicographically Smallest Equivalent String-zh.md" new file mode 100644 index 00000000..99aa93ef --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1061.leetcode1061 Lexicographically Smallest Equivalent String-zh.md" @@ -0,0 +1,85 @@ +# [1061. 按字典序排列最小的等效字符串](https://leetcode-cn.com/problems/lexicographically-smallest-equivalent-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1061.Lexicographically%20Smallest%20Equivalent%20String/README_EN.md) + +## 题目描述 + + + +

    给出长度相同的两个字符串:A 和 B,其中 A[i] 和 B[i] 是一组等价字符。举个例子,如果 A = "abc" 且 B = "cde",那么就有 'a' == 'c', 'b' == 'd', 'c' == 'e'

    + +

    等价字符遵循任何等价关系的一般规则:

    + +
      +
    • 自反性:'a' == 'a'
    • +
    • 对称性:'a' == 'b' 则必定有 'b' == 'a'
    • +
    • 传递性:'a' == 'b' 且 'b' == 'c' 就表明 'a' == 'c'
    • +
    + +

    例如,A 和 B 的等价信息和之前的例子一样,那么 S = "eed", "acd" 或 "aab",这三个字符串都是等价的,而 "aab" 是 S 的按字典序最小的等价字符串

    + +

    利用 A 和 B 的等价信息,找出并返回 S 的按字典序排列最小的等价字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:A = "parker", B = "morris", S = "parser"
    +输出:"makkek"
    +解释:根据 AB 中的等价信息,我们可以将这些字符分为 [m,p], [a,o], [k,r,s], [e,i] 共 4 组。每组中的字符都是等价的,并按字典序排列。所以答案是 "makkek"。
    +
    + +

    示例 2:

    + +
    输入:A = "hello", B = "world", S = "hold"
    +输出:"hdld"
    +解释:根据 AB 中的等价信息,我们可以将这些字符分为 [h,w], [d,e,o], [l,r] 共 3 组。所以只有 S 中的第二个字符 'o' 变成 'd',最后答案为 "hdld"。
    +
    + +

    示例 3:

    + +
    输入:A = "leetcode", B = "programs", S = "sourcecode"
    +输出:"aauaaaaada"
    +解释:我们可以把 A 和 B 中的等价字符分为 [a,o,e,r,s,c], [l,p], [g,t][d,m] 共 4 组,因此 S 中除了 'u''d' 之外的所有字母都转化成了 'a',最后答案为 "aauaaaaada"。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 字符串 AB 和 S 仅有从 'a' 到 'z' 的小写英文字母组成。
    2. +
    3. 字符串 AB 和 S 的长度在 1 到 1000 之间。
    4. +
    5. 字符串 A 和 B 长度相同。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1062.leetcode1062 Longest Repeating Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1062.leetcode1062 Longest Repeating Substring-zh.md" new file mode 100644 index 00000000..989de138 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1062.leetcode1062 Longest Repeating Substring-zh.md" @@ -0,0 +1,78 @@ +# [1062. 最长重复子串](https://leetcode-cn.com/problems/longest-repeating-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1062.Longest%20Repeating%20Substring/README_EN.md) + +## 题目描述 + + + +

    给定字符串 S,找出最长重复子串的长度。如果不存在重复子串就返回 0

    + +

     

    + +

    示例 1:

    + +
    输入:"abcd"
    +输出:0
    +解释:没有重复子串。
    +
    + +

    示例 2:

    + +
    输入:"abbaba"
    +输出:2
    +解释:最长的重复子串为 "ab" 和 "ba",每个出现 2 次。
    +
    + +

    示例 3:

    + +
    输入:"aabcaabdaab"
    +输出:3
    +解释:最长的重复子串为 "aab",出现 3 次。
    +
    + +

    示例 4:

    + +
    输入:"aaaaa"
    +输出:4
    +解释:最长的重复子串为 "aaaa",出现 2 次。
    + +

     

    + +

    提示:

    + +
      +
    1. 字符串 S 仅包含从 'a' 到 'z' 的小写英文字母。
    2. +
    3. 1 <= S.length <= 1500
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1063.leetcode1063 Number of Valid Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1063.leetcode1063 Number of Valid Subarrays-zh.md" new file mode 100644 index 00000000..00c884b6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1063.leetcode1063 Number of Valid Subarrays-zh.md" @@ -0,0 +1,74 @@ +# [1063. 有效子数组的数目](https://leetcode-cn.com/problems/number-of-valid-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1063.Number%20of%20Valid%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 A,返回满足下面条件的 非空连续 子数组的数目:

    + +

    子数组中,最左侧的元素不大于其他元素。

    + +

     

    + +

    示例 1:

    + +
    输入:[1,4,2,5,3]
    +输出:11
    +解释:有 11 个有效子数组,分别是:[1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3] 。
    +
    + +

    示例 2:

    + +
    输入:[3,2,1]
    +输出:3
    +解释:有 3 个有效子数组,分别是:[3],[2],[1] 。
    +
    + +

    示例 3:

    + +
    输入:[2,2,2]
    +输出:6
    +解释:有 6 个有效子数组,分别为是:[2],[2],[2],[2,2],[2,2],[2,2,2] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 50000
    2. +
    3. 0 <= A[i] <= 100000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1064.leetcode1064 Fixed Point-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1064.leetcode1064 Fixed Point-zh.md" new file mode 100644 index 00000000..9e433047 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1064.leetcode1064 Fixed Point-zh.md" @@ -0,0 +1,143 @@ +# [1064. 不动点](https://leetcode-cn.com/problems/fixed-point) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1064.Fixed%20Point/README_EN.md) + +## 题目描述 + + + +

    给定已经按 升序 排列、由不同整数组成的数组 arr,返回满足 arr[i] == i 的最小索引 i。如果不存在这样的 i,返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [-10,-5,0,3,7]
    +输出:3
    +解释:对于给定的数组,arr[0] = -10,arr[1] = -5,arr[2] = 0,arr[3] = 3,因此输出为 3 。
    +
    + +

    示例 2:

    + +
    +输入:arr = [0,2,5,8,17]
    +输出:0
    +解释:arr[0] = 0,因此输出为 0 。
    +
    + +

    示例 3:

    + +
    +输入:arr = [-10,-5,3,4,7,9]
    +输出:-1
    +解释:不存在这样的 i 满足 arr[i] = i,因此输出为 -1 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length < 104
    • +
    • -109 <= arr[i] <= 109
    • +
    + +

     

    + +

    进阶:时间复杂度为 O(n) 的解决方案很直观也很简单。你可以设计更优的解决方案吗?

    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def fixedPoint(self, arr: List[int]) -> int: + left, right = 0, len(arr) - 1 + while left < right: + mid = (left + right) >> 1 + if arr[mid] >= mid: + right = mid + else: + left = mid + 1 + return left if arr[left] == left else -1 +``` + +### **Java** + + + +```java +class Solution { + public int fixedPoint(int[] arr) { + int left = 0, right = arr.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] >= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == left ? left : -1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int fixedPoint(vector& arr) { + int left = 0, right = arr.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (arr[mid] >= mid) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == left ? left : -1; + } +}; +``` + +### **Go** + +```go +func fixedPoint(arr []int) int { + left, right := 0, len(arr)-1 + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= mid { + right = mid + } else { + left = mid + 1 + } + } + if arr[left] == left { + return left + } + return -1 +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1065.leetcode1065 Index Pairs of a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1065.leetcode1065 Index Pairs of a String-zh.md" new file mode 100644 index 00000000..23e72ffa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1065.leetcode1065 Index Pairs of a String-zh.md" @@ -0,0 +1,69 @@ +# [1065. 字符串的索引对](https://leetcode-cn.com/problems/index-pairs-of-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1065.Index%20Pairs%20of%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给出 字符串 text 和 字符串列表 words, 返回所有的索引对 [i, j] 使得在索引对范围内的子字符串 text[i]...text[j](包括 i 和 j)属于字符串列表 words

    + +

     

    + +

    示例 1:

    + +
    输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
    +输出: [[3,7],[9,13],[10,17]]
    +
    + +

    示例 2:

    + +
    输入: text = "ababa", words = ["aba","ab"]
    +输出: [[0,1],[0,2],[2,3],[2,4]]
    +解释: 
    +注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 所有字符串都只包含小写字母。
    2. +
    3. 保证 words 中的字符串无重复。
    4. +
    5. 1 <= text.length <= 100
    6. +
    7. 1 <= words.length <= 20
    8. +
    9. 1 <= words[i].length <= 50
    10. +
    11. 按序返回索引对 [i,j](即,按照索引对的第一个索引进行排序,当第一个索引对相同时按照第二个索引对排序)。
    12. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1066.leetcode1066 Campus Bikes II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1066.leetcode1066 Campus Bikes II-zh.md" new file mode 100644 index 00000000..f1814f37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1066.leetcode1066 Campus Bikes II-zh.md" @@ -0,0 +1,78 @@ +# [1066. 校园自行车分配 II](https://leetcode-cn.com/problems/campus-bikes-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1066.Campus%20Bikes%20II/README_EN.md) + +## 题目描述 + + + +

    在由 2D 网格表示的校园里有 n 位工人(worker)和 m 辆自行车(bike),n <= m。所有工人和自行车的位置都用网格上的 2D 坐标表示。

    + +

    我们为每一位工人分配一辆专属自行车,使每个工人与其分配到的自行车之间的曼哈顿距离最小化。

    + +

    p1 和 p2 之间的曼哈顿距离为 Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|

    + +

    返回每个工人与分配到的自行车之间的曼哈顿距离的最小可能总和。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
    +输出:6
    +解释:
    +自行车 0 分配给工人 0,自行车 1 分配给工人 1 。分配得到的曼哈顿距离都是 3, 所以输出为 6 。
    +
    + +

    示例 2:

    + +

    + +
    输入:workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
    +输出:4
    +解释:
    +先将自行车 0 分配给工人 0,再将自行车 1 分配给工人 1(或工人 2),自行车 2 给工人 2(或工人 1)。如此分配使得曼哈顿距离的总和为 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000
    2. +
    3. 所有工人和自行车的位置都不相同。
    4. +
    5. 1 <= workers.length <= bikes.length <= 10
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1067.leetcode1067 Digit Count in Range-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1067.leetcode1067 Digit Count in Range-zh.md" new file mode 100644 index 00000000..c9925819 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1067.leetcode1067 Digit Count in Range-zh.md" @@ -0,0 +1,67 @@ +# [1067. 范围内的数字计数](https://leetcode-cn.com/problems/digit-count-in-range) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1067.Digit%20Count%20in%20Range/README_EN.md) + +## 题目描述 + + + +

    给定一个在 0 到 9 之间的整数 d,和两个正整数 low 和 high 分别作为上下界。返回 d 在 low 和 high 之间的整数中出现的次数,包括边界 low 和 high

    + +

     

    + +

    示例 1:

    + +
    输入:d = 1, low = 1, high = 13
    +输出:6
    +解释: 
    +数字 d=11,10,11,12,13 中出现 6 次。注意 d=1 在数字 11 中出现两次。
    +
    + +

    示例 2:

    + +
    输入:d = 3, low = 100, high = 250
    +输出:35
    +解释:
    +数字 d=3103,113,123,130,131,...,238,239,243 出现 35 次。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 0 <= d <= 9
    2. +
    3. 1 <= low <= high <= 2×10^8
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1068.leetcode1068 Product Sales Analysis I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1068.leetcode1068 Product Sales Analysis I-zh.md" new file mode 100644 index 00000000..a403e82b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1068.leetcode1068 Product Sales Analysis I-zh.md" @@ -0,0 +1,95 @@ +# [1068. 产品销售分析 I](https://leetcode-cn.com/problems/product-sales-analysis-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1068.Product%20Sales%20Analysis%20I/README_EN.md) + +## 题目描述 + + + +

    销售表 Sales

    + +
    +-------------+-------+
    +| Column Name | Type  |
    ++-------------+-------+
    +| sale_id     | int   |
    +| product_id  | int   |
    +| year        | int   |
    +| quantity    | int   |
    +| price       | int   |
    ++-------------+-------+
    +(sale_id, year) 是销售表 Sales 的主键.
    +product_id 是关联到产品表 Product 的外键.
    +注意: price 表示每单位价格
    +
    + +

    产品表 Product

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    ++--------------+---------+
    +product_id 是表的主键.
    +
    + +

     

    + +

    写一条SQL 查询语句获取 Sales 表中所有产品对应的 产品名称 product_name 以及该产品的所有 售卖年份 year 和 价格 price

    + +

     

    + +

    示例

    + +
    Sales 表:
    ++---------+------------+------+----------+-------+
    +| sale_id | product_id | year | quantity | price |
    ++---------+------------+------+----------+-------+ 
    +| 1       | 100        | 2008 | 10       | 5000  |
    +| 2       | 100        | 2009 | 12       | 5000  |
    +| 7       | 200        | 2011 | 15       | 9000  |
    ++---------+------------+------+----------+-------+
    +
    +Product 表:
    ++------------+--------------+
    +| product_id | product_name |
    ++------------+--------------+
    +| 100        | Nokia        |
    +| 200        | Apple        |
    +| 300        | Samsung      |
    ++------------+--------------+
    +
    +Result 表:
    ++--------------+-------+-------+
    +| product_name | year  | price |
    ++--------------+-------+-------+
    +| Nokia        | 2008  | 5000  |
    +| Nokia        | 2009  | 5000  |
    +| Apple        | 2011  | 9000  |
    ++--------------+-------+-------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + p.product_name AS product_name, + s.year AS year, + s.price AS price +FROM + Sales s +LEFT JOIN + Product p +ON + s.product_id = p.product_id; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1069.leetcode1069 Product Sales Analysis II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1069.leetcode1069 Product Sales Analysis II-zh.md" new file mode 100644 index 00000000..5fc44a8d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1069.leetcode1069 Product Sales Analysis II-zh.md" @@ -0,0 +1,90 @@ +# [1069. 产品销售分析 II](https://leetcode-cn.com/problems/product-sales-analysis-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1069.Product%20Sales%20Analysis%20II/README_EN.md) + +## 题目描述 + + + +

    销售表:Sales

    + +
    +-------------+-------+
    +| Column Name | Type  |
    ++-------------+-------+
    +| sale_id     | int   |
    +| product_id  | int   |
    +| year        | int   |
    +| quantity    | int   |
    +| price       | int   |
    ++-------------+-------+
    +sale_id 是这个表的主键。
    +product_id 是 Product 表的外键。
    +请注意价格是每单位的。
    +
    + +

    产品表:Product

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    ++--------------+---------+
    +product_id 是这个表的主键。
    +
    + +

     

    + +

    编写一个 SQL 查询,按产品 id product_id 来统计每个产品的销售总量。

    + +

     

    + +

    查询结果格式如下面例子所示:

    + +
    Sales 表:
    ++---------+------------+------+----------+-------+
    +| sale_id | product_id | year | quantity | price |
    ++---------+------------+------+----------+-------+ 
    +| 1       | 100        | 2008 | 10       | 5000  |
    +| 2       | 100        | 2009 | 12       | 5000  |
    +| 7       | 200        | 2011 | 15       | 9000  |
    ++---------+------------+------+----------+-------+
    +
    +Product 表:
    ++------------+--------------+
    +| product_id | product_name |
    ++------------+--------------+
    +| 100        | Nokia        |
    +| 200        | Apple        |
    +| 300        | Samsung      |
    ++------------+--------------+
    +
    +Result 表:
    ++--------------+----------------+
    +| product_id   | total_quantity |
    ++--------------+----------------+
    +| 100          | 22             |
    +| 200          | 15             |
    ++--------------+----------------+
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + product_id, + sum(quantity) AS total_quantity +FROM + Sales +GROUP BY + product_id; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1070.leetcode1070 Product Sales Analysis III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1070.leetcode1070 Product Sales Analysis III-zh.md" new file mode 100644 index 00000000..3856d135 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1070.leetcode1070 Product Sales Analysis III-zh.md" @@ -0,0 +1,96 @@ +# [1070. 产品销售分析 III](https://leetcode-cn.com/problems/product-sales-analysis-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1070.Product%20Sales%20Analysis%20III/README_EN.md) + +## 题目描述 + + + +

    销售表 Sales

    + +
    +-------------+-------+
    +| Column Name | Type  |
    ++-------------+-------+
    +| sale_id     | int   |
    +| product_id  | int   |
    +| year        | int   |
    +| quantity    | int   |
    +| price       | int   |
    ++-------------+-------+
    +sale_id 是此表的主键。
    +product_id 是产品表的外键。
    +请注意,价格是按每单位计的。
    +
    + +

    产品表 Product

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    ++--------------+---------+
    +product_id 是此表的主键。
    + +

     

    + +

    编写一个 SQL 查询,选出每个销售产品的 第一年产品 id年份数量 价格

    + +

    查询结果格式如下:

    + +
    Sales table:
    ++---------+------------+------+----------+-------+
    +| sale_id | product_id | year | quantity | price |
    ++---------+------------+------+----------+-------+ 
    +| 1       | 100        | 2008 | 10       | 5000  |
    +| 2       | 100        | 2009 | 12       | 5000  |
    +| 7       | 200        | 2011 | 15       | 9000  |
    ++---------+------------+------+----------+-------+
    +
    +Product table:
    ++------------+--------------+
    +| product_id | product_name |
    ++------------+--------------+
    +| 100        | Nokia        |
    +| 200        | Apple        |
    +| 300        | Samsung      |
    ++------------+--------------+
    +
    +Result table:
    ++------------+------------+----------+-------+
    +| product_id | first_year | quantity | price |
    ++------------+------------+----------+-------+ 
    +| 100        | 2008       | 10       | 5000  |
    +| 200        | 2011       | 15       | 9000  |
    ++------------+------------+----------+-------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + product_id, + year as first_year, + quantity, + price +FROM + Sales +WHERE + (product_id, year) IN ( + SELECT + product_id, min(year) year + FROM + Sales + GROUP BY product_id + ); +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1071.leetcode1071 Greatest Common Divisor of Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1071.leetcode1071 Greatest Common Divisor of Strings-zh.md" new file mode 100644 index 00000000..d473ec91 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1071.leetcode1071 Greatest Common Divisor of Strings-zh.md" @@ -0,0 +1,75 @@ +# [1071. 字符串的最大公因子](https://leetcode-cn.com/problems/greatest-common-divisor-of-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1071.Greatest%20Common%20Divisor%20of%20Strings/README_EN.md) + +## 题目描述 + + + +

    对于字符串 S 和 T,只有在 S = T + ... + TT 自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。

    + +

    返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2

    + +

     

    + +

    示例 1:

    + +
    +输入:str1 = "ABCABC", str2 = "ABC"
    +输出:"ABC"
    +
    + +

    示例 2:

    + +
    +输入:str1 = "ABABAB", str2 = "ABAB"
    +输出:"AB"
    +
    + +

    示例 3:

    + +
    +输入:str1 = "LEET", str2 = "CODE"
    +输出:""
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= str1.length <= 1000
    2. +
    3. 1 <= str2.length <= 1000
    4. +
    5. str1[i] 和 str2[i] 为大写英文字母
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1072.leetcode1072 Flip Columns For Maximum Number of Equal Rows-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1072.leetcode1072 Flip Columns For Maximum Number of Equal Rows-zh.md" new file mode 100644 index 00000000..36ceed6c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1072.leetcode1072 Flip Columns For Maximum Number of Equal Rows-zh.md" @@ -0,0 +1,81 @@ +# [1072. 按列翻转得到最大值等行数](https://leetcode-cn.com/problems/flip-columns-for-maximum-number-of-equal-rows) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1072.Flip%20Columns%20For%20Maximum%20Number%20of%20Equal%20Rows/README_EN.md) + +## 题目描述 + + + +

    给定由若干 0 和 1 组成的矩阵 matrix,从中选出任意数量的列并翻转其上的 每个 单元格。翻转后,单元格的值从 0 变成 1,或者从 1 变为 0 。

    + +

    回经过一些翻转后,行与行之间所有值都相等的最大行数。

    + +

     

    + +
      +
    + +

    示例 1:

    + +
    +输入:[[0,1],[1,1]]
    +输出:1
    +解释:不进行翻转,有 1 行所有值都相等。
    +
    + +

    示例 2:

    + +
    +输入:[[0,1],[1,0]]
    +输出:2
    +解释:翻转第一列的值之后,这两行都由相等的值组成。
    +
    + +

    示例 3:

    + +
    +输入:[[0,0,0],[0,0,1],[1,1,0]]
    +输出:2
    +解释:翻转前两列的值之后,后两行由相等的值组成。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= matrix.length <= 300
    2. +
    3. 1 <= matrix[i].length <= 300
    4. +
    5. 所有 matrix[i].length 都相等
    6. +
    7. matrix[i][j] 为 0 或 1
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1073.leetcode1073 Adding Two Negabinary Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1073.leetcode1073 Adding Two Negabinary Numbers-zh.md" new file mode 100644 index 00000000..8d02295a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1073.leetcode1073 Adding Two Negabinary Numbers-zh.md" @@ -0,0 +1,65 @@ +# [1073. 负二进制数相加](https://leetcode-cn.com/problems/adding-two-negabinary-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1073.Adding%20Two%20Negabinary%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给出基数为 -2 的两个数 arr1 和 arr2,返回两数相加的结果。

    + +

    数字以 数组形式 给出:数组由若干 0 和 1 组成,按最高有效位到最低有效位的顺序排列。例如,arr = [1,1,0,1] 表示数字 (-2)^3 + (-2)^2 + (-2)^0 = -3数组形式 的数字也同样不含前导零:以 arr 为例,这意味着要么 arr == [0],要么 arr[0] == 1

    + +

    返回相同表示形式的 arr1arr2 相加的结果。两数的表示形式为:不含前导零、由若干 0 和 1 组成的数组。

    + +

     

    + +

    示例:

    + +
    输入:arr1 = [1,1,1,1,1], arr2 = [1,0,1]
    +输出:[1,0,0,0,0]
    +解释:arr1 表示 11,arr2 表示 5,输出表示 16 。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= arr1.length <= 1000
    2. +
    3. 1 <= arr2.length <= 1000
    4. +
    5. arr1 和 arr2 都不含前导零
    6. +
    7. arr1[i] 为 0 或 1
    8. +
    9. arr2[i] 为 0 或 1
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1074.leetcode1074 Number of Submatrices That Sum to Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1074.leetcode1074 Number of Submatrices That Sum to Target-zh.md" new file mode 100644 index 00000000..a33a6a35 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1074.leetcode1074 Number of Submatrices That Sum to Target-zh.md" @@ -0,0 +1,71 @@ +# [1074. 元素和为目标值的子矩阵数量](https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1074.Number%20of%20Submatrices%20That%20Sum%20to%20Target/README_EN.md) + +## 题目描述 + + + +

    给出矩阵 matrix 和目标值 target,返回元素总和等于目标值的非空子矩阵的数量。

    + +

    子矩阵 x1, y1, x2, y2 是满足 x1 <= x <= x2 且 y1 <= y <= y2 的所有单元 matrix[x][y] 的集合。

    + +

    如果 (x1, y1, x2, y2) 和 (x1', y1', x2', y2') 两个子矩阵中部分坐标不同(如:x1 != x1'),那么这两个子矩阵也不同。

    + +

     

    + +

    示例 1:

    + +
    输入:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
    +输出:4
    +解释:四个只含 0 的 1x1 子矩阵。
    +
    + +

    示例 2:

    + +
    输入:matrix = [[1,-1],[-1,1]], target = 0
    +输出:5
    +解释:两个 1x2 子矩阵,加上两个 2x1 子矩阵,再加上一个 2x2 子矩阵。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= matrix.length <= 300
    2. +
    3. 1 <= matrix[0].length <= 300
    4. +
    5. -1000 <= matrix[i] <= 1000
    6. +
    7. -10^8 <= target <= 10^8
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1075.leetcode1075 Project Employees I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1075.leetcode1075 Project Employees I-zh.md" new file mode 100644 index 00000000..6d4829cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1075.leetcode1075 Project Employees I-zh.md" @@ -0,0 +1,86 @@ +# [1075. 项目员工 I](https://leetcode-cn.com/problems/project-employees-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1075.Project%20Employees%20I/README_EN.md) + +## 题目描述 + + + +

    项目表 Project: 

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| project_id  | int     |
    +| employee_id | int     |
    ++-------------+---------+
    +主键为 (project_id, employee_id)。
    +employee_id 是员工表 Employee 表的外键。
    +
    + +

    员工表 Employee

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| employee_id      | int     |
    +| name             | varchar |
    +| experience_years | int     |
    ++------------------+---------+
    +主键是 employee_id。
    +
    + +

     

    + +

    请写一个 SQL 语句,查询每一个项目中员工的 平均 工作年限,精确到小数点后两位

    + +

    查询结果的格式如下:

    + +
    +Project 表:
    ++-------------+-------------+
    +| project_id  | employee_id |
    ++-------------+-------------+
    +| 1           | 1           |
    +| 1           | 2           |
    +| 1           | 3           |
    +| 2           | 1           |
    +| 2           | 4           |
    ++-------------+-------------+
    +
    +Employee 表:
    ++-------------+--------+------------------+
    +| employee_id | name   | experience_years |
    ++-------------+--------+------------------+
    +| 1           | Khaled | 3                |
    +| 2           | Ali    | 2                |
    +| 3           | John   | 1                |
    +| 4           | Doe    | 2                |
    ++-------------+--------+------------------+
    +
    +Result 表:
    ++-------------+---------------+
    +| project_id  | average_years |
    ++-------------+---------------+
    +| 1           | 2.00          |
    +| 2           | 2.50          |
    ++-------------+---------------+
    +第一个项目中,员工的平均工作年限是 (3 + 2 + 1) / 3 = 2.00;第二个项目中,员工的平均工作年限是 (3 + 2) / 2 = 2.50
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1076.leetcode1076 Project Employees II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1076.leetcode1076 Project Employees II-zh.md" new file mode 100644 index 00000000..ff0ff011 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1076.leetcode1076 Project Employees II-zh.md" @@ -0,0 +1,80 @@ +# [1076. 项目员工II](https://leetcode-cn.com/problems/project-employees-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1076.Project%20Employees%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Project

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| project_id  | int     |
    +| employee_id | int     |
    ++-------------+---------+
    +主键为 (project_id, employee_id)。
    +employee_id 是员工表 Employee 表的外键。
    +
    + +

    Table: Employee

    + +
    +------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| employee_id      | int     |
    +| name             | varchar |
    +| experience_years | int     |
    ++------------------+---------+
    +主键是 employee_id。
    + +

     

    + +

    编写一个SQL查询,报告所有雇员最多的项目。

    + +

    查询结果格式如下所示:

    + +
    Project table:
    ++-------------+-------------+
    +| project_id  | employee_id |
    ++-------------+-------------+
    +| 1           | 1           |
    +| 1           | 2           |
    +| 1           | 3           |
    +| 2           | 1           |
    +| 2           | 4           |
    ++-------------+-------------+
    +
    +Employee table:
    ++-------------+--------+------------------+
    +| employee_id | name   | experience_years |
    ++-------------+--------+------------------+
    +| 1           | Khaled | 3                |
    +| 2           | Ali    | 2                |
    +| 3           | John   | 1                |
    +| 4           | Doe    | 2                |
    ++-------------+--------+------------------+
    +
    +Result table:
    ++-------------+
    +| project_id  |
    ++-------------+
    +| 1           |
    ++-------------+
    +第一个项目有3名员工,第二个项目有2名员工。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1077.leetcode1077 Project Employees III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1077.leetcode1077 Project Employees III-zh.md" new file mode 100644 index 00000000..5e9e50b3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1077.leetcode1077 Project Employees III-zh.md" @@ -0,0 +1,86 @@ +# [1077. 项目员工 III](https://leetcode-cn.com/problems/project-employees-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1077.Project%20Employees%20III/README_EN.md) + +## 题目描述 + + + +

    项目表 Project

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| project_id  | int     |
    +| employee_id | int     |
    ++-------------+---------+
    +(project_id, employee_id) 是这个表的主键
    +employee_id 是员工表 Employee 的外键
    +
    + +

    员工表 Employee

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| employee_id      | int     |
    +| name             | varchar |
    +| experience_years | int     |
    ++------------------+---------+
    +employee_id 是这个表的主键
    +
    + +

     

    + +

    写 一个 SQL 查询语句,报告在每一个项目中经验最丰富的雇员是谁。如果出现经验年数相同的情况,请报告所有具有最大经验年数的员工。

    + +

    查询结果格式在以下示例中:

    + +
    +Project 表:
    ++-------------+-------------+
    +| project_id  | employee_id |
    ++-------------+-------------+
    +| 1           | 1           |
    +| 1           | 2           |
    +| 1           | 3           |
    +| 2           | 1           |
    +| 2           | 4           |
    ++-------------+-------------+
    +
    +Employee 表:
    ++-------------+--------+------------------+
    +| employee_id | name   | experience_years |
    ++-------------+--------+------------------+
    +| 1           | Khaled | 3                |
    +| 2           | Ali    | 2                |
    +| 3           | John   | 3                |
    +| 4           | Doe    | 2                |
    ++-------------+--------+------------------+
    +
    +Result 表:
    ++-------------+---------------+
    +| project_id  | employee_id   |
    ++-------------+---------------+
    +| 1           | 1             |
    +| 1           | 3             |
    +| 2           | 1             |
    ++-------------+---------------+
    +employee_id 为 1 和 3 的员工在 project_id 为 1 的项目中拥有最丰富的经验。在 project_id 为 2 的项目中,employee_id 为 1 的员工拥有最丰富的经验。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1078.leetcode1078 Occurrences After Bigram-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1078.leetcode1078 Occurrences After Bigram-zh.md" new file mode 100644 index 00000000..6223a6c1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1078.leetcode1078 Occurrences After Bigram-zh.md" @@ -0,0 +1,67 @@ +# [1078. Bigram 分词](https://leetcode-cn.com/problems/occurrences-after-bigram) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1078.Occurrences%20After%20Bigram/README_EN.md) + +## 题目描述 + + + +

    给出第一个词 first 和第二个词 second,考虑在某些文本 text 中可能以 "first second third" 形式出现的情况,其中 second 紧随 first 出现,third 紧随 second 出现。

    + +

    对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。

    + +

     

    + +

    示例 1:

    + +
    输入:text = "alice is a good girl she is a good student", first = "a", second = "good"
    +输出:["girl","student"]
    +
    + +

    示例 2:

    + +
    输入:text = "we will we will rock you", first = "we", second = "will"
    +输出:["we","rock"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= text.length <= 1000
    2. +
    3. text 由一些用空格分隔的单词组成,每个单词都由小写英文字母组成
    4. +
    5. 1 <= first.length, second.length <= 10
    6. +
    7. first 和 second 由小写英文字母组成
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1079.leetcode1079 Letter Tile Possibilities-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1079.leetcode1079 Letter Tile Possibilities-zh.md" new file mode 100644 index 00000000..b5f298fe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1079.leetcode1079 Letter Tile Possibilities-zh.md" @@ -0,0 +1,66 @@ +# [1079. 活字印刷](https://leetcode-cn.com/problems/letter-tile-possibilities) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1079.Letter%20Tile%20Possibilities/README_EN.md) + +## 题目描述 + + + +

    你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。

    + +

    注意:本题中,每个活字字模只能使用一次。

    + +

     

    + +

    示例 1:

    + +
    输入:"AAB"
    +输出:8
    +解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。
    +
    + +

    示例 2:

    + +
    输入:"AAABBC"
    +输出:188
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= tiles.length <= 7
    2. +
    3. tiles 由大写英文字母组成
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1080.leetcode1080 Insufficient Nodes in Root to Leaf Paths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1080.leetcode1080 Insufficient Nodes in Root to Leaf Paths-zh.md" new file mode 100644 index 00000000..6506c388 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1080.leetcode1080 Insufficient Nodes in Root to Leaf Paths-zh.md" @@ -0,0 +1,79 @@ +# [1080. 根到叶路径上的不足节点](https://leetcode-cn.com/problems/insufficient-nodes-in-root-to-leaf-paths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1080.Insufficient%20Nodes%20in%20Root%20to%20Leaf%20Paths/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树的根 root,请你考虑它所有 从根到叶的路径:从根到任何叶的路径。(所谓一个叶子节点,就是一个没有子节点的节点)

    + +

    假如通过节点 node 的每种可能的 “根-叶” 路径上值的总和全都小于给定的 limit,则该节点被称之为「不足节点」,需要被删除。

    + +

    请你删除所有不足节点,并返回生成的二叉树的根。

    + +

     

    + +

    示例 1:

    + +
    
    +输入:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
    +
    +输出:[1,2,3,4,null,null,7,8,9,null,14]
    +
    + +

    示例 2:

    + +
    
    +输入:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
    +
    +输出:[5,4,8,11,null,17,4,7,null,null,null,5]
    + +

    示例 3:

    + +
    
    +输入:root = [5,-6,-6], limit = 0
    +输出:[]
    + +

     

    + +

    提示:

    + +
      +
    1. 给定的树有 1 到 5000 个节点
    2. +
    3. -10^5 <= node.val <= 10^5
    4. +
    5. -10^9 <= limit <= 10^9
    6. +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1081.leetcode1081 Smallest Subsequence of Distinct Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1081.leetcode1081 Smallest Subsequence of Distinct Characters-zh.md" new file mode 100644 index 00000000..1ae1fc70 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1081.leetcode1081 Smallest Subsequence of Distinct Characters-zh.md" @@ -0,0 +1,66 @@ +# [1081. 不同字符的最小子序列](https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1081.Smallest%20Subsequence%20of%20Distinct%20Characters/README_EN.md) + +## 题目描述 + + + +

    返回 s 字典序最小的子序列,该子序列包含 s 的所有不同字符,且只包含一次。

    + +

    注意:该题与 316 https://leetcode.com/problems/remove-duplicate-letters/ 相同

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "bcabc"
    +输出"abc"
    +
    + +

    示例 2:

    + +
    +输入:s = "cbacdcbc"
    +输出:"acdb"
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1082.leetcode1082 Sales Analysis I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1082.leetcode1082 Sales Analysis I-zh.md" new file mode 100644 index 00000000..32ec04f7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1082.leetcode1082 Sales Analysis I-zh.md" @@ -0,0 +1,84 @@ +# [1082. 销售分析 I ](https://leetcode-cn.com/problems/sales-analysis-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1082.Sales%20Analysis%20I/README_EN.md) + +## 题目描述 + + + +

    产品表:Product

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    +| unit_price   | int     |
    ++--------------+---------+
    +product_id 是这个表的主键.
    +
    + +

    销售表:Sales

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| seller_id   | int     |
    +| product_id  | int     |
    +| buyer_id    | int     |
    +| sale_date   | date    |
    +| quantity    | int     |
    +| price       | int     |
    ++------ ------+---------+
    +这个表没有主键,它可以有重复的行.
    +product_id 是 Product 表的外键.
    +
    + +

     

    + +

    编写一个 SQL 查询,查询总销售额最高的销售者,如果有并列的,就都展示出来。

    + +

    查询结果格式如下所示:

    + +
    Product 表:
    ++------------+--------------+------------+
    +| product_id | product_name | unit_price |
    ++------------+--------------+------------+
    +| 1          | S8           | 1000       |
    +| 2          | G4           | 800        |
    +| 3          | iPhone       | 1400       |
    ++------------+--------------+------------+
    +
    +Sales 表:
    ++-----------+------------+----------+------------+----------+-------+
    +| seller_id | product_id | buyer_id | sale_date  | quantity | price |
    ++-----------+------------+----------+------------+----------+-------+
    +| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
    +| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
    +| 2         | 2          | 3        | 2019-06-02 | 1        | 800   |
    +| 3         | 3          | 4        | 2019-05-13 | 2        | 2800  |
    ++-----------+------------+----------+------------+----------+-------+
    +
    +Result 表:
    ++-------------+
    +| seller_id   |
    ++-------------+
    +| 1           |
    +| 3           |
    ++-------------+
    +Id 为 1 和 3 的销售者,销售总金额都为最高的 2800。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1083.leetcode1083 Sales Analysis II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1083.leetcode1083 Sales Analysis II-zh.md" new file mode 100644 index 00000000..885dfdba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1083.leetcode1083 Sales Analysis II-zh.md" @@ -0,0 +1,83 @@ +# [1083. 销售分析 II](https://leetcode-cn.com/problems/sales-analysis-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1083.Sales%20Analysis%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Product

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    +| unit_price   | int     |
    ++--------------+---------+
    +product_id 是这张表的主键
    +
    + +

    Table: Sales

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| seller_id   | int     |
    +| product_id  | int     |
    +| buyer_id    | int     |
    +| sale_date   | date    |
    +| quantity    | int     |
    +| price       | int     |
    ++------ ------+---------+
    +这个表没有主键,它可以有重复的行.
    +product_id 是 Product 表的外键.
    +
    + +

    编写一个 SQL 查询,查询购买了 S8 手机却没有购买 iPhone 的买家。注意这里 S8 和 iPhone 是 Product 表中的产品。

    + +

    查询结果格式如下图表示:

    + +
    Product table:
    ++------------+--------------+------------+
    +| product_id | product_name | unit_price |
    ++------------+--------------+------------+
    +| 1          | S8           | 1000       |
    +| 2          | G4           | 800        |
    +| 3          | iPhone       | 1400       |
    ++------------+--------------+------------+
    +
    +Sales table:
    ++-----------+------------+----------+------------+----------+-------+
    +| seller_id | product_id | buyer_id | sale_date  | quantity | price |
    ++-----------+------------+----------+------------+----------+-------+
    +| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
    +| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
    +| 2         | 1          | 3        | 2019-06-02 | 1        | 800   |
    +| 3         | 3          | 3        | 2019-05-13 | 2        | 2800  |
    ++-----------+------------+----------+------------+----------+-------+
    +
    +Result table:
    ++-------------+
    +| buyer_id    |
    ++-------------+
    +| 1           |
    ++-------------+
    +id 为 1 的买家购买了一部 S8,但是却没有购买 iPhone,而 id 为 3 的买家却同时购买了这 2 部手机。
    +
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1084.leetcode1084 Sales Analysis III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1084.leetcode1084 Sales Analysis III-zh.md" new file mode 100644 index 00000000..b4496e7b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1084.leetcode1084 Sales Analysis III-zh.md" @@ -0,0 +1,82 @@ +# [1084. 销售分析III](https://leetcode-cn.com/problems/sales-analysis-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1084.Sales%20Analysis%20III/README_EN.md) + +## 题目描述 + + + +

    Table: Product

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| product_id   | int     |
    +| product_name | varchar |
    +| unit_price   | int     |
    ++--------------+---------+
    +product_id 是这个表的主键
    +
    + +

    Table: Sales

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| seller_id   | int     |
    +| product_id  | int     |
    +| buyer_id    | int     |
    +| sale_date   | date    |
    +| quantity    | int     |
    +| price       | int     |
    ++------ ------+---------+
    +这个表没有主键,它可以有重复的行.
    +product_id 是 Product 表的外键.
    + +

     

    + +

    编写一个SQL查询,报告2019年春季才售出的产品。即2019-01-012019-03-31(含)之间出售的商品。

    + +

    查询结果格式如下所示:

    + +
    Product table:
    ++------------+--------------+------------+
    +| product_id | product_name | unit_price |
    ++------------+--------------+------------+
    +| 1          | S8           | 1000       |
    +| 2          | G4           | 800        |
    +| 3          | iPhone       | 1400       |
    ++------------+--------------+------------+
    +
    +Sales table:
    ++-----------+------------+----------+------------+----------+-------+
    +| seller_id | product_id | buyer_id | sale_date  | quantity | price |
    ++-----------+------------+----------+------------+----------+-------+
    +| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
    +| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
    +| 2         | 2          | 3        | 2019-06-02 | 1        | 800   |
    +| 3         | 3          | 4        | 2019-05-13 | 2        | 2800  |
    ++-----------+------------+----------+------------+----------+-------+
    +
    +Result table:
    ++-------------+--------------+
    +| product_id  | product_name |
    ++-------------+--------------+
    +| 1           | S8           |
    ++-------------+--------------+
    +id为1的产品仅在2019年春季销售,其他两个产品在之后销售。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1085.leetcode1085 Sum of Digits in the Minimum Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1085.leetcode1085 Sum of Digits in the Minimum Number-zh.md" new file mode 100644 index 00000000..a129b94a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1085.leetcode1085 Sum of Digits in the Minimum Number-zh.md" @@ -0,0 +1,73 @@ +# [1085. 最小元素各数位之和](https://leetcode-cn.com/problems/sum-of-digits-in-the-minimum-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1085.Sum%20of%20Digits%20in%20the%20Minimum%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数的数组 A

    + +

    然后计算 S,使其等于数组 A 当中最小的那个元素各个数位上数字之和。

    + +

    最后,假如 S 所得计算结果是 奇数 ,返回 0 ;否则请返回 1。

    + +

     

    + +

    示例 1:

    + +
    +输入:[34,23,1,24,75,33,54,8]
    +输出:0
    +解释:
    +最小元素为 1 ,该元素各个数位上的数字之和 S = 1 ,是奇数所以答案为 0 。
    +
    + +

    示例 2:

    + +
    +输入:[99,77,33,66,55]
    +输出:1
    +解释:
    +最小元素为 33 ,该元素各个数位上的数字之和 S = 3 + 3 = 6 ,是偶数所以答案为 1 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= A.length <= 100
    • +
    • 1 <= A[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1086.leetcode1086 High Five-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1086.leetcode1086 High Five-zh.md" new file mode 100644 index 00000000..5ee12480 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1086.leetcode1086 High Five-zh.md" @@ -0,0 +1,125 @@ +# [1086. 前五科的均分](https://leetcode-cn.com/problems/high-five) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1086.High%20Five/README_EN.md) + +## 题目描述 + + + +

    给你一个不同学生的分数列表 items,其中 items[i] = [IDi, scorei] 表示 IDi 的学生的一科分数,你需要计算每个学生 最高的五科 成绩的 平均分

    + +

    返回答案 result 以数对数组形式给出其中 result[j] = [IDj, topFiveAveragej] 表示 IDj 的学生和他 最高的五科 成绩的 平均分result 需要按 IDj  递增的 顺序排列

    + +

    学生 最高的五科 成绩的 平均分 的计算方法是将最高的五科分数相加,然后用 整数除法 除以 5 。

    + +

     

    + +

    示例 1:

    + +
    +输入:items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
    +输出:[[1,87],[2,88]]
    +解释:
    +ID = 1 的学生分数为 91、92、60、65、87 和 100 。前五科的平均分 (100 + 92 + 91 + 87 + 65) / 5 = 87
    +ID = 2 的学生分数为 93、97、77、100 和 76 。前五科的平均分 (100 + 97 + 93 + 77 + 76) / 5 = 88.6,但是由于使用整数除法,结果转换为 88
    +
    + +

    示例 2:

    + +
    +输入:items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]
    +输出:[[1,100],[7,100]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= items.length <= 1000
    • +
    • items[i].length == 2
    • +
    • 1 <= IDi <= 1000
    • +
    • 0 <= scorei <= 100
    • +
    • 对于每个 IDi至少 存在五个分数
    • +
    + +## 解法 + + + +“桶排序 + 小根堆”实现。 + + + +### **Python3** + + + +```python +class Solution: + def highFive(self, items: List[List[int]]) -> List[List[int]]: + s = [None] * 101 + for i, score in items: + if s[i] is None: + s[i] = [] + s[i].append(score) + res = [] + for i, scores in enumerate(s): + if scores is None: + continue + avg = sum(heapq.nlargest(5, scores)) // 5 + res.append([i, avg]) + return res +``` + +### **Java** + + + +```java +class Solution { + public int[][] highFive(int[][] items) { + int size = 0; + PriorityQueue[] s = new PriorityQueue[101]; + int n = 5; + for (int[] item : items) { + int i = item[0], score = item[1]; + if (s[i] == null) { + ++size; + s[i] = new PriorityQueue<>(n); + } + s[i].offer(score); + if (s[i].size() > n) { + s[i].poll(); + } + } + int[][] res = new int[size][2]; + int j = 0; + for (int i = 0; i < 101; ++i) { + if (s[i] == null) { + continue; + } + int avg = sum(s[i]) / n; + res[j][0] = i; + res[j++][1] = avg; + } + return res; + } + + private int sum(PriorityQueue q) { + int s = 0; + while (!q.isEmpty()) { + s += q.poll(); + } + return s; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1087.leetcode1087 Brace Expansion-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1087.leetcode1087 Brace Expansion-zh.md" new file mode 100644 index 00000000..d88ee54b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1087.leetcode1087 Brace Expansion-zh.md" @@ -0,0 +1,72 @@ +# [1087. 花括号展开](https://leetcode-cn.com/problems/brace-expansion) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1087.Brace%20Expansion/README_EN.md) + +## 题目描述 + + + +

    我们用一个特殊的字符串 S 来表示一份单词列表,之所以能展开成为一个列表,是因为这个字符串 S 中存在一个叫做「选项」的概念:

    + +

    单词中的每个字母可能只有一个选项或存在多个备选项。如果只有一个选项,那么该字母按原样表示。

    + +

    如果存在多个选项,就会以花括号包裹来表示这些选项(使它们与其他字母分隔开),例如 "{a,b,c}" 表示 ["a", "b", "c"]

    + +

    例子:"{a,b,c}d{e,f}" 可以表示单词列表 ["ade", "adf", "bde", "bdf", "cde", "cdf"]

    + +

    请你按字典顺序,返回所有以这种方式形成的单词。

    + +

     

    + +

    示例 1:

    + +
    输入:"{a,b}c{d,e}f"
    +输出:["acdf","acef","bcdf","bcef"]
    +
    + +

    示例 2:

    + +
    输入:"abcd"
    +输出:["abcd"]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 50
    2. +
    3. 你可以假设题目中不存在嵌套的花括号
    4. +
    5. 在一对连续的花括号(开花括号与闭花括号)之间的所有字母都不会相同
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1088.leetcode1088 Confusing Number II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1088.leetcode1088 Confusing Number II-zh.md" new file mode 100644 index 00000000..aa0ad773 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1088.leetcode1088 Confusing Number II-zh.md" @@ -0,0 +1,80 @@ +# [1088. 易混淆数 II](https://leetcode-cn.com/problems/confusing-number-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1088.Confusing%20Number%20II/README_EN.md) + +## 题目描述 + + + +

    本题我们会将数字旋转 180° 来生成一个新的数字。

    + +

    比如 0、1、6、8、9 旋转 180° 以后,我们得到的新数字分别为 0、1、9、8、6。

    + +

    2、3、4、5、7 旋转 180° 后,是 无法 得到任何数字的。

    + +

    易混淆数(Confusing Number)指的是一个数字在整体旋转 180° 以后,能够得到一个和原来 不同 的数,且新数字的每一位都应该是有效的。(请注意,旋转后得到的新数字可能大于原数字)

    + +

    给出正整数 N,请你返回 1N 之间易混淆数字的数量。

    + +

     

    + +

    示例 1:

    + +
    输入:20
    +输出:6
    +解释:
    +易混淆数为 [6,9,10,16,18,19]。
    +6 转换为 9
    +9 转换为 6
    +10 转换为 01 也就是 1
    +16 转换为 91
    +18 转换为 81
    +19 转换为 61
    +
    + +

    示例 2:

    + +
    输入:100
    +输出:19
    +解释:
    +易混淆数为 [6,9,10,16,18,19,60,61,66,68,80,81,86,89,90,91,98,99,100]。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10^9
    2. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1089.leetcode1089 Duplicate Zeros-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1089.leetcode1089 Duplicate Zeros-zh.md" new file mode 100644 index 00000000..d78dcccb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1089.leetcode1089 Duplicate Zeros-zh.md" @@ -0,0 +1,69 @@ +# [1089. 复写零](https://leetcode-cn.com/problems/duplicate-zeros) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1089.Duplicate%20Zeros/README_EN.md) + +## 题目描述 + + + +

    给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。

    + +

    注意:请不要在超过该数组长度的位置写入元素。

    + +

    要求:请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。

    + +

     

    + +

    示例 1:

    + +
    输入:[1,0,2,3,0,4,5,0]
    +输出:null
    +解释:调用函数后,输入的数组将被修改为:[1,0,0,2,3,0,0,4]
    +
    + +

    示例 2:

    + +
    输入:[1,2,3]
    +输出:null
    +解释:调用函数后,输入的数组将被修改为:[1,2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= arr.length <= 10000
    2. +
    3. 0 <= arr[i] <= 9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1090.leetcode1090 Largest Values From Labels-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1090.leetcode1090 Largest Values From Labels-zh.md" new file mode 100644 index 00000000..4976f25e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1090.leetcode1090 Largest Values From Labels-zh.md" @@ -0,0 +1,89 @@ +# [1090. 受标签影响的最大值](https://leetcode-cn.com/problems/largest-values-from-labels) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1090.Largest%20Values%20From%20Labels/README_EN.md) + +## 题目描述 + + + +

    我们有一个项的集合,其中第 i 项的值为 values[i],标签为 labels[i]

    + +

    我们从这些项中选出一个子集 S,这样一来:

    + +
      +
    • |S| <= num_wanted
    • +
    • 对于任意的标签 L,子集 S 中标签为 L 的项的数目总满足 <= use_limit
    • +
    + +

    返回子集 S 的最大可能的 

    + +

     

    + +

    示例 1:

    + +
    输入:values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
    +输出:9
    +解释:选出的子集是第一项,第三项和第五项。
    +
    + +

    示例 2:

    + +
    输入:values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
    +输出:12
    +解释:选出的子集是第一项,第二项和第三项。
    +
    + +

    示例 3:

    + +
    输入:values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
    +输出:16
    +解释:选出的子集是第一项和第四项。
    +
    + +

    示例 4:

    + +
    输入:values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
    +输出:24
    +解释:选出的子集是第一项,第二项和第四项。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= values.length == labels.length <= 20000
    2. +
    3. 0 <= values[i], labels[i] <= 20000
    4. +
    5. 1 <= num_wanted, use_limit <= values.length
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1091.leetcode1091 Shortest Path in Binary Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1091.leetcode1091 Shortest Path in Binary Matrix-zh.md" new file mode 100644 index 00000000..02d5525a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1091.leetcode1091 Shortest Path in Binary Matrix-zh.md" @@ -0,0 +1,83 @@ +# [1091. 二进制矩阵中的最短路径](https://leetcode-cn.com/problems/shortest-path-in-binary-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1091.Shortest%20Path%20in%20Binary%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 n x n 的二进制矩阵 grid 中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1

    + +

    二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即,(0, 0))到 右下角 单元格(即,(n - 1, n - 1))的路径,该路径同时满足下述要求:

    + +
      +
    • 路径途经的所有单元格都的值都是 0
    • +
    • 路径中所有相邻的单元格应当在 8 个方向之一 上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
    • +
    + +

    畅通路径的长度 是该路径途经的单元格总数。

    + +

     

    + +

    示例 1:

    + +
    +输入:grid = [[0,1],[1,0]]
    +输出:2
    +
    + +

    示例 2:

    + +
    +输入:grid = [[0,0,0],[1,1,0],[1,1,0]]
    +输出:4
    +
    + +

    示例 3:

    + +
    +输入:grid = [[1,0,0],[1,1,0],[1,1,0]]
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 100
    • +
    • grid[i][j]01
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1092.leetcode1092 Shortest Common Supersequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1092.leetcode1092 Shortest Common Supersequence-zh.md" new file mode 100644 index 00000000..439d1131 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1092.leetcode1092 Shortest Common Supersequence-zh.md" @@ -0,0 +1,63 @@ +# [1092. 最短公共超序列](https://leetcode-cn.com/problems/shortest-common-supersequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1092.Shortest%20Common%20Supersequence/README_EN.md) + +## 题目描述 + + + +

    给出两个字符串 str1 和 str2,返回同时以 str1 和 str2 作为子序列的最短字符串。如果答案不止一个,则可以返回满足条件的任意一个答案。

    + +

    (如果从字符串 T 中删除一些字符(也可能不删除,并且选出的这些字符可以位于 T 中的 任意位置),可以得到字符串 S,那么 S 就是 T 的子序列)

    + +

     

    + +

    示例:

    + +
    输入:str1 = "abac", str2 = "cab"
    +输出:"cabac"
    +解释:
    +str1 = "abac" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 的第一个 "c"得到 "abac"。 
    +str2 = "cab" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 末尾的 "ac" 得到 "cab"。
    +最终我们给出的答案是满足上述属性的最短字符串。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= str1.length, str2.length <= 1000
    2. +
    3. str1 和 str2 都由小写英文字母组成。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1093.leetcode1093 Statistics from a Large Sample-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1093.leetcode1093 Statistics from a Large Sample-zh.md" new file mode 100644 index 00000000..80a922ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1093.leetcode1093 Statistics from a Large Sample-zh.md" @@ -0,0 +1,74 @@ +# [1093. 大样本统计](https://leetcode-cn.com/problems/statistics-from-a-large-sample) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1093.Statistics%20from%20a%20Large%20Sample/README_EN.md) + +## 题目描述 + + + +

    我们对 0 到 255 之间的整数进行采样,并将结果存储在数组 count 中:count[k] 就是整数 k 的采样个数。

    + +

    我们以 浮点数 数组的形式,分别返回样本的最小值、最大值、平均值、中位数和众数。其中,众数是保证唯一的。

    + +

    我们先来回顾一下中位数的知识:

    + +
      +
    • 如果样本中的元素有序,并且元素数量为奇数时,中位数为最中间的那个元素;
    • +
    • 如果样本中的元素有序,并且元素数量为偶数时,中位数为中间的两个元素的平均值。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    +输出:[1.00000,3.00000,2.37500,2.50000,3.00000]
    +
    + +

    示例 2:

    + +
    输入:count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    +输出:[1.00000,4.00000,2.18182,2.00000,1.00000]
    +
    + +

     

    + +

    提示:

    + +
      +
    1. count.length == 256
    2. +
    3. 1 <= sum(count) <= 10^9
    4. +
    5. 计数表示的众数是唯一的
    6. +
    7. 答案与真实值误差在 10^-5 以内就会被视为正确答案
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1094.leetcode1094 Car Pooling-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1094.leetcode1094 Car Pooling-zh.md" new file mode 100644 index 00000000..4b900f26 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1094.leetcode1094 Car Pooling-zh.md" @@ -0,0 +1,197 @@ +# [1094. 拼车](https://leetcode-cn.com/problems/car-pooling) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1094.Car%20Pooling/README_EN.md) + +## 题目描述 + + + +

    假设你是一位顺风车司机,车上最初有 capacity 个空座位可以用来载客。由于道路的限制,车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向,你可以将其想象为一个向量)。

    + +

    这儿有一份乘客行程计划表 trips[][],其中 trips[i] = [num_passengers, start_location, end_location] 包含了第 i 组乘客的行程信息:

    + +
      +
    • 必须接送的乘客数量;
    • +
    • 乘客的上车地点;
    • +
    • 以及乘客的下车地点。
    • +
    + +

    这些给出的地点位置是从你的 初始 出发位置向前行驶到这些地点所需的距离(它们一定在你的行驶方向上)。

    + +

    请你根据给出的行程计划表和车子的座位数,来判断你的车是否可以顺利完成接送所有乘客的任务(当且仅当你可以在所有给定的行程中接送所有乘客时,返回 true,否则请返回 false)。

    + +

     

    + +

    示例 1:

    + +
    输入:trips = [[2,1,5],[3,3,7]], capacity = 4
    +输出:false
    +
    + +

    示例 2:

    + +
    输入:trips = [[2,1,5],[3,3,7]], capacity = 5
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:trips = [[2,1,5],[3,5,7]], capacity = 3
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 你可以假设乘客会自觉遵守 “先下后上” 的良好素质
    • +
    • trips.length <= 1000
    • +
    • trips[i].length == 3
    • +
    • 1 <= trips[i][0] <= 100
    • +
    • 0 <= trips[i][1] < trips[i][2] <= 1000
    • +
    • 1 <= capacity <= 100000
    • +
    + + +## 解法 + + + +差分数组 + + + +### **Python3** + + + +```python +class Solution: + def carPooling(self, trips: List[List[int]], capacity: int) -> bool: + delta = [0] * 1001 + for num, start, end in trips: + delta[start] += num + delta[end] -= num + cur = 0 + for num in delta: + cur += num + if cur > capacity: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean carPooling(int[][] trips, int capacity) { + int[] delta = new int[1001]; + for (int[] trip : trips) { + int num = trip[0], start = trip[1], end = trip[2]; + delta[start] += num; + delta[end] -= num; + } + int cur = 0; + for (int num : delta) { + cur += num; + if (cur > capacity) { + return false; + } + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} trips + * @param {number} capacity + * @return {boolean} + */ + var carPooling = function(trips, capacity) { + let delta = new Array(); + for (let trip of trips) { + let [num, start, end] = trip; + delta[start] = (delta[start] || 0) + num; + delta[end] = (delta[end] || 0) - num; + } + let total = 0; + for (let i = 0; i < delta.length; i++) { + let cur = delta[i]; + if (cur == undefined) continue; + total += cur; + if (total > capacity) return false; + } + return true; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + bool carPooling(vector>& trips, int capacity) { + vector delta(1001); + for (auto &trip : trips) { + int num = trip[0], start = trip[1], end = trip[2]; + delta[start] += num; + delta[end] -= num; + } + int cur = 0; + for (auto &num : delta) { + cur += num; + if (cur > capacity) { + return false; + } + } + return true; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} trips + * @param {number} capacity + * @return {boolean} + */ + var carPooling = function(trips, capacity) { + let delta = new Array(); + for (let trip of trips) { + let [num, start, end] = trip; + delta[start] = (delta[start] || 0) + num; + delta[end] = (delta[end] || 0) - num; + } + let total = 0; + for (let i = 0; i < delta.length; i++) { + let cur = delta[i]; + if (cur == undefined) continue; + total += cur; + if (total > capacity) return false; + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1095.leetcode1095 Find in Mountain Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1095.leetcode1095 Find in Mountain Array-zh.md" new file mode 100644 index 00000000..c347d972 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1095.leetcode1095 Find in Mountain Array-zh.md" @@ -0,0 +1,102 @@ +# [1095. 山脉数组中查找目标值](https://leetcode-cn.com/problems/find-in-mountain-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1095.Find%20in%20Mountain%20Array/README_EN.md) + +## 题目描述 + + + +

    (这是一个 交互式问题 

    + +

    给你一个 山脉数组 mountainArr,请你返回能够使得 mountainArr.get(index) 等于 target 最小 的下标 index 值。

    + +

    如果不存在这样的下标 index,就请返回 -1

    + +

     

    + +

    何为山脉数组?如果数组 A 是一个山脉数组的话,那它满足如下条件:

    + +

    首先A.length >= 3

    + +

    其次,在 0 < i < A.length - 1 条件下,存在 i 使得:

    + +
      +
    • A[0] < A[1] < ... A[i-1] < A[i]
    • +
    • A[i] > A[i+1] > ... > A[A.length - 1]
    • +
    + +

     

    + +

    你将 不能直接访问该山脉数组,必须通过 MountainArray 接口来获取数据:

    + +
      +
    • MountainArray.get(k) - 会返回数组中索引为k 的元素(下标从 0 开始)
    • +
    • MountainArray.length() - 会返回该数组的长度
    • +
    + +

     

    + +

    注意:

    + +

    对 MountainArray.get 发起超过 100 次调用的提交将被视为错误答案。此外,任何试图规避判题系统的解决方案都将会导致比赛资格被取消。

    + +

    为了帮助大家更好地理解交互式问题,我们准备了一个样例 “答案”:https://leetcode-cn.com/playground/RKhe3ave,请注意这 不是一个正确答案

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    输入:array = [1,2,3,4,5,3,1], target = 3
    +输出:2
    +解释:3 在数组中出现了两次,下标分别为 2 和 5,我们返回最小的下标 2。
    + +

    示例 2:

    + +
    输入:array = [0,1,2,4,2,1], target = 3
    +输出:-1
    +解释:3 在数组中没有出现,返回 -1。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= mountain_arr.length() <= 10000
    • +
    • 0 <= target <= 10^9
    • +
    • 0 <= mountain_arr.get(index) <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1096.leetcode1096 Brace Expansion II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1096.leetcode1096 Brace Expansion II-zh.md" new file mode 100644 index 00000000..cf685cc5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1096.leetcode1096 Brace Expansion II-zh.md" @@ -0,0 +1,99 @@ +# [1096. 花括号展开 II](https://leetcode-cn.com/problems/brace-expansion-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1096.Brace%20Expansion%20II/README_EN.md) + +## 题目描述 + + + +

    如果你熟悉 Shell 编程,那么一定了解过花括号展开,它可以用来生成任意字符串。

    + +

    花括号展开的表达式可以看作一个由 花括号逗号小写英文字母 组成的字符串,定义下面几条语法规则:

    + +
      +
    • 如果只给出单一的元素 x,那么表达式表示的字符串就只有 "x"R(x) = {x} + +
        +
      • 例如,表达式 {"a"} 表示字符串 "a"
      • +
      • 而表达式 {"w"} 就表示字符串 "w"
      • +
      +
    • +
    • 当两个或多个表达式并列,以逗号分隔时,我们取这些表达式中元素的并集。R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ... +
        +
      • 例如,表达式 "{a,b,c}" 表示字符串 "a","b","c"
      • +
      • 而表达式 "{{a,b},{b,c}}" 也可以表示字符串 "a","b","c"
      • +
      +
    • +
    • 要是两个或多个表达式相接,中间没有隔开时,我们从这些表达式中各取一个元素依次连接形成字符串。R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)} +
        +
      • 例如,表达式 "{a,b}{c,d}" 表示字符串 "ac","ad","bc","bd"
      • +
      +
    • +
    • 表达式之间允许嵌套,单一元素与表达式的连接也是允许的。 +
        +
      • 例如,表达式 "a{b,c,d}" 表示字符串 "ab","ac","ad"​​​​​​
      • +
      • 例如,表达式 "a{b,c}{d,e}f{g,h}" 可以表示字符串 "abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"
      • +
      +
    • +
    + +

    给出表示基于给定语法规则的表达式 expression,返回它所表示的所有字符串组成的有序列表。

    + +

    假如你希望以「集合」的概念了解此题,也可以通过点击 “显示英文描述” 获取详情。

    + +

     

    + +

    示例 1:

    + +
    +输入:"{a,b}{c,{d,e}}"
    +输出:["ac","ad","ae","bc","bd","be"]
    + +

    示例 2:

    + +
    +输入:"{{a,z},a{b,c},{ab,z}}"
    +输出:["a","ab","ac","z"]
    +解释:输出中 不应 出现重复的组合结果。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= expression.length <= 50
    2. +
    3. expression[i]'{''}'',' 或小写英文字母组成
    4. +
    5. 给出的表达式 expression 用以表示一组基于题目描述中语法构造的字符串
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1097.leetcode1097 Game Play Analysis V-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1097.leetcode1097 Game Play Analysis V-zh.md" new file mode 100644 index 00000000..8300e319 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1097.leetcode1097 Game Play Analysis V-zh.md" @@ -0,0 +1,73 @@ +# [1097. 游戏玩法分析 V](https://leetcode-cn.com/problems/game-play-analysis-v) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1097.Game%20Play%20Analysis%20V/README_EN.md) + +## 题目描述 + + + +

    Activity 活动记录表

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| player_id    | int     |
    +| device_id    | int     |
    +| event_date   | date    |
    +| games_played | int     |
    ++--------------+---------+
    +(player_id,event_date)是此表的主键
    +这张表显示了某些游戏的玩家的活动情况
    +每一行表示一个玩家的记录,在某一天使用某个设备注销之前,登录并玩了很多游戏(可能是 0)
    +
    + +

     

    + +

    玩家的 安装日期 定义为该玩家的第一个登录日。

    + +

    玩家的 第一天留存率 定义为:假定安装日期为 X 的玩家的数量为 N ,其中在 X 之后的某一天重新登录的玩家数量为 MM/N 就是第一天留存率,四舍五入到小数点后两位

    + +

    编写一个 SQL 查询,报告所有安装日期、当天安装游戏的玩家数量和玩家的第一天留存率。

    + +

     

    + +

    查询结果格式如下所示:

    + +
    +Activity 表:
    ++-----------+-----------+------------+--------------+
    +| player_id | device_id | event_date | games_played |
    ++-----------+-----------+------------+--------------+
    +| 1         | 2         | 2016-03-01 | 5            |
    +| 1         | 2         | 2016-03-02 | 6            |
    +| 2         | 3         | 2017-06-25 | 1            |
    +| 3         | 1         | 2016-03-01 | 0            |
    +| 3         | 4         | 2016-07-03 | 5            |
    ++-----------+-----------+------------+--------------+
    +
    +Result 表:
    ++------------+----------+----------------+
    +| install_dt | installs | Day1_retention |
    ++------------+----------+----------------+
    +| 2016-03-01 | 2        | 0.50           |
    +| 2017-06-25 | 1        | 0.00           |
    ++------------+----------+----------------+
    +玩家 1 和 3 在 2016-03-01 安装了游戏,但只有玩家 1 在 2016-03-02 重新登录,所以 2016-03-01 的第一天留存率是 1/2=0.50
    +玩家 2 在 2017-06-25 安装了游戏,但在 2017-06-26 没有重新登录,因此 2017-06-25 的第一天留存率为 0/1=0.00
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1098.leetcode1098 Unpopular Books-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1098.leetcode1098 Unpopular Books-zh.md" new file mode 100644 index 00000000..11ddac69 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1098.leetcode1098 Unpopular Books-zh.md" @@ -0,0 +1,108 @@ +# [1098. 小众书籍](https://leetcode-cn.com/problems/unpopular-books) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1098.Unpopular%20Books/README_EN.md) + +## 题目描述 + + + +

    书籍表 Books

    + +
    +----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| book_id        | int     |
    +| name           | varchar |
    +| available_from | date    |
    ++----------------+---------+
    +book_id 是这个表的主键。
    +
    + +

    订单表 Orders

    + +
    +----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| order_id       | int     |
    +| book_id        | int     |
    +| quantity       | int     |
    +| dispatch_date  | date    |
    ++----------------+---------+
    +order_id 是这个表的主键。
    +book_id  是 Books 表的外键。
    +
    + +

     

    + +

    你需要写一段 SQL 命令,筛选出过去一年中订单总量 少于10本 的 书籍 

    + +

    注意:不考虑 上架(available from)距今 不满一个月 的书籍。并且 假设今天是 2019-06-23 

    + +

     

    + +

    下面是样例输出结果:

    + +
    Books 表:
    ++---------+--------------------+----------------+
    +| book_id | name               | available_from |
    ++---------+--------------------+----------------+
    +| 1       | "Kalila And Demna" | 2010-01-01     |
    +| 2       | "28 Letters"       | 2012-05-12     |
    +| 3       | "The Hobbit"       | 2019-06-10     |
    +| 4       | "13 Reasons Why"   | 2019-06-01     |
    +| 5       | "The Hunger Games" | 2008-09-21     |
    ++---------+--------------------+----------------+
    +
    +Orders 表:
    ++----------+---------+----------+---------------+
    +| order_id | book_id | quantity | dispatch_date |
    ++----------+---------+----------+---------------+
    +| 1        | 1       | 2        | 2018-07-26    |
    +| 2        | 1       | 1        | 2018-11-05    |
    +| 3        | 3       | 8        | 2019-06-11    |
    +| 4        | 4       | 6        | 2019-06-05    |
    +| 5        | 4       | 5        | 2019-06-20    |
    +| 6        | 5       | 9        | 2009-02-02    |
    +| 7        | 5       | 8        | 2010-04-13    |
    ++----------+---------+----------+---------------+
    +
    +Result 表:
    ++-----------+--------------------+
    +| book_id   | name               |
    ++-----------+--------------------+
    +| 1         | "Kalila And Demna" |
    +| 2         | "28 Letters"       |
    +| 5         | "The Hunger Games" |
    ++-----------+--------------------+
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1099.leetcode1099 Two Sum Less Than K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1099.leetcode1099 Two Sum Less Than K-zh.md" new file mode 100644 index 00000000..833f589d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1099.leetcode1099 Two Sum Less Than K-zh.md" @@ -0,0 +1,122 @@ +# [1099. 小于 K 的两数之和](https://leetcode-cn.com/problems/two-sum-less-than-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1000-1099/1099.Two%20Sum%20Less%20Than%20K/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和整数 k ,返回最大和 sum ,满足存在 i < j 使得 nums[i] + nums[j] = sumsum < k 。如果没有满足此等式的 i,j 存在,则返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [34,23,1,24,75,33,54,8], k = 60
    +输出:58
    +解释:
    +34 和 24 相加得到 58,58 小于 60,满足题意。
    +
    + +

    示例 2:

    + +
    +输入:nums = [10,20,30], k = 15
    +输出:-1
    +解释:
    +我们无法找到和小于 15 的两个元素。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 1000
    • +
    • 1 <= k <= 2000
    • +
    + + +## 解法 + + + +先进行排序,再用双指针 `low` 、`high` 分别指向排序数组的首尾,遍历获取满足条件的和 `nums[low] + nums[high]` 并求最大和。 + + + +### **Python3** + + + +```python +class Solution: + def twoSumLessThanK(self, nums: List[int], k: int) -> int: + nums.sort() + low, high = 0, len(nums) - 1 + res = -1 + while low < high: + val = nums[low] + nums[high] + if val < k: + res = max(res, val) + low += 1 + else: + high -= 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int twoSumLessThanK(int[] nums, int k) { + Arrays.sort(nums); + int low = 0, high = nums.length - 1; + int res = -1; + while (low < high) { + int val = nums[low] + nums[high]; + if (val < k) { + res = Math.max(res, val); + ++low; + } else { + --high; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int twoSumLessThanK(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int low = 0, high = nums.size() - 1; + int res = -1; + while (low < high) { + int val = nums[low] + nums[high]; + if (val < k) { + res = max(res, val); + ++low; + } else { + --high; + } + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1100.leetcode1100 Find K-Length Substrings With No Repeated Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1100.leetcode1100 Find K-Length Substrings With No Repeated Characters-zh.md" new file mode 100644 index 00000000..49f9819b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1100.leetcode1100 Find K-Length Substrings With No Repeated Characters-zh.md" @@ -0,0 +1,67 @@ +# [1100. 长度为 K 的无重复字符子串](https://leetcode-cn.com/problems/find-k-length-substrings-with-no-repeated-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1100.Find%20K-Length%20Substrings%20With%20No%20Repeated%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 S,找出所有长度为 K 且不含重复字符的子串,请你返回全部满足要求的子串的 数目

    + +

     

    + +

    示例 1:

    + +
    输入:S = "havefunonleetcode", K = 5
    +输出:6
    +解释:
    +这里有 6 个满足题意的子串,分别是:'havef','avefu','vefun','efuno','etcod','tcode'。
    +
    + +

    示例 2:

    + +
    输入:S = "home", K = 5
    +输出:0
    +解释:
    +注意:K 可能会大于 S 的长度。在这种情况下,就无法找到任何长度为 K 的子串。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 10^4
    2. +
    3. S 中的所有字符均为小写英文字母
    4. +
    5. 1 <= K <= 10^4
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1101.leetcode1101 The Earliest Moment When Everyone Become Friends-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1101.leetcode1101 The Earliest Moment When Everyone Become Friends-zh.md" new file mode 100644 index 00000000..15850308 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1101.leetcode1101 The Earliest Moment When Everyone Become Friends-zh.md" @@ -0,0 +1,77 @@ +# [1101. 彼此熟识的最早时间](https://leetcode-cn.com/problems/the-earliest-moment-when-everyone-become-friends) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1101.The%20Earliest%20Moment%20When%20Everyone%20Become%20Friends/README_EN.md) + +## 题目描述 + + + +

    在一个社交圈子当中,有 N 个人。每个人都有一个从 0 到 N-1 唯一的 id 编号。

    + +

    我们有一份日志列表 logs,其中每条记录都包含一个非负整数的时间戳,以及分属两个人的不同 id,logs[i] = [timestamp, id_A, id_B]

    + +

    每条日志标识出两个人成为好友的时间,友谊是相互的:如果 A 和 B 是好友,那么 B 和 A 也是好友。

    + +

    如果 A 是 B 的好友,或者 A 是 B 的好友的好友,那么就可以认为 A 也与 B 熟识。

    + +

    返回圈子里所有人之间都熟识的最早时间。如果找不到最早时间,就返回 -1

    + +

     

    + +

    示例:

    + +
    输入:logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], N = 6
    +输出:20190301
    +解释:
    +第一次结交发生在 timestamp = 20190101,0 和 1 成为好友,社交朋友圈如下 [0,1], [2], [3], [4], [5]。
    +第二次结交发生在 timestamp = 20190104,3 和 4 成为好友,社交朋友圈如下 [0,1], [2], [3,4], [5].
    +第三次结交发生在 timestamp = 20190107,2 和 3 成为好友,社交朋友圈如下 [0,1], [2,3,4], [5].
    +第四次结交发生在 timestamp = 20190211,1 和 5 成为好友,社交朋友圈如下 [0,1,5], [2,3,4].
    +第五次结交发生在 timestamp = 20190224,2 和 4 已经是好友了。
    +第六次结交发生在 timestamp = 20190301,0 和 3 成为好友,大家都互相熟识了。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 100
    2. +
    3. 1 <= logs.length <= 10^4
    4. +
    5. 0 <= logs[i][0] <= 10^9
    6. +
    7. 0 <= logs[i][1], logs[i][2] <= N - 1
    8. +
    9. 保证 logs[i][0] 中的所有时间戳都不同
    10. +
    11. Logs 不一定按某一标准排序
    12. +
    13. logs[i][1] != logs[i][2]
    14. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1102.leetcode1102 Path With Maximum Minimum Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1102.leetcode1102 Path With Maximum Minimum Value-zh.md" new file mode 100644 index 00000000..54bedda6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1102.leetcode1102 Path With Maximum Minimum Value-zh.md" @@ -0,0 +1,81 @@ +# [1102. 得分最高的路径](https://leetcode-cn.com/problems/path-with-maximum-minimum-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1102.Path%20With%20Maximum%20Minimum%20Value/README_EN.md) + +## 题目描述 + + + +

    给你一个 R 行 C 列的整数矩阵 A。矩阵上的路径从 [0,0] 开始,在 [R-1,C-1] 结束。

    + +

    路径沿四个基本方向(上、下、左、右)展开,从一个已访问单元格移动到任一相邻的未访问单元格。

    + +

    路径的得分是该路径上的 最小 值。例如,路径 8 →  4 →  5 →  9 的值为 4 。

    + +

    找出所有路径中得分 最高 的那条路径,返回其 得分

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[[5,4,5],[1,2,6],[7,4,6]]
    +输出:4
    +解释: 
    +得分最高的路径用黄色突出显示。 
    +
    + +

    示例 2:

    + +

    + +
    输入:[[2,2,1,2,2,2],[1,2,2,2,1,2]]
    +输出:2
    + +

    示例 3:

    + +

    + +
    输入:[[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]
    +输出:3
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= R, C <= 100
    2. +
    3. 0 <= A[i][j] <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1103.leetcode1103 Distribute Candies to People-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1103.leetcode1103 Distribute Candies to People-zh.md" new file mode 100644 index 00000000..2e241825 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1103.leetcode1103 Distribute Candies to People-zh.md" @@ -0,0 +1,83 @@ +# [1103. 分糖果 II](https://leetcode-cn.com/problems/distribute-candies-to-people) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1103.Distribute%20Candies%20to%20People/README_EN.md) + +## 题目描述 + + + +

    排排坐,分糖果。

    + +

    我们买了一些糖果 candies,打算把它们分给排好队的 n = num_people 个小朋友。

    + +

    给第一个小朋友 1 颗糖果,第二个小朋友 2 颗,依此类推,直到给最后一个小朋友 n 颗糖果。

    + +

    然后,我们再回到队伍的起点,给第一个小朋友 n + 1 颗糖果,第二个小朋友 n + 2 颗,依此类推,直到给最后一个小朋友 2 * n 颗糖果。

    + +

    重复上述过程(每次都比上一次多给出一颗糖果,当到达队伍终点后再次从队伍起点开始),直到我们分完所有的糖果。注意,就算我们手中的剩下糖果数不够(不比前一次发出的糖果多),这些糖果也会全部发给当前的小朋友。

    + +

    返回一个长度为 num_people、元素之和为 candies 的数组,以表示糖果的最终分发情况(即 ans[i] 表示第 i 个小朋友分到的糖果数)。

    + +

     

    + +

    示例 1:

    + +
    输入:candies = 7, num_people = 4
    +输出:[1,2,3,1]
    +解释:
    +第一次,ans[0] += 1,数组变为 [1,0,0,0]。
    +第二次,ans[1] += 2,数组变为 [1,2,0,0]。
    +第三次,ans[2] += 3,数组变为 [1,2,3,0]。
    +第四次,ans[3] += 1(因为此时只剩下 1 颗糖果),最终数组变为 [1,2,3,1]。
    +
    + +

    示例 2:

    + +
    输入:candies = 10, num_people = 3
    +输出:[5,2,3]
    +解释:
    +第一次,ans[0] += 1,数组变为 [1,0,0]。
    +第二次,ans[1] += 2,数组变为 [1,2,0]。
    +第三次,ans[2] += 3,数组变为 [1,2,3]。
    +第四次,ans[0] += 4,最终数组变为 [5,2,3]。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= candies <= 10^9
    • +
    • 1 <= num_people <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1104.leetcode1104 Path In Zigzag Labelled Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1104.leetcode1104 Path In Zigzag Labelled Binary Tree-zh.md" new file mode 100644 index 00000000..b9c17627 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1104.leetcode1104 Path In Zigzag Labelled Binary Tree-zh.md" @@ -0,0 +1,70 @@ +# [1104. 二叉树寻路](https://leetcode-cn.com/problems/path-in-zigzag-labelled-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1104.Path%20In%20Zigzag%20Labelled%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    在一棵无限的二叉树上,每个节点都有两个子节点,树中的节点 逐行 依次按 “之” 字形进行标记。

    + +

    如下图所示,在奇数行(即,第一行、第三行、第五行……)中,按从左到右的顺序进行标记;

    + +

    而偶数行(即,第二行、第四行、第六行……)中,按从右到左的顺序进行标记。

    + +

    + +

    给你树上某一个节点的标号 label,请你返回从根节点到该标号为 label 节点的路径,该路径是由途经的节点标号所组成的。

    + +

     

    + +

    示例 1:

    + +
    输入:label = 14
    +输出:[1,3,4,14]
    +
    + +

    示例 2:

    + +
    输入:label = 26
    +输出:[1,2,6,10,26]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= label <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1105.leetcode1105 Filling Bookcase Shelves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1105.leetcode1105 Filling Bookcase Shelves-zh.md" new file mode 100644 index 00000000..78f0e7e4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1105.leetcode1105 Filling Bookcase Shelves-zh.md" @@ -0,0 +1,75 @@ +# [1105. 填充书架](https://leetcode-cn.com/problems/filling-bookcase-shelves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1105.Filling%20Bookcase%20Shelves/README_EN.md) + +## 题目描述 + + + +

    附近的家居城促销,你买回了一直心仪的可调节书架,打算把自己的书都整理到新的书架上。

    + +

    你把要摆放的书 books 都整理好,叠成一摞:从上往下,第 i 本书的厚度为 books[i][0],高度为 books[i][1]

    + +

    按顺序 将这些书摆放到总宽度为 shelf_width 的书架上。

    + +

    先选几本书放在书架上(它们的厚度之和小于等于书架的宽度 shelf_width),然后再建一层书架。重复这个过程,直到把所有的书都放在书架上。

    + +

    需要注意的是,在上述过程的每个步骤中,摆放书的顺序与你整理好的顺序相同。 例如,如果这里有 5 本书,那么可能的一种摆放情况是:第一和第二本书放在第一层书架上,第三本书放在第二层书架上,第四和第五本书放在最后一层书架上。

    + +

    每一层所摆放的书的最大高度就是这一层书架的层高,书架整体的高度为各层高之和。

    + +

    以这种方式布置书架,返回书架整体可能的最小高度。

    + +

     

    + +

    示例:

    + +

    + +
    输入:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4
    +输出:6
    +解释:
    +3 层书架的高度和为 1 + 3 + 2 = 6 。
    +第 2 本书不必放在第一层书架上。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= books.length <= 1000
    • +
    • 1 <= books[i][0] <= shelf_width <= 1000
    • +
    • 1 <= books[i][1] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1106.leetcode1106 Parsing A Boolean Expression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1106.leetcode1106 Parsing A Boolean Expression-zh.md" new file mode 100644 index 00000000..3bbc6d37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1106.leetcode1106 Parsing A Boolean Expression-zh.md" @@ -0,0 +1,86 @@ +# [1106. 解析布尔表达式](https://leetcode-cn.com/problems/parsing-a-boolean-expression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1106.Parsing%20A%20Boolean%20Expression/README_EN.md) + +## 题目描述 + + + +

    给你一个以字符串形式表述的 布尔表达式(boolean) expression,返回该式的运算结果。

    + +

    有效的表达式需遵循以下约定:

    + +
      +
    • "t",运算结果为 True
    • +
    • "f",运算结果为 False
    • +
    • "!(expr)",运算过程为对内部表达式 expr 进行逻辑 非的运算(NOT)
    • +
    • "&(expr1,expr2,...)",运算过程为对 2 个或以上内部表达式 expr1, expr2, ... 进行逻辑 与的运算(AND)
    • +
    • "|(expr1,expr2,...)",运算过程为对 2 个或以上内部表达式 expr1, expr2, ... 进行逻辑 或的运算(OR)
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:expression = "!(f)"
    +输出:true
    +
    + +

    示例 2:

    + +
    输入:expression = "|(f,t)"
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:expression = "&(t,f)"
    +输出:false
    +
    + +

    示例 4:

    + +
    输入:expression = "|(&(t,f,t),!(t))"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= expression.length <= 20000
    • +
    • expression[i]{'(', ')', '&', '|', '!', 't', 'f', ','} 中的字符组成。
    • +
    • expression 是以上述形式给出的有效表达式,表示一个布尔值。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1107.leetcode1107 New Users Daily Count-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1107.leetcode1107 New Users Daily Count-zh.md" new file mode 100644 index 00000000..c0add8b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1107.leetcode1107 New Users Daily Count-zh.md" @@ -0,0 +1,73 @@ +# [1107. 每日新用户统计](https://leetcode-cn.com/problems/new-users-daily-count) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1107.New%20Users%20Daily%20Count/README_EN.md) + +## 题目描述 + + + +

    Traffic 表:

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| activity      | enum    |
    +| activity_date | date    |
    ++---------------+---------+
    +该表没有主键,它可能有重复的行。
    +activity 列是 ENUM 类型,可能取 ('login', 'logout', 'jobs', 'groups', 'homepage') 几个值之一。
    +
    + +

     

    + +

    编写一个 SQL 查询,以查询从今天起最多 90 天内,每个日期该日期首次登录的用户数。假设今天是 2019-06-30.

    + +

    查询结果格式如下例所示:

    + +
    Traffic 表:
    ++---------+----------+---------------+
    +| user_id | activity | activity_date |
    ++---------+----------+---------------+
    +| 1       | login    | 2019-05-01    |
    +| 1       | homepage | 2019-05-01    |
    +| 1       | logout   | 2019-05-01    |
    +| 2       | login    | 2019-06-21    |
    +| 2       | logout   | 2019-06-21    |
    +| 3       | login    | 2019-01-01    |
    +| 3       | jobs     | 2019-01-01    |
    +| 3       | logout   | 2019-01-01    |
    +| 4       | login    | 2019-06-21    |
    +| 4       | groups   | 2019-06-21    |
    +| 4       | logout   | 2019-06-21    |
    +| 5       | login    | 2019-03-01    |
    +| 5       | logout   | 2019-03-01    |
    +| 5       | login    | 2019-06-21    |
    +| 5       | logout   | 2019-06-21    |
    ++---------+----------+---------------+
    +
    +Result 表:
    ++------------+-------------+
    +| login_date | user_count  |
    ++------------+-------------+
    +| 2019-05-01 | 1           |
    +| 2019-06-21 | 2           |
    ++------------+-------------+
    +请注意,我们只关心用户数非零的日期.
    +ID 为 5 的用户第一次登陆于 2019-03-01,因此他不算在 2019-06-21 的的统计内。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1108.leetcode1108 Defanging an IP Address-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1108.leetcode1108 Defanging an IP Address-zh.md" new file mode 100644 index 00000000..e00256ea --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1108.leetcode1108 Defanging an IP Address-zh.md" @@ -0,0 +1,64 @@ +# [1108. IP 地址无效化](https://leetcode-cn.com/problems/defanging-an-ip-address) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1108.Defanging%20an%20IP%20Address/README_EN.md) + +## 题目描述 + + + +

    给你一个有效的 IPv4 地址 address,返回这个 IP 地址的无效化版本。

    + +

    所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 "."

    + +

     

    + +

    示例 1:

    + +
    输入:address = "1.1.1.1"
    +输出:"1[.]1[.]1[.]1"
    +
    + +

    示例 2:

    + +
    输入:address = "255.100.50.0"
    +输出:"255[.]100[.]50[.]0"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给出的 address 是一个有效的 IPv4 地址
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1109.leetcode1109 Corporate Flight Bookings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1109.leetcode1109 Corporate Flight Bookings-zh.md" new file mode 100644 index 00000000..d1c9c97f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1109.leetcode1109 Corporate Flight Bookings-zh.md" @@ -0,0 +1,181 @@ +# [1109. 航班预订统计](https://leetcode-cn.com/problems/corporate-flight-bookings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1109.Corporate%20Flight%20Bookings/README_EN.md) + +## 题目描述 + + + +

    这里有 n 个航班,它们分别从 1n 进行编号。

    + +

    有一份航班预订表 bookings ,表中第 i 条预订记录 bookings[i] = [firsti, lasti, seatsi] 意味着在从 firsti 到 lasti包含 firstilasti )的 每个航班 上预订了 seatsi 个座位。

    + +

    请你返回一个长度为 n 的数组 answer,其中 answer[i] 是航班 i 上预订的座位总数。

    + +

     

    + +

    示例 1:

    + +
    +输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
    +输出:[10,55,45,25,25]
    +解释:
    +航班编号        1   2   3   4   5
    +预订记录 1 :   10  10
    +预订记录 2 :       20  20
    +预订记录 3 :       25  25  25  25
    +总座位数:      10  55  45  25  25
    +因此,answer = [10,55,45,25,25]
    +
    + +

    示例 2:

    + +
    +输入:bookings = [[1,2,10],[2,2,15]], n = 2
    +输出:[10,25]
    +解释:
    +航班编号        1   2
    +预订记录 1 :   10  10
    +预订记录 2 :       15
    +总座位数:      10  25
    +因此,answer = [10,25]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 2 * 104
    • +
    • 1 <= bookings.length <= 2 * 104
    • +
    • bookings[i].length == 3
    • +
    • 1 <= firsti <= lasti <= n
    • +
    • 1 <= seatsi <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + delta = [0] * n + for first, last, seats in bookings: + delta[first - 1] += seats + if last < n: + delta[last] -= seats + for i in range(n - 1): + delta[i + 1] += delta[i] + return delta +``` + +### **Java** + + + +```java +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] delta = new int[n]; + for (int[] booking : bookings) { + int first = booking[0], last = booking[1], seats = booking[2]; + delta[first - 1] += seats; + if (last < n) { + delta[last] -= seats; + } + } + for (int i = 0; i < n - 1; ++i) { + delta[i + 1] += delta[i]; + } + return delta; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} bookings + * @param {number} n + * @return {number[]} + */ +var corpFlightBookings = function(bookings, n) { + let delta = new Array(n).fill(0); + for (let book of bookings) { + let [start, end, num] = book; + start -= 1; + delta[start] += num; + if (end != n) { + delta[end] -= num; + } + } + for (let i = 1; i < n; i++) { + delta[i] += delta[i - 1]; + } + return delta; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + vector delta(n); + for (auto &booking : bookings) { + int first = booking[0], last = booking[1], seats = booking[2]; + delta[first - 1] += seats; + if (last < n) { + delta[last] -= seats; + } + } + for (int i = 0; i < n - 1; ++i) { + delta[i + 1] += delta[i]; + } + return delta; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} bookings + * @param {number} n + * @return {number[]} + */ +var corpFlightBookings = function(bookings, n) { + let delta = new Array(n).fill(0); + for (let book of bookings) { + let [start, end, num] = book; + start -= 1; + delta[start] += num; + if (end != n) { + delta[end] -= num; + } + } + for (let i = 1; i < n; i++) { + delta[i] += delta[i - 1]; + } + return delta; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1110.leetcode1110 Delete Nodes And Return Forest-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1110.leetcode1110 Delete Nodes And Return Forest-zh.md" new file mode 100644 index 00000000..fb88432b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1110.leetcode1110 Delete Nodes And Return Forest-zh.md" @@ -0,0 +1,65 @@ +# [1110. 删点成林](https://leetcode-cn.com/problems/delete-nodes-and-return-forest) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1110.Delete%20Nodes%20And%20Return%20Forest/README_EN.md) + +## 题目描述 + + + +

    给出二叉树的根节点 root,树上每个节点都有一个不同的值。

    + +

    如果节点值在 to_delete 中出现,我们就把该节点从树上删去,最后得到一个森林(一些不相交的树构成的集合)。

    + +

    返回森林中的每棵树。你可以按任意顺序组织答案。

    + +

     

    + +

    示例:

    + +

    + +
    输入:root = [1,2,3,4,5,6,7], to_delete = [3,5]
    +输出:[[1,2,null,4],[6],[7]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数最大为 1000
    • +
    • 每个节点都有一个介于 1 到 1000 之间的值,且各不相同。
    • +
    • to_delete.length <= 1000
    • +
    • to_delete 包含一些从 1 到 1000、各不相同的值。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1111.leetcode1111 Maximum Nesting Depth of Two Valid Parentheses Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1111.leetcode1111 Maximum Nesting Depth of Two Valid Parentheses Strings-zh.md" new file mode 100644 index 00000000..1c5ec0ea --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1111.leetcode1111 Maximum Nesting Depth of Two Valid Parentheses Strings-zh.md" @@ -0,0 +1,114 @@ +# [1111. 有效括号的嵌套深度](https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1111.Maximum%20Nesting%20Depth%20of%20Two%20Valid%20Parentheses%20Strings/README_EN.md) + +## 题目描述 + + + +

    有效括号字符串 定义:对于每个左括号,都能找到与之对应的右括号,反之亦然。详情参见题末「有效括号字符串」部分。

    + +

    嵌套深度 depth 定义:即有效括号字符串嵌套的层数,depth(A) 表示有效括号字符串 A 的嵌套深度。详情参见题末「嵌套深度」部分。

    + +

    有效括号字符串类型与对应的嵌套深度计算方法如下图所示:

    + +

    + +

     

    + +

    给你一个「有效括号字符串」 seq,请你将其分成两个不相交的有效括号字符串,A 和 B,并使这两个字符串的深度最小。

    + +
      +
    • 不相交:每个 seq[i] 只能分给 AB 二者中的一个,不能既属于 A 也属于 B
    • +
    • AB 中的元素在原字符串中可以不连续。
    • +
    • A.length + B.length = seq.length
    • +
    • 深度最小:max(depth(A), depth(B)) 的可能取值最小。 
    • +
    + +

    划分方案用一个长度为 seq.length 的答案数组 answer 表示,编码规则如下:

    + +
      +
    • answer[i] = 0seq[i] 分给 A
    • +
    • answer[i] = 1seq[i] 分给 B
    • +
    + +

    如果存在多个满足要求的答案,只需返回其中任意 一个 即可。

    + +

     

    + +

    示例 1:

    + +
    输入:seq = "(()())"
    +输出:[0,1,1,1,1,0]
    +
    + +

    示例 2:

    + +
    输入:seq = "()(())()"
    +输出:[0,0,0,1,1,0,1,1]
    +解释:本示例答案不唯一。
    +按此输出 A = "()()", B = "()()", max(depth(A), depth(B)) = 1,它们的深度最小。
    +像 [1,1,1,0,0,1,1,1],也是正确结果,其中 A = "()()()", B = "()", max(depth(A), depth(B)) = 1 。 
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 < seq.size <= 10000
    • +
    + +

     

    + +

    有效括号字符串:

    + +
    仅由 "(" 和 ")" 构成的字符串,对于每个左括号,都能找到与之对应的右括号,反之亦然。
    +下述几种情况同样属于有效括号字符串:
    +
    +  1. 空字符串
    +  2. 连接,可以记作 ABAB 连接),其中 A 和 B 都是有效括号字符串
    +  3. 嵌套,可以记作 (A),其中 A 是有效括号字符串
    +
    + +

    嵌套深度:

    + +
    类似地,我们可以定义任意有效括号字符串 s嵌套深度 depth(S):
    +
    +  1. s 为空时,depth("") = 0
    +  2. sAB 连接时,depth(A + B) = max(depth(A), depth(B)),其中 A 和 B 都是有效括号字符串
    +  3. s 为嵌套情况,depth("(" + A + ")") = 1 + depth(A),其中 A 是有效括号字符串
    +
    +例如:"""()()",和 "()(()())" 都是有效括号字符串,嵌套深度分别为 0,1,2,而 ")(" 和 "(()" 都不是有效括号字符串。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1112.leetcode1112 Highest Grade For Each Student-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1112.leetcode1112 Highest Grade For Each Student-zh.md" new file mode 100644 index 00000000..07592eb3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1112.leetcode1112 Highest Grade For Each Student-zh.md" @@ -0,0 +1,66 @@ +# [1112. 每位学生的最高成绩](https://leetcode-cn.com/problems/highest-grade-for-each-student) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1112.Highest%20Grade%20For%20Each%20Student/README_EN.md) + +## 题目描述 + + + +

    表:Enrollments

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| course_id     | int     |
    +| grade         | int     |
    ++---------------+---------+
    +(student_id, course_id) 是该表的主键。
    +
    +
    + +

     

    + +

    编写一个 SQL 查询,查询每位学生获得的最高成绩和它所对应的科目,若科目成绩并列,取 course_id 最小的一门。查询结果需按 student_id 增序进行排序。

    + +

    查询结果格式如下所示:

    + +
    +Enrollments 表:
    ++------------+-------------------+
    +| student_id | course_id | grade |
    ++------------+-----------+-------+
    +| 2          | 2         | 95    |
    +| 2          | 3         | 95    |
    +| 1          | 1         | 90    |
    +| 1          | 2         | 99    |
    +| 3          | 1         | 80    |
    +| 3          | 2         | 75    |
    +| 3          | 3         | 82    |
    ++------------+-----------+-------+
    +
    +Result 表:
    ++------------+-------------------+
    +| student_id | course_id | grade |
    ++------------+-----------+-------+
    +| 1          | 2         | 99    |
    +| 2          | 2         | 95    |
    +| 3          | 3         | 82    |
    ++------------+-----------+-------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1113.leetcode1113 Reported Posts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1113.leetcode1113 Reported Posts-zh.md" new file mode 100644 index 00000000..7d40d6e2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1113.leetcode1113 Reported Posts-zh.md" @@ -0,0 +1,73 @@ +# [1113. 报告的记录](https://leetcode-cn.com/problems/reported-posts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1113.Reported%20Posts/README_EN.md) + +## 题目描述 + + + +

    动作表:Actions

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| post_id       | int     |
    +| action_date   | date    | 
    +| action        | enum    |
    +| extra         | varchar |
    ++---------------+---------+
    +此表没有主键,所以可能会有重复的行。
    +action 字段是 ENUM 类型的,包含:('view', 'like', 'reaction', 'comment', 'report', 'share')
    +extra 字段是可选的信息(可能为 null),其中的信息例如有:1.报告理由(a reason for report) 2.反应类型(a type of reaction)
    +
    + +

     

    + +

    编写一条SQL,查询每种 报告理由(report reason)在昨天的不同报告数量(post_id)。假设今天是 2019-07-05

    + +

    查询及结果的格式示例:

    + +
    Actions table:
    ++---------+---------+-------------+--------+--------+
    +| user_id | post_id | action_date | action | extra  |
    ++---------+---------+-------------+--------+--------+
    +| 1       | 1       | 2019-07-01  | view   | null   |
    +| 1       | 1       | 2019-07-01  | like   | null   |
    +| 1       | 1       | 2019-07-01  | share  | null   |
    +| 2       | 4       | 2019-07-04  | view   | null   |
    +| 2       | 4       | 2019-07-04  | report | spam   |
    +| 3       | 4       | 2019-07-04  | view   | null   |
    +| 3       | 4       | 2019-07-04  | report | spam   |
    +| 4       | 3       | 2019-07-02  | view   | null   |
    +| 4       | 3       | 2019-07-02  | report | spam   |
    +| 5       | 2       | 2019-07-04  | view   | null   |
    +| 5       | 2       | 2019-07-04  | report | racism |
    +| 5       | 5       | 2019-07-04  | view   | null   |
    +| 5       | 5       | 2019-07-04  | report | racism |
    ++---------+---------+-------------+--------+--------+
    +
    +Result table:
    ++---------------+--------------+
    +| report_reason | report_count |
    ++---------------+--------------+
    +| spam          | 1            |
    +| racism        | 2            |
    ++---------------+--------------+ 
    +注意,我们只关心报告数量非零的结果。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1114.leetcode1114 Print in Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1114.leetcode1114 Print in Order-zh.md" new file mode 100644 index 00000000..f4ba254c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1114.leetcode1114 Print in Order-zh.md" @@ -0,0 +1,88 @@ +# [1114. 按序打印](https://leetcode-cn.com/problems/print-in-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1114.Print%20in%20Order/README_EN.md) + +## 题目描述 + + + +

    我们提供了一个类:

    + +
    +public class Foo {
    +  public void first() { print("first"); }
    +  public void second() { print("second"); }
    +  public void third() { print("third"); }
    +}
    + +

    三个不同的线程 A、B、C 将会共用一个 Foo 实例。

    + +
      +
    • 一个将会调用 first() 方法
    • +
    • 一个将会调用 second() 方法
    • +
    • 还有一个将会调用 third() 方法
    • +
    + +

    请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。

    + +

     

    + +

    示例 1:

    + +
    +输入: [1,2,3]
    +输出: "firstsecondthird"
    +解释: 
    +有三个线程会被异步启动。
    +输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。
    +正确的输出是 "firstsecondthird"。
    +
    + +

    示例 2:

    + +
    +输入: [1,3,2]
    +输出: "firstsecondthird"
    +解释: 
    +输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。
    +正确的输出是 "firstsecondthird"。
    + +

     

    + +

    提示:

    + +
      +
    • 尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。
    • +
    • 你看到的输入格式主要是为了确保测试的全面性。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1115.leetcode1115 Print FooBar Alternately-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1115.leetcode1115 Print FooBar Alternately-zh.md" new file mode 100644 index 00000000..29143d3a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1115.leetcode1115 Print FooBar Alternately-zh.md" @@ -0,0 +1,78 @@ +# [1115. 交替打印FooBar](https://leetcode-cn.com/problems/print-foobar-alternately) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1115.Print%20FooBar%20Alternately/README_EN.md) + +## 题目描述 + + + +

    我们提供一个类:

    + +
    +class FooBar {
    +  public void foo() {
    +    for (int i = 0; i < n; i++) {
    +      print("foo");
    +    }
    +  }
    +
    +  public void bar() {
    +    for (int i = 0; i < n; i++) {
    +      print("bar");
    +    }
    +  }
    +}
    +
    + +

    两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。

    + +

    请设计修改程序,以确保 "foobar" 被输出 n 次。

    + +

     

    + +

    示例 1:

    + +
    +输入: n = 1
    +输出: "foobar"
    +解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。
    +
    + +

    示例 2:

    + +
    +输入: n = 2
    +输出: "foobarfoobar"
    +解释: "foobar" 将被输出两次。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1116.leetcode1116 Print Zero Even Odd-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1116.leetcode1116 Print Zero Even Odd-zh.md" new file mode 100644 index 00000000..8727010f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1116.leetcode1116 Print Zero Even Odd-zh.md" @@ -0,0 +1,73 @@ +# [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1116.Print%20Zero%20Even%20Odd/README_EN.md) + +## 题目描述 + + + +

    假设有这么一个类:

    + +
    class ZeroEvenOdd {
    +  public ZeroEvenOdd(int n) { ... }      // 构造函数
    +  public void zero(printNumber) { ... }  // 仅打印出 0
    +  public void even(printNumber) { ... }  // 仅打印出 偶数
    +  public void odd(printNumber) { ... }   // 仅打印出 奇数
    +}
    +
    + +

    相同的一个 ZeroEvenOdd 类实例将会传递给三个不同的线程:

    + +
      +
    1. 线程 A 将调用 zero(),它只输出 0 。
    2. +
    3. 线程 B 将调用 even(),它只输出偶数。
    4. +
    5. 线程 C 将调用 odd(),它只输出奇数。
    6. +
    + +

    每个线程都有一个 printNumber 方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506... ,其中序列的长度必须为 2n

    + +

     

    + +

    示例 1:

    + +
    输入:n = 2
    +输出:"0102"
    +说明:三条线程异步执行,其中一个调用 zero(),另一个线程调用 even(),最后一个线程调用odd()。正确的输出为 "0102"。
    +
    + +

    示例 2:

    + +
    输入:n = 5
    +输出:"0102030405"
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1117.leetcode1117 Building H2O-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1117.leetcode1117 Building H2O-zh.md" new file mode 100644 index 00000000..a576417f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1117.leetcode1117 Building H2O-zh.md" @@ -0,0 +1,83 @@ +# [1117. H2O 生成](https://leetcode-cn.com/problems/building-h2o) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1117.Building%20H2O/README_EN.md) + +## 题目描述 + + + +

    现在有两种线程,氧 oxygen 和氢 hydrogen,你的目标是组织这两种线程来产生水分子。

    + +

    存在一个屏障(barrier)使得每个线程必须等候直到一个完整水分子能够被产生出来。

    + +

    氢和氧线程会被分别给予 releaseHydrogenreleaseOxygen 方法来允许它们突破屏障。

    + +

    这些线程应该三三成组突破屏障并能立即组合产生一个水分子。

    + +

    你必须保证产生一个水分子所需线程的结合必须发生在下一个水分子产生之前。

    + +

    换句话说:

    + +
      +
    • 如果一个氧线程到达屏障时没有氢线程到达,它必须等候直到两个氢线程到达。
    • +
    • 如果一个氢线程到达屏障时没有其它线程到达,它必须等候直到一个氧线程和另一个氢线程到达。
    • +
    + +

    书写满足这些限制条件的氢、氧线程同步代码。

    + +

     

    + +

    示例 1:

    + +
    输入: "HOH"
    +输出: "HHO"
    +解释: "HOH" 和 "OHH" 依然都是有效解。
    +
    + +

    示例 2:

    + +
    输入: "OOHHHH"
    +输出: "HHOHHO"
    +解释: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" 和 "OHHOHH" 依然都是有效解。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 输入字符串的总长将会是 3n, 1 ≤ n ≤ 50;
    • +
    • 输入字符串中的 “H” 总数将会是 2n 。
    • +
    • 输入字符串中的 “O” 总数将会是 n 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1118.leetcode1118 Number of Days in a Month-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1118.leetcode1118 Number of Days in a Month-zh.md" new file mode 100644 index 00000000..d9b0b4c5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1118.leetcode1118 Number of Days in a Month-zh.md" @@ -0,0 +1,69 @@ +# [1118. 一月有多少天](https://leetcode-cn.com/problems/number-of-days-in-a-month) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1118.Number%20of%20Days%20in%20a%20Month/README_EN.md) + +## 题目描述 + + + +

    指定年份 Y 和月份 M,请你帮忙计算出该月一共有多少天。

    + +

     

    + +

    示例 1:

    + +
    输入:Y = 1992, M = 7
    +输出:31
    +
    + +

    示例 2:

    + +
    输入:Y = 2000, M = 2
    +输出:29
    +
    + +

    示例 3:

    + +
    输入:Y = 1900, M = 2
    +输出:28
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1583 <= Y <= 2100
    2. +
    3. 1 <= M <= 12
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1119.leetcode1119 Remove Vowels from a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1119.leetcode1119 Remove Vowels from a String-zh.md" new file mode 100644 index 00000000..5baa852c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1119.leetcode1119 Remove Vowels from a String-zh.md" @@ -0,0 +1,79 @@ +# [1119. 删去字符串中的元音](https://leetcode-cn.com/problems/remove-vowels-from-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1119.Remove%20Vowels%20from%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 S,请你删去其中的所有元音字母( 'a''e''i''o''u'),并返回这个新字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:"leetcodeisacommunityforcoders"
    +输出:"ltcdscmmntyfrcdrs"
    +
    + +

    示例 2:

    + +
    输入:"aeiou"
    +输出:""
    +
    + +

     

    + +

    提示:

    + +
      +
    1. S 仅由小写英文字母组成。
    2. +
    3. 1 <= S.length <= 1000
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def removeVowels(self, s: str) -> str: + res = [] + for c in s: + if c not in {'a', 'e', 'i', 'o', 'u'}: + res.append(c) + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String removeVowels(String s) { + StringBuilder res = new StringBuilder(); + for (char c : s.toCharArray()) { + if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')) { + res.append(c); + } + } + return res.toString(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1120.leetcode1120 Maximum Average Subtree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1120.leetcode1120 Maximum Average Subtree-zh.md" new file mode 100644 index 00000000..ddf7db4e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1120.leetcode1120 Maximum Average Subtree-zh.md" @@ -0,0 +1,69 @@ +# [1120. 子树的最大平均值](https://leetcode-cn.com/problems/maximum-average-subtree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1120.Maximum%20Average%20Subtree/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树的根节点 root,找出这棵树的 每一棵 子树的 平均值 中的 最大 值。

    + +

    子树是树中的任意节点和它的所有后代构成的集合。

    + +

    树的平均值是树中节点值的总和除以节点数。

    + +

     

    + +

    示例:

    + +

    + +
    输入:[5,6,1]
    +输出:6.00000
    +解释: 
    +以 value = 5 的节点作为子树的根节点,得到的平均值为 (5 + 6 + 1) / 3 = 4。
    +以 value = 6 的节点作为子树的根节点,得到的平均值为 6 / 1 = 6。
    +以 value = 1 的节点作为子树的根节点,得到的平均值为 1 / 1 = 1。
    +所以答案取最大值 6。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 树中的节点数介于 1 到 5000之间。
    2. +
    3. 每个节点的值介于 0 到 100000 之间。
    4. +
    5. 如果结果与标准答案的误差不超过 10^-5,那么该结果将被视为正确答案。
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1121.leetcode1121 Divide Array Into Increasing Sequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1121.leetcode1121 Divide Array Into Increasing Sequences-zh.md" new file mode 100644 index 00000000..4031c565 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1121.leetcode1121 Divide Array Into Increasing Sequences-zh.md" @@ -0,0 +1,68 @@ +# [1121. 将数组分成几个递增序列](https://leetcode-cn.com/problems/divide-array-into-increasing-sequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1121.Divide%20Array%20Into%20Increasing%20Sequences/README_EN.md) + +## 题目描述 + + + +

    给你一个 非递减 的正整数数组 nums 和整数 K,判断该数组是否可以被分成一个或几个 长度至少 为 K 的 不相交的递增子序列

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,2,3,3,4,4], K = 3
    +输出:true
    +解释:
    +该数组可以分成两个子序列 [1,2,3,4] 和 [2,3,4],每个子序列的长度都至少是 3。
    +
    + +

    示例 2:

    + +
    输入:nums = [5,6,6,7,8], K = 3
    +输出:false
    +解释:
    +没有办法根据条件来划分数组。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= nums.length <= 10^5
    2. +
    3. 1 <= K <= nums.length
    4. +
    5. 1 <= nums[i] <= 10^5
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1122.leetcode1122 Relative Sort Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1122.leetcode1122 Relative Sort Array-zh.md" new file mode 100644 index 00000000..d15fa72a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1122.leetcode1122 Relative Sort Array-zh.md" @@ -0,0 +1,67 @@ +# [1122. 数组的相对排序](https://leetcode-cn.com/problems/relative-sort-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1122.Relative%20Sort%20Array/README_EN.md) + +## 题目描述 + + + +

    给你两个数组,arr1 和 arr2

    + +
      +
    • arr2 中的元素各不相同
    • +
    • arr2 中的每个元素都出现在 arr1 中
    • +
    + +

    arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。

    + +

     

    + +

    示例:

    + +
    +输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
    +输出:[2,2,2,1,4,3,3,9,6,7,19]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 1000
    • +
    • 0 <= arr1[i], arr2[i] <= 1000
    • +
    • arr2 中的元素 arr2[i] 各不相同
    • +
    • arr2 中的每个元素 arr2[i] 都出现在 arr1 中
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1123.leetcode1123 Lowest Common Ancestor of Deepest Leaves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1123.leetcode1123 Lowest Common Ancestor of Deepest Leaves-zh.md" new file mode 100644 index 00000000..0d30adfa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1123.leetcode1123 Lowest Common Ancestor of Deepest Leaves-zh.md" @@ -0,0 +1,90 @@ +# [1123. 最深叶节点的最近公共祖先](https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1123.Lowest%20Common%20Ancestor%20of%20Deepest%20Leaves/README_EN.md) + +## 题目描述 + + + +

    给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。

    + +

    回想一下:

    + +
      +
    • 叶节点 是二叉树中没有子节点的节点
    • +
    • 树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
    • +
    • 如果我们假定 A 是一组节点 S 的 最近公共祖先S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。
    • +
    + +

     

    + +

    注意:本题与力扣 865 重复:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4]
    +输出:[2,7,4]
    +解释:
    +我们返回值为 2 的节点,在图中用黄色标记。
    +在图中用蓝色标记的是树的最深的节点。
    +注意,节点 6、0 和 8 也是叶节点,但是它们的深度是 2 ,而节点 7 和 4 的深度是 3 。
    +
    + +

    示例 2:

    + +
    +输入:root = [1]
    +输出:[1]
    +解释:根节点是树中最深的节点,它是它本身的最近公共祖先。
    +
    + +

    示例 3:

    + +
    +输入:root = [0,1,3,null,2]
    +输出:[2]
    +解释:树中最深的叶节点是 2 ,最近公共祖先是它自己。
    + +

     

    + +

    提示:

    + +
      +
    • 给你的树中将有 1 到 1000 个节点。
    • +
    • 树中每个节点的值都在 1 到 1000 之间。
    • +
    • 每个节点的值都是独一无二的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1124.leetcode1124 Longest Well-Performing Interval-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1124.leetcode1124 Longest Well-Performing Interval-zh.md" new file mode 100644 index 00000000..c2325c3b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1124.leetcode1124 Longest Well-Performing Interval-zh.md" @@ -0,0 +1,63 @@ +# [1124. 表现良好的最长时间段](https://leetcode-cn.com/problems/longest-well-performing-interval) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1124.Longest%20Well-Performing%20Interval/README_EN.md) + +## 题目描述 + + + +

    给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。

    + +

    我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。

    + +

    所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。

    + +

    请你返回「表现良好时间段」的最大长度。

    + +

     

    + +

    示例 1:

    + +
    输入:hours = [9,9,6,0,6,6,9]
    +输出:3
    +解释:最长的表现良好时间段是 [9,9,6]。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= hours.length <= 10000
    • +
    • 0 <= hours[i] <= 16
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1125.leetcode1125 Smallest Sufficient Team-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1125.leetcode1125 Smallest Sufficient Team-zh.md" new file mode 100644 index 00000000..ede6845f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1125.leetcode1125 Smallest Sufficient Team-zh.md" @@ -0,0 +1,82 @@ +# [1125. 最小的必要团队](https://leetcode-cn.com/problems/smallest-sufficient-team) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1125.Smallest%20Sufficient%20Team/README_EN.md) + +## 题目描述 + + + +

    作为项目经理,你规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。

    + +

    所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。可以用每个人的编号来表示团队中的成员:

    + +
      +
    • 例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0]people[1],和 people[3] 的备选人员。
    • +
    + +

    请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按 任意顺序 返回答案,题目数据保证答案存在。

    + +

     

    + +

    示例 1:

    + +
    +输入:req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
    +输出:[0,2]
    +
    + +

    示例 2:

    + +
    +输入:req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
    +输出:[1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= req_skills.length <= 16
    • +
    • 1 <= req_skills[i].length <= 16
    • +
    • req_skills[i] 由小写英文字母组成
    • +
    • req_skills 中的所有字符串 互不相同
    • +
    • 1 <= people.length <= 60
    • +
    • 0 <= people[i].length <= 16
    • +
    • 1 <= people[i][j].length <= 16
    • +
    • people[i][j] 由小写英文字母组成
    • +
    • people[i] 中的所有字符串 互不相同
    • +
    • people[i] 中的每个技能是 req_skills 中的技能
    • +
    • 题目数据保证「必要团队」一定存在
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1126.leetcode1126 Active Businesses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1126.leetcode1126 Active Businesses-zh.md" new file mode 100644 index 00000000..a7de80ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1126.leetcode1126 Active Businesses-zh.md" @@ -0,0 +1,67 @@ +# [1126. 查询活跃业务](https://leetcode-cn.com/problems/active-businesses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1126.Active%20Businesses/README_EN.md) + +## 题目描述 + + + +

    事件表:Events

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| business_id   | int     |
    +| event_type    | varchar |
    +| occurences    | int     | 
    ++---------------+---------+
    +此表的主键是 (business_id, event_type)。
    +表中的每一行记录了某种类型的事件在某些业务中多次发生的信息。
    +
    + +

     

    + +

    写一段 SQL 来查询所有活跃的业务。

    + +

    如果一个业务的某个事件类型的发生次数大于此事件类型在所有业务中的平均发生次数,并且该业务至少有两个这样的事件类型,那么该业务就可被看做是活跃业务。

    + +

    查询结果格式如下所示:

    + +
    +Events table:
    ++-------------+------------+------------+
    +| business_id | event_type | occurences |
    ++-------------+------------+------------+
    +| 1           | reviews    | 7          |
    +| 3           | reviews    | 3          |
    +| 1           | ads        | 11         |
    +| 2           | ads        | 7          |
    +| 3           | ads        | 6          |
    +| 1           | page views | 3          |
    +| 2           | page views | 12         |
    ++-------------+------------+------------+
    +
    +结果表
    ++-------------+
    +| business_id |
    ++-------------+
    +| 1           |
    ++-------------+ 
    +'reviews'、 'ads' 和 'page views' 的总平均发生次数分别是 (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5。
    +id 为 1 的业务有 7 个 'reviews' 事件(大于 5)和 11 个 'ads' 事件(大于 8),所以它是活跃业务。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1127.leetcode1127 User Purchase Platform-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1127.leetcode1127 User Purchase Platform-zh.md" new file mode 100644 index 00000000..5b6e91ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1127.leetcode1127 User Purchase Platform-zh.md" @@ -0,0 +1,70 @@ +# [1127. 用户购买平台](https://leetcode-cn.com/problems/user-purchase-platform) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1127.User%20Purchase%20Platform/README_EN.md) + +## 题目描述 + + + +

    支出表: Spending

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| spend_date  | date    |
    +| platform    | enum    | 
    +| amount      | int     |
    ++-------------+---------+
    +这张表记录了用户在一个在线购物网站的支出历史,该在线购物平台同时拥有桌面端('desktop')和手机端('mobile')的应用程序。
    +这张表的主键是 (user_id, spend_date, platform)。
    +平台列 platform 是一种 ENUM ,类型为('desktop', 'mobile')。
    + +

     

    + +

    写一段 SQL 来查找每天 仅 使用手机端用户、仅 使用桌面端用户和 同时 使用桌面端和手机端的用户人数和总支出金额。

    + +

    查询结果格式如下例所示:

    + +
    +Spending table:
    ++---------+------------+----------+--------+
    +| user_id | spend_date | platform | amount |
    ++---------+------------+----------+--------+
    +| 1       | 2019-07-01 | mobile   | 100    |
    +| 1       | 2019-07-01 | desktop  | 100    |
    +| 2       | 2019-07-01 | mobile   | 100    |
    +| 2       | 2019-07-02 | mobile   | 100    |
    +| 3       | 2019-07-01 | desktop  | 100    |
    +| 3       | 2019-07-02 | desktop  | 100    |
    ++---------+------------+----------+--------+
    +
    +Result table:
    ++------------+----------+--------------+-------------+
    +| spend_date | platform | total_amount | total_users |
    ++------------+----------+--------------+-------------+
    +| 2019-07-01 | desktop  | 100          | 1           |
    +| 2019-07-01 | mobile   | 100          | 1           |
    +| 2019-07-01 | both     | 200          | 1           |
    +| 2019-07-02 | desktop  | 100          | 1           |
    +| 2019-07-02 | mobile   | 100          | 1           |
    +| 2019-07-02 | both     | 0            | 0           |
    ++------------+----------+--------------+-------------+ 
    +在 2019-07-01, 用户1 同时 使用桌面端和手机端购买, 用户2 使用了手机端购买,而用户3 使用了桌面端购买。
    +在 2019-07-02, 用户2 使用了手机端购买, 用户3 使用了桌面端购买,且没有用户 同时 使用桌面端和手机端购买。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1128.leetcode1128 Number of Equivalent Domino Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1128.leetcode1128 Number of Equivalent Domino Pairs-zh.md" new file mode 100644 index 00000000..8afa1943 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1128.leetcode1128 Number of Equivalent Domino Pairs-zh.md" @@ -0,0 +1,63 @@ +# [1128. 等价多米诺骨牌对的数量](https://leetcode-cn.com/problems/number-of-equivalent-domino-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1128.Number%20of%20Equivalent%20Domino%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给你一个由一些多米诺骨牌组成的列表 dominoes

    + +

    如果其中某一张多米诺骨牌可以通过旋转 0 度或 180 度得到另一张多米诺骨牌,我们就认为这两张牌是等价的。

    + +

    形式上,dominoes[i] = [a, b] 和 dominoes[j] = [c, d] 等价的前提是 a==c 且 b==d,或是 a==d 且 b==c

    + +

    在 0 <= i < j < dominoes.length 的前提下,找出满足 dominoes[i] 和 dominoes[j] 等价的骨牌对 (i, j) 的数量。

    + +

     

    + +

    示例:

    + +
    输入:dominoes = [[1,2],[2,1],[3,4],[5,6]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= dominoes.length <= 40000
    • +
    • 1 <= dominoes[i][j] <= 9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1129.leetcode1129 Shortest Path with Alternating Colors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1129.leetcode1129 Shortest Path with Alternating Colors-zh.md" new file mode 100644 index 00000000..7452c415 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1129.leetcode1129 Shortest Path with Alternating Colors-zh.md" @@ -0,0 +1,88 @@ +# [1129. 颜色交替的最短路径](https://leetcode-cn.com/problems/shortest-path-with-alternating-colors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1129.Shortest%20Path%20with%20Alternating%20Colors/README_EN.md) + +## 题目描述 + + + +

    在一个有向图中,节点分别标记为 0, 1, ..., n-1。这个图中的每条边不是红色就是蓝色,且存在自环或平行边。

    + +

    red_edges 中的每一个 [i, j] 对表示从节点 i 到节点 j 的红色有向边。类似地,blue_edges 中的每一个 [i, j] 对表示从节点 i 到节点 j 的蓝色有向边。

    + +

    返回长度为 n 的数组 answer,其中 answer[X] 是从节点 0 到节点 X 的红色边和蓝色边交替出现的最短路径的长度。如果不存在这样的路径,那么 answer[x] = -1

    + +

     

    + +

    示例 1:

    + +
    输入:n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
    +输出:[0,1,-1]
    +
    + +

    示例 2:

    + +
    输入:n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
    +输出:[0,1,-1]
    +
    + +

    示例 3:

    + +
    输入:n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
    +输出:[0,-1,-1]
    +
    + +

    示例 4:

    + +
    输入:n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
    +输出:[0,1,2]
    +
    + +

    示例 5:

    + +
    输入:n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
    +输出:[0,1,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 100
    • +
    • red_edges.length <= 400
    • +
    • blue_edges.length <= 400
    • +
    • red_edges[i].length == blue_edges[i].length == 2
    • +
    • 0 <= red_edges[i][j], blue_edges[i][j] < n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1130.leetcode1130 Minimum Cost Tree From Leaf Values-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1130.leetcode1130 Minimum Cost Tree From Leaf Values-zh.md" new file mode 100644 index 00000000..c57399a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1130.leetcode1130 Minimum Cost Tree From Leaf Values-zh.md" @@ -0,0 +1,73 @@ +# [1130. 叶值的最小代价生成树](https://leetcode-cn.com/problems/minimum-cost-tree-from-leaf-values) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1130.Minimum%20Cost%20Tree%20From%20Leaf%20Values/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 arr,考虑所有满足以下条件的二叉树:

    + +
      +
    • 每个节点都有 0 个或是 2 个子节点。
    • +
    • 数组 arr 中的值与树的中序遍历中每个叶节点的值一一对应。(知识回顾:如果一个节点有 0 个子节点,那么该节点为叶节点。)
    • +
    • 每个非叶节点的值等于其左子树和右子树中叶节点的最大值的乘积。
    • +
    + +

    在所有这样的二叉树中,返回每个非叶节点的值的最小可能总和。这个和的值是一个 32 位整数。

    + +

     

    + +

    示例:

    + +
    输入:arr = [6,2,4]
    +输出:32
    +解释:
    +有两种可能的树,第一种的非叶节点的总和为 36,第二种非叶节点的总和为 32。
    +
    +    24            24
    +   /  \          /  \
    +  12   4        6    8
    + /  \               / \
    +6    2             2   4
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 40
    • +
    • 1 <= arr[i] <= 15
    • +
    • 答案保证是一个 32 位带符号整数,即小于 2^31
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1131.leetcode1131 Maximum of Absolute Value Expression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1131.leetcode1131 Maximum of Absolute Value Expression-zh.md" new file mode 100644 index 00000000..dd687246 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1131.leetcode1131 Maximum of Absolute Value Expression-zh.md" @@ -0,0 +1,66 @@ +# [1131. 绝对值表达式的最大值](https://leetcode-cn.com/problems/maximum-of-absolute-value-expression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1131.Maximum%20of%20Absolute%20Value%20Expression/README_EN.md) + +## 题目描述 + + + +

    给你两个长度相等的整数数组,返回下面表达式的最大值:

    + +

    |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|

    + +

    其中下标 ij 满足 0 <= i, j < arr1.length

    + +

     

    + +

    示例 1:

    + +
    输入:arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
    +输出:13
    +
    + +

    示例 2:

    + +
    输入:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
    +输出:20
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr1.length == arr2.length <= 40000
    • +
    • -10^6 <= arr1[i], arr2[i] <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1132.leetcode1132 Reported Posts II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1132.leetcode1132 Reported Posts II-zh.md" new file mode 100644 index 00000000..59e29fee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1132.leetcode1132 Reported Posts II-zh.md" @@ -0,0 +1,96 @@ +# [1132. 报告的记录 II](https://leetcode-cn.com/problems/reported-posts-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1132.Reported%20Posts%20II/README_EN.md) + +## 题目描述 + + + +

    动作表: Actions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| post_id       | int     |
    +| action_date   | date    |
    +| action        | enum    |
    +| extra         | varchar |
    ++---------------+---------+
    +这张表没有主键,并有可能存在重复的行。
    +action 列的类型是 ENUM,可能的值为 ('view', 'like', 'reaction', 'comment', 'report', 'share')。
    +extra 列拥有一些可选信息,例如:报告理由(a reason for report)或反应类型(a type of reaction)等。
    + +

    移除表: Removals

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| post_id       | int     |
    +| remove_date   | date    | 
    ++---------------+---------+
    +这张表的主键是 post_id。
    +这张表的每一行表示一个被移除的帖子,原因可能是由于被举报或被管理员审查。
    +
    + +

     

    + +

    编写一段 SQL 来查找:在被报告为垃圾广告的帖子中,被移除的帖子的每日平均占比,四舍五入到小数点后 2 位

    + +

    查询结果的格式如下:

    + +
    +Actions table:
    ++---------+---------+-------------+--------+--------+
    +| user_id | post_id | action_date | action | extra  |
    ++---------+---------+-------------+--------+--------+
    +| 1       | 1       | 2019-07-01  | view   | null   |
    +| 1       | 1       | 2019-07-01  | like   | null   |
    +| 1       | 1       | 2019-07-01  | share  | null   |
    +| 2       | 2       | 2019-07-04  | view   | null   |
    +| 2       | 2       | 2019-07-04  | report | spam   |
    +| 3       | 4       | 2019-07-04  | view   | null   |
    +| 3       | 4       | 2019-07-04  | report | spam   |
    +| 4       | 3       | 2019-07-02  | view   | null   |
    +| 4       | 3       | 2019-07-02  | report | spam   |
    +| 5       | 2       | 2019-07-03  | view   | null   |
    +| 5       | 2       | 2019-07-03  | report | racism |
    +| 5       | 5       | 2019-07-03  | view   | null   |
    +| 5       | 5       | 2019-07-03  | report | racism |
    ++---------+---------+-------------+--------+--------+
    +
    +Removals table:
    ++---------+-------------+
    +| post_id | remove_date |
    ++---------+-------------+
    +| 2       | 2019-07-20  |
    +| 3       | 2019-07-18  |
    ++---------+-------------+
    +
    +Result table:
    ++-----------------------+
    +| average_daily_percent |
    ++-----------------------+
    +| 75.00                 |
    ++-----------------------+
    +2019-07-04 的垃圾广告移除率是 50%,因为有两张帖子被报告为垃圾广告,但只有一个得到移除。
    +2019-07-02 的垃圾广告移除率是 100%,因为有一张帖子被举报为垃圾广告并得到移除。
    +其余几天没有收到垃圾广告的举报,因此平均值为:(50 + 100) / 2 = 75%
    +注意,输出仅需要一个平均值即可,我们并不关注移除操作的日期。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1133.leetcode1133 Largest Unique Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1133.leetcode1133 Largest Unique Number-zh.md" new file mode 100644 index 00000000..e6d21355 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1133.leetcode1133 Largest Unique Number-zh.md" @@ -0,0 +1,110 @@ +# [1133. 最大唯一数](https://leetcode-cn.com/problems/largest-unique-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1133.Largest%20Unique%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 A,请找出并返回在该数组中仅出现一次的最大整数。

    + +

    如果不存在这个只出现一次的整数,则返回 -1。

    + +

     

    + +

    示例 1:

    + +
    输入:[5,7,3,9,4,9,8,3,1]
    +输出:8
    +解释: 
    +数组中最大的整数是 9,但它在数组中重复出现了。而第二大的整数是 8,它只出现了一次,所以答案是 8。
    +
    + +

    示例 2:

    + +
    输入:[9,9,8,8]
    +输出:-1
    +解释: 
    +数组中不存在仅出现一次的整数。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= A.length <= 2000
    2. +
    3. 0 <= A[i] <= 1000
    4. +
    + +## 解法 + + + +计数器实现。 + + + +### **Python3** + + + +```python +class Solution: + def largestUniqueNumber(self, A: List[int]) -> int: + counter = collections.Counter(A) + for i in range(1000, -1, -1): + if counter[i] == 1: + return i + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int largestUniqueNumber(int[] A) { + int[] counter = new int[1001]; + for (int a : A) { + ++counter[a]; + } + for (int i = 1000; i >= 0; --i) { + if (counter[i] == 1) { + return i; + } + } + return -1; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} A + * @return {number} + */ +var largestUniqueNumber = function (A) { + let counter = {}; + for (const a of A) { + counter[a] = (counter[a] || 0) + 1; + } + for (let i = 1000; i >= 0; --i) { + if (counter[i] == 1) { + return i; + } + } + return -1; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1134.leetcode1134 Armstrong Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1134.leetcode1134 Armstrong Number-zh.md" new file mode 100644 index 00000000..6bcfe1d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1134.leetcode1134 Armstrong Number-zh.md" @@ -0,0 +1,105 @@ +# [1134. 阿姆斯特朗数](https://leetcode-cn.com/problems/armstrong-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1134.Armstrong%20Number/README_EN.md) + +## 题目描述 + + + +

    假设存在一个 k 位数 N,其每一位上的数字的 k 次幂的总和也是 N,那么这个数是阿姆斯特朗数。

    + +

    给你一个正整数 N,让你来判定他是否是阿姆斯特朗数,是则返回 true,不是则返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:153
    +输出:true
    +示例: 
    +153 是一个 3 位数,且 153 = 1^3 + 5^3 + 3^3。
    +
    + +

    示例 2:

    + +
    输入:123
    +输出:false
    +解释: 
    +123 是一个 3 位数,且 123 != 1^3 + 2^3 + 3^3 = 36。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10^8
    2. +
    + +## 解法 + + + +先求数字 n 的长度 k,然后累加 n 上每一位的数字的 k 次幂。最后判断累加的结果是否与 n 相等即可。 + + + +### **Python3** + + + +```python +class Solution: + def isArmstrong(self, n: int) -> bool: + k = len(str(n)) + s, t = 0, n + while t: + t, v = divmod(t, 10) + s += pow(v, k) + return n == s +``` + +### **Java** + + + +```java +class Solution { + public boolean isArmstrong(int n) { + int k = String.valueOf(n).length(); + int s = 0, t = n; + while (t != 0) { + s += Math.pow(t % 10, k); + t /= 10; + } + return n == s; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {boolean} + */ +var isArmstrong = function (n) { + const k = String(n).length; + let s = 0; + let t = n; + while (t) { + s += Math.pow(t % 10, k); + t = Math.floor(t / 10); + } + return n == s; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1135.leetcode1135 Connecting Cities With Minimum Cost-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1135.leetcode1135 Connecting Cities With Minimum Cost-zh.md" new file mode 100644 index 00000000..01ee5ed1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1135.leetcode1135 Connecting Cities With Minimum Cost-zh.md" @@ -0,0 +1,78 @@ +# [1135. 最低成本联通所有城市](https://leetcode-cn.com/problems/connecting-cities-with-minimum-cost) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1135.Connecting%20Cities%20With%20Minimum%20Cost/README_EN.md) + +## 题目描述 + + + +

    想象一下你是个城市基建规划者,地图上有 N 座城市,它们按以 1 到 N 的次序编号。

    + +

    给你一些可连接的选项 conections,其中每个选项 conections[i] = [city1, city2, cost] 表示将城市 city1 和城市 city2 连接所要的成本。(连接是双向的,也就是说城市 city1 和城市 city2 相连也同样意味着城市 city2 和城市 city1 相连)。

    + +

    返回使得每对城市间都存在将它们连接在一起的连通路径(可能长度为 1 的)最小成本。该最小成本应该是所用全部连接代价的综合。如果根据已知条件无法完成该项任务,则请你返回 -1。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:N = 3, conections = [[1,2,5],[1,3,6],[2,3,1]]
    +输出:6
    +解释:
    +选出任意 2 条边都可以连接所有城市,我们从中选取成本最小的 2 条。
    +
    + +

    示例 2:

    + +

    + +
    输入:N = 4, conections = [[1,2,3],[3,4,4]]
    +输出:-1
    +解释: 
    +即使连通所有的边,也无法连接所有城市。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 10000
    2. +
    3. 1 <= conections.length <= 10000
    4. +
    5. 1 <= conections[i][0], conections[i][1] <= N
    6. +
    7. 0 <= conections[i][2] <= 10^5
    8. +
    9. conections[i][0] != conections[i][1]
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1136.leetcode1136 Parallel Courses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1136.leetcode1136 Parallel Courses-zh.md" new file mode 100644 index 00000000..f5586e10 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1136.leetcode1136 Parallel Courses-zh.md" @@ -0,0 +1,80 @@ +# [1136. 平行课程](https://leetcode-cn.com/problems/parallel-courses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1136.Parallel%20Courses/README_EN.md) + +## 题目描述 + + + +

    已知有 N 门课程,它们以 1 到 N 进行编号。

    + +

    给你一份课程关系表 relations[i] = [X, Y],用以表示课程 X 和课程 Y 之间的先修关系:课程 X 必须在课程 Y 之前修完。

    + +

    假设在一个学期里,你可以学习任何数量的课程,但前提是你已经学习了将要学习的这些课程的所有先修课程。

    + +

    请你返回学完全部课程所需的最少学期数。

    + +

    如果没有办法做到学完全部这些课程的话,就返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:N = 3, relations = [[1,3],[2,3]]
    +输出:2
    +解释:
    +在第一个学期学习课程 1 和 2,在第二个学期学习课程 3。
    +
    + +

    示例 2:

    + +

    + +
    输入:N = 3, relations = [[1,2],[2,3],[3,1]]
    +输出:-1
    +解释:
    +没有课程可以学习,因为它们相互依赖。
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= N <= 5000
    2. +
    3. 1 <= relations.length <= 5000
    4. +
    5. relations[i][0] != relations[i][1]
    6. +
    7. 输入中没有重复的关系
    8. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1137.leetcode1137 N-th Tribonacci Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1137.leetcode1137 N-th Tribonacci Number-zh.md" new file mode 100644 index 00000000..5759ab64 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1137.leetcode1137 N-th Tribonacci Number-zh.md" @@ -0,0 +1,137 @@ +# [1137. 第 N 个泰波那契数](https://leetcode-cn.com/problems/n-th-tribonacci-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1137.N-th%20Tribonacci%20Number/README_EN.md) + +## 题目描述 + + + +

    泰波那契序列 Tn 定义如下: 

    + +

    T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

    + +

    给你整数 n,请返回第 n 个泰波那契数 Tn 的值。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 4
    +输出:4
    +解释:
    +T_3 = 0 + 1 + 1 = 2
    +T_4 = 1 + 1 + 2 = 4
    +
    + +

    示例 2:

    + +
    输入:n = 25
    +输出:1389537
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 37
    • +
    • 答案保证是一个 32 位整数,即 answer <= 2^31 - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + for _ in range(n): + a, b, c = b, c, a + b + c + return a +``` + +### **Java** + + + +```java +class Solution { + public int tribonacci(int n) { + int a = 0, b = 1, c = 1; + while (n-- > 0) { + int d = a + b + c; + a = b; + b = c; + c = d; + } + return a; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int tribonacci(int n) { + long long a = 0, b = 1, c = 1; + while (n--) { + long long d = a + b + c; + a = b; + b = c; + c = d; + } + return (int) a; + } +}; +``` + +### **Go** + +```go +func tribonacci(n int) int { + a, b, c := 0, 1, 1 + for i := 0; i < n; i++ { + a, b, c = b, c, a+b+c + } + return a +} +``` + +### **JavaScript** + +```js +/** + * @param {number} n + * @return {number} + */ +var tribonacci = function(n) { + let a = 0; + let b = 1; + let c = 1; + while (n--) { + let d = a + b + c; + a = b; + b = c; + c = d; + } + return a; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1138.leetcode1138 Alphabet Board Path-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1138.leetcode1138 Alphabet Board Path-zh.md" new file mode 100644 index 00000000..72014346 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1138.leetcode1138 Alphabet Board Path-zh.md" @@ -0,0 +1,81 @@ +# [1138. 字母板上的路径](https://leetcode-cn.com/problems/alphabet-board-path) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1138.Alphabet%20Board%20Path/README_EN.md) + +## 题目描述 + + + +

    我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]

    + +

    在本题里,字母板为board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"],如下所示。

    + +

    + +

    我们可以按下面的指令规则行动:

    + +
      +
    • 如果方格存在,'U' 意味着将我们的位置上移一行;
    • +
    • 如果方格存在,'D' 意味着将我们的位置下移一行;
    • +
    • 如果方格存在,'L' 意味着将我们的位置左移一列;
    • +
    • 如果方格存在,'R' 意味着将我们的位置右移一列;
    • +
    • '!' 会把在我们当前位置 (r, c) 的字符 board[r][c] 添加到答案中。
    • +
    + +

    (注意,字母板上只存在有字母的位置。)

    + +

    返回指令序列,用最小的行动次数让答案和目标 target 相同。你可以返回任何达成目标的路径。

    + +

     

    + +

    示例 1:

    + +
    输入:target = "leet"
    +输出:"DDR!UURRR!!DDD!"
    +
    + +

    示例 2:

    + +
    输入:target = "code"
    +输出:"RR!DDRR!UUL!R!"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target.length <= 100
    • +
    • target 仅含有小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1139.leetcode1139 Largest 1-Bordered Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1139.leetcode1139 Largest 1-Bordered Square-zh.md" new file mode 100644 index 00000000..f42e5cfc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1139.leetcode1139 Largest 1-Bordered Square-zh.md" @@ -0,0 +1,64 @@ +# [1139. 最大的以 1 为边界的正方形](https://leetcode-cn.com/problems/largest-1-bordered-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1139.Largest%201-Bordered%20Square/README_EN.md) + +## 题目描述 + + + +

    给你一个由若干 01 组成的二维网格 grid,请你找出边界全部由 1 组成的最大 正方形 子网格,并返回该子网格中的元素数量。如果不存在,则返回 0

    + +

     

    + +

    示例 1:

    + +
    输入:grid = [[1,1,1],[1,0,1],[1,1,1]]
    +输出:9
    +
    + +

    示例 2:

    + +
    输入:grid = [[1,1,0,0]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length <= 100
    • +
    • 1 <= grid[0].length <= 100
    • +
    • grid[i][j] 为 0 或 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1140.leetcode1140 Stone Game II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1140.leetcode1140 Stone Game II-zh.md" new file mode 100644 index 00000000..c503439a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1140.leetcode1140 Stone Game II-zh.md" @@ -0,0 +1,69 @@ +# [1140. 石子游戏 II](https://leetcode-cn.com/problems/stone-game-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1140.Stone%20Game%20II/README_EN.md) + +## 题目描述 + + + +

    亚历克斯和李继续他们的石子游戏。许多堆石子 排成一行,每堆都有正整数颗石子 piles[i]。游戏以谁手中的石子最多来决出胜负。

    + +

    亚历克斯和李轮流进行,亚历克斯先开始。最初,M = 1

    + +

    在每个玩家的回合中,该玩家可以拿走剩下的  X 堆的所有石子,其中 1 <= X <= 2M。然后,令 M = max(M, X)

    + +

    游戏一直持续到所有石子都被拿走。

    + +

    假设亚历克斯和李都发挥出最佳水平,返回亚历克斯可以得到的最大数量的石头。

    + +

     

    + +

    示例:

    + +
    输入:piles = [2,7,9,4,4]
    +输出:10
    +解释:
    +如果亚历克斯在开始时拿走一堆石子,李拿走两堆,接着亚历克斯也拿走两堆。在这种情况下,亚历克斯可以拿到 2 + 4 + 4 = 10 颗石子。 
    +如果亚历克斯在开始时拿走两堆石子,那么李就可以拿走剩下全部三堆石子。在这种情况下,亚历克斯可以拿到 2 + 7 = 9 颗石子。
    +所以我们返回更大的 10。 
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= piles.length <= 100
    • +
    • 1 <= piles[i] <= 10 ^ 4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1141.leetcode1141 User Activity for the Past 30 Days I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1141.leetcode1141 User Activity for the Past 30 Days I-zh.md" new file mode 100644 index 00000000..dbd09737 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1141.leetcode1141 User Activity for the Past 30 Days I-zh.md" @@ -0,0 +1,70 @@ +# [1141. 查询近30天活跃用户数](https://leetcode-cn.com/problems/user-activity-for-the-past-30-days-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1141.User%20Activity%20for%20the%20Past%2030%20Days%20I/README_EN.md) + +## 题目描述 + + + +

    活动记录表:Activity

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| session_id    | int     |
    +| activity_date | date    |
    +| activity_type | enum    |
    ++---------------+---------+
    +该表是用户在社交网站的活动记录。
    +该表没有主键,可能包含重复数据。
    +activity_type 字段为以下四种值 ('open_session', 'end_session', 'scroll_down', 'send_message')。
    +每个 session_id 只属于一个用户。
    +
    + +

     

    + +

    请写SQL查询出截至 2019-07-27(包含2019-07-27),近 30天的每日活跃用户数(当天只要有一条活动记录,即为活跃用户)。

    + +

    查询结果示例如下:

    + +
    Activity table:
    ++---------+------------+---------------+---------------+
    +| user_id | session_id | activity_date | activity_type |
    ++---------+------------+---------------+---------------+
    +| 1       | 1          | 2019-07-20    | open_session  |
    +| 1       | 1          | 2019-07-20    | scroll_down   |
    +| 1       | 1          | 2019-07-20    | end_session   |
    +| 2       | 4          | 2019-07-20    | open_session  |
    +| 2       | 4          | 2019-07-21    | send_message  |
    +| 2       | 4          | 2019-07-21    | end_session   |
    +| 3       | 2          | 2019-07-21    | open_session  |
    +| 3       | 2          | 2019-07-21    | send_message  |
    +| 3       | 2          | 2019-07-21    | end_session   |
    +| 4       | 3          | 2019-06-25    | open_session  |
    +| 4       | 3          | 2019-06-25    | end_session   |
    ++---------+------------+---------------+---------------+
    +
    +Result table:
    ++------------+--------------+ 
    +| day        | active_users |
    ++------------+--------------+ 
    +| 2019-07-20 | 2            |
    +| 2019-07-21 | 2            |
    ++------------+--------------+ 
    +非活跃用户的记录不需要展示。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1142.leetcode1142 User Activity for the Past 30 Days II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1142.leetcode1142 User Activity for the Past 30 Days II-zh.md" new file mode 100644 index 00000000..defeb55a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1142.leetcode1142 User Activity for the Past 30 Days II-zh.md" @@ -0,0 +1,75 @@ +# [1142. 过去30天的用户活动 II](https://leetcode-cn.com/problems/user-activity-for-the-past-30-days-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1142.User%20Activity%20for%20the%20Past%2030%20Days%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Activity

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| session_id    | int     |
    +| activity_date | date    |
    +| activity_type | enum    |
    ++---------------+---------+
    +该表没有主键,它可能有重复的行。
    +activity_type 列是 ENUM(“ open_session”,“ end_session”,“ scroll_down”,“ send_message”)中的某一类型。
    +该表显示了社交媒体网站的用户活动。
    +请注意,每个会话完全属于一个用户。
    + +

     

    + +

    编写SQL查询以查找截至2019年7月27日(含)的30天内每个用户的平均会话数,四舍五入到小数点后两位。我们只统计那些会话期间用户至少进行一项活动的有效会话。

    + +

     

    + +

    查询结果格式如下例所示:

    + +
    +Activity table:
    ++---------+------------+---------------+---------------+
    +| user_id | session_id | activity_date | activity_type |
    ++---------+------------+---------------+---------------+
    +| 1       | 1          | 2019-07-20    | open_session  |
    +| 1       | 1          | 2019-07-20    | scroll_down   |
    +| 1       | 1          | 2019-07-20    | end_session   |
    +| 2       | 4          | 2019-07-20    | open_session  |
    +| 2       | 4          | 2019-07-21    | send_message  |
    +| 2       | 4          | 2019-07-21    | end_session   |
    +| 3       | 2          | 2019-07-21    | open_session  |
    +| 3       | 2          | 2019-07-21    | send_message  |
    +| 3       | 2          | 2019-07-21    | end_session   |
    +| 3       | 5          | 2019-07-21    | open_session  |
    +| 3       | 5          | 2019-07-21    | scroll_down   |
    +| 3       | 5          | 2019-07-21    | end_session   |
    +| 4       | 3          | 2019-06-25    | open_session  |
    +| 4       | 3          | 2019-06-25    | end_session   |
    ++---------+------------+---------------+---------------+
    +
    +Result table:
    ++---------------------------+ 
    +| average_sessions_per_user |
    ++---------------------------+ 
    +| 1.33                      |
    ++---------------------------+ 
    +User 1 和 2 在过去30天内各自进行了1次会话,而用户3进行了2次会话,因此平均值为(1 +1 + 2)/ 3 = 1.33。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1143.leetcode1143 Longest Common Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1143.leetcode1143 Longest Common Subsequence-zh.md" new file mode 100644 index 00000000..4044df3c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1143.leetcode1143 Longest Common Subsequence-zh.md" @@ -0,0 +1,110 @@ +# [1143. 最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1143.Longest%20Common%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0

    + +

    一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。

    + +
      +
    • 例如,"ace""abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。
    • +
    + +

    两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:text1 = "abcde", text2 = "ace" 
    +输出:3  
    +解释:最长公共子序列是 "ace" ,它的长度为 3 。
    +
    + +

    示例 2:

    + +
    +输入:text1 = "abc", text2 = "abc"
    +输出:3
    +解释:最长公共子序列是 "abc" ,它的长度为 3 。
    +
    + +

    示例 3:

    + +
    +输入:text1 = "abc", text2 = "def"
    +输出:0
    +解释:两个字符串没有公共子序列,返回 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text1.length, text2.length <= 1000
    • +
    • text1 和 text2 仅由小写英文字符组成。
    • +
    + + +## 解法 + + + +动态规划法。 + +定义 `dp[i][j]` 表示 `text1[0:i-1]` 和 `text2[0:j-1]` 的最长公共子序列(闭区间)。 + +递推公式如下: + +![](https://cdn.jsdelivr.net/gh/yanglr/leetcode-ac@master/assets/1100-1199/1143.Longest%20Common%20Subsequence/images/gif.gif) + + + +### **Python3** + + + +```python +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + m, n = len(text1), len(text2) + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = dp[i - 1][j - 1] + 1 if text1[i - 1] == text2[j - 1] else max(dp[i - 1][j], dp[i][j - 1]) + return dp[m][n] +``` + +### **Java** + + + +```java +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int m = text1.length(), n = text2.length(); + int[][] dp = new int[m + 1][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + char c1 = text1.charAt(i - 1), c2 = text2.charAt(j - 1); + dp[i][j] = c1 == c2 ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp[m][n]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1144.leetcode1144 Decrease Elements To Make Array Zigzag-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1144.leetcode1144 Decrease Elements To Make Array Zigzag-zh.md" new file mode 100644 index 00000000..0c628c61 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1144.leetcode1144 Decrease Elements To Make Array Zigzag-zh.md" @@ -0,0 +1,73 @@ +# [1144. 递减元素使数组呈锯齿状](https://leetcode-cn.com/problems/decrease-elements-to-make-array-zigzag) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1144.Decrease%20Elements%20To%20Make%20Array%20Zigzag/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,每次 操作 会从中选择一个元素并 将该元素的值减少 1

    + +

    如果符合下列情况之一,则数组 A 就是 锯齿数组

    + +
      +
    • 每个偶数索引对应的元素都大于相邻的元素,即 A[0] > A[1] < A[2] > A[3] < A[4] > ...
    • +
    • 或者,每个奇数索引对应的元素都大于相邻的元素,即 A[0] < A[1] > A[2] < A[3] > A[4] < ...
    • +
    + +

    返回将数组 nums 转换为锯齿数组所需的最小操作次数。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3]
    +输出:2
    +解释:我们可以把 2 递减到 0,或把 3 递减到 1。
    +
    + +

    示例 2:

    + +
    输入:nums = [9,6,1,6,2]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1145.leetcode1145 Binary Tree Coloring Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1145.leetcode1145 Binary Tree Coloring Game-zh.md" new file mode 100644 index 00000000..3d8a2978 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1145.leetcode1145 Binary Tree Coloring Game-zh.md" @@ -0,0 +1,83 @@ +# [1145. 二叉树着色游戏](https://leetcode-cn.com/problems/binary-tree-coloring-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1145.Binary%20Tree%20Coloring%20Game/README_EN.md) + +## 题目描述 + + + +

    有两位极客玩家参与了一场「二叉树着色」的游戏。游戏中,给出二叉树的根节点 root,树上总共有 n 个节点,且 n 为奇数,其中每个节点上的值从 1 到 n 各不相同。

    + +

     

    + +

    游戏从「一号」玩家开始(「一号」玩家为红色,「二号」玩家为蓝色),最开始时,

    + +

    「一号」玩家从 [1, n] 中取一个值 x1 <= x <= n);

    + +

    「二号」玩家也从 [1, n] 中取一个值 y1 <= y <= n)且 y != x

    + +

    「一号」玩家给值为 x 的节点染上红色,而「二号」玩家给值为 y 的节点染上蓝色。

    + +

     

    + +

    之后两位玩家轮流进行操作,每一回合,玩家选择一个他之前涂好颜色的节点,将所选节点一个 未着色 的邻节点(即左右子节点、或父节点)进行染色。

    + +

    如果当前玩家无法找到这样的节点来染色时,他的回合就会被跳过。

    + +

    若两个玩家都没有可以染色的节点时,游戏结束。着色节点最多的那位玩家获得胜利 ✌️。

    + +

     

    + +

    现在,假设你是「二号」玩家,根据所给出的输入,假如存在一个 y 值可以确保你赢得这场游戏,则返回 true;若无法获胜,就请返回 false

    + +

     

    + +

    示例:

    + +

    + +
    输入:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
    +输出:True
    +解释:第二个玩家可以选择值为 2 的节点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 二叉树的根节点为 root,树上由 n 个节点,节点上的值从 1n 各不相同。
    • +
    • n 为奇数。
    • +
    • 1 <= x <= n <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1146.leetcode1146 Snapshot Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1146.leetcode1146 Snapshot Array-zh.md" new file mode 100644 index 00000000..4a4bff5f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1146.leetcode1146 Snapshot Array-zh.md" @@ -0,0 +1,73 @@ +# [1146. 快照数组](https://leetcode-cn.com/problems/snapshot-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1146.Snapshot%20Array/README_EN.md) + +## 题目描述 + + + +

    实现支持下列接口的「快照数组」- SnapshotArray:

    + +
      +
    • SnapshotArray(int length) - 初始化一个与指定长度相等的 类数组 的数据结构。初始时,每个元素都等于 0
    • +
    • void set(index, val) - 会将指定索引 index 处的元素设置为 val
    • +
    • int snap() - 获取该数组的快照,并返回快照的编号 snap_id(快照号是调用 snap() 的总次数减去 1)。
    • +
    • int get(index, snap_id) - 根据指定的 snap_id 选择快照,并返回该快照指定索引 index 的值。
    • +
    + +

     

    + +

    示例:

    + +
    输入:["SnapshotArray","set","snap","set","get"]
    +     [[3],[0,5],[],[0,6],[0,0]]
    +输出:[null,null,0,null,5]
    +解释:
    +SnapshotArray snapshotArr = new SnapshotArray(3); // 初始化一个长度为 3 的快照数组
    +snapshotArr.set(0,5);  // 令 array[0] = 5
    +snapshotArr.snap();  // 获取快照,返回 snap_id = 0
    +snapshotArr.set(0,6);
    +snapshotArr.get(0,0);  // 获取 snap_id = 0 的快照中 array[0] 的值,返回 5
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= length <= 50000
    • +
    • 题目最多进行50000setsnap,和 get的调用 。
    • +
    • 0 <= index < length
    • +
    • 0 <= snap_id < 我们调用 snap() 的总次数
    • +
    • 0 <= val <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1147.leetcode1147 Longest Chunked Palindrome Decomposition-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1147.leetcode1147 Longest Chunked Palindrome Decomposition-zh.md" new file mode 100644 index 00000000..e0ef63be --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1147.leetcode1147 Longest Chunked Palindrome Decomposition-zh.md" @@ -0,0 +1,93 @@ +# [1147. 段式回文](https://leetcode-cn.com/problems/longest-chunked-palindrome-decomposition) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1147.Longest%20Chunked%20Palindrome%20Decomposition/README_EN.md) + +## 题目描述 + + + +

    段式回文 其实与 一般回文 类似,只不过是最小的单位是 一段字符 而不是 单个字母。

    + +

    举个例子,对于一般回文 "abcba" 是回文,而 "volvo" 不是,但如果我们把 "volvo" 分为 "vo"、"l"、"vo" 三段,则可以认为 “(vo)(l)(vo)” 是段式回文(分为 3 段)。

    + +

     

    + +

    给你一个字符串 text,在确保它满足段式回文的前提下,请你返回 的 最大数量 k

    + +

    如果段的最大数量为 k,那么存在满足以下条件的 a_1, a_2, ..., a_k

    + +
      +
    • 每个 a_i 都是一个非空字符串;
    • +
    • 将这些字符串首位相连的结果 a_1 + a_2 + ... + a_k 和原始字符串 text 相同;
    • +
    • 对于所有1 <= i <= k,都有 a_i = a_{k+1 - i}
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:text = "ghiabcdefhelloadamhelloabcdefghi"
    +输出:7
    +解释:我们可以把字符串拆分成 "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)"。
    +
    + +

    示例 2:

    + +
    输入:text = "merchant"
    +输出:1
    +解释:我们可以把字符串拆分成 "(merchant)"。
    +
    + +

    示例 3:

    + +
    输入:text = "antaprezatepzapreanta"
    +输出:11
    +解释:我们可以把字符串拆分成 "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)"。
    +
    + +

    示例 4:

    + +
    输入:text = "aaa"
    +输出:3
    +解释:我们可以把字符串拆分成 "(a)(a)(a)"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • text 仅由小写英文字符组成。
    • +
    • 1 <= text.length <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1148.leetcode1148 Article Views I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1148.leetcode1148 Article Views I-zh.md" new file mode 100644 index 00000000..75508678 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1148.leetcode1148 Article Views I-zh.md" @@ -0,0 +1,76 @@ +# [1148. 文章浏览 I](https://leetcode-cn.com/problems/article-views-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1148.Article%20Views%20I/README_EN.md) + +## 题目描述 + + + +

    Views 表:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| article_id    | int     |
    +| author_id     | int     |
    +| viewer_id     | int     |
    +| view_date     | date    |
    ++---------------+---------+
    +此表无主键,因此可能会存在重复行。
    +此表的每一行都表示某人在某天浏览了某位作者的某篇文章。
    +请注意,同一人的 author_id 和 viewer_id 是相同的。
    +
    + +

     

    + +

    请编写一条 SQL 查询以找出所有浏览过自己文章的作者,结果按照 id 升序排列。

    + +

    查询结果的格式如下所示:

    + +
    +Views 表:
    ++------------+-----------+-----------+------------+
    +| article_id | author_id | viewer_id | view_date  |
    ++------------+-----------+-----------+------------+
    +| 1          | 3         | 5         | 2019-08-01 |
    +| 1          | 3         | 6         | 2019-08-02 |
    +| 2          | 7         | 7         | 2019-08-01 |
    +| 2          | 7         | 6         | 2019-08-02 |
    +| 4          | 7         | 1         | 2019-07-22 |
    +| 3          | 4         | 4         | 2019-07-21 |
    +| 3          | 4         | 4         | 2019-07-21 |
    ++------------+-----------+-----------+------------+
    +
    +结果表:
    ++------+
    +| id   |
    ++------+
    +| 4    |
    +| 7    |
    ++------+
    +
    + +## 解法 + + + +“`DISTINCT` + `ORDER BY`” 实现。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + DISTINCT(author_id) as id +FROM + Views +WHERE + author_id = viewer_id +ORDER BY + id; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1149.leetcode1149 Article Views II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1149.leetcode1149 Article Views II-zh.md" new file mode 100644 index 00000000..462501fe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1149.leetcode1149 Article Views II-zh.md" @@ -0,0 +1,76 @@ +# [1149. 文章浏览 II](https://leetcode-cn.com/problems/article-views-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1149.Article%20Views%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Views

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| article_id    | int     |
    +| author_id     | int     |
    +| viewer_id     | int     |
    +| view_date     | date    |
    ++---------------+---------+
    +此表无主键,因此可能会存在重复行。此表的每一行都表示某人在某天浏览了某位作者的某篇文章。 请注意,同一人的 author_id 和 viewer_id 是相同的。
    +
    + +

     

    + +

    编写一条 SQL 查询来找出在同一天阅读至少两篇文章的人,结果按照 id 升序排序。

    + +

    查询结果的格式如下:

    + +
    +Views table:
    ++------------+-----------+-----------+------------+
    +| article_id | author_id | viewer_id | view_date  |
    ++------------+-----------+-----------+------------+
    +| 1          | 3         | 5         | 2019-08-01 |
    +| 3          | 4         | 5         | 2019-08-01 |
    +| 1          | 3         | 6         | 2019-08-02 |
    +| 2          | 7         | 7         | 2019-08-01 |
    +| 2          | 7         | 6         | 2019-08-02 |
    +| 4          | 7         | 1         | 2019-07-22 |
    +| 3          | 4         | 4         | 2019-07-21 |
    +| 3          | 4         | 4         | 2019-07-21 |
    ++------------+-----------+-----------+------------+
    +
    +Result table:
    ++------+
    +| id   |
    ++------+
    +| 5    |
    +| 6    |
    ++------+
    + +## 解法 + + + +“`DISTINCT` + `GROUP BY`” 实现。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + DISTINCT(viewer_id) as id +FROM + Views +GROUP BY + view_date, viewer_id +HAVING + COUNT(DISTINCT(article_id)) > 1 +ORDER BY + id; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1150.leetcode1150 Check If a Number Is Majority Element in a Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1150.leetcode1150 Check If a Number Is Majority Element in a Sorted Array-zh.md" new file mode 100644 index 00000000..932c018a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1150.leetcode1150 Check If a Number Is Majority Element in a Sorted Array-zh.md" @@ -0,0 +1,150 @@ +# [1150. 检查一个数是否在数组中占绝大多数](https://leetcode-cn.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1150.Check%20If%20a%20Number%20Is%20Majority%20Element%20in%20a%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给出一个按 非递减 顺序排列的数组 nums,和一个目标数值 target。假如数组 nums 中绝大多数元素的数值都等于 target,则返回 True,否则请返回 False

    + +

    所谓占绝大多数,是指在长度为 N 的数组中出现必须 超过 N/2 

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,4,5,5,5,5,5,6,6], target = 5
    +输出:true
    +解释:
    +数字 5 出现了 5 次,而数组的长度为 9。
    +所以,5 在数组中占绝大多数,因为 5 次 > 9/2。
    +
    + +

    示例 2:

    + +
    +输入:nums = [10,100,101,101], target = 101
    +输出:false
    +解释:
    +数字 101 出现了 2 次,而数组的长度是 4。
    +所以,101 不是 数组占绝大多数的元素,因为 2 次 = 4/2。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 10^9
    • +
    • 1 <= target <= 10^9
    • +
    + +## 解法 + + + +“二分查找”求 `target` 在数组 `nums` 中的左右边界。 + + + +### **Python3** + + + +自己实现二分查找: + +```python +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + def bsearch_left(nums, target, left, right): + while left < right: + mid = (left + right) >> 1 + if nums[mid] >= target: + right = mid + else: + left = mid + 1 + return left if nums[left] == target else -1 + + def bsearch_right(nums, target, left, right): + while left < right: + mid = (left + right + 1) >> 1 + if nums[mid] <= target: + left = mid + else: + right = mid - 1 + return left if nums[left] == target else -1 + + n = len(nums) + left = bsearch_left(nums, target, 0, n - 1) + if left == -1: + return False + right = bsearch_right(nums, target, left, n - 1) + if right == -1: + return False + return right - left + 1 > n >> 1 +``` + +使用 `bisect` 实现二分查找: + +```python +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + left, right = bisect.bisect_left(nums, target), bisect.bisect_right(nums, target) + return right - left > (len(nums) >> 1) +``` + +### **Java** + + + +```java +class Solution { + public boolean isMajorityElement(int[] nums, int target) { + int n = nums.length; + int left = bsearchLeft(nums, target, 0, n - 1); + if (left == -1) { + return false; + } + int right = bsearchRight(nums, target, left, n - 1); + if (right == -1) { + return false; + } + return right - left + 1 > (n >> 1); + } + + private int bsearchLeft(int[] nums, int target, int left, int right) { + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; + } + + private int bsearchRight(int[] nums, int target, int left, int right) { + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums[mid] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return nums[left] == target ? left : -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1151.leetcode1151 Minimum Swaps to Group All 1's Together-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1151.leetcode1151 Minimum Swaps to Group All 1's Together-zh.md" new file mode 100644 index 00000000..63e39a31 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1151.leetcode1151 Minimum Swaps to Group All 1's Together-zh.md" @@ -0,0 +1,79 @@ +# [1151. 最少交换次数来组合所有的 1](https://leetcode-cn.com/problems/minimum-swaps-to-group-all-1s-together) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1151.Minimum%20Swaps%20to%20Group%20All%201%27s%20Together/README_EN.md) + +## 题目描述 + + + +

    给出一个二进制数组 data,你需要通过交换位置,将数组中 任何位置 上的 1 组合到一起,并返回所有可能中所需 最少的交换次数

    + +

     

    + +

    示例 1:

    + +
    输入:[1,0,1,0,1]
    +输出:1
    +解释: 
    +有三种可能的方法可以把所有的 1 组合在一起:
    +[1,1,1,0,0],交换 1 次;
    +[0,1,1,1,0],交换 2 次;
    +[0,0,1,1,1],交换 1 次。
    +所以最少的交换次数为 1。
    +
    + +

    示例 2:

    + +
    输入:[0,0,0,1,0]
    +输出:0
    +解释: 
    +由于数组中只有一个 1,所以不需要交换。
    +
    + +

    示例 3:

    + +
    输入:[1,0,1,0,1,0,0,1,1,0,1]
    +输出:3
    +解释:
    +交换 3 次,一种可行的只用 3 次交换的解决方案是 [0,0,0,0,0,1,1,1,1,1,1]。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= data.length <= 10^5
    2. +
    3. 0 <= data[i] <= 1
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1152.leetcode1152 Analyze User Website Visit Pattern-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1152.leetcode1152 Analyze User Website Visit Pattern-zh.md" new file mode 100644 index 00000000..a7458092 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1152.leetcode1152 Analyze User Website Visit Pattern-zh.md" @@ -0,0 +1,87 @@ +# [1152. 用户网站访问行为分析](https://leetcode-cn.com/problems/analyze-user-website-visit-pattern) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1152.Analyze%20User%20Website%20Visit%20Pattern/README_EN.md) + +## 题目描述 + + + +

    为了评估某网站的用户转化率,我们需要对用户的访问行为进行分析,并建立用户行为模型。日志文件中已经记录了用户名、访问时间 以及 页面路径。

    + +

    为了方便分析,日志文件中的 N 条记录已经被解析成三个长度相同且长度都为 N 的数组,分别是:用户名 username,访问时间 timestamp 和 页面路径 website。第 i 条记录意味着用户名是 username[i] 的用户在 timestamp[i] 的时候访问了路径为 website[i] 的页面。

    + +

    我们需要找到用户访问网站时的 『共性行为路径』,也就是有最多的用户都 至少按某种次序访问过一次 的三个页面路径。需要注意的是,用户 可能不是连续访问 这三个路径的。

    + +

    『共性行为路径』是一个 长度为 3 的页面路径列表,列表中的路径 不必不同,并且按照访问时间的先后升序排列。

    + +

    如果有多个满足要求的答案,那么就请返回按字典序排列最小的那个。(页面路径列表 X 按字典序小于 Y 的前提条件是:X[0] < Y[0]X[0] == Y[0] 且 (X[1] < Y[1] 或 X[1] == Y[1] 且 X[2] < Y[2])

    + +

    题目保证一个用户会至少访问 3 个路径一致的页面,并且一个用户不会在同一时间访问两个路径不同的页面。

    + +

     

    + +

    示例:

    + +
    输入:username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"], timestamp = [1,2,3,4,5,6,7,8,9,10], website = ["home","about","career","home","cart","maps","home","home","about","career"]
    +输出:["home","about","career"]
    +解释:
    +由示例输入得到的记录如下:
    +["joe", 1, "home"]
    +["joe", 2, "about"]
    +["joe", 3, "career"]
    +["james", 4, "home"]
    +["james", 5, "cart"]
    +["james", 6, "maps"]
    +["james", 7, "home"]
    +["mary", 8, "home"]
    +["mary", 9, "about"]
    +["mary", 10, "career"]
    +有 2 个用户至少访问过一次 ("home", "about", "career")。
    +有 1 个用户至少访问过一次 ("home", "cart", "maps")。
    +有 1 个用户至少访问过一次 ("home", "cart", "home")。
    +有 1 个用户至少访问过一次 ("home", "maps", "home")。
    +有 1 个用户至少访问过一次 ("cart", "maps", "home")。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 3 <= N = username.length = timestamp.length = website.length <= 50
    2. +
    3. 1 <= username[i].length <= 10
    4. +
    5. 0 <= timestamp[i] <= 10^9
    6. +
    7. 1 <= website[i].length <= 10
    8. +
    9. username[i] 和 website[i] 都只含小写字符
    10. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1153.leetcode1153 String Transforms Into Another String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1153.leetcode1153 String Transforms Into Another String-zh.md" new file mode 100644 index 00000000..b5edcabe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1153.leetcode1153 String Transforms Into Another String-zh.md" @@ -0,0 +1,69 @@ +# [1153. 字符串转化](https://leetcode-cn.com/problems/string-transforms-into-another-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1153.String%20Transforms%20Into%20Another%20String/README_EN.md) + +## 题目描述 + + + +

    给出两个长度相同的字符串,分别是 str1 和 str2。请你帮忙判断字符串 str1 能不能在 零次 或 多次 转化后变成字符串 str2

    + +

    每一次转化时,将会一次性将 str1 中出现的 所有 相同字母变成其他 任何 小写英文字母(见示例)。

    + +

    只有在字符串 str1 能够通过上述方式顺利转化为字符串 str2 时才能返回 True,否则返回 False。​​

    + +

     

    + +

    示例 1:

    + +
    输入:str1 = "aabcc", str2 = "ccdee"
    +输出:true
    +解释:将 'c' 变成 'e',然后把 'b' 变成 'd',接着再把 'a' 变成 'c'。注意,转化的顺序也很重要。
    +
    + +

    示例 2:

    + +
    输入:str1 = "leetcode", str2 = "codeleet"
    +输出:false
    +解释:我们没有办法能够把 str1 转化为 str2。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= str1.length == str2.length <= 10^4
    2. +
    3. str1 和 str2 中都只会出现 小写英文字母
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1154.leetcode1154 Day of the Year-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1154.leetcode1154 Day of the Year-zh.md" new file mode 100644 index 00000000..aa3860cb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1154.leetcode1154 Day of the Year-zh.md" @@ -0,0 +1,77 @@ +# [1154. 一年中的第几天](https://leetcode-cn.com/problems/day-of-the-year) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1154.Day%20of%20the%20Year/README_EN.md) + +## 题目描述 + + + +

    给你一个按 YYYY-MM-DD 格式表示日期的字符串 date,请你计算并返回该日期是当年的第几天。

    + +

    通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。

    + +

     

    + +

    示例 1:

    + +
    输入:date = "2019-01-09"
    +输出:9
    +
    + +

    示例 2:

    + +
    输入:date = "2019-02-10"
    +输出:41
    +
    + +

    示例 3:

    + +
    输入:date = "2003-03-01"
    +输出:60
    +
    + +

    示例 4:

    + +
    输入:date = "2004-03-01"
    +输出:61
    + +

     

    + +

    提示:

    + +
      +
    • date.length == 10
    • +
    • date[4] == date[7] == '-',其他的 date[i] 都是数字。
    • +
    • date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1155.leetcode1155 Number of Dice Rolls With Target Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1155.leetcode1155 Number of Dice Rolls With Target Sum-zh.md" new file mode 100644 index 00000000..16540374 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1155.leetcode1155 Number of Dice Rolls With Target Sum-zh.md" @@ -0,0 +1,84 @@ +# [1155. 掷骰子的N种方法](https://leetcode-cn.com/problems/number-of-dice-rolls-with-target-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1155.Number%20of%20Dice%20Rolls%20With%20Target%20Sum/README_EN.md) + +## 题目描述 + + + +

    这里有 d 个一样的骰子,每个骰子上都有 f 个面,分别标号为 1, 2, ..., f

    + +

    我们约定:掷骰子的得到总点数为各骰子面朝上的数字的总和。

    + +

    如果需要掷出的总点数为 target,请你计算出有多少种不同的组合情况(所有的组合情况总共有 f^d 种),模 10^9 + 7 后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:d = 1, f = 6, target = 3
    +输出:1
    +
    + +

    示例 2:

    + +
    输入:d = 2, f = 6, target = 7
    +输出:6
    +
    + +

    示例 3:

    + +
    输入:d = 2, f = 5, target = 10
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:d = 1, f = 2, target = 3
    +输出:0
    +
    + +

    示例 5:

    + +
    输入:d = 30, f = 30, target = 500
    +输出:222616187
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= d, f <= 30
    • +
    • 1 <= target <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1156.leetcode1156 Swap For Longest Repeated Character Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1156.leetcode1156 Swap For Longest Repeated Character Substring-zh.md" new file mode 100644 index 00000000..1da2e592 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1156.leetcode1156 Swap For Longest Repeated Character Substring-zh.md" @@ -0,0 +1,83 @@ +# [1156. 单字符重复子串的最大长度](https://leetcode-cn.com/problems/swap-for-longest-repeated-character-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1156.Swap%20For%20Longest%20Repeated%20Character%20Substring/README_EN.md) + +## 题目描述 + + + +

    如果字符串中的所有字符都相同,那么这个字符串是单字符重复的字符串。

    + +

    给你一个字符串 text,你只能交换其中两个字符一次或者什么都不做,然后得到一些单字符重复的子串。返回其中最长的子串的长度。

    + +

     

    + +

    示例 1:

    + +
    输入:text = "ababa"
    +输出:3
    +
    + +

    示例 2:

    + +
    输入:text = "aaabaaa"
    +输出:6
    +
    + +

    示例 3:

    + +
    输入:text = "aaabbaaa"
    +输出:4
    +
    + +

    示例 4:

    + +
    输入:text = "aaaaa"
    +输出:5
    +
    + +

    示例 5:

    + +
    输入:text = "abcdef"
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text.length <= 20000
    • +
    • text 仅由小写英文字母组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1157.leetcode1157 Online Majority Element In Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1157.leetcode1157 Online Majority Element In Subarray-zh.md" new file mode 100644 index 00000000..f914f738 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1157.leetcode1157 Online Majority Element In Subarray-zh.md" @@ -0,0 +1,74 @@ +# [1157. 子数组中占绝大多数的元素](https://leetcode-cn.com/problems/online-majority-element-in-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1157.Online%20Majority%20Element%20In%20Subarray/README_EN.md) + +## 题目描述 + + + +

    实现一个 MajorityChecker 的类,它应该具有下述几个 API:

    + +
      +
    • MajorityChecker(int[] arr) 会用给定的数组 arr 来构造一个 MajorityChecker 的实例。
    • +
    • int query(int left, int right, int threshold) 有这么几个参数: +
        +
      • 0 <= left <= right < arr.length 表示数组 arr 的子数组的长度。
      • +
      • 2 * threshold > right - left + 1,也就是说阈值 threshold 始终比子序列长度的一半还要大。
      • +
      +
    • +
    + +

    每次查询 query(...) 会返回在 arr[left], arr[left+1], ..., arr[right] 中至少出现阈值次数 threshold 的元素,如果不存在这样的元素,就返回 -1

    + +

     

    + +

    示例:

    + +
    MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
    +majorityChecker.query(0,5,4); // 返回 1
    +majorityChecker.query(0,3,3); // 返回 -1
    +majorityChecker.query(2,3,2); // 返回 2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 20000
    • +
    • 1 <= arr[i] <= 20000
    • +
    • 对于每次查询,0 <= left <= right < len(arr)
    • +
    • 对于每次查询,2 * threshold > right - left + 1
    • +
    • 查询次数最多为 10000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1158.leetcode1158 Market Analysis I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1158.leetcode1158 Market Analysis I-zh.md" new file mode 100644 index 00000000..09338381 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1158.leetcode1158 Market Analysis I-zh.md" @@ -0,0 +1,112 @@ +# [1158. 市场分析 I](https://leetcode-cn.com/problems/market-analysis-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1158.Market%20Analysis%20I/README_EN.md) + +## 题目描述 + + + +

    Table: Users

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| user_id        | int     |
    +| join_date      | date    |
    +| favorite_brand | varchar |
    ++----------------+---------+
    +此表主键是 user_id,表中描述了购物网站的用户信息,用户可以在此网站上进行商品买卖。
    +
    + +

    Table: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| item_id       | int     |
    +| buyer_id      | int     |
    +| seller_id     | int     |
    ++---------------+---------+
    +此表主键是 order_id,外键是 item_id 和(buyer_id,seller_id)。
    +
    + +

    Table: Item

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| item_id       | int     |
    +| item_brand    | varchar |
    ++---------------+---------+
    +此表主键是 item_id。
    +
    + +

     

    + +

    请写出一条SQL语句以查询每个用户的注册日期和在 2019 年作为买家的订单总数。

    + +

    查询结果格式如下:

    + +
    +Users table:
    ++---------+------------+----------------+
    +| user_id | join_date  | favorite_brand |
    ++---------+------------+----------------+
    +| 1       | 2018-01-01 | Lenovo         |
    +| 2       | 2018-02-09 | Samsung        |
    +| 3       | 2018-01-19 | LG             |
    +| 4       | 2018-05-21 | HP             |
    ++---------+------------+----------------+
    +
    +Orders table:
    ++----------+------------+---------+----------+-----------+
    +| order_id | order_date | item_id | buyer_id | seller_id |
    ++----------+------------+---------+----------+-----------+
    +| 1        | 2019-08-01 | 4       | 1        | 2         |
    +| 2        | 2018-08-02 | 2       | 1        | 3         |
    +| 3        | 2019-08-03 | 3       | 2        | 3         |
    +| 4        | 2018-08-04 | 1       | 4        | 2         |
    +| 5        | 2018-08-04 | 1       | 3        | 4         |
    +| 6        | 2019-08-05 | 2       | 2        | 4         |
    ++----------+------------+---------+----------+-----------+
    +
    +Items table:
    ++---------+------------+
    +| item_id | item_brand |
    ++---------+------------+
    +| 1       | Samsung    |
    +| 2       | Lenovo     |
    +| 3       | LG         |
    +| 4       | HP         |
    ++---------+------------+
    +
    +Result table:
    ++-----------+------------+----------------+
    +| buyer_id  | join_date  | orders_in_2019 |
    ++-----------+------------+----------------+
    +| 1         | 2018-01-01 | 1              |
    +| 2         | 2018-02-09 | 2              |
    +| 3         | 2018-01-19 | 0              |
    +| 4         | 2018-05-21 | 0              |
    ++-----------+------------+----------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1159.leetcode1159 Market Analysis II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1159.leetcode1159 Market Analysis II-zh.md" new file mode 100644 index 00000000..d01bffc6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1159.leetcode1159 Market Analysis II-zh.md" @@ -0,0 +1,121 @@ +# [1159. 市场分析 II](https://leetcode-cn.com/problems/market-analysis-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1159.Market%20Analysis%20II/README_EN.md) + +## 题目描述 + + + +

    表: Users

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| user_id        | int     |
    +| join_date      | date    |
    +| favorite_brand | varchar |
    ++----------------+---------+
    +user_id 是该表的主键
    +表中包含一位在线购物网站用户的个人信息,用户可以在该网站出售和购买商品。
    +
    + +

    表: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| item_id       | int     |
    +| buyer_id      | int     |
    +| seller_id     | int     |
    ++---------------+---------+
    +order_id 是该表的主键
    +item_id 是 Items 表的外键
    +buyer_id 和 seller_id 是 Users 表的外键
    +
    + +

    表: Items

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| item_id       | int     |
    +| item_brand    | varchar |
    ++---------------+---------+
    +item_id 是该表的主键
    +
    + +

     

    + +

    写一个 SQL 查询确定每一个用户按日期顺序卖出的第二件商品的品牌是否是他们最喜爱的品牌。如果一个用户卖出少于两件商品,查询的结果是 no

    + +

    题目保证没有一个用户在一天中卖出超过一件商品

    + +

    下面是查询结果格式的例子:

    + +
    +Users table:
    ++---------+------------+----------------+
    +| user_id | join_date  | favorite_brand |
    ++---------+------------+----------------+
    +| 1       | 2019-01-01 | Lenovo         |
    +| 2       | 2019-02-09 | Samsung        |
    +| 3       | 2019-01-19 | LG             |
    +| 4       | 2019-05-21 | HP             |
    ++---------+------------+----------------+
    +
    +Orders table:
    ++----------+------------+---------+----------+-----------+
    +| order_id | order_date | item_id | buyer_id | seller_id |
    ++----------+------------+---------+----------+-----------+
    +| 1        | 2019-08-01 | 4       | 1        | 2         |
    +| 2        | 2019-08-02 | 2       | 1        | 3         |
    +| 3        | 2019-08-03 | 3       | 2        | 3         |
    +| 4        | 2019-08-04 | 1       | 4        | 2         |
    +| 5        | 2019-08-04 | 1       | 3        | 4         |
    +| 6        | 2019-08-05 | 2       | 2        | 4         |
    ++----------+------------+---------+----------+-----------+
    +
    +Items table:
    ++---------+------------+
    +| item_id | item_brand |
    ++---------+------------+
    +| 1       | Samsung    |
    +| 2       | Lenovo     |
    +| 3       | LG         |
    +| 4       | HP         |
    ++---------+------------+
    +
    +Result table:
    ++-----------+--------------------+
    +| seller_id | 2nd_item_fav_brand |
    ++-----------+--------------------+
    +| 1         | no                 |
    +| 2         | yes                |
    +| 3         | yes                |
    +| 4         | no                 |
    ++-----------+--------------------+
    +
    +id 为 1 的用户的查询结果是 no,因为他什么也没有卖出
    +id为 2 和 3 的用户的查询结果是 yes,因为他们卖出的第二件商品的品牌是他们自己最喜爱的品牌
    +id为 4 的用户的查询结果是 no,因为他卖出的第二件商品的品牌不是他最喜爱的品牌
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1160.leetcode1160 Find Words That Can Be Formed by Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1160.leetcode1160 Find Words That Can Be Formed by Characters-zh.md" new file mode 100644 index 00000000..e20da1ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1160.leetcode1160 Find Words That Can Be Formed by Characters-zh.md" @@ -0,0 +1,74 @@ +# [1160. 拼写单词](https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1160.Find%20Words%20That%20Can%20Be%20Formed%20by%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars

    + +

    假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

    + +

    注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。

    + +

    返回词汇表 words 中你掌握的所有单词的 长度之和

    + +

     

    + +

    示例 1:

    + +
    输入:words = ["cat","bt","hat","tree"], chars = "atach"
    +输出:6
    +解释: 
    +可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
    +
    + +

    示例 2:

    + +
    输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
    +输出:10
    +解释:
    +可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= words.length <= 1000
    2. +
    3. 1 <= words[i].length, chars.length <= 100
    4. +
    5. 所有字符串中都仅包含小写英文字母
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1161.leetcode1161 Maximum Level Sum of a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1161.leetcode1161 Maximum Level Sum of a Binary Tree-zh.md" new file mode 100644 index 00000000..bc2e1f6e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1161.leetcode1161 Maximum Level Sum of a Binary Tree-zh.md" @@ -0,0 +1,72 @@ +# [1161. 最大层内元素和](https://leetcode-cn.com/problems/maximum-level-sum-of-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1161.Maximum%20Level%20Sum%20of%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。

    + +

    请你找出层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [1,7,0,7,-8,null,null]
    +输出:2
    +解释:
    +第 1 层各元素之和为 1,
    +第 2 层各元素之和为 7 + 0 = 7,
    +第 3 层各元素之和为 7 + -8 = -1,
    +所以我们返回第 2 层的层号,它的层内元素之和最大。
    +
    + +

    示例 2:

    + +
    输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中的节点数介于 1 和 10^4 之间
    • +
    • -10^5 <= node.val <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1162.leetcode1162 As Far from Land as Possible-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1162.leetcode1162 As Far from Land as Possible-zh.md" new file mode 100644 index 00000000..ea5fce73 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1162.leetcode1162 As Far from Land as Possible-zh.md" @@ -0,0 +1,75 @@ +# [1162. 地图分析](https://leetcode-cn.com/problems/as-far-from-land-as-possible) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1162.As%20Far%20from%20Land%20as%20Possible/README_EN.md) + +## 题目描述 + + + +

    你现在手里有一份大小为 N x N 的 网格 grid,上面的每个 单元格 都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,请你找出一个海洋单元格,这个海洋单元格到离它最近的陆地单元格的距离是最大的。

    + +

    我们这里说的距离是「曼哈顿距离」( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个单元格之间的距离是 |x0 - x1| + |y0 - y1| 。

    + +

    如果网格上只有陆地或者海洋,请返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:[[1,0,1],[0,0,0],[1,0,1]]
    +输出:2
    +解释: 
    +海洋单元格 (1, 1) 和所有陆地单元格之间的距离都达到最大,最大距离为 2。
    +
    + +

    示例 2:

    + +

    + +
    输入:[[1,0,0],[0,0,0],[0,0,0]]
    +输出:4
    +解释: 
    +海洋单元格 (2, 2) 和所有陆地单元格之间的距离都达到最大,最大距离为 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= grid.length == grid[0].length <= 100
    2. +
    3. grid[i][j] 不是 0 就是 1
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1163.leetcode1163 Last Substring in Lexicographical Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1163.leetcode1163 Last Substring in Lexicographical Order-zh.md" new file mode 100644 index 00000000..92908527 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1163.leetcode1163 Last Substring in Lexicographical Order-zh.md" @@ -0,0 +1,64 @@ +# [1163. 按字典序排在最后的子串](https://leetcode-cn.com/problems/last-substring-in-lexicographical-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1163.Last%20Substring%20in%20Lexicographical%20Order/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,找出它的所有子串并按字典序排列,返回排在最后的那个子串。

    + +

     

    + +

    示例 1:

    + +
    输入:"abab"
    +输出:"bab"
    +解释:我们可以找出 7 个子串 ["a", "ab", "aba", "abab", "b", "ba", "bab"]。按字典序排在最后的子串是 "bab"。
    +
    + +

    示例 2:

    + +
    输入:"leetcode"
    +输出:"tcode"
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= s.length <= 4 * 10^5
    2. +
    3. s 仅含有小写英文字符。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1164.leetcode1164 Product Price at a Given Date-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1164.leetcode1164 Product Price at a Given Date-zh.md" new file mode 100644 index 00000000..f48c843d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1164.leetcode1164 Product Price at a Given Date-zh.md" @@ -0,0 +1,64 @@ +# [1164. 指定日期的产品价格](https://leetcode-cn.com/problems/product-price-at-a-given-date) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1164.Product%20Price%20at%20a%20Given%20Date/README_EN.md) + +## 题目描述 + + + +

    产品数据表: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| new_price     | int     |
    +| change_date   | date    |
    ++---------------+---------+
    +这张表的主键是 (product_id, change_date)。
    +这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。
    + +

     

    + +

    写一段 SQL来查找在 2019-08-16 时全部产品的价格,假设所有产品在修改前的价格都是 10。

    + +

    查询结果格式如下例所示:

    + +
    +Products table:
    ++------------+-----------+-------------+
    +| product_id | new_price | change_date |
    ++------------+-----------+-------------+
    +| 1          | 20        | 2019-08-14  |
    +| 2          | 50        | 2019-08-14  |
    +| 1          | 30        | 2019-08-15  |
    +| 1          | 35        | 2019-08-16  |
    +| 2          | 65        | 2019-08-17  |
    +| 3          | 20        | 2019-08-18  |
    ++------------+-----------+-------------+
    +
    +Result table:
    ++------------+-------+
    +| product_id | price |
    ++------------+-------+
    +| 2          | 50    |
    +| 1          | 35    |
    +| 3          | 10    |
    ++------------+-------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1165.leetcode1165 Single-Row Keyboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1165.leetcode1165 Single-Row Keyboard-zh.md" new file mode 100644 index 00000000..ea3feee1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1165.leetcode1165 Single-Row Keyboard-zh.md" @@ -0,0 +1,144 @@ +# [1165. 单行键盘](https://leetcode-cn.com/problems/single-row-keyboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1165.Single-Row%20Keyboard/README_EN.md) + +## 题目描述 + + + +

    我们定制了一款特殊的力扣键盘,所有的键都排列在一行上。

    + +

    我们可以按从左到右的顺序,用一个长度为 26 的字符串 keyboard (索引从 0 开始,到 25 结束)来表示该键盘的键位布局。

    + +

    现在需要测试这个键盘是否能够有效工作,那么我们就需要个机械手来测试这个键盘。

    + +

    最初的时候,机械手位于左边起第一个键(也就是索引为 0 的键)的上方。当机械手移动到某一字符所在的键位时,就会在终端上输出该字符。

    + +

    机械手从索引 i 移动到索引 j 所需要的时间是 |i - j|

    + +

    当前测试需要你使用机械手输出指定的单词 word,请你编写一个函数来计算机械手输出该单词所需的时间。

    + +

     

    + +

    示例 1:

    + +
    输入:keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
    +输出:4
    +解释:
    +机械手从 0 号键移动到 2 号键来输出 'c',又移动到 1 号键来输出 'b',接着移动到 0 号键来输出 'a'。
    +总用时 = 2 + 1 + 1 = 4. 
    +
    + +

    示例 2:

    + +
    输入:keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"
    +输出:73
    +
    + +

     

    + +

    提示:

    + +
      +
    • keyboard.length == 26
    • +
    • keyboard 按某种特定顺序排列,并包含每个小写英文字母一次。
    • +
    • 1 <= word.length <= 10^4
    • +
    • word[i] 是一个小写英文字母
    • +
    + +## 解法 + + + +哈希表实现。 + + + +### **Python3** + + + +```python +class Solution: + def calculateTime(self, keyboard: str, word: str) -> int: + index = {c: i for i, c in enumerate(keyboard)} + res = t = 0 + for c in word: + res += abs(index[c] - t) + t = index[c] + return res +``` + +### **Java** + + + +```java +class Solution { + public int calculateTime(String keyboard, String word) { + Map index = new HashMap<>(); + for (int i = 0; i < keyboard.length(); ++i) { + index.put(keyboard.charAt(i), i); + } + int res = 0, t = 0; + for (char c : word.toCharArray()) { + res += Math.abs(index.get(c) - t); + t = index.get(c); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int calculateTime(string keyboard, string word) { + unordered_map index; + for (int i = 0; i < keyboard.size(); ++i) { + index[keyboard[i]] = i; + } + int res = 0, t = 0; + for (char c : word) { + res += abs(index[c] - t); + t = index[c]; + } + return res; + } +}; +``` + +### **Go** + +```go +func calculateTime(keyboard string, word string) int { + index := map[byte]int{} + for i := 0; i < len(keyboard); i++ { + index[keyboard[i]] = i + } + res := 0 + t := 0 + for i := 0; i < len(word); i++ { + res += abs(index[word[i]] - t) + t = index[word[i]] + } + return res +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1166.leetcode1166 Design File System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1166.leetcode1166 Design File System-zh.md" new file mode 100644 index 00000000..1b798f6a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1166.leetcode1166 Design File System-zh.md" @@ -0,0 +1,94 @@ +# [1166. 设计文件系统](https://leetcode-cn.com/problems/design-file-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1166.Design%20File%20System/README_EN.md) + +## 题目描述 + + + +

    你需要设计一个能提供下面两个函数的文件系统:

    + +
      +
    • create(path, value): 创建一个新的路径,并尽可能将值 value 与路径 path 关联,然后返回 True。如果路径已经存在或者路径的父路径不存在,则返回 False
    • +
    • get(path): 返回与路径关联的值。如果路径不存在,则返回 -1
    • +
    + +

    “路径” 是由一个或多个符合下述格式的字符串连接起来形成的:在 / 后跟着一个或多个小写英文字母。

    + +

    例如 /leetcode 和 /leetcode/problems 都是有效的路径,但空字符串和 / 不是有效的路径。

    + +

    好了,接下来就请你来实现这两个函数吧!(请参考示例以获得更多信息)

    + +

     

    + +

    示例 1:

    + +
    输入: 
    +["FileSystem","create","get"]
    +[[],["/a",1],["/a"]]
    +输出: 
    +[null,true,1]
    +解释: 
    +FileSystem fileSystem = new FileSystem();
    +
    +fileSystem.create("/a", 1); // 返回 true
    +fileSystem.get("/a"); // 返回 1
    +
    + +

    示例 2:

    + +
    输入: 
    +["FileSystem","create","create","get","create","get"]
    +[[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]]
    +输出: 
    +[null,true,true,2,false,-1]
    +解释:
    +FileSystem fileSystem = new FileSystem();
    +
    +fileSystem.create("/leet", 1); // 返回 true
    +fileSystem.create("/leet/code", 2); // 返回 true
    +fileSystem.get("/leet/code"); // 返回 2
    +fileSystem.create("/c/d", 1); // 返回 false 因为父路径 "/c" 不存在。
    +fileSystem.get("/c"); // 返回 -1 因为该路径不存在。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 对两个函数的调用次数加起来小于等于 10^4
    • +
    • 2 <= path.length <= 100
    • +
    • 1 <= value <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1167.leetcode1167 Minimum Cost to Connect Sticks-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1167.leetcode1167 Minimum Cost to Connect Sticks-zh.md" new file mode 100644 index 00000000..498b1146 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1167.leetcode1167 Minimum Cost to Connect Sticks-zh.md" @@ -0,0 +1,86 @@ +# [1167. 连接棒材的最低费用](https://leetcode-cn.com/problems/minimum-cost-to-connect-sticks) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1167.Minimum%20Cost%20to%20Connect%20Sticks/README_EN.md) + +## 题目描述 + + + +

    为了装修新房,你需要加工一些长度为正整数的棒材 。棒材以数组 sticks 的形式给出,其中 sticks[i] 是第 i 根棒材的长度。

    + +

    如果要将长度分别为 xy 的两根棒材连接在一起,你需要支付 x + y 的费用。 由于施工需要,你必须将所有棒材连接成一根。

    + +

    返回你把所有棒材 sticks 连成一根所需要的最低费用。注意你可以任意选择棒材连接的顺序。

    + +

     

    + +

    示例 1:

    + +
    +输入:sticks = [2,4,3]
    +输出:14
    +解释:从 sticks = [2,4,3] 开始。
    +1. 连接 2 和 3 ,费用为 2 + 3 = 5 。现在 sticks = [5,4]
    +2. 连接 5 和 4 ,费用为 5 + 4 = 9 。现在 sticks = [9]
    +所有棒材已经连成一根,总费用 5 + 9 = 14
    +
    + +

    示例 2:

    + +
    +输入:sticks = [1,8,3,5]
    +输出:30
    +解释:从 sticks = [1,8,3,5] 开始。
    +1. 连接 1 和 3 ,费用为 1 + 3 = 4 。现在 sticks = [4,8,5]
    +2. 连接 4 和 5 ,费用为 4 + 5 = 9 。现在 sticks = [9,8]
    +3. 连接 9 和 8 ,费用为 9 + 8 = 17 。现在 sticks = [17]
    +所有棒材已经连成一根,总费用 4 + 9 + 17 = 30
    +
    + +

    示例 3:

    + +
    +输入:sticks = [5]
    +输出:0
    +解释:只有一根棒材,不必再连接。总费用 0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= sticks.length <= 104
    • +
    • 1 <= sticks[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1168.leetcode1168 Optimize Water Distribution in a Village-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1168.leetcode1168 Optimize Water Distribution in a Village-zh.md" new file mode 100644 index 00000000..42876f95 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1168.leetcode1168 Optimize Water Distribution in a Village-zh.md" @@ -0,0 +1,76 @@ +# [1168. 水资源分配优化](https://leetcode-cn.com/problems/optimize-water-distribution-in-a-village) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1168.Optimize%20Water%20Distribution%20in%20a%20Village/README_EN.md) + +## 题目描述 + + + +

    村里面一共有 n 栋房子。我们希望通过建造水井和铺设管道来为所有房子供水。

    + +

    对于每个房子 i,我们有两种可选的供水方案:

    + +
      +
    • 一种是直接在房子内建造水井,成本为 wells[i]
    • +
    • 另一种是从另一口井铺设管道引水,数组 pipes 给出了在房子间铺设管道的成本,其中每个 pipes[i] = [house1, house2, cost] 代表用管道将 house1 和 house2 连接在一起的成本。当然,连接是双向的。
    • +
    + +

    请你帮忙计算为所有房子都供水的最低总成本。

    + +

     

    + +

    示例:

    + +

    + +
    输入:n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
    +输出:3
    +解释: 
    +上图展示了铺设管道连接房屋的成本。
    +最好的策略是在第一个房子里建造水井(成本为 1),然后将其他房子铺设管道连起来(成本为 2),所以总成本为 3。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10000
    • +
    • wells.length == n
    • +
    • 0 <= wells[i] <= 10^5
    • +
    • 1 <= pipes.length <= 10000
    • +
    • 1 <= pipes[i][0], pipes[i][1] <= n
    • +
    • 0 <= pipes[i][2] <= 10^5
    • +
    • pipes[i][0] != pipes[i][1]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1169.leetcode1169 Invalid Transactions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1169.leetcode1169 Invalid Transactions-zh.md" new file mode 100644 index 00000000..e9adccae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1169.leetcode1169 Invalid Transactions-zh.md" @@ -0,0 +1,81 @@ +# [1169. 查询无效交易](https://leetcode-cn.com/problems/invalid-transactions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1169.Invalid%20Transactions/README_EN.md) + +## 题目描述 + + + +

    如果出现下述两种情况,交易 可能无效

    + +
      +
    • 交易金额超过 ¥1000
    • +
    • 或者,它和另一个城市中同名的另一笔交易相隔不超过 60 分钟(包含 60 分钟整)
    • +
    + +

    每个交易字符串 transactions[i] 由一些用逗号分隔的值组成,这些值分别表示交易的名称,时间(以分钟计),金额以及城市。

    + +

    给你一份交易清单 transactions,返回可能无效的交易列表。你可以按任何顺序返回答案。

    + +

     

    + +

    示例 1:

    + +
    输入:transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
    +输出:["alice,20,800,mtv","alice,50,100,beijing"]
    +解释:第一笔交易是无效的,因为第二笔交易和它间隔不超过 60 分钟、名称相同且发生在不同的城市。同样,第二笔交易也是无效的。
    + +

    示例 2:

    + +
    输入:transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
    +输出:["alice,50,1200,mtv"]
    +
    + +

    示例 3:

    + +
    输入:transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
    +输出:["bob,50,1200,mtv"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • transactions.length <= 1000
    • +
    • 每笔交易 transactions[i] 按 "{name},{time},{amount},{city}" 的格式进行记录
    • +
    • 每个交易名称 {name} 和城市 {city} 都由小写英文字母组成,长度在 1 到 10 之间
    • +
    • 每个交易时间 {time} 由一些数字组成,表示一个 0 到 1000 之间的整数
    • +
    • 每笔交易金额 {amount} 由一些数字组成,表示一个 0 到 2000 之间的整数
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1170.leetcode1170 Compare Strings by Frequency of the Smallest Character-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1170.leetcode1170 Compare Strings by Frequency of the Smallest Character-zh.md" new file mode 100644 index 00000000..c800fdc8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1170.leetcode1170 Compare Strings by Frequency of the Smallest Character-zh.md" @@ -0,0 +1,75 @@ +# [1170. 比较字符串最小字母出现频次](https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1170.Compare%20Strings%20by%20Frequency%20of%20the%20Smallest%20Character/README_EN.md) + +## 题目描述 + + + +

    定义一个函数 f(s),统计 s  中(按字典序比较)最小字母的出现频次 ,其中 s 是一个非空字符串。

    + +

    例如,若 s = "dcce",那么 f(s) = 2,因为字典序最小字母是 "c",它出现了 2 次。

    + +

    现在,给你两个字符串数组待查表 queries 和词汇表 words 。对于每次查询 queries[i] ,需统计 words 中满足 f(queries[i]) < f(W) 的 词的数目W 表示词汇表 words 中的每个词。

    + +

    请你返回一个整数数组 answer 作为答案,其中每个 answer[i] 是第 i 次查询的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:queries = ["cbd"], words = ["zaaaz"]
    +输出:[1]
    +解释:查询 f("cbd") = 1,而 f("zaaaz") = 3 所以 f("cbd") < f("zaaaz")。
    +
    + +

    示例 2:

    + +
    +输入:queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
    +输出:[1,2]
    +解释:第一个查询 f("bbb") < f("aaaa"),第二个查询 f("aaa") 和 f("aaaa") 都 > f("cc")。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= queries.length <= 2000
    • +
    • 1 <= words.length <= 2000
    • +
    • 1 <= queries[i].length, words[i].length <= 10
    • +
    • queries[i][j]words[i][j] 都由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1171.leetcode1171 Remove Zero Sum Consecutive Nodes from Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1171.leetcode1171 Remove Zero Sum Consecutive Nodes from Linked List-zh.md" new file mode 100644 index 00000000..c8d34c7c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1171.leetcode1171 Remove Zero Sum Consecutive Nodes from Linked List-zh.md" @@ -0,0 +1,129 @@ +# [1171. 从链表中删去总和值为零的连续节点](https://leetcode-cn.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1171.Remove%20Zero%20Sum%20Consecutive%20Nodes%20from%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给你一个链表的头节点 head,请你编写代码,反复删去链表中由 总和 值为 0 的连续节点组成的序列,直到不存在这样的序列为止。

    + +

    删除完毕后,请你返回最终结果链表的头节点。

    + +

     

    + +

    你可以返回任何满足题目要求的答案。

    + +

    (注意,下面示例中的所有序列,都是对 ListNode 对象序列化的表示。)

    + +

    示例 1:

    + +
    输入:head = [1,2,-3,3,1]
    +输出:[3,1]
    +提示:答案 [1,2,1] 也是正确的。
    +
    + +

    示例 2:

    + +
    输入:head = [1,2,3,-3,4]
    +输出:[1,2,4]
    +
    + +

    示例 3:

    + +
    输入:head = [1,2,3,-3,-2]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给你的链表中可能有 1 到 1000 个节点。
    • +
    • 对于链表中的每个节点,节点的值:-1000 <= node.val <= 1000.
    • +
    + +## 解法 + + + +“前缀和 + 哈希表”实现。 + +若链表节点的两个前缀和相等,说明两个前缀和之间的连续节点序列的和为 0,那么可以消去这部分连续节点。 + +第一次遍历链表,用哈希表 `pre_sum_node` 记录前缀和以及对应的链表节点,同一前缀和 s,**后者的链表节点覆盖前者**。 + +第二次遍历链表,若当前节点 cur 的前缀和 s 在 `pre_sum_node` 出现,说明 cur 与 pre_sum_node[s] 之间的所有节点和为 0,直接修改 cur 的指向,`cur.next = pre_sum_node[s].next`,就删去了这部分和为 0 的连续节点。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def removeZeroSumSublists(self, head: ListNode) -> ListNode: + dummy = ListNode(0) + dummy.next = head + s, cur = 0, dummy + pre_sum_node = {} + while cur: + s += cur.val + pre_sum_node[s] = cur + cur = cur.next + s, cur = 0, dummy + while cur: + s += cur.val + cur.next = pre_sum_node[s].next + cur = cur.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode removeZeroSumSublists(ListNode head) { + ListNode dummy = new ListNode(0); + dummy.next = head; + Map preSumNode = new HashMap<>(); + int s = 0; + for (ListNode cur = dummy; cur != null; cur = cur.next) { + s += cur.val; + preSumNode.put(s, cur); + } + s = 0; + for (ListNode cur = dummy; cur != null; cur = cur.next) { + s += cur.val; + cur.next = preSumNode.get(s).next; + } + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1172.leetcode1172 Dinner Plate Stacks-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1172.leetcode1172 Dinner Plate Stacks-zh.md" new file mode 100644 index 00000000..3bda870e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1172.leetcode1172 Dinner Plate Stacks-zh.md" @@ -0,0 +1,105 @@ +# [1172. 餐盘栈](https://leetcode-cn.com/problems/dinner-plate-stacks) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1172.Dinner%20Plate%20Stacks/README_EN.md) + +## 题目描述 + + + +

    我们把无限数量 ∞ 的栈排成一行,按从左到右的次序从 0 开始编号。每个栈的的最大容量 capacity 都相同。

    + +

    实现一个叫「餐盘」的类 DinnerPlates

    + +
      +
    • DinnerPlates(int capacity) - 给出栈的最大容量 capacity
    • +
    • void push(int val) - 将给出的正整数 val 推入 从左往右第一个 没有满的栈。
    • +
    • int pop() - 返回 从右往左第一个 非空栈顶部的值,并将其从栈中删除;如果所有的栈都是空的,请返回 -1
    • +
    • int popAtStack(int index) - 返回编号 index 的栈顶部的值,并将其从栈中删除;如果编号 index 的栈是空的,请返回 -1
    • +
    + +

     

    + +

    示例:

    + +
    输入: 
    +["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"]
    +[[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]
    +输出:
    +[null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]
    +
    +解释:
    +DinnerPlates D = DinnerPlates(2);  // 初始化,栈最大容量 capacity = 2
    +D.push(1);
    +D.push(2);
    +D.push(3);
    +D.push(4);
    +D.push(5);         // 栈的现状为:    2  4
    +                                    1  3  5
    +                                    ﹈ ﹈ ﹈
    +D.popAtStack(0);   // 返回 2。栈的现状为:      4
    +                                          1  3  5
    +                                          ﹈ ﹈ ﹈
    +D.push(20);        // 栈的现状为:  20  4
    +                                   1  3  5
    +                                   ﹈ ﹈ ﹈
    +D.push(21);        // 栈的现状为:  20  4 21
    +                                   1  3  5
    +                                   ﹈ ﹈ ﹈
    +D.popAtStack(0);   // 返回 20。栈的现状为:       4 21
    +                                            1  3  5
    +                                            ﹈ ﹈ ﹈
    +D.popAtStack(2);   // 返回 21。栈的现状为:       4
    +                                            1  3  5
    +                                            ﹈ ﹈ ﹈ 
    +D.pop()            // 返回 5。栈的现状为:        4
    +                                            1  3 
    +                                            ﹈ ﹈  
    +D.pop()            // 返回 4。栈的现状为:    1  3 
    +                                           ﹈ ﹈   
    +D.pop()            // 返回 3。栈的现状为:    1 
    +                                           ﹈   
    +D.pop()            // 返回 1。现在没有栈。
    +D.pop()            // 返回 -1。仍然没有栈。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= capacity <= 20000
    • +
    • 1 <= val <= 20000
    • +
    • 0 <= index <= 100000
    • +
    • 最多会对 pushpop,和 popAtStack 进行 200000 次调用。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1173.leetcode1173 Immediate Food Delivery I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1173.leetcode1173 Immediate Food Delivery I-zh.md" new file mode 100644 index 00000000..5c979b84 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1173.leetcode1173 Immediate Food Delivery I-zh.md" @@ -0,0 +1,64 @@ +# [1173. 即时食物配送 I](https://leetcode-cn.com/problems/immediate-food-delivery-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1173.Immediate%20Food%20Delivery%20I/README_EN.md) + +## 题目描述 + + + +

    配送表: Delivery

    + +
    +-----------------------------+---------+
    +| Column Name                 | Type    |
    ++-----------------------------+---------+
    +| delivery_id                 | int     |
    +| customer_id                 | int     |
    +| order_date                  | date    |
    +| customer_pref_delivery_date | date    |
    ++-----------------------------+---------+
    +delivery_id 是表的主键。
    +该表保存着顾客的食物配送信息,顾客在某个日期下了订单,并指定了一个期望的配送日期(和下单日期相同或者在那之后)。
    +
    + +

     

    + +

    如果顾客期望的配送日期和下单日期相同,则该订单称为 「即时订单」,否则称为「计划订单」。

    + +

    写一条 SQL 查询语句获取即时订单所占的百分比, 保留两位小数。

    + +

    查询结果如下所示:

    + +
    Delivery 表:
    ++-------------+-------------+------------+-----------------------------+
    +| delivery_id | customer_id | order_date | customer_pref_delivery_date |
    ++-------------+-------------+------------+-----------------------------+
    +| 1           | 1           | 2019-08-01 | 2019-08-02                  |
    +| 2           | 5           | 2019-08-02 | 2019-08-02                  |
    +| 3           | 1           | 2019-08-11 | 2019-08-11                  |
    +| 4           | 3           | 2019-08-24 | 2019-08-26                  |
    +| 5           | 4           | 2019-08-21 | 2019-08-22                  |
    +| 6           | 2           | 2019-08-11 | 2019-08-13                  |
    ++-------------+-------------+------------+-----------------------------+
    +
    +Result 表:
    ++----------------------+
    +| immediate_percentage |
    ++----------------------+
    +| 33.33                |
    ++----------------------+
    +2 和 3 号订单为即时订单,其他的为计划订单。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1174.leetcode1174 Immediate Food Delivery II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1174.leetcode1174 Immediate Food Delivery II-zh.md" new file mode 100644 index 00000000..b1895f72 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1174.leetcode1174 Immediate Food Delivery II-zh.md" @@ -0,0 +1,74 @@ +# [1174. 即时食物配送 II](https://leetcode-cn.com/problems/immediate-food-delivery-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1174.Immediate%20Food%20Delivery%20II/README_EN.md) + +## 题目描述 + + + +

    配送表: Delivery

    + +
    +-----------------------------+---------+
    +| Column Name                 | Type    |
    ++-----------------------------+---------+
    +| delivery_id                 | int     |
    +| customer_id                 | int     |
    +| order_date                  | date    |
    +| customer_pref_delivery_date | date    |
    ++-----------------------------+---------+
    +delivery_id 是表的主键。
    +该表保存着顾客的食物配送信息,顾客在某个日期下了订单,并指定了一个期望的配送日期(和下单日期相同或者在那之后)。
    +
    + +

     

    + +

    如果顾客期望的配送日期和下单日期相同,则该订单称为 「即时订单」,否则称为「计划订单」。

    + +

    「首次订单」是顾客最早创建的订单。我们保证一个顾客只会有一个「首次订单」。

    + +

    写一条 SQL 查询语句获取即时订单在所有用户的首次订单中的比例。保留两位小数。

    + +

     

    + +

    查询结果如下所示:

    + +
    Delivery 表:
    ++-------------+-------------+------------+-----------------------------+
    +| delivery_id | customer_id | order_date | customer_pref_delivery_date |
    ++-------------+-------------+------------+-----------------------------+
    +| 1           | 1           | 2019-08-01 | 2019-08-02                  |
    +| 2           | 2           | 2019-08-02 | 2019-08-02                  |
    +| 3           | 1           | 2019-08-11 | 2019-08-12                  |
    +| 4           | 3           | 2019-08-24 | 2019-08-24                  |
    +| 5           | 3           | 2019-08-21 | 2019-08-22                  |
    +| 6           | 2           | 2019-08-11 | 2019-08-13                  |
    +| 7           | 4           | 2019-08-09 | 2019-08-09                  |
    ++-------------+-------------+------------+-----------------------------+
    +
    +Result 表:
    ++----------------------+
    +| immediate_percentage |
    ++----------------------+
    +| 50.00                |
    ++----------------------+
    +1 号顾客的 1 号订单是首次订单,并且是计划订单。
    +2 号顾客的 2 号订单是首次订单,并且是即时订单。
    +3 号顾客的 5 号订单是首次订单,并且是计划订单。
    +4 号顾客的 7 号订单是首次订单,并且是即时订单。
    +因此,一半顾客的首次订单是即时的。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1175.leetcode1175 Prime Arrangements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1175.leetcode1175 Prime Arrangements-zh.md" new file mode 100644 index 00000000..99b93e98 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1175.leetcode1175 Prime Arrangements-zh.md" @@ -0,0 +1,67 @@ +# [1175. 质数排列](https://leetcode-cn.com/problems/prime-arrangements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1175.Prime%20Arrangements/README_EN.md) + +## 题目描述 + + + +

    请你帮忙给从 1n 的数设计排列方案,使得所有的「质数」都应该被放在「质数索引」(索引从 1 开始)上;你需要返回可能的方案总数。

    + +

    让我们一起来回顾一下「质数」:质数一定是大于 1 的,并且不能用两个小于它的正整数的乘积来表示。

    + +

    由于答案可能会很大,所以请你返回答案 模 mod 10^9 + 7 之后的结果即可。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 5
    +输出:12
    +解释:举个例子,[1,2,5,4,3] 是一个有效的排列,但 [5,2,3,4,1] 不是,因为在第二种情况里质数 5 被错误地放在索引为 1 的位置上。
    +
    + +

    示例 2:

    + +
    输入:n = 100
    +输出:682289015
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1176.leetcode1176 Diet Plan Performance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1176.leetcode1176 Diet Plan Performance-zh.md" new file mode 100644 index 00000000..6f0fbc59 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1176.leetcode1176 Diet Plan Performance-zh.md" @@ -0,0 +1,86 @@ +# [1176. 健身计划评估](https://leetcode-cn.com/problems/diet-plan-performance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1176.Diet%20Plan%20Performance/README_EN.md) + +## 题目描述 + + + +

    你的好友是一位健身爱好者。前段日子,他给自己制定了一份健身计划。现在想请你帮他评估一下这份计划是否合理。

    + +

    他会有一份计划消耗的卡路里表,其中 calories[i] 给出了你的这位好友在第 i 天需要消耗的卡路里总量。

    + +

    为了更好地评估这份计划,对于卡路里表中的每一天,你都需要计算他 「这一天以及之后的连续几天」 (共 k 天)内消耗的总卡路里 T:

    + +
      +
    • 如果 T < lower,那么这份计划相对糟糕,并失去 1 分; 
    • +
    • 如果 T > upper,那么这份计划相对优秀,并获得 1 分;
    • +
    • 否则,这份计划普普通通,分值不做变动。
    • +
    + +

    请返回统计完所有 calories.length 天后得到的总分作为评估结果。

    + +

    注意:总分可能是负数。

    + +

     

    + +

    示例 1:

    + +
    输入:calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
    +输出:0
    +解释:calories[0], calories[1] < lower 而 calories[3], calories[4] > upper, 总分 = 0.
    + +

    示例 2:

    + +
    输入:calories = [3,2], k = 2, lower = 0, upper = 1
    +输出:1
    +解释:calories[0] + calories[1] > upper, 总分 = 1.
    +
    + +

    示例 3:

    + +
    输入:calories = [6,5,0,0], k = 2, lower = 1, upper = 5
    +输出:0
    +解释:calories[0] + calories[1] > upper, calories[2] + calories[3] < lower, 总分 = 0.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= calories.length <= 10^5
    • +
    • 0 <= calories[i] <= 20000
    • +
    • 0 <= lower <= upper
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1177.leetcode1177 Can Make Palindrome from Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1177.leetcode1177 Can Make Palindrome from Substring-zh.md" new file mode 100644 index 00000000..ea4193b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1177.leetcode1177 Can Make Palindrome from Substring-zh.md" @@ -0,0 +1,73 @@ +# [1177. 构建回文串检测](https://leetcode-cn.com/problems/can-make-palindrome-from-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1177.Can%20Make%20Palindrome%20from%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,请你对 s 的子串进行检测。

    + +

    每次检测,待检子串都可以表示为 queries[i] = [left, right, k]。我们可以 重新排列 子串 s[left], ..., s[right],并从中选择 最多 k 项替换成任何小写英文字母。 

    + +

    如果在上述检测过程中,子串可以变成回文形式的字符串,那么检测结果为 true,否则结果为 false

    + +

    返回答案数组 answer[],其中 answer[i] 是第 i 个待检子串 queries[i] 的检测结果。

    + +

    注意:在替换时,子串中的每个字母都必须作为 独立的 项进行计数,也就是说,如果 s[left..right] = "aaa" 且 k = 2,我们只能替换其中的两个字母。(另外,任何检测都不会修改原始字符串 s,可以认为每次检测都是独立的)

    + +

     

    + +

    示例:

    + +
    输入:s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
    +输出:[true,false,false,true,true]
    +解释:
    +queries[0] : 子串 = "d",回文。
    +queries[1] : 子串 = "bc",不是回文。
    +queries[2] : 子串 = "abcd",只替换 1 个字符是变不成回文串的。
    +queries[3] : 子串 = "abcd",可以变成回文的 "abba"。 也可以变成 "baab",先重新排序变成 "bacd",然后把 "cd" 替换为 "ab"。
    +queries[4] : 子串 = "abcda",可以变成回文的 "abcba"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length, queries.length <= 10^5
    • +
    • 0 <= queries[i][0] <= queries[i][1] < s.length
    • +
    • 0 <= queries[i][2] <= s.length
    • +
    • s 中只有小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1178.leetcode1178 Number of Valid Words for Each Puzzle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1178.leetcode1178 Number of Valid Words for Each Puzzle-zh.md" new file mode 100644 index 00000000..47f31a2f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1178.leetcode1178 Number of Valid Words for Each Puzzle-zh.md" @@ -0,0 +1,81 @@ +# [1178. 猜字谜](https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1178.Number%20of%20Valid%20Words%20for%20Each%20Puzzle/README_EN.md) + +## 题目描述 + + + +

    外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。

    + +

    字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底:

    + +
      +
    • 单词 word 中包含谜面 puzzle 的第一个字母。
    • +
    • 单词 word 中的每一个字母都可以在谜面 puzzle 中找到。
      + 例如,如果字谜的谜面是 "abcdefg",那么可以作为谜底的单词有 "faced", "cabbage", 和 "baggage";而 "beefed"(不含字母 "a")以及 "based"(其中的 "s" 没有出现在谜面中)都不能作为谜底。
    • +
    + +

    返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。

    + +

     

    + +

    示例:

    + +
    +输入:
    +words = ["aaaa","asas","able","ability","actt","actor","access"], 
    +puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
    +输出:[1,1,3,2,4,0]
    +解释:
    +1 个单词可以作为 "aboveyz" 的谜底 : "aaaa" 
    +1 个单词可以作为 "abrodyz" 的谜底 : "aaaa"
    +3 个单词可以作为 "abslute" 的谜底 : "aaaa", "asas", "able"
    +2 个单词可以作为 "absoryz" 的谜底 : "aaaa", "asas"
    +4 个单词可以作为 "actresz" 的谜底 : "aaaa", "asas", "actt", "access"
    +没有单词可以作为 "gaswxyz" 的谜底,因为列表中的单词都不含字母 'g'。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 10^5
    • +
    • 4 <= words[i].length <= 50
    • +
    • 1 <= puzzles.length <= 10^4
    • +
    • puzzles[i].length == 7
    • +
    • words[i][j], puzzles[i][j] 都是小写英文字母。
    • +
    • 每个 puzzles[i] 所包含的字符都不重复。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1179.leetcode1179 Reformat Department Table-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1179.leetcode1179 Reformat Department Table-zh.md" new file mode 100644 index 00000000..2d88be98 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1179.leetcode1179 Reformat Department Table-zh.md" @@ -0,0 +1,83 @@ +# [1179. 重新格式化部门表](https://leetcode-cn.com/problems/reformat-department-table) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1179.Reformat%20Department%20Table/README_EN.md) + +## 题目描述 + + + +

    部门表 Department

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| revenue       | int     |
    +| month         | varchar |
    ++---------------+---------+
    +(id, month) 是表的联合主键。
    +这个表格有关于每个部门每月收入的信息。
    +月份(month)可以取下列值 ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]。
    +
    + +

     

    + +

    编写一个 SQL 查询来重新格式化表,使得新的表中有一个部门 id 列和一些对应 每个月 的收入(revenue)列。

    + +

    查询结果格式如下面的示例所示:

    + +
    +Department 表:
    ++------+---------+-------+
    +| id   | revenue | month |
    ++------+---------+-------+
    +| 1    | 8000    | Jan   |
    +| 2    | 9000    | Jan   |
    +| 3    | 10000   | Feb   |
    +| 1    | 7000    | Feb   |
    +| 1    | 6000    | Mar   |
    ++------+---------+-------+
    +
    +查询得到的结果表:
    ++------+-------------+-------------+-------------+-----+-------------+
    +| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
    ++------+-------------+-------------+-------------+-----+-------------+
    +| 1    | 8000        | 7000        | 6000        | ... | null        |
    +| 2    | 9000        | null        | null        | ... | null        |
    +| 3    | null        | 10000       | null        | ... | null        |
    ++------+-------------+-------------+-------------+-----+-------------+
    +
    +注意,结果表有 13 列 (1个部门 id 列 + 12个月份的收入列)。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1180.leetcode1180 Count Substrings with Only One Distinct Letter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1180.leetcode1180 Count Substrings with Only One Distinct Letter-zh.md" new file mode 100644 index 00000000..8e749b25 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1180.leetcode1180 Count Substrings with Only One Distinct Letter-zh.md" @@ -0,0 +1,68 @@ +# [1180. 统计只含单一字母的子串](https://leetcode-cn.com/problems/count-substrings-with-only-one-distinct-letter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1180.Count%20Substrings%20with%20Only%20One%20Distinct%20Letter/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 S,返回只含 单一字母 的子串个数。

    + +

    示例 1:

    + +
    输入: "aaaba"
    +输出: 8
    +解释: 
    +只含单一字母的子串分别是 "aaa", "aa", "a", "b"。
    +"aaa" 出现 1 次。
    +"aa" 出现 2 次。
    +"a" 出现 4 次。
    +"b" 出现 1 次。
    +所以答案是 1 + 2 + 4 + 1 = 8。
    +
    + +

    示例 2:

    + +
    输入: "aaaaaaaaaa"
    +输出: 55
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= S.length <= 1000
    2. +
    3. S[i] 仅由小写英文字母组成。
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1181.leetcode1181 Before and After Puzzle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1181.leetcode1181 Before and After Puzzle-zh.md" new file mode 100644 index 00000000..bc1c34f2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1181.leetcode1181 Before and After Puzzle-zh.md" @@ -0,0 +1,140 @@ +# [1181. 前后拼接](https://leetcode-cn.com/problems/before-and-after-puzzle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1181.Before%20and%20After%20Puzzle/README_EN.md) + +## 题目描述 + + + +

    给你一个「短语」列表 phrases,请你帮忙按规则生成拼接后的「新短语」列表。

    + +

    「短语」(phrase)是仅由小写英文字母和空格组成的字符串。「短语」的开头和结尾都不会出现空格,「短语」中的空格不会连续出现。

    + +

    「前后拼接」(Before and After puzzles)是合并两个「短语」形成「新短语」的方法。我们规定拼接时,第一个短语的最后一个单词第二个短语的第一个单词 必须相同。

    + +

    返回每两个「短语」 phrases[i] 和 phrases[j]i != j)进行「前后拼接」得到的「新短语」。

    + +

    注意,两个「短语」拼接时的顺序也很重要,我们需要同时考虑这两个「短语」。另外,同一个「短语」可以多次参与拼接,但「新短语」不能再参与拼接。

    + +

    请你按字典序排列并返回「新短语」列表,列表中的字符串应该是 不重复的

    + +

     

    + +

    示例 1:

    + +
    输入:phrases = ["writing code","code rocks"]
    +输出:["writing code rocks"]
    +
    + +

    示例 2:

    + +
    输入:phrases = ["mission statement",
    +                "a quick bite to eat",
    +                "a chip off the old block",
    +                "chocolate bar",
    +                "mission impossible",
    +                "a man on a mission",
    +                "block party",
    +                "eat my words",
    +                "bar of soap"]
    +输出:["a chip off the old block party",
    +      "a man on a mission impossible",
    +      "a man on a mission statement",
    +      "a quick bite to eat my words",
    +      "chocolate bar of soap"]
    +
    + +

    示例 3:

    + +
    输入:phrases = ["a","b","a"]
    +输出:["a"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= phrases.length <= 100
    • +
    • 1 <= phrases[i].length <= 100
    • +
    + +## 解法 + + + +“哈希表 + 排序”实现。 + + + +### **Python3** + + + +```python +class Solution: + def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]: + same_first_word = collections.defaultdict(set) + for i, phrase in enumerate(phrases): + same_first_word[phrase.split()[0]].add(i) + res = set() + for i, phrase in enumerate(phrases): + words = phrase.split() + last_word = words[-1] + if last_word in same_first_word: + for j in same_first_word[last_word]: + if i != j: + res.add(' '.join(words[:-1] + phrases[j].split())) + return sorted(list(res)) +``` + +### **Java** + + + +```java +class Solution { + public List beforeAndAfterPuzzles(String[] phrases) { + Map> sameFirstWord = new HashMap<>(); + for (int i = 0; i < phrases.length; ++i) { + String phrase = phrases[i]; + String word = phrase.split(" ")[0]; + if (!sameFirstWord.containsKey(word)) { + sameFirstWord.put(word, new HashSet<>()); + } + sameFirstWord.get(word).add(i); + } + Set res = new HashSet<>(); + for (int i = 0; i < phrases.length; ++i) { + String phrase = phrases[i]; + String[] words = phrase.split(" "); + String lastWord = words[words.length - 1]; + if (sameFirstWord.containsKey(lastWord)) { + for (int j : sameFirstWord.get(lastWord)) { + if (i != j) { + List t = new ArrayList<>(); + for (int k = 0; k < words.length - 1; ++k) { + t.add(words[k]); + } + for (String word : phrases[j].split(" ")) { + t.add(word); + } + res.add(String.join(" ", t)); + } + } + } + } + List output = new ArrayList<>(res); + Collections.sort(output); + return output; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1182.leetcode1182 Shortest Distance to Target Color-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1182.leetcode1182 Shortest Distance to Target Color-zh.md" new file mode 100644 index 00000000..8263763b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1182.leetcode1182 Shortest Distance to Target Color-zh.md" @@ -0,0 +1,143 @@ +# [1182. 与目标颜色间的最短距离](https://leetcode-cn.com/problems/shortest-distance-to-target-color) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1182.Shortest%20Distance%20to%20Target%20Color/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 colors,里面有  12、 3 三种颜色。

    + +

    我们需要在 colors 上进行一些查询操作 queries,其中每个待查项都由两个整数 ic 组成。

    + +

    现在请你帮忙设计一个算法,查找从索引 i 到具有目标颜色 c 的元素之间的最短距离。

    + +

    如果不存在解决方案,请返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
    +输出:[3,0,3]
    +解释: 
    +距离索引 1 最近的颜色 3 位于索引 4(距离为 3)。
    +距离索引 2 最近的颜色 2 就是它自己(距离为 0)。
    +距离索引 6 最近的颜色 1 位于索引 3(距离为 3)。
    +
    + +

    示例 2:

    + +
    输入:colors = [1,2], queries = [[0,3]]
    +输出:[-1]
    +解释:colors 中没有颜色 3。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= colors.length <= 5*10^4
    • +
    • 1 <= colors[i] <= 3
    • +
    • 1 <= queries.length <= 5*10^4
    • +
    • queries[i].length == 2
    • +
    • 0 <= queries[i][0] < colors.length
    • +
    • 1 <= queries[i][1] <= 3
    • +
    + +## 解法 + + + +二分查找。 + +先用哈希表记录每种颜色的索引位置。然后遍历 `queries`,如果当前 `color` 不在哈希表中,说明不存在解决方案,此时此 `query` 对应的结果元素是 `-1`。否则,在哈希表中取出当前 `color` 对应的索引列表,二分查找即可。 + + + +### **Python3** + + + +```python +class Solution: + def shortestDistanceColor(self, colors: List[int], queries: List[List[int]]) -> List[int]: + color_indexes = collections.defaultdict(list) + for i, c in enumerate(colors): + color_indexes[c].append(i) + res = [] + for i, c in queries: + if c not in color_indexes: + res.append(-1) + else: + t = color_indexes[c] + left, right = 0, len(t) - 1 + while left < right: + mid = (left + right) >> 1 + if t[mid] >= i: + right = mid + else: + left = mid + 1 + val = abs(t[left] - i) + if left > 0: + val = min(val, abs(t[left - 1] - i)) + if left < len(t) - 1: + val = min(val, abs(t[left + 1] - i)) + res.append(val) + return res +``` + +### **Java** + + + +```java +class Solution { + public List shortestDistanceColor(int[] colors, int[][] queries) { + Map> colorIndexes = new HashMap<>(); + for (int i = 0; i < colors.length; ++i) { + int c = colors[i]; + if (!colorIndexes.containsKey(c)) { + colorIndexes.put(c, new ArrayList<>()); + } + colorIndexes.get(c).add(i); + } + List res = new ArrayList<>(); + for (int[] query : queries) { + int i = query[0], c = query[1]; + if (!colorIndexes.containsKey(c)) { + res.add(-1); + continue; + } + List t = colorIndexes.get(c); + int left = 0, right = t.size() - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (t.get(mid) >= i) { + right = mid; + } else { + left = mid + 1; + } + } + int val = Math.abs(t.get(left) - i); + if (left > 0) { + val = Math.min(val, Math.abs(t.get(left - 1) - i)); + } + if (left < t.size() - 1) { + val = Math.min(val, Math.abs(t.get(left + 1) - i)); + } + res.add(val); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1183.leetcode1183 Maximum Number of Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1183.leetcode1183 Maximum Number of Ones-zh.md" new file mode 100644 index 00000000..ff37462e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1183.leetcode1183 Maximum Number of Ones-zh.md" @@ -0,0 +1,78 @@ +# [1183. 矩阵中 1 的最大数量](https://leetcode-cn.com/problems/maximum-number-of-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1183.Maximum%20Number%20of%20Ones/README_EN.md) + +## 题目描述 + + + +

    现在有一个尺寸为 width * height 的矩阵 M,矩阵中的每个单元格的值不是 0 就是 1

    + +

    而且矩阵 M 中每个大小为 sideLength * sideLength 的 正方形 子阵中,1 的数量不得超过 maxOnes

    + +

    请你设计一个算法,计算矩阵中最多可以有多少个 1

    + +

     

    + +

    示例 1:

    + +
    输入:width = 3, height = 3, sideLength = 2, maxOnes = 1
    +输出:4
    +解释:
    +题目要求:在一个 3*3 的矩阵中,每一个 2*2 的子阵中的 1 的数目不超过 1 个。
    +最好的解决方案中,矩阵 M 里最多可以有 4 个 1,如下所示:
    +[1,0,1]
    +[0,0,0]
    +[1,0,1]
    +
    + +

    示例 2:

    + +
    输入:width = 3, height = 3, sideLength = 2, maxOnes = 2
    +输出:6
    +解释:
    +[1,0,1]
    +[1,0,1]
    +[1,0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= width, height <= 100
    • +
    • 1 <= sideLength <= width, height
    • +
    • 0 <= maxOnes <= sideLength * sideLength
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1184.leetcode1184 Distance Between Bus Stops-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1184.leetcode1184 Distance Between Bus Stops-zh.md" new file mode 100644 index 00000000..1e2de0ec --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1184.leetcode1184 Distance Between Bus Stops-zh.md" @@ -0,0 +1,87 @@ +# [1184. 公交站间的距离](https://leetcode-cn.com/problems/distance-between-bus-stops) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1184.Distance%20Between%20Bus%20Stops/README_EN.md) + +## 题目描述 + + + +

    环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。

    + +

    环线上的公交车都可以按顺时针和逆时针的方向行驶。

    + +

    返回乘客从出发点 start 到目的地 destination 之间的最短距离。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:distance = [1,2,3,4], start = 0, destination = 1
    +输出:1
    +解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。
    + +

     

    + +

    示例 2:

    + +

    + +
    输入:distance = [1,2,3,4], start = 0, destination = 2
    +输出:3
    +解释:公交站 0 和 2 之间的距离是 3 或 7,最小值是 3。
    +
    + +

     

    + +

    示例 3:

    + +

    + +
    输入:distance = [1,2,3,4], start = 0, destination = 3
    +输出:4
    +解释:公交站 0 和 3 之间的距离是 6 或 4,最小值是 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    • distance.length == n
    • +
    • 0 <= start, destination < n
    • +
    • 0 <= distance[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1185.leetcode1185 Day of the Week-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1185.leetcode1185 Day of the Week-zh.md" new file mode 100644 index 00000000..edb89886 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1185.leetcode1185 Day of the Week-zh.md" @@ -0,0 +1,72 @@ +# [1185. 一周中的第几天](https://leetcode-cn.com/problems/day-of-the-week) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1185.Day%20of%20the%20Week/README_EN.md) + +## 题目描述 + + + +

    给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。

    + +

    输入为三个整数:daymonth 和 year,分别表示日、月、年。

    + +

    您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

    + +

     

    + +

    示例 1:

    + +
    输入:day = 31, month = 8, year = 2019
    +输出:"Saturday"
    +
    + +

    示例 2:

    + +
    输入:day = 18, month = 7, year = 1999
    +输出:"Sunday"
    +
    + +

    示例 3:

    + +
    输入:day = 15, month = 8, year = 1993
    +输出:"Sunday"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给出的日期一定是在 1971 到 2100 年之间的有效日期。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1186.leetcode1186 Maximum Subarray Sum with One Deletion-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1186.leetcode1186 Maximum Subarray Sum with One Deletion-zh.md" new file mode 100644 index 00000000..22fccaa3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1186.leetcode1186 Maximum Subarray Sum with One Deletion-zh.md" @@ -0,0 +1,76 @@ +# [1186. 删除一次得到子数组最大和](https://leetcode-cn.com/problems/maximum-subarray-sum-with-one-deletion) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1186.Maximum%20Subarray%20Sum%20with%20One%20Deletion/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组,返回它的某个 非空 子数组(连续元素)在执行一次可选的删除操作后,所能得到的最大元素总和。

    + +

    换句话说,你可以从原数组中选出一个子数组,并可以决定要不要从中删除一个元素(只能删一次哦),(删除后)子数组中至少应当有一个元素,然后该子数组(剩下)的元素总和是所有子数组之中最大的。

    + +

    注意,删除一个元素后,子数组 不能为空

    + +

    请看示例:

    + +

    示例 1:

    + +
    输入:arr = [1,-2,0,3]
    +输出:4
    +解释:我们可以选出 [1, -2, 0, 3],然后删掉 -2,这样得到 [1, 0, 3],和最大。
    + +

    示例 2:

    + +
    输入:arr = [1,-2,-2,3]
    +输出:3
    +解释:我们直接选出 [3],这就是最大和。
    +
    + +

    示例 3:

    + +
    输入:arr = [-1,-1,-1,-1]
    +输出:-1
    +解释:最后得到的子数组不能为空,所以我们不能选择 [-1] 并从中删去 -1 来得到 0。
    +     我们应该直接选择 [-1],或者选择 [-1, -1] 再从中删去一个 -1。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • -10^4 <= arr[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1187.leetcode1187 Make Array Strictly Increasing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1187.leetcode1187 Make Array Strictly Increasing-zh.md" new file mode 100644 index 00000000..4c108c54 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1187.leetcode1187 Make Array Strictly Increasing-zh.md" @@ -0,0 +1,77 @@ +# [1187. 使数组严格递增](https://leetcode-cn.com/problems/make-array-strictly-increasing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1187.Make%20Array%20Strictly%20Increasing/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 arr1arr2,返回使 arr1 严格递增所需要的最小「操作」数(可能为 0)。

    + +

    每一步「操作」中,你可以分别从 arr1arr2 中各选出一个索引,分别为 i 和 j0 <= i < arr1.length 和 0 <= j < arr2.length,然后进行赋值运算 arr1[i] = arr2[j]

    + +

    如果无法让 arr1 严格递增,请返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
    +输出:1
    +解释:用 2 来替换 5,之后 arr1 = [1, 2, 3, 6, 7]。
    +
    + +

    示例 2:

    + +
    输入:arr1 = [1,5,3,6,7], arr2 = [4,3,1]
    +输出:2
    +解释:用 3 来替换 5,然后用 4 来替换 3,得到 arr1 = [1, 3, 4, 6, 7]。
    +
    + +

    示例 3:

    + +
    输入:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
    +输出:-1
    +解释:无法使 arr1 严格递增
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 2000
    • +
    • 0 <= arr1[i], arr2[i] <= 10^9
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1188.leetcode1188 Design Bounded Blocking Queue-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1188.leetcode1188 Design Bounded Blocking Queue-zh.md" new file mode 100644 index 00000000..c1c88bdf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1188.leetcode1188 Design Bounded Blocking Queue-zh.md" @@ -0,0 +1,97 @@ +# [1188. 设计有限阻塞队列](https://leetcode-cn.com/problems/design-bounded-blocking-queue) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1188.Design%20Bounded%20Blocking%20Queue/README_EN.md) + +## 题目描述 + + + +

    实现一个拥有如下方法的线程安全有限阻塞队列:

    + +
      +
    • BoundedBlockingQueue(int capacity) 构造方法初始化队列,其中capacity代表队列长度上限。
    • +
    • void enqueue(int element) 在队首增加一个element. 如果队列满,调用线程被阻塞直到队列非满。
    • +
    • int dequeue() 返回队尾元素并从队列中将其删除. 如果队列为空,调用线程被阻塞直到队列非空。
    • +
    • int size() 返回当前队列元素个数。
    • +
    + +

    你的实现将会被多线程同时访问进行测试。每一个线程要么是一个只调用enqueue方法的生产者线程,要么是一个只调用dequeue方法的消费者线程。size方法将会在每一个测试用例之后进行调用。

    + +

    请不要使用内置的有限阻塞队列实现,否则面试将不会通过。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +1
    +1
    +["BoundedBlockingQueue","enqueue","dequeue","dequeue","enqueue","enqueue","enqueue","enqueue","dequeue"]
    +[[2],[1],[],[],[0],[2],[3],[4],[]]
    +
    +输出:
    +[1,0,2,2]
    +
    +解释:
    +生产者线程数目 = 1
    +消费者线程数目 = 1
    +
    +BoundedBlockingQueue queue = new BoundedBlockingQueue(2);   // 使用capacity = 2初始化队列。
    +
    +queue.enqueue(1);   // 生产者线程将1插入队列。
    +queue.dequeue();    // 消费者线程调用dequeue并返回1。
    +queue.dequeue();    // 由于队列为空,消费者线程被阻塞。
    +queue.enqueue(0);   // 生产者线程将0插入队列。消费者线程被解除阻塞同时将0弹出队列并返回。
    +queue.enqueue(2);   // 生产者线程将2插入队列。
    +queue.enqueue(3);   // 生产者线程将3插入队列。
    +queue.enqueue(4);   // 生产者线程由于队列长度已达到上限2而被阻塞。
    +queue.dequeue();    // 消费者线程将2从队列弹出并返回。生产者线程解除阻塞同时将4插入队列。
    +queue.size();       // 队列中还有2个元素。size()方法在每组测试用例最后调用。
    +
    + +

     

    + +

    示例 2:

    + +
    +输入:
    +3
    +4
    +["BoundedBlockingQueue","enqueue","enqueue","enqueue","dequeue","dequeue","dequeue","enqueue"]
    +[[3],[1],[0],[2],[],[],[],[3]]
    +
    +输出:
    +[1,0,2,1]
    +
    +解释:
    +生产者线程数目 = 3
    +消费者线程数目 = 4
    +
    +BoundedBlockingQueue queue = new BoundedBlockingQueue(3);   // 使用capacity = 3初始化队列。
    +
    +queue.enqueue(1);   // 生产者线程P1将1插入队列。
    +queue.enqueue(0);   // 生产者线程P2将0插入队列。
    +queue.enqueue(2);   // 生产者线程P3将2插入队列。
    +queue.dequeue();    // 消费者线程C1调用dequeue。
    +queue.dequeue();    // 消费者线程C2调用dequeue。
    +queue.dequeue();    // 消费者线程C3调用dequeue。
    +queue.enqueue(3);   // 其中一个生产者线程将3插入队列。
    +queue.size();       // 队列中还有1个元素。
    +
    +由于生产者/消费者线程的数目可能大于1,我们并不知道线程如何被操作系统调度,即使输入看上去隐含了顺序。因此任意一种输出[1,0,2]或[1,2,0]或[0,1,2]或[0,2,1]或[2,0,1]或[2,1,0]都可被接受。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1189.leetcode1189 Maximum Number of Balloons-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1189.leetcode1189 Maximum Number of Balloons-zh.md" new file mode 100644 index 00000000..96bef2cc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1189.leetcode1189 Maximum Number of Balloons-zh.md" @@ -0,0 +1,75 @@ +# [1189. “气球” 的最大数量](https://leetcode-cn.com/problems/maximum-number-of-balloons) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1189.Maximum%20Number%20of%20Balloons/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)

    + +

    字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:text = "nlaebolko"
    +输出:1
    +
    + +

    示例 2:

    + +

    + +
    输入:text = "loonbalxballpoon"
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:text = "leetcode"
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text.length <= 10^4
    • +
    • text 全部由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1190.leetcode1190 Reverse Substrings Between Each Pair of Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1190.leetcode1190 Reverse Substrings Between Each Pair of Parentheses-zh.md" new file mode 100644 index 00000000..467e0bd8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1190.leetcode1190 Reverse Substrings Between Each Pair of Parentheses-zh.md" @@ -0,0 +1,155 @@ +# [1190. 反转每对括号间的子串](https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1190.Reverse%20Substrings%20Between%20Each%20Pair%20of%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给出一个字符串 s(仅含有小写英文字母和括号)。

    + +

    请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。

    + +

    注意,您的结果中 不应 包含任何括号。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "(abcd)"
    +输出:"dcba"
    +
    + +

    示例 2:

    + +
    输入:s = "(u(love)i)"
    +输出:"iloveu"
    +
    + +

    示例 3:

    + +
    输入:s = "(ed(et(oc))el)"
    +输出:"leetcode"
    +
    + +

    示例 4:

    + +
    输入:s = "a(bcdefghijkl(mno)p)q"
    +输出:"apmnolkjihgfedcbq"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 2000
    • +
    • s 中只有小写英文字母和括号
    • +
    • 我们确保所有括号都是成对出现的
    • +
    + + +## 解法 + + + +用双端队列或者栈,模拟反转过程 + + + +### **Python3** + + + +```python +class Solution: + def reverseParentheses(self, s: str) -> str: + stack = [] + for c in s: + if c == ")": + tmp = [] + while stack[-1] != "(": + tmp += stack.pop() + stack.pop() + stack += tmp + else: + stack.append(c) + return "".join(stack) +``` + +### **Java** + + + +```java +class Solution { + public String reverseParentheses(String s) { + Deque deque = new ArrayDeque<>(); + for (char c : s.toCharArray()) { + if (c == ')') { + StringBuilder sb = new StringBuilder(); + while (deque.peekLast() != '(') { + sb.append(deque.pollLast()); + } + deque.pollLast(); + for (int i = 0, n = sb.length(); i < n; i++) { + deque.offerLast(sb.charAt(i)); + } + } else { + deque.offerLast(c); + } + } + StringBuilder sb = new StringBuilder(); + while (!deque.isEmpty()) { + sb.append(deque.pollFirst()); + } + return sb.toString(); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {string} + */ +var reverseParentheses = function(s) { + let stack = []; + let hashMap = {}; + const n = s.length; + for (let i = 0; i < n; i++) { + let cur = s.charAt(i); + if (cur == '(') { + stack.push(i); + } else if (cur == ')') { + let left = stack.pop(); + hashMap[left] = i; + hashMap[i] = left; + } + } + let res = []; + let i = 0; + let step = 1; // 1向右,-1向左 + while (i > -1 && i < n) { + let cur = s.charAt(i); + if (cur == '(' || cur == ')') { + step = -step; + i = hashMap[i]; + } else { + res.push(cur); + } + i += step; + } + return res.join(''); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1191.leetcode1191 K-Concatenation Maximum Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1191.leetcode1191 K-Concatenation Maximum Sum-zh.md" new file mode 100644 index 00000000..a37e50c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1191.leetcode1191 K-Concatenation Maximum Sum-zh.md" @@ -0,0 +1,82 @@ +# [1191. K 次串联后最大子数组之和](https://leetcode-cn.com/problems/k-concatenation-maximum-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1191.K-Concatenation%20Maximum%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数 k

    + +

    首先,我们要对该数组进行修改,即把原数组 arr 重复 k 次。

    + +
    +

    举个例子,如果 arr = [1, 2]k = 3,那么修改后的数组就是 [1, 2, 1, 2, 1, 2]

    +
    + +

    然后,请你返回修改后的数组中的最大的子数组之和。

    + +

    注意,子数组长度可以是 0,在这种情况下它的总和也是 0

    + +

    由于 结果可能会很大,所以需要 模(mod) 10^9 + 7 后再返回。 

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2], k = 3
    +输出:9
    +
    + +

    示例 2:

    + +
    输入:arr = [1,-2,1], k = 5
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:arr = [-1,-2], k = 7
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= k <= 10^5
    • +
    • -10^4 <= arr[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1192.leetcode1192 Critical Connections in a Network-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1192.leetcode1192 Critical Connections in a Network-zh.md" new file mode 100644 index 00000000..942d9e6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1192.leetcode1192 Critical Connections in a Network-zh.md" @@ -0,0 +1,69 @@ +# [1192. 查找集群内的「关键连接」](https://leetcode-cn.com/problems/critical-connections-in-a-network) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1192.Critical%20Connections%20in%20a%20Network/README_EN.md) + +## 题目描述 + + + +

    力扣数据中心有 n 台服务器,分别按从 0 到 n-1 的方式进行了编号。

    + +

    它们之间以「服务器到服务器」点对点的形式相互连接组成了一个内部集群,其中连接 connections 是无向的。

    + +

    从形式上讲,connections[i] = [a, b] 表示服务器 a 和 b 之间形成连接。任何服务器都可以直接或者间接地通过网络到达任何其他服务器。

    + +

    「关键连接」是在该集群中的重要连接,也就是说,假如我们将它移除,便会导致某些服务器无法访问其他服务器。

    + +

    请你以任意顺序返回该集群内的所有 「关键连接」。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
    +输出:[[1,3]]
    +解释:[[3,1]] 也是正确的。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • n-1 <= connections.length <= 10^5
    • +
    • connections[i][0] != connections[i][1]
    • +
    • 不存在重复的连接
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1193.leetcode1193 Monthly Transactions I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1193.leetcode1193 Monthly Transactions I-zh.md" new file mode 100644 index 00000000..6c50ff06 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1193.leetcode1193 Monthly Transactions I-zh.md" @@ -0,0 +1,66 @@ +# [1193. 每月交易 I](https://leetcode-cn.com/problems/monthly-transactions-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1193.Monthly%20Transactions%20I/README_EN.md) + +## 题目描述 + + + +

    Table: Transactions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| country       | varchar |
    +| state         | enum    |
    +| amount        | int     |
    +| trans_date    | date    |
    ++---------------+---------+
    +id 是这个表的主键。
    +该表包含有关传入事务的信息。
    +state 列类型为 “[”批准“,”拒绝“] 之一。
    +
    + +

     

    + +

    编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

    + +

    查询结果格式如下所示:

    + +
    +Transactions table:
    ++------+---------+----------+--------+------------+
    +| id   | country | state    | amount | trans_date |
    ++------+---------+----------+--------+------------+
    +| 121  | US      | approved | 1000   | 2018-12-18 |
    +| 122  | US      | declined | 2000   | 2018-12-19 |
    +| 123  | US      | approved | 2000   | 2019-01-01 |
    +| 124  | DE      | approved | 2000   | 2019-01-07 |
    ++------+---------+----------+--------+------------+
    +
    +Result table:
    ++----------+---------+-------------+----------------+--------------------+-----------------------+
    +| month    | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
    ++----------+---------+-------------+----------------+--------------------+-----------------------+
    +| 2018-12  | US      | 2           | 1              | 3000               | 1000                  |
    +| 2019-01  | US      | 1           | 1              | 2000               | 2000                  |
    +| 2019-01  | DE      | 1           | 1              | 2000               | 2000                  |
    ++----------+---------+-------------+----------------+--------------------+-----------------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1194.leetcode1194 Tournament Winners-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1194.leetcode1194 Tournament Winners-zh.md" new file mode 100644 index 00000000..f5c18a75 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1194.leetcode1194 Tournament Winners-zh.md" @@ -0,0 +1,98 @@ +# [1194. 锦标赛优胜者](https://leetcode-cn.com/problems/tournament-winners) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1194.Tournament%20Winners/README_EN.md) + +## 题目描述 + + + +

    Players 玩家表

    + +
    ++-------------+-------+
    +| Column Name | Type  |
    ++-------------+-------+
    +| player_id   | int   |
    +| group_id    | int   |
    ++-------------+-------+
    +player_id 是此表的主键。
    +此表的每一行表示每个玩家的组。
    +
    + +

    Matches 赛事表

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| match_id      | int     |
    +| first_player  | int     |
    +| second_player | int     | 
    +| first_score   | int     |
    +| second_score  | int     |
    ++---------------+---------+
    +match_id 是此表的主键。
    +每一行是一场比赛的记录,first_player 和 second_player 表示该场比赛的球员 ID。
    +first_score 和 second_score 分别表示 first_player 和 second_player 的得分。
    +你可以假设,在每一场比赛中,球员都属于同一组。
    +
    + +

     

    + +

    每组的获胜者是在组内累积得分最高的选手。如果平局,player_id 最小 的选手获胜。

    + +

    编写一个 SQL 查询来查找每组中的获胜者。

    + +

    查询结果格式如下所示

    + +
    +Players 表:
    ++-----------+------------+
    +| player_id | group_id   |
    ++-----------+------------+
    +| 15        | 1          |
    +| 25        | 1          |
    +| 30        | 1          |
    +| 45        | 1          |
    +| 10        | 2          |
    +| 35        | 2          |
    +| 50        | 2          |
    +| 20        | 3          |
    +| 40        | 3          |
    ++-----------+------------+
    +
    +Matches 表:
    ++------------+--------------+---------------+-------------+--------------+
    +| match_id   | first_player | second_player | first_score | second_score |
    ++------------+--------------+---------------+-------------+--------------+
    +| 1          | 15           | 45            | 3           | 0            |
    +| 2          | 30           | 25            | 1           | 2            |
    +| 3          | 30           | 15            | 2           | 0            |
    +| 4          | 40           | 20            | 5           | 2            |
    +| 5          | 35           | 50            | 1           | 1            |
    ++------------+--------------+---------------+-------------+--------------+
    +
    +Result 表:
    ++-----------+------------+
    +| group_id  | player_id  |
    ++-----------+------------+ 
    +| 1         | 15         |
    +| 2         | 35         |
    +| 3         | 40         |
    ++-----------+------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1195.leetcode1195 Fizz Buzz Multithreaded-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1195.leetcode1195 Fizz Buzz Multithreaded-zh.md" new file mode 100644 index 00000000..4a0193d7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1195.leetcode1195 Fizz Buzz Multithreaded-zh.md" @@ -0,0 +1,137 @@ +# [1195. 交替打印字符串](https://leetcode-cn.com/problems/fizz-buzz-multithreaded) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1195.Fizz%20Buzz%20Multithreaded/README_EN.md) + +## 题目描述 + + + +

    编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是:

    + +
      +
    • 如果这个数字可以被 3 整除,输出 "fizz"。
    • +
    • 如果这个数字可以被 5 整除,输出 "buzz"。
    • +
    • 如果这个数字可以同时被 3 和 5 整除,输出 "fizzbuzz"。
    • +
    + +

    例如,当 n = 15,输出: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz

    + +

    假设有这么一个类:

    + +
    +class FizzBuzz {
    +  public FizzBuzz(int n) { ... }               // constructor
    +  public void fizz(printFizz) { ... }          // only output "fizz"
    +  public void buzz(printBuzz) { ... }          // only output "buzz"
    +  public void fizzbuzz(printFizzBuzz) { ... }  // only output "fizzbuzz"
    +  public void number(printNumber) { ... }      // only output the numbers
    +}
    + +

    请你实现一个有四个线程的多线程版  FizzBuzz, 同一个 FizzBuzz 实例会被如下四个线程使用:

    + +
      +
    1. 线程A将调用 fizz() 来判断是否能被 3 整除,如果可以,则输出 fizz
    2. +
    3. 线程B将调用 buzz() 来判断是否能被 5 整除,如果可以,则输出 buzz
    4. +
    5. 线程C将调用 fizzbuzz() 来判断是否同时能被 3 和 5 整除,如果可以,则输出 fizzbuzz
    6. +
    7. 线程D将调用 number() 来实现输出既不能被 3 整除也不能被 5 整除的数字。
    8. +
    + +

     

    + +

    提示:

    + +
      +
    • 本题已经提供了打印字符串的相关方法,如 printFizz() 等,具体方法名请参考答题模板中的注释部分。
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **C++** + +```cpp +class FizzBuzz { +private: + std::mutex mtx; + atomic index; + int n; + +// 这里主要运用到了C++11中的RAII锁(lock_guard)的知识。 +// 需要强调的一点是,在进入循环后,要时刻不忘加入index <= n的逻辑 +public: + FizzBuzz(int n) { + this->n = n; + index = 1; + } + + void fizz(function printFizz) { + while (index <= n) { + std::lock_guard lk(mtx); + if (0 == index % 3 && 0 != index % 5 && index <= n) { + printFizz(); + index++; + } + } + } + + void buzz(function printBuzz) { + while (index <= n) { + std::lock_guard lk(mtx); + if (0 == index % 5 && 0 != index % 3 && index <= n){ + printBuzz(); + index++; + } + } + } + + void fizzbuzz(function printFizzBuzz) { + while (index <= n) { + std::lock_guard lk(mtx); + if (0 == index % 15 && index <= n) { + printFizzBuzz(); + index++; + } + } + } + + void number(function printNumber) { + while (index <= n) { + std::lock_guard lk(mtx); + if (0 != index % 3 && 0 != index % 5 && index <= n) { + printNumber(index); + index++; + } + } + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1196.leetcode1196 How Many Apples Can You Put into the Basket-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1196.leetcode1196 How Many Apples Can You Put into the Basket-zh.md" new file mode 100644 index 00000000..f9b98e60 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1196.leetcode1196 How Many Apples Can You Put into the Basket-zh.md" @@ -0,0 +1,67 @@ +# [1196. 最多可以买到的苹果数量](https://leetcode-cn.com/problems/how-many-apples-can-you-put-into-the-basket) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1196.How%20Many%20Apples%20Can%20You%20Put%20into%20the%20Basket/README_EN.md) + +## 题目描述 + + + +

    楼下水果店正在促销,你打算买些苹果,arr[i] 表示第 i 个苹果的单位重量。

    + +

    你有一个购物袋,最多可以装 5000 单位重量的东西,算一算,最多可以往购物袋里装入多少苹果。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [100,200,150,1000]
    +输出:4
    +解释:所有 4 个苹果都可以装进去,因为它们的重量之和为 1450。
    +
    + +

    示例 2:

    + +
    输入:arr = [900,950,800,1000,700,800]
    +输出:5
    +解释:6 个苹果的总重量超过了 5000,所以我们只能从中任选 5 个。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^3
    • +
    • 1 <= arr[i] <= 10^3
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1197.leetcode1197 Minimum Knight Moves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1197.leetcode1197 Minimum Knight Moves-zh.md" new file mode 100644 index 00000000..ee1549cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1197.leetcode1197 Minimum Knight Moves-zh.md" @@ -0,0 +1,74 @@ +# [1197. 进击的骑士](https://leetcode-cn.com/problems/minimum-knight-moves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1197.Minimum%20Knight%20Moves/README_EN.md) + +## 题目描述 + + + +

    一个坐标可以从 -infinity 延伸到 +infinity 的 无限大的 棋盘上,你的 骑士 驻扎在坐标为 [0, 0] 的方格里。

    + +

    骑士的走法和中国象棋中的马相似,走 “日” 字:即先向左(或右)走 1 格,再向上(或下)走 2 格;或先向左(或右)走 2 格,再向上(或下)走 1 格。

    + +

    每次移动,他都可以按图示八个方向之一前进。

    + +

    + +

    现在,骑士需要前去征服坐标为 [x, y] 的部落,请你为他规划路线。

    + +

    最后返回所需的最小移动次数即可。本题确保答案是一定存在的。

    + +

     

    + +

    示例 1:

    + +
    输入:x = 2, y = 1
    +输出:1
    +解释:[0, 0] → [2, 1]
    +
    + +

    示例 2:

    + +
    输入:x = 5, y = 5
    +输出:4
    +解释:[0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • |x| + |y| <= 300
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1198.leetcode1198 Find Smallest Common Element in All Rows-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1198.leetcode1198 Find Smallest Common Element in All Rows-zh.md" new file mode 100644 index 00000000..00bd5f97 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1198.leetcode1198 Find Smallest Common Element in All Rows-zh.md" @@ -0,0 +1,83 @@ +# [1198. 找出所有行中最小公共元素](https://leetcode-cn.com/problems/find-smallest-common-element-in-all-rows) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1198.Find%20Smallest%20Common%20Element%20in%20All%20Rows/README_EN.md) + +## 题目描述 + + + +

    给你一个矩阵 mat,其中每一行的元素都已经按 严格递增 顺序排好了。请你帮忙找出在所有这些行中 最小的公共元素

    + +

    如果矩阵中没有这样的公共元素,就请返回 -1

    + +

     

    + +

    示例:

    + +
    +输入:mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= mat.length, mat[i].length <= 500
    • +
    • 1 <= mat[i][j] <= 10^4
    • +
    • mat[i] 已按严格递增顺序排列。
    • +
    + +## 解法 + + + +“计数器”实现。 + + + +### **Python3** + + + +```python +class Solution: + def smallestCommonElement(self, mat: List[List[int]]) -> int: + counter = collections.Counter() + for row in mat: + for num in row: + counter[num] += 1 + if counter[num] == len(mat): + return num + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int smallestCommonElement(int[][] mat) { + int[] counter = new int[10001]; + for (int[] row : mat) { + for (int num : row) { + ++counter[num]; + if (counter[num] == mat.length) { + return num; + } + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1199.leetcode1199 Minimum Time to Build Blocks-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1199.leetcode1199 Minimum Time to Build Blocks-zh.md" new file mode 100644 index 00000000..ce9b4cbf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1199.leetcode1199 Minimum Time to Build Blocks-zh.md" @@ -0,0 +1,86 @@ +# [1199. 建造街区的最短时间](https://leetcode-cn.com/problems/minimum-time-to-build-blocks) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1100-1199/1199.Minimum%20Time%20to%20Build%20Blocks/README_EN.md) + +## 题目描述 + + + +

    你是个城市规划工作者,手里负责管辖一系列的街区。在这个街区列表中 blocks[i] = t 意味着第  i 个街区需要 t 个单位的时间来建造。

    + +

    由于一个街区只能由一个工人来完成建造。

    + +

    所以,一个工人要么需要再召唤一个工人(工人数增加 1);要么建造完一个街区后回家。这两个决定都需要花费一定的时间。

    + +

    一个工人再召唤一个工人所花费的时间由整数 split 给出。

    + +

    注意:如果两个工人同时召唤别的工人,那么他们的行为是并行的,所以时间花费仍然是 split

    + +

    最开始的时候只有 一个 工人,请你最后输出建造完所有街区所需要的最少时间。

    + +

     

    + +

    示例 1:

    + +
    输入:blocks = [1], split = 1
    +输出:1
    +解释:我们使用 1 个工人在 1 个时间单位内来建完 1 个街区。
    +
    + +

    示例 2:

    + +
    输入:blocks = [1,2], split = 5
    +输出:7
    +解释:我们用 5 个时间单位将这个工人分裂为 2 个工人,然后指派每个工人分别去建造街区,从而时间花费为 5 + max(1, 2) = 7
    +
    + +

    示例 3:

    + +
    输入:blocks = [1,2,3], split = 1
    +输出:4
    +解释:
    +将 1 个工人分裂为 2 个工人,然后指派第一个工人去建造最后一个街区,并将第二个工人分裂为 2 个工人。
    +然后,用这两个未分派的工人分别去建造前两个街区。
    +时间花费为 1 + max(3, 1 + max(1, 2)) = 4
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= blocks.length <= 1000
    2. +
    3. 1 <= blocks[i] <= 10^5
    4. +
    5. 1 <= split <= 100
    6. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1200.leetcode1200 Minimum Absolute Difference-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1200.leetcode1200 Minimum Absolute Difference-zh.md" new file mode 100644 index 00000000..04cd3c51 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1200.leetcode1200 Minimum Absolute Difference-zh.md" @@ -0,0 +1,71 @@ +# [1200. 最小绝对差](https://leetcode-cn.com/problems/minimum-absolute-difference) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1200.Minimum%20Absolute%20Difference/README_EN.md) + +## 题目描述 + + + +

    给你个整数数组 arr,其中每个元素都 不相同

    + +

    请你找到所有具有最小绝对差的元素对,并且按升序的顺序返回。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [4,2,1,3]
    +输出:[[1,2],[2,3],[3,4]]
    +
    + +

    示例 2:

    + +
    输入:arr = [1,3,6,10,15]
    +输出:[[1,3]]
    +
    + +

    示例 3:

    + +
    输入:arr = [3,8,-10,23,19,-4,-14,27]
    +输出:[[-14,-10],[19,23],[23,27]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 10^5
    • +
    • -10^6 <= arr[i] <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1201.leetcode1201 Ugly Number III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1201.leetcode1201 Ugly Number III-zh.md" new file mode 100644 index 00000000..1af91bbe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1201.leetcode1201 Ugly Number III-zh.md" @@ -0,0 +1,84 @@ +# [1201. 丑数 III](https://leetcode-cn.com/problems/ugly-number-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1201.Ugly%20Number%20III/README_EN.md) + +## 题目描述 + + + +

    给你四个整数:nabc ,请你设计一个算法来找出第 n 个丑数。

    + +

    丑数是可以被 a  b  c 整除的 正整数

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, a = 2, b = 3, c = 5
    +输出:4
    +解释:丑数序列为 2, 3, 4, 5, 6, 8, 9, 10... 其中第 3 个是 4。
    + +

    示例 2:

    + +
    +输入:n = 4, a = 2, b = 3, c = 4
    +输出:6
    +解释:丑数序列为 2, 3, 4, 6, 8, 9, 10, 12... 其中第 4 个是 6。
    +
    + +

    示例 3:

    + +
    +输入:n = 5, a = 2, b = 11, c = 13
    +输出:10
    +解释:丑数序列为 2, 4, 6, 8, 10, 11, 12, 13... 其中第 5 个是 10。
    +
    + +

    示例 4:

    + +
    +输入:n = 1000000000, a = 2, b = 217983653, c = 336916467
    +输出:1999999984
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n, a, b, c <= 10^9
    • +
    • 1 <= a * b * c <= 10^18
    • +
    • 本题结果在 [1, 2 * 10^9] 的范围内
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1202.leetcode1202 Smallest String With Swaps-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1202.leetcode1202 Smallest String With Swaps-zh.md" new file mode 100644 index 00000000..63ca1e64 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1202.leetcode1202 Smallest String With Swaps-zh.md" @@ -0,0 +1,85 @@ +# [1202. 交换字符串中的元素](https://leetcode-cn.com/problems/smallest-string-with-swaps) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1202.Smallest%20String%20With%20Swaps/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。

    + +

    你可以 任意多次交换 在 pairs 中任意一对索引处的字符。

    + +

    返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "dcab", pairs = [[0,3],[1,2]]
    +输出:"bacd"
    +解释: 
    +交换 s[0] 和 s[3], s = "bcad"
    +交换 s[1] 和 s[2], s = "bacd"
    +
    + +

    示例 2:

    + +
    输入:s = "dcab", pairs = [[0,3],[1,2],[0,2]]
    +输出:"abcd"
    +解释:
    +交换 s[0] 和 s[3], s = "bcad"
    +交换 s[0] 和 s[2], s = "acbd"
    +交换 s[1] 和 s[2], s = "abcd"
    + +

    示例 3:

    + +
    输入:s = "cba", pairs = [[0,1],[1,2]]
    +输出:"abc"
    +解释:
    +交换 s[0] 和 s[1], s = "bca"
    +交换 s[1] 和 s[2], s = "bac"
    +交换 s[0] 和 s[1], s = "abc"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • 0 <= pairs.length <= 10^5
    • +
    • 0 <= pairs[i][0], pairs[i][1] < s.length
    • +
    • s 中只含有小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1203.leetcode1203 Sort Items by Groups Respecting Dependencies-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1203.leetcode1203 Sort Items by Groups Respecting Dependencies-zh.md" new file mode 100644 index 00000000..9f49df46 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1203.leetcode1203 Sort Items by Groups Respecting Dependencies-zh.md" @@ -0,0 +1,82 @@ +# [1203. 项目管理](https://leetcode-cn.com/problems/sort-items-by-groups-respecting-dependencies) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1203.Sort%20Items%20by%20Groups%20Respecting%20Dependencies/README_EN.md) + +## 题目描述 + + + +

    n 个项目,每个项目或者不属于任何小组,或者属于 m 个小组之一。group[i] 表示第 i 个项目所属的小组,如果第 i 个项目不属于任何小组,则 group[i] 等于 -1。项目和小组都是从零开始编号的。可能存在小组不负责任何项目,即没有任何项目属于这个小组。

    + +

    请你帮忙按要求安排这些项目的进度,并返回排序后的项目列表:

    + +
      +
    • 同一小组的项目,排序后在列表中彼此相邻。
    • +
    • 项目之间存在一定的依赖关系,我们用一个列表 beforeItems 来表示,其中 beforeItems[i] 表示在进行第 i 个项目前(位于第 i 个项目左侧)应该完成的所有项目。
    • +
    + +

    如果存在多个解决方案,只需要返回其中任意一个即可。如果没有合适的解决方案,就请返回一个 空列表

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
    +输出:[6,3,4,1,5,2,0,7]
    +
    + +

    示例 2:

    + +
    +输入:n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
    +输出:[]
    +解释:与示例 1 大致相同,但是在排序后的列表中,4 必须放在 6 的前面。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m <= n <= 3 * 104
    • +
    • group.length == beforeItems.length == n
    • +
    • -1 <= group[i] <= m - 1
    • +
    • 0 <= beforeItems[i].length <= n - 1
    • +
    • 0 <= beforeItems[i][j] <= n - 1
    • +
    • i != beforeItems[i][j]
    • +
    • beforeItems[i] 不含重复元素
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1204.leetcode1204 Last Person to Fit in the Bus-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1204.leetcode1204 Last Person to Fit in the Bus-zh.md" new file mode 100644 index 00000000..85b17966 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1204.leetcode1204 Last Person to Fit in the Bus-zh.md" @@ -0,0 +1,71 @@ +# [1204. 最后一个能进入电梯的人](https://leetcode-cn.com/problems/last-person-to-fit-in-the-bus) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1204.Last%20Person%20to%20Fit%20in%20the%20Bus/README_EN.md) + +## 题目描述 + + + +

    表: Queue

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| person_id   | int     |
    +| person_name | varchar |
    +| weight      | int     |
    +| turn        | int     |
    ++-------------+---------+
    +person_id 是这个表的主键。
    +该表展示了所有等待电梯的人的信息。
    +表中 person_id 和 turn 列将包含从 1 到 n 的所有数字,其中 n 是表中的行数。
    +
    + +

     

    + +

    电梯最大载重量为 1000

    + +

    写一条 SQL 查询语句查找最后一个能进入电梯且不超过重量限制的 person_name 。题目确保队列中第一位的人可以进入电梯 。

    + +

    查询结果如下所示 :

    + +
    Queue 表
    ++-----------+-------------------+--------+------+
    +| person_id | person_name       | weight | turn |
    ++-----------+-------------------+--------+------+
    +| 5         | George Washington | 250    | 1    |
    +| 3         | John Adams        | 350    | 2    |
    +| 6         | Thomas Jefferson  | 400    | 3    |
    +| 2         | Will Johnliams    | 200    | 4    |
    +| 4         | Thomas Jefferson  | 175    | 5    |
    +| 1         | James Elephant    | 500    | 6    |
    ++-----------+-------------------+--------+------+
    +
    +Result 表
    ++-------------------+
    +| person_name       |
    ++-------------------+
    +| Thomas Jefferson  |
    ++-------------------+
    +
    +为了简化,Queue 表按 turn 列由小到大排序。
    +上例中 George Washington(id 5), John Adams(id 3) 和 Thomas Jefferson(id 6) 将可以进入电梯,因为他们的体重和为 250 + 350 + 400 = 1000。
    +Thomas Jefferson(id 6) 是最后一个体重合适并进入电梯的人。
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1204.leetcode1204 Last Person to Fit in the Elevator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1204.leetcode1204 Last Person to Fit in the Elevator-zh.md" new file mode 100644 index 00000000..20af7146 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1204.leetcode1204 Last Person to Fit in the Elevator-zh.md" @@ -0,0 +1,69 @@ +# [1204. 最后一个能进入电梯的人](https://leetcode-cn.com/problems/last-person-to-fit-in-the-elevator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1204.Last%20Person%20to%20Fit%20in%20the%20Elevator/README_EN.md) + +## 题目描述 + + + +

    表: Queue

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| person_id   | int     |
    +| person_name | varchar |
    +| weight      | int     |
    +| turn        | int     |
    ++-------------+---------+
    +person_id 是这个表的主键。
    +该表展示了所有等待电梯的人的信息。
    +表中 person_id 和 turn 列将包含从 1 到 n 的所有数字,其中 n 是表中的行数。
    +
    + +

     

    + +

    电梯最大载重量为 1000

    + +

    写一条 SQL 查询语句查找最后一个能进入电梯且不超过重量限制的 person_name 。题目确保队列中第一位的人可以进入电梯 。

    + +

    查询结果如下所示 :

    + +
    Queue 表
    ++-----------+-------------------+--------+------+
    +| person_id | person_name       | weight | turn |
    ++-----------+-------------------+--------+------+
    +| 5         | George Washington | 250    | 1    |
    +| 3         | John Adams        | 350    | 2    |
    +| 6         | Thomas Jefferson  | 400    | 3    |
    +| 2         | Will Johnliams    | 200    | 4    |
    +| 4         | Thomas Jefferson  | 175    | 5    |
    +| 1         | James Elephant    | 500    | 6    |
    ++-----------+-------------------+--------+------+
    +
    +Result 表
    ++-------------------+
    +| person_name       |
    ++-------------------+
    +| Thomas Jefferson  |
    ++-------------------+
    +
    +为了简化,Queue 表按 turn 列由小到大排序。
    +上例中 George Washington(id 5), John Adams(id 3) 和 Thomas Jefferson(id 6) 将可以进入电梯,因为他们的体重和为 250 + 350 + 400 = 1000。
    +Thomas Jefferson(id 6) 是最后一个体重合适并进入电梯的人。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1205.leetcode1205 Monthly Transactions II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1205.leetcode1205 Monthly Transactions II-zh.md" new file mode 100644 index 00000000..13feb729 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1205.leetcode1205 Monthly Transactions II-zh.md" @@ -0,0 +1,89 @@ +# [1205. 每月交易II](https://leetcode-cn.com/problems/monthly-transactions-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1205.Monthly%20Transactions%20II/README_EN.md) + +## 题目描述 + + + +

    Transactions 记录表

    + +
    +----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| id             | int     |
    +| country        | varchar |
    +| state          | enum    |
    +| amount         | int     |
    +| trans_date     | date    |
    ++----------------+---------+
    +id 是这个表的主键。
    +该表包含有关传入事务的信息。
    +状态列是类型为 [approved(已批准)、declined(已拒绝)] 的枚举。
    + +

     

    + +

    Chargebacks

    + +
    +----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| trans_id       | int     |
    +| charge_date    | date    |
    ++----------------+---------+
    +退单包含有关放置在事务表中的某些事务的传入退单的基本信息。
    +trans_id 是 transactions 表的 id 列的外键。
    +每项退单都对应于之前进行的交易,即使未经批准。
    + +

     

    + +

    编写一个 SQL 查询,以查找每个月和每个国家/地区的已批准交易的数量及其总金额、退单的数量及其总金额。

    + +

    注意:在您的查询中,给定月份和国家,忽略所有为零的行。

    + +

    查询结果格式如下所示:

    + +
    Transactions 表:
    ++------+---------+----------+--------+------------+
    +| id   | country | state    | amount | trans_date |
    ++------+---------+----------+--------+------------+
    +| 101  | US      | approved | 1000   | 2019-05-18 |
    +| 102  | US      | declined | 2000   | 2019-05-19 |
    +| 103  | US      | approved | 3000   | 2019-06-10 |
    +| 104  | US      | declined | 4000   | 2019-06-13 |
    +| 105  | US      | approved | 5000   | 2019-06-15 |
    ++------+---------+----------+--------+------------+
    +
    +Chargebacks 表:
    ++------------+------------+
    +| trans_id   | trans_date |
    ++------------+------------+
    +| 102        | 2019-05-29 |
    +| 101        | 2019-06-30 |
    +| 105        | 2019-09-18 |
    ++------------+------------+
    +
    +Result 表:
    ++----------+---------+----------------+-----------------+-------------------+--------------------+
    +| month    | country | approved_count | approved_amount | chargeback_count  | chargeback_amount  |
    ++----------+---------+----------------+-----------------+-------------------+--------------------+
    +| 2019-05  | US      | 1              | 1000            | 1                 | 2000               |
    +| 2019-06  | US      | 2              | 8000            | 1                 | 1000               |
    +| 2019-09  | US      | 0              | 0               | 1                 | 5000               |
    ++----------+---------+----------------+-----------------+-------------------+--------------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1206.leetcode1206 Design Skiplist-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1206.leetcode1206 Design Skiplist-zh.md" new file mode 100644 index 00000000..f3f4049a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1206.leetcode1206 Design Skiplist-zh.md" @@ -0,0 +1,83 @@ +# [1206. 设计跳表](https://leetcode-cn.com/problems/design-skiplist) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1206.Design%20Skiplist/README_EN.md) + +## 题目描述 + + + +

    不使用任何库函数,设计一个跳表。

    + +

    跳表是在 O(log(n)) 时间内完成增加、删除、搜索操作的数据结构。跳表相比于树堆与红黑树,其功能与性能相当,并且跳表的代码长度相较下更短,其设计思想与链表相似。

    + +

    例如,一个跳表包含 [30, 40, 50, 60, 70, 90],然后增加 80、45 到跳表中,以下图的方式操作:

    + +


    +Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons

    + +

    跳表中有很多层,每一层是一个短的链表。在第一层的作用下,增加、删除和搜索操作的时间复杂度不超过 O(n)。跳表的每一个操作的平均时间复杂度是 O(log(n)),空间复杂度是 O(n)。

    + +

    在本题中,你的设计应该要包含这些函数:

    + +
      +
    • bool search(int target) : 返回target是否存在于跳表中。
    • +
    • void add(int num): 插入一个元素到跳表。
    • +
    • bool erase(int num): 在跳表中删除一个值,如果 num 不存在,直接返回false. 如果存在多个 num ,删除其中任意一个即可。
    • +
    + +

    了解更多 : https://en.wikipedia.org/wiki/Skip_list

    + +

    注意,跳表中可能存在多个相同的值,你的代码需要处理这种情况。

    + +

    样例:

    + +
    Skiplist skiplist = new Skiplist();
    +
    +skiplist.add(1);
    +skiplist.add(2);
    +skiplist.add(3);
    +skiplist.search(0);   // 返回 false
    +skiplist.add(4);
    +skiplist.search(1);   // 返回 true
    +skiplist.erase(0);    // 返回 false,0 不在跳表中
    +skiplist.erase(1);    // 返回 true
    +skiplist.search(1);   // 返回 false,1 已被擦除
    +
    + +

    约束条件:

    + +
      +
    • 0 <= num, target <= 20000
    • +
    • 最多调用 50000 次 search, add, 以及 erase操作。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1207.leetcode1207 Unique Number of Occurrences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1207.leetcode1207 Unique Number of Occurrences-zh.md" new file mode 100644 index 00000000..9153535f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1207.leetcode1207 Unique Number of Occurrences-zh.md" @@ -0,0 +1,71 @@ +# [1207. 独一无二的出现次数](https://leetcode-cn.com/problems/unique-number-of-occurrences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1207.Unique%20Number%20of%20Occurrences/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。

    + +

    如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2,2,1,1,3]
    +输出:true
    +解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。
    + +

    示例 2:

    + +
    输入:arr = [1,2]
    +输出:false
    +
    + +

    示例 3:

    + +
    输入:arr = [-3,0,1,-3,1,1,1,-3,10,0]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • -1000 <= arr[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1208.leetcode1208 Get Equal Substrings Within Budget-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1208.leetcode1208 Get Equal Substrings Within Budget-zh.md" new file mode 100644 index 00000000..5c7aac83 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1208.leetcode1208 Get Equal Substrings Within Budget-zh.md" @@ -0,0 +1,83 @@ +# [1208. 尽可能使字符串相等](https://leetcode-cn.com/problems/get-equal-substrings-within-budget) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1208.Get%20Equal%20Substrings%20Within%20Budget/README_EN.md) + +## 题目描述 + + + +

    给你两个长度相同的字符串,st

    + +

    s 中的第 i 个字符变到 t 中的第 i 个字符需要 |s[i] - t[i]| 的开销(开销可能为 0),也就是两个字符的 ASCII 码值的差的绝对值。

    + +

    用于变更字符串的最大预算是 maxCost。在转化字符串时,总开销应当小于等于该预算,这也意味着字符串的转化可能是不完全的。

    + +

    如果你可以将 s 的子字符串转化为它在 t 中对应的子字符串,则返回可以转化的最大长度。

    + +

    如果 s 中没有子字符串可以转化成 t 中对应的子字符串,则返回 0

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abcd", t = "bcdf", maxCost = 3
    +输出:3
    +解释:s 中的 "abc" 可以变为 "bcd"。开销为 3,所以最大长度为 3。
    + +

    示例 2:

    + +
    +输入:s = "abcd", t = "cdef", maxCost = 3
    +输出:1
    +解释:s 中的任一字符要想变成 t 中对应的字符,其开销都是 2。因此,最大长度为 1。
    +
    + +

    示例 3:

    + +
    +输入:s = "abcd", t = "acde", maxCost = 0
    +输出:1
    +解释:a -> a, cost = 0,字符串未发生变化,所以最大长度为 1。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length, t.length <= 10^5
    • +
    • 0 <= maxCost <= 10^6
    • +
    • s 和 t 都只含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1209.leetcode1209 Remove All Adjacent Duplicates in String II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1209.leetcode1209 Remove All Adjacent Duplicates in String II-zh.md" new file mode 100644 index 00000000..730205a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1209.leetcode1209 Remove All Adjacent Duplicates in String II-zh.md" @@ -0,0 +1,79 @@ +# [1209. 删除字符串中的所有相邻重复项 II](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1209.Remove%20All%20Adjacent%20Duplicates%20in%20String%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,「k 倍重复项删除操作」将会从 s 中选择 k 个相邻且相等的字母,并删除它们,使被删去的字符串的左侧和右侧连在一起。

    + +

    你需要对 s 重复进行无限次这样的删除操作,直到无法继续为止。

    + +

    在执行完所有删除操作后,返回最终得到的字符串。

    + +

    本题答案保证唯一。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "abcd", k = 2
    +输出:"abcd"
    +解释:没有要删除的内容。
    + +

    示例 2:

    + +
    输入:s = "deeedbbcccbdaa", k = 3
    +输出:"aa"
    +解释: 
    +先删除 "eee" 和 "ccc",得到 "ddbbbdaa"
    +再删除 "bbb",得到 "dddaa"
    +最后删除 "ddd",得到 "aa"
    + +

    示例 3:

    + +
    输入:s = "pbbcggttciiippooaais", k = 2
    +输出:"ps"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • 2 <= k <= 10^4
    • +
    • s 中只含有小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1210.leetcode1210 Minimum Moves to Reach Target with Rotations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1210.leetcode1210 Minimum Moves to Reach Target with Rotations-zh.md" new file mode 100644 index 00000000..e8619e46 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1210.leetcode1210 Minimum Moves to Reach Target with Rotations-zh.md" @@ -0,0 +1,95 @@ +# [1210. 穿过迷宫的最少移动次数](https://leetcode-cn.com/problems/minimum-moves-to-reach-target-with-rotations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1210.Minimum%20Moves%20to%20Reach%20Target%20with%20Rotations/README_EN.md) + +## 题目描述 + + + +

    你还记得那条风靡全球的贪吃蛇吗?

    + +

    我们在一个 n*n 的网格上构建了新的迷宫地图,蛇的长度为 2,也就是说它会占去两个单元格。蛇会从左上角((0, 0) 和 (0, 1))开始移动。我们用 0 表示空单元格,用 1 表示障碍物。蛇需要移动到迷宫的右下角((n-1, n-2) 和 (n-1, n-1))。

    + +

    每次移动,蛇可以这样走:

    + +
      +
    • 如果没有障碍,则向右移动一个单元格。并仍然保持身体的水平/竖直状态。
    • +
    • 如果没有障碍,则向下移动一个单元格。并仍然保持身体的水平/竖直状态。
    • +
    • 如果它处于水平状态并且其下面的两个单元都是空的,就顺时针旋转 90 度。蛇从((r, c)(r, c+1))移动到 ((r, c)(r+1, c))。
      +
    • +
    • 如果它处于竖直状态并且其右面的两个单元都是空的,就逆时针旋转 90 度。蛇从((r, c)(r+1, c))移动到((r, c)(r, c+1))。
      +
    • +
    + +

    返回蛇抵达目的地所需的最少移动次数。

    + +

    如果无法到达目的地,请返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[0,0,0,0,0,1],
    +               [1,1,0,0,1,0],
    +               [0,0,0,0,1,1],
    +               [0,0,1,0,1,0],
    +               [0,1,1,0,0,0],
    +               [0,1,1,0,0,0]]
    +输出:11
    +解释:
    +一种可能的解决方案是 [右, 右, 顺时针旋转, 右, 下, 下, 下, 下, 逆时针旋转, 右, 下]。
    +
    + +

    示例 2:

    + +
    输入:grid = [[0,0,1,1,1,1],
    +               [0,0,0,0,1,1],
    +               [1,1,0,0,0,1],
    +               [1,1,1,0,0,1],
    +               [1,1,1,0,0,1],
    +               [1,1,1,0,0,0]]
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • 0 <= grid[i][j] <= 1
    • +
    • 蛇保证从空单元格开始出发。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1211.leetcode1211 Queries Quality and Percentage-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1211.leetcode1211 Queries Quality and Percentage-zh.md" new file mode 100644 index 00000000..75173bd8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1211.leetcode1211 Queries Quality and Percentage-zh.md" @@ -0,0 +1,87 @@ +# [1211. 查询结果的质量和占比](https://leetcode-cn.com/problems/queries-quality-and-percentage) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1211.Queries%20Quality%20and%20Percentage/README_EN.md) + +## 题目描述 + + + +

    查询表 Queries: 

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| query_name  | varchar |
    +| result      | varchar |
    +| position    | int     |
    +| rating      | int     |
    ++-------------+---------+
    +此表没有主键,并可能有重复的行。
    +此表包含了一些从数据库中收集的查询信息。
    +“位置”(position)列的值为 1 到 500 。
    +“评分”(rating)列的值为 1 到 5 。评分小于 3 的查询被定义为质量很差的查询。
    +
    + +

     

    + +

    将查询结果的质量 quality 定义为:

    + +
    +

    各查询结果的评分与其位置之间比率的平均值。

    +
    + +

    将劣质查询百分比 poor_query_percentage 为:

    + +
    +

    评分小于 3 的查询结果占全部查询结果的百分比。

    +
    + +

    编写一组 SQL 来查找每次查询的名称(query_name)、质量(quality) 和 劣质查询百分比(poor_query_percentage)。

    + +

    质量(quality) 和劣质查询百分比(poor_query_percentage) 都应四舍五入到小数点后两位。

    + +

    查询结果格式如下所示:

    + +
    +Queries table:
    ++------------+-------------------+----------+--------+
    +| query_name | result            | position | rating |
    ++------------+-------------------+----------+--------+
    +| Dog        | Golden Retriever  | 1        | 5      |
    +| Dog        | German Shepherd   | 2        | 5      |
    +| Dog        | Mule              | 200      | 1      |
    +| Cat        | Shirazi           | 5        | 2      |
    +| Cat        | Siamese           | 3        | 3      |
    +| Cat        | Sphynx            | 7        | 4      |
    ++------------+-------------------+----------+--------+
    +
    +Result table:
    ++------------+---------+-----------------------+
    +| query_name | quality | poor_query_percentage |
    ++------------+---------+-----------------------+
    +| Dog        | 2.50    | 33.33                 |
    +| Cat        | 0.66    | 33.33                 |
    ++------------+---------+-----------------------+
    +
    +Dog 查询结果的质量为 ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50
    +Dog 查询结果的劣质查询百分比为 (1 / 3) * 100 = 33.33
    +
    +Cat 查询结果的质量为 ((2 / 5) + (3 / 3) + (4 / 7)) / 3 = 0.66
    +Cat 查询结果的劣质查询百分比为 (1 / 3) * 100 = 33.33
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1212.leetcode1212 Team Scores in Football Tournament-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1212.leetcode1212 Team Scores in Football Tournament-zh.md" new file mode 100644 index 00000000..bdcd1a32 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1212.leetcode1212 Team Scores in Football Tournament-zh.md" @@ -0,0 +1,98 @@ +# [1212. 查询球队积分](https://leetcode-cn.com/problems/team-scores-in-football-tournament) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1212.Team%20Scores%20in%20Football%20Tournament/README_EN.md) + +## 题目描述 + + + +

    Table: Teams

    + +
    ++---------------+----------+
    +| Column Name   | Type     |
    ++---------------+----------+
    +| team_id       | int      |
    +| team_name     | varchar  |
    ++---------------+----------+
    +此表的主键是 team_id,表中的每一行都代表一支独立足球队。
    +
    + +

    Table: Matches

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| match_id      | int     |
    +| host_team     | int     |
    +| guest_team    | int     | 
    +| host_goals    | int     |
    +| guest_goals   | int     |
    ++---------------+---------+
    +此表的主键是 match_id,表中的每一行都代表一场已结束的比赛,比赛的主客队分别由它们自己的 id 表示,他们的进球由 host_goals 和 guest_goals 分别表示。
    +
    + +

     

    + +

    积分规则如下:

    + +
      +
    • 赢一场得三分;
    • +
    • 平一场得一分;
    • +
    • 输一场不得分。
    • +
    + +

    写出一条SQL语句以查询每个队的 team_idteam_namenum_points。结果根据 num_points 降序排序,如果有两队积分相同,那么这两队按 team_id  升序排序

    + +

    查询结果格式如下:

    + +
    +Teams table:
    ++-----------+--------------+
    +| team_id   | team_name    |
    ++-----------+--------------+
    +| 10        | Leetcode FC  |
    +| 20        | NewYork FC   |
    +| 30        | Atlanta FC   |
    +| 40        | Chicago FC   |
    +| 50        | Toronto FC   |
    ++-----------+--------------+
    +
    +Matches table:
    ++------------+--------------+---------------+-------------+--------------+
    +| match_id   | host_team    | guest_team    | host_goals  | guest_goals  |
    ++------------+--------------+---------------+-------------+--------------+
    +| 1          | 10           | 20            | 3           | 0            |
    +| 2          | 30           | 10            | 2           | 2            |
    +| 3          | 10           | 50            | 5           | 1            |
    +| 4          | 20           | 30            | 1           | 0            |
    +| 5          | 50           | 30            | 1           | 0            |
    ++------------+--------------+---------------+-------------+--------------+
    +
    +Result table:
    ++------------+--------------+---------------+
    +| team_id    | team_name    | num_points    |
    ++------------+--------------+---------------+
    +| 10         | Leetcode FC  | 7             |
    +| 20         | NewYork FC   | 3             |
    +| 50         | Toronto FC   | 3             |
    +| 30         | Atlanta FC   | 1             |
    +| 40         | Chicago FC   | 0             |
    ++------------+--------------+---------------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1213.leetcode1213 Intersection of Three Sorted Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1213.leetcode1213 Intersection of Three Sorted Arrays-zh.md" new file mode 100644 index 00000000..27cc0e7e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1213.leetcode1213 Intersection of Three Sorted Arrays-zh.md" @@ -0,0 +1,159 @@ +# [1213. 三个有序数组的交集](https://leetcode-cn.com/problems/intersection-of-three-sorted-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1213.Intersection%20of%20Three%20Sorted%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给出三个均为 严格递增排列 的整数数组 arr1arr2 和 arr3

    + +

    返回一个由 在这三个数组中 同时出现 的整数所构成的有序数组。

    + +

     

    + +

    示例:

    + +
    输入: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
    +输出: [1,5]
    +解释: 只有 1 和 5 同时在这三个数组中出现.
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= arr1.length, arr2.length, arr3.length <= 1000
    2. +
    3. 1 <= arr1[i], arr2[i], arr3[i] <= 2000
    4. +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: + def find(arr, val): + left, right = 0, len(arr) - 1 + while left < right: + mid = (left + right) >> 1 + if arr[mid] >= val: + right = mid + else: + left = mid + 1 + return arr[left] == val + + res = [] + for num in arr1: + if find(arr2, num) and find(arr3, num): + res.append(num) + return res +``` + +### **Java** + + + +```java +class Solution { + public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { + List res = new ArrayList<>(); + for (int num : arr1) { + if (find(arr2, num) && find(arr3, num)) { + res.add(num); + } + } + return res; + } + + private boolean find(int[] arr, int val) { + int left = 0, right = arr.length - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (arr[mid] >= val) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == val; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + vector res; + for (int num : arr1) { + if (find(arr2, num) && find(arr3, num)) { + res.push_back(num); + } + } + return res; + } + +private: + bool find(vector& arr, int val) { + int left = 0, right = arr.size() - 1; + while (left < right) { + int mid = left + right >> 1; + if (arr[mid] >= val) { + right = mid; + } else { + left = mid + 1; + } + } + return arr[left] == val; + } +}; +``` + +### **Go** + +```go +func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) []int { + var res []int + for _, num := range arr1 { + if find(arr2, num) && find(arr3, num) { + res = append(res, num) + } + } + return res +} + +func find(arr []int, val int) bool { + left, right := 0, len(arr)-1 + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= val { + right = mid + } else { + left = mid + 1 + } + } + return arr[left] == val +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1214.leetcode1214 Two Sum BSTs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1214.leetcode1214 Two Sum BSTs-zh.md" new file mode 100644 index 00000000..8c6436f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1214.leetcode1214 Two Sum BSTs-zh.md" @@ -0,0 +1,69 @@ +# [1214. 查找两棵二叉搜索树之和](https://leetcode-cn.com/problems/two-sum-bsts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1214.Two%20Sum%20BSTs/README_EN.md) + +## 题目描述 + + + +

    给出两棵二叉搜索树,请你从两棵树中各找出一个节点,使得这两个节点的值之和等于目标值 Target

    + +

    如果可以找到返回 True,否则返回 False

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root1 = [2,1,4], root2 = [1,0,3], target = 5
    +输出:true
    +解释:2 加 3 和为 5 。
    +
    + +

    示例 2:

    + +

    + +
    输入:root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
    +输出:false
    + +

     

    + +

    提示:

    + +
      +
    1. 每棵树上最多有 5000 个节点。
    2. +
    3. -10^9 <= target, node.val <= 10^9
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1215.leetcode1215 Stepping Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1215.leetcode1215 Stepping Numbers-zh.md" new file mode 100644 index 00000000..f107fb0c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1215.leetcode1215 Stepping Numbers-zh.md" @@ -0,0 +1,60 @@ +# [1215. 步进数](https://leetcode-cn.com/problems/stepping-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1215.Stepping%20Numbers/README_EN.md) + +## 题目描述 + + + +

    如果一个整数上的每一位数字与其相邻位上的数字的绝对差都是 1,那么这个数就是一个「步进数」。

    + +

    例如,321 是一个步进数,而 421 不是。

    + +

    给你两个整数,low 和 high,请你找出在 [low, high] 范围内的所有步进数,并返回 排序后 的结果。

    + +

     

    + +

    示例:

    + +
    输入:low = 0, high = 21
    +输出:[0,1,2,3,4,5,6,7,8,9,10,12,21]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= low <= high <= 2 * 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1216.leetcode1216 Valid Palindrome III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1216.leetcode1216 Valid Palindrome III-zh.md" new file mode 100644 index 00000000..a5e457ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1216.leetcode1216 Valid Palindrome III-zh.md" @@ -0,0 +1,61 @@ +# [1216. 验证回文字符串 III](https://leetcode-cn.com/problems/valid-palindrome-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1216.Valid%20Palindrome%20III/README_EN.md) + +## 题目描述 + + + +

    给出一个字符串 s 和一个整数 k,请你帮忙判断这个字符串是不是一个「K 回文」。

    + +

    所谓「K 回文」:如果可以通过从字符串中删去最多 k 个字符将其转换为回文,那么这个字符串就是一个「K 回文」。

    + +

     

    + +

    示例:

    + +
    输入:s = "abcdeca", k = 2
    +出:true
    +解释:删除字符 “b” 和 “e”。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 中只含有小写英文字母
    • +
    • 1 <= k <= s.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1217.leetcode1217 Minimum Cost to Move Chips to The Same Position-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1217.leetcode1217 Minimum Cost to Move Chips to The Same Position-zh.md" new file mode 100644 index 00000000..a0a6e086 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1217.leetcode1217 Minimum Cost to Move Chips to The Same Position-zh.md" @@ -0,0 +1,76 @@ +# [1217. 玩筹码](https://leetcode-cn.com/problems/minimum-cost-to-move-chips-to-the-same-position) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1217.Minimum%20Cost%20to%20Move%20Chips%20to%20The%20Same%20Position/README_EN.md) + +## 题目描述 + + + +

    数轴上放置了一些筹码,每个筹码的位置存在数组 chips 当中。

    + +

    你可以对 任何筹码 执行下面两种操作之一(不限操作次数,0 次也可以):

    + +
      +
    • 将第 i 个筹码向左或者右移动 2 个单位,代价为 0
    • +
    • 将第 i 个筹码向左或者右移动 1 个单位,代价为 1
    • +
    + +

    最开始的时候,同一位置上也可能放着两个或者更多的筹码。

    + +

    返回将所有筹码移动到同一位置(任意位置)上所需要的最小代价。

    + +

     

    + +

    示例 1:

    + +
    输入:chips = [1,2,3]
    +输出:1
    +解释:第二个筹码移动到位置三的代价是 1,第一个筹码移动到位置三的代价是 0,总代价为 1。
    +
    + +

    示例 2:

    + +
    输入:chips = [2,2,2,3,3]
    +输出:2
    +解释:第四和第五个筹码移动到位置二的代价都是 1,所以最小总代价为 2。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= chips.length <= 100
    • +
    • 1 <= chips[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1218.leetcode1218 Longest Arithmetic Subsequence of Given Difference-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1218.leetcode1218 Longest Arithmetic Subsequence of Given Difference-zh.md" new file mode 100644 index 00000000..f1c82713 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1218.leetcode1218 Longest Arithmetic Subsequence of Given Difference-zh.md" @@ -0,0 +1,76 @@ +# [1218. 最长定差子序列](https://leetcode-cn.com/problems/longest-arithmetic-subsequence-of-given-difference) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1218.Longest%20Arithmetic%20Subsequence%20of%20Given%20Difference/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数 difference,请你找出并返回 arr 中最长等差子序列的长度,该子序列中相邻元素之间的差等于 difference

    + +

    子序列 是指在不改变其余元素顺序的情况下,通过删除一些元素或不删除任何元素而从 arr 派生出来的序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [1,2,3,4], difference = 1
    +输出:4
    +解释:最长的等差子序列是 [1,2,3,4]。
    + +

    示例 2:

    + +
    +输入:arr = [1,3,5,7], difference = 1
    +输出:1
    +解释:最长的等差子序列是任意单个元素。
    +
    + +

    示例 3:

    + +
    +输入:arr = [1,5,7,8,5,3,4,2,1], difference = -2
    +输出:4
    +解释:最长的等差子序列是 [7,5,3,1]。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • -104 <= arr[i], difference <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1219.leetcode1219 Path with Maximum Gold-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1219.leetcode1219 Path with Maximum Gold-zh.md" new file mode 100644 index 00000000..813047ce --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1219.leetcode1219 Path with Maximum Gold-zh.md" @@ -0,0 +1,86 @@ +# [1219. 黄金矿工](https://leetcode-cn.com/problems/path-with-maximum-gold) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1219.Path%20with%20Maximum%20Gold/README_EN.md) + +## 题目描述 + + + +

    你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0

    + +

    为了使收益最大化,矿工需要按以下规则来开采黄金:

    + +
      +
    • 每当矿工进入一个单元,就会收集该单元格中的所有黄金。
    • +
    • 矿工每次可以从当前位置向上下左右四个方向走。
    • +
    • 每个单元格只能被开采(进入)一次。
    • +
    • 不得开采(进入)黄金数目为 0 的单元格。
    • +
    • 矿工可以从网格中 任意一个 有黄金的单元格出发或者是停止。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:grid = [[0,6,0],[5,8,7],[0,9,0]]
    +输出:24
    +解释:
    +[[0,6,0],
    + [5,8,7],
    + [0,9,0]]
    +一种收集最多黄金的路线是:9 -> 8 -> 7。
    +
    + +

    示例 2:

    + +
    输入:grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
    +输出:28
    +解释:
    +[[1,0,7],
    + [2,0,6],
    + [3,4,5],
    + [0,3,0],
    + [9,0,20]]
    +一种收集最多黄金的路线是:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length, grid[i].length <= 15
    • +
    • 0 <= grid[i][j] <= 100
    • +
    • 最多 25 个单元格中有黄金。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1220.leetcode1220 Count Vowels Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1220.leetcode1220 Count Vowels Permutation-zh.md" new file mode 100644 index 00000000..9e62c8ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1220.leetcode1220 Count Vowels Permutation-zh.md" @@ -0,0 +1,80 @@ +# [1220. 统计元音字母序列的数目](https://leetcode-cn.com/problems/count-vowels-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1220.Count%20Vowels%20Permutation/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,请你帮忙统计一下我们可以按下述规则形成多少个长度为 n 的字符串:

    + +
      +
    • 字符串中的每个字符都应当是小写元音字母('a', 'e', 'i', 'o', 'u'
    • +
    • 每个元音 'a' 后面都只能跟着 'e'
    • +
    • 每个元音 'e' 后面只能跟着 'a' 或者是 'i'
    • +
    • 每个元音 'i' 后面 不能 再跟着另一个 'i'
    • +
    • 每个元音 'o' 后面只能跟着 'i' 或者是 'u'
    • +
    • 每个元音 'u' 后面只能跟着 'a'
    • +
    + +

    由于答案可能会很大,所以请你返回 模 10^9 + 7 之后的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 1
    +输出:5
    +解释:所有可能的字符串分别是:"a", "e", "i" , "o" 和 "u"。
    +
    + +

    示例 2:

    + +
    输入:n = 2
    +输出:10
    +解释:所有可能的字符串分别是:"ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" 和 "ua"。
    +
    + +

    示例 3:

    + +
    输入:n = 5
    +输出:68
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 2 * 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1221.leetcode1221 Split a String in Balanced Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1221.leetcode1221 Split a String in Balanced Strings-zh.md" new file mode 100644 index 00000000..4fcd3792 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1221.leetcode1221 Split a String in Balanced Strings-zh.md" @@ -0,0 +1,90 @@ +# [1221. 分割平衡字符串](https://leetcode-cn.com/problems/split-a-string-in-balanced-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1221.Split%20a%20String%20in%20Balanced%20Strings/README_EN.md) + +## 题目描述 + + + +

    在一个 平衡字符串 中,'L''R' 字符的数量是相同的。

    + +

    给你一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。

    + +

    注意:分割得到的每个字符串都必须是平衡字符串。

    + +

    返回可以通过分割得到的平衡字符串的 最大数量

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "RLRRLLRLRL"
    +输出:4
    +解释:s 可以分割为 "RL"、"RRLL"、"RL"、"RL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。
    +
    + +

    示例 2:

    + +
    +输入:s = "RLLLLRRRLR"
    +输出:3
    +解释:s 可以分割为 "RL"、"LLLRRR"、"LR" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。
    +
    + +

    示例 3:

    + +
    +输入:s = "LLLLRRRR"
    +输出:1
    +解释:s 只能保持原样 "LLLLRRRR".
    +
    + +

    示例 4:

    + +
    +输入:s = "RLRRRLLRLL"
    +输出:2
    +解释:s 可以分割为 "RL"、"RRRLLRLL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] = 'L' 或 'R'
    • +
    • s 是一个 平衡 字符串
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1222.leetcode1222 Queens That Can Attack the King-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1222.leetcode1222 Queens That Can Attack the King-zh.md" new file mode 100644 index 00000000..658d3bbf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1222.leetcode1222 Queens That Can Attack the King-zh.md" @@ -0,0 +1,95 @@ +# [1222. 可以攻击国王的皇后](https://leetcode-cn.com/problems/queens-that-can-attack-the-king) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1222.Queens%20That%20Can%20Attack%20the%20King/README_EN.md) + +## 题目描述 + + + +

    在一个 8x8 的棋盘上,放置着若干「黑皇后」和一个「白国王」。

    + +

    「黑皇后」在棋盘上的位置分布用整数坐标数组 queens 表示,「白国王」的坐标用数组 king 表示。

    + +

    「黑皇后」的行棋规定是:横、直、斜都可以走,步数不受限制,但是,不能越子行棋。

    + +

    请你返回可以直接攻击到「白国王」的所有「黑皇后」的坐标(任意顺序)。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
    +输出:[[0,1],[1,0],[3,3]]
    +解释: 
    +[0,1] 的皇后可以攻击到国王,因为他们在同一行上。 
    +[1,0] 的皇后可以攻击到国王,因为他们在同一列上。 
    +[3,3] 的皇后可以攻击到国王,因为他们在同一条对角线上。 
    +[0,4] 的皇后无法攻击到国王,因为她被位于 [0,1] 的皇后挡住了。 
    +[4,0] 的皇后无法攻击到国王,因为她被位于 [1,0] 的皇后挡住了。 
    +[2,4] 的皇后无法攻击到国王,因为她和国王不在同一行/列/对角线上。
    +
    + +

    示例 2:

    + +

    + +
    +输入:queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
    +输出:[[2,2],[3,4],[4,4]]
    +
    + +

    示例 3:

    + +

    + +
    +输入:queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]
    +输出:[[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= queens.length <= 63
    • +
    • queens[i].length == 2
    • +
    • 0 <= queens[i][j] < 8
    • +
    • king.length == 2
    • +
    • 0 <= king[0], king[1] < 8
    • +
    • 一个棋盘格上最多只能放置一枚棋子。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1223.leetcode1223 Dice Roll Simulation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1223.leetcode1223 Dice Roll Simulation-zh.md" new file mode 100644 index 00000000..771f7f81 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1223.leetcode1223 Dice Roll Simulation-zh.md" @@ -0,0 +1,77 @@ +# [1223. 掷骰子模拟](https://leetcode-cn.com/problems/dice-roll-simulation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1223.Dice%20Roll%20Simulation/README_EN.md) + +## 题目描述 + + + +

    有一个骰子模拟器会每次投掷的时候生成一个 1 到 6 的随机数。

    + +

    不过我们在使用它时有个约束,就是使得投掷骰子时,连续 掷出数字 i 的次数不能超过 rollMax[i]i 从 1 开始编号)。

    + +

    现在,给你一个整数数组 rollMax 和一个整数 n,请你来计算掷 n 次骰子可得到的不同点数序列的数量。

    + +

    假如两个序列中至少存在一个元素不同,就认为这两个序列是不同的。由于答案可能很大,所以请返回 模 10^9 + 7 之后的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 2, rollMax = [1,1,2,2,2,3]
    +输出:34
    +解释:我们掷 2 次骰子,如果没有约束的话,共有 6 * 6 = 36 种可能的组合。但是根据 rollMax 数组,数字 1 和 2 最多连续出现一次,所以不会出现序列 (1,1) 和 (2,2)。因此,最终答案是 36-2 = 34。
    +
    + +

    示例 2:

    + +
    输入:n = 2, rollMax = [1,1,1,1,1,1]
    +输出:30
    +
    + +

    示例 3:

    + +
    输入:n = 3, rollMax = [1,1,1,2,2,3]
    +输出:181
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 5000
    • +
    • rollMax.length == 6
    • +
    • 1 <= rollMax[i] <= 15
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1224.leetcode1224 Maximum Equal Frequency-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1224.leetcode1224 Maximum Equal Frequency-zh.md" new file mode 100644 index 00000000..7b457ca2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1224.leetcode1224 Maximum Equal Frequency-zh.md" @@ -0,0 +1,82 @@ +# [1224. 最大相等频率](https://leetcode-cn.com/problems/maximum-equal-frequency) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1224.Maximum%20Equal%20Frequency/README_EN.md) + +## 题目描述 + + + +

    给出一个正整数数组 nums,请你帮忙从该数组中找出能满足下面要求的 最长 前缀,并返回其长度:

    + +
      +
    • 从前缀中 删除一个 元素后,使得所剩下的每个数字的出现次数相同。
    • +
    + +

    如果删除这个元素后没有剩余元素存在,仍可认为每个数字都具有相同的出现次数(也就是 0 次)。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [2,2,1,1,5,3,3,5]
    +输出:7
    +解释:对于长度为 7 的子数组 [2,2,1,1,5,3,3],如果我们从中删去 nums[4]=5,就可以得到 [2,2,1,1,3,3],里面每个数字都出现了两次。
    +
    + +

    示例 2:

    + +
    输入:nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
    +输出:13
    +
    + +

    示例 3:

    + +
    输入:nums = [1,1,1,2,2,2]
    +输出:5
    +
    + +

    示例 4:

    + +
    输入:nums = [10,2,8,9,3,8,1,5,2,3,7,6]
    +输出:8
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1225.leetcode1225 Report Contiguous Dates-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1225.leetcode1225 Report Contiguous Dates-zh.md" new file mode 100644 index 00000000..ef9a2ee3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1225.leetcode1225 Report Contiguous Dates-zh.md" @@ -0,0 +1,92 @@ +# [1225. 报告系统状态的连续日期](https://leetcode-cn.com/problems/report-contiguous-dates) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1225.Report%20Contiguous%20Dates/README_EN.md) + +## 题目描述 + + + +

    Table: Failed

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| fail_date    | date    |
    ++--------------+---------+
    +该表主键为 fail_date。
    +该表包含失败任务的天数.
    +
    + +

    Table: Succeeded

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| success_date | date    |
    ++--------------+---------+
    +该表主键为 success_date。
    +该表包含成功任务的天数.
    +
    + +

     

    + +

    系统 每天 运行一个任务。每个任务都独立于先前的任务。任务的状态可以是失败或是成功。

    + +

    编写一个 SQL 查询 2019-01-01 到 2019-12-31 期间任务连续同状态 period_state 的起止日期(start_dateend_date)。即如果任务失败了,就是失败状态的起止日期,如果任务成功了,就是成功状态的起止日期。

    + +

    最后结果按照起始日期 start_date 排序

    + +

    查询结果样例如下所示:

    + +
    Failed table:
    ++-------------------+
    +| fail_date         |
    ++-------------------+
    +| 2018-12-28        |
    +| 2018-12-29        |
    +| 2019-01-04        |
    +| 2019-01-05        |
    ++-------------------+
    +
    +Succeeded table:
    ++-------------------+
    +| success_date      |
    ++-------------------+
    +| 2018-12-30        |
    +| 2018-12-31        |
    +| 2019-01-01        |
    +| 2019-01-02        |
    +| 2019-01-03        |
    +| 2019-01-06        |
    ++-------------------+
    +
    +
    +Result table:
    ++--------------+--------------+--------------+
    +| period_state | start_date   | end_date     |
    ++--------------+--------------+--------------+
    +| succeeded    | 2019-01-01   | 2019-01-03   |
    +| failed       | 2019-01-04   | 2019-01-05   |
    +| succeeded    | 2019-01-06   | 2019-01-06   |
    ++--------------+--------------+--------------+
    +
    +结果忽略了 2018 年的记录,因为我们只关心从 2019-01-01 到 2019-12-31 的记录
    +从 2019-01-01 到 2019-01-03 所有任务成功,系统状态为 "succeeded"。
    +从 2019-01-04 到 2019-01-05 所有任务失败,系统状态为 "failed"。
    +从 2019-01-06 到 2019-01-06 所有任务成功,系统状态为 "succeeded"。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1226.leetcode1226 The Dining Philosophers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1226.leetcode1226 The Dining Philosophers-zh.md" new file mode 100644 index 00000000..dd17d9f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1226.leetcode1226 The Dining Philosophers-zh.md" @@ -0,0 +1,112 @@ +# [1226. 哲学家进餐](https://leetcode-cn.com/problems/the-dining-philosophers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1226.The%20Dining%20Philosophers/README_EN.md) + +## 题目描述 + + + +

    5 个沉默寡言的哲学家围坐在圆桌前,每人面前一盘意面。叉子放在哲学家之间的桌面上。(5 个哲学家,5 根叉子)

    + +

    所有的哲学家都只会在思考和进餐两种行为间交替。哲学家只有同时拿到左边和右边的叉子才能吃到面,而同一根叉子在同一时间只能被一个哲学家使用。每个哲学家吃完面后都需要把叉子放回桌面以供其他哲学家吃面。只要条件允许,哲学家可以拿起左边或者右边的叉子,但在没有同时拿到左右叉子时不能进食。

    + +

    假设面的数量没有限制,哲学家也能随便吃,不需要考虑吃不吃得下。

    + +

    设计一个进餐规则(并行算法)使得每个哲学家都不会挨饿;也就是说,在没有人知道别人什么时候想吃东西或思考的情况下,每个哲学家都可以在吃饭和思考之间一直交替下去。

    + +

    + +

    问题描述和图片来自维基百科 wikipedia.org

    + +

     

    + +

    哲学家从 04顺时针 编号。请实现函数 void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork)

    + +
      +
    • philosopher 哲学家的编号。
    • +
    • pickLeftFork 和 pickRightFork 表示拿起左边或右边的叉子。
    • +
    • eat 表示吃面。
    • +
    • putLeftFork 和 putRightFork 表示放下左边或右边的叉子。
    • +
    • 由于哲学家不是在吃面就是在想着啥时候吃面,所以思考这个方法没有对应的回调。
    • +
    + +

    给你 5 个线程,每个都代表一个哲学家,请你使用类的同一个对象来模拟这个过程。在最后一次调用结束之前,可能会为同一个哲学家多次调用该函数。

    + +

     

    + +

    示例:

    + +
    输入:n = 1
    +输出:[[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]
    +解释:
    +n 表示每个哲学家需要进餐的次数。
    +输出数组描述了叉子的控制和进餐的调用,它的格式如下:
    +output[i] = [a, b, c] (3个整数)
    +- a 哲学家编号。
    +- b 指定叉子:{1 : 左边, 2 : 右边}.
    +- c 指定行为:{1 : 拿起, 2 : 放下, 3 : 吃面}。
    +如 [4,2,1] 表示 4 号哲学家拿起了右边的叉子。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 60
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **C++** + +```cpp +class DiningPhilosophers { +public: + using Act = function; + + void wantsToEat(int philosopher, Act pickLeftFork, Act pickRightFork, Act eat, Act putLeftFork, Act putRightFork) { + /* 这一题实际上是用到了C++17中的scoped_lock知识。 + 作用是传入scoped_lock(mtx1, mtx2)两个锁,然后在作用范围内,依次顺序上锁mtx1和mtx2;然后在作用范围结束时,再反续解锁mtx2和mtx1。 + 从而保证了philosopher1有动作的时候,philosopher2无法操作;但是philosopher3和philosopher4不受影响 */ + std::scoped_lock lock(mutexes_[philosopher], mutexes_[philosopher >= 4 ? 0 : philosopher + 1]); + pickLeftFork(); + pickRightFork(); + eat(); + putLeftFork(); + putRightFork(); + } + +private: + vector mutexes_ = vector(5); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1227.leetcode1227 Airplane Seat Assignment Probability-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1227.leetcode1227 Airplane Seat Assignment Probability-zh.md" new file mode 100644 index 00000000..7c17843c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1227.leetcode1227 Airplane Seat Assignment Probability-zh.md" @@ -0,0 +1,76 @@ +# [1227. 飞机座位分配概率](https://leetcode-cn.com/problems/airplane-seat-assignment-probability) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1227.Airplane%20Seat%20Assignment%20Probability/README_EN.md) + +## 题目描述 + + + +

    n 位乘客即将登机,飞机正好有 n 个座位。第一位乘客的票丢了,他随便选了一个座位坐下。

    + +

    剩下的乘客将会:

    + +
      +
    • +

      如果他们自己的座位还空着,就坐到自己的座位上,

      +
    • +
    • 当他们自己的座位被占用时,随机选择其他座位
    • +
    + +

    n 位乘客坐在自己的座位上的概率是多少?

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 1
    +输出:1.00000
    +解释:第一个人只会坐在自己的位置上。
    + +

    示例 2:

    + +
    +输入: n = 2
    +输出: 0.50000
    +解释:在第一个人选好座位坐下后,第二个人坐在自己的座位上的概率是 0.5。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1228.leetcode1228 Missing Number In Arithmetic Progression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1228.leetcode1228 Missing Number In Arithmetic Progression-zh.md" new file mode 100644 index 00000000..70c12d69 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1228.leetcode1228 Missing Number In Arithmetic Progression-zh.md" @@ -0,0 +1,72 @@ +# [1228. 等差数列中缺失的数字](https://leetcode-cn.com/problems/missing-number-in-arithmetic-progression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1228.Missing%20Number%20In%20Arithmetic%20Progression/README_EN.md) + +## 题目描述 + + + +

    有一个数组,其中的值符合等差数列的数值规律,也就是说:

    + +
      +
    • 在 0 <= i < arr.length - 1 的前提下,arr[i+1] - arr[i] 的值都相等。
    • +
    + +

    我们会从该数组中删除一个 既不是第一个  不是最后一个的值,得到一个新的数组  arr

    + +

    给你这个缺值的数组 arr,请你帮忙找出被删除的那个数。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [5,7,11,13]
    +输出:9
    +解释:原来的数组是 [5,7,9,11,13]。
    +
    + +

    示例 2:

    + +
    输入:arr = [15,13,12]
    +输出:14
    +解释:原来的数组是 [15,14,13,12]。
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= arr.length <= 1000
    • +
    • 0 <= arr[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1229.leetcode1229 Meeting Scheduler-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1229.leetcode1229 Meeting Scheduler-zh.md" new file mode 100644 index 00000000..7c621daf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1229.leetcode1229 Meeting Scheduler-zh.md" @@ -0,0 +1,77 @@ +# [1229. 安排会议日程](https://leetcode-cn.com/problems/meeting-scheduler) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1229.Meeting%20Scheduler/README_EN.md) + +## 题目描述 + + + +

    你是一名行政助理,手里有两位客户的空闲时间表:slots1slots2,以及会议的预计持续时间 duration,请你为他们安排合适的会议时间。

    + +

    「会议时间」是两位客户都有空参加,并且持续时间能够满足预计时间 duration最早的时间间隔

    + +

    如果没有满足要求的会议时间,就请返回一个 空数组

    + +

     

    + +

    「空闲时间」的格式是 [start, end],由开始时间 start 和结束时间 end 组成,表示从 start 开始,到 end 结束。 

    + +

    题目保证数据有效:同一个人的空闲时间不会出现交叠的情况,也就是说,对于同一个人的两个空闲时间 [start1, end1] 和 [start2, end2],要么 start1 > end2,要么 start2 > end1

    + +

     

    + +

    示例 1:

    + +
    输入:slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8
    +输出:[60,68]
    +
    + +

    示例 2:

    + +
    输入:slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= slots1.length, slots2.length <= 10^4
    • +
    • slots1[i].length, slots2[i].length == 2
    • +
    • slots1[i][0] < slots1[i][1]
    • +
    • slots2[i][0] < slots2[i][1]
    • +
    • 0 <= slots1[i][j], slots2[i][j] <= 10^9
    • +
    • 1 <= duration <= 10^6 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1230.leetcode1230 Toss Strange Coins-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1230.leetcode1230 Toss Strange Coins-zh.md" new file mode 100644 index 00000000..9d99a435 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1230.leetcode1230 Toss Strange Coins-zh.md" @@ -0,0 +1,67 @@ +# [1230. 抛掷硬币](https://leetcode-cn.com/problems/toss-strange-coins) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1230.Toss%20Strange%20Coins/README_EN.md) + +## 题目描述 + + + +

    有一些不规则的硬币。在这些硬币中,prob[i] 表示第 i 枚硬币正面朝上的概率。

    + +

    请对每一枚硬币抛掷 一次,然后返回正面朝上的硬币数等于 target 的概率。

    + +

     

    + +

    示例 1:

    + +
    输入:prob = [0.4], target = 1
    +输出:0.40000
    +
    + +

    示例 2:

    + +
    输入:prob = [0.5,0.5,0.5,0.5,0.5], target = 0
    +输出:0.03125
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= prob.length <= 1000
    • +
    • 0 <= prob[i] <= 1
    • +
    • 0 <= target <= prob.length
    • +
    • 如果答案与标准答案的误差在 10^-5 内,则被视为正确答案。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1231.leetcode1231 Divide Chocolate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1231.leetcode1231 Divide Chocolate-zh.md" new file mode 100644 index 00000000..56026451 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1231.leetcode1231 Divide Chocolate-zh.md" @@ -0,0 +1,78 @@ +# [1231. 分享巧克力](https://leetcode-cn.com/problems/divide-chocolate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1231.Divide%20Chocolate/README_EN.md) + +## 题目描述 + + + +

    你有一大块巧克力,它由一些甜度不完全相同的小块组成。我们用数组 sweetness 来表示每一小块的甜度。

    + +

    你打算和 K 名朋友一起分享这块巧克力,所以你需要将切割 K 次才能得到 K+1 块,每一块都由一些 连续 的小块组成。

    + +

    为了表现出你的慷慨,你将会吃掉 总甜度最小 的一块,并将其余几块分给你的朋友们。

    + +

    请找出一个最佳的切割策略,使得你所分得的巧克力 总甜度最大,并返回这个 最大总甜度

    + +

     

    + +

    示例 1:

    + +
    输入:sweetness = [1,2,3,4,5,6,7,8,9], K = 5
    +输出:6
    +解释:你可以把巧克力分成 [1,2,3], [4,5], [6], [7], [8], [9]。
    +
    + +

    示例 2:

    + +
    输入:sweetness = [5,6,7,8,9,1,2,3,4], K = 8
    +输出:1
    +解释:只有一种办法可以把巧克力分成 9 块。
    +
    + +

    示例 3:

    + +
    输入:sweetness = [1,2,2,1,2,2,1,2,2], K = 2
    +输出:5
    +解释:你可以把巧克力分成 [1,2,2], [1,2,2], [1,2,2]。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= K < sweetness.length <= 10^4
    • +
    • 1 <= sweetness[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1232.leetcode1232 Check If It Is a Straight Line-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1232.leetcode1232 Check If It Is a Straight Line-zh.md" new file mode 100644 index 00000000..bfb18dcf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1232.leetcode1232 Check If It Is a Straight Line-zh.md" @@ -0,0 +1,71 @@ +# [1232. 缀点成线](https://leetcode-cn.com/problems/check-if-it-is-a-straight-line) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1232.Check%20If%20It%20Is%20a%20Straight%20Line/README_EN.md) + +## 题目描述 + + + +

    在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。

    + +

    请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
    +输出:true
    +
    + +

    示例 2:

    + +

    + +
    输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= coordinates.length <= 1000
    • +
    • coordinates[i].length == 2
    • +
    • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
    • +
    • coordinates 中不含重复的点
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1233.leetcode1233 Remove Sub-Folders from the Filesystem-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1233.leetcode1233 Remove Sub-Folders from the Filesystem-zh.md" new file mode 100644 index 00000000..36a66f17 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1233.leetcode1233 Remove Sub-Folders from the Filesystem-zh.md" @@ -0,0 +1,88 @@ +# [1233. 删除子文件夹](https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1233.Remove%20Sub-Folders%20from%20the%20Filesystem/README_EN.md) + +## 题目描述 + + + +

    你是一位系统管理员,手里有一份文件夹列表 folder,你的任务是要删除该列表中的所有 子文件夹,并以 任意顺序 返回剩下的文件夹。

    + +

    我们这样定义「子文件夹」:

    + +
      +
    • 如果文件夹 folder[i] 位于另一个文件夹 folder[j] 下,那么 folder[i] 就是 folder[j] 的子文件夹。
    • +
    + +

    文件夹的「路径」是由一个或多个按以下格式串联形成的字符串:

    + +
      +
    • / 后跟一个或者多个小写英文字母。
    • +
    + +

    例如,/leetcode 和 /leetcode/problems 都是有效的路径,而空字符串和 / 不是。

    + +

     

    + +

    示例 1:

    + +
    输入:folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
    +输出:["/a","/c/d","/c/f"]
    +解释:"/a/b/" 是 "/a" 的子文件夹,而 "/c/d/e" 是 "/c/d" 的子文件夹。
    +
    + +

    示例 2:

    + +
    输入:folder = ["/a","/a/b/c","/a/b/d"]
    +输出:["/a"]
    +解释:文件夹 "/a/b/c" 和 "/a/b/d/" 都会被删除,因为它们都是 "/a" 的子文件夹。
    +
    + +

    示例 3:

    + +
    输入:folder = ["/a/b/c","/a/b/d","/a/b/ca"]
    +输出:["/a/b/c","/a/b/ca","/a/b/d"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= folder.length <= 4 * 10^4
    • +
    • 2 <= folder[i].length <= 100
    • +
    • folder[i] 只包含小写字母和 /
    • +
    • folder[i] 总是以字符 / 起始
    • +
    • 每个文件夹名都是唯一的
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1234.leetcode1234 Replace the Substring for Balanced String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1234.leetcode1234 Replace the Substring for Balanced String-zh.md" new file mode 100644 index 00000000..a73d245e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1234.leetcode1234 Replace the Substring for Balanced String-zh.md" @@ -0,0 +1,91 @@ +# [1234. 替换子串得到平衡字符串](https://leetcode-cn.com/problems/replace-the-substring-for-balanced-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1234.Replace%20the%20Substring%20for%20Balanced%20String/README_EN.md) + +## 题目描述 + + + +

    有一个只含有 'Q', 'W', 'E', 'R' 四种字符,且长度为 n 的字符串。

    + +

    假如在该字符串中,这四个字符都恰好出现 n/4 次,那么它就是一个「平衡字符串」。

    + +

     

    + +

    给你一个这样的字符串 s,请通过「替换一个子串」的方式,使原字符串 s 变成一个「平衡字符串」。

    + +

    你可以用和「待替换子串」长度相同的 任何 其他字符串来完成替换。

    + +

    请返回待替换子串的最小可能长度。

    + +

    如果原字符串自身就是一个平衡字符串,则返回 0

    + +

     

    + +

    示例 1:

    + +
    输入:s = "QWER"
    +输出:0
    +解释:s 已经是平衡的了。
    + +

    示例 2:

    + +
    输入:s = "QQWE"
    +输出:1
    +解释:我们需要把一个 'Q' 替换成 'R',这样得到的 "RQWE" (或 "QRWE") 是平衡的。
    +
    + +

    示例 3:

    + +
    输入:s = "QQQW"
    +输出:2
    +解释:我们可以把前面的 "QQ" 替换成 "ER"。 
    +
    + +

    示例 4:

    + +
    输入:s = "QQQQ"
    +输出:3
    +解释:我们可以替换后 3 个 'Q',使 s = "QWER"。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s.length 是 4 的倍数
    • +
    • s 中只含有 'Q', 'W', 'E''R' 四种字符
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1235.leetcode1235 Maximum Profit in Job Scheduling-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1235.leetcode1235 Maximum Profit in Job Scheduling-zh.md" new file mode 100644 index 00000000..cadd3633 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1235.leetcode1235 Maximum Profit in Job Scheduling-zh.md" @@ -0,0 +1,90 @@ +# [1235. 规划兼职工作](https://leetcode-cn.com/problems/maximum-profit-in-job-scheduling) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README_EN.md) + +## 题目描述 + + + +

    你打算利用空闲时间来做兼职工作赚些零花钱。

    + +

    这里有 n 份兼职工作,每份工作预计从 startTime[i] 开始到 endTime[i] 结束,报酬为 profit[i]

    + +

    给你一份兼职工作表,包含开始时间 startTime,结束时间 endTime 和预计报酬 profit 三个数组,请你计算并返回可以获得的最大报酬。

    + +

    注意,时间上出现重叠的 2 份工作不能同时进行。

    + +

    如果你选择的工作在时间 X 结束,那么你可以立刻进行在时间 X 开始的下一份工作。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
    +输出:120
    +解释:
    +我们选出第 1 份和第 4 份工作, 
    +时间范围是 [1-3]+[3-6],共获得报酬 120 = 50 + 70。
    +
    + +

    示例 2:

    + +

    + +
    输入:startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
    +输出:150
    +解释:
    +我们选择第 1,4,5 份工作。 
    +共获得报酬 150 = 20 + 70 + 60。
    +
    + +

    示例 3:

    + +

    + +
    输入:startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= startTime.length == endTime.length == profit.length <= 5 * 10^4
    • +
    • 1 <= startTime[i] < endTime[i] <= 10^9
    • +
    • 1 <= profit[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1236.leetcode1236 Web Crawler-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1236.leetcode1236 Web Crawler-zh.md" new file mode 100644 index 00000000..144f548c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1236.leetcode1236 Web Crawler-zh.md" @@ -0,0 +1,116 @@ +# [1236. 网络爬虫](https://leetcode-cn.com/problems/web-crawler) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1236.Web%20Crawler/README_EN.md) + +## 题目描述 + + + +

    给定一个链接 startUrl 和一个接口 HtmlParser ,请你实现一个网络爬虫,以实现爬取同 startUrl 拥有相同 域名标签 的全部链接。该爬虫得到的全部链接可以 任何顺序 返回结果。

    + +

    你的网络爬虫应当按照如下模式工作:

    + +
      +
    • 自链接 startUrl 开始爬取
    • +
    • 调用 HtmlParser.getUrls(url) 来获得链接url页面中的全部链接
    • +
    • 同一个链接最多只爬取一次
    • +
    • 只输出 域名  startUrl 相同 的链接集合
    • +
    + +

    + +

    如上所示的一个链接,其域名为 example.org。简单起见,你可以假设所有的链接都采用 http协议 并没有指定 端口。例如,链接 http://leetcode.com/problems 和 http://leetcode.com/contest 是同一个域名下的,而链接http://example.org/test 和 http://example.com/abc 是不在同一域名下的。

    + +

    HtmlParser 接口定义如下: 

    + +
    interface HtmlParser {
    +  // 返回给定 url 对应的页面中的全部 url 。
    +  public List<String> getUrls(String url);
    +}
    + +

    下面是两个实例,用以解释该问题的设计功能,对于自定义测试,你可以使用三个变量  urlsedges 和 startUrl。注意在代码实现中,你只可以访问 startUrl ,而 urls 和 edges 不可以在你的代码中被直接访问。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com",
    +  "http://news.yahoo.com/us"
    +]
    +edges = [[2,0],[2,1],[3,2],[3,1],[0,4]]
    +startUrl = "http://news.yahoo.com/news/topics/"
    +输出:[
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.yahoo.com/us"
    +]
    +
    + +

    示例 2:

    + +

    + +
    输入:
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com"
    +]
    +edges = [[0,2],[2,1],[3,2],[3,1],[3,0]]
    +startUrl = "http://news.google.com"
    +输入:["http://news.google.com"]
    +解释:startUrl 链接到所有其他不共享相同主机名的页面。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= urls.length <= 1000
    • +
    • 1 <= urls[i].length <= 300
    • +
    • startUrl 为 urls 中的一个。
    • +
    • 域名标签的长为1到63个字符(包括点),只能包含从‘a’到‘z’的ASCII字母、‘0’到‘9’的数字以及连字符即减号(‘-’)。
    • +
    • 域名标签不会以连字符即减号(‘-’)开头或结尾。
    • +
    • 关于域名有效性的约束可参考:  https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
    • +
    • 你可以假定url库中不包含重复项。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1237.leetcode1237 Find Positive Integer Solution for a Given Equation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1237.leetcode1237 Find Positive Integer Solution for a Given Equation-zh.md" new file mode 100644 index 00000000..4208d94d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1237.leetcode1237 Find Positive Integer Solution for a Given Equation-zh.md" @@ -0,0 +1,227 @@ +# [1237. 找出给定方程的正整数解](https://leetcode-cn.com/problems/find-positive-integer-solution-for-a-given-equation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1237.Find%20Positive%20Integer%20Solution%20for%20a%20Given%20Equation/README_EN.md) + +## 题目描述 + + + +

    给你一个函数  f(x, y) 和一个目标结果 z,函数公式未知,请你计算方程 f(x,y) == z 所有可能的正整数 数对 xy。满足条件的结果数对可以按任意顺序返回。

    + +

    尽管函数的具体式子未知,但它是单调递增函数,也就是说:

    + +
      +
    • f(x, y) < f(x + 1, y)
    • +
    • f(x, y) < f(x, y + 1)
    • +
    + +

    函数接口定义如下:

    + +
    +interface CustomFunction {
    +public:
    +  // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
    +  int f(int x, int y);
    +};
    + +

    你的解决方案将按如下规则进行评判:

    + +
      +
    • 判题程序有一个由 CustomFunction9 种实现组成的列表,以及一种为特定的 z 生成所有有效数对的答案的方法。
    • +
    • 判题程序接受两个输入:function_id(决定使用哪种实现测试你的代码)以及目标结果 z
    • +
    • 判题程序将会调用你实现的 findSolution 并将你的结果与答案进行比较。
    • +
    • 如果你的结果与答案相符,那么解决方案将被视作正确答案,即 Accepted
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:function_id = 1, z = 5
    +输出:[[1,4],[2,3],[3,2],[4,1]]
    +解释:function_id = 1 暗含的函数式子为 f(x, y) = x + y
    +以下 x 和 y 满足 f(x, y) 等于 5:
    +x=1, y=4 -> f(1, 4) = 1 + 4 = 5
    +x=2, y=3 -> f(2, 3) = 2 + 3 = 5
    +x=3, y=2 -> f(3, 2) = 3 + 2 = 5
    +x=4, y=1 -> f(4, 1) = 4 + 1 = 5
    +
    + +

    示例 2:

    + +
    +输入:function_id = 2, z = 5
    +输出:[[1,5],[5,1]]
    +解释:function_id = 2 暗含的函数式子为 f(x, y) = x * y
    +以下 x 和 y 满足 f(x, y) 等于 5:
    +x=1, y=5 -> f(1, 5) = 1 * 5 = 5
    +x=5, y=1 -> f(5, 1) = 5 * 1 = 5
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= function_id <= 9
    • +
    • 1 <= z <= 100
    • +
    • 题目保证 f(x, y) == z 的解处于 1 <= x, y <= 1000 的范围内。
    • +
    • 1 <= x, y <= 1000 的前提下,题目保证 f(x, y) 是一个 32 位有符号整数。
    • +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +""" + This is the custom function interface. + You should not implement it, or speculate about its implementation + class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): + +""" + +class Solution: + def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: + res = [] + for x in range(1, 1001): + left, right = 1, 1000 + while left < right: + mid = (left + right) >> 1 + if customfunction.f(x, mid) >= z: + right = mid + else: + left = mid + 1 + if customfunction.f(x, left) == z: + res.append([x, left]) + return res +``` + +### **Java** + + + +```java +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * public int f(int x, int y); + * }; + */ + +class Solution { + public List> findSolution(CustomFunction customfunction, int z) { + List> res = new ArrayList<>(); + for (int i = 1; i <= 1000; ++i) { + int left = 1, right = 1000; + while (left < right) { + int mid = (left + right) >> 1; + if (customfunction.f(i, mid) >= z) { + right = mid; + } else { + left = mid + 1; + } + } + if (customfunction.f(i, left) == z) { + res.add(Arrays.asList(i, left)); + } + } + return res; + } +} +``` + +### **C++** + +```cpp +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * public: + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * int f(int x, int y); + * }; + */ + +class Solution { +public: + vector> findSolution(CustomFunction& customfunction, int z) { + vector> res; + for (int i = 1; i <= 1000; ++i) { + int left = 1, right = 1000; + while (left < right) { + int mid = left + right >> 1; + if (customfunction.f(i, mid) >= z) { + right = mid; + } else { + left = mid + 1; + } + } + if (customfunction.f(i, left) == z) { + res.push_back({i, left}); + } + } + return res; + } +}; +``` + +### **Go** + +```go +/** + * This is the declaration of customFunction API. + * @param x int + * @param x int + * @return Returns f(x, y) for any given positive integers x and y. + * Note that f(x, y) is increasing with respect to both x and y. + * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + */ + +func findSolution(customFunction func(int, int) int, z int) [][]int { + res := [][]int{} + for i := 1; i <= 1000; i++ { + left, right := 1, 1000 + for left < right { + mid := (left + right) >> 1 + if customFunction(i, mid) >= z { + right = mid + } else { + left = mid + 1 + } + } + if customFunction(i, left) == z { + res = append(res, []int{i, left}) + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1238.leetcode1238 Circular Permutation in Binary Representation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1238.leetcode1238 Circular Permutation in Binary Representation-zh.md" new file mode 100644 index 00000000..144396ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1238.leetcode1238 Circular Permutation in Binary Representation-zh.md" @@ -0,0 +1,72 @@ +# [1238. 循环码排列](https://leetcode-cn.com/problems/circular-permutation-in-binary-representation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1238.Circular%20Permutation%20in%20Binary%20Representation/README_EN.md) + +## 题目描述 + + + +

    给你两个整数 nstart。你的任务是返回任意 (0,1,2,,...,2^n-1) 的排列 p,并且满足:

    + +
      +
    • p[0] = start
    • +
    • p[i]p[i+1] 的二进制表示形式只有一位不同
    • +
    • p[0]p[2^n -1] 的二进制表示形式也只有一位不同
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:n = 2, start = 3
    +输出:[3,2,0,1]
    +解释:这个排列的二进制表示是 (11,10,00,01)
    +     所有的相邻元素都有一位是不同的,另一个有效的排列是 [3,1,0,2]
    +
    + +

    示例 2:

    + +
    输出:n = 3, start = 2
    +输出:[2,6,7,5,4,0,1,3]
    +解释:这个排列的二进制表示是 (010,110,111,101,100,000,001,011)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 16
    • +
    • 0 <= start < 2^n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1239.leetcode1239 Maximum Length of a Concatenated String with Unique Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1239.leetcode1239 Maximum Length of a Concatenated String with Unique Characters-zh.md" new file mode 100644 index 00000000..4605bbab --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1239.leetcode1239 Maximum Length of a Concatenated String with Unique Characters-zh.md" @@ -0,0 +1,166 @@ +# [1239. 串联字符串的最大长度](https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1239.Maximum%20Length%20of%20a%20Concatenated%20String%20with%20Unique%20Characters/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串数组 arr,字符串 s 是将 arr 某一子序列字符串连接所得的字符串,如果 s 中的每一个字符都只出现过一次,那么它就是一个可行解。

    + +

    请返回所有可行解 s 中最长长度。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = ["un","iq","ue"]
    +输出:4
    +解释:所有可能的串联组合是 "","un","iq","ue","uniq" 和 "ique",最大长度为 4。
    +
    + +

    示例 2:

    + +
    输入:arr = ["cha","r","act","ers"]
    +输出:6
    +解释:可能的解答有 "chaers" 和 "acters"。
    +
    + +

    示例 3:

    + +
    输入:arr = ["abcdefghijklmnopqrstuvwxyz"]
    +输出:26
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 16
    • +
    • 1 <= arr[i].length <= 26
    • +
    • arr[i] 中只含有小写英文字母
    • +
    + +## 解法 + + + +状态压缩,用一个 32 位数记录字母的出现情况,`masks` 存储之前枚举的字符串。 + + + +### **Python3** + + + +```python +class Solution: + def maxLength(self, arr: List[str]) -> int: + def ones_count(x): + c = 0 + while x: + x &= x - 1 + c += 1 + return c + + ans = 0 + masks = [0] + for s in arr: + mask = 0 + for ch in s: + ch = ord(ch) - ord('a') + if (mask >> ch) & 1 == 1: + mask = 0 + break + mask |= 1 << ch + if mask == 0: + continue + for m in masks: + if m & mask == 0: + masks.append(m | mask) + ans = max(ans, ones_count(m | mask)) + + return ans +``` + +### **Java** + + + +```java +class Solution { + public int maxLength(List arr) { + int ans = 0; + List masks = new ArrayList<>(); + masks.add(0); + + loop: + for (String s : arr) { + int mask = 0; + for (char ch : s.toCharArray()) { + ch -= 'a'; + if (((mask >> ch) & 1) == 1) { + continue loop; + } + mask |= 1 << ch; + } + int n = masks.size(); + for (int i = 0; i < n; i++) { + int m = masks.get(i); + if ((m & mask) == 0) { + masks.add(m | mask); + ans = Math.max(ans, Integer.bitCount(m | mask)); + } + } + } + + return ans; + } +} +``` + +### **Go** + +```go +func maxLength(arr []string) int { + + max := func(x, y int) int { + if x > y { + return x + } + return y + } + + ans := 0 + masks := []int{0} + +loop: + for _, s := range arr { + mask := 0 + for _, ch := range s { + ch -= 'a' + if (mask>>ch)&1 == 1 { + continue loop + } + mask |= 1 << ch + } + for _, m := range masks { + if m&mask == 0 { + masks = append(masks, m|mask) + ans = max(ans, bits.OnesCount(uint(m|mask))) + } + } + } + + return ans +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1240.leetcode1240 Tiling a Rectangle with the Fewest Squares-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1240.leetcode1240 Tiling a Rectangle with the Fewest Squares-zh.md" new file mode 100644 index 00000000..38d5dba3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1240.leetcode1240 Tiling a Rectangle with the Fewest Squares-zh.md" @@ -0,0 +1,83 @@ +# [1240. 铺瓷砖](https://leetcode-cn.com/problems/tiling-a-rectangle-with-the-fewest-squares) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1240.Tiling%20a%20Rectangle%20with%20the%20Fewest%20Squares/README_EN.md) + +## 题目描述 + + + +

    你是一位施工队的工长,根据设计师的要求准备为一套设计风格独特的房子进行室内装修。

    + +

    房子的客厅大小为 n x m,为保持极简的风格,需要使用尽可能少的 正方形 瓷砖来铺盖地面。

    + +

    假设正方形瓷砖的规格不限,边长都是整数。

    + +

    请你帮设计师计算一下,最少需要用到多少块方形瓷砖?

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 2, m = 3
    +输出:3
    +解释:3 块地砖就可以铺满卧室。
    +     21x1 地砖
    +     12x2 地砖
    + +

    示例 2:

    + +

    + +
    输入:n = 5, m = 8
    +输出:5
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 11, m = 13
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 13
    • +
    • 1 <= m <= 13
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1241.leetcode1241 Number of Comments per Post-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1241.leetcode1241 Number of Comments per Post-zh.md" new file mode 100644 index 00000000..7d826059 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1241.leetcode1241 Number of Comments per Post-zh.md" @@ -0,0 +1,82 @@ +# [1241. 每个帖子的评论数](https://leetcode-cn.com/problems/number-of-comments-per-post) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1241.Number%20of%20Comments%20per%20Post/README_EN.md) + +## 题目描述 + + + +

    表 Submissions 结构如下:

    + +
    ++---------------+----------+
    +| 列名           | 类型     |
    ++---------------+----------+
    +| sub_id        | int      |
    +| parent_id     | int      |
    ++---------------+----------+
    +上表没有主键, 所以可能会出现重复的行。
    +每行可以是一个帖子或对该帖子的评论。
    +如果是帖子的话,parent_id 就是 null。
    +对于评论来说,parent_id 就是表中对应帖子的 sub_id。
    +
    + +

     

    + +

    编写 SQL 语句以查找每个帖子的评论数。

    + +

    结果表应包含帖子的 post_id 和对应的评论数 number_of_comments 并且按 post_id 升序排列。

    + +

    Submissions 可能包含重复的评论。您应该计算每个帖子的唯一评论数。

    + +

    Submissions 可能包含重复的帖子。您应该将它们视为一个帖子。

    + +

    查询结果格式如下例所示:

    + +
    +Submissions table:
    ++---------+------------+
    +| sub_id  | parent_id  |
    ++---------+------------+
    +| 1       | Null       |
    +| 2       | Null       |
    +| 1       | Null       |
    +| 12      | Null       |
    +| 3       | 1          |
    +| 5       | 2          |
    +| 3       | 1          |
    +| 4       | 1          |
    +| 9       | 1          |
    +| 10      | 2          |
    +| 6       | 7          |
    ++---------+------------+
    +
    +结果表:
    ++---------+--------------------+
    +| post_id | number_of_comments |
    ++---------+--------------------+
    +| 1       | 3                  |
    +| 2       | 2                  |
    +| 12      | 0                  |
    ++---------+--------------------+
    +
    +表中 ID 为 1 的帖子有 ID 为 3、4 和 9 的三个评论。表中 ID 为 3 的评论重复出现了,所以我们只对它进行了一次计数。
    +表中 ID 为 2 的帖子有 ID 为 5 和 10 的两个评论。
    +ID 为 12 的帖子在表中没有评论。
    +表中 ID 为 6 的评论是对 ID 为 7 的已删除帖子的评论,因此我们将其忽略。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1242.leetcode1242 Web Crawler Multithreaded-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1242.leetcode1242 Web Crawler Multithreaded-zh.md" new file mode 100644 index 00000000..c5e7f036 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1242.leetcode1242 Web Crawler Multithreaded-zh.md" @@ -0,0 +1,134 @@ +# [1242. 多线程网页爬虫](https://leetcode-cn.com/problems/web-crawler-multithreaded) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1242.Web%20Crawler%20Multithreaded/README_EN.md) + +## 题目描述 + + + +

    给你一个初始地址 startUrl 和一个 HTML 解析器接口 HtmlParser,请你实现一个 多线程的网页爬虫,用于获取与 startUrl 有 相同主机名 的所有链接。 

    + +

    以 任意 顺序返回爬虫获取的路径。

    + +

    爬虫应该遵循:

    + +
      +
    • 从 startUrl 开始
    • +
    • 调用 HtmlParser.getUrls(url) 从指定网页路径获得的所有路径。
    • +
    • 不要抓取相同的链接两次。
    • +
    • 仅浏览与 startUrl 相同主机名 的链接。
    • +
    + +

    + +

    如上图所示,主机名是 example.org 。简单起见,你可以假设所有链接都采用 http 协议,并且没有指定 端口号。举个例子,链接 http://leetcode.com/problems 和链接 http://leetcode.com/contest 属于同一个 主机名, 而 http://example.org/test 与 http://example.com/abc 并不属于同一个 主机名

    + +

    HtmlParser 的接口定义如下:

    + +
    +interface HtmlParser {
    +  // Return a list of all urls from a webpage of given url.
    +  // This is a blocking call, that means it will do HTTP request and return when this request is finished.
    +  public List<String> getUrls(String url);
    +}
    + +

    注意一点,getUrls(String url) 模拟执行一个HTTP的请求。 你可以将它当做一个阻塞式的方法,直到请求结束。 getUrls(String url) 保证会在 15ms 内返回所有的路径。 单线程的方案会超过时间限制,你能用多线程方案做的更好吗?

    + +

    对于问题所需的功能,下面提供了两个例子。为了方便自定义测试,你可以声明三个变量 urlsedges 和 startUrl。但要注意你只能在代码中访问 startUrl,并不能直接访问 urls 和 edges

    + +

     

    + +

    拓展问题:

    + +
      +
    1. 假设我们要要抓取 10000 个节点和 10 亿个路径。并且在每个节点部署相同的的软件。软件可以发现所有的节点。我们必须尽可能减少机器之间的通讯,并确保每个节点负载均衡。你将如何设计这个网页爬虫?
    2. +
    3. 如果有一个节点发生故障不工作该怎么办?
    4. +
    5. 如何确认爬虫任务已经完成?
    6. +
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com",
    +  "http://news.yahoo.com/us"
    +]
    +edges = [[2,0],[2,1],[3,2],[3,1],[0,4]]
    +startUrl = "http://news.yahoo.com/news/topics/"
    +输出:[
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.yahoo.com/us"
    +]
    +
    + +

    示例 2:

    + +

    + +
    +输入:
    +urls = [
    +  "http://news.yahoo.com",
    +  "http://news.yahoo.com/news",
    +  "http://news.yahoo.com/news/topics/",
    +  "http://news.google.com"
    +]
    +edges = [[0,2],[2,1],[3,2],[3,1],[3,0]]
    +startUrl = "http://news.google.com"
    +输出:["http://news.google.com"]
    +解释:startUrl 链接与其他页面不共享一个主机名。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= urls.length <= 1000
    • +
    • 1 <= urls[i].length <= 300
    • +
    • startUrl 是 urls 中的一个。
    • +
    • 主机名的长度必须为 1 到 63 个字符(包括点 . 在内),只能包含从 “a” 到 “z” 的 ASCII 字母和 “0” 到 “9” 的数字,以及中划线 “-”。
    • +
    • 主机名开头和结尾不能是中划线 “-”。
    • +
    • 参考资料:https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
    • +
    • 你可以假设路径都是不重复的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1243.leetcode1243 Array Transformation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1243.leetcode1243 Array Transformation-zh.md" new file mode 100644 index 00000000..bf1f22b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1243.leetcode1243 Array Transformation-zh.md" @@ -0,0 +1,118 @@ +# [1243. 数组变换](https://leetcode-cn.com/problems/array-transformation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1243.Array%20Transformation/README_EN.md) + +## 题目描述 + + + +

    首先,给你一个初始数组 arr。然后,每天你都要根据前一天的数组生成一个新的数组。

    + +

    第 i 天所生成的数组,是由你对第 i-1 天的数组进行如下操作所得的:

    + +
      +
    1. 假如一个元素小于它的左右邻居,那么该元素自增 1
    2. +
    3. 假如一个元素大于它的左右邻居,那么该元素自减 1
    4. +
    5. 首、尾元素 永不 改变。
    6. +
    + +

    过些时日,你会发现数组将会不再发生变化,请返回最终所得到的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:[6,2,3,4]
    +输出:[6,3,3,4]
    +解释:
    +第一天,数组从 [6,2,3,4] 变为 [6,3,3,4]。
    +无法再对该数组进行更多操作。
    +
    + +

    示例 2:

    + +
    输入:[1,6,3,4,3,5]
    +输出:[1,4,4,4,4,5]
    +解释:
    +第一天,数组从 [1,6,3,4,3,5] 变为 [1,5,4,3,4,5]。
    +第二天,数组从 [1,5,4,3,4,5] 变为 [1,4,4,4,4,5]。
    +无法再对该数组进行更多操作。
    +
    + +

     

    + +

    提示:

    + +
      +
    1. 1 <= arr.length <= 100
    2. +
    3. 1 <= arr[i] <= 100
    4. +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def transformArray(self, arr: List[int]) -> List[int]: + copy = [e for e in arr] + has_change, n = True, len(arr) + while has_change: + has_change = False + for i in range(1, n - 1): + if arr[i] < copy[i - 1] and arr[i] < copy[i + 1]: + arr[i] += 1 + has_change = True + elif arr[i] > copy[i - 1] and arr[i] > copy[i + 1]: + arr[i] -= 1 + has_change = True + copy = [e for e in arr] + return arr +``` + +### **Java** + + + +```java +class Solution { + public List transformArray(int[] arr) { + int n = arr.length; + int[] copy = Arrays.copyOf(arr, n); + boolean hasChange = true; + while (hasChange) { + hasChange = false; + for (int i = 1; i < n - 1; ++i) { + if (arr[i] < copy[i - 1] && arr[i] < copy[i + 1]) { + ++arr[i]; + hasChange = true; + } else if (arr[i] > copy[i - 1] && arr[i] > copy[i + 1]) { + --arr[i]; + hasChange = true; + } + } + System.arraycopy(arr, 0, copy, 0, n); + } + List res = new ArrayList<>(); + for (int e : arr) { + res.add(e); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1244.leetcode1244 Design A Leaderboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1244.leetcode1244 Design A Leaderboard-zh.md" new file mode 100644 index 00000000..a5d8c62f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1244.leetcode1244 Design A Leaderboard-zh.md" @@ -0,0 +1,146 @@ +# [1244. 力扣排行榜](https://leetcode-cn.com/problems/design-a-leaderboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1244.Design%20A%20Leaderboard/README_EN.md) + +## 题目描述 + + + +

    新一轮的「力扣杯」编程大赛即将启动,为了动态显示参赛者的得分数据,需要设计一个排行榜 Leaderboard。

    + +

    请你帮忙来设计这个 Leaderboard 类,使得它有如下 3 个函数:

    + +
      +
    1. addScore(playerId, score): +
        +
      • 假如参赛者已经在排行榜上,就给他的当前得分增加 score 点分值并更新排行。
      • +
      • 假如该参赛者不在排行榜上,就把他添加到榜单上,并且将分数设置为 score
      • +
      +
    2. +
    3. top(K):返回前 K 名参赛者的 得分总和
    4. +
    5. reset(playerId):将指定参赛者的成绩清零(换句话说,将其从排行榜中删除)。题目保证在调用此函数前,该参赛者已有成绩,并且在榜单上。
    6. +
    + +

    请注意,在初始状态下,排行榜是空的。

    + +

     

    + +

    示例 1:

    + +
    +输入: 
    +["Leaderboard","addScore","addScore","addScore","addScore","addScore","top","reset","reset","addScore","top"]
    +[[],[1,73],[2,56],[3,39],[4,51],[5,4],[1],[1],[2],[2,51],[3]]
    +输出:
    +[null,null,null,null,null,null,73,null,null,null,141]
    +
    +解释: 
    +Leaderboard leaderboard = new Leaderboard ();
    +leaderboard.addScore(1,73);   // leaderboard = [[1,73]];
    +leaderboard.addScore(2,56);   // leaderboard = [[1,73],[2,56]];
    +leaderboard.addScore(3,39);   // leaderboard = [[1,73],[2,56],[3,39]];
    +leaderboard.addScore(4,51);   // leaderboard = [[1,73],[2,56],[3,39],[4,51]];
    +leaderboard.addScore(5,4);    // leaderboard = [[1,73],[2,56],[3,39],[4,51],[5,4]];
    +leaderboard.top(1);           // returns 73;
    +leaderboard.reset(1);         // leaderboard = [[2,56],[3,39],[4,51],[5,4]];
    +leaderboard.reset(2);         // leaderboard = [[3,39],[4,51],[5,4]];
    +leaderboard.addScore(2,51);   // leaderboard = [[2,51],[3,39],[4,51],[5,4]];
    +leaderboard.top(3);           // returns 141 = 51 + 51 + 39;
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= playerId, K <= 10000
    • +
    • 题目保证 K 小于或等于当前参赛者的数量
    • +
    • 1 <= score <= 100
    • +
    • 最多进行 1000 次函数调用
    • +
    + +## 解法 + + + +用哈希表存放每个 playerId 所对应的分数。 + +计算 topK 时,取出所有的分数,进行排序,获取前 K 个分数,累加得到结果。 + + + +### **Python3** + + + +```python +class Leaderboard: + + def __init__(self): + self.player_scores = {} + + def addScore(self, playerId: int, score: int) -> None: + self.player_scores[playerId] = self.player_scores.get(playerId, 0) + score + + def top(self, K: int) -> int: + scores = sorted(list(self.player_scores.values()), reverse=True) + return sum(scores[:K]) + + def reset(self, playerId: int) -> None: + self.player_scores[playerId] = 0 + + +# Your Leaderboard object will be instantiated and called as such: +# obj = Leaderboard() +# obj.addScore(playerId,score) +# param_2 = obj.top(K) +# obj.reset(playerId) +``` + +### **Java** + + + +```java +class Leaderboard { + private Map playerScores; + + public Leaderboard() { + playerScores = new HashMap<>(); + } + + public void addScore(int playerId, int score) { + playerScores.put(playerId, playerScores.getOrDefault(playerId, 0) + score); + } + + public int top(int K) { + List scores = new ArrayList<>(playerScores.values()); + Collections.sort(scores, Collections.reverseOrder()); + int res = 0; + for (int i = 0; i < K; ++i) { + res += scores.get(i); + } + return res; + } + + public void reset(int playerId) { + playerScores.put(playerId, 0); + } +} + +/** + * Your Leaderboard object will be instantiated and called as such: + * Leaderboard obj = new Leaderboard(); + * obj.addScore(playerId,score); + * int param_2 = obj.top(K); + * obj.reset(playerId); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1245.leetcode1245 Tree Diameter-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1245.leetcode1245 Tree Diameter-zh.md" new file mode 100644 index 00000000..fbe4477e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1245.leetcode1245 Tree Diameter-zh.md" @@ -0,0 +1,77 @@ +# [1245. 树的直径](https://leetcode-cn.com/problems/tree-diameter) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1245.Tree%20Diameter/README_EN.md) + +## 题目描述 + + + +

    给你这棵「无向树」,请你测算并返回它的「直径」:这棵树上最长简单路径的 边数

    + +

    我们用一个由所有「边」组成的数组 edges 来表示一棵无向树,其中 edges[i] = [u, v] 表示节点 uv 之间的双向边。

    + +

    树上的节点都已经用 {0, 1, ..., edges.length} 中的数做了标记,每个节点上的标记都是独一无二的。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:edges = [[0,1],[0,2]]
    +输出:2
    +解释:
    +这棵树上最长的路径是 1 - 0 - 2,边数为 2。
    +
    + +

    示例 2:

    + +

    + +
    输入:edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
    +输出:4
    +解释: 
    +这棵树上最长的路径是 3 - 2 - 1 - 4 - 5,边数为 4。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= edges.length < 10^4
    • +
    • edges[i][0] != edges[i][1]
    • +
    • 0 <= edges[i][j] <= edges.length
    • +
    • edges 会形成一棵无向树
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1246.leetcode1246 Palindrome Removal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1246.leetcode1246 Palindrome Removal-zh.md" new file mode 100644 index 00000000..aa8d7928 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1246.leetcode1246 Palindrome Removal-zh.md" @@ -0,0 +1,68 @@ +# [1246. 删除回文子数组](https://leetcode-cn.com/problems/palindrome-removal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1246.Palindrome%20Removal/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr,每一次操作你都可以选择并删除它的一个 回文 子数组 arr[i], arr[i+1], ..., arr[j]i <= j)。

    + +

    注意,每当你删除掉一个子数组,右侧元素都会自行向前移动填补空位。

    + +

    请你计算并返回从数组中删除所有数字所需的最少操作次数。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2]
    +输出:2
    +
    + +

    示例 2:

    + +
    输入:arr = [1,3,4,1,5]
    +输出:3
    +解释:先删除 [4],然后删除 [1,3,1],最后再删除 [5]。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1247.leetcode1247 Minimum Swaps to Make Strings Equal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1247.leetcode1247 Minimum Swaps to Make Strings Equal-zh.md" new file mode 100644 index 00000000..0628193e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1247.leetcode1247 Minimum Swaps to Make Strings Equal-zh.md" @@ -0,0 +1,85 @@ +# [1247. 交换字符使得字符串相同](https://leetcode-cn.com/problems/minimum-swaps-to-make-strings-equal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1247.Minimum%20Swaps%20to%20Make%20Strings%20Equal/README_EN.md) + +## 题目描述 + + + +

    有两个长度相同的字符串 s1 和 s2,且它们其中 只含有 字符 "x" 和 "y",你需要通过「交换字符」的方式使这两个字符串相同。

    + +

    每次「交换字符」的时候,你都可以在两个字符串中各选一个字符进行交换。

    + +

    交换只能发生在两个不同的字符串之间,绝对不能发生在同一个字符串内部。也就是说,我们可以交换 s1[i] 和 s2[j],但不能交换 s1[i] 和 s1[j]

    + +

    最后,请你返回使 s1s2 相同的最小交换次数,如果没有方法能够使得这两个字符串相同,则返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:s1 = "xx", s2 = "yy"
    +输出:1
    +解释:
    +交换 s1[0] 和 s2[1],得到 s1 = "yx",s2 = "yx"。
    + +

    示例 2:

    + +
    输入:s1 = "xy", s2 = "yx"
    +输出:2
    +解释:
    +交换 s1[0] 和 s2[0],得到 s1 = "yy",s2 = "xx" 。
    +交换 s1[0] 和 s2[1],得到 s1 = "xy",s2 = "xy" 。
    +注意,你不能交换 s1[0] 和 s1[1] 使得 s1 变成 "yx",因为我们只能交换属于两个不同字符串的字符。
    + +

    示例 3:

    + +
    输入:s1 = "xx", s2 = "xy"
    +输出:-1
    +
    + +

    示例 4:

    + +
    输入:s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s1.length, s2.length <= 1000
    • +
    • s1, s2 只包含 'x' 或 'y'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1248.leetcode1248 Count Number of Nice Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1248.leetcode1248 Count Number of Nice Subarrays-zh.md" new file mode 100644 index 00000000..84d1526c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1248.leetcode1248 Count Number of Nice Subarrays-zh.md" @@ -0,0 +1,76 @@ +# [1248. 统计「优美子数组」](https://leetcode-cn.com/problems/count-number-of-nice-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1248.Count%20Number%20of%20Nice%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 k

    + +

    如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。

    + +

    请返回这个数组中「优美子数组」的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,1,2,1,1], k = 3
    +输出:2
    +解释:包含 3 个奇数的子数组是 [1,1,2,1] 和 [1,2,1,1] 。
    +
    + +

    示例 2:

    + +
    输入:nums = [2,4,6], k = 1
    +输出:0
    +解释:数列中不包含任何奇数,所以不存在优美子数组。
    +
    + +

    示例 3:

    + +
    输入:nums = [2,2,2,1,2,2,1,2,2,2], k = 2
    +输出:16
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 50000
    • +
    • 1 <= nums[i] <= 10^5
    • +
    • 1 <= k <= nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1249.leetcode1249 Minimum Remove to Make Valid Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1249.leetcode1249 Minimum Remove to Make Valid Parentheses-zh.md" new file mode 100644 index 00000000..3d0c4270 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1249.leetcode1249 Minimum Remove to Make Valid Parentheses-zh.md" @@ -0,0 +1,89 @@ +# [1249. 移除无效的括号](https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1249.Minimum%20Remove%20to%20Make%20Valid%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    给你一个由 '('')' 和小写字母组成的字符串 s

    + +

    你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。

    + +

    请返回任意一个合法字符串。

    + +

    有效「括号字符串」应当符合以下 任意一条 要求:

    + +
      +
    • 空字符串或只包含小写字母的字符串
    • +
    • 可以被写作 ABA 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
    • +
    • 可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:s = "lee(t(c)o)de)"
    +输出:"lee(t(c)o)de"
    +解释:"lee(t(co)de)" , "lee(t(c)ode)" 也是一个可行答案。
    +
    + +

    示例 2:

    + +
    输入:s = "a)b(c)d"
    +输出:"ab(c)d"
    +
    + +

    示例 3:

    + +
    输入:s = "))(("
    +输出:""
    +解释:空字符串也是有效的
    +
    + +

    示例 4:

    + +
    输入:s = "(a(b(c)d)"
    +输出:"a(b(c)d)"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s[i] 可能是 '('')' 或英文小写字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1250.leetcode1250 Check If It Is a Good Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1250.leetcode1250 Check If It Is a Good Array-zh.md" new file mode 100644 index 00000000..6df4989f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1250.leetcode1250 Check If It Is a Good Array-zh.md" @@ -0,0 +1,75 @@ +# [1250. 检查「好数组」](https://leetcode-cn.com/problems/check-if-it-is-a-good-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1250.Check%20If%20It%20Is%20a%20Good%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 nums,你需要从中任选一些子集,然后将子集中每一个数乘以一个 任意整数,并求出他们的和。

    + +

    假如该和结果为 1,那么原数组就是一个「好数组」,则返回 True;否则请返回 False

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [12,5,7,23]
    +输出:true
    +解释:挑选数字 5 和 7。
    +5*3 + 7*(-2) = 1
    +
    + +

    示例 2:

    + +
    输入:nums = [29,6,10]
    +输出:true
    +解释:挑选数字 29, 6 和 10。
    +29*1 + 6*(-3) + 10*(-1) = 1
    +
    + +

    示例 3:

    + +
    输入:nums = [3,6]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1251.leetcode1251 Average Selling Price-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1251.leetcode1251 Average Selling Price-zh.md" new file mode 100644 index 00000000..c156fa9d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1251.leetcode1251 Average Selling Price-zh.md" @@ -0,0 +1,90 @@ +# [1251. 平均售价](https://leetcode-cn.com/problems/average-selling-price) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1251.Average%20Selling%20Price/README_EN.md) + +## 题目描述 + + + +

    Table: Prices

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| start_date    | date    |
    +| end_date      | date    |
    +| price         | int     |
    ++---------------+---------+
    +(product_id,start_date,end_date) 是 Prices 表的主键。
    +Prices 表的每一行表示的是某个产品在一段时期内的价格。
    +每个产品的对应时间段是不会重叠的,这也意味着同一个产品的价格时段不会出现交叉。
    + +

     

    + +

    Table: UnitsSold

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| purchase_date | date    |
    +| units         | int     |
    ++---------------+---------+
    +UnitsSold 表没有主键,它可能包含重复项。
    +UnitsSold 表的每一行表示的是每种产品的出售日期,单位和产品 id。
    + +

     

    + +

    编写SQL查询以查找每种产品的平均售价。
    +average_price 应该四舍五入到小数点后两位。
    +查询结果格式如下例所示:

    + +
    +Prices table:
    ++------------+------------+------------+--------+
    +| product_id | start_date | end_date   | price  |
    ++------------+------------+------------+--------+
    +| 1          | 2019-02-17 | 2019-02-28 | 5      |
    +| 1          | 2019-03-01 | 2019-03-22 | 20     |
    +| 2          | 2019-02-01 | 2019-02-20 | 15     |
    +| 2          | 2019-02-21 | 2019-03-31 | 30     |
    ++------------+------------+------------+--------+
    + 
    +UnitsSold table:
    ++------------+---------------+-------+
    +| product_id | purchase_date | units |
    ++------------+---------------+-------+
    +| 1          | 2019-02-25    | 100   |
    +| 1          | 2019-03-01    | 15    |
    +| 2          | 2019-02-10    | 200   |
    +| 2          | 2019-03-22    | 30    |
    ++------------+---------------+-------+
    +
    +Result table:
    ++------------+---------------+
    +| product_id | average_price |
    ++------------+---------------+
    +| 1          | 6.96          |
    +| 2          | 16.96         |
    ++------------+---------------+
    +平均售价 = 产品总价 / 销售的产品数量。
    +产品 1 的平均售价 = ((100 * 5)+(15 * 20) )/ 115 = 6.96
    +产品 2 的平均售价 = ((200 * 15)+(30 * 30) )/ 230 = 16.96
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1252.leetcode1252 Cells with Odd Values in a Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1252.leetcode1252 Cells with Odd Values in a Matrix-zh.md" new file mode 100644 index 00000000..e3b831ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1252.leetcode1252 Cells with Odd Values in a Matrix-zh.md" @@ -0,0 +1,90 @@ +# [1252. 奇数值单元格的数目](https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1252.Cells%20with%20Odd%20Values%20in%20a%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的矩阵,最开始的时候,每个单元格中的值都是 0

    + +

    另有一个二维索引数组 indicesindices[i] = [ri, ci] 指向矩阵中的某个位置,其中 rici 分别表示指定的行和列(0 开始编号)。

    + +

    indices[i] 所指向的每个位置,应同时执行下述增量操作:

    + +
      +
    1. ri 行上的所有单元格,加 1
    2. +
    3. ci 列上的所有单元格,加 1
    4. +
    + +

    给你 mnindices 。请你在执行完所有 indices 指定的增量操作后,返回矩阵中 奇数值单元格 的数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:m = 2, n = 3, indices = [[0,1],[1,1]]
    +输出:6
    +解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。
    +第一次增量操作后得到 [[1,2,1],[0,1,0]]。
    +最后的矩阵是 [[1,3,1],[1,3,1]],里面有 6 个奇数。
    +
    + +

    示例 2:

    + +

    + +
    +输入:m = 2, n = 2, indices = [[1,1],[0,0]]
    +输出:0
    +解释:最后的矩阵是 [[2,2],[2,2]],里面没有奇数。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m, n <= 50
    • +
    • 1 <= indices.length <= 100
    • +
    • 0 <= ri < m
    • +
    • 0 <= ci < n
    • +
    + +

     

    + +

    进阶:你可以设计一个时间复杂度为 O(n + m + indices.length) 且仅用 O(n + m) 额外空间的算法来解决此问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1253.leetcode1253 Reconstruct a 2-Row Binary Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1253.leetcode1253 Reconstruct a 2-Row Binary Matrix-zh.md" new file mode 100644 index 00000000..312c90d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1253.leetcode1253 Reconstruct a 2-Row Binary Matrix-zh.md" @@ -0,0 +1,84 @@ +# [1253. 重构 2 行二进制矩阵](https://leetcode-cn.com/problems/reconstruct-a-2-row-binary-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1253.Reconstruct%20a%202-Row%20Binary%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 2 行 n 列的二进制数组:

    + +
      +
    • 矩阵是一个二进制矩阵,这意味着矩阵中的每个元素不是 0 就是 1
    • +
    • 0 行的元素之和为 upper
    • +
    • 1 行的元素之和为 lower
    • +
    • i 列(从 0 开始编号)的元素之和为 colsum[i]colsum 是一个长度为 n 的整数数组。
    • +
    + +

    你需要利用 upperlower 和 colsum 来重构这个矩阵,并以二维整数数组的形式返回它。

    + +

    如果有多个不同的答案,那么任意一个都可以通过本题。

    + +

    如果不存在符合要求的答案,就请返回一个空的二维数组。

    + +

     

    + +

    示例 1:

    + +
    输入:upper = 2, lower = 1, colsum = [1,1,1]
    +输出:[[1,1,0],[0,0,1]]
    +解释:[[1,0,1],[0,1,0]] 和 [[0,1,1],[1,0,0]] 也是正确答案。
    +
    + +

    示例 2:

    + +
    输入:upper = 2, lower = 3, colsum = [2,2,1,1]
    +输出:[]
    +
    + +

    示例 3:

    + +
    输入:upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
    +输出:[[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= colsum.length <= 10^5
    • +
    • 0 <= upper, lower <= colsum.length
    • +
    • 0 <= colsum[i] <= 2
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1254.leetcode1254 Number of Closed Islands-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1254.leetcode1254 Number of Closed Islands-zh.md" new file mode 100644 index 00000000..fba11689 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1254.leetcode1254 Number of Closed Islands-zh.md" @@ -0,0 +1,86 @@ +# [1254. 统计封闭岛屿的数目](https://leetcode-cn.com/problems/number-of-closed-islands) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1254.Number%20of%20Closed%20Islands/README_EN.md) + +## 题目描述 + + + +

    有一个二维矩阵 grid ,每个位置要么是陆地(记号为 0 )要么是水域(记号为 1 )。

    + +

    我们从一块陆地出发,每次可以往上下左右 4 个方向相邻区域走,能走到的所有陆地区域,我们将其称为一座「岛屿」。

    + +

    如果一座岛屿 完全 由水域包围,即陆地边缘上下左右所有相邻区域都是水域,那么我们将其称为 「封闭岛屿」。

    + +

    请返回封闭岛屿的数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
    +输出:2
    +解释:
    +灰色区域的岛屿是封闭岛屿,因为这座岛屿完全被水域包围(即被 1 区域包围)。
    + +

    示例 2:

    + +

    + +
    输入:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
    +输出:1
    +
    + +

    示例 3:

    + +
    输入:grid = [[1,1,1,1,1,1,1],
    +             [1,0,0,0,0,0,1],
    +             [1,0,1,1,1,0,1],
    +             [1,0,1,0,1,0,1],
    +             [1,0,1,1,1,0,1],
    +             [1,0,0,0,0,0,1],
    +             [1,1,1,1,1,1,1]]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length, grid[0].length <= 100
    • +
    • 0 <= grid[i][j] <=1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1255.leetcode1255 Maximum Score Words Formed by Letters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1255.leetcode1255 Maximum Score Words Formed by Letters-zh.md" new file mode 100644 index 00000000..d6c9ba1c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1255.leetcode1255 Maximum Score Words Formed by Letters-zh.md" @@ -0,0 +1,93 @@ +# [1255. 得分最高的单词集合](https://leetcode-cn.com/problems/maximum-score-words-formed-by-letters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1255.Maximum%20Score%20Words%20Formed%20by%20Letters/README_EN.md) + +## 题目描述 + + + +

    你将会得到一份单词表 words,一个字母表 letters (可能会有重复字母),以及每个字母对应的得分情况表 score

    + +

    请你帮忙计算玩家在单词拼写游戏中所能获得的「最高得分」:能够由 letters 里的字母拼写出的 任意 属于 words 单词子集中,分数最高的单词集合的得分。

    + +

    单词拼写游戏的规则概述如下:

    + +
      +
    • 玩家需要用字母表 letters 里的字母来拼写单词表 words 中的单词。
    • +
    • 可以只使用字母表 letters 中的部分字母,但是每个字母最多被使用一次。
    • +
    • 单词表 words 中每个单词只能计分(使用)一次。
    • +
    • 根据字母得分情况表score,字母 'a''b''c', ... , 'z' 对应的得分分别为 score[0], score[1], ..., score[25]
    • +
    • 本场游戏的「得分」是指:玩家所拼写出的单词集合里包含的所有字母的得分之和。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
    +输出:23
    +解释:
    +字母得分为  a=1, c=9, d=5, g=3, o=2
    +使用给定的字母表 letters,我们可以拼写单词 "dad" (5+1+5)和 "good" (3+2+2+5),得分为 23 。
    +而单词 "dad" 和 "dog" 只能得到 21 分。
    + +

    示例 2:

    + +
    输入:words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
    +输出:27
    +解释:
    +字母得分为  a=4, b=4, c=4, x=5, z=10
    +使用给定的字母表 letters,我们可以组成单词 "ax" (4+5), "bx" (4+5) 和 "cx" (4+5) ,总得分为 27 。
    +单词 "xxxz" 的得分仅为 25 。
    + +

    示例 3:

    + +
    输入:words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
    +输出:0
    +解释:
    +字母 "e" 在字母表 letters 中只出现了一次,所以无法组成单词表 words 中的单词。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 14
    • +
    • 1 <= words[i].length <= 15
    • +
    • 1 <= letters.length <= 100
    • +
    • letters[i].length == 1
    • +
    • score.length == 26
    • +
    • 0 <= score[i] <= 10
    • +
    • words[i] 和 letters[i] 只包含小写的英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1256.leetcode1256 Encode Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1256.leetcode1256 Encode Number-zh.md" new file mode 100644 index 00000000..9da64d37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1256.leetcode1256 Encode Number-zh.md" @@ -0,0 +1,66 @@ +# [1256. 加密数字](https://leetcode-cn.com/problems/encode-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1256.Encode%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个非负整数 num ,返回它的「加密字符串」。

    + +

    加密的过程是把一个整数用某个未知函数进行转化,你需要从下表推测出该转化函数:

    + +

    + +

     

    + +

    示例 1:

    + +
    输入:num = 23
    +输出:"1000"
    +
    + +

    示例 2:

    + +
    输入:num = 107
    +输出:"101100"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= num <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1257.leetcode1257 Smallest Common Region-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1257.leetcode1257 Smallest Common Region-zh.md" new file mode 100644 index 00000000..4b8b3cf0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1257.leetcode1257 Smallest Common Region-zh.md" @@ -0,0 +1,74 @@ +# [1257. 最小公共区域](https://leetcode-cn.com/problems/smallest-common-region) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1257.Smallest%20Common%20Region/README_EN.md) + +## 题目描述 + + + +

    给你一些区域列表 regions ,每个列表的第一个区域都包含这个列表内所有其他区域。

    + +

    很自然地,如果区域 X 包含区域 Y ,那么区域 X  比区域 Y 大。

    + +

    给定两个区域 region1 和 region2 ,找到同时包含这两个区域的 最小 区域。

    + +

    如果区域列表中 r1 包含 r2 和 r3 ,那么数据保证 r2 不会包含 r3 。

    + +

    数据同样保证最小公共区域一定存在。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +regions = [["Earth","North America","South America"],
    +["North America","United States","Canada"],
    +["United States","New York","Boston"],
    +["Canada","Ontario","Quebec"],
    +["South America","Brazil"]],
    +region1 = "Quebec",
    +region2 = "New York"
    +输出:"North America"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= regions.length <= 10^4
    • +
    • region1 != region2
    • +
    • 所有字符串只包含英文字母和空格,且最多只有 20 个字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1258.leetcode1258 Synonymous Sentences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1258.leetcode1258 Synonymous Sentences-zh.md" new file mode 100644 index 00000000..186d70a3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1258.leetcode1258 Synonymous Sentences-zh.md" @@ -0,0 +1,71 @@ +# [1258. 近义词句子](https://leetcode-cn.com/problems/synonymous-sentences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1258.Synonymous%20Sentences/README_EN.md) + +## 题目描述 + + + +

    给你一个近义词表 synonyms 和一个句子 text , synonyms 表中是一些近义词对 ,你可以将句子 text 中每个单词用它的近义词来替换。

    + +

    请你找出所有用近义词替换后的句子,按 字典序排序 后返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],
    +text = "I am happy today but was sad yesterday"
    +输出:
    +["I am cheerful today but was sad yesterday",
    +"I am cheerful today but was sorrow yesterday",
    +"I am happy today but was sad yesterday",
    +"I am happy today but was sorrow yesterday",
    +"I am joy today but was sad yesterday",
    +"I am joy today but was sorrow yesterday"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= synonyms.length <= 10
    • +
    • synonyms[i].length == 2
    • +
    • synonyms[0] != synonyms[1]
    • +
    • 所有单词仅包含英文字母,且长度最多为 10
    • +
    • text 最多包含 10 个单词,且单词间用单个空格分隔开。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1259.leetcode1259 Handshakes That Don't Cross-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1259.leetcode1259 Handshakes That Don't Cross-zh.md" new file mode 100644 index 00000000..c8af00fe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1259.leetcode1259 Handshakes That Don't Cross-zh.md" @@ -0,0 +1,84 @@ +# [1259. 不相交的握手](https://leetcode-cn.com/problems/handshakes-that-dont-cross) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1259.Handshakes%20That%20Don%27t%20Cross/README_EN.md) + +## 题目描述 + + + +

    偶数 个人站成一个圆,总人数为 num_people 。每个人与除自己外的一个人握手,所以总共会有 num_people / 2 次握手。

    + +

    将握手的人之间连线,请你返回连线不会相交的握手方案数。

    + +

    由于结果可能会很大,请你返回答案  10^9+7 后的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:num_people = 2
    +输出:1
    +
    + +

    示例 2:

    + +

    + +
    输入:num_people = 4
    +输出:2
    +解释:总共有两种方案,第一种方案是 [(1,2),(3,4)] ,第二种方案是 [(2,3),(4,1)] 。
    +
    + +

    示例 3:

    + +

    + +
    输入:num_people = 6
    +输出:5
    +
    + +

    示例 4:

    + +
    输入:num_people = 8
    +输出:14
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= num_people <= 1000
    • +
    • num_people % 2 == 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1260.leetcode1260 Shift 2D Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1260.leetcode1260 Shift 2D Grid-zh.md" new file mode 100644 index 00000000..463e713b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1260.leetcode1260 Shift 2D Grid-zh.md" @@ -0,0 +1,90 @@ +# [1260. 二维网格迁移](https://leetcode-cn.com/problems/shift-2d-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1260.Shift%202D%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个 mn 列的二维网格 grid 和一个整数 k。你需要将 grid 迁移 k 次。

    + +

    每次「迁移」操作将会引发下述活动:

    + +
      +
    • 位于 grid[i][j] 的元素将会移动到 grid[i][j + 1]
    • +
    • 位于 grid[i][n - 1] 的元素将会移动到 grid[i + 1][0]
    • +
    • 位于 grid[m - 1][n - 1] 的元素将会移动到 grid[0][0]
    • +
    + +

    请你返回 k 次迁移操作后最终得到的 二维网格

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
    +输出:[[9,1,2],[3,4,5],[6,7,8]]
    +
    + +

    示例 2:

    + +

    + +
    +输入:grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
    +输出:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]
    +
    + +

    示例 3:

    + +
    +输入:grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
    +输出:[[1,2,3],[4,5,6],[7,8,9]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 50
    • +
    • 1 <= n <= 50
    • +
    • -1000 <= grid[i][j] <= 1000
    • +
    • 0 <= k <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1261.leetcode1261 Find Elements in a Contaminated Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1261.leetcode1261 Find Elements in a Contaminated Binary Tree-zh.md" new file mode 100644 index 00000000..76f62d7d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1261.leetcode1261 Find Elements in a Contaminated Binary Tree-zh.md" @@ -0,0 +1,115 @@ +# [1261. 在受污染的二叉树中查找元素](https://leetcode-cn.com/problems/find-elements-in-a-contaminated-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1261.Find%20Elements%20in%20a%20Contaminated%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给出一个满足下述规则的二叉树:

    + +
      +
    1. root.val == 0
    2. +
    3. 如果 treeNode.val == x 且 treeNode.left != null,那么 treeNode.left.val == 2 * x + 1
    4. +
    5. 如果 treeNode.val == xtreeNode.right != null,那么 treeNode.right.val == 2 * x + 2
    6. +
    + +

    现在这个二叉树受到「污染」,所有的 treeNode.val 都变成了 -1

    + +

    请你先还原二叉树,然后实现 FindElements 类:

    + +
      +
    • FindElements(TreeNode* root) 用受污染的二叉树初始化对象,你需要先把它还原。
    • +
    • bool find(int target) 判断目标值 target 是否存在于还原后的二叉树中并返回结果。
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    输入:
    +["FindElements","find","find"]
    +[[[-1,null,-1]],[1],[2]]
    +输出:
    +[null,false,true]
    +解释:
    +FindElements findElements = new FindElements([-1,null,-1]); 
    +findElements.find(1); // return False 
    +findElements.find(2); // return True 
    + +

    示例 2:

    + +

    + +
    输入:
    +["FindElements","find","find","find"]
    +[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
    +输出:
    +[null,true,true,false]
    +解释:
    +FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
    +findElements.find(1); // return True
    +findElements.find(3); // return True
    +findElements.find(5); // return False
    + +

    示例 3:

    + +

    + +
    输入:
    +["FindElements","find","find","find","find"]
    +[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
    +输出:
    +[null,true,false,false,true]
    +解释:
    +FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
    +findElements.find(2); // return True
    +findElements.find(3); // return False
    +findElements.find(4); // return False
    +findElements.find(5); // return True
    +
    + +

     

    + +

    提示:

    + +
      +
    • TreeNode.val == -1
    • +
    • 二叉树的高度不超过 20
    • +
    • 节点的总数在 [1, 10^4] 之间
    • +
    • 调用 find() 的总次数在 [1, 10^4] 之间
    • +
    • 0 <= target <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1262.leetcode1262 Greatest Sum Divisible by Three-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1262.leetcode1262 Greatest Sum Divisible by Three-zh.md" new file mode 100644 index 00000000..e8f4f1ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1262.leetcode1262 Greatest Sum Divisible by Three-zh.md" @@ -0,0 +1,74 @@ +# [1262. 可被三整除的最大和](https://leetcode-cn.com/problems/greatest-sum-divisible-by-three) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1262.Greatest%20Sum%20Divisible%20by%20Three/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,请你找出并返回能被三整除的元素最大和。

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    输入:nums = [3,6,5,1,8]
    +输出:18
    +解释:选出数字 3, 6, 1 和 8,它们的和是 18(可被 3 整除的最大和)。
    + +

    示例 2:

    + +
    输入:nums = [4]
    +输出:0
    +解释:4 不能被 3 整除,所以无法选出数字,返回 0。
    +
    + +

    示例 3:

    + +
    输入:nums = [1,2,3,4,4]
    +输出:12
    +解释:选出数字 1, 3, 4 以及 4,它们的和是 12(可被 3 整除的最大和)。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 4 * 10^4
    • +
    • 1 <= nums[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1263.leetcode1263 Minimum Moves to Move a Box to Their Target Location-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1263.leetcode1263 Minimum Moves to Move a Box to Their Target Location-zh.md" new file mode 100644 index 00000000..9d87c912 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1263.leetcode1263 Minimum Moves to Move a Box to Their Target Location-zh.md" @@ -0,0 +1,112 @@ +# [1263. 推箱子](https://leetcode-cn.com/problems/minimum-moves-to-move-a-box-to-their-target-location) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1263.Minimum%20Moves%20to%20Move%20a%20Box%20to%20Their%20Target%20Location/README_EN.md) + +## 题目描述 + + + +

    「推箱子」是一款风靡全球的益智小游戏,玩家需要将箱子推到仓库中的目标位置。

    + +

    游戏地图用大小为 n * m 的网格 grid 表示,其中每个元素可以是墙、地板或者是箱子。

    + +

    现在你将作为玩家参与游戏,按规则将箱子 'B' 移动到目标位置 'T'

    + +
      +
    • 玩家用字符 'S' 表示,只要他在地板上,就可以在网格中向上、下、左、右四个方向移动。
    • +
    • 地板用字符 '.' 表示,意味着可以自由行走。
    • +
    • 墙用字符 '#' 表示,意味着障碍物,不能通行。 
    • +
    • 箱子仅有一个,用字符 'B' 表示。相应地,网格上有一个目标位置 'T'
    • +
    • 玩家需要站在箱子旁边,然后沿着箱子的方向进行移动,此时箱子会被移动到相邻的地板单元格。记作一次「推动」。
    • +
    • 玩家无法越过箱子。
    • +
    + +

    返回将箱子推到目标位置的最小 推动 次数,如果无法做到,请返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [["#","#","#","#","#","#"],
    +             ["#","T","#","#","#","#"],
    +             ["#",".",".","B",".","#"],
    +             ["#",".","#","#",".","#"],
    +             ["#",".",".",".","S","#"],
    +             ["#","#","#","#","#","#"]]
    +输出:3
    +解释:我们只需要返回推箱子的次数。
    + +

    示例 2:

    + +
    输入:grid = [["#","#","#","#","#","#"],
    +             ["#","T","#","#","#","#"],
    +             ["#",".",".","B",".","#"],
    +             ["#","#","#","#",".","#"],
    +             ["#",".",".",".","S","#"],
    +             ["#","#","#","#","#","#"]]
    +输出:-1
    +
    + +

    示例 3:

    + +
    输入:grid = [["#","#","#","#","#","#"],
    +             ["#","T",".",".","#","#"],
    +             ["#",".","#","B",".","#"],
    +             ["#",".",".",".",".","#"],
    +             ["#",".",".",".","S","#"],
    +             ["#","#","#","#","#","#"]]
    +输出:5
    +解释:向下、向左、向左、向上再向上。
    +
    + +

    示例 4:

    + +
    输入:grid = [["#","#","#","#","#","#","#"],
    +             ["#","S","#",".","B","T","#"],
    +             ["#","#","#","#","#","#","#"]]
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length <= 20
    • +
    • 1 <= grid[i].length <= 20
    • +
    • grid 仅包含字符 '.', '#''S' , 'T', 以及 'B'
    • +
    • grid 中 'S', 'B' 和 'T' 各只能出现一个。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1264.leetcode1264 Page Recommendations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1264.leetcode1264 Page Recommendations-zh.md" new file mode 100644 index 00000000..85d5fd33 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1264.leetcode1264 Page Recommendations-zh.md" @@ -0,0 +1,103 @@ +# [1264. 页面推荐](https://leetcode-cn.com/problems/page-recommendations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1264.Page%20Recommendations/README_EN.md) + +## 题目描述 + + + +

    朋友关系列表: Friendship

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user1_id      | int     |
    +| user2_id      | int     |
    ++---------------+---------+
    +这张表的主键是 (user1_id, user2_id)。
    +这张表的每一行代表着 user1_id 和 user2_id 之间存在着朋友关系。
    +
    + +

     

    + +

    喜欢列表: Likes

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| page_id     | int     |
    ++-------------+---------+
    +这张表的主键是 (user_id, page_id)。
    +这张表的每一行代表着 user_id 喜欢 page_id。
    +
    + +

     

    + +

    写一段 SQL  向user_id = 1 的用户,推荐其朋友们喜欢的页面。不要推荐该用户已经喜欢的页面。

    + +

    你返回的结果中不应当包含重复项。

    + +

    返回结果的格式如下例所示:

    + +
    +Friendship table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    +| 1        | 3        |
    +| 1        | 4        |
    +| 2        | 3        |
    +| 2        | 4        |
    +| 2        | 5        |
    +| 6        | 1        |
    ++----------+----------+
    + 
    +Likes table:
    ++---------+---------+
    +| user_id | page_id |
    ++---------+---------+
    +| 1       | 88      |
    +| 2       | 23      |
    +| 3       | 24      |
    +| 4       | 56      |
    +| 5       | 11      |
    +| 6       | 33      |
    +| 2       | 77      |
    +| 3       | 77      |
    +| 6       | 88      |
    ++---------+---------+
    +
    +Result table:
    ++------------------+
    +| recommended_page |
    ++------------------+
    +| 23               |
    +| 24               |
    +| 56               |
    +| 33               |
    +| 77               |
    ++------------------+
    +用户1 同 用户2, 3, 4, 6 是朋友关系。
    +推荐页面为: 页面23 来自于 用户2, 页面24 来自于 用户3, 页面56 来自于 用户3 以及 页面33 来自于 用户6。
    +页面77 同时被 用户2 和 用户3 推荐。
    +页面88 没有被推荐,因为 用户1 已经喜欢了它。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1265.leetcode1265 Print Immutable Linked List in Reverse-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1265.leetcode1265 Print Immutable Linked List in Reverse-zh.md" new file mode 100644 index 00000000..57e45cac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1265.leetcode1265 Print Immutable Linked List in Reverse-zh.md" @@ -0,0 +1,177 @@ +# [1265. 逆序打印不可变链表](https://leetcode-cn.com/problems/print-immutable-linked-list-in-reverse) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1265.Print%20Immutable%20Linked%20List%20in%20Reverse/README_EN.md) + +## 题目描述 + + + +

    给您一个不可变的链表,使用下列接口逆序打印每个节点的值:

    + +
      +
    • ImmutableListNode: 描述不可变链表的接口,链表的头节点已给出。
    • +
    + +

    您需要使用以下函数来访问此链表(您 不能 直接访问 ImmutableListNode):

    + +
      +
    • ImmutableListNode.printValue():打印当前节点的值。
    • +
    • ImmutableListNode.getNext():返回下一个节点。
    • +
    + +

    输入只用来内部初始化链表。您不可以通过修改链表解决问题。也就是说,您只能通过上述 API 来操作链表。

    + +

     

    + +

    进阶:

    + +

    您是否可以:

    + +
      +
    • 使用常数级空间复杂度解决问题?
    • +
    • 使用线性级时间复杂度和低于线性级空间复杂度解决问题?
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4]
    +输出:[4,3,2,1]
    +
    + +

    示例 2:

    + +
    +输入:head = [0,-4,-1,3,-5]
    +输出:[-5,3,-1,-4,0]
    +
    + +

    示例 3:

    + +
    +输入:head = [-2,0,6,4,4,-6]
    +输出:[-6,4,4,6,0,-2]
    +
    + +
      +
    + +

     

    + +

    提示:

    + +
      +
    • 链表的长度在 [1, 1000] 之间。
    • +
    • 每个节点的值在 [-1000, 1000] 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# """ +# This is the ImmutableListNode's API interface. +# You should not implement it, or speculate about its implementation. +# """ +# class ImmutableListNode: +# def printValue(self) -> None: # print the value of this node. +# def getNext(self) -> 'ImmutableListNode': # return the next node. + +class Solution: + def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None: + if head: + self.printLinkedListInReverse(head.getNext()) + head.printValue() +``` + +### **Java** + + + +```java +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * interface ImmutableListNode { + * public void printValue(); // print the value of this node. + * public ImmutableListNode getNext(); // return the next node. + * }; + */ + +class Solution { + public void printLinkedListInReverse(ImmutableListNode head) { + if (head != null) { + printLinkedListInReverse(head.getNext()); + head.printValue(); + } + } +} +``` + +### **C++** + +```cpp +/** + * // This is the ImmutableListNode's API interface. + * // You should not implement it, or speculate about its implementation. + * class ImmutableListNode { + * public: + * void printValue(); // print the value of the node. + * ImmutableListNode* getNext(); // return the next node. + * }; + */ + +class Solution { +public: + void printLinkedListInReverse(ImmutableListNode* head) { + if (head) { + printLinkedListInReverse(head->getNext()); + head->printValue(); + } + } +}; +``` + +### **Go** + +```go +/* Below is the interface for ImmutableListNode, which is already defined for you. + * + * type ImmutableListNode struct { + * + * } + * + * func (this *ImmutableListNode) getNext() ImmutableListNode { + * // return the next node. + * } + * + * func (this *ImmutableListNode) printValue() { + * // print the value of this node. + * } + */ + +func printLinkedListInReverse(head ImmutableListNode) { + if head != nil { + printLinkedListInReverse(head.getNext()) + head.printValue() + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1266.leetcode1266 Minimum Time Visiting All Points-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1266.leetcode1266 Minimum Time Visiting All Points-zh.md" new file mode 100644 index 00000000..b388c14a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1266.leetcode1266 Minimum Time Visiting All Points-zh.md" @@ -0,0 +1,86 @@ +# [1266. 访问所有点的最小时间](https://leetcode-cn.com/problems/minimum-time-visiting-all-points) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1266.Minimum%20Time%20Visiting%20All%20Points/README_EN.md) + +## 题目描述 + + + +

    平面上有 n 个点,点的位置用整数坐标表示 points[i] = [xi, yi] 。请你计算访问所有这些点需要的 最小时间(以秒为单位)。

    + +

    你需要按照下面的规则在平面上移动:

    + +
      +
    • 每一秒内,你可以: +
        +
      • 沿水平方向移动一个单位长度,或者
      • +
      • 沿竖直方向移动一个单位长度,或者
      • +
      • 跨过对角线移动 sqrt(2) 个单位长度(可以看作在一秒内向水平和竖直方向各移动一个单位长度)。
      • +
      +
    • +
    • 必须按照数组中出现的顺序来访问这些点。
    • +
    • 在访问某个点时,可以经过该点后面出现的点,但经过的那些点不算作有效访问。
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:points = [[1,1],[3,4],[-1,0]]
    +输出:7
    +解释:一条最佳的访问路径是: [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]   
    +从 [1,1] 到 [3,4] 需要 3 秒 
    +从 [3,4] 到 [-1,0] 需要 4 秒
    +一共需要 7 秒
    + +

    示例 2:

    + +
    +输入:points = [[3,2],[-2,2]]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • points.length == n
    • +
    • 1 <= n <= 100
    • +
    • points[i].length == 2
    • +
    • -1000 <= points[i][0], points[i][1] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1267.leetcode1267 Count Servers that Communicate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1267.leetcode1267 Count Servers that Communicate-zh.md" new file mode 100644 index 00000000..5dbea9cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1267.leetcode1267 Count Servers that Communicate-zh.md" @@ -0,0 +1,84 @@ +# [1267. 统计参与通信的服务器](https://leetcode-cn.com/problems/count-servers-that-communicate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1267.Count%20Servers%20that%20Communicate/README_EN.md) + +## 题目描述 + + + +

    这里有一幅服务器分布图,服务器的位置标识在 m * n 的整数矩阵网格 grid 中,1 表示单元格上有服务器,0 表示没有。

    + +

    如果两台服务器位于同一行或者同一列,我们就认为它们之间可以进行通信。

    + +

    请你统计并返回能够与至少一台其他服务器进行通信的服务器的数量。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[1,0],[0,1]]
    +输出:0
    +解释:没有一台服务器能与其他服务器进行通信。
    + +

    示例 2:

    + +

    + +
    输入:grid = [[1,0],[1,1]]
    +输出:3
    +解释:所有这些服务器都至少可以与一台别的服务器进行通信。
    +
    + +

    示例 3:

    + +

    + +
    输入:grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
    +输出:4
    +解释:第一行的两台服务器互相通信,第三列的两台服务器互相通信,但右下角的服务器无法与其他服务器通信。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 250
    • +
    • 1 <= n <= 250
    • +
    • grid[i][j] == 0 or 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1268.leetcode1268 Search Suggestions System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1268.leetcode1268 Search Suggestions System-zh.md" new file mode 100644 index 00000000..cdcdd120 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1268.leetcode1268 Search Suggestions System-zh.md" @@ -0,0 +1,91 @@ +# [1268. 搜索推荐系统](https://leetcode-cn.com/problems/search-suggestions-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1268.Search%20Suggestions%20System/README_EN.md) + +## 题目描述 + + + +

    给你一个产品数组 products 和一个字符串 searchWord ,products  数组中每个产品都是一个字符串。

    + +

    请你设计一个推荐系统,在依次输入单词 searchWord 的每一个字母后,推荐 products 数组中前缀与 searchWord 相同的最多三个产品。如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个。

    + +

    请你以二维列表的形式,返回在输入 searchWord 每个字母后相应的推荐产品的列表。

    + +

     

    + +

    示例 1:

    + +
    输入:products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
    +输出:[
    +["mobile","moneypot","monitor"],
    +["mobile","moneypot","monitor"],
    +["mouse","mousepad"],
    +["mouse","mousepad"],
    +["mouse","mousepad"]
    +]
    +解释:按字典序排序后的产品列表是 ["mobile","moneypot","monitor","mouse","mousepad"]
    +输入 m 和 mo,由于所有产品的前缀都相同,所以系统返回字典序最小的三个产品 ["mobile","moneypot","monitor"]
    +输入 mou, mous 和 mouse 后系统都返回 ["mouse","mousepad"]
    +
    + +

    示例 2:

    + +
    输入:products = ["havana"], searchWord = "havana"
    +输出:[["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
    +
    + +

    示例 3:

    + +
    输入:products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
    +输出:[["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
    +
    + +

    示例 4:

    + +
    输入:products = ["havana"], searchWord = "tatiana"
    +输出:[[],[],[],[],[],[],[]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= products.length <= 1000
    • +
    • 1 <= Σ products[i].length <= 2 * 10^4
    • +
    • products[i] 中所有的字符都是小写英文字母。
    • +
    • 1 <= searchWord.length <= 1000
    • +
    • searchWord 中所有字符都是小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1269.leetcode1269 Number of Ways to Stay in the Same Place After Some Steps-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1269.leetcode1269 Number of Ways to Stay in the Same Place After Some Steps-zh.md" new file mode 100644 index 00000000..56192cae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1269.leetcode1269 Number of Ways to Stay in the Same Place After Some Steps-zh.md" @@ -0,0 +1,83 @@ +# [1269. 停在原地的方案数](https://leetcode-cn.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1269.Number%20of%20Ways%20to%20Stay%20in%20the%20Same%20Place%20After%20Some%20Steps/README_EN.md) + +## 题目描述 + + + +

    有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。

    + +

    每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。

    + +

    给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。

    + +

    由于答案可能会很大,请返回方案数  10^9 + 7 后的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:steps = 3, arrLen = 2
    +输出:4
    +解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。
    +向右,向左,不动
    +不动,向右,向左
    +向右,不动,向左
    +不动,不动,不动
    +
    + +

    示例  2:

    + +
    输入:steps = 2, arrLen = 4
    +输出:2
    +解释:2 步后,总共有 2 种不同的方法可以停在索引 0 处。
    +向右,向左
    +不动,不动
    +
    + +

    示例 3:

    + +
    输入:steps = 4, arrLen = 2
    +输出:8
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= steps <= 500
    • +
    • 1 <= arrLen <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1270.leetcode1270 All People Report to the Given Manager-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1270.leetcode1270 All People Report to the Given Manager-zh.md" new file mode 100644 index 00000000..8ffb82ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1270.leetcode1270 All People Report to the Given Manager-zh.md" @@ -0,0 +1,77 @@ +# [1270. 向公司CEO汇报工作的所有人](https://leetcode-cn.com/problems/all-people-report-to-the-given-manager) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1270.All%20People%20Report%20to%20the%20Given%20Manager/README_EN.md) + +## 题目描述 + + + +

    员工表:Employees

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| employee_id   | int     |
    +| employee_name | varchar |
    +| manager_id    | int     |
    ++---------------+---------+
    +employee_id 是这个表的主键。
    +这个表中每一行中,employee_id 表示职工的 ID,employee_name 表示职工的名字,manager_id 表示该职工汇报工作的直线经理。
    +这个公司 CEO 是 employee_id = 1 的人。
    +
    + +

     

    + +

    用 SQL 查询出所有直接或间接向公司 CEO 汇报工作的职工的 employee_id 。

    + +

    由于公司规模较小,经理之间的间接关系不超过 3 个经理。

    + +

    可以以任何顺序返回的结果,不需要去重。

    + +

    查询结果示例如下:

    + +
    Employees table:
    ++-------------+---------------+------------+
    +| employee_id | employee_name | manager_id |
    ++-------------+---------------+------------+
    +| 1           | Boss          | 1          |
    +| 3           | Alice         | 3          |
    +| 2           | Bob           | 1          |
    +| 4           | Daniel        | 2          |
    +| 7           | Luis          | 4          |
    +| 8           | Jhon          | 3          |
    +| 9           | Angela        | 8          |
    +| 77          | Robert        | 1          |
    ++-------------+---------------+------------+
    +
    +Result table:
    ++-------------+
    +| employee_id |
    ++-------------+
    +| 2           |
    +| 77          |
    +| 4           |
    +| 7           |
    ++-------------+
    +
    +公司 CEO 的 employee_id 是 1.
    +employee_id 是 2 和 77 的职员直接汇报给公司 CEO。
    +employee_id 是 4 的职员间接汇报给公司 CEO 4 --> 2 --> 1 。
    +employee_id 是 7 的职员间接汇报给公司 CEO 7 --> 4 --> 2 --> 1 。
    +employee_id 是 3, 8 ,9 的职员不会直接或间接的汇报给公司 CEO。 
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1271.leetcode1271 Hexspeak-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1271.leetcode1271 Hexspeak-zh.md" new file mode 100644 index 00000000..21dba59e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1271.leetcode1271 Hexspeak-zh.md" @@ -0,0 +1,69 @@ +# [1271. 十六进制魔术数字](https://leetcode-cn.com/problems/hexspeak) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1271.Hexspeak/README_EN.md) + +## 题目描述 + + + +

    你有一个十进制数字,请按照此规则将它变成「十六进制魔术数字」:首先将它变成字母大写的十六进制字符串,然后将所有的数字 0 变成字母 O ,将数字 1  变成字母 I

    + +

    如果一个数字在转换后只包含 {"A", "B", "C", "D", "E", "F", "I", "O"} ,那么我们就认为这个转换是有效的。

    + +

    给你一个字符串 num ,它表示一个十进制数 N,如果它的十六进制魔术数字转换是有效的,请返回转换后的结果,否则返回 "ERROR"

    + +

     

    + +

    示例 1:

    + +
    输入:num = "257"
    +输出:"IOI"
    +解释:257 的十六进制表示是 101 。
    +
    + +

    示例 2:

    + +
    输入:num = "3"
    +输出:"ERROR"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= N <= 10^12
    • +
    • 给定字符串不会有前导 0 。
    • +
    • 结果中的所有字母都应该是大写字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1272.leetcode1272 Remove Interval-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1272.leetcode1272 Remove Interval-zh.md" new file mode 100644 index 00000000..ae2b52c5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1272.leetcode1272 Remove Interval-zh.md" @@ -0,0 +1,76 @@ +# [1272. 删除区间](https://leetcode-cn.com/problems/remove-interval) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1272.Remove%20Interval/README_EN.md) + +## 题目描述 + + + +

    实数集合可以表示为若干不相交区间的并集,其中每个区间的形式为 [a, b)(左闭右开),表示满足 a <= x < b 的所有实数  x 的集合。如果某个区间 [a, b) 中包含实数 x ,则称实数 x 在集合中。

    + +

    给你一个 有序的 不相交区间列表 intervals 和一个要删除的区间 toBeRemovedintervals 表示一个实数集合,其中每一项 intervals[i] = [ai, bi] 都表示一个区间 [ai, bi)

    + +

    请你 intervals 中任意区间与 toBeRemoved 有交集的部分都删除。返回删除所有交集区间后, intervals 剩余部分的 有序 列表。换句话说,返回实数集合,并满足集合中的每个实数 x 都在 intervals 中,但不在 toBeRemoved 中。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
    +输出:[[0,1],[6,7]]
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[0,5]], toBeRemoved = [2,3]
    +输出:[[0,2],[3,5]]
    +
    + +

    示例 3:

    + +
    +输入:intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
    +输出:[[-5,-4],[-3,-2],[4,5],[8,9]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= intervals.length <= 104
    • +
    • -109 <= ai < bi <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1273.leetcode1273 Delete Tree Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1273.leetcode1273 Delete Tree Nodes-zh.md" new file mode 100644 index 00000000..7a788015 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1273.leetcode1273 Delete Tree Nodes-zh.md" @@ -0,0 +1,92 @@ +# [1273. 删除树节点](https://leetcode-cn.com/problems/delete-tree-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1273.Delete%20Tree%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给你一棵以节点 0 为根节点的树,定义如下:

    + +
      +
    • 节点的总数为 nodes 个;
    • +
    • 第 i 个节点的值为 value[i] ;
    • +
    • 第 i 个节点的父节点是 parent[i] 。
    • +
    + +

    请你删除节点值之和为 0 的每一棵子树。

    + +

    在完成所有删除之后,返回树中剩余节点的数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
    +输出:2
    +
    + +

    示例 2:

    + +
    输入:nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2]
    +输出:6
    +
    + +

    示例 3:

    + +
    输入:nodes = 5, parent = [-1,0,1,0,0], value = [-672,441,18,728,378]
    +输出:5
    +
    + +

    示例 4:

    + +
    输入:nodes = 5, parent = [-1,0,0,1,1], value = [-686,-842,616,-739,-746]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nodes <= 10^4
    • +
    • parent.length == nodes
    • +
    • 0 <= parent[i] <= nodes - 1
    • +
    • parent[0] == -1 表示节点 0 是树的根。
    • +
    • value.length == nodes
    • +
    • -10^5 <= value[i] <= 10^5
    • +
    • 题目输入数据 保证 是一棵 有效的树
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1274.leetcode1274 Number of Ships in a Rectangle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1274.leetcode1274 Number of Ships in a Rectangle-zh.md" new file mode 100644 index 00000000..bf0865c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1274.leetcode1274 Number of Ships in a Rectangle-zh.md" @@ -0,0 +1,70 @@ +# [1274. 矩形内船只的数目](https://leetcode-cn.com/problems/number-of-ships-in-a-rectangle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1274.Number%20of%20Ships%20in%20a%20Rectangle/README_EN.md) + +## 题目描述 + + + +

    (此题是 交互式问题 )

    + +

    在用笛卡尔坐标系表示的二维海平面上,有一些船。每一艘船都在一个整数点上,且每一个整数点最多只有 1 艘船。

    + +

    有一个函数 Sea.hasShips(topRight, bottomLeft) ,输入参数为右上角和左下角两个点的坐标,当且仅当这两个点所表示的矩形区域(包含边界)内至少有一艘船时,这个函数才返回 true ,否则返回 false

    + +

    给你矩形的右上角 topRight 和左下角 bottomLeft 的坐标,请你返回此矩形内船只的数目。题目保证矩形内 至多只有 10 艘船

    + +

    调用函数 hasShips 超过400次 的提交将被判为 错误答案(Wrong Answer) 。同时,任何尝试绕过评测系统的行为都将被取消比赛资格。

    + +

     

    + +

    示例:

    + +

    + +
    输入:
    +ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0]
    +输出:3
    +解释:在 [0,0] 到 [4,4] 的范围内总共有 3 艘船。
    +
    + +

     

    + +

    提示:

    + +
      +
    • ships 数组只用于评测系统内部初始化。你无法得知 ships 的信息,所以只能通过调用 hasShips 接口来求解。
    • +
    • 0 <= bottomLeft[0] <= topRight[0] <= 1000
    • +
    • 0 <= bottomLeft[1] <= topRight[1] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1275.leetcode1275 Find Winner on a Tic Tac Toe Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1275.leetcode1275 Find Winner on a Tic Tac Toe Game-zh.md" new file mode 100644 index 00000000..561e0e33 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1275.leetcode1275 Find Winner on a Tic Tac Toe Game-zh.md" @@ -0,0 +1,169 @@ +# [1275. 找出井字棋的获胜者](https://leetcode-cn.com/problems/find-winner-on-a-tic-tac-toe-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1275.Find%20Winner%20on%20a%20Tic%20Tac%20Toe%20Game/README_EN.md) + +## 题目描述 + + + +

    A 和 B 在一个 3 x 3 的网格上玩井字棋。

    + +

    井字棋游戏的规则如下:

    + +
      +
    • 玩家轮流将棋子放在空方格 (" ") 上。
    • +
    • 第一个玩家 A 总是用 "X" 作为棋子,而第二个玩家 B 总是用 "O" 作为棋子。
    • +
    • "X" 和 "O" 只能放在空方格中,而不能放在已经被占用的方格上。
    • +
    • 只要有 3 个相同的(非空)棋子排成一条直线(行、列、对角线)时,游戏结束。
    • +
    • 如果所有方块都放满棋子(不为空),游戏也会结束。
    • +
    • 游戏结束后,棋子无法再进行任何移动。
    • +
    + +

    给你一个数组 moves,其中每个元素是大小为 2 的另一个数组(元素分别对应网格的行和列),它按照 AB 的行动顺序(先 AB)记录了两人各自的棋子位置。

    + +

    如果游戏存在获胜者(AB),就返回该游戏的获胜者;如果游戏以平局结束,则返回 "Draw";如果仍会有行动(游戏未结束),则返回 "Pending"。

    + +

    你可以假设 moves 都 有效(遵循井字棋规则),网格最初是空的,A 将先行动。

    + +

     

    + +

    示例 1:

    + +
    输入:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
    +输出:"A"
    +解释:"A" 获胜,他总是先走。
    +"X  "    "X  "    "X  "    "X  "    "X  "
    +"   " -> "   " -> " X " -> " X " -> " X "
    +"   "    "O  "    "O  "    "OO "    "OOX"
    +
    + +

    示例 2:

    + +
    输入:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
    +输出:"B"
    +解释:"B" 获胜。
    +"X  "    "X  "    "XX "    "XXO"    "XXO"    "XXO"
    +"   " -> " O " -> " O " -> " O " -> "XO " -> "XO " 
    +"   "    "   "    "   "    "   "    "   "    "O  "
    +
    + +

    示例 3:

    + +
    输入:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
    +输出:"Draw"
    +输出:由于没有办法再行动,游戏以平局结束。
    +"XXO"
    +"OOX"
    +"XOX"
    +
    + +

    示例 4:

    + +
    输入:moves = [[0,0],[1,1]]
    +输出:"Pending"
    +解释:游戏还没有结束。
    +"X  "
    +" O "
    +"   "
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= moves.length <= 9
    • +
    • moves[i].length == 2
    • +
    • 0 <= moves[i][j] <= 2
    • +
    • moves 里没有重复的元素。
    • +
    • moves 遵循井字棋的规则。
    • +
    + +## 解法 + + + +判断 A、B 谁能获胜,只需判断最后一个落棋的人能否获胜即可。我们用数组 `counter` 记录 `0~2` 行、`0~2` 列、`正对角线`、`副对角线`是否已满 3 个棋子。如果等于 3,此人获胜,游戏结束。 + +若最后落棋者为未能获胜,棋盘被下满返回 `Draw`,未下满则返回 `Pending`。 + +> 数组 `counter` 长度为 8,其中,`counter[0..2]` 对应 `0~2` 行,`counter[3..5]` 对应 `0~2` 列,`counter[6]` 对应正对角线,`counter[7]` 对应副对角线的落棋次数。 + + + +### **Python3** + + + +```python +class Solution: + def tictactoe(self, moves: List[List[int]]) -> str: + n = len(moves) + counter = [0] * 8 + for i in range(n - 1, -1, -2): + row, col = moves[i][0], moves[i][1] + counter[row] += 1 + counter[col + 3] += 1 + if row == col: + counter[6] += 1 + if row + col == 2: + counter[7] += 1 + if counter[row] == 3 or counter[col + 3] == 3 or counter[6] == 3 or counter[7] == 3: + return "A" if (i % 2) == 0 else "B" + return "Draw" if n == 9 else "Pending" +``` + +### **Java** + + + +```java +class Solution { + public String tictactoe(int[][] moves) { + int n = moves.length; + int[] counter = new int[8]; + for (int i = n - 1; i >= 0; i -= 2) { + int row = moves[i][0], col = moves[i][1]; + ++counter[row]; + ++counter[col + 3]; + if (row == col) ++counter[6]; + if (row + col == 2) ++counter[7]; + if (counter[row] == 3 || counter[col + 3] == 3 || counter[6] == 3 || counter[7] == 3) { + return (i % 2) == 0 ? "A" : "B"; + } + } + return n == 9 ? "Draw" : "Pending"; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string tictactoe(vector>& moves) { + int n = moves.size(); + vector counter(8, 0); + for (int i = n - 1; i >= 0; i -= 2) { + int row = moves[i][0], col = moves[i][1]; + ++counter[row]; + ++counter[col + 3]; + if (row == col) ++counter[6]; + if (row + col == 2) ++counter[7]; + if (counter[row] == 3 || counter[col + 3] == 3 || counter[6] == 3 || counter[7] == 3) { + return (i % 2 == 0) ? "A" : "B"; + } + } + return n == 9 ? "Draw" : "Pending"; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1276.leetcode1276 Number of Burgers with No Waste of Ingredients-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1276.leetcode1276 Number of Burgers with No Waste of Ingredients-zh.md" new file mode 100644 index 00000000..5a9f6adb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1276.leetcode1276 Number of Burgers with No Waste of Ingredients-zh.md" @@ -0,0 +1,95 @@ +# [1276. 不浪费原料的汉堡制作方案](https://leetcode-cn.com/problems/number-of-burgers-with-no-waste-of-ingredients) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1276.Number%20of%20Burgers%20with%20No%20Waste%20of%20Ingredients/README_EN.md) + +## 题目描述 + + + +

    圣诞活动预热开始啦,汉堡店推出了全新的汉堡套餐。为了避免浪费原料,请你帮他们制定合适的制作计划。

    + +

    给你两个整数 tomatoSlices 和 cheeseSlices,分别表示番茄片和奶酪片的数目。不同汉堡的原料搭配如下:

    + +
      +
    • 巨无霸汉堡:4 片番茄和 1 片奶酪
    • +
    • 小皇堡:2 片番茄和 1 片奶酪
    • +
    + +

    请你以 [total_jumbo, total_small]([巨无霸汉堡总数,小皇堡总数])的格式返回恰当的制作方案,使得剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的数量都是 0

    + +

    如果无法使剩下的番茄片 tomatoSlices 和奶酪片 cheeseSlices 的数量为 0,就请返回 []

    + +

     

    + +

    示例 1:

    + +
    输入:tomatoSlices = 16, cheeseSlices = 7
    +输出:[1,6]
    +解释:制作 1 个巨无霸汉堡和 6 个小皇堡需要 4*1 + 2*6 = 16 片番茄和 1 + 6 = 7 片奶酪。不会剩下原料。
    +
    + +

    示例 2:

    + +
    输入:tomatoSlices = 17, cheeseSlices = 4
    +输出:[]
    +解释:只制作小皇堡和巨无霸汉堡无法用光全部原料。
    +
    + +

    示例 3:

    + +
    输入:tomatoSlices = 4, cheeseSlices = 17
    +输出:[]
    +解释:制作 1 个巨无霸汉堡会剩下 16 片奶酪,制作 2 个小皇堡会剩下 15 片奶酪。
    +
    + +

    示例 4:

    + +
    输入:tomatoSlices = 0, cheeseSlices = 0
    +输出:[0,0]
    +
    + +

    示例 5:

    + +
    输入:tomatoSlices = 2, cheeseSlices = 1
    +输出:[0,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= tomatoSlices <= 10^7
    • +
    • 0 <= cheeseSlices <= 10^7
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1277.leetcode1277 Count Square Submatrices with All Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1277.leetcode1277 Count Square Submatrices with All Ones-zh.md" new file mode 100644 index 00000000..8a8fc181 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1277.leetcode1277 Count Square Submatrices with All Ones-zh.md" @@ -0,0 +1,83 @@ +# [1277. 统计全为 1 的正方形子矩阵](https://leetcode-cn.com/problems/count-square-submatrices-with-all-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1277.Count%20Square%20Submatrices%20with%20All%20Ones/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。

    + +

     

    + +

    示例 1:

    + +
    输入:matrix =
    +[
    +  [0,1,1,1],
    +  [1,1,1,1],
    +  [0,1,1,1]
    +]
    +输出:15
    +解释: 
    +边长为 1 的正方形有 10 个。
    +边长为 2 的正方形有 4 个。
    +边长为 3 的正方形有 1 个。
    +正方形的总数 = 10 + 4 + 1 = 15.
    +
    + +

    示例 2:

    + +
    输入:matrix = 
    +[
    +  [1,0,1],
    +  [1,1,0],
    +  [1,1,0]
    +]
    +输出:7
    +解释:
    +边长为 1 的正方形有 6 个。 
    +边长为 2 的正方形有 1 个。
    +正方形的总数 = 6 + 1 = 7.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 300
    • +
    • 1 <= arr[0].length <= 300
    • +
    • 0 <= arr[i][j] <= 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1278.leetcode1278 Palindrome Partitioning III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1278.leetcode1278 Palindrome Partitioning III-zh.md" new file mode 100644 index 00000000..a79c3d6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1278.leetcode1278 Palindrome Partitioning III-zh.md" @@ -0,0 +1,79 @@ +# [1278. 分割回文串 III](https://leetcode-cn.com/problems/palindrome-partitioning-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1278.Palindrome%20Partitioning%20III/README_EN.md) + +## 题目描述 + + + +

    给你一个由小写字母组成的字符串 s,和一个整数 k

    + +

    请你按下面的要求分割字符串:

    + +
      +
    • 首先,你可以将 s 中的部分字符修改为其他的小写英文字母。
    • +
    • 接着,你需要把 s 分割成 k 个非空且不相交的子串,并且每个子串都是回文串。
    • +
    + +

    请返回以这种方式分割字符串所需修改的最少字符数。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "abc", k = 2
    +输出:1
    +解释:你可以把字符串分割成 "ab" 和 "c",并修改 "ab" 中的 1 个字符,将它变成回文串。
    +
    + +

    示例 2:

    + +
    输入:s = "aabbc", k = 3
    +输出:0
    +解释:你可以把字符串分割成 "aa"、"bb" 和 "c",它们都是回文串。
    + +

    示例 3:

    + +
    输入:s = "leetcode", k = 8
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= s.length <= 100
    • +
    • s 中只含有小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1279.leetcode1279 Traffic Light Controlled Intersection-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1279.leetcode1279 Traffic Light Controlled Intersection-zh.md" new file mode 100644 index 00000000..cf14e6bf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1279.leetcode1279 Traffic Light Controlled Intersection-zh.md" @@ -0,0 +1,97 @@ +# [1279. 红绿灯路口](https://leetcode-cn.com/problems/traffic-light-controlled-intersection) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1279.Traffic%20Light%20Controlled%20Intersection/README_EN.md) + +## 题目描述 + + + +

    这是两条路的交叉路口。第一条路是 A 路,车辆可沿 1 号方向由北向南行驶,也可沿 2 号方向由南向北行驶。第二条路是 B 路,车辆可沿 3 号方向由西向东行驶,也可沿 4 号方向由东向西行驶。

    + +

    + +

    每条路在路口前都有一个红绿灯。红绿灯可以亮起红灯或绿灯。

    + +
      +
    1. 绿灯表示两个方向的车辆都可通过路口。
    2. +
    3. 红灯表示两个方向的车辆都不可以通过路口,必须等待绿灯亮起。
    4. +
    + +

    两条路上的红绿灯不可以同时为绿灯。这意味着,当 A 路上的绿灯亮起时,B 路上的红灯会亮起;当 B 路上的绿灯亮起时,A 路上的红灯会亮起.

    + +

    开始时,A 路上的绿灯亮起,B 路上的红灯亮起。当一条路上的绿灯亮起时,所有车辆都可以从任意两个方向通过路口,直到另一条路上的绿灯亮起。不同路上的车辆不可以同时通过路口。

    + +

    给这个路口设计一个没有死锁的红绿灯控制系统。

    + +

    实现函数 void carArrived(carId, roadId, direction, turnGreen, crossCar) :

    + +
      +
    • carId 为到达车辆的编号。
    • +
    • roadId 为车辆所在道路的编号。
    • +
    • direction 为车辆的行进方向。
    • +
    • turnGreen 是一个函数,调用此函数会使当前道路上的绿灯亮起。
    • +
    • crossCar 是一个函数,调用此函数会允许车辆通过路口。
    • +
    + +

    当你的答案避免了车辆在路口出现死锁,此答案会被认定为正确的。当路口已经亮起绿灯时仍打开绿灯,此答案会被认定为错误的。

    + +

     

    + +

    示例 1:

    + +
    +输入: cars = [1,3,5,2,4], directions = [2,1,2,4,3], arrivalTimes = [10,20,30,40,50]
    +输出: [
    +"Car 1 Has Passed Road A In Direction 2",    // A 路上的红绿灯为绿色,1 号车可通过路口。
    +"Car 3 Has Passed Road A In Direction 1",    // 红绿灯仍为绿色,3 号车通过路口。
    +"Car 5 Has Passed Road A In Direction 2",    // 红绿灯仍为绿色,5 号车通过路口。
    +"Traffic Light On Road B Is Green",          // 2 号车在 B 路请求绿灯。
    +"Car 2 Has Passed Road B In Direction 4",    // B 路上的绿灯现已亮起,2 号车通过路口。
    +"Car 4 Has Passed Road B In Direction 3"     // 红绿灯仍为绿色,4 号车通过路口。
    +]
    +
    + +

    示例 2:

    + +
    +输入: cars = [1,2,3,4,5], directions = [2,4,3,3,1], arrivalTimes = [10,20,30,40,40]
    +输出: [
    +"Car 1 Has Passed Road A In Direction 2",    // A 路上的红绿灯为绿色,1 号车可通过路口。
    +"Traffic Light On Road B Is Green",          // 2 号车在 B 路请求绿灯。
    +"Car 2 Has Passed Road B In Direction 4",    // B 路上的绿灯现已亮起,2 号车通过路口。
    +"Car 3 Has Passed Road B In Direction 3",    // B 路上的绿灯现已亮起,3 号车通过路口。
    +"Traffic Light On Road A Is Green",          // 5 号车在 A 路请求绿灯。
    +"Car 5 Has Passed Road A In Direction 1",    // A 路上的绿灯现已亮起,5 号车通过路口。
    +"Traffic Light On Road B Is Green",          // 4 号车在 B 路请求绿灯。4 号车在路口等灯,直到 5 号车通过路口,B 路的绿灯亮起。
    +"Car 4 Has Passed Road B In Direction 3"     // B 路上的绿灯现已亮起,4 号车通过路口。
    +]
    +解释: 这是一个无死锁的方案。注意,在 A 路上的绿灯亮起、5 号车通过前让 4 号车通过,也是一个正确被接受的方案。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= cars.length <= 20
    • +
    • cars.length = directions.length
    • +
    • cars.length = arrivalTimes.length
    • +
    • cars 中的所有值都是唯一的。
    • +
    • 1 <= directions[i] <= 4
    • +
    • arrivalTimes 是非递减的。
    • +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1280.leetcode1280 Students and Examinations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1280.leetcode1280 Students and Examinations-zh.md" new file mode 100644 index 00000000..d3859d58 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1280.leetcode1280 Students and Examinations-zh.md" @@ -0,0 +1,122 @@ +# [1280. 学生们参加各科测试的次数](https://leetcode-cn.com/problems/students-and-examinations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1280.Students%20and%20Examinations/README_EN.md) + +## 题目描述 + + + +

    学生表: Students

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +主键为 student_id(学生ID),该表内的每一行都记录有学校一名学生的信息。
    +
    + +

     

    + +

    科目表: Subjects

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| subject_name | varchar |
    ++--------------+---------+
    +主键为 subject_name(科目名称),每一行记录学校的一门科目名称。
    +
    + +

     

    + +

    考试表: Examinations

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| student_id   | int     |
    +| subject_name | varchar |
    ++--------------+---------+
    +这张表压根没有主键,可能会有重复行。
    +学生表里的一个学生修读科目表里的每一门科目,而这张考试表的每一行记录就表示学生表里的某个学生参加了一次科目表里某门科目的测试。
    +
    + +

     

    + +

    要求写一段 SQL 语句,查询出每个学生参加每一门科目测试的次数,结果按 student_idsubject_name 排序。

    + +

    查询结构格式如下所示:

    + +
    Students table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 1          | Alice        |
    +| 2          | Bob          |
    +| 13         | John         |
    +| 6          | Alex         |
    ++------------+--------------+
    +Subjects table:
    ++--------------+
    +| subject_name |
    ++--------------+
    +| Math         |
    +| Physics      |
    +| Programming  |
    ++--------------+
    +Examinations table:
    ++------------+--------------+
    +| student_id | subject_name |
    ++------------+--------------+
    +| 1          | Math         |
    +| 1          | Physics      |
    +| 1          | Programming  |
    +| 2          | Programming  |
    +| 1          | Physics      |
    +| 1          | Math         |
    +| 13         | Math         |
    +| 13         | Programming  |
    +| 13         | Physics      |
    +| 2          | Math         |
    +| 1          | Math         |
    ++------------+--------------+
    +Result table:
    ++------------+--------------+--------------+----------------+
    +| student_id | student_name | subject_name | attended_exams |
    ++------------+--------------+--------------+----------------+
    +| 1          | Alice        | Math         | 3              |
    +| 1          | Alice        | Physics      | 2              |
    +| 1          | Alice        | Programming  | 1              |
    +| 2          | Bob          | Math         | 1              |
    +| 2          | Bob          | Physics      | 0              |
    +| 2          | Bob          | Programming  | 1              |
    +| 6          | Alex         | Math         | 0              |
    +| 6          | Alex         | Physics      | 0              |
    +| 6          | Alex         | Programming  | 0              |
    +| 13         | John         | Math         | 1              |
    +| 13         | John         | Physics      | 1              |
    +| 13         | John         | Programming  | 1              |
    ++------------+--------------+--------------+----------------+
    +结果表需包含所有学生和所有科目(即便测试次数为0):
    +Alice 参加了 3 次数学测试, 2 次物理测试,以及 1 次编程测试;
    +Bob 参加了 1 次数学测试, 1 次编程测试,没有参加物理测试;
    +Alex 啥测试都没参加;
    +John  参加了数学、物理、编程测试各 1 次。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1281.leetcode1281 Subtract the Product and Sum of Digits of an Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1281.leetcode1281 Subtract the Product and Sum of Digits of an Integer-zh.md" new file mode 100644 index 00000000..c39c68c0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1281.leetcode1281 Subtract the Product and Sum of Digits of an Integer-zh.md" @@ -0,0 +1,70 @@ +# [1281. 整数的各位积和之差](https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1281.Subtract%20the%20Product%20and%20Sum%20of%20Digits%20of%20an%20Integer/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 234
    +输出:15 
    +解释:
    +各位数之积 = 2 * 3 * 4 = 24 
    +各位数之和 = 2 + 3 + 4 = 9 
    +结果 = 24 - 9 = 15
    +
    + +

    示例 2:

    + +
    输入:n = 4421
    +输出:21
    +解释: 
    +各位数之积 = 4 * 4 * 2 * 1 = 32 
    +各位数之和 = 4 + 4 + 2 + 1 = 11 
    +结果 = 32 - 11 = 21
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1282.leetcode1282 Group the People Given the Group Size They Belong To-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1282.leetcode1282 Group the People Given the Group Size They Belong To-zh.md" new file mode 100644 index 00000000..940b3d71 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1282.leetcode1282 Group the People Given the Group Size They Belong To-zh.md" @@ -0,0 +1,68 @@ +# [1282. 用户分组](https://leetcode-cn.com/problems/group-the-people-given-the-group-size-they-belong-to) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1282.Group%20the%20People%20Given%20the%20Group%20Size%20They%20Belong%20To/README_EN.md) + +## 题目描述 + + + +

    有 n 位用户参加活动,他们的 ID 从 0n - 1,每位用户都 恰好 属于某一用户组。给你一个长度为 n 的数组 groupSizes,其中包含每位用户所处的用户组的大小,请你返回用户分组情况(存在的用户组以及每个组中用户的 ID)。

    + +

    你可以任何顺序返回解决方案,ID 的顺序也不受限制。此外,题目给出的数据保证至少存在一种解决方案。

    + +

     

    + +

    示例 1:

    + +
    输入:groupSizes = [3,3,3,3,3,1,3]
    +输出:[[5],[0,1,2],[3,4,6]]
    +解释: 
    +其他可能的解决方案有 [[2,1,6],[5],[0,4,3]] 和 [[5],[0,6,2],[4,3,1]]。
    +
    + +

    示例 2:

    + +
    输入:groupSizes = [2,1,3,3,3,2]
    +输出:[[1],[0,5],[2,3,4]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • groupSizes.length == n
    • +
    • 1 <= n <= 500
    • +
    • 1 <= groupSizes[i] <= n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1283.leetcode1283 Find the Smallest Divisor Given a Threshold-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1283.leetcode1283 Find the Smallest Divisor Given a Threshold-zh.md" new file mode 100644 index 00000000..d77c783e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1283.leetcode1283 Find the Smallest Divisor Given a Threshold-zh.md" @@ -0,0 +1,157 @@ +# [1283. 使结果不超过阈值的最小除数](https://leetcode-cn.com/problems/find-the-smallest-divisor-given-a-threshold) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1283.Find%20the%20Smallest%20Divisor%20Given%20a%20Threshold/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个正整数 threshold  ,你需要选择一个正整数作为除数,然后将数组里每个数都除以它,并对除法结果求和。

    + +

    请你找出能够使上述结果小于等于阈值 threshold 的除数中 最小 的那个。

    + +

    每个数除以除数后都向上取整,比方说 7/3 = 3 , 10/2 = 5 。

    + +

    题目保证一定有解。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,5,9], threshold = 6
    +输出:5
    +解释:如果除数为 1 ,我们可以得到和为 17 (1+2+5+9)。
    +如果除数为 4 ,我们可以得到和为 7 (1+1+2+3) 。如果除数为 5 ,和为 5 (1+1+1+2)。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,3,5,7,11], threshold = 11
    +输出:3
    +
    + +

    示例 3:

    + +
    +输入:nums = [19], threshold = 5
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5 * 10^4
    • +
    • 1 <= nums[i] <= 10^6
    • +
    • nums.length <= threshold <= 10^6
    • +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + left, right = 1, 1000000 + while left < right: + mid = (left + right) >> 1 + s = 0 + for num in nums: + s += (num + mid - 1) // mid + if s <= threshold: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int smallestDivisor(int[] nums, int threshold) { + int left = 1, right = 1000000; + while (left < right) { + int mid = (left + right) >> 1; + int s = 0; + for (int num : nums) { + s += (num + mid - 1) / mid; + } + if (s <= threshold) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int smallestDivisor(vector& nums, int threshold) { + int left = 1, right = 1000000; + while (left < right) { + int mid = left + right >> 1; + int s = 0; + for (int& num : nums) { + s += (num + mid - 1) / mid; + } + if (s <= threshold) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func smallestDivisor(nums []int, threshold int) int { + left, right := 1, 1000000 + for left < right { + mid := (left + right) >> 1 + s := 0 + for _, num := range nums { + s += (num + mid - 1) / mid + } + if s <= threshold { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1284.leetcode1284 Minimum Number of Flips to Convert Binary Matrix to Zero Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1284.leetcode1284 Minimum Number of Flips to Convert Binary Matrix to Zero Matrix-zh.md" new file mode 100644 index 00000000..0676a74f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1284.leetcode1284 Minimum Number of Flips to Convert Binary Matrix to Zero Matrix-zh.md" @@ -0,0 +1,91 @@ +# [1284. 转化为全零矩阵的最少反转次数](https://leetcode-cn.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1284.Minimum%20Number%20of%20Flips%20to%20Convert%20Binary%20Matrix%20to%20Zero%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的二进制矩阵 mat

    + +

    每一步,你可以选择一个单元格并将它反转(反转表示 0 变 1 ,1 变 0 )。如果存在和它相邻的单元格,那么这些相邻的单元格也会被反转。(注:相邻的两个单元格共享同一条边。)

    + +

    请你返回将矩阵 mat 转化为全零矩阵的最少反转次数,如果无法转化为全零矩阵,请返回 -1 。

    + +

    二进制矩阵的每一个格子要么是 0 要么是 1 。

    + +

    全零矩阵是所有格子都为 0 的矩阵。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:mat = [[0,0],[0,1]]
    +输出:3
    +解释:一个可能的解是反转 (1, 0),然后 (0, 1) ,最后是 (1, 1) 。
    +
    + +

    示例 2:

    + +
    输入:mat = [[0]]
    +输出:0
    +解释:给出的矩阵是全零矩阵,所以你不需要改变它。
    +
    + +

    示例 3:

    + +
    输入:mat = [[1,1,1],[1,0,1],[0,0,0]]
    +输出:6
    +
    + +

    示例 4:

    + +
    输入:mat = [[1,0,0],[1,0,0]]
    +输出:-1
    +解释:该矩阵无法转变成全零矩阵
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == mat.length
    • +
    • n == mat[0].length
    • +
    • 1 <= m <= 3
    • +
    • 1 <= n <= 3
    • +
    • mat[i][j] 是 0 或 1 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1285.leetcode1285 Find the Start and End Number of Continuous Ranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1285.leetcode1285 Find the Start and End Number of Continuous Ranges-zh.md" new file mode 100644 index 00000000..73559004 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1285.leetcode1285 Find the Start and End Number of Continuous Ranges-zh.md" @@ -0,0 +1,71 @@ +# [1285. 找到连续区间的开始和结束数字](https://leetcode-cn.com/problems/find-the-start-and-end-number-of-continuous-ranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1285.Find%20the%20Start%20and%20End%20Number%20of%20Continuous%20Ranges/README_EN.md) + +## 题目描述 + + + +

    表:Logs

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| log_id        | int     |
    ++---------------+---------+
    +id 是上表的主键。
    +上表的每一行包含日志表中的一个 ID。
    +
    + +

     

    + +

    后来一些 ID 从 Logs 表中删除。编写一个 SQL 查询得到 Logs 表中的连续区间的开始数字和结束数字。

    + +

    将查询表按照 start_id 排序。

    + +

    查询结果格式如下面的例子:

    + +
    +Logs 表:
    ++------------+
    +| log_id     |
    ++------------+
    +| 1          |
    +| 2          |
    +| 3          |
    +| 7          |
    +| 8          |
    +| 10         |
    ++------------+
    +
    +结果表:
    ++------------+--------------+
    +| start_id   | end_id       |
    ++------------+--------------+
    +| 1          | 3            |
    +| 7          | 8            |
    +| 10         | 10           |
    ++------------+--------------+
    +结果表应包含 Logs 表中的所有区间。
    +从 1 到 3 在表中。
    +从 4 到 6 不在表中。
    +从 7 到 8 在表中。
    +9 不在表中。
    +10 在表中。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1286.leetcode1286 Iterator for Combination-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1286.leetcode1286 Iterator for Combination-zh.md" new file mode 100644 index 00000000..d1d5ad50 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1286.leetcode1286 Iterator for Combination-zh.md" @@ -0,0 +1,70 @@ +# [1286. 字母组合迭代器](https://leetcode-cn.com/problems/iterator-for-combination) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1286.Iterator%20for%20Combination/README_EN.md) + +## 题目描述 + + + +

    请你设计一个迭代器类,包括以下内容:

    + +
      +
    • 一个构造函数,输入参数包括:一个 有序且字符唯一 的字符串 characters(该字符串只包含小写英文字母)和一个数字 combinationLength 。
    • +
    • 函数 next() ,按 字典序 返回长度为 combinationLength 的下一个字母组合。
    • +
    • 函数 hasNext() ,只有存在长度为 combinationLength 的下一个字母组合时,才返回 True;否则,返回 False
    • +
    + +

     

    + +

    示例:

    + +
    CombinationIterator iterator = new CombinationIterator("abc", 2); // 创建迭代器 iterator
    +
    +iterator.next(); // 返回 "ab"
    +iterator.hasNext(); // 返回 true
    +iterator.next(); // 返回 "ac"
    +iterator.hasNext(); // 返回 true
    +iterator.next(); // 返回 "bc"
    +iterator.hasNext(); // 返回 false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= combinationLength <= characters.length <= 15
    • +
    • 每组测试数据最多包含 10^4 次函数调用。
    • +
    • 题目保证每次调用函数 next 时都存在下一个字母组合。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1287.leetcode1287 Element Appearing More Than 25% In Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1287.leetcode1287 Element Appearing More Than 25% In Sorted Array-zh.md" new file mode 100644 index 00000000..ddc57121 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1287.leetcode1287 Element Appearing More Than 25% In Sorted Array-zh.md" @@ -0,0 +1,60 @@ +# [1287. 有序数组中出现次数超过25%的元素](https://leetcode-cn.com/problems/element-appearing-more-than-25-in-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1287.Element%20Appearing%20More%20Than%2025%25%20In%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个非递减的 有序 整数数组,已知这个数组中恰好有一个整数,它的出现次数超过数组元素总数的 25%。

    + +

    请你找到并返回这个整数

    + +

     

    + +

    示例:

    + +
    +输入:arr = [1,2,2,6,6,6,6,7,10]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^4
    • +
    • 0 <= arr[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1288.leetcode1288 Remove Covered Intervals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1288.leetcode1288 Remove Covered Intervals-zh.md" new file mode 100644 index 00000000..ba62c20d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1288.leetcode1288 Remove Covered Intervals-zh.md" @@ -0,0 +1,64 @@ +# [1288. 删除被覆盖区间](https://leetcode-cn.com/problems/remove-covered-intervals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1288.Remove%20Covered%20Intervals/README_EN.md) + +## 题目描述 + + + +

    给你一个区间列表,请你删除列表中被其他区间所覆盖的区间。

    + +

    只有当 c <= a 且 b <= d 时,我们才认为区间 [a,b) 被区间 [c,d) 覆盖。

    + +

    在完成所有删除操作后,请你返回列表中剩余区间的数目。

    + +

     

    + +

    示例:

    + +
    +输入:intervals = [[1,4],[3,6],[2,8]]
    +输出:2
    +解释:区间 [3,6] 被区间 [2,8] 覆盖,所以它被删除了。
    +
    + +

     

    + +

    提示:​​​​​​

    + +
      +
    • 1 <= intervals.length <= 1000
    • +
    • 0 <= intervals[i][0] < intervals[i][1] <= 10^5
    • +
    • 对于所有的 i != jintervals[i] != intervals[j]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1289.leetcode1289 Minimum Falling Path Sum II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1289.leetcode1289 Minimum Falling Path Sum II-zh.md" new file mode 100644 index 00000000..8add5555 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1289.leetcode1289 Minimum Falling Path Sum II-zh.md" @@ -0,0 +1,66 @@ +# [1289. 下降路径最小和 II](https://leetcode-cn.com/problems/minimum-falling-path-sum-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1289.Minimum%20Falling%20Path%20Sum%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数方阵 arr ,定义「非零偏移下降路径」为:从 arr 数组中的每一行选择一个数字,且按顺序选出来的数字中,相邻数字不在原数组的同一列。

    + +

    请你返回非零偏移下降路径数字和的最小值。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [[1,2,3],[4,5,6],[7,8,9]]
    +输出:13
    +解释:
    +所有非零偏移下降路径包括:
    +[1,5,9], [1,5,7], [1,6,7], [1,6,8],
    +[2,4,8], [2,4,9], [2,6,7], [2,6,8],
    +[3,4,8], [3,4,9], [3,5,7], [3,5,9]
    +下降路径中数字和最小的是 [1,5,7] ,所以答案是 13 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length == arr[i].length <= 200
    • +
    • -99 <= arr[i][j] <= 99
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1290.leetcode1290 Convert Binary Number in a Linked List to Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1290.leetcode1290 Convert Binary Number in a Linked List to Integer-zh.md" new file mode 100644 index 00000000..ad97da95 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1290.leetcode1290 Convert Binary Number in a Linked List to Integer-zh.md" @@ -0,0 +1,167 @@ +# [1290. 二进制链表转整数](https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1290.Convert%20Binary%20Number%20in%20a%20Linked%20List%20to%20Integer/README_EN.md) + +## 题目描述 + + + +

    给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。

    + +

    请你返回该链表所表示数字的 十进制值

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:head = [1,0,1]
    +输出:5
    +解释:二进制数 (101) 转化为十进制数 (5)
    +
    + +

    示例 2:

    + +
    输入:head = [0]
    +输出:0
    +
    + +

    示例 3:

    + +
    输入:head = [1]
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
    +输出:18880
    +
    + +

    示例 5:

    + +
    输入:head = [0,0]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表不为空。
    • +
    • 链表的结点总数不超过 30
    • +
    • 每个结点的值不是 0 就是 1
    • +
    + +## 解法 + + + +遍历链表。 + +当遍历到链表某个结点,先将已有结果 res 乘以 2(即左移 1 位:`<< 1`),再加上当前结点的值,得出已遍历过的结点的十进制值。最后返回 res 即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def getDecimalValue(self, head: ListNode) -> int: + res = 0 + while head: + res = (res << 1) + head.val + head = head.next + return res +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public int getDecimalValue(ListNode head) { + int res = 0; + while (head != null) { + res = (res << 1) + head.val; + head = head.next; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number} + */ +var getDecimalValue = function (head) { + let res = 0; + while (head != null) { + res = (res << 1) + head.val; + head = head.next; + } + return res; +}; +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + int getDecimalValue(ListNode* head) { + int res = 0; + while (head != NULL) { + res = (res << 1) + head->val; + head = head->next; + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1291.leetcode1291 Sequential Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1291.leetcode1291 Sequential Digits-zh.md" new file mode 100644 index 00000000..b92e991b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1291.leetcode1291 Sequential Digits-zh.md" @@ -0,0 +1,64 @@ +# [1291. 顺次数](https://leetcode-cn.com/problems/sequential-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1291.Sequential%20Digits/README_EN.md) + +## 题目描述 + + + +

    我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。

    + +

    请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。

    + +

     

    + +

    示例 1:

    + +
    输出:low = 100, high = 300
    +输出:[123,234]
    +
    + +

    示例 2:

    + +
    输出:low = 1000, high = 13000
    +输出:[1234,2345,3456,4567,5678,6789,12345]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 10 <= low <= high <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1292.leetcode1292 Maximum Side Length of a Square with Sum Less than or Equal to Threshold-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1292.leetcode1292 Maximum Side Length of a Square with Sum Less than or Equal to Threshold-zh.md" new file mode 100644 index 00000000..0bf135fa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1292.leetcode1292 Maximum Side Length of a Square with Sum Less than or Equal to Threshold-zh.md" @@ -0,0 +1,86 @@ +# [1292. 元素和小于等于阈值的正方形的最大边长](https://leetcode-cn.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1292.Maximum%20Side%20Length%20of%20a%20Square%20with%20Sum%20Less%20than%20or%20Equal%20to%20Threshold/README_EN.md) + +## 题目描述 + + + +

    给你一个大小为 m x n 的矩阵 mat 和一个整数阈值 threshold

    + +

    请你返回元素总和小于或等于阈值的正方形区域的最大边长;如果没有这样的正方形区域,则返回

    + +

    示例 1:

    + +

    + +
    +输入:mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
    +输出:2
    +解释:总和小于或等于 4 的正方形的最大边长为 2,如图所示。
    +
    + +

    示例 2:

    + +
    +输入:mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
    +输出:3
    +
    + +

    示例 4:

    + +
    +输入:mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m, n <= 300
    • +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 0 <= mat[i][j] <= 10000
    • +
    • 0 <= threshold <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1293.leetcode1293 Shortest Path in a Grid with Obstacles Elimination-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1293.leetcode1293 Shortest Path in a Grid with Obstacles Elimination-zh.md" new file mode 100644 index 00000000..ba40dd76 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1293.leetcode1293 Shortest Path in a Grid with Obstacles Elimination-zh.md" @@ -0,0 +1,88 @@ +# [1293. 网格中的最短路径](https://leetcode-cn.com/problems/shortest-path-in-a-grid-with-obstacles-elimination) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1293.Shortest%20Path%20in%20a%20Grid%20with%20Obstacles%20Elimination/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的网格,其中每个单元格不是 0(空)就是 1(障碍物)。每一步,您都可以在空白单元格中上、下、左、右移动。

    + +

    如果您 最多 可以消除 k 个障碍物,请找出从左上角 (0, 0) 到右下角 (m-1, n-1) 的最短路径,并返回通过该路径所需的步数。如果找不到这样的路径,则返回 -1。

    + +

     

    + +

    示例 1:

    + +
    输入: 
    +grid = 
    +[[0,0,0],
    + [1,1,0],
    + [0,0,0],
    + [0,1,1],
    + [0,0,0]], 
    +k = 1
    +输出:6
    +解释:
    +不消除任何障碍的最短路径是 10。
    +消除位置 (3,2) 处的障碍后,最短路径是 6 。该路径是 (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
    +
    + +

     

    + +

    示例 2:

    + +
    输入:
    +grid = 
    +[[0,1,1],
    + [1,1,1],
    + [1,0,0]], 
    +k = 1
    +输出:-1
    +解释:
    +我们至少需要消除两个障碍才能找到这样的路径。
    +
    + +

     

    + +

    提示:

    + +
      +
    • grid.length == m
    • +
    • grid[0].length == n
    • +
    • 1 <= m, n <= 40
    • +
    • 1 <= k <= m*n
    • +
    • grid[i][j] == 0 or 1
    • +
    • grid[0][0] == grid[m-1][n-1] == 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1294.leetcode1294 Weather Type in Each Country-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1294.leetcode1294 Weather Type in Each Country-zh.md" new file mode 100644 index 00000000..56f8b661 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1294.leetcode1294 Weather Type in Each Country-zh.md" @@ -0,0 +1,113 @@ +# [1294. 不同国家的天气类型](https://leetcode-cn.com/problems/weather-type-in-each-country) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1294.Weather%20Type%20in%20Each%20Country/README_EN.md) + +## 题目描述 + + + +

    国家表:Countries

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| country_id    | int     |
    +| country_name  | varchar |
    ++---------------+---------+
    +country_id 是这张表的主键。
    +该表的每行有 country_id 和 country_name 两列。
    +
    + +

     

    + +

    天气表:Weather

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| country_id    | int     |
    +| weather_state | varchar |
    +| day           | date    |
    ++---------------+---------+
    +(country_id, day) 是该表的复合主键。
    +该表的每一行记录了某个国家某一天的天气情况。
    +
    + +

     

    + +

    写一段 SQL 来找到表中每个国家在 2019 年 11 月的天气类型。

    + +

    天气类型的定义如下:当 weather_state 的平均值小于或等于15返回 Cold,当 weather_state 的平均值大于或等于 25 返回 Hot,否则返回 Warm

    + +

    你可以以任意顺序返回你的查询结果。

    + +

    查询结果格式如下所示:

    + +
    +Countries table:
    ++------------+--------------+
    +| country_id | country_name |
    ++------------+--------------+
    +| 2          | USA          |
    +| 3          | Australia    |
    +| 7          | Peru         |
    +| 5          | China        |
    +| 8          | Morocco      |
    +| 9          | Spain        |
    ++------------+--------------+
    +Weather table:
    ++------------+---------------+------------+
    +| country_id | weather_state | day        |
    ++------------+---------------+------------+
    +| 2          | 15            | 2019-11-01 |
    +| 2          | 12            | 2019-10-28 |
    +| 2          | 12            | 2019-10-27 |
    +| 3          | -2            | 2019-11-10 |
    +| 3          | 0             | 2019-11-11 |
    +| 3          | 3             | 2019-11-12 |
    +| 5          | 16            | 2019-11-07 |
    +| 5          | 18            | 2019-11-09 |
    +| 5          | 21            | 2019-11-23 |
    +| 7          | 25            | 2019-11-28 |
    +| 7          | 22            | 2019-12-01 |
    +| 7          | 20            | 2019-12-02 |
    +| 8          | 25            | 2019-11-05 |
    +| 8          | 27            | 2019-11-15 |
    +| 8          | 31            | 2019-11-25 |
    +| 9          | 7             | 2019-10-23 |
    +| 9          | 3             | 2019-12-23 |
    ++------------+---------------+------------+
    +Result table:
    ++--------------+--------------+
    +| country_name | weather_type |
    ++--------------+--------------+
    +| USA          | Cold         |
    +| Austraila    | Cold         |
    +| Peru         | Hot          |
    +| China        | Warm         |
    +| Morocco      | Hot          |
    ++--------------+--------------+
    +USA 11 月的平均 weather_state 为 (15) / 1 = 15 所以天气类型为 Cold。
    +Australia 11 月的平均 weather_state 为 (-2 + 0 + 3) / 3 = 0.333 所以天气类型为 Cold。
    +Peru 11 月的平均 weather_state 为 (25) / 1 = 25 所以天气类型为 Hot。
    +China 11 月的平均 weather_state 为 (16 + 18 + 21) / 3 = 18.333 所以天气类型为 Warm。
    +Morocco 11 月的平均 weather_state 为 (25 + 27 + 31) / 3 = 27.667 所以天气类型为 Hot。
    +我们并不知道 Spain 在 11 月的 weather_state 情况所以无需将他包含在结果中。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1295.leetcode1295 Find Numbers with Even Number of Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1295.leetcode1295 Find Numbers with Even Number of Digits-zh.md" new file mode 100644 index 00000000..d0e69520 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1295.leetcode1295 Find Numbers with Even Number of Digits-zh.md" @@ -0,0 +1,87 @@ +# [1295. 统计位数为偶数的数字](https://leetcode-cn.com/problems/find-numbers-with-even-number-of-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1295.Find%20Numbers%20with%20Even%20Number%20of%20Digits/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [12,345,2,6,7896]
    +输出:2
    +解释:
    +12 是 2 位数字(位数为偶数) 
    +345 是 3 位数字(位数为奇数)  
    +2 是 1 位数字(位数为奇数) 
    +6 是 1 位数字 位数为奇数) 
    +7896 是 4 位数字(位数为偶数)  
    +因此只有 12 和 7896 是位数为偶数的数字
    +
    + +

    示例 2:

    + +
    输入:nums = [555,901,482,1771]
    +输出:1 
    +解释: 
    +只有 1771 是位数为偶数的数字。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 500
    • +
    • 1 <= nums[i] <= 10^5
    • +
    + + +## 解法 + + + +首先将数组元素转换为字符串,判断字符串长度是否为偶数即可。 + + + +### **Python3** + + + +```python +class Solution: + def findNumbers(self, nums: List[int]) -> int: + res = 0 + for num in nums: + res += (len(str(num)) & 1) == 0 + return res +``` + +### **Java** + + + +```java +class Solution { + public int findNumbers(int[] nums) { + int res = 0; + for (int num : nums) { + res += (String.valueOf(num).length() & 1) == 0 ? 1 : 0; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1296.leetcode1296 Divide Array in Sets of K Consecutive Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1296.leetcode1296 Divide Array in Sets of K Consecutive Numbers-zh.md" new file mode 100644 index 00000000..62944a87 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1296.leetcode1296 Divide Array in Sets of K Consecutive Numbers-zh.md" @@ -0,0 +1,88 @@ +# [1296. 划分数组为连续数字的集合](https://leetcode-cn.com/problems/divide-array-in-sets-of-k-consecutive-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1296.Divide%20Array%20in%20Sets%20of%20K%20Consecutive%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个正整数 k,请你判断是否可以把这个数组划分成一些由 k 个连续数字组成的集合。
    +如果可以,请返回 True;否则,返回 False

    + +

     

    + +

    注意:此题目与 846 重复:https://leetcode-cn.com/problems/hand-of-straights/

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,3,4,4,5,6], k = 4
    +输出:true
    +解释:数组可以分成 [1,2,3,4] 和 [3,4,5,6]。
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
    +输出:true
    +解释:数组可以分成 [1,2,3] , [2,3,4] , [3,4,5] 和 [9,10,11]。
    +
    + +

    示例 3:

    + +
    +输入:nums = [3,3,2,2,1,1], k = 3
    +输出:true
    +
    + +

    示例 4:

    + +
    +输入:nums = [1,2,3,4], k = 3
    +输出:false
    +解释:数组不能分成几个大小为 3 的子数组。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^9
    • +
    • 1 <= k <= nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1297.leetcode1297 Maximum Number of Occurrences of a Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1297.leetcode1297 Maximum Number of Occurrences of a Substring-zh.md" new file mode 100644 index 00000000..3b4012d9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1297.leetcode1297 Maximum Number of Occurrences of a Substring-zh.md" @@ -0,0 +1,85 @@ +# [1297. 子串的最大出现次数](https://leetcode-cn.com/problems/maximum-number-of-occurrences-of-a-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1297.Maximum%20Number%20of%20Occurrences%20of%20a%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,请你返回满足以下条件且出现次数最大的 任意 子串的出现次数:

    + +
      +
    • 子串中不同字母的数目必须小于等于 maxLetters
    • +
    • 子串的长度必须大于等于 minSize 且小于等于 maxSize
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
    +输出:2
    +解释:子串 "aab" 在原字符串中出现了 2 次。
    +它满足所有的要求:2 个不同的字母,长度为 3 (在 minSize 和 maxSize 范围内)。
    +
    + +

    示例 2:

    + +
    输入:s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
    +输出:2
    +解释:子串 "aaa" 在原字符串中出现了 2 次,且它们有重叠部分。
    +
    + +

    示例 3:

    + +
    输入:s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3
    +输出:3
    +
    + +

    示例 4:

    + +
    输入:s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • 1 <= maxLetters <= 26
    • +
    • 1 <= minSize <= maxSize <= min(26, s.length)
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1298.leetcode1298 Maximum Candies You Can Get from Boxes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1298.leetcode1298 Maximum Candies You Can Get from Boxes-zh.md" new file mode 100644 index 00000000..95275731 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1298.leetcode1298 Maximum Candies You Can Get from Boxes-zh.md" @@ -0,0 +1,111 @@ +# [1298. 你能从盒子里获得的最大糖果数](https://leetcode-cn.com/problems/maximum-candies-you-can-get-from-boxes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1298.Maximum%20Candies%20You%20Can%20Get%20from%20Boxes/README_EN.md) + +## 题目描述 + + + +

    给你 n 个盒子,每个盒子的格式为 [status, candies, keys, containedBoxes] ,其中:

    + +
      +
    • 状态字 status[i]:整数,如果 box[i] 是开的,那么是 ,否则是
    • +
    • 糖果数 candies[i]: 整数,表示 box[i] 中糖果的数目。
    • +
    • 钥匙 keys[i]:数组,表示你打开 box[i] 后,可以得到一些盒子的钥匙,每个元素分别为该钥匙对应盒子的下标。
    • +
    • 内含的盒子 containedBoxes[i]:整数,表示放在 box[i] 里的盒子所对应的下标。
    • +
    + +

    给你一个 initialBoxes 数组,表示你现在得到的盒子,你可以获得里面的糖果,也可以用盒子里的钥匙打开新的盒子,还可以继续探索从这个盒子里找到的其他盒子。

    + +

    请你按照上述规则,返回可以获得糖果的 最大数目 

    + +

     

    + +

    示例 1:

    + +
    输入:status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
    +输出:16
    +解释:
    +一开始你有盒子 0 。你将获得它里面的 7 个糖果和盒子 1 和 2。
    +盒子 1 目前状态是关闭的,而且你还没有对应它的钥匙。所以你将会打开盒子 2 ,并得到里面的 4 个糖果和盒子 1 的钥匙。
    +在盒子 1 中,你会获得 5 个糖果和盒子 3 ,但是你没法获得盒子 3 的钥匙所以盒子 3 会保持关闭状态。
    +你总共可以获得的糖果数目 = 7 + 4 + 5 = 16 个。
    +
    + +

    示例 2:

    + +
    输入:status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
    +输出:6
    +解释:
    +你一开始拥有盒子 0 。打开它你可以找到盒子 1,2,3,4,5 和它们对应的钥匙。
    +打开这些盒子,你将获得所有盒子的糖果,所以总糖果数为 6 个。
    +
    + +

    示例 3:

    + +
    输入:status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []
    +输出:0
    +
    + +

    示例 5:

    + +
    输入:status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= status.length <= 1000
    • +
    • status.length == candies.length == keys.length == containedBoxes.length == n
    • +
    • status[i] 要么是 0 要么是 1
    • +
    • 1 <= candies[i] <= 1000
    • +
    • 0 <= keys[i].length <= status.length
    • +
    • 0 <= keys[i][j] < status.length
    • +
    • keys[i] 中的值都是互不相同的。
    • +
    • 0 <= containedBoxes[i].length <= status.length
    • +
    • 0 <= containedBoxes[i][j] < status.length
    • +
    • containedBoxes[i] 中的值都是互不相同的。
    • +
    • 每个盒子最多被一个盒子包含。
    • +
    • 0 <= initialBoxes.length <= status.length
    • +
    • 0 <= initialBoxes[i] < status.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1299.leetcode1299 Replace Elements with Greatest Element on Right Side-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1299.leetcode1299 Replace Elements with Greatest Element on Right Side-zh.md" new file mode 100644 index 00000000..33ae681d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1299.leetcode1299 Replace Elements with Greatest Element on Right Side-zh.md" @@ -0,0 +1,91 @@ +# [1299. 将每个元素替换为右侧最大元素](https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1200-1299/1299.Replace%20Elements%20with%20Greatest%20Element%20on%20Right%20Side/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 arr ,请你将每个元素用它右边最大的元素替换,如果是最后一个元素,用 -1 替换。

    + +

    完成所有替换操作后,请你返回这个数组。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [17,18,5,4,6,1]
    +输出:[18,6,6,6,1,-1]
    +解释:
    +- 下标 0 的元素 --> 右侧最大元素是下标 1 的元素 (18)
    +- 下标 1 的元素 --> 右侧最大元素是下标 4 的元素 (6)
    +- 下标 2 的元素 --> 右侧最大元素是下标 4 的元素 (6)
    +- 下标 3 的元素 --> 右侧最大元素是下标 4 的元素 (6)
    +- 下标 4 的元素 --> 右侧最大元素是下标 5 的元素 (1)
    +- 下标 5 的元素 --> 右侧没有其他元素,替换为 -1
    +
    + +

    示例 2:

    + +
    +输入:arr = [400]
    +输出:[-1]
    +解释:下标 0 的元素右侧没有其他元素。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 104
    • +
    • 1 <= arr[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def replaceElements(self, arr: List[int]) -> List[int]: + m = -1 + for i in range(len(arr) - 1, -1, -1): + t = arr[i] + arr[i] = m + m = max(m, t) + return arr +``` + +### **Java** + + + +```java +class Solution { + public int[] replaceElements(int[] arr) { + for (int i = arr.length - 1, max = -1; i >= 0; --i) { + int t = arr[i]; + arr[i] = max; + max = Math.max(max, t); + } + return arr; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1300.leetcode1300 Sum of Mutated Array Closest to Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1300.leetcode1300 Sum of Mutated Array Closest to Target-zh.md" new file mode 100644 index 00000000..93fe8ad2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1300.leetcode1300 Sum of Mutated Array Closest to Target-zh.md" @@ -0,0 +1,74 @@ +# [1300. 转变数组后最接近目标值的数组和](https://leetcode-cn.com/problems/sum-of-mutated-array-closest-to-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1300.Sum%20of%20Mutated%20Array%20Closest%20to%20Target/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个目标值 target ,请你返回一个整数 value ,使得将数组中所有大于 value 的值变成 value 后,数组的和最接近  target (最接近表示两者之差的绝对值最小)。

    + +

    如果有多种使得和最接近 target 的方案,请你返回这些整数中的最小值。

    + +

    请注意,答案不一定是 arr 中的数字。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [4,9,3], target = 10
    +输出:3
    +解释:当选择 value 为 3 时,数组会变成 [3, 3, 3],和为 9 ,这是最接近 target 的方案。
    +
    + +

    示例 2:

    + +
    输入:arr = [2,3,5], target = 10
    +输出:5
    +
    + +

    示例 3:

    + +
    输入:arr = [60864,25176,27249,21296,20204], target = 56803
    +输出:11361
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^4
    • +
    • 1 <= arr[i], target <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1301.leetcode1301 Number of Paths with Max Score-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1301.leetcode1301 Number of Paths with Max Score-zh.md" new file mode 100644 index 00000000..20f77a61 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1301.leetcode1301 Number of Paths with Max Score-zh.md" @@ -0,0 +1,79 @@ +# [1301. 最大得分的路径数目](https://leetcode-cn.com/problems/number-of-paths-with-max-score) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1301.Number%20of%20Paths%20with%20Max%20Score/README_EN.md) + +## 题目描述 + + + +

    给你一个正方形字符数组 board ,你从数组最右下方的字符 'S' 出发。

    + +

    你的目标是到达数组最左上角的字符 'E' ,数组剩余的部分为数字字符 1, 2, ..., 9 或者障碍 'X'。在每一步移动中,你可以向上、向左或者左上方移动,可以移动的前提是到达的格子没有障碍。

    + +

    一条路径的 「得分」 定义为:路径上所有数字的和。

    + +

    请你返回一个列表,包含两个整数:第一个整数是 「得分」 的最大值,第二个整数是得到最大得分的方案数,请把结果对 10^9 + 7 取余

    + +

    如果没有任何路径可以到达终点,请返回 [0, 0]

    + +

     

    + +

    示例 1:

    + +
    +输入:board = ["E23","2X2","12S"]
    +输出:[7,1]
    +
    + +

    示例 2:

    + +
    +输入:board = ["E12","1X1","21S"]
    +输出:[4,2]
    +
    + +

    示例 3:

    + +
    +输入:board = ["E11","XXX","11S"]
    +输出:[0,0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= board.length == board[i].length <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1302.leetcode1302 Deepest Leaves Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1302.leetcode1302 Deepest Leaves Sum-zh.md" new file mode 100644 index 00000000..428b473e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1302.leetcode1302 Deepest Leaves Sum-zh.md" @@ -0,0 +1,67 @@ +# [1302. 层数最深叶子节点的和](https://leetcode-cn.com/problems/deepest-leaves-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1302.Deepest%20Leaves%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
    +输出:15
    +
    + +

    示例 2:

    + +
    +输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
    +输出:19
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数目在范围 [1, 104] 之间。
    • +
    • 1 <= Node.val <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1303.leetcode1303 Find the Team Size-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1303.leetcode1303 Find the Team Size-zh.md" new file mode 100644 index 00000000..415afb3b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1303.leetcode1303 Find the Team Size-zh.md" @@ -0,0 +1,99 @@ +# [1303. 求团队人数](https://leetcode-cn.com/problems/find-the-team-size) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1303.Find%20the%20Team%20Size/README_EN.md) + +## 题目描述 + + + +

    员工表:Employee

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| employee_id   | int     |
    +| team_id       | int     |
    ++---------------+---------+
    +employee_id 字段是这张表的主键,表中的每一行都包含每个员工的 ID 和他们所属的团队。
    +
    + +

    编写一个 SQL 查询,以求得每个员工所在团队的总人数。

    + +

    查询结果中的顺序无特定要求。

    + +

    查询结果格式示例如下:

    + +
    +Employee Table:
    ++-------------+------------+
    +| employee_id | team_id    |
    ++-------------+------------+
    +|     1       |     8      |
    +|     2       |     8      |
    +|     3       |     8      |
    +|     4       |     7      |
    +|     5       |     9      |
    +|     6       |     9      |
    ++-------------+------------+
    +Result table:
    ++-------------+------------+
    +| employee_id | team_size  |
    ++-------------+------------+
    +|     1       |     3      |
    +|     2       |     3      |
    +|     3       |     3      |
    +|     4       |     1      |
    +|     5       |     2      |
    +|     6       |     2      |
    ++-------------+------------+
    +ID 为 1、2、3 的员工是 team_id 为 8 的团队的成员,
    +ID 为 4 的员工是 team_id 为 7 的团队的成员,
    +ID 为 5、6 的员工是 team_id 为 9 的团队的成员。
    +
    + +## 解法 + + + + + +### **SQL** + +解法 1: + +```sql +# Write your MySQL query statement below +SELECT + e.employee_id, t.team_size +FROM + Employee e +LEFT JOIN + (SELECT + team_id, count(1) as team_size + FROM + Employee + GROUP BY + team_id + ) t +ON + e.team_id = t.team_id; +``` + +解法 2: + +```sql +# Write your MySQL query statement below +SELECT + e1.employee_id, count(*) as team_size +FROM + Employee e1 +LEFT JOIN + Employee e2 +ON + e1.team_id = e2.team_id +GROUP BY + e1.employee_id; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1304.leetcode1304 Find N Unique Integers Sum up to Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1304.leetcode1304 Find N Unique Integers Sum up to Zero-zh.md" new file mode 100644 index 00000000..b00ef257 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1304.leetcode1304 Find N Unique Integers Sum up to Zero-zh.md" @@ -0,0 +1,69 @@ +# [1304. 和为零的N个唯一整数](https://leetcode-cn.com/problems/find-n-unique-integers-sum-up-to-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1304.Find%20N%20Unique%20Integers%20Sum%20up%20to%20Zero/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,请你返回 任意 一个由 n 个 各不相同 的整数组成的数组,并且这 n 个数相加和为 0

    + +

     

    + +

    示例 1:

    + +
    输入:n = 5
    +输出:[-7,-1,1,3,4]
    +解释:这些数组也是正确的 [-5,-1,1,2,3],[-3,-1,2,-2,4]。
    +
    + +

    示例 2:

    + +
    输入:n = 3
    +输出:[-1,0,1]
    +
    + +

    示例 3:

    + +
    输入:n = 1
    +输出:[0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1305.leetcode1305 All Elements in Two Binary Search Trees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1305.leetcode1305 All Elements in Two Binary Search Trees-zh.md" new file mode 100644 index 00000000..daea16f9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1305.leetcode1305 All Elements in Two Binary Search Trees-zh.md" @@ -0,0 +1,87 @@ +# [1305. 两棵二叉搜索树中的所有元素](https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1305.All%20Elements%20in%20Two%20Binary%20Search%20Trees/README_EN.md) + +## 题目描述 + + + +

    给你 root1root2 这两棵二叉搜索树。

    + +

    请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root1 = [2,1,4], root2 = [1,0,3]
    +输出:[0,1,1,2,3,4]
    +
    + +

    示例 2:

    + +
    输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
    +输出:[-10,0,0,1,2,5,7,10]
    +
    + +

    示例 3:

    + +
    输入:root1 = [], root2 = [5,1,7,0,2]
    +输出:[0,1,2,5,7]
    +
    + +

    示例 4:

    + +
    输入:root1 = [0,-10,10], root2 = []
    +输出:[-10,0,10]
    +
    + +

    示例 5:

    + +

    + +
    输入:root1 = [1,null,8], root2 = [8,1]
    +输出:[1,1,8,8]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每棵树最多有 5000 个节点。
    • +
    • 每个节点的值在 [-10^5, 10^5] 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1306.leetcode1306 Jump Game III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1306.leetcode1306 Jump Game III-zh.md" new file mode 100644 index 00000000..299c07f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1306.leetcode1306 Jump Game III-zh.md" @@ -0,0 +1,82 @@ +# [1306. 跳跃游戏 III](https://leetcode-cn.com/problems/jump-game-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1306.Jump%20Game%20III/README_EN.md) + +## 题目描述 + + + +

    这里有一个非负整数数组 arr,你最开始位于该数组的起始下标 start 处。当你位于下标 i 处时,你可以跳到 i + arr[i] 或者 i - arr[i]

    + +

    请你判断自己是否能够跳到对应元素值为 0 的 任一 下标处。

    + +

    注意,不管是什么情况下,你都无法跳到数组之外。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [4,2,3,0,3,1,2], start = 5
    +输出:true
    +解释:
    +到达值为 0 的下标 3 有以下可能方案: 
    +下标 5 -> 下标 4 -> 下标 1 -> 下标 3 
    +下标 5 -> 下标 6 -> 下标 4 -> 下标 1 -> 下标 3 
    +
    + +

    示例 2:

    + +
    输入:arr = [4,2,3,0,3,1,2], start = 0
    +输出:true 
    +解释:
    +到达值为 0 的下标 3 有以下可能方案: 
    +下标 0 -> 下标 4 -> 下标 1 -> 下标 3
    +
    + +

    示例 3:

    + +
    输入:arr = [3,0,2,1,2], start = 2
    +输出:false
    +解释:无法到达值为 0 的下标 1 处。 
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 5 * 10^4
    • +
    • 0 <= arr[i] < arr.length
    • +
    • 0 <= start < arr.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1307.leetcode1307 Verbal Arithmetic Puzzle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1307.leetcode1307 Verbal Arithmetic Puzzle-zh.md" new file mode 100644 index 00000000..f7b48d8f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1307.leetcode1307 Verbal Arithmetic Puzzle-zh.md" @@ -0,0 +1,90 @@ +# [1307. 口算难题](https://leetcode-cn.com/problems/verbal-arithmetic-puzzle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1307.Verbal%20Arithmetic%20Puzzle/README_EN.md) + +## 题目描述 + + + +

    给你一个方程,左边用 words 表示,右边用 result 表示。

    + +

    你需要根据以下规则检查方程是否可解:

    + +
      +
    • 每个字符都会被解码成一位数字(0 - 9)。
    • +
    • 每对不同的字符必须映射到不同的数字。
    • +
    • 每个 words[i]result 都会被解码成一个没有前导零的数字。
    • +
    • 左侧数字之和(words)等于右侧数字(result)。 
    • +
    + +

    如果方程可解,返回 True,否则返回 False

    + +

     

    + +

    示例 1:

    + +
    输入:words = ["SEND","MORE"], result = "MONEY"
    +输出:true
    +解释:映射 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
    +所以 "SEND" + "MORE" = "MONEY" ,  9567 + 1085 = 10652
    + +

    示例 2:

    + +
    输入:words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
    +输出:true
    +解释:映射 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
    +所以 "SIX" + "SEVEN" + "SEVEN" = "TWENTY" ,  650 + 68782 + 68782 = 138214
    + +

    示例 3:

    + +
    输入:words = ["THIS","IS","TOO"], result = "FUNNY"
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:words = ["LEET","CODE"], result = "POINT"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= words.length <= 5
    • +
    • 1 <= words[i].length, results.length <= 7
    • +
    • words[i], result 只含有大写英文字母
    • +
    • 表达式中使用的不同字符数最大为 10
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1308.leetcode1308 Running Total for Different Genders-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1308.leetcode1308 Running Total for Different Genders-zh.md" new file mode 100644 index 00000000..f72b444e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1308.leetcode1308 Running Total for Different Genders-zh.md" @@ -0,0 +1,87 @@ +# [1308. 不同性别每日分数总计](https://leetcode-cn.com/problems/running-total-for-different-genders) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1308.Running%20Total%20for%20Different%20Genders/README_EN.md) + +## 题目描述 + + + +

    表: Scores

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| player_name   | varchar |
    +| gender        | varchar |
    +| day           | date    |
    +| score_points  | int     |
    ++---------------+---------+
    +(gender, day)是该表的主键
    +一场比赛是在女队和男队之间举行的
    +该表的每一行表示一个名叫 (player_name) 性别为 (gender) 的参赛者在某一天获得了 (score_points) 的分数
    +如果参赛者是女性,那么 gender 列为 'F',如果参赛者是男性,那么 gender 列为 'M'
    +
    + +

     

    + +

    写一条SQL语句查询每种性别在每一天的总分,并按性别和日期对查询结果排序

    + +

    下面是查询结果格式的例子:

    + +
    +Scores表:
    ++-------------+--------+------------+--------------+
    +| player_name | gender | day        | score_points |
    ++-------------+--------+------------+--------------+
    +| Aron        | F      | 2020-01-01 | 17           |
    +| Alice       | F      | 2020-01-07 | 23           |
    +| Bajrang     | M      | 2020-01-07 | 7            |
    +| Khali       | M      | 2019-12-25 | 11           |
    +| Slaman      | M      | 2019-12-30 | 13           |
    +| Joe         | M      | 2019-12-31 | 3            |
    +| Jose        | M      | 2019-12-18 | 2            |
    +| Priya       | F      | 2019-12-31 | 23           |
    +| Priyanka    | F      | 2019-12-30 | 17           |
    ++-------------+--------+------------+--------------+
    +结果表:
    ++--------+------------+-------+
    +| gender | day        | total |
    ++--------+------------+-------+
    +| F      | 2019-12-30 | 17    |
    +| F      | 2019-12-31 | 40    |
    +| F      | 2020-01-01 | 57    |
    +| F      | 2020-01-07 | 80    |
    +| M      | 2019-12-18 | 2     |
    +| M      | 2019-12-25 | 13    |
    +| M      | 2019-12-30 | 26    |
    +| M      | 2019-12-31 | 29    |
    +| M      | 2020-01-07 | 36    |
    ++--------+------------+-------+
    +女性队伍:
    +第一天是 2019-12-30,Priyanka 获得 17 分,队伍的总分是 17 分
    +第二天是 2019-12-31, Priya 获得 23 分,队伍的总分是 40 分
    +第三天是 2020-01-01, Aron 获得 17 分,队伍的总分是 57 分
    +第四天是 2020-01-07, Alice 获得 23 分,队伍的总分是 80 分
    +男性队伍:
    +第一天是 2019-12-18, Jose 获得 2 分,队伍的总分是 2 分
    +第二天是 2019-12-25, Khali 获得 11 分,队伍的总分是 13 分
    +第三天是 2019-12-30, Slaman 获得 13 分,队伍的总分是 26 分
    +第四天是 2019-12-31, Joe 获得 3 分,队伍的总分是 29 分
    +第五天是 2020-01-07, Bajrang 获得 7 分,队伍的总分是 36 分
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1309.leetcode1309 Decrypt String from Alphabet to Integer Mapping-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1309.leetcode1309 Decrypt String from Alphabet to Integer Mapping-zh.md" new file mode 100644 index 00000000..3f613ef3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1309.leetcode1309 Decrypt String from Alphabet to Integer Mapping-zh.md" @@ -0,0 +1,86 @@ +# [1309. 解码字母到整数映射](https://leetcode-cn.com/problems/decrypt-string-from-alphabet-to-integer-mapping) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1309.Decrypt%20String%20from%20Alphabet%20to%20Integer%20Mapping/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,它由数字('0' - '9')和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符:

    + +
      +
    • 字符('a' - 'i')分别用('1''9')表示。
    • +
    • 字符('j' - 'z')分别用('10#' - '26#')表示。 
    • +
    + +

    返回映射之后形成的新字符串。

    + +

    题目数据保证映射始终唯一。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "10#11#12"
    +输出:"jkab"
    +解释:"j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
    +
    + +

    示例 2:

    + +
    输入:s = "1326#"
    +输出:"acz"
    +
    + +

    示例 3:

    + +
    输入:s = "25#"
    +输出:"y"
    +
    + +

    示例 4:

    + +
    输入:s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
    +输出:"abcdefghijklmnopqrstuvwxyz"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] 只包含数字('0'-'9')和 '#' 字符。
    • +
    • s 是映射始终存在的有效字符串。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1310.leetcode1310 XOR Queries of a Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1310.leetcode1310 XOR Queries of a Subarray-zh.md" new file mode 100644 index 00000000..f61b80e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1310.leetcode1310 XOR Queries of a Subarray-zh.md" @@ -0,0 +1,125 @@ +# [1310. 子数组异或查询](https://leetcode-cn.com/problems/xor-queries-of-a-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1310.XOR%20Queries%20of%20a%20Subarray/README_EN.md) + +## 题目描述 + + + +

    有一个正整数数组 arr,现给你一个对应的查询数组 queries,其中 queries[i] = [Li, Ri]

    + +

    对于每个查询 i,请你计算从 Li 到 Ri 的 XOR 值(即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri])作为本次查询的结果。

    + +

    并返回一个包含给定查询 queries 所有结果的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
    +输出:[2,7,14,8] 
    +解释:
    +数组中元素的二进制表示形式是:
    +1 = 0001 
    +3 = 0011 
    +4 = 0100 
    +8 = 1000 
    +查询的 XOR 值为:
    +[0,1] = 1 xor 3 = 2 
    +[1,2] = 3 xor 4 = 7 
    +[0,3] = 1 xor 3 xor 4 xor 8 = 14 
    +[3,3] = 8
    +
    + +

    示例 2:

    + +
    输入:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
    +输出:[8,0,4,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 3 * 10^4
    • +
    • 1 <= arr[i] <= 10^9
    • +
    • 1 <= queries.length <= 3 * 10^4
    • +
    • queries[i].length == 2
    • +
    • 0 <= queries[i][0] <= queries[i][1] < arr.length
    • +
    + +## 解法 + + + +由于 `A ^ B = C` => `A ^ A ^ B = A ^ C` => `B = A ^ C`。因此,我们求解 `arr[l] ^ ... ^ arr[r]`,可以转换为求解 `arr[0] ^ ... ^ arr[l - 1]` ^ `arr[0] ^ ... ^ ... ^ arr[r]`。 + +所以,我们先求解前缀异或,再进行两数异或即可求得每一个 query 的结果。 + + + +### **Python3** + + + +```python +class Solution: + def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: + pre_xor = [0] * (len(arr) + 1) + for i in range(1, len(arr) + 1): + pre_xor[i] = pre_xor[i - 1] ^ arr[i - 1] + return [pre_xor[l] ^ pre_xor[r + 1] for l, r in queries] +``` + +### **Java** + + + +```java +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + int[] preXor = new int[arr.length + 1]; + for (int i = 1; i <= arr.length; ++i) { + preXor[i] = preXor[i - 1] ^ arr[i - 1]; + } + int[] res = new int[queries.length]; + for (int i = 0; i < queries.length; ++i) { + int l = queries[i][0], r = queries[i][1]; + res[i] = preXor[l] ^ preXor[r + 1]; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @param {number[][]} queries + * @return {number[]} + */ +var xorQueries = function(arr, queries) { + let n = arr.length; + let xors = new Array(n + 1).fill(0); + for (let i = 0; i < n; i++) { + xors[i + 1] = xors[i] ^ arr[i]; + } + let res = []; + for (let query of queries) { + let [start, end] = query; + res.push(xors[start] ^ xors[end + 1]); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1311.leetcode1311 Get Watched Videos by Your Friends-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1311.leetcode1311 Get Watched Videos by Your Friends-zh.md" new file mode 100644 index 00000000..867f629c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1311.leetcode1311 Get Watched Videos by Your Friends-zh.md" @@ -0,0 +1,89 @@ +# [1311. 获取你好友已观看的视频](https://leetcode-cn.com/problems/get-watched-videos-by-your-friends) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1311.Get%20Watched%20Videos%20by%20Your%20Friends/README_EN.md) + +## 题目描述 + + + +

    有 n 个人,每个人都有一个  0 到 n-1 的唯一 id 。

    + +

    给你数组 watchedVideos  和 friends ,其中 watchedVideos[i]  和 friends[i] 分别表示 id = i 的人观看过的视频列表和他的好友列表。

    + +

    Level 1 的视频包含所有你好友观看过的视频,level 2 的视频包含所有你好友的好友观看过的视频,以此类推。一般的,Level 为 k 的视频包含所有从你出发,最短距离为 k 的好友观看过的视频。

    + +

    给定你的 id  和一个 level 值,请你找出所有指定 level 的视频,并将它们按观看频率升序返回。如果有频率相同的视频,请将它们按字母顺序从小到大排列。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
    +输出:["B","C"] 
    +解释:
    +你的 id 为 0(绿色),你的朋友包括(黄色):
    +id 为 1 -> watchedVideos = ["C"] 
    +id 为 2 -> watchedVideos = ["B","C"] 
    +你朋友观看过视频的频率为:
    +B -> 1 
    +C -> 2
    +
    + +

    示例 2:

    + +

    + +
    输入:watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
    +输出:["D"]
    +解释:
    +你的 id 为 0(绿色),你朋友的朋友只有一个人,他的 id 为 3(黄色)。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == watchedVideos.length == friends.length
    • +
    • 2 <= n <= 100
    • +
    • 1 <= watchedVideos[i].length <= 100
    • +
    • 1 <= watchedVideos[i][j].length <= 8
    • +
    • 0 <= friends[i].length < n
    • +
    • 0 <= friends[i][j] < n
    • +
    • 0 <= id < n
    • +
    • 1 <= level < n
    • +
    • 如果 friends[i] 包含 j ,那么 friends[j] 包含 i
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1312.leetcode1312 Minimum Insertion Steps to Make a String Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1312.leetcode1312 Minimum Insertion Steps to Make a String Palindrome-zh.md" new file mode 100644 index 00000000..f357a7e2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1312.leetcode1312 Minimum Insertion Steps to Make a String Palindrome-zh.md" @@ -0,0 +1,93 @@ +# [1312. 让字符串成为回文串的最少插入次数](https://leetcode-cn.com/problems/minimum-insertion-steps-to-make-a-string-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1312.Minimum%20Insertion%20Steps%20to%20Make%20a%20String%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。

    + +

    请你返回让 s 成为回文串的 最少操作次数 。

    + +

    「回文串」是正读和反读都相同的字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "zzazz"
    +输出:0
    +解释:字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。
    +
    + +

    示例 2:

    + +
    +输入:s = "mbadm"
    +输出:2
    +解释:字符串可变为 "mbdadbm" 或者 "mdbabdm" 。
    +
    + +

    示例 3:

    + +
    +输入:s = "leetcode"
    +输出:5
    +解释:插入 5 个字符后字符串变为 "leetcodocteel" 。
    +
    + +

    示例 4:

    + +
    +输入:s = "g"
    +输出:0
    +
    + +

    示例 5:

    + +
    +输入:s = "no"
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 中所有字符都是小写字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1313.leetcode1313 Decompress Run-Length Encoded List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1313.leetcode1313 Decompress Run-Length Encoded List-zh.md" new file mode 100644 index 00000000..80a1eee7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1313.leetcode1313 Decompress Run-Length Encoded List-zh.md" @@ -0,0 +1,72 @@ +# [1313. 解压缩编码列表](https://leetcode-cn.com/problems/decompress-run-length-encoded-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1313.Decompress%20Run-Length%20Encoded%20List/README_EN.md) + +## 题目描述 + + + +

    给你一个以行程长度编码压缩的整数列表 nums 。

    + +

    考虑每对相邻的两个元素 [freq, val] = [nums[2*i], nums[2*i+1]] (其中 i >= 0 ),每一对都表示解压后子列表中有 freq 个值为 val 的元素,你需要从左到右连接所有子列表以生成解压后的列表。

    + +

    请你返回解压后的列表。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,4]
    +输出:[2,4,4,4]
    +解释:第一对 [1,2] 代表着 2 的出现频次为 1,所以生成数组 [2]。
    +第二对 [3,4] 代表着 4 的出现频次为 3,所以生成数组 [4,4,4]。
    +最后将它们串联到一起 [2] + [4,4,4] = [2,4,4,4]。
    + +

    示例 2:

    + +
    +输入:nums = [1,1,2,3]
    +输出:[1,3,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 100
    • +
    • nums.length % 2 == 0
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1314.leetcode1314 Matrix Block Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1314.leetcode1314 Matrix Block Sum-zh.md" new file mode 100644 index 00000000..2d929a92 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1314.leetcode1314 Matrix Block Sum-zh.md" @@ -0,0 +1,194 @@ +# [1314. 矩阵区域和](https://leetcode-cn.com/problems/matrix-block-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1314.Matrix%20Block%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的矩阵 mat 和一个整数 K ,请你返回一个矩阵 answer ,其中每个 answer[i][j] 是所有满足下述条件的元素 mat[r][c] 的和: 

    + +
      +
    • i - K <= r <= i + K, j - K <= c <= j + K 
    • +
    • (r, c) 在矩阵内。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1
    +输出:[[12,21,16],[27,45,33],[24,39,28]]
    +
    + +

    示例 2:

    + +
    输入:mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2
    +输出:[[45,45,45],[45,45,45],[45,45,45]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n, K <= 100
    • +
    • 1 <= mat[i][j] <= 100
    • +
    + + +## 解法 + + + +动态规划-二维前缀和。 + + + +### **Python3** + + + +```python +class Solution: + def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: + m, n = len(mat), len(mat[0]) + pre = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + mat[i - 1][j - 1] + + def get(i, j): + i = max(min(m, i), 0) + j = max(min(n, j), 0) + return pre[i][j] + + ans = [[0] * n for _ in range(m)] + for i in range(m): + for j in range(n): + ans[i][j] = get(i + k + 1, j + k + 1) - get(i + k + 1, j - k) - get(i - k, j + k + 1) + get(i - k, j - k) + return ans +``` + +### **Java** + + + +```java +class Solution { + private int[][] pre; + private int m; + private int n; + public int[][] matrixBlockSum(int[][] mat, int k) { + int m = mat.length, n = mat[0].length; + int[][] pre = new int[m + 1][n + 1]; + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] + - pre[i - 1][j - 1] + mat[i - 1][j - 1]; + } + } + this.pre = pre; + this.m = m; + this.n = n; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = get(i + k + 1, j + k + 1) - get(i + k + 1, j - k) - get(i - k, j + k + 1) + get(i - k, j - k); + } + } + return ans; + } + + private int get(int i, int j) { + i = Math.max(Math.min(m, i), 0); + j = Math.max(Math.min(n, j), 0); + return pre[i][j]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector> matrixBlockSum(vector>& mat, int k) { + int m = mat.size(), n = mat[0].size(); + vector> pre(m + 1, vector(n + 1)); + for (int i = 1; i < m + 1; ++i) { + for (int j = 1; j < n + 1; ++j) { + pre[i][j] = pre[i - 1][j] + pre[i][j - 1] + - pre[i - 1][j - 1] + mat[i - 1][j - 1]; + } + } + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = get(i + k + 1, j + k + 1, m, n, pre) - get(i + k + 1, j - k, m, n, pre) - get(i - k, j + k + 1, m, n, pre) + get(i - k, j - k, m, n, pre); + } + } + return ans; + } + + int get(int i, int j, int m, int n, vector>& pre) { + i = max(min(m, i), 0); + j = max(min(n, j), 0); + return pre[i][j]; + } +}; +``` + +### **Go** + +```go +func matrixBlockSum(mat [][]int, k int) [][]int { + m, n := len(mat), len(mat[0]) + pre := make([][]int, m+1) + for i := 0; i < m+1; i++ { + pre[i] = make([]int, n+1) + } + for i := 1; i < m+1; i++ { + for j := 1; j < n+1; j++ { + pre[i][j] = pre[i-1][j] + pre[i][j-1] + -pre[i-1][j-1] + mat[i-1][j-1] + } + } + + get := func(i, j int) int { + i = max(min(m, i), 0) + j = max(min(n, j), 0) + return pre[i][j] + } + + ans := make([][]int, m) + for i := 0; i < m; i++ { + ans[i] = make([]int, n) + for j := 0; j < n; j++ { + ans[i][j] = get(i+k+1, j+k+1) - get(i+k+1, j-k) - get(i-k, j+k+1) + get(i-k, j-k) + } + } + return ans +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1315.leetcode1315 Sum of Nodes with Even-Valued Grandparent-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1315.leetcode1315 Sum of Nodes with Even-Valued Grandparent-zh.md" new file mode 100644 index 00000000..c178b1e1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1315.leetcode1315 Sum of Nodes with Even-Valued Grandparent-zh.md" @@ -0,0 +1,66 @@ +# [1315. 祖父节点值为偶数的节点和](https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1315.Sum%20of%20Nodes%20with%20Even-Valued%20Grandparent/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树,请你返回满足以下条件的所有节点的值之和:

    + +
      +
    • 该节点的祖父节点的值为偶数。(一个节点的祖父节点是指该节点的父节点的父节点。)
    • +
    + +

    如果不存在祖父节点值为偶数的节点,那么返回 0

    + +

     

    + +

    示例:

    + +

    + +
    输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
    +输出:18
    +解释:图中红色节点的祖父节点的值为偶数,蓝色节点为这些红色节点的祖父节点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数目在 1 到 10^4 之间。
    • +
    • 每个节点的值在 1 到 100 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1316.leetcode1316 Distinct Echo Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1316.leetcode1316 Distinct Echo Substrings-zh.md" new file mode 100644 index 00000000..3bd193d4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1316.leetcode1316 Distinct Echo Substrings-zh.md" @@ -0,0 +1,71 @@ +# [1316. 不同的循环子字符串](https://leetcode-cn.com/problems/distinct-echo-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1316.Distinct%20Echo%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 text ,请你返回满足下述条件的 不同 非空子字符串的数目:

    + +
      +
    • 可以写成某个字符串与其自身相连接的形式(即,可以写为 a + a,其中 a 是某个字符串)。
    • +
    + +

    例如,abcabc 就是 abc 和它自身连接形成的。

    + +

     

    + +

    示例 1:

    + +
    输入:text = "abcabcabc"
    +输出:3
    +解释:3 个子字符串分别为 "abcabc","bcabca" 和 "cabcab" 。
    +
    + +

    示例 2:

    + +
    输入:text = "leetcodeleetcode"
    +输出:2
    +解释:2 个子字符串为 "ee" 和 "leetcodeleetcode" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text.length <= 2000
    • +
    • text 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1317.leetcode1317 Convert Integer to the Sum of Two No-Zero Integers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1317.leetcode1317 Convert Integer to the Sum of Two No-Zero Integers-zh.md" new file mode 100644 index 00000000..23ac7ec0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1317.leetcode1317 Convert Integer to the Sum of Two No-Zero Integers-zh.md" @@ -0,0 +1,92 @@ +# [1317. 将整数转换为两个无零整数的和](https://leetcode-cn.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1317.Convert%20Integer%20to%20the%20Sum%20of%20Two%20No-Zero%20Integers/README_EN.md) + +## 题目描述 + + + +

    「无零整数」是十进制表示中 不含任何 0 的正整数。

    + +

    给你一个整数 n,请你返回一个 由两个整数组成的列表 [A, B],满足:

    + +
      +
    • AB 都是无零整数
    • +
    • A + B = n
    • +
    + +

    题目数据保证至少有一个有效的解决方案。

    + +

    如果存在多个有效解决方案,你可以返回其中任意一个。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 2
    +输出:[1,1]
    +解释:A = 1, B = 1. A + B = n 并且 A 和 B 的十进制表示形式都不包含任何 0 。
    +
    + +

    示例 2:

    + +
    输入:n = 11
    +输出:[2,9]
    +
    + +

    示例 3:

    + +
    输入:n = 10000
    +输出:[1,9999]
    +
    + +

    示例 4:

    + +
    输入:n = 69
    +输出:[1,68]
    +
    + +

    示例 5:

    + +
    输入:n = 1010
    +输出:[11,999]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1318.leetcode1318 Minimum Flips to Make a OR b Equal to c-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1318.leetcode1318 Minimum Flips to Make a OR b Equal to c-zh.md" new file mode 100644 index 00000000..4e7a92f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1318.leetcode1318 Minimum Flips to Make a OR b Equal to c-zh.md" @@ -0,0 +1,76 @@ +# [1318. 或运算的最小翻转次数](https://leetcode-cn.com/problems/minimum-flips-to-make-a-or-b-equal-to-c) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1318.Minimum%20Flips%20to%20Make%20a%20OR%20b%20Equal%20to%20c/README_EN.md) + +## 题目描述 + + + +

    给你三个正整数 abc

    + +

    你可以对 ab 的二进制表示进行位翻转操作,返回能够使按位或运算   a OR b == c  成立的最小翻转次数。

    + +

    「位翻转操作」是指将一个数的二进制表示任何单个位上的 1 变成 0 或者 0 变成 1 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:a = 2, b = 6, c = 5
    +输出:3
    +解释:翻转后 a = 1 , b = 4 , c = 5 使得 a OR b == c
    + +

    示例 2:

    + +
    输入:a = 4, b = 2, c = 7
    +输出:1
    +
    + +

    示例 3:

    + +
    输入:a = 1, b = 2, c = 3
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= a <= 10^9
    • +
    • 1 <= b <= 10^9
    • +
    • 1 <= c <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1319.leetcode1319 Number of Operations to Make Network Connected-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1319.leetcode1319 Number of Operations to Make Network Connected-zh.md" new file mode 100644 index 00000000..ce172e97 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1319.leetcode1319 Number of Operations to Make Network Connected-zh.md" @@ -0,0 +1,90 @@ +# [1319. 连通网络的操作次数](https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1319.Number%20of%20Operations%20to%20Make%20Network%20Connected/README_EN.md) + +## 题目描述 + + + +

    用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b

    + +

    网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。

    + +

    给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。 

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 4, connections = [[0,1],[0,2],[1,2]]
    +输出:1
    +解释:拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
    +输出:-1
    +解释:线缆数量不足。
    +
    + +

    示例 4:

    + +
    输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • 1 <= connections.length <= min(n*(n-1)/2, 10^5)
    • +
    • connections[i].length == 2
    • +
    • 0 <= connections[i][0], connections[i][1] < n
    • +
    • connections[i][0] != connections[i][1]
    • +
    • 没有重复的连接。
    • +
    • 两台计算机不会通过多条线缆连接。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1320.leetcode1320 Minimum Distance to Type a Word Using Two Fingers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1320.leetcode1320 Minimum Distance to Type a Word Using Two Fingers-zh.md" new file mode 100644 index 00000000..946e9ef0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1320.leetcode1320 Minimum Distance to Type a Word Using Two Fingers-zh.md" @@ -0,0 +1,96 @@ +# [1320. 二指输入的的最小距离](https://leetcode-cn.com/problems/minimum-distance-to-type-a-word-using-two-fingers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1320.Minimum%20Distance%20to%20Type%20a%20Word%20Using%20Two%20Fingers/README_EN.md) + +## 题目描述 + + + +

    + +

    二指输入法定制键盘在 XY 平面上的布局如上图所示,其中每个大写英文字母都位于某个坐标处,例如字母 A 位于坐标 (0,0),字母 B 位于坐标 (0,1),字母 P 位于坐标 (2,3) 且字母 Z 位于坐标 (4,1)

    + +

    给你一个待输入字符串 word,请你计算并返回在仅使用两根手指的情况下,键入该字符串需要的最小移动总距离。坐标 (x1,y1)(x2,y2) 之间的距离是 |x1 - x2| + |y1 - y2|。 

    + +

    注意,两根手指的起始位置是零代价的,不计入移动总距离。你的两根手指的起始位置也不必从首字母或者前两个字母开始。

    + +

     

    + +

    示例 1:

    + +
    输入:word = "CAKE"
    +输出:3
    +解释: 
    +使用两根手指输入 "CAKE" 的最佳方案之一是: 
    +手指 1 在字母 'C' 上 -> 移动距离 = 0 
    +手指 1 在字母 'A' 上 -> 移动距离 = 从字母 'C' 到字母 'A' 的距离 = 2 
    +手指 2 在字母 'K' 上 -> 移动距离 = 0 
    +手指 2 在字母 'E' 上 -> 移动距离 = 从字母 'K' 到字母 'E' 的距离  = 1 
    +总距离 = 3
    +
    + +

    示例 2:

    + +
    输入:word = "HAPPY"
    +输出:6
    +解释: 
    +使用两根手指输入 "HAPPY" 的最佳方案之一是:
    +手指 1 在字母 'H' 上 -> 移动距离 = 0
    +手指 1 在字母 'A' 上 -> 移动距离 = 从字母 'H' 到字母 'A' 的距离 = 2
    +手指 2 在字母 'P' 上 -> 移动距离 = 0
    +手指 2 在字母 'P' 上 -> 移动距离 = 从字母 'P' 到字母 'P' 的距离 = 0
    +手指 1 在字母 'Y' 上 -> 移动距离 = 从字母 'A' 到字母 'Y' 的距离 = 4
    +总距离 = 6
    +
    + +

    示例 3:

    + +
    输入:word = "NEW"
    +输出:3
    +
    + +

    示例 4:

    + +
    输入:word = "YEAR"
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= word.length <= 300
    • +
    • 每个 word[i] 都是一个大写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1321.leetcode1321 Restaurant Growth-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1321.leetcode1321 Restaurant Growth-zh.md" new file mode 100644 index 00000000..f0ea2d62 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1321.leetcode1321 Restaurant Growth-zh.md" @@ -0,0 +1,85 @@ +# [1321. 餐馆营业额变化增长](https://leetcode-cn.com/problems/restaurant-growth) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1321.Restaurant%20Growth/README_EN.md) + +## 题目描述 + + + +

    表: Customer

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    +| visited_on    | date    |
    +| amount        | int     |
    ++---------------+---------+
    +(customer_id, visited_on) 是该表的主键
    +该表包含一家餐馆的顾客交易数据
    +visited_on 表示 (customer_id) 的顾客在 visited_on 那天访问了餐馆
    +amount 是一个顾客某一天的消费总额
    +
    + +

     

    + +

    你是餐馆的老板,现在你想分析一下可能的营业额变化增长(每天至少有一位顾客)

    + +

    写一条 SQL 查询计算以 7 天(某日期 + 该日期前的 6 天)为一个时间段的顾客消费平均值

    + +

    查询结果格式的例子如下:

    + +
      +
    • 查询结果按 visited_on 排序
    • +
    • average_amount 要 保留两位小数,日期数据的格式为 ('YYYY-MM-DD')
    • +
    + +

     

    + +
    Customer 表:
    ++-------------+--------------+--------------+-------------+
    +| customer_id | name         | visited_on   | amount      |
    ++-------------+--------------+--------------+-------------+
    +| 1           | Jhon         | 2019-01-01   | 100         |
    +| 2           | Daniel       | 2019-01-02   | 110         |
    +| 3           | Jade         | 2019-01-03   | 120         |
    +| 4           | Khaled       | 2019-01-04   | 130         |
    +| 5           | Winston      | 2019-01-05   | 110         | 
    +| 6           | Elvis        | 2019-01-06   | 140         | 
    +| 7           | Anna         | 2019-01-07   | 150         |
    +| 8           | Maria        | 2019-01-08   | 80          |
    +| 9           | Jaze         | 2019-01-09   | 110         | 
    +| 1           | Jhon         | 2019-01-10   | 130         | 
    +| 3           | Jade         | 2019-01-10   | 150         | 
    ++-------------+--------------+--------------+-------------+
    +
    +结果表:
    ++--------------+--------------+----------------+
    +| visited_on   | amount       | average_amount |
    ++--------------+--------------+----------------+
    +| 2019-01-07   | 860          | 122.86         |
    +| 2019-01-08   | 840          | 120            |
    +| 2019-01-09   | 840          | 120            |
    +| 2019-01-10   | 1000         | 142.86         |
    ++--------------+--------------+----------------+
    +
    +第一个七天消费平均值从 2019-01-01 到 2019-01-07 是 (100 + 110 + 120 + 130 + 110 + 140 + 150)/7 = 122.86
    +第二个七天消费平均值从 2019-01-02 到 2019-01-08 是 (110 + 120 + 130 + 110 + 140 + 150 + 80)/7 = 120
    +第三个七天消费平均值从 2019-01-03 到 2019-01-09 是 (120 + 130 + 110 + 140 + 150 + 80 + 110)/7 = 120
    +第四个七天消费平均值从 2019-01-04 到 2019-01-10 是 (130 + 110 + 140 + 150 + 80 + 110 + 130 + 150)/7 = 142.86
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1322.leetcode1322 Ads Performance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1322.leetcode1322 Ads Performance-zh.md" new file mode 100644 index 00000000..e1309c00 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1322.leetcode1322 Ads Performance-zh.md" @@ -0,0 +1,84 @@ +# [1322. 广告效果](https://leetcode-cn.com/problems/ads-performance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1322.Ads%20Performance/README_EN.md) + +## 题目描述 + + + +

    表: Ads

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ad_id         | int     |
    +| user_id       | int     |
    +| action        | enum    |
    ++---------------+---------+
    +(ad_id, user_id) 是该表的主键
    +该表的每一行包含一条广告的 ID(ad_id),用户的 ID(user_id) 和用户对广告采取的行为 (action)
    +action 列是一个枚举类型 ('Clicked', 'Viewed', 'Ignored') 。
    +
    + +

     

    + +

    一家公司正在运营这些广告并想计算每条广告的效果。

    + +

    广告效果用点击通过率(Click-Through Rate:CTR)来衡量,公式如下:

    + +

    + +

    写一条SQL语句来查询每一条广告的 ctr ,

    + +

     ctr 要保留两位小数。结果需要按 ctr 降序、按 ad_id 升序 进行排序。

    + +

     

    + +

    查询结果示例如下:

    + +
    Ads 表:
    ++-------+---------+---------+
    +| ad_id | user_id | action  |
    ++-------+---------+---------+
    +| 1     | 1       | Clicked |
    +| 2     | 2       | Clicked |
    +| 3     | 3       | Viewed  |
    +| 5     | 5       | Ignored |
    +| 1     | 7       | Ignored |
    +| 2     | 7       | Viewed  |
    +| 3     | 5       | Clicked |
    +| 1     | 4       | Viewed  |
    +| 2     | 11      | Viewed  |
    +| 1     | 2       | Clicked |
    ++-------+---------+---------+
    +结果表:
    ++-------+-------+
    +| ad_id | ctr   |
    ++-------+-------+
    +| 1     | 66.67 |
    +| 3     | 50.00 |
    +| 2     | 33.33 |
    +| 5     | 0.00  |
    ++-------+-------+
    +对于 ad_id = 1, ctr = (2/(2+1)) * 100 = 66.67
    +对于 ad_id = 2, ctr = (1/(1+2)) * 100 = 33.33
    +对于 ad_id = 3, ctr = (1/(1+1)) * 100 = 50.00
    +对于 ad_id = 5, ctr = 0.00, 注意 ad_id = 5 没有被点击 (Clicked) 或查看 (Viewed) 过
    +注意我们不关心 action 为 Ingnored 的广告
    +结果按 ctr(降序),ad_id(升序)排序
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1323.leetcode1323 Maximum 69 Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1323.leetcode1323 Maximum 69 Number-zh.md" new file mode 100644 index 00000000..ff99d197 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1323.leetcode1323 Maximum 69 Number-zh.md" @@ -0,0 +1,79 @@ +# [1323. 6 和 9 组成的最大数字](https://leetcode-cn.com/problems/maximum-69-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1323.Maximum%2069%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个仅由数字 6 和 9 组成的正整数 num

    + +

    你最多只能翻转一位数字,将 6 变成 9,或者把 9 变成 6 。

    + +

    请返回你可以得到的最大数字。

    + +

     

    + +

    示例 1:

    + +
    输入:num = 9669
    +输出:9969
    +解释:
    +改变第一位数字可以得到 6669 。
    +改变第二位数字可以得到 9969 。
    +改变第三位数字可以得到 9699 。
    +改变第四位数字可以得到 9666 。
    +其中最大的数字是 9969 。
    +
    + +

    示例 2:

    + +
    输入:num = 9996
    +输出:9999
    +解释:将最后一位从 6 变到 9,其结果 9999 是最大的数。
    + +

    示例 3:

    + +
    输入:num = 9999
    +输出:9999
    +解释:无需改变就已经是最大的数字了。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num <= 10^4
    • +
    • num 每一位上的数字都是 6 或者 9 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1324.leetcode1324 Print Words Vertically-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1324.leetcode1324 Print Words Vertically-zh.md" new file mode 100644 index 00000000..73663d96 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1324.leetcode1324 Print Words Vertically-zh.md" @@ -0,0 +1,80 @@ +# [1324. 竖直打印单词](https://leetcode-cn.com/problems/print-words-vertically) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1324.Print%20Words%20Vertically/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。
    +单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。
    +每个单词只能放在一列上,每一列中也只能有一个单词。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "HOW ARE YOU"
    +输出:["HAY","ORO","WEU"]
    +解释:每个单词都应该竖直打印。 
    + "HAY"
    + "ORO"
    + "WEU"
    +
    + +

    示例 2:

    + +
    输入:s = "TO BE OR NOT TO BE"
    +输出:["TBONTB","OEROOE","   T"]
    +解释:题目允许使用空格补位,但不允许输出末尾出现空格。
    +"TBONTB"
    +"OEROOE"
    +"   T"
    +
    + +

    示例 3:

    + +
    输入:s = "CONTEST IS COMING"
    +输出:["CIC","OSO","N M","T I","E N","S G","T"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 200
    • +
    • s 仅含大写英文字母。
    • +
    • 题目数据保证两个单词之间只有一个空格。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1325.leetcode1325 Delete Leaves With a Given Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1325.leetcode1325 Delete Leaves With a Given Value-zh.md" new file mode 100644 index 00000000..e9a48725 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1325.leetcode1325 Delete Leaves With a Given Value-zh.md" @@ -0,0 +1,95 @@ +# [1325. 删除给定值的叶子节点](https://leetcode-cn.com/problems/delete-leaves-with-a-given-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1325.Delete%20Leaves%20With%20a%20Given%20Value/README_EN.md) + +## 题目描述 + + + +

    给你一棵以 root 为根的二叉树和一个整数 target ,请你删除所有值为 target 的 叶子节点

    + +

    注意,一旦删除值为 target 的叶子节点,它的父节点就可能变成叶子节点;如果新叶子节点的值恰好也是 target ,那么这个节点也应该被删除。

    + +

    也就是说,你需要重复此过程直到不能继续删除。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [1,2,3,2,null,2,4], target = 2
    +输出:[1,null,3,null,4]
    +解释:
    +上面左边的图中,绿色节点为叶子节点,且它们的值与 target 相同(同为 2 ),它们会被删除,得到中间的图。
    +有一个新的节点变成了叶子节点且它的值与 target 相同,所以将再次进行删除,从而得到最右边的图。
    +
    + +

    示例 2:

    + +

    + +
    输入:root = [1,3,3,3,2], target = 3
    +输出:[1,3,null,null,2]
    +
    + +

    示例 3:

    + +

    + +
    输入:root = [1,2,null,2,null,2], target = 2
    +输出:[1]
    +解释:每一步都删除一个绿色的叶子节点(值为 2)。
    + +

    示例 4:

    + +
    输入:root = [1,1,1], target = 1
    +输出:[]
    +
    + +

    示例 5:

    + +
    输入:root = [1,2,3], target = 1
    +输出:[1,2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target <= 1000
    • +
    • 每一棵树最多有 3000 个节点。
    • +
    • 每一个节点值的范围是 [1, 1000] 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1326.leetcode1326 Minimum Number of Taps to Open to Water a Garden-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1326.leetcode1326 Minimum Number of Taps to Open to Water a Garden-zh.md" new file mode 100644 index 00000000..1037d700 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1326.leetcode1326 Minimum Number of Taps to Open to Water a Garden-zh.md" @@ -0,0 +1,99 @@ +# [1326. 灌溉花园的最少水龙头数目](https://leetcode-cn.com/problems/minimum-number-of-taps-to-open-to-water-a-garden) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1326.Minimum%20Number%20of%20Taps%20to%20Open%20to%20Water%20a%20Garden/README_EN.md) + +## 题目描述 + + + +

    在 x 轴上有一个一维的花园。花园长度为 n,从点 0 开始,到点 n 结束。

    + +

    花园里总共有 n + 1 个水龙头,分别位于 [0, 1, ..., n]

    + +

    给你一个整数 n 和一个长度为 n + 1 的整数数组 ranges ,其中 ranges[i] (下标从 0 开始)表示:如果打开点 i 处的水龙头,可以灌溉的区域为 [i -  ranges[i], i + ranges[i]] 。

    + +

    请你返回可以灌溉整个花园的 最少水龙头数目 。如果花园始终存在无法灌溉到的地方,请你返回 -1 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 5, ranges = [3,4,1,1,0,0]
    +输出:1
    +解释:
    +点 0 处的水龙头可以灌溉区间 [-3,3]
    +点 1 处的水龙头可以灌溉区间 [-3,5]
    +点 2 处的水龙头可以灌溉区间 [1,3]
    +点 3 处的水龙头可以灌溉区间 [2,4]
    +点 4 处的水龙头可以灌溉区间 [4,4]
    +点 5 处的水龙头可以灌溉区间 [5,5]
    +只需要打开点 1 处的水龙头即可灌溉整个花园 [0,5] 。
    +
    + +

    示例 2:

    + +
    输入:n = 3, ranges = [0,0,0,0]
    +输出:-1
    +解释:即使打开所有水龙头,你也无法灌溉整个花园。
    +
    + +

    示例 3:

    + +
    输入:n = 7, ranges = [1,2,1,0,2,1,0,1]
    +输出:3
    +
    + +

    示例 4:

    + +
    输入:n = 8, ranges = [4,0,0,0,0,0,0,0,4]
    +输出:2
    +
    + +

    示例 5:

    + +
    输入:n = 8, ranges = [4,0,0,0,4,0,0,0,4]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    • ranges.length == n + 1
    • +
    • 0 <= ranges[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1327.leetcode1327 List the Products Ordered in a Period-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1327.leetcode1327 List the Products Ordered in a Period-zh.md" new file mode 100644 index 00000000..168ba862 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1327.leetcode1327 List the Products Ordered in a Period-zh.md" @@ -0,0 +1,103 @@ +# [1327. 列出指定时间段内所有的下单产品](https://leetcode-cn.com/problems/list-the-products-ordered-in-a-period) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1327.List%20the%20Products%20Ordered%20in%20a%20Period/README_EN.md) + +## 题目描述 + + + +

    表: Products

    + +
    +------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| product_id       | int     |
    +| product_name     | varchar |
    +| product_category | varchar |
    ++------------------+---------+
    +product_id 是该表主键。
    +该表包含该公司产品的数据。
    +
    + +

    表: Orders

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| order_date    | date    |
    +| unit          | int     |
    ++---------------+---------+
    +该表无主键,可能包含重复行。
    +product_id 是表单 Products 的外键。
    +unit 是在日期 order_date 内下单产品的数目。
    +
    + +

     

    + +

    写一个 SQL 语句,要求获取在 2020 年 2 月份下单的数量不少于 100 的产品的名字和数目。

    + +

    返回结果表单的顺序无要求。

    + +

     

    + +

    查询结果的格式如下:

    + +
    Products 表:
    ++-------------+-----------------------+------------------+
    +| product_id  | product_name          | product_category |
    ++-------------+-----------------------+------------------+
    +| 1           | Leetcode Solutions    | Book             |
    +| 2           | Jewels of Stringology | Book             |
    +| 3           | HP                    | Laptop           |
    +| 4           | Lenovo                | Laptop           |
    +| 5           | Leetcode Kit          | T-shirt          |
    ++-------------+-----------------------+------------------+
    +
    +Orders 表:
    ++--------------+--------------+----------+
    +| product_id   | order_date   | unit     |
    ++--------------+--------------+----------+
    +| 1            | 2020-02-05   | 60       |
    +| 1            | 2020-02-10   | 70       |
    +| 2            | 2020-01-18   | 30       |
    +| 2            | 2020-02-11   | 80       |
    +| 3            | 2020-02-17   | 2        |
    +| 3            | 2020-02-24   | 3        |
    +| 4            | 2020-03-01   | 20       |
    +| 4            | 2020-03-04   | 30       |
    +| 4            | 2020-03-04   | 60       |
    +| 5            | 2020-02-25   | 50       |
    +| 5            | 2020-02-27   | 50       |
    +| 5            | 2020-03-01   | 50       |
    ++--------------+--------------+----------+
    +
    +Result 表:
    ++--------------------+---------+
    +| product_name       | unit    |
    ++--------------------+---------+
    +| Leetcode Solutions | 130     |
    +| Leetcode Kit       | 100     |
    ++--------------------+---------+
    +
    +2020 年 2 月份下单 product_id = 1 的产品的数目总和为 (60 + 70) = 130 。
    +2020 年 2 月份下单 product_id = 2 的产品的数目总和为 80 。
    +2020 年 2 月份下单 product_id = 3 的产品的数目总和为 (2 + 3) = 5 。
    +2020 年 2 月份 product_id = 4 的产品并没有下单。
    +2020 年 2 月份下单 product_id = 5 的产品的数目总和为 (50 + 50) = 100 。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1328.leetcode1328 Break a Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1328.leetcode1328 Break a Palindrome-zh.md" new file mode 100644 index 00000000..08d761aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1328.leetcode1328 Break a Palindrome-zh.md" @@ -0,0 +1,65 @@ +# [1328. 破坏回文串](https://leetcode-cn.com/problems/break-a-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1328.Break%20a%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给你一个回文字符串 palindrome ,请你将其中 一个 字符用任意小写英文字母替换,使得结果字符串的字典序最小,且 不是 回文串。

    + +

    请你返回结果字符串。如果无法做到,则返回一个空串。

    + +

     

    + +

    示例 1:

    + +
    输入:palindrome = "abccba"
    +输出:"aaccba"
    +
    + +

    示例 2:

    + +
    输入:palindrome = "a"
    +输出:""
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= palindrome.length <= 1000
    • +
    • palindrome 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1329.leetcode1329 Sort the Matrix Diagonally-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1329.leetcode1329 Sort the Matrix Diagonally-zh.md" new file mode 100644 index 00000000..4eddd882 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1329.leetcode1329 Sort the Matrix Diagonally-zh.md" @@ -0,0 +1,71 @@ +# [1329. 将矩阵按对角线排序](https://leetcode-cn.com/problems/sort-the-matrix-diagonally) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1329.Sort%20the%20Matrix%20Diagonally/README_EN.md) + +## 题目描述 + + + +

    矩阵对角线 是一条从矩阵最上面行或者最左侧列中的某个元素开始的对角线,沿右下方向一直到矩阵末尾的元素。例如,矩阵 mat63 列,从 mat[2][0] 开始的 矩阵对角线 将会经过 mat[2][0]mat[3][1]mat[4][2]

    + +

    给你一个 m * n 的整数矩阵 mat ,请你将同一条 矩阵对角线 上的元素按升序排序后,返回排好序的矩阵。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
    +输出:[[1,1,1,1],[1,2,2,2],[1,2,3,3]]
    +
    + +

    示例 2:

    + +
    +输入:mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
    +输出:[[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • 1 <= mat[i][j] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1330.leetcode1330 Reverse Subarray To Maximize Array Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1330.leetcode1330 Reverse Subarray To Maximize Array Value-zh.md" new file mode 100644 index 00000000..29a8a4e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1330.leetcode1330 Reverse Subarray To Maximize Array Value-zh.md" @@ -0,0 +1,68 @@ +# [1330. 翻转子数组得到最大的数组值](https://leetcode-cn.com/problems/reverse-subarray-to-maximize-array-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1330.Reverse%20Subarray%20To%20Maximize%20Array%20Value/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 。「数组值」定义为所有满足 0 <= i < nums.length-1 的 |nums[i]-nums[i+1]| 的和。

    + +

    你可以选择给定数组的任意子数组,并将该子数组翻转。但你只能执行这个操作 一次

    + +

    请你找到可行的最大 数组值 

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [2,3,1,5,4]
    +输出:10
    +解释:通过翻转子数组 [3,1,5] ,数组变成 [2,5,1,3,4] ,数组值为 10 。
    +
    + +

    示例 2:

    + +
    输入:nums = [2,4,9,24,2,1,10]
    +输出:68
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 3*10^4
    • +
    • -10^5 <= nums[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1331.leetcode1331 Rank Transform of an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1331.leetcode1331 Rank Transform of an Array-zh.md" new file mode 100644 index 00000000..319f3621 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1331.leetcode1331 Rank Transform of an Array-zh.md" @@ -0,0 +1,78 @@ +# [1331. 数组序号转换](https://leetcode-cn.com/problems/rank-transform-of-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1331.Rank%20Transform%20of%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,请你将数组中的每个元素替换为它们排序后的序号。

    + +

    序号代表了一个元素有多大。序号编号的规则如下:

    + +
      +
    • 序号从 1 开始编号。
    • +
    • 一个元素越大,那么序号越大。如果两个元素相等,那么它们的序号相同。
    • +
    • 每个数字的序号都应该尽可能地小。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:arr = [40,10,20,30]
    +输出:[4,1,2,3]
    +解释:40 是最大的元素。 10 是最小的元素。 20 是第二小的数字。 30 是第三小的数字。
    + +

    示例 2:

    + +
    输入:arr = [100,100,100]
    +输出:[1,1,1]
    +解释:所有元素有相同的序号。
    +
    + +

    示例 3:

    + +
    输入:arr = [37,12,28,9,100,56,80,5,12]
    +输出:[5,3,4,2,8,6,7,1,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= arr.length <= 105
    • +
    • -109 <= arr[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1332.leetcode1332 Remove Palindromic Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1332.leetcode1332 Remove Palindromic Subsequences-zh.md" new file mode 100644 index 00000000..4ed16f14 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1332.leetcode1332 Remove Palindromic Subsequences-zh.md" @@ -0,0 +1,86 @@ +# [1332. 删除回文子序列](https://leetcode-cn.com/problems/remove-palindromic-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1332.Remove%20Palindromic%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,它仅由字母 'a''b' 组成。每一次删除操作都可以从 s 中删除一个回文 子序列

    + +

    返回删除给定字符串中所有字符(字符串为空)的最小删除次数。

    + +

    「子序列」定义:如果一个字符串可以通过删除原字符串某些字符而不改变原字符顺序得到,那么这个字符串就是原字符串的一个子序列。

    + +

    「回文」定义:如果一个字符串向后和向前读是一致的,那么这个字符串就是一个回文。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "ababa"
    +输出:1
    +解释:字符串本身就是回文序列,只需要删除一次。
    +
    + +

    示例 2:

    + +
    输入:s = "abb"
    +输出:2
    +解释:"abb" -> "bb" -> "". 
    +先删除回文子序列 "a",然后再删除 "bb"。
    +
    + +

    示例 3:

    + +
    输入:s = "baabb"
    +输出:2
    +解释:"baabb" -> "b" -> "". 
    +先删除回文子序列 "baab",然后再删除 "b"。
    +
    + +

    示例 4:

    + +
    输入:s = ""
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= s.length <= 1000
    • +
    • s 仅包含字母 'a'  和 'b'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1333.leetcode1333 Filter Restaurants by Vegan-Friendly, Price and Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1333.leetcode1333 Filter Restaurants by Vegan-Friendly, Price and Distance-zh.md" new file mode 100644 index 00000000..a60d87e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1333.leetcode1333 Filter Restaurants by Vegan-Friendly, Price and Distance-zh.md" @@ -0,0 +1,86 @@ +# [1333. 餐厅过滤器](https://leetcode-cn.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1333.Filter%20Restaurants%20by%20Vegan-Friendly%2C%20Price%20and%20Distance/README_EN.md) + +## 题目描述 + + + +

    给你一个餐馆信息数组 restaurants,其中  restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]。你必须使用以下三个过滤器来过滤这些餐馆信息。

    + +

    其中素食者友好过滤器 veganFriendly 的值可以为 true 或者 false,如果为 true 就意味着你应该只包括 veganFriendlyi 为 true 的餐馆,为 false 则意味着可以包括任何餐馆。此外,我们还有最大价格 maxPrice 和最大距离 maxDistance 两个过滤器,它们分别考虑餐厅的价格因素和距离因素的最大值。

    + +

    过滤后返回餐馆的 id,按照 rating 从高到低排序。如果 rating 相同,那么按 id 从高到低排序。简单起见, veganFriendlyiveganFriendly 为 true 时取值为 1,为 false 时,取值为 0 。

    + +

     

    + +

    示例 1:

    + +
    输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
    +输出:[3,1,5] 
    +解释: 
    +这些餐馆为:
    +餐馆 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
    +餐馆 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
    +餐馆 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
    +餐馆 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
    +餐馆 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] 
    +在按照 veganFriendly = 1, maxPrice = 50 和 maxDistance = 10 进行过滤后,我们得到了餐馆 3, 餐馆 1 和 餐馆 5(按评分从高到低排序)。 
    +
    + +

    示例 2:

    + +
    输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
    +输出:[4,3,2,1,5]
    +解释:餐馆与示例 1 相同,但在 veganFriendly = 0 的过滤条件下,应该考虑所有餐馆。
    +
    + +

    示例 3:

    + +
    输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
    +输出:[4,5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= restaurants.length <= 10^4
    • +
    • restaurants[i].length == 5
    • +
    • 1 <= idi, ratingi, pricei, distancei <= 10^5
    • +
    • 1 <= maxPrice, maxDistance <= 10^5
    • +
    • veganFriendlyi 和 veganFriendly 的值为 0 或 1 。
    • +
    • 所有 idi 各不相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1334.leetcode1334 Find the City With the Smallest Number of Neighbors at a Threshold Distance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1334.leetcode1334 Find the City With the Smallest Number of Neighbors at a Threshold Distance-zh.md" new file mode 100644 index 00000000..dcbc7628 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1334.leetcode1334 Find the City With the Smallest Number of Neighbors at a Threshold Distance-zh.md" @@ -0,0 +1,92 @@ +# [1334. 阈值距离内邻居最少的城市](https://leetcode-cn.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1334.Find%20the%20City%20With%20the%20Smallest%20Number%20of%20Neighbors%20at%20a%20Threshold%20Distance/README_EN.md) + +## 题目描述 + + + +

    n 个城市,按从 0n-1 编号。给你一个边数组 edges,其中 edges[i] = [fromi, toi, weighti] 代表 fromi 和 toi 两个城市之间的双向加权边,距离阈值是一个整数 distanceThreshold

    + +

    返回能通过某些路径到达其他城市数目最少、且路径距离 最大 为 distanceThreshold 的城市。如果有多个这样的城市,则返回编号最大的城市。

    + +

    注意,连接城市 ij 的路径的距离等于沿该路径的所有边的权重之和。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
    +输出:3
    +解释:城市分布图如上。
    +每个城市阈值距离 distanceThreshold = 4 内的邻居城市分别是:
    +城市 0 -> [城市 1, 城市 2] 
    +城市 1 -> [城市 0, 城市 2, 城市 3] 
    +城市 2 -> [城市 0, 城市 1, 城市 3] 
    +城市 3 -> [城市 1, 城市 2] 
    +城市 0 和 3 在阈值距离 4 以内都有 2 个邻居城市,但是我们必须返回城市 3,因为它的编号最大。
    +
    + +

    示例 2:

    + +

    + +
    +输入:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
    +输出:0
    +解释:城市分布图如上。 
    +每个城市阈值距离 distanceThreshold = 2 内的邻居城市分别是:
    +城市 0 -> [城市 1] 
    +城市 1 -> [城市 0, 城市 4] 
    +城市 2 -> [城市 3, 城市 4] 
    +城市 3 -> [城市 2, 城市 4]
    +城市 4 -> [城市 1, 城市 2, 城市 3] 
    +城市 0 在阈值距离 2 以内只有 1 个邻居城市。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • 1 <= edges.length <= n * (n - 1) / 2
    • +
    • edges[i].length == 3
    • +
    • 0 <= fromi < toi < n
    • +
    • 1 <= weighti, distanceThreshold <= 10^4
    • +
    • 所有 (fromi, toi) 都是不同的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1335.leetcode1335 Minimum Difficulty of a Job Schedule-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1335.leetcode1335 Minimum Difficulty of a Job Schedule-zh.md" new file mode 100644 index 00000000..ccd2f93d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1335.leetcode1335 Minimum Difficulty of a Job Schedule-zh.md" @@ -0,0 +1,95 @@ +# [1335. 工作计划的最低难度](https://leetcode-cn.com/problems/minimum-difficulty-of-a-job-schedule) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1335.Minimum%20Difficulty%20of%20a%20Job%20Schedule/README_EN.md) + +## 题目描述 + + + +

    你需要制定一份 d 天的工作计划表。工作之间存在依赖,要想执行第 i 项工作,你必须完成全部 j 项工作( 0 <= j < i)。

    + +

    你每天 至少 需要完成一项任务。工作计划的总难度是这 d 天每一天的难度之和,而一天的工作难度是当天应该完成工作的最大难度。

    + +

    给你一个整数数组 jobDifficulty 和一个整数 d,分别代表工作难度和需要计划的天数。第 i 项工作的难度是 jobDifficulty[i]

    + +

    返回整个工作计划的 最小难度 。如果无法制定工作计划,则返回 -1 

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:jobDifficulty = [6,5,4,3,2,1], d = 2
    +输出:7
    +解释:第一天,您可以完成前 5 项工作,总难度 = 6.
    +第二天,您可以完成最后一项工作,总难度 = 1.
    +计划表的难度 = 6 + 1 = 7 
    +
    + +

    示例 2:

    + +
    输入:jobDifficulty = [9,9,9], d = 4
    +输出:-1
    +解释:就算你每天完成一项工作,仍然有一天是空闲的,你无法制定一份能够满足既定工作时间的计划表。
    +
    + +

    示例 3:

    + +
    输入:jobDifficulty = [1,1,1], d = 3
    +输出:3
    +解释:工作计划为每天一项工作,总难度为 3 。
    +
    + +

    示例 4:

    + +
    输入:jobDifficulty = [7,1,7,1,7,1], d = 3
    +输出:15
    +
    + +

    示例 5:

    + +
    输入:jobDifficulty = [11,111,22,222,33,333,44,444], d = 6
    +输出:843
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= jobDifficulty.length <= 300
    • +
    • 0 <= jobDifficulty[i] <= 1000
    • +
    • 1 <= d <= 10
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1336.leetcode1336 Number of Transactions per Visit-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1336.leetcode1336 Number of Transactions per Visit-zh.md" new file mode 100644 index 00000000..51178e0a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1336.leetcode1336 Number of Transactions per Visit-zh.md" @@ -0,0 +1,119 @@ +# [1336. 每次访问的交易次数](https://leetcode-cn.com/problems/number-of-transactions-per-visit) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1336.Number%20of%20Transactions%20per%20Visit/README_EN.md) + +## 题目描述 + + + +

    表: Visits

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| visit_date    | date    |
    ++---------------+---------+
    +(user_id, visit_date) 是该表的主键
    +该表的每行表示 user_id 在 visit_date 访问了银行
    +
    + +

     

    + +

    表: Transactions

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| user_id          | int     |
    +| transaction_date | date    |
    +| amount           | int     |
    ++------------------+---------+
    +该表没有主键,所以可能有重复行
    +该表的每一行表示 user_id 在 transaction_date 完成了一笔 amount 数额的交易
    +可以保证用户 (user) 在 transaction_date 访问了银行 (也就是说 Visits 表包含 (user_id, transaction_date) 行)
    +
    + +

     

    + +

    银行想要得到银行客户在一次访问时的交易次数和相应的在一次访问时该交易次数的客户数量的图表

    + +

    写一条 SQL 查询多少客户访问了银行但没有进行任何交易,多少客户访问了银行进行了一次交易等等

    + +

    结果包含两列:

    + +
      +
    • transactions_count: 客户在一次访问中的交易次数
    • +
    • visits_count: 在 transactions_count 交易次数下相应的一次访问时的客户数量
    • +
    + +

    transactions_count 的值从 0 到所有用户一次访问中的 max(transactions_count) 

    + +

    按 transactions_count 排序

    + +

    下面是查询结果格式的例子:

    + +
    +Visits 表:
    ++---------+------------+
    +| user_id | visit_date |
    ++---------+------------+
    +| 1       | 2020-01-01 |
    +| 2       | 2020-01-02 |
    +| 12      | 2020-01-01 |
    +| 19      | 2020-01-03 |
    +| 1       | 2020-01-02 |
    +| 2       | 2020-01-03 |
    +| 1       | 2020-01-04 |
    +| 7       | 2020-01-11 |
    +| 9       | 2020-01-25 |
    +| 8       | 2020-01-28 |
    ++---------+------------+
    +Transactions 表:
    ++---------+------------------+--------+
    +| user_id | transaction_date | amount |
    ++---------+------------------+--------+
    +| 1       | 2020-01-02       | 120    |
    +| 2       | 2020-01-03       | 22     |
    +| 7       | 2020-01-11       | 232    |
    +| 1       | 2020-01-04       | 7      |
    +| 9       | 2020-01-25       | 33     |
    +| 9       | 2020-01-25       | 66     |
    +| 8       | 2020-01-28       | 1      |
    +| 9       | 2020-01-25       | 99     |
    ++---------+------------------+--------+
    +结果表:
    ++--------------------+--------------+
    +| transactions_count | visits_count |
    ++--------------------+--------------+
    +| 0                  | 4            |
    +| 1                  | 5            |
    +| 2                  | 0            |
    +| 3                  | 1            |
    ++--------------------+--------------+
    +* 对于 transactions_count = 0, visits 中 (1, "2020-01-01"), (2, "2020-01-02"), (12, "2020-01-01") 和 (19, "2020-01-03") 没有进行交易,所以 visits_count = 4 。
    +* 对于 transactions_count = 1, visits 中 (2, "2020-01-03"), (7, "2020-01-11"), (8, "2020-01-28"), (1, "2020-01-02") 和 (1, "2020-01-04") 进行了一次交易,所以 visits_count = 5 。
    +* 对于 transactions_count = 2, 没有客户访问银行进行了两次交易,所以 visits_count = 0 。
    +* 对于 transactions_count = 3, visits 中 (9, "2020-01-25") 进行了三次交易,所以 visits_count = 1 。
    +* 对于 transactions_count >= 4, 没有客户访问银行进行了超过3次交易,所以我们停止在 transactions_count = 3 。
    +
    +如下是这个例子的图表:
    +
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1337.leetcode1337 The K Weakest Rows in a Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1337.leetcode1337 The K Weakest Rows in a Matrix-zh.md" new file mode 100644 index 00000000..97645663 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1337.leetcode1337 The K Weakest Rows in a Matrix-zh.md" @@ -0,0 +1,143 @@ +# [1337. 矩阵中战斗力最弱的 K 行](https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1337.The%20K%20Weakest%20Rows%20in%20a%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个大小为 m * n 的矩阵 mat,矩阵由若干军人和平民组成,分别用 1 和 0 表示。

    + +

    请你返回矩阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。

    + +

    如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j,那么我们认为第 i 行的战斗力比第 j 行弱。

    + +

    军人 总是 排在一行中的靠前位置,也就是说 1 总是出现在 0 之前。

    + +

     

    + +

    示例 1:

    + +
    +输入:mat = 
    +[[1,1,0,0,0],
    + [1,1,1,1,0],
    + [1,0,0,0,0],
    + [1,1,0,0,0],
    + [1,1,1,1,1]], 
    +k = 3
    +输出:[2,0,3]
    +解释:
    +每行中的军人数目:
    +行 0 -> 2 
    +行 1 -> 4 
    +行 2 -> 1 
    +行 3 -> 2 
    +行 4 -> 5 
    +从最弱到最强对这些行排序后得到 [2,0,3,1,4]
    +
    + +

    示例 2:

    + +
    +输入:mat = 
    +[[1,0,0,0],
    + [1,1,1,1],
    + [1,0,0,0],
    + [1,0,0,0]], 
    +k = 2
    +输出:[0,2]
    +解释: 
    +每行中的军人数目:
    +行 0 -> 1 
    +行 1 -> 4 
    +行 2 -> 1 
    +行 3 -> 1 
    +从最弱到最强对这些行排序后得到 [0,2,3,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 2 <= n, m <= 100
    • +
    • 1 <= k <= m
    • +
    • matrix[i][j] 不是 0 就是 1
    • +
    + + +## 解法 + + + +二分查找 + 排序。 + + + +### **Python3** + + + +```python +class Solution: + def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: + m, n = len(mat), len(mat[0]) + res = [] + for row in mat: + left, right = 0, n + while left < right: + mid = (left + right) >> 1 + if row[mid] == 0: + right = mid + else: + left = mid + 1 + res.append(left) + idx = list(range(m)) + idx.sort(key=lambda x: res[x]) + return idx[:k] +``` + +### **Java** + + + +```java +class Solution { + public int[] kWeakestRows(int[][] mat, int k) { + int m = mat.length, n = mat[0].length; + int[] res = new int[m]; + List idx = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + idx.add(i); + int[] row = mat[i]; + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (row[mid] == 0) { + right = mid; + } else { + left = mid + 1; + } + } + res[i] = left; + } + idx.sort(Comparator.comparingInt(a -> res[a])); + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = idx.get(i); + } + return ans; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1338.leetcode1338 Reduce Array Size to The Half-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1338.leetcode1338 Reduce Array Size to The Half-zh.md" new file mode 100644 index 00000000..8ecaddb9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1338.leetcode1338 Reduce Array Size to The Half-zh.md" @@ -0,0 +1,88 @@ +# [1338. 数组大小减半](https://leetcode-cn.com/problems/reduce-array-size-to-the-half) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1338.Reduce%20Array%20Size%20to%20The%20Half/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr。你可以从中选出一个整数集合,并删除这些整数在数组中的每次出现。

    + +

    返回 至少 能删除数组中的一半整数的整数集合的最小大小。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [3,3,3,3,5,5,5,2,2,7]
    +输出:2
    +解释:选择 {3,7} 使得结果数组为 [5,5,5,2,2]、长度为 5(原数组长度的一半)。
    +大小为 2 的可行集合有 {3,5},{3,2},{5,2}。
    +选择 {2,7} 是不可行的,它的结果数组为 [3,3,3,3,5,5,5],新数组长度大于原数组的二分之一。
    +
    + +

    示例 2:

    + +
    输入:arr = [7,7,7,7,7,7]
    +输出:1
    +解释:我们只能选择集合 {7},结果数组为空。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,9]
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:arr = [1000,1000,3,7]
    +输出:1
    +
    + +

    示例 5:

    + +
    输入:arr = [1,2,3,4,5,6,7,8,9,10]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • arr.length 为偶数
    • +
    • 1 <= arr[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1339.leetcode1339 Maximum Product of Splitted Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1339.leetcode1339 Maximum Product of Splitted Binary Tree-zh.md" new file mode 100644 index 00000000..1b9683dc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1339.leetcode1339 Maximum Product of Splitted Binary Tree-zh.md" @@ -0,0 +1,83 @@ +# [1339. 分裂二叉树的最大乘积](https://leetcode-cn.com/problems/maximum-product-of-splitted-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1339.Maximum%20Product%20of%20Splitted%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树,它的根为 root 。请你删除 1 条边,使二叉树分裂成两棵子树,且它们子树和的乘积尽可能大。

    + +

    由于答案可能会很大,请你将结果对 10^9 + 7 取模后再返回。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [1,2,3,4,5,6]
    +输出:110
    +解释:删除红色的边,得到 2 棵子树,和分别为 11 和 10 。它们的乘积是 110 (11*10)
    +
    + +

    示例 2:

    + +

    + +
    输入:root = [1,null,2,3,4,null,null,5,6]
    +输出:90
    +解释:移除红色的边,得到 2 棵子树,和分别是 15 和 6 。它们的乘积为 90 (15*6)
    +
    + +

    示例 3:

    + +
    输入:root = [2,3,9,10,7,8,6,5,4,11,1]
    +输出:1025
    +
    + +

    示例 4:

    + +
    输入:root = [1,1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每棵树最多有 50000 个节点,且至少有 2 个节点。
    • +
    • 每个节点的值在 [1, 10000] 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1340.leetcode1340 Jump Game V-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1340.leetcode1340 Jump Game V-zh.md" new file mode 100644 index 00000000..5f95ab88 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1340.leetcode1340 Jump Game V-zh.md" @@ -0,0 +1,100 @@ +# [1340. 跳跃游戏 V](https://leetcode-cn.com/problems/jump-game-v) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1340.Jump%20Game%20V/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数 d 。每一步你可以从下标 i 跳到:

    + +
      +
    • i + x ,其中 i + x < arr.length 且 0 < x <= d 。
    • +
    • i - x ,其中 i - x >= 0 且 0 < x <= d 。
    • +
    + +

    除此以外,你从下标 i 跳到下标 j 需要满足:arr[i] > arr[j] 且 arr[i] > arr[k] ,其中下标 k 是所有 i 到 j 之间的数字(更正式的,min(i, j) < k < max(i, j))。

    + +

    你可以选择数组的任意下标开始跳跃。请你返回你 最多 可以访问多少个下标。

    + +

    请注意,任何时刻你都不能跳到数组的外面。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
    +输出:4
    +解释:你可以从下标 10 出发,然后如上图依次经过 10 --> 8 --> 6 --> 7 。
    +注意,如果你从下标 6 开始,你只能跳到下标 7 处。你不能跳到下标 5 处因为 13 > 9 。你也不能跳到下标 4 处,因为下标 5 在下标 4 和 6 之间且 13 > 9 。
    +类似的,你不能从下标 3 处跳到下标 2 或者下标 1 处。
    +
    + +

    示例 2:

    + +
    输入:arr = [3,3,3,3,3], d = 3
    +输出:1
    +解释:你可以从任意下标处开始且你永远无法跳到任何其他坐标。
    +
    + +

    示例 3:

    + +
    输入:arr = [7,6,5,4,3,2,1], d = 1
    +输出:7
    +解释:从下标 0 处开始,你可以按照数值从大到小,访问所有的下标。
    +
    + +

    示例 4:

    + +
    输入:arr = [7,1,7,1,7,1], d = 2
    +输出:2
    +
    + +

    示例 5:

    + +
    输入:arr = [66], d = 1
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 10^5
    • +
    • 1 <= d <= arr.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1341.leetcode1341 Movie Rating-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1341.leetcode1341 Movie Rating-zh.md" new file mode 100644 index 00000000..2275dd47 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1341.leetcode1341 Movie Rating-zh.md" @@ -0,0 +1,121 @@ +# [1341. 电影评分](https://leetcode-cn.com/problems/movie-rating) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1341.Movie%20Rating/README_EN.md) + +## 题目描述 + + + +

    表:Movies

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| movie_id      | int     |
    +| title         | varchar |
    ++---------------+---------+
    +movie_id 是这个表的主键。
    +title 是电影的名字。
    +
    + +

    表:Users

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| name          | varchar |
    ++---------------+---------+
    +user_id 是表的主键。
    +
    + +

    表:Movie_Rating

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| movie_id      | int     |
    +| user_id       | int     |
    +| rating        | int     |
    +| created_at    | date    |
    ++---------------+---------+
    +(movie_id, user_id) 是这个表的主键。
    +这个表包含用户在其评论中对电影的评分 rating 。
    +created_at 是用户的点评日期。 
    +
    + +

     

    + +

    请你编写一组 SQL 查询:

    + +
      +
    • 查找评论电影数量最多的用户名。 +

      如果出现平局,返回字典序较小的用户名。

      +
    • +
    • 查找在 2020 年 2 月 平均评分最高 的电影名称。 +

      如果出现平局,返回字典序较小的电影名称。

      +
    • +
    + +

    查询分两行返回,查询结果格式如下例所示:

    + +
    Movies 表:
    ++-------------+--------------+
    +| movie_id    |  title       |
    ++-------------+--------------+
    +| 1           | Avengers     |
    +| 2           | Frozen 2     |
    +| 3           | Joker        |
    ++-------------+--------------+
    +
    +Users 表:
    ++-------------+--------------+
    +| user_id     |  name        |
    ++-------------+--------------+
    +| 1           | Daniel       |
    +| 2           | Monica       |
    +| 3           | Maria        |
    +| 4           | James        |
    ++-------------+--------------+
    +
    +Movie_Rating 表:
    ++-------------+--------------+--------------+-------------+
    +| movie_id    | user_id      | rating       | created_at  |
    ++-------------+--------------+--------------+-------------+
    +| 1           | 1            | 3            | 2020-01-12  |
    +| 1           | 2            | 4            | 2020-02-11  |
    +| 1           | 3            | 2            | 2020-02-12  |
    +| 1           | 4            | 1            | 2020-01-01  |
    +| 2           | 1            | 5            | 2020-02-17  | 
    +| 2           | 2            | 2            | 2020-02-01  | 
    +| 2           | 3            | 2            | 2020-03-01  |
    +| 3           | 1            | 3            | 2020-02-22  | 
    +| 3           | 2            | 4            | 2020-02-25  | 
    ++-------------+--------------+--------------+-------------+
    +
    +Result 表:
    ++--------------+
    +| results      |
    ++--------------+
    +| Daniel       |
    +| Frozen 2     |
    ++--------------+
    +
    +Daniel 和 Monica 都点评了 3 部电影("Avengers", "Frozen 2" 和 "Joker") 但是 Daniel 字典序比较小。
    +Frozen 2 和 Joker 在 2 月的评分都是 3.5,但是 Frozen 2 的字典序比较小。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1342.leetcode1342 Number of Steps to Reduce a Number to Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1342.leetcode1342 Number of Steps to Reduce a Number to Zero-zh.md" new file mode 100644 index 00000000..b5623054 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1342.leetcode1342 Number of Steps to Reduce a Number to Zero-zh.md" @@ -0,0 +1,80 @@ +# [1342. 将数字变成 0 的操作次数](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1342.Number%20of%20Steps%20to%20Reduce%20a%20Number%20to%20Zero/README_EN.md) + +## 题目描述 + + + +

    给你一个非负整数 num ,请你返回将它变成 0 所需要的步数。 如果当前数字是偶数,你需要把它除以 2 ;否则,减去 1 。

    + +

     

    + +

    示例 1:

    + +
    输入:num = 14
    +输出:6
    +解释:
    +步骤 1) 14 是偶数,除以 2 得到 7 。
    +步骤 2) 7 是奇数,减 1 得到 6 。
    +步骤 3) 6 是偶数,除以 2 得到 3 。
    +步骤 4) 3 是奇数,减 1 得到 2 。
    +步骤 5) 2 是偶数,除以 2 得到 1 。
    +步骤 6) 1 是奇数,减 1 得到 0 。
    +
    + +

    示例 2:

    + +
    输入:num = 8
    +输出:4
    +解释:
    +步骤 1) 8 是偶数,除以 2 得到 4 。
    +步骤 2) 4 是偶数,除以 2 得到 2 。
    +步骤 3) 2 是偶数,除以 2 得到 1 。
    +步骤 4) 1 是奇数,减 1 得到 0 。
    +
    + +

    示例 3:

    + +
    输入:num = 123
    +输出:12
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= num <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1343.leetcode1343 Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1343.leetcode1343 Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold-zh.md" new file mode 100644 index 00000000..96bf7105 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1343.leetcode1343 Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold-zh.md" @@ -0,0 +1,87 @@ +# [1343. 大小为 K 且平均值大于等于阈值的子数组数目](https://leetcode-cn.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1343.Number%20of%20Sub-arrays%20of%20Size%20K%20and%20Average%20Greater%20than%20or%20Equal%20to%20Threshold/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和两个整数 k 和 threshold 。

    + +

    请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
    +输出:3
    +解释:子数组 [2,5,5],[5,5,5] 和 [5,5,8] 的平均值分别为 4,5 和 6 。其他长度为 3 的子数组的平均值都小于 4 (threshold 的值)。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,1,1,1,1], k = 1, threshold = 0
    +输出:5
    +
    + +

    示例 3:

    + +
    输入:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
    +输出:6
    +解释:前 6 个长度为 3 的子数组平均值都大于 5 。注意平均值不是整数。
    +
    + +

    示例 4:

    + +
    输入:arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
    +输出:1
    +
    + +

    示例 5:

    + +
    输入:arr = [4,4,4,4], k = 4, threshold = 1
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^4
    • +
    • 1 <= k <= arr.length
    • +
    • 0 <= threshold <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1344.leetcode1344 Angle Between Hands of a Clock-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1344.leetcode1344 Angle Between Hands of a Clock-zh.md" new file mode 100644 index 00000000..ec1bc53b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1344.leetcode1344 Angle Between Hands of a Clock-zh.md" @@ -0,0 +1,88 @@ +# [1344. 时钟指针的夹角](https://leetcode-cn.com/problems/angle-between-hands-of-a-clock) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1344.Angle%20Between%20Hands%20of%20a%20Clock/README_EN.md) + +## 题目描述 + + + +

    给你两个数 hour 和 minutes 。请你返回在时钟上,由给定时间的时针和分针组成的较小角的角度(60 单位制)。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:hour = 12, minutes = 30
    +输出:165
    +
    + +

    示例 2:

    + +

    + +
    输入:hour = 3, minutes = 30
    +输出;75
    +
    + +

    示例 3:

    + +

    + +
    输入:hour = 3, minutes = 15
    +输出:7.5
    +
    + +

    示例 4:

    + +
    输入:hour = 4, minutes = 50
    +输出:155
    +
    + +

    示例 5:

    + +
    输入:hour = 12, minutes = 0
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= hour <= 12
    • +
    • 0 <= minutes <= 59
    • +
    • 与标准答案误差在 10^-5 以内的结果都被视为正确结果。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1345.leetcode1345 Jump Game IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1345.leetcode1345 Jump Game IV-zh.md" new file mode 100644 index 00000000..1ab99d65 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1345.leetcode1345 Jump Game IV-zh.md" @@ -0,0 +1,96 @@ +# [1345. 跳跃游戏 IV](https://leetcode-cn.com/problems/jump-game-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1345.Jump%20Game%20IV/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,你一开始在数组的第一个元素处(下标为 0)。

    + +

    每一步,你可以从下标 i 跳到下标:

    + +
      +
    • i + 1 满足:i + 1 < arr.length
    • +
    • i - 1 满足:i - 1 >= 0
    • +
    • j 满足:arr[i] == arr[j] 且 i != j
    • +
    + +

    请你返回到达数组最后一个元素的下标处所需的 最少操作次数 。

    + +

    注意:任何时候你都不能跳到数组外面。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [100,-23,-23,404,100,23,23,23,3,404]
    +输出:3
    +解释:那你需要跳跃 3 次,下标依次为 0 --> 4 --> 3 --> 9 。下标 9 为数组的最后一个元素的下标。
    +
    + +

    示例 2:

    + +
    输入:arr = [7]
    +输出:0
    +解释:一开始就在最后一个元素处,所以你不需要跳跃。
    +
    + +

    示例 3:

    + +
    输入:arr = [7,6,9,6,9,6,9,7]
    +输出:1
    +解释:你可以直接从下标 0 处跳到下标 7 处,也就是数组的最后一个元素处。
    +
    + +

    示例 4:

    + +
    输入:arr = [6,1,9]
    +输出:2
    +
    + +

    示例 5:

    + +
    输入:arr = [11,22,7,7,7,7,7,7,7,22,13]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 5 * 10^4
    • +
    • -10^8 <= arr[i] <= 10^8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1346.leetcode1346 Check If N and Its Double Exist-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1346.leetcode1346 Check If N and Its Double Exist-zh.md" new file mode 100644 index 00000000..0073bce2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1346.leetcode1346 Check If N and Its Double Exist-zh.md" @@ -0,0 +1,80 @@ +# [1346. 检查整数及其两倍数是否存在](https://leetcode-cn.com/problems/check-if-n-and-its-double-exist) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1346.Check%20If%20N%20and%20Its%20Double%20Exist/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr,请你检查是否存在两个整数 NM,满足 N 是 M 的两倍(即,N = 2 * M)。

    + +

    更正式地,检查是否存在两个下标 ij 满足:

    + +
      +
    • i != j
    • +
    • 0 <= i, j < arr.length
    • +
    • arr[i] == 2 * arr[j]
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:arr = [10,2,5,3]
    +输出:true
    +解释:N = 10 是 M = 5 的两倍,即 10 = 2 * 5 。
    +
    + +

    示例 2:

    + +
    输入:arr = [7,1,14,11]
    +输出:true
    +解释:N = 14 是 M = 7 的两倍,即 14 = 2 * 7 。
    +
    + +

    示例 3:

    + +
    输入:arr = [3,1,7,11]
    +输出:false
    +解释:在该情况下不存在 N 和 M 满足 N = 2 * M 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 500
    • +
    • -10^3 <= arr[i] <= 10^3
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1347.leetcode1347 Minimum Number of Steps to Make Two Strings Anagram-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1347.leetcode1347 Minimum Number of Steps to Make Two Strings Anagram-zh.md" new file mode 100644 index 00000000..6e1c1b1e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1347.leetcode1347 Minimum Number of Steps to Make Two Strings Anagram-zh.md" @@ -0,0 +1,89 @@ +# [1347. 制造字母异位词的最小步骤数](https://leetcode-cn.com/problems/minimum-number-of-steps-to-make-two-strings-anagram) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1347.Minimum%20Number%20of%20Steps%20to%20Make%20Two%20Strings%20Anagram/README_EN.md) + +## 题目描述 + + + +

    给你两个长度相等的字符串 st。每一个步骤中,你可以选择将 t 中的 任一字符 替换为 另一个字符

    + +

    返回使 t 成为 s 的字母异位词的最小步骤数。

    + +

    字母异位词 指字母相同,但排列不同(也可能相同)的字符串。

    + +

     

    + +

    示例 1:

    + +
    输出:s = "bab", t = "aba"
    +输出:1
    +提示:用 'b' 替换 t 中的第一个 'a',t = "bba" 是 s 的一个字母异位词。
    +
    + +

    示例 2:

    + +
    输出:s = "leetcode", t = "practice"
    +输出:5
    +提示:用合适的字符替换 t 中的 'p', 'r', 'a', 'i' 和 'c',使 t 变成 s 的字母异位词。
    +
    + +

    示例 3:

    + +
    输出:s = "anagram", t = "mangaar"
    +输出:0
    +提示:"anagram" 和 "mangaar" 本身就是一组字母异位词。 
    +
    + +

    示例 4:

    + +
    输出:s = "xxyyzz", t = "xxyyzz"
    +输出:0
    +
    + +

    示例 5:

    + +
    输出:s = "friend", t = "family"
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 50000
    • +
    • s.length == t.length
    • +
    • st 只包含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1348.leetcode1348 Tweet Counts Per Frequency-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1348.leetcode1348 Tweet Counts Per Frequency-zh.md" new file mode 100644 index 00000000..33c7d59f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1348.leetcode1348 Tweet Counts Per Frequency-zh.md" @@ -0,0 +1,86 @@ +# [1348. 推文计数](https://leetcode-cn.com/problems/tweet-counts-per-frequency) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1348.Tweet%20Counts%20Per%20Frequency/README_EN.md) + +## 题目描述 + + + +

    请你实现一个能够支持以下两种方法的推文计数类 TweetCounts

    + +

    1. recordTweet(string tweetName, int time)

    + +
      +
    • 记录推文发布情况:用户 tweetName 在 time(以  为单位)时刻发布了一条推文。
    • +
    + +

    2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)

    + +
      +
    • 返回从开始时间 startTime(以 为单位)到结束时间 endTime(以 为单位)内,每 分 minute时 hour 或者  day (取决于 freq)内指定用户 tweetName 发布的推文总数。
    • +
    • freq 的值始终为 分 minute hour 或者  day 之一,表示获取指定用户 tweetName 发布推文次数的时间间隔。
    • +
    • 第一个时间间隔始终从 startTime 开始,因此时间间隔为 [startTime, startTime + delta*1>,  [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)>,其中 idelta(取决于 freq)都是非负整数。
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
    +[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
    +
    +输出:
    +[null,null,null,null,[2],[2,1],null,[4]]
    +
    +解释:
    +TweetCounts tweetCounts = new TweetCounts();
    +tweetCounts.recordTweet("tweet3", 0);
    +tweetCounts.recordTweet("tweet3", 60);
    +tweetCounts.recordTweet("tweet3", 10);                             // "tweet3" 发布推文的时间分别是 0, 10 和 60 。
    +tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // 返回 [2]。统计频率是每分钟(60 秒),因此只有一个有效时间间隔 [0,60> - > 2 条推文。
    +tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // 返回 [2,1]。统计频率是每分钟(60 秒),因此有两个有效时间间隔 1) [0,60> - > 2 条推文,和 2) [60,61> - > 1 条推文。 
    +tweetCounts.recordTweet("tweet3", 120);                            // "tweet3" 发布推文的时间分别是 0, 10, 60 和 120 。
    +tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210);  // 返回 [4]。统计频率是每小时(3600 秒),因此只有一个有效时间间隔 [0,211> - > 4 条推文。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 同时考虑 recordTweet 和 getTweetCountsPerFrequency,最多有 10000 次操作。
    • +
    • 0 <= time, startTime, endTime <= 10^9
    • +
    • 0 <= endTime - startTime <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1349.leetcode1349 Maximum Students Taking Exam-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1349.leetcode1349 Maximum Students Taking Exam-zh.md" new file mode 100644 index 00000000..81349f12 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1349.leetcode1349 Maximum Students Taking Exam-zh.md" @@ -0,0 +1,91 @@ +# [1349. 参加考试的最大学生数](https://leetcode-cn.com/problems/maximum-students-taking-exam) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1349.Maximum%20Students%20Taking%20Exam/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的矩阵 seats 表示教室中的座位分布。如果座位是坏的(不可用),就用 '#' 表示;否则,用 '.' 表示。

    + +

    学生可以看到左侧、右侧、左上、右上这四个方向上紧邻他的学生的答卷,但是看不到直接坐在他前面或者后面的学生的答卷。请你计算并返回该考场可以容纳的一起参加考试且无法作弊的最大学生人数。

    + +

    学生必须坐在状况良好的座位上。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:seats = [["#",".","#","#",".","#"],
    +              [".","#","#","#","#","."],
    +              ["#",".","#","#",".","#"]]
    +输出:4
    +解释:教师可以让 4 个学生坐在可用的座位上,这样他们就无法在考试中作弊。 
    +
    + +

    示例 2:

    + +
    输入:seats = [[".","#"],
    +              ["#","#"],
    +              ["#","."],
    +              ["#","#"],
    +              [".","#"]]
    +输出:3
    +解释:让所有学生坐在可用的座位上。
    +
    + +

    示例 3:

    + +
    输入:seats = [["#",".",".",".","#"],
    +              [".","#",".","#","."],
    +              [".",".","#",".","."],
    +              [".","#",".","#","."],
    +              ["#",".",".",".","#"]]
    +输出:10
    +解释:让学生坐在第 1、3 和 5 列的可用座位上。
    +
    + +

     

    + +

    提示:

    + +
      +
    • seats 只包含字符 '.' 和'#'
    • +
    • m == seats.length
    • +
    • n == seats[i].length
    • +
    • 1 <= m <= 8
    • +
    • 1 <= n <= 8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1350.leetcode1350 Students With Invalid Departments-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1350.leetcode1350 Students With Invalid Departments-zh.md" new file mode 100644 index 00000000..e183cdb3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1350.leetcode1350 Students With Invalid Departments-zh.md" @@ -0,0 +1,110 @@ +# [1350. 院系无效的学生](https://leetcode-cn.com/problems/students-with-invalid-departments) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1350.Students%20With%20Invalid%20Departments/README_EN.md) + +## 题目描述 + + + +

    院系表: Departments

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id 是该表的主键
    +该表包含一所大学每个院系的 id 信息
    +
    + +

     

    + +

    学生表: Students

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    +| department_id | int     |
    ++---------------+---------+
    +id 是该表的主键
    +该表包含一所大学每个学生的 id 和他/她就读的院系信息
    +
    + +

     

    + +

    写一条 SQL 语句以查询那些所在院系不存在的学生的 id 和姓名

    + +

    可以以任何顺序返回结果

    + +

    下面是返回结果格式的例子

    + +
    +Departments 表:
    ++------+--------------------------+
    +| id   | name                     |
    ++------+--------------------------+
    +| 1    | Electrical Engineering   |
    +| 7    | Computer Engineering     |
    +| 13   | Bussiness Administration |
    ++------+--------------------------+
    +
    +Students 表:
    ++------+----------+---------------+
    +| id   | name     | department_id |
    ++------+----------+---------------+
    +| 23   | Alice    | 1             |
    +| 1    | Bob      | 7             |
    +| 5    | Jennifer | 13            |
    +| 2    | John     | 14            |
    +| 4    | Jasmine  | 77            |
    +| 3    | Steve    | 74            |
    +| 6    | Luis     | 1             |
    +| 8    | Jonathan | 7             |
    +| 7    | Daiana   | 33            |
    +| 11   | Madelynn | 1             |
    ++------+----------+---------------+
    +
    +结果表:
    ++------+----------+
    +| id   | name     |
    ++------+----------+
    +| 2    | John     |
    +| 7    | Daiana   |
    +| 4    | Jasmine  |
    +| 3    | Steve    |
    ++------+----------+
    +
    +John, Daiana, Steve 和 Jasmine 所在的院系分别是 14, 33, 74 和 77, 其中 14, 33, 74 和 77 并不存在于院系表
    +
    + + +## 解法 + + + +外连接查询。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + s.id, s.name +FROM + Students s +LEFT JOIN + Departments d +ON + s.department_id = d.id +WHERE + d.id IS NULL; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1351.leetcode1351 Count Negative Numbers in a Sorted Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1351.leetcode1351 Count Negative Numbers in a Sorted Matrix-zh.md" new file mode 100644 index 00000000..ba78b0f3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1351.leetcode1351 Count Negative Numbers in a Sorted Matrix-zh.md" @@ -0,0 +1,176 @@ +# [1351. 统计有序矩阵中的负数](https://leetcode-cn.com/problems/count-negative-numbers-in-a-sorted-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1351.Count%20Negative%20Numbers%20in%20a%20Sorted%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。 

    + +

    请你统计并返回 grid 中 负数 的数目。

    + +

     

    + +

    示例 1:

    + +
    +输入:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
    +输出:8
    +解释:矩阵中共有 8 个负数。
    +
    + +

    示例 2:

    + +
    +输入:grid = [[3,2],[1,0]]
    +输出:0
    +
    + +

    示例 3:

    + +
    +输入:grid = [[1,-1],[-1,-1]]
    +输出:3
    +
    + +

    示例 4:

    + +
    +输入:grid = [[-1]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • -100 <= grid[i][j] <= 100
    • +
    + +

     

    + +

    进阶:你可以设计一个时间复杂度为 O(n + m) 的解决方案吗?

    + +

     

    + +## 解法 + + + +从右上角开始遍历。当遇到负数时,说明这一列从当前行往下的所有数(共 `m - i` 个数)均为负数,`cnt += (m - i)`,然后 j 往左移动一个位置。否则 i 往下移动一个位置。 + +最后返回 cnt 值即可。 + + + +### **Python3** + + + +```python +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + m, n, cnt = len(grid), len(grid[0]), 0 + i, j = 0, n - 1 + while i < m and j >= 0: + if grid[i][j] < 0: + cnt += (m - i) + j -= 1 + else: + i += 1 + return cnt +``` + +### **Java** + + + +```java +class Solution { + public int countNegatives(int[][] grid) { + int m = grid.length, n = grid[0].length; + int cnt = 0; + for (int i = 0, j = n - 1; j >= 0 && i < m;) { + if (grid[i][j] < 0) { + cnt += (m - i); + --j; + } else { + ++i; + } + } + return cnt; + } +} +``` + +### **TypeScript** + +```ts +function countNegatives(grid: number[][]): number { + let m = grid.length, n = grid[0].length; + let i = 0, j = n - 1; + let ans = 0; + while (i < m && j > -1) { + let cur = grid[i][j]; + if (cur < 0) { + j--; + ans += (m - i); + } else { + i++; + } + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int countNegatives(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int i = 0, j = n - 1, cnt = 0; + while (i < m && j >= 0) { + if (grid[i][j] < 0) { + cnt += (m - i); + --j; + } else { + ++i; + } + } + return cnt; + } +}; +``` + +### **Go** + +```go +func countNegatives(grid [][]int) int { + m, n := len(grid), len(grid[0]) + i, j, cnt := 0, n-1, 0 + for i < m && j >= 0 { + if grid[i][j] < 0 { + cnt += (m - i) + j-- + } else { + i++ + } + } + return cnt +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1352.leetcode1352 Product of the Last K Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1352.leetcode1352 Product of the Last K Numbers-zh.md" new file mode 100644 index 00000000..d97bd3eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1352.leetcode1352 Product of the Last K Numbers-zh.md" @@ -0,0 +1,142 @@ +# [1352. 最后 K 个数的乘积](https://leetcode-cn.com/problems/product-of-the-last-k-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1352.Product%20of%20the%20Last%20K%20Numbers/README_EN.md) + +## 题目描述 + + + +

    请你实现一个「数字乘积类」ProductOfNumbers,要求支持下述两种方法:

    + +

    1. add(int num)

    + +
      +
    • 将数字 num 添加到当前数字列表的最后面。
    • +
    + +

    2. getProduct(int k)

    + +
      +
    • 返回当前数字列表中,最后 k 个数字的乘积。
    • +
    • 你可以假设当前列表中始终 至少 包含 k 个数字。
    • +
    + +

    题目数据保证:任何时候,任一连续数字序列的乘积都在 32-bit 整数范围内,不会溢出。

    + +

     

    + +

    示例:

    + +
    输入:
    +["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
    +[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
    +
    +输出:
    +[null,null,null,null,null,null,20,40,0,null,32]
    +
    +解释:
    +ProductOfNumbers productOfNumbers = new ProductOfNumbers();
    +productOfNumbers.add(3);        // [3]
    +productOfNumbers.add(0);        // [3,0]
    +productOfNumbers.add(2);        // [3,0,2]
    +productOfNumbers.add(5);        // [3,0,2,5]
    +productOfNumbers.add(4);        // [3,0,2,5,4]
    +productOfNumbers.getProduct(2); // 返回 20 。最后 2 个数字的乘积是 5 * 4 = 20
    +productOfNumbers.getProduct(3); // 返回 40 。最后 3 个数字的乘积是 2 * 5 * 4 = 40
    +productOfNumbers.getProduct(4); // 返回  0 。最后 4 个数字的乘积是 0 * 2 * 5 * 4 = 0
    +productOfNumbers.add(8);        // [3,0,2,5,4,8]
    +productOfNumbers.getProduct(2); // 返回 32 。最后 2 个数字的乘积是 4 * 8 = 32 
    +
    + +

     

    + +

    提示:

    + +
      +
    • addgetProduct 两种操作加起来总共不会超过 40000 次。
    • +
    • 0 <= num <= 100
    • +
    • 1 <= k <= 40000
    • +
    + +## 解法 + + + +“前缀积”实现。 + +若遇到 0,则清空前缀积列表。 + + + +### **Python3** + + + +```python +class ProductOfNumbers: + + def __init__(self): + self.pre_product = [] + + def add(self, num: int) -> None: + if num == 0: + self.pre_product = [] + return + if not self.pre_product: + self.pre_product.append(1) + self.pre_product.append(num * self.pre_product[-1]) + + def getProduct(self, k: int) -> int: + n = len(self.pre_product) + return 0 if n <= k else self.pre_product[n - 1] // self.pre_product[n - k - 1] + + +# Your ProductOfNumbers object will be instantiated and called as such: +# obj = ProductOfNumbers() +# obj.add(num) +# param_2 = obj.getProduct(k) +``` + +### **Java** + + + +```java +class ProductOfNumbers { + private List preProduct; + + public ProductOfNumbers() { + preProduct = new ArrayList<>(); + } + + public void add(int num) { + if (num == 0) { + preProduct.clear(); + return; + } + if (preProduct.isEmpty()) { + preProduct.add(1); + } + preProduct.add(num * preProduct.get(preProduct.size() - 1)); + } + + public int getProduct(int k) { + return preProduct.size() <= k ? 0 : preProduct.get(preProduct.size() - 1) / preProduct.get(preProduct.size() - 1 - k); + } +} + +/** + * Your ProductOfNumbers object will be instantiated and called as such: + * ProductOfNumbers obj = new ProductOfNumbers(); + * obj.add(num); + * int param_2 = obj.getProduct(k); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1353.leetcode1353 Maximum Number of Events That Can Be Attended-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1353.leetcode1353 Maximum Number of Events That Can Be Attended-zh.md" new file mode 100644 index 00000000..562ac56d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1353.leetcode1353 Maximum Number of Events That Can Be Attended-zh.md" @@ -0,0 +1,93 @@ +# [1353. 最多可以参加的会议数目](https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1353.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 events,其中 events[i] = [startDayi, endDayi] ,表示会议 i 开始于 startDayi ,结束于 endDayi 。

    + +

    你可以在满足 startDayi <= d <= endDayi 中的任意一天 d 参加会议 i 。注意,一天只能参加一个会议。

    + +

    请你返回你可以参加的 最大 会议数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:events = [[1,2],[2,3],[3,4]]
    +输出:3
    +解释:你可以参加所有的三个会议。
    +安排会议的一种方案如上图。
    +第 1 天参加第一个会议。
    +第 2 天参加第二个会议。
    +第 3 天参加第三个会议。
    +
    + +

    示例 2:

    + +
    输入:events= [[1,2],[2,3],[3,4],[1,2]]
    +输出:4
    +
    + +

    示例 3:

    + +
    输入:events = [[1,4],[4,4],[2,2],[3,4],[1,1]]
    +输出:4
    +
    + +

    示例 4:

    + +
    输入:events = [[1,100000]]
    +输出:1
    +
    + +

    示例 5:

    + +
    输入:events = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7]]
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= events.length <= 10^5
    • +
    • events[i].length == 2
    • +
    • 1 <= events[i][0] <= events[i][1] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1354.leetcode1354 Construct Target Array With Multiple Sums-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1354.leetcode1354 Construct Target Array With Multiple Sums-zh.md" new file mode 100644 index 00000000..7dc24979 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1354.leetcode1354 Construct Target Array With Multiple Sums-zh.md" @@ -0,0 +1,84 @@ +# [1354. 多次求和构造目标数组](https://leetcode-cn.com/problems/construct-target-array-with-multiple-sums) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1354.Construct%20Target%20Array%20With%20Multiple%20Sums/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 target 。一开始,你有一个数组 A ,它的所有元素均为 1 ,你可以执行以下操作:

    + +
      +
    • 令 x 为你数组里所有元素的和
    • +
    • 选择满足 0 <= i < target.size 的任意下标 i ,并让 A 数组里下标为 i 处的值为 x 。
    • +
    • 你可以重复该过程任意次
    • +
    + +

    如果能从 A 开始构造出目标数组 target ,请你返回 True ,否则返回 False 。

    + +

     

    + +

    示例 1:

    + +
    输入:target = [9,3,5]
    +输出:true
    +解释:从 [1, 1, 1] 开始
    +[1, 1, 1], 和为 3 ,选择下标 1
    +[1, 3, 1], 和为 5, 选择下标 2
    +[1, 3, 5], 和为 9, 选择下标 0
    +[9, 3, 5] 完成
    +
    + +

    示例 2:

    + +
    输入:target = [1,1,1,2]
    +输出:false
    +解释:不可能从 [1,1,1,1] 出发构造目标数组。
    +
    + +

    示例 3:

    + +
    输入:target = [8,5]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • N == target.length
    • +
    • 1 <= target.length <= 5 * 10^4
    • +
    • 1 <= target[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1355.leetcode1355 Activity Participants-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1355.leetcode1355 Activity Participants-zh.md" new file mode 100644 index 00000000..0aa979bd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1355.leetcode1355 Activity Participants-zh.md" @@ -0,0 +1,94 @@ +# [1355. 活动参与者](https://leetcode-cn.com/problems/activity-participants) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1355.Activity%20Participants/README_EN.md) + +## 题目描述 + + + +

    表: Friends

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    +| activity      | varchar |
    ++---------------+---------+
    +id 是朋友的 id 和该表的主键
    +name 是朋友的名字
    +activity 是朋友参加的活动的名字
    +
    + +

    表: Activities

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id 是该表的主键
    +name 是活动的名字
    +
    + +

     

    + +

    写一条 SQL 查询那些既没有最多,也没有最少参与者的活动的名字

    + +

    可以以任何顺序返回结果,Activities 表的每项活动的参与者都来自 Friends 表

    + +

    注意:名称相同 id 不同的参与者算作两个人

    + +

    下面是查询结果格式的例子:

    + +
    +Friends 表:
    ++------+--------------+---------------+
    +| id   | name         | activity      |
    ++------+--------------+---------------+
    +| 1    | Jonathan D.  | Eating        |
    +| 2    | Jade W.      | Singing       |
    +| 3    | Victor J.    | Singing       |
    +| 4    | Elvis Q.     | Eating        |
    +| 5    | Daniel A.    | Eating        |
    +| 6    | Bob B.       | Horse Riding  |
    ++------+--------------+---------------+
    +
    +Activities 表:
    ++------+--------------+
    +| id   | name         |
    ++------+--------------+
    +| 1    | Eating       |
    +| 2    | Singing      |
    +| 3    | Horse Riding |
    ++------+--------------+
    +
    +Result 表:
    ++--------------+
    +| activity     |
    ++--------------+
    +| Singing      |
    ++--------------+
    +
    +Eating 活动有三个人参加, 是最多人参加的活动 (Jonathan D. , Elvis Q. and Daniel A.)
    +Horse Riding 活动有一个人参加, 是最少人参加的活动 (Bob B.)
    +Singing 活动有两个人参加 (Victor J. and Jade W.)
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1356.leetcode1356 Sort Integers by The Number of 1 Bits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1356.leetcode1356 Sort Integers by The Number of 1 Bits-zh.md" new file mode 100644 index 00000000..d65f016f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1356.leetcode1356 Sort Integers by The Number of 1 Bits-zh.md" @@ -0,0 +1,91 @@ +# [1356. 根据数字二进制下 1 的数目排序](https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1356.Sort%20Integers%20by%20The%20Number%20of%201%20Bits/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。

    + +

    如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。

    + +

    请你返回排序后的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [0,1,2,3,4,5,6,7,8]
    +输出:[0,1,2,4,8,3,5,6,7]
    +解释:[0] 是唯一一个有 0 个 1 的数。
    +[1,2,4,8] 都有 1 个 1 。
    +[3,5,6] 有 2 个 1 。
    +[7] 有 3 个 1 。
    +按照 1 的个数排序得到的结果数组为 [0,1,2,4,8,3,5,6,7]
    +
    + +

    示例 2:

    + +
    输入:arr = [1024,512,256,128,64,32,16,8,4,2,1]
    +输出:[1,2,4,8,16,32,64,128,256,512,1024]
    +解释:数组中所有整数二进制下都只有 1 个 1 ,所以你需要按照数值大小将它们排序。
    +
    + +

    示例 3:

    + +
    输入:arr = [10000,10000]
    +输出:[10000,10000]
    +
    + +

    示例 4:

    + +
    输入:arr = [2,3,5,7,11,13,17,19]
    +输出:[2,3,5,17,7,11,13,19]
    +
    + +

    示例 5:

    + +
    输入:arr = [10,100,1000,10000]
    +输出:[10,100,10000,1000]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 500
    • +
    • 0 <= arr[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1357.leetcode1357 Apply Discount Every n Orders-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1357.leetcode1357 Apply Discount Every n Orders-zh.md" new file mode 100644 index 00000000..d78cc05d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1357.leetcode1357 Apply Discount Every n Orders-zh.md" @@ -0,0 +1,93 @@ +# [1357. 每隔 n 个顾客打折](https://leetcode-cn.com/problems/apply-discount-every-n-orders) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1357.Apply%20Discount%20Every%20n%20Orders/README_EN.md) + +## 题目描述 + + + +

    超市里正在举行打折活动,每隔 n 个顾客会得到 discount 的折扣。

    + +

    超市里有一些商品,第 i 种商品为 products[i] 且每件单品的价格为 prices[i] 。

    + +

    结账系统会统计顾客的数目,每隔 n 个顾客结账时,该顾客的账单都会打折,折扣为 discount (也就是如果原本账单为 x ,那么实际金额会变成 x - (discount * x) / 100 ),然后系统会重新开始计数。

    + +

    顾客会购买一些商品, product[i] 是顾客购买的第 i 种商品, amount[i] 是对应的购买该种商品的数目。

    + +

    请你实现 Cashier 类:

    + +
      +
    • Cashier(int n, int discount, int[] products, int[] prices) 初始化实例对象,参数分别为打折频率 n ,折扣大小 discount ,超市里的商品列表 products 和它们的价格 prices 。
    • +
    • double getBill(int[] product, int[] amount) 返回账单的实际金额(如果有打折,请返回打折后的结果)。返回结果与标准答案误差在 10^-5 以内都视为正确结果。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入
    +["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
    +[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
    +输出
    +[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
    +解释
    +Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);
    +cashier.getBill([1,2],[1,2]);                        // 返回 500.0, 账单金额为 = 1 * 100 + 2 * 200 = 500.
    +cashier.getBill([3,7],[10,10]);                      // 返回 4000.0
    +cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]);    // 返回 800.0 ,账单原本为 1600.0 ,但由于该顾客是第三位顾客,他将得到 50% 的折扣,所以实际金额为 1600 - 1600 * (50 / 100) = 800 。
    +cashier.getBill([4],[10]);                           // 返回 4000.0
    +cashier.getBill([7,3],[10,10]);                      // 返回 4000.0
    +cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // 返回 7350.0 ,账单原本为 14700.0 ,但由于系统计数再次达到三,该顾客将得到 50% 的折扣,实际金额为 7350.0 。
    +cashier.getBill([2,3,5],[5,3,2]);                    // 返回 2500.0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    • 0 <= discount <= 100
    • +
    • 1 <= products.length <= 200
    • +
    • 1 <= products[i] <= 200
    • +
    • products 列表中 不会 有重复的元素。
    • +
    • prices.length == products.length
    • +
    • 1 <= prices[i] <= 1000
    • +
    • 1 <= product.length <= products.length
    • +
    • product[i] 在 products 出现过。
    • +
    • amount.length == product.length
    • +
    • 1 <= amount[i] <= 1000
    • +
    • 最多有 1000 次对 getBill 函数的调用。
    • +
    • 返回结果与标准答案误差在 10^-5 以内都视为正确结果。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1358.leetcode1358 Number of Substrings Containing All Three Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1358.leetcode1358 Number of Substrings Containing All Three Characters-zh.md" new file mode 100644 index 00000000..1dd0c272 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1358.leetcode1358 Number of Substrings Containing All Three Characters-zh.md" @@ -0,0 +1,73 @@ +# [1358. 包含所有三种字符的子字符串数目](https://leetcode-cn.com/problems/number-of-substrings-containing-all-three-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1358.Number%20of%20Substrings%20Containing%20All%20Three%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,它只包含三种字符 a, b 和 c 。

    + +

    请你返回 a,b 和 c 都 至少 出现过一次的子字符串数目。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "abcabc"
    +输出:10
    +解释:包含 a,b 和 c 各至少一次的子字符串为 "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc"  "abc" (相同字符串算多次)
    +
    + +

    示例 2:

    + +
    输入:s = "aaacb"
    +输出:3
    +解释:包含 a,b 和 c 各至少一次的子字符串为 "aaacb", "aacb"  "acb" 。
    +
    + +

    示例 3:

    + +
    输入:s = "abc"
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= s.length <= 5 x 10^4
    • +
    • s 只包含字符 a,b 和 c 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1359.leetcode1359 Count All Valid Pickup and Delivery Options-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1359.leetcode1359 Count All Valid Pickup and Delivery Options-zh.md" new file mode 100644 index 00000000..aaee3cfe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1359.leetcode1359 Count All Valid Pickup and Delivery Options-zh.md" @@ -0,0 +1,76 @@ +# [1359. 有效的快递序列数目](https://leetcode-cn.com/problems/count-all-valid-pickup-and-delivery-options) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1359.Count%20All%20Valid%20Pickup%20and%20Delivery%20Options/README_EN.md) + +## 题目描述 + + + +

    给你 n 笔订单,每笔订单都需要快递服务。

    + +

    请你统计所有有效的 收件/配送 序列的数目,确保第 i 个物品的配送服务 delivery(i) 总是在其收件服务 pickup(i) 之后。

    + +

    由于答案可能很大,请返回答案对 10^9 + 7 取余的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 1
    +输出:1
    +解释:只有一种序列 (P1, D1),物品 1 的配送服务(D1)在物品 1 的收件服务(P1)后。
    +
    + +

    示例 2:

    + +
    输入:n = 2
    +输出:6
    +解释:所有可能的序列包括:
    +(P1,P2,D1,D2),(P1,P2,D2,D1),(P1,D1,P2,D2),(P2,P1,D1,D2),(P2,P1,D2,D1) 和 (P2,D2,P1,D1)。
    +(P1,D2,P2,D1) 是一个无效的序列,因为物品 2 的收件服务(P2)不应在物品 2 的配送服务(D2)之后。
    +
    + +

    示例 3:

    + +
    输入:n = 3
    +输出:90
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 500
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1360.leetcode1360 Number of Days Between Two Dates-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1360.leetcode1360 Number of Days Between Two Dates-zh.md" new file mode 100644 index 00000000..75bc623a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1360.leetcode1360 Number of Days Between Two Dates-zh.md" @@ -0,0 +1,64 @@ +# [1360. 日期之间隔几天](https://leetcode-cn.com/problems/number-of-days-between-two-dates) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1360.Number%20of%20Days%20Between%20Two%20Dates/README_EN.md) + +## 题目描述 + + + +

    请你编写一个程序来计算两个日期之间隔了多少天。

    + +

    日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。

    + +

     

    + +

    示例 1:

    + +
    输入:date1 = "2019-06-29", date2 = "2019-06-30"
    +输出:1
    +
    + +

    示例 2:

    + +
    输入:date1 = "2020-01-15", date2 = "2019-12-31"
    +输出:15
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定的日期是 1971 年到 2100 年之间的有效日期。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1361.leetcode1361 Validate Binary Tree Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1361.leetcode1361 Validate Binary Tree Nodes-zh.md" new file mode 100644 index 00000000..c7112386 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1361.leetcode1361 Validate Binary Tree Nodes-zh.md" @@ -0,0 +1,90 @@ +# [1361. 验证二叉树](https://leetcode-cn.com/problems/validate-binary-tree-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1361.Validate%20Binary%20Tree%20Nodes/README_EN.md) + +## 题目描述 + + + +

    二叉树上有 n 个节点,按从 0 到 n - 1 编号,其中节点 i 的两个子节点分别是 leftChild[i] 和 rightChild[i]

    + +

    只有 所有 节点能够形成且 形成 一颗 有效的二叉树时,返回 true;否则返回 false

    + +

    如果节点 i 没有左子节点,那么 leftChild[i] 就等于 -1。右子节点也符合该规则。

    + +

    注意:节点没有值,本问题中仅仅使用节点编号。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
    +输出:true
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
    +输出:false
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 2, leftChild = [1,0], rightChild = [-1,-1]
    +输出:false
    +
    + +

    示例 4:

    + +

    + +
    输入:n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    • leftChild.length == rightChild.length == n
    • +
    • -1 <= leftChild[i], rightChild[i] <= n - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1362.leetcode1362 Closest Divisors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1362.leetcode1362 Closest Divisors-zh.md" new file mode 100644 index 00000000..c607e6cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1362.leetcode1362 Closest Divisors-zh.md" @@ -0,0 +1,76 @@ +# [1362. 最接近的因数](https://leetcode-cn.com/problems/closest-divisors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1362.Closest%20Divisors/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 num,请你找出同时满足下面全部要求的两个整数:

    + +
      +
    • 两数乘积等于  num + 1 或 num + 2
    • +
    • 以绝对差进行度量,两数大小最接近
    • +
    + +

    你可以按任意顺序返回这两个整数。

    + +

     

    + +

    示例 1:

    + +
    输入:num = 8
    +输出:[3,3]
    +解释:对于 num + 1 = 9,最接近的两个因数是 3 & 3;对于 num + 2 = 10, 最接近的两个因数是 2 & 5,因此返回 3 & 3 。
    +
    + +

    示例 2:

    + +
    输入:num = 123
    +输出:[5,25]
    +
    + +

    示例 3:

    + +
    输入:num = 999
    +输出:[40,25]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1363.leetcode1363 Largest Multiple of Three-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1363.leetcode1363 Largest Multiple of Three-zh.md" new file mode 100644 index 00000000..ed2a6cf5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1363.leetcode1363 Largest Multiple of Three-zh.md" @@ -0,0 +1,80 @@ +# [1363. 形成三的最大倍数](https://leetcode-cn.com/problems/largest-multiple-of-three) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1363.Largest%20Multiple%20of%20Three/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 digits,你可以通过按任意顺序连接其中某些数字来形成 3 的倍数,请你返回所能得到的最大的 3 的倍数。

    + +

    由于答案可能不在整数数据类型范围内,请以字符串形式返回答案。

    + +

    如果无法得到答案,请返回一个空字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:digits = [8,1,9]
    +输出:"981"
    +
    + +

    示例 2:

    + +
    输入:digits = [8,6,7,1,0]
    +输出:"8760"
    +
    + +

    示例 3:

    + +
    输入:digits = [1]
    +输出:""
    +
    + +

    示例 4:

    + +
    输入:digits = [0,0,0,0,0,0]
    +输出:"0"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= digits.length <= 10^4
    • +
    • 0 <= digits[i] <= 9
    • +
    • 返回的结果不应包含不必要的前导零。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1364.leetcode1364 Number of Trusted Contacts of a Customer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1364.leetcode1364 Number of Trusted Contacts of a Customer-zh.md" new file mode 100644 index 00000000..38fac0b8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1364.leetcode1364 Number of Trusted Contacts of a Customer-zh.md" @@ -0,0 +1,129 @@ +# [1364. 顾客的可信联系人数量](https://leetcode-cn.com/problems/number-of-trusted-contacts-of-a-customer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1364.Number%20of%20Trusted%20Contacts%20of%20a%20Customer/README_EN.md) + +## 题目描述 + + + +

    顾客表:Customers

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| customer_name | varchar |
    +| email         | varchar |
    ++---------------+---------+
    +customer_id 是这张表的主键。
    +此表的每一行包含了某在线商店顾客的姓名和电子邮件。
    +
    + +

     

    + +

    联系方式表:Contacts

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | id      |
    +| contact_name  | varchar |
    +| contact_email | varchar |
    ++---------------+---------+
    +(user_id, contact_email) 是这张表的主键。
    +此表的每一行表示编号为 user_id 的顾客的某位联系人的姓名和电子邮件。
    +此表包含每位顾客的联系人信息,但顾客的联系人不一定存在于顾客表中。
    +
    + +

     

    + +

    发票表:Invoices

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| invoice_id   | int     |
    +| price        | int     |
    +| user_id      | int     |
    ++--------------+---------+
    +invoice_id 是这张表的主键。
    +此表的每一行分别表示编号为 user_id 的顾客拥有有一张编号为 invoice_id、价格为 price 的发票。
    +
    + +

     

    + +

    为每张发票 invoice_id 编写一个SQL查询以查找以下内容:

    + +
      +
    • customer_name:与发票相关的顾客名称。
    • +
    • price:发票的价格。
    • +
    • contacts_cnt:该顾客的联系人数量。
    • +
    • trusted_contacts_cnt:可信联系人的数量:既是该顾客的联系人又是商店顾客的联系人数量(即:可信联系人的电子邮件存在于客户表中)。
    • +
    + +

    将查询的结果按照 invoice_id 排序。

    + +

    查询结果的格式如下例所示:

    + +
    Customers table:
    ++-------------+---------------+--------------------+
    +| customer_id | customer_name | email              |
    ++-------------+---------------+--------------------+
    +| 1           | Alice         | alice@leetcode.com |
    +| 2           | Bob           | bob@leetcode.com   |
    +| 13          | John          | john@leetcode.com  |
    +| 6           | Alex          | alex@leetcode.com  |
    ++-------------+---------------+--------------------+
    +Contacts table:
    ++-------------+--------------+--------------------+
    +| user_id     | contact_name | contact_email      |
    ++-------------+--------------+--------------------+
    +| 1           | Bob          | bob@leetcode.com   |
    +| 1           | John         | john@leetcode.com  |
    +| 1           | Jal          | jal@leetcode.com   |
    +| 2           | Omar         | omar@leetcode.com  |
    +| 2           | Meir         | meir@leetcode.com  |
    +| 6           | Alice        | alice@leetcode.com |
    ++-------------+--------------+--------------------+
    +Invoices table:
    ++------------+-------+---------+
    +| invoice_id | price | user_id |
    ++------------+-------+---------+
    +| 77         | 100   | 1       |
    +| 88         | 200   | 1       |
    +| 99         | 300   | 2       |
    +| 66         | 400   | 2       |
    +| 55         | 500   | 13      |
    +| 44         | 60    | 6       |
    ++------------+-------+---------+
    +Result table:
    ++------------+---------------+-------+--------------+----------------------+
    +| invoice_id | customer_name | price | contacts_cnt | trusted_contacts_cnt |
    ++------------+---------------+-------+--------------+----------------------+
    +| 44         | Alex          | 60    | 1            | 1                    |
    +| 55         | John          | 500   | 0            | 0                    |
    +| 66         | Bob           | 400   | 2            | 0                    |
    +| 77         | Alice         | 100   | 3            | 2                    |
    +| 88         | Alice         | 200   | 3            | 2                    |
    +| 99         | Bob           | 300   | 2            | 0                    |
    ++------------+---------------+-------+--------------+----------------------+
    +Alice 有三位联系人,其中两位(Bob 和 John)是可信联系人。
    +Bob 有两位联系人, 他们中的任何一位都不是可信联系人。
    +Alex 只有一位联系人(Alice),并是一位可信联系人。
    +John 没有任何联系人。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1365.leetcode1365 How Many Numbers Are Smaller Than the Current Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1365.leetcode1365 How Many Numbers Are Smaller Than the Current Number-zh.md" new file mode 100644 index 00000000..02589bd3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1365.leetcode1365 How Many Numbers Are Smaller Than the Current Number-zh.md" @@ -0,0 +1,106 @@ +# [1365. 有多少小于当前数字的数字](https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1365.How%20Many%20Numbers%20Are%20Smaller%20Than%20the%20Current%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。

    + +

    换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i nums[j] < nums[i] 。

    + +

    以数组形式返回答案。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [8,1,2,2,3]
    +输出:[4,0,1,1,3]
    +解释: 
    +对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。 
    +对于 nums[1]=1 不存在比它小的数字。
    +对于 nums[2]=2 存在一个比它小的数字:(1)。 
    +对于 nums[3]=2 存在一个比它小的数字:(1)。 
    +对于 nums[4]=3 存在三个比它小的数字:(1,2 和 2)。
    +
    + +

    示例 2:

    + +
    输入:nums = [6,5,4,8]
    +输出:[2,1,0,3]
    +
    + +

    示例 3:

    + +
    输入:nums = [7,7,7,7]
    +输出:[0,0,0,0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 500
    • +
    • 0 <= nums[i] <= 100
    • +
    + + +## 解法 + + + +计数排序,求前缀和。 + + + +### **Python3** + + + +```python +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + cnt = [0] * 101 + for num in nums: + cnt[num] += 1 + for i in range(1, 101): + cnt[i] += cnt[i - 1] + res = [] + for num in nums: + res.append(0 if num == 0 else cnt[num - 1]) + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] cnt = new int[101]; + for (int e : nums) { + ++cnt[e]; + } + for (int i = 1; i < 101; ++i) { + cnt[i] += cnt[i - 1]; + } + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) { + res[i] = nums[i] == 0 ? 0 : cnt[nums[i] - 1]; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1366.leetcode1366 Rank Teams by Votes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1366.leetcode1366 Rank Teams by Votes-zh.md" new file mode 100644 index 00000000..e91d37f7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1366.leetcode1366 Rank Teams by Votes-zh.md" @@ -0,0 +1,108 @@ +# [1366. 通过投票对团队排名](https://leetcode-cn.com/problems/rank-teams-by-votes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1366.Rank%20Teams%20by%20Votes/README_EN.md) + +## 题目描述 + + + +

    现在有一个特殊的排名系统,依据参赛团队在投票人心中的次序进行排名,每个投票者都需要按从高到低的顺序对参与排名的所有团队进行排位。

    + +

    排名规则如下:

    + +
      +
    • 参赛团队的排名次序依照其所获「排位第一」的票的多少决定。如果存在多个团队并列的情况,将继续考虑其「排位第二」的票的数量。以此类推,直到不再存在并列的情况。
    • +
    • 如果在考虑完所有投票情况后仍然出现并列现象,则根据团队字母的字母顺序进行排名。
    • +
    + +

    给你一个字符串数组 votes 代表全体投票者给出的排位情况,请你根据上述排名规则对所有参赛团队进行排名。

    + +

    请你返回能表示按排名系统 排序后 的所有团队排名的字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:votes = ["ABC","ACB","ABC","ACB","ACB"]
    +输出:"ACB"
    +解释:A 队获得五票「排位第一」,没有其他队获得「排位第一」,所以 A 队排名第一。
    +B 队获得两票「排位第二」,三票「排位第三」。
    +C 队获得三票「排位第二」,两票「排位第三」。
    +由于 C 队「排位第二」的票数较多,所以 C 队排第二,B 队排第三。
    +
    + +

    示例 2:

    + +
    输入:votes = ["WXYZ","XYZW"]
    +输出:"XWYZ"
    +解释:X 队在并列僵局打破后成为排名第一的团队。X 队和 W 队的「排位第一」票数一样,但是 X 队有一票「排位第二」,而 W 没有获得「排位第二」。 
    +
    + +

    示例 3:

    + +
    输入:votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
    +输出:"ZMNAGUEDSJYLBOPHRQICWFXTVK"
    +解释:只有一个投票者,所以排名完全按照他的意愿。
    +
    + +

    示例 4:

    + +
    输入:votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
    +输出:"ABC"
    +解释: 
    +A 队获得两票「排位第一」,两票「排位第二」,两票「排位第三」。
    +B 队获得两票「排位第一」,两票「排位第二」,两票「排位第三」。
    +C 队获得两票「排位第一」,两票「排位第二」,两票「排位第三」。
    +完全并列,所以我们需要按照字母升序排名。
    +
    + +

    示例 5:

    + +
    输入:votes = ["M","M","M","M"]
    +输出:"M"
    +解释:只有 M 队参赛,所以它排名第一。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= votes.length <= 1000
    • +
    • 1 <= votes[i].length <= 26
    • +
    • votes[i].length == votes[j].length for 0 <= i, j < votes.length
    • +
    • votes[i][j] 是英文 大写 字母
    • +
    • votes[i] 中的所有字母都是唯一的
    • +
    • votes[0] 中出现的所有字母 同样也 出现在 votes[j] 中,其中 1 <= j < votes.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1367.leetcode1367 Linked List in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1367.leetcode1367 Linked List in Binary Tree-zh.md" new file mode 100644 index 00000000..185e3222 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1367.leetcode1367 Linked List in Binary Tree-zh.md" @@ -0,0 +1,148 @@ +# [1367. 二叉树中的列表](https://leetcode-cn.com/problems/linked-list-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1367.Linked%20List%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。

    + +

    如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False

    + +

    一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
    +输出:true
    +解释:树中蓝色的节点构成了与链表对应的子路径。
    +
    + +

    示例 2:

    + +

    + +
    输入:head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
    +输出:false
    +解释:二叉树中不存在一一对应链表的路径。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 二叉树和链表中的每个节点的值都满足 1 <= node.val <= 100 。
    • +
    • 链表包含的节点数目在 1 到 100 之间。
    • +
    • 二叉树包含的节点数目在 1 到 2500 之间。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSubPath(self, head: ListNode, root: TreeNode) -> bool: + def dfs(head, root): + if head is None: + return True + if root is None: + return False + if root.val != head.val: + return False + return dfs(head.next, root.left) or dfs(head.next, root.right) + + if root is None: + return False + return dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSubPath(ListNode head, TreeNode root) { + if (root == null) { + return false; + } + return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right); + } + + private boolean dfs(ListNode head, TreeNode root) { + if (head == null) { + return true; + } + if (root == null) { + return false; + } + if (root.val != head.val) { + return false; + } + return dfs(head.next, root.left) || dfs(head.next, root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1368.leetcode1368 Minimum Cost to Make at Least One Valid Path in a Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1368.leetcode1368 Minimum Cost to Make at Least One Valid Path in a Grid-zh.md" new file mode 100644 index 00000000..ff4a5c7a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1368.leetcode1368 Minimum Cost to Make at Least One Valid Path in a Grid-zh.md" @@ -0,0 +1,107 @@ +# [1368. 使网格图至少有一条有效路径的最小代价](https://leetcode-cn.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1368.Minimum%20Cost%20to%20Make%20at%20Least%20One%20Valid%20Path%20in%20a%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的网格图 grid 。 grid 中每个格子都有一个数字,对应着从该格子出发下一步走的方向。 grid[i][j] 中的数字可能为以下几种情况:

    + +
      +
    • 1 ,下一步往右走,也就是你会从 grid[i][j] 走到 grid[i][j + 1]
    • +
    • 2 ,下一步往左走,也就是你会从 grid[i][j] 走到 grid[i][j - 1]
    • +
    • 3 ,下一步往下走,也就是你会从 grid[i][j] 走到 grid[i + 1][j]
    • +
    • 4 ,下一步往上走,也就是你会从 grid[i][j] 走到 grid[i - 1][j]
    • +
    + +

    注意网格图中可能会有 无效数字 ,因为它们可能指向 grid 以外的区域。

    + +

    一开始,你会从最左上角的格子 (0,0) 出发。我们定义一条 有效路径 为从格子 (0,0) 出发,每一步都顺着数字对应方向走,最终在最右下角的格子 (m - 1, n - 1) 结束的路径。有效路径 不需要是最短路径 。

    + +

    你可以花费 cost = 1 的代价修改一个格子中的数字,但每个格子中的数字 只能修改一次 。

    + +

    请你返回让网格图至少有一条有效路径的最小代价。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
    +输出:3
    +解释:你将从点 (0, 0) 出发。
    +到达 (3, 3) 的路径为: (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) 花费代价 cost = 1 使方向向下 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) 花费代价 cost = 1 使方向向下 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) 花费代价 cost = 1 使方向向下 --> (3, 3)
    +总花费为 cost = 3.
    +
    + +

    示例 2:

    + +

    + +
    输入:grid = [[1,1,3],[3,2,2],[1,1,4]]
    +输出:0
    +解释:不修改任何数字你就可以从 (0, 0) 到达 (2, 2) 。
    +
    + +

    示例 3:

    + +

    + +
    输入:grid = [[1,2],[4,3]]
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:grid = [[2,2,2],[2,2,2]]
    +输出:3
    +
    + +

    示例 5:

    + +
    输入:grid = [[4]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1369.leetcode1369 Get the Second Most Recent Activity-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1369.leetcode1369 Get the Second Most Recent Activity-zh.md" new file mode 100644 index 00000000..15dc297e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1369.leetcode1369 Get the Second Most Recent Activity-zh.md" @@ -0,0 +1,71 @@ +# [1369. 获取最近第二次的活动](https://leetcode-cn.com/problems/get-the-second-most-recent-activity) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1369.Get%20the%20Second%20Most%20Recent%20Activity/README_EN.md) + +## 题目描述 + + + +

    表: UserActivity

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| username      | varchar |
    +| activity      | varchar |
    +| startDate     | Date    |
    +| endDate       | Date    |
    ++---------------+---------+
    +该表不包含主键
    +该表包含每个用户在一段时间内进行的活动的信息
    +名为 username 的用户在 startDate 到 endDate 日内有一次活动
    +
    + +

     

    + +

    写一条SQL查询展示每一位用户 最近第二次 的活动

    + +

    如果用户仅有一次活动,返回该活动

    + +

    一个用户不能同时进行超过一项活动,以 任意 顺序返回结果

    + +

    下面是查询结果格式的例子:

    + +
    +UserActivity 表:
    ++------------+--------------+-------------+-------------+
    +| username   | activity     | startDate   | endDate     |
    ++------------+--------------+-------------+-------------+
    +| Alice      | Travel       | 2020-02-12  | 2020-02-20  |
    +| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
    +| Alice      | Travel       | 2020-02-24  | 2020-02-28  |
    +| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
    ++------------+--------------+-------------+-------------+
    +
    +Result 表:
    ++------------+--------------+-------------+-------------+
    +| username   | activity     | startDate   | endDate     |
    ++------------+--------------+-------------+-------------+
    +| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
    +| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
    ++------------+--------------+-------------+-------------+
    +
    +Alice 最近一次的活动是从 2020-02-24 到 2020-02-28 的旅行, 在此之前的 2020-02-21 到 2020-02-23 她进行了舞蹈
    +Bob 只有一条记录,我们就取这条记录
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1370.leetcode1370 Increasing Decreasing String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1370.leetcode1370 Increasing Decreasing String-zh.md" new file mode 100644 index 00000000..3d17471d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1370.leetcode1370 Increasing Decreasing String-zh.md" @@ -0,0 +1,101 @@ +# [1370. 上升下降字符串](https://leetcode-cn.com/problems/increasing-decreasing-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1370.Increasing%20Decreasing%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,请你根据下面的算法重新构造字符串:

    + +
      +
    1. s 中选出 最小 的字符,将它 接在 结果字符串的后面。
    2. +
    3. s 剩余字符中选出 最小 的字符,且该字符比上一个添加的字符大,将它 接在 结果字符串后面。
    4. +
    5. 重复步骤 2 ,直到你没法从 s 中选择字符。
    6. +
    7. s 中选出 最大 的字符,将它 接在 结果字符串的后面。
    8. +
    9. s 剩余字符中选出 最大 的字符,且该字符比上一个添加的字符小,将它 接在 结果字符串后面。
    10. +
    11. 重复步骤 5 ,直到你没法从 s 中选择字符。
    12. +
    13. 重复步骤 1 到 6 ,直到 s 中所有字符都已经被选过。
    14. +
    + +

    在任何一步中,如果最小或者最大字符不止一个 ,你可以选择其中任意一个,并将其添加到结果字符串。

    + +

    请你返回将 s 中字符重新排序后的 结果字符串

    + +

     

    + +

    示例 1:

    + +
    输入:s = "aaaabbbbcccc"
    +输出:"abccbaabccba"
    +解释:第一轮的步骤 1,2,3 后,结果字符串为 result = "abc"
    +第一轮的步骤 4,5,6 后,结果字符串为 result = "abccba"
    +第一轮结束,现在 s = "aabbcc" ,我们再次回到步骤 1
    +第二轮的步骤 1,2,3 后,结果字符串为 result = "abccbaabc"
    +第二轮的步骤 4,5,6 后,结果字符串为 result = "abccbaabccba"
    +
    + +

    示例 2:

    + +
    输入:s = "rat"
    +输出:"art"
    +解释:单词 "rat" 在上述算法重排序以后变成 "art"
    +
    + +

    示例 3:

    + +
    输入:s = "leetcode"
    +输出:"cdelotee"
    +
    + +

    示例 4:

    + +
    输入:s = "ggggggg"
    +输出:"ggggggg"
    +
    + +

    示例 5:

    + +
    输入:s = "spo"
    +输出:"ops"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1371.leetcode1371 Find the Longest Substring Containing Vowels in Even Counts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1371.leetcode1371 Find the Longest Substring Containing Vowels in Even Counts-zh.md" new file mode 100644 index 00000000..88973a37 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1371.leetcode1371 Find the Longest Substring Containing Vowels in Even Counts-zh.md" @@ -0,0 +1,75 @@ +# [1371. 每个元音包含偶数次的最长子字符串](https://leetcode-cn.com/problems/find-the-longest-substring-containing-vowels-in-even-counts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1371.Find%20the%20Longest%20Substring%20Containing%20Vowels%20in%20Even%20Counts/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,请你返回满足以下条件的最长子字符串的长度:每个元音字母,即 'a','e','i','o','u' ,在子字符串中都恰好出现了偶数次。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "eleetminicoworoep"
    +输出:13
    +解释:最长子字符串是 "leetminicowor" ,它包含 e,i,o 各 2 个,以及 0 个 au 。
    +
    + +

    示例 2:

    + +
    +输入:s = "leetcodeisgreat"
    +输出:5
    +解释:最长子字符串是 "leetc" ,其中包含 2 个 e 。
    +
    + +

    示例 3:

    + +
    +输入:s = "bcbcbc"
    +输出:6
    +解释:这个示例中,字符串 "bcbcbc" 本身就是最长的,因为所有的元音 a,e,i,o,u 都出现了 0 次。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 5 x 10^5
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1372.leetcode1372 Longest ZigZag Path in a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1372.leetcode1372 Longest ZigZag Path in a Binary Tree-zh.md" new file mode 100644 index 00000000..77ccb341 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1372.leetcode1372 Longest ZigZag Path in a Binary Tree-zh.md" @@ -0,0 +1,86 @@ +# [1372. 二叉树中的最长交错路径](https://leetcode-cn.com/problems/longest-zigzag-path-in-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1372.Longest%20ZigZag%20Path%20in%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵以 root 为根的二叉树,二叉树中的交错路径定义如下:

    + +
      +
    • 选择二叉树中 任意 节点和一个方向(左或者右)。
    • +
    • 如果前进方向为右,那么移动到当前节点的的右子节点,否则移动到它的左子节点。
    • +
    • 改变前进方向:左变右或者右变左。
    • +
    • 重复第二步和第三步,直到你在树中无法继续移动。
    • +
    + +

    交错路径的长度定义为:访问过的节点数目 - 1(单个节点的路径长度为 0 )。

    + +

    请你返回给定树中最长 交错路径 的长度。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
    +输出:3
    +解释:蓝色节点为树中最长交错路径(右 -> 左 -> 右)。
    +
    + +

    示例 2:

    + +

    + +
    输入:root = [1,1,1,null,1,null,null,1,1,null,1]
    +输出:4
    +解释:蓝色节点为树中最长交错路径(左 -> 右 -> 左 -> 右)。
    +
    + +

    示例 3:

    + +
    输入:root = [1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每棵树最多有 50000 个节点。
    • +
    • 每个节点的值在 [1, 100] 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1373.leetcode1373 Maximum Sum BST in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1373.leetcode1373 Maximum Sum BST in Binary Tree-zh.md" new file mode 100644 index 00000000..e7dd38a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1373.leetcode1373 Maximum Sum BST in Binary Tree-zh.md" @@ -0,0 +1,101 @@ +# [1373. 二叉搜索子树的最大键值和](https://leetcode-cn.com/problems/maximum-sum-bst-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1373.Maximum%20Sum%20BST%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵以 root 为根的 二叉树 ,请你返回 任意 二叉搜索子树的最大键值和。

    + +

    二叉搜索树的定义如下:

    + +
      +
    • 任意节点的左子树中的键值都 小于 此节点的键值。
    • +
    • 任意节点的右子树中的键值都 大于 此节点的键值。
    • +
    • 任意节点的左子树和右子树都是二叉搜索树。
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
    +输出:20
    +解释:键值为 3 的子树是和最大的二叉搜索树。
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [4,3,null,1,2]
    +输出:2
    +解释:键值为 2 的单节点子树是和最大的二叉搜索树。
    +
    + +

    示例 3:

    + +
    +输入:root = [-4,-2,-5]
    +输出:0
    +解释:所有节点键值都为负数,和最大的二叉搜索树为空。
    +
    + +

    示例 4:

    + +
    +输入:root = [2,1,3]
    +输出:6
    +
    + +

    示例 5:

    + +
    +输入:root = [5,4,8,3,null,6,3]
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 每棵树有 140000 个节点。
    • +
    • 每个节点的键值在 [-4 * 10^4 , 4 * 10^4] 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1374.leetcode1374 Generate a String With Characters That Have Odd Counts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1374.leetcode1374 Generate a String With Characters That Have Odd Counts-zh.md" new file mode 100644 index 00000000..db9aa5f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1374.leetcode1374 Generate a String With Characters That Have Odd Counts-zh.md" @@ -0,0 +1,72 @@ +# [1374. 生成每种字符都是奇数个的字符串](https://leetcode-cn.com/problems/generate-a-string-with-characters-that-have-odd-counts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1374.Generate%20a%20String%20With%20Characters%20That%20Have%20Odd%20Counts/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,请你返回一个含 n 个字符的字符串,其中每种字符在该字符串中都恰好出现 奇数次

    + +

    返回的字符串必须只含小写英文字母。如果存在多个满足题目要求的字符串,则返回其中任意一个即可。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 4
    +输出:"pppz"
    +解释:"pppz" 是一个满足题目要求的字符串,因为 'p' 出现 3 次,且 'z' 出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ohhh" 和 "love"。
    +
    + +

    示例 2:

    + +
    输入:n = 2
    +输出:"xy"
    +解释:"xy" 是一个满足题目要求的字符串,因为 'x' 和 'y' 各出现 1 次。当然,还有很多其他字符串也满足题目要求,比如:"ag" 和 "ur"。
    +
    + +

    示例 3:

    + +
    输入:n = 7
    +输出:"holasss"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 500
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1375.leetcode1375 Bulb Switcher III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1375.leetcode1375 Bulb Switcher III-zh.md" new file mode 100644 index 00000000..834e151e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1375.leetcode1375 Bulb Switcher III-zh.md" @@ -0,0 +1,99 @@ +# [1375. 灯泡开关 III](https://leetcode-cn.com/problems/bulb-switcher-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1375.Bulb%20Switcher%20III/README_EN.md) + +## 题目描述 + + + +

    房间中有 n 枚灯泡,编号从 1n,自左向右排成一排。最初,所有的灯都是关着的。

    + +

    k  时刻( k 的取值范围是 0n - 1),我们打开 light[k] 这个灯。

    + +

    灯的颜色要想 变成蓝色 就必须同时满足下面两个条件:

    + +
      +
    • 灯处于打开状态。
    • +
    • 排在它之前(左侧)的所有灯也都处于打开状态。
    • +
    + +

    请返回能够让 所有开着的 灯都 变成蓝色 的时刻 数目 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:light = [2,1,3,5,4]
    +输出:3
    +解释:所有开着的灯都变蓝的时刻分别是 1,2 和 4 。
    +
    + +

    示例 2:

    + +
    输入:light = [3,2,4,1,5]
    +输出:2
    +解释:所有开着的灯都变蓝的时刻分别是 3 和 4(index-0)。
    +
    + +

    示例 3:

    + +
    输入:light = [4,1,2,3]
    +输出:1
    +解释:所有开着的灯都变蓝的时刻是 3(index-0)。
    +第 4 个灯在时刻 3 变蓝。
    +
    + +

    示例 4:

    + +
    输入:light = [2,1,4,3,6,5]
    +输出:3
    +
    + +

    示例 5:

    + +
    输入:light = [1,2,3,4,5,6]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == light.length
    • +
    • 1 <= n <= 5 * 10^4
    • +
    • light[1, 2, ..., n] 的一个排列。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1376.leetcode1376 Time Needed to Inform All Employees-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1376.leetcode1376 Time Needed to Inform All Employees-zh.md" new file mode 100644 index 00000000..35ffdbdf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1376.leetcode1376 Time Needed to Inform All Employees-zh.md" @@ -0,0 +1,113 @@ +# [1376. 通知所有员工所需的时间](https://leetcode-cn.com/problems/time-needed-to-inform-all-employees) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1376.Time%20Needed%20to%20Inform%20All%20Employees/README_EN.md) + +## 题目描述 + + + +

    公司里有 n 名员工,每个员工的 ID 都是独一无二的,编号从 0n - 1。公司的总负责人通过 headID 进行标识。

    + +

    manager 数组中,每个员工都有一个直属负责人,其中 manager[i] 是第 i 名员工的直属负责人。对于总负责人,manager[headID] = -1。题目保证从属关系可以用树结构显示。

    + +

    公司总负责人想要向公司所有员工通告一条紧急消息。他将会首先通知他的直属下属们,然后由这些下属通知他们的下属,直到所有的员工都得知这条紧急消息。

    + +

    i 名员工需要 informTime[i] 分钟来通知它的所有直属下属(也就是说在 informTime[i] 分钟后,他的所有直属下属都可以开始传播这一消息)。

    + +

    返回通知所有员工这一紧急消息所需要的 分钟数

    + +

     

    + +

    示例 1:

    + +
    输入:n = 1, headID = 0, manager = [-1], informTime = [0]
    +输出:0
    +解释:公司总负责人是该公司的唯一一名员工。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
    +输出:1
    +解释:id = 2 的员工是公司的总负责人,也是其他所有员工的直属负责人,他需要 1 分钟来通知所有员工。
    +上图显示了公司员工的树结构。
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 7, headID = 6, manager = [1,2,3,4,5,6,-1], informTime = [0,6,5,4,3,2,1]
    +输出:21
    +解释:总负责人 id = 6。他将在 1 分钟内通知 id = 5 的员工。
    +id = 5 的员工将在 2 分钟内通知 id = 4 的员工。
    +id = 4 的员工将在 3 分钟内通知 id = 3 的员工。
    +id = 3 的员工将在 4 分钟内通知 id = 2 的员工。
    +id = 2 的员工将在 5 分钟内通知 id = 1 的员工。
    +id = 1 的员工将在 6 分钟内通知 id = 0 的员工。
    +所需时间 = 1 + 2 + 3 + 4 + 5 + 6 = 21 。
    +
    + +

    示例 4:

    + +
    输入:n = 15, headID = 0, manager = [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], informTime = [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0]
    +输出:3
    +解释:第一分钟总负责人通知员工 1 和 2 。
    +第二分钟他们将会通知员工 3, 4, 5 和 6 。
    +第三分钟他们将会通知剩下的员工。
    +
    + +

    示例 5:

    + +
    输入:n = 4, headID = 2, manager = [3,3,-1,2], informTime = [0,0,162,914]
    +输出:1076
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • 0 <= headID < n
    • +
    • manager.length == n
    • +
    • 0 <= manager[i] < n
    • +
    • manager[headID] == -1
    • +
    • informTime.length == n
    • +
    • 0 <= informTime[i] <= 1000
    • +
    • 如果员工 i 没有下属,informTime[i] == 0
    • +
    • 题目 保证 所有员工都可以收到通知。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1377.leetcode1377 Frog Position After T Seconds-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1377.leetcode1377 Frog Position After T Seconds-zh.md" new file mode 100644 index 00000000..1946ab55 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1377.leetcode1377 Frog Position After T Seconds-zh.md" @@ -0,0 +1,91 @@ +# [1377. T 秒后青蛙的位置](https://leetcode-cn.com/problems/frog-position-after-t-seconds) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1377.Frog%20Position%20After%20T%20Seconds/README_EN.md) + +## 题目描述 + + + +

    给你一棵由 n 个顶点组成的无向树,顶点编号从 1 到 n。青蛙从 顶点 1 开始起跳。规则如下:

    + +
      +
    • 在一秒内,青蛙从它所在的当前顶点跳到另一个 未访问 过的顶点(如果它们直接相连)。
    • +
    • 青蛙无法跳回已经访问过的顶点。
    • +
    • 如果青蛙可以跳到多个不同顶点,那么它跳到其中任意一个顶点上的机率都相同。
    • +
    • 如果青蛙不能跳到任何未访问过的顶点上,那么它每次跳跃都会停留在原地。
    • +
    + +

    无向树的边用数组 edges 描述,其中 edges[i] = [fromi, toi] 意味着存在一条直接连通 fromitoi 两个顶点的边。

    + +

    返回青蛙在 t 秒后位于目标顶点 target 上的概率。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
    +输出:0.16666666666666666 
    +解释:上图显示了青蛙的跳跃路径。青蛙从顶点 1 起跳,第 1 秒 有 1/3 的概率跳到顶点 2 ,然后第 2 秒 有 1/2 的概率跳到顶点 4,因此青蛙在 2 秒后位于顶点 4 的概率是 1/3 * 1/2 = 1/6 = 0.16666666666666666 。 
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
    +输出:0.3333333333333333
    +解释:上图显示了青蛙的跳跃路径。青蛙从顶点 1 起跳,有 1/3 = 0.3333333333333333 的概率能够 1 秒 后跳到顶点 7 。 
    +
    + +

    示例 3:

    + +
    输入:n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
    +输出:0.16666666666666666
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 100
    • +
    • edges.length == n-1
    • +
    • edges[i].length == 2
    • +
    • 1 <= edges[i][0], edges[i][1] <= n
    • +
    • 1 <= t <= 50
    • +
    • 1 <= target <= n
    • +
    • 与准确值误差在 10^-5 之内的结果将被判定为正确。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1378.leetcode1378 Replace Employee ID With The Unique Identifier-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1378.leetcode1378 Replace Employee ID With The Unique Identifier-zh.md" new file mode 100644 index 00000000..7bd78b52 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1378.leetcode1378 Replace Employee ID With The Unique Identifier-zh.md" @@ -0,0 +1,105 @@ +# [1378. 使用唯一标识码替换员工ID](https://leetcode-cn.com/problems/replace-employee-id-with-the-unique-identifier) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1378.Replace%20Employee%20ID%20With%20The%20Unique%20Identifier/README_EN.md) + +## 题目描述 + + + +

    Employees 表:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id 是这张表的主键。
    +这张表的每一行分别代表了某公司其中一位员工的名字和 ID 。
    +
    + +

     

    + +

    EmployeeUNI 表:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| unique_id     | int     |
    ++---------------+---------+
    +(id, unique_id) 是这张表的主键。
    +这张表的每一行包含了该公司某位员工的 ID 和他的唯一标识码(unique ID)。
    +
    + +

     

    + +

    写一段SQL查询来展示每位用户的 唯一标识码(unique ID );如果某位员工没有唯一标识码,使用 null 填充即可。

    + +

    你可以以 任意 顺序返回结果表。

    + +

    查询结果的格式如下例所示:

    + +
    +Employees table:
    ++----+----------+
    +| id | name     |
    ++----+----------+
    +| 1  | Alice    |
    +| 7  | Bob      |
    +| 11 | Meir     |
    +| 90 | Winston  |
    +| 3  | Jonathan |
    ++----+----------+
    +
    +EmployeeUNI table:
    ++----+-----------+
    +| id | unique_id |
    ++----+-----------+
    +| 3  | 1         |
    +| 11 | 2         |
    +| 90 | 3         |
    ++----+-----------+
    +
    +EmployeeUNI table:
    ++-----------+----------+
    +| unique_id | name     |
    ++-----------+----------+
    +| null      | Alice    |
    +| null      | Bob      |
    +| 2         | Meir     |
    +| 3         | Winston  |
    +| 1         | Jonathan |
    ++-----------+----------+
    +
    +Alice and Bob 没有唯一标识码, 因此我们使用 null 替代。
    +Meir 的唯一标识码是 2 。
    +Winston 的唯一标识码是 3 。
    +Jonathan 唯一标识码是 1 。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + b.unique_id AS unique_id, + a.name AS name +FROM + Employees a +LEFT JOIN + EmployeeUNI b +ON + a.id = b.id; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1379.leetcode1379 Find a Corresponding Node of a Binary Tree in a Clone of That Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1379.leetcode1379 Find a Corresponding Node of a Binary Tree in a Clone of That Tree-zh.md" new file mode 100644 index 00000000..a2244a88 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1379.leetcode1379 Find a Corresponding Node of a Binary Tree in a Clone of That Tree-zh.md" @@ -0,0 +1,112 @@ +# [1379. 找出克隆二叉树中的相同节点](https://leetcode-cn.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1379.Find%20a%20Corresponding%20Node%20of%20a%20Binary%20Tree%20in%20a%20Clone%20of%20That%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你两棵二叉树,原始树 original 和克隆树 cloned,以及一个位于原始树 original 中的目标节点 target

    + +

    其中,克隆树 cloned 是原始树 original 的一个 副本

    + +

    请找出在树 cloned 中,与 target 相同 的节点,并返回对该节点的引用(在 C/C++ 等有指针的语言中返回 节点指针,其他语言返回节点本身)。

    + +

     

    + +

    注意:

    + +
      +
    1. 不能 对两棵二叉树,以及 target 节点进行更改。
    2. +
    3. 只能 返回对克隆树 cloned 中已有的节点的引用。
    4. +
    + +
      +
    + +

    进阶:如果树中允许出现值相同的节点,你将如何解答?

    + +

     

    + +
      +
    + +

    示例 1:

    + +

    + +
    输入: tree = [7,4,3,null,null,6,19], target = 3
    +输出: 3
    +解释: 上图画出了树 original 和 cloned。target 节点在树 original 中,用绿色标记。答案是树 cloned 中的黄颜色的节点(其他示例类似)。
    + +

    示例 2:

    + +

    + +
    输入: tree = [7], target =  7
    +输出: 7
    +
    + +

    示例 3:

    + +

    + +
    输入: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
    +输出: 4
    +
    + +

    示例 4:

    + +

    + +
    输入: tree = [1,2,3,4,5,6,7,8,9,10], target = 5
    +输出: 5
    +
    + +

    示例 5:

    + +

    + +
    输入: tree = [1,2,null,3], target = 2
    +输出: 2
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的数量范围为 [1, 10^4] 。
    • +
    • 同一棵树中,没有值相同的节点。
    • +
    • target 节点是树 original 中的一个节点,并且不会是 null 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1380.leetcode1380 Lucky Numbers in a Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1380.leetcode1380 Lucky Numbers in a Matrix-zh.md" new file mode 100644 index 00000000..55a59d13 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1380.leetcode1380 Lucky Numbers in a Matrix-zh.md" @@ -0,0 +1,112 @@ +# [1380. 矩阵中的幸运数](https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1380.Lucky%20Numbers%20in%20a%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。

    + +

    幸运数是指矩阵中满足同时下列两个条件的元素:

    + +
      +
    • 在同一行的所有元素中最小
    • +
    • 在同一列的所有元素中最大
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:matrix = [[3,7,8],[9,11,13],[15,16,17]]
    +输出:[15]
    +解释:15 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。
    +
    + +

    示例 2:

    + +
    输入:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
    +输出:[12]
    +解释:12 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。
    +
    + +

    示例 3:

    + +
    输入:matrix = [[7,8],[1,2]]
    +输出:[7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= n, m <= 50
    • +
    • 1 <= matrix[i][j] <= 10^5
    • +
    • 矩阵中的所有元素都是不同的
    • +
    + + +## 解法 + + + +取行最小值与列最大值的交集即可。 + + + +### **Python3** + + + +```python +class Solution: + def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: + row_min = {min(rows) for rows in matrix} + col_max = {max(cols) for cols in zip(*matrix)} + return [e for e in row_min if e in col_max] +``` + +### **Java** + + + +```java +class Solution { + public List luckyNumbers (int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + Set rowMin = new HashSet<>(); + List res = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + int min = Integer.MAX_VALUE; + for (int j = 0; j < n; ++j) { + min = Math.min(min, matrix[i][j]); + } + rowMin.add(min); + } + + for (int j = 0; j < n; ++j) { + int max = Integer.MIN_VALUE; + for (int i = 0; i < m; ++i) { + max = Math.max(max, matrix[i][j]); + } + if (rowMin.contains(max)) { + res.add(max); + } + + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1381.leetcode1381 Design a Stack With Increment Operation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1381.leetcode1381 Design a Stack With Increment Operation-zh.md" new file mode 100644 index 00000000..42ec085f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1381.leetcode1381 Design a Stack With Increment Operation-zh.md" @@ -0,0 +1,143 @@ +# [1381. 设计一个支持增量操作的栈](https://leetcode-cn.com/problems/design-a-stack-with-increment-operation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1381.Design%20a%20Stack%20With%20Increment%20Operation/README_EN.md) + +## 题目描述 + + + +

    请你设计一个支持下述操作的栈。

    + +

    实现自定义栈类 CustomStack

    + +
      +
    • CustomStack(int maxSize):用 maxSize 初始化对象,maxSize 是栈中最多能容纳的元素数量,栈在增长到 maxSize 之后则不支持 push 操作。
    • +
    • void push(int x):如果栈还未增长到 maxSize ,就将 x 添加到栈顶。
    • +
    • int pop():弹出栈顶元素,并返回栈顶的值,或栈为空时返回 -1
    • +
    • void inc(int k, int val):栈底的 k 个元素的值都增加 val 。如果栈中元素总数小于 k ,则栈中的所有元素都增加 val
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]
    +[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
    +输出:
    +[null,null,null,2,null,null,null,null,null,103,202,201,-1]
    +解释:
    +CustomStack customStack = new CustomStack(3); // 栈是空的 []
    +customStack.push(1);                          // 栈变为 [1]
    +customStack.push(2);                          // 栈变为 [1, 2]
    +customStack.pop();                            // 返回 2 --> 返回栈顶值 2,栈变为 [1]
    +customStack.push(2);                          // 栈变为 [1, 2]
    +customStack.push(3);                          // 栈变为 [1, 2, 3]
    +customStack.push(4);                          // 栈仍然是 [1, 2, 3],不能添加其他元素使栈大小变为 4
    +customStack.increment(5, 100);                // 栈变为 [101, 102, 103]
    +customStack.increment(2, 100);                // 栈变为 [201, 202, 103]
    +customStack.pop();                            // 返回 103 --> 返回栈顶值 103,栈变为 [201, 202]
    +customStack.pop();                            // 返回 202 --> 返回栈顶值 202,栈变为 [201]
    +customStack.pop();                            // 返回 201 --> 返回栈顶值 201,栈变为 []
    +customStack.pop();                            // 返回 -1 --> 栈为空,返回 -1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= maxSize <= 1000
    • +
    • 1 <= x <= 1000
    • +
    • 1 <= k <= 1000
    • +
    • 0 <= val <= 100
    • +
    • 每种方法 incrementpush 以及 pop 分别最多调用 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class CustomStack: + + def __init__(self, maxSize: int): + self.s = [0] * maxSize + self.tail = 0 + + def push(self, x: int) -> None: + if self.tail < len(self.s): + self.s[self.tail] = x + self.tail += 1 + + def pop(self) -> int: + if self.tail == 0: + return -1 + self.tail -= 1 + return self.s[self.tail] + + def increment(self, k: int, val: int) -> None: + for i in range(min(k, self.tail)): + self.s[i] += val + + +# Your CustomStack object will be instantiated and called as such: +# obj = CustomStack(maxSize) +# obj.push(x) +# param_2 = obj.pop() +# obj.increment(k,val) +``` + +### **Java** + + + +```java +class CustomStack { + private int[] s; + private int tail; + + public CustomStack(int maxSize) { + s = new int[maxSize]; + } + + public void push(int x) { + if (tail < s.length) { + s[tail++] = x; + } + } + + public int pop() { + return tail == 0 ? -1 : s[--tail]; + } + + public void increment(int k, int val) { + for (int i = 0; i < Math.min(k, tail); ++i) { + s[i] += val; + } + } +} + +/** + * Your CustomStack object will be instantiated and called as such: + * CustomStack obj = new CustomStack(maxSize); + * obj.push(x); + * int param_2 = obj.pop(); + * obj.increment(k,val); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1382.leetcode1382 Balance a Binary Search Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1382.leetcode1382 Balance a Binary Search Tree-zh.md" new file mode 100644 index 00000000..dabbd037 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1382.leetcode1382 Balance a Binary Search Tree-zh.md" @@ -0,0 +1,64 @@ +# [1382. 将二叉搜索树变平衡](https://leetcode-cn.com/problems/balance-a-binary-search-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1382.Balance%20a%20Binary%20Search%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。

    + +

    如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的

    + +

    如果有多种构造方法,请你返回任意一种。

    + +

     

    + +

    示例:

    + +

    + +
    输入:root = [1,null,2,null,3,null,4,null,null]
    +输出:[2,1,3,null,null,null,4]
    +解释:这不是唯一的正确答案,[3,1,4,null,2,null,null] 也是一个可行的构造方案。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树节点的数目在 1 到 10^4 之间。
    • +
    • 树节点的值互不相同,且在 1 到 10^5 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1383.leetcode1383 Maximum Performance of a Team-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1383.leetcode1383 Maximum Performance of a Team-zh.md" new file mode 100644 index 00000000..ceba541b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1383.leetcode1383 Maximum Performance of a Team-zh.md" @@ -0,0 +1,79 @@ +# [1383. 最大的团队表现值](https://leetcode-cn.com/problems/maximum-performance-of-a-team) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1383.Maximum%20Performance%20of%20a%20Team/README_EN.md) + +## 题目描述 + + + +

    公司有编号为 1 到 n 的 n 个工程师,给你两个数组 speed 和 efficiency ,其中 speed[i] 和 efficiency[i] 分别代表第 i 位工程师的速度和效率。请你返回由最多 k 个工程师组成的 ​​​​​​最大团队表现值 ,由于答案可能很大,请你返回结果对 10^9 + 7 取余后的结果。

    + +

    团队表现值 的定义为:一个团队中「所有工程师速度的和」乘以他们「效率值中的最小值」。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
    +输出:60
    +解释:
    +我们选择工程师 2(speed=10 且 efficiency=4)和工程师 5(speed=5 且 efficiency=7)。他们的团队表现值为 performance = (10 + 5) * min(4, 7) = 60 。
    +
    + +

    示例 2:

    + +
    输入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
    +输出:68
    +解释:
    +此示例与第一个示例相同,除了 k = 3 。我们可以选择工程师 1 ,工程师 2 和工程师 5 得到最大的团队表现值。表现值为 performance = (2 + 10 + 5) * min(5, 4, 7) = 68 。
    +
    + +

    示例 3:

    + +
    输入:n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4
    +输出:72
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • speed.length == n
    • +
    • efficiency.length == n
    • +
    • 1 <= speed[i] <= 10^5
    • +
    • 1 <= efficiency[i] <= 10^8
    • +
    • 1 <= k <= n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1384.leetcode1384 Total Sales Amount by Year-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1384.leetcode1384 Total Sales Amount by Year-zh.md" new file mode 100644 index 00000000..f7bf80db --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1384.leetcode1384 Total Sales Amount by Year-zh.md" @@ -0,0 +1,96 @@ +# [1384. 按年度列出销售总额](https://leetcode-cn.com/problems/total-sales-amount-by-year) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1384.Total%20Sales%20Amount%20by%20Year/README_EN.md) + +## 题目描述 + + + +

     Product 表:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    ++---------------+---------+
    +product_id 是这张表的主键。
    +product_name 是产品的名称。
    +
    + +

     

    + +

    Sales 表:

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| product_id          | int     |
    +| period_start        | date    |
    +| period_end          | date    |
    +| average_daily_sales | int     |
    ++---------------------+---------+
    +product_id 是这张表的主键。
    +period_start 和 period_end 是该产品销售期的起始日期和结束日期,且这两个日期包含在销售期内。
    +average_daily_sales 列存储销售期内该产品的日平均销售额。
    +
    + +

     

    + +

    编写一段 SQL 查询每个产品每年的总销售额,并包含 product_id, product_name 以及 report_year 等信息。

    + +

    销售年份的日期介于 2018 年到 2020 年之间。你返回的结果需要按 product_id 和 report_year 排序

    + +

    查询结果格式如下例所示:

    + +
    +Product table:
    ++------------+--------------+
    +| product_id | product_name |
    ++------------+--------------+
    +| 1          | LC Phone     |
    +| 2          | LC T-Shirt   |
    +| 3          | LC Keychain  |
    ++------------+--------------+
    +
    +Sales table:
    ++------------+--------------+-------------+---------------------+
    +| product_id | period_start | period_end  | average_daily_sales |
    ++------------+--------------+-------------+---------------------+
    +| 1          | 2019-01-25   | 2019-02-28  | 100                 |
    +| 2          | 2018-12-01   | 2020-01-01  | 10                  |
    +| 3          | 2019-12-01   | 2020-01-31  | 1                   |
    ++------------+--------------+-------------+---------------------+
    +
    +Result table:
    ++------------+--------------+-------------+--------------+
    +| product_id | product_name | report_year | total_amount |
    ++------------+--------------+-------------+--------------+
    +| 1          | LC Phone     |    2019     | 3500         |
    +| 2          | LC T-Shirt   |    2018     | 310          |
    +| 2          | LC T-Shirt   |    2019     | 3650         |
    +| 2          | LC T-Shirt   |    2020     | 10           |
    +| 3          | LC Keychain  |    2019     | 31           |
    +| 3          | LC Keychain  |    2020     | 31           |
    ++------------+--------------+-------------+--------------+
    +LC Phone 在 2019-01-25 至 2019-02-28 期间销售,该产品销售时间总计35天。销售总额 35*100 = 3500。
    +LC T-shirt 在 2018-12-01 至 2020-01-01 期间销售,该产品在2018年、2019年、2020年的销售时间分别是31天、365天、1天,2018年、2019年、2020年的销售总额分别是31*10=310、365*10=3650、1*10=10。
    +LC Keychain 在 2019-12-01 至 2020-01-31 期间销售,该产品在2019年、2020年的销售时间分别是:31天、31天,2019年、2020年的销售总额分别是31*1=31、31*1=31。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1385.leetcode1385 Find the Distance Value Between Two Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1385.leetcode1385 Find the Distance Value Between Two Arrays-zh.md" new file mode 100644 index 00000000..a0640816 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1385.leetcode1385 Find the Distance Value Between Two Arrays-zh.md" @@ -0,0 +1,166 @@ +# [1385. 两个数组间的距离值](https://leetcode-cn.com/problems/find-the-distance-value-between-two-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1385.Find%20the%20Distance%20Value%20Between%20Two%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 arr1 , arr2 和一个整数 d ,请你返回两个数组之间的 距离值 。

    + +

    距离值 定义为符合此距离要求的元素数目:对于元素 arr1[i] ,不存在任何元素 arr2[j] 满足 |arr1[i]-arr2[j]| <= d

    + +

     

    + +

    示例 1:

    + +
    输入:arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
    +输出:2
    +解释:
    +对于 arr1[0]=4 我们有:
    +|4-10|=6 > d=2 
    +|4-9|=5 > d=2 
    +|4-1|=3 > d=2 
    +|4-8|=4 > d=2 
    +所以 arr1[0]=4 符合距离要求
    +
    +对于 arr1[1]=5 我们有:
    +|5-10|=5 > d=2 
    +|5-9|=4 > d=2 
    +|5-1|=4 > d=2 
    +|5-8|=3 > d=2
    +所以 arr1[1]=5 也符合距离要求
    +
    +对于 arr1[2]=8 我们有:
    +|8-10|=2 <= d=2
    +|8-9|=1 <= d=2
    +|8-1|=7 > d=2
    +|8-8|=0 <= d=2
    +存在距离小于等于 2 的情况,不符合距离要求 
    +
    +故而只有 arr1[0]=4 和 arr1[1]=5 两个符合距离要求,距离值为 2
    + +

    示例 2:

    + +
    输入:arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 500
    • +
    • -10^3 <= arr1[i], arr2[j] <= 10^3
    • +
    • 0 <= d <= 100
    • +
    + +## 解法 + + + +由于 arr1,arr2 的长度不超过 500,直接暴力遍历即可。 + + + +### **Python3** + + + +```python +class Solution: + def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: + res = 0 + for a in arr1: + exist = False + for b in arr2: + if abs(a - b) <= d: + exist = True + break + if not exist: + res += 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { + int res = 0; + for (int a : arr1) { + boolean exist = false; + for (int b : arr2) { + if (Math.abs(a - b) <= d) { + exist = true; + break; + } + } + if (!exist) { + ++res; + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + int res = 0; + for (auto& a : arr1) { + bool exist = false; + for (auto& b : arr2) { + if (abs(a - b) <= d) { + exist = true; + break; + } + } + if (!exist) ++res; + } + return res; + } +}; +``` + +### **Go** + +```go +func findTheDistanceValue(arr1 []int, arr2 []int, d int) int { + res := 0 + for _, a := range arr1 { + exist := false + for _, b := range arr2 { + if math.Abs(float64(a-b)) <= float64(d) { + exist = true + break + } + } + if !exist { + res++ + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1386.leetcode1386 Cinema Seat Allocation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1386.leetcode1386 Cinema Seat Allocation-zh.md" new file mode 100644 index 00000000..49a4f90c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1386.leetcode1386 Cinema Seat Allocation-zh.md" @@ -0,0 +1,82 @@ +# [1386. 安排电影院座位](https://leetcode-cn.com/problems/cinema-seat-allocation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1386.Cinema%20Seat%20Allocation/README_EN.md) + +## 题目描述 + + + +

    + +

    如上图所示,电影院的观影厅中有 n 行座位,行编号从 1 到 n ,且每一行内总共有 10 个座位,列编号从 1 到 10 。

    + +

    给你数组 reservedSeats ,包含所有已经被预约了的座位。比如说,researvedSeats[i]=[3,8] ,它表示第 3 行第 8 个座位被预约了。

    + +

    请你返回 最多能安排多少个 4 人家庭 。4 人家庭要占据 同一行内连续 的 4 个座位。隔着过道的座位(比方说 [3,3] 和 [3,4])不是连续的座位,但是如果你可以将 4 人家庭拆成过道两边各坐 2 人,这样子是允许的。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
    +输出:4
    +解释:上图所示是最优的安排方案,总共可以安排 4 个家庭。蓝色的叉表示被预约的座位,橙色的连续座位表示一个 4 人家庭。
    +
    + +

    示例 2:

    + +
    输入:n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
    +输出:2
    +
    + +

    示例 3:

    + +
    输入:n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^9
    • +
    • 1 <= reservedSeats.length <= min(10*n, 10^4)
    • +
    • reservedSeats[i].length == 2
    • +
    • 1 <= reservedSeats[i][0] <= n
    • +
    • 1 <= reservedSeats[i][1] <= 10
    • +
    • 所有 reservedSeats[i] 都是互不相同的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1387.leetcode1387 Sort Integers by The Power Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1387.leetcode1387 Sort Integers by The Power Value-zh.md" new file mode 100644 index 00000000..7688d3c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1387.leetcode1387 Sort Integers by The Power Value-zh.md" @@ -0,0 +1,103 @@ +# [1387. 将整数按权重排序](https://leetcode-cn.com/problems/sort-integers-by-the-power-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1387.Sort%20Integers%20by%20The%20Power%20Value/README_EN.md) + +## 题目描述 + + + +

    我们将整数 x 的 权重 定义为按照下述规则将 x 变成 1 所需要的步数:

    + +
      +
    • 如果 x 是偶数,那么 x = x / 2
    • +
    • 如果 x 是奇数,那么 x = 3 * x + 1
    • +
    + +

    比方说,x=3 的权重为 7 。因为 3 需要 7 步变成 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)。

    + +

    给你三个整数 lo, hi 和 k 。你的任务是将区间 [lo, hi] 之间的整数按照它们的权重 升序排序 ,如果大于等于 2 个整数有 相同 的权重,那么按照数字自身的数值 升序排序 。

    + +

    请你返回区间 [lo, hi] 之间的整数按权重排序后的第 k 个数。

    + +

    注意,题目保证对于任意整数 x (lo <= x <= hi) ,它变成 1 所需要的步数是一个 32 位有符号整数。

    + +

     

    + +

    示例 1:

    + +
    输入:lo = 12, hi = 15, k = 2
    +输出:13
    +解释:12 的权重为 9(12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
    +13 的权重为 9
    +14 的权重为 17
    +15 的权重为 17
    +区间内的数按权重排序以后的结果为 [12,13,14,15] 。对于 k = 2 ,答案是第二个整数也就是 13 。
    +注意,12 和 13 有相同的权重,所以我们按照它们本身升序排序。14 和 15 同理。
    +
    + +

    示例 2:

    + +
    输入:lo = 1, hi = 1, k = 1
    +输出:1
    +
    + +

    示例 3:

    + +
    输入:lo = 7, hi = 11, k = 4
    +输出:7
    +解释:区间内整数 [7, 8, 9, 10, 11] 对应的权重为 [16, 3, 19, 6, 14] 。
    +按权重排序后得到的结果为 [8, 10, 11, 7, 9] 。
    +排序后数组中第 4 个数字为 7 。
    +
    + +

    示例 4:

    + +
    输入:lo = 10, hi = 20, k = 5
    +输出:13
    +
    + +

    示例 5:

    + +
    输入:lo = 1, hi = 1000, k = 777
    +输出:570
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= lo <= hi <= 1000
    • +
    • 1 <= k <= hi - lo + 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1388.leetcode1388 Pizza With 3n Slices-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1388.leetcode1388 Pizza With 3n Slices-zh.md" new file mode 100644 index 00000000..949ae78a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1388.leetcode1388 Pizza With 3n Slices-zh.md" @@ -0,0 +1,93 @@ +# [1388. 3n 块披萨](https://leetcode-cn.com/problems/pizza-with-3n-slices) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1388.Pizza%20With%203n%20Slices/README_EN.md) + +## 题目描述 + + + +

    给你一个披萨,它由 3n 块不同大小的部分组成,现在你和你的朋友们需要按照如下规则来分披萨:

    + +
      +
    • 你挑选 任意 一块披萨。
    • +
    • Alice 将会挑选你所选择的披萨逆时针方向的下一块披萨。
    • +
    • Bob 将会挑选你所选择的披萨顺时针方向的下一块披萨。
    • +
    • 重复上述过程直到没有披萨剩下。
    • +
    + +

    每一块披萨的大小按顺时针方向由循环数组 slices 表示。

    + +

    请你返回你可以获得的披萨大小总和的最大值。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:slices = [1,2,3,4,5,6]
    +输出:10
    +解释:选择大小为 4 的披萨,Alice 和 Bob 分别挑选大小为 3 和 5 的披萨。然后你选择大小为 6 的披萨,Alice 和 Bob 分别挑选大小为 2 和 1 的披萨。你获得的披萨总大小为 4 + 6 = 10 。
    +
    + +

    示例 2:

    + +

    + +
    输入:slices = [8,9,8,6,1,1]
    +输出:16
    +解释:两轮都选大小为 8 的披萨。如果你选择大小为 9 的披萨,你的朋友们就会选择大小为 8 的披萨,这种情况下你的总和不是最大的。
    +
    + +

    示例 3:

    + +
    输入:slices = [4,1,2,5,8,3,1,9,7]
    +输出:21
    +
    + +

    示例 4:

    + +
    输入:slices = [3,1,2]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= slices.length <= 500
    • +
    • slices.length % 3 == 0
    • +
    • 1 <= slices[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1389.leetcode1389 Create Target Array in the Given Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1389.leetcode1389 Create Target Array in the Given Order-zh.md" new file mode 100644 index 00000000..478521b1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1389.leetcode1389 Create Target Array in the Given Order-zh.md" @@ -0,0 +1,95 @@ +# [1389. 按既定顺序创建目标数组](https://leetcode-cn.com/problems/create-target-array-in-the-given-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1389.Create%20Target%20Array%20in%20the%20Given%20Order/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 numsindex。你需要按照以下规则创建目标数组:

    + +
      +
    • 目标数组 target 最初为空。
    • +
    • 按从左到右的顺序依次读取 nums[i]index[i],在 target 数组中的下标 index[i] 处插入值 nums[i]
    • +
    • 重复上一步,直到在 numsindex 中都没有要读取的元素。
    • +
    + +

    请你返回目标数组。

    + +

    题目保证数字插入位置总是存在。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [0,1,2,3,4], index = [0,1,2,2,1]
    +输出:[0,4,1,3,2]
    +解释:
    +nums       index     target
    +0            0        [0]
    +1            1        [0,1]
    +2            2        [0,1,2]
    +3            2        [0,1,3,2]
    +4            1        [0,4,1,3,2]
    +
    + +

    示例 2:

    + +
    输入:nums = [1,2,3,4,0], index = [0,1,2,3,0]
    +输出:[0,1,2,3,4]
    +解释:
    +nums       index     target
    +1            0        [1]
    +2            1        [1,2]
    +3            2        [1,2,3]
    +4            3        [1,2,3,4]
    +0            0        [0,1,2,3,4]
    +
    + +

    示例 3:

    + +
    输入:nums = [1], index = [0]
    +输出:[1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length, index.length <= 100
    • +
    • nums.length == index.length
    • +
    • 0 <= nums[i] <= 100
    • +
    • 0 <= index[i] <= i
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1390.leetcode1390 Four Divisors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1390.leetcode1390 Four Divisors-zh.md" new file mode 100644 index 00000000..9cb8ea73 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1390.leetcode1390 Four Divisors-zh.md" @@ -0,0 +1,64 @@ +# [1390. 四因数](https://leetcode-cn.com/problems/four-divisors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1390.Four%20Divisors/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,请你返回该数组中恰有四个因数的这些整数的各因数之和。

    + +

    如果数组中不存在满足题意的整数,则返回 0

    + +

     

    + +

    示例:

    + +
    输入:nums = [21,4,7]
    +输出:32
    +解释:
    +21 有 4 个因数:1, 3, 7, 21
    +4 有 3 个因数:1, 2, 4
    +7 有 2 个因数:1, 7
    +答案仅为 21 的所有因数的和。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^4
    • +
    • 1 <= nums[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1391.leetcode1391 Check if There is a Valid Path in a Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1391.leetcode1391 Check if There is a Valid Path in a Grid-zh.md" new file mode 100644 index 00000000..4f39040e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1391.leetcode1391 Check if There is a Valid Path in a Grid-zh.md" @@ -0,0 +1,107 @@ +# [1391. 检查网格中是否存在有效路径](https://leetcode-cn.com/problems/check-if-there-is-a-valid-path-in-a-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1391.Check%20if%20There%20is%20a%20Valid%20Path%20in%20a%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的网格 grid。网格里的每个单元都代表一条街道。grid[i][j] 的街道可以是:

    + +
      +
    • 1 表示连接左单元格和右单元格的街道。
    • +
    • 2 表示连接上单元格和下单元格的街道。
    • +
    • 3 表示连接左单元格和下单元格的街道。
    • +
    • 4 表示连接右单元格和下单元格的街道。
    • +
    • 5 表示连接左单元格和上单元格的街道。
    • +
    • 6 表示连接右单元格和上单元格的街道。
    • +
    + +

    + +

    你最开始从左上角的单元格 (0,0) 开始出发,网格中的「有效路径」是指从左上方的单元格 (0,0) 开始、一直到右下方的 (m-1,n-1) 结束的路径。该路径必须只沿着街道走

    + +

    注意:不能 变更街道。

    + +

    如果网格中存在有效的路径,则返回 true,否则返回 false

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[2,4,3],[6,5,2]]
    +输出:true
    +解释:如图所示,你可以从 (0, 0) 开始,访问网格中的所有单元格并到达 (m - 1, n - 1) 。
    +
    + +

    示例 2:

    + +

    + +
    输入:grid = [[1,2,1],[1,2,1]]
    +输出:false
    +解释:如图所示,单元格 (0, 0) 上的街道没有与任何其他单元格上的街道相连,你只会停在 (0, 0) 处。
    +
    + +

    示例 3:

    + +
    输入:grid = [[1,1,2]]
    +输出:false
    +解释:你会停在 (0, 1),而且无法到达 (0, 2) 。
    +
    + +

    示例 4:

    + +
    输入:grid = [[1,1,1,1,1,1,3]]
    +输出:true
    +
    + +

    示例 5:

    + +
    输入:grid = [[2],[2],[2],[2],[2],[2],[6]]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 300
    • +
    • 1 <= grid[i][j] <= 6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1392.leetcode1392 Longest Happy Prefix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1392.leetcode1392 Longest Happy Prefix-zh.md" new file mode 100644 index 00000000..7d77ef7e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1392.leetcode1392 Longest Happy Prefix-zh.md" @@ -0,0 +1,81 @@ +# [1392. 最长快乐前缀](https://leetcode-cn.com/problems/longest-happy-prefix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1392.Longest%20Happy%20Prefix/README_EN.md) + +## 题目描述 + + + +

    「快乐前缀」是在原字符串中既是 非空 前缀也是后缀(不包括原字符串自身)的字符串。

    + +

    给你一个字符串 s,请你返回它的 最长快乐前缀

    + +

    如果不存在满足题意的前缀,则返回一个空字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "level"
    +输出:"l"
    +解释:不包括 s 自己,一共有 4 个前缀("l", "le", "lev", "leve")和 4 个后缀("l", "el", "vel", "evel")。最长的既是前缀也是后缀的字符串是 "l" 。
    +
    + +

    示例 2:

    + +
    输入:s = "ababab"
    +输出:"abab"
    +解释:"abab" 是最长的既是前缀也是后缀的字符串。题目允许前后缀在原字符串中重叠。
    +
    + +

    示例 3:

    + +
    输入:s = "leetcodeleet"
    +输出:"leet"
    +
    + +

    示例 4:

    + +
    输入:s = "a"
    +输出:""
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s 只含有小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1393.leetcode1393 Capital GainLoss-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1393.leetcode1393 Capital GainLoss-zh.md" new file mode 100644 index 00000000..7829a1a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1393.leetcode1393 Capital GainLoss-zh.md" @@ -0,0 +1,89 @@ +# [1393. 股票的资本损益](https://leetcode-cn.com/problems/capital-gainloss) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1393.Capital%20GainLoss/README_EN.md) + +## 题目描述 + + + +

    Stocks 表:

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| stock_name    | varchar |
    +| operation     | enum    |
    +| operation_day | int     |
    +| price         | int     |
    ++---------------+---------+
    +(stock_name, day) 是这张表的主键
    +operation 列使用的是一种枚举类型,包括:('Sell','Buy')
    +此表的每一行代表了名为 stock_name 的某支股票在 operation_day 这一天的操作价格。
    +保证股票的每次'Sell'操作前,都有相应的'Buy'操作。
    +
    + +

     

    + +

    编写一个SQL查询来报告每支股票的资本损益。

    + +

    股票的资本损益是一次或多次买卖股票后的全部收益或损失。

    + +

    以任意顺序返回结果即可。

    + +

    SQL查询结果的格式如下例所示:

    + +
    Stocks 表:
    ++---------------+-----------+---------------+--------+
    +| stock_name    | operation | operation_day | price  |
    ++---------------+-----------+---------------+--------+
    +| Leetcode      | Buy       | 1             | 1000   |
    +| Corona Masks  | Buy       | 2             | 10     |
    +| Leetcode      | Sell      | 5             | 9000   |
    +| Handbags      | Buy       | 17            | 30000  |
    +| Corona Masks  | Sell      | 3             | 1010   |
    +| Corona Masks  | Buy       | 4             | 1000   |
    +| Corona Masks  | Sell      | 5             | 500    |
    +| Corona Masks  | Buy       | 6             | 1000   |
    +| Handbags      | Sell      | 29            | 7000   |
    +| Corona Masks  | Sell      | 10            | 10000  |
    ++---------------+-----------+---------------+--------+
    +
    +Result 表:
    ++---------------+-------------------+
    +| stock_name    | capital_gain_loss |
    ++---------------+-------------------+
    +| Corona Masks  | 9500              |
    +| Leetcode      | 8000              |
    +| Handbags      | -23000            |
    ++---------------+-------------------+
    +Leetcode 股票在第一天以1000美元的价格买入,在第五天以9000美元的价格卖出。资本收益=9000-1000=8000美元。
    +Handbags 股票在第17天以30000美元的价格买入,在第29天以7000美元的价格卖出。资本损失=7000-30000=-23000美元。
    +Corona Masks 股票在第1天以10美元的价格买入,在第3天以1010美元的价格卖出。在第4天以1000美元的价格再次购买,在第5天以500美元的价格出售。最后,它在第6天以1000美元的价格被买走,在第10天以10000美元的价格被卖掉。资本损益是每次(’Buy'->'Sell')操作资本收益或损失的和=(1010-10)+(500-1000)+(10000-1000)=1000-500+9000=9500美元。
    +
    + + +## 解法 + + + + +`CASE WHEN` + `GROUP BY`。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + stock_name, + sum( + CASE WHEN operation = 'Buy' THEN -price ELSE price END + ) AS capital_gain_loss +FROM + Stocks +GROUP BY + stock_name; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1394.leetcode1394 Find Lucky Integer in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1394.leetcode1394 Find Lucky Integer in an Array-zh.md" new file mode 100644 index 00000000..f94b4c3f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1394.leetcode1394 Find Lucky Integer in an Array-zh.md" @@ -0,0 +1,91 @@ +# [1394. 找出数组中的幸运数](https://leetcode-cn.com/problems/find-lucky-integer-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1394.Find%20Lucky%20Integer%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。

    + +

    给你一个整数数组 arr,请你从中找出并返回一个幸运数。

    + +
      +
    • 如果数组中存在多个幸运数,只需返回 最大 的那个。
    • +
    • 如果数组中不含幸运数,则返回 -1
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:arr = [2,2,3,4]
    +输出:2
    +解释:数组中唯一的幸运数是 2 ,因为数值 2 的出现频次也是 2 。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,2,2,3,3,3]
    +输出:3
    +解释:1、2 以及 3 都是幸运数,只需要返回其中最大的 3 。
    +
    + +

    示例 3:

    + +
    输入:arr = [2,2,2,3,3]
    +输出:-1
    +解释:数组中不存在幸运数。
    +
    + +

    示例 4:

    + +
    输入:arr = [5]
    +输出:-1
    +
    + +

    示例 5:

    + +
    输入:arr = [7,7,7,7,7,7,7]
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 500
    • +
    • 1 <= arr[i] <= 500
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1395.leetcode1395 Count Number of Teams-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1395.leetcode1395 Count Number of Teams-zh.md" new file mode 100644 index 00000000..b2b011b4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1395.leetcode1395 Count Number of Teams-zh.md" @@ -0,0 +1,85 @@ +# [1395. 统计作战单位数](https://leetcode-cn.com/problems/count-number-of-teams) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1395.Count%20Number%20of%20Teams/README_EN.md) + +## 题目描述 + + + +

     n 名士兵站成一排。每个士兵都有一个 独一无二 的评分 rating

    + +

    3 个士兵可以组成一个作战单位,分组规则如下:

    + +
      +
    • 从队伍中选出下标分别为 ijk 的 3 名士兵,他们的评分分别为 rating[i]rating[j]rating[k]
    • +
    • 作战单位需满足: rating[i] < rating[j] < rating[k] 或者 rating[i] > rating[j] > rating[k] ,其中  0 <= i < j < k < n
    • +
    + +

    请你返回按上述条件可以组建的作战单位数量。每个士兵都可以是多个作战单位的一部分。

    + +

     

    + +

    示例 1:

    + +
    +输入:rating = [2,5,3,4,1]
    +输出:3
    +解释:我们可以组建三个作战单位 (2,3,4)、(5,4,1)、(5,3,1) 。
    +
    + +

    示例 2:

    + +
    +输入:rating = [2,1,3]
    +输出:0
    +解释:根据题目条件,我们无法组建作战单位。
    +
    + +

    示例 3:

    + +
    +输入:rating = [1,2,3,4]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == rating.length
    • +
    • 3 <= n <= 1000
    • +
    • 1 <= rating[i] <= 10^5
    • +
    • rating 中的元素都是唯一的
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1396.leetcode1396 Design Underground System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1396.leetcode1396 Design Underground System-zh.md" new file mode 100644 index 00000000..040051a3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1396.leetcode1396 Design Underground System-zh.md" @@ -0,0 +1,171 @@ +# [1396. 设计地铁系统](https://leetcode-cn.com/problems/design-underground-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1396.Design%20Underground%20System/README_EN.md) + +## 题目描述 + + + +

    请你实现一个类 UndergroundSystem ,它支持以下 3 种方法:

    + +

    1. checkIn(int id, string stationName, int t)

    + +
      +
    • 编号为 id 的乘客在 t 时刻进入地铁站 stationName 。
    • +
    • 一个乘客在同一时间只能在一个地铁站进入或者离开。
    • +
    + +

    2. checkOut(int id, string stationName, int t)

    + +
      +
    • 编号为 id 的乘客在 t 时刻离开地铁站 stationName 。
    • +
    + +

    3. getAverageTime(string startStation, string endStation) 

    + +
      +
    • 返回从地铁站 startStation 到地铁站 endStation 的平均花费时间。
    • +
    • 平均时间计算的行程包括当前为止所有从 startStation 直接到达 endStation 的行程。
    • +
    • 调用 getAverageTime 时,询问的路线至少包含一趟行程。
    • +
    + +

    你可以假设所有对 checkIn 和 checkOut 的调用都是符合逻辑的。也就是说,如果一个顾客在 t1 时刻到达某个地铁站,那么他离开的时间 t2 一定满足 t2 > t1 。所有的事件都按时间顺序给出。

    + +

     

    + +

    示例:

    + +
    输入:
    +["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
    +[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]
    +
    +输出:
    +[null,null,null,null,null,null,null,14.0,11.0,null,11.0,null,12.0]
    +
    +解释:
    +UndergroundSystem undergroundSystem = new UndergroundSystem();
    +undergroundSystem.checkIn(45, "Leyton", 3);
    +undergroundSystem.checkIn(32, "Paradise", 8);
    +undergroundSystem.checkIn(27, "Leyton", 10);
    +undergroundSystem.checkOut(45, "Waterloo", 15);
    +undergroundSystem.checkOut(27, "Waterloo", 20);
    +undergroundSystem.checkOut(32, "Cambridge", 22);
    +undergroundSystem.getAverageTime("Paradise", "Cambridge");       // 返回 14.0。从 "Paradise"(时刻 8)到 "Cambridge"(时刻 22)的行程只有一趟
    +undergroundSystem.getAverageTime("Leyton", "Waterloo");          // 返回 11.0。总共有 2 躺从 "Leyton" 到 "Waterloo" 的行程,编号为 id=45 的乘客出发于 time=3 到达于 time=15,编号为 id=27 的乘客于 time=10 出发于 time=20 到达。所以平均时间为 ( (15-3) + (20-10) ) / 2 = 11.0
    +undergroundSystem.checkIn(10, "Leyton", 24);
    +undergroundSystem.getAverageTime("Leyton", "Waterloo");          // 返回 11.0
    +undergroundSystem.checkOut(10, "Waterloo", 38);
    +undergroundSystem.getAverageTime("Leyton", "Waterloo");          // 返回 12.0
    + +

     

    + +

    提示:

    + +
      +
    • 总共最多有 20000 次操作。
    • +
    • 1 <= id, t <= 10^6
    • +
    • 所有的字符串包含大写字母,小写字母和数字。
    • +
    • 1 <= stationName.length <= 10
    • +
    • 与标准答案误差在 10^-5 以内的结果都视为正确结果。
    • +
    + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +class UndergroundSystem: + + def __init__(self): + self.check_in_station = {} + self.check_in_time = {} + self.total_time = {} + + def checkIn(self, id: int, stationName: str, t: int) -> None: + self.check_in_station[id] = stationName + self.check_in_time[id] = t + + def checkOut(self, id: int, stationName: str, t: int) -> None: + cost = t - self.check_in_time.pop(id) + start_station = self.check_in_station.pop(id) + stations = start_station + '.' + stationName + times = self.total_time.get(stations, [0, 0]) + times[0] += cost + times[1] += 1 + self.total_time[stations] = times + + def getAverageTime(self, startStation: str, endStation: str) -> float: + stations = startStation + '.' + endStation + times = self.total_time[stations] + return times[0] / times[1] + + +# Your UndergroundSystem object will be instantiated and called as such: +# obj = UndergroundSystem() +# obj.checkIn(id,stationName,t) +# obj.checkOut(id,stationName,t) +# param_3 = obj.getAverageTime(startStation,endStation) +``` + +### **Java** + + + +```java +class UndergroundSystem { + private Map checkInStation; + private Map checkInTime; + private Map totalTime; + + public UndergroundSystem() { + checkInStation = new HashMap<>(); + checkInTime = new HashMap<>(); + totalTime = new HashMap<>(); + } + + public void checkIn(int id, String stationName, int t) { + checkInStation.put(id, stationName); + checkInTime.put(id, t); + } + + public void checkOut(int id, String stationName, int t) { + int cost = t - checkInTime.remove(id); + String startStation = checkInStation.remove(id); + String stations = startStation + "." + stationName; + int[] times = totalTime.getOrDefault(stations, new int[2]); + times[0] += cost; + ++times[1]; + totalTime.put(stations, times); + } + + public double getAverageTime(String startStation, String endStation) { + String stations = startStation + "." + endStation; + int[] times = totalTime.get(stations); + return times[0] * 1.0 / times[1]; + } +} + +/** + * Your UndergroundSystem object will be instantiated and called as such: + * UndergroundSystem obj = new UndergroundSystem(); + * obj.checkIn(id,stationName,t); + * obj.checkOut(id,stationName,t); + * double param_3 = obj.getAverageTime(startStation,endStation); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1397.leetcode1397 Find All Good Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1397.leetcode1397 Find All Good Strings-zh.md" new file mode 100644 index 00000000..d743c96f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1397.leetcode1397 Find All Good Strings-zh.md" @@ -0,0 +1,79 @@ +# [1397. 找到所有好字符串](https://leetcode-cn.com/problems/find-all-good-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1397.Find%20All%20Good%20Strings/README_EN.md) + +## 题目描述 + + + +

    给你两个长度为 n 的字符串 s1 和 s2 ,以及一个字符串 evil 。请你返回 好字符串 的数目。

    + +

    好字符串 的定义为:它的长度为 n ,字典序大于等于 s1 ,字典序小于等于 s2 ,且不包含 evil 为子字符串。

    + +

    由于答案可能很大,请你返回答案对 10^9 + 7 取余的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 2, s1 = "aa", s2 = "da", evil = "b"
    +输出:51 
    +解释:总共有 25 个以 'a' 开头的好字符串:"aa","ac","ad",...,"az"。还有 25 个以 'c' 开头的好字符串:"ca","cc","cd",...,"cz"。最后,还有一个以 'd' 开头的好字符串:"da"。
    +
    + +

    示例 2:

    + +
    输入:n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
    +输出:0 
    +解释:所有字典序大于等于 s1 且小于等于 s2 的字符串都以 evil 字符串 "leet" 开头。所以没有好字符串。
    +
    + +

    示例 3:

    + +
    输入:n = 2, s1 = "gx", s2 = "gz", evil = "x"
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • s1.length == n
    • +
    • s2.length == n
    • +
    • s1 <= s2
    • +
    • 1 <= n <= 500
    • +
    • 1 <= evil.length <= 50
    • +
    • 所有字符串都只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1398.leetcode1398 Customers Who Bought Products A and B but Not C-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1398.leetcode1398 Customers Who Bought Products A and B but Not C-zh.md" new file mode 100644 index 00000000..4c0f839e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1398.leetcode1398 Customers Who Bought Products A and B but Not C-zh.md" @@ -0,0 +1,93 @@ +# [1398. 购买了产品 A 和产品 B 却没有购买产品 C 的顾客](https://leetcode-cn.com/problems/customers-who-bought-products-a-and-b-but-not-c) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1398.Customers%20Who%20Bought%20Products%20A%20and%20B%20but%20Not%20C/README_EN.md) + +## 题目描述 + + + +

     Customers 表:

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| customer_id         | int     |
    +| customer_name       | varchar |
    ++---------------------+---------+
    +customer_id 是这张表的主键。
    +customer_name 是顾客的名称。
    + +

     

    + +

    Orders 表:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| customer_id   | int     |
    +| product_name  | varchar |
    ++---------------+---------+
    +order_id 是这张表的主键。
    +customer_id 是购买了名为 "product_name" 产品顾客的id。
    +
    + +

     

    + +

    请你设计 SQL 查询来报告购买了产品 A 和产品 B 却没有购买产品 C 的顾客的 ID 和姓名( customer_id 和 customer_name ),我们将基于此结果为他们推荐产品 C 。
    +您返回的查询结果需要按照 customer_id 排序

    + +

     

    + +

    查询结果如下例所示。

    + +
    +Customers table:
    ++-------------+---------------+
    +| customer_id | customer_name |
    ++-------------+---------------+
    +| 1           | Daniel        |
    +| 2           | Diana         |
    +| 3           | Elizabeth     |
    +| 4           | Jhon          |
    ++-------------+---------------+
    +
    +Orders table:
    ++------------+--------------+---------------+
    +| order_id   | customer_id  | product_name  |
    ++------------+--------------+---------------+
    +| 10         |     1        |     A         |
    +| 20         |     1        |     B         |
    +| 30         |     1        |     D         |
    +| 40         |     1        |     C         |
    +| 50         |     2        |     A         |
    +| 60         |     3        |     A         |
    +| 70         |     3        |     B         |
    +| 80         |     3        |     D         |
    +| 90         |     4        |     C         |
    ++------------+--------------+---------------+
    +
    +Result table:
    ++-------------+---------------+
    +| customer_id | customer_name |
    ++-------------+---------------+
    +| 3           | Elizabeth     |
    ++-------------+---------------+
    +只有 customer_id 为 3 的顾客购买了产品 A 和产品 B ,却没有购买产品 C 。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1399.leetcode1399 Count Largest Group-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1399.leetcode1399 Count Largest Group-zh.md" new file mode 100644 index 00000000..43fac8eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1399.leetcode1399 Count Largest Group-zh.md" @@ -0,0 +1,79 @@ +# [1399. 统计最大组的数目](https://leetcode-cn.com/problems/count-largest-group) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1300-1399/1399.Count%20Largest%20Group/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n 。请你先求出从 1 到 n 的每个整数 10 进制表示下的数位和(每一位上的数字相加),然后把数位和相等的数字放到同一个组中。

    + +

    请你统计每个组中的数字数目,并返回数字数目并列最多的组有多少个。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 13
    +输出:4
    +解释:总共有 9 个组,将 1 到 13 按数位求和后这些组分别是:
    +[1,10],[2,11],[3,12],[4,13],[5],[6],[7],[8],[9]。总共有 4 个组拥有的数字并列最多。
    +
    + +

    示例 2:

    + +
    输入:n = 2
    +输出:2
    +解释:总共有 2 个大小为 1 的组 [1],[2]。
    +
    + +

    示例 3:

    + +
    输入:n = 15
    +输出:6
    +
    + +

    示例 4:

    + +
    输入:n = 24
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1400.leetcode1400 Construct K Palindrome Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1400.leetcode1400 Construct K Palindrome Strings-zh.md" new file mode 100644 index 00000000..07835758 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1400.leetcode1400 Construct K Palindrome Strings-zh.md" @@ -0,0 +1,95 @@ +# [1400. 构造 K 个回文字符串](https://leetcode-cn.com/problems/construct-k-palindrome-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1400.Construct%20K%20Palindrome%20Strings/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个整数 k 。请你用 s 字符串中 所有字符 构造 k 个非空 回文串 。

    + +

    如果你可以用 s 中所有字符构造 k 个回文字符串,那么请你返回 True ,否则返回 False 。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "annabelle", k = 2
    +输出:true
    +解释:可以用 s 中所有字符构造 2 个回文字符串。
    +一些可行的构造方案包括:"anna" + "elble","anbna" + "elle","anellena" + "b"
    +
    + +

    示例 2:

    + +
    +输入:s = "leetcode", k = 3
    +输出:false
    +解释:无法用 s 中所有字符构造 3 个回文串。
    +
    + +

    示例 3:

    + +
    +输入:s = "true", k = 4
    +输出:true
    +解释:唯一可行的方案是让 s 中每个字符单独构成一个字符串。
    +
    + +

    示例 4:

    + +
    +输入:s = "yzyzyzyzyzyzyzy", k = 2
    +输出:true
    +解释:你只需要将所有的 z 放在一个字符串中,所有的 y 放在另一个字符串中。那么两个字符串都是回文串。
    +
    + +

    示例 5:

    + +
    +输入:s = "cr", k = 7
    +输出:false
    +解释:我们没有足够的字符去构造 7 个回文串。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s 中所有字符都是小写英文字母。
    • +
    • 1 <= k <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1401.leetcode1401 Circle and Rectangle Overlapping-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1401.leetcode1401 Circle and Rectangle Overlapping-zh.md" new file mode 100644 index 00000000..b72f6b4a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1401.leetcode1401 Circle and Rectangle Overlapping-zh.md" @@ -0,0 +1,88 @@ +# [1401. 圆和矩形是否有重叠](https://leetcode-cn.com/problems/circle-and-rectangle-overlapping) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1401.Circle%20and%20Rectangle%20Overlapping/README_EN.md) + +## 题目描述 + + + +

    给你一个以 (radius, x_center, y_center) 表示的圆和一个与坐标轴平行的矩形 (x1, y1, x2, y2),其中 (x1, y1) 是矩形左下角的坐标,(x2, y2) 是右上角的坐标。

    + +

    如果圆和矩形有重叠的部分,请你返回 True ,否则返回 False 。

    + +

    换句话说,请你检测是否 存在 点 (xi, yi) ,它既在圆上也在矩形上(两者都包括点落在边界上的情况)。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
    +输出:true
    +解释:圆和矩形有公共点 (1,0) 
    +
    + +

    示例 2:

    + +

    + +
    输入:radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
    +输出:true
    +
    + +

    示例 3:

    + +

    + +
    输入:radius = 1, x_center = 1, y_center = 1, x1 = -3, y1 = -3, x2 = 3, y2 = 3
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:radius = 1, x_center = 1, y_center = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= radius <= 2000
    • +
    • -10^4 <= x_center, y_center, x1, y1, x2, y2 <= 10^4
    • +
    • x1 < x2
    • +
    • y1 < y2
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1402.leetcode1402 Reducing Dishes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1402.leetcode1402 Reducing Dishes-zh.md" new file mode 100644 index 00000000..7352123e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1402.leetcode1402 Reducing Dishes-zh.md" @@ -0,0 +1,84 @@ +# [1402. 做菜顺序](https://leetcode-cn.com/problems/reducing-dishes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1402.Reducing%20Dishes/README_EN.md) + +## 题目描述 + + + +

    一个厨师收集了他 n 道菜的满意程度 satisfaction ,这个厨师做出每道菜的时间都是 1 单位时间。

    + +

    一道菜的 「喜爱时间」系数定义为烹饪这道菜以及之前每道菜所花费的时间乘以这道菜的满意程度,也就是 time[i]*satisfaction[i] 。

    + +

    请你返回做完所有菜 「喜爱时间」总和的最大值为多少。

    + +

    你可以按 任意 顺序安排做菜的顺序,你也可以选择放弃做某些菜来获得更大的总和。

    + +

     

    + +

    示例 1:

    + +
    输入:satisfaction = [-1,-8,0,5,-9]
    +输出:14
    +解释:去掉第二道和最后一道菜,最大的喜爱时间系数和为 (-1*1 + 0*2 + 5*3 = 14) 。每道菜都需要花费 1 单位时间完成。
    + +

    示例 2:

    + +
    输入:satisfaction = [4,3,2]
    +输出:20
    +解释:按照原来顺序相反的时间做菜 (2*1 + 3*2 + 4*3 = 20)
    +
    + +

    示例 3:

    + +
    输入:satisfaction = [-1,-4,-5]
    +输出:0
    +解释:大家都不喜欢这些菜,所以不做任何菜可以获得最大的喜爱时间系数。
    +
    + +

    示例 4:

    + +
    输入:satisfaction = [-2,5,-1,0,3,-3]
    +输出:35
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == satisfaction.length
    • +
    • 1 <= n <= 500
    • +
    • -10^3 <= satisfaction[i] <= 10^3
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1403.leetcode1403 Minimum Subsequence in Non-Increasing Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1403.leetcode1403 Minimum Subsequence in Non-Increasing Order-zh.md" new file mode 100644 index 00000000..13afc0c5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1403.leetcode1403 Minimum Subsequence in Non-Increasing Order-zh.md" @@ -0,0 +1,77 @@ +# [1403. 非递增顺序的最小子序列](https://leetcode-cn.com/problems/minimum-subsequence-in-non-increasing-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1403.Minimum%20Subsequence%20in%20Non-Increasing%20Order/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums,请你从中抽取一个子序列,满足该子序列的元素之和 严格 大于未包含在该子序列中的各元素之和。

    + +

    如果存在多个解决方案,只需返回 长度最小 的子序列。如果仍然有多个解决方案,则返回 元素之和最大 的子序列。

    + +

    与子数组不同的地方在于,「数组的子序列」不强调元素在原数组中的连续性,也就是说,它可以通过从数组中分离一些(也可能不分离)元素得到。

    + +

    注意,题目数据保证满足所有约束条件的解决方案是 唯一 的。同时,返回的答案应当按 非递增顺序 排列。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [4,3,10,9,8]
    +输出:[10,9] 
    +解释:子序列 [10,9] 和 [10,8] 是最小的、满足元素之和大于其他各元素之和的子序列。但是 [10,9] 的元素之和最大。 
    +
    + +

    示例 2:

    + +
    输入:nums = [4,4,7,6,7]
    +输出:[7,7,6] 
    +解释:子序列 [7,7] 的和为 14 ,不严格大于剩下的其他元素之和(14 = 4 + 4 + 6)。因此,[7,6,7] 是满足题意的最小子序列。注意,元素按非递增顺序返回。  
    +
    + +

    示例 3:

    + +
    输入:nums = [6]
    +输出:[6]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 500
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1404.leetcode1404 Number of Steps to Reduce a Number in Binary Representation to One-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1404.leetcode1404 Number of Steps to Reduce a Number in Binary Representation to One-zh.md" new file mode 100644 index 00000000..bf991829 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1404.leetcode1404 Number of Steps to Reduce a Number in Binary Representation to One-zh.md" @@ -0,0 +1,90 @@ +# [1404. 将二进制表示减到 1 的步骤数](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1404.Number%20of%20Steps%20to%20Reduce%20a%20Number%20in%20Binary%20Representation%20to%20One/README_EN.md) + +## 题目描述 + + + +

    给你一个以二进制形式表示的数字 s 。请你返回按下述规则将其减少到 1 所需要的步骤数:

    + +
      +
    • +

      如果当前数字为偶数,则将其除以 2 。

      +
    • +
    • +

      如果当前数字为奇数,则将其加上 1 。

      +
    • +
    + +

    题目保证你总是可以按上述规则将测试用例变为 1 。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "1101"
    +输出:6
    +解释:"1101" 表示十进制数 13 。
    +Step 1) 13 是奇数,加 1 得到 14 
    +Step 2) 14 是偶数,除 2 得到 7
    +Step 3) 7  是奇数,加 1 得到 8
    +Step 4) 8  是偶数,除 2 得到 4  
    +Step 5) 4  是偶数,除 2 得到 2 
    +Step 6) 2  是偶数,除 2 得到 1  
    +
    + +

    示例 2:

    + +
    输入:s = "10"
    +输出:1
    +解释:"10" 表示十进制数 2 。
    +Step 1) 2 是偶数,除 2 得到 1 
    +
    + +

    示例 3:

    + +
    输入:s = "1"
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 由字符 '0''1' 组成。
    • +
    • s[0] == '1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1405.leetcode1405 Longest Happy String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1405.leetcode1405 Longest Happy String-zh.md" new file mode 100644 index 00000000..df219856 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1405.leetcode1405 Longest Happy String-zh.md" @@ -0,0 +1,80 @@ +# [1405. 最长快乐字符串](https://leetcode-cn.com/problems/longest-happy-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1405.Longest%20Happy%20String/README_EN.md) + +## 题目描述 + + + +

    如果字符串中不含有任何 'aaa''bbb''ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。

    + +

    给你三个整数 abc,请你返回 任意一个 满足下列全部条件的字符串 s

    + +
      +
    • s 是一个尽可能长的快乐字符串。
    • +
    • s最多a 个字母 'a'b 个字母 'b'c 个字母 'c'
    • +
    • s 中只含有 'a''b''c' 三种字母。
    • +
    + +

    如果不存在这样的字符串 s ,请返回一个空字符串 ""

    + +

     

    + +

    示例 1:

    + +
    输入:a = 1, b = 1, c = 7
    +输出:"ccaccbcc"
    +解释:"ccbccacc" 也是一种正确答案。
    +
    + +

    示例 2:

    + +
    输入:a = 2, b = 2, c = 1
    +输出:"aabbc"
    +
    + +

    示例 3:

    + +
    输入:a = 7, b = 1, c = 0
    +输出:"aabaa"
    +解释:这是该测试用例的唯一正确答案。
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= a, b, c <= 100
    • +
    • a + b + c > 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1406.leetcode1406 Stone Game III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1406.leetcode1406 Stone Game III-zh.md" new file mode 100644 index 00000000..42e093ff --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1406.leetcode1406 Stone Game III-zh.md" @@ -0,0 +1,92 @@ +# [1406. 石子游戏 III](https://leetcode-cn.com/problems/stone-game-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1406.Stone%20Game%20III/README_EN.md) + +## 题目描述 + + + +

    Alice 和 Bob 用几堆石子在做游戏。几堆石子排成一行,每堆石子都对应一个得分,由数组 stoneValue 给出。

    + +

    Alice 和 Bob 轮流取石子,Alice 总是先开始。在每个玩家的回合中,该玩家可以拿走剩下石子中的的前 1、2 或 3 堆石子 。比赛一直持续到所有石头都被拿走。

    + +

    每个玩家的最终得分为他所拿到的每堆石子的对应得分之和。每个玩家的初始分数都是 0 。比赛的目标是决出最高分,得分最高的选手将会赢得比赛,比赛也可能会出现平局。

    + +

    假设 Alice 和 Bob 都采取 最优策略 。如果 Alice 赢了就返回 "Alice" Bob 赢了就返回 "Bob",平局(分数相同)返回 "Tie"

    + +

     

    + +

    示例 1:

    + +
    输入:values = [1,2,3,7]
    +输出:"Bob"
    +解释:Alice 总是会输,她的最佳选择是拿走前三堆,得分变成 6 。但是 Bob 的得分为 7,Bob 获胜。
    +
    + +

    示例 2:

    + +
    输入:values = [1,2,3,-9]
    +输出:"Alice"
    +解释:Alice 要想获胜就必须在第一个回合拿走前三堆石子,给 Bob 留下负分。
    +如果 Alice 只拿走第一堆,那么她的得分为 1,接下来 Bob 拿走第二、三堆,得分为 5 。之后 Alice 只能拿到分数 -9 的石子堆,输掉比赛。
    +如果 Alice 拿走前两堆,那么她的得分为 3,接下来 Bob 拿走第三堆,得分为 3 。之后 Alice 只能拿到分数 -9 的石子堆,同样会输掉比赛。
    +注意,他们都应该采取 最优策略 ,所以在这里 Alice 将选择能够使她获胜的方案。
    + +

    示例 3:

    + +
    输入:values = [1,2,3,6]
    +输出:"Tie"
    +解释:Alice 无法赢得比赛。如果她决定选择前三堆,她可以以平局结束比赛,否则她就会输。
    +
    + +

    示例 4:

    + +
    输入:values = [1,2,3,-1,-2,-3,7]
    +输出:"Alice"
    +
    + +

    示例 5:

    + +
    输入:values = [-1,-2,-3]
    +输出:"Tie"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= values.length <= 50000
    • +
    • -1000 <= values[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1407.leetcode1407 Top Travellers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1407.leetcode1407 Top Travellers-zh.md" new file mode 100644 index 00000000..f5e60cd0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1407.leetcode1407 Top Travellers-zh.md" @@ -0,0 +1,104 @@ +# [1407. 排名靠前的旅行者](https://leetcode-cn.com/problems/top-travellers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1407.Top%20Travellers/README_EN.md) + +## 题目描述 + + + +

    表:Users

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id 是该表单主键。
    +name 是用户名字。
    + +

     

    + +

    表:Rides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| user_id       | int     |
    +| distance      | int     |
    ++---------------+---------+
    +id 是该表单主键。
    +user_id 是本次行程的用户的 id, 而该用户此次行程距离为 distance 。
    +
    + +

     

    + +

    写一段 SQL , 报告每个用户的旅行距离。

    + +

    返回的结果表单,以 travelled_distance 降序排列 ,如果有两个或者更多的用户旅行了相同的距离, 那么再以 name 升序排列

    + +

    查询结果格式如下例所示。

    + +
    +Users 表:
    ++------+-----------+
    +| id   | name      |
    ++------+-----------+
    +| 1    | Alice     |
    +| 2    | Bob       |
    +| 3    | Alex      |
    +| 4    | Donald    |
    +| 7    | Lee       |
    +| 13   | Jonathan  |
    +| 19   | Elvis     |
    ++------+-----------+
    +
    +Rides 表:
    ++------+----------+----------+
    +| id   | user_id  | distance |
    ++------+----------+----------+
    +| 1    | 1        | 120      |
    +| 2    | 2        | 317      |
    +| 3    | 3        | 222      |
    +| 4    | 7        | 100      |
    +| 5    | 13       | 312      |
    +| 6    | 19       | 50       |
    +| 7    | 7        | 120      |
    +| 8    | 19       | 400      |
    +| 9    | 7        | 230      |
    ++------+----------+----------+
    +
    +Result 表:
    ++----------+--------------------+
    +| name     | travelled_distance |
    ++----------+--------------------+
    +| Elvis    | 450                |
    +| Lee      | 450                |
    +| Bob      | 317                |
    +| Jonathan | 312                |
    +| Alex     | 222                |
    +| Alice    | 120                |
    +| Donald   | 0                  |
    ++----------+--------------------+
    +Elvis 和 Lee 旅行了 450 英里,Elvis 是排名靠前的旅行者,因为他的名字在字母表上的排序比 Lee 更小。
    +Bob, Jonathan, Alex 和 Alice 只有一次行程,我们只按此次行程的全部距离对他们排序。
    +Donald 没有任何行程, 他的旅行距离为 0。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1408.leetcode1408 String Matching in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1408.leetcode1408 String Matching in an Array-zh.md" new file mode 100644 index 00000000..e291cad3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1408.leetcode1408 String Matching in an Array-zh.md" @@ -0,0 +1,76 @@ +# [1408. 数组中的字符串匹配](https://leetcode-cn.com/problems/string-matching-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1408.String%20Matching%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。

    + +

    如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:words = ["mass","as","hero","superhero"]
    +输出:["as","hero"]
    +解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
    +["hero","as"] 也是有效的答案。
    +
    + +

    示例 2:

    + +
    输入:words = ["leetcode","et","code"]
    +输出:["et","code"]
    +解释:"et" 和 "code" 都是 "leetcode" 的子字符串。
    +
    + +

    示例 3:

    + +
    输入:words = ["blue","green","bu"]
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 100
    • +
    • 1 <= words[i].length <= 30
    • +
    • words[i] 仅包含小写英文字母。
    • +
    • 题目数据 保证 每个 words[i] 都是独一无二的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1409.leetcode1409 Queries on a Permutation With Key-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1409.leetcode1409 Queries on a Permutation With Key-zh.md" new file mode 100644 index 00000000..589ca877 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1409.leetcode1409 Queries on a Permutation With Key-zh.md" @@ -0,0 +1,83 @@ +# [1409. 查询带键的排列](https://leetcode-cn.com/problems/queries-on-a-permutation-with-key) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1409.Queries%20on%20a%20Permutation%20With%20Key/README_EN.md) + +## 题目描述 + + + +

    给你一个待查数组 queries ,数组中的元素为 1m 之间的正整数。 请你根据以下规则处理所有待查项 queries[i](从 i=0i=queries.length-1):

    + +
      +
    • 一开始,排列 P=[1,2,3,...,m]
    • +
    • 对于当前的 i ,请你找出待查项 queries[i] 在排列 P 中的位置(下标从 0 开始),然后将其从原位置移动到排列 P 的起始位置(即下标为 0 处)。注意, queries[i]P 中的位置就是 queries[i] 的查询结果。
    • +
    + +

    请你以数组形式返回待查数组  queries 的查询结果。

    + +

     

    + +

    示例 1:

    + +
    输入:queries = [3,1,2,1], m = 5
    +输出:[2,1,2,1] 
    +解释:待查数组 queries 处理如下:
    +对于 i=0: queries[i]=3, P=[1,2,3,4,5], 3 在 P 中的位置是 2,接着我们把 3 移动到 P 的起始位置,得到 P=[3,1,2,4,5] 。
    +对于 i=1: queries[i]=1, P=[3,1,2,4,5], 1 在 P 中的位置是 1,接着我们把 1 移动到 P 的起始位置,得到 P=[1,3,2,4,5] 。 
    +对于 i=2: queries[i]=2, P=[1,3,2,4,5], 2 在 P 中的位置是 2,接着我们把 2 移动到 P 的起始位置,得到 P=[2,1,3,4,5] 。
    +对于 i=3: queries[i]=1, P=[2,1,3,4,5], 1 在 P 中的位置是 1,接着我们把 1 移动到 P 的起始位置,得到 P=[1,2,3,4,5] 。 
    +因此,返回的结果数组为 [2,1,2,1] 。  
    +
    + +

    示例 2:

    + +
    输入:queries = [4,1,2,2], m = 4
    +输出:[3,1,2,0]
    +
    + +

    示例 3:

    + +
    输入:queries = [7,5,5,8,3], m = 8
    +输出:[6,5,0,7,5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m <= 10^3
    • +
    • 1 <= queries.length <= m
    • +
    • 1 <= queries[i] <= m
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1410.leetcode1410 HTML Entity Parser-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1410.leetcode1410 HTML Entity Parser-zh.md" new file mode 100644 index 00000000..87ee2e91 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1410.leetcode1410 HTML Entity Parser-zh.md" @@ -0,0 +1,100 @@ +# [1410. HTML 实体解析器](https://leetcode-cn.com/problems/html-entity-parser) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1410.HTML%20Entity%20Parser/README_EN.md) + +## 题目描述 + + + +

    「HTML 实体解析器」 是一种特殊的解析器,它将 HTML 代码作为输入,并用字符本身替换掉所有这些特殊的字符实体。

    + +

    HTML 里这些特殊字符和它们对应的字符实体包括:

    + +
      +
    • 双引号:字符实体为 &quot; ,对应的字符是 " 。
    • +
    • 单引号:字符实体为 &apos; ,对应的字符是 ' 。
    • +
    • 与符号:字符实体为 &amp; ,对应对的字符是 & 。
    • +
    • 大于号:字符实体为 &gt; ,对应的字符是 > 。
    • +
    • 小于号:字符实体为 &lt; ,对应的字符是 < 。
    • +
    • 斜线号:字符实体为 &frasl; ,对应的字符是 / 。
    • +
    + +

    给你输入字符串 text ,请你实现一个 HTML 实体解析器,返回解析器解析后的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:text = "&amp; is an HTML entity but &ambassador; is not."
    +输出:"& is an HTML entity but &ambassador; is not."
    +解释:解析器把字符实体 &amp; 用 & 替换
    +
    + +

    示例 2:

    + +
    +输入:text = "and I quote: &quot;...&quot;"
    +输出:"and I quote: \"...\""
    +
    + +

    示例 3:

    + +
    +输入:text = "Stay home! Practice on Leetcode :)"
    +输出:"Stay home! Practice on Leetcode :)"
    +
    + +

    示例 4:

    + +
    +输入:text = "x &gt; y &amp;&amp; x &lt; y is always false"
    +输出:"x > y && x < y is always false"
    +
    + +

    示例 5:

    + +
    +输入:text = "leetcode.com&frasl;problemset&frasl;all"
    +输出:"leetcode.com/problemset/all"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text.length <= 10^5
    • +
    • 字符串可能包含 256 个ASCII 字符中的任意字符。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1411.leetcode1411 Number of Ways to Paint N \303\227 3 Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1411.leetcode1411 Number of Ways to Paint N \303\227 3 Grid-zh.md" new file mode 100644 index 00000000..be00646c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1411.leetcode1411 Number of Ways to Paint N \303\227 3 Grid-zh.md" @@ -0,0 +1,88 @@ +# [1411. 给 N x 3 网格图涂色的方案数](https://leetcode-cn.com/problems/number-of-ways-to-paint-n-3-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1411.Number%20of%20Ways%20to%20Paint%20N%20%C3%97%203%20Grid/README_EN.md) + +## 题目描述 + + + +

    你有一个 n x 3 的网格图 grid ,你需要用 红,黄,绿 三种颜色之一给每一个格子上色,且确保相邻格子颜色不同(也就是有相同水平边或者垂直边的格子颜色不同)。

    + +

    给你网格图的行数 n 。

    + +

    请你返回给 grid 涂色的方案数。由于答案可能会非常大,请你返回答案对 10^9 + 7 取余的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 1
    +输出:12
    +解释:总共有 12 种可行的方法:
    +
    +
    + +

    示例 2:

    + +
    输入:n = 2
    +输出:54
    +
    + +

    示例 3:

    + +
    输入:n = 3
    +输出:246
    +
    + +

    示例 4:

    + +
    输入:n = 7
    +输出:106494
    +
    + +

    示例 5:

    + +
    输入:n = 5000
    +输出:30228214
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == grid.length
    • +
    • grid[i].length == 3
    • +
    • 1 <= n <= 5000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1412.leetcode1412 Find the Quiet Students in All Exams-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1412.leetcode1412 Find the Quiet Students in All Exams-zh.md" new file mode 100644 index 00000000..63ab971d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1412.leetcode1412 Find the Quiet Students in All Exams-zh.md" @@ -0,0 +1,104 @@ +# [1412. 查找成绩处于中游的学生](https://leetcode-cn.com/problems/find-the-quiet-students-in-all-exams) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1412.Find%20the%20Quiet%20Students%20in%20All%20Exams/README_EN.md) + +## 题目描述 + + + +

    表: Student

    + +
    ++---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| student_id          | int     |
    +| student_name        | varchar |
    ++---------------------+---------+
    +student_id 是该表主键.
    +student_name 学生名字.
    + +

     

    + +

    表: Exam

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| exam_id       | int     |
    +| student_id    | int     |
    +| score         | int     |
    ++---------------+---------+
    +(exam_id, student_id) 是该表主键.
    +学生 student_id 在测验 exam_id 中得分为 score.
    +
    + +

     

    + +

    成绩处于中游的学生是指至少参加了一次测验, 且得分既不是最高分也不是最低分的学生。

    + +

    写一个 SQL 语句,找出在 所有 测验中都处于中游的学生 (student_id, student_name)

    + +

    不要返回从来没有参加过测验的学生。返回结果表按照 student_id 排序。

    + +

    查询结果格式如下。

    + +

     

    + +
    +Student 表:
    ++-------------+---------------+
    +| student_id  | student_name  |
    ++-------------+---------------+
    +| 1           | Daniel        |
    +| 2           | Jade          |
    +| 3           | Stella        |
    +| 4           | Jonathan      |
    +| 5           | Will          |
    ++-------------+---------------+
    +
    +Exam 表:
    ++------------+--------------+-----------+
    +| exam_id    | student_id   | score     |
    ++------------+--------------+-----------+
    +| 10         |     1        |    70     |
    +| 10         |     2        |    80     |
    +| 10         |     3        |    90     |
    +| 20         |     1        |    80     |
    +| 30         |     1        |    70     |
    +| 30         |     3        |    80     |
    +| 30         |     4        |    90     |
    +| 40         |     1        |    60     |
    +| 40         |     2        |    70     |
    +| 40         |     4        |    80     |
    ++------------+--------------+-----------+
    +
    +Result 表:
    ++-------------+---------------+
    +| student_id  | student_name  |
    ++-------------+---------------+
    +| 2           | Jade          |
    ++-------------+---------------+
    +
    +对于测验 1: 学生 1 和 3 分别获得了最低分和最高分。
    +对于测验 2: 学生 1 既获得了最高分, 也获得了最低分。
    +对于测验 3 和 4: 学生 1 和 4 分别获得了最低分和最高分。
    +学生 2 和 5 没有在任一场测验中获得了最高分或者最低分。
    +因为学生 5 从来没有参加过任何测验, 所以他被排除于结果表。
    +由此, 我们仅仅返回学生 2 的信息。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1413.leetcode1413 Minimum Value to Get Positive Step by Step Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1413.leetcode1413 Minimum Value to Get Positive Step by Step Sum-zh.md" new file mode 100644 index 00000000..592d37e9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1413.leetcode1413 Minimum Value to Get Positive Step by Step Sum-zh.md" @@ -0,0 +1,85 @@ +# [1413. 逐步求和得到正数的最小值](https://leetcode-cn.com/problems/minimum-value-to-get-positive-step-by-step-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1413.Minimum%20Value%20to%20Get%20Positive%20Step%20by%20Step%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 。你可以选定任意的 正数 startValue 作为初始值。

    + +

    你需要从左到右遍历 nums 数组,并将 startValue 依次累加上 nums 数组中的值。

    + +

    请你在确保累加和始终大于等于 1 的前提下,选出一个最小的 正数 作为 startValue 。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [-3,2,-3,4,2]
    +输出:5
    +解释:如果你选择 startValue = 4,在第三次累加时,和小于 1 。
    +                累加求和
    +                startValue = 4 | startValue = 5 | nums
    +                  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3
    +                  (1 +2 ) = 3  | (2 +2 ) = 4    |   2
    +                  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3
    +                  (0 +4 ) = 4  | (1 +4 ) = 5    |   4
    +                  (4 +2 ) = 6  | (5 +2 ) = 7    |   2
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2]
    +输出:1
    +解释:最小的 startValue 需要是正数。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,-2,-3]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • -100 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1414.leetcode1414 Find the Minimum Number of Fibonacci Numbers Whose Sum Is K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1414.leetcode1414 Find the Minimum Number of Fibonacci Numbers Whose Sum Is K-zh.md" new file mode 100644 index 00000000..4344b7a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1414.leetcode1414 Find the Minimum Number of Fibonacci Numbers Whose Sum Is K-zh.md" @@ -0,0 +1,81 @@ +# [1414. 和为 K 的最少斐波那契数字数目](https://leetcode-cn.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1414.Find%20the%20Minimum%20Number%20of%20Fibonacci%20Numbers%20Whose%20Sum%20Is%20K/README_EN.md) + +## 题目描述 + + + +

    给你数字 k ,请你返回和为 k 的斐波那契数字的最少数目,其中,每个斐波那契数字都可以被使用多次。

    + +

    斐波那契数字定义为:

    + +
      +
    • F1 = 1
    • +
    • F2 = 1
    • +
    • Fn = Fn-1 + Fn-2 , 其中 n > 2 。
    • +
    + +

    数据保证对于给定的 k ,一定能找到可行解。

    + +

     

    + +

    示例 1:

    + +
    输入:k = 7
    +输出:2 
    +解释:斐波那契数字为:1,1,2,3,5,8,13,……
    +对于 k = 7 ,我们可以得到 2 + 5 = 7 。
    + +

    示例 2:

    + +
    输入:k = 10
    +输出:2 
    +解释:对于 k = 10 ,我们可以得到 2 + 8 = 10 。
    +
    + +

    示例 3:

    + +
    输入:k = 19
    +输出:3 
    +解释:对于 k = 19 ,我们可以得到 1 + 5 + 13 = 19 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1415.leetcode1415 The k-th Lexicographical String of All Happy Strings of Length n-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1415.leetcode1415 The k-th Lexicographical String of All Happy Strings of Length n-zh.md" new file mode 100644 index 00000000..0c88e0b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1415.leetcode1415 The k-th Lexicographical String of All Happy Strings of Length n-zh.md" @@ -0,0 +1,97 @@ +# [1415. 长度为 n 的开心字符串中字典序第 k 小的字符串](https://leetcode-cn.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1415.The%20k-th%20Lexicographical%20String%20of%20All%20Happy%20Strings%20of%20Length%20n/README_EN.md) + +## 题目描述 + + + +

    一个 「开心字符串」定义为:

    + +
      +
    • 仅包含小写字母 ['a', 'b', 'c'].
    • +
    • 对所有在 1 到 s.length - 1 之间的 i ,满足 s[i] != s[i + 1] (字符串的下标从 1 开始)。
    • +
    + +

    比方说,字符串 "abc""ac","b" 和 "abcbabcbcb" 都是开心字符串,但是 "aa""baa" 和 "ababbc" 都不是开心字符串。

    + +

    给你两个整数 n 和 k ,你需要将长度为 n 的所有开心字符串按字典序排序。

    + +

    请你返回排序后的第 k 个开心字符串,如果长度为 n 的开心字符串少于 k 个,那么请你返回 空字符串 。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 1, k = 3
    +输出:"c"
    +解释:列表 ["a", "b", "c"] 包含了所有长度为 1 的开心字符串。按照字典序排序后第三个字符串为 "c" 。
    +
    + +

    示例 2:

    + +
    输入:n = 1, k = 4
    +输出:""
    +解释:长度为 1 的开心字符串只有 3 个。
    +
    + +

    示例 3:

    + +
    输入:n = 3, k = 9
    +输出:"cab"
    +解释:长度为 3 的开心字符串总共有 12 个 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"] 。第 9 个字符串为 "cab"
    +
    + +

    示例 4:

    + +
    输入:n = 2, k = 7
    +输出:""
    +
    + +

    示例 5:

    + +
    输入:n = 10, k = 100
    +输出:"abacbabacb"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10
    • +
    • 1 <= k <= 100
    • +
    + +

     

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1416.leetcode1416 Restore The Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1416.leetcode1416 Restore The Array-zh.md" new file mode 100644 index 00000000..a3138190 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1416.leetcode1416 Restore The Array-zh.md" @@ -0,0 +1,92 @@ +# [1416. 恢复数组](https://leetcode-cn.com/problems/restore-the-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1416.Restore%20The%20Array/README_EN.md) + +## 题目描述 + + + +

    某个程序本来应该输出一个整数数组。但是这个程序忘记输出空格了以致输出了一个数字字符串,我们所知道的信息只有:数组中所有整数都在 [1, k] 之间,且数组中的数字都没有前导 0 。

    + +

    给你字符串 s 和整数 k 。可能会有多种不同的数组恢复结果。

    + +

    按照上述程序,请你返回所有可能输出字符串 s 的数组方案数。

    + +

    由于数组方案数可能会很大,请你返回它对 10^9 + 7 取余 后的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "1000", k = 10000
    +输出:1
    +解释:唯一一种可能的数组方案是 [1000]
    +
    + +

    示例 2:

    + +
    输入:s = "1000", k = 10
    +输出:0
    +解释:不存在任何数组方案满足所有整数都 >= 1 且 <= 10 同时输出结果为 s 。
    +
    + +

    示例 3:

    + +
    输入:s = "1317", k = 2000
    +输出:8
    +解释:可行的数组方案为 [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
    +
    + +

    示例 4:

    + +
    输入:s = "2020", k = 30
    +输出:1
    +解释:唯一可能的数组方案是 [20,20] 。 [2020] 不是可行的数组方案,原因是 2020 > 30 。 [2,020] 也不是可行的数组方案,因为 020 含有前导 0 。
    +
    + +

    示例 5:

    + +
    输入:s = "1234567890", k = 90
    +输出:34
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5.
    • +
    • s 只包含数字且不包含前导 0 。
    • +
    • 1 <= k <= 10^9.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1417.leetcode1417 Reformat The String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1417.leetcode1417 Reformat The String-zh.md" new file mode 100644 index 00000000..e5ca656d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1417.leetcode1417 Reformat The String-zh.md" @@ -0,0 +1,88 @@ +# [1417. 重新格式化字符串](https://leetcode-cn.com/problems/reformat-the-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1417.Reformat%20The%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。

    + +

    请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。

    + +

    请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串

    + +

     

    + +

    示例 1:

    + +
    输入:s = "a0b1c2"
    +输出:"0a1b2c"
    +解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。
    +
    + +

    示例 2:

    + +
    输入:s = "leetcode"
    +输出:""
    +解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。
    +
    + +

    示例 3:

    + +
    输入:s = "1229857369"
    +输出:""
    +解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。
    +
    + +

    示例 4:

    + +
    输入:s = "covid2019"
    +输出:"c2o0v1i9d"
    +
    + +

    示例 5:

    + +
    输入:s = "ab123"
    +输出:"1a2b3"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 仅由小写英文字母和/或数字组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1418.leetcode1418 Display Table of Food Orders in a Restaurant-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1418.leetcode1418 Display Table of Food Orders in a Restaurant-zh.md" new file mode 100644 index 00000000..5ce0b21d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1418.leetcode1418 Display Table of Food Orders in a Restaurant-zh.md" @@ -0,0 +1,88 @@ +# [1418. 点菜展示表](https://leetcode-cn.com/problems/display-table-of-food-orders-in-a-restaurant) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1418.Display%20Table%20of%20Food%20Orders%20in%20a%20Restaurant/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 orders,表示客户在餐厅中完成的订单,确切地说, orders[i]=[customerNamei,tableNumberi,foodItemi] ,其中 customerNamei 是客户的姓名,tableNumberi 是客户所在餐桌的桌号,而 foodItemi 是客户点的餐品名称。

    + +

    请你返回该餐厅的 点菜展示表在这张表中,表中第一行为标题,其第一列为餐桌桌号 “Table” ,后面每一列都是按字母顺序排列的餐品名称。接下来每一行中的项则表示每张餐桌订购的相应餐品数量,第一列应当填对应的桌号,后面依次填写下单的餐品数量。

    + +

    注意:客户姓名不是点菜展示表的一部分。此外,表中的数据行应该按餐桌桌号升序排列。

    + +

     

    + +

    示例 1:

    + +
    输入:orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
    +输出:[["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] 
    +解释:
    +点菜展示表如下所示:
    +Table,Beef Burrito,Ceviche,Fried Chicken,Water
    +3    ,0           ,2      ,1            ,0
    +5    ,0           ,1      ,0            ,1
    +10   ,1           ,0      ,0            ,0
    +对于餐桌 3:David 点了 "Ceviche" 和 "Fried Chicken",而 Rous 点了 "Ceviche"
    +而餐桌 5:Carla 点了 "Water" 和 "Ceviche"
    +餐桌 10:Corina 点了 "Beef Burrito" 
    +
    + +

    示例 2:

    + +
    输入:orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
    +输出:[["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] 
    +解释:
    +对于餐桌 1:Adam 和 Brianna 都点了 "Canadian Waffles"
    +而餐桌 12:James, Ratesh 和 Amadeus 都点了 "Fried Chicken"
    +
    + +

    示例 3:

    + +
    输入:orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
    +输出:[["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= orders.length <= 5 * 10^4
    • +
    • orders[i].length == 3
    • +
    • 1 <= customerNamei.length, foodItemi.length <= 20
    • +
    • customerNameifoodItemi 由大小写英文字母及空格字符 ' ' 组成。
    • +
    • tableNumberi1500 范围内的整数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1419.leetcode1419 Minimum Number of Frogs Croaking-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1419.leetcode1419 Minimum Number of Frogs Croaking-zh.md" new file mode 100644 index 00000000..10aefaac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1419.leetcode1419 Minimum Number of Frogs Croaking-zh.md" @@ -0,0 +1,88 @@ +# [1419. 数青蛙](https://leetcode-cn.com/problems/minimum-number-of-frogs-croaking) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1419.Minimum%20Number%20of%20Frogs%20Croaking/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 croakOfFrogs,它表示不同青蛙发出的蛙鸣声(字符串 "croak" )的组合。由于同一时间可以有多只青蛙呱呱作响,所以 croakOfFrogs 中会混合多个 “croak” 请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。

    + +

    注意:要想发出蛙鸣 "croak",青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母,那么它就不会发出声音。

    + +

    如果字符串 croakOfFrogs 不是由若干有效的 "croak" 字符混合而成,请返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:croakOfFrogs = "croakcroak"
    +输出:1 
    +解释:一只青蛙 “呱呱” 两次
    +
    + +

    示例 2:

    + +
    +输入:croakOfFrogs = "crcoakroak"
    +输出:2 
    +解释:最少需要两只青蛙,“呱呱” 声用黑体标注
    +第一只青蛙 "crcoakroak"
    +第二只青蛙 "crcoakroak"
    +
    + +

    示例 3:

    + +
    +输入:croakOfFrogs = "croakcrook"
    +输出:-1
    +解释:给出的字符串不是 "croak" 的有效组合。
    +
    + +

    示例 4:

    + +
    +输入:croakOfFrogs = "croakcroa"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= croakOfFrogs.length <= 10^5
    • +
    • 字符串中的字符只有 'c', 'r', 'o', 'a' 或者 'k'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1420.leetcode1420 Build Array Where You Can Find The Maximum Exactly K Comparisons-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1420.leetcode1420 Build Array Where You Can Find The Maximum Exactly K Comparisons-zh.md" new file mode 100644 index 00000000..0b74e142 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1420.leetcode1420 Build Array Where You Can Find The Maximum Exactly K Comparisons-zh.md" @@ -0,0 +1,98 @@ +# [1420. 生成数组](https://leetcode-cn.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1420.Build%20Array%20Where%20You%20Can%20Find%20The%20Maximum%20Exactly%20K%20Comparisons/README_EN.md) + +## 题目描述 + + + +

    给你三个整数 nmk 。下图描述的算法用于找出正整数数组中最大的元素。

    + +

    + +

    请你生成一个具有下述属性的数组 arr

    + +
      +
    • arr 中有 n 个整数。
    • +
    • 1 <= arr[i] <= m 其中 (0 <= i < n)
    • +
    • 将上面提到的算法应用于 arrsearch_cost 的值等于 k
    • +
    + +

    返回上述条件下生成数组 arr方法数 ,由于答案可能会很大,所以 必须10^9 + 7 取余。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 2, m = 3, k = 1
    +输出:6
    +解释:可能的数组分别为 [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
    +
    + +

    示例 2:

    + +
    输入:n = 5, m = 2, k = 3
    +输出:0
    +解释:没有数组可以满足上述条件
    +
    + +

    示例 3:

    + +
    输入:n = 9, m = 1, k = 1
    +输出:1
    +解释:可能的数组只有 [1, 1, 1, 1, 1, 1, 1, 1, 1]
    +
    + +

    示例 4:

    + +
    输入:n = 50, m = 100, k = 25
    +输出:34549172
    +解释:不要忘了对 1000000007 取余
    +
    + +

    示例 5:

    + +
    输入:n = 37, m = 17, k = 7
    +输出:418930126
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 50
    • +
    • 1 <= m <= 100
    • +
    • 0 <= k <= n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1421.leetcode1421 NPV Queries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1421.leetcode1421 NPV Queries-zh.md" new file mode 100644 index 00000000..e598a774 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1421.leetcode1421 NPV Queries-zh.md" @@ -0,0 +1,101 @@ +# [1421. 净现值查询](https://leetcode-cn.com/problems/npv-queries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1421.NPV%20Queries/README_EN.md) + +## 题目描述 + + + +

    表: NPV

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| year          | int     |
    +| npv           | int     |
    ++---------------+---------+
    +(id, year) 是该表主键.
    +该表有每一笔存货的年份, id 和对应净现值的信息.
    +
    + +

     

    + +

    表: Queries

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| year          | int     |
    ++---------------+---------+
    +(id, year) 是该表主键.
    +该表有每一次查询所对应存货的 id 和年份的信息.
    +
    + +

     

    + +

    写一个 SQL, 找到 Queries 表中每一次查询的净现值.

    + +

    结果表没有顺序要求.

    + +

    查询结果的格式如下所示:

    + +
    NPV 表:
    ++------+--------+--------+
    +| id   | year   | npv    |
    ++------+--------+--------+
    +| 1    | 2018   | 100    |
    +| 7    | 2020   | 30     |
    +| 13   | 2019   | 40     |
    +| 1    | 2019   | 113    |
    +| 2    | 2008   | 121    |
    +| 3    | 2009   | 12     |
    +| 11   | 2020   | 99     |
    +| 7    | 2019   | 0      |
    ++------+--------+--------+
    +
    +Queries 表:
    ++------+--------+
    +| id   | year   |
    ++------+--------+
    +| 1    | 2019   |
    +| 2    | 2008   |
    +| 3    | 2009   |
    +| 7    | 2018   |
    +| 7    | 2019   |
    +| 7    | 2020   |
    +| 13   | 2019   |
    ++------+--------+
    +
    +结果表:
    ++------+--------+--------+
    +| id   | year   | npv    |
    ++------+--------+--------+
    +| 1    | 2019   | 113    |
    +| 2    | 2008   | 121    |
    +| 3    | 2009   | 12     |
    +| 7    | 2018   | 0      |
    +| 7    | 2019   | 0      |
    +| 7    | 2020   | 30     |
    +| 13   | 2019   | 40     |
    ++------+--------+--------+
    +
    +(7, 2018)的净现值不在 NPV 表中, 我们把它看作是 0.
    +所有其它查询的净现值都能在 NPV 表中找到.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1422.leetcode1422 Maximum Score After Splitting a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1422.leetcode1422 Maximum Score After Splitting a String-zh.md" new file mode 100644 index 00000000..f3ba7df9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1422.leetcode1422 Maximum Score After Splitting a String-zh.md" @@ -0,0 +1,79 @@ +# [1422. 分割字符串的最大得分](https://leetcode-cn.com/problems/maximum-score-after-splitting-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1422.Maximum%20Score%20After%20Splitting%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个由若干 0 和 1 组成的字符串 s ,请你计算并返回将该字符串分割成两个 非空 子字符串(即  子字符串和 子字符串)所能获得的最大得分。

    + +

    「分割字符串的得分」为 子字符串中 0 的数量加上 子字符串中 1 的数量。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "011101"
    +输出:5 
    +解释:
    +将字符串 s 划分为两个非空子字符串的可行方案有:
    +左子字符串 = "0" 且 右子字符串 = "11101",得分 = 1 + 4 = 5 
    +左子字符串 = "01" 且 右子字符串 = "1101",得分 = 1 + 3 = 4 
    +左子字符串 = "011" 且 右子字符串 = "101",得分 = 1 + 2 = 3 
    +左子字符串 = "0111" 且 右子字符串 = "01",得分 = 1 + 1 = 2 
    +左子字符串 = "01110" 且 右子字符串 = "1",得分 = 2 + 1 = 3
    +
    + +

    示例 2:

    + +
    输入:s = "00111"
    +输出:5
    +解释:当 左子字符串 = "00" 且 右子字符串 = "111" 时,我们得到最大得分 = 2 + 3 = 5
    +
    + +

    示例 3:

    + +
    输入:s = "1111"
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= s.length <= 500
    • +
    • 字符串 s 仅由字符 '0''1' 组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1423.leetcode1423 Maximum Points You Can Obtain from Cards-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1423.leetcode1423 Maximum Points You Can Obtain from Cards-zh.md" new file mode 100644 index 00000000..8e4655b5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1423.leetcode1423 Maximum Points You Can Obtain from Cards-zh.md" @@ -0,0 +1,92 @@ +# [1423. 可获得的最大点数](https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1423.Maximum%20Points%20You%20Can%20Obtain%20from%20Cards/README_EN.md) + +## 题目描述 + + + +

    几张卡牌 排成一行,每张卡牌都有一个对应的点数。点数由整数数组 cardPoints 给出。

    + +

    每次行动,你可以从行的开头或者末尾拿一张卡牌,最终你必须正好拿 k 张卡牌。

    + +

    你的点数就是你拿到手中的所有卡牌的点数之和。

    + +

    给你一个整数数组 cardPoints 和整数 k,请你返回可以获得的最大点数。

    + +

     

    + +

    示例 1:

    + +
    输入:cardPoints = [1,2,3,4,5,6,1], k = 3
    +输出:12
    +解释:第一次行动,不管拿哪张牌,你的点数总是 1 。但是,先拿最右边的卡牌将会最大化你的可获得点数。最优策略是拿右边的三张牌,最终点数为 1 + 6 + 5 = 12 。
    +
    + +

    示例 2:

    + +
    输入:cardPoints = [2,2,2], k = 2
    +输出:4
    +解释:无论你拿起哪两张卡牌,可获得的点数总是 4 。
    +
    + +

    示例 3:

    + +
    输入:cardPoints = [9,7,7,9,7,7,9], k = 7
    +输出:55
    +解释:你必须拿起所有卡牌,可以获得的点数为所有卡牌的点数之和。
    +
    + +

    示例 4:

    + +
    输入:cardPoints = [1,1000,1], k = 1
    +输出:1
    +解释:你无法拿到中间那张卡牌,所以可以获得的最大点数为 1 。 
    +
    + +

    示例 5:

    + +
    输入:cardPoints = [1,79,80,1,1,1,200,1], k = 3
    +输出:202
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= cardPoints.length <= 10^5
    • +
    • 1 <= cardPoints[i] <= 10^4
    • +
    • 1 <= k <= cardPoints.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1424.leetcode1424 Diagonal Traverse II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1424.leetcode1424 Diagonal Traverse II-zh.md" new file mode 100644 index 00000000..75bd2636 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1424.leetcode1424 Diagonal Traverse II-zh.md" @@ -0,0 +1,81 @@ +# [1424. 对角线遍历 II](https://leetcode-cn.com/problems/diagonal-traverse-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1424.Diagonal%20Traverse%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个列表 nums ,里面每一个元素都是一个整数列表。请你依照下面各图的规则,按顺序返回 nums 中对角线上的整数。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:nums = [[1,2,3],[4,5,6],[7,8,9]]
    +输出:[1,4,2,7,5,3,8,6,9]
    +
    + +

    示例 2:

    + +

    + +
    输入:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
    +输出:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
    +
    + +

    示例 3:

    + +
    输入:nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]]
    +输出:[1,4,2,5,3,8,6,9,7,10,11]
    +
    + +

    示例 4:

    + +
    输入:nums = [[1,2,3,4,5,6]]
    +输出:[1,2,3,4,5,6]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i].length <= 10^5
    • +
    • 1 <= nums[i][j] <= 10^9
    • +
    • nums 中最多有 10^5 个数字。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1425.leetcode1425 Constrained Subsequence Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1425.leetcode1425 Constrained Subsequence Sum-zh.md" new file mode 100644 index 00000000..82f5c2a3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1425.leetcode1425 Constrained Subsequence Sum-zh.md" @@ -0,0 +1,74 @@ +# [1425. 带限制的子序列和](https://leetcode-cn.com/problems/constrained-subsequence-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1425.Constrained%20Subsequence%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 k ,请你返回 非空 子序列元素和的最大值,子序列需要满足:子序列中每两个 相邻 的整数 nums[i] 和 nums[j] ,它们在原数组中的下标 i 和 j 满足 i < j 且 j - i <= k

    + +

    数组的子序列定义为:将数组中的若干个数字删除(可以删除 0 个数字),剩下的数字按照原本的顺序排布。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [10,2,-10,5,20], k = 2
    +输出:37
    +解释:子序列为 [10, 2, 5, 20] 。
    +
    + +

    示例 2:

    + +
    输入:nums = [-1,-2,-3], k = 1
    +输出:-1
    +解释:子序列必须是非空的,所以我们选择最大的数字。
    +
    + +

    示例 3:

    + +
    输入:nums = [10,-2,-10,-5,20], k = 2
    +输出:23
    +解释:子序列为 [10, -2, -5, 20] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= nums.length <= 10^5
    • +
    • -10^4 <= nums[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1426.leetcode1426 Counting Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1426.leetcode1426 Counting Elements-zh.md" new file mode 100644 index 00000000..af8fe226 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1426.leetcode1426 Counting Elements-zh.md" @@ -0,0 +1,80 @@ +# [1426. 数元素](https://leetcode-cn.com/problems/counting-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1426.Counting%20Elements/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr, 对于元素 x ,只有当 x + 1 也在数组 arr 里时,才能记为 1 个数。

    + +

    如果数组 arr 里有重复的数,每个重复的数单独计算。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2,3]
    +输出:2
    +解释:1 和 2 被计算次数因为 2 和 3 在数组 arr 里。
    + +

    示例 2:

    + +
    输入:arr = [1,1,3,3,5,5,7,7]
    +输出:0
    +解释:所有的数都不算, 因为数组里没有 2、4、6、8。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,3,2,3,5,0]
    +输出:3
    +解释:0、1、2 被计算了因为 1、2、3 在数组里。
    +
    + +

    示例 4:

    + +
    输入:arr = [1,1,2,2]
    +输出:2
    +解释:两个 1 被计算了因为有 2 在数组里。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 0 <= arr[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1427.leetcode1427 Perform String Shifts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1427.leetcode1427 Perform String Shifts-zh.md" new file mode 100644 index 00000000..99584600 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1427.leetcode1427 Perform String Shifts-zh.md" @@ -0,0 +1,84 @@ +# [1427. 字符串的左右移](https://leetcode-cn.com/problems/perform-string-shifts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1427.Perform%20String%20Shifts/README_EN.md) + +## 题目描述 + + + +

    给定一个包含小写英文字母的字符串 s 以及一个矩阵 shift,其中 shift[i] = [direction, amount]

    + +
      +
    • direction 可以为 0 (表示左移)或 1 (表示右移)。
    • +
    • amount 表示 s 左右移的位数。
    • +
    • 左移 1 位表示移除 s 的第一个字符,并将该字符插入到 s 的结尾。
    • +
    • 类似地,右移 1 位表示移除 s 的最后一个字符,并将该字符插入到 s 的开头。
    • +
    + +

    对这个字符串进行所有操作后,返回最终结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abc", shift = [[0,1],[1,2]]
    +输出:"cab"
    +解释:
    +[0,1] 表示左移 1 位。 "abc" -> "bca"
    +[1,2] 表示右移 2 位。 "bca" -> "cab"
    + +

    示例 2:

    + +
    +输入:s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
    +输出:"efgabcd"
    +解释: 
    +[1,1] 表示右移 1 位。 "abcdefg" -> "gabcdef"
    +[1,1] 表示右移 1 位。 "gabcdef" -> "fgabcde"
    +[0,2] 表示左移 2 位。 "fgabcde" -> "abcdefg"
    +[1,3] 表示右移 3 位。 "abcdefg" -> "efgabcd"
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s 只包含小写英文字母
    • +
    • 1 <= shift.length <= 100
    • +
    • shift[i].length == 2
    • +
    • 0 <= shift[i][0] <= 1
    • +
    • 0 <= shift[i][1] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1428.leetcode1428 Leftmost Column with at Least a One-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1428.leetcode1428 Leftmost Column with at Least a One-zh.md" new file mode 100644 index 00000000..f1cf23a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1428.leetcode1428 Leftmost Column with at Least a One-zh.md" @@ -0,0 +1,252 @@ +# [1428. 至少有一个 1 的最左端列](https://leetcode-cn.com/problems/leftmost-column-with-at-least-a-one) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1428.Leftmost%20Column%20with%20at%20Least%20a%20One/README_EN.md) + +## 题目描述 + + + +

    (这是一个交互题

    + +

    我们称只包含元素 0 或 1 的矩阵为二进制矩阵。矩阵中每个单独的行都按非递减顺序排序。

    + +

    给定一个这样的二进制矩阵,返回至少包含一个 1 的最左端列的索引(从 0 开始)。如果这样的列不存在,返回 -1

    + +

    您不能直接访问该二进制矩阵。你只可以通过 BinaryMatrix 接口来访问。

    + +
      +
    • BinaryMatrix.get(row, col) 返回位于索引 (row, col) (从 0 开始)的元素。
    • +
    • BinaryMatrix.dimensions() 返回含有 2 个元素的列表 [rows, cols],表示这是一个 rows * cols的矩阵。
    • +
    + +

    如果提交的答案调用 BinaryMatrix.get 超过 1000 次,则该答案会被判定为错误答案。提交任何试图规避判定机制的答案将会被取消资格。

    + +

    下列示例中, mat 为给定的二进制矩阵。您不能直接访问该矩阵。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入: mat = [[0,0],[1,1]]
    +输出: 0
    +
    + +

    示例 2:

    + +

    + +
    +输入: mat = [[0,0],[0,1]]
    +输出: 1
    +
    + +

    示例 3:

    + +

    + +
    +输入: mat = [[0,0],[0,0]]
    +输出: -1
    + +

    示例 4:

    + +

    + +
    +输入: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
    +输出: 1
    +
    + +

     

    + +

    提示:

    + +
      +
    • rows == mat.length
    • +
    • cols == mat[i].length
    • +
    • 1 <= rows, cols <= 100
    • +
    • mat[i][j] 只会是 0 或 1
    • +
    • mat[i] 已按非递减顺序排序。
    • +
    + + +## 解法 + + + +二分查找。 + + + +### **Python3** + + + +```python +# """ +# This is BinaryMatrix's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class BinaryMatrix(object): +# def get(self, row: int, col: int) -> int: +# def dimensions(self) -> list[]: + +class Solution: + def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int: + rows, cols = binaryMatrix.dimensions() + res = -1 + for row in range(rows): + left, right = 0, cols - 1 + while left < right: + mid = (left + right) >> 1 + if binaryMatrix.get(row, mid) == 1: + right = mid + else: + left = mid + 1 + if binaryMatrix.get(row, left) == 1: + if res == -1: + res = left + else: + res = min(res, left) + return res +``` + +### **Java** + + + +```java +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * interface BinaryMatrix { + * public int get(int row, int col) {} + * public List dimensions {} + * }; + */ + +class Solution { + public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) { + List scale = binaryMatrix.dimensions(); + int rows = scale.get(0), cols = scale.get(1); + int res = -1; + for (int row = 0; row < rows; ++row) { + int left = 0, right = cols - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (binaryMatrix.get(row, mid) == 1) { + right = mid; + } else { + left = mid + 1; + } + } + if (binaryMatrix.get(row, left) == 1) { + if (res == -1) { + res = left; + } else { + res = Math.min(res, left); + } + } + } + return res; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * class BinaryMatrix { + * public: + * int get(int row, int col); + * vector dimensions(); + * }; + */ + +class Solution { +public: + int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { + vector scale = binaryMatrix.dimensions(); + int rows = scale[0], cols = scale[1]; + int res = -1; + for (int row = 0; row < rows; ++row) { + int left = 0, right = cols - 1; + while (left < right) { + int mid = left + right >> 1; + if (binaryMatrix.get(row, mid) == 1) { + right = mid; + } else { + left = mid + 1; + } + } + if (binaryMatrix.get(row, left) == 1) { + if (res == -1) { + res = left; + } else { + res = min(res, left); + } + } + } + return res; + } +}; +``` + +### **Go** + +```go +/** + * // This is the BinaryMatrix's API interface. + * // You should not implement it, or speculate about its implementation + * type BinaryMatrix struct { + * Get func(int, int) int + * Dimensions func() []int + * } + */ + +func leftMostColumnWithOne(binaryMatrix BinaryMatrix) int { + scale := binaryMatrix.Dimensions() + rows, cols := scale[0], scale[1] + res := -1 + for row := 0; row < rows; row++ { + left, right := 0, cols-1 + for left < right { + mid := (left + right) >> 1 + if binaryMatrix.Get(row, mid) == 1 { + right = mid + } else { + left = mid + 1 + } + } + if binaryMatrix.Get(row, left) == 1 { + if res == -1 { + res = left + } else { + res = min(res, left) + } + } + } + return res +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1429.leetcode1429 First Unique Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1429.leetcode1429 First Unique Number-zh.md" new file mode 100644 index 00000000..8a78e23f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1429.leetcode1429 First Unique Number-zh.md" @@ -0,0 +1,181 @@ +# [1429. 第一个唯一数字](https://leetcode-cn.com/problems/first-unique-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1429.First%20Unique%20Number/README_EN.md) + +## 题目描述 + + + +

    给定一系列整数,插入一个队列中,找出队列中第一个唯一整数。

    + +

    实现 FirstUnique 类:

    + +
      +
    • FirstUnique(int[] nums) 用数组里的数字初始化队列。
    • +
    • int showFirstUnique() 返回队列中的 第一个唯一 整数的值。如果没有唯一整数,返回 -1。(译者注:此方法不移除队列中的任何元素)
    • +
    • void add(int value) 将 value 插入队列中。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"]
    +[[[2,3,5]],[],[5],[],[2],[],[3],[]]
    +输出:
    +[null,2,null,2,null,3,null,-1]
    +解释:
    +FirstUnique firstUnique = new FirstUnique([2,3,5]);
    +firstUnique.showFirstUnique(); // 返回 2
    +firstUnique.add(5);            // 此时队列为 [2,3,5,5]
    +firstUnique.showFirstUnique(); // 返回 2
    +firstUnique.add(2);            // 此时队列为 [2,3,5,5,2]
    +firstUnique.showFirstUnique(); // 返回 3
    +firstUnique.add(3);            // 此时队列为 [2,3,5,5,2,3]
    +firstUnique.showFirstUnique(); // 返回 -1
    +
    + +

    示例 2:

    + +
    +输入:
    +["FirstUnique","showFirstUnique","add","add","add","add","add","showFirstUnique"]
    +[[[7,7,7,7,7,7]],[],[7],[3],[3],[7],[17],[]]
    +输出:
    +[null,-1,null,null,null,null,null,17]
    +解释:
    +FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]);
    +firstUnique.showFirstUnique(); // 返回 -1
    +firstUnique.add(7);            // 此时队列为 [7,7,7,7,7,7,7]
    +firstUnique.add(3);            // 此时队列为 [7,7,7,7,7,7,7,3]
    +firstUnique.add(3);            // 此时队列为 [7,7,7,7,7,7,7,3,3]
    +firstUnique.add(7);            // 此时队列为 [7,7,7,7,7,7,7,3,3,7]
    +firstUnique.add(17);           // 此时队列为 [7,7,7,7,7,7,7,3,3,7,17]
    +firstUnique.showFirstUnique(); // 返回 17
    +
    + +

    示例 3:

    + +
    +输入:
    +["FirstUnique","showFirstUnique","add","showFirstUnique"]
    +[[[809]],[],[809],[]]
    +输出:
    +[null,809,null,-1]
    +解释:
    +FirstUnique firstUnique = new FirstUnique([809]);
    +firstUnique.showFirstUnique(); // 返回 809
    +firstUnique.add(809);          // 此时队列为 [809,809]
    +firstUnique.showFirstUnique(); // 返回 -1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^8
    • +
    • 1 <= value <= 10^8
    • +
    • 最多调用 5000 次 showFirstUnique 和 add
    • +
    + +## 解法 + + + +“有序哈希表”实现。 + + + +### **Python3** + + + +```python +class FirstUnique: + + def __init__(self, nums: List[int]): + self.counter = collections.OrderedDict() + self.unique_nums = collections.OrderedDict() + for num in nums: + self.counter[num] = self.counter.get(num, 0) + 1 + for k, v in self.counter.items(): + if v == 1: + self.unique_nums[k] = 1 + + def showFirstUnique(self) -> int: + if len(self.unique_nums) == 0: + return -1 + for k in self.unique_nums.keys(): + return k + + def add(self, value: int) -> None: + if value not in self.counter: + self.counter[value] = 1 + self.unique_nums[value] = 1 + else: + self.counter[value] += 1 + if value in self.unique_nums: + self.unique_nums.pop(value) + +# Your FirstUnique object will be instantiated and called as such: +# obj = FirstUnique(nums) +# param_1 = obj.showFirstUnique() +# obj.add(value) +``` + +### **Java** + + + +```java +class FirstUnique { + private Map counter; + private Set uniqueNums; + + public FirstUnique(int[] nums) { + counter = new LinkedHashMap<>(); + uniqueNums = new LinkedHashSet<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + for (Map.Entry entry : counter.entrySet()) { + if (entry.getValue() == 1) { + uniqueNums.add(entry.getKey()); + } + } + } + + public int showFirstUnique() { + return uniqueNums.isEmpty() ? -1 : uniqueNums.iterator().next(); + } + + public void add(int value) { + if (!counter.containsKey(value)) { + counter.put(value, 1); + uniqueNums.add(value); + } else { + counter.put(value, counter.get(value) + 1); + uniqueNums.remove(value); + } + } +} + +/** + * Your FirstUnique object will be instantiated and called as such: + * FirstUnique obj = new FirstUnique(nums); + * int param_1 = obj.showFirstUnique(); + * obj.add(value); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1430.leetcode1430 Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1430.leetcode1430 Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree-zh.md" new file mode 100644 index 00000000..22693c13 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1430.leetcode1430 Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree-zh.md" @@ -0,0 +1,88 @@ +# [1430. 判断给定的序列是否是二叉树从根到叶的路径](https://leetcode-cn.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1430.Check%20If%20a%20String%20Is%20a%20Valid%20Sequence%20from%20Root%20to%20Leaves%20Path%20in%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一个二叉树,我们称从根节点到任意叶节点的任意路径中的节点值所构成的序列为该二叉树的一个 “有效序列” 。检查一个给定的序列是否是给定二叉树的一个 “有效序列” 。

    + +

    我们以整数数组 arr 的形式给出这个序列。从根节点到任意叶节点的任意路径中的节点值所构成的序列都是这个二叉树的 “有效序列” 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
    +输出:true
    +解释:
    +路径 0 -> 1 -> 0 -> 1 是一个“有效序列”(图中的绿色节点)。
    +其他的“有效序列”是:
    +0 -> 1 -> 1 -> 0 
    +0 -> 0 -> 0
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
    +输出:false 
    +解释:路径 0 -> 0 -> 1 不存在,所以这不是一个“序列”。
    +
    + +

    示例 3:

    + +

    + +
    +输入:root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
    +输出:false
    +解释:路径 0 -> 1 -> 1 是一个序列,但不是一个“有效序列”(译者注:因为序列的终点不是叶节点)。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 5000
    • +
    • 0 <= arr[i] <= 9
    • +
    • 每个节点的值的取值范围是 [0 - 9]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1431.leetcode1431 Kids With the Greatest Number of Candies-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1431.leetcode1431 Kids With the Greatest Number of Candies-zh.md" new file mode 100644 index 00000000..f955fbde --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1431.leetcode1431 Kids With the Greatest Number of Candies-zh.md" @@ -0,0 +1,79 @@ +# [1431. 拥有最多糖果的孩子](https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1431.Kids%20With%20the%20Greatest%20Number%20of%20Candies/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 candies 和一个整数 extraCandies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目。

    + +

    对每一个孩子,检查是否存在一种方案,将额外的 extraCandies 个糖果分配给孩子们之后,此孩子有 最多 的糖果。注意,允许有多个孩子同时拥有 最多 的糖果数目。

    + +

     

    + +

    示例 1:

    + +
    输入:candies = [2,3,5,1,3], extraCandies = 3
    +输出:[true,true,true,false,true] 
    +解释:
    +孩子 1 有 2 个糖果,如果他得到所有额外的糖果(3个),那么他总共有 5 个糖果,他将成为拥有最多糖果的孩子。
    +孩子 2 有 3 个糖果,如果他得到至少 2 个额外糖果,那么他将成为拥有最多糖果的孩子。
    +孩子 3 有 5 个糖果,他已经是拥有最多糖果的孩子。
    +孩子 4 有 1 个糖果,即使他得到所有额外的糖果,他也只有 4 个糖果,无法成为拥有糖果最多的孩子。
    +孩子 5 有 3 个糖果,如果他得到至少 2 个额外糖果,那么他将成为拥有最多糖果的孩子。
    +
    + +

    示例 2:

    + +
    输入:candies = [4,2,1,1,2], extraCandies = 1
    +输出:[true,false,false,false,false] 
    +解释:只有 1 个额外糖果,所以不管额外糖果给谁,只有孩子 1 可以成为拥有糖果最多的孩子。
    +
    + +

    示例 3:

    + +
    输入:candies = [12,1,12], extraCandies = 10
    +输出:[true,false,true]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= candies.length <= 100
    • +
    • 1 <= candies[i] <= 100
    • +
    • 1 <= extraCandies <= 50
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1432.leetcode1432 Max Difference You Can Get From Changing an Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1432.leetcode1432 Max Difference You Can Get From Changing an Integer-zh.md" new file mode 100644 index 00000000..a3773ef3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1432.leetcode1432 Max Difference You Can Get From Changing an Integer-zh.md" @@ -0,0 +1,97 @@ +# [1432. 改变一个整数能得到的最大差值](https://leetcode-cn.com/problems/max-difference-you-can-get-from-changing-an-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1432.Max%20Difference%20You%20Can%20Get%20From%20Changing%20an%20Integer/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 num 。你可以对它进行如下步骤恰好 两次 :

    + +
      +
    • 选择一个数字 x (0 <= x <= 9).
    • +
    • 选择另一个数字 y (0 <= y <= 9) 。数字 y 可以等于 x 。
    • +
    • num 中所有出现 x 的数位都用 y 替换。
    • +
    • 得到的新的整数 不能 有前导 0 ,得到的新整数也 不能 是 0 。
    • +
    + +

    令两次对 num 的操作得到的结果分别为 a 和 b 。

    + +

    请你返回 a 和 b 的 最大差值

    + +

     

    + +

    示例 1:

    + +
    输入:num = 555
    +输出:888
    +解释:第一次选择 x = 5 且 y = 9 ,并把得到的新数字保存在 a 中。
    +第二次选择 x = 5 且 y = 1 ,并把得到的新数字保存在 b 中。
    +现在,我们有 a = 999 和 b = 111 ,最大差值为 888
    +
    + +

    示例 2:

    + +
    输入:num = 9
    +输出:8
    +解释:第一次选择 x = 9 且 y = 9 ,并把得到的新数字保存在 a 中。
    +第二次选择 x = 9 且 y = 1 ,并把得到的新数字保存在 b 中。
    +现在,我们有 a = 9 和 b = 1 ,最大差值为 8
    +
    + +

    示例 3:

    + +
    输入:num = 123456
    +输出:820000
    +
    + +

    示例 4:

    + +
    输入:num = 10000
    +输出:80000
    +
    + +

    示例 5:

    + +
    输入:num = 9288
    +输出:8700
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num <= 10^8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1433.leetcode1433 Check If a String Can Break Another String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1433.leetcode1433 Check If a String Can Break Another String-zh.md" new file mode 100644 index 00000000..22d8758a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1433.leetcode1433 Check If a String Can Break Another String-zh.md" @@ -0,0 +1,75 @@ +# [1433. 检查一个字符串是否可以打破另一个字符串](https://leetcode-cn.com/problems/check-if-a-string-can-break-another-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1433.Check%20If%20a%20String%20Can%20Break%20Another%20String/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 s1 和 s2 ,它们长度相等,请你检查是否存在一个 s1  的排列可以打破 s2 的一个排列,或者是否存在一个 s2 的排列可以打破 s1 的一个排列。

    + +

    字符串 x 可以打破字符串 y (两者长度都为 n )需满足对于所有 i(在 0 到 n - 1 之间)都有 x[i] >= y[i](字典序意义下的顺序)。

    + +

     

    + +

    示例 1:

    + +
    输入:s1 = "abc", s2 = "xya"
    +输出:true
    +解释:"ayx" 是 s2="xya" 的一个排列,"abc" 是字符串 s1="abc" 的一个排列,且 "ayx" 可以打破 "abc" 。
    +
    + +

    示例 2:

    + +
    输入:s1 = "abe", s2 = "acd"
    +输出:false 
    +解释:s1="abe" 的所有排列包括:"abe","aeb","bae","bea","eab" 和 "eba" ,s2="acd" 的所有排列包括:"acd","adc","cad","cda","dac" 和 "dca"。然而没有任何 s1 的排列可以打破 s2 的排列。也没有 s2 的排列能打破 s1 的排列。
    +
    + +

    示例 3:

    + +
    输入:s1 = "leetcodee", s2 = "interview"
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • s1.length == n
    • +
    • s2.length == n
    • +
    • 1 <= n <= 10^5
    • +
    • 所有字符串都只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1434.leetcode1434 Number of Ways to Wear Different Hats to Each Other-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1434.leetcode1434 Number of Ways to Wear Different Hats to Each Other-zh.md" new file mode 100644 index 00000000..ac9aebbb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1434.leetcode1434 Number of Ways to Wear Different Hats to Each Other-zh.md" @@ -0,0 +1,93 @@ +# [1434. 每个人戴不同帽子的方案数](https://leetcode-cn.com/problems/number-of-ways-to-wear-different-hats-to-each-other) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1434.Number%20of%20Ways%20to%20Wear%20Different%20Hats%20to%20Each%20Other/README_EN.md) + +## 题目描述 + + + +

    总共有 n 个人和 40 种不同的帽子,帽子编号从 140

    + +

    给你一个整数列表的列表 hats ,其中 hats[i] 是第 i 个人所有喜欢帽子的列表。

    + +

    请你给每个人安排一顶他喜欢的帽子,确保每个人戴的帽子跟别人都不一样,并返回方案数。

    + +

    由于答案可能很大,请返回它对 10^9 + 7 取余后的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:hats = [[3,4],[4,5],[5]]
    +输出:1
    +解释:给定条件下只有一种方法选择帽子。
    +第一个人选择帽子 3,第二个人选择帽子 4,最后一个人选择帽子 5。
    + +

    示例 2:

    + +
    +输入:hats = [[3,5,1],[3,5]]
    +输出:4
    +解释:总共有 4 种安排帽子的方法:
    +(3,5),(5,3),(1,3) 和 (1,5)
    +
    + +

    示例 3:

    + +
    +输入:hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
    +输出:24
    +解释:每个人都可以从编号为 1 到 4 的帽子中选。
    +(1,2,3,4) 4 个帽子的排列方案数为 24 。
    +
    + +

    示例 4:

    + +
    +输入:hats = [[1,2,3],[2,3,5,6],[1,3,7,9],[1,8,9],[2,5,7]]
    +输出:111
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == hats.length
    • +
    • 1 <= n <= 10
    • +
    • 1 <= hats[i].length <= 40
    • +
    • 1 <= hats[i][j] <= 40
    • +
    • hats[i] 包含一个数字互不相同的整数列表。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1435.leetcode1435 Create a Session Bar Chart-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1435.leetcode1435 Create a Session Bar Chart-zh.md" new file mode 100644 index 00000000..2aea344c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1435.leetcode1435 Create a Session Bar Chart-zh.md" @@ -0,0 +1,71 @@ +# [1435. 制作会话柱状图](https://leetcode-cn.com/problems/create-a-session-bar-chart) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1435.Create%20a%20Session%20Bar%20Chart/README_EN.md) + +## 题目描述 + + + +

    表:Sessions

    + +
    +---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| session_id          | int     |
    +| duration            | int     |
    ++---------------------+---------+
    +session_id 是该表主键
    +duration 是用户访问应用的时间, 以秒为单位
    +
    + +

     

    + +

    你想知道用户在你的 app 上的访问时长情况。因此决定统计访问时长区间分别为 "[0-5>", "[5-10>", "[10-15>" 和 "15 or more" (单位:分钟)的会话数量,并以此绘制柱状图。

    + +

    写一个SQL查询来报告(访问时长区间,会话总数)。结果可用任何顺序呈现。

    + +

     

    + +

    下方为查询的输出格式:

    + +
    Sessions 表:
    ++-------------+---------------+
    +| session_id  | duration      |
    ++-------------+---------------+
    +| 1           | 30            |
    +| 2           | 199           |
    +| 3           | 299           |
    +| 4           | 580           |
    +| 5           | 1000          |
    ++-------------+---------------+
    +
    +Result 表:
    ++--------------+--------------+
    +| bin          | total        |
    ++--------------+--------------+
    +| [0-5>        | 3            |
    +| [5-10>       | 1            |
    +| [10-15>      | 0            |
    +| 15 or more   | 1            |
    ++--------------+--------------+
    +
    +对于 session_id 1,2 和 3 ,它们的访问时间大于等于 0 分钟且小于 5 分钟。
    +对于 session_id 4,它的访问时间大于等于 5 分钟且小于 10 分钟。
    +没有会话的访问时间大于等于 10 分钟且小于 15 分钟。
    +对于 session_id 5, 它的访问时间大于等于 15 分钟。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1436.leetcode1436 Destination City-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1436.leetcode1436 Destination City-zh.md" new file mode 100644 index 00000000..2082c248 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1436.leetcode1436 Destination City-zh.md" @@ -0,0 +1,81 @@ +# [1436. 旅行终点站](https://leetcode-cn.com/problems/destination-city) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1436.Destination%20City/README_EN.md) + +## 题目描述 + + + +

    给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市

    + +

    题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。

    + +

     

    + +

    示例 1:

    + +
    输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
    +输出:"Sao Paulo" 
    +解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> "Lima" -> "Sao Paulo" 。
    +
    + +

    示例 2:

    + +
    输入:paths = [["B","C"],["D","B"],["C","A"]]
    +输出:"A"
    +解释:所有可能的线路是:
    +"D" -> "B" -> "C" -> "A". 
    +"B" -> "C" -> "A". 
    +"C" -> "A". 
    +"A". 
    +显然,旅行终点站是 "A" 。
    +
    + +

    示例 3:

    + +
    输入:paths = [["A","Z"]]
    +输出:"Z"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= paths.length <= 100
    • +
    • paths[i].length == 2
    • +
    • 1 <= cityAi.length, cityBi.length <= 10
    • +
    • cityA!= cityBi
    • +
    • 所有字符串均由大小写英文字母和空格字符组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1437.leetcode1437 Check If All 1's Are at Least Length K Places Away-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1437.leetcode1437 Check If All 1's Are at Least Length K Places Away-zh.md" new file mode 100644 index 00000000..4538aa62 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1437.leetcode1437 Check If All 1's Are at Least Length K Places Away-zh.md" @@ -0,0 +1,80 @@ +# [1437. 是否所有 1 都至少相隔 k 个元素](https://leetcode-cn.com/problems/check-if-all-1s-are-at-least-length-k-places-away) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1437.Check%20If%20All%201%27s%20Are%20at%20Least%20Length%20K%20Places%20Away/README_EN.md) + +## 题目描述 + + + +

    给你一个由若干 01 组成的数组 nums 以及整数 k。如果所有 1 都至少相隔 k 个元素,则返回 True ;否则,返回 False

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:nums = [1,0,0,0,1,0,0,1], k = 2
    +输出:true
    +解释:每个 1 都至少相隔 2 个元素。
    + +

    示例 2:

    + +

    + +
    输入:nums = [1,0,0,1,0,1], k = 2
    +输出:false
    +解释:第二个 1 和第三个 1 之间只隔了 1 个元素。
    + +

    示例 3:

    + +
    输入:nums = [1,1,1,1,1], k = 0
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:nums = [0,1,0,1], k = 1
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 0 <= k <= nums.length
    • +
    • nums[i] 的值为 01
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1438.leetcode1438 Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1438.leetcode1438 Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit-zh.md" new file mode 100644 index 00000000..9b65bd74 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1438.leetcode1438 Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit-zh.md" @@ -0,0 +1,85 @@ +# [1438. 绝对差不超过限制的最长连续子数组](https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1438.Longest%20Continuous%20Subarray%20With%20Absolute%20Diff%20Less%20Than%20or%20Equal%20to%20Limit/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,和一个表示限制的整数 limit,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit

    + +

    如果不存在满足条件的子数组,则返回 0

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [8,2,4,7], limit = 4
    +输出:2 
    +解释:所有子数组如下:
    +[8] 最大绝对差 |8-8| = 0 <= 4.
    +[8,2] 最大绝对差 |8-2| = 6 > 4. 
    +[8,2,4] 最大绝对差 |8-2| = 6 > 4.
    +[8,2,4,7] 最大绝对差 |8-2| = 6 > 4.
    +[2] 最大绝对差 |2-2| = 0 <= 4.
    +[2,4] 最大绝对差 |2-4| = 2 <= 4.
    +[2,4,7] 最大绝对差 |2-7| = 5 > 4.
    +[4] 最大绝对差 |4-4| = 0 <= 4.
    +[4,7] 最大绝对差 |4-7| = 3 <= 4.
    +[7] 最大绝对差 |7-7| = 0 <= 4. 
    +因此,满足题意的最长子数组的长度为 2 。
    +
    + +

    示例 2:

    + +
    输入:nums = [10,1,2,4,7,2], limit = 5
    +输出:4 
    +解释:满足题意的最长子数组是 [2,4,7,2],其最大绝对差 |2-7| = 5 <= 5 。
    +
    + +

    示例 3:

    + +
    输入:nums = [4,2,2,2,4,4,2,2], limit = 0
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^9
    • +
    • 0 <= limit <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1439.leetcode1439 Find the Kth Smallest Sum of a Matrix With Sorted Rows-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1439.leetcode1439 Find the Kth Smallest Sum of a Matrix With Sorted Rows-zh.md" new file mode 100644 index 00000000..6d5d82a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1439.leetcode1439 Find the Kth Smallest Sum of a Matrix With Sorted Rows-zh.md" @@ -0,0 +1,84 @@ +# [1439. 有序矩阵中的第 k 个最小数组和](https://leetcode-cn.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1439.Find%20the%20Kth%20Smallest%20Sum%20of%20a%20Matrix%20With%20Sorted%20Rows/README_EN.md) + +## 题目描述 + + + +

    给你一个 m * n 的矩阵 mat,以及一个整数 k ,矩阵中的每一行都以非递减的顺序排列。

    + +

    你可以从每一行中选出 1 个元素形成一个数组。返回所有可能数组中的第 k 个 最小 数组和。

    + +

     

    + +

    示例 1:

    + +
    输入:mat = [[1,3,11],[2,4,6]], k = 5
    +输出:7
    +解释:从每一行中选出一个元素,前 k 个和最小的数组分别是:
    +[1,2], [1,4], [3,2], [3,4], [1,6]。其中第 5 个的和是 7 。  
    + +

    示例 2:

    + +
    输入:mat = [[1,3,11],[2,4,6]], k = 9
    +输出:17
    +
    + +

    示例 3:

    + +
    输入:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
    +输出:9
    +解释:从每一行中选出一个元素,前 k 个和最小的数组分别是:
    +[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]。其中第 7 个的和是 9 。 
    +
    + +

    示例 4:

    + +
    输入:mat = [[1,1,10],[2,2,9]], k = 7
    +输出:12
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == mat.length
    • +
    • n == mat.length[i]
    • +
    • 1 <= m, n <= 40
    • +
    • 1 <= k <= min(200, n ^ m)
    • +
    • 1 <= mat[i][j] <= 5000
    • +
    • mat[i] 是一个非递减数组
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1440.leetcode1440 Evaluate Boolean Expression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1440.leetcode1440 Evaluate Boolean Expression-zh.md" new file mode 100644 index 00000000..2a7fad17 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1440.leetcode1440 Evaluate Boolean Expression-zh.md" @@ -0,0 +1,93 @@ +# [1440. 计算布尔表达式的值](https://leetcode-cn.com/problems/evaluate-boolean-expression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1440.Evaluate%20Boolean%20Expression/README_EN.md) + +## 题目描述 + + + +

    Variables:

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| name          | varchar |
    +| value         | int     |
    ++---------------+---------+
    +name 是该表主键.
    +该表包含了存储的变量及其对应的值.
    +
    + +

     

    + +

    Expressions:

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| left_operand  | varchar |
    +| operator      | enum    |
    +| right_operand | varchar |
    ++---------------+---------+
    +(left_operand, operator, right_operand) 是该表主键.
    +该表包含了需要计算的布尔表达式.
    +operator 是枚举类型, 取值于('<', '>', '=')
    +left_operand 和 right_operand 的值保证存在于 Variables 表单中.
    +
    + +

     

    + +

    写一个 SQL 查询,  以计算表 Expressions 中的布尔表达式.

    + +

    返回的结果表没有顺序要求.

    + +

    查询结果格式如下例所示.

    + +
    Variables 表:
    ++------+-------+
    +| name | value |
    ++------+-------+
    +| x    | 66    |
    +| y    | 77    |
    ++------+-------+
    +
    +Expressions 表:
    ++--------------+----------+---------------+
    +| left_operand | operator | right_operand |
    ++--------------+----------+---------------+
    +| x            | >        | y             |
    +| x            | <        | y             |
    +| x            | =        | y             |
    +| y            | >        | x             |
    +| y            | <        | x             |
    +| x            | =        | x             |
    ++--------------+----------+---------------+
    +
    +Result 表:
    ++--------------+----------+---------------+-------+
    +| left_operand | operator | right_operand | value |
    ++--------------+----------+---------------+-------+
    +| x            | >        | y             | false |
    +| x            | <        | y             | true  |
    +| x            | =        | y             | false |
    +| y            | >        | x             | true  |
    +| y            | <        | x             | false |
    +| x            | =        | x             | true  |
    ++--------------+----------+---------------+-------+
    +如上所示, 你需要通过使用 Variables 表来找到 Expressions 表中的每一个布尔表达式的值.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1441.leetcode1441 Build an Array With Stack Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1441.leetcode1441 Build an Array With Stack Operations-zh.md" new file mode 100644 index 00000000..dbdd23b6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1441.leetcode1441 Build an Array With Stack Operations-zh.md" @@ -0,0 +1,100 @@ +# [1441. 用栈操作构建数组](https://leetcode-cn.com/problems/build-an-array-with-stack-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1441.Build%20an%20Array%20With%20Stack%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你一个目标数组 target 和一个整数 n。每次迭代,需要从  list = {1,2,3..., n} 中依序读取一个数字。

    + +

    请使用下述操作来构建目标数组 target

    + +
      +
    • Push:从 list 中读取一个新元素, 并将其推入数组中。
    • +
    • Pop:删除数组中的最后一个元素。
    • +
    • 如果目标数组构建完成,就停止读取更多元素。
    • +
    + +

    题目数据保证目标数组严格递增,并且只包含 1n 之间的数字。

    + +

    请返回构建目标数组所用的操作序列。

    + +

    题目数据保证答案是唯一的。

    + +

     

    + +

    示例 1:

    + +
    +输入:target = [1,3], n = 3
    +输出:["Push","Push","Pop","Push"]
    +解释: 
    +读取 1 并自动推入数组 -> [1]
    +读取 2 并自动推入数组,然后删除它 -> [1]
    +读取 3 并自动推入数组 -> [1,3]
    +
    + +

    示例 2:

    + +
    +输入:target = [1,2,3], n = 3
    +输出:["Push","Push","Push"]
    +
    + +

    示例 3:

    + +
    +输入:target = [1,2], n = 4
    +输出:["Push","Push"]
    +解释:只需要读取前 2 个数字就可以停止。
    +
    + +

    示例 4:

    + +
    +输入:target = [2,3,4], n = 4
    +输出:["Push","Pop","Push","Push","Push"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target.length <= 100
    • +
    • 1 <= target[i] <= 100
    • +
    • 1 <= n <= 100
    • +
    • target 是严格递增的
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1442.leetcode1442 Count Triplets That Can Form Two Arrays of Equal XOR-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1442.leetcode1442 Count Triplets That Can Form Two Arrays of Equal XOR-zh.md" new file mode 100644 index 00000000..a51d05dd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1442.leetcode1442 Count Triplets That Can Form Two Arrays of Equal XOR-zh.md" @@ -0,0 +1,95 @@ +# [1442. 形成两个异或相等数组的三元组数目](https://leetcode-cn.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1442.Count%20Triplets%20That%20Can%20Form%20Two%20Arrays%20of%20Equal%20XOR/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr

    + +

    现需要从数组中取三个下标 ijk ,其中 (0 <= i < j <= k < arr.length)

    + +

    ab 定义如下:

    + +
      +
    • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
    • +
    • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
    • +
    + +

    注意:^ 表示 按位异或 操作。

    + +

    请返回能够令 a == b 成立的三元组 (i, j , k) 的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [2,3,1,6,7]
    +输出:4
    +解释:满足题意的三元组分别是 (0,1,2), (0,2,2), (2,3,4) 以及 (2,4,4)
    +
    + +

    示例 2:

    + +
    输入:arr = [1,1,1,1,1]
    +输出:10
    +
    + +

    示例 3:

    + +
    输入:arr = [2,3]
    +输出:0
    +
    + +

    示例 4:

    + +
    输入:arr = [1,3,5,7,9]
    +输出:3
    +
    + +

    示例 5:

    + +
    输入:arr = [7,11,12,9,5,2,7,17,22]
    +输出:8
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 300
    • +
    • 1 <= arr[i] <= 10^8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1443.leetcode1443 Minimum Time to Collect All Apples in a Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1443.leetcode1443 Minimum Time to Collect All Apples in a Tree-zh.md" new file mode 100644 index 00000000..651da05c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1443.leetcode1443 Minimum Time to Collect All Apples in a Tree-zh.md" @@ -0,0 +1,81 @@ +# [1443. 收集树上所有苹果的最少时间](https://leetcode-cn.com/problems/minimum-time-to-collect-all-apples-in-a-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1443.Minimum%20Time%20to%20Collect%20All%20Apples%20in%20a%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵有 n 个节点的无向树,节点编号为 0 到 n-1 ,它们中有一些节点有苹果。通过树上的一条边,需要花费 1 秒钟。你从 节点 0 出发,请你返回最少需要多少秒,可以收集到所有苹果,并回到节点 0 。

    + +

    无向树的边由 edges 给出,其中 edges[i] = [fromi, toi] ,表示有一条边连接 from 和 toi 。除此以外,还有一个布尔数组 hasApple ,其中 hasApple[i] = true 代表节点 i 有一个苹果,否则,节点 i 没有苹果。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
    +输出:8 
    +解释:上图展示了给定的树,其中红色节点表示有苹果。一个能收集到所有苹果的最优方案由绿色箭头表示。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
    +输出:6
    +解释:上图展示了给定的树,其中红色节点表示有苹果。一个能收集到所有苹果的最优方案由绿色箭头表示。
    +
    + +

    示例 3:

    + +
    输入:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • edges.length == n-1
    • +
    • edges[i].length == 2
    • +
    • 0 <= fromi, toi <= n-1
    • +
    • fromi < toi
    • +
    • hasApple.length == n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1444.leetcode1444 Number of Ways of Cutting a Pizza-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1444.leetcode1444 Number of Ways of Cutting a Pizza-zh.md" new file mode 100644 index 00000000..b5f6c4c5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1444.leetcode1444 Number of Ways of Cutting a Pizza-zh.md" @@ -0,0 +1,79 @@ +# [1444. 切披萨的方案数](https://leetcode-cn.com/problems/number-of-ways-of-cutting-a-pizza) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1444.Number%20of%20Ways%20of%20Cutting%20a%20Pizza/README_EN.md) + +## 题目描述 + + + +

    给你一个 rows x cols 大小的矩形披萨和一个整数 k ,矩形包含两种字符: 'A' (表示苹果)和 '.' (表示空白格子)。你需要切披萨 k-1 次,得到 k 块披萨并送给别人。

    + +

    切披萨的每一刀,先要选择是向垂直还是水平方向切,再在矩形的边界上选一个切的位置,将披萨一分为二。如果垂直地切披萨,那么需要把左边的部分送给一个人,如果水平地切,那么需要把上面的部分送给一个人。在切完最后一刀后,需要把剩下来的一块送给最后一个人。

    + +

    请你返回确保每一块披萨包含 至少 一个苹果的切披萨方案数。由于答案可能是个很大的数字,请你返回它对 10^9 + 7 取余的结果。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:pizza = ["A..","AAA","..."], k = 3
    +输出:3 
    +解释:上图展示了三种切披萨的方案。注意每一块披萨都至少包含一个苹果。
    +
    + +

    示例 2:

    + +
    输入:pizza = ["A..","AA.","..."], k = 3
    +输出:1
    +
    + +

    示例 3:

    + +
    输入:pizza = ["A..","A..","..."], k = 1
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rows, cols <= 50
    • +
    • rows == pizza.length
    • +
    • cols == pizza[i].length
    • +
    • 1 <= k <= 10
    • +
    • pizza 只包含字符 'A' 和 '.' 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1445.leetcode1445 Apples & Oranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1445.leetcode1445 Apples & Oranges-zh.md" new file mode 100644 index 00000000..92ccbcf4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1445.leetcode1445 Apples & Oranges-zh.md" @@ -0,0 +1,86 @@ +# [1445. 苹果和桔子](https://leetcode-cn.com/problems/apples-oranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1445.Apples%20%26%20Oranges/README_EN.md) + +## 题目描述 + + + +

    表: Sales

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| sale_date     | date    |
    +| fruit         | enum    | 
    +| sold_num      | int     | 
    ++---------------+---------+
    +(sale_date,fruit) 是该表主键.
    +该表包含了每一天中"苹果" 和 "桔子"的销售情况.
    +
    + +

     

    + +

    写一个 SQL 查询, 报告每一天 苹果 和 桔子 销售的数目的差异.

    + +

    返回的结果表, 按照格式为 ('YYYY-MM-DD') 的 sale_date 排序.

    + +

    查询结果表如下例所示:

    + +

     

    + +
    Sales 表:
    ++------------+------------+-------------+
    +| sale_date  | fruit      | sold_num    |
    ++------------+------------+-------------+
    +| 2020-05-01 | apples     | 10          |
    +| 2020-05-01 | oranges    | 8           |
    +| 2020-05-02 | apples     | 15          |
    +| 2020-05-02 | oranges    | 15          |
    +| 2020-05-03 | apples     | 20          |
    +| 2020-05-03 | oranges    | 0           |
    +| 2020-05-04 | apples     | 15          |
    +| 2020-05-04 | oranges    | 16          |
    ++------------+------------+-------------+
    +
    +Result 表:
    ++------------+--------------+
    +| sale_date  | diff         |
    ++------------+--------------+
    +| 2020-05-01 | 2            |
    +| 2020-05-02 | 0            |
    +| 2020-05-03 | 20           |
    +| 2020-05-04 | -1           |
    ++------------+--------------+
    +
    +在 2020-05-01, 卖了 10 个苹果 和 8 个桔子 (差异为 10 - 8 = 2).
    +在 2020-05-02, 卖了 15 个苹果 和 15 个桔子 (差异为 15 - 15 = 0).
    +在 2020-05-03, 卖了 20 个苹果 和 0 个桔子 (差异为 20 - 0 = 20).
    +在 2020-05-04, 卖了 15 个苹果 和 16 个桔子 (差异为 15 - 16 = -1).
    +
    + + +## 解法 + + + +`CASE WHEN` + `GROUP BY`。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + sale_date AS SALE_DATE, + sum( + CASE WHEN fruit = 'oranges' THEN -sold_num ELSE sold_num END + ) AS DIFF +FROM + Sales +GROUP BY sale_date +ORDER BY sale_date; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1446.leetcode1446 Consecutive Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1446.leetcode1446 Consecutive Characters-zh.md" new file mode 100644 index 00000000..b017cbe2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1446.leetcode1446 Consecutive Characters-zh.md" @@ -0,0 +1,85 @@ +# [1446. 连续字符](https://leetcode-cn.com/problems/consecutive-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1446.Consecutive%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。

    + +

    请你返回字符串的能量。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "leetcode"
    +输出:2
    +解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。
    +
    + +

    示例 2:

    + +
    输入:s = "abbcccddddeeeeedcba"
    +输出:5
    +解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
    +
    + +

    示例 3:

    + +
    输入:s = "triplepillooooow"
    +输出:5
    +
    + +

    示例 4:

    + +
    输入:s = "hooraaaaaaaaaaay"
    +输出:11
    +
    + +

    示例 5:

    + +
    输入:s = "tourist"
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1447.leetcode1447 Simplified Fractions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1447.leetcode1447 Simplified Fractions-zh.md" new file mode 100644 index 00000000..d9e65f38 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1447.leetcode1447 Simplified Fractions-zh.md" @@ -0,0 +1,74 @@ +# [1447. 最简分数](https://leetcode-cn.com/problems/simplified-fractions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1447.Simplified%20Fractions/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n ,请你返回所有 0 到 1 之间(不包括 0 和 1)满足分母小于等于  n 的 最简 分数 。分数可以以 任意 顺序返回。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 2
    +输出:["1/2"]
    +解释:"1/2" 是唯一一个分母小于等于 2 的最简分数。
    + +

    示例 2:

    + +
    输入:n = 3
    +输出:["1/2","1/3","2/3"]
    +
    + +

    示例 3:

    + +
    输入:n = 4
    +输出:["1/2","1/3","1/4","2/3","3/4"]
    +解释:"2/4" 不是最简分数,因为它可以化简为 "1/2" 。
    + +

    示例 4:

    + +
    输入:n = 1
    +输出:[]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1448.leetcode1448 Count Good Nodes in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1448.leetcode1448 Count Good Nodes in Binary Tree-zh.md" new file mode 100644 index 00000000..cfe65b35 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1448.leetcode1448 Count Good Nodes in Binary Tree-zh.md" @@ -0,0 +1,79 @@ +# [1448. 统计二叉树中好节点的数目](https://leetcode-cn.com/problems/count-good-nodes-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1448.Count%20Good%20Nodes%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。

    + +

    「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [3,1,4,3,null,1,5]
    +输出:4
    +解释:图中蓝色节点为好节点。
    +根节点 (3) 永远是个好节点。
    +节点 4 -> (3,4) 是路径中的最大值。
    +节点 5 -> (3,4,5) 是路径中的最大值。
    +节点 3 -> (3,1,3) 是路径中的最大值。
    + +

    示例 2:

    + +

    + +
    输入:root = [3,3,null,4,2]
    +输出:3
    +解释:节点 2 -> (3, 3, 2) 不是好节点,因为 "3" 比它大。
    + +

    示例 3:

    + +
    输入:root = [1]
    +输出:1
    +解释:根节点是好节点。
    + +

     

    + +

    提示:

    + +
      +
    • 二叉树中节点数目范围是 [1, 10^5] 。
    • +
    • 每个节点权值的范围是 [-10^4, 10^4] 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1449.leetcode1449 Form Largest Integer With Digits That Add up to Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1449.leetcode1449 Form Largest Integer With Digits That Add up to Target-zh.md" new file mode 100644 index 00000000..698f6255 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1449.leetcode1449 Form Largest Integer With Digits That Add up to Target-zh.md" @@ -0,0 +1,103 @@ +# [1449. 数位成本和为目标值的最大数字](https://leetcode-cn.com/problems/form-largest-integer-with-digits-that-add-up-to-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1449.Form%20Largest%20Integer%20With%20Digits%20That%20Add%20up%20to%20Target/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 cost 和一个整数 target 。请你返回满足如下规则可以得到的 最大 整数:

    + +
      +
    • 给当前结果添加一个数位(i + 1)的成本为 cost[i] (cost 数组下标从 0 开始)。
    • +
    • 总成本必须恰好等于 target 。
    • +
    • 添加的数位中没有数字 0 。
    • +
    + +

    由于答案可能会很大,请你以字符串形式返回。

    + +

    如果按照上述要求无法得到任何整数,请你返回 "0" 。

    + +

     

    + +

    示例 1:

    + +
    +输入:cost = [4,3,2,5,6,7,2,5,5], target = 9
    +输出:"7772"
    +解释:添加数位 '7' 的成本为 2 ,添加数位 '2' 的成本为 3 。所以 "7772" 的代价为 2*3+ 3*1 = 9 。 "977" 也是满足要求的数字,但 "7772" 是较大的数字。
    + 数字     成本
    +  1  ->   4
    +  2  ->   3
    +  3  ->   2
    +  4  ->   5
    +  5  ->   6
    +  6  ->   7
    +  7  ->   2
    +  8  ->   5
    +  9  ->   5
    +
    + +

    示例 2:

    + +
    +输入:cost = [7,6,5,5,5,6,8,7,8], target = 12
    +输出:"85"
    +解释:添加数位 '8' 的成本是 7 ,添加数位 '5' 的成本是 5 。"85" 的成本为 7 + 5 = 12 。
    +
    + +

    示例 3:

    + +
    +输入:cost = [2,4,6,2,4,6,4,4,4], target = 5
    +输出:"0"
    +解释:总成本是 target 的条件下,无法生成任何整数。
    +
    + +

    示例 4:

    + +
    +输入:cost = [6,10,15,40,40,40,40,40,40], target = 47
    +输出:"32211"
    +
    + +

     

    + +

    提示:

    + +
      +
    • cost.length == 9
    • +
    • 1 <= cost[i] <= 5000
    • +
    • 1 <= target <= 5000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1450.leetcode1450 Number of Students Doing Homework at a Given Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1450.leetcode1450 Number of Students Doing Homework at a Given Time-zh.md" new file mode 100644 index 00000000..22d53754 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1450.leetcode1450 Number of Students Doing Homework at a Given Time-zh.md" @@ -0,0 +1,92 @@ +# [1450. 在既定时间做作业的学生人数](https://leetcode-cn.com/problems/number-of-students-doing-homework-at-a-given-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1450.Number%20of%20Students%20Doing%20Homework%20at%20a%20Given%20Time/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 startTime(开始时间)和 endTime(结束时间),并指定一个整数 queryTime 作为查询时间。

    + +

    已知,第 i 名学生在 startTime[i] 时开始写作业并于 endTime[i] 时完成作业。

    + +

    请返回在查询时间 queryTime 时正在做作业的学生人数。形式上,返回能够使 queryTime 处于区间 [startTime[i], endTime[i]](含)的学生人数。

    + +

     

    + +

    示例 1:

    + +
    输入:startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
    +输出:1
    +解释:一共有 3 名学生。
    +第一名学生在时间 1 开始写作业,并于时间 3 完成作业,在时间 4 没有处于做作业的状态。
    +第二名学生在时间 2 开始写作业,并于时间 2 完成作业,在时间 4 没有处于做作业的状态。
    +第三名学生在时间 3 开始写作业,预计于时间 7 完成作业,这是是唯一一名在时间 4 时正在做作业的学生。
    +
    + +

    示例 2:

    + +
    输入:startTime = [4], endTime = [4], queryTime = 4
    +输出:1
    +解释:在查询时间只有一名学生在做作业。
    +
    + +

    示例 3:

    + +
    输入:startTime = [4], endTime = [4], queryTime = 5
    +输出:0
    +
    + +

    示例 4:

    + +
    输入:startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
    +输出:0
    +
    + +

    示例 5:

    + +
    输入:startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • startTime.length == endTime.length
    • +
    • 1 <= startTime.length <= 100
    • +
    • 1 <= startTime[i] <= endTime[i] <= 1000
    • +
    • 1 <= queryTime <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1451.leetcode1451 Rearrange Words in a Sentence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1451.leetcode1451 Rearrange Words in a Sentence-zh.md" new file mode 100644 index 00000000..29af0724 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1451.leetcode1451 Rearrange Words in a Sentence-zh.md" @@ -0,0 +1,86 @@ +# [1451. 重新排列句子中的单词](https://leetcode-cn.com/problems/rearrange-words-in-a-sentence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1451.Rearrange%20Words%20in%20a%20Sentence/README_EN.md) + +## 题目描述 + + + +

    「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text :

    + +
      +
    • 句子的首字母大写
    • +
    • text 中的每个单词都用单个空格分隔。
    • +
    + +

    请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序。

    + +

    请同样按上述格式返回新的句子。

    + +

     

    + +

    示例 1:

    + +
    输入:text = "Leetcode is cool"
    +输出:"Is cool leetcode"
    +解释:句子中共有 3 个单词,长度为 8 的 "Leetcode" ,长度为 2 的 "is" 以及长度为 4 的 "cool" 。
    +输出需要按单词的长度升序排列,新句子中的第一个单词首字母需要大写。
    +
    + +

    示例 2:

    + +
    输入:text = "Keep calm and code on"
    +输出:"On and keep calm code"
    +解释:输出的排序情况如下:
    +"On" 2 个字母。
    +"and" 3 个字母。
    +"keep" 4 个字母,因为存在长度相同的其他单词,所以它们之间需要保留在原句子中的相对顺序。
    +"calm" 4 个字母。
    +"code" 4 个字母。
    +
    + +

    示例 3:

    + +
    输入:text = "To be or not to be"
    +输出:"To be or to be not"
    +
    + +

     

    + +

    提示:

    + +
      +
    • text 以大写字母开头,然后包含若干小写字母以及单词间的单个空格。
    • +
    • 1 <= text.length <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1452.leetcode1452 People Whose List of Favorite Companies Is Not a Subset of Another List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1452.leetcode1452 People Whose List of Favorite Companies Is Not a Subset of Another List-zh.md" new file mode 100644 index 00000000..7b18d659 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1452.leetcode1452 People Whose List of Favorite Companies Is Not a Subset of Another List-zh.md" @@ -0,0 +1,80 @@ +# [1452. 收藏清单](https://leetcode-cn.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1452.People%20Whose%20List%20of%20Favorite%20Companies%20Is%20Not%20a%20Subset%20of%20Another%20List/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 favoriteCompanies ,其中 favoriteCompanies[i] 是第 i 名用户收藏的公司清单(下标从 0 开始)。

    + +

    请找出不是其他任何人收藏的公司清单的子集的收藏清单,并返回该清单下标下标需要按升序排列

    + +

     

    + +

    示例 1:

    + +
    输入:favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
    +输出:[0,1,4] 
    +解释:
    +favoriteCompanies[2]=["google","facebook"] 是 favoriteCompanies[0]=["leetcode","google","facebook"] 的子集。
    +favoriteCompanies[3]=["google"] 是 favoriteCompanies[0]=["leetcode","google","facebook"] 和 favoriteCompanies[1]=["google","microsoft"] 的子集。
    +其余的收藏清单均不是其他任何人收藏的公司清单的子集,因此,答案为 [0,1,4] 。
    +
    + +

    示例 2:

    + +
    输入:favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
    +输出:[0,1] 
    +解释:favoriteCompanies[2]=["facebook","google"] 是 favoriteCompanies[0]=["leetcode","google","facebook"] 的子集,因此,答案为 [0,1] 。
    +
    + +

    示例 3:

    + +
    输入:favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
    +输出:[0,1,2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= favoriteCompanies.length <= 100
    • +
    • 1 <= favoriteCompanies[i].length <= 500
    • +
    • 1 <= favoriteCompanies[i][j].length <= 20
    • +
    • favoriteCompanies[i] 中的所有字符串 各不相同
    • +
    • 用户收藏的公司清单也 各不相同 ,也就是说,即便我们按字母顺序排序每个清单, favoriteCompanies[i] != favoriteCompanies[j] 仍然成立。
    • +
    • 所有字符串仅包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1453.leetcode1453 Maximum Number of Darts Inside of a Circular Dartboard-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1453.leetcode1453 Maximum Number of Darts Inside of a Circular Dartboard-zh.md" new file mode 100644 index 00000000..344ca57f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1453.leetcode1453 Maximum Number of Darts Inside of a Circular Dartboard-zh.md" @@ -0,0 +1,86 @@ +# [1453. 圆形靶内的最大飞镖数量](https://leetcode-cn.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1453.Maximum%20Number%20of%20Darts%20Inside%20of%20a%20Circular%20Dartboard/README_EN.md) + +## 题目描述 + + + +

    墙壁上挂着一个圆形的飞镖靶。现在请你蒙着眼睛向靶上投掷飞镖。

    + +

    投掷到墙上的飞镖用二维平面上的点坐标数组表示。飞镖靶的半径为 r

    + +

    请返回能够落在 任意 半径为 r 的圆形靶内或靶上的最大飞镖数。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
    +输出:4
    +解释:如果圆形的飞镖靶的圆心为 (0,0) ,半径为 2 ,所有的飞镖都落在靶上,此时落在靶上的飞镖数最大,值为 4 。
    +
    + +

    示例 2:

    + +

    + +
    输入:points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
    +输出:5
    +解释:如果圆形的飞镖靶的圆心为 (0,4) ,半径为 5 ,则除了 (7,8) 之外的飞镖都落在靶上,此时落在靶上的飞镖数最大,值为 5 。
    + +

    示例 3:

    + +
    输入:points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= points.length <= 100
    • +
    • points[i].length == 2
    • +
    • -10^4 <= points[i][0], points[i][1] <= 10^4
    • +
    • 1 <= r <= 5000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1454.leetcode1454 Active Users-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1454.leetcode1454 Active Users-zh.md" new file mode 100644 index 00000000..316135d8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1454.leetcode1454 Active Users-zh.md" @@ -0,0 +1,99 @@ +# [1454. 活跃用户](https://leetcode-cn.com/problems/active-users) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1454.Active%20Users/README_EN.md) + +## 题目描述 + + + +

    Accounts:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| name          | varchar |
    ++---------------+---------+
    +id 是该表主键.
    +该表包含账户 id 和账户的用户名.
    +
    + +

     

    + +

    Logins:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| login_date    | date    |
    ++---------------+---------+
    +该表无主键, 可能包含重复项.
    +该表包含登录用户的账户 id 和登录日期. 用户也许一天内登录多次.
    +
    + +

     

    + +

    写一个 SQL 查询,  找到活跃用户的 id 和 name.

    + +

    活跃用户是指那些至少连续 5 天登录账户的用户.

    + +

    返回的结果表按照 id 排序.

    + +

    结果表格式如下例所示:

    + +
    +Accounts 表:
    ++----+----------+
    +| id | name     |
    ++----+----------+
    +| 1  | Winston  |
    +| 7  | Jonathan |
    ++----+----------+
    +
    +Logins 表:
    ++----+------------+
    +| id | login_date |
    ++----+------------+
    +| 7  | 2020-05-30 |
    +| 1  | 2020-05-30 |
    +| 7  | 2020-05-31 |
    +| 7  | 2020-06-01 |
    +| 7  | 2020-06-02 |
    +| 7  | 2020-06-02 |
    +| 7  | 2020-06-03 |
    +| 1  | 2020-06-07 |
    +| 7  | 2020-06-10 |
    ++----+------------+
    +
    +Result 表:
    ++----+----------+
    +| id | name     |
    ++----+----------+
    +| 7  | Jonathan |
    ++----+----------+
    +id = 1 的用户 Winston 仅仅在不同的 2 天内登录了 2 次, 所以, Winston 不是活跃用户.
    +id = 7 的用户 Jonathon 在不同的 6 天内登录了 7 次, , 6 天中有 5 天是连续的, 所以, Jonathan 是活跃用户.
    +
    + +

     

    + +

    进阶问题:
    +如果活跃用户是那些至少连续 n 天登录账户的用户, 你能否写出通用的解决方案?

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1455.leetcode1455 Check If a Word Occurs As a Prefix of Any Word in a Sentence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1455.leetcode1455 Check If a Word Occurs As a Prefix of Any Word in a Sentence-zh.md" new file mode 100644 index 00000000..76ac1225 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1455.leetcode1455 Check If a Word Occurs As a Prefix of Any Word in a Sentence-zh.md" @@ -0,0 +1,121 @@ +# [1455. 检查单词是否为句中其他单词的前缀](https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1455.Check%20If%20a%20Word%20Occurs%20As%20a%20Prefix%20of%20Any%20Word%20in%20a%20Sentence/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 sentence 作为句子并指定检索词为 searchWord ,其中句子由若干用 单个空格 分隔的单词组成。

    + +

    请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。

    + +
      +
    • 如果 searchWord 是某一个单词的前缀,则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)。
    • +
    • 如果 searchWord 是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。
    • +
    • 如果 searchWord 不是任何单词的前缀,则返回 -1
    • +
    + +

    字符串 S前缀S 的任何前导连续子字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:sentence = "i love eating burger", searchWord = "burg"
    +输出:4
    +解释:"burg" 是 "burger" 的前缀,而 "burger" 是句子中第 4 个单词。
    + +

    示例 2:

    + +
    +输入:sentence = "this problem is an easy problem", searchWord = "pro"
    +输出:2
    +解释:"pro" 是 "problem" 的前缀,而 "problem" 是句子中第 2 个也是第 6 个单词,但是应该返回最小下标 2 。
    +
    + +

    示例 3:

    + +
    +输入:sentence = "i am tired", searchWord = "you"
    +输出:-1
    +解释:"you" 不是句子中任何单词的前缀。
    +
    + +

    示例 4:

    + +
    +输入:sentence = "i use triple pillow", searchWord = "pill"
    +输出:4
    +
    + +

    示例 5:

    + +
    +输入:sentence = "hello from the other side", searchWord = "they"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= sentence.length <= 100
    • +
    • 1 <= searchWord.length <= 10
    • +
    • sentence 由小写英文字母和空格组成。
    • +
    • searchWord 由小写英文字母组成。
    • +
    • 前缀就是紧密附着于词根的语素,中间不能插入其它成分,并且它的位置是固定的——-位于词根之前。(引用自 前缀_百度百科
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: + words = sentence.split(' ') + i, n = 0, len(words) + while i < n: + word = words[i] + if word[: len(searchWord)] == searchWord: + return i + 1 + i += 1 + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int isPrefixOfWord(String sentence, String searchWord) { + String[] words = sentence.split(" "); + int i = 0, n = words.length; + for (; i < n; ++i) { + if (words[i].indexOf(searchWord) == 0) { + return i + 1; + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1456.leetcode1456 Maximum Number of Vowels in a Substring of Given Length-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1456.leetcode1456 Maximum Number of Vowels in a Substring of Given Length-zh.md" new file mode 100644 index 00000000..aeb1cf47 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1456.leetcode1456 Maximum Number of Vowels in a Substring of Given Length-zh.md" @@ -0,0 +1,90 @@ +# [1456. 定长子串中元音的最大数目](https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1456.Maximum%20Number%20of%20Vowels%20in%20a%20Substring%20of%20Given%20Length/README_EN.md) + +## 题目描述 + + + +

    给你字符串 s 和整数 k

    + +

    请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。

    + +

    英文中的 元音字母 为(a, e, i, o, u)。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "abciiidef", k = 3
    +输出:3
    +解释:子字符串 "iii" 包含 3 个元音字母。
    +
    + +

    示例 2:

    + +
    输入:s = "aeiou", k = 2
    +输出:2
    +解释:任意长度为 2 的子字符串都包含 2 个元音字母。
    +
    + +

    示例 3:

    + +
    输入:s = "leetcode", k = 3
    +输出:2
    +解释:"lee"、"eet" 和 "ode" 都包含 2 个元音字母。
    +
    + +

    示例 4:

    + +
    输入:s = "rhythms", k = 4
    +输出:0
    +解释:字符串 s 中不含任何元音字母。
    +
    + +

    示例 5:

    + +
    输入:s = "tryhard", k = 4
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s 由小写英文字母组成
    • +
    • 1 <= k <= s.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1457.leetcode1457 Pseudo-Palindromic Paths in a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1457.leetcode1457 Pseudo-Palindromic Paths in a Binary Tree-zh.md" new file mode 100644 index 00000000..70181c4c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1457.leetcode1457 Pseudo-Palindromic Paths in a Binary Tree-zh.md" @@ -0,0 +1,79 @@ +# [1457. 二叉树中的伪回文路径](https://leetcode-cn.com/problems/pseudo-palindromic-paths-in-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1457.Pseudo-Palindromic%20Paths%20in%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一棵二叉树,每个节点的值为 1 到 9 。我们称二叉树中的一条路径是 「伪回文」的,当它满足:路径经过的所有节点值的排列中,存在一个回文序列。

    + +

    请你返回从根到叶子节点的所有路径中 伪回文 路径的数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [2,3,1,3,1,null,1]
    +输出:2 
    +解释:上图为给定的二叉树。总共有 3 条从根到叶子的路径:红色路径 [2,3,3] ,绿色路径 [2,1,1] 和路径 [2,3,1] 。
    +     在这些路径中,只有红色和绿色的路径是伪回文路径,因为红色路径 [2,3,3] 存在回文排列 [3,2,3] ,绿色路径 [2,1,1] 存在回文排列 [1,2,1] 。
    +
    + +

    示例 2:

    + +

    + +
    输入:root = [2,1,1,1,3,null,null,null,null,null,1]
    +输出:1 
    +解释:上图为给定二叉树。总共有 3 条从根到叶子的路径:绿色路径 [2,1,1] ,路径 [2,1,3,1] 和路径 [2,1] 。
    +     这些路径中只有绿色路径是伪回文路径,因为 [2,1,1] 存在回文排列 [1,2,1] 。
    +
    + +

    示例 3:

    + +
    输入:root = [9]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定二叉树的节点数目在 1 到 10^5 之间。
    • +
    • 节点值在 1 到 9 之间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1458.leetcode1458 Max Dot Product of Two Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1458.leetcode1458 Max Dot Product of Two Subsequences-zh.md" new file mode 100644 index 00000000..f2b1545a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1458.leetcode1458 Max Dot Product of Two Subsequences-zh.md" @@ -0,0 +1,91 @@ +# [1458. 两个子序列的最大点积](https://leetcode-cn.com/problems/max-dot-product-of-two-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1458.Max%20Dot%20Product%20of%20Two%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给你两个数组 nums1 和 nums2 。

    + +

    请你返回 nums1nums2 中两个长度相同的 非空 子序列的最大点积。

    + +

    数组的非空子序列是通过删除原数组中某些元素(可能一个也不删除)后剩余数字组成的序列,但不能改变数字间相对顺序。比方说,[2,3,5] 是 [1,2,3,4,5] 的一个子序列而 [1,5,3] 不是。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums1 = [2,1,-2,5], nums2 = [3,0,-6]
    +输出:18
    +解释:从 nums1 中得到子序列 [2,-2] ,从 nums2 中得到子序列 [3,-6] 。
    +它们的点积为 (2*3 + (-2)*(-6)) = 18 。
    + +

    示例 2:

    + +
    +输入:nums1 = [3,-2], nums2 = [2,-6,7]
    +输出:21
    +解释:从 nums1 中得到子序列 [3] ,从 nums2 中得到子序列 [7] 。
    +它们的点积为 (3*7) = 21 。
    + +

    示例 3:

    + +
    +输入:nums1 = [-1,-1], nums2 = [1,1]
    +输出:-1
    +解释:从 nums1 中得到子序列 [-1] ,从 nums2 中得到子序列 [1] 。
    +它们的点积为 -1 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 500
    • +
    • -1000 <= nums1[i], nums2[i] <= 100
    • +
    + +

     

    + +

    点积:

    + +
    +定义 a = [a1a2,…, an] b = [b1b2,…, bn] 的点积为:
    +
    +\mathbf{a}\cdot \mathbf{b} = \sum_{i=1}^n a_ib_i = a_1b_1 + a_2b_2 + \cdots + a_nb_n 
    +
    +这里的 Σ 指示总和符号。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1459.leetcode1459 Rectangles Area-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1459.leetcode1459 Rectangles Area-zh.md" new file mode 100644 index 00000000..b04ea803 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1459.leetcode1459 Rectangles Area-zh.md" @@ -0,0 +1,75 @@ +# [1459. 矩形面积](https://leetcode-cn.com/problems/rectangles-area) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1459.Rectangles%20Area/README_EN.md) + +## 题目描述 + + + +

    表: Points

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| id            | int     |
    +| x_value       | int     |
    +| y_value       | int     |
    ++---------------+---------+
    +id 是该表主键
    +每个点都用二维坐标 (x_value, y_value) 表示
    + +

     

    + +

    写一个 SQL 语句,报告由表中任意两点可以形成的所有 边与坐标轴平行 面积不为零 的矩形。

    + +

    结果表中的每一行包含三列 (p1, p2, area) 如下:

    + +
      +
    • p1 和 p2 是矩形两个对角的 id
    • +
    • 矩形的面积由列 area 表示
    • +
    + +

    请按照面积 area 大小降序排列;如果面积相同的话, 则按照 p1 升序排序;若仍相同,则按 p2 升序排列。

    + +

    查询结果如下例所示:

    + +
    +Points 表:
    ++----------+-------------+-------------+
    +| id       | x_value     | y_value     |
    ++----------+-------------+-------------+
    +| 1        | 2           | 7           |
    +| 2        | 4           | 8           |
    +| 3        | 2           | 10          |
    ++----------+-------------+-------------+
    +
    +Result 表:
    ++----------+-------------+-------------+
    +| p1       | p2          | area        |
    ++----------+-------------+-------------+
    +| 2        | 3           | 4           |
    +| 1        | 2           | 2           |
    ++----------+-------------+-------------+
    +
    +
    +
    +p1 = 2 且 p2 = 3 时, 面积等于 |4-2| * |8-10| = 4
    +p1 = 1 且 p2 = 2 时, 面积等于 ||2-4| * |7-8| = 2 
    +p1 = 1 且 p2 = 3 时, 是不可能为矩形的, 面积等于 0
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1460.leetcode1460 Make Two Arrays Equal by Reversing Sub-arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1460.leetcode1460 Make Two Arrays Equal by Reversing Sub-arrays-zh.md" new file mode 100644 index 00000000..61ca5e8f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1460.leetcode1460 Make Two Arrays Equal by Reversing Sub-arrays-zh.md" @@ -0,0 +1,106 @@ +# [1460. 通过翻转子数组使两个数组相等](https://leetcode-cn.com/problems/make-two-arrays-equal-by-reversing-sub-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1460.Make%20Two%20Arrays%20Equal%20by%20Reversing%20Sub-arrays/README_EN.md) + +## 题目描述 + + + +

    给你两个长度相同的整数数组 target 和 arr 。

    + +

    每一步中,你可以选择 arr 的任意 非空子数组 并将它翻转。你可以执行此过程任意次。

    + +

    如果你能让 arr 变得与 target 相同,返回 True;否则,返回 False 。

    + +

     

    + +

    示例 1:

    + +
    输入:target = [1,2,3,4], arr = [2,4,1,3]
    +输出:true
    +解释:你可以按照如下步骤使 arr 变成 target:
    +1- 翻转子数组 [2,4,1] ,arr 变成 [1,4,2,3]
    +2- 翻转子数组 [4,2] ,arr 变成 [1,2,4,3]
    +3- 翻转子数组 [4,3] ,arr 变成 [1,2,3,4]
    +上述方法并不是唯一的,还存在多种将 arr 变成 target 的方法。
    +
    + +

    示例 2:

    + +
    输入:target = [7], arr = [7]
    +输出:true
    +解释:arr 不需要做任何翻转已经与 target 相等。
    +
    + +

    示例 3:

    + +
    输入:target = [1,12], arr = [12,1]
    +输出:true
    +
    + +

    示例 4:

    + +
    输入:target = [3,7,9], arr = [3,7,11]
    +输出:false
    +解释:arr 没有数字 9 ,所以无论如何也无法变成 target 。
    +
    + +

    示例 5:

    + +
    输入:target = [1,1,1,1,1], arr = [1,1,1,1,1]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • target.length == arr.length
    • +
    • 1 <= target.length <= 1000
    • +
    • 1 <= target[i] <= 1000
    • +
    • 1 <= arr[i] <= 1000
    • +
    + + +## 解法 + + + +只要两数组元素均相同,那么就能通过翻转使得两个数组相等。 + +因此,对两数组进行排序,然后判断两数组是否相同即可。 + + + +### **Python3** + + + +```python +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return sorted(target) == sorted(arr) +``` + +### **Java** + + + +```java +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + Arrays.sort(target); + Arrays.sort(arr); + return Arrays.equals(target, arr); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1461.leetcode1461 Check If a String Contains All Binary Codes of Size K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1461.leetcode1461 Check If a String Contains All Binary Codes of Size K-zh.md" new file mode 100644 index 00000000..71fc38ed --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1461.leetcode1461 Check If a String Contains All Binary Codes of Size K-zh.md" @@ -0,0 +1,115 @@ +# [1461. 检查一个字符串是否包含所有长度为 K 的二进制子串](https://leetcode-cn.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1461.Check%20If%20a%20String%20Contains%20All%20Binary%20Codes%20of%20Size%20K/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 s 和一个整数 k 。

    + +

    如果所有长度为 k 的二进制字符串都是 s 的子串,请返回 True ,否则请返回 False 。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "00110110", k = 2
    +输出:true
    +解释:长度为 2 的二进制串包括 "00","01","10" 和 "11"。它们分别是 s 中下标为 0,1,3,2 开始的长度为 2 的子串。
    +
    + +

    示例 2:

    + +
    输入:s = "00110", k = 2
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:s = "0110", k = 1
    +输出:true
    +解释:长度为 1 的二进制串包括 "0" 和 "1",显然它们都是 s 的子串。
    +
    + +

    示例 4:

    + +
    输入:s = "0110", k = 2
    +输出:false
    +解释:长度为 2 的二进制串 "00" 没有出现在 s 中。
    +
    + +

    示例 5:

    + +
    输入:s = "0000000001011100", k = 4
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 5 * 10^5
    • +
    • s 中只含 0 和 1 。
    • +
    • 1 <= k <= 20
    • +
    + + +## 解法 + + + +遍历字符串 s,用一个 set 存储所有长度为 k 的不同子串。只需要判断子串数能否达到 2k 即可。 + + + +### **Python3** + + + +```python +class Solution: + def hasAllCodes(self, s: str, k: int) -> bool: + counter = 1 << k + exists = set() + for i in range(k, len(s) + 1): + if s[i - k: i] not in exists: + exists.add(s[i - k: i]) + counter -= 1 + if counter == 0: + return True + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean hasAllCodes(String s, int k) { + int counter = 1 << k; + Set exists = new HashSet<>(); + for (int i = k; i <= s.length(); ++i) { + String t = s.substring(i - k, i); + if (!exists.contains(t)) { + exists.add(t); + --counter; + } + if (counter == 0) { + return true; + } + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1462.leetcode1462 Course Schedule IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1462.leetcode1462 Course Schedule IV-zh.md" new file mode 100644 index 00000000..15f0863f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1462.leetcode1462 Course Schedule IV-zh.md" @@ -0,0 +1,103 @@ +# [1462. 课程表 IV](https://leetcode-cn.com/problems/course-schedule-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1462.Course%20Schedule%20IV/README_EN.md) + +## 题目描述 + + + +

    你总共需要上 n 门课,课程编号依次为 0 到 n-1 。

    + +

    有的课会有直接的先修课程,比如如果想上课程 0 ,你必须先上课程 1 ,那么会以 [1,0] 数对的形式给出先修课程数对。

    + +

    给你课程总数 n 和一个直接先修课程数对列表 prerequisite 和一个查询对列表 queries 。

    + +

    对于每个查询对 queries[i] ,请判断 queries[i][0] 是否是 queries[i][1] 的先修课程。

    + +

    请返回一个布尔值列表,列表中每个元素依次分别对应 queries 每个查询对的判断结果。

    + +

    注意:如果课程 a 是课程 b 的先修课程且课程 b 是课程 c 的先修课程,那么课程 a 也是课程 c 的先修课程。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
    +输出:[false,true]
    +解释:课程 0 不是课程 1 的先修课程,但课程 1 是课程 0 的先修课程。
    +
    + +

    示例 2:

    + +
    输入:n = 2, prerequisites = [], queries = [[1,0],[0,1]]
    +输出:[false,false]
    +解释:没有先修课程对,所以每门课程之间是独立的。
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
    +输出:[true,true]
    +
    + +

    示例 4:

    + +
    输入:n = 3, prerequisites = [[1,0],[2,0]], queries = [[0,1],[2,0]]
    +输出:[false,true]
    +
    + +

    示例 5:

    + +
    输入:n = 5, prerequisites = [[0,1],[1,2],[2,3],[3,4]], queries = [[0,4],[4,0],[1,3],[3,0]]
    +输出:[true,false,true,false]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • 0 <= prerequisite.length <= (n * (n - 1) / 2)
    • +
    • 0 <= prerequisite[i][0], prerequisite[i][1] < n
    • +
    • prerequisite[i][0] != prerequisite[i][1]
    • +
    • 先修课程图中没有环。
    • +
    • 先修课程图中没有重复的边。
    • +
    • 1 <= queries.length <= 10^4
    • +
    • queries[i][0] != queries[i][1]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1463.leetcode1463 Cherry Pickup II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1463.leetcode1463 Cherry Pickup II-zh.md" new file mode 100644 index 00000000..e8271039 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1463.leetcode1463 Cherry Pickup II-zh.md" @@ -0,0 +1,101 @@ +# [1463. 摘樱桃 II](https://leetcode-cn.com/problems/cherry-pickup-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1463.Cherry%20Pickup%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个 rows x cols 的矩阵 grid 来表示一块樱桃地。 grid 中每个格子的数字表示你能获得的樱桃数目。

    + +

    你有两个机器人帮你收集樱桃,机器人 1 从左上角格子 (0,0) 出发,机器人 2 从右上角格子 (0, cols-1) 出发。

    + +

    请你按照如下规则,返回两个机器人能收集的最多樱桃数目:

    + +
      +
    • 从格子 (i,j) 出发,机器人可以移动到格子 (i+1, j-1)(i+1, j) 或者 (i+1, j+1) 。
    • +
    • 当一个机器人经过某个格子时,它会把该格子内所有的樱桃都摘走,然后这个位置会变成空格子,即没有樱桃的格子。
    • +
    • 当两个机器人同时到达同一个格子时,它们中只有一个可以摘到樱桃。
    • +
    • 两个机器人在任意时刻都不能移动到 grid 外面。
    • +
    • 两个机器人最后都要到达 grid 最底下一行。
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
    +输出:24
    +解释:机器人 1 和机器人 2 的路径在上图中分别用绿色和蓝色表示。
    +机器人 1 摘的樱桃数目为 (3 + 2 + 5 + 2) = 12 。
    +机器人 2 摘的樱桃数目为 (1 + 5 + 5 + 1) = 12 。
    +樱桃总数为: 12 + 12 = 24 。
    +
    + +

    示例 2:

    + +

    + +
    输入:grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
    +输出:28
    +解释:机器人 1 和机器人 2 的路径在上图中分别用绿色和蓝色表示。
    +机器人 1 摘的樱桃数目为 (1 + 9 + 5 + 2) = 17 。
    +机器人 2 摘的樱桃数目为 (1 + 3 + 4 + 3) = 11 。
    +樱桃总数为: 17 + 11 = 28 。
    +
    + +

    示例 3:

    + +
    输入:grid = [[1,0,0,3],[0,0,0,3],[0,0,3,3],[9,0,3,3]]
    +输出:22
    +
    + +

    示例 4:

    + +
    输入:grid = [[1,1],[1,1]]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • rows == grid.length
    • +
    • cols == grid[i].length
    • +
    • 2 <= rows, cols <= 70
    • +
    • 0 <= grid[i][j] <= 100 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1464.leetcode1464 Maximum Product of Two Elements in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1464.leetcode1464 Maximum Product of Two Elements in an Array-zh.md" new file mode 100644 index 00000000..d134ad4c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1464.leetcode1464 Maximum Product of Two Elements in an Array-zh.md" @@ -0,0 +1,101 @@ +# [1464. 数组中两元素的最大乘积](https://leetcode-cn.com/problems/maximum-product-of-two-elements-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1464.Maximum%20Product%20of%20Two%20Elements%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums,请你选择数组的两个不同下标 ij使 (nums[i]-1)*(nums[j]-1) 取得最大值。

    + +

    请你计算并返回该式的最大值。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [3,4,5,2]
    +输出:12 
    +解释:如果选择下标 i=1 和 j=2(下标从 0 开始),则可以获得最大值,(nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12 。 
    +
    + +

    示例 2:

    + +
    输入:nums = [1,5,4,5]
    +输出:16
    +解释:选择下标 i=1 和 j=3(下标从 0 开始),则可以获得最大值 (5-1)*(5-1) = 16 。
    +
    + +

    示例 3:

    + +
    输入:nums = [3,7]
    +输出:12
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 500
    • +
    • 1 <= nums[i] <= 10^3
    • +
    + + +## 解法 + + + +找出数组中最大的两个元素的下标 i、j,然后计算 `(nums[i]-1)*(nums[j]-1)` 即可。 + + + +### **Python3** + + + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + i = 0 if nums[0] > nums[1] else 1 + j = 1 - i + for k in range(2, len(nums)): + if nums[k] > nums[i]: + j = k + i, j = j, i + elif nums[k] > nums[j]: + j = k + return (nums[i] - 1) * (nums[j] - 1) +``` + +### **Java** + + + +```java +class Solution { + public int maxProduct(int[] nums) { + int i = nums[0] > nums[1] ? 0 : 1; + int j = 1 - i; + for (int k = 2; k < nums.length; ++k) { + if (nums[k] > nums[i]) { + j = k; + int t = i; + i = j; + j = t; + } else if (nums[k] > nums[j]) { + j = k; + } + } + return (nums[i] - 1) * (nums[j] - 1); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1465.leetcode1465 Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1465.leetcode1465 Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts-zh.md" new file mode 100644 index 00000000..705ef183 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1465.leetcode1465 Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts-zh.md" @@ -0,0 +1,81 @@ +# [1465. 切割后面积最大的蛋糕](https://leetcode-cn.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1465.Maximum%20Area%20of%20a%20Piece%20of%20Cake%20After%20Horizontal%20and%20Vertical%20Cuts/README_EN.md) + +## 题目描述 + + + +

    矩形蛋糕的高度为 h 且宽度为 w,给你两个整数数组 horizontalCutsverticalCuts,其中 horizontalCuts[i] 是从矩形蛋糕顶部到第  i 个水平切口的距离,类似地, verticalCuts[j] 是从矩形蛋糕的左侧到第 j 个竖直切口的距离。

    + +

    请你按数组 horizontalCuts verticalCuts 中提供的水平和竖直位置切割后,请你找出 面积最大 的那份蛋糕,并返回其 面积 。由于答案可能是一个很大的数字,因此需要将结果对 10^9 + 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
    +输出:4 
    +解释:上图所示的矩阵蛋糕中,红色线表示水平和竖直方向上的切口。切割蛋糕后,绿色的那份蛋糕面积最大。
    +
    + +

    示例 2:

    + +

    + +
    输入:h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
    +输出:6
    +解释:上图所示的矩阵蛋糕中,红色线表示水平和竖直方向上的切口。切割蛋糕后,绿色和黄色的两份蛋糕面积最大。
    + +

    示例 3:

    + +
    输入:h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= h, w <= 10^9
    • +
    • 1 <= horizontalCuts.length < min(h, 10^5)
    • +
    • 1 <= verticalCuts.length < min(w, 10^5)
    • +
    • 1 <= horizontalCuts[i] < h
    • +
    • 1 <= verticalCuts[i] < w
    • +
    • 题目数据保证 horizontalCuts 中的所有元素各不相同
    • +
    • 题目数据保证 verticalCuts 中的所有元素各不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1466.leetcode1466 Reorder Routes to Make All Paths Lead to the City Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1466.leetcode1466 Reorder Routes to Make All Paths Lead to the City Zero-zh.md" new file mode 100644 index 00000000..2d71650b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1466.leetcode1466 Reorder Routes to Make All Paths Lead to the City Zero-zh.md" @@ -0,0 +1,84 @@ +# [1466. 重新规划路线](https://leetcode-cn.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1466.Reorder%20Routes%20to%20Make%20All%20Paths%20Lead%20to%20the%20City%20Zero/README_EN.md) + +## 题目描述 + + + +

    n 座城市,从 0n-1 编号,其间共有 n-1 条路线。因此,要想在两座不同城市之间旅行只有唯一一条路线可供选择(路线网形成一颗树)。去年,交通运输部决定重新规划路线,以改变交通拥堵的状况。

    + +

    路线用 connections 表示,其中 connections[i] = [a, b] 表示从城市 ab 的一条有向路线。

    + +

    今年,城市 0 将会举办一场大型比赛,很多游客都想前往城市 0 。

    + +

    请你帮助重新规划路线方向,使每个城市都可以访问城市 0 。返回需要变更方向的最小路线数。

    + +

    题目数据 保证 每个城市在重新规划路线方向后都能到达城市 0 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
    +输出:3
    +解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。
    + +

    示例 2:

    + +

    + +
    输入:n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
    +输出:2
    +解释:更改以红色显示的路线的方向,使每个城市都可以到达城市 0 。
    + +

    示例 3:

    + +
    输入:n = 3, connections = [[1,0],[2,0]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 5 * 10^4
    • +
    • connections.length == n-1
    • +
    • connections[i].length == 2
    • +
    • 0 <= connections[i][0], connections[i][1] <= n-1
    • +
    • connections[i][0] != connections[i][1]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1467.leetcode1467 Probability of a Two Boxes Having The Same Number of Distinct Balls-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1467.leetcode1467 Probability of a Two Boxes Having The Same Number of Distinct Balls-zh.md" new file mode 100644 index 00000000..7eef067c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1467.leetcode1467 Probability of a Two Boxes Having The Same Number of Distinct Balls-zh.md" @@ -0,0 +1,103 @@ +# [1467. 两个盒子中球的颜色数相同的概率](https://leetcode-cn.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1467.Probability%20of%20a%20Two%20Boxes%20Having%20The%20Same%20Number%20of%20Distinct%20Balls/README_EN.md) + +## 题目描述 + + + +

    桌面上有 2n 个颜色不完全相同的球,球上的颜色共有 k 种。给你一个大小为 k 的整数数组 balls ,其中 balls[i] 是颜色为 i 的球的数量。

    + +

    所有的球都已经 随机打乱顺序 ,前 n 个球放入第一个盒子,后 n 个球放入另一个盒子(请认真阅读示例 2 的解释部分)。

    + +

    注意:这两个盒子是不同的。例如,两个球颜色分别为 ab,盒子分别为 [](),那么 [a] (b)[b] (a) 这两种分配方式是不同的(请认真阅读示例 1 的解释部分)。

    + +

    请计算「两个盒子中球的颜色数相同」的情况的概率。

    + +

     

    + +

    示例 1:

    + +
    输入:balls = [1,1]
    +输出:1.00000
    +解释:球平均分配的方式只有两种:
    +- 颜色为 1 的球放入第一个盒子,颜色为 2 的球放入第二个盒子
    +- 颜色为 2 的球放入第一个盒子,颜色为 1 的球放入第二个盒子
    +这两种分配,两个盒子中球的颜色数都相同。所以概率为 2/2 = 1 。
    +
    + +

    示例 2:

    + +
    输入:balls = [2,1,1]
    +输出:0.66667
    +解释:球的列表为 [1, 1, 2, 3]
    +随机打乱,得到 12 种等概率的不同打乱方案,每种方案概率为 1/12 :
    +[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
    +然后,我们将前两个球放入第一个盒子,后两个球放入第二个盒子。
    +这 12 种可能的随机打乱方式中的 8 种满足「两个盒子中球的颜色数相同」。
    +概率 = 8/12 = 0.66667
    +
    + +

    示例 3:

    + +
    输入:balls = [1,2,1,2]
    +输出:0.60000
    +解释:球的列表为 [1, 2, 2, 3, 4, 4]。要想显示所有 180 种随机打乱方案是很难的,但只检查「两个盒子中球的颜色数相同」的 108 种情况是比较容易的。
    +概率 = 108 / 180 = 0.6 。
    +
    + +

    示例 4:

    + +
    输入:balls = [3,2,1]
    +输出:0.30000
    +解释:球的列表为 [1, 1, 1, 2, 2, 3]。要想显示所有 60 种随机打乱方案是很难的,但只检查「两个盒子中球的颜色数相同」的 18 种情况是比较容易的。
    +概率 = 18 / 60 = 0.3 。
    +
    + +

    示例 5:

    + +
    输入:balls = [6,6,6,6,6,6]
    +输出:0.90327
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= balls.length <= 8
    • +
    • 1 <= balls[i] <= 6
    • +
    • sum(balls) 是偶数
    • +
    • 答案与真实值误差在 10^-5 以内,则被视为正确答案
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1468.leetcode1468 Calculate Salaries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1468.leetcode1468 Calculate Salaries-zh.md" new file mode 100644 index 00000000..92e2e821 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1468.leetcode1468 Calculate Salaries-zh.md" @@ -0,0 +1,94 @@ +# [1468. 计算税后工资](https://leetcode-cn.com/problems/calculate-salaries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1468.Calculate%20Salaries/README_EN.md) + +## 题目描述 + + + +

    Salaries 表:

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| company_id    | int     |
    +| employee_id   | int     |
    +| employee_name | varchar |
    +| salary        | int     |
    ++---------------+---------+
    +(company_id, employee_id) 是这个表的主键
    +这个表包括员工的company id, id, name 和 salary 
    +
    + +

     

    + +

    写一条查询 SQL 来查找每个员工的税后工资

    + +

    每个公司的税率计算依照以下规则

    + +
      +
    • 如果这个公司员工最高工资不到 1000 ,税率为 0%
    • +
    • 如果这个公司员工最高工资在 1000 到 10000 之间,税率为 24%
    • +
    • 如果这个公司员工最高工资大于 10000 ,税率为 49%
    • +
    + +

    按任意顺序返回结果,税后工资结果取整

    + +

     

    + +

    结果表格式如下例所示:

    + +
    +Salaries 表:
    ++------------+-------------+---------------+--------+
    +| company_id | employee_id | employee_name | salary |
    ++------------+-------------+---------------+--------+
    +| 1          | 1           | Tony          | 2000   |
    +| 1          | 2           | Pronub        | 21300  |
    +| 1          | 3           | Tyrrox        | 10800  |
    +| 2          | 1           | Pam           | 300    |
    +| 2          | 7           | Bassem        | 450    |
    +| 2          | 9           | Hermione      | 700    |
    +| 3          | 7           | Bocaben       | 100    |
    +| 3          | 2           | Ognjen        | 2200   |
    +| 3          | 13          | Nyancat       | 3300   |
    +| 3          | 15          | Morninngcat   | 7777   |
    ++------------+-------------+---------------+--------+
    +
    +Result 表:
    ++------------+-------------+---------------+--------+
    +| company_id | employee_id | employee_name | salary |
    ++------------+-------------+---------------+--------+
    +| 1          | 1           | Tony          | 1020   |
    +| 1          | 2           | Pronub        | 10863  |
    +| 1          | 3           | Tyrrox        | 5508   |
    +| 2          | 1           | Pam           | 300    |
    +| 2          | 7           | Bassem        | 450    |
    +| 2          | 9           | Hermione      | 700    |
    +| 3          | 7           | Bocaben       | 76     |
    +| 3          | 2           | Ognjen        | 1672   |
    +| 3          | 13          | Nyancat       | 2508   |
    +| 3          | 15          | Morninngcat   | 5911   |
    ++------------+-------------+---------------+--------+
    +对于公司 1 ,最高工资是 21300 ,其每个员工的税率为 49%
    +对于公司 2 ,最高工资是 700 ,其每个员工税率为 0%
    +对于公司 3 ,最高工资是 7777 ,其每个员工税率是 24%
    +税后工资计算 = 工资 - ( 税率 / 100)*工资
    +对于上述案例,Morninngcat 的税后工资 = 7777 - 7777 * ( 24 / 100) = 7777 - 1866.48 = 5910.52 ,取整为 5911
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1469.leetcode1469 Find All The Lonely Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1469.leetcode1469 Find All The Lonely Nodes-zh.md" new file mode 100644 index 00000000..a7d4066b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1469.leetcode1469 Find All The Lonely Nodes-zh.md" @@ -0,0 +1,156 @@ +# [1469. 寻找所有的独生节点](https://leetcode-cn.com/problems/find-all-the-lonely-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1469.Find%20All%20The%20Lonely%20Nodes/README_EN.md) + +## 题目描述 + + + +

    二叉树中,如果一个节点是其父节点的唯一子节点,则称这样的节点为 “独生节点” 。二叉树的根节点不会是独生节点,因为它没有父节点。

    + +

    给定一棵二叉树的根节点 root ,返回树中 所有的独生节点的值所构成的数组 。数组的顺序 不限

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,2,3,null,4]
    +输出:[4]
    +解释:浅蓝色的节点是唯一的独生节点。
    +节点 1 是根节点,不是独生的。
    +节点 2 和 3 有共同的父节点,所以它们都不是独生的。
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [7,1,4,6,null,5,3,null,null,null,null,null,2]
    +输出:[6,2]
    +输出:浅蓝色的节点是独生节点。
    +请谨记,顺序是不限的。 [2,6] 也是一种可接受的答案。
    +
    + +

    示例 3:

    + +

    + +
    +输入:root = [11,99,88,77,null,null,66,55,null,null,44,33,null,null,22]
    +输出:[77,55,33,66,44,22]
    +解释:节点 99 和 88 有共同的父节点,节点 11 是根节点。
    +其他所有节点都是独生节点。
    + +

    示例 4:

    + +
    +输入:root = [197]
    +输出:[]
    +
    + +

    示例 5:

    + +
    +输入:root = [31,null,78,null,28]
    +输出:[78,28]
    +
    + +

     

    + +

    提示:

    + +
      +
    •  tree 中节点个数的取值范围是 [1, 1000]
    • +
    • 每个节点的值的取值范围是 [1, 10^6]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def getLonelyNodes(self, root: TreeNode) -> List[int]: + def traverse(root): + if root is None: + return + if root.left is None and root.right is not None: + self.res.append(root.right.val) + if root.left is not None and root.right is None: + self.res.append(root.left.val) + traverse(root.left) + traverse(root.right) + self.res = [] + traverse(root) + return self.res +``` + +### **Java** + + + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List res; + + public List getLonelyNodes(TreeNode root) { + res = new ArrayList<>(); + traverse(root); + return res; + } + + private void traverse(TreeNode root) { + if (root == null) { + return; + } + if (root.left == null && root.right != null) { + res.add(root.right.val); + } + if (root.left != null && root.right == null) { + res.add(root.left.val); + } + traverse(root.left); + traverse(root.right); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1470.leetcode1470 Shuffle the Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1470.leetcode1470 Shuffle the Array-zh.md" new file mode 100644 index 00000000..26cd2bab --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1470.leetcode1470 Shuffle the Array-zh.md" @@ -0,0 +1,73 @@ +# [1470. 重新排列数组](https://leetcode-cn.com/problems/shuffle-the-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1470.Shuffle%20the%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,...,xn,y1,y2,...,yn] 的格式排列。

    + +

    请你将数组按 [x1,y1,x2,y2,...,xn,yn] 格式重新排列,返回重排后的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [2,5,1,3,4,7], n = 3
    +输出:[2,3,5,4,1,7] 
    +解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7]
    +
    + +

    示例 2:

    + +
    输入:nums = [1,2,3,4,4,3,2,1], n = 4
    +输出:[1,4,2,3,3,2,4,1]
    +
    + +

    示例 3:

    + +
    输入:nums = [1,1,2,2], n = 2
    +输出:[1,2,1,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 500
    • +
    • nums.length == 2n
    • +
    • 1 <= nums[i] <= 10^3
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1471.leetcode1471 The k Strongest Values in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1471.leetcode1471 The k Strongest Values in an Array-zh.md" new file mode 100644 index 00000000..6a352a7d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1471.leetcode1471 The k Strongest Values in an Array-zh.md" @@ -0,0 +1,102 @@ +# [1471. 数组中的 k 个最强值](https://leetcode-cn.com/problems/the-k-strongest-values-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1471.The%20k%20Strongest%20Values%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数 k

    + +

    m 为数组的中位数,只要满足下述两个前提之一,就可以判定 arr[i] 的值比 arr[j] 的值更强:

    + +
      +
    •  |arr[i] - m| > |arr[j] - m|
    • +
    •  |arr[i] - m| == |arr[j] - m|,且 arr[i] > arr[j]
    • +
    + +

    请返回由数组中最强的 k 个值组成的列表。答案可以以 任意顺序 返回。

    + +

    中位数 是一个有序整数列表中处于中间位置的值。形式上,如果列表的长度为 n ,那么中位数就是该有序列表(下标从 0 开始)中位于 ((n - 1) / 2) 的元素。

    + +
      +
    • 例如 arr = [6, -3, 7, 2, 11]n = 5:数组排序后得到 arr = [-3, 2, 6, 7, 11] ,数组的中间位置为 m = ((5 - 1) / 2) = 2 ,中位数 arr[m] 的值为 6
    • +
    • 例如 arr = [-7, 22, 17, 3]n = 4:数组排序后得到 arr = [-7, 3, 17, 22] ,数组的中间位置为 m = ((4 - 1) / 2) = 1 ,中位数 arr[m] 的值为 3
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2,3,4,5], k = 2
    +输出:[5,1]
    +解释:中位数为 3,按从强到弱顺序排序后,数组变为 [5,1,4,2,3]。最强的两个元素是 [5, 1]。[1, 5] 也是正确答案。
    +注意,尽管 |5 - 3| == |1 - 3| ,但是 5 比 1 更强,因为 5 > 1 。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,1,3,5,5], k = 2
    +输出:[5,5]
    +解释:中位数为 3, 按从强到弱顺序排序后,数组变为 [5,5,1,1,3]。最强的两个元素是 [5, 5]。
    +
    + +

    示例 3:

    + +
    输入:arr = [6,7,11,7,6,8], k = 5
    +输出:[11,8,6,6,7]
    +解释:中位数为 7, 按从强到弱顺序排序后,数组变为 [11,8,6,6,7,7]。
    +[11,8,6,6,7] 的任何排列都是正确答案。
    + +

    示例 4:

    + +
    输入:arr = [6,-3,7,2,11], k = 3
    +输出:[-3,11,2]
    +
    + +

    示例 5:

    + +
    输入:arr = [-7,22,17,3], k = 2
    +输出:[22,17]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • -10^5 <= arr[i] <= 10^5
    • +
    • 1 <= k <= arr.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1472.leetcode1472 Design Browser History-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1472.leetcode1472 Design Browser History-zh.md" new file mode 100644 index 00000000..3b36da7e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1472.leetcode1472 Design Browser History-zh.md" @@ -0,0 +1,238 @@ +# [1472. 设计浏览器历史记录](https://leetcode-cn.com/problems/design-browser-history) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1472.Design%20Browser%20History/README_EN.md) + +## 题目描述 + + + +

    你有一个只支持单个标签页的 浏览器 ,最开始你浏览的网页是 homepage ,你可以访问其他的网站 url ,也可以在浏览历史中后退 steps 步或前进 steps 步。

    + +

    请你实现 BrowserHistory 类:

    + +
      +
    • BrowserHistory(string homepage) ,用 homepage 初始化浏览器类。
    • +
    • void visit(string url) 从当前页跳转访问 url 对应的页面  。执行此操作会把浏览历史前进的记录全部删除。
    • +
    • string back(int steps) 在浏览历史中后退 steps 步。如果你只能在浏览历史中后退至多 x 步且 steps > x ,那么你只后退 x 步。请返回后退 至多 steps 步以后的 url 。
    • +
    • string forward(int steps) 在浏览历史中前进 steps 步。如果你只能在浏览历史中前进至多 x 步且 steps > x ,那么你只前进 x 步。请返回前进 至多 steps步以后的 url 。
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
    +[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
    +输出:
    +[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
    +
    +解释:
    +BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
    +browserHistory.visit("google.com");       // 你原本在浏览 "leetcode.com" 。访问 "google.com"
    +browserHistory.visit("facebook.com");     // 你原本在浏览 "google.com" 。访问 "facebook.com"
    +browserHistory.visit("youtube.com");      // 你原本在浏览 "facebook.com" 。访问 "youtube.com"
    +browserHistory.back(1);                   // 你原本在浏览 "youtube.com" ,后退到 "facebook.com" 并返回 "facebook.com"
    +browserHistory.back(1);                   // 你原本在浏览 "facebook.com" ,后退到 "google.com" 并返回 "google.com"
    +browserHistory.forward(1);                // 你原本在浏览 "google.com" ,前进到 "facebook.com" 并返回 "facebook.com"
    +browserHistory.visit("linkedin.com");     // 你原本在浏览 "facebook.com" 。 访问 "linkedin.com"
    +browserHistory.forward(2);                // 你原本在浏览 "linkedin.com" ,你无法前进任何步数。
    +browserHistory.back(2);                   // 你原本在浏览 "linkedin.com" ,后退两步依次先到 "facebook.com" ,然后到 "google.com" ,并返回 "google.com"
    +browserHistory.back(7);                   // 你原本在浏览 "google.com", 你只能后退一步到 "leetcode.com" ,并返回 "leetcode.com"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= homepage.length <= 20
    • +
    • 1 <= url.length <= 20
    • +
    • 1 <= steps <= 100
    • +
    • homepage 和 url 都只包含 '.' 或者小写英文字母。
    • +
    • 最多调用 5000 次 visit, back 和 forward 函数。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +列表实现。 + +```python +class BrowserHistory: + + def __init__(self, homepage: str): + self.urls = [] + self.cur = -1 + self.tail = -1 + self.visit(homepage) + + def visit(self, url: str) -> None: + self.cur += 1 + if self.cur < len(self.urls): + self.urls[self.cur] = url + else: + self.urls.append(url) + self.tail = self.cur + + def back(self, steps: int) -> str: + self.cur = max(0, self.cur -steps) + return self.urls[self.cur] + + def forward(self, steps: int) -> str: + self.cur = min(self.tail, self.cur + steps) + return self.urls[self.cur] + +# Your BrowserHistory object will be instantiated and called as such: +# obj = BrowserHistory(homepage) +# obj.visit(url) +# param_2 = obj.back(steps) +# param_3 = obj.forward(steps) +``` + +栈实现。 + +```python +class BrowserHistory: + + def __init__(self, homepage: str): + self.s1 = [] + self.s2 = [] + self.cur = homepage + + def visit(self, url: str) -> None: + self.s2.clear() + self.s1.append(self.cur) + self.cur = url + + def back(self, steps: int) -> str: + while steps > 0 and self.s1: + self.s2.append(self.cur) + self.cur = self.s1.pop() + steps -= 1 + return self.cur + + def forward(self, steps: int) -> str: + while steps > 0 and self.s2: + self.s1.append(self.cur) + self.cur = self.s2.pop() + steps -= 1 + return self.cur + + +# Your BrowserHistory object will be instantiated and called as such: +# obj = BrowserHistory(homepage) +# obj.visit(url) +# param_2 = obj.back(steps) +# param_3 = obj.forward(steps) +``` + +### **Java** + + + +列表实现。 + +```java +class BrowserHistory { + private List urls; + private int cur = -1; + private int tail = -1; + + public BrowserHistory(String homepage) { + urls = new ArrayList<>(); + visit(homepage); + } + + public void visit(String url) { + ++cur; + if (cur < urls.size()) { + urls.set(cur, url); + } else { + urls.add(url); + } + tail = cur; + } + + public String back(int steps) { + cur = Math.max(0, cur - steps); + return urls.get(cur); + } + + public String forward(int steps) { + cur = Math.min(tail, cur + steps); + return urls.get(cur); + } +} + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory obj = new BrowserHistory(homepage); + * obj.visit(url); + * String param_2 = obj.back(steps); + * String param_3 = obj.forward(steps); + */ +``` + +栈实现。 + +```java +class BrowserHistory { + private Deque s1; + private Deque s2; + private String cur; + + public BrowserHistory(String homepage) { + s1 = new ArrayDeque<>(); + s2 = new ArrayDeque<>(); + cur = homepage; + } + + public void visit(String url) { + s2.clear(); + s1.push(cur); + cur = url; + } + + public String back(int steps) { + while (steps > 0 && !s1.isEmpty()) { + s2.push(cur); + cur = s1.pop(); + --steps; + } + return cur; + } + + public String forward(int steps) { + while (steps > 0 && !s2.isEmpty()) { + s1.push(cur); + cur = s2.pop(); + --steps; + } + return cur; + } +} + +/** + * Your BrowserHistory object will be instantiated and called as such: + * BrowserHistory obj = new BrowserHistory(homepage); + * obj.visit(url); + * String param_2 = obj.back(steps); + * String param_3 = obj.forward(steps); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1473.leetcode1473 Paint House III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1473.leetcode1473 Paint House III-zh.md" new file mode 100644 index 00000000..33cffc49 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1473.leetcode1473 Paint House III-zh.md" @@ -0,0 +1,98 @@ +# [1473. 粉刷房子 III](https://leetcode-cn.com/problems/paint-house-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1473.Paint%20House%20III/README_EN.md) + +## 题目描述 + + + +

    在一个小城市里,有 m 个房子排成一排,你需要给每个房子涂上 n 种颜色之一(颜色编号为 1n )。有的房子去年夏天已经涂过颜色了,所以这些房子不需要被重新涂色。

    + +

    我们将连续相同颜色尽可能多的房子称为一个街区。(比方说 houses = [1,2,2,3,3,2,1,1] ,它包含 5 个街区  [{1}, {2,2}, {3,3}, {2}, {1,1}] 。)

    + +

    给你一个数组 houses ,一个 m * n 的矩阵 cost 和一个整数 target ,其中:

    + +
      +
    • houses[i]:是第 i 个房子的颜色,0 表示这个房子还没有被涂色。
    • +
    • cost[i][j]:是将第 i 个房子涂成颜色 j+1 的花费。
    • +
    + +

    请你返回房子涂色方案的最小总花费,使得每个房子都被涂色后,恰好组成 target 个街区。如果没有可用的涂色方案,请返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    输入:houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
    +输出:9
    +解释:房子涂色方案为 [1,2,2,1,1]
    +此方案包含 target = 3 个街区,分别是 [{1}, {2,2}, {1,1}]。
    +涂色的总花费为 (1 + 1 + 1 + 1 + 5) = 9。
    +
    + +

    示例 2:

    + +
    输入:houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
    +输出:11
    +解释:有的房子已经被涂色了,在此基础上涂色方案为 [2,2,1,2,2]
    +此方案包含 target = 3 个街区,分别是 [{2,2}, {1}, {2,2}]。
    +给第一个和最后一个房子涂色的花费为 (10 + 1) = 11。
    +
    + +

    示例 3:

    + +
    输入:houses = [0,0,0,0,0], cost = [[1,10],[10,1],[1,10],[10,1],[1,10]], m = 5, n = 2, target = 5
    +输出:5
    +
    + +

    示例 4:

    + +
    输入:houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
    +输出:-1
    +解释:房子已经被涂色并组成了 4 个街区,分别是 [{3},{1},{2},{3}] ,无法形成 target = 3 个街区。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == houses.length == cost.length
    • +
    • n == cost[i].length
    • +
    • 1 <= m <= 100
    • +
    • 1 <= n <= 20
    • +
    • 1 <= target <= m
    • +
    • 0 <= houses[i] <= n
    • +
    • 1 <= cost[i][j] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1474.leetcode1474 Delete N Nodes After M Nodes of a Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1474.leetcode1474 Delete N Nodes After M Nodes of a Linked List-zh.md" new file mode 100644 index 00000000..9ceb904a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1474.leetcode1474 Delete N Nodes After M Nodes of a Linked List-zh.md" @@ -0,0 +1,148 @@ +# [1474. 删除链表 M 个节点之后的 N 个节点](https://leetcode-cn.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1474.Delete%20N%20Nodes%20After%20M%20Nodes%20of%20a%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给定链表 head 和两个整数 m 和 n. 遍历该链表并按照如下方式删除节点:

    + +
      +
    • 开始时以头节点作为当前节点.
    • +
    • 保留以当前节点开始的前 m 个节点.
    • +
    • 删除接下来的 n 个节点.
    • +
    • 重复步骤 2 和 3, 直到到达链表结尾.
    • +
    + +

    在删除了指定结点之后, 返回修改过后的链表的头节点.

    + +

    进阶问题: 你能通过就地修改链表的方式解决这个问题吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3
    +输出: [1,2,6,7,11,12]
    +解析: 保留前(m = 2)个结点,  也就是以黑色节点表示的从链表头结点开始的结点(1 ->2).
    +删除接下来的(n = 3)个结点(3 -> 4 -> 5), 在图中以红色结点表示.
    +继续相同的操作, 直到链表的末尾.
    +返回删除结点之后的链表的头结点.
    + +

    示例 2:

    + +

    + +
    +输入: head = [1,2,3,4,5,6,7,8,9,10,11], m = 1, n = 3
    +输出: [1,5,9]
    +解析: 返回删除结点之后的链表的头结点.
    + +

    示例 3:

    + +
    +输入: head = [1,2,3,4,5,6,7,8,9,10,11], m = 3, n = 1
    +输出: [1,2,3,5,6,7,9,10,11]
    +
    + +

    示例 4:

    + +
    +输入: head = [9,3,7,7,9,10,8,2], m = 1, n = 2
    +输出: [9,7,8]
    +
    + +

     

    + +

    提示:

    + +
      +
    •  1 <= 链表结点数 <= 10^4
    • +
    • [1 <= 链表的每一个结点值 <=10^6]
    • +
    • 1 <= m,n <= 1000
    • +
    + +## 解法 + + + +遍历链表,修改指针指向即可。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode: + pre = head + while pre: + for i in range(m - 1): + if pre: + pre = pre.next + if pre is None: + return head + cur = pre + for i in range(n): + if cur: + cur = cur.next + pre.next = None if cur is None else cur.next + pre = pre.next + return head +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteNodes(ListNode head, int m, int n) { + ListNode pre = head; + while (pre != null) { + for (int i = 0; i < m - 1 && pre != null; ++i) { + pre = pre.next; + } + if (pre == null) { + return head; + } + ListNode cur = pre; + for (int i = 0; i < n && cur != null; ++i) { + cur = cur.next; + } + pre.next = cur == null ? null : cur.next; + pre = pre.next; + } + return head; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1475.leetcode1475 Final Prices With a Special Discount in a Shop-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1475.leetcode1475 Final Prices With a Special Discount in a Shop-zh.md" new file mode 100644 index 00000000..75d8b421 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1475.leetcode1475 Final Prices With a Special Discount in a Shop-zh.md" @@ -0,0 +1,79 @@ +# [1475. 商品折扣后的最终价格](https://leetcode-cn.com/problems/final-prices-with-a-special-discount-in-a-shop) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1475.Final%20Prices%20With%20a%20Special%20Discount%20in%20a%20Shop/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。

    + +

    商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > i 且 prices[j] <= prices[i] 的 最小下标 ,如果没有满足条件的 j ,你将没有任何折扣。

    + +

    请你返回一个数组,数组中第 i 个元素是折扣后你购买商品 i 最终需要支付的价格。

    + +

     

    + +

    示例 1:

    + +
    输入:prices = [8,4,6,2,3]
    +输出:[4,2,4,2,3]
    +解释:
    +商品 0 的价格为 price[0]=8 ,你将得到 prices[1]=4 的折扣,所以最终价格为 8 - 4 = 4 。
    +商品 1 的价格为 price[1]=4 ,你将得到 prices[3]=2 的折扣,所以最终价格为 4 - 2 = 2 。
    +商品 2 的价格为 price[2]=6 ,你将得到 prices[3]=2 的折扣,所以最终价格为 6 - 2 = 4 。
    +商品 3 和 4 都没有折扣。
    +
    + +

    示例 2:

    + +
    输入:prices = [1,2,3,4,5]
    +输出:[1,2,3,4,5]
    +解释:在这个例子中,所有商品都没有折扣。
    +
    + +

    示例 3:

    + +
    输入:prices = [10,1,1,6]
    +输出:[9,0,1,6]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= prices.length <= 500
    • +
    • 1 <= prices[i] <= 10^3
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1476.leetcode1476 Subrectangle Queries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1476.leetcode1476 Subrectangle Queries-zh.md" new file mode 100644 index 00000000..8159f68d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1476.leetcode1476 Subrectangle Queries-zh.md" @@ -0,0 +1,204 @@ +# [1476. 子矩形查询](https://leetcode-cn.com/problems/subrectangle-queries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1476.Subrectangle%20Queries/README_EN.md) + +## 题目描述 + + + +

    请你实现一个类 SubrectangleQueries ,它的构造函数的参数是一个 rows x cols 的矩形(这里用整数矩阵表示),并支持以下两种操作:

    + +

    1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

    + +
      +
    • 用 newValue 更新以 (row1,col1) 为左上角且以 (row2,col2) 为右下角的子矩形。
    • +
    + +

    2. getValue(int row, int col)

    + +
      +
    • 返回矩形中坐标 (row,col) 的当前值。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:
    +["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]
    +[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
    +输出:
    +[null,1,null,5,5,null,10,5]
    +解释:
    +SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);  
    +// 初始的 (4x3) 矩形如下:
    +// 1 2 1
    +// 4 3 4
    +// 3 2 1
    +// 1 1 1
    +subrectangleQueries.getValue(0, 2); // 返回 1
    +subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
    +// 此次更新后矩形变为:
    +// 5 5 5
    +// 5 5 5
    +// 5 5 5
    +// 5 5 5 
    +subrectangleQueries.getValue(0, 2); // 返回 5
    +subrectangleQueries.getValue(3, 1); // 返回 5
    +subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
    +// 此次更新后矩形变为:
    +// 5   5   5
    +// 5   5   5
    +// 5   5   5
    +// 10  10  10 
    +subrectangleQueries.getValue(3, 1); // 返回 10
    +subrectangleQueries.getValue(0, 2); // 返回 5
    +
    + +

    示例 2:

    + +
    输入:
    +["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"]
    +[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]
    +输出:
    +[null,1,null,100,100,null,20]
    +解释:
    +SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);
    +subrectangleQueries.getValue(0, 0); // 返回 1
    +subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);
    +subrectangleQueries.getValue(0, 0); // 返回 100
    +subrectangleQueries.getValue(2, 2); // 返回 100
    +subrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);
    +subrectangleQueries.getValue(2, 2); // 返回 20
    +
    + +

     

    + +

    提示:

    + +
      +
    • 最多有 500 次updateSubrectangle 和 getValue 操作。
    • +
    • 1 <= rows, cols <= 100
    • +
    • rows == rectangle.length
    • +
    • cols == rectangle[i].length
    • +
    • 0 <= row1 <= row2 < rows
    • +
    • 0 <= col1 <= col2 < cols
    • +
    • 1 <= newValue, rectangle[i][j] <= 10^9
    • +
    • 0 <= row < rows
    • +
    • 0 <= col < cols
    • +
    + + +## 解法 + + + +用历史记录列表保存修改历史。 + + + +### **Python3** + + + +```python +class SubrectangleQueries: + + def __init__(self, rectangle: List[List[int]]): + self.rec = rectangle + self.history = [] + + def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: + self.history.append((row1, col1, row2, col2, newValue)) + + def getValue(self, row: int, col: int) -> int: + for row1, col1, row2, col2, newValue in self.history[::-1]: + if row >= row1 and row <= row2 and col >= col1 and col <= col2: + return newValue + return self.rec[row][col] + + +# Your SubrectangleQueries object will be instantiated and called as such: +# obj = SubrectangleQueries(rectangle) +# obj.updateSubrectangle(row1,col1,row2,col2,newValue) +# param_2 = obj.getValue(row,col) +``` + +### **Java** + + + +```java +class SubrectangleQueries { + private int[][] rec; + private List history; + + public SubrectangleQueries(int[][] rectangle) { + rec = rectangle; + history = new ArrayList<>(); + } + + public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) { + history.add(new int[]{row1, col1, row2, col2, newValue}); + } + + public int getValue(int row, int col) { + for (int i = history.size() - 1; i >= 0; --i) { + int[] record = history.get(i); + if (row >= record[0] && row <= record[2] && col >= record[1] && col <= record[3]) { + return record[4]; + } + } + return rec[row][col]; + } +} + +/** + * Your SubrectangleQueries object will be instantiated and called as such: + * SubrectangleQueries obj = new SubrectangleQueries(rectangle); + * obj.updateSubrectangle(row1,col1,row2,col2,newValue); + * int param_2 = obj.getValue(row,col); + */ +``` + +### **TypeScript** + +```ts +class SubrectangleQueries { + grid: number[][]; + history: number[][]; + constructor(rectangle: number[][]) { + this.grid = rectangle; + this.history = []; + } + + updateSubrectangle(row1: number, col1: number, row2: number, col2: number, newValue: number): void { + this.history.push([row1, col1, row2, col2, newValue]); + } + + getValue(row: number, col: number): number { + for (let i = this.history.length - 1; i >= 0; --i) { + let [row1, col1, row2, col2, newValue] = this.history[i]; + if (row >= row1 && row <= row2 && col >= col1 && col <= col2) { + return newValue; + } + } + return this.grid[row][col]; + } +} + +/** + * Your SubrectangleQueries object will be instantiated and called as such: + * var obj = new SubrectangleQueries(rectangle) + * obj.updateSubrectangle(row1,col1,row2,col2,newValue) + * var param_2 = obj.getValue(row,col) + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1477.leetcode1477 Find Two Non-overlapping Sub-arrays Each With Target Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1477.leetcode1477 Find Two Non-overlapping Sub-arrays Each With Target Sum-zh.md" new file mode 100644 index 00000000..c64a98a3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1477.leetcode1477 Find Two Non-overlapping Sub-arrays Each With Target Sum-zh.md" @@ -0,0 +1,91 @@ +# [1477. 找两个和为目标值且不重叠的子数组](https://leetcode-cn.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1477.Find%20Two%20Non-overlapping%20Sub-arrays%20Each%20With%20Target%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数值 target 。

    + +

    请你在 arr 中找 两个互不重叠的子数组 且它们的和都等于 target 。可能会有多种方案,请你返回满足要求的两个子数组长度和的 最小值

    + +

    请返回满足要求的最小长度和,如果无法找到这样的两个子数组,请返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [3,2,2,4,3], target = 3
    +输出:2
    +解释:只有两个子数组和为 3 ([3] 和 [3])。它们的长度和为 2 。
    +
    + +

    示例 2:

    + +
    输入:arr = [7,3,4,7], target = 7
    +输出:2
    +解释:尽管我们有 3 个互不重叠的子数组和为 7 ([7], [3,4] 和 [7]),但我们会选择第一个和第三个子数组,因为它们的长度和 2 是最小值。
    +
    + +

    示例 3:

    + +
    输入:arr = [4,3,2,6,2,3,4], target = 6
    +输出:-1
    +解释:我们只有一个和为 6 的子数组。
    +
    + +

    示例 4:

    + +
    输入:arr = [5,5,4,4,5], target = 3
    +输出:-1
    +解释:我们无法找到和为 3 的子数组。
    +
    + +

    示例 5:

    + +
    输入:arr = [3,1,1,1,5,1,2,1], target = 3
    +输出:3
    +解释:注意子数组 [1,2] 和 [2,1] 不能成为一个方案因为它们重叠了。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 1000
    • +
    • 1 <= target <= 10^8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1478.leetcode1478 Allocate Mailboxes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1478.leetcode1478 Allocate Mailboxes-zh.md" new file mode 100644 index 00000000..4bdc8bec --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1478.leetcode1478 Allocate Mailboxes-zh.md" @@ -0,0 +1,90 @@ +# [1478. 安排邮筒](https://leetcode-cn.com/problems/allocate-mailboxes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1478.Allocate%20Mailboxes/README_EN.md) + +## 题目描述 + + + +

    给你一个房屋数组houses 和一个整数 k ,其中 houses[i] 是第 i 栋房子在一条街上的位置,现需要在这条街上安排 k 个邮筒。

    + +

    请你返回每栋房子与离它最近的邮筒之间的距离的 最小 总和。

    + +

    答案保证在 32 位有符号整数范围以内。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:houses = [1,4,8,10,20], k = 3
    +输出:5
    +解释:将邮筒分别安放在位置 3, 9 和 20 处。
    +每个房子到最近邮筒的距离和为 |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 。
    +
    + +

    示例 2:

    + +

    + +
    输入:houses = [2,3,5,12,18], k = 2
    +输出:9
    +解释:将邮筒分别安放在位置 3 和 14 处。
    +每个房子到最近邮筒距离和为 |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9 。
    +
    + +

    示例 3:

    + +
    输入:houses = [7,4,6,1], k = 1
    +输出:8
    +
    + +

    示例 4:

    + +
    输入:houses = [3,6,14,10], k = 4
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == houses.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= houses[i] <= 10^4
    • +
    • 1 <= k <= n
    • +
    • 数组 houses 中的整数互不相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1479.leetcode1479 Sales by Day of the Week-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1479.leetcode1479 Sales by Day of the Week-zh.md" new file mode 100644 index 00000000..01e2ca2c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1479.leetcode1479 Sales by Day of the Week-zh.md" @@ -0,0 +1,109 @@ +# [1479. 周内每天的销售情况](https://leetcode-cn.com/problems/sales-by-day-of-the-week) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1479.Sales%20by%20Day%20of%20the%20Week/README_EN.md) + +## 题目描述 + + + +

    表:Orders

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| customer_id   | int     |
    +| order_date    | date    | 
    +| item_id       | varchar |
    +| quantity      | int     |
    ++---------------+---------+
    +(order_id, item_id) 是该表主键
    +该表包含了订单信息
    +order_date 是id为 item_id 的商品被id为 customer_id 的消费者订购的日期.
    + +

    表:Items

    + +
    +---------------------+---------+
    +| Column Name         | Type    |
    ++---------------------+---------+
    +| item_id             | varchar |
    +| item_name           | varchar |
    +| item_category       | varchar |
    ++---------------------+---------+
    +item_id 是该表主键
    +item_name 是商品的名字
    +item_category 是商品的类别
    +
    + +

     

    + +

    你是企业主,想要获得分类商品和周内每天的销售报告。

    + +

    写一个SQL语句,报告 周内每天 每个商品类别下订购了多少单位。

    + +

    返回结果表单 按商品类别排序

    + +

    查询结果格式如下例所示:

    + +

     

    + +
    Orders 表:
    ++------------+--------------+-------------+--------------+-------------+
    +| order_id   | customer_id  | order_date  | item_id      | quantity    |
    ++------------+--------------+-------------+--------------+-------------+
    +| 1          | 1            | 2020-06-01  | 1            | 10          |
    +| 2          | 1            | 2020-06-08  | 2            | 10          |
    +| 3          | 2            | 2020-06-02  | 1            | 5           |
    +| 4          | 3            | 2020-06-03  | 3            | 5           |
    +| 5          | 4            | 2020-06-04  | 4            | 1           |
    +| 6          | 4            | 2020-06-05  | 5            | 5           |
    +| 7          | 5            | 2020-06-05  | 1            | 10          |
    +| 8          | 5            | 2020-06-14  | 4            | 5           |
    +| 9          | 5            | 2020-06-21  | 3            | 5           |
    ++------------+--------------+-------------+--------------+-------------+
    +
    +Items 表:
    ++------------+----------------+---------------+
    +| item_id    | item_name      | item_category |
    ++------------+----------------+---------------+
    +| 1          | LC Alg. Book   | Book          |
    +| 2          | LC DB. Book    | Book          |
    +| 3          | LC SmarthPhone | Phone         |
    +| 4          | LC Phone 2020  | Phone         |
    +| 5          | LC SmartGlass  | Glasses       |
    +| 6          | LC T-Shirt XL  | T-Shirt       |
    ++------------+----------------+---------------+
    +
    +Result 表:
    ++------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
    +| Category   | Monday    | Tuesday   | Wednesday | Thursday  | Friday    | Saturday  | Sunday    |
    ++------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
    +| Book       | 20        | 5         | 0         | 0         | 10        | 0         | 0         |
    +| Glasses    | 0         | 0         | 0         | 0         | 5         | 0         | 0         |
    +| Phone      | 0         | 0         | 5         | 1         | 0         | 0         | 10        |
    +| T-Shirt    | 0         | 0         | 0         | 0         | 0         | 0         | 0         |
    ++------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
    +在周一(2020-06-01, 2020-06-08),Book分类(ids: 1, 2)下,总共销售了20个单位(10 + 10)
    +在周二(2020-06-02),Book分类(ids: 1, 2)下,总共销售了5个单位
    +在周三(2020-06-03),Phone分类(ids: 3, 4)下,总共销售了5个单位
    +在周四(2020-06-04),Phone分类(ids: 3, 4)下,总共销售了1个单位
    +在周五(2020-06-05),Book分类(ids: 1, 2)下,总共销售了10个单位,Glasses分类(ids: 5)下,总共销售了5个单位
    +在周六, 没有商品销售
    +在周天(2020-06-14, 2020-06-21),Phone分类(ids: 3, 4)下,总共销售了10个单位(5 + 5)
    +没有销售 T-Shirt 类别的商品
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1480.leetcode1480 Running Sum of 1d Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1480.leetcode1480 Running Sum of 1d Array-zh.md" new file mode 100644 index 00000000..bbd72d15 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1480.leetcode1480 Running Sum of 1d Array-zh.md" @@ -0,0 +1,109 @@ +# [1480. 一维数组的动态和](https://leetcode-cn.com/problems/running-sum-of-1d-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1480.Running%20Sum%20of%201d%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i])

    + +

    请返回 nums 的动态和。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,4]
    +输出:[1,3,6,10]
    +解释:动态和计算过程为 [1, 1+2, 1+2+3, 1+2+3+4] 。
    + +

    示例 2:

    + +
    输入:nums = [1,1,1,1,1]
    +输出:[1,2,3,4,5]
    +解释:动态和计算过程为 [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1] 。
    + +

    示例 3:

    + +
    输入:nums = [3,1,2,10,1]
    +输出:[3,4,6,16,17]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • -10^6 <= nums[i] <= 10^6
    • +
    + + +## 解法 + + + +原地修改数组。 + + + +### **Python3** + + + +```python +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + for i in range(1, len(nums)): + nums[i] += nums[i - 1] + return nums +``` + +### **Java** + + + +```java +class Solution { + public int[] runningSum(int[] nums) { + for (int i = 1; i < nums.length; ++i) { + nums[i] += nums[i - 1]; + } + return nums; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + vector runningSum(vector& nums) { + for (int i = 1; i < nums.size(); ++i) { + nums[i] += nums[i - 1]; + } + return nums; + } +}; +``` + +### **Go** + +```go +func runningSum(nums []int) []int { + for i := 1; i < len(nums); i++ { + nums[i] += nums[i-1] + } + return nums +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1481.leetcode1481 Least Number of Unique Integers after K Removals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1481.leetcode1481 Least Number of Unique Integers after K Removals-zh.md" new file mode 100644 index 00000000..3ab32de5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1481.leetcode1481 Least Number of Unique Integers after K Removals-zh.md" @@ -0,0 +1,68 @@ +# [1481. 不同整数的最少数目](https://leetcode-cn.com/problems/least-number-of-unique-integers-after-k-removals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1481.Least%20Number%20of%20Unique%20Integers%20after%20K%20Removals/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目。

    + +
      +
    + +

     

    + +

    示例 1:

    + +
    输入:arr = [5,5,4], k = 1
    +输出:1
    +解释:移除 1 个 4 ,数组中只剩下 5 一种整数。
    +
    + +

    示例 2:

    + +
    输入:arr = [4,3,1,1,3,3,2], k = 3
    +输出:2
    +解释:先移除 4、2 ,然后再移除两个 1 中的任意 1 个或者三个 3 中的任意 1 个,最后剩下 1 和 3 两种整数。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^9
    • +
    • 0 <= k <= arr.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1482.leetcode1482 Minimum Number of Days to Make m Bouquets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1482.leetcode1482 Minimum Number of Days to Make m Bouquets-zh.md" new file mode 100644 index 00000000..3e9f5125 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1482.leetcode1482 Minimum Number of Days to Make m Bouquets-zh.md" @@ -0,0 +1,254 @@ +# [1482. 制作 m 束花所需的最少天数](https://leetcode-cn.com/problems/minimum-number-of-days-to-make-m-bouquets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1482.Minimum%20Number%20of%20Days%20to%20Make%20m%20Bouquets/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 bloomDay,以及两个整数 mk

    + +

    现需要制作 m 束花。制作花束时,需要使用花园中 相邻的 k 朵花

    + +

    花园中有 n 朵花,第 i 朵花会在 bloomDay[i] 时盛开,恰好 可以用于 一束 花中。

    + +

    请你返回从花园中摘 m 束花需要等待的最少的天数。如果不能摘到 m 束花则返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:bloomDay = [1,10,3,10,2], m = 3, k = 1
    +输出:3
    +解释:让我们一起观察这三天的花开过程,x 表示花开,而 _ 表示花还未开。
    +现在需要制作 3 束花,每束只需要 1 朵。
    +1 天后:[x, _, _, _, _]   // 只能制作 1 束花
    +2 天后:[x, _, _, _, x]   // 只能制作 2 束花
    +3 天后:[x, _, x, _, x]   // 可以制作 3 束花,答案为 3
    +
    + +

    示例 2:

    + +
    输入:bloomDay = [1,10,3,10,2], m = 3, k = 2
    +输出:-1
    +解释:要制作 3 束花,每束需要 2 朵花,也就是一共需要 6 朵花。而花园中只有 5 朵花,无法满足制作要求,返回 -1 。
    +
    + +

    示例 3:

    + +
    输入:bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
    +输出:12
    +解释:要制作 2 束花,每束需要 3 朵。
    +花园在 7 天后和 12 天后的情况如下:
    +7 天后:[x, x, x, x, _, x, x]
    +可以用前 3 朵盛开的花制作第一束花。但不能使用后 3 朵盛开的花,因为它们不相邻。
    +12 天后:[x, x, x, x, x, x, x]
    +显然,我们可以用不同的方式制作两束花。
    +
    + +

    示例 4:

    + +
    输入:bloomDay = [1000000000,1000000000], m = 1, k = 1
    +输出:1000000000
    +解释:需要等 1000000000 天才能采到花来制作花束
    +
    + +

    示例 5:

    + +
    输入:bloomDay = [1,10,2,9,3,8,4,7,5,6], m = 4, k = 2
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • bloomDay.length == n
    • +
    • 1 <= n <= 10^5
    • +
    • 1 <= bloomDay[i] <= 10^9
    • +
    • 1 <= m <= 10^6
    • +
    • 1 <= k <= n
    • +
    + + +## 解法 + + + +利用二分查找快速定位。 + + + +### **Python3** + + + +```python +class Solution: + def minDays(self, bloomDay: List[int], m: int, k: int) -> int: + if m * k > len(bloomDay): + return -1 + + def check(day: int) -> bool: + cnt = cur = 0 + for bd in bloomDay: + cur = cur + 1 if bd <= day else 0 + if cur == k: + cnt += 1 + cur = 0 + return cnt >= m + + left, right = min(bloomDay), max(bloomDay) + while left < right: + mid = (left + right) >> 1 + if check(mid): + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int minDays(int[] bloomDay, int m, int k) { + if (m * k > bloomDay.length) { + return -1; + } + int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; + for (int bd : bloomDay) { + min = Math.min(min, bd); + max = Math.max(max, bd); + } + int left = min, right = max; + while (left < right) { + int mid = (left + right) >>> 1; + if (check(bloomDay, m, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean check(int[] bloomDay, int m, int k, int day) { + int cnt = 0, cur = 0; + for (int bd : bloomDay) { + cur = bd <= day ? cur + 1 : 0; + if (cur == k) { + cnt++; + cur = 0; + } + } + return cnt >= m; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minDays(vector& bloomDay, int m, int k) { + if (m * k > bloomDay.size()) { + return -1; + } + int mi = INT_MIN, mx = INT_MAX; + for (int& bd : bloomDay) { + mi = min(mi, bd); + mx = max(mx, bd); + } + int left = mi, right = mx; + while (left < right) { + int mid = left + right >> 1; + if (check(bloomDay, m, k, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + bool check(vector& bloomDay, int m, int k, int day) { + int cnt = 0, cur = 0; + for (int& bd : bloomDay) { + cur = bd <= day ? cur + 1 : 0; + if (cur == k) { + ++cnt; + cur = 0; + } + } + return cnt >= m; + } +}; +``` + +### **Go** + +```go +func minDays(bloomDay []int, m int, k int) int { + if m*k > len(bloomDay) { + return -1 + } + mi, mx := 0, 1000000000 + for _, bd := range bloomDay { + mi = min(mi, bd) + mx = max(mx, bd) + } + left, right := mi, mx + for left < right { + mid := (left + right) >> 1 + if check(bloomDay, m, k, mid) { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func check(bloomDay []int, m, k, day int) bool { + cnt, cur := 0, 0 + for _, bd := range bloomDay { + if bd <= day { + cur++ + } else { + cur = 0 + } + if cur == k { + cnt++ + cur = 0 + } + } + return cnt >= m +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1483.leetcode1483 Kth Ancestor of a Tree Node-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1483.leetcode1483 Kth Ancestor of a Tree Node-zh.md" new file mode 100644 index 00000000..1f8db391 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1483.leetcode1483 Kth Ancestor of a Tree Node-zh.md" @@ -0,0 +1,77 @@ +# [1483. 树节点的第 K 个祖先](https://leetcode-cn.com/problems/kth-ancestor-of-a-tree-node) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1483.Kth%20Ancestor%20of%20a%20Tree%20Node/README_EN.md) + +## 题目描述 + + + +

    给你一棵树,树上有 n 个节点,按从 0n-1 编号。树以父节点数组的形式给出,其中 parent[i] 是节点 i 的父节点。树的根节点是编号为 0 的节点。

    + +

    请你设计并实现 getKthAncestor(int node, int k) 函数,函数返回节点 node 的第 k 个祖先节点。如果不存在这样的祖先节点,返回 -1

    + +

    树节点的第 k 个祖先节点是从该节点到根节点路径上的第 k 个节点。

    + +

     

    + +

    示例:

    + +

    + +
    输入:
    +["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"]
    +[[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]]
    +
    +输出:
    +[null,1,0,-1]
    +
    +解释:
    +TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
    +
    +treeAncestor.getKthAncestor(3, 1);  // 返回 1 ,它是 3 的父节点
    +treeAncestor.getKthAncestor(5, 2);  // 返回 0 ,它是 5 的祖父节点
    +treeAncestor.getKthAncestor(6, 3);  // 返回 -1 因为不存在满足要求的祖先节点
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= n <= 5*10^4
    • +
    • parent[0] == -1 表示编号为 0 的节点是根节点。
    • +
    • 对于所有的 0 < i < n0 <= parent[i] < n 总成立
    • +
    • 0 <= node < n
    • +
    • 至多查询 5*10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1484.leetcode1484 Group Sold Products By The Date-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1484.leetcode1484 Group Sold Products By The Date-zh.md" new file mode 100644 index 00000000..4bb3b5b3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1484.leetcode1484 Group Sold Products By The Date-zh.md" @@ -0,0 +1,71 @@ +# [1484. 按日期分组销售产品](https://leetcode-cn.com/problems/group-sold-products-by-the-date) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1484.Group%20Sold%20Products%20By%20The%20Date/README_EN.md) + +## 题目描述 + + + +

    表 Activities

    + +
    +-------------+---------+
    +| 列名         | 类型    |
    ++-------------+---------+
    +| sell_date   | date    |
    +| product     | varchar |
    ++-------------+---------+
    +此表没有主键,它可能包含重复项。
    +此表的每一行都包含产品名称和在市场上销售的日期。
    +
    + +

     

    + +

    编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。
    +每个日期的销售产品名称应按词典序排列。
    +返回按 sell_date 排序的结果表。

    + +


    +查询结果格式如下例所示。

    + +
    Activities 表:
    ++------------+-------------+
    +| sell_date  | product     |
    ++------------+-------------+
    +| 2020-05-30 | Headphone   |
    +| 2020-06-01 | Pencil      |
    +| 2020-06-02 | Mask        |
    +| 2020-05-30 | Basketball  |
    +| 2020-06-01 | Bible       |
    +| 2020-06-02 | Mask        |
    +| 2020-05-30 | T-Shirt     |
    ++------------+-------------+
    +
    +Result 表:
    ++------------+----------+------------------------------+
    +| sell_date  | num_sold | products                     |
    ++------------+----------+------------------------------+
    +| 2020-05-30 | 3        | Basketball,Headphone,T-shirt |
    +| 2020-06-01 | 2        | Bible,Pencil                 |
    +| 2020-06-02 | 1        | Mask                         |
    ++------------+----------+------------------------------+
    +对于2020-05-30,出售的物品是 (Headphone, Basketball, T-shirt),按词典序排列,并用逗号 ',' 分隔。
    +对于2020-06-01,出售的物品是 (Pencil, Bible),按词典序排列,并用逗号分隔。
    +对于2020-06-02,出售的物品是 (Mask),只需返回该物品名。
    +
    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1485.leetcode1485 Clone Binary Tree With Random Pointer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1485.leetcode1485 Clone Binary Tree With Random Pointer-zh.md" new file mode 100644 index 00000000..59bb980a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1485.leetcode1485 Clone Binary Tree With Random Pointer-zh.md" @@ -0,0 +1,103 @@ +# [1485. 克隆含随机指针的二叉树](https://leetcode-cn.com/problems/clone-binary-tree-with-random-pointer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1485.Clone%20Binary%20Tree%20With%20Random%20Pointer/README_EN.md) + +## 题目描述 + + + +

    给你一个二叉树,树中每个节点都含有一个附加的随机指针,该指针可以指向树中的任何节点或者指向空(null)。

    + +

    请返回该树的 深拷贝

    + +

    该树的输入/输出形式与普通二叉树相同,每个节点都用 [val, random_index] 表示:

    + +
      +
    • val:表示 Node.val 的整数
    • +
    • random_index:随机指针指向的节点(在输入的树数组中)的下标;如果未指向任何节点,则为 null
    • +
    + +

    该树以 Node 类的形式给出,而你需要以 NodeCopy 类的形式返回克隆得到的树。NodeCopy 类和Node 类定义一致。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:root = [[1,null],null,[4,3],[7,0]]
    +输出:[[1,null],null,[4,3],[7,0]]
    +解释:初始二叉树为 [1,null,4,7] 。
    +节点 1 的随机指针指向 null,所以表示为 [1, null] 。
    +节点 4 的随机指针指向 7,所以表示为 [4, 3] 其中 3 是树数组中节点 7 对应的下标。
    +节点 7 的随机指针指向 1,所以表示为 [7, 0] 其中 0 是树数组中节点 1 对应的下标。
    +
    + +

    示例 2:

    + +

    + +
    输入:root = [[1,4],null,[1,0],null,[1,5],[1,5]]
    +输出:[[1,4],null,[1,0],null,[1,5],[1,5]]
    +解释:节点的随机指针可以指向它自身。
    +
    + +

    示例 3:

    + +

    + +
    输入:root = [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
    +输出:[[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
    +
    + +

    示例 4:

    + +
    输入:root = []
    +输出:[]
    +
    + +

    示例 5:

    + +
    输入:root = [[1,null],null,[2,null],null,[1,null]]
    +输出:[[1,null],null,[2,null],null,[1,null]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • tree 中节点数目范围是 [0, 1000]
    • +
    • 每个节点的值的范围是 [1, 10^6]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1486.leetcode1486 XOR Operation in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1486.leetcode1486 XOR Operation in an Array-zh.md" new file mode 100644 index 00000000..43cb324c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1486.leetcode1486 XOR Operation in an Array-zh.md" @@ -0,0 +1,87 @@ +# [1486. 数组异或操作](https://leetcode-cn.com/problems/xor-operation-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1486.XOR%20Operation%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你两个整数,nstart

    + +

    数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length

    + +

    请返回 nums 中所有元素按位异或(XOR)后得到的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 5, start = 0
    +输出:8
    +解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。
    +     "^" 为按位异或 XOR 运算符。
    +
    + +

    示例 2:

    + +
    输入:n = 4, start = 3
    +输出:8
    +解释:数组 nums 为 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8.
    + +

    示例 3:

    + +
    输入:n = 1, start = 7
    +输出:7
    +
    + +

    示例 4:

    + +
    输入:n = 10, start = 5
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1000
    • +
    • 0 <= start <= 1000
    • +
    • n == nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def xorOperation(self, n: int, start: int) -> int: + res = 0 + for i in range(n): + res ^= (start + (i << 1)) + return res +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1487.leetcode1487 Making File Names Unique-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1487.leetcode1487 Making File Names Unique-zh.md" new file mode 100644 index 00000000..cd403070 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1487.leetcode1487 Making File Names Unique-zh.md" @@ -0,0 +1,98 @@ +# [1487. 保证文件名唯一](https://leetcode-cn.com/problems/making-file-names-unique) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1487.Making%20File%20Names%20Unique/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的字符串数组 names 。你将会在文件系统中创建 n 个文件夹:在第 i 分钟,新建名为 names[i] 的文件夹。

    + +

    由于两个文件 不能 共享相同的文件名,因此如果新建文件夹使用的文件名已经被占用,系统会以 (k) 的形式为新文件夹的文件名添加后缀,其中 k 是能保证文件名唯一的 最小正整数

    + +

    返回长度为 n 的字符串数组,其中 ans[i] 是创建第 i 个文件夹时系统分配给该文件夹的实际名称。

    + +

     

    + +

    示例 1:

    + +
    输入:names = ["pes","fifa","gta","pes(2019)"]
    +输出:["pes","fifa","gta","pes(2019)"]
    +解释:文件系统将会这样创建文件名:
    +"pes" --> 之前未分配,仍为 "pes"
    +"fifa" --> 之前未分配,仍为 "fifa"
    +"gta" --> 之前未分配,仍为 "gta"
    +"pes(2019)" --> 之前未分配,仍为 "pes(2019)"
    +
    + +

    示例 2:

    + +
    输入:names = ["gta","gta(1)","gta","avalon"]
    +输出:["gta","gta(1)","gta(2)","avalon"]
    +解释:文件系统将会这样创建文件名:
    +"gta" --> 之前未分配,仍为 "gta"
    +"gta(1)" --> 之前未分配,仍为 "gta(1)"
    +"gta" --> 文件名被占用,系统为该名称添加后缀 (k),由于 "gta(1)" 也被占用,所以 k = 2 。实际创建的文件名为 "gta(2)" 。
    +"avalon" --> 之前未分配,仍为 "avalon"
    +
    + +

    示例 3:

    + +
    输入:names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]
    +输出:["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]
    +解释:当创建最后一个文件夹时,最小的正有效 k 为 4 ,文件名变为 "onepiece(4)"。
    +
    + +

    示例 4:

    + +
    输入:names = ["wano","wano","wano","wano"]
    +输出:["wano","wano(1)","wano(2)","wano(3)"]
    +解释:每次创建文件夹 "wano" 时,只需增加后缀中 k 的值即可。
    + +

    示例 5:

    + +
    输入:names = ["kaido","kaido(1)","kaido","kaido(1)"]
    +输出:["kaido","kaido(1)","kaido(2)","kaido(1)(1)"]
    +解释:注意,如果含后缀文件名被占用,那么系统也会按规则在名称后添加新的后缀 (k) 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= names.length <= 5 * 10^4
    • +
    • 1 <= names[i].length <= 20
    • +
    • names[i] 由小写英文字母、数字和/或圆括号组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1488.leetcode1488 Avoid Flood in The City-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1488.leetcode1488 Avoid Flood in The City-zh.md" new file mode 100644 index 00000000..60a5958b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1488.leetcode1488 Avoid Flood in The City-zh.md" @@ -0,0 +1,116 @@ +# [1488. 避免洪水泛滥](https://leetcode-cn.com/problems/avoid-flood-in-the-city) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1488.Avoid%20Flood%20in%20The%20City/README_EN.md) + +## 题目描述 + + + +

    你的国家有无数个湖泊,所有湖泊一开始都是空的。当第 n 个湖泊下雨的时候,如果第 n 个湖泊是空的,那么它就会装满水,否则这个湖泊会发生洪水。你的目标是避免任意一个湖泊发生洪水。

    + +

    给你一个整数数组 rains ,其中:

    + +
      +
    • rains[i] > 0 表示第 i 天时,第 rains[i] 个湖泊会下雨。
    • +
    • rains[i] == 0 表示第 i 天没有湖泊会下雨,你可以选择 一个 湖泊并 抽干 这个湖泊的水。
    • +
    + +

    请返回一个数组 ans ,满足:

    + +
      +
    • ans.length == rains.length
    • +
    • 如果 rains[i] > 0 ,那么ans[i] == -1 。
    • +
    • 如果 rains[i] == 0 ,ans[i] 是你第 i 天选择抽干的湖泊。
    • +
    + +

    如果有多种可行解,请返回它们中的 任意一个 。如果没办法阻止洪水,请返回一个 空的数组 。

    + +

    请注意,如果你选择抽干一个装满水的湖泊,它会变成一个空的湖泊。但如果你选择抽干一个空的湖泊,那么将无事发生(详情请看示例 4)。

    + +

     

    + +

    示例 1:

    + +
    输入:rains = [1,2,3,4]
    +输出:[-1,-1,-1,-1]
    +解释:第一天后,装满水的湖泊包括 [1]
    +第二天后,装满水的湖泊包括 [1,2]
    +第三天后,装满水的湖泊包括 [1,2,3]
    +第四天后,装满水的湖泊包括 [1,2,3,4]
    +没有哪一天你可以抽干任何湖泊的水,也没有湖泊会发生洪水。
    +
    + +

    示例 2:

    + +
    输入:rains = [1,2,0,0,2,1]
    +输出:[-1,-1,2,1,-1,-1]
    +解释:第一天后,装满水的湖泊包括 [1]
    +第二天后,装满水的湖泊包括 [1,2]
    +第三天后,我们抽干湖泊 2 。所以剩下装满水的湖泊包括 [1]
    +第四天后,我们抽干湖泊 1 。所以暂时没有装满水的湖泊了。
    +第五天后,装满水的湖泊包括 [2]。
    +第六天后,装满水的湖泊包括 [1,2]。
    +可以看出,这个方案下不会有洪水发生。同时, [-1,-1,1,2,-1,-1] 也是另一个可行的没有洪水的方案。
    +
    + +

    示例 3:

    + +
    输入:rains = [1,2,0,1,2]
    +输出:[]
    +解释:第二天后,装满水的湖泊包括 [1,2]。我们可以在第三天抽干一个湖泊的水。
    +但第三天后,湖泊 1 和 2 都会再次下雨,所以不管我们第三天抽干哪个湖泊的水,另一个湖泊都会发生洪水。
    +
    + +

    示例 4:

    + +
    输入:rains = [69,0,0,0,69]
    +输出:[-1,69,1,1,-1]
    +解释:任何形如 [-1,69,x,y,-1], [-1,x,69,y,-1] 或者 [-1,x,y,69,-1] 都是可行的解,其中 1 <= x,y <= 10^9
    +
    + +

    示例 5:

    + +
    输入:rains = [10,20,20]
    +输出:[]
    +解释:由于湖泊 20 会连续下 2 天的雨,所以没有没有办法阻止洪水。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rains.length <= 10^5
    • +
    • 0 <= rains[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1489.leetcode1489 Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1489.leetcode1489 Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree-zh.md" new file mode 100644 index 00000000..34568134 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1489.leetcode1489 Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree-zh.md" @@ -0,0 +1,81 @@ +# [1489. 找到最小生成树里的关键边和伪关键边](https://leetcode-cn.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1489.Find%20Critical%20and%20Pseudo-Critical%20Edges%20in%20Minimum%20Spanning%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一个 n 个点的带权无向连通图,节点编号为 0 到 n-1 ,同时还有一个数组 edges ,其中 edges[i] = [fromi, toi, weighti] 表示在 fromi 和 toi 节点之间有一条带权无向边。最小生成树 (MST) 是给定图中边的一个子集,它连接了所有节点且没有环,而且这些边的权值和最小。

    + +

    请你找到给定图中最小生成树的所有关键边和伪关键边。如果从图中删去某条边,会导致最小生成树的权值和增加,那么我们就说它是一条关键边。伪关键边则是可能会出现在某些最小生成树中但不会出现在所有最小生成树中的边。

    + +

    请注意,你可以分别以任意顺序返回关键边的下标和伪关键边的下标。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]
    +输出:[[0,1],[2,3,4,5]]
    +解释:上图描述了给定图。
    +下图是所有的最小生成树。
    +
    +注意到第 0 条边和第 1 条边出现在了所有最小生成树中,所以它们是关键边,我们将这两个下标作为输出的第一个列表。
    +边 2,3,4 和 5 是所有 MST 的剩余边,所以它们是伪关键边。我们将它们作为输出的第二个列表。
    +
    + +

    示例 2 :

    + +

    + +
    输入:n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]
    +输出:[[],[0,1,2,3]]
    +解释:可以观察到 4 条边都有相同的权值,任选它们中的 3 条可以形成一棵 MST 。所以 4 条边都是伪关键边。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • 1 <= edges.length <= min(200, n * (n - 1) / 2)
    • +
    • edges[i].length == 3
    • +
    • 0 <= fromi < toi < n
    • +
    • 1 <= weighti <= 1000
    • +
    • 所有 (fromi, toi) 数对都是互不相同的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1490.leetcode1490 Clone N-ary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1490.leetcode1490 Clone N-ary Tree-zh.md" new file mode 100644 index 00000000..a04c87ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1490.leetcode1490 Clone N-ary Tree-zh.md" @@ -0,0 +1,82 @@ +# [1490. 克隆 N 叉树](https://leetcode-cn.com/problems/clone-n-ary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1490.Clone%20N-ary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵 N 叉树的根节点 root ,返回该树的深拷贝(克隆)。

    + +

    N 叉树的每个节点都包含一个值( int )和子节点的列表( List[Node] )。

    + +
    +class Node {
    +    public int val;
    +    public List<Node> children;
    +}
    +
    + +

    N 叉树的输入序列用层序遍历表示,每组子节点用 null 分隔(见示例)。

    + +

    进阶:你的答案可以适用于克隆图问题吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,null,3,2,4,null,5,6]
    +输出:[1,null,3,2,4,null,5,6]
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出:[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定的 N 叉树的深度小于或等于 1000
    • +
    • 节点的总个数在 [0, 10^4] 之间
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1491.leetcode1491 Average Salary Excluding the Minimum and Maximum Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1491.leetcode1491 Average Salary Excluding the Minimum and Maximum Salary-zh.md" new file mode 100644 index 00000000..339528cc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1491.leetcode1491 Average Salary Excluding the Minimum and Maximum Salary-zh.md" @@ -0,0 +1,83 @@ +# [1491. 去掉最低工资和最高工资后的工资平均值](https://leetcode-cn.com/problems/average-salary-excluding-the-minimum-and-maximum-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1491.Average%20Salary%20Excluding%20the%20Minimum%20and%20Maximum%20Salary/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 salary ,数组里每个数都是 唯一 的,其中 salary[i] 是第 i 个员工的工资。

    + +

    请你返回去掉最低工资和最高工资以后,剩下员工工资的平均值。

    + +

     

    + +

    示例 1:

    + +
    输入:salary = [4000,3000,1000,2000]
    +输出:2500.00000
    +解释:最低工资和最高工资分别是 1000 和 4000 。
    +去掉最低工资和最高工资以后的平均工资是 (2000+3000)/2= 2500
    +
    + +

    示例 2:

    + +
    输入:salary = [1000,2000,3000]
    +输出:2000.00000
    +解释:最低工资和最高工资分别是 1000 和 3000 。
    +去掉最低工资和最高工资以后的平均工资是 (2000)/1= 2000
    +
    + +

    示例 3:

    + +
    输入:salary = [6000,5000,4000,3000,2000,1000]
    +输出:3500.00000
    +
    + +

    示例 4:

    + +
    输入:salary = [8000,9000,2000,3000,6000,1000]
    +输出:4750.00000
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= salary.length <= 100
    • +
    • 10^3 <= salary[i] <= 10^6
    • +
    • salary[i] 是唯一的。
    • +
    • 与真实值误差在 10^-5 以内的结果都将视为正确答案。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1492.leetcode1492 The kth Factor of n-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1492.leetcode1492 The kth Factor of n-zh.md" new file mode 100644 index 00000000..25c7e749 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1492.leetcode1492 The kth Factor of n-zh.md" @@ -0,0 +1,89 @@ +# [1492. n 的第 k 个因子](https://leetcode-cn.com/problems/the-kth-factor-of-n) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1492.The%20kth%20Factor%20of%20n/README_EN.md) + +## 题目描述 + + + +

    给你两个正整数 n 和 k 。

    + +

    如果正整数 i 满足 n % i == 0 ,那么我们就说正整数 i 是整数 n 的因子。

    + +

    考虑整数 n 的所有因子,将它们 升序排列 。请你返回第 k 个因子。如果 n 的因子数少于 k ,请你返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 12, k = 3
    +输出:3
    +解释:因子列表包括 [1, 2, 3, 4, 6, 12],第 3 个因子是 3 。
    +
    + +

    示例 2:

    + +
    输入:n = 7, k = 2
    +输出:7
    +解释:因子列表包括 [1, 7] ,第 2 个因子是 7 。
    +
    + +

    示例 3:

    + +
    输入:n = 4, k = 4
    +输出:-1
    +解释:因子列表包括 [1, 2, 4] ,只有 3 个因子,所以我们应该返回 -1 。
    +
    + +

    示例 4:

    + +
    输入:n = 1, k = 1
    +输出:1
    +解释:因子列表包括 [1] ,第 1 个因子为 1 。
    +
    + +

    示例 5:

    + +
    输入:n = 1000, k = 3
    +输出:4
    +解释:因子列表包括 [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= n <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1493.leetcode1493 Longest Subarray of 1's After Deleting One Element-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1493.leetcode1493 Longest Subarray of 1's After Deleting One Element-zh.md" new file mode 100644 index 00000000..ee8c4f2d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1493.leetcode1493 Longest Subarray of 1's After Deleting One Element-zh.md" @@ -0,0 +1,85 @@ +# [1493. 删掉一个元素以后全为 1 的最长子数组](https://leetcode-cn.com/problems/longest-subarray-of-1s-after-deleting-one-element) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1493.Longest%20Subarray%20of%201%27s%20After%20Deleting%20One%20Element/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制数组 nums ,你需要从中删掉一个元素。

    + +

    请你在删掉元素的结果数组中,返回最长的且只包含 1 的非空子数组的长度。

    + +

    如果不存在这样的子数组,请返回 0 。

    + +

     

    + +

    提示 1:

    + +
    输入:nums = [1,1,0,1]
    +输出:3
    +解释:删掉位置 2 的数后,[1,1,1] 包含 3 个 1 。
    + +

    示例 2:

    + +
    输入:nums = [0,1,1,1,0,1,1,0,1]
    +输出:5
    +解释:删掉位置 4 的数字后,[0,1,1,1,1,1,0,1] 的最长全 1 子数组为 [1,1,1,1,1] 。
    + +

    示例 3:

    + +
    输入:nums = [1,1,1]
    +输出:2
    +解释:你必须要删除一个元素。
    + +

    示例 4:

    + +
    输入:nums = [1,1,0,0,1,1,1,0,1]
    +输出:4
    +
    + +

    示例 5:

    + +
    输入:nums = [0,0,0]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • nums[i] 要么是 0 要么是 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1494.leetcode1494 Parallel Courses II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1494.leetcode1494 Parallel Courses II-zh.md" new file mode 100644 index 00000000..cf91125a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1494.leetcode1494 Parallel Courses II-zh.md" @@ -0,0 +1,85 @@ +# [1494. 并行课程 II](https://leetcode-cn.com/problems/parallel-courses-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1494.Parallel%20Courses%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n 表示某所大学里课程的数目,编号为 1 到 n ,数组 dependencies 中, dependencies[i] = [xi, yi]  表示一个先修课的关系,也就是课程 xi 必须在课程 yi 之前上。同时你还有一个整数 k 。

    + +

    在一个学期中,你 最多 可以同时上 k 门课,前提是这些课的先修课在之前的学期里已经上过了。

    + +

    请你返回上完所有课最少需要多少个学期。题目保证一定存在一种上完所有课的方式。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2
    +输出:3 
    +解释:上图展示了题目输入的图。在第一个学期中,我们可以上课程 2 和课程 3 。然后第二个学期上课程 1 ,第三个学期上课程 4 。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2
    +输出:4 
    +解释:上图展示了题目输入的图。一个最优方案是:第一学期上课程 2 和 3,第二学期上课程 4 ,第三学期上课程 1 ,第四学期上课程 5 。
    +
    + +

    示例 3:

    + +
    输入:n = 11, dependencies = [], k = 2
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 15
    • +
    • 1 <= k <= n
    • +
    • 0 <= dependencies.length <= n * (n-1) / 2
    • +
    • dependencies[i].length == 2
    • +
    • 1 <= xi, yi <= n
    • +
    • xi != yi
    • +
    • 所有先修关系都是不同的,也就是说 dependencies[i] != dependencies[j] 。
    • +
    • 题目输入的图是个有向无环图。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1495.leetcode1495 Friendly Movies Streamed Last Month-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1495.leetcode1495 Friendly Movies Streamed Last Month-zh.md" new file mode 100644 index 00000000..3f088694 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1495.leetcode1495 Friendly Movies Streamed Last Month-zh.md" @@ -0,0 +1,118 @@ +# [1495. 上月播放的儿童适宜电影](https://leetcode-cn.com/problems/friendly-movies-streamed-last-month) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1495.Friendly%20Movies%20Streamed%20Last%20Month/README_EN.md) + +## 题目描述 + + + +

    表: TVProgram

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| program_date  | date    |
    +| content_id    | int     |
    +| channel       | varchar |
    ++---------------+---------+
    +(program_date, content_id) 是该表主键.
    +该表包含电视上的节目信息.
    +content_id 是电视一些频道上的节目的 id.
    + +

     

    + +

    表: Content

    + +
    ++------------------+---------+
    +| Column Name      | Type    |
    ++------------------+---------+
    +| content_id       | varchar |
    +| title            | varchar |
    +| Kids_content     | enum    |
    +| content_type     | varchar |
    ++------------------+---------+
    +content_id 是该表主键.
    +Kids_content 是枚举类型, 取值为('Y', 'N'), 其中: 
    +'Y' 表示儿童适宜内容, 而'N'表示儿童不宜内容.
    +content_type 表示内容的类型, 比如电影, 电视剧等.
    +
    + +

     

    + +

    写一个 SQL 语句,  报告在 2020 年 6 月份播放的儿童适宜电影的去重电影名.

    + +

    返回的结果表单没有顺序要求.

    + +

    查询结果的格式如下例所示.

    + +

     

    + +
    +TVProgram 表:
    ++--------------------+--------------+-------------+
    +| program_date       | content_id   | channel     |
    ++--------------------+--------------+-------------+
    +| 2020-06-10 08:00   | 1            | LC-Channel  |
    +| 2020-05-11 12:00   | 2            | LC-Channel  |
    +| 2020-05-12 12:00   | 3            | LC-Channel  |
    +| 2020-05-13 14:00   | 4            | Disney Ch   |
    +| 2020-06-18 14:00   | 4            | Disney Ch   |
    +| 2020-07-15 16:00   | 5            | Disney Ch   |
    ++--------------------+--------------+-------------+
    +
    +Content 表:
    ++------------+----------------+---------------+---------------+
    +| content_id | title          | Kids_content  | content_type  |
    ++------------+----------------+---------------+---------------+
    +| 1          | Leetcode Movie | N             | Movies        |
    +| 2          | Alg. for Kids  | Y             | Series        |
    +| 3          | Database Sols  | N             | Series        |
    +| 4          | Aladdin        | Y             | Movies        |
    +| 5          | Cinderella     | Y             | Movies        |
    ++------------+----------------+---------------+---------------+
    +
    +Result 表:
    ++--------------+
    +| title        |
    ++--------------+
    +| Aladdin      |
    ++--------------+
    +"Leetcode Movie" 是儿童不宜的电影.
    +"Alg. for Kids" 不是电影.
    +"Database Sols" 不是电影
    +"Alladin" 是电影, 儿童适宜, 并且在 2020 年 6 月份播放.
    +"Cinderella" 不在 2020 年 6 月份播放.
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1496.leetcode1496 Path Crossing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1496.leetcode1496 Path Crossing-zh.md" new file mode 100644 index 00000000..7c5e3080 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1496.leetcode1496 Path Crossing-zh.md" @@ -0,0 +1,71 @@ +# [1496. 判断路径是否相交](https://leetcode-cn.com/problems/path-crossing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1496.Path%20Crossing/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 path,其中 path[i] 的值可以是 'N''S''E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。

    + +

    机器人从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。

    + +

    如果路径在任何位置上出现相交的情况,也就是走到之前已经走过的位置,请返回 True ;否则,返回 False

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:path = "NES"
    +输出:false 
    +解释:该路径没有在任何位置相交。
    + +

    示例 2:

    + +

    + +
    输入:path = "NESWW"
    +输出:true
    +解释:该路径经过原点两次。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= path.length <= 10^4
    • +
    • path 仅由 {'N', 'S', 'E', 'W} 中的字符组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1497.leetcode1497 Check If Array Pairs Are Divisible by k-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1497.leetcode1497 Check If Array Pairs Are Divisible by k-zh.md" new file mode 100644 index 00000000..fc3a930b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1497.leetcode1497 Check If Array Pairs Are Divisible by k-zh.md" @@ -0,0 +1,133 @@ +# [1497. 检查数组对是否可以被 k 整除](https://leetcode-cn.com/problems/check-if-array-pairs-are-divisible-by-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1497.Check%20If%20Array%20Pairs%20Are%20Divisible%20by%20k/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 和一个整数 k ,其中数组长度是偶数,值为 n

    + +

    现在需要把数组恰好分成 n / 2 对,以使每对数字的和都能够被 k 整除。

    + +

    如果存在这样的分法,请返回 True ;否则,返回 False

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2,3,4,5,10,6,7,8,9], k = 5
    +输出:true
    +解释:划分后的数字对为 (1,9),(2,8),(3,7),(4,6) 以及 (5,10) 。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,2,3,4,5,6], k = 7
    +输出:true
    +解释:划分后的数字对为 (1,6),(2,5) 以及 (3,4) 。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,2,3,4,5,6], k = 10
    +输出:false
    +解释:无法在将数组中的数字分为三对的同时满足每对数字和能够被 10 整除的条件。
    +
    + +

    示例 4:

    + +
    输入:arr = [-10,10], k = 2
    +输出:true
    +
    + +

    示例 5:

    + +
    输入:arr = [-1,1,-2,2,-3,3,-4,4], k = 3
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • arr.length == n
    • +
    • 1 <= n <= 10^5
    • +
    • n 为偶数
    • +
    • -10^9 <= arr[i] <= 10^9
    • +
    • 1 <= k <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isPathCrossing(self, path: str) -> bool: + x = y = 0 + visited = set() + visited.add('0.0') + for c in path: + if c == 'N': + y += 1 + elif c == 'S': + y -= 1 + elif c == 'E': + x += 1 + else: + x -= 1 + pos = f'{x}.{y}' + if pos in visited: + return True + visited.add(pos) + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean isPathCrossing(String path) { + Set visited = new HashSet<>(); + visited.add("0.0"); + int x = 0, y = 0; + for (int i = 0; i < path.length(); ++i) { + char c = path.charAt(i); + if (c == 'N') { + ++y; + } else if (c == 'S') { + --y; + } else if (c == 'E') { + ++x; + } else { + --x; + } + String pos = x + "." + y; + if (visited.contains(pos)) { + return true; + } + visited.add(pos); + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1498.leetcode1498 Number of Subsequences That Satisfy the Given Sum Condition-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1498.leetcode1498 Number of Subsequences That Satisfy the Given Sum Condition-zh.md" new file mode 100644 index 00000000..7bb575bb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1498.leetcode1498 Number of Subsequences That Satisfy the Given Sum Condition-zh.md" @@ -0,0 +1,88 @@ +# [1498. 满足条件的子序列数目](https://leetcode-cn.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1498.Number%20of%20Subsequences%20That%20Satisfy%20the%20Given%20Sum%20Condition/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 target

    + +

    请你统计并返回 nums 中能满足其最小元素与最大元素的 小于或等于 target非空 子序列的数目。

    + +

    由于答案可能很大,请将结果对 10^9 + 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [3,5,6,7], target = 9
    +输出:4
    +解释:有 4 个子序列满足该条件。
    +[3] -> 最小元素 + 最大元素 <= target (3 + 3 <= 9)
    +[3,5] -> (3 + 5 <= 9)
    +[3,5,6] -> (3 + 6 <= 9)
    +[3,6] -> (3 + 6 <= 9)
    +
    + +

    示例 2:

    + +
    输入:nums = [3,3,6,8], target = 10
    +输出:6
    +解释:有 6 个子序列满足该条件。(nums 中可以有重复数字)
    +[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
    + +

    示例 3:

    + +
    输入:nums = [2,3,3,4,6,7], target = 12
    +输出:61
    +解释:共有 63 个非空子序列,其中 2 个不满足条件([6,7], [7])
    +有效序列总数为(63 - 2 = 61)
    +
    + +

    示例 4:

    + +
    输入:nums = [5,2,4,1,7,6,8], target = 16
    +输出:127
    +解释:所有非空子序列都满足条件 (2^7 - 1) = 127
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 1 <= nums[i] <= 10^6
    • +
    • 1 <= target <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1499.leetcode1499 Max Value of Equation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1499.leetcode1499 Max Value of Equation-zh.md" new file mode 100644 index 00000000..4d34ea4d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1499.leetcode1499 Max Value of Equation-zh.md" @@ -0,0 +1,72 @@ +# [1499. 满足不等式的最大值](https://leetcode-cn.com/problems/max-value-of-equation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1400-1499/1499.Max%20Value%20of%20Equation/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 points 和一个整数 k 。数组中每个元素都表示二维平面上的点的坐标,并按照横坐标 x 的值从小到大排序。也就是说 points[i] = [xi, yi] ,并且在 1 <= i < j <= points.length 的前提下, xi < xj 总成立。

    + +

    请你找出 yi + yj + |xi - xj|最大值,其中 |xi - xj| <= k1 <= i < j <= points.length

    + +

    题目测试数据保证至少存在一对能够满足 |xi - xj| <= k 的点。

    + +

     

    + +

    示例 1:

    + +
    输入:points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
    +输出:4
    +解释:前两个点满足 |xi - xj| <= 1 ,代入方程计算,则得到值 3 + 0 + |1 - 2| = 4 。第三个和第四个点也满足条件,得到值 10 + -10 + |5 - 6| = 1 。
    +没有其他满足条件的点,所以返回 4 和 1 中最大的那个。
    + +

    示例 2:

    + +
    输入:points = [[0,0],[3,0],[9,2]], k = 3
    +输出:3
    +解释:只有前两个点满足 |xi - xj| <= 3 ,代入方程后得到值 0 + 0 + |0 - 3| = 3 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= points.length <= 10^5
    • +
    • points[i].length == 2
    • +
    • -10^8 <= points[i][0], points[i][1] <= 10^8
    • +
    • 0 <= k <= 2 * 10^8
    • +
    • 对于所有的1 <= i < j <= points.lengthpoints[i][0] < points[j][0] 都成立。也就是说,xi 是严格递增的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1500.leetcode1500 Design a File Sharing System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1500.leetcode1500 Design a File Sharing System-zh.md" new file mode 100644 index 00000000..04db75cb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1500.leetcode1500 Design a File Sharing System-zh.md" @@ -0,0 +1,203 @@ +# [1500. 设计文件分享系统](https://leetcode-cn.com/problems/design-a-file-sharing-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1500.Design%20a%20File%20Sharing%20System/README_EN.md) + +## 题目描述 + + + +

    我们需要使用一套文件分享系统来分享一个非常大的文件,该文件由 m 个从 1 到 m 编号的文件块组成。

    + +

    当用户加入系统时,系统应为其注册一个独有的 ID。这个独有的 ID 应当被相应的用户使用一次,但是当用户离开系统时,其 ID 应可以被(后续新注册的用户)再次使用

    + +

    用户可以请求文件中的某个指定的文件块,系统应当返回拥有这个文件块的所有用户的 ID。如果用户收到 ID 的非空列表,就表示成功接收到请求的文件块。

    + +


    +实现 FileSharing 类:

    + +
      +
    • FileSharing(int m) 初始化该对象,文件有 m 个文件块。
    • +
    • int join(int[] ownedChunks):一个新用户加入系统,并拥有文件的一些文件块。系统应当为该用户注册一个 ID,该 ID 应是未被其他用户占用的最小正整数。返回注册的 ID。
    • +
    • void leave(int userID):ID 为 userID 的用户将离开系统,你不能再从该用户提取文件块了。
    • +
    • int[] request(int userID, int chunkID):ID 为 userID 的用户请求编号为 chunkID 的文件块。返回拥有这个文件块的所有用户的 ID 所构成的列表或数组,按升序排列。
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 当系统以用户的 IP 地址而不是独有 ID 来识别用户,且用户断开连接后以相同 IP 重新连接系统时,会发生什么?
    • +
    • 当用户频繁加入并退出系统,且该用户不请求任何文件块时,你的解决方案仍然保持高效吗?
    • +
    • 当所有用户同时加入系统,请求所有文件并离开时,你的解决方案仍然保持高效吗?
    • +
    • 如果系统用于分享 n 个文件,其中第  i 个文件由 m[i] 组成,你需要如何修改?
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["FileSharing","join","join","join","request","request","leave","request","leave","join"]
    +[[4],[[1,2]],[[2,3]],[[4]],[1,3],[2,2],[1],[2,1],[2],[[]]]
    +输出:
    +[null,1,2,3,[2],[1,2],null,[],null,1]
    +解释:
    +FileSharing fileSharing = new FileSharing(4); // 我们用该系统分享由 4 个文件块组成的文件。
    +
    +fileSharing.join([1, 2]);    // 一个拥有文件块 [1,2] 的用户加入系统,为其注册 id = 1 并返回 1。
    +
    +fileSharing.join([2, 3]);    // 一个拥有文件块 [2,3] 的用户加入系统,为其注册 id = 2 并返回 2。
    +
    +fileSharing.join([4]);       // 一个拥有文件块 [4] 的用户加入系统,为其注册 id = 3 并返回 3。
    +
    +fileSharing.request(1, 3);   // id = 1 的用户请求第 3 个文件块,只有 id = 2 的用户拥有文件块,返回 [2] 。注意,现在用户 1 现拥有文件块 [1,2,3]。
    +
    +fileSharing.request(2, 2);   // id = 2 的用户请求第 2 个文件块,id 为 [1,2] 的用户拥有该文件块,所以我们返回 [1,2] 。
    +
    +fileSharing.leave(1);        // id = 1 的用户离开系统,其所拥有的所有文件块不再对其他用户可用。
    +
    +fileSharing.request(2, 1);   // id = 2 的用户请求第 1 个文件块,系统中没有用户拥有该文件块,所以我们返回空列表 [] 。
    +
    +fileSharing.leave(2);        // id = 2 的用户离开系统。
    +
    +fileSharing.join([]);        // 一个不拥有任何文件块的用户加入系统,为其注册 id = 1 并返回 1 。注意,id 1 和 2 空闲,可以重新使用。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m <= 10^5
    • +
    • 0 <= ownedChunks.length <= min(100, m)
    • +
    • 1 <= ownedChunks[i] <= m
    • +
    • ownedChunks 的值是互不相同的。
    • +
    • 1 <= chunkID <= m
    • +
    • 当你正确地注册用户 ID 时,题目保证 userID 是系统中的一个已注册用户。
    • +
    • join、 leave 和 request 最多被调用 10^4 次。
    • +
    • 每次对 leave 的调用都有对应的对 join 的调用。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class FileSharing: + + def __init__(self, m: int): + self.cur = 0 + self.chunks = m + self.reused = [] + self.user_chunks = collections.defaultdict(set) + + def join(self, ownedChunks: List[int]) -> int: + if self.reused: + userID = heapq.heappop(self.reused) + else: + self.cur += 1 + userID = self.cur + self.user_chunks[userID] = set(ownedChunks) + return userID + + def leave(self, userID: int) -> None: + heapq.heappush(self.reused, userID) + self.user_chunks.pop(userID) + + def request(self, userID: int, chunkID: int) -> List[int]: + if chunkID < 1 or chunkID > self.chunks: + return [] + res = [] + for k, v in self.user_chunks.items(): + if chunkID in v: + res.append(k) + if res: + self.user_chunks[userID].add(chunkID) + return sorted(res) + +# Your FileSharing object will be instantiated and called as such: +# obj = FileSharing(m) +# param_1 = obj.join(ownedChunks) +# obj.leave(userID) +# param_3 = obj.request(userID,chunkID) +``` + +### **Java** + + + +```java +class FileSharing { + private int chunks; + private int cur; + private TreeSet reused; + private TreeMap> userChunks; + + public FileSharing(int m) { + cur = 0; + chunks = m; + reused = new TreeSet<>(); + userChunks = new TreeMap<>(); + } + + public int join(List ownedChunks) { + int userID; + if (reused.isEmpty()) { + ++cur; + userID = cur; + } else { + userID = reused.pollFirst(); + } + userChunks.put(userID, new HashSet<>(ownedChunks)); + return userID; + } + + public void leave(int userID) { + reused.add(userID); + userChunks.remove(userID); + } + + public List request(int userID, int chunkID) { + if (chunkID < 1 || chunkID > chunks) { + return Collections.emptyList(); + } + List res = new ArrayList<>(); + for (Map.Entry> entry : userChunks.entrySet()) { + if (entry.getValue().contains(chunkID)) { + res.add(entry.getKey()); + } + } + if (!userChunks.containsKey(userID)) { + userChunks.put(userID, new HashSet<>()); + } + if (!res.isEmpty()) { + userChunks.get(userID).add(chunkID); + } + return res; + } +} + +/** + * Your FileSharing object will be instantiated and called as such: + * FileSharing obj = new FileSharing(m); + * int param_1 = obj.join(ownedChunks); + * obj.leave(userID); + * List param_3 = obj.request(userID,chunkID); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1501.leetcode1501 Countries You Can Safely Invest In-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1501.leetcode1501 Countries You Can Safely Invest In-zh.md" new file mode 100644 index 00000000..99694fa1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1501.leetcode1501 Countries You Can Safely Invest In-zh.md" @@ -0,0 +1,127 @@ +# [1501. 可以放心投资的国家](https://leetcode-cn.com/problems/countries-you-can-safely-invest-in) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1501.Countries%20You%20Can%20Safely%20Invest%20In/README_EN.md) + +## 题目描述 + + + +

    表 Person:

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| id             | int     |
    +| name           | varchar |
    +| phone_number   | varchar |
    ++----------------+---------+
    +id 是该表主键.
    +该表每一行包含一个人的名字和电话号码.
    +电话号码的格式是:'xxx-yyyyyyy', 其中xxx是国家码(3个字符), yyyyyyy是电话号码(7个字符), x和y都表示数字. 同时, 国家码和电话号码都可以包含前导0.
    +
    + +

    表 Country:

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| name           | varchar |
    +| country_code   | varchar |
    ++----------------+---------+
    +country_code是该表主键.
    +该表每一行包含国家名和国家码. country_code的格式是'xxx', x是数字.
    +
    + +

     

    + +

    表 Calls:

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| caller_id   | int  |
    +| callee_id   | int  |
    +| duration    | int  |
    ++-------------+------+
    +该表无主键, 可能包含重复行.
    +每一行包含呼叫方id, 被呼叫方id和以分钟为单位的通话时长. caller_id != callee_id
    +
    + +

    一家电信公司想要投资新的国家. 该公司想要投资的国家是:  该国的平均通话时长要严格地大于全球平均通话时长.

    + +

    写一段 SQL,  找到所有该公司可以投资的国家.

    + +

    返回的结果表没有顺序要求.

    + +

    查询的结果格式如下例所示.

    + +
    +Person 表:
    ++----+----------+--------------+
    +| id | name     | phone_number |
    ++----+----------+--------------+
    +| 3  | Jonathan | 051-1234567  |
    +| 12 | Elvis    | 051-7654321  |
    +| 1  | Moncef   | 212-1234567  |
    +| 2  | Maroua   | 212-6523651  |
    +| 7  | Meir     | 972-1234567  |
    +| 9  | Rachel   | 972-0011100  |
    ++----+----------+--------------+
    +
    +Country 表:
    ++----------+--------------+
    +| name     | country_code |
    ++----------+--------------+
    +| Peru     | 051          |
    +| Israel   | 972          |
    +| Morocco  | 212          |
    +| Germany  | 049          |
    +| Ethiopia | 251          |
    ++----------+--------------+
    +
    +Calls 表:
    ++-----------+-----------+----------+
    +| caller_id | callee_id | duration |
    ++-----------+-----------+----------+
    +| 1         | 9         | 33       |
    +| 2         | 9         | 4        |
    +| 1         | 2         | 59       |
    +| 3         | 12        | 102      |
    +| 3         | 12        | 330      |
    +| 12        | 3         | 5        |
    +| 7         | 9         | 13       |
    +| 7         | 1         | 3        |
    +| 9         | 7         | 1        |
    +| 1         | 7         | 7        |
    ++-----------+-----------+----------+
    +
    +Result 表:
    ++----------+
    +| country  |
    ++----------+
    +| Peru     |
    ++----------+
    +国家Peru的平均通话时长是 (102 + 102 + 330 + 330 + 5 + 5) / 6 = 145.666667
    +国家Israel的平均通话时长是 (33 + 4 + 13 + 13 + 3 + 1 + 1 + 7) / 8 = 9.37500
    +国家Morocco的平均通话时长是 (33 + 4 + 59 + 59 + 3 + 7) / 6 = 27.5000 
    +全球平均通话时长 = (2 * (33 + 4 + 59 + 102 + 330 + 5 + 13 + 3 + 1 + 7)) / 20 = 55.70000
    +所以, Peru是唯一的平均通话时长大于全球平均通话时长的国家, 也是唯一的推荐投资的国家.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1502.leetcode1502 Can Make Arithmetic Progression From Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1502.leetcode1502 Can Make Arithmetic Progression From Sequence-zh.md" new file mode 100644 index 00000000..4a033e67 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1502.leetcode1502 Can Make Arithmetic Progression From Sequence-zh.md" @@ -0,0 +1,101 @@ +# [1502. 判断能否形成等差数列](https://leetcode-cn.com/problems/can-make-arithmetic-progression-from-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1502.Can%20Make%20Arithmetic%20Progression%20From%20Sequence/README_EN.md) + +## 题目描述 + + + +

    给你一个数字数组 arr

    + +

    如果一个数列中,任意相邻两项的差总等于同一个常数,那么这个数列就称为 等差数列

    + +

    如果可以重新排列数组形成等差数列,请返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [3,5,1]
    +输出:true
    +解释:对数组重新排序得到 [1,3,5] 或者 [5,3,1] ,任意相邻两项的差分别为 2 或 -2 ,可以形成等差数列。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,2,4]
    +输出:false
    +解释:无法通过重新排序得到等差数列。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 1000
    • +
    • -10^6 <= arr[i] <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + arr.sort() + for i in range(1, len(arr) - 1): + if (arr[i] << 1) != arr[i - 1] + arr[i + 1]: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean canMakeArithmeticProgression(int[] arr) { + Arrays.sort(arr); + for (int i = 1; i < arr.length - 1; ++i) { + if ((arr[i] << 1) != arr[i - 1] + arr[i + 1]) { + return false; + } + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function(arr) { + arr.sort((a, b) => a - b); + for (let i = 1; i < arr.length - 1; i++) { + if ((arr[i] << 1) != (arr[i - 1] + arr[i + 1])) return false; + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1503.leetcode1503 Last Moment Before All Ants Fall Out of a Plank-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1503.leetcode1503 Last Moment Before All Ants Fall Out of a Plank-zh.md" new file mode 100644 index 00000000..c1d809c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1503.leetcode1503 Last Moment Before All Ants Fall Out of a Plank-zh.md" @@ -0,0 +1,108 @@ +# [1503. 所有蚂蚁掉下来前的最后一刻](https://leetcode-cn.com/problems/last-moment-before-all-ants-fall-out-of-a-plank) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1503.Last%20Moment%20Before%20All%20Ants%20Fall%20Out%20of%20a%20Plank/README_EN.md) + +## 题目描述 + + + +

    有一块木板,长度为 n单位 。一些蚂蚁在木板上移动,每只蚂蚁都以 每秒一个单位 的速度移动。其中,一部分蚂蚁向 移动,其他蚂蚁向 移动。

    + +

    当两只向 不同 方向移动的蚂蚁在某个点相遇时,它们会同时改变移动方向并继续移动。假设更改方向不会花费任何额外时间。

    + +

    而当蚂蚁在某一时刻 t 到达木板的一端时,它立即从木板上掉下来。

    + +

    给你一个整数 n 和两个整数数组 left 以及 right 。两个数组分别标识向左或者向右移动的蚂蚁在 t = 0 时的位置。请你返回最后一只蚂蚁从木板上掉下来的时刻。

    + +

     

    + +

    示例 1:

    + +

     

    + +

    + +
    输入:n = 4, left = [4,3], right = [0,1]
    +输出:4
    +解释:如上图所示:
    +-下标 0 处的蚂蚁命名为 A 并向右移动。
    +-下标 1 处的蚂蚁命名为 B 并向右移动。
    +-下标 3 处的蚂蚁命名为 C 并向左移动。
    +-下标 4 处的蚂蚁命名为 D 并向左移动。
    +请注意,蚂蚁在木板上的最后时刻是 t = 4 秒,之后蚂蚁立即从木板上掉下来。(也就是说在 t = 4.0000000001 时,木板上没有蚂蚁)。
    + +

    示例 2:

    + +

    + +
    输入:n = 7, left = [], right = [0,1,2,3,4,5,6,7]
    +输出:7
    +解释:所有蚂蚁都向右移动,下标为 0 的蚂蚁需要 7 秒才能从木板上掉落。
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 7, left = [0,1,2,3,4,5,6,7], right = []
    +输出:7
    +解释:所有蚂蚁都向左移动,下标为 7 的蚂蚁需要 7 秒才能从木板上掉落。
    +
    + +

    示例 4:

    + +
    输入:n = 9, left = [5], right = [4]
    +输出:5
    +解释:t = 1 秒时,两只蚂蚁将回到初始位置,但移动方向与之前相反。
    +
    + +

    示例 5:

    + +
    输入:n = 6, left = [6], right = [0]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    • 0 <= left.length <= n + 1
    • +
    • 0 <= left[i] <= n
    • +
    • 0 <= right.length <= n + 1
    • +
    • 0 <= right[i] <= n
    • +
    • 1 <= left.length + right.length <= n + 1
    • +
    • leftright 中的所有值都是唯一的,并且每个值 只能出现在二者之一 中。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1504.leetcode1504 Count Submatrices With All Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1504.leetcode1504 Count Submatrices With All Ones-zh.md" new file mode 100644 index 00000000..25c8d54a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1504.leetcode1504 Count Submatrices With All Ones-zh.md" @@ -0,0 +1,100 @@ +# [1504. 统计全 1 子矩形](https://leetcode-cn.com/problems/count-submatrices-with-all-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1504.Count%20Submatrices%20With%20All%20Ones/README_EN.md) + +## 题目描述 + + + +

    给你一个只包含 0 和 1 的 rows * columns 矩阵 mat ,请你返回有多少个 子矩形 的元素全部都是 1 。

    + +

     

    + +

    示例 1:

    + +
    +输入:mat = [[1,0,1],
    +            [1,1,0],
    +            [1,1,0]]
    +输出:13
    +解释:
    +6 个 1x1 的矩形。
    +有 2 个 1x2 的矩形。
    +有 3 个 2x1 的矩形。
    +有 1 个 2x2 的矩形。
    +有 1 个 3x1 的矩形。
    +矩形数目总共 = 6 + 2 + 3 + 1 + 1 = 13 。
    +
    + +

    示例 2:

    + +
    +输入:mat = [[0,1,1,0],
    +            [0,1,1,1],
    +            [1,1,1,0]]
    +输出:24
    +解释:
    +有 8 个 1x1 的子矩形。
    +有 5 个 1x2 的子矩形。
    +有 2 个 1x3 的子矩形。
    +有 4 个 2x1 的子矩形。
    +有 2 个 2x2 的子矩形。
    +有 2 个 3x1 的子矩形。
    +有 1 个 3x2 的子矩形。
    +矩形数目总共 = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24
    +
    + +

    示例 3:

    + +
    +输入:mat = [[1,1,1,1,1,1]]
    +输出:21
    +
    + +

    示例 4:

    + +
    +输入:mat = [[1,0,1],[0,1,0],[1,0,1]]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rows <= 150
    • +
    • 1 <= columns <= 150
    • +
    • 0 <= mat[i][j] <= 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1505.leetcode1505 Minimum Possible Integer After at Most K Adjacent Swaps On Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1505.leetcode1505 Minimum Possible Integer After at Most K Adjacent Swaps On Digits-zh.md" new file mode 100644 index 00000000..65395056 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1505.leetcode1505 Minimum Possible Integer After at Most K Adjacent Swaps On Digits-zh.md" @@ -0,0 +1,96 @@ +# [1505. 最多 K 次交换相邻数位后得到的最小整数](https://leetcode-cn.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1505.Minimum%20Possible%20Integer%20After%20at%20Most%20K%20Adjacent%20Swaps%20On%20Digits/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 num 和一个整数 k 。其中,num 表示一个很大的整数,字符串中的每个字符依次对应整数上的各个 数位

    + +

    你可以交换这个整数相邻数位的数字 最多 k 次。

    + +

    请你返回你能得到的最小整数,并以字符串形式返回。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:num = "4321", k = 4
    +输出:"1342"
    +解释:4321 通过 4 次交换相邻数位得到最小整数的步骤如上图所示。
    +
    + +

    示例 2:

    + +
    +输入:num = "100", k = 1
    +输出:"010"
    +解释:输出可以包含前导 0 ,但输入保证不会有前导 0 。
    +
    + +

    示例 3:

    + +
    +输入:num = "36789", k = 1000
    +输出:"36789"
    +解释:不需要做任何交换。
    +
    + +

    示例 4:

    + +
    +输入:num = "22", k = 22
    +输出:"22"
    +
    + +

    示例 5:

    + +
    +输入:num = "9438957234785635408", k = 23
    +输出:"0345989723478563548"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num.length <= 30000
    • +
    • num 只包含 数字 且不含有 前导 0 
    • +
    • 1 <= k <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1506.leetcode1506 Find Root of N-Ary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1506.leetcode1506 Find Root of N-Ary Tree-zh.md" new file mode 100644 index 00000000..514362cb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1506.leetcode1506 Find Root of N-Ary Tree-zh.md" @@ -0,0 +1,102 @@ +# [1506. 找到 N 叉树的根节点](https://leetcode-cn.com/problems/find-root-of-n-ary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1506.Find%20Root%20of%20N-Ary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵 N 叉树 的所有节点在一个数组  Node[] tree 中,树中每个节点都有 唯一的值

    + +

    找到并返回 N 叉树的 根节点

    + +

     

    + +

    自定义测试:

    + +

    N 叉树的输入序列为其层序遍历序列,每组子节点用 null 分隔(见示例)。

    + +

    + +

    上图中的 N 叉树的序列化描述为 [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

    + +

    测试将以下列方式进行:

    + +
      +
    • 输入数据的形式为树的序列化描述。
    • +
    • 驱动程序代码将根据序列化的输入数据构造树,并以任意顺序将每个 Node 对象放入一个数组中。
    • +
    • 驱动程序代码将把数组传递给 findRoot ,你所编写的函数应该在数组中查找并返回根 Node 对象。
    • +
    • 驱动程序代码将接受返回的 Node 对象并对其进行序列化。如果序列化的结果和输入数据 相同 ,则测试 通过
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:tree = [1,null,3,2,4,null,5,6]
    +输出:[1,null,3,2,4,null,5,6]
    +解释:来自输入数据的树如上所示。
    +驱动程序代码创建树,并以任意顺序向 findRoot 提供 Node 对象。
    +例如,传递的数组可以是 [Node(5),Node(4),Node(3),Node(6),Node(2),Node(1)] 或 [Node(2),Node(6),Node(1),Node(3),Node(5),Node(4)] 。
    +findRoot 函数应该返回根 Node(1) ,驱动程序代码将序列化它并与输入数据进行比较。
    +输入数据和序列化的 Node(1) 相同,因此测试通过。
    + +

    示例 2:

    + +

    + +
    +输入:tree = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出:[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 节点的总个数在 [1, 5*10^4] 之间。
    • +
    • 每个节点都有唯一的值。
    • +
    + +

     

    + +

    进阶:

    + +
      +
    • 你可以使用 O(1) 额外内存空间且 O(n) 时间复杂度的算法来找到该树的根节点吗?
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1507.leetcode1507 Reformat Date-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1507.leetcode1507 Reformat Date-zh.md" new file mode 100644 index 00000000..bd35a6cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1507.leetcode1507 Reformat Date-zh.md" @@ -0,0 +1,105 @@ +# [1507. 转变日期格式](https://leetcode-cn.com/problems/reformat-date) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1507.Reformat%20Date/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 date ,它的格式为 Day Month Year ,其中:

    + +
      +
    • Day 是集合 {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"} 中的一个元素。
    • +
    • Month 是集合 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} 中的一个元素。
    • +
    • Year 的范围在 ​[1900, 2100] 之间。
    • +
    + +

    请你将字符串转变为 YYYY-MM-DD 的格式,其中:

    + +
      +
    • YYYY 表示 4 位的年份。
    • +
    • MM 表示 2 位的月份。
    • +
    • DD 表示 2 位的天数。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:date = "20th Oct 2052"
    +输出:"2052-10-20"
    +
    + +

    示例 2:

    + +
    输入:date = "6th Jun 1933"
    +输出:"1933-06-06"
    +
    + +

    示例 3:

    + +
    输入:date = "26th May 1960"
    +输出:"1960-05-26"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 给定日期保证是合法的,所以不需要处理异常输入。
    • +
    + + +## 解法 + + + +切分 `date` 字符串,获取对应的 `year`, `month`, `day`,然后拼接起来即可。 + + + +### **Python3** + + + +```python +class Solution: + def reformatDate(self, date: str) -> str: + months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + mapper = {v: str(k + 1) for k, v in enumerate(months)} + split = date.split(' ') + year = split[2] + month = mapper.get(split[1]) + day = split[0][:len(split[0]) - 2] + return year + '-' + month.zfill(2) + '-' + day.zfill(2) +``` + +### **Java** + + + +```java +class Solution { + public String reformatDate(String date) { + Map mapper = new HashMap<>(); + String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + for (int i = 0; i < months.length; ++i) { + mapper.put(months[i], i + 1); + } + String[] split = date.split(" "); + int year = Integer.parseInt(split[2]); + int month = mapper.get(split[1]); + int day = Integer.parseInt(split[0].substring(0, split[0].length() -2)); + return String.format("%d-%02d-%02d", year, month, day); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1508.leetcode1508 Range Sum of Sorted Subarray Sums-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1508.leetcode1508 Range Sum of Sorted Subarray Sums-zh.md" new file mode 100644 index 00000000..f8eadc04 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1508.leetcode1508 Range Sum of Sorted Subarray Sums-zh.md" @@ -0,0 +1,78 @@ +# [1508. 子数组和排序后的区间和](https://leetcode-cn.com/problems/range-sum-of-sorted-subarray-sums) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1508.Range%20Sum%20of%20Sorted%20Subarray%20Sums/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums ,它包含 n 个正整数。你需要计算所有非空连续子数组的和,并将它们按升序排序,得到一个新的包含 n * (n + 1) / 2 个数字的数组。

    + +

    请你返回在新数组中下标为 left 到 right (下标从 1 开始)的所有数字和(包括左右端点)。由于答案可能很大,请你将它对 10^9 + 7 取模后返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,4], n = 4, left = 1, right = 5
    +输出:13 
    +解释:所有的子数组和为 1, 3, 6, 10, 2, 5, 9, 3, 7, 4 。将它们升序排序后,我们得到新的数组 [1, 2, 3, 3, 4, 5, 6, 7, 9, 10] 。下标从 le = 1 到 ri = 5 的和为 1 + 2 + 3 + 3 + 4 = 13 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,3,4], n = 4, left = 3, right = 4
    +输出:6
    +解释:给定数组与示例 1 一样,所以新数组为 [1, 2, 3, 3, 4, 5, 6, 7, 9, 10] 。下标从 le = 3 到 ri = 4 的和为 3 + 3 = 6 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,2,3,4], n = 4, left = 1, right = 10
    +输出:50
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^3
    • +
    • nums.length == n
    • +
    • 1 <= nums[i] <= 100
    • +
    • 1 <= left <= right <= n * (n + 1) / 2
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1509.leetcode1509 Minimum Difference Between Largest and Smallest Value in Three Moves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1509.leetcode1509 Minimum Difference Between Largest and Smallest Value in Three Moves-zh.md" new file mode 100644 index 00000000..35d8844b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1509.leetcode1509 Minimum Difference Between Largest and Smallest Value in Three Moves-zh.md" @@ -0,0 +1,80 @@ +# [1509. 三次操作后最大值与最小值的最小差](https://leetcode-cn.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1509.Minimum%20Difference%20Between%20Largest%20and%20Smallest%20Value%20in%20Three%20Moves/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums ,每次操作你可以选择 nums 中的任意一个元素并将它改成任意值。

    + +

    请你返回三次操作后, nums 中最大值与最小值的差的最小值。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [5,3,2,4]
    +输出:0
    +解释:将数组 [5,3,2,4] 变成 [2,2,2,2].
    +最大值与最小值的差为 2-2 = 0 。
    + +

    示例 2:

    + +
    输入:nums = [1,5,0,10,14]
    +输出:1
    +解释:将数组 [1,5,0,10,14] 变成 [1,1,0,1,1] 。
    +最大值与最小值的差为 1-0 = 1 。
    +
    + +

    示例 3:

    + +
    输入:nums = [6,6,0,1,1,4,6]
    +输出:2
    +
    + +

    示例 4:

    + +
    输入:nums = [1,5,6,14,15]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • -10^9 <= nums[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1510.leetcode1510 Stone Game IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1510.leetcode1510 Stone Game IV-zh.md" new file mode 100644 index 00000000..4ade2c19 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1510.leetcode1510 Stone Game IV-zh.md" @@ -0,0 +1,95 @@ +# [1510. 石子游戏 IV](https://leetcode-cn.com/problems/stone-game-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1510.Stone%20Game%20IV/README_EN.md) + +## 题目描述 + + + +

    Alice 和 Bob 两个人轮流玩一个游戏,Alice 先手。

    + +

    一开始,有 n 个石子堆在一起。每个人轮流操作,正在操作的玩家可以从石子堆里拿走 任意 非零 平方数 个石子。

    + +

    如果石子堆里没有石子了,则无法操作的玩家输掉游戏。

    + +

    给你正整数 n ,且已知两个人都采取最优策略。如果 Alice 会赢得比赛,那么返回 True ,否则返回 False 。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 1
    +输出:true
    +解释:Alice 拿走 1 个石子并赢得胜利,因为 Bob 无法进行任何操作。
    + +

    示例 2:

    + +
    +输入:n = 2
    +输出:false
    +解释:Alice 只能拿走 1 个石子,然后 Bob 拿走最后一个石子并赢得胜利(2 -> 1 -> 0)。
    + +

    示例 3:

    + +
    +输入:n = 4
    +输出:true
    +解释:n 已经是一个平方数,Alice 可以一次全拿掉 4 个石子并赢得胜利(4 -> 0)。
    +
    + +

    示例 4:

    + +
    +输入:n = 7
    +输出:false
    +解释:当 Bob 采取最优策略时,Alice 无法赢得比赛。
    +如果 Alice 一开始拿走 4 个石子, Bob 会拿走 1 个石子,然后 Alice 只能拿走 1 个石子,Bob 拿走最后一个石子并赢得胜利(7 -> 3 -> 2 -> 1 -> 0)。
    +如果 Alice 一开始拿走 1 个石子, Bob 会拿走 4 个石子,然后 Alice 只能拿走 1 个石子,Bob 拿走最后一个石子并赢得胜利(7 -> 6 -> 2 -> 1 -> 0)。
    + +

    示例 5:

    + +
    +输入:n = 17
    +输出:false
    +解释:如果 Bob 采取最优策略,Alice 无法赢得胜利。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1511.leetcode1511 Customer Order Frequency-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1511.leetcode1511 Customer Order Frequency-zh.md" new file mode 100644 index 00000000..f9dc14ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1511.leetcode1511 Customer Order Frequency-zh.md" @@ -0,0 +1,133 @@ +# [1511. 消费者下单频率](https://leetcode-cn.com/problems/customer-order-frequency) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1511.Customer%20Order%20Frequency/README_EN.md) + +## 题目描述 + + + +

    表: Customers

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    +| country       | varchar |
    ++---------------+---------+
    +customer_id 是该表主键.
    +该表包含公司消费者的信息.
    +
    + +

     

    + +

    表: Product

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| description   | varchar |
    +| price         | int     |
    ++---------------+---------+
    +product_id 是该表主键.
    +该表包含公司产品的信息.
    +price 是本产品的花销.
    + +

     

    + +

    表: Orders

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| customer_id   | int     |
    +| product_id    | int     |
    +| order_date    | date    |
    +| quantity      | int     |
    ++---------------+---------+
    +order_id 是该表主键.
    +该表包含消费者下单的信息.
    +customer_id 是买了数量为"quantity", id为"product_id"产品的消费者的 id.
    +Order_date 是订单发货的日期, 格式为('YYYY-MM-DD').
    + +

     

    + +

    写一个 SQL 语句,  报告消费者的 id 和名字, 其中消费者在 2020 年 6 月和 7 月, 每月至少花费了$100.

    + +

    结果表无顺序要求.

    + +

    查询结果格式如下例所示.

    + +

     

    + +
    Customers
    ++--------------+-----------+-------------+
    +| customer_id  | name      | country     |
    ++--------------+-----------+-------------+
    +| 1            | Winston   | USA         |
    +| 2            | Jonathan  | Peru        |
    +| 3            | Moustafa  | Egypt       |
    ++--------------+-----------+-------------+
    +
    +Product
    ++--------------+-------------+-------------+
    +| product_id   | description | price       |
    ++--------------+-------------+-------------+
    +| 10           | LC Phone    | 300         |
    +| 20           | LC T-Shirt  | 10          |
    +| 30           | LC Book     | 45          |
    +| 40           | LC Keychain | 2           |
    ++--------------+-------------+-------------+
    +
    +Orders
    ++--------------+-------------+-------------+-------------+-----------+
    +| order_id     | customer_id | product_id  | order_date  | quantity  |
    ++--------------+-------------+-------------+-------------+-----------+
    +| 1            | 1           | 10          | 2020-06-10  | 1         |
    +| 2            | 1           | 20          | 2020-07-01  | 1         |
    +| 3            | 1           | 30          | 2020-07-08  | 2         |
    +| 4            | 2           | 10          | 2020-06-15  | 2         |
    +| 5            | 2           | 40          | 2020-07-01  | 10        |
    +| 6            | 3           | 20          | 2020-06-24  | 2         |
    +| 7            | 3           | 30          | 2020-06-25  | 2         |
    +| 9            | 3           | 30          | 2020-05-08  | 3         |
    ++--------------+-------------+-------------+-------------+-----------+
    +
    +Result 表:
    ++--------------+------------+
    +| customer_id  | name       |  
    ++--------------+------------+
    +| 1            | Winston    |
    ++--------------+------------+ 
    +Winston 在2020年6月花费了$300(300 * 1), 在7月花费了$100(10 * 1 + 45 * 2).
    +Jonathan 在2020年6月花费了$600(300 * 2), 在7月花费了$20(2 * 10).
    +Moustafa 在2020年6月花费了$110 (10 * 2 + 45 * 2), 在7月花费了$0.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + c.customer_id AS CUSTOMER_ID, + c.name AS NAME +FROM + Customers c, Product p, Orders o +WHERE + c.customer_id = o.customer_id +AND p.product_id = o.product_id +GROUP BY c.customer_id +HAVING sum(if(month(o.order_date)=6, price*quantity, 0)) >= 100 +AND sum(if(month(o.order_date)=7, price*quantity, 0)) >= 100; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1512.leetcode1512 Number of Good Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1512.leetcode1512 Number of Good Pairs-zh.md" new file mode 100644 index 00000000..737a93a8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1512.leetcode1512 Number of Good Pairs-zh.md" @@ -0,0 +1,124 @@ +# [1512. 好数对的数目](https://leetcode-cn.com/problems/number-of-good-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1512.Number%20of%20Good%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums

    + +

    如果一组数字 (i,j) 满足 nums[i] == nums[j]i < j ,就可以认为这是一组 好数对

    + +

    返回好数对的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,1,1,3]
    +输出:4
    +解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始
    +
    + +

    示例 2:

    + +
    输入:nums = [1,1,1,1]
    +输出:6
    +解释:数组中的每组数字都是好数对
    + +

    示例 3:

    + +
    输入:nums = [1,2,3]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + counter = collections.Counter(nums) + return sum([x * (x - 1) for x in counter.values()]) >> 1 +``` + +### **Java** + + + +```java +class Solution { + public int numIdenticalPairs(int[] nums) { + Map counter = new HashMap<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + int res = 0; + for (int n : counter.values()) { + res += n * (n - 1); + } + return res >> 1; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numIdenticalPairs(vector& nums) { + unordered_map counter; + for (int num : nums) { + ++counter[num]; + } + int res = 0; + for (auto &[num, n] : counter) { + res += n * (n - 1); + } + return res >> 1; + } +}; +``` + +### **Go** + +```go +func numIdenticalPairs(nums []int) int { + counter := make(map[int]int) + for _, num := range nums { + counter[num]++ + } + res := 0 + for _, n := range counter { + res += n * (n - 1) + } + return res >> 1 +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1513.leetcode1513 Number of Substrings With Only 1s-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1513.leetcode1513 Number of Substrings With Only 1s-zh.md" new file mode 100644 index 00000000..4156e2b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1513.leetcode1513 Number of Substrings With Only 1s-zh.md" @@ -0,0 +1,84 @@ +# [1513. 仅含 1 的子串数](https://leetcode-cn.com/problems/number-of-substrings-with-only-1s) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1513.Number%20of%20Substrings%20With%20Only%201s/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 s(仅由 '0' 和 '1' 组成的字符串)。

    + +

    返回所有字符都为 1 的子字符串的数目。

    + +

    由于答案可能很大,请你将它对 10^9 + 7 取模后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "0110111"
    +输出:9
    +解释:共有 9 个子字符串仅由 '1' 组成
    +"1" -> 5 次
    +"11" -> 3 次
    +"111" -> 1 次
    + +

    示例 2:

    + +
    输入:s = "101"
    +输出:2
    +解释:子字符串 "1" 在 s 中共出现 2 次
    +
    + +

    示例 3:

    + +
    输入:s = "111111"
    +输出:21
    +解释:每个子字符串都仅由 '1' 组成
    +
    + +

    示例 4:

    + +
    输入:s = "000"
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • s[i] == '0's[i] == '1'
    • +
    • 1 <= s.length <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1514.leetcode1514 Path with Maximum Probability-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1514.leetcode1514 Path with Maximum Probability-zh.md" new file mode 100644 index 00000000..1be27c94 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1514.leetcode1514 Path with Maximum Probability-zh.md" @@ -0,0 +1,87 @@ +# [1514. 概率最大的路径](https://leetcode-cn.com/problems/path-with-maximum-probability) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1514.Path%20with%20Maximum%20Probability/README_EN.md) + +## 题目描述 + + + +

    给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成,其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i]

    + +

    指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。

    + +

    如果不存在从 startend 的路径,请 返回 0 。只要答案与标准答案的误差不超过 1e-5 ,就会被视作正确答案。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
    +输出:0.25000
    +解释:从起点到终点有两条路径,其中一条的成功概率为 0.2 ,而另一条为 0.5 * 0.5 = 0.25
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
    +输出:0.30000
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
    +输出:0.00000
    +解释:节点 0 和 节点 2 之间不存在路径
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 10^4
    • +
    • 0 <= start, end < n
    • +
    • start != end
    • +
    • 0 <= a, b < n
    • +
    • a != b
    • +
    • 0 <= succProb.length == edges.length <= 2*10^4
    • +
    • 0 <= succProb[i] <= 1
    • +
    • 每两个节点之间最多有一条边
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1515.leetcode1515 Best Position for a Service Centre-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1515.leetcode1515 Best Position for a Service Centre-zh.md" new file mode 100644 index 00000000..96a9cb43 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1515.leetcode1515 Best Position for a Service Centre-zh.md" @@ -0,0 +1,100 @@ +# [1515. 服务中心的最佳位置](https://leetcode-cn.com/problems/best-position-for-a-service-centre) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1515.Best%20Position%20for%20a%20Service%20Centre/README_EN.md) + +## 题目描述 + + + +

    一家快递公司希望在新城市建立新的服务中心。公司统计了该城市所有客户在二维地图上的坐标,并希望能够以此为依据为新的服务中心选址:使服务中心 到所有客户的欧几里得距离的总和最小

    + +

    给你一个数组 positions ,其中 positions[i] = [xi, yi] 表示第 i 个客户在二维地图上的位置,返回到所有客户的 欧几里得距离的最小总和 。

    + +

    换句话说,请你为服务中心选址,该位置的坐标 [xcentre, ycentre] 需要使下面的公式取到最小值:

    + +

    + +

    与真实值误差在 10^-5 之内的答案将被视作正确答案。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:positions = [[0,1],[1,0],[1,2],[2,1]]
    +输出:4.00000
    +解释:如图所示,你可以选 [xcentre, ycentre] = [1, 1] 作为新中心的位置,这样一来到每个客户的距离就都是 1,所有距离之和为 4 ,这也是可以找到的最小值。
    +
    + +

    示例 2:

    + +

    + +
    输入:positions = [[1,1],[3,3]]
    +输出:2.82843
    +解释:欧几里得距离可能的最小总和为 sqrt(2) + sqrt(2) = 2.82843
    +
    + +

    示例 3:

    + +
    输入:positions = [[1,1]]
    +输出:0.00000
    +
    + +

    示例 4:

    + +
    输入:positions = [[1,1],[0,0],[2,0]]
    +输出:2.73205
    +解释:乍一看,你可能会将中心定在 [1, 0] 并期待能够得到最小总和,但是如果选址在 [1, 0] 距离总和为 3
    +如果将位置选在 [1.0, 0.5773502711] ,距离总和将会变为 2.73205
    +当心精度问题!
    +
    + +

    示例 5:

    + +
    输入:positions = [[0,1],[3,2],[4,5],[7,6],[8,9],[11,1],[2,12]]
    +输出:32.94036
    +解释:你可以用 [4.3460852395, 4.9813795505] 作为新中心的位置
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= positions.length <= 50
    • +
    • positions[i].length == 2
    • +
    • 0 <= positions[i][0], positions[i][1] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1516.leetcode1516 Move Sub-Tree of N-Ary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1516.leetcode1516 Move Sub-Tree of N-Ary Tree-zh.md" new file mode 100644 index 00000000..e0e7cc1c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1516.leetcode1516 Move Sub-Tree of N-Ary Tree-zh.md" @@ -0,0 +1,126 @@ +# [1516. 移动 N 叉树的子树](https://leetcode-cn.com/problems/move-sub-tree-of-n-ary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1516.Move%20Sub-Tree%20of%20N-Ary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵没有重复值的 N 叉树的根节点 root ,以及其中的两个节点 p 和 q

    + +

    移动节点 p 及其子树,使节点 p 成为节点 q 的直接子节点。如果 p 已经是 q 的直接子节点,则请勿改动任何节点。节点 p 必须是节点 q 的子节点列表的最后一项。

    + +

    返回改动后的树的根节点

    + +

     

    + +

    节点 p 和 q 可能是下列三种情况之一:

    + +
      +
    1. 节点 q 在节点 p 的子树中。
    2. +
    3. 节点 p 在节点 q 的子树中。
    4. +
    5. 节点 p 不在节点 q 的子树中,且节点 q 也不在节点 p 的子树中。
    6. +
    + +

    在第 2 种和第 3 种情况中,你只需要移动 p (及其子树),使 p 成为 q 的子节点。但是在第 1 种情况中,树的节点可能会断连,因此你还需要重新连接这些节点。请在解题前仔细阅读示例。

    + +

     

    + +

    N 叉树的输入序列以层序遍历的形式给出,每组子节点用 null 分隔(见示例)。

    + +

    + +

    例如,上面的树会被序列化为 [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 4, q = 1
    +输出: [1,null,2,3,4,null,5,null,6,null,7,8]
    +解释: 该示例属于第二种情况,节点 p 在节点 q 的子树中。我们可以移动节点 p 及其子树,使 p 成为节点 q 的直接子节点。
    +注意,节点 4 是节点 1 的最后一个子节点。
    + +

    示例 2:

    + +

    + +
    输入: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 7, q = 4
    +输出: [1,null,2,3,null,4,5,null,6,null,7,8]
    +解释: 节点 7 已经是节点 4 的直接子节点,因此我们不改动任何节点。
    +
    + +

    示例 3:

    + +

    + +
    输入: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 3, q = 8
    +输出: [1,null,2,null,4,5,null,7,8,null,null,null,3,null,6]
    +解释: 该示例属于第三种情况,节点 p 不在节点 q 的子树中,反之亦然。我们可以移动节点 3 及其子树,使之成为节点 8 的子节点。
    +
    + +

    示例 4:

    + +

    + +
    输入: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 2, q = 7
    +输出: [1,null,7,3,null,2,null,6,null,4,5,null,null,8]
    +解释: 节点 q 在节点 p 的子树中,因此该示例属于第一种情况。
    +第一步,我们移动节点 p (及其所有子树,除节点 q 的子树外),并将其加入节点 q 的子节点列表中。
    +然后我们发现树已断连,你需要重新连接节点 q 来代替节点 p,如图所示。
    +
    + +

    示例 5:

    + +

    + +
    输入: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 1, q = 2
    +输出: [2,null,4,5,1,null,7,8,null,null,3,null,null,null,6]
    +解释: 节点 q 在节点 p 的子树中,因此该示例属于第一种情况。
    +第一步,我们移动节点 p (及其所有子树,除节点 q 的子树外),并将其加入节点 q 的子节点列表中。
    +因为节点 p 是原树的根节点,因此节点 q 代替之成为新树的根节点。
    + +

     

    + +

    提示:

    + +
      +
    • 节点的总数在 [2, 1000] 间。
    • +
    • 每个节点都有唯一的值。
    • +
    • p != null
    • +
    • q != null
    • +
    • p 和 q 是两个不同的节点(即 p != q )。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1517.leetcode1517 Find Users With Valid E-Mails-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1517.leetcode1517 Find Users With Valid E-Mails-zh.md" new file mode 100644 index 00000000..c9d6a37e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1517.leetcode1517 Find Users With Valid E-Mails-zh.md" @@ -0,0 +1,80 @@ +# [1517. 查找拥有有效邮箱的用户](https://leetcode-cn.com/problems/find-users-with-valid-e-mails) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1517.Find%20Users%20With%20Valid%20E-Mails/README_EN.md) + +## 题目描述 + + + +

    用户表: Users

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user_id       | int     |
    +| name          | varchar |
    +| mail          | varchar | 
    ++---------------+---------+
    +user_id (用户 ID)是该表的主键。
    +这个表包含用户在某网站上注册的信息。有些邮箱是无效的。
    + +

     

    + +

    写一条 SQL 语句,查询拥有有效邮箱的用户。

    + +

    有效的邮箱包含符合下列条件的前缀名和域名:

    + +
      +
    • 前缀名是包含字母(大写或小写)、数字、下划线 '_'、句点 '.' 和/或横杠 '-' 的字符串。前缀名必须以字母开头。
    • +
    • 域名是 '@leetcode.com' 。
    • +
    + +

    按任意顺序返回结果表。

    + +

     

    + +

    查询格式如下所示:

    + +
    +Users
    ++---------+-----------+-------------------------+
    +| user_id | name      | mail                    |
    ++---------+-----------+-------------------------+
    +| 1       | Winston   | winston@leetcode.com    |
    +| 2       | Jonathan  | jonathanisgreat         |
    +| 3       | Annabelle | bella-@leetcode.com     |
    +| 4       | Sally     | sally.come@leetcode.com |
    +| 5       | Marwan    | quarz#2020@leetcode.com |
    +| 6       | David     | david69@gmail.com       |
    +| 7       | Shapiro   | .shapo@leetcode.com     |
    ++---------+-----------+-------------------------+
    +
    +结果表:
    ++---------+-----------+-------------------------+
    +| user_id | name      | mail                    |
    ++---------+-----------+-------------------------+
    +| 1       | Winston   | winston@leetcode.com    |
    +| 3       | Annabelle | bella-@leetcode.com     |
    +| 4       | Sally     | sally.come@leetcode.com |
    ++---------+-----------+-------------------------+
    +2 号用户的邮箱没有域名。
    +5 号用户的邮箱包含非法字符 #。
    +6 号用户的邮箱的域名不是 leetcode。
    +7 号用户的邮箱以句点(.)开头。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1518.leetcode1518 Water Bottles-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1518.leetcode1518 Water Bottles-zh.md" new file mode 100644 index 00000000..ae937772 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1518.leetcode1518 Water Bottles-zh.md" @@ -0,0 +1,87 @@ +# [1518. 换酒问题](https://leetcode-cn.com/problems/water-bottles) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1518.Water%20Bottles/README_EN.md) + +## 题目描述 + + + +

    小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。

    + +

    如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。

    + +

    请你计算 最多 能喝到多少瓶酒。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:numBottles = 9, numExchange = 3
    +输出:13
    +解释:你可以用 3 个空酒瓶兑换 1 瓶酒。
    +所以最多能喝到 9 + 3 + 1 = 13 瓶酒。
    +
    + +

    示例 2:

    + +

    + +
    输入:numBottles = 15, numExchange = 4
    +输出:19
    +解释:你可以用 4 个空酒瓶兑换 1 瓶酒。
    +所以最多能喝到 15 + 3 + 1 = 19 瓶酒。
    +
    + +

    示例 3:

    + +
    输入:numBottles = 5, numExchange = 5
    +输出:6
    +
    + +

    示例 4:

    + +
    输入:numBottles = 2, numExchange = 3
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= numBottles <= 100
    • +
    • 2 <= numExchange <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1519.leetcode1519 Number of Nodes in the Sub-Tree With the Same Label-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1519.leetcode1519 Number of Nodes in the Sub-Tree With the Same Label-zh.md" new file mode 100644 index 00000000..7cbe15e3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1519.leetcode1519 Number of Nodes in the Sub-Tree With the Same Label-zh.md" @@ -0,0 +1,104 @@ +# [1519. 子树中标签相同的节点数](https://leetcode-cn.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1519.Number%20of%20Nodes%20in%20the%20Sub-Tree%20With%20the%20Same%20Label/README_EN.md) + +## 题目描述 + + + +

    给你一棵树(即,一个连通的无环无向图),这棵树由编号从 0  到 n - 1 的 n 个节点组成,且恰好有 n - 1edges 。树的根节点为节点 0 ,树上的每一个节点都有一个标签,也就是字符串 labels 中的一个小写字符(编号为 i 的 节点的标签就是 labels[i]

    + +

    边数组 edgesedges[i] = [ai, bi] 的形式给出,该格式表示节点 aibi 之间存在一条边。

    + +

    返回一个大小为 n 的数组,其中 ans[i] 表示第 i 个节点的子树中与节点 i 标签相同的节点数。

    + +

    T 中的子树是由 T 中的某个节点及其所有后代节点组成的树。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
    +输出:[2,1,1,1,1,1,1]
    +解释:节点 0 的标签为 'a' ,以 'a' 为根节点的子树中,节点 2 的标签也是 'a' ,因此答案为 2 。注意树中的每个节点都是这棵子树的一部分。
    +节点 1 的标签为 'b' ,节点 1 的子树包含节点 1、4 和 5,但是节点 4、5 的标签与节点 1 不同,故而答案为 1(即,该节点本身)。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
    +输出:[4,2,1,1]
    +解释:节点 2 的子树中只有节点 2 ,所以答案为 1 。
    +节点 3 的子树中只有节点 3 ,所以答案为 1 。
    +节点 1 的子树中包含节点 1 和 2 ,标签都是 'b' ,因此答案为 2 。
    +节点 0 的子树中包含节点 0、1、2 和 3,标签都是 'b',因此答案为 4 。
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
    +输出:[3,2,1,1,1]
    +
    + +

    示例 4:

    + +
    输入:n = 6, edges = [[0,1],[0,2],[1,3],[3,4],[4,5]], labels = "cbabaa"
    +输出:[1,2,1,1,2,1]
    +
    + +

    示例 5:

    + +
    输入:n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], labels = "aaabaaa"
    +输出:[6,5,4,1,3,2,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • edges.length == n - 1
    • +
    • edges[i].length == 2
    • +
    • 0 <= ai, bi < n
    • +
    • ai != bi
    • +
    • labels.length == n
    • +
    • labels 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1520.leetcode1520 Maximum Number of Non-Overlapping Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1520.leetcode1520 Maximum Number of Non-Overlapping Substrings-zh.md" new file mode 100644 index 00000000..6d1fe4c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1520.leetcode1520 Maximum Number of Non-Overlapping Substrings-zh.md" @@ -0,0 +1,83 @@ +# [1520. 最多的不重叠子字符串](https://leetcode-cn.com/problems/maximum-number-of-non-overlapping-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1520.Maximum%20Number%20of%20Non-Overlapping%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给你一个只包含小写字母的字符串 s ,你需要找到 s 中最多数目的非空子字符串,满足如下条件:

    + +
      +
    1. 这些字符串之间互不重叠,也就是说对于任意两个子字符串 s[i..j] 和 s[k..l] ,要么 j < k 要么 i > l 。
    2. +
    3. 如果一个子字符串包含字符 char ,那么 s 中所有 char 字符都应该在这个子字符串中。
    4. +
    + +

    请你找到满足上述条件的最多子字符串数目。如果有多个解法有相同的子字符串数目,请返回这些子字符串总长度最小的一个解。可以证明最小总长度解是唯一的。

    + +

    请注意,你可以以 任意 顺序返回最优解的子字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "adefaddaccc"
    +输出:["e","f","ccc"]
    +解释:下面为所有满足第二个条件的子字符串:
    +[
    +  "adefaddaccc"
    +  "adefadda",
    +  "ef",
    +  "e",
    +  "f",
    +  "ccc",
    +]
    +如果我们选择第一个字符串,那么我们无法再选择其他任何字符串,所以答案为 1 。如果我们选择 "adefadda" ,剩下子字符串中我们只可以选择 "ccc" ,它是唯一不重叠的子字符串,所以答案为 2 。同时我们可以发现,选择 "ef" 不是最优的,因为它可以被拆分成 2 个子字符串。所以最优解是选择 ["e","f","ccc"] ,答案为 3 。不存在别的相同数目子字符串解。
    +
    + +

    示例 2:

    + +
    输入:s = "abbaccd"
    +输出:["d","bb","cc"]
    +解释:注意到解 ["d","abba","cc"] 答案也为 3 ,但它不是最优解,因为它的总长度更长。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1521.leetcode1521 Find a Value of a Mysterious Function Closest to Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1521.leetcode1521 Find a Value of a Mysterious Function Closest to Target-zh.md" new file mode 100644 index 00000000..51b51ebc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1521.leetcode1521 Find a Value of a Mysterious Function Closest to Target-zh.md" @@ -0,0 +1,78 @@ +# [1521. 找到最接近目标值的函数值](https://leetcode-cn.com/problems/find-a-value-of-a-mysterious-function-closest-to-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1521.Find%20a%20Value%20of%20a%20Mysterious%20Function%20Closest%20to%20Target/README_EN.md) + +## 题目描述 + + + +

    + +

    Winston 构造了一个如上所示的函数 func 。他有一个整数数组 arr 和一个整数 target ,他想找到让 |func(arr, l, r) - target| 最小的 l 和 r 。

    + +

    请你返回 |func(arr, l, r) - target| 的最小值。

    + +

    请注意, func 的输入参数 l 和 r 需要满足 0 <= l, r < arr.length 。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [9,12,3,7,15], target = 5
    +输出:2
    +解释:所有可能的 [l,r] 数对包括 [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston 得到的相应结果为 [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0] 。最接近 5 的值是 7 和 3,所以最小差值为 2 。
    +
    + +

    示例 2:

    + +
    输入:arr = [1000000,1000000,1000000], target = 1
    +输出:999999
    +解释:Winston 输入函数的所有可能 [l,r] 数对得到的函数值都为 1000000 ,所以最小差值为 999999 。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,2,4,8,16], target = 0
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^6
    • +
    • 0 <= target <= 10^7
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1522.leetcode1522 Diameter of N-Ary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1522.leetcode1522 Diameter of N-Ary Tree-zh.md" new file mode 100644 index 00000000..35344cba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1522.leetcode1522 Diameter of N-Ary Tree-zh.md" @@ -0,0 +1,82 @@ +# [1522. N 叉树的直径](https://leetcode-cn.com/problems/diameter-of-n-ary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1522.Diameter%20of%20N-Ary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵 N 叉树的根节点 root ,计算这棵树的直径长度。

    + +

    N 叉树的直径指的是树中任意两个节点间路径中 最长 路径的长度。这条路径可能经过根节点,也可能不经过根节点。

    + +

    (N 叉树的输入序列以层序遍历的形式给出,每组子节点用 null 分隔)

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,null,3,2,4,null,5,6]
    +输出:3
    +解释:直径如图中红线所示。
    + +

    示例 2:

    + +

    + +
    +输入:root = [1,null,2,null,3,4,null,5,null,6]
    +输出:4
    +
    + +

    示例 3:

    + +

    + +
    +输入: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    +输出: 7
    +
    + +

     

    + +

    提示:

    + +
      +
    • N 叉树的深度小于或等于 1000 。
    • +
    • 节点的总个数在 [0, 10^4] 间。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1523.leetcode1523 Count Odd Numbers in an Interval Range-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1523.leetcode1523 Count Odd Numbers in an Interval Range-zh.md" new file mode 100644 index 00000000..722515b1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1523.leetcode1523 Count Odd Numbers in an Interval Range-zh.md" @@ -0,0 +1,62 @@ +# [1523. 在区间范围内统计奇数数目](https://leetcode-cn.com/problems/count-odd-numbers-in-an-interval-range) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1523.Count%20Odd%20Numbers%20in%20an%20Interval%20Range/README_EN.md) + +## 题目描述 + + + +

    给你两个非负整数 low 和 high 。请你返回 low  high 之间(包括二者)奇数的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:low = 3, high = 7
    +输出:3
    +解释:3 到 7 之间奇数数字为 [3,5,7] 。
    + +

    示例 2:

    + +
    输入:low = 8, high = 10
    +输出:1
    +解释:8 到 10 之间奇数数字为 [9] 。
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= low <= high <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1524.leetcode1524 Number of Sub-arrays With Odd Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1524.leetcode1524 Number of Sub-arrays With Odd Sum-zh.md" new file mode 100644 index 00000000..dff8c634 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1524.leetcode1524 Number of Sub-arrays With Odd Sum-zh.md" @@ -0,0 +1,89 @@ +# [1524. 和为奇数的子数组数目](https://leetcode-cn.com/problems/number-of-sub-arrays-with-odd-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1524.Number%20of%20Sub-arrays%20With%20Odd%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr 。请你返回和为 奇数 的子数组数目。

    + +

    由于答案可能会很大,请你将结果对 10^9 + 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,3,5]
    +输出:4
    +解释:所有的子数组为 [[1],[1,3],[1,3,5],[3],[3,5],[5]] 。
    +所有子数组的和为 [1,4,9,3,8,5].
    +奇数和包括 [1,9,3,5] ,所以答案为 4 。
    +
    + +

    示例 2 :

    + +
    输入:arr = [2,4,6]
    +输出:0
    +解释:所有子数组为 [[2],[2,4],[2,4,6],[4],[4,6],[6]] 。
    +所有子数组和为 [2,6,12,4,10,6] 。
    +所有子数组和都是偶数,所以答案为 0 。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,2,3,4,5,6,7]
    +输出:16
    +
    + +

    示例 4:

    + +
    输入:arr = [100,100,99,99]
    +输出:4
    +
    + +

    示例 5:

    + +
    输入:arr = [7]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1525.leetcode1525 Number of Good Ways to Split a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1525.leetcode1525 Number of Good Ways to Split a String-zh.md" new file mode 100644 index 00000000..094bc091 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1525.leetcode1525 Number of Good Ways to Split a String-zh.md" @@ -0,0 +1,84 @@ +# [1525. 字符串的好分割数目](https://leetcode-cn.com/problems/number-of-good-ways-to-split-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1525.Number%20of%20Good%20Ways%20to%20Split%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,一个分割被称为 「好分割」 当它满足:将 s 分割成 2 个字符串 p 和 q ,它们连接起来等于 s 且 p 和 q 中不同字符的数目相同。

    + +

    请你返回 s 中好分割的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "aacaba"
    +输出:2
    +解释:总共有 5 种分割字符串 "aacaba" 的方法,其中 2 种是好分割。
    +("a", "acaba") 左边字符串和右边字符串分别包含 1 个和 3 个不同的字符。
    +("aa", "caba") 左边字符串和右边字符串分别包含 1 个和 3 个不同的字符。
    +("aac", "aba") 左边字符串和右边字符串分别包含 2 个和 2 个不同的字符。这是一个好分割。
    +("aaca", "ba") 左边字符串和右边字符串分别包含 2 个和 2 个不同的字符。这是一个好分割。
    +("aacab", "a") 左边字符串和右边字符串分别包含 3 个和 1 个不同的字符。
    +
    + +

    示例 2:

    + +
    输入:s = "abcd"
    +输出:1
    +解释:好分割为将字符串分割成 ("ab", "cd") 。
    +
    + +

    示例 3:

    + +
    输入:s = "aaaaa"
    +输出:4
    +解释:所有分割都是好分割。
    + +

    示例 4:

    + +
    输入:s = "acbadbaada"
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • s 只包含小写英文字母。
    • +
    • 1 <= s.length <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1526.leetcode1526 Minimum Number of Increments on Subarrays to Form a Target Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1526.leetcode1526 Minimum Number of Increments on Subarrays to Form a Target Array-zh.md" new file mode 100644 index 00000000..113599a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1526.leetcode1526 Minimum Number of Increments on Subarrays to Form a Target Array-zh.md" @@ -0,0 +1,91 @@ +# [1526. 形成目标数组的子数组最少增加次数](https://leetcode-cn.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1526.Minimum%20Number%20of%20Increments%20on%20Subarrays%20to%20Form%20a%20Target%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 target 和一个数组 initial ,initial 数组与 target  数组有同样的维度,且一开始全部为 0 。

    + +

    请你返回从 initial 得到  target 的最少操作次数,每次操作需遵循以下规则:

    + +
      +
    • initial 中选择 任意 子数组,并将子数组中每个元素增加 1 。
    • +
    + +

    答案保证在 32 位有符号整数以内。

    + +

     

    + +

    示例 1:

    + +
    输入:target = [1,2,3,2,1]
    +输出:3
    +解释:我们需要至少 3 次操作从 intial 数组得到 target 数组。
    +[0,0,0,0,0] 将下标为 0 到 4 的元素(包含二者)加 1 。
    +[1,1,1,1,1] 将下标为 1 到 3 的元素(包含二者)加 1 。
    +[1,2,2,2,1] 将下表为 2 的元素增加 1 。
    +[1,2,3,2,1] 得到了目标数组。
    +
    + +

    示例 2:

    + +
    输入:target = [3,1,1,2]
    +输出:4
    +解释:(initial)[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] (target) 。
    +
    + +

    示例 3:

    + +
    输入:target = [3,1,5,4,2]
    +输出:7
    +解释:(initial)[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] 
    +                                  -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2] (target)。
    +
    + +

    示例 4:

    + +
    输入:target = [1,1,1,1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target.length <= 10^5
    • +
    • 1 <= target[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1527.leetcode1527 Patients With a Condition-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1527.leetcode1527 Patients With a Condition-zh.md" new file mode 100644 index 00000000..53eb1bba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1527.leetcode1527 Patients With a Condition-zh.md" @@ -0,0 +1,66 @@ +# [1527. 患某种疾病的患者](https://leetcode-cn.com/problems/patients-with-a-condition) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1527.Patients%20With%20a%20Condition/README_EN.md) + +## 题目描述 + + + +

    患者信息表: Patients

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| patient_id   | int     |
    +| patient_name | varchar |
    +| conditions   | varchar |
    ++--------------+---------+
    +patient_id (患者 ID)是该表的主键。
    +'conditions' (疾病)包含 0 个或以上的疾病代码,以空格分隔。
    +这个表包含医院中患者的信息。
    + +

     

    + +

    写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1 。

    + +

    按任意顺序返回结果表。

    + +

    查询结果格式如下示例所示:

    + +

     

    + +
    Patients
    ++------------+--------------+--------------+
    +| patient_id | patient_name | conditions   |
    ++------------+--------------+--------------+
    +| 1          | Daniel       | YFEV COUGH   |
    +| 2          | Alice        |              |
    +| 3          | Bob          | DIAB100 MYOP |
    +| 4          | George       | ACNE DIAB100 |
    +| 5          | Alain        | DIAB201      |
    ++------------+--------------+--------------+
    +
    +结果表:
    ++------------+--------------+--------------+
    +| patient_id | patient_name | conditions   |
    ++------------+--------------+--------------+
    +| 3          | Bob          | DIAB100 MYOP |
    +| 4          | George       | ACNE DIAB100 | 
    ++------------+--------------+--------------+
    +Bob 和 George 都患有代码以 DIAB1 开头的疾病。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1528.leetcode1528 Shuffle String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1528.leetcode1528 Shuffle String-zh.md" new file mode 100644 index 00000000..f16a0b2f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1528.leetcode1528 Shuffle String-zh.md" @@ -0,0 +1,92 @@ +# [1528. 重新排列字符串](https://leetcode-cn.com/problems/shuffle-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1528.Shuffle%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个 长度相同 的整数数组 indices

    + +

    请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。

    + +

    返回重新排列后的字符串。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
    +输出:"leetcode"
    +解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
    +
    + +

    示例 2:

    + +
    输入:s = "abc", indices = [0,1,2]
    +输出:"abc"
    +解释:重新排列后,每个字符都还留在原来的位置上。
    +
    + +

    示例 3:

    + +
    输入:s = "aiohn", indices = [3,1,4,2,0]
    +输出:"nihao"
    +
    + +

    示例 4:

    + +
    输入:s = "aaiougrt", indices = [4,0,2,6,7,3,1,5]
    +输出:"arigatou"
    +
    + +

    示例 5:

    + +
    输入:s = "art", indices = [1,0,2]
    +输出:"rat"
    +
    + +

     

    + +

    提示:

    + +
      +
    • s.length == indices.length == n
    • +
    • 1 <= n <= 100
    • +
    • s 仅包含小写英文字母。
    • +
    • 0 <= indices[i] < n
    • +
    • indices 的所有的值都是唯一的(也就是说,indices 是整数 0n - 1 形成的一组排列)。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1529.leetcode1529 Bulb Switcher IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1529.leetcode1529 Bulb Switcher IV-zh.md" new file mode 100644 index 00000000..21c72e86 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1529.leetcode1529 Bulb Switcher IV-zh.md" @@ -0,0 +1,93 @@ +# [1529. 灯泡开关 IV](https://leetcode-cn.com/problems/bulb-switcher-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1529.Bulb%20Switcher%20IV/README_EN.md) + +## 题目描述 + + + +

    房间中有 n 个灯泡,编号从 0n-1 ,自左向右排成一行。最开始的时候,所有的灯泡都是 着的。

    + +

    请你设法使得灯泡的开关状态和 target 描述的状态一致,其中 target[i] 等于 1i 个灯泡是开着的,等于 0 意味着第 i 个灯是关着的。

    + +

    有一个开关可以用于翻转灯泡的状态,翻转操作定义如下:

    + +
      +
    • 选择当前配置下的任意一个灯泡(下标为 i
    • +
    • 翻转下标从 in-1 的每个灯泡
    • +
    + +

    翻转时,如果灯泡的状态为 0 就变为 1,为 1 就变为 0

    + +

    返回达成 target 描述的状态所需的 最少 翻转次数。

    + +

     

    + +

    示例 1:

    + +
    输入:target = "10111"
    +输出:3
    +解释:初始配置 "00000".
    +从第 3 个灯泡(下标为 2)开始翻转 "00000" -> "00111"
    +从第 1 个灯泡(下标为 0)开始翻转 "00111" -> "11000"
    +从第 2 个灯泡(下标为 1)开始翻转 "11000" -> "10111"
    +至少需要翻转 3 次才能达成 target 描述的状态
    + +

    示例 2:

    + +
    输入:target = "101"
    +输出:3
    +解释:"000" -> "111" -> "100" -> "101".
    +
    + +

    示例 3:

    + +
    输入:target = "00000"
    +输出:0
    +
    + +

    示例 4:

    + +
    输入:target = "001011101"
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target.length <= 10^5
    • +
    • target[i] == '0' 或者 target[i] == '1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1530.leetcode1530 Number of Good Leaf Nodes Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1530.leetcode1530 Number of Good Leaf Nodes Pairs-zh.md" new file mode 100644 index 00000000..e7b47a8d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1530.leetcode1530 Number of Good Leaf Nodes Pairs-zh.md" @@ -0,0 +1,95 @@ +# [1530. 好叶子节点对的数量](https://leetcode-cn.com/problems/number-of-good-leaf-nodes-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1530.Number%20of%20Good%20Leaf%20Nodes%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给你二叉树的根节点 root 和一个整数 distance

    + +

    如果二叉树中两个 节点之间的 最短路径长度 小于或者等于 distance ,那它们就可以构成一组 好叶子节点对

    + +

    返回树中 好叶子节点对的数量

    + +

     

    + +

    示例 1:

    + +

     

    + +

    + +
    输入:root = [1,2,3,null,4], distance = 3
    +输出:1
    +解释:树的叶节点是 3 和 4 ,它们之间的最短路径的长度是 3 。这是唯一的好叶子节点对。
    +
    + +

    示例 2:

    + +

    + +
    输入:root = [1,2,3,4,5,6,7], distance = 3
    +输出:2
    +解释:好叶子节点对为 [4,5] 和 [6,7] ,最短路径长度都是 2 。但是叶子节点对 [4,6] 不满足要求,因为它们之间的最短路径长度为 4 。
    +
    + +

    示例 3:

    + +
    输入:root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
    +输出:1
    +解释:唯一的好叶子节点对是 [2,5] 。
    +
    + +

    示例 4:

    + +
    输入:root = [100], distance = 1
    +输出:0
    +
    + +

    示例 5:

    + +
    输入:root = [1,1,1], distance = 2
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • tree 的节点数在 [1, 2^10] 范围内。
    • +
    • 每个节点的值都在 [1, 100] 之间。
    • +
    • 1 <= distance <= 10
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1531.leetcode1531 String Compression II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1531.leetcode1531 String Compression II-zh.md" new file mode 100644 index 00000000..14bb8038 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1531.leetcode1531 String Compression II-zh.md" @@ -0,0 +1,78 @@ +# [1531. 压缩字符串 II](https://leetcode-cn.com/problems/string-compression-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1531.String%20Compression%20II/README_EN.md) + +## 题目描述 + + + +

    行程长度编码 是一种常用的字符串压缩方法,它将连续的相同字符(重复 2 次或更多次)替换为字符和表示字符计数的数字(行程长度)。例如,用此方法压缩字符串 "aabccc" ,将 "aa" 替换为 "a2""ccc" 替换为` "c3" 。因此压缩后的字符串变为 "a2bc3"

    + +

    注意,本问题中,压缩时没有在单个字符后附加计数 '1'

    + +

    给你一个字符串 s 和一个整数 k 。你需要从字符串 s 中删除最多 k 个字符,以使 s 的行程长度编码长度最小。

    + +

    请你返回删除最多 k 个字符后,s 行程长度编码的最小长度

    + +

     

    + +

    示例 1:

    + +
    输入:s = "aaabcccd", k = 2
    +输出:4
    +解释:在不删除任何内容的情况下,压缩后的字符串是 "a3bc3d" ,长度为 6 。最优的方案是删除 'b' 和 'd',这样一来,压缩后的字符串为 "a3c3" ,长度是 4 。
    + +

    示例 2:

    + +
    输入:s = "aabbaa", k = 2
    +输出:2
    +解释:如果删去两个 'b' 字符,那么压缩后的字符串是长度为 2 的 "a4" 。
    +
    + +

    示例 3:

    + +
    输入:s = "aaaaaaaaaaa", k = 0
    +输出:3
    +解释:由于 k 等于 0 ,不能删去任何字符。压缩后的字符串是 "a11" ,长度为 3 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • 0 <= k <= s.length
    • +
    • s 仅包含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1532.leetcode1532 The Most Recent Three Orders-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1532.leetcode1532 The Most Recent Three Orders-zh.md" new file mode 100644 index 00000000..e467252b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1532.leetcode1532 The Most Recent Three Orders-zh.md" @@ -0,0 +1,118 @@ +# [1532. 最近的三笔订单](https://leetcode-cn.com/problems/the-most-recent-three-orders) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1532.The%20Most%20Recent%20Three%20Orders/README_EN.md) + +## 题目描述 + + + +

    表:Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    ++---------------+---------+
    +customer_id 是该表主键
    +该表包含消费者的信息
    +
    + +

     

    + +

    表:Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| cost          | int     |
    ++---------------+---------+
    +order_id 是该表主键
    +该表包含id为customer_id的消费者的订单信息
    +每一个消费者 每天一笔订单
    +
    + +

     

    + +

    写一个 SQL 语句,找到每个用户的最近三笔订单。如果用户的订单少于 3 笔,则返回他的全部订单。

    + +

    返回的结果按照 customer_name 升序排列。如果排名有相同,则继续按照 customer_id 升序排列。如果排名还有相同,则继续按照 order_date 降序排列。

    + +

    查询结果格式如下例所示:

    + +
    +Customers
    ++-------------+-----------+
    +| customer_id | name      |
    ++-------------+-----------+
    +| 1           | Winston   |
    +| 2           | Jonathan  |
    +| 3           | Annabelle |
    +| 4           | Marwan    |
    +| 5           | Khaled    |
    ++-------------+-----------+
    +
    +Orders
    ++----------+------------+-------------+------+
    +| order_id | order_date | customer_id | cost |
    ++----------+------------+-------------+------+
    +| 1        | 2020-07-31 | 1           | 30   |
    +| 2        | 2020-07-30 | 2           | 40   |
    +| 3        | 2020-07-31 | 3           | 70   |
    +| 4        | 2020-07-29 | 4           | 100  |
    +| 5        | 2020-06-10 | 1           | 1010 |
    +| 6        | 2020-08-01 | 2           | 102  |
    +| 7        | 2020-08-01 | 3           | 111  |
    +| 8        | 2020-08-03 | 1           | 99   |
    +| 9        | 2020-08-07 | 2           | 32   |
    +| 10       | 2020-07-15 | 1           | 2    |
    ++----------+------------+-------------+------+
    +
    +Result table:
    ++---------------+-------------+----------+------------+
    +| customer_name | customer_id | order_id | order_date |
    ++---------------+-------------+----------+------------+
    +| Annabelle     | 3           | 7        | 2020-08-01 |
    +| Annabelle     | 3           | 3        | 2020-07-31 |
    +| Jonathan      | 2           | 9        | 2020-08-07 |
    +| Jonathan      | 2           | 6        | 2020-08-01 |
    +| Jonathan      | 2           | 2        | 2020-07-30 |
    +| Marwan        | 4           | 4        | 2020-07-29 |
    +| Winston       | 1           | 8        | 2020-08-03 |
    +| Winston       | 1           | 1        | 2020-07-31 |
    +| Winston       | 1           | 10       | 2020-07-15 |
    ++---------------+-------------+----------+------------+
    +Winston 有 4 笔订单, 排除了 "2020-06-10" 的订单, 因为它是最老的订单。
    +Annabelle 只有 2 笔订单, 全部返回。
    +Jonathan 恰好有 3 笔订单。
    +Marwan 只有 1 笔订单。
    +结果表我们按照 customer_name 升序排列,customer_id 升序排列,order_date 降序排列。
    +
    + +

     

    + +

    进阶:

    + +
      +
    • 你能写出来最近 n 笔订单的通用解决方案吗?
    • +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1533.leetcode1533 Find the Index of the Large Integer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1533.leetcode1533 Find the Index of the Large Integer-zh.md" new file mode 100644 index 00000000..0d586e83 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1533.leetcode1533 Find the Index of the Large Integer-zh.md" @@ -0,0 +1,230 @@ +# [1533. 找到最大整数的索引](https://leetcode-cn.com/problems/find-the-index-of-the-large-integer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1533.Find%20the%20Index%20of%20the%20Large%20Integer/README_EN.md) + +## 题目描述 + + + +

    我们有这样一个整数数组 arr ,除了一个最大的整数外,其他所有整数都相等。你不能直接访问该数组,你需要通过 API ArrayReader 来间接访问,这个 API 有以下成员函数:

    + +
      +
    • int compareSub(int l, int r, int x, int y):其中 0 <= l, r, x, y < ArrayReader.length(), l <= r 且 x <= y。这个函数比较子数组 arr[l..r] 与子数组 arr[x..y] 的和。该函数返回: +
        +
      • 1 若 arr[l]+arr[l+1]+...+arr[r] > arr[x]+arr[x+1]+...+arr[y] 。
      • +
      • 0 若 arr[l]+arr[l+1]+...+arr[r] == arr[x]+arr[x+1]+...+arr[y] 。
      • +
      • -1 若 arr[l]+arr[l+1]+...+arr[r] < arr[x]+arr[x+1]+...+arr[y] 。
      • +
      +
    • +
    • int length():返回数组的长度。
    • +
    + +

    你最多可以调用函数 compareSub() 20 次。你可以认为这两个函数的时间复杂度都为 O(1) 。

    + +

    返回 arr 中最大整数的索引。

    + +

    进阶

    + +
      +
    • 如果 arr 中有两个整数比其他数大呢?
    • +
    • 如果有一个数比其他数大,另一个数比其他数小呢?
    • +
    + +

     

    + +

    示例 1:

    + +
    输入: arr = [7,7,7,7,10,7,7,7]
    +输出: 4
    +解释: API 的调用如下:
    +reader.compareSub(0, 0, 1, 1) // 返回 0。比较子数组 (0, 0) 与子数组 (1, 1) (即比较 arr[0] 和 arr[1])。
    +因此我们知道 arr[0] 和 arr[1] 不包含最大元素。
    +reader.compareSub(2, 2, 3, 3) // 返回 0。我们可以排除 arr[2] 和 arr[3]。
    +reader.compareSub(4, 4, 5, 5) // 返回 1。因此,可以确定 arr[4] 是数组中最大的元素。
    +注意,我们只调用了 3 次 compareSub,所以这个答案是有效的。
    +
    + +

    示例 2:

    + +
    输入: nums = [6,6,12]
    +输出: 2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 5 * 10^5
    • +
    • 1 <= arr[i] <= 100
    • +
    • arr 中除一个最大元素外,其余所有元素都相等。
    • +
    + +## 解法 + + + +三分查找。 + +前两部分数量相等,进行 `compareSub` 比较。 + + + +### **Python3** + + + +```python +# """ +# This is ArrayReader's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class ArrayReader(object): +# # Compares the sum of arr[l..r] with the sum of arr[x..y] +# # return 1 if sum(arr[l..r]) > sum(arr[x..y]) +# # return 0 if sum(arr[l..r]) == sum(arr[x..y]) +# # return -1 if sum(arr[l..r]) < sum(arr[x..y]) +# def compareSub(self, l: int, r: int, x: int, y: int) -> int: +# +# # Returns the length of the array +# def length(self) -> int: +# + + +class Solution: + def getIndex(self, reader: 'ArrayReader') -> int: + left, right = 0, reader.length() - 1 + while left < right: + t1, t2, t3 = left, left + (right - left) // 3, left + ((right - left) // 3) * 2 + 1 + cmp = reader.compareSub(t1, t2, t2 + 1, t3) + if cmp == 0: + left = t3 + 1 + elif cmp == 1: + right = t2 + else: + left, right = t2 + 1, t3 + return left +``` + +### **Java** + + + +```java +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * public int compareSub(int l, int r, int x, int y) {} + * + * // Returns the length of the array + * public int length() {} + * } + */ + +class Solution { + public int getIndex(ArrayReader reader) { + int left = 0, right = reader.length() - 1; + while (left < right) { + int t1 = left, t2 = left + (right - left) / 3, t3 = left + (right - left) / 3 * 2 + 1; + int cmp = reader.compareSub(t1, t2, t2 + 1, t3); + if (cmp == 0) { + left = t3 + 1; + } else if (cmp == 1) { + right = t2; + } else { + left = t2 + 1; + right = t3; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * class ArrayReader { + * public: + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * int compareSub(int l, int r, int x, int y); + * + * // Returns the length of the array + * int length(); + * }; + */ + +class Solution { +public: + int getIndex(ArrayReader &reader) { + int left = 0, right = reader.length() - 1; + while (left < right) { + int t1 = left, t2 = left + (right - left) / 3, t3 = left + (right - left) / 3 * 2 + 1; + int cmp = reader.compareSub(t1, t2, t2 + 1, t3); + if (cmp == 0) { + left = t3 + 1; + } else if (cmp == 1) { + right = t2; + } else { + left = t2 + 1; + right = t3; + } + } + return left; + } +}; +``` + +### **Go** + +```go +/** + * // This is the ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * type ArrayReader struct { + * } + * // Compares the sum of arr[l..r] with the sum of arr[x..y] + * // return 1 if sum(arr[l..r]) > sum(arr[x..y]) + * // return 0 if sum(arr[l..r]) == sum(arr[x..y]) + * // return -1 if sum(arr[l..r]) < sum(arr[x..y]) + * func (this *ArrayReader) compareSub(l, r, x, y int) int {} + * + * // Returns the length of the array + * func (this *ArrayReader) length() int {} + */ + +func getIndex(reader *ArrayReader) int { + left, right := 0, reader.length()-1 + for left < right { + t1, t2, t3 := left, left+(right-left)/3, left+(right-left)/3*2+1 + cmp := reader.compareSub(t1, t2, t2+1, t3) + if cmp == 0 { + left = t3 + 1 + } else if cmp == 1 { + right = t2 + } else { + left, right = t2+1, t3 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1534.leetcode1534 Count Good Triplets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1534.leetcode1534 Count Good Triplets-zh.md" new file mode 100644 index 00000000..bf5e6f14 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1534.leetcode1534 Count Good Triplets-zh.md" @@ -0,0 +1,79 @@ +# [1534. 统计好三元组](https://leetcode-cn.com/problems/count-good-triplets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1534.Count%20Good%20Triplets/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,以及 abc 三个整数。请你统计其中好三元组的数量。

    + +

    如果三元组 (arr[i], arr[j], arr[k]) 满足下列全部条件,则认为它是一个 好三元组

    + +
      +
    • 0 <= i < j < k < arr.length
    • +
    • |arr[i] - arr[j]| <= a
    • +
    • |arr[j] - arr[k]| <= b
    • +
    • |arr[i] - arr[k]| <= c
    • +
    + +

    其中 |x| 表示 x 的绝对值。

    + +

    返回 好三元组的数量

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
    +输出:4
    +解释:一共有 4 个好三元组:[(3,0,1), (3,0,1), (3,1,1), (0,1,1)] 。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,1,2,2,3], a = 0, b = 0, c = 1
    +输出:0
    +解释:不存在满足所有条件的三元组。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= arr.length <= 100
    • +
    • 0 <= arr[i] <= 1000
    • +
    • 0 <= a, b, c <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1535.leetcode1535 Find the Winner of an Array Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1535.leetcode1535 Find the Winner of an Array Game-zh.md" new file mode 100644 index 00000000..4068ce10 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1535.leetcode1535 Find the Winner of an Array Game-zh.md" @@ -0,0 +1,87 @@ +# [1535. 找出数组游戏的赢家](https://leetcode-cn.com/problems/find-the-winner-of-an-array-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1535.Find%20the%20Winner%20of%20an%20Array%20Game/README_EN.md) + +## 题目描述 + + + +

    给你一个由 不同 整数组成的整数数组 arr 和一个整数 k

    + +

    每回合游戏都在数组的前两个元素(即 arr[0]arr[1] )之间进行。比较 arr[0]arr[1] 的大小,较大的整数将会取得这一回合的胜利并保留在位置 0 ,较小的整数移至数组的末尾。当一个整数赢得 k 个连续回合时,游戏结束,该整数就是比赛的 赢家

    + +

    返回赢得比赛的整数。

    + +

    题目数据 保证 游戏存在赢家。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [2,1,3,5,4,6,7], k = 2
    +输出:5
    +解释:一起看一下本场游戏每回合的情况:
    +
    +因此将进行 4 回合比赛,其中 5 是赢家,因为它连胜 2 回合。
    +
    + +

    示例 2:

    + +
    输入:arr = [3,2,1], k = 10
    +输出:3
    +解释:3 将会在前 10 个回合中连续获胜。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,9,8,2,3,7,6,4,5], k = 7
    +输出:9
    +
    + +

    示例 4:

    + +
    输入:arr = [1,11,22,33,44,55,66,77,88,99], k = 1000000000
    +输出:99
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 10^5
    • +
    • 1 <= arr[i] <= 10^6
    • +
    • arr 所含的整数 各不相同
    • +
    • 1 <= k <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1536.leetcode1536 Minimum Swaps to Arrange a Binary Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1536.leetcode1536 Minimum Swaps to Arrange a Binary Grid-zh.md" new file mode 100644 index 00000000..5a43494f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1536.leetcode1536 Minimum Swaps to Arrange a Binary Grid-zh.md" @@ -0,0 +1,84 @@ +# [1536. 排布二进制网格的最少交换次数](https://leetcode-cn.com/problems/minimum-swaps-to-arrange-a-binary-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1536.Minimum%20Swaps%20to%20Arrange%20a%20Binary%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个 n x n 的二进制网格 grid,每一次操作中,你可以选择网格的 相邻两行 进行交换。

    + +

    一个符合要求的网格需要满足主对角线以上的格子全部都是 0 。

    + +

    请你返回使网格满足要求的最少操作次数,如果无法使网格符合要求,请你返回 -1 。

    + +

    主对角线指的是从 (1, 1) 到 (n, n) 的这些格子。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[0,0,1],[1,1,0],[1,0,0]]
    +输出:3
    +
    + +

    示例 2:

    + +

    + +
    输入:grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
    +输出:-1
    +解释:所有行都是一样的,交换相邻行无法使网格符合要求。
    +
    + +

    示例 3:

    + +

    + +
    输入:grid = [[1,0,0],[1,1,0],[1,1,1]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= n <= 200
    • +
    • grid[i][j] 要么是 0 要么是 1 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1537.leetcode1537 Get the Maximum Score-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1537.leetcode1537 Get the Maximum Score-zh.md" new file mode 100644 index 00000000..d5d11c6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1537.leetcode1537 Get the Maximum Score-zh.md" @@ -0,0 +1,100 @@ +# [1537. 最大得分](https://leetcode-cn.com/problems/get-the-maximum-score) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1537.Get%20the%20Maximum%20Score/README_EN.md) + +## 题目描述 + + + +

    你有两个 有序 且数组内元素互不相同的数组 nums1 和 nums2 。

    + +

    一条 合法路径 定义如下:

    + +
      +
    • 选择数组 nums1 或者 nums2 开始遍历(从下标 0 处开始)。
    • +
    • 从左到右遍历当前数组。
    • +
    • 如果你遇到了 nums1 和 nums2 中都存在的值,那么你可以切换路径到另一个数组对应数字处继续遍历(但在合法路径中重复数字只会被统计一次)。
    • +
    + +

    得分定义为合法路径中不同数字的和。

    + +

    请你返回所有可能合法路径中的最大得分。

    + +

    由于答案可能很大,请你将它对 10^9 + 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
    +输出:30
    +解释:合法路径包括:
    +[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],(从 nums1 开始遍历)
    +[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10]  (从 nums2 开始遍历)
    +最大得分为上图中的绿色路径 [2,4,6,8,10] 。
    +
    + +

    示例 2:

    + +
    输入:nums1 = [1,3,5,7,9], nums2 = [3,5,100]
    +输出:109
    +解释:最大得分由路径 [1,3,5,100] 得到。
    +
    + +

    示例 3:

    + +
    输入:nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
    +输出:40
    +解释:nums1 和 nums2 之间无相同数字。
    +最大得分由路径 [6,7,8,9,10] 得到。
    +
    + +

    示例 4:

    + +
    输入:nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]
    +输出:61
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length <= 10^5
    • +
    • 1 <= nums2.length <= 10^5
    • +
    • 1 <= nums1[i], nums2[i] <= 10^7
    • +
    • nums1 和 nums2 都是严格递增的数组。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1538.leetcode1538 Guess the Majority in a Hidden Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1538.leetcode1538 Guess the Majority in a Hidden Array-zh.md" new file mode 100644 index 00000000..246e208a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1538.leetcode1538 Guess the Majority in a Hidden Array-zh.md" @@ -0,0 +1,94 @@ +# [1538. 找出隐藏数组中出现次数最多的元素](https://leetcode-cn.com/problems/guess-the-majority-in-a-hidden-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1538.Guess%20the%20Majority%20in%20a%20Hidden%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个整数数组 nums,且 nums 中的所有整数都为 01。你不能直接访问这个数组,你需要使用 API ArrayReader ,该 API 含有下列成员函数:

    + +
      +
    • int query(int a, int b, int c, int d):其中 0 <= a < b < c < d < ArrayReader.length() 。此函数查询以这四个参数为下标的元素并返回: + +
        +
      • 4 : 当这四个元素相同(0 或 1)时。
      • +
      • 2 : 当其中三个元素的值等于 0 且一个元素等于 1 时,或当其中三个元素的值等于 1 且一个元素等于 0 时。
      • +
      • : 当其中两个元素等于 0 且两个元素等于 1 时。
      • +
      +
    • +
    • int length():返回数组的长度。
    • +
    + +

    你可以调用 query() 最多 2 * n 次,其中 n 等于 ArrayReader.length()

    + +

    返回 nums 中出现次数最多的值的任意索引,若所有的值出现次数均相同,返回 -1。

    + +

    进阶:要找到出现次数最多的元素,需要至少调用 query() 多少次?

    + +

     

    + +

    示例 1:

    + +
    输入: nums = [0,0,1,0,1,1,1,1]
    +输出: 5
    +解释: API 的调用情况如下:
    +reader.length() // 返回 8,因为隐藏数组中有 8 个元素。
    +reader.query(0,1,2,3) // 返回 2,查询元素 nums[0], nums[1], nums[2], nums[3] 间的比较。
    +// 三个元素等于 0 且一个元素等于 1 或出现相反情况。
    +reader.query(4,5,6,7) // 返回 4,因为 nums[4], nums[5], nums[6], nums[7] 有相同值。
    +我们可以推断,最常出现的值在最后 4 个元素中。
    +索引 2, 4, 6, 7 也是正确答案。
    +
    + +

    示例 2:

    + +
    输入: nums = [0,0,1,1,0]
    +输出: 0
    +
    + +

    示例 3:

    + +
    输入: nums = [1,0,1,0,1,0,1,0]
    +输出: -1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 5 <= nums.length <= 10^5
    • +
    • 0 <= nums[i] <= 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1539.leetcode1539 Kth Missing Positive Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1539.leetcode1539 Kth Missing Positive Number-zh.md" new file mode 100644 index 00000000..6e361411 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1539.leetcode1539 Kth Missing Positive Number-zh.md" @@ -0,0 +1,69 @@ +# [1539. 第 k 个缺失的正整数](https://leetcode-cn.com/problems/kth-missing-positive-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1539.Kth%20Missing%20Positive%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个 严格升序排列 的正整数数组 arr 和一个整数 k 。

    + +

    请你找到这个数组里第 k 个缺失的正整数。

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [2,3,4,7,11], k = 5
    +输出:9
    +解释:缺失的正整数包括 [1,5,6,8,9,10,12,13,...] 。第 5 个缺失的正整数为 9 。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,2,3,4], k = 2
    +输出:6
    +解释:缺失的正整数包括 [5,6,7,...] 。第 2 个缺失的正整数为 6 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 1000
    • +
    • 1 <= k <= 1000
    • +
    • 对于所有 1 <= i < j <= arr.length 的 i 和 j 满足 arr[i] < arr[j] 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1540.leetcode1540 Can Convert String in K Moves-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1540.leetcode1540 Can Convert String in K Moves-zh.md" new file mode 100644 index 00000000..35f1d54e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1540.leetcode1540 Can Convert String in K Moves-zh.md" @@ -0,0 +1,86 @@ +# [1540. K 次操作转变字符串](https://leetcode-cn.com/problems/can-convert-string-in-k-moves) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1540.Can%20Convert%20String%20in%20K%20Moves/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 s 和 t ,你的目标是在 k 次操作以内把字符串 s 转变成 t 。

    + +

    在第 i 次操作时(1 <= i <= k),你可以选择进行如下操作:

    + +
      +
    • 选择字符串 s 中满足 1 <= j <= s.length 且之前未被选过的任意下标 j (下标从 1 开始),并将此位置的字符切换 i 次。
    • +
    • 不进行任何操作。
    • +
    + +

    切换 1 次字符的意思是用字母表中该字母的下一个字母替换它(字母表环状接起来,所以 'z' 切换后会变成 'a')。

    + +

    请记住任意一个下标 j 最多只能被操作 1 次。

    + +

    如果在不超过 k 次操作内可以把字符串 s 转变成 t ,那么请你返回 true ,否则请你返回 false 。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "input", t = "ouput", k = 9
    +输出:true
    +解释:第 6 次操作时,我们将 'i' 切换 6 次得到 'o' 。第 7 次操作时,我们将 'n' 切换 7 次得到 'u' 。
    +
    + +

    示例 2:

    + +
    输入:s = "abc", t = "bcd", k = 10
    +输出:false
    +解释:我们需要将每个字符切换 1 次才能得到 t 。我们可以在第 1 次操作时将 'a' 切换成 'b' ,但另外 2 个字母在剩余操作中无法再转变为 t 中对应字母。
    +
    + +

    示例 3:

    + +
    输入:s = "aab", t = "bbb", k = 27
    +输出:true
    +解释:第 1 次操作时,我们将第一个 'a' 切换 1 次得到 'b' 。在第 27 次操作时,我们将第二个字母 'a' 切换 27 次得到 'b' 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length, t.length <= 10^5
    • +
    • 0 <= k <= 10^9
    • +
    • s 和 t 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1541.leetcode1541 Minimum Insertions to Balance a Parentheses String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1541.leetcode1541 Minimum Insertions to Balance a Parentheses String-zh.md" new file mode 100644 index 00000000..06d3e213 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1541.leetcode1541 Minimum Insertions to Balance a Parentheses String-zh.md" @@ -0,0 +1,97 @@ +# [1541. 平衡括号字符串的最少插入次数](https://leetcode-cn.com/problems/minimum-insertions-to-balance-a-parentheses-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1541.Minimum%20Insertions%20to%20Balance%20a%20Parentheses%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个括号字符串 s ,它只包含字符 '(' 和 ')' 。一个括号字符串被称为平衡的当它满足:

    + +
      +
    • 任何左括号 '(' 必须对应两个连续的右括号 '))' 。
    • +
    • 左括号 '(' 必须在对应的连续两个右括号 '))' 之前。
    • +
    + +

    比方说 "())", "())(())))" 和 "(())())))" 都是平衡的, ")()", "()))" 和 "(()))" 都是不平衡的。

    + +

    你可以在任意位置插入字符 '(' 和 ')' 使字符串平衡。

    + +

    请你返回让 s 平衡的最少插入次数。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "(()))"
    +输出:1
    +解释:第二个左括号有与之匹配的两个右括号,但是第一个左括号只有一个右括号。我们需要在字符串结尾额外增加一个 ')' 使字符串变成平衡字符串 "(())))" 。
    +
    + +

    示例 2:

    + +
    输入:s = "())"
    +输出:0
    +解释:字符串已经平衡了。
    +
    + +

    示例 3:

    + +
    输入:s = "))())("
    +输出:3
    +解释:添加 '(' 去匹配最开头的 '))' ,然后添加 '))' 去匹配最后一个 '(' 。
    +
    + +

    示例 4:

    + +
    输入:s = "(((((("
    +输出:12
    +解释:添加 12 个 ')' 得到平衡字符串。
    +
    + +

    示例 5:

    + +
    输入:s = ")))))))"
    +输出:5
    +解释:在字符串开头添加 4 个 '(' 并在结尾添加 1 个 ')' ,字符串变成平衡字符串 "(((())))))))" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s 只包含 '(' 和 ')' 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1542.leetcode1542 Find Longest Awesome Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1542.leetcode1542 Find Longest Awesome Substring-zh.md" new file mode 100644 index 00000000..704586cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1542.leetcode1542 Find Longest Awesome Substring-zh.md" @@ -0,0 +1,84 @@ +# [1542. 找出最长的超赞子字符串](https://leetcode-cn.com/problems/find-longest-awesome-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1542.Find%20Longest%20Awesome%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 。请返回 s 中最长的 超赞子字符串 的长度。

    + +

    「超赞子字符串」需满足满足下述两个条件:

    + +
      +
    • 该字符串是 s 的一个非空子字符串
    • +
    • 进行任意次数的字符交换后,该字符串可以变成一个回文字符串
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:s = "3242415"
    +输出:5
    +解释:"24241" 是最长的超赞子字符串,交换其中的字符后,可以得到回文 "24142"
    +
    + +

    示例 2:

    + +
    输入:s = "12345678"
    +输出:1
    +
    + +

    示例 3:

    + +
    输入:s = "213123"
    +输出:6
    +解释:"213123" 是最长的超赞子字符串,交换其中的字符后,可以得到回文 "231132"
    +
    + +

    示例 4:

    + +
    输入:s = "00"
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 10^5
    • +
    • s 仅由数字组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1543.leetcode1543 Fix Product Name Format-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1543.leetcode1543 Fix Product Name Format-zh.md" new file mode 100644 index 00000000..6c2ec643 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1543.leetcode1543 Fix Product Name Format-zh.md" @@ -0,0 +1,78 @@ +# [1543. 产品名称格式修复](https://leetcode-cn.com/problems/fix-product-name-format) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1543.Fix%20Product%20Name%20Format/README_EN.md) + +## 题目描述 + + + +

    表:Sales

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| sale_id      | int     |
    +| product_name | varchar |
    +| sale_date    | date    |
    ++--------------+---------+
    +sale_id 是该表主键
    +该表的每一行包含了产品的名称及其销售日期
    +
    + +

    因为在 2000 年该表是手工填写的,product_name 可能包含前后空格,而且包含大小写。

    + +

    写一个 SQL 语句报告每个月的销售情况:

    + +
      +
    • product_name 是小写字母且不包含前后空格
    • +
    • sale_date 格式为 ('YYYY-MM') 
    • +
    • total 是产品在本月销售的次数
    • +
    + +

    返回结果以 product_name 升序 排列,如果有排名相同,再以 sale_date 升序 排列。

    + +

    查询结果格式如下所示:

    + +
    +Sales 表:
    ++------------+------------------+--------------+
    +| sale_id    | product_name     | sale_date    |
    ++------------+------------------+--------------+
    +| 1          |      LCPHONE     | 2000-01-16   |
    +| 2          |    LCPhone       | 2000-01-17   |
    +| 3          |     LcPhOnE      | 2000-02-18   |
    +| 4          |      LCKeyCHAiN  | 2000-02-19   |
    +| 5          |   LCKeyChain     | 2000-02-28   |
    +| 6          | Matryoshka       | 2000-03-31   | 
    ++------------+------------------+--------------+
    +
    +Result 表:
    ++--------------+--------------+----------+
    +| product_name | sale_date    | total    |
    ++--------------+--------------+----------+
    +| lcphone      | 2000-01      | 2        |
    +| lckeychain   | 2000-02      | 2        | 
    +| lcphone      | 2000-02      | 1        | 
    +| matryoshka   | 2000-03      | 1        | 
    ++--------------+--------------+----------+
    +
    +1 月份,卖了 2 个 LcPhones,请注意产品名称是小写的,中间可能包含空格
    +2 月份,卖了 2 个 LCKeychains 和 1 个 LCPhone
    +3 月份,卖了 1 个 matryoshka
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1544.leetcode1544 Make The String Great-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1544.leetcode1544 Make The String Great-zh.md" new file mode 100644 index 00000000..63f246a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1544.leetcode1544 Make The String Great-zh.md" @@ -0,0 +1,89 @@ +# [1544. 整理字符串](https://leetcode-cn.com/problems/make-the-string-great) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1544.Make%20The%20String%20Great/README_EN.md) + +## 题目描述 + + + +

    给你一个由大小写英文字母组成的字符串 s

    + +

    一个整理好的字符串中,两个相邻字符 s[i]s[i+1],其中 0<= i <= s.length-2 ,要满足如下条件:

    + +
      +
    • s[i] 是小写字符,则 s[i+1] 不可以是相同的大写字符。
    • +
    • s[i] 是大写字符,则 s[i+1] 不可以是相同的小写字符。
    • +
    + +

    请你将字符串整理好,每次你都可以从字符串中选出满足上述条件的 两个相邻 字符并删除,直到字符串整理好为止。

    + +

    请返回整理好的 字符串 。题目保证在给出的约束条件下,测试样例对应的答案是唯一的。

    + +

    注意:空字符串也属于整理好的字符串,尽管其中没有任何字符。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "leEeetcode"
    +输出:"leetcode"
    +解释:无论你第一次选的是 i = 1 还是 i = 2,都会使 "leEeetcode" 缩减为 "leetcode" 。
    +
    + +

    示例 2:

    + +
    +输入:s = "abBAcC"
    +输出:""
    +解释:存在多种不同情况,但所有的情况都会导致相同的结果。例如:
    +"abBAcC" --> "aAcC" --> "cC" --> ""
    +"abBAcC" --> "abBA" --> "aA" --> ""
    +
    + +

    示例 3:

    + +
    +输入:s = "s"
    +输出:"s"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s 只包含小写和大写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1545.leetcode1545 Find Kth Bit in Nth Binary String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1545.leetcode1545 Find Kth Bit in Nth Binary String-zh.md" new file mode 100644 index 00000000..800a8254 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1545.leetcode1545 Find Kth Bit in Nth Binary String-zh.md" @@ -0,0 +1,99 @@ +# [1545. 找出第 N 个二进制字符串中的第 K 位](https://leetcode-cn.com/problems/find-kth-bit-in-nth-binary-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1545.Find%20Kth%20Bit%20in%20Nth%20Binary%20String/README_EN.md) + +## 题目描述 + + + +

    给你两个正整数 nk,二进制字符串  Sn 的形成规则如下:

    + +
      +
    • S1 = "0"
    • +
    • i > 1 时,Si = Si-1 + "1" + reverse(invert(Si-1))
    • +
    + +

    其中 + 表示串联操作,reverse(x) 返回反转 x 后得到的字符串,而 invert(x) 则会翻转 x 中的每一位(0 变为 1,而 1 变为 0)。

    + +

    例如,符合上述描述的序列的前 4 个字符串依次是:

    + +
      +
    • S= "0"
    • +
    • S= "011"
    • +
    • S= "0111001"
    • +
    • S4 = "011100110110001"
    • +
    + +

    请你返回  Snk 位字符 ,题目数据保证 k 一定在 Sn 长度范围以内。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, k = 1
    +输出:"0"
    +解释:S3 为 "0111001",其第 1 位为 "0" 。
    +
    + +

    示例 2:

    + +
    +输入:n = 4, k = 11
    +输出:"1"
    +解释:S4 为 "011100110110001",其第 11 位为 "1" 。
    +
    + +

    示例 3:

    + +
    +输入:n = 1, k = 1
    +输出:"0"
    +
    + +

    示例 4:

    + +
    +输入:n = 2, k = 3
    +输出:"1"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 20
    • +
    • 1 <= k <= 2n - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1546.leetcode1546 Maximum Number of Non-Overlapping Subarrays With Sum Equals Target-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1546.leetcode1546 Maximum Number of Non-Overlapping Subarrays With Sum Equals Target-zh.md" new file mode 100644 index 00000000..41161c70 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1546.leetcode1546 Maximum Number of Non-Overlapping Subarrays With Sum Equals Target-zh.md" @@ -0,0 +1,80 @@ +# [1546. 和为目标值的最大数目不重叠非空子数组数目](https://leetcode-cn.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1546.Maximum%20Number%20of%20Non-Overlapping%20Subarrays%20With%20Sum%20Equals%20Target/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums 和一个整数 target 。

    + +

    请你返回 非空不重叠 子数组的最大数目,且每个子数组中数字和都为 target 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,1,1,1,1], target = 2
    +输出:2
    +解释:总共有 2 个不重叠子数组(加粗数字表示) [1,1,1,1,1] ,它们的和为目标值 2 。
    +
    + +

    示例 2:

    + +
    输入:nums = [-1,3,5,1,4,2,-9], target = 6
    +输出:2
    +解释:总共有 3 个子数组和为 6 。
    +([5,1], [4,2], [3,5,1,4,2,-9]) 但只有前 2 个是不重叠的。
    + +

    示例 3:

    + +
    输入:nums = [-2,6,6,3,5,4,1,2,8], target = 10
    +输出:3
    +
    + +

    示例 4:

    + +
    输入:nums = [0,0,0], target = 0
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • -10^4 <= nums[i] <= 10^4
    • +
    • 0 <= target <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1547.leetcode1547 Minimum Cost to Cut a Stick-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1547.leetcode1547 Minimum Cost to Cut a Stick-zh.md" new file mode 100644 index 00000000..3c3701af --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1547.leetcode1547 Minimum Cost to Cut a Stick-zh.md" @@ -0,0 +1,83 @@ +# [1547. 切棍子的最小成本](https://leetcode-cn.com/problems/minimum-cost-to-cut-a-stick) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1547.Minimum%20Cost%20to%20Cut%20a%20Stick/README_EN.md) + +## 题目描述 + + + +

    有一根长度为 n 个单位的木棍,棍上从 0n 标记了若干位置。例如,长度为 6 的棍子可以标记如下:

    + +

    + +

    给你一个整数数组 cuts ,其中 cuts[i] 表示你需要将棍子切开的位置。

    + +

    你可以按顺序完成切割,也可以根据需要更改切割的顺序。

    + +

    每次切割的成本都是当前要切割的棍子的长度,切棍子的总成本是历次切割成本的总和。对棍子进行切割将会把一根木棍分成两根较小的木棍(这两根木棍的长度和就是切割前木棍的长度)。请参阅第一个示例以获得更直观的解释。

    + +

    返回切棍子的 最小总成本

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 7, cuts = [1,3,4,5]
    +输出:16
    +解释:按 [1, 3, 4, 5] 的顺序切割的情况如下所示:
    +
    +第一次切割长度为 7 的棍子,成本为 7 。第二次切割长度为 6 的棍子(即第一次切割得到的第二根棍子),第三次切割为长度 4 的棍子,最后切割长度为 3 的棍子。总成本为 7 + 6 + 4 + 3 = 20 。
    +而将切割顺序重新排列为 [3, 5, 1, 4] 后,总成本 = 16(如示例图中 7 + 4 + 3 + 2 = 16)。
    +
    + +

    示例 2:

    + +
    +输入:n = 9, cuts = [5,6,1,4,2]
    +输出:22
    +解释:如果按给定的顺序切割,则总成本为 25 。总成本 <= 25 的切割顺序很多,例如,[4, 6, 5, 2, 1] 的总成本 = 22,是所有可能方案中成本最小的。
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 10^6
    • +
    • 1 <= cuts.length <= min(n - 1, 100)
    • +
    • 1 <= cuts[i] <= n - 1
    • +
    • cuts 数组中的所有整数都 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1548.leetcode1548 The Most Similar Path in a Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1548.leetcode1548 The Most Similar Path in a Graph-zh.md" new file mode 100644 index 00000000..3ad0a8fe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1548.leetcode1548 The Most Similar Path in a Graph-zh.md" @@ -0,0 +1,123 @@ +# [1548. 图中最相似的路径](https://leetcode-cn.com/problems/the-most-similar-path-in-a-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1548.The%20Most%20Similar%20Path%20in%20a%20Graph/README_EN.md) + +## 题目描述 + + + +

    我们有 n 座城市和 m 条双向道路 roads ,其中 roads[i] = [ai, bi] 连接城市 ai 和城市 bi。每个城市有一个正好 3 个大写字母的名字,在数组 names中给出。从任意城市 x 出发,你可以到达任意城市 y ,其中 y != x (即:城市和道路形成一张无向连通图)。

    + +

    给定一个字符串数组 targetPath,你需要找出图中与 targetPath 的 长度相同 编辑距离最小 的路径。

    + +

    你需要返回 编辑距离最小的路径中节点的顺序 。该路径应当与 targetPath 的长度相等,且路径需有效(即: ans[i] 和 ans[i + 1] 间应存在直接连通的道路)。如果有多个答案,返回任意一个。

    + +

    编辑距离 的定义如下:

    + +
    +define editDistance(targetPath, myPath) {
    +    dis := 0
    +    a := targetPath.length
    +    b := myPath.length
    +    if a != b {
    +        return 1000000000
    +    }
    +    for (i := 0; i < a; i += 1) {
    +        if targetPath[i] != myPath[i] {
    +            dis += 1
    +        }
    +    }
    +    return dis
    +}
    +
    + +

     

    + +

    进阶:如果路径中每个节点只可访问一次,你该如何修改你的答案?

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 5, roads = [[0,2],[0,3],[1,2],[1,3],[1,4],[2,4]], names = ["ATL","PEK","LAX","DXB","HND"], targetPath = ["ATL","DXB","HND","LAX"]
    +输出:[0,2,4,2]
    +解释:[0,2,4,2], [0,3,0,2] 和 [0,3,1,2] 都是正确答案。
    +[0,2,4,2] 等价于 ["ATL","LAX","HND","LAX"] ,与 targetPath 的编辑距离 = 1。
    +[0,3,0,2] 等价于 ["ATL","DXB","ATL","LAX"] ,与 targetPath 的编辑距离 = 1。
    +[0,3,1,2] 等价于 ["ATL","DXB","PEK","LAX"] ,与 targetPath 的编辑距离 = 1。
    +
    + +

    示例 2:

    + +

    + +
    +输入:n = 4, roads = [[1,0],[2,0],[3,0],[2,1],[3,1],[3,2]], names = ["ATL","PEK","LAX","DXB"], targetPath = ["ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX"]
    +输出:[0,1,0,1,0,1,0,1]
    +解释:任意路径与 targetPath 的编辑距离都等于 8。
    +
    + +

    示例 3:

    + +

    + +
    +输入:n = 6, roads = [[0,1],[1,2],[2,3],[3,4],[4,5]], names = ["ATL","PEK","LAX","ATL","DXB","HND"], targetPath = ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
    +输出:[3,4,5,4,3,2,1]
    +解释:[3,4,5,4,3,2,1] 是唯一与 targetPath 的编辑距离 = 0 的路径。
    +该路径等价于 ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • m == roads.length
    • +
    • n - 1 <= m <= (n * (n - 1) / 2)
    • +
    • 0 <= ai, bi <= n - 1
    • +
    • ai != bi 
    • +
    • 给定的图保证是连通的,任意两个节点至多有一个直接连通的道路。
    • +
    • names.length == n
    • +
    • names[i].length == 3
    • +
    • names[i] 包含大写英文字母。
    • +
    • 可能有两个名称相同的城市。
    • +
    • 1 <= targetPath.length <= 100
    • +
    • targetPath[i].length == 3
    • +
    • targetPath[i] 由大写英文字母组成。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1549.leetcode1549 The Most Recent Orders for Each Product-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1549.leetcode1549 The Most Recent Orders for Each Product-zh.md" new file mode 100644 index 00000000..b30ec505 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1549.leetcode1549 The Most Recent Orders for Each Product-zh.md" @@ -0,0 +1,129 @@ +# [1549. 每件商品的最新订单](https://leetcode-cn.com/problems/the-most-recent-orders-for-each-product) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1549.The%20Most%20Recent%20Orders%20for%20Each%20Product/README_EN.md) + +## 题目描述 + + + +

    表: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    ++---------------+---------+
    +customer_id 是该表主键.
    +该表包含消费者的信息.
    +
    + +

     

    + +

    表: Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| product_id    | int     |
    ++---------------+---------+
    +order_id 是该表主键.
    +该表包含消费者customer_id产生的订单.
    +不会有商品被相同的用户在一天内下单超过一次.
    + +

     

    + +

    表: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    +| price         | int     |
    ++---------------+---------+
    +product_id 是该表主键.
    +该表包含所有商品的信息.
    +
    + +

     

    + +

    写一个SQL 语句, 找到每件商品的最新订单(可能有多个).

    + +

    返回的结果以 product_name 升序排列, 如果有排序相同, 再以 product_id 升序排列. 如果还有排序相同, 再以 order_id 升序排列.

    + +

    查询结果格式如下例所示:

    + +
    +Customers
    ++-------------+-----------+
    +| customer_id | name      |
    ++-------------+-----------+
    +| 1           | Winston   |
    +| 2           | Jonathan  |
    +| 3           | Annabelle |
    +| 4           | Marwan    |
    +| 5           | Khaled    |
    ++-------------+-----------+
    +
    +Orders
    ++----------+------------+-------------+------------+
    +| order_id | order_date | customer_id | product_id |
    ++----------+------------+-------------+------------+
    +| 1        | 2020-07-31 | 1           | 1          |
    +| 2        | 2020-07-30 | 2           | 2          |
    +| 3        | 2020-08-29 | 3           | 3          |
    +| 4        | 2020-07-29 | 4           | 1          |
    +| 5        | 2020-06-10 | 1           | 2          |
    +| 6        | 2020-08-01 | 2           | 1          |
    +| 7        | 2020-08-01 | 3           | 1          |
    +| 8        | 2020-08-03 | 1           | 2          |
    +| 9        | 2020-08-07 | 2           | 3          |
    +| 10       | 2020-07-15 | 1           | 2          |
    ++----------+------------+-------------+------------+
    +
    +Products
    ++------------+--------------+-------+
    +| product_id | product_name | price |
    ++------------+--------------+-------+
    +| 1          | keyboard     | 120   |
    +| 2          | mouse        | 80    |
    +| 3          | screen       | 600   |
    +| 4          | hard disk    | 450   |
    ++------------+--------------+-------+
    +
    +Result
    ++--------------+------------+----------+------------+
    +| product_name | product_id | order_id | order_date |
    ++--------------+------------+----------+------------+
    +| keyboard     | 1          | 6        | 2020-08-01 |
    +| keyboard     | 1          | 7        | 2020-08-01 |
    +| mouse        | 2          | 8        | 2020-08-03 |
    +| screen       | 3          | 3        | 2020-08-29 |
    ++--------------+------------+----------+------------+
    +keyboard 的最新订单在2020-08-01, 在这天有两次下单.
    +mouse 的最新订单在2020-08-03, 在这天只有一次下单.
    +screen 的最新订单在2020-08-29, 在这天只有一次下单.
    +hard disk 没有被下单, 我们不把它包含在结果表中.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1550.leetcode1550 Three Consecutive Odds-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1550.leetcode1550 Three Consecutive Odds-zh.md" new file mode 100644 index 00000000..d6798837 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1550.leetcode1550 Three Consecutive Odds-zh.md" @@ -0,0 +1,65 @@ +# [1550. 存在连续三个奇数的数组](https://leetcode-cn.com/problems/three-consecutive-odds) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1550.Three%20Consecutive%20Odds/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr,请你判断数组中是否存在连续三个元素都是奇数的情况:如果存在,请返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [2,6,4,1]
    +输出:false
    +解释:不存在连续三个元素都是奇数的情况。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,2,34,3,4,5,7,23,12]
    +输出:true
    +解释:存在连续三个元素都是奇数的情况,即 [5,7,23] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 1000
    • +
    • 1 <= arr[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1551.leetcode1551 Minimum Operations to Make Array Equal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1551.leetcode1551 Minimum Operations to Make Array Equal-zh.md" new file mode 100644 index 00000000..951695d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1551.leetcode1551 Minimum Operations to Make Array Equal-zh.md" @@ -0,0 +1,69 @@ +# [1551. 使数组中所有元素相等的最小操作数](https://leetcode-cn.com/problems/minimum-operations-to-make-array-equal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1551.Minimum%20Operations%20to%20Make%20Array%20Equal/README_EN.md) + +## 题目描述 + + + +

    存在一个长度为 n 的数组 arr ,其中 arr[i] = (2 * i) + 10 <= i < n )。

    + +

    一次操作中,你可以选出两个下标,记作 xy0 <= x, y < n )并使 arr[x] 减去 1arr[y] 加上 1 (即 arr[x] -=1 arr[y] += 1 )。最终的目标是使数组中的所有元素都 相等 。题目测试用例将会 保证 :在执行若干步操作后,数组中的所有元素最终可以全部相等。

    + +

    给你一个整数 n,即数组的长度。请你返回使数组 arr 中所有元素相等所需的 最小操作数

    + +

     

    + +

    示例 1:

    + +
    输入:n = 3
    +输出:2
    +解释:arr = [1, 3, 5]
    +第一次操作选出 x = 2 和 y = 0,使数组变为 [2, 3, 4]
    +第二次操作继续选出 x = 2 和 y = 0,数组将会变成 [3, 3, 3]
    +
    + +

    示例 2:

    + +
    输入:n = 6
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1552.leetcode1552 Magnetic Force Between Two Balls-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1552.leetcode1552 Magnetic Force Between Two Balls-zh.md" new file mode 100644 index 00000000..2daf9ba2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1552.leetcode1552 Magnetic Force Between Two Balls-zh.md" @@ -0,0 +1,74 @@ +# [1552. 两球之间的磁力](https://leetcode-cn.com/problems/magnetic-force-between-two-balls) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1552.Magnetic%20Force%20Between%20Two%20Balls/README_EN.md) + +## 题目描述 + + + +

    在代号为 C-137 的地球上,Rick 发现如果他将两个球放在他新发明的篮子里,它们之间会形成特殊形式的磁力。Rick 有 n 个空的篮子,第 i 个篮子的位置在 position[i] ,Morty 想把 m 个球放到这些篮子里,使得任意两球间 最小磁力 最大。

    + +

    已知两个球如果分别位于 x 和 y ,那么它们之间的磁力为 |x - y| 。

    + +

    给你一个整数数组 position 和一个整数 m ,请你返回最大化的最小磁力。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:position = [1,2,3,4,7], m = 3
    +输出:3
    +解释:将 3 个球分别放入位于 1,4 和 7 的三个篮子,两球间的磁力分别为 [3, 3, 6]。最小磁力为 3 。我们没办法让最小磁力大于 3 。
    +
    + +

    示例 2:

    + +
    输入:position = [5,4,3,2,1,1000000000], m = 2
    +输出:999999999
    +解释:我们使用位于 1 和 1000000000 的篮子时最小磁力最大。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == position.length
    • +
    • 2 <= n <= 10^5
    • +
    • 1 <= position[i] <= 10^9
    • +
    • 所有 position 中的整数 互不相同 。
    • +
    • 2 <= m <= position.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1553.leetcode1553 Minimum Number of Days to Eat N Oranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1553.leetcode1553 Minimum Number of Days to Eat N Oranges-zh.md" new file mode 100644 index 00000000..4c2a11b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1553.leetcode1553 Minimum Number of Days to Eat N Oranges-zh.md" @@ -0,0 +1,95 @@ +# [1553. 吃掉 N 个橘子的最少天数](https://leetcode-cn.com/problems/minimum-number-of-days-to-eat-n-oranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1553.Minimum%20Number%20of%20Days%20to%20Eat%20N%20Oranges/README_EN.md) + +## 题目描述 + + + +

    厨房里总共有 n 个橘子,你决定每一天选择如下方式之一吃这些橘子:

    + +
      +
    • 吃掉一个橘子。
    • +
    • 如果剩余橘子数 n 能被 2 整除,那么你可以吃掉 n/2 个橘子。
    • +
    • 如果剩余橘子数 n 能被 3 整除,那么你可以吃掉 2*(n/3) 个橘子。
    • +
    + +

    每天你只能从以上 3 种方案中选择一种方案。

    + +

    请你返回吃掉所有 n 个橘子的最少天数。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 10
    +输出:4
    +解释:你总共有 10 个橘子。
    +第 1 天:吃 1 个橘子,剩余橘子数 10 - 1 = 9。
    +第 2 天:吃 6 个橘子,剩余橘子数 9 - 2*(9/3) = 9 - 6 = 3。(9 可以被 3 整除)
    +第 3 天:吃 2 个橘子,剩余橘子数 3 - 2*(3/3) = 3 - 2 = 1。
    +第 4 天:吃掉最后 1 个橘子,剩余橘子数 1 - 1 = 0。
    +你需要至少 4 天吃掉 10 个橘子。
    +
    + +

    示例 2:

    + +
    输入:n = 6
    +输出:3
    +解释:你总共有 6 个橘子。
    +第 1 天:吃 3 个橘子,剩余橘子数 6 - 6/2 = 6 - 3 = 3。(6 可以被 2 整除)
    +第 2 天:吃 2 个橘子,剩余橘子数 3 - 2*(3/3) = 3 - 2 = 1。(3 可以被 3 整除)
    +第 3 天:吃掉剩余 1 个橘子,剩余橘子数 1 - 1 = 0。
    +你至少需要 3 天吃掉 6 个橘子。
    +
    + +

    示例 3:

    + +
    输入:n = 1
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:n = 56
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 2*10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1554.leetcode1554 Strings Differ by One Character-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1554.leetcode1554 Strings Differ by One Character-zh.md" new file mode 100644 index 00000000..1c5c9ece --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1554.leetcode1554 Strings Differ by One Character-zh.md" @@ -0,0 +1,79 @@ +# [1554. 只有一个不同字符的字符串](https://leetcode-cn.com/problems/strings-differ-by-one-character) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1554.Strings%20Differ%20by%20One%20Character/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串列表 dict ,其中所有字符串的长度都相同。

    + +

    当存在两个字符串在相同索引处只有一个字符不同时,返回 True ,否则返回 False

    + +

    进阶:你可以以 O(n*m) 的复杂度解决问题吗?其中 n 是列表 dict 的长度,m 是字符串的长度。

    + +

     

    + +

    示例 1:

    + +
    +输入:dict = ["abcd","acbd", "aacd"]
    +输出:true
    +解释:字符串 "abcd" 和 "aacd" 只在索引 1 处有一个不同的字符。
    +
    + +

    示例 2:

    + +
    +输入:dict = ["ab","cd","yz"]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:dict = ["abcd","cccc","abyd","abab"]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • dict 中的字符数小于或等于 10^5 。
    • +
    • dict[i].length == dict[j].length
    • +
    • dict[i] 是互不相同的。
    • +
    • dict[i] 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1555.leetcode1555 Bank Account Summary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1555.leetcode1555 Bank Account Summary-zh.md" new file mode 100644 index 00000000..60ca9ab3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1555.leetcode1555 Bank Account Summary-zh.md" @@ -0,0 +1,123 @@ +# [1555. 银行账户概要](https://leetcode-cn.com/problems/bank-account-summary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1555.Bank%20Account%20Summary/README_EN.md) + +## 题目描述 + + + +

    用户表: Users

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| user_id      | int     |
    +| user_name    | varchar |
    +| credit       | int     |
    ++--------------+---------+
    +user_id 是这个表的主键。
    +表中的每一列包含每一个用户当前的额度信息。
    + +

     

    + +

    交易表:Transactions

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| trans_id      | int     |
    +| paid_by       | int     |
    +| paid_to       | int     |
    +| amount        | int     |
    +| transacted_on | date    |
    ++---------------+---------+
    +trans_id 是这个表的主键。
    +表中的每一列包含银行的交易信息。
    +ID 为 paid_by 的用户给 ID 为 paid_to 的用户转账。
    +
    + +

     

    + +

    力扣银行 (LCB) 帮助程序员们完成虚拟支付。我们的银行在表 Transaction 中记录每条交易信息,我们要查询每个用户的当前余额,并检查他们是否已透支(当前额度小于 0)。

    + +

    写一条 SQL 语句,查询:

    + +
      +
    • user_id 用户 ID
    • +
    • user_name 用户名
    • +
    • credit 完成交易后的余额
    • +
    • credit_limit_breached 检查是否透支 ("Yes" 或 "No")
    • +
    + +

    任意顺序返回结果表。

    + +

     

    + +

    查询格式见如下示例:

    + +
    +Users 表:
    ++------------+--------------+-------------+
    +| user_id    | user_name    | credit      |
    ++------------+--------------+-------------+
    +| 1          | Moustafa     | 100         |
    +| 2          | Jonathan     | 200         |
    +| 3          | Winston      | 10000       |
    +| 4          | Luis         | 800         | 
    ++------------+--------------+-------------+
    +
    +Transactions 表:
    ++------------+------------+------------+----------+---------------+
    +| trans_id   | paid_by    | paid_to    | amount   | transacted_on |
    ++------------+------------+------------+----------+---------------+
    +| 1          | 1          | 3          | 400      | 2020-08-01    |
    +| 2          | 3          | 2          | 500      | 2020-08-02    |
    +| 3          | 2          | 1          | 200      | 2020-08-03    |
    ++------------+------------+------------+----------+---------------+
    +
    +结果表:
    ++------------+------------+------------+-----------------------+
    +| user_id    | user_name  | credit     | credit_limit_breached |
    ++------------+------------+------------+-----------------------+
    +| 1          | Moustafa   | -100       | Yes                   | 
    +| 2          | Jonathan   | 500        | No                    |
    +| 3          | Winston    | 9900       | No                    |
    +| 4          | Luis       | 800        | No                    |
    ++------------+------------+------------+-----------------------+
    +Moustafa 在 "2020-08-01" 支付了 $400 并在 "2020-08-03" 收到了 $200 ,当前额度 (100 -400 +200) = -$100
    +Jonathan 在 "2020-08-02" 收到了 $500 并在 "2020-08-08" 支付了 $200 ,当前额度 (200 +500 -200) = $500
    +Winston 在 "2020-08-01" 收到了 $400 并在 "2020-08-03" 支付了 $500 ,当前额度 (10000 +400 -500) = $9900
    +Luis 未收到任何转账信息,额度 = $800
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1556.leetcode1556 Thousand Separator-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1556.leetcode1556 Thousand Separator-zh.md" new file mode 100644 index 00000000..1b457a43 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1556.leetcode1556 Thousand Separator-zh.md" @@ -0,0 +1,74 @@ +# [1556. 千位分隔数](https://leetcode-cn.com/problems/thousand-separator) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1556.Thousand%20Separator/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,请你每隔三位添加点(即 "." 符号)作为千位分隔符,并将结果以字符串格式返回。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 987
    +输出:"987"
    +
    + +

    示例 2:

    + +
    输入:n = 1234
    +输出:"1.234"
    +
    + +

    示例 3:

    + +
    输入:n = 123456789
    +输出:"123.456.789"
    +
    + +

    示例 4:

    + +
    输入:n = 0
    +输出:"0"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n < 2^31
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1557.leetcode1557 Minimum Number of Vertices to Reach All Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1557.leetcode1557 Minimum Number of Vertices to Reach All Nodes-zh.md" new file mode 100644 index 00000000..c8a8e2aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1557.leetcode1557 Minimum Number of Vertices to Reach All Nodes-zh.md" @@ -0,0 +1,75 @@ +# [1557. 可以到达所有点的最少点数目](https://leetcode-cn.com/problems/minimum-number-of-vertices-to-reach-all-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1557.Minimum%20Number%20of%20Vertices%20to%20Reach%20All%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给你一个 有向无环图 , n 个节点编号为 0 到 n-1 ,以及一个边数组 edges ,其中 edges[i] = [fromi, toi] 表示一条从点  fromi 到点 toi 的有向边。

    + +

    找到最小的点集使得从这些点出发能到达图中所有点。题目保证解存在且唯一。

    + +

    你可以以任意顺序返回这些节点编号。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
    +输出:[0,3]
    +解释:从单个节点出发无法到达所有节点。从 0 出发我们可以到达 [0,1,2,5] 。从 3 出发我们可以到达 [3,4,2,5] 。所以我们输出 [0,3] 。
    + +

    示例 2:

    + +

    + +
    输入:n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
    +输出:[0,2,3]
    +解释:注意到节点 0,3 和 2 无法从其他节点到达,所以我们必须将它们包含在结果点集中,这些点都能到达节点 1 和 4 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 10^5
    • +
    • 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
    • +
    • edges[i].length == 2
    • +
    • 0 <= fromi, toi < n
    • +
    • 所有点对 (fromi, toi) 互不相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1558.leetcode1558 Minimum Numbers of Function Calls to Make Target Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1558.leetcode1558 Minimum Numbers of Function Calls to Make Target Array-zh.md" new file mode 100644 index 00000000..7c2b1a3c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1558.leetcode1558 Minimum Numbers of Function Calls to Make Target Array-zh.md" @@ -0,0 +1,100 @@ +# [1558. 得到目标数组的最少函数调用次数](https://leetcode-cn.com/problems/minimum-numbers-of-function-calls-to-make-target-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1558.Minimum%20Numbers%20of%20Function%20Calls%20to%20Make%20Target%20Array/README_EN.md) + +## 题目描述 + + + +

    + +

    给你一个与 nums 大小相同且初始值全为 0 的数组 arr ,请你调用以上函数得到整数数组 nums 。

    + +

    请你返回将 arr 变成 nums 的最少函数调用次数。

    + +

    答案保证在 32 位有符号整数以内。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,5]
    +输出:5
    +解释:给第二个数加 1 :[0, 0] 变成 [0, 1] (1 次操作)。
    +将所有数字乘以 2 :[0, 1] -> [0, 2] -> [0, 4] (2 次操作)。
    +给两个数字都加 1 :[0, 4] -> [1, 4] -> [1, 5] (2 次操作)。
    +总操作次数为:1 + 2 + 2 = 5 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,2]
    +输出:3
    +解释:给两个数字都加 1 :[0, 0] -> [0, 1] -> [1, 1] (2 次操作)。
    +将所有数字乘以 2 : [1, 1] -> [2, 2] (1 次操作)。
    +总操作次数为: 2 + 1 = 3 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [4,2,5]
    +输出:6
    +解释:(初始)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5] (nums 数组)。
    +
    + +

    示例 4:

    + +
    +输入:nums = [3,2,2,4]
    +输出:7
    +
    + +

    示例 5:

    + +
    +输入:nums = [2,4,8,16]
    +输出:8
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • 0 <= nums[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1559.leetcode1559 Detect Cycles in 2D Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1559.leetcode1559 Detect Cycles in 2D Grid-zh.md" new file mode 100644 index 00000000..12bd98c7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1559.leetcode1559 Detect Cycles in 2D Grid-zh.md" @@ -0,0 +1,88 @@ +# [1559. 二维网格图中探测环](https://leetcode-cn.com/problems/detect-cycles-in-2d-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1559.Detect%20Cycles%20in%202D%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个二维字符网格数组 grid ,大小为 m x n ,你需要检查 grid 中是否存在 相同值 形成的环。

    + +

    一个环是一条开始和结束于同一个格子的长度 大于等于 4 的路径。对于一个给定的格子,你可以移动到它上、下、左、右四个方向相邻的格子之一,可以移动的前提是这两个格子有 相同的值 

    + +

    同时,你也不能回到上一次移动时所在的格子。比方说,环  (1, 1) -> (1, 2) -> (1, 1) 是不合法的,因为从 (1, 2) 移动到 (1, 1) 回到了上一次移动时的格子。

    + +

    如果 grid 中有相同值形成的环,请你返回 true ,否则返回 false 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
    +输出:true
    +解释:如下图所示,有 2 个用不同颜色标出来的环:
    +
    +
    + +

    示例 2:

    + +

    + +
    输入:grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
    +输出:true
    +解释:如下图所示,只有高亮所示的一个合法环:
    +
    +
    + +

    示例 3:

    + +

    + +
    输入:grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m <= 500
    • +
    • 1 <= n <= 500
    • +
    • grid 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1560.leetcode1560 Most Visited Sector in a Circular Track-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1560.leetcode1560 Most Visited Sector in a Circular Track-zh.md" new file mode 100644 index 00000000..1eaa8a7e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1560.leetcode1560 Most Visited Sector in a Circular Track-zh.md" @@ -0,0 +1,80 @@ +# [1560. 圆形赛道上经过次数最多的扇区](https://leetcode-cn.com/problems/most-visited-sector-in-a-circular-track) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1560.Most%20Visited%20Sector%20in%20%20a%20Circular%20Track/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n 和一个整数数组 rounds 。有一条圆形赛道由 n 个扇区组成,扇区编号从 1n 。现将在这条赛道上举办一场马拉松比赛,该马拉松全程由 m 个阶段组成。其中,第 i 个阶段将会从扇区 rounds[i - 1] 开始,到扇区 rounds[i] 结束。举例来说,第 1 阶段从 rounds[0] 开始,到 rounds[1] 结束。

    + +

    请你以数组形式返回经过次数最多的那几个扇区,按扇区编号 升序 排列。

    + +

    注意,赛道按扇区编号升序逆时针形成一个圆(请参见第一个示例)。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 4, rounds = [1,3,1,2]
    +输出:[1,2]
    +解释:本场马拉松比赛从扇区 1 开始。经过各个扇区的次序如下所示:
    +1 --> 2 --> 3(阶段 1 结束)--> 4 --> 1(阶段 2 结束)--> 2(阶段 3 结束,即本场马拉松结束)
    +其中,扇区 1 和 2 都经过了两次,它们是经过次数最多的两个扇区。扇区 3 和 4 都只经过了一次。
    + +

    示例 2:

    + +
    输入:n = 2, rounds = [2,1,2,1,2,1,2,1,2]
    +输出:[2]
    +
    + +

    示例 3:

    + +
    输入:n = 7, rounds = [1,3,5,7]
    +输出:[1,2,3,4,5,6,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • 1 <= m <= 100
    • +
    • rounds.length == m + 1
    • +
    • 1 <= rounds[i] <= n
    • +
    • rounds[i] != rounds[i + 1] ,其中 0 <= i < m
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1561.leetcode1561 Maximum Number of Coins You Can Get-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1561.leetcode1561 Maximum Number of Coins You Can Get-zh.md" new file mode 100644 index 00000000..1c3aef35 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1561.leetcode1561 Maximum Number of Coins You Can Get-zh.md" @@ -0,0 +1,86 @@ +# [1561. 你可以获得的最大硬币数目](https://leetcode-cn.com/problems/maximum-number-of-coins-you-can-get) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1561.Maximum%20Number%20of%20Coins%20You%20Can%20Get/README_EN.md) + +## 题目描述 + + + +

    有 3n 堆数目不一的硬币,你和你的朋友们打算按以下方式分硬币:

    + +
      +
    • 每一轮中,你将会选出 任意 3 堆硬币(不一定连续)。
    • +
    • Alice 将会取走硬币数量最多的那一堆。
    • +
    • 你将会取走硬币数量第二多的那一堆。
    • +
    • Bob 将会取走最后一堆。
    • +
    • 重复这个过程,直到没有更多硬币。
    • +
    + +

    给你一个整数数组 piles ,其中 piles[i] 是第 i 堆中硬币的数目。

    + +

    返回你可以获得的最大硬币数目。

    + +

     

    + +

    示例 1:

    + +
    输入:piles = [2,4,1,2,7,8]
    +输出:9
    +解释:选出 (2, 7, 8) ,Alice 取走 8 枚硬币的那堆,你取走 7 枚硬币的那堆,Bob 取走最后一堆。
    +选出 (1, 2, 4) , Alice 取走 4 枚硬币的那堆,你取走 2 枚硬币的那堆,Bob 取走最后一堆。
    +你可以获得的最大硬币数目:7 + 2 = 9.
    +考虑另外一种情况,如果选出的是 (1, 2, 8) 和 (2, 4, 7) ,你就只能得到 2 + 4 = 6 枚硬币,这不是最优解。
    +
    + +

    示例 2:

    + +
    输入:piles = [2,4,5]
    +输出:4
    +
    + +

    示例 3:

    + +
    输入:piles = [9,8,7,6,5,1,2,3,4]
    +输出:18
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= piles.length <= 10^5
    • +
    • piles.length % 3 == 0
    • +
    • 1 <= piles[i] <= 10^4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1562.leetcode1562 Find Latest Group of Size M-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1562.leetcode1562 Find Latest Group of Size M-zh.md" new file mode 100644 index 00000000..9ee200da --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1562.leetcode1562 Find Latest Group of Size M-zh.md" @@ -0,0 +1,97 @@ +# [1562. 查找大小为 M 的最新分组](https://leetcode-cn.com/problems/find-latest-group-of-size-m) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1562.Find%20Latest%20Group%20of%20Size%20M/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 arr ,该数组表示一个从 1n 的数字排列。有一个长度为 n 的二进制字符串,该字符串上的所有位最初都设置为 0

    + +

    在从 1n 的每个步骤 i 中(假设二进制字符串和 arr 都是从 1 开始索引的情况下),二进制字符串上位于位置 arr[i] 的位将会设为 1

    + +

    给你一个整数 m ,请你找出二进制字符串上存在长度为 m 的一组 1 的最后步骤。一组 1 是一个连续的、由 1 组成的子串,且左右两边不再有可以延伸的 1

    + +

    返回存在长度 恰好m一组 1  的最后步骤。如果不存在这样的步骤,请返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [3,5,1,2,4], m = 1
    +输出:4
    +解释:
    +步骤 1:"00100",由 1 构成的组:["1"]
    +步骤 2:"00101",由 1 构成的组:["1", "1"]
    +步骤 3:"10101",由 1 构成的组:["1", "1", "1"]
    +步骤 4:"11101",由 1 构成的组:["111", "1"]
    +步骤 5:"11111",由 1 构成的组:["11111"]
    +存在长度为 1 的一组 1 的最后步骤是步骤 4 。
    + +

    示例 2:

    + +
    输入:arr = [3,1,5,4,2], m = 2
    +输出:-1
    +解释:
    +步骤 1:"00100",由 1 构成的组:["1"]
    +步骤 2:"10100",由 1 构成的组:["1", "1"]
    +步骤 3:"10101",由 1 构成的组:["1", "1", "1"]
    +步骤 4:"10111",由 1 构成的组:["1", "111"]
    +步骤 5:"11111",由 1 构成的组:["11111"]
    +不管是哪一步骤都无法形成长度为 2 的一组 1 。
    +
    + +

    示例 3:

    + +
    输入:arr = [1], m = 1
    +输出:1
    +
    + +

    示例 4:

    + +
    输入:arr = [2,1], m = 2
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == arr.length
    • +
    • 1 <= n <= 10^5
    • +
    • 1 <= arr[i] <= n
    • +
    • arr 中的所有整数 互不相同
    • +
    • 1 <= m <= arr.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1563.leetcode1563 Stone Game V-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1563.leetcode1563 Stone Game V-zh.md" new file mode 100644 index 00000000..871c2c3e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1563.leetcode1563 Stone Game V-zh.md" @@ -0,0 +1,78 @@ +# [1563. 石子游戏 V](https://leetcode-cn.com/problems/stone-game-v) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1563.Stone%20Game%20V/README_EN.md) + +## 题目描述 + + + +

    几块石子 排成一行 ,每块石子都有一个关联值,关联值为整数,由数组 stoneValue 给出。

    + +

    游戏中的每一轮:Alice 会将这行石子分成两个 非空行(即,左侧行和右侧行);Bob 负责计算每一行的值,即此行中所有石子的值的总和。Bob 会丢弃值最大的行,Alice 的得分为剩下那行的值(每轮累加)。如果两行的值相等,Bob 让 Alice 决定丢弃哪一行。下一轮从剩下的那一行开始。

    + +

    剩下一块石子 时,游戏结束。Alice 的分数最初为 0

    + +

    返回 Alice 能够获得的最大分数

    + +

     

    + +

    示例 1:

    + +
    输入:stoneValue = [6,2,3,4,5,5]
    +输出:18
    +解释:在第一轮中,Alice 将行划分为 [6,2,3],[4,5,5] 。左行的值是 11 ,右行的值是 14 。Bob 丢弃了右行,Alice 的分数现在是 11 。
    +在第二轮中,Alice 将行分成 [6],[2,3] 。这一次 Bob 扔掉了左行,Alice 的分数变成了 16(11 + 5)。
    +最后一轮 Alice 只能将行分成 [2],[3] 。Bob 扔掉右行,Alice 的分数现在是 18(16 + 2)。游戏结束,因为这行只剩下一块石头了。
    +
    + +

    示例 2:

    + +
    输入:stoneValue = [7,7,7,7,7,7,7]
    +输出:28
    +
    + +

    示例 3:

    + +
    输入:stoneValue = [4]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= stoneValue.length <= 500
    • +
    • 1 <= stoneValue[i] <= 10^6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1564.leetcode1564 Put Boxes Into the Warehouse I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1564.leetcode1564 Put Boxes Into the Warehouse I-zh.md" new file mode 100644 index 00000000..7b08512d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1564.leetcode1564 Put Boxes Into the Warehouse I-zh.md" @@ -0,0 +1,104 @@ +# [1564. 把箱子放进仓库里 I](https://leetcode-cn.com/problems/put-boxes-into-the-warehouse-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1564.Put%20Boxes%20Into%20the%20Warehouse%20I/README_EN.md) + +## 题目描述 + + + +

    给定两个正整数数组 boxes 和 warehouse ,分别包含单位宽度的箱子的高度,以及仓库中 n 个房间各自的高度。仓库的房间分别从 0 到 n - 1 自左向右编号, warehouse[i] (索引从 0 开始)是第 i 个房间的高度。

    + +

    箱子放进仓库时遵循下列规则:

    + +
      +
    • 箱子不可叠放。
    • +
    • 你可以重新调整箱子的顺序。
    • +
    • 箱子只能从左向右推进仓库中。
    • +
    • 如果仓库中某房间的高度小于某箱子的高度,则这个箱子和之后的箱子都会停在这个房间的前面。
    • +
    + +

    你最多可以在仓库中放进多少个箱子?

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:boxes = [4,3,4,1], warehouse = [5,3,3,4,1]
    +输出:3
    +解释:
    +
    +我们可以先把高度为 1 的箱子放入 4 号房间,然后再把高度为 3 的箱子放入 1 号、 2 号或 3 号房间,最后再把高度为 4 的箱子放入 0 号房间。
    +我们不可能把所有 4 个箱子全部放进仓库里。
    + +

    示例 2:

    + +

    + +
    +输入:boxes = [1,2,2,3,4], warehouse = [3,4,1,2]
    +输出:3
    +解释:
    +
    +我们注意到,不可能把高度为 4 的箱子放入仓库中,因为它不能通过高度为 3 的房间。
    +而且,对于最后两个房间 2 号和 3 号来说,只有高度为 1 的箱子可以放进去。
    +我们最多可以放进 3 个箱子,如上图所示。黄色的箱子也可以放入 2 号房间。
    +交换橙色和绿色箱子的位置,或是将这两个箱子与红色箱子交换位置,也是可以的。
    + +

    示例 3:

    + +
    +输入:boxes = [1,2,3], warehouse = [1,2,3,4]
    +输出:1
    +解释:由于第一个房间的高度为 1,我们只能放进高度为 1 的箱子。
    +
    + +

    示例 4:

    + +
    +输入:boxes = [4,5,6], warehouse = [3,3,3,3,3]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == warehouse.length
    • +
    • 1 <= boxes.length, warehouse.length <= 10^5
    • +
    • 1 <= boxes[i], warehouse[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1565.leetcode1565 Unique Orders and Customers Per Month-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1565.leetcode1565 Unique Orders and Customers Per Month-zh.md" new file mode 100644 index 00000000..4a7fa701 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1565.leetcode1565 Unique Orders and Customers Per Month-zh.md" @@ -0,0 +1,92 @@ +# [1565. 按月统计订单数与顾客数](https://leetcode-cn.com/problems/unique-orders-and-customers-per-month) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1565.Unique%20Orders%20and%20Customers%20Per%20Month/README_EN.md) + +## 题目描述 + + + +

    表:Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| invoice       | int     |
    ++---------------+---------+
    +order_id 是 Orders 表的主键
    +这张表包含顾客(customer_id)所下订单的信息
    +
    + +

    写一个查询语句来 按月 统计 金额大于 $20 的唯一 订单数 和唯一 顾客数 。

    + +

    查询结果无排序要求。

    + +

    查询结果格式如下面例子所示:

    + +
    +Orders
    ++----------+------------+-------------+------------+
    +| order_id | order_date | customer_id | invoice    |
    ++----------+------------+-------------+------------+
    +| 1        | 2020-09-15 | 1           | 30         |
    +| 2        | 2020-09-17 | 2           | 90         |
    +| 3        | 2020-10-06 | 3           | 20         |
    +| 4        | 2020-10-20 | 3           | 21         |
    +| 5        | 2020-11-10 | 1           | 10         |
    +| 6        | 2020-11-21 | 2           | 15         |
    +| 7        | 2020-12-01 | 4           | 55         |
    +| 8        | 2020-12-03 | 4           | 77         |
    +| 9        | 2021-01-07 | 3           | 31         |
    +| 10       | 2021-01-15 | 2           | 20         |
    ++----------+------------+-------------+------------+
    +
    +Result 表:
    ++---------+-------------+----------------+
    +| month   | order_count | customer_count |
    ++---------+-------------+----------------+
    +| 2020-09 | 2           | 2              |
    +| 2020-10 | 1           | 1              |
    +| 2020-12 | 2           | 1              |
    +| 2021-01 | 1           | 1              |
    ++---------+-------------+----------------+
    +在 2020 年 09 月有 2 份来自 2 位不同顾客的金额大于 $20 的订单
    +在 2020 年 10 月有 2 份来自 1 位顾客的订单并且只有其中的 1 份订单金额大于 $20 
    +在 2020 年 11 月有 2 份来自 2 位不同顾客的订单但由于金额都小于 $20 所以我们的查询结果中不包含这个月的数据
    +在 2020 年 12 月有 2 份来自 1 位顾客的订单且 2 份订单金额都大于 $20
    +在 2021 年 01 月有 2 份来自 2 位不同顾客的订单但只有其中一份订单金额大于 $20 
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1566.leetcode1566 Detect Pattern of Length M Repeated K or More Times-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1566.leetcode1566 Detect Pattern of Length M Repeated K or More Times-zh.md" new file mode 100644 index 00000000..c3538d18 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1566.leetcode1566 Detect Pattern of Length M Repeated K or More Times-zh.md" @@ -0,0 +1,92 @@ +# [1566. 重复至少 K 次且长度为 M 的模式](https://leetcode-cn.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1566.Detect%20Pattern%20of%20Length%20M%20Repeated%20K%20or%20More%20Times/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 arr,请你找出一个长度为 m 且在数组中至少重复 k 次的模式。

    + +

    模式 是由一个或多个值组成的子数组(连续的子序列),连续 重复多次但 不重叠 。 模式由其长度和重复次数定义。

    + +

    如果数组中存在至少重复 k 次且长度为 m 的模式,则返回 true ,否则返回  false

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,2,4,4,4,4], m = 1, k = 3
    +输出:true
    +解释:模式 (4) 的长度为 1 ,且连续重复 4 次。注意,模式可以重复 k 次或更多次,但不能少于 k 次。
    +
    + +

    示例 2:

    + +
    输入:arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
    +输出:true
    +解释:模式 (1,2) 长度为 2 ,且连续重复 2 次。另一个符合题意的模式是 (2,1) ,同样重复 2 次。
    +
    + +

    示例 3:

    + +
    输入:arr = [1,2,1,2,1,3], m = 2, k = 3
    +输出:false
    +解释:模式 (1,2) 长度为 2 ,但是只连续重复 2 次。不存在长度为 2 且至少重复 3 次的模式。
    +
    + +

    示例 4:

    + +
    输入:arr = [1,2,3,1,2], m = 2, k = 2
    +输出:false
    +解释:模式 (1,2) 出现 2 次但并不连续,所以不能算作连续重复 2 次。
    +
    + +

    示例 5:

    + +
    输入:arr = [2,2,2,2], m = 2, k = 3
    +输出:false
    +解释:长度为 2 的模式只有 (2,2) ,但是只连续重复 2 次。注意,不能计算重叠的重复次数。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 100
    • +
    • 1 <= m <= 100
    • +
    • 2 <= k <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1567.leetcode1567 Maximum Length of Subarray With Positive Product-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1567.leetcode1567 Maximum Length of Subarray With Positive Product-zh.md" new file mode 100644 index 00000000..f482a3a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1567.leetcode1567 Maximum Length of Subarray With Positive Product-zh.md" @@ -0,0 +1,230 @@ +# [1567. 乘积为正数的最长子数组长度](https://leetcode-cn.com/problems/maximum-length-of-subarray-with-positive-product) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1567.Maximum%20Length%20of%20Subarray%20With%20Positive%20Product/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,请你求出乘积为正数的最长子数组的长度。

    + +

    一个数组的子数组是由原数组中零个或者更多个连续数字组成的数组。

    + +

    请你返回乘积为正数的最长子数组长度。

    + +

     

    + +

    示例  1:

    + +
    输入:nums = [1,-2,-3,4]
    +输出:4
    +解释:数组本身乘积就是正数,值为 24 。
    +
    + +

    示例 2:

    + +
    输入:nums = [0,1,-2,-3,-4]
    +输出:3
    +解释:最长乘积为正数的子数组为 [1,-2,-3] ,乘积为 6 。
    +注意,我们不能把 0 也包括到子数组中,因为这样乘积为 0 ,不是正数。
    + +

    示例 3:

    + +
    输入:nums = [-1,-2,-3,0,1]
    +输出:2
    +解释:乘积为正数的最长子数组是 [-1,-2] 或者 [-2,-3] 。
    +
    + +

    示例 4:

    + +
    输入:nums = [-1,2]
    +输出:1
    +
    + +

    示例 5:

    + +
    输入:nums = [1,2,3,5,-6,4,0,10]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 10^5
    • +
    • -10^9 <= nums[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def getMaxLen(self, nums: List[int]) -> int: + f1 = 1 if nums[0] > 0 else 0 + f2 = 1 if nums[0] < 0 else 0 + res = f1 + for num in nums[1:]: + pf1, pf2 = f1, f2 + if num > 0: + f1 += 1 + if f2 > 0: + f2 += 1 + else: + f2 = 0 + elif num < 0: + pf1, pf2 = f1, f2 + f2 = pf1 + 1 + if pf2 > 0: + f1 = pf2 + 1 + else: + f1 = 0 + else: + f1 = 0 + f2 = 0 + res = max(res, f1) + return res +``` + +### **Java** + + + +```java +class Solution { + public int getMaxLen(int[] nums) { + int f1 = nums[0] > 0 ? 1 : 0; + int f2 = nums[0] < 0 ? 1 : 0; + int res = f1; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] > 0) { + ++f1; + f2 = f2 > 0 ? f2 + 1 : 0; + } else if (nums[i] < 0) { + int pf1 = f1, pf2 = f2; + f2 = pf1 + 1; + f1 = pf2 > 0 ? pf2 + 1 : 0; + } else { + f1 = 0; + f2 = 0; + } + res = Math.max(res, f1); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function getMaxLen(nums: number[]): number { + // 连续正数计数n1, 连续负数计数n2 + let n1 = nums[0] > 0 ? 1 : 0, n2 = nums[0] < 0 ? 1 : 0; + let ans = n1; + for (let i = 1; i < nums.length; ++i) { + let cur = nums[i]; + if (cur == 0) { + n1 = 0, n2 = 0; + } else if (cur > 0) { + ++n1; + n2 = n2 > 0 ? n2 + 1 : 0; + } else { + let t1 = n1, t2 = n2; + n1 = t2 > 0 ? t2 + 1 : 0; + n2 = t1 + 1; + } + ans = Math.max(ans, n1); + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int getMaxLen(vector& nums) { + int f1 = nums[0] > 0 ? 1 : 0; + int f2 = nums[0] < 0 ? 1 : 0; + int res = f1; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > 0) { + ++f1; + f2 = f2 > 0 ? f2 + 1 : 0; + } else if (nums[i] < 0) { + int pf1 = f1, pf2 = f2; + f2 = pf1 + 1; + f1 = pf2 > 0 ? pf2 + 1 : 0; + } else { + f1 = 0; + f2 = 0; + } + res = max(res, f1); + } + return res; + } +}; +``` + +### **Go** + +```go +func getMaxLen(nums []int) int { + f1, f2 := 0, 0 + if nums[0] > 0 { + f1 = 1 + } + if nums[0] < 0 { + f2 = 1 + } + res := f1 + for i := 1; i < len(nums); i++ { + if nums[i] > 0 { + f1++ + if f2 > 0 { + f2++ + } else { + f2 = 0 + } + } else if nums[i] < 0 { + pf1, pf2 := f1, f2 + f2 = pf1 + 1 + if pf2 > 0 { + f1 = pf2 + 1 + } else { + f1 = 0 + } + } else { + f1, f2 = 0, 0 + } + res = max(res, f1) + } + return res +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1568.leetcode1568 Minimum Number of Days to Disconnect Island-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1568.leetcode1568 Minimum Number of Days to Disconnect Island-zh.md" new file mode 100644 index 00000000..3ceff0ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1568.leetcode1568 Minimum Number of Days to Disconnect Island-zh.md" @@ -0,0 +1,98 @@ +# [1568. 使陆地分离的最少天数](https://leetcode-cn.com/problems/minimum-number-of-days-to-disconnect-island) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1568.Minimum%20Number%20of%20Days%20to%20Disconnect%20Island/README_EN.md) + +## 题目描述 + + + +

    给你一个由若干 01 组成的二维网格 grid ,其中 0 表示水,而 1 表示陆地。岛屿由水平方向或竖直方向上相邻的 1 (陆地)连接形成。

    + +

    如果 恰好只有一座岛屿 ,则认为陆地是 连通的 ;否则,陆地就是 分离的

    + +

    一天内,可以将任何单个陆地单元(1)更改为水单元(0)。

    + +

    返回使陆地分离的最少天数。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]
    +输出:2
    +解释:至少需要 2 天才能得到分离的陆地。
    +将陆地 grid[1][1] 和 grid[0][2] 更改为水,得到两个分离的岛屿。
    +
    + +

    示例 2:

    + +
    输入:grid = [[1,1]]
    +输出:2
    +解释:如果网格中都是水,也认为是分离的 ([[1,1]] -> [[0,0]]),0 岛屿。
    +
    + +

    示例 3:

    + +
    输入:grid = [[1,0,1,0]]
    +输出:0
    +
    + +

    示例 4:

    + +
    输入:grid = [[1,1,0,1,1],
    +             [1,1,1,1,1],
    +             [1,1,0,1,1],
    +             [1,1,0,1,1]]
    +输出:1
    +
    + +

    示例 5:

    + +
    输入:grid = [[1,1,0,1,1],
    +             [1,1,1,1,1],
    +             [1,1,0,1,1],
    +             [1,1,1,1,1]]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= grid.length, grid[i].length <= 30
    • +
    • grid[i][j]01
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1569.leetcode1569 Number of Ways to Reorder Array to Get Same BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1569.leetcode1569 Number of Ways to Reorder Array to Get Same BST-zh.md" new file mode 100644 index 00000000..1ef3ae78 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1569.leetcode1569 Number of Ways to Reorder Array to Get Same BST-zh.md" @@ -0,0 +1,105 @@ +# [1569. 将子数组重新排序得到同一个二叉查找树的方案数](https://leetcode-cn.com/problems/number-of-ways-to-reorder-array-to-get-same-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1569.Number%20of%20Ways%20to%20Reorder%20Array%20to%20Get%20Same%20BST/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums 表示 1 到 n 的一个排列。我们按照元素在 nums 中的顺序依次插入一个初始为空的二叉查找树(BST)。请你统计将 nums 重新排序后,统计满足如下条件的方案数:重排后得到的二叉查找树与 nums 原本数字顺序得到的二叉查找树相同。

    + +

    比方说,给你 nums = [2,1,3],我们得到一棵 2 为根,1 为左孩子,3 为右孩子的树。数组 [2,3,1] 也能得到相同的 BST,但 [3,2,1] 会得到一棵不同的 BST 。

    + +

    请你返回重排 nums 后,与原数组 nums 得到相同二叉查找树的方案数。

    + +

    由于答案可能会很大,请将结果对 10^9 + 7 取余数。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:nums = [2,1,3]
    +输出:1
    +解释:我们将 nums 重排, [2,3,1] 能得到相同的 BST 。没有其他得到相同 BST 的方案了。
    +
    + +

    示例 2:

    + +

    + +
    输入:nums = [3,4,5,1,2]
    +输出:5
    +解释:下面 5 个数组会得到相同的 BST:
    +[3,1,2,4,5]
    +[3,1,4,2,5]
    +[3,1,4,5,2]
    +[3,4,1,2,5]
    +[3,4,1,5,2]
    +
    + +

    示例 3:

    + +

    + +
    输入:nums = [1,2,3]
    +输出:0
    +解释:没有别的排列顺序能得到相同的 BST 。
    +
    + +

    示例 4:

    + +

    + +
    输入:nums = [3,1,2,5,4,6]
    +输出:19
    +
    + +

    示例  5:

    + +
    输入:nums = [9,4,2,1,3,6,5,7,8,14,11,10,12,13,16,15,17,18]
    +输出:216212978
    +解释:得到相同 BST 的方案数是 3216212999。将它对 10^9 + 7 取余后得到 216212978。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= nums.length
    • +
    • nums 中所有数 互不相同 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1570.leetcode1570 Dot Product of Two Sparse Vectors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1570.leetcode1570 Dot Product of Two Sparse Vectors-zh.md" new file mode 100644 index 00000000..be9a4b56 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1570.leetcode1570 Dot Product of Two Sparse Vectors-zh.md" @@ -0,0 +1,145 @@ +# [1570. 两个稀疏向量的点积](https://leetcode-cn.com/problems/dot-product-of-two-sparse-vectors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1570.Dot%20Product%20of%20Two%20Sparse%20Vectors/README_EN.md) + +## 题目描述 + + + +

    给定两个稀疏向量,计算它们的点积(数量积)。

    + +

    实现类 SparseVector

    + +
      +
    • SparseVector(nums) 以向量 nums 初始化对象。
    • +
    • dotProduct(vec) 计算此向量与 vec 的点积。
    • +
    + +

    稀疏向量 是指绝大多数分量为 0 的向量。你需要 高效 地存储这个向量,并计算两个稀疏向量的点积。

    + +

    进阶:当其中只有一个向量是稀疏向量时,你该如何解决此问题?

    + +

     

    + +

    示例 1:

    + +
    +输入:nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
    +输出:8
    +解释:v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
    +v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8
    +
    + +

    示例 2:

    + +
    +输入:nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
    +输出:0
    +解释:v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
    +v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0
    +
    + +

    示例 3:

    + +
    +输入:nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4]
    +输出:6
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums1.length == nums2.length
    • +
    • 1 <= n <= 10^5
    • +
    • 0 <= nums1[i], nums2[i] <= 100
    • +
    + +## 解法 + + + +哈希表实现。 + +用哈希表存储非 0 点的下标与值。求点积时,遍历长度较小的哈希表。 + + + +### **Python3** + + + +```python +class SparseVector: + def __init__(self, nums: List[int]): + self.v = {} + for i, num in enumerate(nums): + if num != 0: + self.v[i] = num + + # Return the dotProduct of two sparse vectors + def dotProduct(self, vec: 'SparseVector') -> int: + res = 0 + if len(self.v) > len(vec.v): + self.v, vec.v = vec.v, self.v + for i, num in self.v.items(): + if i not in vec.v: + continue + res += num * vec.v[i] + return res + + +# Your SparseVector object will be instantiated and called as such: +# v1 = SparseVector(nums1) +# v2 = SparseVector(nums2) +# ans = v1.dotProduct(v2) +``` + +### **Java** + + + +```java +class SparseVector { + + private Map v; + + SparseVector(int[] nums) { + v = new HashMap<>(); + for (int i = 0; i < nums.length; ++i) { + if (nums[i] != 0) { + v.put(i, nums[i]); + } + } + } + + // Return the dotProduct of two sparse vectors + public int dotProduct(SparseVector vec) { + int res = 0; + if (v.size() > vec.v.size()) { + Map t = v; + v = vec.v; + vec.v = t; + } + for (Map.Entry entry : v.entrySet()) { + int i = entry.getKey(), num = entry.getValue(); + res += num * vec.v.getOrDefault(i, 0); + } + return res; + } +} + +// Your SparseVector object will be instantiated and called as such: +// SparseVector v1 = new SparseVector(nums1); +// SparseVector v2 = new SparseVector(nums2); +// int ans = v1.dotProduct(v2); +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1571.leetcode1571 Warehouse Manager-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1571.leetcode1571 Warehouse Manager-zh.md" new file mode 100644 index 00000000..cd5333e6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1571.leetcode1571 Warehouse Manager-zh.md" @@ -0,0 +1,128 @@ +# [1571. 仓库经理](https://leetcode-cn.com/problems/warehouse-manager) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1571.Warehouse%20Manager/README_EN.md) + +## 题目描述 + + + +

    表: Warehouse

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| name         | varchar |
    +| product_id   | int     |
    +| units        | int     |
    ++--------------+---------+
    +(name, product_id) 是该表主键.
    +该表的行包含了每个仓库的所有商品信息.
    +
    + +

     

    + +

    表: Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    +| Width         | int     |
    +| Length        | int     |
    +| Height        | int     |
    ++---------------+---------+
    +product_id 是该表主键.
    +该表的行包含了每件商品以英尺为单位的尺寸(宽度, 长度和高度)信息.
    +
    + +

     

    + +

    写一个 SQL 查询来报告, 每个仓库的存货量是多少立方英尺.

    + +
      +
    • 仓库名
    • +
    • 存货量
    • +
    + +

    返回结果没有顺序要求.

    + +

    查询结果如下例所示.

    + +

     

    + +
    +Warehouse 表:
    ++------------+--------------+-------------+
    +| name       | product_id   | units       |
    ++------------+--------------+-------------+
    +| LCHouse1   | 1            | 1           |
    +| LCHouse1   | 2            | 10          |
    +| LCHouse1   | 3            | 5           |
    +| LCHouse2   | 1            | 2           |
    +| LCHouse2   | 2            | 2           |
    +| LCHouse3   | 4            | 1           |
    ++------------+--------------+-------------+
    +
    +Products 表:
    ++------------+--------------+------------+----------+-----------+
    +| product_id | product_name | Width      | Length   | Height    |
    ++------------+--------------+------------+----------+-----------+
    +| 1          | LC-TV        | 5          | 50       | 40        |
    +| 2          | LC-KeyChain  | 5          | 5        | 5         |
    +| 3          | LC-Phone     | 2          | 10       | 10        |
    +| 4          | LC-T-Shirt   | 4          | 10       | 20        |
    ++------------+--------------+------------+----------+-----------+
    +
    +Result 表:
    ++----------------+------------+
    +| WAREHOUSE_NAME | VOLUME     | 
    ++----------------+------------+
    +| LCHouse1       | 12250      | 
    +| LCHouse2       | 20250      |
    +| LCHouse3       | 800        |
    ++----------------+------------+
    +Id为1的商品(LC-TV)的存货量为 5x50x40 = 10000
    +Id为2的商品(LC-KeyChain)的存货量为 5x5x5 = 125 
    +Id为3的商品(LC-Phone)的存货量为 2x10x10 = 200
    +Id为4的商品(LC-T-Shirt)的存货量为 4x10x20 = 800
    +仓库LCHouse1: 1个单位的LC-TV + 10个单位的LC-KeyChain + 5个单位的LC-Phone.
    +          总存货量为: 1*10000 + 10*125  + 5*200 = 12250 立方英尺
    +仓库LCHouse2: 2个单位的LC-TV + 2个单位的LC-KeyChain.
    +          总存货量为: 2*10000 + 2*125 = 20250 立方英尺
    +仓库LCHouse3: 1个单位的LC-T-Shirt.
    +          总存货量为: 1*800 = 800 立方英尺.
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1572.leetcode1572 Matrix Diagonal Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1572.leetcode1572 Matrix Diagonal Sum-zh.md" new file mode 100644 index 00000000..9dcfe81e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1572.leetcode1572 Matrix Diagonal Sum-zh.md" @@ -0,0 +1,84 @@ +# [1572. 矩阵对角线元素的和](https://leetcode-cn.com/problems/matrix-diagonal-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1572.Matrix%20Diagonal%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个正方形矩阵 mat,请你返回矩阵对角线元素的和。

    + +

    请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。

    + +

     

    + +

    示例  1:

    + +

    + +
    +输入:mat = [[1,2,3],
    +            [4,5,6],
    +            [7,8,9]]
    +输出:25
    +解释:对角线的和为:1 + 5 + 9 + 3 + 7 = 25
    +请注意,元素 mat[1][1] = 5 只会被计算一次。
    +
    + +

    示例  2:

    + +
    +输入:mat = [[1,1,1,1],
    +            [1,1,1,1],
    +            [1,1,1,1],
    +            [1,1,1,1]]
    +输出:8
    +
    + +

    示例 3:

    + +
    +输入:mat = [[5]]
    +输出:5
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == mat.length == mat[i].length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= mat[i][j] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1573.leetcode1573 Number of Ways to Split a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1573.leetcode1573 Number of Ways to Split a String-zh.md" new file mode 100644 index 00000000..d8161d58 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1573.leetcode1573 Number of Ways to Split a String-zh.md" @@ -0,0 +1,88 @@ +# [1573. 分割字符串的方案数](https://leetcode-cn.com/problems/number-of-ways-to-split-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1573.Number%20of%20Ways%20to%20Split%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制串 s  (一个只包含 0 和 1 的字符串),我们可以将 s 分割成 3 个 非空 字符串 s1, s2, s3 (s1 + s2 + s3 = s)。

    + +

    请你返回分割 s 的方案数,满足 s1,s2 和 s3 中字符 '1' 的数目相同。

    + +

    由于答案可能很大,请将它对 10^9 + 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "10101"
    +输出:4
    +解释:总共有 4 种方法将 s 分割成含有 '1' 数目相同的三个子字符串。
    +"1|010|1"
    +"1|01|01"
    +"10|10|1"
    +"10|1|01"
    +
    + +

    示例 2:

    + +
    输入:s = "1001"
    +输出:0
    +
    + +

    示例 3:

    + +
    输入:s = "0000"
    +输出:3
    +解释:总共有 3 种分割 s 的方法。
    +"0|0|00"
    +"0|00|0"
    +"00|0|0"
    +
    + +

    示例 4:

    + +
    输入:s = "100100010100110"
    +输出:12
    +
    + +

     

    + +

    提示:

    + +
      +
    • s[i] == '0' 或者 s[i] == '1'
    • +
    • 3 <= s.length <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1574.leetcode1574 Shortest Subarray to be Removed to Make Array Sorted-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1574.leetcode1574 Shortest Subarray to be Removed to Make Array Sorted-zh.md" new file mode 100644 index 00000000..88168673 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1574.leetcode1574 Shortest Subarray to be Removed to Make Array Sorted-zh.md" @@ -0,0 +1,86 @@ +# [1574. 删除最短的子数组使剩余数组有序](https://leetcode-cn.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1574.Shortest%20Subarray%20to%20be%20Removed%20to%20Make%20Array%20Sorted/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,请你删除一个子数组(可以为空),使得 arr 中剩下的元素是 非递减 的。

    + +

    一个子数组指的是原数组中连续的一个子序列。

    + +

    请你返回满足题目要求的最短子数组的长度。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [1,2,3,10,4,2,3,5]
    +输出:3
    +解释:我们需要删除的最短子数组是 [10,4,2] ,长度为 3 。剩余元素形成非递减数组 [1,2,3,3,5] 。
    +另一个正确的解为删除子数组 [3,10,4] 。
    + +

    示例 2:

    + +
    +输入:arr = [5,4,3,2,1]
    +输出:4
    +解释:由于数组是严格递减的,我们只能保留一个元素。所以我们需要删除长度为 4 的子数组,要么删除 [5,4,3,2],要么删除 [4,3,2,1]。
    +
    + +

    示例 3:

    + +
    +输入:arr = [1,2,3]
    +输出:0
    +解释:数组已经是非递减的了,我们不需要删除任何元素。
    +
    + +

    示例 4:

    + +
    +输入:arr = [1]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 10^5
    • +
    • 0 <= arr[i] <= 10^9
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1575.leetcode1575 Count All Possible Routes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1575.leetcode1575 Count All Possible Routes-zh.md" new file mode 100644 index 00000000..b20e16b2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1575.leetcode1575 Count All Possible Routes-zh.md" @@ -0,0 +1,109 @@ +# [1575. 统计所有可行路径](https://leetcode-cn.com/problems/count-all-possible-routes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1575.Count%20All%20Possible%20Routes/README_EN.md) + +## 题目描述 + + + +

    给你一个 互不相同 的整数数组,其中 locations[i] 表示第 i 个城市的位置。同时给你 startfinish 和 fuel 分别表示出发城市、目的地城市和你初始拥有的汽油总量

    + +

    每一步中,如果你在城市 i ,你可以选择任意一个城市 j ,满足  j != i 且 0 <= j < locations.length ,并移动到城市 j 。从城市 i 移动到 j 消耗的汽油量为 |locations[i] - locations[j]||x| 表示 x 的绝对值。

    + +

    请注意, fuel 任何时刻都 不能 为负,且你 可以 经过任意城市超过一次(包括 start 和 finish )。

    + +

    请你返回从 start 到 finish 所有可能路径的数目。

    + +

    由于答案可能很大, 请将它对 10^9 + 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
    +输出:4
    +解释:以下为所有可能路径,每一条都用了 5 单位的汽油:
    +1 -> 3
    +1 -> 2 -> 3
    +1 -> 4 -> 3
    +1 -> 4 -> 2 -> 3
    +
    + +

    示例 2:

    + +
    +输入:locations = [4,3,1], start = 1, finish = 0, fuel = 6
    +输出:5
    +解释:以下为所有可能的路径:
    +1 -> 0,使用汽油量为 fuel = 1
    +1 -> 2 -> 0,使用汽油量为 fuel = 5
    +1 -> 2 -> 1 -> 0,使用汽油量为 fuel = 5
    +1 -> 0 -> 1 -> 0,使用汽油量为 fuel = 3
    +1 -> 0 -> 1 -> 0 -> 1 -> 0,使用汽油量为 fuel = 5
    +
    + +

    示例 3:

    + +
    +输入:locations = [5,2,1], start = 0, finish = 2, fuel = 3
    +输出:0
    +解释:没有办法只用 3 单位的汽油从 0 到达 2 。因为最短路径需要 4 单位的汽油。
    + +

    示例 4 :

    + +
    +输入:locations = [2,1,5], start = 0, finish = 0, fuel = 3
    +输出:2
    +解释:总共有两条可行路径,0 和 0 -> 1 -> 0 。
    + +

    示例 5:

    + +
    +输入:locations = [1,2,3], start = 0, finish = 2, fuel = 40
    +输出:615088286
    +解释:路径总数为 2615088300 。将结果对 10^9 + 7 取余,得到 615088286 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= locations.length <= 100
    • +
    • 1 <= locations[i] <= 10^9
    • +
    • 所有 locations 中的整数 互不相同 。
    • +
    • 0 <= start, finish < locations.length
    • +
    • 1 <= fuel <= 200
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1576.leetcode1576 Replace All 's to Avoid Consecutive Repeating Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1576.leetcode1576 Replace All 's to Avoid Consecutive Repeating Characters-zh.md" new file mode 100644 index 00000000..af1a3120 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1576.leetcode1576 Replace All 's to Avoid Consecutive Repeating Characters-zh.md" @@ -0,0 +1,128 @@ +# [1576. 替换所有的问号](https://leetcode-cn.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1576.Replace%20All%20%27s%20to%20Avoid%20Consecutive%20Repeating%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个仅包含小写英文字母和 '?' 字符的字符串 s,请你将所有的 '?' 转换为若干小写字母,使最终的字符串不包含任何 连续重复 的字符。

    + +

    注意:你 不能 修改非 '?' 字符。

    + +

    题目测试用例保证 '?' 字符 之外,不存在连续重复的字符。

    + +

    在完成所有转换(可能无需转换)后返回最终的字符串。如果有多个解决方案,请返回其中任何一个。可以证明,在给定的约束条件下,答案总是存在的。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "?zs"
    +输出:"azs"
    +解释:该示例共有 25 种解决方案,从 "azs" 到 "yzs" 都是符合题目要求的。只有 "z" 是无效的修改,因为字符串 "zzs" 中有连续重复的两个 'z' 。
    + +

    示例 2:

    + +
    输入:s = "ubv?w"
    +输出:"ubvaw"
    +解释:该示例共有 24 种解决方案,只有替换成 "v" 和 "w" 不符合题目要求。因为 "ubvvw" 和 "ubvww" 都包含连续重复的字符。
    +
    + +

    示例 3:

    + +
    输入:s = "j?qg??b"
    +输出:"jaqgacb"
    +
    + +

    示例 4:

    + +
    输入:s = "??yw?ipkj?"
    +输出:"acywaipkja"
    +
    + +

     

    + +

    提示:

    + +
      +
    • +

      1 <= s.length <= 100

      +
    • +
    • +

      s 仅包含小写英文字母和 '?' 字符

      +
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def modifyString(self, s: str) -> str: + s = list(s) + for i in range(len(s)): + if s[i] == '?': + ahead = ' ' if i == 0 else s[i - 1] + behind = ' ' if i == len(s) - 1 else s[i + 1] + for c in string.ascii_lowercase: + if c != ahead and c != behind: + s[i] = c + break + return "".join(s) +``` + +### **Java** + + + +```java +class Solution { + public String modifyString(String s) { + char[] chars = s.toCharArray(); + for (int i = 0; i < chars.length; i++) { + if (chars[i] == '?') { + // 前面的字符 + char ahead = i == 0 ? ' ' : chars[i - 1]; + // 后面的字符 + char behind = i == chars.length - 1 ? ' ' : chars[i + 1]; + char temp = 'a'; + while (temp == ahead || temp == behind) { + temp++; + } + chars[i] = temp; + } + } + return new String(chars); + } +} +``` + +### **Go** + +```go +func modifyString(s string) string { + data := []byte(" " + s + " ") + for i, c := range data { + if c == byte('?') { + ahead, behind := data[i-1], data[i+1] + for t := byte('a'); t <= byte('z'); t++ { + if t != ahead && t != behind { + data[i] = t + } + } + } + } + return string(data[1 : len(data)-1]) +} +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1577.leetcode1577 Number of Ways Where Square of Number Is Equal to Product of Two Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1577.leetcode1577 Number of Ways Where Square of Number Is Equal to Product of Two Numbers-zh.md" new file mode 100644 index 00000000..26277cc3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1577.leetcode1577 Number of Ways Where Square of Number Is Equal to Product of Two Numbers-zh.md" @@ -0,0 +1,87 @@ +# [1577. 数的平方等于两数乘积的方法数](https://leetcode-cn.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1577.Number%20of%20Ways%20Where%20Square%20of%20Number%20Is%20Equal%20to%20Product%20of%20Two%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 nums1nums2 ,请你返回根据以下规则形成的三元组的数目(类型 1 和类型 2 ):

    + +
      +
    • 类型 1:三元组 (i, j, k) ,如果 nums1[i]2 == nums2[j] * nums2[k] 其中 0 <= i < nums1.length0 <= j < k < nums2.length
    • +
    • 类型 2:三元组 (i, j, k) ,如果 nums2[i]2 == nums1[j] * nums1[k] 其中 0 <= i < nums2.length0 <= j < k < nums1.length
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:nums1 = [7,4], nums2 = [5,2,8,9]
    +输出:1
    +解释:类型 1:(1,1,2), nums1[1]^2 = nums2[1] * nums2[2] (4^2 = 2 * 8)
    + +

    示例 2:

    + +
    输入:nums1 = [1,1], nums2 = [1,1,1]
    +输出:9
    +解释:所有三元组都符合题目要求,因为 1^2 = 1 * 1
    +类型 1:(0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2), nums1[i]^2 = nums2[j] * nums2[k]
    +类型 2:(0,0,1), (1,0,1), (2,0,1), nums2[i]^2 = nums1[j] * nums1[k]
    +
    + +

    示例 3:

    + +
    输入:nums1 = [7,7,8,3], nums2 = [1,2,9,7]
    +输出:2
    +解释:有两个符合题目要求的三元组
    +类型 1:(3,0,2), nums1[3]^2 = nums2[0] * nums2[2]
    +类型 2:(3,0,1), nums2[3]^2 = nums1[0] * nums1[1]
    +
    + +

    示例 4:

    + +
    输入:nums1 = [4,7,9,11,23], nums2 = [3,5,1024,12,18]
    +输出:0
    +解释:不存在符合题目要求的三元组
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 1000
    • +
    • 1 <= nums1[i], nums2[i] <= 10^5
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1578.leetcode1578 Minimum Deletion Cost to Avoid Repeating Letters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1578.leetcode1578 Minimum Deletion Cost to Avoid Repeating Letters-zh.md" new file mode 100644 index 00000000..3ec71ef7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1578.leetcode1578 Minimum Deletion Cost to Avoid Repeating Letters-zh.md" @@ -0,0 +1,81 @@ +# [1578. 避免重复字母的最小删除成本](https://leetcode-cn.com/problems/minimum-deletion-cost-to-avoid-repeating-letters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1578.Minimum%20Deletion%20Cost%20to%20Avoid%20Repeating%20Letters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和一个整数数组 cost ,其中 cost[i] 是从 s 中删除字符 i 的代价。

    + +

    返回使字符串任意相邻两个字母不相同的最小删除成本。

    + +

    请注意,删除一个字符后,删除其他字符的成本不会改变。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abaac", cost = [1,2,3,4,5]
    +输出:3
    +解释:删除字母 "a" 的成本为 3,然后得到 "abac"(字符串中相邻两个字母不相同)。
    +
    + +

    示例 2:

    + +
    +输入:s = "abc", cost = [1,2,3]
    +输出:0
    +解释:无需删除任何字母,因为字符串中不存在相邻两个字母相同的情况。
    +
    + +

    示例 3:

    + +
    +输入:s = "aabaa", cost = [1,2,3,4,1]
    +输出:2
    +解释:删除第一个和最后一个字母,得到字符串 ("aba") 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • s.length == cost.length
    • +
    • 1 <= s.length, cost.length <= 10^5
    • +
    • 1 <= cost[i] <= 10^4
    • +
    • s 中只含有小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1579.leetcode1579 Remove Max Number of Edges to Keep Graph Fully Traversable-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1579.leetcode1579 Remove Max Number of Edges to Keep Graph Fully Traversable-zh.md" new file mode 100644 index 00000000..186a6c17 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1579.leetcode1579 Remove Max Number of Edges to Keep Graph Fully Traversable-zh.md" @@ -0,0 +1,91 @@ +# [1579. 保证图可完全遍历](https://leetcode-cn.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1579.Remove%20Max%20Number%20of%20Edges%20to%20Keep%20Graph%20Fully%20Traversable/README_EN.md) + +## 题目描述 + + + +

    Alice 和 Bob 共有一个无向图,其中包含 n 个节点和 3  种类型的边:

    + +
      +
    • 类型 1:只能由 Alice 遍历。
    • +
    • 类型 2:只能由 Bob 遍历。
    • +
    • 类型 3:Alice 和 Bob 都可以遍历。
    • +
    + +

    给你一个数组 edges ,其中 edges[i] = [typei, ui, vi] 表示节点 uivi 之间存在类型为 typei 的双向边。请你在保证图仍能够被 Alice和 Bob 完全遍历的前提下,找出可以删除的最大边数。如果从任何节点开始,Alice 和 Bob 都可以到达所有其他节点,则认为图是可以完全遍历的。

    + +

    返回可以删除的最大边数,如果 Alice 和 Bob 无法完全遍历图,则返回 -1 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
    +输出:2
    +解释:如果删除 [1,1,2] 和 [1,1,3] 这两条边,Alice 和 Bob 仍然可以完全遍历这个图。再删除任何其他的边都无法保证图可以完全遍历。所以可以删除的最大边数是 2 。
    +
    + +

    示例 2:

    + +

    + +
    输入:n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
    +输出:0
    +解释:注意,删除任何一条边都会使 Alice 和 Bob 无法完全遍历这个图。
    +
    + +

    示例 3:

    + +

    + +
    输入:n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
    +输出:-1
    +解释:在当前图中,Alice 无法从其他节点到达节点 4 。类似地,Bob 也不能达到节点 1 。因此,图无法完全遍历。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 10^5
    • +
    • 1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2)
    • +
    • edges[i].length == 3
    • +
    • 1 <= edges[i][0] <= 3
    • +
    • 1 <= edges[i][1] < edges[i][2] <= n
    • +
    • 所有元组 (typei, ui, vi) 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1580.leetcode1580 Put Boxes Into the Warehouse II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1580.leetcode1580 Put Boxes Into the Warehouse II-zh.md" new file mode 100644 index 00000000..561fb350 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1580.leetcode1580 Put Boxes Into the Warehouse II-zh.md" @@ -0,0 +1,103 @@ +# [1580. 把箱子放进仓库里 II](https://leetcode-cn.com/problems/put-boxes-into-the-warehouse-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1580.Put%20Boxes%20Into%20the%20Warehouse%20II/README_EN.md) + +## 题目描述 + + + +

    给定两个正整数数组 boxeswarehouse ,分别包含单位宽度的箱子的高度,以及仓库中n个房间各自的高度。仓库的房间分别从0 到 n - 1自左向右编号,warehouse[i](索引从 0 开始)是第 i 个房间的高度。

    + +

    箱子放进仓库时遵循下列规则:

    + +
      +
    • 箱子不可叠放。
    • +
    • 你可以重新调整箱子的顺序。
    • +
    • 箱子可以从任意方向(左边或右边)推入仓库中。
    • +
    • 如果仓库中某房间的高度小于某箱子的高度,则这个箱子和之后的箱子都会停在这个房间的前面。
    • +
    + +

    你最多可以在仓库中放进多少个箱子?

    + +

     

    + +

    示例 1:

    + +
    +输入: boxes = [1,2,2,3,4], warehouse = [3,4,1,2]
    +输出: 4
    +解释:
    +
    +我们可以按如下顺序推入箱子:
    +1- 从左边或右边把黄色箱子推入2号房间;
    +2- 从右边把橙色箱子推入3号房间;
    +3- 从左边把绿色箱子推入1号房间;
    +4- 从左边把红色箱子推入0号房间;
    +还有其他方式推入4个箱子,比如交换红色与绿色箱子,或者交换红色与橙色箱子。
    +
    + +

    示例 2:

    + +
    +输入: boxes = [3,5,5,2], warehouse = [2,1,3,4,5]
    +输出: 3
    +解释:
    +
    +因为只有一个高度大于等于5的房间,所以无法将两个高度为5的箱子都推入仓库。
    +还有其他方式推入箱子,比如将绿色箱子推入2号房间,或者在绿色及红色箱子之前将橙色箱子推入2号房间。
    +
    + +

    示例 3:

    + +
    +输入: boxes = [1,2,3], warehouse = [1,2,3,4]
    +输出: 3
    +
    + +

    示例 4:

    + +
    +输入: boxes = [4,5,6], warehouse = [3,3,3,3,3]
    +输出: 0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == warehouse.length
    • +
    • 1 <= boxes.length, warehouse.length <= 105
    • +
    • 1 <= boxes[i], warehouse[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1581.leetcode1581 Customer Who Visited but Did Not Make Any Transactions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1581.leetcode1581 Customer Who Visited but Did Not Make Any Transactions-zh.md" new file mode 100644 index 00000000..e1a27b76 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1581.leetcode1581 Customer Who Visited but Did Not Make Any Transactions-zh.md" @@ -0,0 +1,114 @@ +# [1581. 进店却未进行过交易的顾客](https://leetcode-cn.com/problems/customer-who-visited-but-did-not-make-any-transactions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1581.Customer%20Who%20Visited%20but%20Did%20Not%20Make%20Any%20Transactions/README_EN.md) + +## 题目描述 + + + +

    表:Visits

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| visit_id    | int     |
    +| customer_id | int     |
    ++-------------+---------+
    +visit_id 是该表的主键。
    +该表包含有关光临过购物中心的顾客的信息。
    +
    + +

     

    + +

    表:Transactions

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| transaction_id | int     |
    +| visit_id       | int     |
    +| amount         | int     |
    ++----------------+---------+
    +transaction_id 是此表的主键。
    +此表包含 visit_id 期间进行的交易的信息。
    +
    + +

    有一些顾客可能光顾了购物中心但没有进行交易。请你编写一个 SQL 查询,来查找这些顾客的 ID ,以及他们只光顾不交易的次数。

    + +

    返回以任何顺序排序的结果表。

    + +

    查询结果格式如下例所示:

    + +
    +Visits
    ++----------+-------------+
    +| visit_id | customer_id |
    ++----------+-------------+
    +| 1        | 23          |
    +| 2        | 9           |
    +| 4        | 30          |
    +| 5        | 54          |
    +| 6        | 96          |
    +| 7        | 54          |
    +| 8        | 54          |
    ++----------+-------------+
    +
    +Transactions
    ++----------------+----------+--------+
    +| transaction_id | visit_id | amount |
    ++----------------+----------+--------+
    +| 2              | 5        | 310    |
    +| 3              | 5        | 300    |
    +| 9              | 5        | 200    |
    +| 12             | 1        | 910    |
    +| 13             | 2        | 970    |
    ++----------------+----------+--------+
    +
    +Result 表:
    ++-------------+----------------+
    +| customer_id | count_no_trans |
    ++-------------+----------------+
    +| 54          | 2              |
    +| 30          | 1              |
    +| 96          | 1              |
    ++-------------+----------------+
    +ID = 23 的顾客曾经逛过一次购物中心,并在 ID = 12 的访问期间进行了一笔交易。
    +ID = 9 的顾客曾经逛过一次购物中心,并在 ID = 13 的访问期间进行了一笔交易。
    +ID = 30 的顾客曾经去过购物中心,并且没有进行任何交易。
    +ID = 54 的顾客三度造访了购物中心。在 2 次访问中,他们没有进行任何交易,在 1 次访问中,他们进行了 3 次交易。
    +ID = 96 的顾客曾经去过购物中心,并且没有进行任何交易。
    +如我们所见,ID 为 30 和 96 的顾客一次没有进行任何交易就去了购物中心。顾客 54 也两次访问了购物中心并且没有进行任何交易。
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1582.leetcode1582 Special Positions in a Binary Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1582.leetcode1582 Special Positions in a Binary Matrix-zh.md" new file mode 100644 index 00000000..05b5c427 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1582.leetcode1582 Special Positions in a Binary Matrix-zh.md" @@ -0,0 +1,92 @@ +# [1582. 二进制矩阵中的特殊位置](https://leetcode-cn.com/problems/special-positions-in-a-binary-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1582.Special%20Positions%20in%20a%20Binary%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j]01,请返回 矩阵 mat 中特殊位置的数目

    + +

    特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。

    + +

     

    + +

    示例 1:

    + +
    输入:mat = [[1,0,0],
    +            [0,0,1],
    +            [1,0,0]]
    +输出:1
    +解释:(1,2) 是一个特殊位置,因为 mat[1][2] == 1 且所处的行和列上所有其他元素都是 0
    +
    + +

    示例 2:

    + +
    输入:mat = [[1,0,0],
    +            [0,1,0],
    +            [0,0,1]]
    +输出:3
    +解释:(0,0), (1,1) 和 (2,2) 都是特殊位置
    +
    + +

    示例 3:

    + +
    输入:mat = [[0,0,0,1],
    +            [1,0,0,0],
    +            [0,1,1,0],
    +            [0,0,0,0]]
    +输出:2
    +
    + +

    示例 4:

    + +
    输入:mat = [[0,0,0,0,0],
    +            [1,0,0,0,0],
    +            [0,1,0,0,0],
    +            [0,0,1,0,0],
    +            [0,0,0,1,1]]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • rows == mat.length
    • +
    • cols == mat[i].length
    • +
    • 1 <= rows, cols <= 100
    • +
    • mat[i][j]01
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1583.leetcode1583 Count Unhappy Friends-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1583.leetcode1583 Count Unhappy Friends-zh.md" new file mode 100644 index 00000000..b57d4be4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1583.leetcode1583 Count Unhappy Friends-zh.md" @@ -0,0 +1,101 @@ +# [1583. 统计不开心的朋友](https://leetcode-cn.com/problems/count-unhappy-friends) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1583.Count%20Unhappy%20Friends/README_EN.md) + +## 题目描述 + + + +

    给你一份 n 位朋友的亲近程度列表,其中 n 总是 偶数

    + +

    对每位朋友 ipreferences[i] 包含一份 按亲近程度从高到低排列 的朋友列表。换句话说,排在列表前面的朋友与 i 的亲近程度比排在列表后面的朋友更高。每个列表中的朋友均以 0n-1 之间的整数表示。

    + +

    所有的朋友被分成几对,配对情况以列表 pairs 给出,其中 pairs[i] = [xi, yi] 表示 xiyi 配对,且 yixi 配对。

    + +

    但是,这样的配对情况可能会是其中部分朋友感到不开心。在 xy 配对且 uv 配对的情况下,如果同时满足下述两个条件,x 就会不开心:

    + +
      +
    • xu 的亲近程度胜过 xy,且
    • +
    • ux 的亲近程度胜过 uv
    • +
    + +

    返回 不开心的朋友的数目

    + +

     

    + +

    示例 1:

    + +
    输入:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
    +输出:2
    +解释:
    +朋友 1 不开心,因为:
    +- 1 与 0 配对,但 1 与 3 的亲近程度比 1 与 0 高,且
    +- 3 与 1 的亲近程度比 3 与 2 高。
    +朋友 3 不开心,因为:
    +- 3 与 2 配对,但 3 与 1 的亲近程度比 3 与 2 高,且
    +- 1 与 3 的亲近程度比 1 与 0 高。
    +朋友 0 和 2 都是开心的。
    +
    + +

    示例 2:

    + +
    输入:n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
    +输出:0
    +解释:朋友 0 和 1 都开心。
    +
    + +

    示例 3:

    + +
    输入:n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 500
    • +
    • n 是偶数
    • +
    • preferences.length == n
    • +
    • preferences[i].length == n - 1
    • +
    • 0 <= preferences[i][j] <= n - 1
    • +
    • preferences[i] 不包含 i
    • +
    • preferences[i] 中的所有值都是独一无二的
    • +
    • pairs.length == n/2
    • +
    • pairs[i].length == 2
    • +
    • xi != yi
    • +
    • 0 <= xi, yi <= n - 1
    • +
    • 每位朋友都 恰好 被包含在一对中
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1584.leetcode1584 Min Cost to Connect All Points-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1584.leetcode1584 Min Cost to Connect All Points-zh.md" new file mode 100644 index 00000000..975671df --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1584.leetcode1584 Min Cost to Connect All Points-zh.md" @@ -0,0 +1,97 @@ +# [1584. 连接所有点的最小费用](https://leetcode-cn.com/problems/min-cost-to-connect-all-points) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1584.Min%20Cost%20to%20Connect%20All%20Points/README_EN.md) + +## 题目描述 + + + +

    给你一个points 数组,表示 2D 平面上的一些点,其中 points[i] = [xi, yi] 。

    + +

    连接点 [xi, yi] 和点 [xj, yj] 的费用为它们之间的 曼哈顿距离 :|xi - xj| + |yi - yj| ,其中 |val| 表示 val 的绝对值。

    + +

    请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有 一条简单路径时,才认为所有点都已连接。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
    +输出:20
    +解释:
    +
    +我们可以按照上图所示连接所有点得到最小总费用,总费用为 20 。
    +注意到任意两个点之间只有唯一一条路径互相到达。
    +
    + +

    示例 2:

    + +
    +输入:points = [[3,12],[-2,5],[-4,1]]
    +输出:18
    +
    + +

    示例 3:

    + +
    +输入:points = [[0,0],[1,1],[1,0],[-1,1]]
    +输出:4
    +
    + +

    示例 4:

    + +
    +输入:points = [[-1000000,-1000000],[1000000,1000000]]
    +输出:4000000
    +
    + +

    示例 5:

    + +
    +输入:points = [[0,0]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= points.length <= 1000
    • +
    • -106 <= xi, yi <= 106
    • +
    • 所有点 (xi, yi) 两两不同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1585.leetcode1585 Check If String Is Transformable With Substring Sort Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1585.leetcode1585 Check If String Is Transformable With Substring Sort Operations-zh.md" new file mode 100644 index 00000000..074f4849 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1585.leetcode1585 Check If String Is Transformable With Substring Sort Operations-zh.md" @@ -0,0 +1,96 @@ +# [1585. 检查字符串是否可以通过排序子字符串得到另一个字符串](https://leetcode-cn.com/problems/check-if-string-is-transformable-with-substring-sort-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1585.Check%20If%20String%20Is%20Transformable%20With%20Substring%20Sort%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 s 和 t ,请你通过若干次以下操作将字符串 s 转化成字符串 t :

    + +
      +
    • 选择 s 中一个 非空 子字符串并将它包含的字符就地 升序 排序。
    • +
    + +

    比方说,对下划线所示的子字符串进行操作可以由 "14234" 得到 "12344" 。

    + +

    如果可以将字符串 s 变成 t ,返回 true 。否则,返回 false 。

    + +

    一个 子字符串 定义为一个字符串中连续的若干字符。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "84532", t = "34852"
    +输出:true
    +解释:你可以按以下操作将 s 转变为 t :
    +"84532" (从下标 2 到下标 3)-> "84352"
    +"84352" (从下标 0 到下标 2) -> "34852"
    +
    + +

    示例 2:

    + +
    +输入:s = "34521", t = "23415"
    +输出:true
    +解释:你可以按以下操作将 s 转变为 t :
    +"34521" -> "23451"
    +"23451" -> "23415"
    +
    + +

    示例 3:

    + +
    +输入:s = "12345", t = "12435"
    +输出:false
    +
    + +

    示例 4:

    + +
    +输入:s = "1", t = "2"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • s.length == t.length
    • +
    • 1 <= s.length <= 105
    • +
    • s 和 t 都只包含数字字符,即 '0' 到 '9'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1586.leetcode1586 Binary Search Tree Iterator II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1586.leetcode1586 Binary Search Tree Iterator II-zh.md" new file mode 100644 index 00000000..9bf7efdb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1586.leetcode1586 Binary Search Tree Iterator II-zh.md" @@ -0,0 +1,93 @@ +# [1586. 二叉搜索树迭代器 II](https://leetcode-cn.com/problems/binary-search-tree-iterator-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1586.Binary%20Search%20Tree%20Iterator%20II/README_EN.md) + +## 题目描述 + + + +

    实现二叉搜索树(BST)的中序遍历迭代器 BSTIterator 类:

    + +
      +
    • BSTIterator(TreeNode root) 初始化 BSTIterator 类的实例。二叉搜索树的根节点 root 作为构造函数的参数传入。内部指针使用一个不存在于树中且小于树中任意值的数值来初始化。
    • +
    • boolean hasNext() 如果当前指针在中序遍历序列中,存在右侧数值,返回 true ,否则返回 false 。
    • +
    • int next() 将指针在中序遍历序列中向右移动,然后返回移动后指针所指数值。
    • +
    • boolean hasPrev() 如果当前指针在中序遍历序列中,存在左侧数值,返回 true ,否则返回 false 。
    • +
    • int prev() 将指针在中序遍历序列中向左移动,然后返回移动后指针所指数值。
    • +
    + +

    注意,虽然我们使用树中不存在的最小值来初始化内部指针,第一次调用 next() 需要返回二叉搜索树中最小的元素。

    + +

    你可以假设 next() 和 prev() 的调用总是有效的。即,当 next()/prev() 被调用的时候,在中序遍历序列中一定存在下一个/上一个元素。

    + +

    进阶:你可以不提前遍历树中的值来解决问题吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    输入
    +["BSTIterator", "next", "next", "prev", "next", "hasNext", "next", "next", "next", "hasNext", "hasPrev", "prev", "prev"]
    +[[[7, 3, 15, null, null, 9, 20]], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null]]
    +输出
    +[null, 3, 7, 3, 7, true, 9, 15, 20, false, true, 15, 9]
    +
    +解释
    +// 划线的元素表示指针当前的位置。
    +BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); // 当前状态为 <u> </u> [3, 7, 9, 15, 20]
    +bSTIterator.next(); // 状态变为 [<u>3</u>, 7, 9, 15, 20], 返回 3
    +bSTIterator.next(); // 状态变为 [3, <u>7</u>, 9, 15, 20], 返回 7
    +bSTIterator.prev(); // 状态变为 [<u>3</u>, 7, 9, 15, 20], 返回 3
    +bSTIterator.next(); // 状态变为 [3, <u>7</u>, 9, 15, 20], 返回 7
    +bSTIterator.hasNext(); // 返回 true
    +bSTIterator.next(); // 状态变为 [3, 7, <u>9</u>, 15, 20], 返回 9
    +bSTIterator.next(); // 状态变为 [3, 7, 9, <u>15</u>, 20], 返回 15
    +bSTIterator.next(); // 状态变为 [3, 7, 9, 15, <u>20</u>], 返回 20
    +bSTIterator.hasNext(); // 返回 false
    +bSTIterator.hasPrev(); // 返回 true
    +bSTIterator.prev(); // 状态变为 [3, 7, 9, <u>15</u>, 20], 返回 15
    +bSTIterator.prev(); // 状态变为 [3, 7, <u>9</u>, 15, 20], 返回 9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点个数的范围是 [1, 105] 。
    • +
    • 0 <= Node.val <= 106
    • +
    • 最多调用 105 次 hasNext、 next、 hasPrev 和 prev 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1587.leetcode1587 Bank Account Summary II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1587.leetcode1587 Bank Account Summary II-zh.md" new file mode 100644 index 00000000..a32c784c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1587.leetcode1587 Bank Account Summary II-zh.md" @@ -0,0 +1,111 @@ +# [1587. 银行账户概要 II](https://leetcode-cn.com/problems/bank-account-summary-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1587.Bank%20Account%20Summary%20II/README_EN.md) + +## 题目描述 + + + +

    表: Users

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| account      | int     |
    +| name         | varchar |
    ++--------------+---------+
    +account 是该表的主键.
    +表中的每一行包含银行里中每一个用户的账号.
    +
    + +

     

    + +

    表: Transactions

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| trans_id      | int     |
    +| account       | int     |
    +| amount        | int     |
    +| transacted_on | date    |
    ++---------------+---------+
    +trans_id 是该表主键.
    +该表的每一行包含了所有账户的交易改变情况.
    +如果用户收到了钱, 那么金额是正的; 如果用户转了钱, 那么金额是负的.
    +所有账户的起始余额为 0.
    +
    + +

     

    + +

    写一个 SQL,  报告余额高于 10000 的所有用户的名字和余额. 账户的余额等于包含该账户的所有交易的总和.

    + +

    返回结果表单没有顺序要求.

    + +

    查询结果格式如下例所示.

    + +

     

    + +
    Users table:
    ++------------+--------------+
    +| account    | name         |
    ++------------+--------------+
    +| 900001     | Alice        |
    +| 900002     | Bob          |
    +| 900003     | Charlie      |
    ++------------+--------------+
    +
    +Transactions table:
    ++------------+------------+------------+---------------+
    +| trans_id   | account    | amount     | transacted_on |
    ++------------+------------+------------+---------------+
    +| 1          | 900001     | 7000       |  2020-08-01   |
    +| 2          | 900001     | 7000       |  2020-09-01   |
    +| 3          | 900001     | -3000      |  2020-09-02   |
    +| 4          | 900002     | 1000       |  2020-09-12   |
    +| 5          | 900003     | 6000       |  2020-08-07   |
    +| 6          | 900003     | 6000       |  2020-09-07   |
    +| 7          | 900003     | -4000      |  2020-09-11   |
    ++------------+------------+------------+---------------+
    +
    +Result table:
    ++------------+------------+
    +| name       | balance    |
    ++------------+------------+
    +| Alice      | 11000      |
    ++------------+------------+
    +Alice 的余额为(7000 + 7000 - 3000) = 11000.
    +Bob 的余额为1000.
    +Charlie 的余额为(6000 + 6000 - 4000) = 8000.
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1588.leetcode1588 Sum of All Odd Length Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1588.leetcode1588 Sum of All Odd Length Subarrays-zh.md" new file mode 100644 index 00000000..4924d5e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1588.leetcode1588 Sum of All Odd Length Subarrays-zh.md" @@ -0,0 +1,83 @@ +# [1588. 所有奇数长度子数组的和](https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1588.Sum%20of%20All%20Odd%20Length%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 arr ,请你计算所有可能的奇数长度子数组的和。

    + +

    子数组 定义为原数组中的一个连续子序列。

    + +

    请你返回 arr 中 所有奇数长度子数组的和

    + +

     

    + +

    示例 1:

    + +
    输入:arr = [1,4,2,5,3]
    +输出:58
    +解释:所有奇数长度子数组和它们的和为:
    +[1] = 1
    +[4] = 4
    +[2] = 2
    +[5] = 5
    +[3] = 3
    +[1,4,2] = 7
    +[4,2,5] = 11
    +[2,5,3] = 10
    +[1,4,2,5,3] = 15
    +我们将所有值求和得到 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
    + +

    示例 2:

    + +
    输入:arr = [1,2]
    +输出:3
    +解释:总共只有 2 个长度为奇数的子数组,[1] 和 [2]。它们的和为 3 。
    + +

    示例 3:

    + +
    输入:arr = [10,11,12]
    +输出:66
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 100
    • +
    • 1 <= arr[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1589.leetcode1589 Maximum Sum Obtained of Any Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1589.leetcode1589 Maximum Sum Obtained of Any Permutation-zh.md" new file mode 100644 index 00000000..09a6ef42 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1589.leetcode1589 Maximum Sum Obtained of Any Permutation-zh.md" @@ -0,0 +1,85 @@ +# [1589. 所有排列中的最大和](https://leetcode-cn.com/problems/maximum-sum-obtained-of-any-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1589.Maximum%20Sum%20Obtained%20of%20Any%20Permutation/README_EN.md) + +## 题目描述 + + + +

    有一个整数数组 nums ,和一个查询数组 requests ,其中 requests[i] = [starti, endi] 。第 i 个查询求 nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi] 的结果 ,starti 和 endi 数组索引都是 从 0 开始 的。

    + +

    你可以任意排列 nums 中的数字,请你返回所有查询结果之和的最大值。

    + +

    由于答案可能会很大,请你将它对 109 + 7 取余 后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
    +输出:19
    +解释:一个可行的 nums 排列为 [2,1,3,4,5],并有如下结果:
    +requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
    +requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
    +总和为:8 + 3 = 11。
    +一个总和更大的排列为 [3,5,4,2,1],并有如下结果:
    +requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
    +requests[1] -> nums[0] + nums[1] = 3 + 5  = 8
    +总和为: 11 + 8 = 19,这个方案是所有排列中查询之和最大的结果。
    +
    + +

    示例 2:

    + +
    输入:nums = [1,2,3,4,5,6], requests = [[0,1]]
    +输出:11
    +解释:一个总和最大的排列为 [6,5,4,3,2,1] ,查询和为 [11]。
    + +

    示例 3:

    + +
    输入:nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
    +输出:47
    +解释:一个和最大的排列为 [4,10,5,3,2,1] ,查询结果分别为 [19,18,10]。
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 105
    • +
    • 0 <= nums[i] <= 105
    • +
    • 1 <= requests.length <= 105
    • +
    • requests[i].length == 2
    • +
    • 0 <= starti <= endi < n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1590.leetcode1590 Make Sum Divisible by P-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1590.leetcode1590 Make Sum Divisible by P-zh.md" new file mode 100644 index 00000000..623a3405 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1590.leetcode1590 Make Sum Divisible by P-zh.md" @@ -0,0 +1,90 @@ +# [1590. 使数组和能被 P 整除](https://leetcode-cn.com/problems/make-sum-divisible-by-p) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1590.Make%20Sum%20Divisible%20by%20P/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 nums,请你移除 最短 子数组(可以为 ),使得剩余元素的  能被 p 整除。 不允许 将整个数组都移除。

    + +

    请你返回你需要移除的最短子数组的长度,如果无法满足题目要求,返回 -1 。

    + +

    子数组 定义为原数组中连续的一组元素。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [3,1,4,2], p = 6
    +输出:1
    +解释:nums 中元素和为 10,不能被 p 整除。我们可以移除子数组 [4] ,剩余元素的和为 6 。
    +
    + +

    示例 2:

    + +
    输入:nums = [6,3,5,2], p = 9
    +输出:2
    +解释:我们无法移除任何一个元素使得和被 9 整除,最优方案是移除子数组 [5,2] ,剩余元素为 [6,3],和为 9 。
    +
    + +

    示例 3:

    + +
    输入:nums = [1,2,3], p = 3
    +输出:0
    +解释:和恰好为 6 ,已经能被 3 整除了。所以我们不需要移除任何元素。
    +
    + +

    示例  4:

    + +
    输入:nums = [1,2,3], p = 7
    +输出:-1
    +解释:没有任何方案使得移除子数组后剩余元素的和被 7 整除。
    +
    + +

    示例 5:

    + +
    输入:nums = [1000000000,1000000000,1000000000], p = 3
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • 1 <= p <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1591.leetcode1591 Strange Printer II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1591.leetcode1591 Strange Printer II-zh.md" new file mode 100644 index 00000000..c7a9f76b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1591.leetcode1591 Strange Printer II-zh.md" @@ -0,0 +1,90 @@ +# [1591. 奇怪的打印机 II](https://leetcode-cn.com/problems/strange-printer-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1591.Strange%20Printer%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个奇怪的打印机,它有如下两个特殊的打印规则:

    + +
      +
    • 每一次操作时,打印机会用同一种颜色打印一个矩形的形状,每次打印会覆盖矩形对应格子里原本的颜色。
    • +
    • 一旦矩形根据上面的规则使用了一种颜色,那么 相同的颜色不能再被使用 
    • +
    + +

    给你一个初始没有颜色的 m x n 的矩形 targetGrid ,其中 targetGrid[row][col] 是位置 (row, col) 的颜色。

    + +

    如果你能按照上述规则打印出矩形 targetGrid ,请你返回 true ,否则返回 false 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]
    +输出:true
    +
    + +

    示例 2:

    + +

    + +
    输入:targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]
    +输出:true
    +
    + +

    示例 3:

    + +
    输入:targetGrid = [[1,2,1],[2,1,2],[1,2,1]]
    +输出:false
    +解释:没有办法得到 targetGrid ,因为每一轮操作使用的颜色互不相同。
    + +

    示例 4:

    + +
    输入:targetGrid = [[1,1,1],[3,1,3]]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == targetGrid.length
    • +
    • n == targetGrid[i].length
    • +
    • 1 <= m, n <= 60
    • +
    • 1 <= targetGrid[row][col] <= 60
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1592.leetcode1592 Rearrange Spaces Between Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1592.leetcode1592 Rearrange Spaces Between Words-zh.md" new file mode 100644 index 00000000..b05dc54d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1592.leetcode1592 Rearrange Spaces Between Words-zh.md" @@ -0,0 +1,88 @@ +# [1592. 重新排列单词间的空格](https://leetcode-cn.com/problems/rearrange-spaces-between-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1592.Rearrange%20Spaces%20Between%20Words/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 text ,该字符串由若干被空格包围的单词组成。每个单词由一个或者多个小写英文字母组成,并且两个单词之间至少存在一个空格。题目测试用例保证 text 至少包含一个单词

    + +

    请你重新排列空格,使每对相邻单词之间的空格数目都 相等 ,并尽可能 最大化 该数目。如果不能重新平均分配所有空格,请 将多余的空格放置在字符串末尾 ,这也意味着返回的字符串应当与原 text 字符串的长度相等。

    + +

    返回 重新排列空格后的字符串

    + +

     

    + +

    示例 1:

    + +
    输入:text = "  this   is  a sentence "
    +输出:"this   is   a   sentence"
    +解释:总共有 9 个空格和 4 个单词。可以将 9 个空格平均分配到相邻单词之间,相邻单词间空格数为:9 / (4-1) = 3 个。
    +
    + +

    示例 2:

    + +
    输入:text = " practice   makes   perfect"
    +输出:"practice   makes   perfect "
    +解释:总共有 7 个空格和 3 个单词。7 / (3-1) = 3 个空格加上 1 个多余的空格。多余的空格需要放在字符串的末尾。
    +
    + +

    示例 3:

    + +
    输入:text = "hello   world"
    +输出:"hello   world"
    +
    + +

    示例 4:

    + +
    输入:text = "  walks  udp package   into  bar a"
    +输出:"walks  udp  package  into  bar  a "
    +
    + +

    示例 5:

    + +
    输入:text = "a"
    +输出:"a"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text.length <= 100
    • +
    • text 由小写英文字母和 ' ' 组成
    • +
    • text 中至少包含一个单词
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1593.leetcode1593 Split a String Into the Max Number of Unique Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1593.leetcode1593 Split a String Into the Max Number of Unique Substrings-zh.md" new file mode 100644 index 00000000..d3bbd68f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1593.leetcode1593 Split a String Into the Max Number of Unique Substrings-zh.md" @@ -0,0 +1,80 @@ +# [1593. 拆分字符串使唯一子字符串的数目最大](https://leetcode-cn.com/problems/split-a-string-into-the-max-number-of-unique-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1593.Split%20a%20String%20Into%20the%20Max%20Number%20of%20Unique%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,请你拆分该字符串,并返回拆分后唯一子字符串的最大数目。

    + +

    字符串 s 拆分后可以得到若干 非空子字符串 ,这些子字符串连接后应当能够还原为原字符串。但是拆分出来的每个子字符串都必须是 唯一的

    + +

    注意:子字符串 是字符串中的一个连续字符序列。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "ababccc"
    +输出:5
    +解释:一种最大拆分方法为 ['a', 'b', 'ab', 'c', 'cc'] 。像 ['a', 'b', 'a', 'b', 'c', 'cc'] 这样拆分不满足题目要求,因为其中的 'a' 和 'b' 都出现了不止一次。
    +
    + +

    示例 2:

    + +
    输入:s = "aba"
    +输出:2
    +解释:一种最大拆分方法为 ['a', 'ba'] 。
    +
    + +

    示例 3:

    + +
    输入:s = "aa"
    +输出:1
    +解释:无法进一步拆分字符串。
    +
    + +

     

    + +

    提示:

    + +
      +
    • +

      1 <= s.length <= 16

      +
    • +
    • +

      s 仅包含小写英文字母

      +
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1594.leetcode1594 Maximum Non Negative Product in a Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1594.leetcode1594 Maximum Non Negative Product in a Matrix-zh.md" new file mode 100644 index 00000000..4c403c74 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1594.leetcode1594 Maximum Non Negative Product in a Matrix-zh.md" @@ -0,0 +1,92 @@ +# [1594. 矩阵的最大非负积](https://leetcode-cn.com/problems/maximum-non-negative-product-in-a-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1594.Maximum%20Non%20Negative%20Product%20in%20a%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个大小为 rows x cols 的矩阵 grid 。最初,你位于左上角 (0, 0) ,每一步,你可以在矩阵中 向右向下 移动。

    + +

    在从左上角 (0, 0) 开始到右下角 (rows - 1, cols - 1) 结束的所有路径中,找出具有 最大非负积 的路径。路径的积是沿路径访问的单元格中所有整数的乘积。

    + +

    返回 最大非负积 109 + 7 取余 的结果。如果最大积为负数,则返回 -1

    + +

    注意,取余是在得到最大积之后执行的。

    + +

     

    + +

    示例 1:

    + +
    输入:grid = [[-1,-2,-3],
    +             [-2,-3,-3],
    +             [-3,-3,-2]]
    +输出:-1
    +解释:从 (0, 0) 到 (2, 2) 的路径中无法得到非负积,所以返回 -1
    +
    + +

    示例 2:

    + +
    输入:grid = [[1,-2,1],
    +             [1,-2,1],
    +             [3,-4,1]]
    +输出:8
    +解释:最大非负积对应的路径已经用粗体标出 (1 * 1 * -2 * -4 * 1 = 8)
    +
    + +

    示例 3:

    + +
    输入:grid = [[1, 3],
    +             [0,-4]]
    +输出:0
    +解释:最大非负积对应的路径已经用粗体标出 (1 * 0 * -4 = 0)
    +
    + +

    示例 4:

    + +
    输入:grid = [[ 1, 4,4,0],
    +             [-2, 0,0,1],
    +             [ 1,-1,1,1]]
    +输出:2
    +解释:最大非负积对应的路径已经用粗体标出 (1 * -2 * 1 * -1 * 1 * 1 = 2)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rows, cols <= 15
    • +
    • -4 <= grid[i][j] <= 4
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1595.leetcode1595 Minimum Cost to Connect Two Groups of Points-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1595.leetcode1595 Minimum Cost to Connect Two Groups of Points-zh.md" new file mode 100644 index 00000000..d5fbe8cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1595.leetcode1595 Minimum Cost to Connect Two Groups of Points-zh.md" @@ -0,0 +1,90 @@ +# [1595. 连通两组点的最小成本](https://leetcode-cn.com/problems/minimum-cost-to-connect-two-groups-of-points) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1595.Minimum%20Cost%20to%20Connect%20Two%20Groups%20of%20Points/README_EN.md) + +## 题目描述 + + + +

    给你两组点,其中第一组中有 size1 个点,第二组中有 size2 个点,且 size1 >= size2

    + +

    任意两点间的连接成本 cost 由大小为 size1 x size2 矩阵给出,其中 cost[i][j] 是第一组中的点 i 和第二组中的点 j 的连接成本。如果两个组中的每个点都与另一组中的一个或多个点连接,则称这两组点是连通的。换言之,第一组中的每个点必须至少与第二组中的一个点连接,且第二组中的每个点必须至少与第一组中的一个点连接。

    + +

    返回连通两组点所需的最小成本。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:cost = [[15, 96], [36, 2]]
    +输出:17
    +解释:连通两组点的最佳方法是:
    +1--A
    +2--B
    +总成本为 17 。
    +
    + +

    示例 2:

    + +

    + +
    输入:cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]
    +输出:4
    +解释:连通两组点的最佳方法是:
    +1--A
    +2--B
    +2--C
    +3--A
    +最小成本为 4 。
    +请注意,虽然有多个点连接到第一组中的点 2 和第二组中的点 A ,但由于题目并不限制连接点的数目,所以只需要关心最低总成本。
    + +

    示例 3:

    + +
    输入:cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]
    +输出:10
    +
    + +

     

    + +

    提示:

    + +
      +
    • size1 == cost.length
    • +
    • size2 == cost[i].length
    • +
    • 1 <= size1, size2 <= 12
    • +
    • size1 >= size2
    • +
    • 0 <= cost[i][j] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1596.leetcode1596 The Most Frequently Ordered Products for Each Customer-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1596.leetcode1596 The Most Frequently Ordered Products for Each Customer-zh.md" new file mode 100644 index 00000000..c749cbcb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1596.leetcode1596 The Most Frequently Ordered Products for Each Customer-zh.md" @@ -0,0 +1,150 @@ +# [1596. 每位顾客最经常订购的商品](https://leetcode-cn.com/problems/the-most-frequently-ordered-products-for-each-customer) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1596.The%20Most%20Frequently%20Ordered%20Products%20for%20Each%20Customer/README_EN.md) + +## 题目描述 + + + +

    表:Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| name          | varchar |
    ++---------------+---------+
    +customer_id 是该表主键
    +该表包含所有顾客的信息
    +
    + +

     

    + +

    表:Orders

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| order_date    | date    |
    +| customer_id   | int     |
    +| product_id    | int     |
    ++---------------+---------+
    +order_id 是该表主键
    +该表包含顾客 customer_id 的订单信息
    +没有顾客会在一天内订购相同的商品 多于一次
    + +

     

    + +

    表:Products

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| product_id    | int     |
    +| product_name  | varchar |
    +| price         | int     |
    ++---------------+---------+
    +product_id 是该表主键
    +该表包含了所有商品的信息
    +
    + +

     

    + +

    写一个 SQL 语句,找到每一个顾客最经常订购的商品。

    + +

    结果表单应该有每一位至少下过一次单的顾客 customer_id , 他最经常订购的商品的 product_id 和 product_name

    + +

    返回结果 没有顺序要求

    + +

    查询结果格式如下例所示:

    + +
    +Customers
    ++-------------+-------+
    +| customer_id | name  |
    ++-------------+-------+
    +| 1           | Alice |
    +| 2           | Bob   |
    +| 3           | Tom   |
    +| 4           | Jerry |
    +| 5           | John  |
    ++-------------+-------+
    +
    +Orders
    ++----------+------------+-------------+------------+
    +| order_id | order_date | customer_id | product_id |
    ++----------+------------+-------------+------------+
    +| 1        | 2020-07-31 | 1           | 1          |
    +| 2        | 2020-07-30 | 2           | 2          |
    +| 3        | 2020-08-29 | 3           | 3          |
    +| 4        | 2020-07-29 | 4           | 1          |
    +| 5        | 2020-06-10 | 1           | 2          |
    +| 6        | 2020-08-01 | 2           | 1          |
    +| 7        | 2020-08-01 | 3           | 3          |
    +| 8        | 2020-08-03 | 1           | 2          |
    +| 9        | 2020-08-07 | 2           | 3          |
    +| 10       | 2020-07-15 | 1           | 2          |
    ++----------+------------+-------------+------------+
    +
    +Products
    ++------------+--------------+-------+
    +| product_id | product_name | price |
    ++------------+--------------+-------+
    +| 1          | keyboard     | 120   |
    +| 2          | mouse        | 80    |
    +| 3          | screen       | 600   |
    +| 4          | hard disk    | 450   |
    ++------------+--------------+-------+
    +Result 表:
    ++-------------+------------+--------------+
    +| customer_id | product_id | product_name |
    ++-------------+------------+--------------+
    +| 1           | 2          | mouse        |
    +| 2           | 1          | keyboard     |
    +| 2           | 2          | mouse        |
    +| 2           | 3          | screen       |
    +| 3           | 3          | screen       |
    +| 4           | 1          | keyboard     |
    ++-------------+------------+--------------+
    +
    +Alice (customer 1) 三次订购鼠标, 一次订购键盘, 所以鼠标是 Alice 最经常订购的商品.
    +Bob (customer 2) 一次订购键盘, 一次订购鼠标, 一次订购显示器, 所以这些都是 Bob 最经常订购的商品.
    +Tom (customer 3) 只两次订购显示器, 所以显示器是 Tom 最经常订购的商品.
    +Jerry (customer 4) 只一次订购键盘, 所以键盘是 Jerry 最经常订购的商品.
    +John (customer 5) 没有订购过商品, 所以我们并没有把 John 包含在结果表中.
    +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1597.leetcode1597 Build Binary Expression Tree From Infix Expression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1597.leetcode1597 Build Binary Expression Tree From Infix Expression-zh.md" new file mode 100644 index 00000000..480c5a8e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1597.leetcode1597 Build Binary Expression Tree From Infix Expression-zh.md" @@ -0,0 +1,90 @@ +# [1597. 根据中缀表达式构造二叉表达式树](https://leetcode-cn.com/problems/build-binary-expression-tree-from-infix-expression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1597.Build%20Binary%20Expression%20Tree%20From%20Infix%20Expression/README_EN.md) + +## 题目描述 + + + +

    二叉表达式树 是一种表达算术表达式的二叉树。二叉表达式树中的每一个节点都有零个或两个子节点。 叶节点(有 0 个子节点的节点)表示操作数,非叶节点(有 2 个子节点的节点)表示运算符: '+' (加)、 '-' (减)、 '*' (乘)和 '/' (除)。

    + +

    对于每一个运算符为 o 的非叶节点,对应的 中缀表达式 为 (A o B),其中 A 是左子树所表达的表达式, B 是右子树所表达的表达式。

    + +

    给定一个 中缀表达式 字符串 s,其中包含操作数、上面提到的运算符,以及括号 '(' 与 ')' 。

    + +

    返回一个有效的 二叉表达式树,其 中序遍历 序列对应表达式 s 消除括号后的序列(详情参见下面的示例)

    + +

    注意,表达式的一般解析顺序适用于 s,即优先解析括号内的表达式,然后解析乘除法,最后解析加减法。

    + +

    同时,操作数在 s 和树的中序遍历中 出现顺序相同

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "3*4-2*5"
    +输出:[-,*,*,3,4,2,5]
    +解释:上面是唯一一种有效的二叉表达式树,其中序遍历生成 s 。
    +
    + +

    示例 2:

    + +
    +输入:s = "2-3/(5*2)+1"
    +输出:[+,-,1,2,/,null,null,null,null,3,*,null,null,5,2]
    +解释:上面的树的中序遍历为 2-3/5*2+1 ,与 s 消除括号后相同。该树还会生成正确的结果,其操作数的顺序与 s 中出现的顺序相同。
    +下面的树也是一个有效的二叉表达式树,具有与 s 相同的中序遍历,但它不是一个有效的答案,因为它的求值结果不同。
    +
    +下面的树也是无效的。尽管它的计算结果相等并与上述树等效,但其中序遍历不会产生 s ,并且其操作数与 s 中的顺序也不相同。
    +
    +
    + +

    示例 3:

    + +
    +输入:s = "1+2+3+4+5"
    +输出:[+,+,5,+,4,null,null,+,3,null,null,1,2]
    +解释:二叉树 [+,+,5,+,+,null,null,1,2,3,4] 也是诸多有效的二叉表达式树之一。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s 中包含数字和字符 '+'、 '-'、 '*'、 '/'
    • +
    • s 中的操作数 恰好 是一位数字。
    • +
    • 题目数据保证 s 是一个有效的表达式。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1598.leetcode1598 Crawler Log Folder-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1598.leetcode1598 Crawler Log Folder-zh.md" new file mode 100644 index 00000000..decb6308 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1598.leetcode1598 Crawler Log Folder-zh.md" @@ -0,0 +1,91 @@ +# [1598. 文件夹操作日志搜集器](https://leetcode-cn.com/problems/crawler-log-folder) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1598.Crawler%20Log%20Folder/README_EN.md) + +## 题目描述 + + + +

    每当用户执行变更文件夹操作时,LeetCode 文件系统都会保存一条日志记录。

    + +

    下面给出对变更操作的说明:

    + +
      +
    • "../" :移动到当前文件夹的父文件夹。如果已经在主文件夹下,则 继续停留在当前文件夹
    • +
    • "./" :继续停留在当前文件夹
    • +
    • "x/" :移动到名为 x 的子文件夹中。题目数据 保证总是存在文件夹 x
    • +
    + +

    给你一个字符串列表 logs ,其中 logs[i] 是用户在 ith 步执行的操作。

    + +

    文件系统启动时位于主文件夹,然后执行 logs 中的操作。

    + +

    执行完所有变更文件夹操作后,请你找出 返回主文件夹所需的最小步数

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:logs = ["d1/","d2/","../","d21/","./"]
    +输出:2
    +解释:执行 "../" 操作变更文件夹 2 次,即可回到主文件夹
    +
    + +

    示例 2:

    + +

    + +
    输入:logs = ["d1/","d2/","./","d3/","../","d31/"]
    +输出:3
    +
    + +

    示例 3:

    + +
    输入:logs = ["d1/","../","../","../"]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= logs.length <= 103
    • +
    • 2 <= logs[i].length <= 10
    • +
    • logs[i] 包含小写英文字母,数字,'.''/'
    • +
    • logs[i] 符合语句中描述的格式
    • +
    • 文件夹名称由小写英文字母和数字组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1599.leetcode1599 Maximum Profit of Operating a Centennial Wheel-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1599.leetcode1599 Maximum Profit of Operating a Centennial Wheel-zh.md" new file mode 100644 index 00000000..07cddd23 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1599.leetcode1599 Maximum Profit of Operating a Centennial Wheel-zh.md" @@ -0,0 +1,117 @@ +# [1599. 经营摩天轮的最大利润](https://leetcode-cn.com/problems/maximum-profit-of-operating-a-centennial-wheel) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1500-1599/1599.Maximum%20Profit%20of%20Operating%20a%20Centennial%20Wheel/README_EN.md) + +## 题目描述 + + + +

    你正在经营一座摩天轮,该摩天轮共有 4 个座舱 ,每个座舱 最多可以容纳 4 位游客 。你可以 逆时针 轮转座舱,但每次轮转都需要支付一定的运行成本 runningCost 。摩天轮每次轮转都恰好转动 1 / 4 周。

    + +

    给你一个长度为 n 的数组 customerscustomers[i] 是在第 i 次轮转(下标从 0 开始)之前到达的新游客的数量。这也意味着你必须在新游客到来前轮转 i 次。每位游客在登上离地面最近的座舱前都会支付登舱成本 boardingCost ,一旦该座舱再次抵达地面,他们就会离开座舱结束游玩。

    + +

    你可以随时停下摩天轮,即便是 在服务所有游客之前 。如果你决定停止运营摩天轮,为了保证所有游客安全着陆,将免费进行所有后续轮转 。注意,如果有超过 4 位游客在等摩天轮,那么只有 4 位游客可以登上摩天轮,其余的需要等待 下一次轮转

    + +

    返回最大化利润所需执行的 最小轮转次数 。 如果不存在利润为正的方案,则返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:customers = [8,3], boardingCost = 5, runningCost = 6
    +输出:3
    +解释:座舱上标注的数字是该座舱的当前游客数。
    +1. 8 位游客抵达,4 位登舱,4 位等待下一舱,摩天轮轮转。当前利润为 4 * $5 - 1 * $6 = $14 。
    +2. 3 位游客抵达,4 位在等待的游客登舱,其他 3 位等待,摩天轮轮转。当前利润为 8 * $5 - 2 * $6 = $28 。
    +3. 最后 3 位游客登舱,摩天轮轮转。当前利润为 11 * $5 - 3 * $6 = $37 。
    +轮转 3 次得到最大利润,最大利润为 $37 。
    + +

    示例 2:

    + +
    输入:customers = [10,9,6], boardingCost = 6, runningCost = 4
    +输出:7
    +解释:
    +1. 10 位游客抵达,4 位登舱,6 位等待下一舱,摩天轮轮转。当前利润为 4 * $6 - 1 * $4 = $20 。
    +2. 9 位游客抵达,4 位登舱,11 位等待(2 位是先前就在等待的,9 位新加入等待的),摩天轮轮转。当前利润为 8 * $6 - 2 * $4 = $40 。
    +3. 最后 6 位游客抵达,4 位登舱,13 位等待,摩天轮轮转。当前利润为 12 * $6 - 3 * $4 = $60 。
    +4. 4 位登舱,9 位等待,摩天轮轮转。当前利润为 * $6 - 4 * $4 = $80 。
    +5. 4 位登舱,5 位等待,摩天轮轮转。当前利润为 20 * $6 - 5 * $4 = $100 。
    +6. 4 位登舱,1 位等待,摩天轮轮转。当前利润为 24 * $6 - 6 * $4 = $120 。
    +7. 1 位登舱,摩天轮轮转。当前利润为 25 * $6 - 7 * $4 = $122 。
    +轮转 7 次得到最大利润,最大利润为$122 。
    +
    + +

    示例 3:

    + +
    输入:customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92
    +输出:-1
    +解释:
    +1. 3 位游客抵达,3 位登舱,0 位等待,摩天轮轮转。当前利润为 3 * $1 - 1 * $92 = -$89 。
    +2. 4 位游客抵达,4 位登舱,0 位等待,摩天轮轮转。当前利润为 is 7 * $1 - 2 * $92 = -$177 。
    +3. 0 位游客抵达,0 位登舱,0 位等待,摩天轮轮转。当前利润为 7 * $1 - 3 * $92 = -$269 。
    +4. 5 位游客抵达,4 位登舱,1 位等待,摩天轮轮转。当前利润为 12 * $1 - 4 * $92 = -$356 。
    +5. 1 位游客抵达,2 位登舱,0 位等待,摩天轮轮转。当前利润为 13 * $1 - 5 * $92 = -$447 。
    +利润永不为正,所以返回 -1 。
    +
    + +

    示例 4:

    + +
    输入:customers = [10,10,6,4,7], boardingCost = 3, runningCost = 8
    +输出:9
    +解释:
    +1. 10 位游客抵达,4 位登舱,6 位等待,摩天轮轮转。当前利润为 4 * $3 - 1 * $8 = $4 。
    +2. 10 位游客抵达,4 位登舱,12 位等待,摩天轮轮转。当前利润为 8 * $3 - 2 * $8 = $8 。
    +3. 6 位游客抵达,4 位登舱,14 位等待,摩天轮轮转。当前利润为 12 * $3 - 3 * $8 = $12 。
    +4. 4 位游客抵达,4 位登舱,14 位等待,摩天轮轮转。当前利润为 16 * $3 - 4 * $8 = $16 。
    +5. 7 位游客抵达,4 位登舱,17 位等待,摩天轮轮转。当前利润为 20 * $3 - 5 * $8 = $20 。
    +6. 4 位登舱,13 位等待,摩天轮轮转。当前利润为 24 * $3 - 6 * $8 = $24 。
    +7. 4 位登舱,9 位等待,摩天轮轮转。当前利润为 28 * $3 - 7 * $8 = $28 。
    +8. 4 位登舱,5 位等待,摩天轮轮转。当前利润为 32 * $3 - 8 * $8 = $32 。
    +9. 4 位登舱,1 位等待,摩天轮轮转。当前利润为 36 * $3 - 9 * $8 = $36 。
    +​​​​​​​10. 1 位登舱,0 位等待,摩天轮轮转。当前利润为 37 * $3 - 10 * $8 = $31 。
    +轮转 9 次得到最大利润,最大利润为 $36 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == customers.length
    • +
    • 1 <= n <= 105
    • +
    • 0 <= customers[i] <= 50
    • +
    • 1 <= boardingCost, runningCost <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1600.leetcode1600 Throne Inheritance-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1600.leetcode1600 Throne Inheritance-zh.md" new file mode 100644 index 00000000..9b215b28 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1600.leetcode1600 Throne Inheritance-zh.md" @@ -0,0 +1,107 @@ +# [1600. 皇位继承顺序](https://leetcode-cn.com/problems/throne-inheritance) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1600.Throne%20Inheritance/README_EN.md) + +## 题目描述 + + + +

    一个王国里住着国王、他的孩子们、他的孙子们等等。每一个时间点,这个家庭里有人出生也有人死亡。

    + +

    这个王国有一个明确规定的皇位继承顺序,第一继承人总是国王自己。我们定义递归函数 Successor(x, curOrder) ,给定一个人 x 和当前的继承顺序,该函数返回 x 的下一继承人。

    + +
    Successor(x, curOrder):
    +    如果 x 没有孩子或者所有 x 的孩子都在 curOrder 中:
    +        如果 x 是国王,那么返回 null
    +        否则,返回 Successor(x 的父亲, curOrder)
    +    否则,返回 x 不在 curOrder 中最年长的孩子
    +
    + +

    比方说,假设王国由国王,他的孩子 Alice 和 Bob (Alice 比 Bob 年长)和 Alice 的孩子 Jack 组成。

    + +
      +
    1. 一开始, curOrder 为 ["king"].
    2. +
    3. 调用 Successor(king, curOrder) ,返回 Alice ,所以我们将 Alice 放入 curOrder 中,得到 ["king", "Alice"] 。
    4. +
    5. 调用 Successor(Alice, curOrder) ,返回 Jack ,所以我们将 Jack 放入 curOrder 中,得到 ["king", "Alice", "Jack"] 。
    6. +
    7. 调用 Successor(Jack, curOrder) ,返回 Bob ,所以我们将 Bob 放入 curOrder 中,得到 ["king", "Alice", "Jack", "Bob"] 。
    8. +
    9. 调用 Successor(Bob, curOrder) ,返回 null 。最终得到继承顺序为 ["king", "Alice", "Jack", "Bob"] 。
    10. +
    + +

    通过以上的函数,我们总是能得到一个唯一的继承顺序。

    + +

    请你实现 ThroneInheritance 类:

    + +
      +
    • ThroneInheritance(string kingName) 初始化一个 ThroneInheritance 类的对象。国王的名字作为构造函数的参数传入。
    • +
    • void birth(string parentName, string childName) 表示 parentName 新拥有了一个名为 childName 的孩子。
    • +
    • void death(string name) 表示名为 name 的人死亡。一个人的死亡不会影响 Successor 函数,也不会影响当前的继承顺序。你可以只将这个人标记为死亡状态。
    • +
    • string[] getInheritanceOrder() 返回 除去 死亡人员的当前继承顺序列表。
    • +
    + +

     

    + +

    示例:

    + +
    输入:
    +["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
    +[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
    +输出:
    +[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
    +
    +解释:
    +ThroneInheritance t= new ThroneInheritance("king"); // 继承顺序:king
    +t.birth("king", "andy"); // 继承顺序:king > andy
    +t.birth("king", "bob"); // 继承顺序:king > andy > bob
    +t.birth("king", "catherine"); // 继承顺序:king > andy > bob > catherine
    +t.birth("andy", "matthew"); // 继承顺序:king > andy > matthew > bob > catherine
    +t.birth("bob", "alex"); // 继承顺序:king > andy > matthew > bob > alex > catherine
    +t.birth("bob", "asha"); // 继承顺序:king > andy > matthew > bob > alex > asha > catherine
    +t.getInheritanceOrder(); // 返回 ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
    +t.death("bob"); // 继承顺序:king > andy > matthew > bob(已经去世)> alex > asha > catherine
    +t.getInheritanceOrder(); // 返回 ["king", "andy", "matthew", "alex", "asha", "catherine"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= kingName.length, parentName.length, childName.length, name.length <= 15
    • +
    • kingNameparentName, childName 和 name 仅包含小写英文字母。
    • +
    • 所有的参数 childName 和 kingName 互不相同
    • +
    • 所有 death 函数中的死亡名字 name 要么是国王,要么是已经出生了的人员名字。
    • +
    • 每次调用 birth(parentName, childName) 时,测试用例都保证 parentName 对应的人员是活着的。
    • +
    • 最多调用 105 次birth 和 death 。
    • +
    • 最多调用 10 次 getInheritanceOrder 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1601.leetcode1601 Maximum Number of Achievable Transfer Requests-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1601.leetcode1601 Maximum Number of Achievable Transfer Requests-zh.md" new file mode 100644 index 00000000..41e4e962 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1601.leetcode1601 Maximum Number of Achievable Transfer Requests-zh.md" @@ -0,0 +1,93 @@ +# [1601. 最多可达成的换楼请求数目](https://leetcode-cn.com/problems/maximum-number-of-achievable-transfer-requests) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1601.Maximum%20Number%20of%20Achievable%20Transfer%20Requests/README_EN.md) + +## 题目描述 + + + +

    我们有 n 栋楼,编号从 0 到 n - 1 。每栋楼有若干员工。由于现在是换楼的季节,部分员工想要换一栋楼居住。

    + +

    给你一个数组 requests ,其中 requests[i] = [fromi, toi] ,表示一个员工请求从编号为 fromi 的楼搬到编号为 toi 的楼。

    + +

    一开始 所有楼都是满的,所以从请求列表中选出的若干个请求是可行的需要满足 每栋楼员工净变化为 0 。意思是每栋楼 离开 的员工数目 等于 该楼 搬入 的员工数数目。比方说 n = 3 且两个员工要离开楼 0 ,一个员工要离开楼 1 ,一个员工要离开楼 2 ,如果该请求列表可行,应该要有两个员工搬入楼 0 ,一个员工搬入楼 1 ,一个员工搬入楼 2 。

    + +

    请你从原请求列表中选出若干个请求,使得它们是一个可行的请求列表,并返回所有可行列表中最大请求数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
    +输出:5
    +解释:请求列表如下:
    +从楼 0 离开的员工为 x 和 y ,且他们都想要搬到楼 1 。
    +从楼 1 离开的员工为 a 和 b ,且他们分别想要搬到楼 2 和 0 。
    +从楼 2 离开的员工为 z ,且他想要搬到楼 0 。
    +从楼 3 离开的员工为 c ,且他想要搬到楼 4 。
    +没有员工从楼 4 离开。
    +我们可以让 x 和 b 交换他们的楼,以满足他们的请求。
    +我们可以让 y,a 和 z 三人在三栋楼间交换位置,满足他们的要求。
    +所以最多可以满足 5 个请求。
    + +

    示例 2:

    + +

    + +
    输入:n = 3, requests = [[0,0],[1,2],[2,1]]
    +输出:3
    +解释:请求列表如下:
    +从楼 0 离开的员工为 x ,且他想要回到原来的楼 0 。
    +从楼 1 离开的员工为 y ,且他想要搬到楼 2 。
    +从楼 2 离开的员工为 z ,且他想要搬到楼 1 。
    +我们可以满足所有的请求。
    + +

    示例 3:

    + +
    输入:n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 20
    • +
    • 1 <= requests.length <= 16
    • +
    • requests[i].length == 2
    • +
    • 0 <= fromi, toi < n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1602.leetcode1602 Find Nearest Right Node in Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1602.leetcode1602 Find Nearest Right Node in Binary Tree-zh.md" new file mode 100644 index 00000000..568e2512 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1602.leetcode1602 Find Nearest Right Node in Binary Tree-zh.md" @@ -0,0 +1,81 @@ +# [1602. 找到二叉树中最近的右侧节点](https://leetcode-cn.com/problems/find-nearest-right-node-in-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1602.Find%20Nearest%20Right%20Node%20in%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树的根节点 root 和树中的一个节点 u ,返回与 u 所在层距离最近右侧节点,当 u 是所在层中最右侧的节点,返回 null 。

    + +

    示例 1:

    + +

    + +
    输入: root = [1,2,3,null,4,5,6], u = 4
    +输出: 5
    +解释: 节点 4 所在层中,最近的右侧节点是节点 5。
    +
    + +

    示例 2:

    + +

    + +
    输入: root = [3,null,4,2], u = 2
    +输出: null
    +解释: 2 的右侧没有节点。
    +
    + +

    示例 3:

    + +
    输入: root = [1], u = 1
    +输出: null
    +
    + +

    示例 4:

    + +
    输入: root = [3,4,2,null,null,null,1], u = 4
    +输出: 2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点个数的范围是 [1, 105] 。
    • +
    • 1 <= Node.val <= 105
    • +
    • 树中所有节点的值是唯一的。
    • +
    • u 是以 root 为根的二叉树的一个节点。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1603.leetcode1603 Design Parking System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1603.leetcode1603 Design Parking System-zh.md" new file mode 100644 index 00000000..9cb75d6f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1603.leetcode1603 Design Parking System-zh.md" @@ -0,0 +1,116 @@ +# [1603. 设计停车系统](https://leetcode-cn.com/problems/design-parking-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1603.Design%20Parking%20System/README_EN.md) + +## 题目描述 + + + +

    请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。

    + +

    请你实现 ParkingSystem 类:

    + +
      +
    • ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类,三个参数分别对应每种停车位的数目。
    • +
    • bool addCar(int carType) 检查是否有 carType 对应的停车位。 carType 有三种类型:大,中,小,分别用数字 1, 2 和 3 表示。一辆车只能停在  carType 对应尺寸的停车位中。如果没有空车位,请返回 false ,否则将该车停入车位并返回 true 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
    +[[1, 1, 0], [1], [2], [3], [1]]
    +输出:
    +[null, true, true, false, false]
    +
    +解释:
    +ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
    +parkingSystem.addCar(1); // 返回 true ,因为有 1 个空的大车位
    +parkingSystem.addCar(2); // 返回 true ,因为有 1 个空的中车位
    +parkingSystem.addCar(3); // 返回 false ,因为没有空的小车位
    +parkingSystem.addCar(1); // 返回 false ,因为没有空的大车位,唯一一个大车位已经被占据了
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= big, medium, small <= 1000
    • +
    • carType 取值为 1, 2 或 3
    • +
    • 最多会调用 addCar 函数 1000 次
    • +
    + + +## 解法 + + + +为每种车维护一个计数器,初始值为车位的数目。此后,每来一辆车,就将对应类型的计数器减 1。当计数器为 0 时,说明车位已满。 + + + +### **Python3** + + + +```python +class ParkingSystem: + + def __init__(self, big: int, medium: int, small: int): + self.spaces = [big, medium, small] + + + def addCar(self, carType: int) -> bool: + if self.spaces[carType - 1] <= 0: + return False + self.spaces[carType - 1] -= 1 + return True + + +# Your ParkingSystem object will be instantiated and called as such: +# obj = ParkingSystem(big, medium, small) +# param_1 = obj.addCar(carType) +``` + +### **Java** + + + +```java +class ParkingSystem { + + private int[] spaces = new int[3]; + + public ParkingSystem(int big, int medium, int small) { + spaces[0] = big; + spaces[1] = medium; + spaces[2] = small; + } + + public boolean addCar(int carType) { + if (spaces[carType - 1] <= 0) { + return false; + } + --spaces[carType - 1]; + return true; + } +} + +/** + * Your ParkingSystem object will be instantiated and called as such: + * ParkingSystem obj = new ParkingSystem(big, medium, small); + * boolean param_1 = obj.addCar(carType); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1604.leetcode1604 Alert Using Same Key-Card Three or More Times in a One Hour Period-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1604.leetcode1604 Alert Using Same Key-Card Three or More Times in a One Hour Period-zh.md" new file mode 100644 index 00000000..89f27950 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1604.leetcode1604 Alert Using Same Key-Card Three or More Times in a One Hour Period-zh.md" @@ -0,0 +1,93 @@ +# [1604. 警告一小时内使用相同员工卡大于等于三次的人](https://leetcode-cn.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1604.Alert%20Using%20Same%20Key-Card%20Three%20or%20More%20Times%20in%20a%20One%20Hour%20Period/README_EN.md) + +## 题目描述 + + + +

    力扣公司的员工都使用员工卡来开办公室的门。每当一个员工使用一次他的员工卡,安保系统会记录下员工的名字和使用时间。如果一个员工在一小时时间内使用员工卡的次数大于等于三次,这个系统会自动发布一个 警告 。

    + +

    给你字符串数组 keyName 和 keyTime ,其中 [keyName[i], keyTime[i]] 对应一个人的名字和他在 某一天 内使用员工卡的时间。

    + +

    使用时间的格式是 24小时制 ,形如 "HH:MM" ,比方说 "23:51" 和 "09:49" 。

    + +

    请你返回去重后的收到系统警告的员工名字,将它们按 字典序升序 排序后返回。

    + +

    请注意 "10:00" - "11:00" 视为一个小时时间范围内,而 "23:51" - "00:10" 不被视为一小时内,因为系统记录的是某一天内的使用情况。

    + +

     

    + +

    示例 1:

    + +
    +输入:keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
    +输出:["daniel"]
    +解释:"daniel" 在一小时内使用了 3 次员工卡("10:00","10:40","11:00")。
    +
    + +

    示例 2:

    + +
    +输入:keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]
    +输出:["bob"]
    +解释:"bob" 在一小时内使用了 3 次员工卡("21:00","21:20","21:30")。
    +
    + +

    示例 3:

    + +
    +输入:keyName = ["john","john","john"], keyTime = ["23:58","23:59","00:01"]
    +输出:[]
    +
    + +

    示例 4:

    + +
    +输入:keyName = ["leslie","leslie","leslie","clare","clare","clare","clare"], keyTime = ["13:00","13:20","14:00","18:00","18:51","19:30","19:49"]
    +输出:["clare","leslie"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= keyName.length, keyTime.length <= 105
    • +
    • keyName.length == keyTime.length
    • +
    • keyTime 格式为 "HH:MM" 
    • +
    • 保证 [keyName[i], keyTime[i]] 形成的二元对 互不相同 
    • +
    • 1 <= keyName[i].length <= 10
    • +
    • keyName[i] 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1605.leetcode1605 Find Valid Matrix Given Row and Column Sums-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1605.leetcode1605 Find Valid Matrix Given Row and Column Sums-zh.md" new file mode 100644 index 00000000..1aff7ecc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1605.leetcode1605 Find Valid Matrix Given Row and Column Sums-zh.md" @@ -0,0 +1,104 @@ +# [1605. 给定行和列的和求可行矩阵](https://leetcode-cn.com/problems/find-valid-matrix-given-row-and-column-sums) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1605.Find%20Valid%20Matrix%20Given%20Row%20and%20Column%20Sums/README_EN.md) + +## 题目描述 + + + +

    给你两个非负整数数组 rowSum 和 colSum ,其中 rowSum[i] 是二维矩阵中第 i 行元素的和, colSum[j] 是第 j 列元素的和。换言之你不知道矩阵里的每个元素,但是你知道每一行和每一列的和。

    + +

    请找到大小为 rowSum.length x colSum.length 的任意 非负整数 矩阵,且该矩阵满足 rowSum 和 colSum 的要求。

    + +

    请你返回任意一个满足题目要求的二维矩阵,题目保证存在 至少一个 可行矩阵。

    + +

     

    + +

    示例 1:

    + +
    +输入:rowSum = [3,8], colSum = [4,7]
    +输出:[[3,0],
    +      [1,7]]
    +解释:
    +第 0 行:3 + 0 = 3 == rowSum[0]
    +第 1 行:1 + 7 = 8 == rowSum[1]
    +第 0 列:3 + 1 = 4 == colSum[0]
    +第 1 列:0 + 7 = 7 == colSum[1]
    +行和列的和都满足题目要求,且所有矩阵元素都是非负的。
    +另一个可行的矩阵为:[[1,2],
    +                  [3,5]]
    +
    + +

    示例 2:

    + +
    +输入:rowSum = [5,7,10], colSum = [8,6,8]
    +输出:[[0,5,0],
    +      [6,1,0],
    +      [2,0,8]]
    +
    + +

    示例 3:

    + +
    +输入:rowSum = [14,9], colSum = [6,9,8]
    +输出:[[0,9,5],
    +      [6,0,3]]
    +
    + +

    示例 4:

    + +
    +输入:rowSum = [1,0], colSum = [1]
    +输出:[[1],
    +      [0]]
    +
    + +

    示例 5:

    + +
    +输入:rowSum = [0], colSum = [0]
    +输出:[[0]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rowSum.length, colSum.length <= 500
    • +
    • 0 <= rowSum[i], colSum[i] <= 108
    • +
    • sum(rows) == sum(columns)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1606.leetcode1606 Find Servers That Handled Most Number of Requests11606.leetcode1606 Find Servers That Handled Most Number of Requests-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1606.leetcode1606 Find Servers That Handled Most Number of Requests11606.leetcode1606 Find Servers That Handled Most Number of Requests-zh.md" new file mode 100644 index 00000000..93af3ae5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1606.leetcode1606 Find Servers That Handled Most Number of Requests11606.leetcode1606 Find Servers That Handled Most Number of Requests-zh.md" @@ -0,0 +1,113 @@ +# [1606. 找到处理最多请求的服务器](https://leetcode-cn.com/problems/find-servers-that-handled-most-number-of-requests) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1606.Find%20Servers%20That%20Handled%20Most%20Number%20of%20Requests/README_EN.md) + +## 题目描述 + + + +

    你有 k 个服务器,编号为 0 到 k-1 ,它们可以同时处理多个请求组。每个服务器有无穷的计算能力但是 不能同时处理超过一个请求 。请求分配到服务器的规则如下:

    + +
      +
    • 第 i (序号从 0 开始)个请求到达。
    • +
    • 如果所有服务器都已被占据,那么该请求被舍弃(完全不处理)。
    • +
    • 如果第 (i % k) 个服务器空闲,那么对应服务器会处理该请求。
    • +
    • 否则,将请求安排给下一个空闲的服务器(服务器构成一个环,必要的话可能从第 0 个服务器开始继续找下一个空闲的服务器)。比方说,如果第 i 个服务器在忙,那么会查看第 (i+1) 个服务器,第 (i+2) 个服务器等等。
    • +
    + +

    给你一个 严格递增 的正整数数组 arrival ,表示第 i 个任务的到达时间,和另一个数组 load ,其中 load[i] 表示第 i 个请求的工作量(也就是服务器完成它所需要的时间)。你的任务是找到 最繁忙的服务器 。最繁忙定义为一个服务器处理的请求数是所有服务器里最多的。

    + +

    请你返回包含所有 最繁忙服务器 序号的列表,你可以以任意顺序返回这个列表。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] 
    +输出:[1] 
    +解释:
    +所有服务器一开始都是空闲的。
    +前 3 个请求分别由前 3 台服务器依次处理。
    +请求 3 进来的时候,服务器 0 被占据,所以它呗安排到下一台空闲的服务器,也就是服务器 1 。
    +请求 4 进来的时候,由于所有服务器都被占据,该请求被舍弃。
    +服务器 0 和 2 分别都处理了一个请求,服务器 1 处理了两个请求。所以服务器 1 是最忙的服务器。
    +
    + +

    示例 2:

    + +
    +输入:k = 3, arrival = [1,2,3,4], load = [1,2,1,2]
    +输出:[0]
    +解释:
    +前 3 个请求分别被前 3 个服务器处理。
    +请求 3 进来,由于服务器 0 空闲,它被服务器 0 处理。
    +服务器 0 处理了两个请求,服务器 1 和 2 分别处理了一个请求。所以服务器 0 是最忙的服务器。
    +
    + +

    示例 3:

    + +
    +输入:k = 3, arrival = [1,2,3], load = [10,12,11]
    +输出:[0,1,2]
    +解释:每个服务器分别处理了一个请求,所以它们都是最忙的服务器。
    +
    + +

    示例 4:

    + +
    +输入:k = 3, arrival = [1,2,3,4,8,9,10], load = [5,2,10,3,1,2,2]
    +输出:[1]
    +
    + +

    示例 5:

    + +
    +输入:k = 1, arrival = [1], load = [1]
    +输出:[0]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= 105
    • +
    • 1 <= arrival.length, load.length <= 105
    • +
    • arrival.length == load.length
    • +
    • 1 <= arrival[i], load[i] <= 109
    • +
    • arrival 保证 严格递增 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1607.leetcode1607 Sellers With No Sales-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1607.leetcode1607 Sellers With No Sales-zh.md" new file mode 100644 index 00000000..8a2fdfb2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1607.leetcode1607 Sellers With No Sales-zh.md" @@ -0,0 +1,116 @@ +# [1607. 没有卖出的卖家](https://leetcode-cn.com/problems/sellers-with-no-sales) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1607.Sellers%20With%20No%20Sales/README_EN.md) + +## 题目描述 + + + +

    表: Customer

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| customer_name | varchar |
    ++---------------+---------+
    +customer_id 是该表主键.
    +该表的每行包含网上商城的每一位顾客的信息.
    +
    + +

     

    + +

    表: Orders

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| order_id      | int     |
    +| sale_date     | date    |
    +| order_cost    | int     |
    +| customer_id   | int     |
    +| seller_id     | int     |
    ++---------------+---------+
    +order_id 是该表主键.
    +该表的每行包含网上商城的所有订单的信息.
    +sale_date 是顾客customer_id和卖家seller_id之间交易的日期.
    +
    + +

     

    + +

    表: Seller

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| seller_id     | int     |
    +| seller_name   | varchar |
    ++---------------+---------+
    +seller_id 是该表主键.
    +该表的每行包含每一位卖家的信息.
    +
    + +

     

    + +

    写一个SQL语句, 报告所有在2020年度没有任何卖出的卖家的名字.

    + +

    返回结果按照 seller_name 升序排列.

    + +

    查询结果格式如下例所示.

    + +

     

    + +
    Customer 表:
    ++--------------+---------------+
    +| customer_id  | customer_name |
    ++--------------+---------------+
    +| 101          | Alice         |
    +| 102          | Bob           |
    +| 103          | Charlie       |
    ++--------------+---------------+
    +
    +Orders 表:
    ++-------------+------------+--------------+-------------+-------------+
    +| order_id    | sale_date  | order_cost   | customer_id | seller_id   |
    ++-------------+------------+--------------+-------------+-------------+
    +| 1           | 2020-03-01 | 1500         | 101         | 1           |
    +| 2           | 2020-05-25 | 2400         | 102         | 2           |
    +| 3           | 2019-05-25 | 800          | 101         | 3           |
    +| 4           | 2020-09-13 | 1000         | 103         | 2           |
    +| 5           | 2019-02-11 | 700          | 101         | 2           |
    ++-------------+------------+--------------+-------------+-------------+
    +
    +Seller 表:
    ++-------------+-------------+
    +| seller_id   | seller_name |
    ++-------------+-------------+
    +| 1           | Daniel      |
    +| 2           | Elizabeth   |
    +| 3           | Frank       |
    ++-------------+-------------+
    +
    +Result 表:
    ++-------------+
    +| seller_name |
    ++-------------+
    +| Frank       |
    ++-------------+
    +Daniel在2020年3月卖出1次.
    +Elizabeth在2020年卖出2次, 在2019年卖出1次.
    +Frank在2019年卖出1次, 在2020年没有卖出.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1608.leetcode1608 Special Array With X Elements Greater Than or Equal X-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1608.leetcode1608 Special Array With X Elements Greater Than or Equal X-zh.md" new file mode 100644 index 00000000..85627f0c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1608.leetcode1608 Special Array With X Elements Greater Than or Equal X-zh.md" @@ -0,0 +1,85 @@ +# [1608. 特殊数组的特征值](https://leetcode-cn.com/problems/special-array-with-x-elements-greater-than-or-equal-x) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1608.Special%20Array%20With%20X%20Elements%20Greater%20Than%20or%20Equal%20X/README_EN.md) + +## 题目描述 + + + +

    给你一个非负整数数组 nums 。如果存在一个数 x ,使得 nums 中恰好有 x 个元素 大于或者等于 x ,那么就称 nums 是一个 特殊数组 ,而 x 是该数组的 特征值

    + +

    注意: x 不必nums 的中的元素。

    + +

    如果数组 nums 是一个 特殊数组 ,请返回它的特征值 x 。否则,返回 -1 。可以证明的是,如果 nums 是特殊数组,那么其特征值 x唯一的

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [3,5]
    +输出:2
    +解释:有 2 个元素(3 和 5)大于或等于 2 。
    +
    + +

    示例 2:

    + +
    输入:nums = [0,0]
    +输出:-1
    +解释:没有满足题目要求的特殊数组,故而也不存在特征值 x 。
    +如果 x = 0,应该有 0 个元素 >= x,但实际有 2 个。
    +如果 x = 1,应该有 1 个元素 >= x,但实际有 0 个。
    +如果 x = 2,应该有 2 个元素 >= x,但实际有 0 个。
    +x 不能取更大的值,因为 nums 中只有两个元素。
    + +

    示例 3:

    + +
    输入:nums = [0,4,3,0,4]
    +输出:3
    +解释:有 3 个元素大于或等于 3 。
    +
    + +

    示例 4:

    + +
    输入:nums = [3,6,7,7,0]
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 0 <= nums[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1609.leetcode1609 Even Odd Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1609.leetcode1609 Even Odd Tree-zh.md" new file mode 100644 index 00000000..6b98f8c8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1609.leetcode1609 Even Odd Tree-zh.md" @@ -0,0 +1,112 @@ +# [1609. 奇偶树](https://leetcode-cn.com/problems/even-odd-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1609.Even%20Odd%20Tree/README_EN.md) + +## 题目描述 + + + +

    如果一棵二叉树满足下述几个条件,则可以称为 奇偶树

    + +
      +
    • 二叉树根节点所在层下标为 0 ,根的子节点所在层下标为 1 ,根的孙节点所在层下标为 2 ,依此类推。
    • +
    • 偶数下标 层上的所有节点的值都是 整数,从左到右按顺序 严格递增
    • +
    • 奇数下标 层上的所有节点的值都是 整数,从左到右按顺序 严格递减
    • +
    + +

    给你二叉树的根节点,如果二叉树为 奇偶树 ,则返回 true ,否则返回 false

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
    +输出:true
    +解释:每一层的节点值分别是:
    +0 层:[1]
    +1 层:[10,4]
    +2 层:[3,7,9]
    +3 层:[12,8,6,2]
    +由于 0 层和 2 层上的节点值都是奇数且严格递增,而 1 层和 3 层上的节点值都是偶数且严格递减,因此这是一棵奇偶树。
    +
    + +

    示例 2:

    + +

    + +
    +输入:root = [5,4,2,3,3,7]
    +输出:false
    +解释:每一层的节点值分别是:
    +0 层:[5]
    +1 层:[4,2]
    +2 层:[3,3,7]
    +2 层上的节点值不满足严格递增的条件,所以这不是一棵奇偶树。
    +
    + +

    示例 3:

    + +

    + +
    +输入:root = [5,9,1,3,5,7]
    +输出:false
    +解释:1 层上的节点值应为偶数。
    +
    + +

    示例 4:

    + +
    +输入:root = [1]
    +输出:true
    +
    + +

    示例 5:

    + +
    +输入:root = [11,8,6,1,3,9,11,30,20,18,16,12,10,4,2,17]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点数在范围 [1, 105]
    • +
    • 1 <= Node.val <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1610.leetcode1610 Maximum Number of Visible Points-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1610.leetcode1610 Maximum Number of Visible Points-zh.md" new file mode 100644 index 00000000..59bc0631 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1610.leetcode1610 Maximum Number of Visible Points-zh.md" @@ -0,0 +1,89 @@ +# [1610. 可见点的最大数目](https://leetcode-cn.com/problems/maximum-number-of-visible-points) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1610.Maximum%20Number%20of%20Visible%20Points/README_EN.md) + +## 题目描述 + + + +

    给你一个点数组 points 和一个表示角度的整数 angle ,你的位置是 location ,其中 location = [posx, posy]points[i] = [xi, yi] 都表示 X-Y 平面上的整数坐标。

    + +

    最开始,你面向东方进行观测。你 不能 进行移动改变位置,但可以通过 自转 调整观测角度。换句话说,posxposy 不能改变。你的视野范围的角度用 angle 表示, 这决定了你观测任意方向时可以多宽。设 d 为你逆时针自转旋转的度数,那么你的视野就是角度范围 [d - angle/2, d + angle/2] 所指示的那片区域。

    + + + +

    对于每个点,如果由该点、你的位置以及从你的位置直接向东的方向形成的角度 位于你的视野中 ,那么你就可以看到它。

    + +

    同一个坐标上可以有多个点。你所在的位置也可能存在一些点,但不管你的怎么旋转,总是可以看到这些点。同时,点不会阻碍你看到其他点。

    + +

    返回你能看到的点的最大数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]
    +输出:3
    +解释:阴影区域代表你的视野。在你的视野中,所有的点都清晰可见,尽管 [2,2] 和 [3,3]在同一条直线上,你仍然可以看到 [3,3] 。
    + +

    示例 2:

    + +
    +输入:points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]
    +输出:4
    +解释:在你的视野中,所有的点都清晰可见,包括你所在位置的那个点。
    + +

    示例 3:

    + +

    + +
    +输入:points = [[1,0],[2,1]], angle = 13, location = [1,1]
    +输出:1
    +解释:如图所示,你只能看到两点之一。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= points.length <= 105
    • +
    • points[i].length == 2
    • +
    • location.length == 2
    • +
    • 0 <= angle < 360
    • +
    • 0 <= posx, posy, xi, yi <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1611.leetcode1611 Minimum One Bit Operations to Make Integers Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1611.leetcode1611 Minimum One Bit Operations to Make Integers Zero-zh.md" new file mode 100644 index 00000000..eb88dc63 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1611.leetcode1611 Minimum One Bit Operations to Make Integers Zero-zh.md" @@ -0,0 +1,100 @@ +# [1611. 使整数变为 0 的最少操作次数](https://leetcode-cn.com/problems/minimum-one-bit-operations-to-make-integers-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1611.Minimum%20One%20Bit%20Operations%20to%20Make%20Integers%20Zero/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,你需要重复执行多次下述操作将其转换为 0

    + +
      +
    • 翻转 n 的二进制表示中最右侧位(第 0 位)。
    • +
    • 如果第 (i-1) 位为 1 且从第 (i-2) 位到第 0 位都为 0,则翻转 n 的二进制表示中的第 i 位。
    • +
    + +

    返回将 n 转换为 0 的最小操作次数。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 0
    +输出:0
    +
    + +

    示例 2:

    + +
    +输入:n = 3
    +输出:2
    +解释:3 的二进制表示为 "11"
    +"11" -> "01" ,执行的是第 2 种操作,因为第 0 位为 1 。
    +"01" -> "00" ,执行的是第 1 种操作。
    +
    + +

    示例 3:

    + +
    +输入:n = 6
    +输出:4
    +解释:6 的二进制表示为 "110".
    +"110" -> "010" ,执行的是第 2 种操作,因为第 1 位为 1 ,第 0 到 0 位为 0 。
    +"010" -> "011" ,执行的是第 1 种操作。
    +"011" -> "001" ,执行的是第 2 种操作,因为第 0 位为 1 。
    +"001" -> "000" ,执行的是第 1 种操作。
    +
    + +

    示例 4:

    + +
    +输入:n = 9
    +输出:14
    +
    + +

    示例 5:

    + +
    +输入:n = 333
    +输出:393
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1612.leetcode1612 Check If Two Expression Trees are Equivalent-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1612.leetcode1612 Check If Two Expression Trees are Equivalent-zh.md" new file mode 100644 index 00000000..08cbbf3e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1612.leetcode1612 Check If Two Expression Trees are Equivalent-zh.md" @@ -0,0 +1,84 @@ +# [1612. 检查两棵二叉表达式树是否等价](https://leetcode-cn.com/problems/check-if-two-expression-trees-are-equivalent) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1612.Check%20If%20Two%20Expression%20Trees%20are%20Equivalent/README_EN.md) + +## 题目描述 + + + +

    二叉表达式树是一种表达算术表达式的二叉树。二叉表达式树中的每一个节点都有零个或两个子节点。 叶节点(有 0 个子节点的节点)表示操作数,非叶节点(有 2 个子节点的节点)表示运算符。在本题中,我们只考虑 '+' 运算符(即加法)。

    + +

    给定两棵二叉表达式树的根节点 root1 和 root2 。如果两棵二叉表达式树等价,返回 true ,否则返回 false 。

    + +

    当两棵二叉搜索树中的变量取任意值,分别求得的值都相等时,我们称这两棵二叉表达式树是等价的。

    + +

    进阶:当你的答案需同时支持 '-' 运算符(减法)时,你该如何修改你的答案?

    + +

     

    + +

    示例 1:

    + +
    +输入: root1 = [x], root2 = [x]
    +输出: true
    +
    + +

    示例 2:

    + +

    + +
    +输入:root1 = [+,a,+,null,null,b,c], root2 = [+,+,a,b,c]
    +输出:true
    +解释:a + (b + c) == (b + c) + a
    + +

    示例 3:

    + +

    + +
    +输入: root1 = [+,a,+,null,null,b,c], root2 = [+,+,a,b,d]
    +输出: false
    +解释: a + (b + c) != (b + d) + a
    +
    + +

     

    + +

    提示:

    + +
      +
    • 两棵树中的节点个数相等,且节点个数为范围 [1, 4999] 内的奇数。
    • +
    • Node.val 是 '+' 或小写英文字母。
    • +
    • 给定的树保证是有效的二叉表达式树。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1613.leetcode1613 Find the Missing IDs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1613.leetcode1613 Find the Missing IDs-zh.md" new file mode 100644 index 00000000..3f8fc796 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1613.leetcode1613 Find the Missing IDs-zh.md" @@ -0,0 +1,66 @@ +# [1613. 找到遗失的ID](https://leetcode-cn.com/problems/find-the-missing-ids) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1613.Find%20the%20Missing%20IDs/README_EN.md) + +## 题目描述 + + + +

    表: Customers

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| customer_id   | int     |
    +| customer_name | varchar |
    ++---------------+---------+
    +customer_id 是该表主键.
    +该表第一行包含了顾客的名字和id.
    +
    + +

     

    + +

    写一个 SQL 语句, 找到所有遗失的顾客id. 遗失的顾客id是指那些不在 Customers 表中, 值却处于 1 和表中最大 customer_id 之间的id.

    + +

    注意: 最大的 customer_id 值不会超过 100.

    + +

    返回结果按 ids 升序排列

    + +

    查询结果格式如下例所示.

    + +

     

    + +
    +Customers 表:
    ++-------------+---------------+
    +| customer_id | customer_name |
    ++-------------+---------------+
    +| 1           | Alice         |
    +| 4           | Bob           |
    +| 5           | Charlie       |
    ++-------------+---------------+
    +
    +Result 表:
    ++-----+
    +| ids |
    ++-----+
    +| 2   |
    +| 3   |
    ++-----+
    +表中最大的customer_id是5, 所以在范围[1,5]内, ID2和3从表中遗失.
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1614.leetcode1614 Maximum Nesting Depth of the Parentheses-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1614.leetcode1614 Maximum Nesting Depth of the Parentheses-zh.md" new file mode 100644 index 00000000..59e3ef6d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1614.leetcode1614 Maximum Nesting Depth of the Parentheses-zh.md" @@ -0,0 +1,100 @@ +# [1614. 括号的最大嵌套深度](https://leetcode-cn.com/problems/maximum-nesting-depth-of-the-parentheses) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1614.Maximum%20Nesting%20Depth%20of%20the%20Parentheses/README_EN.md) + +## 题目描述 + + + +

    如果字符串满足以下条件之一,则可以称之为 有效括号字符串(valid parentheses string,可以简写为 VPS):

    + +
      +
    • 字符串是一个空字符串 "",或者是一个不为 "("")" 的单字符。
    • +
    • 字符串可以写为 ABAB 字符串连接),其中 AB 都是 有效括号字符串
    • +
    • 字符串可以写为 (A),其中 A 是一个 有效括号字符串
    • +
    + +

    类似地,可以定义任何有效括号字符串 S嵌套深度 depth(S)

    + +
      +
    • depth("") = 0
    • +
    • depth(C) = 0,其中 C 是单个字符的字符串,且该字符不是 "(" 或者 ")"
    • +
    • depth(A + B) = max(depth(A), depth(B)),其中 AB 都是 有效括号字符串
    • +
    • depth("(" + A + ")") = 1 + depth(A),其中 A 是一个 有效括号字符串
    • +
    + +

    例如:"""()()""()(()())" 都是 有效括号字符串(嵌套深度分别为 0、1、2),而 ")(""(()" 都不是 有效括号字符串

    + +

    给你一个 有效括号字符串 s,返回该字符串的 s 嵌套深度

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "(1+(2*3)+((8)/4))+1"
    +输出:3
    +解释:数字 8 在嵌套的 3 层括号中。
    +
    + +

    示例 2:

    + +
    +输入:s = "(1)+((2))+(((3)))"
    +输出:3
    +
    + +

    示例 3:

    + +
    +输入:s = "1+(2*3)/(2-1)"
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:s = "1"
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s 由数字 0-9 和字符 '+''-''*''/''('')' 组成
    • +
    • 题目数据保证括号表达式 s有效的括号表达式
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1615.leetcode1615 Maximal Network Rank-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1615.leetcode1615 Maximal Network Rank-zh.md" new file mode 100644 index 00000000..a46938da --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1615.leetcode1615 Maximal Network Rank-zh.md" @@ -0,0 +1,89 @@ +# [1615. 最大网络秩](https://leetcode-cn.com/problems/maximal-network-rank) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1615.Maximal%20Network%20Rank/README_EN.md) + +## 题目描述 + + + +

    n 座城市和一些连接这些城市的道路 roads 共同组成一个基础设施网络。每个 roads[i] = [ai, bi] 都表示在城市 aibi 之间有一条双向道路。

    + +

    两座不同城市构成的 城市对网络秩 定义为:与这两座城市 直接 相连的道路总数。如果存在一条道路直接连接这两座城市,则这条道路只计算 一次

    + +

    整个基础设施网络的 最大网络秩 是所有不同城市对中的 最大网络秩

    + +

    给你整数 n 和数组 roads,返回整个基础设施网络的 最大网络秩

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
    +输出:4
    +解释:城市 0 和 1 的网络秩是 4,因为共有 4 条道路与城市 0 或 1 相连。位于 0 和 1 之间的道路只计算一次。
    +
    + +

    示例 2:

    + +

    + +
    +输入:n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
    +输出:5
    +解释:共有 5 条道路与城市 1 或 2 相连。
    +
    + +

    示例 3:

    + +
    +输入:n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
    +输出:5
    +解释:2 和 5 的网络秩为 5,注意并非所有的城市都需要连接起来。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 100
    • +
    • 0 <= roads.length <= n * (n - 1) / 2
    • +
    • roads[i].length == 2
    • +
    • 0 <= ai, bi <= n-1
    • +
    • ai != bi
    • +
    • 每对城市之间 最多只有一条 道路相连
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1616.leetcode1616 Split Two Strings to Make Palindrome-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1616.leetcode1616 Split Two Strings to Make Palindrome-zh.md" new file mode 100644 index 00000000..477b77b2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1616.leetcode1616 Split Two Strings to Make Palindrome-zh.md" @@ -0,0 +1,93 @@ +# [1616. 分割两个字符串得到回文串](https://leetcode-cn.com/problems/split-two-strings-to-make-palindrome) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1616.Split%20Two%20Strings%20to%20Make%20Palindrome/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 a 和 b ,它们长度相同。请你选择一个下标,将两个字符串都在 相同的下标 分割开。由 a 可以得到两个字符串: aprefix 和 asuffix ,满足 a = aprefix + asuffix ,同理,由 b 可以得到两个字符串 bprefix 和 bsuffix ,满足 b = bprefix + bsuffix 。请你判断 aprefix + bsuffix 或者 bprefix + asuffix 能否构成回文串。

    + +

    当你将一个字符串 s 分割成 sprefix 和 ssuffix 时, ssuffix 或者 sprefix 可以为空。比方说, s = "abc" 那么 "" + "abc" , "a" + "bc" , "ab" + "c" 和 "abc" + "" 都是合法分割。

    + +

    如果 能构成回文字符串 ,那么请返回 true,否则返回 false 。

    + +

    注意, x + y 表示连接字符串 x 和 y 。

    + +

     

    + +

    示例 1:

    + +
    +输入:a = "x", b = "y"
    +输出:true
    +解释:如果 a 或者 b 是回文串,那么答案一定为 true ,因为你可以如下分割:
    +aprefix = "", asuffix = "x"
    +bprefix = "", bsuffix = "y"
    +那么 aprefix + bsuffix = "" + "y" = "y" 是回文串。
    +
    + +

    示例 2:

    + +
    +输入:a = "abdef", b = "fecab"
    +输出:true
    +
    + +

    示例 3:

    + +
    +输入:a = "ulacfd", b = "jizalu"
    +输出:true
    +解释:在下标为 3 处分割:
    +aprefix = "ula", asuffix = "cfd"
    +bprefix = "jiz", bsuffix = "alu"
    +那么 aprefix + bsuffix = "ula" + "alu" = "ulaalu" 是回文串。
    + +

    示例 4:

    + +
    +输入:a = "xbdef", b = "xecab"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= a.length, b.length <= 105
    • +
    • a.length == b.length
    • +
    • a 和 b 都只包含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1617.leetcode1617 Count Subtrees With Max Distance Between Cities-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1617.leetcode1617 Count Subtrees With Max Distance Between Cities-zh.md" new file mode 100644 index 00000000..815ce504 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1617.leetcode1617 Count Subtrees With Max Distance Between Cities-zh.md" @@ -0,0 +1,89 @@ +# [1617. 统计子树中城市之间最大距离](https://leetcode-cn.com/problems/count-subtrees-with-max-distance-between-cities) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1617.Count%20Subtrees%20With%20Max%20Distance%20Between%20Cities/README_EN.md) + +## 题目描述 + + + +

    给你 n 个城市,编号为从 1 到 n 。同时给你一个大小为 n-1 的数组 edges ,其中 edges[i] = [ui, vi] 表示城市 ui 和 vi 之间有一条双向边。题目保证任意城市之间只有唯一的一条路径。换句话说,所有城市形成了一棵  。

    + +

    一棵 子树 是城市的一个子集,且子集中任意城市之间可以通过子集中的其他城市和边到达。两个子树被认为不一样的条件是至少有一个城市在其中一棵子树中存在,但在另一棵子树中不存在。

    + +

    对于 d 从 1 到 n-1 ,请你找到城市间 最大距离 恰好为 d 的所有子树数目。

    + +

    请你返回一个大小为 n-1 的数组,其中第 d 个元素(下标从 1 开始)是城市间 最大距离 恰好等于 d 的子树数目。

    + +

    请注意,两个城市间距离定义为它们之间需要经过的边的数目。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 4, edges = [[1,2],[2,3],[2,4]]
    +输出:[3,4,0]
    +解释:
    +子树 {1,2}, {2,3} 和 {2,4} 最大距离都是 1 。
    +子树 {1,2,3}, {1,2,4}, {2,3,4} 和 {1,2,3,4} 最大距离都为 2 。
    +不存在城市间最大距离为 3 的子树。
    +
    + +

    示例 2:

    + +
    +输入:n = 2, edges = [[1,2]]
    +输出:[1]
    +
    + +

    示例 3:

    + +
    +输入:n = 3, edges = [[1,2],[2,3]]
    +输出:[2,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 15
    • +
    • edges.length == n-1
    • +
    • edges[i].length == 2
    • +
    • 1 <= ui, vi <= n
    • +
    • 题目保证 (ui, vi) 所表示的边互不相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1618.leetcode1618 Maximum Font to Fit a Sentence in a Screen-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1618.leetcode1618 Maximum Font to Fit a Sentence in a Screen-zh.md" new file mode 100644 index 00000000..49eb908d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1618.leetcode1618 Maximum Font to Fit a Sentence in a Screen-zh.md" @@ -0,0 +1,230 @@ +# [1618. 找出适应屏幕的最大字号](https://leetcode-cn.com/problems/maximum-font-to-fit-a-sentence-in-a-screen) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1618.Maximum%20Font%20to%20Fit%20a%20Sentence%20in%20a%20Screen/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 text。并能够在 宽为 w 高为 h 的屏幕上显示该文本。

    + +

    字体数组中包含按升序排列的可用字号,您可以从该数组中选择任何字体大小。

    + +

    您可以使用FontInfo接口来获取任何可用字体大小的任何字符的宽度和高度。

    + +

    FontInfo接口定义如下:

    + +
    interface FontInfo {
    +  // 返回 fontSize 大小的字符 ch 在屏幕上的宽度。
    +  // 每调用该函数复杂度为 O(1)
    +  public int getWidth(int fontSize, char ch);
    +
    +  // 返回 fontSize 大小的任意字符在屏幕上的高度。
    +  // 每调用该函数复杂度为 O(1)
    +  public int getHeight(int fontSize);
    +}
    + +

    一串字符的文本宽度应该是每一个字符在对应字号(fontSize)下返回的宽度getHeight(fontSize)总和

    + +

    请注意:文本最多只能排放一排

    + +

    如果使用相同的参数调用 getHeight 或 getWidth ,则可以保证 FontInfo 将返回相同的值。

    + +

    同时,对于任何字体大小的 fontSize 和任何字符 ch

    + +
      +
    • getHeight(fontSize) <= getHeight(fontSize+1)
    • +
    • getWidth(fontSize, ch) <= getWidth(fontSize+1, ch)
    • +
    + +

    返回可用于在屏幕上显示文本的最大字体大小。如果文本不能以任何字体大小显示,则返回-1

    + +

    示例 1:

    + +
    输入: text = "helloworld", w = 80, h = 20, fonts = [6,8,10,12,14,16,18,24,36]
    +输出: 6
    +
    + +

    Example 2:

    + +
    输入: text = "leetcode", w = 1000, h = 50, fonts = [1,2,4]
    +输出: 4
    +
    + +

    Example 3:

    + +
    输入: text = "easyquestion", w = 100, h = 100, fonts = [10,15,20,25]
    +输出: -1
    +
    + +

     

    + +

    注意:

    + +
      +
    • 1 <= text.length <= 50000
    • +
    • text 只包含小写字母
    • +
    • 1 <= w <= 107
    • +
    • 1 <= h <= 104
    • +
    • 1 <= fonts.length <= 105
    • +
    • 1 <= fonts[i] <= 105
    • +
    • fonts 已经按升序排序,且不包含重复项。
    • +
    + + +## 解法 + + + +二分查找,见[整数二分算法模板 2](/basic/searching/BinarySearch/README.md)。 + + + +### **Python3** + + + +```python +# """ +# This is FontInfo's API interface. +# You should not implement it, or speculate about its implementation +# """ +#class FontInfo(object): +# Return the width of char ch when fontSize is used. +# def getWidth(self, fontSize, ch): +# """ +# :type fontSize: int +# :type ch: char +# :rtype int +# """ +# +# def getHeight(self, fontSize): +# """ +# :type fontSize: int +# :rtype int +# """ +class Solution: + def maxFont(self, text: str, w: int, h: int, fonts: List[int], fontInfo : 'FontInfo') -> int: + def check(text, fontSize, w, h, fontInfo) -> bool: + if fontInfo.getHeight(fontSize) > h: + return False + width = 0 + for ch in text: + width += fontInfo.getWidth(fontSize, ch) + if width > w: + return False + return True + + left, right = 0, len(fonts) - 1 + while left < right: + mid = (left + right + 1) >> 1 + fontSize = fonts[mid] + if check(text, fontSize, w, h, fontInfo): + left = mid + else: + right = mid - 1 + return fonts[left] if check(text, fonts[left], w, h, fontInfo) else -1 +``` + +### **Java** + + + +```java +/** + * // This is the FontInfo's API interface. + * // You should not implement it, or speculate about its implementation + * interface FontInfo { + * // Return the width of char ch when fontSize is used. + * public int getWidth(int fontSize, char ch) {} + * // Return Height of any char when fontSize is used. + * public int getHeight(int fontSize) + * } + */ +class Solution { + public int maxFont(String text, int w, int h, int[] fonts, FontInfo fontInfo) { + int left = 0, right = fonts.length - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + int fontSize = fonts[mid]; + if (check(text, fontSize, w, h, fontInfo)) { + left = mid; + } else { + right = mid - 1; + } + } + return check(text, fonts[left], w, h, fontInfo) ? fonts[left] : -1; + } + + private boolean check(String s, int fontSize, int w, int h, FontInfo fontInfo) { + if (fontInfo.getHeight(fontSize) > h) { + return false; + } + int width = 0; + for (int i = 0; i < s.length(); ++i) { + char ch = s.charAt(i); + width += fontInfo.getWidth(fontSize, ch); + if (width > w) { + return false; + } + } + return true; + } +} +``` + +### **C++** + +```cpp +/** + * // This is the FontInfo's API interface. + * // You should not implement it, or speculate about its implementation + * class FontInfo { + * public: + * // Return the width of char ch when fontSize is used. + * int getWidth(int fontSize, char ch); + * + * // Return Height of any char when fontSize is used. + * int getHeight(int fontSize) + * }; + */ +class Solution { +public: + int maxFont(string text, int w, int h, vector& fonts, FontInfo fontInfo) { + int left = 0, right = fonts.size() - 1; + while (left < right) { + int mid = left + right + 1 >> 1; + int fontSize = fonts[mid]; + if (check(text, fontSize, w, h, fontInfo)) { + left = mid; + } else { + right = mid - 1; + } + } + return check(text, fonts[left], w, h, fontInfo) ? fonts[left] : -1; + } + +private: + bool check(string s, int fontSize, int w, int h, FontInfo fontInfo) { + if (fontInfo.getHeight(fontSize) > h) { + return false; + } + int width = 0; + for (auto ch : s) { + width += fontInfo.getWidth(fontSize, ch); + if (width > w) { + return false; + } + } + return true; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1619.leetcode1619 Mean of Array After Removing Some Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1619.leetcode1619 Mean of Array After Removing Some Elements-zh.md" new file mode 100644 index 00000000..175daae8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1619.leetcode1619 Mean of Array After Removing Some Elements-zh.md" @@ -0,0 +1,90 @@ +# [1619. 删除某些元素后的数组均值](https://leetcode-cn.com/problems/mean-of-array-after-removing-some-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1619.Mean%20of%20Array%20After%20Removing%20Some%20Elements/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,请你删除最小 5% 的数字和最大 5% 的数字后,剩余数字的平均值。

    + +

    标准答案 误差在 10-5 的结果都被视为正确结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
    +输出:2.00000
    +解释:删除数组中最大和最小的元素后,所有元素都等于 2,所以平均值为 2 。
    +
    + +

    示例 2:

    + +
    +输入:arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]
    +输出:4.00000
    +
    + +

    示例 3:

    + +
    +输入:arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]
    +输出:4.77778
    +
    + +

    示例 4:

    + +
    +输入:arr = [9,7,8,7,7,8,4,4,6,8,8,7,6,8,8,9,2,6,0,0,1,10,8,6,3,3,5,1,10,9,0,7,10,0,10,4,1,10,6,9,3,6,0,0,2,7,0,6,7,2,9,7,7,3,0,1,6,1,10,3]
    +输出:5.27778
    +
    + +

    示例 5:

    + +
    +输入:arr = [4,8,4,10,0,7,1,3,7,8,8,3,4,1,6,2,1,1,8,0,9,8,0,3,9,10,3,10,1,10,7,3,2,1,4,9,10,7,6,4,0,8,5,1,2,1,6,2,5,0,7,10,9,10,3,7,10,5,8,5,7,6,7,6,10,9,5,10,5,5,7,2,10,7,7,8,2,0,1,1]
    +输出:5.29167
    +
    + +

     

    + +

    提示:

    + +
      +
    • 20 <= arr.length <= 1000
    • +
    • arr.length 是 20 的 倍数 
    • +
    • 0 <= arr[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1620.leetcode1620 Coordinate With Maximum Network Quality-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1620.leetcode1620 Coordinate With Maximum Network Quality-zh.md" new file mode 100644 index 00000000..74641f49 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1620.leetcode1620 Coordinate With Maximum Network Quality-zh.md" @@ -0,0 +1,100 @@ +# [1620. 网络信号最好的坐标](https://leetcode-cn.com/problems/coordinate-with-maximum-network-quality) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1620.Coordinate%20With%20Maximum%20Network%20Quality/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 towers 和一个整数 radius ,数组中包含一些网络信号塔,其中 towers[i] = [xi, yi, qi] 表示第 i 个网络信号塔的坐标是 (xi, yi) 且信号强度参数为 qi 。所有坐标都是在  X-Y 坐标系内的 整数 坐标。两个坐标之间的距离用 欧几里得距离 计算。

    + +

    整数 radius 表示一个塔 能到达 最远距离 。如果一个坐标跟塔的距离在 radius 以内,那么该塔的信号可以到达该坐标。在这个范围以外信号会很微弱,所以 radius 以外的距离该塔是 不能到达的 。

    + +

    如果第 i 个塔能到达 (x, y) ,那么该塔在此处的信号为 ⌊qi / (1 + d)⌋ ,其中 d 是塔跟此坐标的距离。一个坐标的 网络信号 是所有 能到达 该坐标的塔的信号强度之和。

    + +

    请你返回 网络信号 最大的整数坐标点。如果有多个坐标网络信号一样大,请你返回字典序最小的一个坐标。

    + +

    注意:

    + +
      +
    • 坐标 (x1, y1) 字典序比另一个坐标 (x2, y2) 小:要么 x1 < x2 ,要么 x1 == x2 且 y1 < y2 。
    • +
    • ⌊val⌋ 表示小于等于 val 的最大整数(向下取整函数)。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2
    +输出:[2,1]
    +解释:
    +坐标 (2, 1) 信号强度之和为 13
    +- 塔 (2, 1) 强度参数为 7 ,在该点强度为 ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
    +- 塔 (1, 2) 强度参数为 5 ,在该点强度为 ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
    +- 塔 (3, 1) 强度参数为 9 ,在该点强度为 ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
    +没有别的坐标有更大的信号强度。
    + +

    示例 2:

    + +
    +输入:towers = [[23,11,21]], radius = 9
    +输出:[23,11]
    +
    + +

    示例 3:

    + +
    +输入:towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2
    +输出:[1,2]
    +
    + +

    示例 4:

    + +
    +输入:towers = [[2,1,9],[0,1,9]], radius = 2
    +输出:[0,1]
    +解释:坐标 (0, 1) 和坐标 (2, 1) 都是强度最大的位置,但是 (0, 1) 字典序更小。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= towers.length <= 50
    • +
    • towers[i].length == 3
    • +
    • 0 <= xi, yi, qi <= 50
    • +
    • 1 <= radius <= 50
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1621.leetcode1621 Number of Sets of K Non-Overlapping Line Segments-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1621.leetcode1621 Number of Sets of K Non-Overlapping Line Segments-zh.md" new file mode 100644 index 00000000..15a53769 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1621.leetcode1621 Number of Sets of K Non-Overlapping Line Segments-zh.md" @@ -0,0 +1,91 @@ +# [1621. 大小为 K 的不重叠线段的数目](https://leetcode-cn.com/problems/number-of-sets-of-k-non-overlapping-line-segments) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1621.Number%20of%20Sets%20of%20K%20Non-Overlapping%20Line%20Segments/README_EN.md) + +## 题目描述 + + + +

    给你一维空间的 n 个点,其中第 i 个点(编号从 0 到 n-1)位于 x = i 处,请你找到 恰好 k 个不重叠 线段且每个线段至少覆盖两个点的方案数。线段的两个端点必须都是 整数坐标 。这 k 个线段不需要全部覆盖全部 n 个点,且它们的端点 可以 重合。

    + +

    请你返回 k 个不重叠线段的方案数。由于答案可能很大,请将结果对 109 + 7 取余 后返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 4, k = 2
    +输出:5
    +解释:
    +如图所示,两个线段分别用红色和蓝色标出。
    +上图展示了 5 种不同的方案 {(0,2),(2,3)},{(0,1),(1,3)},{(0,1),(2,3)},{(1,2),(2,3)},{(0,1),(1,2)} 。
    + +

    示例 2:

    + +
    +输入:n = 3, k = 1
    +输出:3
    +解释:总共有 3 种不同的方案 {(0,1)}, {(0,2)}, {(1,2)} 。
    +
    + +

    示例 3:

    + +
    +输入:n = 30, k = 7
    +输出:796297179
    +解释:画 7 条线段的总方案数为 3796297200 种。将这个数对 109 + 7 取余得到 796297179 。
    +
    + +

    示例 4:

    + +
    +输入:n = 5, k = 3
    +输出:7
    +
    + +

    示例 5:

    + +
    +输入:n = 3, k = 2
    +输出:1
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 1000
    • +
    • 1 <= k <= n-1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1622.leetcode1622 Fancy Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1622.leetcode1622 Fancy Sequence-zh.md" new file mode 100644 index 00000000..ebf52289 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1622.leetcode1622 Fancy Sequence-zh.md" @@ -0,0 +1,86 @@ +# [1622. 奇妙序列](https://leetcode-cn.com/problems/fancy-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1622.Fancy%20Sequence/README_EN.md) + +## 题目描述 + + + +

    请你实现三个 API appendaddAll 和 multAll 来实现奇妙序列。

    + +

    请实现 Fancy 类 :

    + +
      +
    • Fancy() 初始化一个空序列对象。
    • +
    • void append(val) 将整数 val 添加在序列末尾。
    • +
    • void addAll(inc) 将所有序列中的现有数值都增加 inc 。
    • +
    • void multAll(m) 将序列中的所有现有数值都乘以整数 m 。
    • +
    • int getIndex(idx) 得到下标为 idx 处的数值(下标从 0 开始),并将结果对 109 + 7 取余。如果下标大于等于序列的长度,请返回 -1 。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"]
    +[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]
    +输出:
    +[null, null, null, null, null, 10, null, null, null, 26, 34, 20]
    +
    +解释:
    +Fancy fancy = new Fancy();
    +fancy.append(2);   // 奇妙序列:[2]
    +fancy.addAll(3);   // 奇妙序列:[2+3] -> [5]
    +fancy.append(7);   // 奇妙序列:[5, 7]
    +fancy.multAll(2);  // 奇妙序列:[5*2, 7*2] -> [10, 14]
    +fancy.getIndex(0); // 返回 10
    +fancy.addAll(3);   // 奇妙序列:[10+3, 14+3] -> [13, 17]
    +fancy.append(10);  // 奇妙序列:[13, 17, 10]
    +fancy.multAll(2);  // 奇妙序列:[13*2, 17*2, 10*2] -> [26, 34, 20]
    +fancy.getIndex(0); // 返回 26
    +fancy.getIndex(1); // 返回 34
    +fancy.getIndex(2); // 返回 20
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= val, inc, m <= 100
    • +
    • 0 <= idx <= 105
    • +
    • 总共最多会有 105 次对 appendaddAllmultAll 和 getIndex 的调用。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1623.leetcode1623 All Valid Triplets That Can Represent a Country-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1623.leetcode1623 All Valid Triplets That Can Represent a Country-zh.md" new file mode 100644 index 00000000..2e9a7973 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1623.leetcode1623 All Valid Triplets That Can Represent a Country-zh.md" @@ -0,0 +1,129 @@ +# [1623. 三人国家代表队](https://leetcode-cn.com/problems/all-valid-triplets-that-can-represent-a-country) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1623.All%20Valid%20Triplets%20That%20Can%20Represent%20a%20Country/README_EN.md) + +## 题目描述 + + + +

    表: SchoolA

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id 是表的主键
    +表中的每一行包含了学校A中每一个学生的名字和ID
    +所有student_name在表中都是独一无二的
    +
    + +

     

    + +

    表: SchoolB

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id 是表的主键
    +表中的每一行包含了学校B中每一个学生的名字和ID
    +所有student_name在表中都是独一无二的
    +
    + +

     

    + +

    表: SchoolC

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| student_id    | int     |
    +| student_name  | varchar |
    ++---------------+---------+
    +student_id 是表的主键
    +表中的每一行包含了学校C中每一个学生的名字和ID
    +所有student_name在表中都是独一无二的
    +
    + +

     

    + +

    有一个国家只有三所学校,这个国家的每一个学生只会注册一所学校

    + +

    这个国家正在参加一个竞赛,他们希望从这三所学校中各选出一个学生来组建一支三人的代表队。

    + +

    例如:

    + +
      +
    • member_A是从 SchoolA中选出的
    • +
    • member_B是从 SchoolB中选出的
    • +
    • member_C是从 SchoolC中选出的
    • +
    • 被选中的学生具有不同的名字和ID(没有任何两个学生拥有相同的名字、没有任何两个学生拥有相同的ID)
    • +
    + +

    使用上述条件,编写SQL查询语句来找到所有可能的三人国家代表队组合。

    + +

    查询结果接受任何顺序。

    + +

     

    + +

    查询结果格式样例:

    + +
    SchoolA table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 1          | Alice        |
    +| 2          | Bob          |
    ++------------+--------------+
    +
    +SchoolB table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 3          | Tom          |
    ++------------+--------------+
    +
    +SchoolC table:
    ++------------+--------------+
    +| student_id | student_name |
    ++------------+--------------+
    +| 3          | Tom          |
    +| 2          | Jerry        |
    +| 10         | Alice        |
    ++------------+--------------+
    +
    +预期结果:
    ++----------+----------+----------+
    +| member_A | member_B | member_C |
    ++----------+----------+----------+
    +| Alice    | Tom      | Jerry    |
    +| Bob      | Tom      | Alice    |
    ++----------+----------+----------+
    +
    +让我们看看有哪些可能的组合:
    +- (Alice, Tom, Tom) --> 不适用,因为member_B(Tom)和member_C(Tom)有相同的名字和ID
    +- (Alice, Tom, Jerry) --> 可能的组合
    +- (Alice, Tom, Alice) --> 不适用,因为member_A和member_C有相同的名字
    +- (Bob, Tom, Tom) --> 不适用,因为member_B和member_C有相同的名字和ID
    +- (Bob, Tom, Jerry) --> 不适用,因为member_A和member_C有相同的ID
    +- (Bob, Tom, Alice) --> 可能的组合.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1624.leetcode1624 Largest Substring Between Two Equal Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1624.leetcode1624 Largest Substring Between Two Equal Characters-zh.md" new file mode 100644 index 00000000..185f2f66 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1624.leetcode1624 Largest Substring Between Two Equal Characters-zh.md" @@ -0,0 +1,80 @@ +# [1624. 两个相同字符之间的最长子字符串](https://leetcode-cn.com/problems/largest-substring-between-two-equal-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1624.Largest%20Substring%20Between%20Two%20Equal%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s,请你返回 两个相同字符之间的最长子字符串的长度 计算长度时不含这两个字符。如果不存在这样的子字符串,返回 -1

    + +

    子字符串 是字符串中的一个连续字符序列。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "aa"
    +输出:0
    +解释:最优的子字符串是两个 'a' 之间的空子字符串。
    + +

    示例 2:

    + +
    输入:s = "abca"
    +输出:2
    +解释:最优的子字符串是 "bc" 。
    +
    + +

    示例 3:

    + +
    输入:s = "cbzxy"
    +输出:-1
    +解释:s 中不存在出现出现两次的字符,所以返回 -1 。
    +
    + +

    示例 4:

    + +
    输入:s = "cabbac"
    +输出:4
    +解释:最优的子字符串是 "abba" ,其他的非最优解包括 "bb" 和 "" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 300
    • +
    • s 只含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1625.leetcode1625 Lexicographically Smallest String After Applying Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1625.leetcode1625 Lexicographically Smallest String After Applying Operations-zh.md" new file mode 100644 index 00000000..cf3e85c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1625.leetcode1625 Lexicographically Smallest String After Applying Operations-zh.md" @@ -0,0 +1,111 @@ +# [1625. 执行操作后字典序最小的字符串](https://leetcode-cn.com/problems/lexicographically-smallest-string-after-applying-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1625.Lexicographically%20Smallest%20String%20After%20Applying%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 以及两个整数 ab 。其中,字符串 s 的长度为偶数,且仅由数字 09 组成。

    + +

    你可以在 s 上按任意顺序多次执行下面两个操作之一:

    + +
      +
    • 累加:将  a 加到 s 中所有下标为奇数的元素上(下标从 0 开始)。数字一旦超过 9 就会变成 0,如此循环往复。例如,s = "3456"a = 5,则执行此操作后 s 变成 "3951"
    • +
    • 轮转:将 s 向右轮转 b 位。例如,s = "3456"b = 1,则执行此操作后 s 变成 "6345"
    • +
    + +

    请你返回在 s 上执行上述操作任意次后可以得到的 字典序最小 的字符串。

    + +

    如果两个字符串长度相同,那么字符串 a 字典序比字符串 b 小可以这样定义:在 ab 出现不同的第一个位置上,字符串 a 中的字符出现在字母表中的时间早于 b 中的对应字符。例如,"0158” 字典序比 "0190" 小,因为不同的第一个位置是在第三个字符,显然 '5' 出现在 '9' 之前。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "5525", a = 9, b = 2
    +输出:"2050"
    +解释:执行操作如下:
    +初态:"5525"
    +轮转:"2555"
    +累加:"2454"
    +累加:"2353"
    +轮转:"5323"
    +累加:"5222"
    +累加:"5121"
    +轮转:"2151"
    +累加:"2050"​​​​​​​​​​​​
    +无法获得字典序小于 "2050" 的字符串。
    +
    + +

    示例 2:

    + +
    +输入:s = "74", a = 5, b = 1
    +输出:"24"
    +解释:执行操作如下:
    +初态:"74"
    +轮转:"47"
    +累加:"42"
    +轮转:"24"​​​​​​​​​​​​
    +无法获得字典序小于 "24" 的字符串。
    +
    + +

    示例 3:

    + +
    +输入:s = "0011", a = 4, b = 2
    +输出:"0011"
    +解释:无法获得字典序小于 "0011" 的字符串。
    +
    + +

    示例 4:

    + +
    +输入:s = "43987654", a = 7, b = 3
    +输出:"00553311"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= s.length <= 100
    • +
    • s.length 是偶数
    • +
    • s 仅由数字 09 组成
    • +
    • 1 <= a <= 9
    • +
    • 1 <= b <= s.length - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1626.leetcode1626 Best Team With No Conflicts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1626.leetcode1626 Best Team With No Conflicts-zh.md" new file mode 100644 index 00000000..30db57e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1626.leetcode1626 Best Team With No Conflicts-zh.md" @@ -0,0 +1,77 @@ +# [1626. 无矛盾的最佳球队](https://leetcode-cn.com/problems/best-team-with-no-conflicts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1626.Best%20Team%20With%20No%20Conflicts/README_EN.md) + +## 题目描述 + + + +

    假设你是球队的经理。对于即将到来的锦标赛,你想组合一支总体得分最高的球队。球队的得分是球队中所有球员的分数 总和

    + +

    然而,球队中的矛盾会限制球员的发挥,所以必须选出一支 没有矛盾 的球队。如果一名年龄较小球员的分数 严格大于 一名年龄较大的球员,则存在矛盾。同龄球员之间不会发生矛盾。

    + +

    给你两个列表 scoresages,其中每组 scores[i]ages[i] 表示第 i 名球员的分数和年龄。请你返回 所有可能的无矛盾球队中得分最高那支的分数

    + +

     

    + +

    示例 1:

    + +
    输入:scores = [1,3,5,10,15], ages = [1,2,3,4,5]
    +输出:34
    +解释:你可以选中所有球员。
    + +

    示例 2:

    + +
    输入:scores = [4,5,6,5], ages = [2,1,2,1]
    +输出:16
    +解释:最佳的选择是后 3 名球员。注意,你可以选中多个同龄球员。
    +
    + +

    示例 3:

    + +
    输入:scores = [1,2,3,5], ages = [8,9,10,1]
    +输出:6
    +解释:最佳的选择是前 3 名球员。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= scores.length, ages.length <= 1000
    • +
    • scores.length == ages.length
    • +
    • 1 <= scores[i] <= 106
    • +
    • 1 <= ages[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1627.leetcode1627 Graph Connectivity With Threshold-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1627.leetcode1627 Graph Connectivity With Threshold-zh.md" new file mode 100644 index 00000000..9cdb205b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1627.leetcode1627 Graph Connectivity With Threshold-zh.md" @@ -0,0 +1,112 @@ +# [1627. 带阈值的图连通性](https://leetcode-cn.com/problems/graph-connectivity-with-threshold) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1627.Graph%20Connectivity%20With%20Threshold/README_EN.md) + +## 题目描述 + + + +

    n 座城市,编号从 1n 。编号为 xy 的两座城市直接连通的前提是: xy 的公因数中,至少有一个 严格大于 某个阈值 threshold 。更正式地说,如果存在整数 z ,且满足以下所有条件,则编号 xy 的城市之间有一条道路:

    + +
      +
    • x % z == 0
    • +
    • y % z == 0
    • +
    • z > threshold
    • +
    + +

    给你两个整数 nthreshold ,以及一个待查询数组,请你判断每个查询 queries[i] = [ai, bi] 指向的城市 aibi 是否连通(即,它们之间是否存在一条路径)。

    + +

    返回数组 answer ,其中answer.length == queries.length 。如果第 i 个查询中指向的城市 aibi 连通,则 answer[i]true ;如果不连通,则 answer[i]false

    + +

     

    + +

    示例 1:

    + +

    + +

     

    + +
    +输入:n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]
    +输出:[false,false,true]
    +解释:每个数的因数如下:
    +1:   1
    +2:   1, 2
    +3:   1, 3
    +4:   1, 2, 4
    +5:   1, 5
    +6:   1, 2, 3, 6
    +所有大于阈值的的因数已经加粗标识,只有城市 3 和 6 共享公约数 3 ,因此结果是: 
    +[1,4]   1 与 4 不连通
    +[2,5]   2 与 5 不连通
    +[3,6]   3 与 6 连通,存在路径 3--6
    +
    + +

    示例 2:

    + +

    + +

     

    + +
    +输入:n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]
    +输出:[true,true,true,true,true]
    +解释:每个数的因数与上一个例子相同。但是,由于阈值为 0 ,所有的因数都大于阈值。因为所有的数字共享公因数 1 ,所以所有的城市都互相连通。
    +
    + +

    示例 3:

    + +

    + +

     

    + +
    +输入:n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]
    +输出:[false,false,false,false,false]
    +解释:只有城市 2 和 4 共享的公约数 2 严格大于阈值 1 ,所以只有这两座城市是连通的。
    +注意,同一对节点 [x, y] 可以有多个查询,并且查询 [x,y] 等同于查询 [y,x] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 104
    • +
    • 0 <= threshold <= n
    • +
    • 1 <= queries.length <= 105
    • +
    • queries[i].length == 2
    • +
    • 1 <= ai, bi <= cities
    • +
    • ai != bi
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1628.leetcode1628 Design an Expression Tree With Evaluate Function-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1628.leetcode1628 Design an Expression Tree With Evaluate Function-zh.md" new file mode 100644 index 00000000..340cd4ee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1628.leetcode1628 Design an Expression Tree With Evaluate Function-zh.md" @@ -0,0 +1,96 @@ +# [1628. 设计带解析函数的表达式树](https://leetcode-cn.com/problems/design-an-expression-tree-with-evaluate-function) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1628.Design%20an%20Expression%20Tree%20With%20Evaluate%20Function/README_EN.md) + +## 题目描述 + + + +

    给定一个算术表达式的后缀表示法的标记(token) postfix ,构造并返回该表达式对应的二叉表达式树。

    + +

    后缀表示法是一种将操作数写在运算符之前的表示法。例如,表达式 4*(5-(2+7)) 的后缀表示法表示为数组 postfix = ["4","5","7","2","+","-","*"] 。

    + +

    抽象类 Node 需要用于实现二叉表达式树。我们将通过 evaluate 函数来测试返回的树是否能够解析树中的值。你不可以移除 Node 类,但你可以按需修改此类,也可以定义其他类来实现它。

    + +

    二叉表达式树是一种表达算术表达式的二叉树。二叉表达式树中的每一个节点都有零个或两个子节点。 叶节点(有 0 个子节点的节点)表示操作数,非叶节点(有 2 个子节点的节点)表示运算符: '+' (加)、 '-' (减)、 '*' (乘)和 '/' (除)。

    + +

    我们保证任何子树对应值的绝对值不超过 109 ,且所有操作都是有效的(即没有除以零的操作)

    + +

    进阶: 你可以将表达式树设计得更模块化吗?例如,你的设计能够不修改现有的 evaluate 的实现就能支持更多的操作符吗?

    + +

     

    + +

    示例 1:

    + +

    + +
    输入: s = ["3","4","+","2","*","7","/"]
    +输出: 2
    +解释: 此表达式可解析为上述二叉树,其对应表达式为 ((3+4)*2)/7) = 14/7 = 2.
    +
    + +

    示例 2:

    + +

    + +
    输入: s = ["4","5","7","2","+","-","*"]
    +输出: -16
    +解释: 此表达式可解析为上述二叉树,其对应表达式为 4*(5-(2+7)) = 4*(-4) = -16.
    +
    + +

    示例 3:

    + +
    输入: s = ["4","2","+","3","5","1","-","*","+"]
    +输出: 18
    +
    + +

    示例 4:

    + +
    输入: s = ["100","200","+","2","/","5","*","7","+"]
    +输出: 757
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length < 100
    • +
    • s.length 是奇数。
    • +
    • s 包含数字和字符 '+' 、 '-' 、 '*' 以及 '/' 。
    • +
    • 如果 s[i] 是数,则对应的整数不超过 105 。
    • +
    • s 保证是一个有效的表达式。
    • +
    • 结果值和所有过程值的绝对值均不超过 109 。
    • +
    • 保证表达式不包含除以零的操作。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1629.leetcode1629 Slowest Key-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1629.leetcode1629 Slowest Key-zh.md" new file mode 100644 index 00000000..0c244c99 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1629.leetcode1629 Slowest Key-zh.md" @@ -0,0 +1,90 @@ +# [1629. 按键持续时间最长的键](https://leetcode-cn.com/problems/slowest-key) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1629.Slowest%20Key/README_EN.md) + +## 题目描述 + + + +

    LeetCode 设计了一款新式键盘,正在测试其可用性。测试人员将会点击一系列键(总计 n 个),每次一个。

    + +

    给你一个长度为 n 的字符串 keysPressed ,其中 keysPressed[i] 表示测试序列中第 i 个被按下的键。releaseTimes 是一个升序排列的列表,其中 releaseTimes[i] 表示松开第 i 个键的时间。字符串和数组的 下标都从 0 开始 。第 0 个键在时间为 0 时被按下,接下来每个键都 恰好 在前一个键松开时被按下。

    + +

    测试人员想要找出按键 持续时间最长 的键。第 i 次按键的持续时间为 releaseTimes[i] - releaseTimes[i - 1] ,第 0 次按键的持续时间为 releaseTimes[0]

    + +

    注意,测试期间,同一个键可以在不同时刻被多次按下,而每次的持续时间都可能不同。

    + +

    请返回按键 持续时间最长 的键,如果有多个这样的键,则返回 按字母顺序排列最大 的那个键。

    + +

     

    + +

    示例 1:

    + +
    +输入:releaseTimes = [9,29,49,50], keysPressed = "cbcd"
    +输出:"c"
    +解释:按键顺序和持续时间如下:
    +按下 'c' ,持续时间 9(时间 0 按下,时间 9 松开)
    +按下 'b' ,持续时间 29 - 9 = 20(松开上一个键的时间 9 按下,时间 29 松开)
    +按下 'c' ,持续时间 49 - 29 = 20(松开上一个键的时间 29 按下,时间 49 松开)
    +按下 'd' ,持续时间 50 - 49 = 1(松开上一个键的时间 49 按下,时间 50 松开)
    +按键持续时间最长的键是 'b' 和 'c'(第二次按下时),持续时间都是 20
    +'c' 按字母顺序排列比 'b' 大,所以答案是 'c'
    +
    + +

    示例 2:

    + +
    +输入:releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
    +输出:"a"
    +解释:按键顺序和持续时间如下:
    +按下 's' ,持续时间 12
    +按下 'p' ,持续时间 23 - 12 = 11
    +按下 'u' ,持续时间 36 - 23 = 13
    +按下 'd' ,持续时间 46 - 36 = 10
    +按下 'a' ,持续时间 62 - 46 = 16
    +按键持续时间最长的键是 'a' ,持续时间 16
    + +

     

    + +

    提示:

    + +
      +
    • releaseTimes.length == n
    • +
    • keysPressed.length == n
    • +
    • 2 <= n <= 1000
    • +
    • 1 <= releaseTimes[i] <= 109
    • +
    • releaseTimes[i] < releaseTimes[i+1]
    • +
    • keysPressed 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1630.leetcode1630 Arithmetic Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1630.leetcode1630 Arithmetic Subarrays-zh.md" new file mode 100644 index 00000000..63bbe916 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1630.leetcode1630 Arithmetic Subarrays-zh.md" @@ -0,0 +1,85 @@ +# [1630. 等差子数组](https://leetcode-cn.com/problems/arithmetic-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1630.Arithmetic%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    如果一个数列由至少两个元素组成,且每两个连续元素之间的差值都相同,那么这个序列就是 等差数列 。更正式地,数列 s 是等差数列,只需要满足:对于每个有效的 is[i+1] - s[i] == s[1] - s[0] 都成立。

    + +

    例如,下面这些都是 等差数列

    + +
    1, 3, 5, 7, 9
    +7, 7, 7, 7
    +3, -1, -5, -9
    + +

    下面的数列 不是等差数列

    + +
    1, 1, 2, 5, 7
    + +

    给你一个由 n 个整数组成的数组 nums,和两个由 m 个整数组成的数组 lr,后两个数组表示 m 组范围查询,其中第 i 个查询对应范围 [l[i], r[i]] 。所有数组的下标都是 从 0 开始 的。

    + +

    返回 boolean 元素构成的答案列表 answer 。如果子数组 nums[l[i]], nums[l[i]+1], ... , nums[r[i]] 可以 重新排列 形成 等差数列answer[i] 的值就是 true;否则answer[i] 的值就是 false

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
    +输出:[true,false,true]
    +解释:
    +第 0 个查询,对应子数组 [4,6,5] 。可以重新排列为等差数列 [6,5,4] 。
    +第 1 个查询,对应子数组 [4,6,5,9] 。无法重新排列形成等差数列。
    +第 2 个查询,对应子数组 [5,9,3,7] 。可以重新排列为等差数列 [3,5,7,9] 。
    + +

    示例 2:

    + +
    输入:nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
    +输出:[false,true,false,false,true,true]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • m == l.length
    • +
    • m == r.length
    • +
    • 2 <= n <= 500
    • +
    • 1 <= m <= 500
    • +
    • 0 <= l[i] < r[i] < n
    • +
    • -105 <= nums[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1631.leetcode1631 Path With Minimum Effort-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1631.leetcode1631 Path With Minimum Effort-zh.md" new file mode 100644 index 00000000..8b655635 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1631.leetcode1631 Path With Minimum Effort-zh.md" @@ -0,0 +1,86 @@ +# [1631. 最小体力消耗路径](https://leetcode-cn.com/problems/path-with-minimum-effort) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1631.Path%20With%20Minimum%20Effort/README_EN.md) + +## 题目描述 + + + +

    你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往  四个方向之一移动,你想要找到耗费 体力 最小的一条路径。

    + +

    一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。

    + +

    请你返回从左上角走到右下角的最小 体力消耗值 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:heights = [[1,2,2],[3,8,2],[5,3,5]]
    +输出:2
    +解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。
    +这条路径比路径 [1,2,2,2,5] 更优,因为另一条路径差值最大值为 3 。
    +
    + +

    示例 2:

    + +

    + +
    +输入:heights = [[1,2,3],[3,8,4],[5,3,5]]
    +输出:1
    +解释:路径 [1,2,3,4,5] 的相邻格子差值绝对值最大为 1 ,比路径 [1,3,5,3,5] 更优。
    +
    + +

    示例 3:

    + +
    +输入:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
    +输出:0
    +解释:上图所示路径不需要消耗任何体力。
    +
    + +

     

    + +

    提示:

    + +
      +
    • rows == heights.length
    • +
    • columns == heights[i].length
    • +
    • 1 <= rows, columns <= 100
    • +
    • 1 <= heights[i][j] <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1632.leetcode1632 Rank Transform of a Matrix-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1632.leetcode1632 Rank Transform of a Matrix-zh.md" new file mode 100644 index 00000000..075eca0c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1632.leetcode1632 Rank Transform of a Matrix-zh.md" @@ -0,0 +1,102 @@ +# [1632. 矩阵转换后的秩](https://leetcode-cn.com/problems/rank-transform-of-a-matrix) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1632.Rank%20Transform%20of%20a%20Matrix/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的矩阵 matrix ,请你返回一个新的矩阵 answer ,其中 answer[row][col] 是 matrix[row][col] 的秩。

    + +

    每个元素的  是一个整数,表示这个元素相对于其他元素的大小关系,它按照如下规则计算:

    + +
      +
    • 秩是从 1 开始的一个整数。
    • +
    • 如果两个元素 p 和 q 在 同一行 或者 同一列 ,那么: +
        +
      • 如果 p < q ,那么 rank(p) < rank(q)
      • +
      • 如果 p == q ,那么 rank(p) == rank(q)
      • +
      • 如果 p > q ,那么 rank(p) > rank(q)
      • +
      +
    • +
    •  需要越  越好。
    • +
    + +

    题目保证按照上面规则 answer 数组是唯一的。

    + +

     

    + +

    示例 1:

    + +
    +输入:matrix = [[1,2],[3,4]]
    +输出:[[1,2],[2,3]]
    +解释:
    +matrix[0][0] 的秩为 1 ,因为它是所在行和列的最小整数。
    +matrix[0][1] 的秩为 2 ,因为 matrix[0][1] > matrix[0][0] 且 matrix[0][0] 的秩为 1 。
    +matrix[1][0] 的秩为 2 ,因为 matrix[1][0] > matrix[0][0] 且 matrix[0][0] 的秩为 1 。
    +matrix[1][1] 的秩为 3 ,因为 matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0] 且 matrix[0][1] 和 matrix[1][0] 的秩都为 2 。
    +
    + +

    示例 2:

    + +
    +输入:matrix = [[7,7],[7,7]]
    +输出:[[1,1],[1,1]]
    +
    + +

    示例 3:

    + +
    +输入:matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
    +输出:[[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
    +
    + +

    示例 4:

    + +
    +输入:matrix = [[7,3,6],[1,4,5],[9,8,2]]
    +输出:[[5,1,4],[1,2,3],[6,3,1]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • -109 <= matrix[row][col] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1633.leetcode1633 Percentage of Users Attended a Contest-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1633.leetcode1633 Percentage of Users Attended a Contest-zh.md" new file mode 100644 index 00000000..3f9316ac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1633.leetcode1633 Percentage of Users Attended a Contest-zh.md" @@ -0,0 +1,98 @@ +# [1633. 各赛事的用户注册率](https://leetcode-cn.com/problems/percentage-of-users-attended-a-contest) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1633.Percentage%20of%20Users%20Attended%20a%20Contest/README_EN.md) + +## 题目描述 + + + +

    用户表: Users

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| user_name   | varchar |
    ++-------------+---------+
    +user_id 是该表的主键。
    +该表中的每行包括用户 ID 和用户名。
    + +

     

    + +

    注册表: Register

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| contest_id  | int     |
    +| user_id     | int     |
    ++-------------+---------+
    +(contest_id, user_id) 是该表的主键。
    +该表中的每行包含用户的 ID 和他们注册的赛事。
    + +

     

    + +

    写一条 SQL 语句,查询各赛事的用户注册百分率,保留两位小数。

    + +

    返回的结果表按 percentage 的降序排序,若相同则按 contest_id 的升序排序。

    + +

    查询结果如下示例所示:

    + +

     

    + +
    Users 表:
    ++---------+-----------+
    +| user_id | user_name |
    ++---------+-----------+
    +| 6       | Alice     |
    +| 2       | Bob       |
    +| 7       | Alex      |
    ++---------+-----------+
    +
    +Register 表:
    ++------------+---------+
    +| contest_id | user_id |
    ++------------+---------+
    +| 215        | 6       |
    +| 209        | 2       |
    +| 208        | 2       |
    +| 210        | 6       |
    +| 208        | 6       |
    +| 209        | 7       |
    +| 209        | 6       |
    +| 215        | 7       |
    +| 208        | 7       |
    +| 210        | 2       |
    +| 207        | 2       |
    +| 210        | 7       |
    ++------------+---------+
    +
    +结果表:
    ++------------+------------+
    +| contest_id | percentage |
    ++------------+------------+
    +| 208        | 100.0      |
    +| 209        | 100.0      |
    +| 210        | 100.0      |
    +| 215        | 66.67      |
    +| 207        | 33.33      |
    ++------------+------------+
    +所有用户都注册了 208、209 和 210 赛事,因此这些赛事的注册率为 100% ,我们按 contest_id 的降序排序加入结果表中。
    +Alice 和 Alex 注册了 215 赛事,注册率为 ((2/3) * 100) = 66.67%
    +Bob 注册了 207 赛事,注册率为 ((1/3) * 100) = 33.33%
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1634.leetcode1634 Add Two Polynomials Represented as Linked Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1634.leetcode1634 Add Two Polynomials Represented as Linked Lists-zh.md" new file mode 100644 index 00000000..ca2dec52 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1634.leetcode1634 Add Two Polynomials Represented as Linked Lists-zh.md" @@ -0,0 +1,167 @@ +# [1634. 求两个多项式链表的和](https://leetcode-cn.com/problems/add-two-polynomials-represented-as-linked-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1634.Add%20Two%20Polynomials%20Represented%20as%20Linked%20Lists/README_EN.md) + +## 题目描述 + + + +

    多项式链表是一种特殊形式的链表,每个节点表示多项式的一项。

    + +

    每个节点有三个属性:

    + +
      +
    • coefficient:该项的系数。项 9x4 的系数是 9 。
    • +
    • power:该项的指数。项 9x4 的指数是 4 。
    • +
    • next:指向下一个节点的指针(引用),如果当前节点为链表的最后一个节点则为 null
    • +
    + +

    例如,多项式 5x3 + 4x - 7 可以表示成如下图所示的多项式链表:

    + +

    + +

    多项式链表必须是标准形式的,即多项式必须 严格 按指数 power 的递减顺序排列(即降幂排列)。另外,系数 coefficient 为 0 的项需要省略。

    + +

    给定两个多项式链表的头节点 poly1 和 poly2,返回它们的和的头节点。

    + +

    PolyNode 格式:

    + +

    输入/输出格式表示为 n 个节点的列表,其中每个节点表示为 [coefficient, power] 。例如,多项式 5x3 + 4x - 7 表示为: [[5,3],[4,1],[-7,0]] 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:poly1 = [[1,1]], poly2 = [[1,0]]
    +输出:[[1,1],[1,0]]
    +解释:poly1 = x. poly2 = 1. 和为 x + 1.
    +
    + +

    示例 2:

    + +
    +输入:poly1 = [[2,2],[4,1],[3,0]], poly2 = [[3,2],[-4,1],[-1,0]]
    +输出:[[5,2],[2,0]]
    +解释:poly1 = 2x2 + 4x + 3. poly2 = 3x2 - 4x - 1. 和为 5x2 + 2. 注意,我们省略 "0x" 项。
    +
    + +

    示例 3:

    + +
    +输入:poly1 = [[1,2]], poly2 = [[-1,2]]
    +输出:[]
    +解释:和为 0。我们返回空链表。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 104
    • +
    • -109 <= PolyNode.coefficient <= 109
    • +
    • PolyNode.coefficient != 0
    • +
    • 0 <= PolyNode.power <= 109
    • +
    • PolyNode.power > PolyNode.next.power
    • +
    + +## 解法 + + + +遍历两多项式链表,比较节点间的 power 值,进行节点串联。若两节点 coefficient 值相加和为 0,不串联此合并的节点。 + + + +### **Python3** + + + +```python +# Definition for polynomial singly-linked list. +# class PolyNode: +# def __init__(self, x=0, y=0, next=None): +# self.coefficient = x +# self.power = y +# self.next = next + +class Solution: + def addPoly(self, poly1: 'PolyNode', poly2: 'PolyNode') -> 'PolyNode': + dummy = PolyNode() + cur = dummy + while poly1 or poly2: + if poly1 is None or (poly2 and poly2.power > poly1.power): + cur.next = poly2 + cur = cur.next + poly2 = poly2.next + elif poly2 is None or (poly1 and poly1.power > poly2.power): + cur.next = poly1 + cur = cur.next + poly1 = poly1.next + else: + val = poly1.coefficient + poly2.coefficient + if val != 0: + cur.next = PolyNode(x=val, y=poly1.power) + cur = cur.next + poly1 = poly1.next + poly2 = poly2.next + cur.next = None + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for polynomial singly-linked list. + * class PolyNode { + * int coefficient, power; + * PolyNode next = null; + + * PolyNode() {} + * PolyNode(int x, int y) { this.coefficient = x; this.power = y; } + * PolyNode(int x, int y, PolyNode next) { this.coefficient = x; this.power = y; this.next = next; } + * } + */ + +class Solution { + public PolyNode addPoly(PolyNode poly1, PolyNode poly2) { + PolyNode dummy = new PolyNode(); + PolyNode cur = dummy; + while (poly1 != null || poly2 != null) { + if (poly1 == null || (poly2 != null && poly2.power > poly1.power)) { + cur.next = poly2; + cur = cur.next; + poly2 = poly2.next; + } else if (poly2 == null || (poly1 != null && poly1.power > poly2.power)) { + cur.next = poly1; + cur = cur.next; + poly1 = poly1.next; + } else { + int val = poly1.coefficient + poly2.coefficient; + if (val != 0) { + cur.next = new PolyNode(val, poly1.power); + cur = cur.next; + } + poly1 = poly1.next; + poly2 = poly2.next; + } + } + cur.next = null; + return dummy.next; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1635.leetcode1635 Hopper Company Queries I-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1635.leetcode1635 Hopper Company Queries I-zh.md" new file mode 100644 index 00000000..bd96b3a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1635.leetcode1635 Hopper Company Queries I-zh.md" @@ -0,0 +1,163 @@ +# [1635. Hopper 公司查询 I](https://leetcode-cn.com/problems/hopper-company-queries-i) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1635.Hopper%20Company%20Queries%20I/README_EN.md) + +## 题目描述 + + + +

    表: Drivers

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| driver_id   | int     |
    +| join_date   | date    |
    ++-------------+---------+
    +driver_id是该表的主键。
    +该表的每一行均包含驾驶员的ID以及他们加入Hopper公司的日期。
    +
    + +

     

    + +

    表: Rides

    + +
    +--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| ride_id      | int     |
    +| user_id      | int     |
    +| requested_at | date    |
    ++--------------+---------+
    +ride_id是该表的主键。
    +该表的每一行均包含行程ID(ride_id),用户ID(user_id)以及该行程的日期(requested_at)。
    +该表中可能有一些不被接受的乘车请求。
    +
    + +

     

    + +

    表: AcceptedRides

    + +
    +---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ride_id       | int     |
    +| driver_id     | int     |
    +| ride_distance | int     |
    +| ride_duration | int     |
    ++---------------+---------+
    +ride_id是该表的主键。
    +该表的每一行都包含已接受的行程信息。
    +表中的行程信息都在“Rides”表中存在。
    +
    + +

     

    + +

    编写SQL查询以报告2020年每个月的以下统计信息:

    + +
      +
    • 截至某月底,当前在Hopper公司工作的驾驶员数量(active_drivers)。
    • +
    • 该月接受的乘车次数(accepted_rides)。
    • +
    + +

    返回按month 升序排列的结果表,其中month 是月份的数字(一月是1,二月是2,依此类推)。

    + +

    查询结果格式如下例所示。

    + +
    表 Drivers:
    ++-----------+------------+
    +| driver_id | join_date  |
    ++-----------+------------+
    +| 10        | 2019-12-10 |
    +| 8         | 2020-1-13  |
    +| 5         | 2020-2-16  |
    +| 7         | 2020-3-8   |
    +| 4         | 2020-5-17  |
    +| 1         | 2020-10-24 |
    +| 6         | 2021-1-5   |
    ++-----------+------------+
    +
    +表 Rides:
    ++---------+---------+--------------+
    +| ride_id | user_id | requested_at |
    ++---------+---------+--------------+
    +| 6       | 75      | 2019-12-9    |
    +| 1       | 54      | 2020-2-9     |
    +| 10      | 63      | 2020-3-4     |
    +| 19      | 39      | 2020-4-6     |
    +| 3       | 41      | 2020-6-3     |
    +| 13      | 52      | 2020-6-22    |
    +| 7       | 69      | 2020-7-16    |
    +| 17      | 70      | 2020-8-25    |
    +| 20      | 81      | 2020-11-2    |
    +| 5       | 57      | 2020-11-9    |
    +| 2       | 42      | 2020-12-9    |
    +| 11      | 68      | 2021-1-11    |
    +| 15      | 32      | 2021-1-17    |
    +| 12      | 11      | 2021-1-19    |
    +| 14      | 18      | 2021-1-27    |
    ++---------+---------+--------------+
    +
    +表 AcceptedRides:
    ++---------+-----------+---------------+---------------+
    +| ride_id | driver_id | ride_distance | ride_duration |
    ++---------+-----------+---------------+---------------+
    +| 10      | 10        | 63            | 38            |
    +| 13      | 10        | 73            | 96            |
    +| 7       | 8         | 100           | 28            |
    +| 17      | 7         | 119           | 68            |
    +| 20      | 1         | 121           | 92            |
    +| 5       | 7         | 42            | 101           |
    +| 2       | 4         | 6             | 38            |
    +| 11      | 8         | 37            | 43            |
    +| 15      | 8         | 108           | 82            |
    +| 12      | 8         | 38            | 34            |
    +| 14      | 1         | 90            | 74            |
    ++---------+-----------+---------------+---------------+
    +
    +结果表:
    ++-------+----------------+----------------+
    +| month | active_drivers | accepted_rides |
    ++-------+----------------+----------------+
    +| 1     | 2              | 0              |
    +| 2     | 3              | 0              |
    +| 3     | 4              | 1              |
    +| 4     | 4              | 0              |
    +| 5     | 5              | 0              |
    +| 6     | 5              | 1              |
    +| 7     | 5              | 1              |
    +| 8     | 5              | 1              |
    +| 9     | 5              | 0              |
    +| 10    | 6              | 0              |
    +| 11    | 6              | 2              |
    +| 12    | 6              | 1              |
    ++-------+----------------+----------------+
    +
    +截至1月底->两个活跃的驾驶员(10,8),没有被接受的行程。
    +截至2月底->三个活跃的驾驶员(10,8,5),没有被接受的行程。
    +截至3月底->四个活跃的驾驶员(10,8,5,7),一个被接受的行程(10)。
    +截至4月底->四个活跃的驾驶员(10,8,5,7),没有被接受的行程。
    +截至5月底->五个活跃的驾驶员(10,8,5,7,4),没有被接受的行程。
    +截至6月底->五个活跃的驾驶员(10,8,5,7,4),一个被接受的行程(13)。
    +截至7月底->五个活跃的驾驶员(10,8,5,7,4),一个被接受的行程(7)。
    +截至8月底->五个活跃的驾驶员(10,8,5,7,4),一位接受的行程(17)。
    +截至9月底->五个活跃的驾驶员(10,8,5,7,4),没有被接受的行程。
    +截至10月底->六个活跃的驾驶员(10,8,5,7,4,1),没有被接受的行程。
    +截至11月底->六个活跃的驾驶员(10,8,5,7,4,1),两个被接受的行程(20,5)。
    +截至12月底->六个活跃的驾驶员(10,8,5,7,4,1),一个被接受的行程(2)。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1636.leetcode1636 Sort Array by Increasing Frequency-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1636.leetcode1636 Sort Array by Increasing Frequency-zh.md" new file mode 100644 index 00000000..8fd77e57 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1636.leetcode1636 Sort Array by Increasing Frequency-zh.md" @@ -0,0 +1,72 @@ +# [1636. 按照频率将数组升序排序](https://leetcode-cn.com/problems/sort-array-by-increasing-frequency) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1636.Sort%20Array%20by%20Increasing%20Frequency/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 

    + +

    请你返回排序后的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,1,2,2,2,3]
    +输出:[3,1,1,2,2,2]
    +解释:'3' 频率为 1,'1' 频率为 2,'2' 频率为 3 。
    +
    + +

    示例 2:

    + +
    输入:nums = [2,3,1,3,2]
    +输出:[1,3,3,2,2]
    +解释:'2' 和 '3' 频率都为 2 ,所以它们之间按照数值本身降序排序。
    +
    + +

    示例 3:

    + +
    输入:nums = [-1,1,-6,4,5,-6,1,4,1]
    +输出:[5,-1,4,4,-6,-6,1,1,1]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • -100 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1637.leetcode1637 Widest Vertical Area Between Two Points Containing No Points-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1637.leetcode1637 Widest Vertical Area Between Two Points Containing No Points-zh.md" new file mode 100644 index 00000000..c221db47 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1637.leetcode1637 Widest Vertical Area Between Two Points Containing No Points-zh.md" @@ -0,0 +1,72 @@ +# [1637. 两点之间不包含任何点的最宽垂直面积](https://leetcode-cn.com/problems/widest-vertical-area-between-two-points-containing-no-points) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1637.Widest%20Vertical%20Area%20Between%20Two%20Points%20Containing%20No%20Points/README_EN.md) + +## 题目描述 + + + +

    给你 n 个二维平面上的点 points ,其中 points[i] = [xi, yi] ,请你返回两点之间内部不包含任何点的 最宽垂直面积 的宽度。

    + +

    垂直面积 的定义是固定宽度,而 y 轴上无限延伸的一块区域(也就是高度为无穷大)。 最宽垂直面积 为宽度最大的一个垂直面积。

    + +

    请注意,垂直区域 边上 的点 不在 区域内。

    + +

     

    + +

    示例 1:

    +​ +
    +输入:points = [[8,7],[9,9],[7,4],[9,7]]
    +输出:1
    +解释:红色区域和蓝色区域都是最优区域。
    +
    + +

    示例 2:

    + +
    +输入:points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == points.length
    • +
    • 2 <= n <= 105
    • +
    • points[i].length == 2
    • +
    • 0 <= xi, yi <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1638.leetcode1638 Count Substrings That Differ by One Character-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1638.leetcode1638 Count Substrings That Differ by One Character-zh.md" new file mode 100644 index 00000000..ba4de2e4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1638.leetcode1638 Count Substrings That Differ by One Character-zh.md" @@ -0,0 +1,96 @@ +# [1638. 统计只差一个字符的子串数目](https://leetcode-cn.com/problems/count-substrings-that-differ-by-one-character) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1638.Count%20Substrings%20That%20Differ%20by%20One%20Character/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 s 和 t ,请你找出 s 中的非空子串的数目,这些子串满足替换 一个不同字符 以后,是 t 串的子串。换言之,请你找到 s 和 t 串中 恰好 只有一个字符不同的子字符串对的数目。

    + +

    比方说, "computer" 和 "computation" 加粗部分只有一个字符不同: 'e'/'a' ,所以这一对子字符串会给答案加 1 。

    + +

    请你返回满足上述条件的不同子字符串对数目。

    + +

    一个 子字符串 是一个字符串中连续的字符。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aba", t = "baba"
    +输出:6
    +解释:以下为只相差 1 个字符的 s 和 t 串的子字符串对:
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +("aba", "baba")
    +加粗部分分别表示 s 和 t 串选出来的子字符串。
    +
    +示例 2: + +
    +输入:s = "ab", t = "bb"
    +输出:3
    +解释:以下为只相差 1 个字符的 s 和 t 串的子字符串对:
    +("ab", "bb")
    +("ab", "bb")
    +("ab", "bb")
    +加粗部分分别表示 s 和 t 串选出来的子字符串。
    +
    +示例 3: + +
    +输入:s = "a", t = "a"
    +输出:0
    +
    + +

    示例 4:

    + +
    +输入:s = "abe", t = "bbc"
    +输出:10
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length, t.length <= 100
    • +
    • s 和 t 都只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1639.leetcode1639 Number of Ways to Form a Target String Given a Dictionary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1639.leetcode1639 Number of Ways to Form a Target String Given a Dictionary-zh.md" new file mode 100644 index 00000000..d0bcdc99 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1639.leetcode1639 Number of Ways to Form a Target String Given a Dictionary-zh.md" @@ -0,0 +1,109 @@ +# [1639. 通过给定词典构造目标字符串的方案数](https://leetcode-cn.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1639.Number%20of%20Ways%20to%20Form%20a%20Target%20String%20Given%20a%20Dictionary/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串列表 words 和一个目标字符串 targetwords 中所有字符串都 长度相同  。

    + +

    你的目标是使用给定的 words 字符串列表按照下述规则构造 target :

    + +
      +
    • 从左到右依次构造 target 的每一个字符。
    • +
    • 为了得到 target 第 i 个字符(下标从 0 开始),当 target[i] = words[j][k] 时,你可以使用 words 列表中第 j 个字符串的第 k 个字符。
    • +
    • 一旦你使用了 words 中第 j 个字符串的第 k 个字符,你不能再使用 words 字符串列表中任意单词的第 x 个字符(x <= k)。也就是说,所有单词下标小于等于 k 的字符都不能再被使用。
    • +
    • 请你重复此过程直到得到目标字符串 target 。
    • +
    + +

    请注意, 在构造目标字符串的过程中,你可以按照上述规定使用 words 列表中 同一个字符串 的 多个字符 。

    + +

    请你返回使用 words 构造 target 的方案数。由于答案可能会很大,请对 109 + 7 取余 后返回。

    + +

    (译者注:此题目求的是有多少个不同的 k 序列,详情请见示例。)

    + +

     

    + +

    示例 1:

    + +
    +输入:words = ["acca","bbbb","caca"], target = "aba"
    +输出:6
    +解释:总共有 6 种方法构造目标串。
    +"aba" -> 下标为 0 ("acca"),下标为 1 ("bbbb"),下标为 3 ("caca")
    +"aba" -> 下标为 0 ("acca"),下标为 2 ("bbbb"),下标为 3 ("caca")
    +"aba" -> 下标为 0 ("acca"),下标为 1 ("bbbb"),下标为 3 ("acca")
    +"aba" -> 下标为 0 ("acca"),下标为 2 ("bbbb"),下标为 3 ("acca")
    +"aba" -> 下标为 1 ("caca"),下标为 2 ("bbbb"),下标为 3 ("acca")
    +"aba" -> 下标为 1 ("caca"),下标为 2 ("bbbb"),下标为 3 ("caca")
    +
    + +

    示例 2:

    + +
    +输入:words = ["abba","baab"], target = "bab"
    +输出:4
    +解释:总共有 4 种不同形成 target 的方法。
    +"bab" -> 下标为 0 ("baab"),下标为 1 ("baab"),下标为 2 ("abba")
    +"bab" -> 下标为 0 ("baab"),下标为 1 ("baab"),下标为 3 ("baab")
    +"bab" -> 下标为 0 ("baab"),下标为 2 ("baab"),下标为 3 ("baab")
    +"bab" -> 下标为 1 ("abba"),下标为 2 ("baab"),下标为 3 ("baab")
    +
    + +

    示例 3:

    + +
    +输入:words = ["abcd"], target = "abcd"
    +输出:1
    +
    + +

    示例 4:

    + +
    +输入:words = ["abab","baba","abba","baab"], target = "abba"
    +输出:16
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 1000
    • +
    • 1 <= words[i].length <= 1000
    • +
    • words 中所有单词长度相同。
    • +
    • 1 <= target.length <= 1000
    • +
    • words[i] 和 target 都仅包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1640.leetcode1640 Check Array Formation Through Concatenation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1640.leetcode1640 Check Array Formation Through Concatenation-zh.md" new file mode 100644 index 00000000..8c66fba5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1640.leetcode1640 Check Array Formation Through Concatenation-zh.md" @@ -0,0 +1,154 @@ +# [1640. 能否连接形成数组](https://leetcode-cn.com/problems/check-array-formation-through-concatenation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1640.Check%20Array%20Formation%20Through%20Concatenation/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 arr ,数组中的每个整数 互不相同 。另有一个由整数数组构成的数组 pieces,其中的整数也 互不相同 。请你以 任意顺序 连接 pieces 中的数组以形成 arr 。但是,不允许 对每个数组 pieces[i] 中的整数重新排序。

    + +

    如果可以连接 pieces 中的数组形成 arr ,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [85], pieces = [[85]]
    +输出:true
    +
    + +

    示例 2:

    + +
    +输入:arr = [15,88], pieces = [[88],[15]]
    +输出:true
    +解释:依次连接 [15][88]
    +
    + +

    示例 3:

    + +
    +输入:arr = [49,18,16], pieces = [[16,18,49]]
    +输出:false
    +解释:即便数字相符,也不能重新排列 pieces[0]
    +
    + +

    示例 4:

    + +
    +输入:arr = [91,4,64,78], pieces = [[78],[4,64],[91]]
    +输出:true
    +解释:依次连接 [91][4,64][78]
    + +

    示例 5:

    + +
    +输入:arr = [1,3,5,7], pieces = [[2,4,6,8]]
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= pieces.length <= arr.length <= 100
    • +
    • sum(pieces[i].length) == arr.length
    • +
    • 1 <= pieces[i].length <= arr.length
    • +
    • 1 <= arr[i], pieces[i][j] <= 100
    • +
    • arr 中的整数 互不相同
    • +
    • pieces 中的整数 互不相同(也就是说,如果将 pieces 扁平化成一维数组,数组中的所有整数互不相同)
    • +
    + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +class Solution: + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: + mapper = {piece[0]: piece for piece in pieces} + i, n = 0, len(arr) + while i < n: + if arr[i] not in mapper: + return False + vals = mapper[arr[i]] + for val in vals: + if arr[i] != val: + return False + i += 1 + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + Map map = new HashMap<>(); + for (int[] piece : pieces) { + map.put(piece[0], piece); + } + for (int i = 0; i < arr.length;) { + int[] vals = map.get(arr[i]); + if (vals == null) { + return false; + } + for (int val : vals) { + if (arr[i] != val) { + return false; + } + ++i; + } + } + return true; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} arr + * @param {number[][]} pieces + * @return {boolean} + */ +var canFormArray = function(arr, pieces) { + let mapper = new Map(); + for (let i = 0; i < pieces.length; i++) { + mapper.set(pieces[i][0], pieces[i]); + } + let i = 0, n = arr.length; + while (i < n) { + let cur = arr[i]; + let nums = mapper.get(cur); + if (nums == undefined) return false; + for (let num of nums) { + if (arr[i] != num) return false; + i++; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1641.leetcode1641 Count Sorted Vowel Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1641.leetcode1641 Count Sorted Vowel Strings-zh.md" new file mode 100644 index 00000000..d1940e84 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1641.leetcode1641 Count Sorted Vowel Strings-zh.md" @@ -0,0 +1,77 @@ +# [1641. 统计字典序元音字符串的数目](https://leetcode-cn.com/problems/count-sorted-vowel-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1641.Count%20Sorted%20Vowel%20Strings/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n,请返回长度为 n 、仅由元音 (a, e, i, o, u) 组成且按 字典序排列 的字符串数量。

    + +

    字符串 s字典序排列 需要满足:对于所有有效的 is[i] 在字母表中的位置总是与 s[i+1] 相同或在 s[i+1] 之前。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 1
    +输出:5
    +解释:仅由元音组成的 5 个字典序字符串为 ["a","e","i","o","u"]
    +
    + +

    示例 2:

    + +
    +输入:n = 2
    +输出:15
    +解释:仅由元音组成的 15 个字典序字符串为
    +["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]
    +注意,"ea" 不是符合题意的字符串,因为 'e' 在字母表中的位置比 'a' 靠后
    +
    + +

    示例 3:

    + +
    +输入:n = 33
    +输出:66045
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 50 
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1642.leetcode1642 Furthest Building You Can Reach-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1642.leetcode1642 Furthest Building You Can Reach-zh.md" new file mode 100644 index 00000000..5ececc7a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1642.leetcode1642 Furthest Building You Can Reach-zh.md" @@ -0,0 +1,90 @@ +# [1642. 可以到达的最远建筑](https://leetcode-cn.com/problems/furthest-building-you-can-reach) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1642.Furthest%20Building%20You%20Can%20Reach/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 heights ,表示建筑物的高度。另有一些砖块 bricks 和梯子 ladders

    + +

    你从建筑物 0 开始旅程,不断向后面的建筑物移动,期间可能会用到砖块或梯子。

    + +

    当从建筑物 i 移动到建筑物 i+1(下标 从 0 开始 )时:

    + +
      +
    • 如果当前建筑物的高度 大于或等于 下一建筑物的高度,则不需要梯子或砖块
    • +
    • 如果当前建筑的高度 小于 下一个建筑的高度,您可以使用 一架梯子(h[i+1] - h[i]) 个砖块
    • +
    +如果以最佳方式使用给定的梯子和砖块,返回你可以到达的最远建筑物的下标(下标 从 0 开始 )。 + +

     

    + +

    示例 1:

    + +
    +输入:heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
    +输出:4
    +解释:从建筑物 0 出发,你可以按此方案完成旅程:
    +- 不使用砖块或梯子到达建筑物 1 ,因为 4 >= 2
    +- 使用 5 个砖块到达建筑物 2 。你必须使用砖块或梯子,因为 2 < 7
    +- 不使用砖块或梯子到达建筑物 3 ,因为 7 >= 6
    +- 使用唯一的梯子到达建筑物 4 。你必须使用砖块或梯子,因为 6 < 9
    +无法越过建筑物 4 ,因为没有更多砖块或梯子。
    +
    + +

    示例 2:

    + +
    +输入:heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
    +输出:7
    +
    + +

    示例 3:

    + +
    +输入:heights = [14,3,19,3], bricks = 17, ladders = 0
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= heights.length <= 105
    • +
    • 1 <= heights[i] <= 106
    • +
    • 0 <= bricks <= 109
    • +
    • 0 <= ladders <= heights.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1643.leetcode1643 Kth Smallest Instructions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1643.leetcode1643 Kth Smallest Instructions-zh.md" new file mode 100644 index 00000000..79cbf6ee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1643.leetcode1643 Kth Smallest Instructions-zh.md" @@ -0,0 +1,97 @@ +# [1643. 第 K 条最小指令](https://leetcode-cn.com/problems/kth-smallest-instructions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1643.Kth%20Smallest%20Instructions/README_EN.md) + +## 题目描述 + + + +

    Bob 站在单元格 (0, 0) ,想要前往目的地 destination(row, column) 。他只能向 或向 走。你可以为 Bob 提供导航 指令 来帮助他到达目的地 destination

    + +

    指令 用字符串表示,其中每个字符:

    + +
      +
    • 'H' ,意味着水平向右移动
    • +
    • 'V' ,意味着竖直向下移动
    • +
    + +

    能够为 Bob 导航到目的地 destination 的指令可以有多种,例如,如果目的地 destination(2, 3)"HHHVV""HVHVH" 都是有效 指令

    + +
      +
    + +

    然而,Bob 很挑剔。因为他的幸运数字是 k,他想要遵循 按字典序排列后的第 k 条最小指令 的导航前往目的地 destinationk  的编号 从 1 开始

    + +

    给你一个整数数组 destination 和一个整数 k ,请你返回可以为 Bob 提供前往目的地 destination 导航的 按字典序排列后的第 k 条最小指令

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:destination = [2,3], k = 1
    +输出:"HHHVV"
    +解释:能前往 (2, 3) 的所有导航指令 按字典序排列后 如下所示:
    +["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
    +
    + +

    示例 2:

    + +

    + +
    +输入:destination = [2,3], k = 2
    +输出:"HHVHV"
    +
    + +

    示例 3:

    + +

    + +
    +输入:destination = [2,3], k = 3
    +输出:"HHVVH"
    +
    + +

     

    + +

    提示:

    + +
      +
    • destination.length == 2
    • +
    • 1 <= row, column <= 15
    • +
    • 1 <= k <= nCr(row + column, row),其中 nCr(a, b) 表示组合数,即从 a 个物品中选 b 个物品的不同方案数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1644.leetcode1644 Lowest Common Ancestor of a Binary Tree II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1644.leetcode1644 Lowest Common Ancestor of a Binary Tree II-zh.md" new file mode 100644 index 00000000..a6d40ae3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1644.leetcode1644 Lowest Common Ancestor of a Binary Tree II-zh.md" @@ -0,0 +1,78 @@ +# [1644. 二叉树的最近公共祖先 II](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1644.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree%20II/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树的根节点 root,返回给定节点 pq 的最近公共祖先(LCA)节点。如果 pq 之一不存在于该二叉树中,返回 null。树中的每个节点值都是互不相同的。

    + +

    根据维基百科中对最近公共祖先节点的定义:“两个节点 pq 在二叉树 T 中的最近公共祖先节点是后代节点中既包括 p 又包括 q 的最深节点(我们允许一个节点为自身的一个后代节点)”。一个节点 x 的后代节点是节点 x 到某一叶节点间的路径中的节点 y

    + +

     

    + +

    示例 1:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    +输出: 3
    +解释: 节点 5 和 1 的共同祖先节点是 3。
    + +

    示例 2:

    + +

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    +输出: 5
    +解释: 节点 5 和 4 的共同祖先节点是 5。根据共同祖先节点的定义,一个节点可以是自身的后代节点。
    + +

    示例 3:

    + +

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10
    +输出: null
    +解释: 节点 10 不存在于树中,所以返回 null。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点个数的范围是 [1, 104]
    • +
    • -109 <= Node.val <= 109
    • +
    • 所有节点的值 Node.val 是互不相同的。
    • +
    • p != q
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1645.leetcode1645 Hopper Company Queries II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1645.leetcode1645 Hopper Company Queries II-zh.md" new file mode 100644 index 00000000..058a23c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1645.leetcode1645 Hopper Company Queries II-zh.md" @@ -0,0 +1,168 @@ +# [1645. Hopper Company Queries II](https://leetcode-cn.com/problems/hopper-company-queries-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1645.Hopper%20Company%20Queries%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Drivers

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| driver_id   | int     |
    +| join_date   | date    |
    ++-------------+---------+
    +driver_id is the primary key for this table.
    +Each row of this table contains the driver's ID and the date they joined the Hopper company.
    +
    + +

     

    + +

    Table: Rides

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| ride_id      | int     |
    +| user_id      | int     |
    +| requested_at | date    |
    ++--------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
    +There may be some ride requests in this table that were not accepted.
    +
    + +

     

    + +

    Table: AcceptedRides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ride_id       | int     |
    +| driver_id     | int     |
    +| ride_distance | int     |
    +| ride_duration | int     |
    ++---------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains some information about an accepted ride.
    +It is guaranteed that each accepted ride exists in the Rides table.
    +
    + +

     

    + +

    Write an SQL query to report the percentage of working drivers (working_percentage) for each month of 2020 where:

    + +

    Note that if the number of available drivers during a month is zero, we consider the working_percentage to be 0.

    + +

    Return the result table ordered by month in ascending order, where month is the month's number (January is 1, February is 2, etc.). Round working_percentage to the nearest 2 decimal places.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Drivers table:
    ++-----------+------------+
    +| driver_id | join_date  |
    ++-----------+------------+
    +| 10        | 2019-12-10 |
    +| 8         | 2020-1-13  |
    +| 5         | 2020-2-16  |
    +| 7         | 2020-3-8   |
    +| 4         | 2020-5-17  |
    +| 1         | 2020-10-24 |
    +| 6         | 2021-1-5   |
    ++-----------+------------+
    +
    +Rides table:
    ++---------+---------+--------------+
    +| ride_id | user_id | requested_at |
    ++---------+---------+--------------+
    +| 6       | 75      | 2019-12-9    |
    +| 1       | 54      | 2020-2-9     |
    +| 10      | 63      | 2020-3-4     |
    +| 19      | 39      | 2020-4-6     |
    +| 3       | 41      | 2020-6-3     |
    +| 13      | 52      | 2020-6-22    |
    +| 7       | 69      | 2020-7-16    |
    +| 17      | 70      | 2020-8-25    |
    +| 20      | 81      | 2020-11-2    |
    +| 5       | 57      | 2020-11-9    |
    +| 2       | 42      | 2020-12-9    |
    +| 11      | 68      | 2021-1-11    |
    +| 15      | 32      | 2021-1-17    |
    +| 12      | 11      | 2021-1-19    |
    +| 14      | 18      | 2021-1-27    |
    ++---------+---------+--------------+
    +
    +AcceptedRides table:
    ++---------+-----------+---------------+---------------+
    +| ride_id | driver_id | ride_distance | ride_duration |
    ++---------+-----------+---------------+---------------+
    +| 10      | 10        | 63            | 38            |
    +| 13      | 10        | 73            | 96            |
    +| 7       | 8         | 100           | 28            |
    +| 17      | 7         | 119           | 68            |
    +| 20      | 1         | 121           | 92            |
    +| 5       | 7         | 42            | 101           |
    +| 2       | 4         | 6             | 38            |
    +| 11      | 8         | 37            | 43            |
    +| 15      | 8         | 108           | 82            |
    +| 12      | 8         | 38            | 34            |
    +| 14      | 1         | 90            | 74            |
    ++---------+-----------+---------------+---------------+
    +
    +Result table:
    ++-------+--------------------+
    +| month | working_percentage |
    ++-------+--------------------+
    +| 1     | 0.00               |
    +| 2     | 0.00               |
    +| 3     | 25.00              |
    +| 4     | 0.00               |
    +| 5     | 0.00               |
    +| 6     | 20.00              |
    +| 7     | 20.00              |
    +| 8     | 20.00              |
    +| 9     | 0.00               |
    +| 10    | 0.00               |
    +| 11    | 33.33              |
    +| 12    | 16.67              |
    ++-------+--------------------+
    +
    +By the end of January --> two active drivers (10, 8) and no accepted rides. The percentage is 0%.
    +By the end of February --> three active drivers (10, 8, 5) and no accepted rides. The percentage is 0%.
    +By the end of March --> four active drivers (10, 8, 5, 7) and one accepted ride by driver (10). The percentage is (1 / 4) * 100 = 25%.
    +By the end of April --> four active drivers (10, 8, 5, 7) and no accepted rides. The percentage is 0%.
    +By the end of May --> five active drivers (10, 8, 5, 7, 4) and no accepted rides. The percentage is 0%.
    +By the end of June --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (10). The percentage is (1 / 5) * 100 = 20%.
    +By the end of July --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (8). The percentage is (1 / 5) * 100 = 20%.
    +By the end of August --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (7). The percentage is (1 / 5) * 100 = 20%.
    +By the end of Septemeber --> five active drivers (10, 8, 5, 7, 4) and no accepted rides. The percentage is 0%.
    +By the end of October --> six active drivers (10, 8, 5, 7, 4, 1) and no accepted rides. The percentage is 0%.
    +By the end of November --> six active drivers (10, 8, 5, 7, 4, 1) and two accepted rides by two different drivers (1, 7). The percentage is (2 / 6) * 100 = 33.33%.
    +By the end of December --> six active drivers (10, 8, 5, 7, 4, 1) and one accepted ride by driver (4). The percentage is (1 / 6) * 100 = 16.67%.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1646.leetcode1646 Get Maximum in Generated Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1646.leetcode1646 Get Maximum in Generated Array-zh.md" new file mode 100644 index 00000000..7e7d41f6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1646.leetcode1646 Get Maximum in Generated Array-zh.md" @@ -0,0 +1,92 @@ +# [1646. 获取生成数组中的最大值](https://leetcode-cn.com/problems/get-maximum-in-generated-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1646.Get%20Maximum%20in%20Generated%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n 。按下述规则生成一个长度为 n + 1 的数组 nums

    + +
      +
    • nums[0] = 0
    • +
    • nums[1] = 1
    • +
    • 2 <= 2 * i <= n 时,nums[2 * i] = nums[i]
    • +
    • 2 <= 2 * i + 1 <= n 时,nums[2 * i + 1] = nums[i] + nums[i + 1]
    • +
    + +

    返回生成数组 nums 中的 最大 值。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 7
    +输出:3
    +解释:根据规则:
    +  nums[0] = 0
    +  nums[1] = 1
    +  nums[(1 * 2) = 2] = nums[1] = 1
    +  nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
    +  nums[(2 * 2) = 4] = nums[2] = 1
    +  nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
    +  nums[(3 * 2) = 6] = nums[3] = 2
    +  nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
    +因此,nums = [0,1,1,2,1,3,2,3],最大值 3
    +
    + +

    示例 2:

    + +
    +输入:n = 2
    +输出:1
    +解释:根据规则,nums[0]、nums[1] 和 nums[2] 之中的最大值是 1
    +
    + +

    示例 3:

    + +
    +输入:n = 3
    +输出:2
    +解释:根据规则,nums[0]、nums[1]、nums[2] 和 nums[3] 之中的最大值是 2
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= n <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1647.leetcode1647 Minimum Deletions to Make Character Frequencies Unique-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1647.leetcode1647 Minimum Deletions to Make Character Frequencies Unique-zh.md" new file mode 100644 index 00000000..36f4eb9d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1647.leetcode1647 Minimum Deletions to Make Character Frequencies Unique-zh.md" @@ -0,0 +1,129 @@ +# [1647. 字符频次唯一的最小删除次数](https://leetcode-cn.com/problems/minimum-deletions-to-make-character-frequencies-unique) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1647.Minimum%20Deletions%20to%20Make%20Character%20Frequencies%20Unique/README_EN.md) + +## 题目描述 + + + +

    如果字符串 s不存在 两个不同字符 频次 相同的情况,就称 s优质字符串

    + +

    给你一个字符串 s,返回使 s 成为 优质字符串 需要删除的 最小 字符数。

    + +

    字符串中字符的 频次 是该字符在字符串中的出现次数。例如,在字符串 "aab" 中,'a' 的频次是 2,而 'b' 的频次是 1

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aab"
    +输出:0
    +解释:s 已经是优质字符串。
    +
    + +

    示例 2:

    + +
    +输入:s = "aaabbbcc"
    +输出:2
    +解释:可以删除两个 'b' , 得到优质字符串 "aaabcc" 。
    +另一种方式是删除一个 'b' 和一个 'c' ,得到优质字符串 "aaabbc" 。
    + +

    示例 3:

    + +
    +输入:s = "ceabaacb"
    +输出:2
    +解释:可以删除两个 'c' 得到优质字符串 "eabaab" 。
    +注意,只需要关注结果字符串中仍然存在的字符。(即,频次为 0 的字符会忽略不计。)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s 仅含小写英文字母
    • +
    + + +## 解法 + + + +哈希表 + 排序。 + + + +### **Python3** + + + +```python +class Solution: + def minDeletions(self, s: str) -> int: + counter = collections.Counter(s) + vals = [v for v in counter.values()] + vals.sort(reverse=True) + ans = 0 + for i in range(1, len(vals)): + while vals[i] >= vals[i - 1] and vals[i] > 0: + vals[i] -= 1 + ans += 1 + return ans +``` + +### **Java** + + + +```java +class Solution { + public int minDeletions(String s) { + int[] counter = new int[26]; + for (char c : s.toCharArray()) { + ++counter[c - 'a']; + } + Arrays.sort(counter); + int ans = 0; + for (int i = 24; i >= 0; --i) { + while (counter[i] >= counter[i + 1] && counter[i] > 0) { + --counter[i]; + ++ans; + } + } + return ans; + } +} +``` + +### **TypeScript** + +```ts +function minDeletions(s: string): number { + let map = {}; + for (let c of s) { + map[c] = (map[c] || 0) + 1; + } + let ans = 0; + let vals: number[] = Object.values(map); + vals.sort((a, b) => a - b); + for (let i = 1; i < vals.length; ++i) { + while(vals[i] > 0 && i != vals.indexOf(vals[i])) { + --vals[i]; + ++ans; + } + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1648.leetcode1648 Sell Diminishing-Valued Colored Balls-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1648.leetcode1648 Sell Diminishing-Valued Colored Balls-zh.md" new file mode 100644 index 00000000..24380eaa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1648.leetcode1648 Sell Diminishing-Valued Colored Balls-zh.md" @@ -0,0 +1,91 @@ +# [1648. 销售价值减少的颜色球](https://leetcode-cn.com/problems/sell-diminishing-valued-colored-balls) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1648.Sell%20Diminishing-Valued%20Colored%20Balls/README_EN.md) + +## 题目描述 + + + +

    你有一些球的库存 inventory ,里面包含着不同颜色的球。一个顾客想要 任意颜色 总数为 orders 的球。

    + +

    这位顾客有一种特殊的方式衡量球的价值:每个球的价值是目前剩下的 同色球 的数目。比方说还剩下 6 个黄球,那么顾客买第一个黄球的时候该黄球的价值为 6 。这笔交易以后,只剩下 5 个黄球了,所以下一个黄球的价值为 5 (也就是球的价值随着顾客购买同色球是递减的)

    + +

    给你整数数组 inventory ,其中 inventory[i] 表示第 i 种颜色球一开始的数目。同时给你整数 orders ,表示顾客总共想买的球数目。你可以按照 任意顺序 卖球。

    + +

    请你返回卖了 orders 个球以后 最大 总价值之和。由于答案可能会很大,请你返回答案对 109 + 7 取余数 的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:inventory = [2,5], orders = 4
    +输出:14
    +解释:卖 1 个第一种颜色的球(价值为 2 ),卖 3 个第二种颜色的球(价值为 5 + 4 + 3)。
    +最大总和为 2 + 5 + 4 + 3 = 14 。
    +
    + +

    示例 2:

    + +
    +输入:inventory = [3,5], orders = 6
    +输出:19
    +解释:卖 2 个第一种颜色的球(价值为 3 + 2),卖 4 个第二种颜色的球(价值为 5 + 4 + 3 + 2)。
    +最大总和为 3 + 2 + 5 + 4 + 3 + 2 = 19 。
    +
    + +

    示例 3:

    + +
    +输入:inventory = [2,8,4,10,6], orders = 20
    +输出:110
    +
    + +

    示例 4:

    + +
    +输入:inventory = [1000000000], orders = 1000000000
    +输出:21
    +解释:卖 1000000000 次第一种颜色的球,总价值为 500000000500000000 。 500000000500000000 对 109 + 7 取余为 21 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= inventory.length <= 105
    • +
    • 1 <= inventory[i] <= 109
    • +
    • 1 <= orders <= min(sum(inventory[i]), 109)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1649.leetcode1649 Create Sorted Array through Instructions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1649.leetcode1649 Create Sorted Array through Instructions-zh.md" new file mode 100644 index 00000000..7f201d01 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1649.leetcode1649 Create Sorted Array through Instructions-zh.md" @@ -0,0 +1,102 @@ +# [1649. 通过指令创建有序数组](https://leetcode-cn.com/problems/create-sorted-array-through-instructions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1649.Create%20Sorted%20Array%20through%20Instructions/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 instructions ,你需要根据 instructions 中的元素创建一个有序数组。一开始你有一个空的数组 nums ,你需要 从左到右 遍历 instructions 中的元素,将它们依次插入 nums 数组中。每一次插入操作的 代价 是以下两者的 较小值 :

    + +
      +
    • nums 中 严格小于  instructions[i] 的数字数目。
    • +
    • nums 中 严格大于  instructions[i] 的数字数目。
    • +
    + +

    比方说,如果要将 3 插入到 nums = [1,2,3,5] ,那么插入操作的 代价 为 min(2, 1) (元素 1 和  2 小于 3 ,元素 5 大于 3 ),插入后 nums 变成 [1,2,3,3,5] 。

    + +

    请你返回将 instructions 中所有元素依次插入 nums 后的 总最小代价 。由于答案会很大,请将它对 109 + 7 取余 后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:instructions = [1,5,6,2]
    +输出:1
    +解释:一开始 nums = [] 。
    +插入 1 ,代价为 min(0, 0) = 0 ,现在 nums = [1] 。
    +插入 5 ,代价为 min(1, 0) = 0 ,现在 nums = [1,5] 。
    +插入 6 ,代价为 min(2, 0) = 0 ,现在 nums = [1,5,6] 。
    +插入 2 ,代价为 min(1, 2) = 1 ,现在 nums = [1,2,5,6] 。
    +总代价为 0 + 0 + 0 + 1 = 1 。
    + +

    示例 2:

    + +
    输入:instructions = [1,2,3,6,5,4]
    +输出:3
    +解释:一开始 nums = [] 。
    +插入 1 ,代价为 min(0, 0) = 0 ,现在 nums = [1] 。
    +插入 2 ,代价为 min(1, 0) = 0 ,现在 nums = [1,2] 。
    +插入 3 ,代价为 min(2, 0) = 0 ,现在 nums = [1,2,3] 。
    +插入 6 ,代价为 min(3, 0) = 0 ,现在 nums = [1,2,3,6] 。
    +插入 5 ,代价为 min(3, 1) = 1 ,现在 nums = [1,2,3,5,6] 。
    +插入 4 ,代价为 min(3, 2) = 2 ,现在 nums = [1,2,3,4,5,6] 。
    +总代价为 0 + 0 + 0 + 0 + 1 + 2 = 3 。
    +
    + +

    示例 3:

    + +
    输入:instructions = [1,3,3,3,2,4,2,1,2]
    +输出:4
    +解释:一开始 nums = [] 。
    +插入 1 ,代价为 min(0, 0) = 0 ,现在 nums = [1] 。
    +插入 3 ,代价为 min(1, 0) = 0 ,现在 nums = [1,3] 。
    +插入 3 ,代价为 min(1, 0) = 0 ,现在 nums = [1,3,3] 。
    +插入 3 ,代价为 min(1, 0) = 0 ,现在 nums = [1,3,3,3] 。
    +插入 2 ,代价为 min(1, 3) = 1 ,现在 nums = [1,2,3,3,3] 。
    +插入 4 ,代价为 min(5, 0) = 0 ,现在 nums = [1,2,3,3,3,4] 。
    +​​​​​插入 2 ,代价为 min(1, 4) = 1 ,现在 nums = [1,2,2,3,3,3,4] 。
    +插入 1 ,代价为 min(0, 6) = 0 ,现在 nums = [1,1,2,2,3,3,3,4] 。
    +插入 2 ,代价为 min(2, 4) = 2 ,现在 nums = [1,1,2,2,2,3,3,3,4] 。
    +总代价为 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= instructions.length <= 105
    • +
    • 1 <= instructions[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1650.leetcode1650 Lowest Common Ancestor of a Binary Tree III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1650.leetcode1650 Lowest Common Ancestor of a Binary Tree III-zh.md" new file mode 100644 index 00000000..194ff463 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1650.leetcode1650 Lowest Common Ancestor of a Binary Tree III-zh.md" @@ -0,0 +1,86 @@ +# [1650. 二叉树的最近公共祖先 III](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1650.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree%20III/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树中的两个节点 pq,返回它们的最近公共祖先节点(LCA)。

    + +

    每个节点都包含其父节点的引用(指针)。Node 的定义如下:

    + +
    class Node {
    +    public int val;
    +    public Node left;
    +    public Node right;
    +    public Node parent;
    +}
    +
    + +

    根据维基百科中对最近公共祖先节点的定义:“两个节点 p 和 q 在二叉树 T 中的最近公共祖先节点是后代节点中既包括 p 又包括 q 的最深节点(我们允许一个节点为自身的一个后代节点)”。一个节点 x 的后代节点是节点 x 到某一叶节点间的路径中的节点 y。

    + +

     

    + +

    示例 1:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    +输出: 3
    +解释: 节点 5 和 1 的最近公共祖先是 3。
    +
    + +

    示例 2:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    +输出: 5
    +解释: 节点 5 和 4 的最近公共祖先是 5,根据定义,一个节点可以是自身的最近公共祖先。
    +
    + +

    示例 3:

    + +
    输入: root = [1,2], p = 1, q = 2
    +输出: 1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点个数的范围是 [2, 105]
    • +
    • -109 <= Node.val <= 109
    • +
    • 所有的 Node.val 都是互不相同的。
    • +
    • p != q
    • +
    • p 和 q 存在于树中。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1651.leetcode1651 Hopper Company Queries III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1651.leetcode1651 Hopper Company Queries III-zh.md" new file mode 100644 index 00000000..6ae1270f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1651.leetcode1651 Hopper Company Queries III-zh.md" @@ -0,0 +1,164 @@ +# [1651. Hopper Company Queries III](https://leetcode-cn.com/problems/hopper-company-queries-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1651.Hopper%20Company%20Queries%20III/README_EN.md) + +## 题目描述 + + + +

    Table: Drivers

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| driver_id   | int     |
    +| join_date   | date    |
    ++-------------+---------+
    +driver_id is the primary key for this table.
    +Each row of this table contains the driver's ID and the date they joined the Hopper company.
    +
    + +

     

    + +

    Table: Rides

    + +
    ++--------------+---------+
    +| Column Name  | Type    |
    ++--------------+---------+
    +| ride_id      | int     |
    +| user_id      | int     |
    +| requested_at | date    |
    ++--------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
    +There may be some ride requests in this table that were not accepted.
    +
    + +

     

    + +

    Table: AcceptedRides

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| ride_id       | int     |
    +| driver_id     | int     |
    +| ride_distance | int     |
    +| ride_duration | int     |
    ++---------------+---------+
    +ride_id is the primary key for this table.
    +Each row of this table contains some information about an accepted ride.
    +It is guaranteed that each accepted ride exists in the Rides table.
    +
    + +

     

    + +

    Write an SQL query to compute the average_ride_distance and average_ride_duration of every 3-month window starting from January - March 2020 to October - December 2020. Round average_ride_distance and average_ride_duration to the nearest two decimal places.

    + +

    The average_ride_distance is calculated by summing up the total ride_distance values from the three months and dividing it by 3. The average_ride_duration is calculated in a similar way.

    + +

    Return the result table ordered by month in ascending order, where month is the starting month's number (January is 1, February is 2, etc.).

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Drivers table:
    ++-----------+------------+
    +| driver_id | join_date  |
    ++-----------+------------+
    +| 10        | 2019-12-10 |
    +| 8         | 2020-1-13  |
    +| 5         | 2020-2-16  |
    +| 7         | 2020-3-8   |
    +| 4         | 2020-5-17  |
    +| 1         | 2020-10-24 |
    +| 6         | 2021-1-5   |
    ++-----------+------------+
    +
    +Rides table:
    ++---------+---------+--------------+
    +| ride_id | user_id | requested_at |
    ++---------+---------+--------------+
    +| 6       | 75      | 2019-12-9    |
    +| 1       | 54      | 2020-2-9     |
    +| 10      | 63      | 2020-3-4     |
    +| 19      | 39      | 2020-4-6     |
    +| 3       | 41      | 2020-6-3     |
    +| 13      | 52      | 2020-6-22    |
    +| 7       | 69      | 2020-7-16    |
    +| 17      | 70      | 2020-8-25    |
    +| 20      | 81      | 2020-11-2    |
    +| 5       | 57      | 2020-11-9    |
    +| 2       | 42      | 2020-12-9    |
    +| 11      | 68      | 2021-1-11    |
    +| 15      | 32      | 2021-1-17    |
    +| 12      | 11      | 2021-1-19    |
    +| 14      | 18      | 2021-1-27    |
    ++---------+---------+--------------+
    +
    +AcceptedRides table:
    ++---------+-----------+---------------+---------------+
    +| ride_id | driver_id | ride_distance | ride_duration |
    ++---------+-----------+---------------+---------------+
    +| 10      | 10        | 63            | 38            |
    +| 13      | 10        | 73            | 96            |
    +| 7       | 8         | 100           | 28            |
    +| 17      | 7         | 119           | 68            |
    +| 20      | 1         | 121           | 92            |
    +| 5       | 7         | 42            | 101           |
    +| 2       | 4         | 6             | 38            |
    +| 11      | 8         | 37            | 43            |
    +| 15      | 8         | 108           | 82            |
    +| 12      | 8         | 38            | 34            |
    +| 14      | 1         | 90            | 74            |
    ++---------+-----------+---------------+---------------+
    +
    +Result table:
    ++-------+-----------------------+-----------------------+
    +| month | average_ride_distance | average_ride_duration |
    ++-------+-----------------------+-----------------------+
    +| 1     | 21.00                 | 12.67                 |
    +| 2     | 21.00                 | 12.67                 |
    +| 3     | 21.00                 | 12.67                 |
    +| 4     | 24.33                 | 32.00                 |
    +| 5     | 57.67                 | 41.33                 |
    +| 6     | 97.33                 | 64.00                 |
    +| 7     | 73.00                 | 32.00                 |
    +| 8     | 39.67                 | 22.67                 |
    +| 9     | 54.33                 | 64.33                 |
    +| 10    | 56.33                 | 77.00                 |
    ++-------+-----------------------+-----------------------+
    +
    +By the end of January --> average_ride_distance = (0+0+63)/3=21, average_ride_duration = (0+0+38)/3=12.67
    +By the end of February --> average_ride_distance = (0+63+0)/3=21, average_ride_duration = (0+38+0)/3=12.67
    +By the end of March --> average_ride_distance = (63+0+0)/3=21, average_ride_duration = (38+0+0)/3=12.67
    +By the end of April --> average_ride_distance = (0+0+73)/3=24.33, average_ride_duration = (0+0+96)/3=32.00
    +By the end of May --> average_ride_distance = (0+73+100)/3=57.67, average_ride_duration = (0+96+28)/3=41.33
    +By the end of June --> average_ride_distance = (73+100+119)/3=97.33, average_ride_duration = (96+28+68)/3=64.00
    +By the end of July --> average_ride_distance = (100+119+0)/3=73.00, average_ride_duration = (28+68+0)/3=32.00
    +By the end of August --> average_ride_distance = (119+0+0)/3=39.67, average_ride_duration = (68+0+0)/3=22.67
    +By the end of Septemeber --> average_ride_distance = (0+0+163)/3=54.33, average_ride_duration = (0+0+193)/3=64.33
    +By the end of October --> average_ride_distance = (0+163+6)/3=56.33, average_ride_duration = (0+193+38)/3=77.00
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1652.leetcode1652 Defuse the Bomb-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1652.leetcode1652 Defuse the Bomb-zh.md" new file mode 100644 index 00000000..8468d481 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1652.leetcode1652 Defuse the Bomb-zh.md" @@ -0,0 +1,122 @@ +# [1652. 拆炸弹](https://leetcode-cn.com/problems/defuse-the-bomb) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1652.Defuse%20the%20Bomb/README_EN.md) + +## 题目描述 + + + +

    你有一个炸弹需要拆除,时间紧迫!你的情报员会给你一个长度为 n 的 循环 数组 code 以及一个密钥 k 。

    + +

    为了获得正确的密码,你需要替换掉每一个数字。所有数字会 同时 被替换。

    + +
      +
    • 如果 k > 0 ,将第 i 个数字用 接下来 k 个数字之和替换。
    • +
    • 如果 k < 0 ,将第 i 个数字用 之前 k 个数字之和替换。
    • +
    • 如果 k == 0 ,将第 i 个数字用 0 替换。
    • +
    + +

    由于 code 是循环的, code[n-1] 下一个元素是 code[0] ,且 code[0] 前一个元素是 code[n-1] 。

    + +

    给你 循环 数组 code 和整数密钥 k ,请你返回解密后的结果来拆除炸弹!

    + +

     

    + +

    示例 1:

    + +
    +输入:code = [5,7,1,4], k = 3
    +输出:[12,10,16,13]
    +解释:每个数字都被接下来 3 个数字之和替换。解密后的密码为 [7+1+4, 1+4+5, 4+5+7, 5+7+1]。注意到数组是循环连接的。
    +
    + +

    示例 2:

    + +
    +输入:code = [1,2,3,4], k = 0
    +输出:[0,0,0,0]
    +解释:当 k 为 0 时,所有数字都被 0 替换。
    +
    + +

    示例 3:

    + +
    +输入:code = [2,4,9,3], k = -2
    +输出:[12,5,6,13]
    +解释:解密后的密码为 [3+9, 2+3, 4+2, 9+4] 。注意到数组是循环连接的。如果 k 是负数,那么和为 之前 的数字。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == code.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= code[i] <= 100
    • +
    • -(n - 1) <= k <= n - 1
    • +
    + + +## 解法 + + + +数组下标取模,累加求每一项即可。 + + + +### **Python3** + + + +```python +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + res = [0] * n + if k == 0: + return res + for i in range(n): + if k > 0: + for j in range(i + 1, i + k + 1): + res[i] += code[j % n] + else: + for j in range(i + k, i): + res[i] += code[(j + n) % n] + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] res = new int[n]; + if (k == 0) return res; + for (int i = 0; i < n; ++i) { + if (k > 0) { + for (int j = i + 1; j <= i + k; ++j) { + res[i] += code[j % n]; + } + } else { + for (int j = i + k; j <= i - 1; ++j) { + res[i] += code[(j + n) % n]; + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1653.leetcode1653 Minimum Deletions to Make String Balanced-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1653.leetcode1653 Minimum Deletions to Make String Balanced-zh.md" new file mode 100644 index 00000000..3c802e30 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1653.leetcode1653 Minimum Deletions to Make String Balanced-zh.md" @@ -0,0 +1,73 @@ +# [1653. 使字符串平衡的最少删除次数](https://leetcode-cn.com/problems/minimum-deletions-to-make-string-balanced) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1653.Minimum%20Deletions%20to%20Make%20String%20Balanced/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,它仅包含字符 'a' 和 'b'​​​​ 。

    + +

    你可以删除 s 中任意数目的字符,使得 s 平衡 。我们称 s 平衡的 当不存在下标对 (i,j) 满足 i < j 且 s[i] = 'b' 同时 s[j]= 'a' 。

    + +

    请你返回使 s 平衡 的 最少 删除次数。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aababbab"
    +输出:2
    +解释:你可以选择以下任意一种方案:
    +下标从 0 开始,删除第 2 和第 6 个字符("aababbab" -> "aaabbb"),
    +下标从 0 开始,删除第 3 和第 6 个字符("aababbab" -> "aabbbb")。
    +
    + +

    示例 2:

    + +
    +输入:s = "bbaaaaabb"
    +输出:2
    +解释:唯一的最优解是删除最前面两个字符。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s[i] 要么是 'a' 要么是 'b' 。​
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1654.leetcode1654 Minimum Jumps to Reach Home-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1654.leetcode1654 Minimum Jumps to Reach Home-zh.md" new file mode 100644 index 00000000..9e252f7c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1654.leetcode1654 Minimum Jumps to Reach Home-zh.md" @@ -0,0 +1,90 @@ +# [1654. 到家的最少跳跃次数](https://leetcode-cn.com/problems/minimum-jumps-to-reach-home) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1654.Minimum%20Jumps%20to%20Reach%20Home/README_EN.md) + +## 题目描述 + + + +

    有一只跳蚤的家在数轴上的位置 x 处。请你帮助它从位置 0 出发,到达它的家。

    + +

    跳蚤跳跃的规则如下:

    + +
      +
    • 它可以 往前 跳恰好 a 个位置(即往右跳)。
    • +
    • 它可以 往后 跳恰好 b 个位置(即往左跳)。
    • +
    • 它不能 连续 往后跳 2 次。
    • +
    • 它不能跳到任何 forbidden 数组中的位置。
    • +
    + +

    跳蚤可以往前跳 超过 它的家的位置,但是它 不能跳到负整数 的位置。

    + +

    给你一个整数数组 forbidden ,其中 forbidden[i] 是跳蚤不能跳到的位置,同时给你整数 a, b 和 x ,请你返回跳蚤到家的最少跳跃次数。如果没有恰好到达 x 的可行方案,请你返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9
    +输出:3
    +解释:往前跳 3 次(0 -> 3 -> 6 -> 9),跳蚤就到家了。
    +
    + +

    示例 2:

    + +
    +输入:forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11
    +输出:-1
    +
    + +

    示例 3:

    + +
    +输入:forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7
    +输出:2
    +解释:往前跳一次(0 -> 16),然后往回跳一次(16 -> 7),跳蚤就到家了。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= forbidden.length <= 1000
    • +
    • 1 <= a, b, forbidden[i] <= 2000
    • +
    • 0 <= x <= 2000
    • +
    • forbidden 中所有位置互不相同。
    • +
    • 位置 x 不在 forbidden 中。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1655.leetcode1655 Distribute Repeating Integers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1655.leetcode1655 Distribute Repeating Integers-zh.md" new file mode 100644 index 00000000..20216a5a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1655.leetcode1655 Distribute Repeating Integers-zh.md" @@ -0,0 +1,98 @@ +# [1655. 分配重复整数](https://leetcode-cn.com/problems/distribute-repeating-integers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1655.Distribute%20Repeating%20Integers/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的整数数组 nums ,这个数组中至多有 50 个不同的值。同时你有 m 个顾客的订单 quantity ,其中,整数 quantity[i] 是第 i 位顾客订单的数目。请你判断是否能将 nums 中的整数分配给这些顾客,且满足:

    + +
      +
    • 第 i 位顾客 恰好 有 quantity[i] 个整数。
    • +
    • 第 i 位顾客拿到的整数都是 相同的 。
    • +
    • 每位顾客都满足上述两个要求。
    • +
    + +

    如果你可以分配 nums 中的整数满足上面的要求,那么请返回 true ,否则返回 false 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,4], quantity = [2]
    +输出:false
    +解释:第 0 位顾客没办法得到两个相同的整数。
    +
    + +

    示例 2:

    + +
    输入:nums = [1,2,3,3], quantity = [2]
    +输出:true
    +解释:第 0 位顾客得到 [3,3] 。整数 [1,2] 都没有被使用。
    +
    + +

    示例 3:

    + +
    输入:nums = [1,1,2,2], quantity = [2,2]
    +输出:true
    +解释:第 0 位顾客得到 [1,1] ,第 1 位顾客得到 [2,2] 。
    +
    + +

    示例 4:

    + +
    输入:nums = [1,1,2,3], quantity = [2,2]
    +输出:false
    +解释:尽管第 0 位顾客可以得到 [1,1] ,第 1 位顾客没法得到 2 个一样的整数。
    + +

    示例 5:

    + +
    输入:nums = [1,1,1,1,1], quantity = [2,3]
    +输出:true
    +解释:第 0 位顾客得到 [1,1] ,第 1 位顾客得到 [1,1,1] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums[i] <= 1000
    • +
    • m == quantity.length
    • +
    • 1 <= m <= 10
    • +
    • 1 <= quantity[i] <= 105
    • +
    • nums 中至多有 50 个不同的数字。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1656.leetcode1656 Design an Ordered Stream-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1656.leetcode1656 Design an Ordered Stream-zh.md" new file mode 100644 index 00000000..c09d35aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1656.leetcode1656 Design an Ordered Stream-zh.md" @@ -0,0 +1,91 @@ +# [1656. 设计有序流](https://leetcode-cn.com/problems/design-an-ordered-stream) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1656.Design%20an%20Ordered%20Stream/README_EN.md) + +## 题目描述 + + + +

    n(id, value) 对,其中 id1n 之间的一个整数,value 是一个字符串。不存在 id 相同的两个 (id, value) 对。

    + +

    设计一个流,以 任意 顺序获取 n 个 (id, value) 对,并在多次调用时 id 递增的顺序 返回一些值。

    + +

    实现 OrderedStream 类:

    + +
      +
    • OrderedStream(int n) 构造一个能接收 n 个值的流,并将当前指针 ptr 设为 1
    • +
    • String[] insert(int id, String value) 向流中存储新的 (id, value) 对。存储后: +
        +
      • 如果流存储有 id = ptr(id, value) 对,则找出从 id = ptr 开始的 最长 id 连续递增序列 ,并 按顺序 返回与这些 id 关联的值的列表。然后,将 ptr 更新为最后那个  id + 1 。
      • +
      • +

        否则,返回一个空列表。

        +
      • +
      +
    • +
    + +

     

    + +

    示例:

    + +

    + +
    +输入
    +["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
    +[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
    +输出
    +[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]
    +
    +解释
    +OrderedStream os= new OrderedStream(5);
    +os.insert(3, "ccccc"); // 插入 (3, "ccccc"),返回 []
    +os.insert(1, "aaaaa"); // 插入 (1, "aaaaa"),返回 ["aaaaa"]
    +os.insert(2, "bbbbb"); // 插入 (2, "bbbbb"),返回 ["bbbbb", "ccccc"]
    +os.insert(5, "eeeee"); // 插入 (5, "eeeee"),返回 []
    +os.insert(4, "ddddd"); // 插入 (4, "ddddd"),返回 ["ddddd", "eeeee"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1000
    • +
    • 1 <= id <= n
    • +
    • value.length == 5
    • +
    • value 仅由小写字母组成
    • +
    • 每次调用 insert 都会使用一个唯一的 id
    • +
    • 恰好调用 ninsert
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1657.leetcode1657 Determine if Two Strings Are Close-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1657.leetcode1657 Determine if Two Strings Are Close-zh.md" new file mode 100644 index 00000000..d525967f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1657.leetcode1657 Determine if Two Strings Are Close-zh.md" @@ -0,0 +1,104 @@ +# [1657. 确定两个字符串是否接近](https://leetcode-cn.com/problems/determine-if-two-strings-are-close) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1657.Determine%20if%20Two%20Strings%20Are%20Close/README_EN.md) + +## 题目描述 + + + +

    如果可以使用以下操作从一个字符串得到另一个字符串,则认为两个字符串 接近

    + +
      +
    • 操作 1:交换任意两个 现有 字符。 + +
        +
      • 例如,abcde -> aecdb
      • +
      +
    • +
    • 操作 2:将一个 现有 字符的每次出现转换为另一个 现有 字符,并对另一个字符执行相同的操作。 +
        +
      • 例如,aacabb -> bbcbaa(所有 a 转化为 b ,而所有的 b 转换为 a
      • +
      +
    • +
    + +

    你可以根据需要对任意一个字符串多次使用这两种操作。

    + +

    给你两个字符串,word1word2 。如果 word1 word2 接近 ,就返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:word1 = "abc", word2 = "bca"
    +输出:true
    +解释:2 次操作从 word1 获得 word2 。
    +执行操作 1:"abc" -> "acb"
    +执行操作 1:"acb" -> "bca"
    +
    + +

    示例 2:

    + +
    +输入:word1 = "a", word2 = "aa"
    +输出:false
    +解释:不管执行多少次操作,都无法从 word1 得到 word2 ,反之亦然。
    + +

    示例 3:

    + +
    +输入:word1 = "cabbba", word2 = "abbccc"
    +输出:true
    +解释:3 次操作从 word1 获得 word2 。
    +执行操作 1:"cabbba" -> "caabbb"
    +执行操作 2:"caabbb" -> "baaccc"
    +执行操作 2:"baaccc" -> "abbccc"
    +
    + +

    示例 4:

    + +
    +输入:word1 = "cabbba", word2 = "aabbss"
    +输出:false
    +解释:不管执行多少次操作,都无法从 word1 得到 word2 ,反之亦然。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word1.length, word2.length <= 105
    • +
    • word1word2 仅包含小写英文字母
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1658.leetcode1658 Minimum Operations to Reduce X to Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1658.leetcode1658 Minimum Operations to Reduce X to Zero-zh.md" new file mode 100644 index 00000000..cde0bd2b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1658.leetcode1658 Minimum Operations to Reduce X to Zero-zh.md" @@ -0,0 +1,77 @@ +# [1658. 将 x 减到 0 的最小操作数](https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1658.Minimum%20Operations%20to%20Reduce%20X%20to%20Zero/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 x 。每一次操作时,你应当移除数组 nums 最左边或最右边的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。

    + +

    如果可以将 x 恰好 减到 0 ,返回 最小操作数 ;否则,返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,1,4,2,3], x = 5
    +输出:2
    +解释:最佳解决方案是移除后两个元素,将 x 减到 0 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [5,6,7,8,9], x = 4
    +输出:-1
    +
    + +

    示例 3:

    + +
    +输入:nums = [3,2,20,1,1,3], x = 10
    +输出:5
    +解释:最佳解决方案是移除后三个元素和前两个元素(总共 5 次操作),将 x 减到 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 104
    • +
    • 1 <= x <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1659.leetcode1659 Maximize Grid Happiness-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1659.leetcode1659 Maximize Grid Happiness-zh.md" new file mode 100644 index 00000000..d604fdcc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1659.leetcode1659 Maximize Grid Happiness-zh.md" @@ -0,0 +1,97 @@ +# [1659. 最大化网格幸福感](https://leetcode-cn.com/problems/maximize-grid-happiness) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1659.Maximize%20Grid%20Happiness/README_EN.md) + +## 题目描述 + + + +

    给你四个整数 mnintrovertsCountextrovertsCount 。有一个 m x n 网格,和两种类型的人:内向的人和外向的人。总共有 introvertsCount 个内向的人和 extrovertsCount 个外向的人。

    + +

    请你决定网格中应当居住多少人,并为每个人分配一个网格单元。 注意,不必 让所有人都生活在网格中。

    + +

    每个人的 幸福感 计算如下:

    + +
      +
    • 内向的人 开始 时有 120 个幸福感,但每存在一个邻居(内向的或外向的)他都会 失去  30 个幸福感。
    • +
    • 外向的人 开始 时有 40 个幸福感,每存在一个邻居(内向的或外向的)他都会 得到  20 个幸福感。
    • +
    + +

    邻居是指居住在一个人所在单元的上、下、左、右四个直接相邻的单元中的其他人。

    + +

    网格幸福感 是每个人幸福感的 总和 。 返回 最大可能的网格幸福感

    + +

     

    + +

    示例 1:

    + +
    +输入:m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
    +输出:240
    +解释:假设网格坐标 (row, column) 从 1 开始编号。
    +将内向的人放置在单元 (1,1) ,将外向的人放置在单元 (1,3) 和 (2,3) 。
    +- 位于 (1,1) 的内向的人的幸福感:120(初始幸福感)- (0 * 30)(0 位邻居)= 120
    +- 位于 (1,3) 的外向的人的幸福感:40(初始幸福感)+ (1 * 20)(1 位邻居)= 60
    +- 位于 (2,3) 的外向的人的幸福感:40(初始幸福感)+ (1 * 20)(1 位邻居)= 60
    +网格幸福感为:120 + 60 + 60 = 240
    +上图展示该示例对应网格中每个人的幸福感。内向的人在浅绿色单元中,而外向的人在浅紫色单元中。
    +
    + +

    示例 2:

    + +
    +输入:m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
    +输出:260
    +解释:将内向的人放置在单元 (1,1) 和 (3,1) ,将外向的人放置在单元 (2,1) 。
    +- 位于 (1,1) 的内向的人的幸福感:120(初始幸福感)- (1 * 30)(1 位邻居)= 90
    +- 位于 (2,1) 的外向的人的幸福感:40(初始幸福感)+ (2 * 20)(2 位邻居)= 80
    +- 位于 (3,1) 的内向的人的幸福感:120(初始幸福感)- (1 * 30)(1 位邻居)= 90
    +网格幸福感为 90 + 80 + 90 = 260
    +
    + +

    示例 3:

    + +
    +输入:m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
    +输出:240
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m, n <= 5
    • +
    • 0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1660.leetcode1660 Correct a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1660.leetcode1660 Correct a Binary Tree-zh.md" new file mode 100644 index 00000000..31b9635e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1660.leetcode1660 Correct a Binary Tree-zh.md" @@ -0,0 +1,90 @@ +# [1660. 纠正二叉树](https://leetcode-cn.com/problems/correct-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1660.Correct%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    你有一棵二叉树,这棵二叉树有个小问题,其中有且只有一个无效节点,它的右子节点错误地指向了与其在同一层且在其右侧的一个其他节点。

    + +

    给定一棵这样的问题二叉树的根节点 root ,将该无效节点及其所有子节点移除(除被错误指向的节点外),然后返回新二叉树的根结点。

    + +

    自定义测试用例:

    + +

    测试用例的输入由三行组成:

    + +
      +
    • TreeNode root
    • +
    • int fromNode (在 correctBinaryTree 中不可见
    • +
    • int toNode (在 correctBinaryTree 中不可见
    • +
    + +

    当以 root 为根的二叉树被解析后,值为 fromNode 的节点 TreeNode 将其右子节点指向值为 toNode 的节点 TreeNode 。然后, root 传入 correctBinaryTree 的参数中。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入: root = [1,2,3], fromNode = 2, toNode = 3
    +输出: [1,null,3]
    +解释: 值为 2 的节点是无效的,所以移除之。
    +
    + +

    示例 2:

    + +

    + +
    +输入: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4
    +输出: [8,3,1,null,null,9,4,null,null,5,6]
    +解释: 值为 7 的节点是无效的,所以移除这个节点及其子节点 2。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点个数的范围是 [3, 104] 。
    • +
    • -109 <= Node.val <= 109
    • +
    • 所有的 Node.val 都是互不相同的。
    • +
    • fromNode != toNode
    • +
    • fromNode 和 toNode 将出现在树中的同一层。
    • +
    • toNode 在 fromNode 的右侧。
    • +
    • fromNode.right 在测试用例的树中建立后为 null 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1661.leetcode1661 Average Time of Process per Machine-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1661.leetcode1661 Average Time of Process per Machine-zh.md" new file mode 100644 index 00000000..21a03d6d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1661.leetcode1661 Average Time of Process per Machine-zh.md" @@ -0,0 +1,86 @@ +# [1661. 每台机器的进程平均运行时间](https://leetcode-cn.com/problems/average-time-of-process-per-machine) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1661.Average%20Time%20of%20Process%20per%20Machine/README_EN.md) + +## 题目描述 + + + +

    表: Activity

    + +
    +----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| machine_id     | int     |
    +| process_id     | int     |
    +| activity_type  | enum    |
    +| timestamp      | float   |
    ++----------------+---------+
    +该表展示了一家工厂网站的用户活动.
    +(machine_id, process_id, activity_type) 是当前表的主键.
    +machine_id 是一台机器的ID号.
    +process_id 是运行在各机器上的进程ID号.
    +activity_type 是枚举类型 ('start', 'end').
    +timestamp 是浮点类型,代表当前时间(以秒为单位).
    +'start' 代表该进程在这台机器上的开始运行时间戳 , 'end' 代表该进程在这台机器上的终止运行时间戳.
    +同一台机器,同一个进程都有一对开始时间戳和结束时间戳,而且开始时间戳永远在结束时间戳前面.
    + +

     

    + +

    现在有一个工厂网站由几台机器运行,每台机器上运行着相同数量的进程. 请写出一条SQL计算每台机器各自完成一个进程任务的平均耗时.

    + +

    完成一个进程任务的时间指进程的'end' 时间戳 减去 'start' 时间戳. 平均耗时通过计算每台机器上所有进程任务的总耗费时间除以机器上的总进程数量获得.

    + +

    结果表必须包含machine_id(机器ID) 和对应的 average time(平均耗时) 别名 processing_time, 且四舍五入保留3位小数.

    + +

    具体参考例子如下:

    + +

     

    + +
    Activity table:
    ++------------+------------+---------------+-----------+
    +| machine_id | process_id | activity_type | timestamp |
    ++------------+------------+---------------+-----------+
    +| 0          | 0          | start         | 0.712     |
    +| 0          | 0          | end           | 1.520     |
    +| 0          | 1          | start         | 3.140     |
    +| 0          | 1          | end           | 4.120     |
    +| 1          | 0          | start         | 0.550     |
    +| 1          | 0          | end           | 1.550     |
    +| 1          | 1          | start         | 0.430     |
    +| 1          | 1          | end           | 1.420     |
    +| 2          | 0          | start         | 4.100     |
    +| 2          | 0          | end           | 4.512     |
    +| 2          | 1          | start         | 2.500     |
    +| 2          | 1          | end           | 5.000     |
    ++------------+------------+---------------+-----------+
    +
    +Result table:
    ++------------+-----------------+
    +| machine_id | processing_time |
    ++------------+-----------------+
    +| 0          | 0.894           |
    +| 1          | 0.995           |
    +| 2          | 1.456           |
    ++------------+-----------------+
    +
    +一共有3台机器,每台机器运行着两个进程.
    +机器 0 的平均耗时: ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894
    +机器 1 的平均耗时: ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995
    +机器 2 的平均耗时: ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1662.leetcode1662 Check If Two String Arrays are Equivalent-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1662.leetcode1662 Check If Two String Arrays are Equivalent-zh.md" new file mode 100644 index 00000000..9ce001df --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1662.leetcode1662 Check If Two String Arrays are Equivalent-zh.md" @@ -0,0 +1,79 @@ +# [1662. 检查两个字符串数组是否相等](https://leetcode-cn.com/problems/check-if-two-string-arrays-are-equivalent) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1662.Check%20If%20Two%20String%20Arrays%20are%20Equivalent/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串数组 word1word2 。如果两个数组表示的字符串相同,返回 true ;否则,返回 false

    + +

    数组表示的字符串 是由数组中的所有元素 按顺序 连接形成的字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:word1 = ["ab", "c"], word2 = ["a", "bc"]
    +输出:true
    +解释:
    +word1 表示的字符串为 "ab" + "c" -> "abc"
    +word2 表示的字符串为 "a" + "bc" -> "abc"
    +两个字符串相同,返回 true
    + +

    示例 2:

    + +
    +输入:word1 = ["a", "cb"], word2 = ["ab", "c"]
    +输出:false
    +
    + +

    示例 3:

    + +
    +输入:word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word1.length, word2.length <= 103
    • +
    • 1 <= word1[i].length, word2[i].length <= 103
    • +
    • 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
    • +
    • word1[i]word2[i] 由小写字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1663.leetcode1663 Smallest String With A Given Numeric Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1663.leetcode1663 Smallest String With A Given Numeric Value-zh.md" new file mode 100644 index 00000000..e654d6ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1663.leetcode1663 Smallest String With A Given Numeric Value-zh.md" @@ -0,0 +1,76 @@ +# [1663. 具有给定数值的最小字符串](https://leetcode-cn.com/problems/smallest-string-with-a-given-numeric-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1663.Smallest%20String%20With%20A%20Given%20Numeric%20Value/README_EN.md) + +## 题目描述 + + + +

    小写字符 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1b 的数值为 2c 的数值为 3 ,以此类推。

    + +

    字符串由若干小写字符组成,字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8

    + +

    给你两个整数 nk 。返回 长度 等于 n数值 等于 k字典序最小 的字符串。

    + +

    注意,如果字符串 x 在字典排序中位于 y 之前,就认为 x 字典序比 y 小,有以下两种情况:

    + +
      +
    • xy 的一个前缀;
    • +
    • 如果 i 是 x[i] != y[i] 的第一个位置,且 x[i] 在字母表中的位置比 y[i] 靠前。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, k = 27
    +输出:"aay"
    +解释:字符串的数值为 1 + 1 + 25 = 27,它是数值满足要求且长度等于 3 字典序最小的字符串。
    + +

    示例 2:

    + +
    +输入:n = 5, k = 73
    +输出:"aaszz"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 105
    • +
    • n <= k <= 26 * n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1664.leetcode1664 Ways to Make a Fair Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1664.leetcode1664 Ways to Make a Fair Array-zh.md" new file mode 100644 index 00000000..917afae5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1664.leetcode1664 Ways to Make a Fair Array-zh.md" @@ -0,0 +1,92 @@ +# [1664. 生成平衡数组的方案数](https://leetcode-cn.com/problems/ways-to-make-a-fair-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1664.Ways%20to%20Make%20a%20Fair%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 。你需要选择 恰好 一个下标(下标从 0 开始)并删除对应的元素。请注意剩下元素的下标可能会因为删除操作而发生改变。

    + +

    比方说,如果 nums = [6,1,7,4,1] ,那么:

    + +
      +
    • 选择删除下标 1 ,剩下的数组为 nums = [6,7,4,1] 。
    • +
    • 选择删除下标 2 ,剩下的数组为 nums = [6,1,4,1] 。
    • +
    • 选择删除下标 4 ,剩下的数组为 nums = [6,1,7,4] 。
    • +
    + +

    如果一个数组满足奇数下标元素的和与偶数下标元素的和相等,该数组就是一个 平衡数组

    + +

    请你返回删除操作后,剩下的数组 nums 是 平衡数组 的 方案数 。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,1,6,4]
    +输出:1
    +解释:
    +删除下标 0 :[1,6,4] -> 偶数元素下标为:1 + 4 = 5 。奇数元素下标为:6 。不平衡。
    +删除下标 1 :[2,6,4] -> 偶数元素下标为:2 + 4 = 6 。奇数元素下标为:6 。平衡。
    +删除下标 2 :[2,1,4] -> 偶数元素下标为:2 + 4 = 6 。奇数元素下标为:1 。不平衡。
    +删除下标 3 :[2,1,6] -> 偶数元素下标为:2 + 6 = 8 。奇数元素下标为:1 。不平衡。
    +只有一种让剩余数组成为平衡数组的方案。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,1,1]
    +输出:3
    +解释:你可以删除任意元素,剩余数组都是平衡数组。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,2,3]
    +输出:0
    +解释:不管删除哪个元素,剩下数组都不是平衡数组。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1665.leetcode1665 Minimum Initial Energy to Finish Tasks-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1665.leetcode1665 Minimum Initial Energy to Finish Tasks-zh.md" new file mode 100644 index 00000000..40b806a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1665.leetcode1665 Minimum Initial Energy to Finish Tasks-zh.md" @@ -0,0 +1,99 @@ +# [1665. 完成所有任务的最少初始能量](https://leetcode-cn.com/problems/minimum-initial-energy-to-finish-tasks) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1665.Minimum%20Initial%20Energy%20to%20Finish%20Tasks/README_EN.md) + +## 题目描述 + + + +

    给你一个任务数组 tasks ,其中 tasks[i] = [actuali, minimumi] :

    + +
      +
    • actuali 是完成第 i 个任务 需要耗费 的实际能量。
    • +
    • minimumi 是开始第 i 个任务前需要达到的最低能量。
    • +
    + +

    比方说,如果任务为 [10, 12] 且你当前的能量为 11 ,那么你不能开始这个任务。如果你当前的能量为 13 ,你可以完成这个任务,且完成它后剩余能量为 3 。

    + +

    你可以按照 任意顺序 完成任务。

    + +

    请你返回完成所有任务的 最少 初始能量。

    + +

     

    + +

    示例 1:

    + +
    输入:tasks = [[1,2],[2,4],[4,8]]
    +输出:8
    +解释:
    +一开始有 8 能量,我们按照如下顺序完成任务:
    +    - 完成第 3 个任务,剩余能量为 8 - 4 = 4 。
    +    - 完成第 2 个任务,剩余能量为 4 - 2 = 2 。
    +    - 完成第 1 个任务,剩余能量为 2 - 1 = 1 。
    +注意到尽管我们有能量剩余,但是如果一开始只有 7 能量是不能完成所有任务的,因为我们无法开始第 3 个任务。
    + +

    示例 2:

    + +
    输入:tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]
    +输出:32
    +解释:
    +一开始有 32 能量,我们按照如下顺序完成任务:
    +    - 完成第 1 个任务,剩余能量为 32 - 1 = 31 。
    +    - 完成第 2 个任务,剩余能量为 31 - 2 = 29 。
    +    - 完成第 3 个任务,剩余能量为 29 - 10 = 19 。
    +    - 完成第 4 个任务,剩余能量为 19 - 10 = 9 。
    +    - 完成第 5 个任务,剩余能量为 9 - 8 = 1 。
    + +

    示例 3:

    + +
    输入:tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]
    +输出:27
    +解释:
    +一开始有 27 能量,我们按照如下顺序完成任务:
    +    - 完成第 5 个任务,剩余能量为 27 - 5 = 22 。
    +    - 完成第 2 个任务,剩余能量为 22 - 2 = 20 。
    +    - 完成第 3 个任务,剩余能量为 20 - 3 = 17 。
    +    - 完成第 1 个任务,剩余能量为 17 - 1 = 16 。
    +    - 完成第 4 个任务,剩余能量为 16 - 4 = 12 。
    +    - 完成第 6 个任务,剩余能量为 12 - 6 = 6 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= tasks.length <= 105
    • +
    • 1 <= actual​i <= minimumi <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1666.leetcode1666 Change the Root of a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1666.leetcode1666 Change the Root of a Binary Tree-zh.md" new file mode 100644 index 00000000..3575ac60 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1666.leetcode1666 Change the Root of a Binary Tree-zh.md" @@ -0,0 +1,76 @@ +# [1666. 改变二叉树的根节点](https://leetcode-cn.com/problems/change-the-root-of-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1666.Change%20the%20Root%20of%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树的根节点 root 和一个叶节点 leaf ,更改二叉树,使得 leaf 为新的根节点。

    + +

    你可以按照下列步骤修改 leaf  root 的路径中除 root 外的每个节点 cur :

    + +
      +
    1. 如果 cur 有左子节点,则该子节点变为 cur 的右子节点。注意我们保证 cur 至多有一个子节点。
    2. +
    3. cur 的原父节点变为 cur 的左子节点。
    4. +
    + +

    返回修改后新树的根节点。

    + +

    注意:确保你的答案在操作后正确地设定了 Node.parent (父节点)指针,否则会被判为错误答案。

    + +

     

    + +

    示例 1:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 7
    +输出: [7,2,null,5,4,3,6,null,null,null,1,null,null,0,8]
    +
    + +

    示例 2:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 0
    +输出: [0,1,null,3,8,5,null,null,null,6,2,null,null,7,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点的个数在范围 [2, 100] 内。
    • +
    • -109 <= Node.val <= 109
    • +
    • 所有的 Node.val 都是唯一的。
    • +
    • leaf 存在于树中。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1667.leetcode1667 Fix Names in a Table-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1667.leetcode1667 Fix Names in a Table-zh.md" new file mode 100644 index 00000000..6361846c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1667.leetcode1667 Fix Names in a Table-zh.md" @@ -0,0 +1,61 @@ +# [1667. 修复表中的名字](https://leetcode-cn.com/problems/fix-names-in-a-table) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1667.Fix%20Names%20in%20a%20Table/README_EN.md) + +## 题目描述 + + + +

    表: Users

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| user_id        | int     |
    +| name           | varchar |
    ++----------------+---------+
    +user_id 是该表的主键。
    +该表包含用户的 ID 和名字。名字仅由小写和大写字符组成。
    +
    + +

     

    + +

    编写一个 SQL 查询来修复名字,使得只有第一个字符是大写的,其余都是小写的。

    + +

    返回按 user_id 排序的结果表。

    + +

    查询结果格式示例如下:

    + +
    +Users table:
    ++---------+-------+
    +| user_id | name  |
    ++---------+-------+
    +| 1       | aLice |
    +| 2       | bOB   |
    ++---------+-------+
    +
    +Result table:
    ++---------+-------+
    +| user_id | name  |
    ++---------+-------+
    +| 1       | Alice |
    +| 2       | Bob   |
    ++---------+-------+
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1668.leetcode1668 Maximum Repeating Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1668.leetcode1668 Maximum Repeating Substring-zh.md" new file mode 100644 index 00000000..50cf44c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1668.leetcode1668 Maximum Repeating Substring-zh.md" @@ -0,0 +1,78 @@ +# [1668. 最大重复子字符串](https://leetcode-cn.com/problems/maximum-repeating-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1668.Maximum%20Repeating%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 sequence ,如果字符串 word 连续重复 k 次形成的字符串是 sequence 的一个子字符串,那么单词 word重复值为 k 。单词 word 的 大重复值 是单词 word 在 sequence 中最大的重复值。如果 word 不是 sequence 的子串,那么重复值 k 为 0

    + +

    给你一个字符串 sequence 和 word ,请你返回 最大重复值 k

    + +

     

    + +

    示例 1:

    + +
    +输入:sequence = "ababc", word = "ab"
    +输出:2
    +解释:"abab" 是 "ababc" 的子字符串。
    +
    + +

    示例 2:

    + +
    +输入:sequence = "ababc", word = "ba"
    +输出:1
    +解释:"ba" 是 "ababc" 的子字符串,但 "baba" 不是 "ababc" 的子字符串。
    +
    + +

    示例 3:

    + +
    +输入:sequence = "ababc", word = "ac"
    +输出:0
    +解释:"ac" 不是 "ababc" 的子字符串。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= sequence.length <= 100
    • +
    • 1 <= word.length <= 100
    • +
    • sequence 和 word 都只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1669.leetcode1669 Merge In Between Linked Lists-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1669.leetcode1669 Merge In Between Linked Lists-zh.md" new file mode 100644 index 00000000..d83cdd36 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1669.leetcode1669 Merge In Between Linked Lists-zh.md" @@ -0,0 +1,118 @@ +# [1669. 合并两个链表](https://leetcode-cn.com/problems/merge-in-between-linked-lists) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1669.Merge%20In%20Between%20Linked%20Lists/README_EN.md) + +## 题目描述 + + + +

    给你两个链表 list1 和 list2 ,它们包含的元素分别为 n 个和 m 个。

    + +

    请你将 list1 中第 a 个节点到第 b 个节点删除,并将list2 接在被删除节点的位置。

    + +

    下图中蓝色边和节点展示了操作后的结果:

    + +

    请你返回结果链表的头指针。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
    +输出:[0,1,2,1000000,1000001,1000002,5]
    +解释:我们删除 list1 中第三和第四个节点,并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。
    +
    + +

    示例 2:

    + +
    +输入:list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
    +输出:[0,1,1000000,1000001,1000002,1000003,1000004,6]
    +解释:上图中蓝色的边和节点为答案链表。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= list1.length <= 104
    • +
    • 1 <= a <= b < list1.length - 1
    • +
    • 1 <= list2.length <= 104
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: + p = q = list1 + for _ in range(a - 1): + p = p.next + for _ in range(b + 1): + q = q.next + p.next = list2 + while list2.next: + list2 = list2.next + list2.next = q + return list1 +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode p = list1; + for (int i = 0; i < a - 1; ++i) { + p = p.next; + } + ListNode q = list1; + for (int i = 0; i < b + 1; ++i) { + q = q.next; + } + p.next = list2; + while (list2.next != null) { + list2 = list2.next; + } + list2.next = q; + return list1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1670.leetcode1670 Design Front Middle Back Queue-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1670.leetcode1670 Design Front Middle Back Queue-zh.md" new file mode 100644 index 00000000..121c2bd8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1670.leetcode1670 Design Front Middle Back Queue-zh.md" @@ -0,0 +1,319 @@ +# [1670. 设计前中后队列](https://leetcode-cn.com/problems/design-front-middle-back-queue) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1670.Design%20Front%20Middle%20Back%20Queue/README_EN.md) + +## 题目描述 + + + +

    请你设计一个队列,支持在前,中,后三个位置的 push 和 pop 操作。

    + +

    请你完成 FrontMiddleBack 类:

    + +
      +
    • FrontMiddleBack() 初始化队列。
    • +
    • void pushFront(int val) 将 val 添加到队列的 最前面 。
    • +
    • void pushMiddle(int val) 将 val 添加到队列的 正中间 。
    • +
    • void pushBack(int val) 将 val 添加到队里的 最后面 。
    • +
    • int popFront() 将 最前面 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1 。
    • +
    • int popMiddle()正中间 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1 。
    • +
    • int popBack()最后面 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1 。
    • +
    + +

    请注意当有 两个 中间位置的时候,选择靠前面的位置进行操作。比方说:

    + +
      +
    • 6 添加到 [1, 2, 3, 4, 5] 的中间位置,结果数组为 [1, 2, 6, 3, 4, 5] 。
    • +
    • 从 [1, 2, 3, 4, 5, 6] 的中间位置弹出元素,返回 3 ,数组变为 [1, 2, 4, 5, 6] 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
    +[[], [1], [2], [3], [4], [], [], [], [], []]
    +输出:
    +[null, null, null, null, null, 1, 3, 4, 2, -1]
    +
    +解释:
    +FrontMiddleBackQueue q = new FrontMiddleBackQueue();
    +q.pushFront(1);   // [1]
    +q.pushBack(2);    // [1, 2]
    +q.pushMiddle(3);  // [1, 3, 2]
    +q.pushMiddle(4);  // [1, 4, 3, 2]
    +q.popFront();     // 返回 1 -> [4, 3, 2]
    +q.popMiddle();    // 返回 3 -> [4, 2]
    +q.popMiddle();    // 返回 4 -> [2]
    +q.popBack();      // 返回 2 -> []
    +q.popFront();     // 返回 -1 -> [] (队列为空)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= val <= 109
    • +
    • 最多调用 1000 次 pushFront, pushMiddle, pushBack, popFront, popMiddle 和 popBack
    • +
    + +## 解法 + + + +两个“双端队列”实现。 + + + +### **Python3** + + + +```python +class FrontMiddleBackQueue: + + def __init__(self): + self.left = collections.deque() + self.right = collections.deque() + + def pushFront(self, val: int) -> None: + self.left.appendleft(val) + self.rebalance() + + def pushMiddle(self, val: int) -> None: + self.left.append(val) + self.rebalance() + + def pushBack(self, val: int) -> None: + self.right.append(val) + self.rebalance() + + def popFront(self) -> int: + if self.empty(): + return -1 + if self.left: + val = self.left.popleft() + else: + val = self.right.popleft() + self.rebalance() + return val + + def popMiddle(self) -> int: + if self.empty(): + return -1 + if len(self.left) >= len(self.right): + val = self.left.pop() + else: + val = self.right.popleft() + self.rebalance() + return val + + def popBack(self) -> int: + if self.empty(): + return -1 + val = self.right.pop() + self.rebalance() + return val + + def empty(self) -> bool: + return not self.left and not self.right + + def rebalance(self) -> None: + while len(self.left) > len(self.right): + self.right.appendleft(self.left.pop()) + while len(self.right) - len(self.left) > 1: + self.left.append(self.right.popleft()) + + +# Your FrontMiddleBackQueue object will be instantiated and called as such: +# obj = FrontMiddleBackQueue() +# obj.pushFront(val) +# obj.pushMiddle(val) +# obj.pushBack(val) +# param_4 = obj.popFront() +# param_5 = obj.popMiddle() +# param_6 = obj.popBack() +``` + +### **Java** + + + +```java +class FrontMiddleBackQueue { + private Deque left; + private Deque right; + + public FrontMiddleBackQueue() { + left = new LinkedList<>(); + right = new LinkedList<>(); + } + + public void pushFront(int val) { + left.offerFirst(val); + rebalance(); + } + + public void pushMiddle(int val) { + left.offerLast(val); + rebalance(); + } + + public void pushBack(int val) { + right.offerLast(val); + rebalance(); + } + + public int popFront() { + if (empty()) { + return -1; + } + int val = left.isEmpty() ? right.pollFirst() : left.pollFirst(); + rebalance(); + return val; + } + + public int popMiddle() { + if (empty()) { + return -1; + } + int val = left.size() >= right.size() ? left.pollLast() : right.pollFirst(); + rebalance(); + return val; + } + + public int popBack() { + if (empty()) { + return -1; + } + int val = right.pollLast(); + rebalance(); + return val; + } + + private boolean empty() { + return left.isEmpty() && right.isEmpty(); + } + + private void rebalance() { + while (left.size() > right.size()) { + right.offerFirst(left.pollLast()); + } + while (right.size() - left.size() > 1) { + left.offerLast(right.pollFirst()); + } + } +} + +/** + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * FrontMiddleBackQueue obj = new FrontMiddleBackQueue(); + * obj.pushFront(val); + * obj.pushMiddle(val); + * obj.pushBack(val); + * int param_4 = obj.popFront(); + * int param_5 = obj.popMiddle(); + * int param_6 = obj.popBack(); + */ +``` + +### **JavaScript** + +```js +var FrontMiddleBackQueue = function() { + this.left = []; + this.right = []; +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushFront = function(val) { + this.left.unshift(val); + this.rebalance(); +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushMiddle = function(val) { + this.left.push(val); + this.rebalance(); +}; + +/** + * @param {number} val + * @return {void} + */ +FrontMiddleBackQueue.prototype.pushBack = function(val) { + this.right.push(val); + this.rebalance(); +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popFront = function() { + if (this.isEmpty()) return -1; + let num = this.left.length == 0 ? this.right.shift() : this.left.shift(); + this.rebalance(); + return num; +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popMiddle = function() { + if (this.isEmpty()) return -1; + let num = this.left.length == this.right.length ? this.left.pop() : this.right.shift(); + this.rebalance(); + return num; +}; + +/** + * @return {number} + */ +FrontMiddleBackQueue.prototype.popBack = function() { + if (this.isEmpty()) return -1; + let num = this.right.pop(); + this.rebalance(); + return num; +}; + +FrontMiddleBackQueue.prototype.rebalance = function () { + while (this.left.length > this.right.length) { + this.right.unshift(this.left.pop()); + } + while (this.right.length > this.left.length + 1) { + this.left.push(this.right.shift()); + } +} + +FrontMiddleBackQueue.prototype.isEmpty = function () { + return this.left.length == 0 && this.right.length == 0; +} + +/** + * Your FrontMiddleBackQueue object will be instantiated and called as such: + * var obj = new FrontMiddleBackQueue() + * obj.pushFront(val) + * obj.pushMiddle(val) + * obj.pushBack(val) + * var param_4 = obj.popFront() + * var param_5 = obj.popMiddle() + * var param_6 = obj.popBack() + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1671.leetcode1671 Minimum Number of Removals to Make Mountain Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1671.leetcode1671 Minimum Number of Removals to Make Mountain Array-zh.md" new file mode 100644 index 00000000..b58013d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1671.leetcode1671 Minimum Number of Removals to Make Mountain Array-zh.md" @@ -0,0 +1,90 @@ +# [1671. 得到山形数组的最少删除次数](https://leetcode-cn.com/problems/minimum-number-of-removals-to-make-mountain-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1671.Minimum%20Number%20of%20Removals%20to%20Make%20Mountain%20Array/README_EN.md) + +## 题目描述 + + + +

    我们定义 arr 是 山形数组 当且仅当它满足:

    + +
      +
    • arr.length >= 3
    • +
    • 存在某个下标 i (从 0 开始) 满足 0 < i < arr.length - 1 且: +
        +
      • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
      • +
      • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
      • +
      +
    • +
    + +

    给你整数数组 nums​ ,请你返回将 nums 变成 山形状数组 的​ 最少 删除次数。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,3,1]
    +输出:0
    +解释:数组本身就是山形数组,所以我们不需要删除任何元素。
    +
    + +

    示例 2:

    + +
    输入:nums = [2,1,1,5,6,2,3,1]
    +输出:3
    +解释:一种方法是将下标为 0,1 和 5 的元素删除,剩余元素为 [1,5,6,3,1] ,是山形数组。
    +
    + +

    示例 3:

    + +
    输入:nums = [4,3,2,1,1,2,3,1]
    +输出:4
    +
    + +

    提示:

    + +
    输入:nums = [1,2,3,4,4,3,2,1]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 109
    • +
    • 题目保证 nums 删除一些元素后一定能得到山形数组。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1672.leetcode1672 Richest Customer Wealth-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1672.leetcode1672 Richest Customer Wealth-zh.md" new file mode 100644 index 00000000..610d556f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1672.leetcode1672 Richest Customer Wealth-zh.md" @@ -0,0 +1,135 @@ +# [1672. 最富有客户的资产总量](https://leetcode-cn.com/problems/richest-customer-wealth) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1672.Richest%20Customer%20Wealth/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的整数网格 accounts ,其中 accounts[i][j] 是第 i​​​​​​​​​​​ 位客户在第 j 家银行托管的资产数量。返回最富有客户所拥有的 资产总量

    + +

    客户的 资产总量 就是他们在各家银行托管的资产数量之和。最富有客户就是 资产总量 最大的客户。

    + +

     

    + +

    示例 1:

    + +
    输入:accounts = [[1,2,3],[3,2,1]]
    +输出:6
    +解释:
    +第 1 位客户的资产总量 = 1 + 2 + 3 = 6
    +第 2 位客户的资产总量 = 3 + 2 + 1 = 6
    +两位客户都是最富有的,资产总量都是 6 ,所以返回 6 。
    +
    + +

    示例 2:

    + +
    输入:accounts = [[1,5],[7,3],[3,5]]
    +输出:10
    +解释:
    +第 1 位客户的资产总量 = 6
    +第 2 位客户的资产总量 = 10 
    +第 3 位客户的资产总量 = 8
    +第 2 位客户是最富有的,资产总量是 10
    + +

    示例 3:

    + +
    输入:accounts = [[2,8,7],[7,1,3],[1,9,5]]
    +输出:17
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == accounts.length
    • +
    • n == accounts[i].length
    • +
    • 1 <= m, n <= 50
    • +
    • 1 <= accounts[i][j] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maximumWealth(self, accounts: List[List[int]]) -> int: + res = 0 + for account in accounts: + res = max(res, sum(account)) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maximumWealth(int[][] accounts) { + int res = 0; + for (int[] account : accounts) { + int t = 0; + for (int money : account) { + t += money; + } + res = Math.max(res, t); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maximumWealth(vector>& accounts) { + int res = 0; + for (auto& account : accounts) { + int t = 0; + for (auto& money : account) { + t += money; + } + res = max(res, t); + } + return res; + } +}; +``` + +### **Go** + +```go +func maximumWealth(accounts [][]int) int { + res := 0 + for _, account := range accounts { + t := 0 + for _, money := range account { + t += money + } + if t > res { + res = t + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1673.leetcode1673 Find the Most Competitive Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1673.leetcode1673 Find the Most Competitive Subsequence-zh.md" new file mode 100644 index 00000000..d636afd8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1673.leetcode1673 Find the Most Competitive Subsequence-zh.md" @@ -0,0 +1,71 @@ +# [1673. 找出最具竞争力的子序列](https://leetcode-cn.com/problems/find-the-most-competitive-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1673.Find%20the%20Most%20Competitive%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个正整数 k ,返回长度为 k 且最具 竞争力 nums 子序列。

    + +

    数组的子序列是从数组中删除一些元素(可能不删除元素)得到的序列。

    + +

    在子序列 a 和子序列 b 第一个不相同的位置上,如果 a 中的数字小于 b 中对应的数字,那么我们称子序列 a 比子序列 b(相同长度下)更具 竞争力 。 例如,[1,3,4][1,3,5] 更具竞争力,在第一个不相同的位置,也就是最后一个位置上, 4 小于 5

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3,5,2,6], k = 2
    +输出:[2,6]
    +解释:在所有可能的子序列集合 {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]} 中,[2,6] 最具竞争力。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,4,3,3,5,4,9,6], k = 4
    +输出:[2,3,3,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 0 <= nums[i] <= 109
    • +
    • 1 <= k <= nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1674.leetcode1674 Minimum Moves to Make Array Complementary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1674.leetcode1674 Minimum Moves to Make Array Complementary-zh.md" new file mode 100644 index 00000000..16c1d53b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1674.leetcode1674 Minimum Moves to Make Array Complementary-zh.md" @@ -0,0 +1,86 @@ +# [1674. 使数组互补的最少操作次数](https://leetcode-cn.com/problems/minimum-moves-to-make-array-complementary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1674.Minimum%20Moves%20to%20Make%20Array%20Complementary/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 偶数 n 的整数数组 nums 和一个整数 limit 。每一次操作,你可以将 nums 中的任何整数替换为 1 到 limit 之间的另一个整数。

    + +

    如果对于所有下标 i下标从 0 开始),nums[i] + nums[n - 1 - i] 都等于同一个数,则数组 nums互补的 。例如,数组 [1,2,3,4] 是互补的,因为对于所有下标 inums[i] + nums[n - 1 - i] = 5

    + +

    返回使数组 互补最少 操作次数。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,4,3], limit = 4
    +输出:1
    +解释:经过 1 次操作,你可以将数组 nums 变成 [1,2,2,3](加粗元素是变更的数字):
    +nums[0] + nums[3] = 1 + 3 = 4.
    +nums[1] + nums[2] = 2 + 2 = 4.
    +nums[2] + nums[1] = 2 + 2 = 4.
    +nums[3] + nums[0] = 3 + 1 = 4.
    +对于每个 i ,nums[i] + nums[n-1-i] = 4 ,所以 nums 是互补的。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,2,1], limit = 2
    +输出:2
    +解释:经过 2 次操作,你可以将数组 nums 变成 [2,2,2,2] 。你不能将任何数字变更为 3 ,因为 3 > limit 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,2,1,2], limit = 2
    +输出:0
    +解释:nums 已经是互补的。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 2 <= n <= 105
    • +
    • 1 <= nums[i] <= limit <= 105
    • +
    • n 是偶数。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1675.leetcode1675 Minimize Deviation in Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1675.leetcode1675 Minimize Deviation in Array-zh.md" new file mode 100644 index 00000000..050f8d35 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1675.leetcode1675 Minimize Deviation in Array-zh.md" @@ -0,0 +1,92 @@ +# [1675. 数组的最小偏移量](https://leetcode-cn.com/problems/minimize-deviation-in-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1675.Minimize%20Deviation%20in%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个由 n 个正整数组成的数组 nums

    + +

    你可以对数组的任意元素执行任意次数的两类操作:

    + +
      +
    • 如果元素是 偶数除以 2 + +
        +
      • 例如,如果数组是 [1,2,3,4] ,那么你可以对最后一个元素执行此操作,使其变成 [1,2,3,2]
      • +
      +
    • +
    • 如果元素是 奇数乘上 2 +
        +
      • 例如,如果数组是 [1,2,3,4] ,那么你可以对第一个元素执行此操作,使其变成 [2,2,3,4]
      • +
      +
    • +
    + +

    数组的 偏移量 是数组中任意两个元素之间的 最大差值

    + +

    返回数组在执行某些操作之后可以拥有的 最小偏移量

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,4]
    +输出:1
    +解释:你可以将数组转换为 [1,2,3,2],然后转换成 [2,2,3,2],偏移量是 3 - 2 = 1
    +
    + +

    示例 2:

    + +
    输入:nums = [4,1,5,20,3]
    +输出:3
    +解释:两次操作后,你可以将数组转换为 [4,2,5,5,3],偏移量是 5 - 2 = 3
    +
    + +

    示例 3:

    + +
    输入:nums = [2,10,8]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 2 <= n <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1676.leetcode1676 Lowest Common Ancestor of a Binary Tree IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1676.leetcode1676 Lowest Common Ancestor of a Binary Tree IV-zh.md" new file mode 100644 index 00000000..af51b602 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1676.leetcode1676 Lowest Common Ancestor of a Binary Tree IV-zh.md" @@ -0,0 +1,85 @@ +# [1676. 二叉树的最近公共祖先 IV](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1676.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree%20IV/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树的根节点 root 和 TreeNode 类对象的数组(列表) nodes,返回 nodes 中所有节点的最近公共祖先(LCA)。数组(列表)中所有节点都存在于该二叉树中,且二叉树中所有节点的值都是互不相同的。

    + +

    我们扩展二叉树的最近公共祖先节点在维基百科上的定义:“对于任意合理的 i 值, n 个节点 p1 、 p2、...、 pn 在二叉树 T 中的最近公共祖先节点是后代中包含所有节点 pi 的最深节点(我们允许一个节点是其自身的后代)”。一个节点 x 的后代节点是节点 x 到某一叶节点间的路径中的节点 y

    + +

     

    + +

    示例 1:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
    +输出: 2
    +解释: 节点 4 和 7 的最近公共祖先是 2。
    +
    + +

    示例 2:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1]
    +输出: 1
    +解释: 单个节点的最近公共祖先是该节点本身。
    +
    +
    + +

    示例 3:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [7,6,2,4]
    +输出: 5
    +解释: 节点 7、6、2 和 4 的最近公共祖先节点是 5。
    +
    + +

    示例 4:

    + +
    输入: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [0,1,2,3,4,5,6,7,8]
    +输出: 3
    +解释: 树中所有节点的最近公共祖先是根节点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 树中节点个数的范围是 [1, 104] 。
    • +
    • -109 <= Node.val <= 109
    • +
    • 所有的 Node.val 都是互不相同的。
    • +
    • 所有的 nodes[i] 都存在于该树中。
    • +
    • 所有的 nodes[i] 都是互不相同的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1677.leetcode1677 Product's Worth Over Invoices-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1677.leetcode1677 Product's Worth Over Invoices-zh.md" new file mode 100644 index 00000000..f54869e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1677.leetcode1677 Product's Worth Over Invoices-zh.md" @@ -0,0 +1,102 @@ +# [1677. 发票中的产品金额](https://leetcode-cn.com/problems/products-worth-over-invoices) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1677.Product%27s%20Worth%20Over%20Invoices/README_EN.md) + +## 题目描述 + + + +

    Product 表:

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_id  | int     |
    +| name        | varchar |
    ++-------------+---------+
    +product_id 是这张表的主键
    +表中含有产品 id 、产品名称。产品名称都是小写的英文字母,产品名称都是唯一的
    +
    + +

     

    + +

    Invoice 表:

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| invoice_id  | int  |
    +| product_id  | int  |
    +| rest        | int  |
    +| paid        | int  |
    +| canceled    | int  |
    +| refunded    | int  |
    ++-------------+------+
    +invoice_id 发票 id ,是这张表的主键
    +product_id 产品 id
    +rest 应缴款项
    +paid 已支付金额
    +canceled 已取消金额
    +refunded 已退款金额
    +
    + +

     

    + +

    要求写一个SQL查询,返回全部发票中每个产品的产品名称、总应缴款项、总已支付金额、总已取消金额、总已退款金额

    + +

    查询结果按 product_name排序

    + +

    示例:

    + +
    +Product 表:
    ++------------+-------+
    +| product_id | name  |
    ++------------+-------+
    +| 0          | ham   |
    +| 1          | bacon |
    ++------------+-------+
    +Invoice table:
    ++------------+------------+------+------+----------+----------+
    +| invoice_id | product_id | rest | paid | canceled | refunded |
    ++------------+------------+------+------+----------+----------+
    +| 23         | 0          | 2    | 0    | 5        | 0        |
    +| 12         | 0          | 0    | 4    | 0        | 3        |
    +| 1          | 1          | 1    | 1    | 0        | 1        |
    +| 2          | 1          | 1    | 0    | 1        | 1        |
    +| 3          | 1          | 0    | 1    | 1        | 1        |
    +| 4          | 1          | 1    | 1    | 1        | 0        |
    ++------------+------------+------+------+----------+----------+
    +Result 表:
    ++-------+------+------+----------+----------+
    +| name  | rest | paid | canceled | refunded |
    ++-------+------+------+----------+----------+
    +| bacon | 3    | 3    | 3        | 3        |
    +| ham   | 2    | 4    | 5        | 3        |
    ++-------+------+------+----------+----------+
    +- bacon 的总应缴款项为 1 + 1 + 0 + 1 = 3
    +- bacon 的总已支付金额为 1 + 0 + 1 + 1 = 3
    +- bacon 的总已取消金额为 0 + 1 + 1 + 1 = 3
    +- bacon 的总已退款金额为 1 + 1 + 1 + 0 = 3
    +- ham 的总应缴款项为 2 + 0 = 2
    +- ham 的总已支付金额为 0 + 4 = 4
    +- ham 的总已取消金额为 5 + 0 = 5
    +- ham 的总已退款金额为 0 + 3 = 3
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1678.leetcode1678 Goal Parser Interpretation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1678.leetcode1678 Goal Parser Interpretation-zh.md" new file mode 100644 index 00000000..480f4eb3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1678.leetcode1678 Goal Parser Interpretation-zh.md" @@ -0,0 +1,76 @@ +# [1678. 设计 Goal 解析器](https://leetcode-cn.com/problems/goal-parser-interpretation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1678.Goal%20Parser%20Interpretation/README_EN.md) + +## 题目描述 + + + +

    请你设计一个可以解释字符串 commandGoal 解析器command"G""()" 和/或 "(al)" 按某种顺序组成。Goal 解析器会将 "G" 解释为字符串 "G""()" 解释为字符串 "o""(al)" 解释为字符串 "al" 。然后,按原顺序将经解释得到的字符串连接成一个字符串。

    + +

    给你字符串 command ,返回 Goal 解析器 command 的解释结果。

    + +

     

    + +

    示例 1:

    + +
    输入:command = "G()(al)"
    +输出:"Goal"
    +解释:Goal 解析器解释命令的步骤如下所示:
    +G -> G
    +() -> o
    +(al) -> al
    +最后连接得到的结果是 "Goal"
    +
    + +

    示例 2:

    + +
    输入:command = "G()()()()(al)"
    +输出:"Gooooal"
    +
    + +

    示例 3:

    + +
    输入:command = "(al)G(al)()()G"
    +输出:"alGalooG"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= command.length <= 100
    • +
    • command"G""()" 和/或 "(al)" 按某种顺序组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1679.leetcode1679 Max Number of K-Sum Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1679.leetcode1679 Max Number of K-Sum Pairs-zh.md" new file mode 100644 index 00000000..74be212b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1679.leetcode1679 Max Number of K-Sum Pairs-zh.md" @@ -0,0 +1,75 @@ +# [1679. K 和数对的最大数目](https://leetcode-cn.com/problems/max-number-of-k-sum-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1679.Max%20Number%20of%20K-Sum%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 k

    + +

    每一步操作中,你需要从数组中选出和为 k 的两个整数,并将它们移出数组。

    + +

    返回你可以对数组执行的最大操作数。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,4], k = 5
    +输出:2
    +解释:开始时 nums = [1,2,3,4]:
    +- 移出 1 和 4 ,之后 nums = [2,3]
    +- 移出 2 和 3 ,之后 nums = []
    +不再有和为 5 的数对,因此最多执行 2 次操作。
    + +

    示例 2:

    + +
    +输入:nums = [3,1,3,4,3], k = 6
    +输出:1
    +解释:开始时 nums = [3,1,3,4,3]:
    +- 移出前两个 3 ,之后nums = [1,4,3]
    +不再有和为 6 的数对,因此最多执行 1 次操作。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • 1 <= k <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1680.leetcode1680 Concatenation of Consecutive Binary Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1680.leetcode1680 Concatenation of Consecutive Binary Numbers-zh.md" new file mode 100644 index 00000000..1979d96a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1680.leetcode1680 Concatenation of Consecutive Binary Numbers-zh.md" @@ -0,0 +1,74 @@ +# [1680. 连接连续二进制数字](https://leetcode-cn.com/problems/concatenation-of-consecutive-binary-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1680.Concatenation%20of%20Consecutive%20Binary%20Numbers/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n ,请你将 1 到 n 的二进制表示连接起来,并返回连接结果对应的 十进制 数字对 109 + 7 取余的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 1
    +输出:1
    +解释:二进制的 "1" 对应着十进制的 1 。
    +
    + +

    示例 2:

    + +
    输入:n = 3
    +输出:27
    +解释:二进制下,1,2 和 3 分别对应 "1" ,"10" 和 "11" 。
    +将它们依次连接,我们得到 "11011" ,对应着十进制的 27 。
    +
    + +

    示例 3:

    + +
    输入:n = 12
    +输出:505379714
    +解释:连接结果为 "1101110010111011110001001101010111100" 。
    +对应的十进制数字为 118505380540 。
    +对 109 + 7 取余后,结果为 505379714 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1681.leetcode1681 Minimum Incompatibility-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1681.leetcode1681 Minimum Incompatibility-zh.md" new file mode 100644 index 00000000..5c77330e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1681.leetcode1681 Minimum Incompatibility-zh.md" @@ -0,0 +1,84 @@ +# [1681. 最小不兼容性](https://leetcode-cn.com/problems/minimum-incompatibility) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1681.Minimum%20Incompatibility/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums​​​ 和一个整数 k 。你需要将这个数组划分到 k 个相同大小的子集中,使得同一个子集里面没有两个相同的元素。

    + +

    一个子集的 不兼容性 是该子集里面最大值和最小值的差。

    + +

    请你返回将数组分成 k 个子集后,各子集 不兼容性  的 最小值 ,如果无法分成分成 k 个子集,返回 -1 。

    + +

    子集的定义是数组中一些数字的集合,对数字顺序没有要求。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,1,4], k = 2
    +输出:4
    +解释:最优的分配是 [1,2] 和 [1,4] 。
    +不兼容性和为 (2-1) + (4-1) = 4 。
    +注意到 [1,1] 和 [2,4] 可以得到更小的和,但是第一个集合有 2 个相同的元素,所以不可行。
    + +

    示例 2:

    + +
    +输入:nums = [6,3,8,1,3,1,2,2], k = 4
    +输出:6
    +解释:最优的子集分配为 [1,2],[2,3],[6,8] 和 [1,3] 。
    +不兼容性和为 (2-1) + (3-2) + (8-6) + (3-1) = 6 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [5,3,3,6,3,3], k = 3
    +输出:-1
    +解释:没办法将这些数字分配到 3 个子集且满足每个子集里没有相同数字。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= nums.length <= 16
    • +
    • nums.length 能被 k 整除。
    • +
    • 1 <= nums[i] <= nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1682.leetcode1682 Longest Palindromic Subsequence II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1682.leetcode1682 Longest Palindromic Subsequence II-zh.md" new file mode 100644 index 00000000..c9d1ad39 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1682.leetcode1682 Longest Palindromic Subsequence II-zh.md" @@ -0,0 +1,76 @@ +# [1682. 最长回文子序列 II](https://leetcode-cn.com/problems/longest-palindromic-subsequence-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1682.Longest%20Palindromic%20Subsequence%20II/README_EN.md) + +## 题目描述 + + + +

    字符串 s 的某个子序列符合下列条件时,称为“好的回文子序列”:

    + +
      +
    • 它是 s 的子序列。
    • +
    • 它是回文序列(反转后与原序列相等)。
    • +
    • 长度为偶数
    • +
    • 除中间的两个字符外,其余任意两个连续字符不相等。
    • +
    + +

    例如,若 s = "abcabcabb",则 "abba" 可称为“好的回文子序列”,而 "bcb" (长度不是偶数)和 "bbbb" (含有相等的连续字符)不能称为“好的回文子序列”。

    + +

    给定一个字符串 s, 返回 s 的最长“好的回文子序列”长度

    + +

     

    + +

    示例 1:

    + +
    输入: s = "bbabab"
    +输出: 4
    +解释: s 的最长“好的回文子序列”是 "baab"。
    +
    + +

    示例 2:

    + +
    输入: s = "dcbccacdb"
    +输出: 4
    +解释: The longest good palindromic subsequence of s is "dccd".
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 250
    • +
    • s 包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1683.leetcode1683 Invalid Tweets-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1683.leetcode1683 Invalid Tweets-zh.md" new file mode 100644 index 00000000..1093b0da --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1683.leetcode1683 Invalid Tweets-zh.md" @@ -0,0 +1,71 @@ +# [1683. 无效的推文](https://leetcode-cn.com/problems/invalid-tweets) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1683.Invalid%20Tweets/README_EN.md) + +## 题目描述 + + + +

    表:Tweets

    + +
    +----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| tweet_id       | int     |
    +| content        | varchar |
    ++----------------+---------+
    +tweet_id 是这个表的主键。
    +这个表包含某社交媒体 App 中所有的推文。
    + +

     

    + +

    写一条 SQL 语句,查询所有无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。

    + +

    任意顺序返回结果表。

    + +

    查询结果格式如下示例所示:

    + +

     

    + +
    Tweets 表:
    ++----------+----------------------------------+
    +| tweet_id | content                          |
    ++----------+----------------------------------+
    +| 1        | Vote for Biden                   |
    +| 2        | Let us make America great again! |
    ++----------+----------------------------------+
    +
    +结果表:
    ++----------+
    +| tweet_id |
    ++----------+
    +| 2        |
    ++----------+
    +推文 1 的长度 length = 14。该推文是有效的。
    +推文 2 的长度 length = 32。该推文是无效的。
    +
    + +## 解法 + + + +- `CHAR_LENGTH(str)`: 中文、数字、字母都是 1 字节 +- `LENGTH(str)`: + - utf8: 中文 3 字节,数字、字母 1 字节 + - gbk: 中文 2 字节,数字、字母 1 字节 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + tweet_id +FROM + Tweets +WHERE + CHAR_LENGTH(content) > 15; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1684.leetcode1684 Count the Number of Consistent Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1684.leetcode1684 Count the Number of Consistent Strings-zh.md" new file mode 100644 index 00000000..b008f183 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1684.leetcode1684 Count the Number of Consistent Strings-zh.md" @@ -0,0 +1,80 @@ +# [1684. 统计一致字符串的数目](https://leetcode-cn.com/problems/count-the-number-of-consistent-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1684.Count%20the%20Number%20of%20Consistent%20Strings/README_EN.md) + +## 题目描述 + + + +

    给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串

    + +

    请你返回 words 数组中 一致字符串 的数目。

    + +

     

    + +

    示例 1:

    + +
    +输入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
    +输出:2
    +解释:字符串 "aaab" 和 "baa" 都是一致字符串,因为它们只包含字符 'a' 和 'b' 。
    +
    + +

    示例 2:

    + +
    +输入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
    +输出:7
    +解释:所有字符串都是一致的。
    +
    + +

    示例 3:

    + +
    +输入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
    +输出:4
    +解释:字符串 "cc","acd","ac" 和 "d" 是一致字符串。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 104
    • +
    • 1 <= allowed.length <= 26
    • +
    • 1 <= words[i].length <= 10
    • +
    • allowed 中的字符 互不相同 。
    • +
    • words[i] 和 allowed 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1685.leetcode1685 Sum of Absolute Differences in a Sorted Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1685.leetcode1685 Sum of Absolute Differences in a Sorted Array-zh.md" new file mode 100644 index 00000000..48c964af --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1685.leetcode1685 Sum of Absolute Differences in a Sorted Array-zh.md" @@ -0,0 +1,73 @@ +# [1685. 有序数组中差绝对值之和](https://leetcode-cn.com/problems/sum-of-absolute-differences-in-a-sorted-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1685.Sum%20of%20Absolute%20Differences%20in%20a%20Sorted%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个 非递减 有序整数数组 nums 。

    + +

    请你建立并返回一个整数数组 result,它跟 nums 长度相同,且result[i] 等于 nums[i] 与数组中所有其他元素差的绝对值之和。

    + +

    换句话说, result[i] 等于 sum(|nums[i]-nums[j]|) ,其中 0 <= j < nums.length 且 j != i (下标从 0 开始)。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,3,5]
    +输出:[4,3,5]
    +解释:假设数组下标从 0 开始,那么
    +result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
    +result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
    +result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,4,6,8,10]
    +输出:[24,15,13,15,21]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= nums[i + 1] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1686.leetcode1686 Stone Game VI-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1686.leetcode1686 Stone Game VI-zh.md" new file mode 100644 index 00000000..bc7b64f6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1686.leetcode1686 Stone Game VI-zh.md" @@ -0,0 +1,98 @@ +# [1686. 石子游戏 VI](https://leetcode-cn.com/problems/stone-game-vi) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1686.Stone%20Game%20VI/README_EN.md) + +## 题目描述 + + + +

    Alice 和 Bob 轮流玩一个游戏,Alice 先手。

    + +

    一堆石子里总共有 n 个石子,轮到某个玩家时,他可以 移出 一个石子并得到这个石子的价值。Alice 和 Bob 对石子价值有 不一样的的评判标准 。双方都知道对方的评判标准。

    + +

    给你两个长度为 n 的整数数组 aliceValues 和 bobValues 。aliceValues[i] 和 bobValues[i] 分别表示 Alice 和 Bob 认为第 i 个石子的价值。

    + +

    所有石子都被取完后,得分较高的人为胜者。如果两个玩家得分相同,那么为平局。两位玩家都会采用 最优策略 进行游戏。

    + +

    请你推断游戏的结果,用如下的方式表示:

    + +
      +
    • 如果 Alice 赢,返回 1 。
    • +
    • 如果 Bob 赢,返回 -1 。
    • +
    • 如果游戏平局,返回 0 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:aliceValues = [1,3], bobValues = [2,1]
    +输出:1
    +解释:
    +如果 Alice 拿石子 1 (下标从 0开始),那么 Alice 可以得到 3 分。
    +Bob 只能选择石子 0 ,得到 2 分。
    +Alice 获胜。
    +
    + +

    示例 2:

    + +
    +输入:aliceValues = [1,2], bobValues = [3,1]
    +输出:0
    +解释:
    +Alice 拿石子 0 , Bob 拿石子 1 ,他们得分都为 1 分。
    +打平。
    +
    + +

    示例 3:

    + +
    +输入:aliceValues = [2,4,3], bobValues = [1,6,7]
    +输出:-1
    +解释:
    +不管 Alice 怎么操作,Bob 都可以得到比 Alice 更高的得分。
    +比方说,Alice 拿石子 1 ,Bob 拿石子 2 , Alice 拿石子 0 ,Alice 会得到 6 分而 Bob 得分为 7 分。
    +Bob 会获胜。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == aliceValues.length == bobValues.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= aliceValues[i], bobValues[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1687.leetcode1687 Delivering Boxes from Storage to Ports-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1687.leetcode1687 Delivering Boxes from Storage to Ports-zh.md" new file mode 100644 index 00000000..b6e31d66 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1687.leetcode1687 Delivering Boxes from Storage to Ports-zh.md" @@ -0,0 +1,119 @@ +# [1687. 从仓库到码头运输箱子](https://leetcode-cn.com/problems/delivering-boxes-from-storage-to-ports) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1687.Delivering%20Boxes%20from%20Storage%20to%20Ports/README_EN.md) + +## 题目描述 + + + +

    你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。

    + +

    给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [ports​​i​, weighti] 。

    + +
      +
    • ports​​i 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。
    • +
    • portsCount 是码头的数目。
    • +
    • maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。
    • +
    + +

    箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤:

    + +
      +
    • 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。
    • +
    • 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 ,箱子也会立马被卸货。
    • +
    • 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。
    • +
    + +

    卡车在将所有箱子运输并卸货后,最后必须回到仓库。

    + +

    请你返回将所有箱子送到相应码头的 最少行程 次数。

    + +

     

    + +

    示例 1:

    + +
    输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
    +输出:4
    +解释:最优策略如下:
    +- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。
    +所以总行程数为 4 。
    +注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。
    +
    + +

    示例 2:

    + +
    输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
    +输出:6
    +解释:最优策略如下:
    +- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。
    +总行程数为 2 + 2 + 2 = 6 。
    +
    + +

    示例 3:

    + +
    输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7
    +输出:6
    +解释:最优策略如下:
    +- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
    +总行程数为 2 + 2 + 2 = 6 。
    +
    + +

    示例 4:

    + +
    输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], portsCount = 5, maxBoxes = 5, maxWeight = 7
    +输出:14
    +解释:最优策略如下:
    +- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
    +- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。
    +- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。
    +总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= boxes.length <= 105
    • +
    • 1 <= portsCount, maxBoxes, maxWeight <= 105
    • +
    • 1 <= ports​​i <= portsCount
    • +
    • 1 <= weightsi <= maxWeight
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1688.leetcode1688 Count of Matches in Tournament-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1688.leetcode1688 Count of Matches in Tournament-zh.md" new file mode 100644 index 00000000..903fe6c9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1688.leetcode1688 Count of Matches in Tournament-zh.md" @@ -0,0 +1,80 @@ +# [1688. 比赛中的配对次数](https://leetcode-cn.com/problems/count-of-matches-in-tournament) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1688.Count%20of%20Matches%20in%20Tournament/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n ,表示比赛中的队伍数。比赛遵循一种独特的赛制:

    + +
      +
    • 如果当前队伍数是 偶数 ,那么每支队伍都会与另一支队伍配对。总共进行 n / 2 场比赛,且产生 n / 2 支队伍进入下一轮。
    • +
    • 如果当前队伍数为 奇数 ,那么将会随机轮空并晋级一支队伍,其余的队伍配对。总共进行 (n - 1) / 2 场比赛,且产生 (n - 1) / 2 + 1 支队伍进入下一轮。
    • +
    + +

    返回在比赛中进行的配对次数,直到决出获胜队伍为止。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 7
    +输出:6
    +解释:比赛详情:
    +- 第 1 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。
    +- 第 2 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。
    +- 第 3 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。
    +总配对次数 = 3 + 2 + 1 = 6
    +
    + +

    示例 2:

    + +
    输入:n = 14
    +输出:13
    +解释:比赛详情:
    +- 第 1 轮:队伍数 = 14 ,配对次数 = 7 ,7 支队伍晋级。
    +- 第 2 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。 
    +- 第 3 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。
    +- 第 4 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。
    +总配对次数 = 7 + 3 + 2 + 1 = 13
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 200
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1689.leetcode1689 Partitioning Into Minimum Number Of Deci-Binary Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1689.leetcode1689 Partitioning Into Minimum Number Of Deci-Binary Numbers-zh.md" new file mode 100644 index 00000000..7372f032 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1689.leetcode1689 Partitioning Into Minimum Number Of Deci-Binary Numbers-zh.md" @@ -0,0 +1,124 @@ +# [1689. 十-二进制数的最少数目](https://leetcode-cn.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1689.Partitioning%20Into%20Minimum%20Number%20Of%20Deci-Binary%20Numbers/README_EN.md) + +## 题目描述 + + + +

    如果一个十进制数字不含任何前导零,且每一位上的数字不是 0 就是 1 ,那么该数字就是一个 十-二进制数 。例如,1011100 都是 十-二进制数,而 1123001 不是。

    + +

    给你一个表示十进制整数的字符串 n ,返回和为 n十-二进制数 的最少数目。

    + +

     

    + +

    示例 1:

    + +
    输入:n = "32"
    +输出:3
    +解释:10 + 11 + 11 = 32
    +
    + +

    示例 2:

    + +
    输入:n = "82734"
    +输出:8
    +
    + +

    示例 3:

    + +
    输入:n = "27346209830709182346"
    +输出:9
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n.length <= 105
    • +
    • n 仅由数字组成
    • +
    • n 不含任何前导零并总是表示正整数
    • +
    + +## 解法 + + + +题目等价于找字符串中的最大数。 + + + +### **Python3** + + + +```python +class Solution: + def minPartitions(self, n: str) -> int: + return int(max(n)) +``` + +### **Java** + + + +```java +class Solution { + public int minPartitions(String n) { + int res = 0; + for (char c : n.toCharArray()) { + res = Math.max(res, c - '0'); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function minPartitions(n: string): number { + let nums = n.split('').map(d => parseInt(d)); + let ans = Math.max(...nums); + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int minPartitions(string n) { + int res = 0; + for (auto& c : n) { + res = max(res, c - '0'); + } + return res; + } +}; +``` + +### **Go** + +```go +func minPartitions(n string) int { + res := 0 + for _, c := range n { + t := int(c - '0') + if t > res { + res = t + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1690.leetcode1690 Stone Game VII-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1690.leetcode1690 Stone Game VII-zh.md" new file mode 100644 index 00000000..1b523de4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1690.leetcode1690 Stone Game VII-zh.md" @@ -0,0 +1,78 @@ +# [1690. 石子游戏 VII](https://leetcode-cn.com/problems/stone-game-vii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1690.Stone%20Game%20VII/README_EN.md) + +## 题目描述 + + + +

    石子游戏中,爱丽丝和鲍勃轮流进行自己的回合,爱丽丝先开始

    + +

    n 块石子排成一排。每个玩家的回合中,可以从行中 移除 最左边的石头或最右边的石头,并获得与该行中剩余石头值之 相等的得分。当没有石头可移除时,得分较高者获胜。

    + +

    鲍勃发现他总是输掉游戏(可怜的鲍勃,他总是输),所以他决定尽力 减小得分的差值 。爱丽丝的目标是最大限度地 扩大得分的差值

    + +

    给你一个整数数组 stones ,其中 stones[i] 表示 从左边开始 的第 i 个石头的值,如果爱丽丝和鲍勃都 发挥出最佳水平 ,请返回他们 得分的差值

    + +

     

    + +

    示例 1:

    + +
    +输入:stones = [5,3,1,4,2]
    +输出:6
    +解释:
    +- 爱丽丝移除 2 ,得分 5 + 3 + 1 + 4 = 13 。游戏情况:爱丽丝 = 13 ,鲍勃 = 0 ,石子 = [5,3,1,4] 。
    +- 鲍勃移除 5 ,得分 3 + 1 + 4 = 8 。游戏情况:爱丽丝 = 13 ,鲍勃 = 8 ,石子 = [3,1,4] 。
    +- 爱丽丝移除 3 ,得分 1 + 4 = 5 。游戏情况:爱丽丝 = 18 ,鲍勃 = 8 ,石子 = [1,4] 。
    +- 鲍勃移除 1 ,得分 4 。游戏情况:爱丽丝 = 18 ,鲍勃 = 12 ,石子 = [4] 。
    +- 爱丽丝移除 4 ,得分 0 。游戏情况:爱丽丝 = 18 ,鲍勃 = 12 ,石子 = [] 。
    +得分的差值 18 - 12 = 6 。
    +
    + +

    示例 2:

    + +
    +输入:stones = [7,90,5,1,100,10,10,2]
    +输出:122
    + +

     

    + +

    提示:

    + +
      +
    • n == stones.length
    • +
    • 2 <= n <= 1000
    • +
    • 1 <= stones[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1691.leetcode1691 Maximum Height by Stacking Cuboids-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1691.leetcode1691 Maximum Height by Stacking Cuboids-zh.md" new file mode 100644 index 00000000..e9dd524c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1691.leetcode1691 Maximum Height by Stacking Cuboids-zh.md" @@ -0,0 +1,91 @@ +# [1691. 堆叠长方体的最大高度](https://leetcode-cn.com/problems/maximum-height-by-stacking-cuboids) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1691.Maximum%20Height%20by%20Stacking%20Cuboids/README_EN.md) + +## 题目描述 + + + +

    给你 n 个长方体 cuboids ,其中第 i 个长方体的长宽高表示为 cuboids[i] = [widthi, lengthi, heighti]下标从 0 开始)。请你从 cuboids 选出一个 子集 ,并将它们堆叠起来。

    + +

    如果 widthi <= widthjlengthi <= lengthjheighti <= heightj ,你就可以将长方体 i 堆叠在长方体 j 上。你可以通过旋转把长方体的长宽高重新排列,以将它放在另一个长方体上。

    + +

    返回 堆叠长方体 cuboids 可以得到的 最大高度

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:cuboids = [[50,45,20],[95,37,53],[45,23,12]]
    +输出:190
    +解释:
    +第 1 个长方体放在底部,53x37 的一面朝下,高度为 95 。
    +第 0 个长方体放在中间,45x20 的一面朝下,高度为 50 。
    +第 2 个长方体放在上面,23x12 的一面朝下,高度为 45 。
    +总高度是 95 + 50 + 45 = 190 。
    +
    + +

    示例 2:

    + +
    +输入:cuboids = [[38,25,45],[76,35,3]]
    +输出:76
    +解释:
    +无法将任何长方体放在另一个上面。
    +选择第 1 个长方体然后旋转它,使 35x3 的一面朝下,其高度为 76 。
    +
    + +

    示例 3:

    + +
    +输入:cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
    +输出:102
    +解释:
    +重新排列长方体后,可以看到所有长方体的尺寸都相同。
    +你可以把 11x7 的一面朝下,这样它们的高度就是 17 。
    +堆叠长方体的最大高度为 6 * 17 = 102 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == cuboids.length
    • +
    • 1 <= n <= 100
    • +
    • 1 <= widthi, lengthi, heighti <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1692.leetcode1692 Count Ways to Distribute Candies-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1692.leetcode1692 Count Ways to Distribute Candies-zh.md" new file mode 100644 index 00000000..3fef0596 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1692.leetcode1692 Count Ways to Distribute Candies-zh.md" @@ -0,0 +1,92 @@ +# [1692. 计算分配糖果的不同方式](https://leetcode-cn.com/problems/count-ways-to-distribute-candies) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1692.Count%20Ways%20to%20Distribute%20Candies/README_EN.md) + +## 题目描述 + + + +

    现有 n不同 糖果(分别标记为 1n )和 k 个相同的手袋。请把糖果分配到各个手袋中并保证每个手袋里至少有一颗糖果。

    + +

    不考虑手袋和糖果的摆放顺序,会有多种不同的分配方式。如果某种分配方式中其中一个手袋里的糖果与另一种分配方式中所有手袋里的糖果都不相同,则认为这两种分配方式不同。

    + +

    例如,(1), (2,3) 与(2), (1,3)的分配方式是不同的,因为第一种分配方式中手袋(2,3)里的糖果2和3,在第二种分配方式中被分配到了手袋(2)(1,3) 中。

    + +

    已知整数 n 和 k, 请返回分配糖果的不同方式。返回的答案如果数值太大,请取109 + 7的模,并返回。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 3, k = 2
    +输出:3
    +解释:把糖果 3 分配到 2 个手袋中的一个,共有 3 种方式:
    +(1), (2,3)
    +(1,2), (3)
    +(1,3), (2)
    +
    + +

    示例 2:

    + +
    +输入:n = 4, k = 2
    +输出:6
    +解释:把糖果 4 分配到 2 个手袋中的一个,共有 7 种方式:
    +(1), (2,3,4)s
    +(1,2), (3,4)
    +(1,3), (2,4)
    +(1,4), (2,3)
    +(1,2,3), (4)
    +(1,2,4), (3)
    +(1,3,4), (2)
    +
    + +

    示例 3:

    + +
    +输入:n = 20, k = 5
    +输出:206085257
    +解释:把 20 颗糖果分配到 5 个手袋种,共有 1881780996 种方式。1881780996 取 109 + 7的模,等于 206085257。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= n <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1693.leetcode1693 Daily Leads and Partners-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1693.leetcode1693 Daily Leads and Partners-zh.md" new file mode 100644 index 00000000..ae037aac --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1693.leetcode1693 Daily Leads and Partners-zh.md" @@ -0,0 +1,75 @@ +# [1693. 每天的领导和合伙人](https://leetcode-cn.com/problems/daily-leads-and-partners) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1693.Daily%20Leads%20and%20Partners/README_EN.md) + +## 题目描述 + + + +

    表:DailySales

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| date_id     | date    |
    +| make_name   | varchar |
    +| lead_id     | int     |
    +| partner_id  | int     |
    ++-------------+---------+
    +该表没有主键。
    +该表包含日期、产品的名称,以及售给的领导和合伙人的编号。
    +名称只包含小写英文字母。
    + +

     

    + +

    写一条 SQL 语句,使得对于每一个 date_id 和 make_name,返回不同的 lead_id 以及不同的 partner_id 的数量。

    + +

    按任意顺序返回结果表。

    + +

    查询结果格式如下示例所示:

    + +

     

    + +
    DailySales 表:
    ++-----------+-----------+---------+------------+
    +| date_id   | make_name | lead_id | partner_id |
    ++-----------+-----------+---------+------------+
    +| 2020-12-8 | toyota    | 0       | 1          |
    +| 2020-12-8 | toyota    | 1       | 0          |
    +| 2020-12-8 | toyota    | 1       | 2          |
    +| 2020-12-7 | toyota    | 0       | 2          |
    +| 2020-12-7 | toyota    | 0       | 1          |
    +| 2020-12-8 | honda     | 1       | 2          |
    +| 2020-12-8 | honda     | 2       | 1          |
    +| 2020-12-7 | honda     | 0       | 1          |
    +| 2020-12-7 | honda     | 1       | 2          |
    +| 2020-12-7 | honda     | 2       | 1          |
    ++-----------+-----------+---------+------------+
    +结果表:
    ++-----------+-----------+--------------+-----------------+
    +| date_id   | make_name | unique_leads | unique_partners |
    ++-----------+-----------+--------------+-----------------+
    +| 2020-12-8 | toyota    | 2            | 3               |
    +| 2020-12-7 | toyota    | 1            | 2               |
    +| 2020-12-8 | honda     | 2            | 2               |
    +| 2020-12-7 | honda     | 3            | 2               |
    ++-----------+-----------+--------------+-----------------+
    +在 2020-12-8,丰田(toyota)有领导者 = [0, 1] 和合伙人 = [0, 1, 2] ,同时本田(honda)有领导者 = [1, 2] 和合伙人 = [1, 2]。
    +在 2020-12-7,丰田(toyota)有领导者 = [0] 和合伙人 = [1, 2] ,同时本田(honda)有领导者 = [0, 1, 2] 和合伙人 = [1, 2]。
    + +

     

    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1694.leetcode1694 Reformat Phone Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1694.leetcode1694 Reformat Phone Number-zh.md" new file mode 100644 index 00000000..26ad1fe7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1694.leetcode1694 Reformat Phone Number-zh.md" @@ -0,0 +1,115 @@ +# [1694. 重新格式化电话号码](https://leetcode-cn.com/problems/reformat-phone-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1694.Reformat%20Phone%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串形式的电话号码 numbernumber 由数字、空格 ' '、和破折号 '-' 组成。

    + +

    请你按下述方式重新格式化电话号码。

    + +
      +
    • 首先,删除 所有的空格和破折号。
    • +
    • 其次,将数组从左到右 每 3 个一组 分块,直到 剩下 4 个或更少数字。剩下的数字将按下述规定再分块: +
        +
      • 2 个数字:单个含 2 个数字的块。
      • +
      • 3 个数字:单个含 3 个数字的块。
      • +
      • 4 个数字:两个分别含 2 个数字的块。
      • +
      +
    • +
    + +

    最后用破折号将这些块连接起来。注意,重新格式化过程中 不应该 生成仅含 1 个数字的块,并且 最多 生成两个含 2 个数字的块。

    + +

    返回格式化后的电话号码。

    + +

     

    + +

    示例 1:

    + +
    +输入:number = "1-23-45 6"
    +输出:"123-456"
    +解释:数字是 "123456"
    +步骤 1:共有超过 4 个数字,所以先取 3 个数字分为一组。第 1 个块是 "123" 。
    +步骤 2:剩下 3 个数字,将它们放入单个含 3 个数字的块。第 2 个块是 "456" 。
    +连接这些块后得到 "123-456" 。
    + +

    示例 2:

    + +
    +输入:number = "123 4-567"
    +输出:"123-45-67"
    +解释:数字是 "1234567".
    +步骤 1:共有超过 4 个数字,所以先取 3 个数字分为一组。第 1 个块是 "123" 。
    +步骤 2:剩下 4 个数字,所以将它们分成两个含 2 个数字的块。这 2 块分别是 "45" 和 "67" 。
    +连接这些块后得到 "123-45-67" 。
    +
    + +

    示例 3:

    + +
    +输入:number = "123 4-5678"
    +输出:"123-456-78"
    +解释:数字是 "12345678" 。
    +步骤 1:第 1 个块 "123" 。
    +步骤 2:第 2 个块 "456" 。
    +步骤 3:剩下 2 个数字,将它们放入单个含 2 个数字的块。第 3 个块是 "78" 。
    +连接这些块后得到 "123-456-78" 。
    + +

    示例 4:

    + +
    +输入:number = "12"
    +输出:"12"
    +
    + +

    示例 5:

    + +
    +输入:number = "--17-5 229 35-39475 "
    +输出:"175-229-353-94-75"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= number.length <= 100
    • +
    • number 由数字和字符 '-'' ' 组成。
    • +
    • number 中至少含 2 个数字。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1695.leetcode1695 Maximum Erasure Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1695.leetcode1695 Maximum Erasure Value-zh.md" new file mode 100644 index 00000000..0d06b758 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1695.leetcode1695 Maximum Erasure Value-zh.md" @@ -0,0 +1,71 @@ +# [1695. 删除子数组的最大得分](https://leetcode-cn.com/problems/maximum-erasure-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1695.Maximum%20Erasure%20Value/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 nums ,请你从中删除一个含有 若干不同元素 的子数组删除子数组的 得分 就是子数组各元素之

    + +

    返回 只删除一个 子数组可获得的 最大得分

    + +

    如果数组 b 是数组 a 的一个连续子序列,即如果它等于 a[l],a[l+1],...,a[r] ,那么它就是 a 的一个子数组。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [4,2,4,5,6]
    +输出:17
    +解释:最优子数组是 [2,4,5,6]
    +
    + +

    示例 2:

    + +
    +输入:nums = [5,2,1,2,5,2,1,2,5]
    +输出:8
    +解释:最优子数组是 [5,2,1] 或 [1,2,5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1696.leetcode1696 Jump Game VI-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1696.leetcode1696 Jump Game VI-zh.md" new file mode 100644 index 00000000..13dd44fc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1696.leetcode1696 Jump Game VI-zh.md" @@ -0,0 +1,80 @@ +# [1696. 跳跃游戏 VI](https://leetcode-cn.com/problems/jump-game-vi) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1696.Jump%20Game%20VI/README_EN.md) + +## 题目描述 + + + +

    给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。

    + +

    一开始你在下标 0 处。每一步,你最多可以往前跳 k 步,但你不能跳出数组的边界。也就是说,你可以从下标 i 跳到 [i + 1, min(n - 1, i + k)] 包含 两个端点的任意位置。

    + +

    你的目标是到达数组最后一个位置(下标为 n - 1 ),你的 得分 为经过的所有数字之和。

    + +

    请你返回你能得到的 最大得分 。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,-1,-2,4,-7,3], k = 2
    +输出:7
    +解释:你可以选择子序列 [1,-1,4,3] (上面加粗的数字),和为 7 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [10,-5,-2,4,0,3], k = 3
    +输出:17
    +解释:你可以选择子序列 [10,4,3] (上面加粗数字),和为 17 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    •  1 <= nums.length, k <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1697.leetcode1697 Checking Existence of Edge Length Limited Paths-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1697.leetcode1697 Checking Existence of Edge Length Limited Paths-zh.md" new file mode 100644 index 00000000..d2417042 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1697.leetcode1697 Checking Existence of Edge Length Limited Paths-zh.md" @@ -0,0 +1,80 @@ +# [1697. 检查边长度限制的路径是否存在](https://leetcode-cn.com/problems/checking-existence-of-edge-length-limited-paths) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1697.Checking%20Existence%20of%20Edge%20Length%20Limited%20Paths/README_EN.md) + +## 题目描述 + + + +

    给你一个 n 个点组成的无向图边集 edgeList ,其中 edgeList[i] = [ui, vi, disi] 表示点 ui 和点 vi 之间有一条长度为 disi 的边。请注意,两个点之间可能有 超过一条边 

    + +

    给你一个查询数组queries ,其中 queries[j] = [pj, qj, limitj] ,你的任务是对于每个查询 queries[j] ,判断是否存在从 pj 到 qj 的路径,且这条路径上的每一条边都 严格小于 limitj 。

    + +

    请你返回一个 布尔数组 answer ,其中 answer.length == queries.length ,当 queries[j] 的查询结果为 true 时, answer j 个值为 true ,否则为 false 。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]
    +输出:[false,true]
    +解释:上图为给定的输入数据。注意到 0 和 1 之间有两条重边,分别为 2 和 16 。
    +对于第一个查询,0 和 1 之间没有小于 2 的边,所以我们返回 false 。
    +对于第二个查询,有一条路径(0 -> 1 -> 2)两条边都小于 5 ,所以这个查询我们返回 true 。
    +
    + +

    示例 2:

    + +
    +输入:n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]
    +输出:[true,false]
    +解释:上图为给定数据。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 105
    • +
    • 1 <= edgeList.length, queries.length <= 105
    • +
    • edgeList[i].length == 3
    • +
    • queries[j].length == 3
    • +
    • 0 <= ui, vi, pj, qj <= n - 1
    • +
    • ui != vi
    • +
    • pj != qj
    • +
    • 1 <= disi, limitj <= 109
    • +
    • 两个点之间可能有 多条 边。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1698.leetcode1698 Number of Distinct Substrings in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1698.leetcode1698 Number of Distinct Substrings in a String-zh.md" new file mode 100644 index 00000000..aa5400de --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1698.leetcode1698 Number of Distinct Substrings in a String-zh.md" @@ -0,0 +1,70 @@ +# [1698. 字符串的不同子字符串个数](https://leetcode-cn.com/problems/number-of-distinct-substrings-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1698.Number%20of%20Distinct%20Substrings%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串 s,返回 s 的不同子字符串的个数。

    + +

    字符串的 子字符串 是由原字符串删除开头若干个字符(可能是 0 个)并删除结尾若干个字符(可能是 0 个)形成的字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aabbaba"
    +输出:21
    +解释:不同子字符串的集合是 ["a","b","aa","bb","ab","ba","aab","abb","bab","bba","aba","aabb","abba","bbab","baba","aabba","abbab","bbaba","aabbab","abbaba","aabbaba"]
    +
    + +

    示例 2:

    + +
    +输入:s = "abcdefg"
    +输出:28
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 由小写英文字母组成。
    • +
    + +

    进阶:你可以以 O(n) 时间复杂度解决此问题吗?

    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1699.leetcode1699 Number of Calls Between Two Persons-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1699.leetcode1699 Number of Calls Between Two Persons-zh.md" new file mode 100644 index 00000000..e35faac2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1699.leetcode1699 Number of Calls Between Two Persons-zh.md" @@ -0,0 +1,72 @@ +# [1699. 两人之间的通话次数](https://leetcode-cn.com/problems/number-of-calls-between-two-persons) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1600-1699/1699.Number%20of%20Calls%20Between%20Two%20Persons/README_EN.md) + +## 题目描述 + + + +

    表: Calls

    + +
    +-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| from_id     | int     |
    +| to_id       | int     |
    +| duration    | int     |
    ++-------------+---------+
    +该表没有主键,可能存在重复项。
    +该表包含 from_id 与 to_id 间的一次电话的时长。
    +from_id != to_id
    +
    + +

     

    + +

    编写 SQL 语句,查询每一对用户 (person1, person2) 之间的通话次数和通话总时长,其中 person1 < person2 。

    + +

    以任意顺序返回结果表。

    + +

    查询结果格式如下示例所示:

    + +

     

    + +
    Calls 表:
    ++---------+-------+----------+
    +| from_id | to_id | duration |
    ++---------+-------+----------+
    +| 1       | 2     | 59       |
    +| 2       | 1     | 11       |
    +| 1       | 3     | 20       |
    +| 3       | 4     | 100      |
    +| 3       | 4     | 200      |
    +| 3       | 4     | 200      |
    +| 4       | 3     | 499      |
    ++---------+-------+----------+
    +
    +结果表:
    ++---------+---------+------------+----------------+
    +| person1 | person2 | call_count | total_duration |
    ++---------+---------+------------+----------------+
    +| 1       | 2       | 2          | 70             |
    +| 1       | 3       | 1          | 20             |
    +| 3       | 4       | 4          | 999            |
    ++---------+---------+------------+----------------+
    +用户 1 和 2 打过 2 次电话,总时长为 70 (59 + 11)。
    +用户 1 和 3 打过 1 次电话,总时长为 20。
    +用户 3 和 4 打过 4 次电话,总时长为 999 (100 + 200 + 200 + 499)。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1700.leetcode1700 Number of Students Unable to Eat Lunch-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1700.leetcode1700 Number of Students Unable to Eat Lunch-zh.md" new file mode 100644 index 00000000..0d926333 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1700.leetcode1700 Number of Students Unable to Eat Lunch-zh.md" @@ -0,0 +1,109 @@ +# [1700. 无法吃午餐的学生数量](https://leetcode-cn.com/problems/number-of-students-unable-to-eat-lunch) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1700.Number%20of%20Students%20Unable%20to%20Eat%20Lunch/README_EN.md) + +## 题目描述 + + + +

    学校的自助午餐提供圆形和方形的三明治,分别用数字 0 和 1 表示。所有学生站在一个队列里,每个学生要么喜欢圆形的要么喜欢方形的。
    +餐厅里三明治的数量与学生的数量相同。所有三明治都放在一个  里,每一轮:

    + +
      +
    • 如果队列最前面的学生 喜欢 栈顶的三明治,那么会 拿走它 并离开队列。
    • +
    • 否则,这名学生会 放弃这个三明治 并回到队列的尾部。
    • +
    + +

    这个过程会一直持续到队列里所有学生都不喜欢栈顶的三明治为止。

    + +

    给你两个整数数组 students 和 sandwiches ,其中 sandwiches[i] 是栈里面第 i​​​​​​ 个三明治的类型(i = 0 是栈的顶部), students[j] 是初始队列里第 j​​​​​​ 名学生对三明治的喜好(j = 0 是队列的最开始位置)。请你返回无法吃午餐的学生数量。

    + +

     

    + +

    示例 1:

    + +
    输入:students = [1,1,0,0], sandwiches = [0,1,0,1]
    +输出:0 
    +解释:
    +- 最前面的学生放弃最顶上的三明治,并回到队列的末尾,学生队列变为 students = [1,0,0,1]。
    +- 最前面的学生放弃最顶上的三明治,并回到队列的末尾,学生队列变为 students = [0,0,1,1]。
    +- 最前面的学生拿走最顶上的三明治,剩余学生队列为 students = [0,1,1],三明治栈为 sandwiches = [1,0,1]。
    +- 最前面的学生放弃最顶上的三明治,并回到队列的末尾,学生队列变为 students = [1,1,0]。
    +- 最前面的学生拿走最顶上的三明治,剩余学生队列为 students = [1,0],三明治栈为 sandwiches = [0,1]。
    +- 最前面的学生放弃最顶上的三明治,并回到队列的末尾,学生队列变为 students = [0,1]。
    +- 最前面的学生拿走最顶上的三明治,剩余学生队列为 students = [1],三明治栈为 sandwiches = [1]。
    +- 最前面的学生拿走最顶上的三明治,剩余学生队列为 students = [],三明治栈为 sandwiches = []。
    +所以所有学生都有三明治吃。
    +
    + +

    示例 2:

    + +
    输入:students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= students.length, sandwiches.length <= 100
    • +
    • students.length == sandwiches.length
    • +
    • sandwiches[i] 要么是 0 ,要么是 1 。
    • +
    • students[i] 要么是 0 ,要么是 1 。
    • +
    + +## 解法 + + + +学生位置可调整,而三明治位置不可调整。也就是说,若前面的三明治没被拿走,则往后的所有三明治也无法被拿走。 + +因此,先用计数器 counter 统计学生喜欢的三明治种类和对应的数量,然后遍历三明治,若在 counter 中找不到喜欢此三明治的学生,说明已经找到答案,当前以及往后的三明治均无法被拿走,数量为 `n - i`。 + + + +### **Python3** + + + +```python +class Solution: + def countStudents(self, students: List[int], sandwiches: List[int]) -> int: + counter = collections.Counter(students) + for i, sandwich in enumerate(sandwiches): + if counter[sandwich] == 0: + return len(students) - i + counter[sandwich] -= 1 + return 0 +``` + +### **Java** + + + +```java +class Solution { + public int countStudents(int[] students, int[] sandwiches) { + int[] counter = new int[2]; + for (int i : students) { + counter[i] += 1; + } + for (int i = 0; i < sandwiches.length; ++i) { + if (counter[sandwiches[i]] == 0) { + return sandwiches.length - i; + } + counter[sandwiches[i]] -= 1; + } + return 0; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1701.leetcode1701 Average Waiting Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1701.leetcode1701 Average Waiting Time-zh.md" new file mode 100644 index 00000000..2cbb6d9b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1701.leetcode1701 Average Waiting Time-zh.md" @@ -0,0 +1,103 @@ +# [1701. 平均等待时间](https://leetcode-cn.com/problems/average-waiting-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1701.Average%20Waiting%20Time/README_EN.md) + +## 题目描述 + + + +

    有一个餐厅,只有一位厨师。你有一个顾客数组 customers ,其中 customers[i] = [arrivali, timei] :

    + +
      +
    • arrivali 是第 i 位顾客到达的时间,到达时间按 非递减 顺序排列。
    • +
    • timei 是给第 i 位顾客做菜需要的时间。
    • +
    + +

    当一位顾客到达时,他将他的订单给厨师,厨师一旦空闲的时候就开始做这位顾客的菜。每位顾客会一直等待到厨师完成他的订单。厨师同时只能做一个人的订单。厨师会严格按照 订单给他的顺序 做菜。

    + +

    请你返回所有顾客需要等待的 平均 时间。与标准答案误差在 10-5 范围以内,都视为正确结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:customers = [[1,2],[2,5],[4,3]]
    +输出:5.00000
    +解释:
    +1) 第一位顾客在时刻 1 到达,厨师拿到他的订单并在时刻 1 立马开始做菜,并在时刻 3 完成,第一位顾客等待时间为 3 - 1 = 2 。
    +2) 第二位顾客在时刻 2 到达,厨师在时刻 3 开始为他做菜,并在时刻 8 完成,第二位顾客等待时间为 8 - 2 = 6 。
    +3) 第三位顾客在时刻 4 到达,厨师在时刻 8 开始为他做菜,并在时刻 11 完成,第三位顾客等待时间为 11 - 4 = 7 。
    +平均等待时间为 (2 + 6 + 7) / 3 = 5 。
    +
    + +

    示例 2:

    + +
    +输入:customers = [[5,2],[5,4],[10,3],[20,1]]
    +输出:3.25000
    +解释:
    +1) 第一位顾客在时刻 5 到达,厨师拿到他的订单并在时刻 5 立马开始做菜,并在时刻 7 完成,第一位顾客等待时间为 7 - 5 = 2 。
    +2) 第二位顾客在时刻 5 到达,厨师在时刻 7 开始为他做菜,并在时刻 11 完成,第二位顾客等待时间为 11 - 5 = 6 。
    +3) 第三位顾客在时刻 10 到达,厨师在时刻 11 开始为他做菜,并在时刻 14 完成,第三位顾客等待时间为 14 - 10 = 4 。
    +4) 第四位顾客在时刻 20 到达,厨师拿到他的订单并在时刻 20 立马开始做菜,并在时刻 21 完成,第四位顾客等待时间为 21 - 20 = 1 。
    +平均等待时间为 (2 + 6 + 4 + 1) / 4 = 3.25 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= customers.length <= 105
    • +
    • 1 <= arrivali, timei <= 104
    • +
    • arrival<= arrivali+1
    • +
    + +## 解法 + + + +记 totalWaitingTime 表示总等待时间,f 表示当次做菜完成时间。 + + + +### **Python3** + + + +```python +class Solution: + def averageWaitingTime(self, customers: List[List[int]]) -> float: + f = total_waiting_time = 0 + for arrival, time in customers: + f = max(arrival, f) + time + total_waiting_time += (f - arrival) + return total_waiting_time / len(customers) +``` + +### **Java** + + + +```java +class Solution { + public double averageWaitingTime(int[][] customers) { + int f = 0; + double totalWaitingTime = 0; + for (int[] customer : customers) { + f = Math.max(f, customer[0]) + customer[1]; + totalWaitingTime += (f - customer[0]); + } + return totalWaitingTime / customers.length; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1702.leetcode1702 Maximum Binary String After Change-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1702.leetcode1702 Maximum Binary String After Change-zh.md" new file mode 100644 index 00000000..4bc4d4aa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1702.leetcode1702 Maximum Binary String After Change-zh.md" @@ -0,0 +1,88 @@ +# [1702. 修改后的最大二进制字符串](https://leetcode-cn.com/problems/maximum-binary-string-after-change) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1702.Maximum%20Binary%20String%20After%20Change/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 binary ,它仅有 0 或者 1 组成。你可以使用下面的操作任意次对它进行修改:

    + +
      +
    • 操作 1 :如果二进制串包含子字符串 "00" ,你可以用 "10" 将其替换。 + +
        +
      • 比方说, "00010" -> "10010"
      • +
      +
    • +
    • 操作 2 :如果二进制串包含子字符串 "10" ,你可以用 "01" 将其替换。 +
        +
      • 比方说, "00010" -> "00001"
      • +
      +
    • +
    + +

    请你返回执行上述操作任意次以后能得到的 最大二进制字符串 。如果二进制字符串 x 对应的十进制数字大于二进制字符串 y 对应的十进制数字,那么我们称二进制字符串 x 大于二进制字符串 y 

    + +

     

    + +

    示例 1:

    + +
    +输入:binary = "000110"
    +输出:"111011"
    +解释:一个可行的转换为:
    +"000110" -> "000101" 
    +"000101" -> "100101" 
    +"100101" -> "110101" 
    +"110101" -> "110011" 
    +"110011" -> "111011"
    +
    + +

    示例 2:

    + +
    +输入:binary = "01"
    +输出:"01"
    +解释:"01" 没办法进行任何转换。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= binary.length <= 105
    • +
    • binary 仅包含 '0' 和 '1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1703.leetcode1703 Minimum Adjacent Swaps for K Consecutive Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1703.leetcode1703 Minimum Adjacent Swaps for K Consecutive Ones-zh.md" new file mode 100644 index 00000000..2a13d0d3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1703.leetcode1703 Minimum Adjacent Swaps for K Consecutive Ones-zh.md" @@ -0,0 +1,75 @@ +# [1703. 得到连续 K 个 1 的最少相邻交换次数](https://leetcode-cn.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1703.Minimum%20Adjacent%20Swaps%20for%20K%20Consecutive%20Ones/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个整数 k 。 nums 仅包含 0 和 1 。每一次移动,你可以选择 相邻 两个数字并将它们交换。

    + +

    请你返回使 nums 中包含 k 个 连续 1 的 最少 交换次数。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,0,0,1,0,1], k = 2
    +输出:1
    +解释:在第一次操作时,nums 可以变成 [1,0,0,0,1,1] 得到连续两个 1 。
    +
    + +

    示例 2:

    + +
    输入:nums = [1,0,0,0,0,0,1,1], k = 3
    +输出:5
    +解释:通过 5 次操作,最左边的 1 可以移到右边直到 nums 变为 [0,0,0,0,0,1,1,1] 。
    +
    + +

    示例 3:

    + +
    输入:nums = [1,1,0,1], k = 2
    +输出:0
    +解释:nums 已经有连续 2 个 1 了。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • nums[i] 要么是 0 ,要么是 1 。
    • +
    • 1 <= k <= sum(nums)
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1704.leetcode1704 Determine if String Halves Are Alike-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1704.leetcode1704 Determine if String Halves Are Alike-zh.md" new file mode 100644 index 00000000..5c3b17eb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1704.leetcode1704 Determine if String Halves Are Alike-zh.md" @@ -0,0 +1,104 @@ +# [1704. 判断字符串的两半是否相似](https://leetcode-cn.com/problems/determine-if-string-halves-are-alike) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1704.Determine%20if%20String%20Halves%20Are%20Alike/README_EN.md) + +## 题目描述 + + + +

    给你一个偶数长度的字符串 s 。将其拆分成长度相同的两半,前一半为 a ,后一半为 b

    + +

    两个字符串 相似 的前提是它们都含有相同数目的元音('a''e''i''o''u''A''E''I''O''U')。注意,s 可能同时含有大写和小写字母。

    + +

    如果 a b 相似,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:s = "book"
    +输出:true
    +解释:a = "bo" 且 b = "ok" 。a 中有 1 个元音,b 也有 1 个元音。所以,a 和 b 相似。
    +
    + +

    示例 2:

    + +
    输入:s = "textbook"
    +输出:false
    +解释:a = "text" 且 b = "book" 。a 中有 1 个元音,b 中有 2 个元音。因此,a 和 b 不相似。
    +注意,元音 o 在 b 中出现两次,记为 2 个。
    +
    + +

    示例 3:

    + +
    输入:s = "MerryChristmas"
    +输出:false
    +
    + +

    示例 4:

    + +
    输入:s = "AbCdEfGh"
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= s.length <= 1000
    • +
    • s.length 是偶数
    • +
    • s大写和小写 字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def halvesAreAlike(self, s: str) -> bool: + half = len(s) >> 1 + vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} + s1 = sum(1 for c in s[:half] if c in vowels) + s2 = sum(1 for c in s[half:] if c in vowels) + return s1 == s2 +``` + +### **Java** + + + +```java +class Solution { + public boolean halvesAreAlike(String s) { + int half = s.length() >> 1; + Set vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); + int s1 = 0, s2 = 0; + for (int i = 0; i < half; ++i) { + if (vowels.contains(s.charAt(i))) { + ++s1; + } + if (vowels.contains(s.charAt(half + i))) { + ++s2; + } + } + return s1 == s2; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1705.leetcode1705 Maximum Number of Eaten Apples-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1705.leetcode1705 Maximum Number of Eaten Apples-zh.md" new file mode 100644 index 00000000..06ca644c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1705.leetcode1705 Maximum Number of Eaten Apples-zh.md" @@ -0,0 +1,79 @@ +# [1705. 吃苹果的最大数目](https://leetcode-cn.com/problems/maximum-number-of-eaten-apples) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1705.Maximum%20Number%20of%20Eaten%20Apples/README_EN.md) + +## 题目描述 + + + +

    有一棵特殊的苹果树,一连 n 天,每天都可以长出若干个苹果。在第 i 天,树上会长出 apples[i] 个苹果,这些苹果将会在 days[i] 天后(也就是说,第 i + days[i] 天时)腐烂,变得无法食用。也可能有那么几天,树上不会长出新的苹果,此时用 apples[i] == 0days[i] == 0 表示。

    + +

    你打算每天 最多 吃一个苹果来保证营养均衡。注意,你可以在这 n 天之后继续吃苹果。

    + +

    给你两个长度为 n 的整数数组 daysapples ,返回你可以吃掉的苹果的最大数目

    + +

     

    + +

    示例 1:

    + +
    输入:apples = [1,2,3,5,2], days = [3,2,1,4,2]
    +输出:7
    +解释:你可以吃掉 7 个苹果:
    +- 第一天,你吃掉第一天长出来的苹果。
    +- 第二天,你吃掉一个第二天长出来的苹果。
    +- 第三天,你吃掉一个第二天长出来的苹果。过了这一天,第三天长出来的苹果就已经腐烂了。
    +- 第四天到第七天,你吃的都是第四天长出来的苹果。
    +
    + +

    示例 2:

    + +
    输入:apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
    +输出:5
    +解释:你可以吃掉 5 个苹果:
    +- 第一天到第三天,你吃的都是第一天长出来的苹果。
    +- 第四天和第五天不吃苹果。
    +- 第六天和第七天,你吃的都是第六天长出来的苹果。
    +
    + +

     

    + +

    提示:

    + +
      +
    • apples.length == n
    • +
    • days.length == n
    • +
    • 1 <= n <= 2 * 104
    • +
    • 0 <= apples[i], days[i] <= 2 * 104
    • +
    • 只有在 apples[i] = 0 时,days[i] = 0 才成立
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1706.leetcode1706 Where Will the Ball Fall-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1706.leetcode1706 Where Will the Ball Fall-zh.md" new file mode 100644 index 00000000..4ddf68d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1706.leetcode1706 Where Will the Ball Fall-zh.md" @@ -0,0 +1,94 @@ +# [1706. 球会落何处](https://leetcode-cn.com/problems/where-will-the-ball-fall) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1706.Where%20Will%20the%20Ball%20Fall/README_EN.md) + +## 题目描述 + + + +

    用一个大小为 m x n 的二维网格 grid 表示一个箱子。你有 n 颗球。箱子的顶部和底部都是开着的。

    + +

    箱子中的每个单元格都有一个对角线挡板,跨过单元格的两个角,可以将球导向左侧或者右侧。

    + +
      +
    • 将球导向右侧的挡板跨过左上角和右下角,在网格中用 1 表示。
    • +
    • 将球导向左侧的挡板跨过右上角和左下角,在网格中用 -1 表示。
    • +
    + +

    在箱子每一列的顶端各放一颗球。每颗球都可能卡在箱子里或从底部掉出来。如果球恰好卡在两块挡板之间的 "V" 形图案,或者被一块挡导向到箱子的任意一侧边上,就会卡住。

    + +

    返回一个大小为 n 的数组 answer ,其中 answer[i] 是球放在顶部的第 i 列后从底部掉出来的那一列对应的下标,如果球卡在盒子里,则返回 -1

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
    +输出:[1,-1,-1,-1,-1]
    +解释:示例如图:
    +b0 球开始放在第 0 列上,最终从箱子底部第 1 列掉出。
    +b1 球开始放在第 1 列上,会卡在第 2、3 列和第 1 行之间的 "V" 形里。
    +b2 球开始放在第 2 列上,会卡在第 2、3 列和第 0 行之间的 "V" 形里。
    +b3 球开始放在第 3 列上,会卡在第 2、3 列和第 0 行之间的 "V" 形里。
    +b4 球开始放在第 4 列上,会卡在第 2、3 列和第 1 行之间的 "V" 形里。
    +
    + +

    示例 2:

    + +
    +输入:grid = [[-1]]
    +输出:[-1]
    +解释:球被卡在箱子左侧边上。
    +
    + +

    示例 3:

    + +
    +输入:grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]
    +输出:[0,1,2,3,4,-1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • grid[i][j]1-1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1707.leetcode1707 Maximum XOR With an Element From Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1707.leetcode1707 Maximum XOR With an Element From Array-zh.md" new file mode 100644 index 00000000..7b7b5eee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1707.leetcode1707 Maximum XOR With an Element From Array-zh.md" @@ -0,0 +1,72 @@ +# [1707. 与数组中元素的最大异或值](https://leetcode-cn.com/problems/maximum-xor-with-an-element-from-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1707.Maximum%20XOR%20With%20an%20Element%20From%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个由非负整数组成的数组 nums 。另有一个查询数组 queries ,其中 queries[i] = [xi, mi]

    + +

    i 个查询的答案是 xi 和任何 nums 数组中不超过 mi 的元素按位异或(XOR)得到的最大值。换句话说,答案是 max(nums[j] XOR xi) ,其中所有 j 均满足 nums[j] <= mi 。如果 nums 中的所有元素都大于 mi,最终答案就是 -1

    + +

    返回一个整数数组 answer 作为查询的答案,其中 answer.length == queries.length answer[i] 是第 i 个查询的答案。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
    +输出:[3,3,7]
    +解释:
    +1) 0 和 1 是仅有的两个不超过 1 的整数。0 XOR 3 = 3 而 1 XOR 3 = 2 。二者中的更大值是 3 。
    +2) 1 XOR 2 = 3.
    +3) 5 XOR 2 = 7.
    +
    + +

    示例 2:

    + +
    输入:nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]
    +输出:[15,-1,5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length, queries.length <= 105
    • +
    • queries[i].length == 2
    • +
    • 0 <= nums[j], xi, mi <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1708.leetcode1708 Largest Subarray Length K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1708.leetcode1708 Largest Subarray Length K-zh.md" new file mode 100644 index 00000000..a387e882 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1708.leetcode1708 Largest Subarray Length K-zh.md" @@ -0,0 +1,85 @@ +# [1708. 长度为 K 的最大子数组](https://leetcode-cn.com/problems/largest-subarray-length-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1708.Largest%20Subarray%20Length%20K/README_EN.md) + +## 题目描述 + + + +

    在数组 A 和数组 B 中,对于第一个满足 A[i] != B[i] 的索引 i ,当 A[i] > B[i] 时,数组 A 大于数组 B

    + +

    例如,对于索引从 0 开始的数组:

    + +
      +
    • [1,3,2,4] > [1,2,2,4] ,因为在索引 1 上, 3 > 2
    • +
    • [1,4,4,4] < [2,1,1,1] ,因为在索引 0 上, 1 < 2
    • +
    + +

    一个数组的子数组是原数组上的一个连续子序列。

    + +

    给定一个包含不同整数的整数类型数组 nums ,返回 nums 中长度为 k 的最大子数组。

    + +

     

    + +

    示例 1:

    + +
    输入: nums = [1,4,5,2,3], k = 3
    +输出: [5,2,3]
    +解释: 长度为 3 的子数组有: [1,4,5]、 [4,5,2] 和 [5,2,3]。
    +在这些数组中, [5,2,3] 是最大的。
    + +

    Example 2:

    + +
    输入: nums = [1,4,5,2,3], k = 4
    +输出: [4,5,2,3]
    +解释: 长度为 4 的子数组有: [1,4,5,2] 和 [4,5,2,3]。
    +在这些数组中, [4,5,2,3] 是最大的。
    + +

    示例 3:

    + +
    输入: nums = [1,4,5,2,3], k = 1
    +输出: [5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 109
    • +
    • nums 中的所有整数都是不同的。
    • +
    + +

     

    +进阶:如果允许 nums 中存在相同元素,你该如何解决该问题? + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1709.leetcode1709 Biggest Window Between Visits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1709.leetcode1709 Biggest Window Between Visits-zh.md" new file mode 100644 index 00000000..e372c59d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1709.leetcode1709 Biggest Window Between Visits-zh.md" @@ -0,0 +1,75 @@ +# [1709. 访问日期之间最大的空档期](https://leetcode-cn.com/problems/biggest-window-between-visits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1709.Biggest%20Window%20Between%20Visits/README_EN.md) + +## 题目描述 + + + +

    表: UserVisits

    + +
    +-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| user_id     | int  |
    +| visit_date  | date |
    ++-------------+------+
    +该表没有主键。
    +该表包含用户访问某特定零售商的日期日志。
    + +

     

    + +

    假设今天的日期是 '2021-1-1' 。

    + +

    编写 SQL 语句,对于每个 user_id ,求出每次访问及其下一个访问(若该次访问是最后一次,则为今天)之间最大的空档期天数 window 。

    + +

    返回结果表,按用户编号 user_id 排序。

    + +

    查询格式如下示例所示:

    + +

     

    + +
    UserVisits 表:
    ++---------+------------+
    +| user_id | visit_date |
    ++---------+------------+
    +| 1       | 2020-11-28 |
    +| 1       | 2020-10-20 |
    +| 1       | 2020-12-3  |
    +| 2       | 2020-10-5  |
    +| 2       | 2020-12-9  |
    +| 3       | 2020-11-11 |
    ++---------+------------+
    +结果表:
    ++---------+---------------+
    +| user_id | biggest_window|
    ++---------+---------------+
    +| 1       | 39            |
    +| 2       | 65            |
    +| 3       | 51            |
    ++---------+---------------+
    +对于第一个用户,问题中的空档期在以下日期之间:
    +    - 2020-10-20 至 2020-11-28 ,共计 39 天。
    +    - 2020-11-28 至 2020-12-3 ,共计 5 天。
    +    - 2020-12-3 至 2021-1-1 ,共计 29 天。
    +由此得出,最大的空档期为 39 天。
    +对于第二个用户,问题中的空档期在以下日期之间:
    +    - 2020-10-5 至 2020-12-9 ,共计 65 天。
    +    - 2020-12-9 至 2021-1-1 ,共计 23 天。
    +由此得出,最大的空档期为 65 天。
    +对于第三个用户,问题中的唯一空档期在 2020-11-11 至 2021-1-1 之间,共计 51 天。
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1710.leetcode1710 Maximum Units on a Truck-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1710.leetcode1710 Maximum Units on a Truck-zh.md" new file mode 100644 index 00000000..d5120626 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1710.leetcode1710 Maximum Units on a Truck-zh.md" @@ -0,0 +1,80 @@ +# [1710. 卡车上的最大单元数](https://leetcode-cn.com/problems/maximum-units-on-a-truck) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1710.Maximum%20Units%20on%20a%20Truck/README_EN.md) + +## 题目描述 + + + +

    请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]

    + +
      +
    • numberOfBoxesi 是类型 i 的箱子的数量。
    • +
    • numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。
    • +
    + +

    整数 truckSize 表示卡车上可以装载 箱子最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。

    + +

    返回卡车可以装载 单元最大 总数

    + +

     

    + +

    示例 1:

    + +
    +输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
    +输出:8
    +解释:箱子的情况如下:
    +- 1 个第一类的箱子,里面含 3 个单元。
    +- 2 个第二类的箱子,每个里面含 2 个单元。
    +- 3 个第三类的箱子,每个里面含 1 个单元。
    +可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。
    +单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8
    + +

    示例 2:

    + +
    +输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
    +输出:91
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= boxTypes.length <= 1000
    • +
    • 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
    • +
    • 1 <= truckSize <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1711.leetcode1711 Count Good Meals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1711.leetcode1711 Count Good Meals-zh.md" new file mode 100644 index 00000000..118f7946 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1711.leetcode1711 Count Good Meals-zh.md" @@ -0,0 +1,134 @@ +# [1711. 大餐计数](https://leetcode-cn.com/problems/count-good-meals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1711.Count%20Good%20Meals/README_EN.md) + +## 题目描述 + + + +

    大餐 是指 恰好包含两道不同餐品 的一餐,其美味程度之和等于 2 的幂。

    + +

    你可以搭配 任意 两道餐品做一顿大餐。

    + +

    给你一个整数数组 deliciousness ,其中 deliciousness[i] 是第 i​​​​​​​​​​​​​​ 道餐品的美味程度,返回你可以用数组中的餐品做出的不同 大餐 的数量。结果需要对 109 + 7 取余。

    + +

    注意,只要餐品下标不同,就可以认为是不同的餐品,即便它们的美味程度相同。

    + +

     

    + +

    示例 1:

    + +
    +输入:deliciousness = [1,3,5,7,9]
    +输出:4
    +解释:大餐的美味程度组合为 (1,3) 、(1,7) 、(3,5) 和 (7,9) 。
    +它们各自的美味程度之和分别为 4 、8 、8 和 16 ,都是 2 的幂。
    +
    + +

    示例 2:

    + +
    +输入:deliciousness = [1,1,1,3,3,3,7]
    +输出:15
    +解释:大餐的美味程度组合为 3 种 (1,1) ,9 种 (1,3) ,和 3 种 (1,7) 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= deliciousness.length <= 105
    • +
    • 0 <= deliciousness[i] <= 220
    • +
    + + +## 解法 + +用最暴力的方法枚举每对元素肯定会超时,可以用哈希表优化对**之前元素出现次数**的查询。 + + + + + +### **Python3** + + + +```python +class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + mod = 1000000007 + limit = max(deliciousness) * 2 + pairs = 0 + freq = collections.defaultdict(int) + for d in deliciousness: + target = 1 + while target <= limit: + pairs = (pairs + freq[target - d]) % mod + target = target << 1 + freq[d] += 1 + return pairs +``` + +### **Java** + + + +```java +class Solution { + + private static final int MOD = 1000000007; + + public int countPairs(int[] deliciousness) { + int limit = Arrays.stream(deliciousness).max().getAsInt() * 2; + int pairs = 0; + Map freq = new HashMap<>(); + for (int d : deliciousness) { + for (int sum = 1; sum <= limit; sum <<= 1) { + int count = freq.getOrDefault(sum - d, 0); + pairs = (pairs + count) % MOD; + } + freq.merge(d, 1, Integer::sum); + } + return pairs; + } +} +``` + +### **Go** + +```go +const mod int = 1e9 + 7 + +func countPairs(deliciousness []int) int { + limit := 0 + for _, d := range deliciousness { + limit = max(limit, d) + } + limit *= 2 + pairs := 0 + freq := make(map[int]int) + for _, d := range deliciousness { + for sum := 1; sum <= limit; sum <<= 1 { + pairs = (pairs + freq[sum-d]) % mod + } + freq[d]++ + } + return pairs +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1712.leetcode1712 Ways to Split Array Into Three Subarrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1712.leetcode1712 Ways to Split Array Into Three Subarrays-zh.md" new file mode 100644 index 00000000..f3f4a930 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1712.leetcode1712 Ways to Split Array Into Three Subarrays-zh.md" @@ -0,0 +1,83 @@ +# [1712. 将数组分成三个子数组的方案数](https://leetcode-cn.com/problems/ways-to-split-array-into-three-subarrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1712.Ways%20to%20Split%20Array%20Into%20Three%20Subarrays/README_EN.md) + +## 题目描述 + + + +

    我们称一个分割整数数组的方案是 好的 ,当它满足:

    + +
      +
    • 数组被分成三个 非空 连续子数组,从左至右分别命名为 left , mid , right 。
    • +
    • left 中元素和小于等于 mid 中元素和,mid 中元素和小于等于 right 中元素和。
    • +
    + +

    给你一个 非负 整数数组 nums ,请你返回 好的 分割 nums 方案数目。由于答案可能会很大,请你将结果对 10+ 7 取余后返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,1,1]
    +输出:1
    +解释:唯一一种好的分割方案是将 nums 分成 [1] [1] [1] 。
    + +

    示例 2:

    + +
    +输入:nums = [1,2,2,2,5,0]
    +输出:3
    +解释:nums 总共有 3 种好的分割方案:
    +[1] [2] [2,2,5,0]
    +[1] [2,2] [2,5,0]
    +[1,2] [2,2] [5,0]
    +
    + +

    示例 3:

    + +
    +输入:nums = [3,2,1]
    +输出:0
    +解释:没有好的分割方案。
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= nums.length <= 105
    • +
    • 0 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1713.leetcode1713 Minimum Operations to Make a Subsequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1713.leetcode1713 Minimum Operations to Make a Subsequence-zh.md" new file mode 100644 index 00000000..a0efe43b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1713.leetcode1713 Minimum Operations to Make a Subsequence-zh.md" @@ -0,0 +1,71 @@ +# [1713. 得到子序列的最少操作次数](https://leetcode-cn.com/problems/minimum-operations-to-make-a-subsequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1713.Minimum%20Operations%20to%20Make%20a%20Subsequence/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 target ,包含若干 互不相同 的整数,以及另一个整数数组 arr ,arr 可能 包含重复元素。

    + +

    每一次操作中,你可以在 arr 的任意位置插入任一整数。比方说,如果 arr = [1,4,1,2] ,那么你可以在中间添加 3 得到 [1,4,3,1,2] 。你可以在数组最开始或最后面添加整数。

    + +

    请你返回 最少 操作次数,使得 target 成为 arr 的一个子序列。

    + +

    一个数组的 子序列 指的是删除原数组的某些元素(可能一个元素都不删除),同时不改变其余元素的相对顺序得到的数组。比方说,[2,7,4] 是 [4,2,3,7,2,1,4] 的子序列(加粗元素),但 [2,4,2] 不是子序列。

    + +

     

    + +

    示例 1:

    + +
    输入:target = [5,1,3], arr = [9,4,2,3,4]
    +输出:2
    +解释:你可以添加 5 和 1 ,使得 arr 变为 [5,9,4,1,2,3,4] ,target 为 arr 的子序列。
    +
    + +

    示例 2:

    + +
    输入:target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= target.length, arr.length <= 105
    • +
    • 1 <= target[i], arr[i] <= 109
    • +
    • target 不包含任何重复元素。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1714.leetcode1714 Sum Of Special Evenly-Spaced Elements In Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1714.leetcode1714 Sum Of Special Evenly-Spaced Elements In Array-zh.md" new file mode 100644 index 00000000..bdd56a6d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1714.leetcode1714 Sum Of Special Evenly-Spaced Elements In Array-zh.md" @@ -0,0 +1,75 @@ +# [1714. 数组中特殊等间距元素的和](https://leetcode-cn.com/problems/sum-of-special-evenly-spaced-elements-in-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1714.Sum%20Of%20Special%20Evenly-Spaced%20Elements%20In%20Array/README_EN.md) + +## 题目描述 + + + +

    给定一个索引从 0 开始的整数类型数组 nums ,包含 n 个非负整数。

    + +

    另外给定一个(包含查询指令的)数组 queries ,其中 queries[i] = [xi, yi]。 第 i 个查询指令的答案是 nums[j] 中满足该条件的所有元素的和: xi <= j < n 且 (j - xi) 能被 yi 整除。

    + +

    返回一个数组 answer,其中  answer.length == queries.length 且 answer[i] 是第 i 个查询指令的答案对 109 + 7 取模。

    + +

     

    + +

    示例 1:

    + +
    输入: nums = [0,1,2,3,4,5,6,7], queries = [[0,3],[5,1],[4,2]]
    +输出: [9,18,10]
    +解释: 每次查询的答案如下:
    +1) 符合查询条件的索引 j 有 0、 3 和 6。 nums[0] + nums[3] + nums[6] = 9
    +2) 符合查询条件的索引 j 有 5、 6 和 7。 nums[5] + nums[6] + nums[7] = 18
    +3) 符合查询条件的索引 j 有 4 和 6。 nums[4] + nums[6] = 10
    +
    + +

    示例 2:

    + +
    输入: nums = [100,200,101,201,102,202,103,203], queries = [[0,7]]
    +输出: [303]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 5 * 104
    • +
    • 0 <= nums[i] <= 109
    • +
    • 1 <= queries.length <= 1.5 * 105
    • +
    • 0 <= xi < n
    • +
    • 1 <= yi <= 5 * 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1715.leetcode1715 Count Apples and Oranges-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1715.leetcode1715 Count Apples and Oranges-zh.md" new file mode 100644 index 00000000..c1a6bce2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1715.leetcode1715 Count Apples and Oranges-zh.md" @@ -0,0 +1,112 @@ +# [1715. 苹果和橘子的个数](https://leetcode-cn.com/problems/count-apples-and-oranges) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1715.Count%20Apples%20and%20Oranges/README_EN.md) + +## 题目描述 + + + +

    表: Boxes

    + +
    +--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| box_id       | int  |
    +| chest_id     | int  |
    +| apple_count  | int  |
    +| orange_count | int  |
    ++--------------+------+
    +box_id 是该表的主键。
    +chest_id 是 chests 表的外键。
    +该表包含大箱子 (box) 中包含的苹果和橘子的个数。每个大箱子中可能包含一个小盒子 (chest) ,小盒子中也包含若干苹果和橘子。
    + +

     

    + +

    表: Chests

    + +
    +--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| chest_id     | int  |
    +| apple_count  | int  |
    +| orange_count | int  |
    ++--------------+------+
    +chest_id 是该表的主键。
    +该表包含小盒子的信息,以及小盒子中包含的苹果和橘子的个数。
    + +

     

    + +

    编写 SQL 语句,查询每个大箱子中苹果和橘子的个数。如果大箱子中包含小盒子,还应当包含小盒子中苹果和橘子的个数。

    + +

    以任意顺序返回结果表。

    + +

    查询结果的格式如下示例所示:

    + +

     

    + +
    Boxes 表:
    ++--------+----------+-------------+--------------+
    +| box_id | chest_id | apple_count | orange_count |
    ++--------+----------+-------------+--------------+
    +| 2      | null     | 6           | 15           |
    +| 18     | 14       | 4           | 15           |
    +| 19     | 3        | 8           | 4            |
    +| 12     | 2        | 19          | 20           |
    +| 20     | 6        | 12          | 9            |
    +| 8      | 6        | 9           | 9            |
    +| 3      | 14       | 16          | 7            |
    ++--------+----------+-------------+--------------+
    +
    +Chests 表:
    ++----------+-------------+--------------+
    +| chest_id | apple_count | orange_count |
    ++----------+-------------+--------------+
    +| 6        | 5           | 6            |
    +| 14       | 20          | 10           |
    +| 2        | 8           | 8            |
    +| 3        | 19          | 4            |
    +| 16       | 19          | 19           |
    ++----------+-------------+--------------+
    +
    +结果表:
    ++-------------+--------------+
    +| apple_count | orange_count |
    ++-------------+--------------+
    +| 151         | 123          |
    ++-------------+--------------+
    +大箱子 2 中有 6 个苹果和 15 个橘子。
    +大箱子 18 中有 4 + 20 (在小盒子中) = 24 个苹果和 15 + 10 (在小盒子中) = 25 个橘子。
    +大箱子 19 中有 8 + 19 (在小盒子中) = 27 个苹果和 4 + 4 (在小盒子中) = 8 个橘子。
    +大箱子 12 中有 19 + 8 (在小盒子中) = 27 个苹果和 20 + 8 (在小盒子中) = 28 个橘子。
    +大箱子 20 中有 12 + 5 (在小盒子中) = 17 个苹果和 9 + 6 (在小盒子中) = 15 个橘子。
    +大箱子 8 中有 9 + 5 (在小盒子中) = 14 个苹果和 9 + 6 (在小盒子中) = 15 个橘子。
    +大箱子 3 中有 16 + 20 (在小盒子中) = 36 个苹果和 7 + 10 (在小盒子中) = 17 个橘子。
    +苹果的总个数 = 6 + 24 + 27 + 27 + 17 + 14 + 36 = 151
    +橘子的总个数 = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123
    +
    + + +## 解法 + + + +“`LEFT JOIN` + `IFNULL`”实现。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + SUM(IFNULL(b.apple_count, 0) + IFNULL(c.apple_count, 0)) AS apple_count, + SUM(IFNULL(b.orange_count, 0) + IFNULL(c.orange_count, 0)) AS orange_count +FROM + Boxes b +LEFT JOIN + Chests c +ON + b.chest_id = c.chest_id; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1716.leetcode1716 Calculate Money in Leetcode Bank-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1716.leetcode1716 Calculate Money in Leetcode Bank-zh.md" new file mode 100644 index 00000000..e1b6640f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1716.leetcode1716 Calculate Money in Leetcode Bank-zh.md" @@ -0,0 +1,75 @@ +# [1716. 计算力扣银行的钱](https://leetcode-cn.com/problems/calculate-money-in-leetcode-bank) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1716.Calculate%20Money%20in%20Leetcode%20Bank/README_EN.md) + +## 题目描述 + + + +

    Hercy 想要为购买第一辆车存钱。他 每天 都往力扣银行里存钱。

    + +

    最开始,他在周一的时候存入 1 块钱。从周二到周日,他每天都比前一天多存入 1 块钱。在接下来每一个周一,他都会比 前一个周一 多存入 1 块钱。

    + +

    给你 n ,请你返回在第 n 天结束的时候他在力扣银行总共存了多少块钱。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 4
    +输出:10
    +解释:第 4 天后,总额为 1 + 2 + 3 + 4 = 10 。
    +
    + +

    示例 2:

    + +
    输入:n = 10
    +输出:37
    +解释:第 10 天后,总额为 (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37 。注意到第二个星期一,Hercy 存入 2 块钱。
    +
    + +

    示例 3:

    + +
    输入:n = 20
    +输出:96
    +解释:第 20 天后,总额为 (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1717.leetcode1717 Maximum Score From Removing Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1717.leetcode1717 Maximum Score From Removing Substrings-zh.md" new file mode 100644 index 00000000..c6f408b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1717.leetcode1717 Maximum Score From Removing Substrings-zh.md" @@ -0,0 +1,85 @@ +# [1717. 删除子字符串的最大得分](https://leetcode-cn.com/problems/maximum-score-from-removing-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1717.Maximum%20Score%20From%20Removing%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s 和两个整数 x 和 y 。你可以执行下面两种操作任意次。

    + +
      +
    • 删除子字符串 "ab" 并得到 x 分。 + +
        +
      • 比方说,从 "cabxbae" 删除 ab ,得到 "cxbae" 。
      • +
      +
    • +
    • 删除子字符串"ba" 并得到 y 分。 +
        +
      • 比方说,从 "cabxbae" 删除 ba ,得到 "cabxe" 。
      • +
      +
    • +
    + +

    请返回对 s 字符串执行上面操作若干次能得到的最大得分。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "cdbcbbaaabab", x = 4, y = 5
    +输出:19
    +解释:
    +- 删除 "cdbcbbaaabab" 中加粗的 "ba" ,得到 s = "cdbcbbaaab" ,加 5 分。
    +- 删除 "cdbcbbaaab" 中加粗的 "ab" ,得到 s = "cdbcbbaa" ,加 4 分。
    +- 删除 "cdbcbbaa" 中加粗的 "ba" ,得到 s = "cdbcba" ,加 5 分。
    +- 删除 "cdbcba" 中加粗的 "ba" ,得到 s = "cdbc" ,加 5 分。
    +总得分为 5 + 4 + 5 + 5 = 19 。
    + +

    示例 2:

    + +
    输入:s = "aabbaaxybbaabb", x = 5, y = 4
    +输出:20
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • 1 <= x, y <= 104
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1718.leetcode1718 Construct the Lexicographically Largest Valid Sequence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1718.leetcode1718 Construct the Lexicographically Largest Valid Sequence-zh.md" new file mode 100644 index 00000000..216774ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1718.leetcode1718 Construct the Lexicographically Largest Valid Sequence-zh.md" @@ -0,0 +1,75 @@ +# [1718. 构建字典序最大的可行序列](https://leetcode-cn.com/problems/construct-the-lexicographically-largest-valid-sequence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1718.Construct%20the%20Lexicographically%20Largest%20Valid%20Sequence/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n ,请你找到满足下面条件的一个序列:

    + +
      +
    • 整数 1 在序列中只出现一次。
    • +
    • 2 到 n 之间每个整数都恰好出现两次。
    • +
    • 对于每个 2 到 n 之间的整数 i ,两个 i 之间出现的距离恰好为 i 。
    • +
    + +

    序列里面两个数 a[i] 和 a[j] 之间的 距离 ,我们定义为它们下标绝对值之差 |j - i| 。

    + +

    请你返回满足上述条件中 字典序最大 的序列。题目保证在给定限制条件下,一定存在解。

    + +

    一个序列 a 被认为比序列 b (两者长度相同)字典序更大的条件是: a 和 b 中第一个不一样的数字处,a 序列的数字比 b 序列的数字大。比方说,[0,1,9,0] 比 [0,1,5,6] 字典序更大,因为第一个不同的位置是第三个数字,且 9 比 5 大。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 3
    +输出:[3,1,2,3,2]
    +解释:[2,3,2,1,3] 也是一个可行的序列,但是 [3,1,2,3,2] 是字典序最大的序列。
    +
    + +

    示例 2:

    + +
    输入:n = 5
    +输出:[5,3,1,4,3,5,2,4,2]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1719.leetcode1719 Number Of Ways To Reconstruct A Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1719.leetcode1719 Number Of Ways To Reconstruct A Tree-zh.md" new file mode 100644 index 00000000..c738e9d6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1719.leetcode1719 Number Of Ways To Reconstruct A Tree-zh.md" @@ -0,0 +1,102 @@ +# [1719. 重构一棵树的方案数](https://leetcode-cn.com/problems/number-of-ways-to-reconstruct-a-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1719.Number%20Of%20Ways%20To%20Reconstruct%20A%20Tree/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 pairs ,其中 pairs[i] = [xi, yi] ,并且满足:

    + +
      +
    • pairs 中没有重复元素
    • +
    • xi < yi
    • +
    + +

    令 ways 为满足下面条件的有根树的方案数:

    + +
      +
    • 树所包含的所有节点值都在 pairs 中。
    • +
    • 一个数对 [xi, yi] 出现在 pairs 中 当且仅当 xi 是 yi 的祖先或者 yi 是 xi 的祖先。
    • +
    • 注意:构造出来的树不一定是二叉树。
    • +
    + +

    两棵树被视为不同的方案当存在至少一个节点在两棵树中有不同的父节点。

    + +

    请你返回:

    + +
      +
    • 如果 ways == 0 ,返回 0 。
    • +
    • 如果 ways == 1 ,返回 1 。
    • +
    • 如果 ways > 1 ,返回 2 。
    • +
    + +

    一棵 有根树 指的是只有一个根节点的树,所有边都是从根往外的方向。

    + +

    我们称从根到一个节点路径上的任意一个节点(除去节点本身)都是该节点的 祖先 。根节点没有祖先。

    + +

     

    + +

    示例 1:

    + +
    +输入:pairs = [[1,2],[2,3]]
    +输出:1
    +解释:如上图所示,有且只有一个符合规定的有根树。
    +
    + +

    示例 2:

    + +
    +输入:pairs = [[1,2],[2,3],[1,3]]
    +输出:2
    +解释:有多个符合规定的有根树,其中三个如上图所示。
    +
    + +

    示例 3:

    + +
    +输入:pairs = [[1,2],[2,3],[2,4],[1,5]]
    +输出:0
    +解释:没有符合规定的有根树。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= pairs.length <= 105
    • +
    • 1 <= xi < yi <= 500
    • +
    • pairs 中的元素互不相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1720.leetcode1720 Decode XORed Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1720.leetcode1720 Decode XORed Array-zh.md" new file mode 100644 index 00000000..75dfeb02 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1720.leetcode1720 Decode XORed Array-zh.md" @@ -0,0 +1,92 @@ +# [1720. 解码异或后的数组](https://leetcode-cn.com/problems/decode-xored-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1720.Decode%20XORed%20Array/README_EN.md) + +## 题目描述 + + + +

    未知 整数数组 arrn 个非负整数组成。

    + +

    经编码后变为长度为 n - 1 的另一个整数数组 encoded ,其中 encoded[i] = arr[i] XOR arr[i + 1] 。例如,arr = [1,0,2,1] 经编码后得到 encoded = [1,2,3]

    + +

    给你编码后的数组 encoded 和原数组 arr 的第一个元素 firstarr[0])。

    + +

    请解码返回原数组 arr 。可以证明答案存在并且是唯一的。

    + +

     

    + +

    示例 1:

    + +
    +输入:encoded = [1,2,3], first = 1
    +输出:[1,0,2,1]
    +解释:若 arr = [1,0,2,1] ,那么 first = 1 且 encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
    +
    + +

    示例 2:

    + +
    +输入:encoded = [6,2,7,3], first = 4
    +输出:[4,2,0,7,4]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 104
    • +
    • encoded.length == n - 1
    • +
    • 0 <= encoded[i] <= 105
    • +
    • 0 <= first <= 105
    • +
    + +## 解法 + + + +异或运算。 + +`a = b ^ c` => `a ^ b = b ^ c ^ b` => `c = a ^ b`。 + + + +### **Python3** + + + +```python +class Solution: + def decode(self, encoded: List[int], first: int) -> List[int]: + res = [first] + for e in encoded: + first ^= e + res.append(first) + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] decode(int[] encoded, int first) { + int[] res = new int[encoded.length + 1]; + res[0] = first; + for (int i = 0; i < encoded.length; ++i) { + res[i + 1] = res[i] ^ encoded[i]; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1721.leetcode1721 Swapping Nodes in a Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1721.leetcode1721 Swapping Nodes in a Linked List-zh.md" new file mode 100644 index 00000000..db761102 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1721.leetcode1721 Swapping Nodes in a Linked List-zh.md" @@ -0,0 +1,132 @@ +# [1721. 交换链表中的节点](https://leetcode-cn.com/problems/swapping-nodes-in-a-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1721.Swapping%20Nodes%20in%20a%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    给你链表的头节点 head 和一个整数 k

    + +

    交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。

    + +

     

    + +

    示例 1:

    + +
    +输入:head = [1,2,3,4,5], k = 2
    +输出:[1,4,3,2,5]
    +
    + +

    示例 2:

    + +
    +输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5
    +输出:[7,9,6,6,8,7,3,0,9,5]
    +
    + +

    示例 3:

    + +
    +输入:head = [1], k = 1
    +输出:[1]
    +
    + +

    示例 4:

    + +
    +输入:head = [1,2], k = 1
    +输出:[2,1]
    +
    + +

    示例 5:

    + +
    +输入:head = [1,2,3], k = 2
    +输出:[1,2,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 链表中节点的数目是 n
    • +
    • 1 <= k <= n <= 105
    • +
    • 0 <= Node.val <= 100
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapNodes(self, head: ListNode, k: int) -> ListNode: + fast = head + for _ in range(k - 1): + fast = fast.next + p = fast + slow = head + while fast.next: + slow, fast = slow.next, fast.next + q = slow + p.val, q.val = q.val, p.val + return head +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapNodes(ListNode head, int k) { + ListNode fast = head; + while (--k > 0) { + fast = fast.next; + } + ListNode p = fast; + ListNode slow = head; + while (fast.next != null) { + slow = slow.next; + fast = fast.next; + } + ListNode q = slow; + int t = p.val; + p.val = q.val; + q.val = t; + return head; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1722.leetcode1722 Minimize Hamming Distance After Swap Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1722.leetcode1722 Minimize Hamming Distance After Swap Operations-zh.md" new file mode 100644 index 00000000..5a0b4798 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1722.leetcode1722 Minimize Hamming Distance After Swap Operations-zh.md" @@ -0,0 +1,83 @@ +# [1722. 执行交换操作后的最小汉明距离](https://leetcode-cn.com/problems/minimize-hamming-distance-after-swap-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1722.Minimize%20Hamming%20Distance%20After%20Swap%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 sourcetarget ,长度都是 n 。还有一个数组 allowedSwaps ,其中每个 allowedSwaps[i] = [ai, bi] 表示你可以交换数组 source 中下标为 aibi下标从 0 开始)的两个元素。注意,你可以按 任意 顺序 多次 交换一对特定下标指向的元素。

    + +

    相同长度的两个数组 sourcetarget 间的 汉明距离 是元素不同的下标数量。形式上,其值等于满足 source[i] != target[i]下标从 0 开始)的下标 i0 <= i <= n-1)的数量。

    + +

    在对数组 source 执行 任意 数量的交换操作后,返回 sourcetarget 间的 最小汉明距离

    + +

     

    + +

    示例 1:

    + +
    输入:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
    +输出:1
    +解释:source 可以按下述方式转换:
    +- 交换下标 0 和 1 指向的元素:source = [2,1,3,4]
    +- 交换下标 2 和 3 指向的元素:source = [2,1,4,3]
    +source 和 target 间的汉明距离是 1 ,二者有 1 处元素不同,在下标 3 。
    +
    + +

    示例 2:

    + +
    输入:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
    +输出:2
    +解释:不能对 source 执行交换操作。
    +source 和 target 间的汉明距离是 2 ,二者有 2 处元素不同,在下标 1 和下标 2 。
    + +

    示例 3:

    + +
    输入:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == source.length == target.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= source[i], target[i] <= 105
    • +
    • 0 <= allowedSwaps.length <= 105
    • +
    • allowedSwaps[i].length == 2
    • +
    • 0 <= ai, bi <= n - 1
    • +
    • ai != bi
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1723.leetcode1723 Find Minimum Time to Finish All Jobs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1723.leetcode1723 Find Minimum Time to Finish All Jobs-zh.md" new file mode 100644 index 00000000..e708f33e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1723.leetcode1723 Find Minimum Time to Finish All Jobs-zh.md" @@ -0,0 +1,73 @@ +# [1723. 完成所有工作的最短时间](https://leetcode-cn.com/problems/find-minimum-time-to-finish-all-jobs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1723.Find%20Minimum%20Time%20to%20Finish%20All%20Jobs/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 jobs ,其中 jobs[i] 是完成第 i 项工作要花费的时间。

    + +

    请你将这些工作分配给 k 位工人。所有工作都应该分配给工人,且每项工作只能分配给一位工人。工人的 工作时间 是完成分配给他们的所有工作花费时间的总和。请你设计一套最佳的工作分配方案,使工人的 最大工作时间 得以 最小化

    + +

    返回分配方案中尽可能 最小最大工作时间

    + +

     

    + +

    示例 1:

    + +
    +输入:jobs = [3,2,3], k = 3
    +输出:3
    +解释:给每位工人分配一项工作,最大工作时间是 3 。
    +
    + +

    示例 2:

    + +
    +输入:jobs = [1,2,4,7,8], k = 2
    +输出:11
    +解释:按下述方式分配工作:
    +1 号工人:1、2、8(工作时间 = 1 + 2 + 8 = 11)
    +2 号工人:4、7(工作时间 = 4 + 7 = 11)
    +最大工作时间是 11 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= jobs.length <= 12
    • +
    • 1 <= jobs[i] <= 107
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1724.leetcode1724 Checking Existence of Edge Length Limited Paths II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1724.leetcode1724 Checking Existence of Edge Length Limited Paths II-zh.md" new file mode 100644 index 00000000..41540213 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1724.leetcode1724 Checking Existence of Edge Length Limited Paths II-zh.md" @@ -0,0 +1,85 @@ +# [1724. 检查边长度限制的路径是否存在 II](https://leetcode-cn.com/problems/checking-existence-of-edge-length-limited-paths-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1724.Checking%20Existence%20of%20Edge%20Length%20Limited%20Paths%20II/README_EN.md) + +## 题目描述 + + + +

    一张有 n 个节点的无向图以边的列表 edgeList 的形式定义,其中 edgeList[i] = [ui, vi, disi] 表示一条连接 ui 和 vi ,距离为 disi 的边。注意,同一对节点间可能有多条边,且该图可能不是连通的。

    + +

    实现 DistanceLimitedPathsExist 类:

    + +
      +
    • DistanceLimitedPathsExist(int n, int[][] edgeList) 以给定的无向图初始化对象。
    • +
    • boolean query(int p, int q, int limit) 当存在一条从 p 到 q 的路径,且路径中每条边的距离都严格小于 limit 时,返回 true ,否则返回 false
    • +
    + +

     

    + +

    示例 1:

    + +

    + +
    输入:
    +["DistanceLimitedPathsExist", "query", "query", "query", "query"]
    +[[6, [[0, 2, 4], [0, 3, 2], [1, 2, 3], [2, 3, 1], [4, 5, 5]]], [2, 3, 2], [1, 3, 3], [2, 0, 3], [0, 5, 6]]
    +输出:
    +[null, true, false, true, false]
    +
    +解释:
    +DistanceLimitedPathsExist distanceLimitedPathsExist = new DistanceLimitedPathsExist(6, [[0, 2, 4], [0, 3, 2], [1, 2, 3], [2, 3, 1], [4, 5, 5]]);
    +distanceLimitedPathsExist.query(2, 3, 2); // 返回 true。存在一条从 2 到 3 ,距离为 1 的边,
    +                                          // 这条边的距离小于 2。
    +distanceLimitedPathsExist.query(1, 3, 3); // 返回 false。从 1 到 3 之间不存在每条边的距离都
    +                                          // 严格小于 3 的路径。
    +distanceLimitedPathsExist.query(2, 0, 3); // 返回 true。存在一条从 2 到 0 的路径,使得每条边的
    +                                          // 距离 < 3:从 2 到 3 到 0 行进即可。
    +distanceLimitedPathsExist.query(0, 5, 6); // 返回 false。从 0 到 5 之间不存在路径。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 104
    • +
    • 0 <= edgeList.length <= 104
    • +
    • edgeList[i].length == 3
    • +
    • 0 <= ui, vi, p, q <= n-1
    • +
    • ui != vi
    • +
    • p != q
    • +
    • 1 <= disi, limit <= 109
    • +
    • 最多调用 104 次 query 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1725.leetcode1725 Number Of Rectangles That Can Form The Largest Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1725.leetcode1725 Number Of Rectangles That Can Form The Largest Square-zh.md" new file mode 100644 index 00000000..a902f561 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1725.leetcode1725 Number Of Rectangles That Can Form The Largest Square-zh.md" @@ -0,0 +1,75 @@ +# [1725. 可以形成最大正方形的矩形数目](https://leetcode-cn.com/problems/number-of-rectangles-that-can-form-the-largest-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1725.Number%20Of%20Rectangles%20That%20Can%20Form%20The%20Largest%20Square/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 个矩形的长度为 li 、宽度为 wi

    + +

    如果存在 k 同时满足 k <= lik <= wi ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 4 的正方形。

    + +

    maxLen 为可以从矩形数组 rectangles 切分得到的 最大正方形 的边长。

    + +

    返回可以切出边长为 maxLen 的正方形的矩形 数目

    + +

     

    + +

    示例 1:

    + +
    +输入:rectangles = [[5,8],[3,9],[5,12],[16,5]]
    +输出:3
    +解释:能从每个矩形中切出的最大正方形边长分别是 [5,3,5,5] 。
    +最大正方形的边长为 5 ,可以由 3 个矩形切分得到。
    +
    + +

    示例 2:

    + +
    +输入:rectangles = [[2,3],[3,7],[4,3],[3,7]]
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rectangles.length <= 1000
    • +
    • rectangles[i].length == 2
    • +
    • 1 <= li, wi <= 109
    • +
    • li != wi
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1726.leetcode1726 Tuple with Same Product-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1726.leetcode1726 Tuple with Same Product-zh.md" new file mode 100644 index 00000000..811897b0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1726.leetcode1726 Tuple with Same Product-zh.md" @@ -0,0 +1,88 @@ +# [1726. 同积元组](https://leetcode-cn.com/problems/tuple-with-same-product) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1726.Tuple%20with%20Same%20Product/README_EN.md) + +## 题目描述 + + + +

    给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 abcd 都是 nums 中的元素,且 a != b != c != d

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,3,4,6]
    +输出:8
    +解释:存在 8 个满足题意的元组:
    +(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
    +(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,2,4,5,10]
    +输出:16
    +解释:存在 16 个满足题意的元组:
    +(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
    +(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
    +(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)
    +(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
    +
    + +

    示例 3:

    + +
    +输入:nums = [2,3,4,6,8,12]
    +输出:40
    +
    + +

    示例 4:

    + +
    +输入:nums = [2,3,5,7]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 104
    • +
    • nums 中的所有元素 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1727.leetcode1727 Largest Submatrix With Rearrangements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1727.leetcode1727 Largest Submatrix With Rearrangements-zh.md" new file mode 100644 index 00000000..3b196274 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1727.leetcode1727 Largest Submatrix With Rearrangements-zh.md" @@ -0,0 +1,91 @@ +# [1727. 重新排列后的最大子矩阵](https://leetcode-cn.com/problems/largest-submatrix-with-rearrangements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1727.Largest%20Submatrix%20With%20Rearrangements/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制矩阵 matrix ,它的大小为 m x n ,你可以将 matrix 中的  按任意顺序重新排列。

    + +

    请你返回最优方案下将 matrix 重新排列后,全是 1 的子矩阵面积。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:matrix = [[0,0,1],[1,1,1],[1,0,1]]
    +输出:4
    +解释:你可以按照上图方式重新排列矩阵的每一列。
    +最大的全 1 子矩阵是上图中加粗的部分,面积为 4 。
    +
    + +

    示例 2:

    + +

    + +
    +输入:matrix = [[1,0,1,0,1]]
    +输出:3
    +解释:你可以按照上图方式重新排列矩阵的每一列。
    +最大的全 1 子矩阵是上图中加粗的部分,面积为 3 。
    +
    + +

    示例 3:

    + +
    +输入:matrix = [[1,1,0],[1,0,1]]
    +输出:2
    +解释:由于你只能整列整列重新排布,所以没有比面积为 2 更大的全 1 子矩形。
    + +

    示例 4:

    + +
    +输入:matrix = [[0,0],[0,0]]
    +输出:0
    +解释:由于矩阵中没有 1 ,没有任何全 1 的子矩阵,所以面积为 0 。
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m * n <= 105
    • +
    • matrix[i][j] 要么是 0 ,要么是 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1728.leetcode1728 Cat and Mouse II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1728.leetcode1728 Cat and Mouse II-zh.md" new file mode 100644 index 00000000..edf4432c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1728.leetcode1728 Cat and Mouse II-zh.md" @@ -0,0 +1,126 @@ +# [1728. 猫和老鼠 II](https://leetcode-cn.com/problems/cat-and-mouse-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1728.Cat%20and%20Mouse%20II/README_EN.md) + +## 题目描述 + + + +

    一只猫和一只老鼠在玩一个叫做猫和老鼠的游戏。

    + +

    它们所处的环境设定是一个 rows x cols 的方格 grid ,其中每个格子可能是一堵墙、一块地板、一位玩家(猫或者老鼠)或者食物。

    + +
      +
    • 玩家由字符 'C' (代表猫)和 'M' (代表老鼠)表示。
    • +
    • 地板由字符 '.' 表示,玩家可以通过这个格子。
    • +
    • 墙用字符 '#' 表示,玩家不能通过这个格子。
    • +
    • 食物用字符 'F' 表示,玩家可以通过这个格子。
    • +
    • 字符 'C' , 'M' 和 'F' 在 grid 中都只会出现一次。
    • +
    + +

    猫和老鼠按照如下规则移动:

    + +
      +
    • 老鼠 先移动 ,然后两名玩家轮流移动。
    • +
    • 每一次操作时,猫和老鼠可以跳到上下左右四个方向之一的格子,他们不能跳过墙也不能跳出 grid 。
    • +
    • catJump 和 mouseJump 是猫和老鼠分别跳一次能到达的最远距离,它们也可以跳小于最大距离的长度。
    • +
    • 它们可以停留在原地。
    • +
    • 老鼠可以跳跃过猫的位置。
    • +
    + +

    游戏有 4 种方式会结束:

    + +
      +
    • 如果猫跟老鼠处在相同的位置,那么猫获胜。
    • +
    • 如果猫先到达食物,那么猫获胜。
    • +
    • 如果老鼠先到达食物,那么老鼠获胜。
    • +
    • 如果老鼠不能在 1000 次操作以内到达食物,那么猫获胜。
    • +
    + +

    给你 rows x cols 的矩阵 grid 和两个整数 catJump 和 mouseJump ,双方都采取最优策略,如果老鼠获胜,那么请你返回 true ,否则返回 false 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2
    +输出:true
    +解释:猫无法抓到老鼠,也没法比老鼠先到达食物。
    +
    + +

    示例 2:

    + +

    + +
    +输入:grid = ["M.C...F"], catJump = 1, mouseJump = 4
    +输出:true
    +
    + +

    示例 3:

    + +
    +输入:grid = ["M.C...F"], catJump = 1, mouseJump = 3
    +输出:false
    +
    + +

    示例 4:

    + +
    +输入:grid = ["C...#","...#F","....#","M...."], catJump = 2, mouseJump = 5
    +输出:false
    +
    + +

    示例 5:

    + +
    +输入:grid = [".M...","..#..","#..#.","C#.#.","...#F"], catJump = 3, mouseJump = 1
    +输出:true
    +
    + +

     

    + +

    提示:

    + +
      +
    • rows == grid.length
    • +
    • cols = grid[i].length
    • +
    • 1 <= rows, cols <= 8
    • +
    • grid[i][j] 只包含字符 'C' ,'M' ,'F' ,'.' 和 '#' 。
    • +
    • grid 中只包含一个 'C' ,'M' 和 'F' 。
    • +
    • 1 <= catJump, mouseJump <= 8
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1729.leetcode1729 Find Followers Count-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1729.leetcode1729 Find Followers Count-zh.md" new file mode 100644 index 00000000..20046f39 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1729.leetcode1729 Find Followers Count-zh.md" @@ -0,0 +1,74 @@ +# [1729. 求关注者的数量](https://leetcode-cn.com/problems/find-followers-count) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1729.Find%20Followers%20Count/README_EN.md) + +## 题目描述 + + + +

    表: Followers

    + +
    +-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| user_id     | int  |
    +| follower_id | int  |
    ++-------------+------+
    +(user_id, follower_id) 是这个表的主键。
    +该表包含一个关注关系中关注者和用户的编号,其中关注者关注用户。
    + +

    写出 SQL 语句,对于每一个用户,返回该用户的关注者数量。

    + +

    按 user_id 的顺序返回结果表。

    + +

    查询结果的格式如下示例所示:

    + +

     

    + +
    Followers 表:
    ++---------+-------------+
    +| user_id | follower_id |
    ++---------+-------------+
    +| 0       | 1           |
    +| 1       | 0           |
    +| 2       | 0           |
    +| 2       | 1           |
    ++---------+-------------+
    +结果表:
    ++---------+----------------+
    +| user_id | followers_count|
    ++---------+----------------+
    +| 0       | 1              |
    +| 1       | 1              |
    +| 2       | 2              |
    ++---------+----------------+
    +0 的关注者有 {1}
    +1 的关注者有 {0}
    +2 的关注者有 {0,1}
    +
    + +

     

    + +## 解法 + + + +`GROUP BY` 实现。 + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + user_id, count(1) AS followers_count +FROM + Followers +GROUP BY + user_id +ORDER BY + user_id +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1730.leetcode1730 Shortest Path to Get Food-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1730.leetcode1730 Shortest Path to Get Food-zh.md" new file mode 100644 index 00000000..055feb08 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1730.leetcode1730 Shortest Path to Get Food-zh.md" @@ -0,0 +1,95 @@ +# [1730. 获取食物的最短路径](https://leetcode-cn.com/problems/shortest-path-to-get-food) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1730.Shortest%20Path%20to%20Get%20Food/README_EN.md) + +## 题目描述 + + + +

    你现在很饿,想要尽快找东西吃。你需要找到最短的路径到达一个食物所在的格子。

    + +

    给定一个 m x n 的字符矩阵 grid ,包含下列不同类型的格子:

    + +
      +
    • '*' 是你的位置。矩阵中有且只有一个 '*' 格子。
    • +
    • '#' 是食物。矩阵中可能存在多个食物。
    • +
    • 'O' 是空地,你可以穿过这些格子。
    • +
    • 'X' 是障碍,你不可以穿过这些格子。
    • +
    + +

    返回你到任意食物的最短路径的长度。如果不存在你到任意食物的路径,返回 -1

    + +

     

    + +

    示例 1:

    + +
    输入: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]]
    +输出: 3
    +解释: 要拿到食物,你需要走 3 步。
    + +

    Example 2:

    + +
    输入: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]]
    +输出: -1
    +解释: 你不可能拿到食物。
    +
    + +

    示例 3:

    + +
    输入: grid = [["X","X","X","X","X","X","X","X"],["X","*","O","X","O","#","O","X"],["X","O","O","X","O","O","X","X"],["X","O","O","O","O","#","O","X"],["X","X","X","X","X","X","X","X"]]
    +输出: 6
    +解释: 这里有多个食物。拿到下边的食物仅需走 6 步。
    + +

    示例 4:

    + +
    输入: grid = [["O","*"],["#","O"]]
    +输出: 2
    +
    + +

    示例 5:

    + +
    输入: grid = [["X","*"],["#","X"]]
    +输出: -1
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 200
    • +
    • grid[row][col] 是 '*'、 'X'、 'O' 或 '#' 。
    • +
    • grid 中有且只有一个 '*' 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1731.leetcode1731 The Number of Employees Which Report to Each Employee-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1731.leetcode1731 The Number of Employees Which Report to Each Employee-zh.md" new file mode 100644 index 00000000..ef724c0d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1731.leetcode1731 The Number of Employees Which Report to Each Employee-zh.md" @@ -0,0 +1,67 @@ +# [1731. 每位经理的下属员工数量](https://leetcode-cn.com/problems/the-number-of-employees-which-report-to-each-employee) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1731.The%20Number%20of%20Employees%20Which%20Report%20to%20Each%20Employee/README_EN.md) + +## 题目描述 + + + +

    Table: Employees

    + +
    +-------------+----------+
    +| Column Name | Type     |
    ++-------------+----------+
    +| employee_id | int      |
    +| name        | varchar  |
    +| reports_to  | int      |
    +| age         | int      |
    ++-------------+----------+
    +employee_id 是这个表的主键.
    +该表包含员工以及需要听取他们汇报的上级经理的ID的信息。 有些员工不需要向任何人汇报(reports_to 为空)。
    +
    + +

     

    + +

    对于此问题,我们将至少有一个其他员工需要向他汇报的员工,视为一个经理。

    + +

    编写SQL查询需要听取汇报的所有经理的ID、名称、直接向该经理汇报的员工人数,以及这些员工的平均年龄,其中该平均年龄需要四舍五入到最接近的整数。

    + +

    返回的结果集需要按照 employee_id 进行排序。

    + +

    查询结果的格式如下:

    + +

     

    + +
    Employees table:
    ++-------------+---------+------------+-----+
    +| employee_id | name    | reports_to | age |
    ++-------------+---------+------------+-----+
    +| 9           | Hercy   | null       | 43  |
    +| 6           | Alice   | 9          | 41  |
    +| 4           | Bob     | 9          | 36  |
    +| 2           | Winston | null       | 37  |
    ++-------------+---------+------------+-----+
    +
    +Result table:
    ++-------------+-------+---------------+-------------+
    +| employee_id | name  | reports_count | average_age |
    ++-------------+-------+---------------+-------------+
    +| 9           | Hercy | 2             | 39          |
    ++-------------+-------+---------------+-------------+
    +Hercy 有两个需要向他汇报的员工, 他们是 Alice and Bob. 他们的平均年龄是 (41+36)/2 = 38.5, 四舍五入的结果是 39.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1732.leetcode1732 Find the Highest Altitude-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1732.leetcode1732 Find the Highest Altitude-zh.md" new file mode 100644 index 00000000..af8c7bcc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1732.leetcode1732 Find the Highest Altitude-zh.md" @@ -0,0 +1,70 @@ +# [1732. 找到最高海拔](https://leetcode-cn.com/problems/find-the-highest-altitude) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1732.Find%20the%20Highest%20Altitude/README_EN.md) + +## 题目描述 + + + +

    有一个自行车手打算进行一场公路骑行,这条路线总共由 n + 1 个不同海拔的点组成。自行车手从海拔为 0 的点 0 开始骑行。

    + +

    给你一个长度为 n 的整数数组 gain ,其中 gain[i] 是点 i 和点 i + 1 的 净海拔高度差0 <= i < n)。请你返回 最高点的海拔

    + +

     

    + +

    示例 1:

    + +
    +输入:gain = [-5,1,5,0,-7]
    +输出:1
    +解释:海拔高度依次为 [0,-5,-4,1,1,-6] 。最高海拔为 1 。
    +
    + +

    示例 2:

    + +
    +输入:gain = [-4,-3,-2,-1,4,3,2]
    +输出:0
    +解释:海拔高度依次为 [0,-4,-7,-9,-10,-6,-3,-1] 。最高海拔为 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == gain.length
    • +
    • 1 <= n <= 100
    • +
    • -100 <= gain[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1733.leetcode1733 Minimum Number of People to Teach-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1733.leetcode1733 Minimum Number of People to Teach-zh.md" new file mode 100644 index 00000000..b6b01cd1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1733.leetcode1733 Minimum Number of People to Teach-zh.md" @@ -0,0 +1,85 @@ +# [1733. 需要教语言的最少人数](https://leetcode-cn.com/problems/minimum-number-of-people-to-teach) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1733.Minimum%20Number%20of%20People%20to%20Teach/README_EN.md) + +## 题目描述 + + + +

    在一个由 m 个用户组成的社交网络里,我们获取到一些用户之间的好友关系。两个用户之间可以相互沟通的条件是他们都掌握同一门语言。

    + +

    给你一个整数 n ,数组 languages 和数组 friendships ,它们的含义如下:

    + +
      +
    • 总共有 n 种语言,编号从 1 到 n 。
    • +
    • languages[i] 是第 i 位用户掌握的语言集合。
    • +
    • friendships[i] = [u​​​​​​i​​​, v​​​​​​i] 表示 u​​​​​​​​​​​i​​​​​ 和 vi 为好友关系。
    • +
    + +

    你可以选择 一门 语言并教会一些用户,使得所有好友之间都可以相互沟通。请返回你 最少 需要教会多少名用户。

    +请注意,好友关系没有传递性,也就是说如果 x 和 y 是好友,且 y 和 z 是好友, x 和 z 不一定是好友。 + +

     

    + +

    示例 1:

    + +
    +输入:n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]
    +输出:1
    +解释:你可以选择教用户 1 第二门语言,也可以选择教用户 2 第一门语言。
    +
    + +

    示例 2:

    + +
    +输入:n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]
    +输出:2
    +解释:教用户 1 和用户 3 第三门语言,需要教 2 名用户。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 500
    • +
    • languages.length == m
    • +
    • 1 <= m <= 500
    • +
    • 1 <= languages[i].length <= n
    • +
    • 1 <= languages[i][j] <= n
    • +
    • 1 <= u​​​​​​i < v​​​​​​i <= languages.length
    • +
    • 1 <= friendships.length <= 500
    • +
    • 所有的好友关系 (u​​​​​i, v​​​​​​i) 都是唯一的。
    • +
    • languages[i] 中包含的值互不相同。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1734.leetcode1734 Decode XORed Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1734.leetcode1734 Decode XORed Permutation-zh.md" new file mode 100644 index 00000000..93591613 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1734.leetcode1734 Decode XORed Permutation-zh.md" @@ -0,0 +1,69 @@ +# [1734. 解码异或后的排列](https://leetcode-cn.com/problems/decode-xored-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1734.Decode%20XORed%20Permutation/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。

    + +

    它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。

    + +

    给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。

    + +

     

    + +

    示例 1:

    + +
    输入:encoded = [3,1]
    +输出:[1,2,3]
    +解释:如果 perm = [1,2,3] ,那么 encoded = [1 XOR 2,2 XOR 3] = [3,1]
    +
    + +

    示例 2:

    + +
    输入:encoded = [6,5,4,6]
    +输出:[2,4,1,5,3]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= n < 105
    • +
    • n 是奇数。
    • +
    • encoded.length == n - 1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1735.leetcode1735 Count Ways to Make Array With Product-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1735.leetcode1735 Count Ways to Make Array With Product-zh.md" new file mode 100644 index 00000000..3f98a030 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1735.leetcode1735 Count Ways to Make Array With Product-zh.md" @@ -0,0 +1,71 @@ +# [1735. 生成乘积数组的方案数](https://leetcode-cn.com/problems/count-ways-to-make-array-with-product) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1735.Count%20Ways%20to%20Make%20Array%20With%20Product/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 queries ,其中 queries[i] = [ni, ki] 。第 i 个查询 queries[i] 要求构造长度为 ni 、每个元素都是正整数的数组,且满足所有元素的乘积为 ki ,请你找出有多少种可行的方案。由于答案可能会很大,方案数需要对 109 + 7 取余

    + +

    请你返回一个整数数组 answer,满足 answer.length == queries.length ,其中 answer[i]是第 i 个查询的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:queries = [[2,6],[5,1],[73,660]]
    +输出:[4,1,50734910]
    +解释:每个查询之间彼此独立。
    +[2,6]:总共有 4 种方案得到长度为 2 且乘积为 6 的数组:[1,6],[2,3],[3,2],[6,1]。
    +[5,1]:总共有 1 种方案得到长度为 5 且乘积为 1 的数组:[1,1,1,1,1]。
    +[73,660]:总共有 1050734917 种方案得到长度为 73 且乘积为 660 的数组。1050734917 对 109 + 7 取余得到 50734910 。
    +
    + +

    示例 2 :

    + +
    +输入:queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]
    +输出:[1,2,3,10,5]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= queries.length <= 104
    • +
    • 1 <= ni, ki <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1736.leetcode1736 Latest Time by Replacing Hidden Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1736.leetcode1736 Latest Time by Replacing Hidden Digits-zh.md" new file mode 100644 index 00000000..813f0037 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1736.leetcode1736 Latest Time by Replacing Hidden Digits-zh.md" @@ -0,0 +1,77 @@ +# [1736. 替换隐藏数字得到的最晚时间](https://leetcode-cn.com/problems/latest-time-by-replacing-hidden-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1736.Latest%20Time%20by%20Replacing%20Hidden%20Digits/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 time ,格式为 hh:mm(小时:分钟),其中某几位数字被隐藏(用 ? 表示)。

    + +

    有效的时间为 00:0023:59 之间的所有时间,包括 00:0023:59

    + +

    替换 time 中隐藏的数字,返回你可以得到的最晚有效时间。

    + +

     

    + +

    示例 1:

    + +
    +输入:time = "2?:?0"
    +输出:"23:50"
    +解释:以数字 '2' 开头的最晚一小时是 23 ,以 '0' 结尾的最晚一分钟是 50 。
    +
    + +

    示例 2:

    + +
    +输入:time = "0?:3?"
    +输出:"09:39"
    +
    + +

    示例 3:

    + +
    +输入:time = "1?:22"
    +输出:"19:22"
    +
    + +

     

    + +

    提示:

    + +
      +
    • time 的格式为 hh:mm
    • +
    • 题目数据保证你可以由输入的字符串生成有效的时间
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1737.leetcode1737 Change Minimum Characters to Satisfy One of Three Conditions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1737.leetcode1737 Change Minimum Characters to Satisfy One of Three Conditions-zh.md" new file mode 100644 index 00000000..721de5e9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1737.leetcode1737 Change Minimum Characters to Satisfy One of Three Conditions-zh.md" @@ -0,0 +1,79 @@ +# [1737. 满足三条件之一需改变的最少字符数](https://leetcode-cn.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1737.Change%20Minimum%20Characters%20to%20Satisfy%20One%20of%20Three%20Conditions/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 ab ,二者均由小写字母组成。一步操作中,你可以将 ab 中的 任一字符 改变为 任一小写字母

    + +

    操作的最终目标是满足下列三个条件 之一

    + +
      +
    • a 中的 每个字母 在字母表中 严格小于 b 中的 每个字母
    • +
    • b 中的 每个字母 在字母表中 严格小于 a 中的 每个字母
    • +
    • ab 同一个 字母组成。
    • +
    + +

    返回达成目标所需的 最少 操作数

    + +

     

    + +

    示例 1:

    + +
    输入:a = "aba", b = "caa"
    +输出:2
    +解释:满足每个条件的最佳方案分别是:
    +1) 将 b 变为 "ccc",2 次操作,满足 a 中的每个字母都小于 b 中的每个字母;
    +2) 将 a 变为 "bbb" 并将 b 变为 "aaa",3 次操作,满足 b 中的每个字母都小于 a 中的每个字母;
    +3) 将 a 变为 "aaa" 并将 b 变为 "aaa",2 次操作,满足 a 和 b 由同一个字母组成。
    +最佳的方案只需要 2 次操作(满足条件 1 或者条件 3)。
    +
    + +

    示例 2:

    + +
    输入:a = "dabadd", b = "cda"
    +输出:3
    +解释:满足条件 1 的最佳方案是将 b 变为 "eee" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= a.length, b.length <= 105
    • +
    • ab 只由小写字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1738.leetcode1738 Find Kth Largest XOR Coordinate Value-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1738.leetcode1738 Find Kth Largest XOR Coordinate Value-zh.md" new file mode 100644 index 00000000..5c1d2587 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1738.leetcode1738 Find Kth Largest XOR Coordinate Value-zh.md" @@ -0,0 +1,82 @@ +# [1738. 找出第 K 大的异或坐标值](https://leetcode-cn.com/problems/find-kth-largest-xor-coordinate-value) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1738.Find%20Kth%20Largest%20XOR%20Coordinate%20Value/README_EN.md) + +## 题目描述 + + + +

    给你一个二维矩阵 matrix 和一个整数 k ,矩阵大小为 m x n 由非负整数组成。

    + +

    矩阵中坐标 (a, b) 可由对所有满足 0 <= i <= a < m0 <= j <= b < n 的元素 matrix[i][j]下标从 0 开始计数)执行异或运算得到。

    + +

    请你找出 matrix 的所有坐标中第 k 大的值(k 的值从 1 开始计数)。

    + +

     

    + +

    示例 1:

    + +
    输入:matrix = [[5,2],[1,6]], k = 1
    +输出:7
    +解释:坐标 (0,1) 的值是 5 XOR 2 = 7 ,为最大的值。
    + +

    示例 2:

    + +
    输入:matrix = [[5,2],[1,6]], k = 2
    +输出:5
    +解释:坐标 (0,0) 的值是 5 = 5 ,为第 2 大的值。
    + +

    示例 3:

    + +
    输入:matrix = [[5,2],[1,6]], k = 3
    +输出:4
    +解释:坐标 (1,0) 的值是 5 XOR 1 = 4 ,为第 3 大的值。
    + +

    示例 4:

    + +
    输入:matrix = [[5,2],[1,6]], k = 4
    +输出:0
    +解释:坐标 (1,1) 的值是 5 XOR 2 XOR 1 XOR 6 = 0 ,为第 4 大的值。
    + +

     

    + +

    提示:

    + +
      +
    • m == matrix.length
    • +
    • n == matrix[i].length
    • +
    • 1 <= m, n <= 1000
    • +
    • 0 <= matrix[i][j] <= 106
    • +
    • 1 <= k <= m * n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1739.leetcode1739 Building Boxes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1739.leetcode1739 Building Boxes-zh.md" new file mode 100644 index 00000000..7ab8fbc1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1739.leetcode1739 Building Boxes-zh.md" @@ -0,0 +1,89 @@ +# [1739. 放置盒子](https://leetcode-cn.com/problems/building-boxes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1739.Building%20Boxes/README_EN.md) + +## 题目描述 + + + +

    有一个立方体房间,其长度、宽度和高度都等于 n 个单位。请你在房间里放置 n 个盒子,每个盒子都是一个单位边长的立方体。放置规则如下:

    + +
      +
    • 你可以把盒子放在地板上的任何地方。
    • +
    • 如果盒子 x 需要放置在盒子 y 的顶部,那么盒子 y 竖直的四个侧面都 必须 与另一个盒子或墙相邻。
    • +
    + +

    给你一个整数 n ,返回接触地面的盒子的 最少 可能数量

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:n = 3
    +输出:3
    +解释:上图是 3 个盒子的摆放位置。
    +这些盒子放在房间的一角,对应左侧位置。
    +
    + +

    示例 2:

    + +

    + +
    +输入:n = 4
    +输出:3
    +解释:上图是 3 个盒子的摆放位置。
    +这些盒子放在房间的一角,对应左侧位置。
    +
    + +

    示例 3:

    + +

    + +
    +输入:n = 10
    +输出:6
    +解释:上图是 10 个盒子的摆放位置。
    +这些盒子放在房间的一角,对应后方位置。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1740.leetcode1740 Find Distance in a Binary Tree-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1740.leetcode1740 Find Distance in a Binary Tree-zh.md" new file mode 100644 index 00000000..0d731c95 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1740.leetcode1740 Find Distance in a Binary Tree-zh.md" @@ -0,0 +1,76 @@ +# [1740. 找到二叉树中的距离](https://leetcode-cn.com/problems/find-distance-in-a-binary-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1740.Find%20Distance%20in%20a%20Binary%20Tree/README_EN.md) + +## 题目描述 + + + +

    给定一棵二叉树的根节点 root 以及两个整数 pq ,返回该二叉树中值为 p 的结点与值为 q 的结点间的 距离

    + +

    两个结点间的 距离 就是从一个结点到另一个结点的路径上边的数目。

    + +

     

    + +

    示例 1:

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
    +输出:3
    +解释:在 5 和 0 之间有 3 条边:5-3-1-0
    + +

    示例 2:

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
    +输出:2
    +解释:在 5 和 7 之间有 2 条边:5-2-7
    + +

    示例 3:

    + +
    +输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
    +输出:0
    +解释:一个结点与它本身之间的距离为 0
    + +

     

    + +

    提示:

    + +
      +
    • 树中结点个数的范围在 [1, 104].
    • +
    • 0 <= Node.val <= 109
    • +
    • 树中所有结点的值都是唯一的.
    • +
    • pq 是树中结点的值.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1741.leetcode1741 Find Total Time Spent by Each Employee-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1741.leetcode1741 Find Total Time Spent by Each Employee-zh.md" new file mode 100644 index 00000000..e5edad40 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1741.leetcode1741 Find Total Time Spent by Each Employee-zh.md" @@ -0,0 +1,77 @@ +# [1741. 查找每个员工花费的总时间](https://leetcode-cn.com/problems/find-total-time-spent-by-each-employee) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1741.Find%20Total%20Time%20Spent%20by%20Each%20Employee/README_EN.md) + +## 题目描述 + + + +

    表: Employees

    + +
    +-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| emp_id      | int  |
    +| event_day   | date |
    +| in_time     | int  |
    +| out_time    | int  |
    ++-------------+------+
    +(emp_id, event_day, in_time) 是这个表的主键。
    +该表显示了员工在办公室的出入情况。
    +event_day 是此事件发生的日期,in_time 是员工进入办公室的时间,而 out_time 是他们离开办公室的时间。
    +in_time 和 out_time 的取值在1到1440之间。
    +题目保证同一天没有两个事件在时间上是相交的,并且保证 in_time 小于 out_time。
    +
    + +

     

    + +

    编写一个SQL查询以计算每位员工每天在办公室花费的总时间(以分钟为单位)。 请注意,在一天之内,同一员工是可以多次进入和离开办公室的。 在办公室里一次进出所花费的时间为out_time 减去 in_time。

    + +

    返回结果表单的顺序无要求。
    +查询结果的格式如下:

    + +
    Employees table:
    ++--------+------------+---------+----------+
    +| emp_id | event_day  | in_time | out_time |
    ++--------+------------+---------+----------+
    +| 1      | 2020-11-28 | 4       | 32       |
    +| 1      | 2020-11-28 | 55      | 200      |
    +| 1      | 2020-12-03 | 1       | 42       |
    +| 2      | 2020-11-28 | 3       | 33       |
    +| 2      | 2020-12-09 | 47      | 74       |
    ++--------+------------+---------+----------+
    +Result table:
    ++------------+--------+------------+
    +| day        | emp_id | total_time |
    ++------------+--------+------------+
    +| 2020-11-28 | 1      | 173        |
    +| 2020-11-28 | 2      | 30         |
    +| 2020-12-03 | 1      | 41         |
    +| 2020-12-09 | 2      | 27         |
    ++------------+--------+------------+
    +雇员 1 有三次进出: 有两次发生在 2020-11-28 花费的时间为 (32 - 4) + (200 - 55) = 173, 有一次发生在 2020-12-03 花费的时间为 (42 - 1) = 41。
    +雇员 2 有两次进出: 有一次发生在 2020-11-28 花费的时间为 (33 - 3) = 30,  有一次发生在 2020-12-09 花费的时间为 (74 - 47) = 27。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + event_day AS day, + emp_id, + SUM(out_time - in_time) AS total_time +FROM + Employees +GROUP BY + emp_id, event_day; +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1742.leetcode1742 Maximum Number of Balls in a Box-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1742.leetcode1742 Maximum Number of Balls in a Box-zh.md" new file mode 100644 index 00000000..4b735997 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1742.leetcode1742 Maximum Number of Balls in a Box-zh.md" @@ -0,0 +1,86 @@ +# [1742. 盒子中小球的最大数量](https://leetcode-cn.com/problems/maximum-number-of-balls-in-a-box) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1742.Maximum%20Number%20of%20Balls%20in%20a%20Box/README_EN.md) + +## 题目描述 + + + +

    你在一家生产小球的玩具厂工作,有 n 个小球,编号从 lowLimit 开始,到 highLimit 结束(包括 lowLimit 和 highLimit ,即 n == highLimit - lowLimit + 1)。另有无限数量的盒子,编号从 1infinity

    + +

    你的工作是将每个小球放入盒子中,其中盒子的编号应当等于小球编号上每位数字的和。例如,编号 321 的小球应当放入编号 3 + 2 + 1 = 6 的盒子,而编号 10 的小球应当放入编号 1 + 0 = 1 的盒子。

    + +

    给你两个整数 lowLimithighLimit ,返回放有最多小球的盒子中的小球数量如果有多个盒子都满足放有最多小球,只需返回其中任一盒子的小球数量。

    + +

     

    + +

    示例 1:

    + +
    +输入:lowLimit = 1, highLimit = 10
    +输出:2
    +解释:
    +盒子编号:1 2 3 4 5 6 7 8 9 10 11 ...
    +小球数量:2 1 1 1 1 1 1 1 1 0  0  ...
    +编号 1 的盒子放有最多小球,小球数量为 2 。
    + +

    示例 2:

    + +
    +输入:lowLimit = 5, highLimit = 15
    +输出:2
    +解释:
    +盒子编号:1 2 3 4 5 6 7 8 9 10 11 ...
    +小球数量:1 1 1 1 2 2 1 1 1 0  0  ...
    +编号 5 和 6 的盒子放有最多小球,每个盒子中的小球数量都是 2 。
    +
    + +

    示例 3:

    + +
    +输入:lowLimit = 19, highLimit = 28
    +输出:2
    +解释:
    +盒子编号:1 2 3 4 5 6 7 8 9 10 11 12 ...
    +小球数量:0 1 1 1 1 1 1 1 1 2  0  0  ...
    +编号 10 的盒子放有最多小球,小球数量为 2 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= lowLimit <= highLimit <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1743.leetcode1743 Restore the Array From Adjacent Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1743.leetcode1743 Restore the Array From Adjacent Pairs-zh.md" new file mode 100644 index 00000000..2310324f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1743.leetcode1743 Restore the Array From Adjacent Pairs-zh.md" @@ -0,0 +1,86 @@ +# [1743. 从相邻元素对还原数组](https://leetcode-cn.com/problems/restore-the-array-from-adjacent-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1743.Restore%20the%20Array%20From%20Adjacent%20Pairs/README_EN.md) + +## 题目描述 + + + +

    存在一个由 n 个不同元素组成的整数数组 nums ,但你已经记不清具体内容。好在你还记得 nums 中的每一对相邻元素。

    + +

    给你一个二维整数数组 adjacentPairs ,大小为 n - 1 ,其中每个 adjacentPairs[i] = [ui, vi] 表示元素 uivinums 中相邻。

    + +

    题目数据保证所有由元素 nums[i]nums[i+1] 组成的相邻元素对都存在于 adjacentPairs 中,存在形式可能是 [nums[i], nums[i+1]] ,也可能是 [nums[i+1], nums[i]] 。这些相邻元素对可以 按任意顺序 出现。

    + +

    返回 原始数组 nums 。如果存在多种解答,返回 其中任意一个 即可。

    + +

     

    + +

    示例 1:

    + +
    +输入:adjacentPairs = [[2,1],[3,4],[3,2]]
    +输出:[1,2,3,4]
    +解释:数组的所有相邻元素对都在 adjacentPairs 中。
    +特别要注意的是,adjacentPairs[i] 只表示两个元素相邻,并不保证其 左-右 顺序。
    +
    + +

    示例 2:

    + +
    +输入:adjacentPairs = [[4,-2],[1,4],[-3,1]]
    +输出:[-2,4,1,-3]
    +解释:数组中可能存在负数。
    +另一种解答是 [-3,1,4,-2] ,也会被视作正确答案。
    +
    + +

    示例 3:

    + +
    +输入:adjacentPairs = [[100000,-100000]]
    +输出:[100000,-100000]
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums.length == n
    • +
    • adjacentPairs.length == n - 1
    • +
    • adjacentPairs[i].length == 2
    • +
    • 2 <= n <= 105
    • +
    • -105 <= nums[i], ui, vi <= 105
    • +
    • 题目数据保证存在一些以 adjacentPairs 作为元素对的数组 nums
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1744.leetcode1744 Can You Eat Your Favorite Candy on Your Favorite Day-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1744.leetcode1744 Can You Eat Your Favorite Candy on Your Favorite Day-zh.md" new file mode 100644 index 00000000..fb13a7e7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1744.leetcode1744 Can You Eat Your Favorite Candy on Your Favorite Day-zh.md" @@ -0,0 +1,86 @@ +# [1744. 你能在你最喜欢的那天吃到你最喜欢的糖果吗?](https://leetcode-cn.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1744.Can%20You%20Eat%20Your%20Favorite%20Candy%20on%20Your%20Favorite%20Day/README_EN.md) + +## 题目描述 + + + +

    给你一个下标从 0 开始的正整数数组 candiesCount ,其中 candiesCount[i] 表示你拥有的第 i 类糖果的数目。同时给你一个二维数组 queries ,其中 queries[i] = [favoriteTypei, favoriteDayi, dailyCapi] 。

    + +

    你按照如下规则进行一场游戏:

    + +
      +
    • 你从第 0 天开始吃糖果。
    • +
    • 你在吃完 所有 第 i - 1 类糖果之前,不能 吃任何一颗第 i 类糖果。
    • +
    • 在吃完所有糖果之前,你必须每天 至少 吃 一颗 糖果。
    • +
    + +

    请你构建一个布尔型数组 answer ,满足 answer.length == queries.lengthanswer[i] 为 true 的条件是:在每天吃 不超过 dailyCapi 颗糖果的前提下,你可以在第 favoriteDayi 天吃到第 favoriteTypei 类糖果;否则 answer[i] 为 false 。注意,只要满足上面 3 条规则中的第二条规则,你就可以在同一天吃不同类型的糖果。

    + +

    请你返回得到的数组 answer 。

    + +

     

    + +

    示例 1:

    + +
    +输入:candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
    +输出:[true,false,true]
    +提示:
    +1- 在第 0 天吃 2 颗糖果(类型 0),第 1 天吃 2 颗糖果(类型 0),第 2 天你可以吃到类型 0 的糖果。
    +2- 每天你最多吃 4 颗糖果。即使第 0 天吃 4 颗糖果(类型 0),第 1 天吃 4 颗糖果(类型 0 和类型 1),你也没办法在第 2 天吃到类型 4 的糖果。换言之,你没法在每天吃 4 颗糖果的限制下在第 2 天吃到第 4 类糖果。
    +3- 如果你每天吃 1 颗糖果,你可以在第 13 天吃到类型 2 的糖果。
    +
    + +

    示例 2:

    + +
    +输入:candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
    +输出:[false,true,true,false,false]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= candiesCount.length <= 105
    • +
    • 1 <= candiesCount[i] <= 105
    • +
    • 1 <= queries.length <= 105
    • +
    • queries[i].length == 3
    • +
    • 0 <= favoriteTypei < candiesCount.length
    • +
    • 0 <= favoriteDayi <= 109
    • +
    • 1 <= dailyCapi <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1745.leetcode1745 Palindrome Partitioning IV-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1745.leetcode1745 Palindrome Partitioning IV-zh.md" new file mode 100644 index 00000000..cfa52f21 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1745.leetcode1745 Palindrome Partitioning IV-zh.md" @@ -0,0 +1,69 @@ +# [1745. 回文串分割 IV](https://leetcode-cn.com/problems/palindrome-partitioning-iv) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1745.Palindrome%20Partitioning%20IV/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,如果可以将它分割成三个 非空 回文子字符串,那么返回 true ,否则返回 false 。

    + +

    当一个字符串正着读和反着读是一模一样的,就称其为 回文字符串

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abcbdd"
    +输出:true
    +解释:"abcbdd" = "a" + "bcb" + "dd",三个子字符串都是回文的。
    +
    + +

    示例 2:

    + +
    +输入:s = "bcbddxy"
    +输出:false
    +解释:s 没办法被分割成 3 个回文子字符串。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= s.length <= 2000
    • +
    • s​​​​​​ 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1746.leetcode1746 Maximum Subarray Sum After One Operation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1746.leetcode1746 Maximum Subarray Sum After One Operation-zh.md" new file mode 100644 index 00000000..af739744 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1746.leetcode1746 Maximum Subarray Sum After One Operation-zh.md" @@ -0,0 +1,67 @@ +# [1746. 经过一次操作后的最大子数组和](https://leetcode-cn.com/problems/maximum-subarray-sum-after-one-operation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1746.Maximum%20Subarray%20Sum%20After%20One%20Operation/README_EN.md) + +## 题目描述 + + + +

    你有一个整数数组 nums。你只能将一个元素 nums[i] 替换为 nums[i] * nums[i]

    + +

    返回替换后的最大子数组和。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [2,-1,-4,-3]
    +输出:17
    +解释:你可以把-4替换为16(-4*(-4)),使nums = [2,-1,16,-3]. 现在,最大子数组和为 2 + -1 + 16 = 17.
    + +

    示例 2:

    + +
    +输入:nums = [1,-1,1,1,-1,-1,1]
    +输出:4
    +解释:你可以把第一个-1替换为1,使 nums = [1,1,1,1,-1,-1,1]. 现在,最大子数组和为 1 + 1 + 1 + 1 = 4.
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1747.leetcode1747 Leetflex Banned Accounts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1747.leetcode1747 Leetflex Banned Accounts-zh.md" new file mode 100644 index 00000000..7f5cfb7a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1747.leetcode1747 Leetflex Banned Accounts-zh.md" @@ -0,0 +1,74 @@ +# [1747. 应该被禁止的Leetflex账户](https://leetcode-cn.com/problems/leetflex-banned-accounts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1747.Leetflex%20Banned%20Accounts/README_EN.md) + +## 题目描述 + + + +

    表: LogInfo

    + +
    +-------------+----------+
    +| Column Name | Type     |
    ++-------------+----------+
    +| account_id  | int      |
    +| ip_address  | int      |
    +| login       | datetime |
    +| logout      | datetime |
    ++-------------+----------+
    +该表是没有主键的,它可能包含重复项。
    +该表包含有关Leetflex帐户的登录和注销日期的信息。 它还包含了该账户用于登录和注销的网络地址的信息。
    +题目确保每一个注销时间都在登录时间之后。
    +
    + +

     

    + +

    编写一个SQL查询语句,查找那些应该被禁止的Leetflex帐户编号account_id。 如果某个帐户在某一时刻从两个不同的网络地址登录了,则这个帐户应该被禁止。

    + +

    可以以任何顺序返回结果。

    + +

    查询结果格式如下例所示:

    + +

     

    + +
    LogInfo table:
    ++------------+------------+---------------------+---------------------+
    +| account_id | ip_address | login               | logout              |
    ++------------+------------+---------------------+---------------------+
    +| 1          | 1          | 2021-02-01 09:00:00 | 2021-02-01 09:30:00 |
    +| 1          | 2          | 2021-02-01 08:00:00 | 2021-02-01 11:30:00 |
    +| 2          | 6          | 2021-02-01 20:30:00 | 2021-02-01 22:00:00 |
    +| 2          | 7          | 2021-02-02 20:30:00 | 2021-02-02 22:00:00 |
    +| 3          | 9          | 2021-02-01 16:00:00 | 2021-02-01 16:59:59 |
    +| 3          | 13         | 2021-02-01 17:00:00 | 2021-02-01 17:59:59 |
    +| 4          | 10         | 2021-02-01 16:00:00 | 2021-02-01 17:00:00 |
    +| 4          | 11         | 2021-02-01 17:00:00 | 2021-02-01 17:59:59 |
    ++------------+------------+---------------------+---------------------+
    +
    +Result table:
    ++------------+
    +| account_id |
    ++------------+
    +| 1          |
    +| 4          |
    ++------------+
    +Account ID 1 --> 该账户从 "2021-02-01 09:00:00" 到 "2021-02-01 09:30:00" 在两个不同的网络地址(1 and 2)上激活了。它应该被禁止.
    +Account ID 2 --> 该账户在两个不同的网络地址 (6, 7) 激活了,但在不同的时间上.
    +Account ID 3 --> 该账户在两个不同的网络地址 (9, 13) 激活了,虽然是同一天,但时间上没有交集.
    +Account ID 4 --> 该账户从 "2021-02-01 17:00:00" 到 "2021-02-01 17:00:00" 在两个不同的网络地址 (10 and 11)上激活了。它应该被禁止.
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1748.leetcode1748 Sum of Unique Elements-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1748.leetcode1748 Sum of Unique Elements-zh.md" new file mode 100644 index 00000000..529523cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1748.leetcode1748 Sum of Unique Elements-zh.md" @@ -0,0 +1,96 @@ +# [1748. 唯一元素的和](https://leetcode-cn.com/problems/sum-of-unique-elements) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1748.Sum%20of%20Unique%20Elements/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。

    + +

    请你返回 nums 中唯一元素的  。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,2]
    +输出:4
    +解释:唯一元素为 [1,3] ,和为 4 。
    +
    + +

    示例 2:

    + +
    输入:nums = [1,1,1,1,1]
    +输出:0
    +解释:没有唯一元素,和为 0 。
    +
    + +

    示例 3 :

    + +
    输入:nums = [1,2,3,4,5]
    +输出:15
    +解释:唯一元素为 [1,2,3,4,5] ,和为 15 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + +## 解法 + + + +定义一个计数器 counter,存放数组每个元素出现的次数。 + +然后遍历 counter 中每个元素,累加次数为 1 的所有下标即可。 + + + +### **Python3** + + + +```python +class Solution: + def sumOfUnique(self, nums: List[int]) -> int: + counter = [0] * 101 + for num in nums: + counter[num] += 1 + return sum([i for i in range(1, 101) if counter[i] == 1]) +``` + +### **Java** + + + +```java +class Solution { + public int sumOfUnique(int[] nums) { + int[] counter = new int[101]; + for (int num : nums) { + ++counter[num]; + } + int res = 0; + for (int i = 1; i < 101; ++i) { + if (counter[i] == 1) { + res += i; + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1749.leetcode1749 Maximum Absolute Sum of Any Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1749.leetcode1749 Maximum Absolute Sum of Any Subarray-zh.md" new file mode 100644 index 00000000..526428ab --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1749.leetcode1749 Maximum Absolute Sum of Any Subarray-zh.md" @@ -0,0 +1,76 @@ +# [1749. 任意子数组和的绝对值的最大值](https://leetcode-cn.com/problems/maximum-absolute-sum-of-any-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1749.Maximum%20Absolute%20Sum%20of%20Any%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 。一个子数组 [numsl, numsl+1, ..., numsr-1, numsr] 的 和的绝对值 为 abs(numsl + numsl+1 + ... + numsr-1 + numsr) 。

    + +

    请你找出 nums 中 和的绝对值 最大的任意子数组(可能为空),并返回该 最大值 。

    + +

    abs(x) 定义如下:

    + +
      +
    • 如果 x 是负整数,那么 abs(x) = -x 。
    • +
    • 如果 x 是非负整数,那么 abs(x) = x 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,-3,2,3,-4]
    +输出:5
    +解释:子数组 [2,3] 和的绝对值最大,为 abs(2+3) = abs(5) = 5 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,-5,1,-4,3,-2]
    +输出:8
    +解释:子数组 [-5,1,-4] 和的绝对值最大,为 abs(-5+1-4) = abs(-8) = 8 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • -104 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1750.leetcode1750 Minimum Length of String After Deleting Similar Ends-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1750.leetcode1750 Minimum Length of String After Deleting Similar Ends-zh.md" new file mode 100644 index 00000000..c4421a18 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1750.leetcode1750 Minimum Length of String After Deleting Similar Ends-zh.md" @@ -0,0 +1,90 @@ +# [1750. 删除字符串两端相同字符后的最短长度](https://leetcode-cn.com/problems/minimum-length-of-string-after-deleting-similar-ends) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1750.Minimum%20Length%20of%20String%20After%20Deleting%20Similar%20Ends/README_EN.md) + +## 题目描述 + + + +

    给你一个只包含字符 'a''b' 和 'c' 的字符串 s ,你可以执行下面这个操作(5 个步骤)任意次:

    + +
      +
    1. 选择字符串 s 一个 非空 的前缀,这个前缀的所有字符都相同。
    2. +
    3. 选择字符串 s 一个 非空 的后缀,这个后缀的所有字符都相同。
    4. +
    5. 前缀和后缀在字符串中任意位置都不能有交集。
    6. +
    7. 前缀和后缀包含的所有字符都要相同。
    8. +
    9. 同时删除前缀和后缀。
    10. +
    + +

    请你返回对字符串 s 执行上面操作任意次以后(可能 0 次),能得到的 最短长度 。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "ca"
    +输出:2
    +解释:你没法删除任何一个字符,所以字符串长度仍然保持不变。
    +
    + +

    示例 2:

    + +
    +输入:s = "cabaabac"
    +输出:0
    +解释:最优操作序列为:
    +- 选择前缀 "c" 和后缀 "c" 并删除它们,得到 s = "abaaba" 。
    +- 选择前缀 "a" 和后缀 "a" 并删除它们,得到 s = "baab" 。
    +- 选择前缀 "b" 和后缀 "b" 并删除它们,得到 s = "aa" 。
    +- 选择前缀 "a" 和后缀 "a" 并删除它们,得到 s = "" 。
    + +

    示例 3:

    + +
    +输入:s = "aabccabba"
    +输出:3
    +解释:最优操作序列为:
    +- 选择前缀 "aa" 和后缀 "a" 并删除它们,得到 s = "bccabb" 。
    +- 选择前缀 "b" 和后缀 "bb" 并删除它们,得到 s = "cca" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s 只包含字符 'a''b' 和 'c' 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1751.leetcode1751 Maximum Number of Events That Can Be Attended II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1751.leetcode1751 Maximum Number of Events That Can Be Attended II-zh.md" new file mode 100644 index 00000000..7aab8284 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1751.leetcode1751 Maximum Number of Events That Can Be Attended II-zh.md" @@ -0,0 +1,85 @@ +# [1751. 最多可以参加的会议数目 II](https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README_EN.md) + +## 题目描述 + + + +

    给你一个 events 数组,其中 events[i] = [startDayi, endDayi, valuei] ,表示第 i 个会议在 startDayi 天开始,第 endDayi 天结束,如果你参加这个会议,你能得到价值 valuei 。同时给你一个整数 k 表示你能参加的最多会议数目。

    + +

    你同一时间只能参加一个会议。如果你选择参加某个会议,那么你必须 完整 地参加完这个会议。会议结束日期是包含在会议内的,也就是说你不能同时参加一个开始日期与另一个结束日期相同的两个会议。

    + +

    请你返回能得到的会议价值 最大和 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
    +输出:7
    +解释:选择绿色的活动会议 0 和 1,得到总价值和为 4 + 3 = 7 。
    + +

    示例 2:

    + +

    + +
    +输入:events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
    +输出:10
    +解释:参加会议 2 ,得到价值和为 10 。
    +你没法再参加别的会议了,因为跟会议 2 有重叠。你  需要参加满 k 个会议。
    + +

    示例 3:

    + +

    + +
    +输入:events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
    +输出:9
    +解释:尽管会议互不重叠,你只能参加 3 个会议,所以选择价值最大的 3 个会议。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= events.length
    • +
    • 1 <= k * events.length <= 106
    • +
    • 1 <= startDayi <= endDayi <= 109
    • +
    • 1 <= valuei <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1752.leetcode1752 Check if Array Is Sorted and Rotated-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1752.leetcode1752 Check if Array Is Sorted and Rotated-zh.md" new file mode 100644 index 00000000..ce20cad1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1752.leetcode1752 Check if Array Is Sorted and Rotated-zh.md" @@ -0,0 +1,101 @@ +# [1752. 检查数组是否经排序和轮转得到](https://leetcode-cn.com/problems/check-if-array-is-sorted-and-rotated) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1752.Check%20if%20Array%20Is%20Sorted%20and%20Rotated/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 numsnums 的源数组中,所有元素与 nums 相同,但按非递减顺序排列。

    + +

    如果 nums 能够由源数组轮转若干位置(包括 0 个位置)得到,则返回 true ;否则,返回 false

    + +

    源数组中可能存在 重复项

    + +

    注意:我们称数组 A 在轮转 x 个位置后得到长度相同的数组 B ,当它们满足 A[i] == B[(i+x) % A.length] ,其中 % 为取余运算。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [3,4,5,1,2]
    +输出:true
    +解释:[1,2,3,4,5] 为有序的源数组。
    +可以轮转 x = 3 个位置,使新数组从值为 3 的元素开始:[3,4,5,1,2] 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,1,3,4]
    +输出:false
    +解释:源数组无法经轮转得到 nums 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,2,3]
    +输出:true
    +解释:[1,2,3] 为有序的源数组。
    +可以轮转 x = 0 个位置(即不轮转)得到 nums 。
    +
    + +

    示例 4:

    + +
    +输入:nums = [1,1,1]
    +输出:true
    +解释:[1,1,1] 为有序的源数组。
    +轮转任意个位置都可以得到 nums 。
    +
    + +

    示例 5:

    + +
    +输入:nums = [2,1]
    +输出:true
    +解释:[1,2] 为有序的源数组。
    +可以轮转 x = 5 个位置,使新数组从值为 2 的元素开始:[2,1] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1753.leetcode1753 Maximum Score From Removing Stones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1753.leetcode1753 Maximum Score From Removing Stones-zh.md" new file mode 100644 index 00000000..6a40a6de --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1753.leetcode1753 Maximum Score From Removing Stones-zh.md" @@ -0,0 +1,93 @@ +# [1753. 移除石子的最大得分](https://leetcode-cn.com/problems/maximum-score-from-removing-stones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1753.Maximum%20Score%20From%20Removing%20Stones/README_EN.md) + +## 题目描述 + + + +

    你正在玩一个单人游戏,面前放置着大小分别为 a​​​​​​、bc​​​​​​ 的 三堆 石子。

    + +

    每回合你都要从两个 不同的非空堆 中取出一颗石子,并在得分上加 1 分。当存在 两个或更多 的空堆时,游戏停止。

    + +

    给你三个整数 abc ,返回可以得到的 最大分数

    +  + +

    示例 1:

    + +
    +输入:a = 2, b = 4, c = 6
    +输出:6
    +解释:石子起始状态是 (2, 4, 6) ,最优的一组操作是:
    +- 从第一和第三堆取,石子状态现在是 (1, 4, 5)
    +- 从第一和第三堆取,石子状态现在是 (0, 4, 4)
    +- 从第二和第三堆取,石子状态现在是 (0, 3, 3)
    +- 从第二和第三堆取,石子状态现在是 (0, 2, 2)
    +- 从第二和第三堆取,石子状态现在是 (0, 1, 1)
    +- 从第二和第三堆取,石子状态现在是 (0, 0, 0)
    +总分:6 分 。
    +
    + +

    示例 2:

    + +
    +输入:a = 4, b = 4, c = 6
    +输出:7
    +解释:石子起始状态是 (4, 4, 6) ,最优的一组操作是:
    +- 从第一和第二堆取,石子状态现在是 (3, 3, 6)
    +- 从第一和第三堆取,石子状态现在是 (2, 3, 5)
    +- 从第一和第三堆取,石子状态现在是 (1, 3, 4)
    +- 从第一和第三堆取,石子状态现在是 (0, 3, 3)
    +- 从第二和第三堆取,石子状态现在是 (0, 2, 2)
    +- 从第二和第三堆取,石子状态现在是 (0, 1, 1)
    +- 从第二和第三堆取,石子状态现在是 (0, 0, 0)
    +总分:7 分 。
    +
    + +

    示例 3:

    + +
    +输入:a = 1, b = 8, c = 8
    +输出:8
    +解释:最优的一组操作是连续从第二和第三堆取 8 回合,直到将它们取空。
    +注意,由于第二和第三堆已经空了,游戏结束,不能继续从第一堆中取石子。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= a, b, c <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1754.leetcode1754 Largest Merge Of Two Strings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1754.leetcode1754 Largest Merge Of Two Strings-zh.md" new file mode 100644 index 00000000..339955e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1754.leetcode1754 Largest Merge Of Two Strings-zh.md" @@ -0,0 +1,90 @@ +# [1754. 构造字典序最大的合并字符串](https://leetcode-cn.com/problems/largest-merge-of-two-strings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1754.Largest%20Merge%20Of%20Two%20Strings/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 word1word2 。你需要按下述方式构造一个新字符串 merge :如果 word1word2 非空,选择 下面选项之一 继续操作:

    + +
      +
    • 如果 word1 非空,将 word1 中的第一个字符附加到 merge 的末尾,并将其从 word1 中移除。 + +
        +
      • 例如,word1 = "abc" merge = "dv" ,在执行此选项操作之后,word1 = "bc" ,同时 merge = "dva"
      • +
      +
    • +
    • 如果 word2 非空,将 word2 中的第一个字符附加到 merge 的末尾,并将其从 word2 中移除。 +
        +
      • 例如,word2 = "abc" merge = "" ,在执行此选项操作之后,word2 = "bc" ,同时 merge = "a"
      • +
      +
    • +
    + +

    返回你可以构造的字典序 最大 的合并字符串 merge

    + +

    长度相同的两个字符串 ab 比较字典序大小,如果在 ab 出现不同的第一个位置,a 中字符在字母表中的出现顺序位于 b 中相应字符之后,就认为字符串 a 按字典序比字符串 b 更大。例如,"abcd" 按字典序比 "abcc" 更大,因为两个字符串出现不同的第一个位置是第四个字符,而 d 在字母表中的出现顺序位于 c 之后。

    + +

     

    + +

    示例 1:

    + +
    +输入:word1 = "cabaa", word2 = "bcaaa"
    +输出:"cbcabaaaaa"
    +解释:构造字典序最大的合并字符串,可行的一种方法如下所示:
    +- 从 word1 中取第一个字符:merge = "c",word1 = "abaa",word2 = "bcaaa"
    +- 从 word2 中取第一个字符:merge = "cb",word1 = "abaa",word2 = "caaa"
    +- 从 word2 中取第一个字符:merge = "cbc",word1 = "abaa",word2 = "aaa"
    +- 从 word1 中取第一个字符:merge = "cbca",word1 = "baa",word2 = "aaa"
    +- 从 word1 中取第一个字符:merge = "cbcab",word1 = "aa",word2 = "aaa"
    +- 将 word1 和 word2 中剩下的 5 个 a 附加到 merge 的末尾。
    +
    + +

    示例 2:

    + +
    +输入:word1 = "abcabc", word2 = "abdcaba"
    +输出:"abdcabcabcaba"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word1.length, word2.length <= 3000
    • +
    • word1word2 仅由小写英文组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1755.leetcode1755 Closest Subsequence Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1755.leetcode1755 Closest Subsequence Sum-zh.md" new file mode 100644 index 00000000..018b12fa --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1755.leetcode1755 Closest Subsequence Sum-zh.md" @@ -0,0 +1,80 @@ +# [1755. 最接近目标值的子序列和](https://leetcode-cn.com/problems/closest-subsequence-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1755.Closest%20Subsequence%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums 和一个目标值 goal

    + +

    你需要从 nums 中选出一个子序列,使子序列元素总和最接近 goal 。也就是说,如果子序列元素和为 sum ,你需要 最小化绝对差 abs(sum - goal)

    + +

    返回 abs(sum - goal) 可能的 最小值

    + +

    注意,数组的子序列是通过移除原始数组中的某些元素(可能全部或无)而形成的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [5,-7,3,5], goal = 6
    +输出:0
    +解释:选择整个数组作为选出的子序列,元素和为 6 。
    +子序列和与目标值相等,所以绝对差为 0 。
    +
    + +

    示例 2:

    + +
    输入:nums = [7,-9,15,-2], goal = -5
    +输出:1
    +解释:选出子序列 [7,-9,-2] ,元素和为 -4 。
    +绝对差为 abs(-4 - (-5)) = abs(1) = 1 ,是可能的最小值。
    +
    + +

    示例 3:

    + +
    输入:nums = [1,2,3], goal = -7
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 40
    • +
    • -107 <= nums[i] <= 107
    • +
    • -109 <= goal <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1756.leetcode1756 Design Most Recently Used Queue-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1756.leetcode1756 Design Most Recently Used Queue-zh.md" new file mode 100644 index 00000000..0d89fc21 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1756.leetcode1756 Design Most Recently Used Queue-zh.md" @@ -0,0 +1,78 @@ +# [1756. 设计最近使用(MRU)队列](https://leetcode-cn.com/problems/design-most-recently-used-queue) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1756.Design%20Most%20Recently%20Used%20Queue/README_EN.md) + +## 题目描述 + + + +

    设计一种类似队列的数据结构,该数据结构将最近使用的元素移到队列尾部。

    + +

    实现 MRUQueue 类:

    + +
      +
    • MRUQueue(int n)  使用 n 个元素: [1,2,3,...,n] 构造 MRUQueue 。
    • +
    • fetch(int k) 将第 k 个元素(从 1 开始索引)移到队尾,并返回该元素。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["MRUQueue", "fetch", "fetch", "fetch", "fetch"]
    +[[8], [3], [5], [2], [8]]
    +输出:
    +[null, 3, 6, 2, 2]
    +
    +解释:
    +MRUQueue mRUQueue = new MRUQueue(8); // 初始化队列为 [1,2,3,4,5,6,7,8]。
    +mRUQueue.fetch(3); // 将第 3 个元素 (3) 移到队尾,使队列变为 [1,2,4,5,6,7,8,3] 并返回该元素。
    +mRUQueue.fetch(5); // 将第 5 个元素 (6) 移到队尾,使队列变为 [1,2,4,5,7,8,3,6] 并返回该元素。
    +mRUQueue.fetch(2); // 将第 2 个元素 (2) 移到队尾,使队列变为 [1,4,5,7,8,3,6,2] 并返回该元素。
    +mRUQueue.fetch(8); // 第 8 个元素 (2) 已经在队列尾部了,所以直接返回该元素即可。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 2000
    • +
    • 1 <= k <= n
    • +
    • 最多调用 2000 次 fetch
    • +
    + +

     

    +进阶:找到每次 fetch 的复杂度为 O(n) 的算法比较简单。你可以找到每次 fetch 的复杂度更佳的算法吗? + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1757.leetcode1757 Recyclable and Low Fat Products-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1757.leetcode1757 Recyclable and Low Fat Products-zh.md" new file mode 100644 index 00000000..a5a40def --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1757.leetcode1757 Recyclable and Low Fat Products-zh.md" @@ -0,0 +1,72 @@ +# [1757. 可回收且低脂的产品](https://leetcode-cn.com/problems/recyclable-and-low-fat-products) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1757.Recyclable%20and%20Low%20Fat%20Products/README_EN.md) + +## 题目描述 + + + +

    表:Products

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_id  | int     |
    +| low_fats    | enum    |
    +| recyclable  | enum    |
    ++-------------+---------+
    +product_id 是这个表的主键。
    +low_fats 是枚举类型,取值为以下两种 ('Y', 'N'),其中 'Y' 表示该产品是低脂产品,'N' 表示不是低脂产品。
    +recyclable 是枚举类型,取值为以下两种 ('Y', 'N'),其中 'Y' 表示该产品可回收,而 'N' 表示不可回收。
    + +

     

    + +

    写出 SQL 语句,查找既是低脂又是可回收的产品编号。

    + +

    返回结果 无顺序要求

    + +

    查询结果格式如下例所示:

    + +
    +Products 表:
    ++-------------+----------+------------+
    +| product_id  | low_fats | recyclable |
    ++-------------+----------+------------+
    +| 0           | Y        | N          |
    +| 1           | Y        | Y          |
    +| 2           | N        | Y          |
    +| 3           | Y        | Y          |
    +| 4           | N        | N          |
    ++-------------+----------+------------+
    +Result 表:
    ++-------------+
    +| product_id  |
    ++-------------+
    +| 1           |
    +| 3           |
    ++-------------+
    +只有产品 id 为 1 和 3 的产品,既是低脂又是可回收的产品。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql +# Write your MySQL query statement below +SELECT + product_id +FROM + Products +WHERE + low_fats = 'Y' +AND recyclable = 'Y'; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1758.leetcode1758 Minimum Changes To Make Alternating Binary String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1758.leetcode1758 Minimum Changes To Make Alternating Binary String-zh.md" new file mode 100644 index 00000000..1d4d10a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1758.leetcode1758 Minimum Changes To Make Alternating Binary String-zh.md" @@ -0,0 +1,103 @@ +# [1758. 生成交替二进制字符串的最少操作数](https://leetcode-cn.com/problems/minimum-changes-to-make-alternating-binary-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1758.Minimum%20Changes%20To%20Make%20Alternating%20Binary%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个仅由字符 '0''1' 组成的字符串 s 。一步操作中,你可以将任一 '0' 变成 '1' ,或者将 '1' 变成 '0'

    + +

    交替字符串 定义为:如果字符串中不存在相邻两个字符相等的情况,那么该字符串就是交替字符串。例如,字符串 "010" 是交替字符串,而字符串 "0100" 不是。

    + +

    返回使 s 变成 交替字符串 所需的 最少 操作数。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "0100"
    +输出:1
    +解释:如果将最后一个字符变为 '1' ,s 就变成 "0101" ,即符合交替字符串定义。
    +
    + +

    示例 2:

    + +
    输入:s = "10"
    +输出:0
    +解释:s 已经是交替字符串。
    +
    + +

    示例 3:

    + +
    输入:s = "1111"
    +输出:2
    +解释:需要 2 步操作得到 "0101" 或 "1010" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 104
    • +
    • s[i]'0''1'
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def minOperations(self, s: str) -> int: + cnt = 0 + for i, c in enumerate(s): + cnt += c == '01'[i & 1] + return min(cnt, len(s) - cnt) +``` + +### **Java** + + + +```java +class Solution { + public int minOperations(String s) { + int cnt = 0, n = s.length(); + for (int i = 0; i < n; ++i) { + cnt += (s.charAt(i) == "01".charAt(i & 1) ? 1 : 0); + } + return Math.min(cnt, n - cnt); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minOperations(string s) { + int cnt = 0, n = s.size(); + for (int i = 0; i < n; ++i) { + cnt += s[i] == "01"[i & 1]; + } + return min(cnt, n - cnt); + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1759.leetcode1759 Count Number of Homogenous Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1759.leetcode1759 Count Number of Homogenous Substrings-zh.md" new file mode 100644 index 00000000..694d48d9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1759.leetcode1759 Count Number of Homogenous Substrings-zh.md" @@ -0,0 +1,81 @@ +# [1759. 统计同构子字符串的数目](https://leetcode-cn.com/problems/count-number-of-homogenous-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1759.Count%20Number%20of%20Homogenous%20Substrings/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,返回 s 同构子字符串 的数目。由于答案可能很大,只需返回对 109 + 7 取余 后的结果。

    + +

    同构字符串 的定义为:如果一个字符串中的所有字符都相同,那么该字符串就是同构字符串。

    + +

    子字符串 是字符串中的一个连续字符序列。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "abbcccaa"
    +输出:13
    +解释:同构子字符串如下所列:
    +"a"   出现 3 次。
    +"aa"  出现 1 次。
    +"b"   出现 2 次。
    +"bb"  出现 1 次。
    +"c"   出现 3 次。
    +"cc"  出现 2 次。
    +"ccc" 出现 1 次。
    +3 + 1 + 2 + 1 + 3 + 2 + 1 = 13
    + +

    示例 2:

    + +
    输入:s = "xy"
    +输出:2
    +解释:同构子字符串是 "x" 和 "y" 。
    + +

    示例 3:

    + +
    输入:s = "zzzzz"
    +输出:15
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s 由小写字符串组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1760.leetcode1760 Minimum Limit of Balls in a Bag-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1760.leetcode1760 Minimum Limit of Balls in a Bag-zh.md" new file mode 100644 index 00000000..8e63bcb0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1760.leetcode1760 Minimum Limit of Balls in a Bag-zh.md" @@ -0,0 +1,183 @@ +# [1760. 袋子里最少数目的球](https://leetcode-cn.com/problems/minimum-limit-of-balls-in-a-bag) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1760.Minimum%20Limit%20of%20Balls%20in%20a%20Bag/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,其中 nums[i] 表示第 i 个袋子里球的数目。同时给你一个整数 maxOperations 。

    + +

    你可以进行如下操作至多 maxOperations 次:

    + +
      +
    • 选择任意一个袋子,并将袋子里的球分到 2 个新的袋子中,每个袋子里都有 正整数 个球。 + +
        +
      • 比方说,一个袋子里有 5 个球,你可以把它们分到两个新袋子里,分别有 1 个和 4 个球,或者分别有 2 个和 3 个球。
      • +
      +
    • + +
    + +

    你的开销是单个袋子里球数目的 最大值 ,你想要 最小化 开销。

    + +

    请你返回进行上述操作后的最小开销。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [9], maxOperations = 2
    +输出:3
    +解释:
    +- 将装有 9 个球的袋子分成装有 6 个和 3 个球的袋子。[9] -> [6,3] 。
    +- 将装有 6 个球的袋子分成装有 3 个和 3 个球的袋子。[6,3] -> [3,3,3] 。
    +装有最多球的袋子里装有 3 个球,所以开销为 3 并返回 3 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,4,8,2], maxOperations = 4
    +输出:2
    +解释:
    +- 将装有 8 个球的袋子分成装有 4 个和 4 个球的袋子。[2,4,8,2] -> [2,4,4,4,2] 。
    +- 将装有 4 个球的袋子分成装有 2 个和 2 个球的袋子。[2,4,4,4,2] -> [2,2,2,4,4,2] 。
    +- 将装有 4 个球的袋子分成装有 2 个和 2 个球的袋子。[2,2,2,4,4,2] -> [2,2,2,2,2,4,2] 。
    +- 将装有 4 个球的袋子分成装有 2 个和 2 个球的袋子。[2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2] 。
    +装有最多球的袋子里装有 2 个球,所以开销为 2 并返回 2 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [7,17], maxOperations = 2
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= maxOperations, nums[i] <= 109
    • +
    + +## 解法 + + + +二分查找。 + +题目可以转换为:对某个开销值,看它能不能在 maxOperations 次操作内得到。二分枚举开销值,找到最小的开销值即可。 + + + +### **Python3** + + + +```python +class Solution: + def minimumSize(self, nums: List[int], maxOperations: int) -> int: + left, right = 1, max(nums) + while left < right: + mid = (left + right) >> 1 + ops = sum([(num - 1) // mid for num in nums]) + if ops <= maxOperations: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int minimumSize(int[] nums, int maxOperations) { + int left = 1, right = 1000000000; + while (left < right) { + int mid = (left + right) >>> 1; + long ops = 0; + for (int num : nums) { + ops += (num - 1) / mid; + } + if (ops <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minimumSize(vector& nums, int maxOperations) { + int left = 1, right = *max_element(nums.begin(), nums.end()); + while (left < right) { + int mid = left + (right - left >> 1); + long long ops = 0; + for (int num : nums) { + ops += (num - 1) / mid; + } + if (ops <= maxOperations) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func minimumSize(nums []int, maxOperations int) int { + left, right := 1, max(nums) + for left < right { + mid := (left + right) >> 1 + var ops int + for _, num := range nums { + ops += (num - 1) / mid + } + if ops <= maxOperations { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func max(nums []int) int { + res := 0 + for _, num := range nums { + if res < num { + res = num + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1761.leetcode1761 Minimum Degree of a Connected Trio in a Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1761.leetcode1761 Minimum Degree of a Connected Trio in a Graph-zh.md" new file mode 100644 index 00000000..18c582bd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1761.leetcode1761 Minimum Degree of a Connected Trio in a Graph-zh.md" @@ -0,0 +1,80 @@ +# [1761. 一个图中连通三元组的最小度数](https://leetcode-cn.com/problems/minimum-degree-of-a-connected-trio-in-a-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1761.Minimum%20Degree%20of%20a%20Connected%20Trio%20in%20a%20Graph/README_EN.md) + +## 题目描述 + + + +

    给你一个无向图,整数 n 表示图中节点的数目,edges 数组表示图中的边,其中 edges[i] = [ui, vi] ,表示 ui 和 vi 之间有一条无向边。

    + +

    一个 连通三元组 指的是 三个 节点组成的集合且这三个点之间 两两 有边。

    + +

    连通三元组的度数 是所有满足此条件的边的数目:一个顶点在这个三元组内,而另一个顶点不在这个三元组内。

    + +

    请你返回所有连通三元组中度数的 最小值 ,如果图中没有连通三元组,那么返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]
    +输出:3
    +解释:只有一个三元组 [1,2,3] 。构成度数的边在上图中已被加粗。
    +
    + +

    示例 2:

    + +
    +输入:n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]
    +输出:0
    +解释:有 3 个三元组:
    +1) [1,4,3],度数为 0 。
    +2) [2,5,6],度数为 2 。
    +3) [5,6,7],度数为 2 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 400
    • +
    • edges[i].length == 2
    • +
    • 1 <= edges.length <= n * (n-1) / 2
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 图中没有重复的边。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1762.leetcode1762 Buildings With an Ocean View-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1762.leetcode1762 Buildings With an Ocean View-zh.md" new file mode 100644 index 00000000..c338c71b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1762.leetcode1762 Buildings With an Ocean View-zh.md" @@ -0,0 +1,84 @@ +# [1762. 能看到海景的建筑物](https://leetcode-cn.com/problems/buildings-with-an-ocean-view) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1762.Buildings%20With%20an%20Ocean%20View/README_EN.md) + +## 题目描述 + + + +

    n 座建筑物。给你一个大小为 n 的整数数组 heights 表示每一个建筑物的高度。

    + +

    建筑物的右边是海洋。如果建筑物可以无障碍地看到海洋,则建筑物能看到海景。确切地说,如果一座建筑物右边的所有建筑都比它 时,就认为它能看到海景。

    + +

    返回能看到海景建筑物的下标列表(下标 0 开始 ),并按升序排列。

    + +

     

    + +

    示例 1:

    + +
    +输入:heights = [4,2,3,1]
    +输出:[0,2,3]
    +解释:1 号建筑物看不到海景,因为 2 号建筑物比它高
    +
    + +

    示例 2:

    + +
    +输入:heights = [4,3,2,1]
    +输出:[0,1,2,3]
    +解释:所有的建筑物都能看到海景。
    + +

    示例 3:

    + +
    +输入:heights = [1,3,2,4]
    +输出:[3]
    +解释:只有 3 号建筑物能看到海景。
    + +

    示例 4:

    + +
    +输入:heights = [2,2,2,2]
    +输出:[3]
    +解释:如果建筑物右边有相同高度的建筑物则无法看到海景。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= heights.length <= 105
    • +
    • 1 <= heights[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1763.leetcode1763 Longest Nice Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1763.leetcode1763 Longest Nice Substring-zh.md" new file mode 100644 index 00000000..44a1ca6a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1763.leetcode1763 Longest Nice Substring-zh.md" @@ -0,0 +1,84 @@ +# [1763. 最长的美好子字符串](https://leetcode-cn.com/problems/longest-nice-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1763.Longest%20Nice%20Substring/README_EN.md) + +## 题目描述 + + + +

    当一个字符串 s 包含的每一种字母的大写和小写形式 同时 出现在 s 中,就称这个字符串 s 是 美好 字符串。比方说,"abABB" 是美好字符串,因为 'A' 和 'a' 同时出现了,且 'B' 和 'b' 也同时出现了。然而,"abA" 不是美好字符串因为 'b' 出现了,而 'B' 没有出现。

    + +

    给你一个字符串 s ,请你返回 s 最长的 美好子字符串 。如果有多个答案,请你返回 最早 出现的一个。如果不存在美好子字符串,请你返回一个空字符串。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "YazaAay"
    +输出:"aAa"
    +解释:"aAa" 是一个美好字符串,因为这个子串中仅含一种字母,其小写形式 'a' 和大写形式 'A' 也同时出现了。
    +"aAa" 是最长的美好子字符串。
    +
    + +

    示例 2:

    + +
    +输入:s = "Bb"
    +输出:"Bb"
    +解释:"Bb" 是美好字符串,因为 'B' 和 'b' 都出现了。整个字符串也是原字符串的子字符串。
    + +

    示例 3:

    + +
    +输入:s = "c"
    +输出:""
    +解释:没有美好子字符串。
    + +

    示例 4:

    + +
    +输入:s = "dDzeE"
    +输出:"dD"
    +解释:"dD" 和 "eE" 都是最长美好子字符串。
    +由于有多个美好子字符串,返回 "dD" ,因为它出现得最早。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s 只包含大写和小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1764.leetcode1764 Form Array by Concatenating Subarrays of Another Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1764.leetcode1764 Form Array by Concatenating Subarrays of Another Array-zh.md" new file mode 100644 index 00000000..cddb003f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1764.leetcode1764 Form Array by Concatenating Subarrays of Another Array-zh.md" @@ -0,0 +1,87 @@ +# [1764. 通过连接另一个数组的子数组得到一个数组](https://leetcode-cn.com/problems/form-array-by-concatenating-subarrays-of-another-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1764.Form%20Array%20by%20Concatenating%20Subarrays%20of%20Another%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的二维整数数组 groups ,同时给你一个整数数组 nums 。

    + +

    你是否可以从 nums 中选出 n 个 不相交 的子数组,使得第 i 个子数组与 groups[i] (下标从 0 开始)完全相同,且如果 i > 0 ,那么第 (i-1) 个子数组在 nums 中出现的位置在第 i 个子数组前面。(也就是说,这些子数组在 nums 中出现的顺序需要与 groups 顺序相同)

    + +

    如果你可以找出这样的 n 个子数组,请你返回 true ,否则返回 false 。

    + +

    如果不存在下标为 k 的元素 nums[k] 属于不止一个子数组,就称这些子数组是 不相交 的。子数组指的是原数组中连续元素组成的一个序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
    +输出:true
    +解释:你可以分别在 nums 中选出第 0 个子数组 [1,-1,0,1,-1,-1,3,-2,0] 和第 1 个子数组 [1,-1,0,1,-1,-1,3,-2,0] 。
    +这两个子数组是不相交的,因为它们没有任何共同的元素。
    +
    + +

    示例 2:

    + +
    +输入:groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]
    +输出:false
    +解释:选择子数组 [1,2,3,4,10,-2] 和 [1,2,3,4,10,-2] 是不正确的,因为它们出现的顺序与 groups 中顺序不同。
    +[10,-2] 必须出现在 [1,2,3,4] 之前。
    +
    + +

    示例 3:

    + +
    +输入:groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]
    +输出:false
    +解释:选择子数组 [7,7,1,2,3,4,7,7] 和 [7,7,1,2,3,4,7,7] 是不正确的,因为它们不是不相交子数组。
    +它们有一个共同的元素 nums[4] (下标从 0 开始)。
    +
    + +

     

    + +

    提示:

    + +
      +
    • groups.length == n
    • +
    • 1 <= n <= 103
    • +
    • 1 <= groups[i].length, sum(groups[i].length) <= 103
    • +
    • 1 <= nums.length <= 103
    • +
    • -107 <= groups[i][j], nums[k] <= 107
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1765.leetcode1765 Map of Highest Peak-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1765.leetcode1765 Map of Highest Peak-zh.md" new file mode 100644 index 00000000..a6b817ea --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1765.leetcode1765 Map of Highest Peak-zh.md" @@ -0,0 +1,93 @@ +# [1765. 地图中的最高点](https://leetcode-cn.com/problems/map-of-highest-peak) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1765.Map%20of%20Highest%20Peak/README_EN.md) + +## 题目描述 + + + +

    给你一个大小为 m x n 的整数矩阵 isWater ,它代表了一个由 陆地 和 水域 单元格组成的地图。

    + +
      +
    • 如果 isWater[i][j] == 0 ,格子 (i, j) 是一个 陆地 格子。
    • +
    • 如果 isWater[i][j] == 1 ,格子 (i, j) 是一个 水域 格子。
    • +
    + +

    你需要按照如下规则给每个单元格安排高度:

    + +
      +
    • 每个格子的高度都必须是非负的。
    • +
    • 如果一个格子是是 水域 ,那么它的高度必须为 0 。
    • +
    • 任意相邻的格子高度差 至多 为 1 。当两个格子在正东、南、西、北方向上相互紧挨着,就称它们为相邻的格子。(也就是说它们有一条公共边)
    • +
    + +

    找到一种安排高度的方案,使得矩阵中的最高高度值 最大 。

    + +

    请你返回一个大小为 m x n 的整数矩阵 height ,其中 height[i][j] 是格子 (i, j) 的高度。如果有多种解法,请返回 任意一个 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:isWater = [[0,1],[0,0]]
    +输出:[[1,0],[2,1]]
    +解释:上图展示了给各个格子安排的高度。
    +蓝色格子是水域格,绿色格子是陆地格。
    +
    + +

    示例 2:

    + +

    + +
    +输入:isWater = [[0,0,1],[1,0,0],[0,0,0]]
    +输出:[[1,1,0],[0,1,1],[1,2,2]]
    +解释:所有安排方案中,最高可行高度为 2 。
    +任意安排方案中,只要最高高度为 2 且符合上述规则的,都为可行方案。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == isWater.length
    • +
    • n == isWater[i].length
    • +
    • 1 <= m, n <= 1000
    • +
    • isWater[i][j] 要么是 0 ,要么是 1 。
    • +
    • 至少有 1 个水域格子。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1766.leetcode1766 Tree of Coprimes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1766.leetcode1766 Tree of Coprimes-zh.md" new file mode 100644 index 00000000..7171f6d1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1766.leetcode1766 Tree of Coprimes-zh.md" @@ -0,0 +1,87 @@ +# [1766. 互质树](https://leetcode-cn.com/problems/tree-of-coprimes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1766.Tree%20of%20Coprimes/README_EN.md) + +## 题目描述 + + + +

    给你一个 n 个节点的树(也就是一个无环连通无向图),节点编号从 0 到 n - 1 ,且恰好有 n - 1 条边,每个节点有一个值。树的 根节点 为 0 号点。

    + +

    给你一个整数数组 nums 和一个二维数组 edges 来表示这棵树。nums[i] 表示第 i 个点的值,edges[j] = [uj, vj] 表示节点 uj 和节点 vj 在树中有一条边。

    + +

    当 gcd(x, y) == 1 ,我们称两个数 x 和 y 是 互质的 ,其中 gcd(x, y) 是 x 和 y 的 最大公约数 。

    + +

    从节点 i 到  最短路径上的点都是节点 i 的祖先节点。一个节点 不是 它自己的祖先节点。

    + +

    请你返回一个大小为 n 的数组 ans ,其中 ans[i]是离节点 i 最近的祖先节点且满足 nums[i] nums[ans[i]] 是 互质的 ,如果不存在这样的祖先节点,ans[i] 为 -1 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
    +输出:[-1,0,0,1]
    +解释:上图中,每个节点的值在括号中表示。
    +- 节点 0 没有互质祖先。
    +- 节点 1 只有一个祖先节点 0 。它们的值是互质的(gcd(2,3) == 1)。
    +- 节点 2 有两个祖先节点,分别是节点 1 和节点 0 。节点 1 的值与它的值不是互质的(gcd(3,3) == 3)但节点 0 的值是互质的(gcd(2,3) == 1),所以节点 0 是最近的符合要求的祖先节点。
    +- 节点 3 有两个祖先节点,分别是节点 1 和节点 0 。它与节点 1 互质(gcd(3,2) == 1),所以节点 1 是离它最近的符合要求的祖先节点。
    +
    + +

    示例 2:

    + +

    + +
    +输入:nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
    +输出:[-1,0,-1,0,0,0,-1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums.length == n
    • +
    • 1 <= nums[i] <= 50
    • +
    • 1 <= n <= 105
    • +
    • edges.length == n - 1
    • +
    • edges[j].length == 2
    • +
    • 0 <= uj, vj < n
    • +
    • uj != vj
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1767.leetcode1767 Find the Subtasks That Did Not Execute-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1767.leetcode1767 Find the Subtasks That Did Not Execute-zh.md" new file mode 100644 index 00000000..f60d169e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1767.leetcode1767 Find the Subtasks That Did Not Execute-zh.md" @@ -0,0 +1,97 @@ +# [1767. 寻找没有被执行的任务对](https://leetcode-cn.com/problems/find-the-subtasks-that-did-not-execute) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1767.Find%20the%20Subtasks%20That%20Did%20Not%20Execute/README_EN.md) + +## 题目描述 + + + +

    表:Tasks

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| task_id        | int     |
    +| subtasks_count | int     |
    ++----------------+---------+
    +task_id 是这个表的主键。
    +task_id 表示的为主任务的id,每一个task_id被分为了多个子任务(subtasks),subtasks_count表示为子任务的个数(n),它的值表示了子任务的索引从1到n。
    +本表保证2 <=subtasks_count<= 20。
    +
    + +

    表: Executed

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| task_id       | int     |
    +| subtask_id    | int     |
    ++---------------+---------+
    +(task_id, subtask_id) 是这个表的主键。
    +每一行表示标记为task_id的主任务与标记为subtask_id的子任务被成功执行。
    +本表保证,对于每一个task_id,subtask_id <= subtasks_count。
    +
    + +

     

    + +

    请试写一个SQL查询语句报告没有被执行的(主任务,子任务)对,即没有被执行的(task_id, subtask_id)。

    + +

    任何顺序 返回即可。

    + +

    查询结果格式如下:

    + +

     

    + +
    +Tasks table:
    ++---------+----------------+
    +| task_id | subtasks_count |
    ++---------+----------------+
    +| 1       | 3              |
    +| 2       | 2              |
    +| 3       | 4              |
    ++---------+----------------+
    +
    +Executed table:
    ++---------+------------+
    +| task_id | subtask_id |
    ++---------+------------+
    +| 1       | 2          |
    +| 3       | 1          |
    +| 3       | 2          |
    +| 3       | 3          |
    +| 3       | 4          |
    ++---------+------------+
    +
    +Result table:
    ++---------+------------+
    +| task_id | subtask_id |
    ++---------+------------+
    +| 1       | 1          |
    +| 1       | 3          |
    +| 2       | 1          |
    +| 2       | 2          |
    ++---------+------------+
    +Task 1 被分成了 3 subtasks (1, 2, 3)。只有 subtask 2 被成功执行, 所以我们返回 (1, 1) 和 (1, 3) 这两个主任务子任务对。
    +Task 2 被分成了 2 subtasks (1, 2)。没有一个subtask被成功执行, 因此我们返回(2, 1)和(2, 2)。
    +Task 3 被分成了 4 subtasks (1, 2, 3, 4)。所有的subtask都被成功执行,因此对于Task 3,我们不返回任何值。
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1768.leetcode1768 Merge Strings Alternately-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1768.leetcode1768 Merge Strings Alternately-zh.md" new file mode 100644 index 00000000..0aa5efdf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1768.leetcode1768 Merge Strings Alternately-zh.md" @@ -0,0 +1,131 @@ +# [1768. 交替合并字符串](https://leetcode-cn.com/problems/merge-strings-alternately) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1768.Merge%20Strings%20Alternately/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 word1word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。

    + +

    返回 合并后的字符串

    + +

     

    + +

    示例 1:

    + +
    +输入:word1 = "abc", word2 = "pqr"
    +输出:"apbqcr"
    +解释:字符串合并情况如下所示:
    +word1:  a   b   c
    +word2:    p   q   r
    +合并后:  a p b q c r
    +
    + +

    示例 2:

    + +
    +输入:word1 = "ab", word2 = "pqrs"
    +输出:"apbqrs"
    +解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。
    +word1:  a   b 
    +word2:    p   q   r   s
    +合并后:  a p b q   r   s
    +
    + +

    示例 3:

    + +
    +输入:word1 = "abcd", word2 = "pq"
    +输出:"apbqcd"
    +解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。
    +word1:  a   b   c   d
    +word2:    p   q 
    +合并后:  a p b q c   d
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word1.length, word2.length <= 100
    • +
    • word1word2 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + i, m, n = 0, len(word1), len(word2) + res = [] + while i < m or i < n: + if i < m: + res.append(word1[i]) + if i < n: + res.append(word2[i]) + i += 1 + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String mergeAlternately(String word1, String word2) { + int m = word1.length(), n = word2.length(); + StringBuilder res = new StringBuilder(); + for (int i = 0; i < m || i < n; ++i) { + if (i < m) { + res.append(word1.charAt(i)); + } + if (i < n) { + res.append(word2.charAt(i)); + } + } + return res.toString(); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string mergeAlternately(string word1, string word2) { + int m = word1.size(), n = word2.size(); + string res; + for (int i = 0; i < m || i < n; ++i) { + if (i < m) { + res.push_back(word1[i]); + } + if (i < n) { + res.push_back(word2[i]); + } + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1769.leetcode1769 Minimum Number of Operations to Move All Balls to Each Box-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1769.leetcode1769 Minimum Number of Operations to Move All Balls to Each Box-zh.md" new file mode 100644 index 00000000..22787c11 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1769.leetcode1769 Minimum Number of Operations to Move All Balls to Each Box-zh.md" @@ -0,0 +1,73 @@ +# [1769. 移动所有球到每个盒子所需的最小操作数](https://leetcode-cn.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1769.Minimum%20Number%20of%20Operations%20to%20Move%20All%20Balls%20to%20Each%20Box/README_EN.md) + +## 题目描述 + + + +

    n 个盒子。给你一个长度为 n 的二进制字符串 boxes ,其中 boxes[i] 的值为 '0' 表示第 i 个盒子是 的,而 boxes[i] 的值为 '1' 表示盒子里有 一个 小球。

    + +

    在一步操作中,你可以将 一个 小球从某个盒子移动到一个与之相邻的盒子中。第 i 个盒子和第 j 个盒子相邻需满足 abs(i - j) == 1 。注意,操作执行后,某些盒子中可能会存在不止一个小球。

    + +

    返回一个长度为 n 的数组 answer ,其中 answer[i] 是将所有小球移动到第 i 个盒子所需的 最小 操作数。

    + +

    每个 answer[i] 都需要根据盒子的 初始状态 进行计算。

    + +

     

    + +

    示例 1:

    + +
    输入:boxes = "110"
    +输出:[1,1,3]
    +解释:每个盒子对应的最小操作数如下:
    +1) 第 1 个盒子:将一个小球从第 2 个盒子移动到第 1 个盒子,需要 1 步操作。
    +2) 第 2 个盒子:将一个小球从第 1 个盒子移动到第 2 个盒子,需要 1 步操作。
    +3) 第 3 个盒子:将一个小球从第 1 个盒子移动到第 3 个盒子,需要 2 步操作。将一个小球从第 2 个盒子移动到第 3 个盒子,需要 1 步操作。共计 3 步操作。
    +
    + +

    示例 2:

    + +
    输入:boxes = "001011"
    +输出:[11,8,5,4,3,4]
    + +

     

    + +

    提示:

    + +
      +
    • n == boxes.length
    • +
    • 1 <= n <= 2000
    • +
    • boxes[i]'0''1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1770.leetcode1770 Maximum Score from Performing Multiplication Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1770.leetcode1770 Maximum Score from Performing Multiplication Operations-zh.md" new file mode 100644 index 00000000..4daba9ca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1770.leetcode1770 Maximum Score from Performing Multiplication Operations-zh.md" @@ -0,0 +1,87 @@ +# [1770. 执行乘法运算的最大分数](https://leetcode-cn.com/problems/maximum-score-from-performing-multiplication-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1770.Maximum%20Score%20from%20Performing%20Multiplication%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你两个长度分别 nm 的整数数组 numsmultipliers ,其中 n >= m ,数组下标 从 1 开始 计数。

    + +

    初始时,你的分数为 0 。你需要执行恰好 m 步操作。在第 i 步操作(从 1 开始 计数)中,需要:

    + +
      +
    • 选择数组 nums 开头处或者末尾处 的整数 x
    • +
    • 你获得 multipliers[i] * x 分,并累加到你的分数中。
    • +
    • x 从数组 nums 中移除。
    • +
    + +

    在执行 m 步操作后,返回 最大 分数

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3], multipliers = [3,2,1]
    +输出:14
    +解释:一种最优解决方案如下:
    +- 选择末尾处的整数 3 ,[1,2,3] ,得 3 * 3 = 9 分,累加到分数中。
    +- 选择末尾处的整数 2 ,[1,2] ,得 2 * 2 = 4 分,累加到分数中。
    +- 选择末尾处的整数 1 ,[1] ,得 1 * 1 = 1 分,累加到分数中。
    +总分数为 9 + 4 + 1 = 14 。
    + +

    示例 2:

    + +
    输入:nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
    +输出:102
    +解释:一种最优解决方案如下:
    +- 选择开头处的整数 -5 ,[-5,-3,-3,-2,7,1] ,得 -5 * -10 = 50 分,累加到分数中。
    +- 选择开头处的整数 -3 ,[-3,-3,-2,7,1] ,得 -3 * -5 = 15 分,累加到分数中。
    +- 选择开头处的整数 -3 ,[-3,-2,7,1] ,得 -3 * 3 = -9 分,累加到分数中。
    +- 选择末尾处的整数 1 ,[-2,7,1] ,得 1 * 4 = 4 分,累加到分数中。
    +- 选择末尾处的整数 7 ,[-2,7] ,得 7 * 6 = 42 分,累加到分数中。
    +总分数为 50 + 15 - 9 + 4 + 42 = 102 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • m == multipliers.length
    • +
    • 1 <= m <= 103
    • +
    • m <= n <= 105
    • +
    • -1000 <= nums[i], multipliers[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1771.leetcode1771 Maximize Palindrome Length From Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1771.leetcode1771 Maximize Palindrome Length From Subsequences-zh.md" new file mode 100644 index 00000000..34f8e932 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1771.leetcode1771 Maximize Palindrome Length From Subsequences-zh.md" @@ -0,0 +1,81 @@ +# [1771. 由子序列构造的最长回文串的长度](https://leetcode-cn.com/problems/maximize-palindrome-length-from-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1771.Maximize%20Palindrome%20Length%20From%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 word1word2 ,请你按下述方法构造一个字符串:

    + +
      +
    • word1 中选出某个 非空 子序列 subsequence1
    • +
    • word2 中选出某个 非空 子序列 subsequence2
    • +
    • 连接两个子序列 subsequence1 + subsequence2 ,得到字符串。
    • +
    + +

    返回可按上述方法构造的最长 回文串长度 。如果无法构造回文串,返回 0

    + +

    字符串 s 的一个 子序列 是通过从 s 中删除一些(也可能不删除)字符而不更改其余字符的顺序生成的字符串。

    + +

    回文串 是正着读和反着读结果一致的字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:word1 = "cacb", word2 = "cbba"
    +输出:5
    +解释:从 word1 中选出 "ab" ,从 word2 中选出 "cba" ,得到回文串 "abcba" 。
    + +

    示例 2:

    + +
    输入:word1 = "ab", word2 = "ab"
    +输出:3
    +解释:从 word1 中选出 "ab" ,从 word2 中选出 "a" ,得到回文串 "aba" 。
    + +

    示例 3:

    + +
    输入:word1 = "aa", word2 = "bb"
    +输出:0
    +解释:无法按题面所述方法构造回文串,所以返回 0 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word1.length, word2.length <= 1000
    • +
    • word1word2 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1772.leetcode1772 Sort Features by Popularity-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1772.leetcode1772 Sort Features by Popularity-zh.md" new file mode 100644 index 00000000..4c7d9125 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1772.leetcode1772 Sort Features by Popularity-zh.md" @@ -0,0 +1,117 @@ +# [1772. 按受欢迎程度排列功能](https://leetcode-cn.com/problems/sort-features-by-popularity) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1772.Sort%20Features%20by%20Popularity/README_EN.md) + +## 题目描述 + + + +

    给定一个字符串数组 features ,其中 features[i] 是一个单词,描述你最近参与开发的项目中一个功能的名称。你调查了用户喜欢哪些功能。另给定一个字符串数组 responses,其中 responses[i] 是一个包含以空格分隔的一系列单词的字符串。

    + +

    你想要按照受欢迎程度排列这些功能。 严格地说,令 appearances(word) 是满足 responses[i] 中包含单词 word 的 i 的个数,则当 appearances(features[x]) > appearances(features[y]) 时,第 x 个功能比第 y 个功能更受欢迎。

    + +

    返回一个数组 sortedFeatures ,包含按受欢迎程度排列的功能名称。当第 x  个功能和第 y 个功能的受欢迎程度相同且 x < y 时,你应当将第 x 个功能放在第 y 个功能之前。

    + +

     

    + +

    示例 1:

    + +
    +输入features = ["cooler","lock","touch"], responses = ["i like cooler cooler","lock touch cool","locker like touch"]
    +输出["touch","cooler","lock"]
    +解释appearances("cooler") = 1,appearances("lock") = 1,appearances("touch") = 2。由于 "cooler" 和 "lock" 都出现了 1 次,且 "cooler" 在原数组的前面,所以 "cooler" 也应该在结果数组的前面。
    +
    + +

    示例 2:

    + +
    +输入features = ["a","aa","b","c"], responses = ["a","a aa","a a a a a","b a"]
    +输出["a","aa","b","c"]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= features.length <= 104
    • +
    • 1 <= features[i].length <= 10
    • +
    • features 不包含重复项。
    • +
    • features[i] 由小写字母构成。
    • +
    • 1 <= responses.length <= 102
    • +
    • 1 <= responses[i].length <= 103
    • +
    • responses[i] 由小写字母和空格组成。
    • +
    • responses[i] 不包含两个连续的空格。
    • +
    • responses[i] 没有前置或后置空格。
    • +
    + +## 解法 + + + +“哈希表 + 计数器”实现。 + + + +### **Python3** + + + +```python +class Solution: + def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: + feature_set = set(features) + counter = collections.Counter() + for resp in responses: + for feat in set(resp.split(' ')): + if feat in feature_set: + counter[feat] += 1 + order = {feat: i for i, feat in enumerate(features)} + return sorted(features, key=lambda feat: (-counter[feat], order[feat])) +``` + +### **Java** + + + +```java +class Solution { + public String[] sortFeatures(String[] features, String[] responses) { + Set featureSet = new HashSet<>(); + Map order = new HashMap<>(); + for (int i = 0; i < features.length; ++i) { + featureSet.add(features[i]); + order.put(features[i], i); + } + + Map counter = new HashMap<>(); + for (String resp : responses) { + Set s = new HashSet<>(); + String[] words = resp.split(" "); + for (String word : words) { + s.add(word); + } + for (String word : s) { + if (featureSet.contains(word)) { + counter.put(word, counter.getOrDefault(word, 0) + 1); + } + } + } + String[] copyFeatures = Arrays.copyOf(features, features.length); + Arrays.sort(copyFeatures, (a, b) -> { + // 自定义排序比较器,先按照词频大小从高到低排,若词频相等,再根据features顺序从小到大排 + int diff = counter.getOrDefault(b, 0) - counter.getOrDefault(a, 0); + return diff == 0 ? order.get(a) - order.get(b) : diff; + }); + return copyFeatures; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1773.leetcode1773 Count Items Matching a Rule-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1773.leetcode1773 Count Items Matching a Rule-zh.md" new file mode 100644 index 00000000..f46c32ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1773.leetcode1773 Count Items Matching a Rule-zh.md" @@ -0,0 +1,80 @@ +# [1773. 统计匹配检索规则的物品数量](https://leetcode-cn.com/problems/count-items-matching-a-rule) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1773.Count%20Items%20Matching%20a%20Rule/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。

    + +

    另给你一条由两个字符串 ruleKeyruleValue 表示的检索规则。

    + +

    如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配

    + +
      +
    • ruleKey == "type"ruleValue == typei
    • +
    • ruleKey == "color"ruleValue == colori
    • +
    • ruleKey == "name"ruleValue == namei
    • +
    + +

    统计并返回 匹配检索规则的物品数量

    + +

     

    + +

    示例 1:

    + +
    +输入:items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
    +输出:1
    +解释:只有一件物品匹配检索规则,这件物品是 ["computer","silver","lenovo"] 。
    +
    + +

    示例 2:

    + +
    +输入:items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
    +输出:2
    +解释:只有两件物品匹配检索规则,这两件物品分别是 ["phone","blue","pixel"] 和 ["phone","gold","iphone"] 。注意,["computer","silver","phone"] 未匹配检索规则。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= items.length <= 104
    • +
    • 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
    • +
    • ruleKey 等于 "type""color""name"
    • +
    • 所有字符串仅由小写字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1774.leetcode1774 Closest Dessert Cost-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1774.leetcode1774 Closest Dessert Cost-zh.md" new file mode 100644 index 00000000..12822df2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1774.leetcode1774 Closest Dessert Cost-zh.md" @@ -0,0 +1,112 @@ +# [1774. 最接近目标价格的甜点成本](https://leetcode-cn.com/problems/closest-dessert-cost) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1774.Closest%20Dessert%20Cost/README_EN.md) + +## 题目描述 + + + +

    你打算做甜点,现在需要购买配料。目前共有 n 种冰激凌基料和 m 种配料可供选购。而制作甜点需要遵循以下几条规则:

    + +
      +
    • 必须选择 一种 冰激凌基料。
    • +
    • 可以添加 一种或多种 配料,也可以不添加任何配料。
    • +
    • 每种类型的配料 最多两份
    • +
    + +

    给你以下三个输入:

    + +
      +
    • baseCosts ,一个长度为 n 的整数数组,其中每个 baseCosts[i] 表示第 i 种冰激凌基料的价格。
    • +
    • toppingCosts,一个长度为 m 的整数数组,其中每个 toppingCosts[i] 表示 一份i 种冰激凌配料的价格。
    • +
    • target ,一个整数,表示你制作甜点的目标价格。
    • +
    + +

    你希望自己做的甜点总成本尽可能接近目标价格 target

    + +

    返回最接近 target 的甜点成本。如果有多种方案,返回 成本相对较低 的一种。

    + +

     

    + +

    示例 1:

    + +
    +输入:baseCosts = [1,7], toppingCosts = [3,4], target = 10
    +输出:10
    +解释:考虑下面的方案组合(所有下标均从 0 开始):
    +- 选择 1 号基料:成本 7
    +- 选择 1 份 0 号配料:成本 1 x 3 = 3
    +- 选择 0 份 1 号配料:成本 0 x 4 = 0
    +总成本:7 + 3 + 0 = 10 。
    +
    + +

    示例 2:

    + +
    +输入:baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
    +输出:17
    +解释:考虑下面的方案组合(所有下标均从 0 开始):
    +- 选择 1 号基料:成本 3
    +- 选择 1 份 0 号配料:成本 1 x 4 = 4
    +- 选择 2 份 1 号配料:成本 2 x 5 = 10
    +- 选择 0 份 2 号配料:成本 0 x 100 = 0
    +总成本:3 + 4 + 10 + 0 = 17 。不存在总成本为 18 的甜点制作方案。
    +
    + +

    示例 3:

    + +
    +输入:baseCosts = [3,10], toppingCosts = [2,5], target = 9
    +输出:8
    +解释:可以制作总成本为 8 和 10 的甜点。返回 8 ,因为这是成本更低的方案。
    +
    + +

    示例 4:

    + +
    +输入:baseCosts = [10], toppingCosts = [1], target = 1
    +输出:10
    +解释:注意,你可以选择不添加任何配料,但你必须选择一种基料。
    + +

     

    + +

    提示:

    + +
      +
    • n == baseCosts.length
    • +
    • m == toppingCosts.length
    • +
    • 1 <= n, m <= 10
    • +
    • 1 <= baseCosts[i], toppingCosts[i] <= 104
    • +
    • 1 <= target <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1775.leetcode1775 Equal Sum Arrays With Minimum Number of Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1775.leetcode1775 Equal Sum Arrays With Minimum Number of Operations-zh.md" new file mode 100644 index 00000000..c7263415 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1775.leetcode1775 Equal Sum Arrays With Minimum Number of Operations-zh.md" @@ -0,0 +1,82 @@ +# [1775. 通过最少操作次数使数组的和相等](https://leetcode-cn.com/problems/equal-sum-arrays-with-minimum-number-of-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1775.Equal%20Sum%20Arrays%20With%20Minimum%20Number%20of%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你两个长度可能不等的整数数组 nums1 和 nums2 。两个数组中的所有值都在 1 到 6 之间(包含 1 和 6)。

    + +

    每次操作中,你可以选择 任意 数组中的任意一个整数,将它变成 1 到 6 之间 任意 的值(包含 1 和 6)。

    + +

    请你返回使 nums1 中所有数的和与 nums2 中所有数的和相等的最少操作次数。如果无法使两个数组的和相等,请返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
    +输出:3
    +解释:你可以通过 3 次操作使 nums1 中所有数的和与 nums2 中所有数的和相等。以下数组下标都从 0 开始。
    +- 将 nums2[0] 变为 6 。 nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2] 。
    +- 将 nums1[5] 变为 1 。 nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2] 。
    +- 将 nums1[2] 变为 2 。 nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2] 。
    +
    + +

    示例 2:

    + +
    输入:nums1 = [1,1,1,1,1,1,1], nums2 = [6]
    +输出:-1
    +解释:没有办法减少 nums1 的和或者增加 nums2 的和使二者相等。
    +
    + +

    示例 3:

    + +
    输入:nums1 = [6,6], nums2 = [1]
    +输出:3
    +解释:你可以通过 3 次操作使 nums1 中所有数的和与 nums2 中所有数的和相等。以下数组下标都从 0 开始。
    +- 将 nums1[0] 变为 2 。 nums1 = [2,6], nums2 = [1] 。
    +- 将 nums1[1] 变为 2 。 nums1 = [2,2], nums2 = [1] 。
    +- 将 nums2[0] 变为 4 。 nums1 = [2,2], nums2 = [4] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length, nums2.length <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 6
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1776.leetcode1776 Car Fleet II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1776.leetcode1776 Car Fleet II-zh.md" new file mode 100644 index 00000000..24c8f3e0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1776.leetcode1776 Car Fleet II-zh.md" @@ -0,0 +1,76 @@ +# [1776. 车队 II](https://leetcode-cn.com/problems/car-fleet-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1776.Car%20Fleet%20II/README_EN.md) + +## 题目描述 + + + +

    在一条单车道上有 n 辆车,它们朝着同样的方向行驶。给你一个长度为 n 的数组 cars ,其中 cars[i] = [positioni, speedi] ,它表示:

    + +
      +
    • positioni 是第 i 辆车和道路起点之间的距离(单位:米)。题目保证 positioni < positioni+1 
    • +
    • speedi 是第 i 辆车的初始速度(单位:米/秒)。
    • +
    + +

    简单起见,所有车子可以视为在数轴上移动的点。当两辆车占据同一个位置时,我们称它们相遇了。一旦两辆车相遇,它们会合并成一个车队,这个车队里的车有着同样的位置和相同的速度,速度为这个车队里 最慢 一辆车的速度。

    + +

    请你返回一个数组 answer ,其中 answer[i] 是第 i 辆车与下一辆车相遇的时间(单位:秒),如果这辆车不会与下一辆车相遇,则 answer[i] 为 -1 。答案精度误差需在 10-5 以内。

    + +

     

    + +

    示例 1:

    + +
    +输入:cars = [[1,2],[2,1],[4,3],[7,2]]
    +输出:[1.00000,-1.00000,3.00000,-1.00000]
    +解释:经过恰好 1 秒以后,第一辆车会与第二辆车相遇,并形成一个 1 m/s 的车队。经过恰好 3 秒以后,第三辆车会与第四辆车相遇,并形成一个 2 m/s 的车队。
    +
    + +

    示例 2:

    + +
    +输入:cars = [[3,4],[5,4],[6,3],[9,1]]
    +输出:[2.00000,1.00000,1.50000,-1.00000]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= cars.length <= 105
    • +
    • 1 <= positioni, speedi <= 106
    • +
    • positioni < positioni+1
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1777.leetcode1777 Product's Price for Each Store-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1777.leetcode1777 Product's Price for Each Store-zh.md" new file mode 100644 index 00000000..3917778d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1777.leetcode1777 Product's Price for Each Store-zh.md" @@ -0,0 +1,66 @@ +# [1777. 每家商店的产品价格](https://leetcode-cn.com/problems/products-price-for-each-store) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1777.Product%27s%20Price%20for%20Each%20Store/README_EN.md) + +## 题目描述 + + + +

    表:Products

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_id  | int     |
    +| store       | enum    |
    +| price       | int     |
    ++-------------+---------+
    +(product_id,store) 是这个表的主键。
    +store 字段是枚举类型,它的取值为以下三种 ('store1', 'store2', 'store3') 。
    +price 是该商品在这家商店中的价格。
    + +

     

    + +

    写出一个 SQL 查询语句,查找每种产品在各个商店中的价格。

    + +

    可以以 任何顺序 输出结果。

    + +

    查询结果格式如下例所示:

    + +
    +Products 表:
    ++-------------+--------+-------+
    +| product_id  | store  | price |
    ++-------------+--------+-------+
    +| 0           | store1 | 95    |
    +| 0           | store3 | 105   |
    +| 0           | store2 | 100   |
    +| 1           | store1 | 70    |
    +| 1           | store3 | 80    |
    ++-------------+--------+-------+
    +Result 表:
    ++-------------+--------+--------+--------+
    +| product_id  | store1 | store2 | store3 |
    ++-------------+--------+--------+--------+
    +| 0           | 95     | 100    | 105    |
    +| 1           | 70     | null   | 80     |
    ++-------------+--------+--------+--------+
    +产品 0 的价格在商店 1 为 95 ,商店 2 为 100 ,商店 3 为 105 。
    +产品 1 的价格在商店 1 为 70 ,商店 3 的产品 1 价格为 80 ,但在商店 2 中没有销售。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1778.leetcode1778 Shortest Path in a Hidden Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1778.leetcode1778 Shortest Path in a Hidden Grid-zh.md" new file mode 100644 index 00000000..6678f7a9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1778.leetcode1778 Shortest Path in a Hidden Grid-zh.md" @@ -0,0 +1,118 @@ +# [1778. Shortest Path in a Hidden Grid](https://leetcode-cn.com/problems/shortest-path-in-a-hidden-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1778.Shortest%20Path%20in%20a%20Hidden%20Grid/README_EN.md) + +## 题目描述 + + + +

    This is an interactive problem.

    + +

    There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.

    + +

    You want to find the minimum distance to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.

    + +

    Thr GridMaster class has the following functions:

    + +
      +
    • boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
    • +
    • void move(char direction) Moves the robot in that direction. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, and the robot will remain in the same position.
    • +
    • boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.
    • +
    + +

    Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.

    + +

    Return the minimum distance between the robot's initial starting cell and the target cell. If there is no valid path between the cells, return -1.

    + +

    Custom testing:

    + +

    The test input is read as a 2D matrix grid of size m x n where:

    + +
      +
    • grid[i][j] == -1 indicates that the robot is in cell (i, j) (the starting cell).
    • +
    • grid[i][j] == 0 indicates that the cell (i, j) is blocked.
    • +
    • grid[i][j] == 1 indicates that the cell (i, j) is empty.
    • +
    • grid[i][j] == 2 indicates that the cell (i, j) is the target cell.
    • +
    + +

    There is exactly one -1 and 2 in grid. Remember that you will not have this information in your code.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,2],[-1,0]]
    +Output: 2
    +Explanation: One possible interaction is described below:
    +The robot is initially standing on cell (1, 0), denoted by the -1.
    +- master.canMove('U') returns true.
    +- master.canMove('D') returns false.
    +- master.canMove('L') returns false.
    +- master.canMove('R') returns false.
    +- master.move('U') moves the robot to the cell (0, 0).
    +- master.isTarget() returns false.
    +- master.canMove('U') returns false.
    +- master.canMove('D') returns true.
    +- master.canMove('L') returns false.
    +- master.canMove('R') returns true.
    +- master.move('R') moves the robot to the cell (0, 1).
    +- master.isTarget() returns true. 
    +We now know that the target is the cell (0, 1), and the shortest path to the target cell is 2.
    +
    + +

    Example 2:

    + +
    +Input: grid = [[0,0,-1],[1,1,1],[2,0,0]]
    +Output: 4
    +Explanation: The minimum distance between the robot and the target cell is 4.
    + +

    Example 3:

    + +
    +Input: grid = [[-1,0],[0,2]]
    +Output: -1
    +Explanation: There is no path from the robot to the target cell.
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n, m <= 500
    • +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • grid[i][j] is either -1, 0, 1, or 2.
    • +
    • There is exactly one -1 in grid.
    • +
    • There is exactly one 2 in grid.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1779.leetcode1779 Find Nearest Point That Has the Same X or Y Coordinate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1779.leetcode1779 Find Nearest Point That Has the Same X or Y Coordinate-zh.md" new file mode 100644 index 00000000..af47d2a5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1779.leetcode1779 Find Nearest Point That Has the Same X or Y Coordinate-zh.md" @@ -0,0 +1,74 @@ +# [1779. 找到最近的有相同 X 或 Y 坐标的点](https://leetcode-cn.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1779.Find%20Nearest%20Point%20That%20Has%20the%20Same%20X%20or%20Y%20Coordinate/README_EN.md) + +## 题目描述 + + + +

    给你两个整数 x 和 y ,表示你在一个笛卡尔坐标系下的 (x, y) 处。同时,在同一个坐标系下给你一个数组 points ,其中 points[i] = [ai, bi] 表示在 (ai, bi) 处有一个点。当一个点与你所在的位置有相同的 x 坐标或者相同的 y 坐标时,我们称这个点是 有效的 。

    + +

    请返回距离你当前位置 曼哈顿距离 最近的 有效 点的下标(下标从 0 开始)。如果有多个最近的有效点,请返回下标 最小 的一个。如果没有有效点,请返回 -1 。

    + +

    两个点 (x1, y1) 和 (x2, y2) 之间的 曼哈顿距离 为 abs(x1 - x2) + abs(y1 - y2) 。

    + +

     

    + +

    示例 1:

    + +
    输入:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
    +输出:2
    +解释:所有点中,[3,1],[2,4] 和 [4,4] 是有效点。有效点中,[2,4] 和 [4,4] 距离你当前位置的曼哈顿距离最小,都为 1 。[2,4] 的下标最小,所以返回 2 。
    + +

    示例 2:

    + +
    输入:x = 3, y = 4, points = [[3,4]]
    +输出:0
    +提示:答案可以与你当前所在位置坐标相同。
    + +

    示例 3:

    + +
    输入:x = 3, y = 4, points = [[2,3]]
    +输出:-1
    +解释:没有有效点。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= points.length <= 104
    • +
    • points[i].length == 2
    • +
    • 1 <= x, y, ai, bi <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1780.leetcode1780 Check if Number is a Sum of Powers of Three-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1780.leetcode1780 Check if Number is a Sum of Powers of Three-zh.md" new file mode 100644 index 00000000..fed5b675 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1780.leetcode1780 Check if Number is a Sum of Powers of Three-zh.md" @@ -0,0 +1,72 @@ +# [1780. 判断一个数字是否可以表示成三的幂的和](https://leetcode-cn.com/problems/check-if-number-is-a-sum-of-powers-of-three) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1780.Check%20if%20Number%20is%20a%20Sum%20of%20Powers%20of%20Three/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n ,如果你可以将 n 表示成若干个不同的三的幂之和,请你返回 true ,否则请返回 false 。

    + +

    对于一个整数 y ,如果存在整数 x 满足 y == 3x ,我们称这个整数 y 是三的幂。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 12
    +输出:true
    +解释:12 = 31 + 32
    +
    + +

    示例 2:

    + +
    输入:n = 91
    +输出:true
    +解释:91 = 30 + 32 + 34
    +
    + +

    示例 3:

    + +
    输入:n = 21
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 107
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1781.leetcode1781 Sum of Beauty of All Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1781.leetcode1781 Sum of Beauty of All Substrings-zh.md" new file mode 100644 index 00000000..adee2802 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1781.leetcode1781 Sum of Beauty of All Substrings-zh.md" @@ -0,0 +1,71 @@ +# [1781. 所有子字符串美丽值之和](https://leetcode-cn.com/problems/sum-of-beauty-of-all-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1781.Sum%20of%20Beauty%20of%20All%20Substrings/README_EN.md) + +## 题目描述 + + + +

    一个字符串的 美丽值 定义为:出现频率最高字符与出现频率最低字符的出现次数之差。

    + +
      +
    • 比方说,"abaacc" 的美丽值为 3 - 1 = 2 。
    • +
    + +

    给你一个字符串 s ,请你返回它所有子字符串的 美丽值 之和。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aabcb"
    +输出:5
    +解释:美丽值不为零的字符串包括 ["aab","aabc","aabcb","abcb","bcb"] ,每一个字符串的美丽值都为 1 。
    + +

    示例 2:

    + +
    +输入:s = "aabcbaa"
    +输出:17
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1782.leetcode1782 Count Pairs Of Nodes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1782.leetcode1782 Count Pairs Of Nodes-zh.md" new file mode 100644 index 00000000..1d5cdc92 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1782.leetcode1782 Count Pairs Of Nodes-zh.md" @@ -0,0 +1,81 @@ +# [1782. 统计点对的数目](https://leetcode-cn.com/problems/count-pairs-of-nodes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1782.Count%20Pairs%20Of%20Nodes/README_EN.md) + +## 题目描述 + + + +

    给你一个无向图,无向图由整数 n  ,表示图中节点的数目,和 edges 组成,其中 edges[i] = [ui, vi] 表示 ui 和 vi 之间有一条无向边。同时给你一个代表查询的整数数组 queries 。

    + +

    j 个查询的答案是满足如下条件的点对 (a, b) 的数目:

    + +
      +
    • a < b
    • +
    • cnt 是与 a 或者 b 相连的边的数目,且 cnt 严格大于 queries[j] 。
    • +
    + +

    请你返回一个数组 answers ,其中 answers.length == queries.length 且 answers[j] 是第 j 个查询的答案。

    + +

    请注意,图中可能会有 重复边 。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]
    +输出:[6,5]
    +解释:每个点对中,与至少一个点相连的边的数目如上图所示。
    +
    + +

    示例 2:

    + +
    +输入:n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]
    +输出:[10,10,9,8,6]
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 2 * 104
    • +
    • 1 <= edges.length <= 105
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 1 <= queries.length <= 20
    • +
    • 0 <= queries[j] < edges.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1783.leetcode1783 Grand Slam Titles-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1783.leetcode1783 Grand Slam Titles-zh.md" new file mode 100644 index 00000000..39a2d87a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1783.leetcode1783 Grand Slam Titles-zh.md" @@ -0,0 +1,93 @@ +# [1783. 大满贯数量](https://leetcode-cn.com/problems/grand-slam-titles) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1783.Grand%20Slam%20Titles/README_EN.md) + +## 题目描述 + + + +

    表:Players

    + +
    ++----------------+---------+
    +| Column Name    | Type    |
    ++----------------+---------+
    +| player_id      | int     |
    +| player_name    | varchar |
    ++----------------+---------+
    +player_id 是这个表的主键
    +这个表的每一行给出一个网球运动员的 ID 和 姓名
    +
    + +

    表:Championships

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| year          | int     |
    +| Wimbledon     | int     |
    +| Fr_open       | int     |
    +| US_open       | int     |
    +| Au_open       | int     |
    ++---------------+---------+
    +year 是这个表的主键
    +该表的每一行都包含在每场大满贯网球比赛中赢得比赛的球员的 ID
    +
    + +

     

    + +

    请写出查询语句,查询出每一个球员赢得大满贯比赛的次数。结果不包含没有赢得比赛的球员的ID 。

    + +

    结果集无顺序要求。

    + +

    查询结果的格式,如下所示:

    + +

     

    + +
    +Players 表:
    ++-----------+-------------+
    +| player_id | player_name |
    ++-----------+-------------+
    +| 1         | Nadal       |
    +| 2         | Federer     |
    +| 3         | Novak       |
    ++-----------+-------------+
    +
    +Championships 表:
    ++------+-----------+---------+---------+---------+
    +| year | Wimbledon | Fr_open | US_open | Au_open |
    ++------+-----------+---------+---------+---------+
    +| 2018 | 1         | 1       | 1       | 1       |
    +| 2019 | 1         | 1       | 2       | 2       |
    +| 2020 | 2         | 1       | 2       | 2       |
    ++------+-----------+---------+---------+---------+
    +
    +Result 表:
    ++-----------+-------------+-------------------+
    +| player_id | player_name | grand_slams_count |
    ++-----------+-------------+-------------------+
    +| 2         | Federer     | 5                 |
    +| 1         | Nadal       | 7                 |
    ++-----------+-------------+-------------------+
    +
    +Player 1 (Nadal) 获得了 7 次大满贯:其中温网 2 次(2018, 2019), 法国公开赛 3 次 (2018, 2019, 2020), 美国公开赛 1 次 (2018)以及澳网公开赛 1 次 (2018) 。
    +Player 2 (Federer) 获得了 5 次大满贯:其中温网 1 次 (2020), 美国公开赛 2 次 (2019, 2020) 以及澳网公开赛 2 次 (2019, 2020) 。
    +Player 3 (Novak)  没有赢得,因此不包含在结果集中。
    +
    + + +## 解法 + + + + + +### **SQL** + +```sql + +``` + + \ No newline at end of file diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1784.leetcode1784 Check if Binary String Has at Most One Segment of Ones-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1784.leetcode1784 Check if Binary String Has at Most One Segment of Ones-zh.md" new file mode 100644 index 00000000..5f573097 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1784.leetcode1784 Check if Binary String Has at Most One Segment of Ones-zh.md" @@ -0,0 +1,68 @@ +# [1784. 检查二进制字符串字段](https://leetcode-cn.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1784.Check%20if%20Binary%20String%20Has%20at%20Most%20One%20Segment%20of%20Ones/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 s ,该字符串 不含前导零

    + +

    如果 s 最多包含 一个由连续的 '1' 组成的字段 ,返回 true​​​ 。否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "1001"
    +输出:false
    +解释:字符串中的 1 没有形成一个连续字段。
    +
    + +

    示例 2:

    + +
    +输入:s = "110"
    +输出:true
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s[i]​​​​ 为 '0''1'
    • +
    • s[0]'1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1785.leetcode1785 Minimum Elements to Add to Form a Given Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1785.leetcode1785 Minimum Elements to Add to Form a Given Sum-zh.md" new file mode 100644 index 00000000..db702ffe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1785.leetcode1785 Minimum Elements to Add to Form a Given Sum-zh.md" @@ -0,0 +1,72 @@ +# [1785. 构成特定和需要添加的最少元素](https://leetcode-cn.com/problems/minimum-elements-to-add-to-form-a-given-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1785.Minimum%20Elements%20to%20Add%20to%20Form%20a%20Given%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,和两个整数 limitgoal 。数组 nums 有一条重要属性:abs(nums[i]) <= limit

    + +

    返回使数组元素总和等于 goal 所需要向数组中添加的 最少元素数量 ,添加元素 不应改变 数组中 abs(nums[i]) <= limit 这一属性。

    + +

    注意,如果 x >= 0 ,那么 abs(x) 等于 x ;否则,等于 -x

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,-1,1], limit = 3, goal = -4
    +输出:2
    +解释:可以将 -2 和 -3 添加到数组中,数组的元素总和变为 1 - 1 + 1 - 2 - 3 = -4 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,-10,9,1], limit = 100, goal = 0
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= limit <= 106
    • +
    • -limit <= nums[i] <= limit
    • +
    • -109 <= goal <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1786.leetcode1786 Number of Restricted Paths From First to Last Node-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1786.leetcode1786 Number of Restricted Paths From First to Last Node-zh.md" new file mode 100644 index 00000000..10f927e3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1786.leetcode1786 Number of Restricted Paths From First to Last Node-zh.md" @@ -0,0 +1,81 @@ +# [1786. 从第一个节点出发到最后一个节点的受限路径数](https://leetcode-cn.com/problems/number-of-restricted-paths-from-first-to-last-node) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1786.Number%20of%20Restricted%20Paths%20From%20First%20to%20Last%20Node/README_EN.md) + +## 题目描述 + + + +

    现有一个加权无向连通图。给你一个正整数 n ,表示图中有 n 个节点,并按从 1n 给节点编号;另给你一个数组 edges ,其中每个 edges[i] = [ui, vi, weighti] 表示存在一条位于节点 uivi 之间的边,这条边的权重为 weighti

    + +

    从节点 start 出发到节点 end 的路径是一个形如 [z0, z1, z2, ..., zk] 的节点序列,满足 z0 = startzk = end 且在所有符合 0 <= i <= k-1 的节点 zizi+1 之间存在一条边。

    + +

    路径的距离定义为这条路径上所有边的权重总和。用 distanceToLastNode(x) 表示节点 nx 之间路径的最短距离。受限路径 为满足 distanceToLastNode(zi) > distanceToLastNode(zi+1) 的一条路径,其中 0 <= i <= k-1

    + +

    返回从节点 1 出发到节点 n受限路径数 。由于数字可能很大,请返回对 109 + 7 取余 的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
    +输出:3
    +解释:每个圆包含黑色的节点编号和蓝色的 distanceToLastNode 值。三条受限路径分别是:
    +1) 1 --> 2 --> 5
    +2) 1 --> 2 --> 3 --> 5
    +3) 1 --> 3 --> 5
    +
    + +

    示例 2:

    + +
    +输入:n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
    +输出:1
    +解释:每个圆包含黑色的节点编号和蓝色的 distanceToLastNode 值。唯一一条受限路径是:1 --> 3 --> 7 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 2 * 104
    • +
    • n - 1 <= edges.length <= 4 * 104
    • +
    • edges[i].length == 3
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 1 <= weighti <= 105
    • +
    • 任意两个节点之间至多存在一条边
    • +
    • 任意两个节点之间至少存在一条路径
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1787.leetcode1787 Make the XOR of All Segments Equal to Zero-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1787.leetcode1787 Make the XOR of All Segments Equal to Zero-zh.md" new file mode 100644 index 00000000..8d913267 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1787.leetcode1787 Make the XOR of All Segments Equal to Zero-zh.md" @@ -0,0 +1,76 @@ +# [1787. 使所有区间的异或结果为零](https://leetcode-cn.com/problems/make-the-xor-of-all-segments-equal-to-zero) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1787.Make%20the%20XOR%20of%20All%20Segments%20Equal%20to%20Zero/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums​​​ 和一个整数 k​​​​​ 。区间 [left, right]left <= right)的 异或结果 是对下标位于 leftright(包括 leftright )之间所有元素进行 XOR 运算的结果:nums[left] XOR nums[left+1] XOR ... XOR nums[right]

    + +

    返回数组中 要更改的最小元素数 ,以使所有长度为 k 的区间异或结果等于零。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,0,3,0], k = 1
    +输出:3
    +解释:将数组 [1,2,0,3,0] 修改为 [0,0,0,0,0]
    +
    + +

    示例 2:

    + +
    +输入:nums = [3,4,5,2,1,7,3,4,7], k = 3
    +输出:3
    +解释:将数组 [3,4,5,2,1,7,3,4,7] 修改为 [3,4,7,3,4,7,3,4,7]
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,2,4,1,2,5,1,2,6], k = 3
    +输出:3
    +解释:将数组[1,2,4,1,2,5,1,2,6] 修改为 [1,2,3,1,2,3,1,2,3]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= nums.length <= 2000
    • +
    • ​​​​​​0 <= nums[i] < 210
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1788.leetcode1788 Maximize the Beauty of the Garden-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1788.leetcode1788 Maximize the Beauty of the Garden-zh.md" new file mode 100644 index 00000000..097c8c5e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1788.leetcode1788 Maximize the Beauty of the Garden-zh.md" @@ -0,0 +1,83 @@ +# [1788. 最大化花园的美观度](https://leetcode-cn.com/problems/maximize-the-beauty-of-the-garden) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1788.Maximize%20the%20Beauty%20of%20the%20Garden/README_EN.md) + +## 题目描述 + + + +

    有一个花园,有 n 朵花,这些花都有一个用整数表示的美观度。这些花被种在一条线上。给定一个长度为 n 的整数类型数组 flowers ,每一个 flowers[i] 表示第 i 朵花的美观度。

    + +

    一个花园满足下列条件时,该花园是有效的。

    + +
      +
    • 花园中至少包含两朵花。
    • +
    • 第一朵花和最后一朵花的美观度相同。
    • +
    + +

    作为一个被钦定的园丁,你可以从花园中去除任意朵花(也可以不去除任意一朵)。你想要通过一种方法移除某些花朵,使得剩下的花园变得有效。花园的美观度是其中所有剩余的花朵美观度之和。

    + +

    返回你去除了任意朵花(也可以不去除任意一朵)之后形成的有效花园中最大可能的美观度。

    + +

     

    + +

    示例 1:

    + +
    输入: flowers = [1,2,3,1,2]
    +输出: 8
    +解释: 你可以修整为有效花园 [2,3,1,2] 来达到总美观度 2 + 3 + 1 + 2 = 8。
    + +

    示例 2:

    + +
    输入: flowers = [100,1,1,-3,1]
    +输出: 3
    +解释: 你可以修整为有效花园 [1,1,1] 来达到总美观度 1 + 1 + 1 = 3。
    +
    + +

    示例 3:

    + +
    输入: flowers = [-1,-2,0,-1]
    +输出: -2
    +解释: 你可以修整为有效花园 [-1,-1] 来达到总美观度 -1 + -1 = -2。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= flowers.length <= 105
    • +
    • -104 <= flowers[i] <= 104
    • +
    • 去除一些花朵(可能没有)后,是有可能形成一个有效花园的。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1789.leetcode1789 Primary Department for Each Employee-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1789.leetcode1789 Primary Department for Each Employee-zh.md" new file mode 100644 index 00000000..c10c838d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1789.leetcode1789 Primary Department for Each Employee-zh.md" @@ -0,0 +1,84 @@ +# [1789. 员工的直属部门](https://leetcode-cn.com/problems/primary-department-for-each-employee) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1789.Primary%20Department%20for%20Each%20Employee/README_EN.md) + +## 题目描述 + + + +

    Table: Employee

    + +
    +---------------+---------+
    +| Column Name   |  Type   |
    ++---------------+---------+
    +| employee_id   | int     |
    +| department_id | int     |
    +| primary_flag  | varchar |
    ++---------------+---------+
    +这张表的主键为 employee_id, department_id
    +employee_id 是员工的ID
    +department_id 是部门的ID,表示员工与该部门有关系
    +primary_flag 是一个枚举类型,值分别为('Y', 'N'). 如果值为'Y',表示该部门是员工的直属部门。 如果值是'N',则否
    +
    + +

     

    + +

    一个员工可以属于多个部门。

    + +

    当一个员工加入超过一个部门的时候,他需要决定哪个部门是他的直属部门。

    + +

    请注意,当员工只加入一个部门的时候,那这个部门将默认为他的直属部门,虽然表记录的值为'N'.

    + +

    请编写一段SQL,查出员工所属的直属部门。

    + +

    返回结果没有顺序要求。

    + +

     

    + +

    示例:

    + +
    Employee table:
    ++-------------+---------------+--------------+
    +| employee_id | department_id | primary_flag |
    ++-------------+---------------+--------------+
    +| 1           | 1             | N            |
    +| 2           | 1             | Y            |
    +| 2           | 2             | N            |
    +| 3           | 3             | N            |
    +| 4           | 2             | N            |
    +| 4           | 3             | Y            |
    +| 4           | 4             | N            |
    ++-------------+---------------+--------------+
    +
    +Result table:
    ++-------------+---------------+
    +| employee_id | department_id |
    ++-------------+---------------+
    +| 1           | 1             |
    +| 2           | 1             |
    +| 3           | 3             |
    +| 4           | 3             |
    ++-------------+---------------+
    +- 员工1的直属部门是1
    +- 员工2的直属部门是1
    +- 员工3的直属部门是3
    +- 员工4的直属部门是3
    + +

     

    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1790.leetcode1790 Check if One String Swap Can Make Strings Equal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1790.leetcode1790 Check if One String Swap Can Make Strings Equal-zh.md" new file mode 100644 index 00000000..fc97dd6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1790.leetcode1790 Check if One String Swap Can Make Strings Equal-zh.md" @@ -0,0 +1,81 @@ +# [1790. 仅执行一次字符串交换能否使两个字符串相等](https://leetcode-cn.com/problems/check-if-one-string-swap-can-make-strings-equal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1790.Check%20if%20One%20String%20Swap%20Can%20Make%20Strings%20Equal/README_EN.md) + +## 题目描述 + + + +

    给你长度相等的两个字符串 s1s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。

    + +

    如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:s1 = "bank", s2 = "kanb"
    +输出:true
    +解释:例如,交换 s2 中的第一个和最后一个字符可以得到 "bank"
    +
    + +

    示例 2:

    + +
    输入:s1 = "attack", s2 = "defend"
    +输出:false
    +解释:一次字符串交换无法使两个字符串相等
    +
    + +

    示例 3:

    + +
    输入:s1 = "kelb", s2 = "kelb"
    +输出:true
    +解释:两个字符串已经相等,所以不需要进行字符串交换
    +
    + +

    示例 4:

    + +
    输入:s1 = "abcd", s2 = "dcba"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s1.length, s2.length <= 100
    • +
    • s1.length == s2.length
    • +
    • s1s2 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1791.leetcode1791 Find Center of Star Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1791.leetcode1791 Find Center of Star Graph-zh.md" new file mode 100644 index 00000000..598022ee --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1791.leetcode1791 Find Center of Star Graph-zh.md" @@ -0,0 +1,74 @@ +# [1791. 找出星型图的中心节点](https://leetcode-cn.com/problems/find-center-of-star-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1791.Find%20Center%20of%20Star%20Graph/README_EN.md) + +## 题目描述 + + + +

    有一个无向的 星型 图,由 n 个编号从 1n 的节点组成。星型图有一个 中心 节点,并且恰有 n - 1 条边将中心节点与其他每个节点连接起来。

    + +

    给你一个二维整数数组 edges ,其中 edges[i] = [ui, vi] 表示在节点 uivi 之间存在一条边。请你找出并返回 edges 所表示星型图的中心节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:edges = [[1,2],[2,3],[4,2]]
    +输出:2
    +解释:如上图所示,节点 2 与其他每个节点都相连,所以节点 2 是中心节点。
    +
    + +

    示例 2:

    + +
    +输入:edges = [[1,2],[5,1],[1,3],[1,4]]
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= n <= 105
    • +
    • edges.length == n - 1
    • +
    • edges[i].length == 2
    • +
    • 1 <= ui, vi <= n
    • +
    • ui != vi
    • +
    • 题目数据给出的 edges 表示一个有效的星型图
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def findCenter(self, edges: List[List[int]]) -> int: + return edges[0][0] if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1] else edges[0][1] +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1792.leetcode1792 Maximum Average Pass Ratio-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1792.leetcode1792 Maximum Average Pass Ratio-zh.md" new file mode 100644 index 00000000..5792537f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1792.leetcode1792 Maximum Average Pass Ratio-zh.md" @@ -0,0 +1,74 @@ +# [1792. 最大平均通过率](https://leetcode-cn.com/problems/maximum-average-pass-ratio) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1792.Maximum%20Average%20Pass%20Ratio/README_EN.md) + +## 题目描述 + + + +

    一所学校里有一些班级,每个班级里有一些学生,现在每个班都会进行一场期末考试。给你一个二维数组 classes ,其中 classes[i] = [passi, totali] ,表示你提前知道了第 i 个班级总共有 totali 个学生,其中只有 passi 个学生可以通过考试。

    + +

    给你一个整数 extraStudents ,表示额外有 extraStudents 个聪明的学生,他们 一定 能通过任何班级的期末考。你需要给这 extraStudents 个学生每人都安排一个班级,使得 所有 班级的 平均 通过率 最大 。

    + +

    一个班级的 通过率 等于这个班级通过考试的学生人数除以这个班级的总人数。平均通过率 是所有班级的通过率之和除以班级数目。

    + +

    请你返回在安排这 extraStudents 个学生去对应班级后的 最大 平均通过率。与标准答案误差范围在 10-5 以内的结果都会视为正确结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:classes = [[1,2],[3,5],[2,2]], extraStudents = 2
    +输出:0.78333
    +解释:你可以将额外的两个学生都安排到第一个班级,平均通过率为 (3/4 + 3/5 + 2/2) / 3 = 0.78333 。
    +
    + +

    示例 2:

    + +
    +输入:classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
    +输出:0.53485
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= classes.length <= 105
    • +
    • classes[i].length == 2
    • +
    • 1 <= passi <= totali <= 105
    • +
    • 1 <= extraStudents <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1793.leetcode1793 Maximum Score of a Good Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1793.leetcode1793 Maximum Score of a Good Subarray-zh.md" new file mode 100644 index 00000000..3bbe1380 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1793.leetcode1793 Maximum Score of a Good Subarray-zh.md" @@ -0,0 +1,70 @@ +# [1793. 好子数组的最大分数](https://leetcode-cn.com/problems/maximum-score-of-a-good-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1793.Maximum%20Score%20of%20a%20Good%20Subarray/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums (下标从 0 开始)和一个整数 k 。

    + +

    一个子数组 (i, j) 的 分数 定义为 min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1) 。一个  子数组的两个端点下标需要满足 i <= k <= j 。

    + +

    请你返回  子数组的最大可能 分数 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,4,3,7,4,5], k = 3
    +输出:15
    +解释:最优子数组的左右端点下标是 (1, 5) ,分数为 min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15 。
    +
    + +

    示例 2:

    + +
    输入:nums = [5,5,4,5,4,1,1,1], k = 0
    +输出:20
    +解释:最优子数组的左右端点下标是 (0, 4) ,分数为 min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 2 * 104
    • +
    • 0 <= k < nums.length
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1794.leetcode1794 Count Pairs of Equal Substrings With Minimum Difference-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1794.leetcode1794 Count Pairs of Equal Substrings With Minimum Difference-zh.md" new file mode 100644 index 00000000..198547a2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1794.leetcode1794 Count Pairs of Equal Substrings With Minimum Difference-zh.md" @@ -0,0 +1,76 @@ +# [1794. 统计距离最小的子串对个数](https://leetcode-cn.com/problems/count-pairs-of-equal-substrings-with-minimum-difference) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1794.Count%20Pairs%20of%20Equal%20Substrings%20With%20Minimum%20Difference/README_EN.md) + +## 题目描述 + + + +

    输入数据为两个字符串firstStringsecondString,两个字符串下标均从0开始,且均只包含小写的英文字符,请计算满足下列要求的下标四元组(i,j,a,b)的个数:

    + +
      +
    • 0 <= i <= j < firstString.length
    • +
    • 0 <= a <= b < secondString.length
    • +
    • firstString字符串中从i位置到j位置的子串(包括j位置的字符)和secondString字符串从a位置到b位置的子串(包括b位置字符)相等
    • +
    • j-a的数值是所有符合前面三个条件的四元组中可能的最小值
    • +
    + +

    返回符合上述 4 个条件的四元组的 个数

    + +

     

    + +

    示例1:

    + +
    +输入:firstString = "abcd", secondString = "bccda"
    +输出:1
    +解释:(0,0,4,4)是唯一符合条件的四元组且其j-a的数值是最小的.
    +
    + +

    示例 2:

    + +
    +输入:firstString = "ab", secondString = "cd"
    +输出:0
    +解释:没有任何一个四元组能满足上述4个要求.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= firstString.length, secondString.length <= 2 * 105
    • +
    • 两个输入字符串均只包含小写英文字符.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1795.leetcode1795 Rearrange Products Table-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1795.leetcode1795 Rearrange Products Table-zh.md" new file mode 100644 index 00000000..50201ff7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1795.leetcode1795 Rearrange Products Table-zh.md" @@ -0,0 +1,74 @@ +# [1795. 每个产品在不同商店的价格](https://leetcode-cn.com/problems/rearrange-products-table) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1795.Rearrange%20Products%20Table/README_EN.md) + +## 题目描述 + + + +

    表:Products

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| product_id  | int     |
    +| store1      | int     |
    +| store2      | int     |
    +| store3      | int     |
    ++-------------+---------+
    +这张表的主键是product_id(产品Id)。
    +每行存储了这一产品在不同商店store1, store2, store3的价格。
    +如果这一产品在商店里没有出售,则值将为null。
    +
    + +

     

    + +

    请你重构 Products 表,查询每个产品在不同商店的价格,使得输出的格式变为(product_id, store, price) 。如果这一产品在商店里没有出售,则不输出这一行。

    + +

    输出结果表中的顺序不作要求。

    + +

    查询输出格式请参考下面示例。

    + +

     

    + +
    +Products table:
    ++------------+--------+--------+--------+
    +| product_id | store1 | store2 | store3 |
    ++------------+--------+--------+--------+
    +| 0          | 95     | 100    | 105    |
    +| 1          | 70     | null   | 80     |
    ++------------+--------+--------+--------+
    +
    +Result table:
    ++------------+--------+-------+
    +| product_id | store  | price |
    ++------------+--------+-------+
    +| 0          | store1 | 95    |
    +| 0          | store2 | 100   |
    +| 0          | store3 | 105   |
    +| 1          | store1 | 70    |
    +| 1          | store3 | 80    |
    ++------------+--------+-------+
    +
    +产品0在store1,store2,store3的价格分别为95,100,105。
    +产品1在store1,store3的价格分别为70,80。在store2无法买到。
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1796.leetcode1796 Second Largest Digit in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1796.leetcode1796 Second Largest Digit in a String-zh.md" new file mode 100644 index 00000000..580fed84 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1796.leetcode1796 Second Largest Digit in a String-zh.md" @@ -0,0 +1,105 @@ +# [1796. 字符串中第二大的数字](https://leetcode-cn.com/problems/second-largest-digit-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1796.Second%20Largest%20Digit%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。

    + +

    混合字符串 由小写英文字母和数字组成。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "dfa12321afd"
    +输出:2
    +解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
    +
    + +

    示例 2:

    + +
    +输入:s = "abc1111"
    +输出:-1
    +解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • s 只包含小写英文字母和(或)数字。
    • +
    + +## 解法 + + + +假设字符串最大的数为 `largestDigit`,第二大的数为 `secondLargestDigit`,初始化均为 -1。 + +遍历字符串,判断当前字符是否为数字型字符。若是,先转为数字 `num`。然后判断数字与 `largestDigit`、`secondLargestDigit` 的大小关系: + +- 若 `num > largestDigit`,将 `secondLargestDigit` 更新为 `largestDigit`,而 `largestDigit` 更新为 num; +- 若 `num > secondLargestDigit`,并且 `num < largestDigit`,将 `secondLargestDigit` 更新为 num; +- 其他情况不做处理。 + +最后返回 `secondLargestDigit` 即可。 + + + +### **Python3** + + + +```python +class Solution: + def secondHighest(self, s: str) -> int: + largest_digit = second_largest_digit = -1 + for c in s: + if c.isdigit(): + num = int(c) + if num > largest_digit: + second_largest_digit, largest_digit = largest_digit, num + elif num > second_largest_digit and num < largest_digit: + second_largest_digit = num + return second_largest_digit +``` + +### **Java** + + + +```java +class Solution { + public int secondHighest(String s) { + int largestDigit = -1, secondLargestDigit = -1; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c >= '0' && c <= '9') { + int num = c - '0'; + if (num > largestDigit) { + secondLargestDigit = largestDigit; + largestDigit = num; + } else if (num > secondLargestDigit && num < largestDigit) { + secondLargestDigit = num; + } + } + } + return secondLargestDigit; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1797.leetcode1797 Design Authentication Manager-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1797.leetcode1797 Design Authentication Manager-zh.md" new file mode 100644 index 00000000..42309564 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1797.leetcode1797 Design Authentication Manager-zh.md" @@ -0,0 +1,154 @@ +# [1797. 设计一个验证系统](https://leetcode-cn.com/problems/design-authentication-manager) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1797.Design%20Authentication%20Manager/README_EN.md) + +## 题目描述 + + + +

    你需要设计一个包含验证码的验证系统。每一次验证中,用户会收到一个新的验证码,这个验证码在 currentTime 时刻之后 timeToLive 秒过期。如果验证码被更新了,那么它会在 currentTime (可能与之前的 currentTime 不同)时刻延长 timeToLive 秒。

    + +

    请你实现 AuthenticationManager 类:

    + +
      +
    • AuthenticationManager(int timeToLive) 构造 AuthenticationManager 并设置 timeToLive 参数。
    • +
    • generate(string tokenId, int currentTime) 给定 tokenId ,在当前时间 currentTime 生成一个新的验证码。
    • +
    • renew(string tokenId, int currentTime) 将给定 tokenId 且 未过期 的验证码在 currentTime 时刻更新。如果给定 tokenId 对应的验证码不存在或已过期,请你忽略该操作,不会有任何更新操作发生。
    • +
    • countUnexpiredTokens(int currentTime) 请返回在给定 currentTime 时刻,未过期 的验证码数目。
    • +
    + +

    如果一个验证码在时刻 t 过期,且另一个操作恰好在时刻 t 发生(renew 或者 countUnexpiredTokens 操作),过期事件 优先于 其他操作。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["AuthenticationManager", "renew", "generate", "countUnexpiredTokens", "generate", "renew", "renew", "countUnexpiredTokens"]
    +[[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]]
    +输出:
    +[null, null, null, 1, null, null, null, 0]
    +
    +解释:
    +AuthenticationManager authenticationManager = new AuthenticationManager(5); // 构造 AuthenticationManager ,设置 timeToLive = 5 秒。
    +authenticationManager.renew("aaa", 1); // 时刻 1 时,没有验证码的 tokenId 为 "aaa" ,没有验证码被更新。
    +authenticationManager.generate("aaa", 2); // 时刻 2 时,生成一个 tokenId 为 "aaa" 的新验证码。
    +authenticationManager.countUnexpiredTokens(6); // 时刻 6 时,只有 tokenId 为 "aaa" 的验证码未过期,所以返回 1 。
    +authenticationManager.generate("bbb", 7); // 时刻 7 时,生成一个 tokenId 为 "bbb" 的新验证码。
    +authenticationManager.renew("aaa", 8); // tokenId 为 "aaa" 的验证码在时刻 7 过期,且 8 >= 7 ,所以时刻 8 的 renew 操作被忽略,没有验证码被更新。
    +authenticationManager.renew("bbb", 10); // tokenId 为 "bbb" 的验证码在时刻 10 没有过期,所以 renew 操作会执行,该 token 将在时刻 15 过期。
    +authenticationManager.countUnexpiredTokens(15); // tokenId 为 "bbb" 的验证码在时刻 15 过期,tokenId 为 "aaa" 的验证码在时刻 7 过期,所有验证码均已过期,所以返回 0 。
    +
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= timeToLive <= 108
    • +
    • 1 <= currentTime <= 108
    • +
    • 1 <= tokenId.length <= 5
    • +
    • tokenId 只包含小写英文字母。
    • +
    • 所有 generate 函数的调用都会包含独一无二的 tokenId 值。
    • +
    • 所有函数调用中,currentTime 的值 严格递增 。
    • +
    • 所有函数的调用次数总共不超过 2000 次。
    • +
    + +## 解法 + + + +用哈希表存放 token 与对应的过期时间。 + + + +### **Python3** + + + +```python +class AuthenticationManager: + + def __init__(self, timeToLive: int): + self.timeToLive = timeToLive + self.tokens = {} + + def generate(self, tokenId: str, currentTime: int) -> None: + self.tokens[tokenId] = currentTime + self.timeToLive + + def renew(self, tokenId: str, currentTime: int) -> None: + expire_time = self.tokens.get(tokenId) + if expire_time is None or expire_time <= currentTime: + return + self.tokens[tokenId] = currentTime + self.timeToLive + + def countUnexpiredTokens(self, currentTime: int) -> int: + unexpiredCount = 0 + for val in self.tokens.values(): + if val > currentTime: + unexpiredCount += 1 + return unexpiredCount + + +# Your AuthenticationManager object will be instantiated and called as such: +# obj = AuthenticationManager(timeToLive) +# obj.generate(tokenId,currentTime) +# obj.renew(tokenId,currentTime) +# param_3 = obj.countUnexpiredTokens(currentTime) +``` + +### **Java** + + + +```java +class AuthenticationManager { + private int timeToLive; + private Map tokens; + + public AuthenticationManager(int timeToLive) { + this.timeToLive = timeToLive; + tokens = new HashMap<>(); + } + + public void generate(String tokenId, int currentTime) { + tokens.put(tokenId, currentTime + timeToLive); + } + + public void renew(String tokenId, int currentTime) { + Integer expireTime = tokens.get(tokenId); + if (expireTime == null || expireTime <= currentTime) { + return; + } + tokens.put(tokenId, currentTime + timeToLive); + } + + public int countUnexpiredTokens(int currentTime) { + int unexpiredCount = 0; + for (Integer val : tokens.values()) { + if (val > currentTime) { + ++unexpiredCount; + } + } + return unexpiredCount; + } +} + +/** + * Your AuthenticationManager object will be instantiated and called as such: + * AuthenticationManager obj = new AuthenticationManager(timeToLive); + * obj.generate(tokenId,currentTime); + * obj.renew(tokenId,currentTime); + * int param_3 = obj.countUnexpiredTokens(currentTime); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1798.leetcode1798 Maximum Number of Consecutive Values You Can Make-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1798.leetcode1798 Maximum Number of Consecutive Values You Can Make-zh.md" new file mode 100644 index 00000000..5a6a885f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1798.leetcode1798 Maximum Number of Consecutive Values You Can Make-zh.md" @@ -0,0 +1,118 @@ +# [1798. 你能构造出连续值的最大数目](https://leetcode-cn.com/problems/maximum-number-of-consecutive-values-you-can-make) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1798.Maximum%20Number%20of%20Consecutive%20Values%20You%20Can%20Make/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的整数数组 coins ,它代表你拥有的 n 个硬币。第 i 个硬币的值为 coins[i] 。如果你从这些硬币中选出一部分硬币,它们的和为 x ,那么称,你可以 构造 出 x 。

    + +

    请返回从 0 开始(包括 0 ),你最多能 构造 出多少个连续整数。

    + +

    你可能有多个相同值的硬币。

    + +

     

    + +

    示例 1:

    + +
    +输入:coins = [1,3]
    +输出:2
    +解释:你可以得到以下这些值:
    +- 0:什么都不取 []
    +- 1:取 [1]
    +从 0 开始,你可以构造出 2 个连续整数。
    + +

    示例 2:

    + +
    +输入:coins = [1,1,1,4]
    +输出:8
    +解释:你可以得到以下这些值:
    +- 0:什么都不取 []
    +- 1:取 [1]
    +- 2:取 [1,1]
    +- 3:取 [1,1,1]
    +- 4:取 [4]
    +- 5:取 [4,1]
    +- 6:取 [4,1,1]
    +- 7:取 [4,1,1,1]
    +从 0 开始,你可以构造出 8 个连续整数。
    + +

    示例 3:

    + +
    +输入:nums = [1,4,10,3,1]
    +输出:20
    + +

     

    + +

    提示:

    + +
      +
    • coins.length == n
    • +
    • 1 <= n <= 4 * 104
    • +
    • 1 <= coins[i] <= 4 * 104
    • +
    + +## 解法 + + + +先对 `coins` 数组进行排序。 + +假设前 i 个数所有构造的的连续整数的个数为 res,初始化为 1。 + +遍历排序后的 `coins` 数组: + +- 若 `coins[i] > res`,说明接下来无法组成 `res + 1` 个连续整数,跳出循环。 + + > 对于 `1, 3`,若遍历到 3,此时前面的连续整数个数为 2,即连续整数为:`0, 1`。此时 3 大于 2,无法构成连续整数 `0, 1, 2`,所以最大连续整数个数为 2。 + +- 若 `coins[i] <= res`,说明有 `coins[i]` 个数也能构成连续整数。 + + + +### **Python3** + + + +```python +class Solution: + def getMaximumConsecutive(self, coins: List[int]) -> int: + res = 1 + for coin in sorted(coins): + if coin > res: + break + res += coin + return res +``` + +### **Java** + + + +```java +class Solution { + public int getMaximumConsecutive(int[] coins) { + int res = 1; + Arrays.sort(coins); + for (int coin : coins) { + if (coin > res) { + break; + } + res += coin; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1799.leetcode1799 Maximize Score After N Operations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1799.leetcode1799 Maximize Score After N Operations-zh.md" new file mode 100644 index 00000000..967e4701 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1799.leetcode1799 Maximize Score After N Operations-zh.md" @@ -0,0 +1,88 @@ +# [1799. N 次操作后的最大分数和](https://leetcode-cn.com/problems/maximize-score-after-n-operations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1700-1799/1799.Maximize%20Score%20After%20N%20Operations/README_EN.md) + +## 题目描述 + + + +

    给你 nums ,它是一个大小为 2 * n 的正整数数组。你必须对这个数组执行 n 次操作。

    + +

    在第 i 次操作时(操作编号从 1 开始),你需要:

    + +
      +
    • 选择两个元素 x 和 y 。
    • +
    • 获得分数 i * gcd(x, y) 。
    • +
    • 将 x 和 y 从 nums 中删除。
    • +
    + +

    请你返回 n 次操作后你能获得的分数和最大为多少。

    + +

    函数 gcd(x, y) 是 x 和 y 的最大公约数。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2]
    +输出:1
    +解释:最优操作是:
    +(1 * gcd(1, 2)) = 1
    +
    + +

    示例 2:

    + +
    输入:nums = [3,4,6,8]
    +输出:11
    +解释:最优操作是:
    +(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
    +
    + +

    示例 3:

    + +
    输入:nums = [1,2,3,4,5,6]
    +输出:14
    +解释:最优操作是:
    +(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 7
    • +
    • nums.length == 2 * n
    • +
    • 1 <= nums[i] <= 106
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1800.leetcode1800 Maximum Ascending Subarray Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1800.leetcode1800 Maximum Ascending Subarray Sum-zh.md" new file mode 100644 index 00000000..40bef581 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1800.leetcode1800 Maximum Ascending Subarray Sum-zh.md" @@ -0,0 +1,171 @@ +# [1800. 最大升序子数组和](https://leetcode-cn.com/problems/maximum-ascending-subarray-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1800.Maximum%20Ascending%20Subarray%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数组成的数组 nums ,返回 nums 中一个 升序 子数组的最大可能元素和。

    + +

    子数组是数组中的一个连续数字序列。

    + +

    已知子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,若对所有 il <= i < r),numsi < numsi+1 都成立,则称这一子数组为 升序 子数组。注意,大小为 1 的子数组也视作 升序 子数组。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [10,20,30,5,10,50]
    +输出:65
    +解释:[5,10,50] 是元素和最大的升序子数组,最大元素和为 65 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [10,20,30,40,50]
    +输出:150
    +解释:[10,20,30,40,50] 是元素和最大的升序子数组,最大元素和为 150 。 
    +
    + +

    示例 3:

    + +
    +输入:nums = [12,17,15,13,10,11,12]
    +输出:33
    +解释:[10,11,12] 是元素和最大的升序子数组,最大元素和为 33 。 
    +
    + +

    示例 4:

    + +
    +输入:nums = [100,10,1]
    +输出:100
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 100
    • +
    • 1 <= nums[i] <= 100
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maxAscendingSum(self, nums: List[int]) -> int: + res, cur = 0, nums[0] + for i in range(1, len(nums)): + if nums[i] > nums[i - 1]: + cur += nums[i] + else: + res = max(res, cur) + cur = nums[i] + res = max(res, cur) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxAscendingSum(int[] nums) { + int cur = nums[0]; + int res = 0; + for (int i = 1; i < nums.length; ++i) { + if (nums[i] > nums[i - 1]) { + cur += nums[i]; + } else { + res = Math.max(res, cur); + cur = nums[i]; + } + } + res = Math.max(res, cur); + return res; + } +} +``` + +### **TypeScript** + +```ts +function maxAscendingSum(nums: number[]): number { + let res = 0, sum = nums[0]; + for (let i = 1; i < nums.length; ++i) { + if (nums[i] > nums[i - 1]) { + sum += nums[i]; + } else { + res = Math.max(res, sum); + sum = nums[i]; + } + } + res = Math.max(res, sum); + return res; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int maxAscendingSum(vector& nums) { + int res = 0, cur = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > nums[i - 1]) { + cur += nums[i]; + } else { + res = max(res, cur); + cur = nums[i]; + } + } + res = max(res, cur); + return res; + } +}; +``` + +### **Go** + +```go +func maxAscendingSum(nums []int) int { + res, cur := 0, nums[0] + for i := 1; i < len(nums); i++ { + if nums[i] > nums[i-1] { + cur += nums[i] + } else { + if res < cur { + res = cur + } + cur = nums[i] + } + } + if res < cur { + res = cur + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1801.leetcode1801 Number of Orders in the Backlog-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1801.leetcode1801 Number of Orders in the Backlog-zh.md" new file mode 100644 index 00000000..72ec3aca --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1801.leetcode1801 Number of Orders in the Backlog-zh.md" @@ -0,0 +1,96 @@ +# [1801. 积压订单中的订单总数](https://leetcode-cn.com/problems/number-of-orders-in-the-backlog) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1801.Number%20of%20Orders%20in%20the%20Backlog/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 orders ,其中每个 orders[i] = [pricei, amounti, orderTypei] 表示有 amounti 笔类型为 orderTypei 、价格为 pricei 的订单。

    + +

    订单类型 orderTypei 可以分为两种:

    + +
      +
    • 0 表示这是一批采购订单 buy
    • +
    • 1 表示这是一批销售订单 sell
    • +
    + +

    注意,orders[i] 表示一批共计 amounti 笔的独立订单,这些订单的价格和类型相同。对于所有有效的 i ,由 orders[i] 表示的所有订单提交时间均早于 orders[i+1] 表示的所有订单。

    + +

    存在由未执行订单组成的 积压订单 。积压订单最初是空的。提交订单时,会发生以下情况:

    + +
      +
    • 如果该订单是一笔采购订单 buy ,则可以查看积压订单中价格 最低 的销售订单 sell 。如果该销售订单 sell 的价格 低于或等于 当前采购订单 buy 的价格,则匹配并执行这两笔订单,并将销售订单 sell 从积压订单中删除。否则,采购订单 buy 将会添加到积压订单中。
    • +
    • 反之亦然,如果该订单是一笔销售订单 sell ,则可以查看积压订单中价格 最高 的采购订单 buy 。如果该采购订单 buy 的价格 高于或等于 当前销售订单 sell 的价格,则匹配并执行这两笔订单,并将采购订单 buy 从积压订单中删除。否则,销售订单 sell 将会添加到积压订单中。
    • +
    + +

    输入所有订单后,返回积压订单中的 订单总数 。由于数字可能很大,所以需要返回对 109 + 7 取余的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]
    +输出:6
    +解释:输入订单后会发生下述情况:
    +- 提交 5 笔采购订单,价格为 10 。没有销售订单,所以这 5 笔订单添加到积压订单中。
    +- 提交 2 笔销售订单,价格为 15 。没有采购订单的价格大于或等于 15 ,所以这 2 笔订单添加到积压订单中。
    +- 提交 1 笔销售订单,价格为 25 。没有采购订单的价格大于或等于 25 ,所以这 1 笔订单添加到积压订单中。
    +- 提交 4 笔采购订单,价格为 30 。前 2 笔采购订单与价格最低(价格为 15)的 2 笔销售订单匹配,从积压订单中删除这 2 笔销售订单。第 3 笔采购订单与价格最低的 1 笔销售订单匹配,销售订单价格为 25 ,从积压订单中删除这 1 笔销售订单。积压订单中不存在更多销售订单,所以第 4 笔采购订单需要添加到积压订单中。
    +最终,积压订单中有 5 笔价格为 10 的采购订单,和 1 笔价格为 30 的采购订单。所以积压订单中的订单总数为 6 。
    +
    + +

    示例 2:

    + +
    +输入:orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]
    +输出:999999984
    +解释:输入订单后会发生下述情况:
    +- 提交 109 笔销售订单,价格为 7 。没有采购订单,所以这 109 笔订单添加到积压订单中。
    +- 提交 3 笔采购订单,价格为 15 。这些采购订单与价格最低(价格为 7 )的 3 笔销售订单匹配,从积压订单中删除这 3 笔销售订单。
    +- 提交 999999995 笔采购订单,价格为 5 。销售订单的最低价为 7 ,所以这 999999995 笔订单添加到积压订单中。
    +- 提交 1 笔销售订单,价格为 5 。这笔销售订单与价格最高(价格为 5 )的 1 笔采购订单匹配,从积压订单中删除这 1 笔采购订单。
    +最终,积压订单中有 (1000000000-3) 笔价格为 7 的销售订单,和 (999999995-1) 笔价格为 5 的采购订单。所以积压订单中的订单总数为 1999999991 ,等于 999999984 % (109 + 7) 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= orders.length <= 105
    • +
    • orders[i].length == 3
    • +
    • 1 <= pricei, amounti <= 109
    • +
    • orderTypei01
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1802.leetcode1802 Maximum Value at a Given Index in a Bounded Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1802.leetcode1802 Maximum Value at a Given Index in a Bounded Array-zh.md" new file mode 100644 index 00000000..509753e3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1802.leetcode1802 Maximum Value at a Given Index in a Bounded Array-zh.md" @@ -0,0 +1,76 @@ +# [1802. 有界数组中指定下标处的最大值](https://leetcode-cn.com/problems/maximum-value-at-a-given-index-in-a-bounded-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1802.Maximum%20Value%20at%20a%20Given%20Index%20in%20a%20Bounded%20Array/README_EN.md) + +## 题目描述 + + + +

    给你三个正整数 nindexmaxSum 。你需要构造一个同时满足下述所有条件的数组 nums(下标 从 0 开始 计数):

    + +
      +
    • nums.length == n
    • +
    • nums[i]正整数 ,其中 0 <= i < n
    • +
    • abs(nums[i] - nums[i+1]) <= 1 ,其中 0 <= i < n-1
    • +
    • nums 中所有元素之和不超过 maxSum
    • +
    • nums[index] 的值被 最大化
    • +
    + +

    返回你所构造的数组中的 nums[index]

    + +

    注意:abs(x) 等于 x 的前提是 x >= 0 ;否则,abs(x) 等于 -x

    + +

     

    + +

    示例 1:

    + +
    输入:n = 4, index = 2,  maxSum = 6
    +输出:2
    +解释:数组 [1,1,2,1] 和 [1,2,2,1] 满足所有条件。不存在其他在指定下标处具有更大值的有效数组。
    +
    + +

    示例 2:

    + +
    输入:n = 6, index = 1,  maxSum = 10
    +输出:3
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= maxSum <= 109
    • +
    • 0 <= index < n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1803.leetcode1803 Count Pairs With XOR in a Range-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1803.leetcode1803 Count Pairs With XOR in a Range-zh.md" new file mode 100644 index 00000000..d285d885 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1803.leetcode1803 Count Pairs With XOR in a Range-zh.md" @@ -0,0 +1,81 @@ +# [1803. 统计异或值在范围内的数对有多少](https://leetcode-cn.com/problems/count-pairs-with-xor-in-a-range) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1803.Count%20Pairs%20With%20XOR%20in%20a%20Range/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数:lowhigh ,请返回 漂亮数对 的数目。

    + +

    漂亮数对 是一个形如 (i, j) 的数对,其中 0 <= i < j < nums.lengthlow <= (nums[i] XOR nums[j]) <= high

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,4,2,7], low = 2, high = 6
    +输出:6
    +解释:所有漂亮数对 (i, j) 列出如下:
    +    - (0, 1): nums[0] XOR nums[1] = 5 
    +    - (0, 2): nums[0] XOR nums[2] = 3
    +    - (0, 3): nums[0] XOR nums[3] = 6
    +    - (1, 2): nums[1] XOR nums[2] = 6
    +    - (1, 3): nums[1] XOR nums[3] = 3
    +    - (2, 3): nums[2] XOR nums[3] = 5
    +
    + +

    示例 2:

    + +
    输入:nums = [9,8,4,2,1], low = 5, high = 14
    +输出:8
    +解释:所有漂亮数对 (i, j) 列出如下:
    +​​​​​    - (0, 2): nums[0] XOR nums[2] = 13
    +    - (0, 3): nums[0] XOR nums[3] = 11
    +    - (0, 4): nums[0] XOR nums[4] = 8
    +    - (1, 2): nums[1] XOR nums[2] = 12
    +    - (1, 3): nums[1] XOR nums[3] = 10
    +    - (1, 4): nums[1] XOR nums[4] = 9
    +    - (2, 3): nums[2] XOR nums[3] = 6
    +    - (2, 4): nums[2] XOR nums[4] = 5
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 2 * 104
    • +
    • 1 <= nums[i] <= 2 * 104
    • +
    • 1 <= low <= high <= 2 * 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1804.leetcode1804 Implement Trie II (Prefix Tree)-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1804.leetcode1804 Implement Trie II (Prefix Tree)-zh.md" new file mode 100644 index 00000000..49fc725e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1804.leetcode1804 Implement Trie II (Prefix Tree)-zh.md" @@ -0,0 +1,218 @@ +# [1804. 实现 Trie (前缀树) II](https://leetcode-cn.com/problems/implement-trie-ii-prefix-tree) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1804.Implement%20Trie%20II%20%28Prefix%20Tree%29/README_EN.md) + +## 题目描述 + + + +

    前缀树(trie ,发音为 "try")是一个树状的数据结构,用于高效地存储和检索一系列字符串的前缀。前缀树有许多应用,如自动补全和拼写检查。

    + +

    实现前缀树 Trie 类:

    + +
      +
    • Trie() 初始化前缀树对象。
    • +
    • void insert(String word) 将字符串 word 插入前缀树中。
    • +
    • int countWordsEqualTo(String word) 返回前缀树中字符串 word 的实例个数。
    • +
    • int countWordsStartingWith(String prefix) 返回前缀树中以 prefix 为前缀的字符串个数。
    • +
    • void erase(String word) 从前缀树中移除字符串 word
    • +
    + +

     

    + +

    示例 1:

    + +
    输入
    +["Trie", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsStartingWith"]
    +[[], ["apple"], ["apple"], ["apple"], ["app"], ["apple"], ["apple"], ["app"], ["apple"], ["app"]]
    +输出
    +[null, null, null, 2, 2, null, 1, 1, null, 0]
    +
    +解释
    +Trie trie = new Trie();
    +trie.insert("apple");               // 插入 "apple"。
    +trie.insert("apple");               // 插入另一个 "apple"。
    +trie.countWordsEqualTo("apple");    // 有两个 "apple" 实例,所以返回 2。
    +trie.countWordsStartingWith("app"); // "app" 是 "apple" 的前缀,所以返回 2。
    +trie.erase("apple");                // 移除一个 "apple"。
    +trie.countWordsEqualTo("apple");    // 现在只有一个 "apple" 实例,所以返回 1。
    +trie.countWordsStartingWith("app"); // 返回 1
    +trie.erase("apple");                // 移除 "apple"。现在前缀树是空的。
    +trie.countWordsStartingWith("app"); // 返回 0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word.length, prefix.length <= 2000
    • +
    • word 和 prefix 只包含小写英文字母。
    • +
    • insert、 countWordsEqualTo、 countWordsStartingWith 和 erase 总共调用最多 3 * 104 次。
    • +
    • 保证每次调用 erase 时,字符串 word 总是存在于前缀树中。
    • +
    + +## 解法 + + + +前缀树每个节点包括三部分: + +1. 指向子节点的指针数组 children,对于本题而言,数组长度为 26,即小写英文字母的数量。`children[0]` 对应小写字母 a,...,`children[25]` 对应小写字母 z。 +1. int 变量 `count`,表示以该节点结尾的字符串个数。 +1. int 变量 `preCount`,表示以该节点作为前缀节点的字符串个数。 + +### 1. 插入字符串 + +我们从字典树的根开始,插入字符串。对于当前字符对应的子节点,有两种情况: + +- 子节点存在。沿着指针移动到子节点,继续处理下一个字符。 +- 子节点不存在。创建一个新的子节点,记录在 `children` 数组的对应位置上,然后沿着指针移动到子节点,让子节点的 `preCount` 值加 1。继续搜索下一个字符。 + +重复以上步骤,直到处理字符串的最后一个字符,然后将当前节点的 `count` 值加 1。 + +### 2. 查找前缀 + +我们从字典树的根开始,查找前缀。对于当前字符对应的子节点,有两种情况: + +- 子节点存在。沿着指针移动到子节点,继续搜索下一个字符。 +- 子节点不存在。说明字典树中不包含该前缀,返回空指针。 + +重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。 + + + +### **Python3** + + + +```python +class Trie: + + def __init__(self): + self.children = [None] * 26 + self.count = 0 + self.pre_count = 0 + + def insert(self, word: str) -> None: + node = self + for c in word: + index = ord(c) - ord('a') + if node.children[index] is None: + node.children[index] = Trie() + node = node.children[index] + node.pre_count += 1 + node.count += 1 + + def countWordsEqualTo(self, word: str) -> int: + node = self._search_prefix(word) + return 0 if node is None else node.count + + def countWordsStartingWith(self, prefix: str) -> int: + node = self._search_prefix(prefix) + return 0 if node is None else node.pre_count + + def erase(self, word: str) -> None: + node = self + for c in word: + index = ord(c) - ord('a') + node = node.children[index] + node.pre_count -= 1 + node.count -= 1 + + def _search_prefix(self, prefix: str): + node = self + for c in prefix: + index = ord(c) - ord('a') + if node.children[index] is None: + return None + node = node.children[index] + return node + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.countWordsEqualTo(word) +# param_3 = obj.countWordsStartingWith(prefix) +# obj.erase(word) +``` + +### **Java** + + + +```java +class Trie { + private Trie[] children; + private int count; + private int preCount; + + public Trie() { + children = new Trie[26]; + count = 0; + preCount = 0; + } + + public void insert(String word) { + Trie node = this; + for (int i = 0; i < word.length(); ++i) { + int index = word.charAt(i) - 'a'; + if (node.children[index] == null) { + node.children[index] = new Trie(); + } + node = node.children[index]; + node.preCount += 1; + } + node.count += 1; + } + + public int countWordsEqualTo(String word) { + Trie node = searchPrefix(word); + return node == null ? 0 : node.count; + } + + public int countWordsStartingWith(String prefix) { + Trie node = searchPrefix(prefix); + return node == null ? 0 : node.preCount; + } + + public void erase(String word) { + Trie node = this; + for (int i = 0; i < word.length(); ++i) { + int index = word.charAt(i) - 'a'; + node = node.children[index]; + node.preCount -= 1; + } + node.count -= 1; + } + + private Trie searchPrefix(String prefix) { + Trie node = this; + for (int i = 0; i < prefix.length(); ++i) { + int index = prefix.charAt(i) - 'a'; + if (node.children[index] == null) { + return null; + } + node = node.children[index]; + } + return node; + } +} + +/** + * Your Trie object will be instantiated and called as such: + * Trie obj = new Trie(); + * obj.insert(word); + * int param_2 = obj.countWordsEqualTo(word); + * int param_3 = obj.countWordsStartingWith(prefix); + * obj.erase(word); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1805.leetcode1805 Number of Different Integers in a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1805.leetcode1805 Number of Different Integers in a String-zh.md" new file mode 100644 index 00000000..3787ece0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1805.leetcode1805 Number of Different Integers in a String-zh.md" @@ -0,0 +1,102 @@ +# [1805. 字符串中不同整数的数目](https://leetcode-cn.com/problems/number-of-different-integers-in-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1805.Number%20of%20Different%20Integers%20in%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 word ,该字符串由数字和小写英文字母组成。

    + +

    请你用空格替换每个不是数字的字符。例如,"a123bc34d8ef34" 将会变成 " 123  34 8  34" 。注意,剩下的这些整数为(相邻彼此至少有一个空格隔开):"123""34""8""34"

    + +

    返回对 word 完成替换后形成的 不同 整数的数目。

    + +

    只有当两个整数的 不含前导零 的十进制表示不同, 才认为这两个整数也不同。

    + +

     

    + +

    示例 1:

    + +
    +输入:word = "a123bc34d8ef34"
    +输出:3
    +解释:不同的整数有 "123"、"34" 和 "8" 。注意,"34" 只计数一次。
    +
    + +

    示例 2:

    + +
    +输入:word = "leet1234code234"
    +输出:2
    +
    + +

    示例 3:

    + +
    +输入:word = "a1b01c001"
    +输出:1
    +解释:"1"、"01" 和 "001" 视为同一个整数的十进制表示,因为在比较十进制值时会忽略前导零的存在。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word.length <= 1000
    • +
    • word 由数字和小写英文字母组成
    • +
    + +## 解法 + + + +将 `word` 按照字母切分,得到数字数组 `nums`,然后利用 set 去重,返回 set 的长度即可。 + + + +### **Python3** + + + +```python +import re + +class Solution: + def numDifferentIntegers(self, word: str) -> int: + nums = re.split(r'[a-z]+', word) + return len({int(num) for num in nums if num != ''}) +``` + +### **Java** + + + +```java +class Solution { + public int numDifferentIntegers(String word) { + String[] nums = word.split("[a-z]+"); + Set numSet = new HashSet<>(); + for (String num : nums) { + if ("".equals(num)) { + continue; + } + int j = 0; + while (j < num.length() - 1 && num.charAt(j) == '0') { + ++j; + } + numSet.add(num.substring(j)); + } + return numSet.size(); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1806.leetcode1806 Minimum Number of Operations to Reinitialize a Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1806.leetcode1806 Minimum Number of Operations to Reinitialize a Permutation-zh.md" new file mode 100644 index 00000000..841b0545 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1806.leetcode1806 Minimum Number of Operations to Reinitialize a Permutation-zh.md" @@ -0,0 +1,88 @@ +# [1806. 还原排列的最少操作步数](https://leetcode-cn.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1806.Minimum%20Number%20of%20Operations%20to%20Reinitialize%20a%20Permutation/README_EN.md) + +## 题目描述 + + + +

    给你一个偶数 n​​​​​​ ,已知存在一个长度为 n 的排列 perm ,其中 perm[i] == i​(下标 从 0 开始 计数)。

    + +

    一步操作中,你将创建一个新数组 arr ,对于每个 i

    + +
      +
    • 如果 i % 2 == 0 ,那么 arr[i] = perm[i / 2]
    • +
    • 如果 i % 2 == 1 ,那么 arr[i] = perm[n / 2 + (i - 1) / 2]
    • +
    + +

    然后将 arr​​ 赋值​​给 perm

    + +

    要想使 perm 回到排列初始值,至少需要执行多少步操作?返回最小的 非零 操作步数。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 2
    +输出:1
    +解释:最初,perm = [0,1]
    +第 1 步操作后,perm = [0,1]
    +所以,仅需执行 1 步操作
    + +

    示例 2:

    + +
    +输入:n = 4
    +输出:2
    +解释:最初,perm = [0,1,2,3]
    +第 1 步操作后,perm = [0,2,1,3]
    +第 2 步操作后,perm = [0,1,2,3]
    +所以,仅需执行 2 步操作
    + +

    示例 3:

    + +
    +输入:n = 6
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 1000
    • +
    • n​​​​​​ 是一个偶数
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1807.leetcode1807 Evaluate the Bracket Pairs of a String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1807.leetcode1807 Evaluate the Bracket Pairs of a String-zh.md" new file mode 100644 index 00000000..70ca8edf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1807.leetcode1807 Evaluate the Bracket Pairs of a String-zh.md" @@ -0,0 +1,160 @@ +# [1807. 替换字符串中的括号内容](https://leetcode-cn.com/problems/evaluate-the-bracket-pairs-of-a-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1807.Evaluate%20the%20Bracket%20Pairs%20of%20a%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,它包含一些括号对,每个括号中包含一个 非空 的键。

    + +
      +
    • 比方说,字符串 "(name)is(age)yearsold" 中,有 两个 括号对,分别包含键 "name" 和 "age" 。
    • +
    + +

    你知道许多键对应的值,这些关系由二维字符串数组 knowledge 表示,其中 knowledge[i] = [keyi, valuei] ,表示键 keyi 对应的值为 valuei 

    + +

    你需要替换 所有 的括号对。当你替换一个括号对,且它包含的键为 keyi 时,你需要:

    + +
      +
    • 将 keyi 和括号用对应的值 valuei 替换。
    • +
    • 如果从 knowledge 中无法得知某个键对应的值,你需要将 keyi 和括号用问号 "?" 替换(不需要引号)。
    • +
    + +

    knowledge 中每个键最多只会出现一次。s 中不会有嵌套的括号。

    + +

    请你返回替换 所有 括号对后的结果字符串。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]]
    +输出:"bobistwoyearsold"
    +解释:
    +键 "name" 对应的值为 "bob" ,所以将 "(name)" 替换为 "bob" 。
    +键 "age" 对应的值为 "two" ,所以将 "(age)" 替换为 "two" 。
    +
    + +

    示例 2:

    + +
    输入:s = "hi(name)", knowledge = [["a","b"]]
    +输出:"hi?"
    +解释:由于不知道键 "name" 对应的值,所以用 "?" 替换 "(name)" 。
    +
    + +

    示例 3:

    + +
    输入:s = "(a)(a)(a)aaa", knowledge = [["a","yes"]]
    +输出:"yesyesyesaaa"
    +解释:相同的键在 s 中可能会出现多次。
    +键 "a" 对应的值为 "yes" ,所以将所有的 "(a)" 替换为 "yes" 。
    +注意,不在括号里的 "a" 不需要被替换。
    +
    + +

    示例 4:

    + +
    输入:s = "(a)(b)", knowledge = [["a","b"],["b","a"]]
    +输出:"ba"
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • 0 <= knowledge.length <= 105
    • +
    • knowledge[i].length == 2
    • +
    • 1 <= keyi.length, valuei.length <= 10
    • +
    • s 只包含小写英文字母和圆括号 '(' 和 ')' 。
    • +
    • s 中每一个左圆括号 '(' 都有对应的右圆括号 ')' 。
    • +
    • s 中每对括号内的键都不会为空。
    • +
    • s 中不会有嵌套括号对。
    • +
    • keyi 和 valuei 只包含小写英文字母。
    • +
    • knowledge 中的 keyi 不会重复。
    • +
    + +## 解法 + + + +先将 `knowledge` 转为哈希字典。 + +然后遍历字符串每个字符 `s[i]`: + +- 若 `s[i] == '('`,说明遇到了左括号,因此要找到右括号 `)` 的位置,然后截取括号间的子串作为 `key`,在哈希字典中查找 `key` 对应的 `value`,有则追加 `value` 到结果中,没有则追加 `?`,然后指针跳到右括号位置的下一个位置; +- 若 `s[i]` 是其他字符,则正常追加即可。 + + + +### **Python3** + + + +```python +class Solution: + def evaluate(self, s: str, knowledge: List[List[str]]) -> str: + def find_right_bracket(s, start, end): + for i in range(start, end): + if s[i] == ')': + return i + knowledge_dict = {item[0]: item[1] for item in knowledge} + res, n = [], len(s) + i = 0 + while i < n: + if s[i] == '(': + right_bracket_pos = find_right_bracket(s, i + 1, n) + key = s[i + 1: right_bracket_pos] + res.append(knowledge_dict.get(key, '?')) + i = right_bracket_pos + 1 + else: + res.append(s[i]) + i += 1 + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String evaluate(String s, List> knowledge) { + Map knowledgeDict = new HashMap<>(); + for (List item : knowledge) { + knowledgeDict.put(item.get(0), item.get(1)); + } + StringBuilder res = new StringBuilder(); + int i = 0, n = s.length(); + while (i < n) { + if (s.charAt(i) == '(') { + int rightBracketPos = findRightBracket(s, i + 1, n); + String key = s.substring(i + 1, rightBracketPos); + res.append(knowledgeDict.getOrDefault(key, "?")); + i = rightBracketPos + 1; + } else { + res.append(s.charAt(i)); + i += 1; + } + } + return res.toString(); + } + + private int findRightBracket(String s, int start, int end) { + for (int i = start; i < end; ++i) { + if (s.charAt(i) == ')') { + return i; + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1808.leetcode1808 Maximize Number of Nice Divisors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1808.leetcode1808 Maximize Number of Nice Divisors-zh.md" new file mode 100644 index 00000000..03e6b332 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1808.leetcode1808 Maximize Number of Nice Divisors-zh.md" @@ -0,0 +1,76 @@ +# [1808. 好因子的最大数目](https://leetcode-cn.com/problems/maximize-number-of-nice-divisors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1808.Maximize%20Number%20of%20Nice%20Divisors/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数 primeFactors 。你需要构造一个正整数 n ,它满足以下条件:

    + +
      +
    • n 质因数(质因数需要考虑重复的情况)的数目 不超过 primeFactors 个。
    • +
    • n 好因子的数目最大化。如果 n 的一个因子可以被 n 的每一个质因数整除,我们称这个因子是 好因子 。比方说,如果 n = 12 ,那么它的质因数为 [2,2,3] ,那么 6 和 12 是好因子,但 3 和 4 不是。
    • +
    + +

    请你返回 n 的好因子的数目。由于答案可能会很大,请返回答案对 109 + 7 取余 的结果。

    + +

    请注意,一个质数的定义是大于 1 ,且不能被分解为两个小于该数的自然数相乘。一个数 n 的质因子是将 n 分解为若干个质因子,且它们的乘积为 n 。

    + +

     

    + +

    示例 1:

    + +
    +输入:primeFactors = 5
    +输出:6
    +解释:200 是一个可行的 n 。
    +它有 5 个质因子:[2,2,2,5,5] ,且有 6 个好因子:[10,20,40,50,100,200] 。
    +不存在别的 n 有至多 5 个质因子,且同时有更多的好因子。
    +
    + +

    示例 2:

    + +
    +输入:primeFactors = 8
    +输出:18
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= primeFactors <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1809.leetcode1809 Ad-Free Sessions-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1809.leetcode1809 Ad-Free Sessions-zh.md" new file mode 100644 index 00000000..65912e4c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1809.leetcode1809 Ad-Free Sessions-zh.md" @@ -0,0 +1,100 @@ +# [1809. 没有广告的剧集](https://leetcode-cn.com/problems/ad-free-sessions) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1809.Ad-Free%20Sessions/README_EN.md) + +## 题目描述 + + + +

    Table: Playback

    + +
    +-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| session_id  | int  |
    +| customer_id | int  |
    +| start_time  | int  |
    +| end_time    | int  |
    ++-------------+------+
    +该表主键为:session_id (剧集id)
    +customer_id 是观看该剧集的观众id
    +剧集播放时间包含start_time(开始时间) 及 end_time(结束时间)
    +可以保证的是,start_time(开始时间)<= end_time(结束时间),一个观众观看的两个剧集的时间不会出现重叠。
    + +

     

    + +

    Table: Ads

    + +
    +-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| ad_id       | int  |
    +| customer_id | int  |
    +| timestamp   | int  |
    ++-------------+------+
    +该表的主键为:ad_id(广告id)
    +customer_id 为 观看广告的用户id
    +timestamp 表示广告出现的时间点
    +
    + +

     

    + +

    请查出,所有没有广告出现过的剧集。

    + +

    如果观众观看了剧集,并且剧集里出现了广告,就一定会有观众观看广告的记录。

    + +

    返回结果没有顺序要求。

    + +

     

    + +

    示例:

    + +
    Playback table:
    ++------------+-------------+------------+----------+
    +| session_id | customer_id | start_time | end_time |
    ++------------+-------------+------------+----------+
    +| 1          | 1           | 1          | 5        |
    +| 2          | 1           | 15         | 23       |
    +| 3          | 2           | 10         | 12       |
    +| 4          | 2           | 17         | 28       |
    +| 5          | 2           | 2          | 8        |
    ++------------+-------------+------------+----------+
    +
    +Ads table:
    ++-------+-------------+-----------+
    +| ad_id | customer_id | timestamp |
    ++-------+-------------+-----------+
    +| 1     | 1           | 5         |
    +| 2     | 2           | 17        |
    +| 3     | 2           | 20        |
    ++-------+-------------+-----------+
    +
    +Result table:
    ++------------+
    +| session_id |
    ++------------+
    +| 2          |
    +| 3          |
    +| 5          |
    ++------------+
    +广告1出现在了剧集1的时间段,被观众1看到了。
    +广告2出现在了剧集4的时间段,被观众2看到了。
    +广告3出现在了剧集4的时间段,被观众2看到了。
    +我们可以得出结论,剧集1 、4 内,起码有1处广告。 剧集2 、3 、5 没有广告。
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1810.leetcode1810 Minimum Path Cost in a Hidden Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1810.leetcode1810 Minimum Path Cost in a Hidden Grid-zh.md" new file mode 100644 index 00000000..f0aa689a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1810.leetcode1810 Minimum Path Cost in a Hidden Grid-zh.md" @@ -0,0 +1,121 @@ +# [1810. Minimum Path Cost in a Hidden Grid](https://leetcode-cn.com/problems/minimum-path-cost-in-a-hidden-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1810.Minimum%20Path%20Cost%20in%20a%20Hidden%20Grid/README_EN.md) + +## 题目描述 + + + +

    This is an interactive problem.

    + +

    There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size m x n, and each cell in the grid is either empty or blocked. It is guaranteed that the starting cell and the target cell are different, and neither of them is blocked.

    + +

    Each cell has a cost that you need to pay each time you move to the cell. The starting cell's cost is not applied before the robot moves.

    + +

    You want to find the minimum total cost to move the robot to the target cell. However, you do not know the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the GridMaster object.

    + +

    The GridMaster class has the following functions:

    + +
      +
    • boolean canMove(char direction) Returns true if the robot can move in that direction. Otherwise, it returns false.
    • +
    • int move(char direction) Moves the robot in that direction and returns the cost of moving to that cell. If this move would move the robot to a blocked cell or off the grid, the move will be ignored, the robot will remain in the same position, and the function will return -1.
    • +
    • boolean isTarget() Returns true if the robot is currently on the target cell. Otherwise, it returns false.
    • +
    + +

    Note that direction in the above functions should be a character from {'U','D','L','R'}, representing the directions up, down, left, and right, respectively.

    + +

    Return the minimum total cost to get the robot from its initial starting cell to the target cell. If there is no valid path between the cells, return -1.

    + +

    Custom testing:

    + +

    The test input is read as a 2D matrix grid of size m x n and four integers r1, c1, r2, and c2 where:

    + +
      +
    • grid[i][j] == 0 indicates that the cell (i, j) is blocked.
    • +
    • grid[i][j] >= 1 indicates that the cell (i, j) is empty and grid[i][j] is the cost to move to that cell.
    • +
    • (r1, c1) is the starting cell of the robot.
    • +
    • (r2, c2) is the target cell of the robot.
    • +
    + +

    Remember that you will not have this information in your code.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[2,3],[1,1]], r1 = 0, c1 = 1, r2 = 1, c2 = 0
    +Output: 2
    +Explanation: One possible interaction is described below:
    +The robot is initially standing on cell (0, 1), denoted by the 3.
    +- master.canMove('U') returns false.
    +- master.canMove('D') returns true.
    +- master.canMove('L') returns true.
    +- master.canMove('R') returns false.
    +- master.move('L') moves the robot to the cell (0, 0) and returns 2.
    +- master.isTarget() returns false.
    +- master.canMove('U') returns false.
    +- master.canMove('D') returns true.
    +- master.canMove('L') returns false.
    +- master.canMove('R') returns true.
    +- master.move('D') moves the robot to the cell (1, 0) and returns 1.
    +- master.isTarget() returns true.
    +- master.move('L') doesn't move the robot and returns -1.
    +- master.move('R') moves the robot to the cell (1, 1) and returns 1.
    +We now know that the target is the cell (0, 1), and the minimum total cost to reach it is 2. 
    + +

    Example 2:

    + +
    +Input: grid = [[0,3,1],[3,4,2],[1,2,0]], r1 = 2, c1 = 0, r2 = 0, c2 = 2
    +Output: 9
    +Explanation: The minimum cost path is (2,0) -> (2,1) -> (1,1) -> (1,2) -> (0,2).
    +
    + +

    Example 3:

    + +
    +Input: grid = [[1,0],[0,1]], r1 = 0, c1 = 0, r2 = 1, c2 = 1
    +Output: -1
    +Explanation: There is no path from the robot to the target cell.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= n, m <= 100
    • +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 0 <= grid[i][j] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1811.leetcode1811 Find Interview Candidates-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1811.leetcode1811 Find Interview Candidates-zh.md" new file mode 100644 index 00000000..6fef8986 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1811.leetcode1811 Find Interview Candidates-zh.md" @@ -0,0 +1,120 @@ +# [1811. Find Interview Candidates](https://leetcode-cn.com/problems/find-interview-candidates) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1811.Find%20Interview%20Candidates/README_EN.md) + +## 题目描述 + + + +

    Table: Contests

    + +
    ++--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| contest_id   | int  |
    +| gold_medal   | int  |
    +| silver_medal | int  |
    +| bronze_medal | int  |
    ++--------------+------+
    +contest_id is the primary key for this table.
    +This table contains the LeetCode contest ID and the user IDs of the gold, silver, and bronze medalists.
    +It is guaranteed that any consecutive contests have consecutive IDs and that no ID is skipped.
    + +

     

    + +

    Table: Users

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| mail        | varchar |
    +| name        | varchar |
    ++-------------+---------+
    +user_id is the primary key for this table.
    +This table contains information about the users.
    +
    + +

     

    + +

    Write an SQL query to report the name and the mail of all interview candidates. A user is an interview candidate if at least one of these two conditions is true:

    + +
      +
    • The user won any medal in three or more consecutive contests.
    • +
    • The user won the gold medal in three or more different contests (not necessarily consecutive).
    • +
    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Contests table:
    ++------------+------------+--------------+--------------+
    +| contest_id | gold_medal | silver_medal | bronze_medal |
    ++------------+------------+--------------+--------------+
    +| 190        | 1          | 5            | 2            |
    +| 191        | 2          | 3            | 5            |
    +| 192        | 5          | 2            | 3            |
    +| 193        | 1          | 3            | 5            |
    +| 194        | 4          | 5            | 2            |
    +| 195        | 4          | 2            | 1            |
    +| 196        | 1          | 5            | 2            |
    ++------------+------------+--------------+--------------+
    +
    +Users table:
    ++---------+--------------------+-------+
    +| user_id | mail               | name  |
    ++---------+--------------------+-------+
    +| 1       | sarah@leetcode.com | Sarah |
    +| 2       | bob@leetcode.com   | Bob   |
    +| 3       | alice@leetcode.com | Alice |
    +| 4       | hercy@leetcode.com | Hercy |
    +| 5       | quarz@leetcode.com | Quarz |
    ++---------+--------------------+-------+
    +
    +Result table:
    ++-------+--------------------+
    +| name  | mail               |
    ++-------+--------------------+
    +| Sarah | sarah@leetcode.com |
    +| Bob   | bob@leetcode.com   |
    +| Alice | alice@leetcode.com |
    +| Quarz | quarz@leetcode.com |
    ++-------+--------------------+
    +
    +Sarah won 3 gold medals (190, 193, and 196), so we include her in the result table.
    +Bob won a medal in 3 consecutive contests (190, 191, and 192), so we include him in the result table.
    +    - Note that he also won a medal in 3 other consecutive contests (194, 195, and 196).
    +Alice won a medal in 3 consecutive contests (191, 192, and 193), so we include her in the result table.
    +Quarz won a medal in 5 consecutive contests (190, 191, 192, 193, and 194), so we include them in the result table.
    +
    + +

     

    +

    Follow up:

    + +
      +
    • What if the first condition changed to be "any medal in n or more consecutive contests"? How would you change your solution to get the interview candidates? Imagine that n is the parameter of a stored procedure.
    • +
    • Some users may not participate in every contest but still perform well in the ones they do. How would you change your solution to only consider contests where the user was a participant? Suppose the registered users for each contest are given in another table.
    • +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1812.leetcode1812 Determine Color of a Chessboard Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1812.leetcode1812 Determine Color of a Chessboard Square-zh.md" new file mode 100644 index 00000000..79df1c7d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1812.leetcode1812 Determine Color of a Chessboard Square-zh.md" @@ -0,0 +1,105 @@ +# [1812. 判断国际象棋棋盘中一个格子的颜色](https://leetcode-cn.com/problems/determine-color-of-a-chessboard-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1812.Determine%20Color%20of%20a%20Chessboard%20Square/README_EN.md) + +## 题目描述 + + + +

    给你一个坐标 coordinates ,它是一个字符串,表示国际象棋棋盘中一个格子的坐标。下图是国际象棋棋盘示意图。

    + +

    + +

    如果所给格子的颜色是白色,请你返回 true,如果是黑色,请返回 false 。

    + +

    给定坐标一定代表国际象棋棋盘上一个存在的格子。坐标第一个字符是字母,第二个字符是数字。

    + +

     

    + +

    示例 1:

    + +
    +输入:coordinates = "a1"
    +输出:false
    +解释:如上图棋盘所示,"a1" 坐标的格子是黑色的,所以返回 false 。
    +
    + +

    示例 2:

    + +
    +输入:coordinates = "h3"
    +输出:true
    +解释:如上图棋盘所示,"h3" 坐标的格子是白色的,所以返回 true 。
    +
    + +

    示例 3:

    + +
    +输入:coordinates = "c7"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • coordinates.length == 2
    • +
    • 'a' <= coordinates[0] <= 'h'
    • +
    • '1' <= coordinates[1] <= '8'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def squareIsWhite(self, coordinates: str) -> bool: + x = ord(coordinates[0]) - ord('a') + 1 + y = int(coordinates[1]) + return ((x + y) & 1) == 1 +``` + +### **Java** + + + +```java +class Solution { + public boolean squareIsWhite(String coordinates) { + int x = coordinates.charAt(0) - 'a' + 1; + int y = coordinates.charAt(1) - '0'; + return ((x + y) & 1) == 1; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} coordinates + * @return {boolean} + */ + var squareIsWhite = function(coordinates) { + let x = coordinates.charAt(0).charCodeAt() - 'a'.charCodeAt() + 1; + let y = Number(coordinates.charAt(1)); + return ((x + y) & 1) == 1; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1813.leetcode1813 Sentence Similarity III-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1813.leetcode1813 Sentence Similarity III-zh.md" new file mode 100644 index 00000000..7841b3ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1813.leetcode1813 Sentence Similarity III-zh.md" @@ -0,0 +1,133 @@ +# [1813. 句子相似性 III](https://leetcode-cn.com/problems/sentence-similarity-iii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1813.Sentence%20Similarity%20III/README_EN.md) + +## 题目描述 + + + +

    一个句子是由一些单词与它们之间的单个空格组成,且句子的开头和结尾没有多余空格。比方说,"Hello World" ,"HELLO" ,"hello world hello world" 都是句子。每个单词都  包含大写和小写英文字母。

    + +

    如果两个句子 sentence1 和 sentence2 ,可以通过往其中一个句子插入一个任意的句子(可以是空句子)而得到另一个句子,那么我们称这两个句子是 相似的 。比方说,sentence1 = "Hello my name is Jane" 且 sentence2 = "Hello Jane" ,我们可以往 sentence2 中 "Hello" 和 "Jane" 之间插入 "my name is" 得到 sentence1 。

    + +

    给你两个句子 sentence1 和 sentence2 ,如果 sentence1 sentence2 是相似的,请你返回 true ,否则返回 false 。

    + +

     

    + +

    示例 1:

    + +
    输入:sentence1 = "My name is Haley", sentence2 = "My Haley"
    +输出:true
    +解释:可以往 sentence2 中 "My" 和 "Haley" 之间插入 "name is" ,得到 sentence1 。
    +
    + +

    示例 2:

    + +
    输入:sentence1 = "of", sentence2 = "A lot of words"
    +输出:false
    +解释:没法往这两个句子中的一个句子只插入一个句子就得到另一个句子。
    +
    + +

    示例 3:

    + +
    输入:sentence1 = "Eating right now", sentence2 = "Eating"
    +输出:true
    +解释:可以往 sentence2 的结尾插入 "right now" 得到 sentence1 。
    +
    + +

    示例 4:

    + +
    输入:sentence1 = "Luky", sentence2 = "Lucccky"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= sentence1.length, sentence2.length <= 100
    • +
    • sentence1 和 sentence2 都只包含大小写英文字母和空格。
    • +
    • sentence1 和 sentence2 中的单词都只由单个空格隔开。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: + if sentence1 == sentence2: + return True + n1, n2 = len(sentence1), len(sentence2) + if n1 == n2: + return False + if n1 < n2: + sentence1, sentence2 = sentence2, sentence1 + words1, words2 = sentence1.split(), sentence2.split() + i = j = 0 + while i < len(words2) and words1[i] == words2[i]: + i += 1 + if i == len(words2): + return True + while j < len(words2) and words1[len(words1) - 1 - j] == words2[len(words2) - 1 - j]: + j += 1 + if j == len(words2): + return True + return i + j == len(words2) +``` + +### **Java** + + + +```java +class Solution { + public boolean areSentencesSimilar(String sentence1, String sentence2) { + if (Objects.equals(sentence1, sentence2)) { + return true; + } + int n1 = sentence1.length(), n2 = sentence2.length(); + if (n1 == n2) { + return false; + } + if (n1 < n2) { + String t = sentence1; + sentence1 = sentence2; + sentence2 = t; + } + String[] words1 = sentence1.split(" "); + String[] words2 = sentence2.split(" "); + int i = 0, j = 0; + while (i < words2.length && Objects.equals(words1[i], words2[i])) { + ++i; + } + if (i == words2.length) { + return true; + } + while (j < words2.length && Objects.equals(words1[words1.length - 1 - j], words2[words2.length - 1 - j])) { + ++j; + } + if (j == words2.length) { + return true; + } + return i + j == words2.length; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1814.leetcode1814 Count Nice Pairs in an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1814.leetcode1814 Count Nice Pairs in an Array-zh.md" new file mode 100644 index 00000000..bee94cc6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1814.leetcode1814 Count Nice Pairs in an Array-zh.md" @@ -0,0 +1,73 @@ +# [1814. 统计一个数组中好对子的数目](https://leetcode-cn.com/problems/count-nice-pairs-in-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1814.Count%20Nice%20Pairs%20in%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 nums ,数组中只包含非负整数。定义 rev(x) 的值为将整数 x 各个数字位反转得到的结果。比方说 rev(123) = 321 , rev(120) = 21 。我们称满足下面条件的下标对 (i, j) 是 好的 :

    + +
      +
    • 0 <= i < j < nums.length
    • +
    • nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
    • +
    + +

    请你返回好下标对的数目。由于结果可能会很大,请将结果对 109 + 7 取余 后返回。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [42,11,1,97]
    +输出:2
    +解释:两个坐标对为:
    + - (0,3):42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121 。
    + - (1,2):11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12 。
    +
    + +

    示例 2:

    + +
    输入:nums = [13,10,35,24,76]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 0 <= nums[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1815.leetcode1815 Maximum Number of Groups Getting Fresh Donuts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1815.leetcode1815 Maximum Number of Groups Getting Fresh Donuts-zh.md" new file mode 100644 index 00000000..11c601df --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1815.leetcode1815 Maximum Number of Groups Getting Fresh Donuts-zh.md" @@ -0,0 +1,71 @@ +# [1815. 得到新鲜甜甜圈的最多组数](https://leetcode-cn.com/problems/maximum-number-of-groups-getting-fresh-donuts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1815.Maximum%20Number%20of%20Groups%20Getting%20Fresh%20Donuts/README_EN.md) + +## 题目描述 + + + +

    有一个甜甜圈商店,每批次都烤 batchSize 个甜甜圈。这个店铺有个规则,就是在烤一批新的甜甜圈时,之前 所有 甜甜圈都必须已经全部销售完毕。给你一个整数 batchSize 和一个整数数组 groups ,数组中的每个整数都代表一批前来购买甜甜圈的顾客,其中 groups[i] 表示这一批顾客的人数。每一位顾客都恰好只要一个甜甜圈。

    + +

    当有一批顾客来到商店时,他们所有人都必须在下一批顾客来之前购买完甜甜圈。如果一批顾客中第一位顾客得到的甜甜圈不是上一组剩下的,那么这一组人都会很开心。

    + +

    你可以随意安排每批顾客到来的顺序。请你返回在此前提下,最多 有多少组人会感到开心。

    + +

     

    + +

    示例 1:

    + +
    +输入:batchSize = 3, groups = [1,2,3,4,5,6]
    +输出:4
    +解释:你可以将这些批次的顾客顺序安排为 [6,2,4,5,1,3] 。那么第 1,2,4,6 组都会感到开心。
    +
    + +

    示例 2:

    + +
    +输入:batchSize = 4, groups = [1,3,2,5,2,2,1,6]
    +输出:4
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= batchSize <= 9
    • +
    • 1 <= groups.length <= 30
    • +
    • 1 <= groups[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1816.leetcode1816 Truncate Sentence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1816.leetcode1816 Truncate Sentence-zh.md" new file mode 100644 index 00000000..522069cf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1816.leetcode1816 Truncate Sentence-zh.md" @@ -0,0 +1,135 @@ +# [1816. 截断句子](https://leetcode-cn.com/problems/truncate-sentence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1816.Truncate%20Sentence/README_EN.md) + +## 题目描述 + + + +

    句子 是一个单词列表,列表中的单词之间用单个空格隔开,且不存在前导或尾随空格。每个单词仅由大小写英文字母组成(不含标点符号)。

    + +
      +
    • 例如,"Hello World""HELLO""hello world hello world" 都是句子。
    • +
    + +

    给你一个句子 s​​​​​​ 和一个整数 k​​​​​​ ,请你将 s​​ 截断 ​,​​​使截断后的句子仅含 k​​​​​​ 个单词。返回 截断 s​​​​​​ 后得到的句子

    + +

     

    + +

    示例 1:

    + +
    输入:s = "Hello how are you Contestant", k = 4
    +输出:"Hello how are you"
    +解释:
    +s 中的单词为 ["Hello", "how" "are", "you", "Contestant"]
    +前 4 个单词为 ["Hello", "how", "are", "you"]
    +因此,应当返回 "Hello how are you"
    +
    + +

    示例 2:

    + +
    输入:s = "What is the solution to this problem", k = 4
    +输出:"What is the solution"
    +解释:
    +s 中的单词为 ["What", "is" "the", "solution", "to", "this", "problem"]
    +前 4 个单词为 ["What", "is", "the", "solution"]
    +因此,应当返回 "What is the solution"
    + +

    示例 3:

    + +
    输入:s = "chopper is not a tanuki", k = 5
    +输出:"chopper is not a tanuki"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 500
    • +
    • k 的取值范围是 [1,  s 中单词的数目]
    • +
    • s 仅由大小写英文字母和空格组成
    • +
    • s 中的单词之间由单个空格隔开
    • +
    • 不存在前导或尾随空格
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + for i, c in enumerate(s): + if c == ' ': + k -= 1 + if k == 0: + return s[:i] + return s +``` + +### **Java** + + + +```java +class Solution { + public String truncateSentence(String s, int k) { + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == ' ' && (--k) == 0) { + return s.substring(0, i); + } + } + return s; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string truncateSentence(string s, int k) { + for (int i = 0; i < s.size(); ++i) { + if (s[i] == ' ' && (--k) == 0) { + return s.substr(0, i); + } + } + return s; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var truncateSentence = function (s, k) { + for (let i = 0; i < s.length; ++i) { + if (s[i] == " " && --k == 0) { + return s.substring(0, i); + } + } + return s; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1817.leetcode1817 Finding the Users Active Minutes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1817.leetcode1817 Finding the Users Active Minutes-zh.md" new file mode 100644 index 00000000..eeb4d4de --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1817.leetcode1817 Finding the Users Active Minutes-zh.md" @@ -0,0 +1,84 @@ +# [1817. 查找用户活跃分钟数](https://leetcode-cn.com/problems/finding-the-users-active-minutes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1817.Finding%20the%20Users%20Active%20Minutes/README_EN.md) + +## 题目描述 + + + +

    给你用户在 LeetCode 的操作日志,和一个整数 k 。日志用一个二维整数数组 logs 表示,其中每个 logs[i] = [IDi, timei] 表示 ID 为 IDi 的用户在 timei 分钟时执行了某个操作。

    + +

    多个用户 可以同时执行操作,单个用户可以在同一分钟内执行 多个操作

    + +

    指定用户的 用户活跃分钟数(user active minutes,UAM) 定义为用户对 LeetCode 执行操作的 唯一分钟数 。 即使一分钟内执行多个操作,也只能按一分钟计数。

    + +

    请你统计用户活跃分钟数的分布情况,统计结果是一个长度为 k下标从 1 开始计数 的数组 answer ,对于每个 j1 <= j <= k),answer[j] 表示 用户活跃分钟数 等于 j 的用户数。

    + +

    返回上面描述的答案数组 answer

    + +

     

    + +

    示例 1:

    + +
    +输入:logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5
    +输出:[0,2,0,0,0]
    +解释:
    +ID=0 的用户执行操作的分钟分别是:5 、2 和 5 。因此,该用户的用户活跃分钟数为 2(分钟 5 只计数一次)
    +ID=1 的用户执行操作的分钟分别是:2 和 3 。因此,该用户的用户活跃分钟数为 2
    +2 个用户的用户活跃分钟数都是 2 ,answer[2] 为 2 ,其余 answer[j] 的值都是 0
    +
    + +

    示例 2:

    + +
    +输入:logs = [[1,1],[2,2],[2,3]], k = 4
    +输出:[1,1,0,0]
    +解释:
    +ID=1 的用户仅在分钟 1 执行单个操作。因此,该用户的用户活跃分钟数为 1
    +ID=2 的用户执行操作的分钟分别是:2 和 3 。因此,该用户的用户活跃分钟数为 2
    +1 个用户的用户活跃分钟数是 1 ,1 个用户的用户活跃分钟数是 2 
    +因此,answer[1] = 1 ,answer[2] = 1 ,其余的值都是 0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= logs.length <= 104
    • +
    • 0 <= IDi <= 109
    • +
    • 1 <= timei <= 105
    • +
    • k 的取值范围是 [用户的最大用户活跃分钟数, 105]
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1818.leetcode1818 Minimum Absolute Sum Difference-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1818.leetcode1818 Minimum Absolute Sum Difference-zh.md" new file mode 100644 index 00000000..f4578d75 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1818.leetcode1818 Minimum Absolute Sum Difference-zh.md" @@ -0,0 +1,94 @@ +# [1818. 绝对差值和](https://leetcode-cn.com/problems/minimum-absolute-sum-difference) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1818.Minimum%20Absolute%20Sum%20Difference/README_EN.md) + +## 题目描述 + + + +

    给你两个正整数数组 nums1nums2 ,数组的长度都是 n

    + +

    数组 nums1nums2绝对差值和 定义为所有 |nums1[i] - nums2[i]|0 <= i < n)的 总和下标从 0 开始)。

    + +

    你可以选用 nums1 中的 任意一个 元素来替换 nums1 中的 至多 一个元素,以 最小化 绝对差值和。

    + +

    在替换数组 nums1 中最多一个元素 之后 ,返回最小绝对差值和。因为答案可能很大,所以需要对 109 + 7 取余 后返回。

    + +

    |x| 定义为:

    + +
      +
    • 如果 x >= 0 ,值为 x ,或者
    • +
    • 如果 x <= 0 ,值为 -x
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums1 = [1,7,5], nums2 = [2,3,5]
    +输出:3
    +解释:有两种可能的最优方案:
    +- 将第二个元素替换为第一个元素:[1,7,5] => [1,1,5] ,或者
    +- 将第二个元素替换为第三个元素:[1,7,5] => [1,5,5]
    +两种方案的绝对差值和都是 |1-2| + (|1-3| 或者 |5-3|) + |5-5| = 3
    +
    + +

    示例 2:

    + +
    +输入:nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
    +输出:0
    +解释:nums1 和 nums2 相等,所以不用替换元素。绝对差值和为 0
    +
    + +

    示例 3

    + +
    +输入:nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
    +输出:20
    +解释:将第一个元素替换为第二个元素:[1,10,4,4,2,7] => [10,10,4,4,2,7]
    +绝对差值和为 |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums1.length
    • +
    • n == nums2.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1819.leetcode1819 Number of Different Subsequences GCDs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1819.leetcode1819 Number of Different Subsequences GCDs-zh.md" new file mode 100644 index 00000000..3bdb35ba --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1819.leetcode1819 Number of Different Subsequences GCDs-zh.md" @@ -0,0 +1,81 @@ +# [1819. 序列中不同最大公约数的数目](https://leetcode-cn.com/problems/number-of-different-subsequences-gcds) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1819.Number%20of%20Different%20Subsequences%20GCDs/README_EN.md) + +## 题目描述 + + + +

    给你一个由正整数组成的数组 nums

    + +

    数字序列的 最大公约数 定义为序列中所有整数的共有约数中的最大整数。

    + +
      +
    • 例如,序列 [4,6,16] 的最大公约数是 2
    • +
    + +

    数组的一个 子序列 本质是一个序列,可以通过删除数组中的某些元素(或者不删除)得到。

    + +
      +
    • 例如,[2,5,10][1,2,1,2,4,1,5,10] 的一个子序列。
    • +
    + +

    计算并返回 nums 的所有 非空 子序列中 不同 最大公约数的 数目

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [6,10,3]
    +输出:5
    +解释:上图显示了所有的非空子序列与各自的最大公约数。
    +不同的最大公约数为 6 、10 、3 、2 和 1 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [5,15,40,5,6]
    +输出:7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 2 * 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1820.leetcode1820 Maximum Number of Accepted Invitations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1820.leetcode1820 Maximum Number of Accepted Invitations-zh.md" new file mode 100644 index 00000000..f780fac5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1820.leetcode1820 Maximum Number of Accepted Invitations-zh.md" @@ -0,0 +1,81 @@ +# [1820. Maximum Number of Accepted Invitations](https://leetcode-cn.com/problems/maximum-number-of-accepted-invitations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1820.Maximum%20Number%20of%20Accepted%20Invitations/README_EN.md) + +## 题目描述 + + + +

    There are m boys and n girls in a class attending an upcoming party.

    + +

    You are given an m x n integer matrix grid, where grid[i][j] equals 0 or 1. If grid[i][j] == 1, then that means the ith boy can invite the jth girl to the party. A boy can invite at most one girl, and a girl can accept at most one invitation from a boy.

    + +

    Return the maximum possible number of accepted invitations.

    + +

     

    +

    Example 1:

    + +
    +Input: grid = [[1,1,1],
    +               [1,0,1],
    +               [0,0,1]]
    +Output: 3
    +Explanation: The invitations are sent as follows:
    +- The 1st boy invites the 2nd girl.
    +- The 2nd boy invites the 1st girl.
    +- The 3rd boy invites the 3rd girl.
    + +

    Example 2:

    + +
    +Input: grid = [[1,0,1,0],
    +               [1,0,0,0],
    +               [0,0,1,0],
    +               [1,1,1,0]]
    +Output: 3
    +Explanation: The invitations are sent as follows:
    +-The 1st boy invites the 3rd girl.
    +-The 2nd boy invites the 1st girl.
    +-The 3rd boy invites no one.
    +-The 4th boy invites the 2nd girl.
    + +

     

    +

    Constraints:

    + +
      +
    • grid.length == m
    • +
    • grid[i].length == n
    • +
    • 1 <= m, n <= 200
    • +
    • grid[i][j] is either 0 or 1.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1821.leetcode1821 Find Customers With Positive Revenue this Year-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1821.leetcode1821 Find Customers With Positive Revenue this Year-zh.md" new file mode 100644 index 00000000..3b92eb11 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1821.leetcode1821 Find Customers With Positive Revenue this Year-zh.md" @@ -0,0 +1,83 @@ +# [1821. 寻找今年具有正收入的客户](https://leetcode-cn.com/problems/find-customers-with-positive-revenue-this-year) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1821.Find%20Customers%20With%20Positive%20Revenue%20this%20Year/README_EN.md) + +## 题目描述 + + + +

    表:Customers

    + +
    ++--------------+------+
    +| Column Name  | Type |
    ++--------------+------+
    +| customer_id  | int  |
    +| year         | int  |
    +| revenue      | int  |
    ++--------------+------+
    +(customer_id, year) 是这个表的主键。
    +这个表包含客户 ID 和不同年份的客户收入。
    +注意,这个收入可能是负数。
    +
    + +

     

    + +

    写一个 SQL 查询来查询 2021 年具有 正收入 的客户。

    + +

    可以按 任意顺序 返回结果表。

    + +

    查询结果格式如下例。

    + +

     

    + +
    +Customers
    ++-------------+------+---------+
    +| customer_id | year | revenue |
    ++-------------+------+---------+
    +| 1           | 2018 | 50      |
    +| 1           | 2021 | 30      |
    +| 1           | 2020 | 70      |
    +| 2           | 2021 | -50     |
    +| 3           | 2018 | 10      |
    +| 3           | 2016 | 50      |
    +| 4           | 2021 | 20      |
    ++-------------+------+---------+
    +
    +Result table:
    ++-------------+
    +| customer_id |
    ++-------------+
    +| 1           |
    +| 4           |
    ++-------------+
    +客户 1 在 2021 年的收入等于 30 。
    +客户 2 在 2021 年的收入等于 -50 。
    +客户 3 在 2021 年没有收入。
    +客户 4 在 2021 年的收入等于 20 。
    +因此,只有客户 1 和 4 在 2021 年有正收入。
    + + +## 解法 + + + + + +### **SQL** + + + +```sql +# Write your MySQL query statement below +SELECT + customer_id +FROM + Customers +WHERE + year = '2021' +AND revenue > 0; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1822.leetcode1822 Sign of the Product of an Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1822.leetcode1822 Sign of the Product of an Array-zh.md" new file mode 100644 index 00000000..47bad6cb --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1822.leetcode1822 Sign of the Product of an Array-zh.md" @@ -0,0 +1,155 @@ +# [1822. 数组元素积的符号](https://leetcode-cn.com/problems/sign-of-the-product-of-an-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1822.Sign%20of%20the%20Product%20of%20an%20Array/README_EN.md) + +## 题目描述 + + + +

    已知函数 signFunc(x) 将会根据 x 的正负返回特定值:

    + +
      +
    • 如果 x 是正数,返回 1
    • +
    • 如果 x 是负数,返回 -1
    • +
    • 如果 x 是等于 0 ,返回 0
    • +
    + +

    给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。

    + +

    返回 signFunc(product)

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [-1,-2,-3,-4,3,2,1]
    +输出:1
    +解释:数组中所有值的乘积是 144 ,且 signFunc(144) = 1
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,5,0,2,-3]
    +输出:0
    +解释:数组中所有值的乘积是 0 ,且 signFunc(0) = 0
    +
    + +

    示例 3:

    + +
    +输入:nums = [-1,1,-1,1,-1]
    +输出:-1
    +解释:数组中所有值的乘积是 -1 ,且 signFunc(-1) = -1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • -100 <= nums[i] <= 100
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def arraySign(self, nums: List[int]) -> int: + res = 1 + for num in nums: + if num == 0: + return 0 + if num < 0: + res *= -1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int arraySign(int[] nums) { + int res = 1; + for (int num : nums) { + if (num == 0) return 0; + if (num < 0) res *= -1; + } + return res; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var arraySign = function (nums) { + let res = 1; + for (let num of nums) { + if (num == 0) return 0; + if (num < 0) res *= -1; + } + return res; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int arraySign(vector& nums) { + int res = 1; + for (auto &num : nums) { + if (num == 0) { + return 0; + } + if (num < 0) { + res *= -1; + } + } + return res; + } +}; +``` + +### **Go** + +```go +func arraySign(nums []int) int { + res := 1 + for _, num := range nums { + if num == 0 { + return 0 + } + if num < 0 { + res *= -1 + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1823.leetcode1823 Find the Winner of the Circular Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1823.leetcode1823 Find the Winner of the Circular Game-zh.md" new file mode 100644 index 00000000..d13d9b77 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1823.leetcode1823 Find the Winner of the Circular Game-zh.md" @@ -0,0 +1,86 @@ +# [1823. 找出游戏的获胜者](https://leetcode-cn.com/problems/find-the-winner-of-the-circular-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1823.Find%20the%20Winner%20of%20the%20Circular%20Game/README_EN.md) + +## 题目描述 + + + +

    共有 n 名小伙伴一起做游戏。小伙伴们围成一圈,按 顺时针顺序1n 编号。确切地说,从第 i 名小伙伴顺时针移动一位会到达第 (i+1) 名小伙伴的位置,其中 1 <= i < n ,从第 n 名小伙伴顺时针移动一位会回到第 1 名小伙伴的位置。

    + +

    游戏遵循如下规则:

    + +
      +
    1. 从第 1 名小伙伴所在位置 开始
    2. +
    3. 沿着顺时针方向数 k 名小伙伴,计数时需要 包含 起始时的那位小伙伴。逐个绕圈进行计数,一些小伙伴可能会被数过不止一次。
    4. +
    5. 你数到的最后一名小伙伴需要离开圈子,并视作输掉游戏。
    6. +
    7. 如果圈子中仍然有不止一名小伙伴,从刚刚输掉的小伙伴的 顺时针下一位 小伙伴 开始,回到步骤 2 继续执行。
    8. +
    9. 否则,圈子中最后一名小伙伴赢得游戏。
    10. +
    + +

    给你参与游戏的小伙伴总数 n ,和一个整数 k ,返回游戏的获胜者。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 5, k = 2
    +输出:3
    +解释:游戏运行步骤如下:
    +1) 从小伙伴 1 开始。
    +2) 顺时针数 2 名小伙伴,也就是小伙伴 1 和 2 。
    +3) 小伙伴 2 离开圈子。下一次从小伙伴 3 开始。
    +4) 顺时针数 2 名小伙伴,也就是小伙伴 3 和 4 。
    +5) 小伙伴 4 离开圈子。下一次从小伙伴 5 开始。
    +6) 顺时针数 2 名小伙伴,也就是小伙伴 5 和 1 。
    +7) 小伙伴 1 离开圈子。下一次从小伙伴 3 开始。
    +8) 顺时针数 2 名小伙伴,也就是小伙伴 3 和 5 。
    +9) 小伙伴 5 离开圈子。只剩下小伙伴 3 。所以小伙伴 3 是游戏的获胜者。
    + +

    示例 2:

    + +
    +输入:n = 6, k = 5
    +输出:1
    +解释:小伙伴离开圈子的顺序:5、4、6、2、3 。小伙伴 1 是游戏的获胜者。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= k <= n <= 500
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1824.leetcode1824 Minimum Sideway Jumps-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1824.leetcode1824 Minimum Sideway Jumps-zh.md" new file mode 100644 index 00000000..2532a4de --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1824.leetcode1824 Minimum Sideway Jumps-zh.md" @@ -0,0 +1,94 @@ +# [1824. 最少侧跳次数](https://leetcode-cn.com/problems/minimum-sideway-jumps) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1824.Minimum%20Sideway%20Jumps/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的 3 跑道道路 ,它总共包含 n + 1 个  ,编号为 0 到 n 。一只青蛙从 0 号点第二条跑道 出发 ,它想要跳到点 n 处。然而道路上可能有一些障碍。

    + +

    给你一个长度为 n + 1 的数组 obstacles ,其中 obstacles[i] (取值范围从 0 到 3)表示在点 i 处的 obstacles[i] 跑道上有一个障碍。如果 obstacles[i] == 0 ,那么点 i 处没有障碍。任何一个点的三条跑道中 最多有一个 障碍。

    + +
      +
    • 比方说,如果 obstacles[2] == 1 ,那么说明在点 2 处跑道 1 有障碍。
    • +
    + +

    这只青蛙从点 i 跳到点 i + 1 且跑道不变的前提是点 i + 1 的同一跑道上没有障碍。为了躲避障碍,这只青蛙也可以在 同一个 点处 侧跳 到 另外一条 跑道(这两条跑道可以不相邻),但前提是跳过去的跑道该点处没有障碍。

    + +
      +
    • 比方说,这只青蛙可以从点 3 处的跑道 3 跳到点 3 处的跑道 1 。
    • +
    + +

    这只青蛙从点 0 处跑道 2 出发,并想到达点 n 处的 任一跑道 ,请你返回 最少侧跳次数 。

    + +

    注意:点 0 处和点 n 处的任一跑道都不会有障碍。

    + +

     

    + +

    示例 1:

    + +
    +输入:obstacles = [0,1,2,3,0]
    +输出:2 
    +解释:最优方案如上图箭头所示。总共有 2 次侧跳(红色箭头)。
    +注意,这只青蛙只有当侧跳时才可以跳过障碍(如上图点 2 处所示)。
    +
    + +

    示例 2:

    + +
    +输入:obstacles = [0,1,1,3,3,0]
    +输出:0
    +解释:跑道 2 没有任何障碍,所以不需要任何侧跳。
    +
    + +

    示例 3:

    + +
    +输入:obstacles = [0,2,1,0,3,0]
    +输出:2
    +解释:最优方案如上图所示。总共有 2 次侧跳。
    +
    + +

     

    + +

    提示:

    + +
      +
    • obstacles.length == n + 1
    • +
    • 1 <= n <= 5 * 105
    • +
    • 0 <= obstacles[i] <= 3
    • +
    • obstacles[0] == obstacles[n] == 0
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1825.leetcode1825 Finding MK Average-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1825.leetcode1825 Finding MK Average-zh.md" new file mode 100644 index 00000000..a04983ae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1825.leetcode1825 Finding MK Average-zh.md" @@ -0,0 +1,95 @@ +# [1825. 求出 MK 平均值](https://leetcode-cn.com/problems/finding-mk-average) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1825.Finding%20MK%20Average/README_EN.md) + +## 题目描述 + + + +

    给你两个整数 m 和 k ,以及数据流形式的若干整数。你需要实现一个数据结构,计算这个数据流的 MK 平均值 。

    + +

    MK 平均值 按照如下步骤计算:

    + +
      +
    1. 如果数据流中的整数少于 m 个,MK 平均值 为 -1 ,否则将数据流中最后 m 个元素拷贝到一个独立的容器中。
    2. +
    3. 从这个容器中删除最小的 k 个数和最大的 k 个数。
    4. +
    5. 计算剩余元素的平均值,并 向下取整到最近的整数 。
    6. +
    + +

    请你实现 MKAverage 类:

    + +
      +
    • MKAverage(int m, int k) 用一个空的数据流和两个整数 m 和 k 初始化 MKAverage 对象。
    • +
    • void addElement(int num) 往数据流中插入一个新的元素 num 。
    • +
    • int calculateMKAverage() 对当前的数据流计算并返回 MK 平均数 ,结果需 向下取整到最近的整数
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
    +[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]
    +输出:
    +[null, null, null, -1, null, 3, null, null, null, 5]
    +
    +解释:
    +MKAverage obj = new MKAverage(3, 1); 
    +obj.addElement(3);        // 当前元素为 [3]
    +obj.addElement(1);        // 当前元素为 [3,1]
    +obj.calculateMKAverage(); // 返回 -1 ,因为 m = 3 ,但数据流中只有 2 个元素
    +obj.addElement(10);       // 当前元素为 [3,1,10]
    +obj.calculateMKAverage(); // 最后 3 个元素为 [3,1,10]
    +                          // 删除最小以及最大的 1 个元素后,容器为 [3]
    +                          // [3] 的平均值等于 3/1 = 3 ,故返回 3
    +obj.addElement(5);        // 当前元素为 [3,1,10,5]
    +obj.addElement(5);        // 当前元素为 [3,1,10,5,5]
    +obj.addElement(5);        // 当前元素为 [3,1,10,5,5,5]
    +obj.calculateMKAverage(); // 最后 3 个元素为 [5,5,5]
    +                          // 删除最小以及最大的 1 个元素后,容器为 [5]
    +                          // [5] 的平均值等于 5/1 = 5 ,故返回 5
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= m <= 105
    • +
    • 1 <= k*2 < m
    • +
    • 1 <= num <= 105
    • +
    • addElement 与 calculateMKAverage 总操作次数不超过 105 次。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1826.leetcode1826 Faulty Sensor-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1826.leetcode1826 Faulty Sensor-zh.md" new file mode 100644 index 00000000..b5c2bb06 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1826.leetcode1826 Faulty Sensor-zh.md" @@ -0,0 +1,88 @@ +# [1826. 有缺陷的传感器](https://leetcode-cn.com/problems/faulty-sensor) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1826.Faulty%20Sensor/README_EN.md) + +## 题目描述 + + + +

    实验室里正在进行一项实验。为了确保数据的准确性,同时使用 两个 传感器来采集数据。您将获得2个数组 sensor1 and sensor2,其中 sensor1[i] 和 sensor2[i] 分别是两个传感器对i数据点采集到的数据。

    + +

    但是,这种类型的传感器有可能存在缺陷,它会导致 某一个 数据点采集的数据(掉落值)被丢弃。

    + +

    数据被丢弃后,所有在其右侧的数据点采集的数据,都会被向左移动一个位置,最后一个数据点采集的数据会被一些随机值替换。可以保证此随机值不等于掉落值。

    + +
      +
    • 举个例子, 如果正确的数据是 [1,2,3,4,5] , 此时 3 被丢弃了, 传感器会返回 [1,2,4,5,7] (最后的位置可以是任何值, 不仅仅是 7).
    • +
    + +

    可以确定的是,最多有一个 传感器有缺陷。请返回这个有缺陷的传感器的编号 (12)。如果任一传感器 没有缺陷 ,或者 无法 确定有缺陷的传感器,则返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:sensor1 = [2,3,4,5], sensor2 = [2,1,3,4]
    +输出:1
    +解释:传感器 2 返回了所有正确的数据.
    +传感器2对第二个数据点采集的数据,被传感器1丢弃了,传感器1返回的最后一个数据被替换为 5 。
    + +

    示例 2:

    + +
    +输入:sensor1 = [2,2,2,2,2], sensor2 = [2,2,2,2,5]
    +输出:-1
    +解释:无法判定拿个传感器是有缺陷的。
    +假设任一传感器丢弃的数据是最后一位,那么,另一个传感器就能给出与之对应的输出。
    +
    + +

    示例 3:

    + +
    +输入:sensor1 = [2,3,2,2,3,2], sensor2 = [2,3,2,3,2,7]
    +输出:2
    +解释:传感器 1 返回了所有正确的数据.
    +传感器 1 对第四个数据点的采集数据,被传感器2丢失了, 传感器 2 返回的最后一个数据被替换为 7 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • sensor1.length == sensor2.length
    • +
    • 1 <= sensor1.length <= 100
    • +
    • 1 <= sensor1[i], sensor2[i] <= 100
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1827.leetcode1827 Minimum Operations to Make the Array Increasing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1827.leetcode1827 Minimum Operations to Make the Array Increasing-zh.md" new file mode 100644 index 00000000..7c4e51b4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1827.leetcode1827 Minimum Operations to Make the Array Increasing-zh.md" @@ -0,0 +1,110 @@ +# [1827. 最少操作使数组递增](https://leetcode-cn.com/problems/minimum-operations-to-make-the-array-increasing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1827.Minimum%20Operations%20to%20Make%20the%20Array%20Increasing/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums (下标从 0 开始)。每一次操作中,你可以选择数组中一个元素,并将它增加 1 。

    + +
      +
    • 比方说,如果 nums = [1,2,3] ,你可以选择增加 nums[1] 得到 nums = [1,3,3] 。
    • +
    + +

    请你返回使 nums 严格递增 的 最少 操作次数。

    + +

    我们称数组 nums 是 严格递增的 ,当它满足对于所有的 0 <= i < nums.length - 1 都有 nums[i] < nums[i+1] 。一个长度为 1 的数组是严格递增的一种特殊情况。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,1,1]
    +输出:3
    +解释:你可以进行如下操作:
    +1) 增加 nums[2] ,数组变为 [1,1,2] 。
    +2) 增加 nums[1] ,数组变为 [1,2,2] 。
    +3) 增加 nums[2] ,数组变为 [1,2,3] 。
    +
    + +

    示例 2:

    + +
    输入:nums = [1,5,2,4,1]
    +输出:14
    +
    + +

    示例 3:

    + +
    输入:nums = [8]
    +输出:0
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5000
    • +
    • 1 <= nums[i] <= 104
    • +
    + +## 解法 + + + +遍历数组,维护一个 preMax 变量。 + + + +### **Python3** + + + +```python +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + pre_max = nums[0] + times = 0 + for i in range(1, n): + if nums[i] <= pre_max: + steps = pre_max - nums[i] + 1 + times += steps + pre_max = nums[i] + steps + else: + pre_max = nums[i] + return times +``` + +### **Java** + + + +```java +class Solution { + public int minOperations(int[] nums) { + int n = nums.length; + int preMax = nums[0]; + int times = 0; + for (int i = 1; i < n; ++i) { + if (nums[i] <= preMax) { + int steps = preMax - nums[i] + 1; + times += steps; + preMax = nums[i] + steps; + } else { + preMax = nums[i]; + } + } + return times; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1828.leetcode1828 Queries on Number of Points Inside a Circle-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1828.leetcode1828 Queries on Number of Points Inside a Circle-zh.md" new file mode 100644 index 00000000..9d60e583 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1828.leetcode1828 Queries on Number of Points Inside a Circle-zh.md" @@ -0,0 +1,169 @@ +# [1828. 统计一个圆中点的数目](https://leetcode-cn.com/problems/queries-on-number-of-points-inside-a-circle) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1828.Queries%20on%20Number%20of%20Points%20Inside%20a%20Circle/README_EN.md) + +## 题目描述 + + + +

    给你一个数组 points ,其中 points[i] = [xi, yi] ,表示第 i 个点在二维平面上的坐标。多个点可能会有 相同 的坐标。

    + +

    同时给你一个数组 queries ,其中 queries[j] = [xj, yj, rj] ,表示一个圆心在 (xj, yj) 且半径为 rj 的圆。

    + +

    对于每一个查询 queries[j] ,计算在第 j 个圆  点的数目。如果一个点在圆的 边界上 ,我们同样认为它在圆  。

    + +

    请你返回一个数组 answer ,其中 answer[j]是第 j 个查询的答案。

    + +

     

    + +

    示例 1:

    + +
    输入:points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]
    +输出:[3,2,2]
    +解释:所有的点和圆如上图所示。
    +queries[0] 是绿色的圆,queries[1] 是红色的圆,queries[2] 是蓝色的圆。
    +
    + +

    示例 2:

    + +
    输入:points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]
    +输出:[2,3,2,4]
    +解释:所有的点和圆如上图所示。
    +queries[0] 是绿色的圆,queries[1] 是红色的圆,queries[2] 是蓝色的圆,queries[3] 是紫色的圆。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= points.length <= 500
    • +
    • points[i].length == 2
    • +
    • 0 <= x​​​​​​i, y​​​​​​i <= 500
    • +
    • 1 <= queries.length <= 500
    • +
    • queries[j].length == 3
    • +
    • 0 <= xj, yj <= 500
    • +
    • 1 <= rj <= 500
    • +
    • 所有的坐标都是整数。
    • +
    + +## 解法 + + + +计算每个点与每个圆的圆心之间的距离,若距离小于此圆的半径,说明该点在圆中。 + + + +### **Python3** + + + +```python +class Solution: + def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]: + ans = [] + for x0, y0, r in queries: + count = 0 + for x, y in points: + dx, dy = x - x0, y - y0 + if dx * dx + dy * dy <= r * r: + count += 1 + ans.append(count) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int[] countPoints(int[][] points, int[][] queries) { + int[] ans = new int[queries.length]; + int i = 0; + for (int[] query : queries) { + int x0 = query[0], y0 = query[1], r = query[2]; + for (int[] point : points) { + int x = point[0], y = point[1]; + int dx = x - x0, dy = y - y0; + if (dx * dx + dy * dy <= r * r) { + ++ans[i]; + } + } + ++i; + } + return ans; + } +} +``` + +### **TypeScript** + +```ts +function countPoints(points: number[][], queries: number[][]): number[] { + let ans = []; + for (let [cx, cy, r] of queries) { + let square = r ** 2; + let count = 0; + for (let [px, py] of points) { + if ((px - cx) ** 2 + (py - cy) ** 2 <= square) { + ++count; + } + } + ans.push(count); + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector countPoints(vector>& points, vector>& queries) { + vector ans; + for (auto& query : queries) { + int x0 = query[0], y0 = query[1], r = query[2]; + int count = 0; + for (auto& point : points) { + int x = point[0], y = point[1]; + int dx = x - x0, dy = y - y0; + if (dx * dx + dy * dy <= r * r) { + ++count; + } + } + ans.push_back(count); + } + return ans; + } +}; +``` + +### **Go** + +```go +func countPoints(points [][]int, queries [][]int) []int { + ans := make([]int, len(queries)) + for i, query := range queries { + x0, y0, r := query[0], query[1], query[2] + for _, point := range points { + x, y := point[0], point[1] + dx, dy := x-x0, y-y0 + if dx*dx+dy*dy <= r*r { + ans[i]++ + } + } + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1829.leetcode1829 Maximum XOR for Each Query-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1829.leetcode1829 Maximum XOR for Each Query-zh.md" new file mode 100644 index 00000000..90271238 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1829.leetcode1829 Maximum XOR for Each Query-zh.md" @@ -0,0 +1,92 @@ +# [1829. 每个查询的最大异或值](https://leetcode-cn.com/problems/maximum-xor-for-each-query) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1829.Maximum%20XOR%20for%20Each%20Query/README_EN.md) + +## 题目描述 + + + +

    给你一个 有序 数组 nums ,它由 n 个非负整数组成,同时给你一个整数 maximumBit 。你需要执行以下查询 n 次:

    + +
      +
    1. 找到一个非负整数 k < 2maximumBit ,使得 nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k 的结果 最大化 。k 是第 i 个查询的答案。
    2. +
    3. 从当前数组 nums 删除 最后 一个元素。
    4. +
    + +

    请你返回一个数组 answer ,其中 answer[i]是第 i 个查询的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [0,1,1,3], maximumBit = 2
    +输出:[0,3,2,3]
    +解释:查询的答案如下:
    +第一个查询:nums = [0,1,1,3],k = 0,因为 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3 。
    +第二个查询:nums = [0,1,1],k = 3,因为 0 XOR 1 XOR 1 XOR 3 = 3 。
    +第三个查询:nums = [0,1],k = 2,因为 0 XOR 1 XOR 2 = 3 。
    +第四个查询:nums = [0],k = 3,因为 0 XOR 3 = 3 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,3,4,7], maximumBit = 3
    +输出:[5,2,6,5]
    +解释:查询的答案如下:
    +第一个查询:nums = [2,3,4,7],k = 5,因为 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7。
    +第二个查询:nums = [2,3,4],k = 2,因为 2 XOR 3 XOR 4 XOR 2 = 7 。
    +第三个查询:nums = [2,3],k = 6,因为 2 XOR 3 XOR 6 = 7 。
    +第四个查询:nums = [2],k = 5,因为 2 XOR 5 = 7 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [0,1,2,2,5,7], maximumBit = 3
    +输出:[4,3,6,4,6,7]
    +
    + +

     

    + +

    提示:

    + +
      +
    • nums.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= maximumBit <= 20
    • +
    • 0 <= nums[i] < 2maximumBit
    • +
    • nums​​​ 中的数字已经按 升序 排好序。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1830.leetcode1830 Minimum Number of Operations to Make String Sorted-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1830.leetcode1830 Minimum Number of Operations to Make String Sorted-zh.md" new file mode 100644 index 00000000..3d9920ad --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1830.leetcode1830 Minimum Number of Operations to Make String Sorted-zh.md" @@ -0,0 +1,92 @@ +# [1830. 使字符串有序的最少操作次数](https://leetcode-cn.com/problems/minimum-number-of-operations-to-make-string-sorted) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1830.Minimum%20Number%20of%20Operations%20to%20Make%20String%20Sorted/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s (下标从 0 开始)。你需要对 s 执行以下操作直到它变为一个有序字符串:

    + +
      +
    1. 找到 最大下标 i ,使得 1 <= i < s.length 且 s[i] < s[i - 1] 。
    2. +
    3. 找到 最大下标 j ,使得 i <= j < s.length 且对于所有在闭区间 [i, j] 之间的 k 都有 s[k] < s[i - 1] 。
    4. +
    5. 交换下标为 i - 1​​​​ 和 j​​​​ 处的两个字符。
    6. +
    7. 将下标 i 开始的字符串后缀反转。
    8. +
    + +

    请你返回将字符串变成有序的最少操作次数。由于答案可能会很大,请返回它对 109 + 7 取余 的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "cba"
    +输出:5
    +解释:模拟过程如下所示:
    +操作 1:i=2,j=2。交换 s[1] 和 s[2] 得到 s="cab" ,然后反转下标从 2 开始的后缀字符串,得到 s="cab" 。
    +操作 2:i=1,j=2。交换 s[0] 和 s[2] 得到 s="bac" ,然后反转下标从 1 开始的后缀字符串,得到 s="bca" 。
    +操作 3:i=2,j=2。交换 s[1] 和 s[2] 得到 s="bac" ,然后反转下标从 2 开始的后缀字符串,得到 s="bac" 。
    +操作 4:i=1,j=1。交换 s[0] 和 s[1] 得到 s="abc" ,然后反转下标从 1 开始的后缀字符串,得到 s="acb" 。
    +操作 5:i=2,j=2。交换 s[1] 和 s[2] 得到 s="abc" ,然后反转下标从 2 开始的后缀字符串,得到 s="abc" 。
    +
    + +

    示例 2:

    + +
    输入:s = "aabaa"
    +输出:2
    +解释:模拟过程如下所示:
    +操作 1:i=3,j=4。交换 s[2] 和 s[4] 得到 s="aaaab" ,然后反转下标从 3 开始的后缀字符串,得到 s="aaaba" 。
    +操作 2:i=4,j=4。交换 s[3] 和 s[4] 得到 s="aaaab" ,然后反转下标从 4 开始的后缀字符串,得到 s="aaaab" 。
    +
    + +

    示例 3:

    + +
    输入:s = "cdbea"
    +输出:63
    + +

    示例 4:

    + +
    输入:s = "leetcodeleetcodeleetcode"
    +输出:982157772
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 3000
    • +
    • s​ 只包含小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1831.leetcode1831 Maximum Transaction Each Day-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1831.leetcode1831 Maximum Transaction Each Day-zh.md" new file mode 100644 index 00000000..30c61cd6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1831.leetcode1831 Maximum Transaction Each Day-zh.md" @@ -0,0 +1,78 @@ +# [1831. 每天的最大交易](https://leetcode-cn.com/problems/maximum-transaction-each-day) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1831.Maximum%20Transaction%20Each%20Day/README_EN.md) + +## 题目描述 + + + +

    表: Transactions

    + +
    ++----------------+----------+
    +| Column Name    | Type     |
    ++----------------+----------+
    +| transaction_id | int      |
    +| day            | datetime |
    +| amount         | int      |
    ++----------------+----------+
    +transaction_id 是此表的主键。
    +每行包括了该次交易的信息。
    +
    + +

     

    + +

    写一条 SQL 返回每天交易金额 amount 最大的交易 ID 。如果某天有多个这样的交易,返回这些交易的 ID 。

    + +

    返回结果根据 transaction_id 升序排列。

    + +

    查询结果样例如下:

    + +

     

    + +
    +Transactions table:
    ++----------------+--------------------+--------+
    +| transaction_id | day                | amount |
    ++----------------+--------------------+--------+
    +| 8              | 2021-4-3 15:57:28  | 57     |
    +| 9              | 2021-4-28 08:47:25 | 21     |
    +| 1              | 2021-4-29 13:28:30 | 58     |
    +| 5              | 2021-4-28 16:39:59 | 40     |
    +| 6              | 2021-4-29 23:39:28 | 58     |
    ++----------------+--------------------+--------+
    +
    +Result table:
    ++----------------+
    +| transaction_id |
    ++----------------+
    +| 1              |
    +| 5              |
    +| 6              |
    +| 8              |
    ++----------------+
    +"2021-4-3"  --> 有一个 id 是 8 的交易,因此,把它加入结果表。 
    +"2021-4-28" --> 有两个交易,id 是 5 和 9 ,交易 5 的金额是 40 ,而交易 9 的数量是 21 。只需要将交易 5 加入结果表,因为它是当天金额最大的交易。
    +"2021-4-29" --> 有两个交易,id 是 1 和 6 ,这两个交易的金额都是 58 ,因此需要把它们都写入结果表。
    +最后,把交易 id 按照升序排列。
    + +

     

    + +

    进阶:你可以不使用 MAX() 函数解决这道题目吗?

    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1832.leetcode1832 Check if the Sentence Is Pangram-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1832.leetcode1832 Check if the Sentence Is Pangram-zh.md" new file mode 100644 index 00000000..49d5eefe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1832.leetcode1832 Check if the Sentence Is Pangram-zh.md" @@ -0,0 +1,117 @@ +# [1832. 判断句子是否为全字母句](https://leetcode-cn.com/problems/check-if-the-sentence-is-pangram) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1832.Check%20if%20the%20Sentence%20Is%20Pangram/README_EN.md) + +## 题目描述 + + + +

    全字母句 指包含英语字母表中每个字母至少一次的句子。

    + +

    给你一个仅由小写英文字母组成的字符串 sentence ,请你判断 sentence 是否为 全字母句

    + +

    如果是,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:sentence = "thequickbrownfoxjumpsoverthelazydog"
    +输出:true
    +解释:sentence 包含英语字母表中每个字母至少一次。
    +
    + +

    示例 2:

    + +
    +输入:sentence = "leetcode"
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= sentence.length <= 1000
    • +
    • sentence 由小写英语字母组成
    • +
    + + +## 解法 + + + +转为 Set,判断 Set 长度是否等于 26。若是,说明是全字母句。也可以使用位运算。 + + + +### **Python3** + + + +集合去重并计数: + +```python +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + return len(set(sentence)) == 26 +``` + +位运算: + +```python +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + res = 0 + for c in sentence: + diff = ord(c) - ord('a') + res |= (1 << diff) + if res == 0x3ffffff: + return True + return False +``` + +### **Java** + + + +集合去重并计数: + +```java +class Solution { + public boolean checkIfPangram(String sentence) { + Set s = new HashSet<>(); + for (int i = 0; i < sentence.length(); ++i) { + s.add(sentence.charAt(i)); + if (s.size() == 26) return true; + } + return false; + } +} +``` + +位运算: + +```java +class Solution { + public boolean checkIfPangram(String sentence) { + int res = 0; + for (int i = 0; i < sentence.length(); ++i) { + int diff = sentence.charAt(i) - 'a'; + res |= (1 << diff); + if (res == 0x3ffffff) return true; + } + return false; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1833.leetcode1833 Maximum Ice Cream Bars-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1833.leetcode1833 Maximum Ice Cream Bars-zh.md" new file mode 100644 index 00000000..3dc908f1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1833.leetcode1833 Maximum Ice Cream Bars-zh.md" @@ -0,0 +1,117 @@ +# [1833. 雪糕的最大数量](https://leetcode-cn.com/problems/maximum-ice-cream-bars) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1833.Maximum%20Ice%20Cream%20Bars/README_EN.md) + +## 题目描述 + + + +

    夏日炎炎,小男孩 Tony 想买一些雪糕消消暑。

    + +

    商店中新到 n 支雪糕,用长度为 n 的数组 costs 表示雪糕的定价,其中 costs[i] 表示第 i 支雪糕的现金价格。Tony 一共有 coins 现金可以用于消费,他想要买尽可能多的雪糕。

    + +

    给你价格数组 costs 和现金量 coins ,请你计算并返回 Tony 用 coins 现金能够买到的雪糕的 最大数量

    + +

    注意:Tony 可以按任意顺序购买雪糕。

    + +

     

    + +

    示例 1:

    + +
    输入:costs = [1,3,2,4,1], coins = 7
    +输出:4
    +解释:Tony 可以买下标为 0、1、2、4 的雪糕,总价为 1 + 3 + 2 + 1 = 7
    +
    + +

    示例 2:

    + +
    输入:costs = [10,6,8,7,7,8], coins = 5
    +输出:0
    +解释:Tony 没有足够的钱买任何一支雪糕。
    +
    + +

    示例 3:

    + +
    输入:costs = [1,6,3,1,2,5], coins = 20
    +输出:6
    +解释:Tony 可以买下所有的雪糕,总价为 1 + 6 + 3 + 1 + 2 + 5 = 18 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • costs.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= costs[i] <= 105
    • +
    • 1 <= coins <= 108
    • +
    + + +## 解法 + + + +注意数据范围,题目很容易误导我们使用01背包(会超时),其实这题就是简单贪心,优先选择定价小的雪糕。 + + + +### **Python3** + + + +```python +class Solution: + def maxIceCream(self, costs: List[int], coins: int) -> int: + costs.sort() + ans, n = 0, len(costs) + for i in range(n): + if coins < costs[i]: + break + else: + ans += 1 + coins -= costs[i] + return ans +``` + +### **Java** + + + +```java +class Solution { + public int maxIceCream(int[] costs, int coins) { + Arrays.sort(costs); + int ans = 0, n = costs.length; + for (int i = 0; i < n && coins >= costs[i]; i++) { + ans++; + coins -= costs[i]; + } + return ans; + } +} +``` + +### **Go** + +```go +func maxIceCream(costs []int, coins int) int { + sort.Ints(costs) + n := len(costs) + ans := 0 + for i := 0; i < n && coins >= costs[i]; i++ { + ans++ + coins -= costs[i] + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1834.leetcode1834 Single-Threaded CPU-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1834.leetcode1834 Single-Threaded CPU-zh.md" new file mode 100644 index 00000000..e4bf456d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1834.leetcode1834 Single-Threaded CPU-zh.md" @@ -0,0 +1,92 @@ +# [1834. 单线程 CPU](https://leetcode-cn.com/problems/single-threaded-cpu) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1834.Single-Threaded%20CPU/README_EN.md) + +## 题目描述 + + + +

    给你一个二维数组 tasks ,用于表示 n​​​​​​ 项从 0n - 1 编号的任务。其中 tasks[i] = [enqueueTimei, processingTimei] 意味着第 i​​​​​​​​​​ 项任务将会于 enqueueTimei 时进入任务队列,需要 processingTimei 的时长完成执行。

    + +

    现有一个单线程 CPU ,同一时间只能执行 最多一项 任务,该 CPU 将会按照下述方式运行:

    + +
      +
    • 如果 CPU 空闲,且任务队列中没有需要执行的任务,则 CPU 保持空闲状态。
    • +
    • 如果 CPU 空闲,但任务队列中有需要执行的任务,则 CPU 将会选择 执行时间最短 的任务开始执行。如果多个任务具有同样的最短执行时间,则选择下标最小的任务开始执行。
    • +
    • 一旦某项任务开始执行,CPU 在 执行完整个任务 前都不会停止。
    • +
    • CPU 可以在完成一项任务后,立即开始执行一项新任务。
    • +
    + +

    返回 CPU 处理任务的顺序。

    + +

     

    + +

    示例 1:

    + +
    输入:tasks = [[1,2],[2,4],[3,2],[4,1]]
    +输出:[0,2,3,1]
    +解释:事件按下述流程运行: 
    +- time = 1 ,任务 0 进入任务队列,可执行任务项 = {0}
    +- 同样在 time = 1 ,空闲状态的 CPU 开始执行任务 0 ,可执行任务项 = {}
    +- time = 2 ,任务 1 进入任务队列,可执行任务项 = {1}
    +- time = 3 ,任务 2 进入任务队列,可执行任务项 = {1, 2}
    +- 同样在 time = 3 ,CPU 完成任务 0 并开始执行队列中用时最短的任务 2 ,可执行任务项 = {1}
    +- time = 4 ,任务 3 进入任务队列,可执行任务项 = {1, 3}
    +- time = 5 ,CPU 完成任务 2 并开始执行队列中用时最短的任务 3 ,可执行任务项 = {1}
    +- time = 6 ,CPU 完成任务 3 并开始执行任务 1 ,可执行任务项 = {}
    +- time = 10 ,CPU 完成任务 1 并进入空闲状态
    +
    + +

    示例 2:

    + +
    输入:tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
    +输出:[4,3,2,0,1]
    +解释:事件按下述流程运行: 
    +- time = 7 ,所有任务同时进入任务队列,可执行任务项  = {0,1,2,3,4}
    +- 同样在 time = 7 ,空闲状态的 CPU 开始执行任务 4 ,可执行任务项 = {0,1,2,3}
    +- time = 9 ,CPU 完成任务 4 并开始执行任务 3 ,可执行任务项 = {0,1,2}
    +- time = 13 ,CPU 完成任务 3 并开始执行任务 2 ,可执行任务项 = {0,1}
    +- time = 18 ,CPU 完成任务 2 并开始执行任务 0 ,可执行任务项 = {1}
    +- time = 28 ,CPU 完成任务 0 并开始执行任务 1 ,可执行任务项 = {}
    +- time = 40 ,CPU 完成任务 1 并进入空闲状态
    + +

     

    + +

    提示:

    + +
      +
    • tasks.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= enqueueTimei, processingTimei <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1835.leetcode1835 Find XOR Sum of All Pairs Bitwise AND-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1835.leetcode1835 Find XOR Sum of All Pairs Bitwise AND-zh.md" new file mode 100644 index 00000000..d4f2f1f5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1835.leetcode1835 Find XOR Sum of All Pairs Bitwise AND-zh.md" @@ -0,0 +1,75 @@ +# [1835. 所有数对按位与结果的异或和](https://leetcode-cn.com/problems/find-xor-sum-of-all-pairs-bitwise-and) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1835.Find%20XOR%20Sum%20of%20All%20Pairs%20Bitwise%20AND/README_EN.md) + +## 题目描述 + + + +

    列表的 异或和XOR sum)指对所有元素进行按位 XOR 运算的结果。如果列表中仅有一个元素,那么其 异或和 就等于该元素。

    + +
      +
    • 例如,[1,2,3,4]异或和 等于 1 XOR 2 XOR 3 XOR 4 = 4 ,而 [3]异或和 等于 3
    • +
    + +

    给你两个下标 从 0 开始 计数的数组 arr1arr2 ,两数组均由非负整数组成。

    + +

    根据每个 (i, j) 数对,构造一个由 arr1[i] AND arr2[j](按位 AND 运算)结果组成的列表。其中 0 <= i < arr1.length0 <= j < arr2.length

    + +

    返回上述列表的 异或和

    + +

     

    + +

    示例 1:

    + +
    输入:arr1 = [1,2,3], arr2 = [6,5]
    +输出:0
    +解释:列表 = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1] ,
    +异或和 = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0 。
    + +

    示例 2:

    + +
    输入:arr1 = [12], arr2 = [4]
    +输出:4
    +解释:列表 = [12 AND 4] = [4] ,异或和 = 4 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr1.length, arr2.length <= 105
    • +
    • 0 <= arr1[i], arr2[j] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1836.leetcode1836 Remove Duplicates From an Unsorted Linked List-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1836.leetcode1836 Remove Duplicates From an Unsorted Linked List-zh.md" new file mode 100644 index 00000000..3ee192f2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1836.leetcode1836 Remove Duplicates From an Unsorted Linked List-zh.md" @@ -0,0 +1,190 @@ +# [1836. Remove Duplicates From an Unsorted Linked List](https://leetcode-cn.com/problems/remove-duplicates-from-an-unsorted-linked-list) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1836.Remove%20Duplicates%20From%20an%20Unsorted%20Linked%20List/README_EN.md) + +## 题目描述 + + + +

    Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.

    + + + +

    Return the linked list after the deletions.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: head = [1,2,3,2]
    +
    +Output: [1,3]
    +
    +Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3].
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: head = [2,1,1,2]
    +
    +Output: []
    +
    +Explanation: 2 and 1 both appear twice. All the elements should be deleted.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: head = [3,2,2,1,3,2,4]
    +
    +Output: [1,4]
    +
    +Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4].
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • The number of nodes in the list is in the range [1, 105]
    • +
    • 1 <= Node.val <= 105
    • +
    + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode: + cur = head + counter = collections.Counter() + while cur: + counter[cur.val] += 1 + cur = cur.next + + dummy = ListNode(0, head) + pre, cur = dummy, head + while cur: + if counter[cur.val] > 1: + pre.next = cur.next + else: + pre = cur + cur = cur.next + return dummy.next +``` + +### **Java** + + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicatesUnsorted(ListNode head) { + Map counter = new HashMap<>(); + for (ListNode cur = head; cur != null; cur = cur.next) { + counter.put(cur.val, counter.getOrDefault(cur.val, 0) + 1); + } + + ListNode dummy = new ListNode(0, head); + for (ListNode pre = dummy, cur = head; cur != null; cur = cur.next) { + if (counter.get(cur.val) > 1) { + pre.next = cur.next; + } else { + pre = cur; + } + } + return dummy.next; + } +} +``` + +### **C++** + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicatesUnsorted(ListNode* head) { + unordered_map counter; + for (ListNode* cur = head; cur != nullptr; cur = cur->next) { + ++counter[cur->val]; + } + + ListNode* dummy = new ListNode(0, head); + for (ListNode* pre = dummy, *cur = head; cur != nullptr; cur = cur->next) { + if (counter[cur->val] > 1) { + pre->next = cur->next; + } else { + pre = cur; + } + } + return dummy->next; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1837.leetcode1837 Sum of Digits in Base K-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1837.leetcode1837 Sum of Digits in Base K-zh.md" new file mode 100644 index 00000000..63528582 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1837.leetcode1837 Sum of Digits in Base K-zh.md" @@ -0,0 +1,85 @@ +# [1837. K 进制表示下的各位数字总和](https://leetcode-cn.com/problems/sum-of-digits-in-base-k) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1837.Sum%20of%20Digits%20in%20Base%20K/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 n10 进制)和一个基数 k ,请你将 n10 进制表示转换为 k 进制表示,计算并返回转换后各位数字的 总和

    + +

    转换后,各位数字应当视作是 10 进制数字,且它们的总和也应当按 10 进制表示返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 34, k = 6
    +输出:9
    +解释:34 (10 进制) 在 6 进制下表示为 54 。5 + 4 = 9 。
    +
    + +

    示例 2:

    + +
    +输入:n = 10, k = 10
    +输出:1
    +解释:n 本身就是 10 进制。 1 + 0 = 1 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 100
    • +
    • 2 <= k <= 10
    • +
    + +## 解法 + + + +将 n 除 k 取余,直至为 0,余数相加求得结果。 + + + +### **Python3** + + + +```python +class Solution: + def sumBase(self, n: int, k: int) -> int: + res = 0 + while n != 0: + n, t = divmod(n, k) + res += t + return res +``` + +### **Java** + + + +```java +class Solution { + public int sumBase(int n, int k) { + int res = 0; + while (n != 0) { + res += (n % k); + n /= k; + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1838.leetcode1838 Frequency of the Most Frequent Element-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1838.leetcode1838 Frequency of the Most Frequent Element-zh.md" new file mode 100644 index 00000000..e2614bf1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1838.leetcode1838 Frequency of the Most Frequent Element-zh.md" @@ -0,0 +1,141 @@ +# [1838. 最高频元素的频数](https://leetcode-cn.com/problems/frequency-of-the-most-frequent-element) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1838.Frequency%20of%20the%20Most%20Frequent%20Element/README_EN.md) + +## 题目描述 + + + +

    元素的 频数 是该元素在一个数组中出现的次数。

    + +

    给你一个整数数组 nums 和一个整数 k 。在一步操作中,你可以选择 nums 的一个下标,并将该下标对应元素的值增加 1

    + +

    执行最多 k 次操作后,返回数组中最高频元素的 最大可能频数

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,4], k = 5
    +输出:3
    +解释:对第一个元素执行 3 次递增操作,对第二个元素执 2 次递增操作,此时 nums = [4,4,4] 。
    +4 是数组中最高频元素,频数是 3 。
    + +

    示例 2:

    + +
    +输入:nums = [1,4,8,13], k = 5
    +输出:2
    +解释:存在多种最优解决方案:
    +- 对第一个元素执行 3 次递增操作,此时 nums = [4,4,8,13] 。4 是数组中最高频元素,频数是 2 。
    +- 对第二个元素执行 4 次递增操作,此时 nums = [1,8,8,13] 。8 是数组中最高频元素,频数是 2 。
    +- 对第三个元素执行 5 次递增操作,此时 nums = [1,4,13,13] 。13 是数组中最高频元素,频数是 2 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [3,9,6], k = 2
    +输出:1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    • 1 <= k <= 105
    • +
    + + +## 解法 + + + +排序后,用滑动窗口维护下标 `l` 到 `r` 的数都增加到 `nums[r]` 的操作次数。 + + + +### **Python3** + + + +```python +class Solution: + def maxFrequency(self, nums: List[int], k: int) -> int: + nums.sort() + ans = 1 + window = 0 + l, r, n = 0, 1, len(nums) + while r < n: + window += (nums[r] - nums[r - 1]) * (r - l) + r += 1 + while window > k: + window -= nums[r - 1] - nums[l] + l += 1 + ans = max(ans, r - l) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int maxFrequency(int[] nums, int k) { + Arrays.sort(nums); + int ans = 1; + int window = 0; + int l = 0, r = 1, n = nums.length; + while (r < n) { + window += (nums[r] - nums[r - 1]) * (r++ - l); + while (window > k) { + window -= nums[r - 1] - nums[l]; + l++; + } + ans = Math.max(ans, r - l); + } + return ans; + } +} +``` + +### **Go** + +```go +func maxFrequency(nums []int, k int) int { + sort.Ints(nums) + ans := 1 + window := 0 + l, r, n := 0, 1, len(nums) + for r < n { + window += (nums[r] - nums[r-1]) * (r - l) + r++ + for window > k { + window -= nums[r-1] - nums[l] + l++ + } + ans = max(ans, r-l) + } + return ans +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1839.leetcode1839 Longest Substring Of All Vowels in Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1839.leetcode1839 Longest Substring Of All Vowels in Order-zh.md" new file mode 100644 index 00000000..cbf3559d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1839.leetcode1839 Longest Substring Of All Vowels in Order-zh.md" @@ -0,0 +1,84 @@ +# [1839. 所有元音按顺序排布的最长子字符串](https://leetcode-cn.com/problems/longest-substring-of-all-vowels-in-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1839.Longest%20Substring%20Of%20All%20Vowels%20in%20Order/README_EN.md) + +## 题目描述 + + + +

    当一个字符串满足如下条件时,我们称它是 美丽的 :

    + +
      +
    • 所有 5 个英文元音字母('a' ,'e' ,'i' ,'o' ,'u')都必须 至少 出现一次。
    • +
    • 这些元音字母的顺序都必须按照 字典序 升序排布(也就是说所有的 'a' 都在 'e' 前面,所有的 'e' 都在 'i' 前面,以此类推)
    • +
    + +

    比方说,字符串 "aeiou" 和 "aaaaaaeiiiioou" 都是 美丽的 ,但是 "uaeio" ,"aeoiu" 和 "aaaeeeooo" 不是美丽的 。

    + +

    给你一个只包含英文元音字母的字符串 word ,请你返回 word最长美丽子字符串的长度 。如果不存在这样的子字符串,请返回 0 。

    + +

    子字符串 是字符串中一个连续的字符序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"
    +输出:13
    +解释:最长子字符串是 "aaaaeiiiiouuu" ,长度为 13 。
    + +

    示例 2:

    + +
    +输入:word = "aeeeiiiioooauuuaeiou"
    +输出:5
    +解释:最长子字符串是 "aeiou" ,长度为 5 。
    +
    + +

    示例 3:

    + +
    +输入:word = "a"
    +输出:0
    +解释:没有美丽子字符串,所以返回 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word.length <= 5 * 105
    • +
    • word 只包含字符 'a''e''i''o' 和 'u' 。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1840.leetcode1840 Maximum Building Height-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1840.leetcode1840 Maximum Building Height-zh.md" new file mode 100644 index 00000000..bfcac22b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1840.leetcode1840 Maximum Building Height-zh.md" @@ -0,0 +1,94 @@ +# [1840. 最高建筑高度](https://leetcode-cn.com/problems/maximum-building-height) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1840.Maximum%20Building%20Height/README_EN.md) + +## 题目描述 + + + +

    在一座城市里,你需要建 n 栋新的建筑。这些新的建筑会从 1 到 n 编号排成一列。

    + +

    这座城市对这些新建筑有一些规定:

    + +
      +
    • 每栋建筑的高度必须是一个非负整数。
    • +
    • 第一栋建筑的高度 必须 是 0 。
    • +
    • 任意两栋相邻建筑的高度差 不能超过  1 。
    • +
    + +

    除此以外,某些建筑还有额外的最高高度限制。这些限制会以二维整数数组 restrictions 的形式给出,其中 restrictions[i] = [idi, maxHeighti] ,表示建筑 idi 的高度 不能超过 maxHeighti 。

    + +

    题目保证每栋建筑在 restrictions 中 至多出现一次 ,同时建筑 1 不会 出现在 restrictions 中。

    + +

    请你返回 最高 建筑能达到的 最高高度 。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 5, restrictions = [[2,1],[4,1]]
    +输出:2
    +解释:上图中的绿色区域为每栋建筑被允许的最高高度。
    +我们可以使建筑高度分别为 [0,1,2,1,2] ,最高建筑的高度为 2 。
    + +

    示例 2:

    + +
    +输入:n = 6, restrictions = []
    +输出:5
    +解释:上图中的绿色区域为每栋建筑被允许的最高高度。
    +我们可以使建筑高度分别为 [0,1,2,3,4,5] ,最高建筑的高度为 5 。
    +
    + +

    示例 3:

    + +
    +输入:n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]
    +输出:5
    +解释:上图中的绿色区域为每栋建筑被允许的最高高度。
    +我们可以使建筑高度分别为 [0,1,2,3,3,4,4,5,4,3] ,最高建筑的高度为 5 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 109
    • +
    • 0 <= restrictions.length <= min(n - 1, 105)
    • +
    • 2 <= idi <= n
    • +
    • idi 是 唯一的 。
    • +
    • 0 <= maxHeighti <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1841.leetcode1841 League Statistics-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1841.leetcode1841 League Statistics-zh.md" new file mode 100644 index 00000000..b116ec4c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1841.leetcode1841 League Statistics-zh.md" @@ -0,0 +1,194 @@ +# [1841. League Statistics](https://leetcode-cn.com/problems/league-statistics) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1841.League%20Statistics/README_EN.md) + +## 题目描述 + + + +

    Table: Teams

    + + + +
    +
    ++----------------+---------+
    +
    +| Column Name    | Type    |
    +
    ++----------------+---------+
    +
    +| team_id        | int     |
    +
    +| team_name      | varchar |
    +
    ++----------------+---------+
    +
    +team_id is the primary key for this table.
    +
    +Each row contains information about one team in the league.
    +
    +
    + + + +

     

    + + + +

    Table: Matches

    + + + +
    +
    ++-----------------+---------+
    +
    +| Column Name     | Type    |
    +
    ++-----------------+---------+
    +
    +| home_team_id    | int     |
    +
    +| away_team_id    | int     |
    +
    +| home_team_goals | int     |
    +
    +| away_team_goals | int     |
    +
    ++-----------------+---------+
    +
    +(home_team_id, away_team_id) is the primary key for this table.
    +
    +Each row contains information about one match.
    +
    +home_team_goals is the number of goals scored by the home team.
    +
    +away_team_goals is the number of goals scored by the away team.
    +
    +The winner of the match is the team with the higher number of goals.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the statistics of the league. The statistics should be built using the played matches where the winning team gets three points and the losing team gets no points. If a match ends with a draw, both teams get one point.

    + + + +

    Each row of the result table should contain:

    + + + +
      +
    • team_name - The name of the team in the Teams table.
    • +
    • matches_played - The number of matches played as either a home or away team.
    • +
    • points - The total points the team has so far.
    • +
    • goal_for - The total number of goals scored by the team across all matches.
    • +
    • goal_against - The total number of goals scored by opponent teams against this team across all matches.
    • +
    • goal_diff - The result of goal_for - goal_against.
    • +
    + + + +

    Return the result table in descending order by points. If two or more teams have the same points, order them in descending order by goal_diff. If there is still a tie, order them by team_name in lexicographical order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Teams table:
    +
    ++---------+-----------+
    +
    +| team_id | team_name |
    +
    ++---------+-----------+
    +
    +| 1       | Ajax      |
    +
    +| 4       | Dortmund  |
    +
    +| 6       | Arsenal   |
    +
    ++---------+-----------+
    +
    +
    +
    +Matches table:
    +
    ++--------------+--------------+-----------------+-----------------+
    +
    +| home_team_id | away_team_id | home_team_goals | away_team_goals |
    +
    ++--------------+--------------+-----------------+-----------------+
    +
    +| 1            | 4            | 0               | 1               |
    +
    +| 1            | 6            | 3               | 3               |
    +
    +| 4            | 1            | 5               | 2               |
    +
    +| 6            | 1            | 0               | 0               |
    +
    ++--------------+--------------+-----------------+-----------------+
    +
    +
    +
    +
    +
    +Result table:
    +
    ++-----------+----------------+--------+----------+--------------+-----------+
    +
    +| team_name | matches_played | points | goal_for | goal_against | goal_diff |
    +
    ++-----------+----------------+--------+----------+--------------+-----------+
    +
    +| Dortmund  | 2              | 6      | 6        | 2            | 4         |
    +
    +| Arsenal   | 2              | 2      | 3        | 3            | 0         |
    +
    +| Ajax      | 4              | 2      | 5        | 9            | -4        |
    +
    ++-----------+----------------+--------+----------+--------------+-----------+
    +
    +
    +
    +Ajax (team_id=1) played 4 matches: 2 losses and 2 draws. Total points = 0 + 0 + 1 + 1 = 2.
    +
    +Dortmund (team_id=4) played 2 matches: 2 wins. Total points = 3 + 3 = 6.
    +
    +Arsenal (team_id=6) played 2 matches: 2 draws. Total points = 1 + 1 = 2.
    +
    +Dortmund is the first team in the table. Ajax and Arsenal have the same points, but since Arsenal has a higher goal_diff than Ajax, Arsenal comes before Ajax in the table.
    +
    +
    + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1842.leetcode1842 Next Palindrome Using Same Digits-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1842.leetcode1842 Next Palindrome Using Same Digits-zh.md" new file mode 100644 index 00000000..20fa3a03 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1842.leetcode1842 Next Palindrome Using Same Digits-zh.md" @@ -0,0 +1,110 @@ +# [1842. Next Palindrome Using Same Digits](https://leetcode-cn.com/problems/next-palindrome-using-same-digits) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1842.Next%20Palindrome%20Using%20Same%20Digits/README_EN.md) + +## 题目描述 + + + +

    You are given a numeric string num, representing a very large palindrome.

    + + + +

    Return the smallest palindrome larger than num that can be created by rearranging its digits. If no such palindrome exists, return an empty string "".

    + + + +

    A palindrome is a number that reads the same backward as forward.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: num = "1221"
    +
    +Output: "2112"
    +
    +Explanation: The next palindrome larger than "1221" is "2112".
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: num = "32123"
    +
    +Output: ""
    +
    +Explanation: No palindromes larger than "32123" can be made by rearranging the digits.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: num = "45544554"
    +
    +Output: "54455445"
    +
    +Explanation: The next palindrome larger than "45544554" is "54455445".
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= num.length <= 105
    • +
    • num is a palindrome.
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1843.leetcode1843 Suspicious Bank Accounts-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1843.leetcode1843 Suspicious Bank Accounts-zh.md" new file mode 100644 index 00000000..adad1d96 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1843.leetcode1843 Suspicious Bank Accounts-zh.md" @@ -0,0 +1,199 @@ +# [1843. Suspicious Bank Accounts](https://leetcode-cn.com/problems/suspicious-bank-accounts) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1843.Suspicious%20Bank%20Accounts/README_EN.md) + +## 题目描述 + + + +

    Table: Accounts

    + + + +
    +
    ++----------------+------+
    +
    +| Column Name    | Type |
    +
    ++----------------+------+
    +
    +| account_id     | int  |
    +
    +| max_income     | int  |
    +
    ++----------------+------+
    +
    +account_id is the primary key for this table.
    +
    +Each row contains information about the maximum monthly income for one bank account.
    +
    +
    + + + +

     

    + + + +

    Table: Transactions

    + + + +
    +
    ++----------------+----------+
    +
    +| Column Name    | Type     |
    +
    ++----------------+----------+
    +
    +| transaction_id | int      |
    +
    +| account_id     | int      |
    +
    +| type           | ENUM     |
    +
    +| amount         | int      |
    +
    +| day            | datetime |
    +
    ++----------------+----------+
    +
    +transaction_id is the primary key for this table.
    +
    +Each row contains information about one transaction.
    +
    +type is ENUM ('Creditor','Debtor') where 'Creditor' means the user deposited money into their account and 'Debtor' means the user withdrew money from their account.
    +
    +amount is the amount of money depositied/withdrawn during the transaction.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to report the IDs of all suspicious bank accounts.

    + + + +

    A bank account is suspicious if the total income exceeds the max_income for this account for two or more consecutive months. The total income of an account in some month is the sum of all its deposits in that month (i.e., transactions of the type 'Creditor').

    + + + +

    Return the result table in ascending order by transaction_id.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Accounts table:
    +
    ++------------+------------+
    +
    +| account_id | max_income |
    +
    ++------------+------------+
    +
    +| 3          | 21000      |
    +
    +| 4          | 10400      |
    +
    ++------------+------------+
    +
    +
    +
    +Transactions table:
    +
    ++----------------+------------+----------+--------+---------------------+
    +
    +| transaction_id | account_id | type     | amount | day                 |
    +
    ++----------------+------------+----------+--------+---------------------+
    +
    +| 2              | 3          | Creditor | 107100 | 2021-06-02 11:38:14 |
    +
    +| 4              | 4          | Creditor | 10400  | 2021-06-20 12:39:18 |
    +
    +| 11             | 4          | Debtor   | 58800  | 2021-07-23 12:41:55 |
    +
    +| 1              | 4          | Creditor | 49300  | 2021-05-03 16:11:04 |
    +
    +| 15             | 3          | Debtor   | 75500  | 2021-05-23 14:40:20 |
    +
    +| 10             | 3          | Creditor | 102100 | 2021-06-15 10:37:16 |
    +
    +| 14             | 4          | Creditor | 56300  | 2021-07-21 12:12:25 |
    +
    +| 19             | 4          | Debtor   | 101100 | 2021-05-09 15:21:49 |
    +
    +| 8              | 3          | Creditor | 64900  | 2021-07-26 15:09:56 |
    +
    +| 7              | 3          | Creditor | 90900  | 2021-06-14 11:23:07 |
    +
    ++----------------+------------+----------+--------+---------------------+
    +
    +
    +
    +Result table:
    +
    ++------------+
    +
    +| account_id |
    +
    ++------------+
    +
    +| 3          |
    +
    ++------------+
    +
    +
    +
    +For account 3:
    +
    +- In 6-2021, the user had an income of 107100 + 102100 + 90900 = 300100.
    +
    +- In 7-2021, the user had an income of 64900.
    +
    +We can see that the income exceeded the max income of 21000 for two consecutive months, so we include 3 in the result table.
    +
    +
    +
    +For account 4:
    +
    +- In 5-2021, the user had an income of 49300.
    +
    +- In 6-2021, the user had an income of 10400.
    +
    +- In 7-2021, the user had an income of 56300.
    +
    +We can see that the income exceeded the max income in May and July, but not in June. Since the account did not exceed the max income for two consecutive months, we do not include it in the result table.
    +
    +
    + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1844.leetcode1844 Replace All Digits with Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1844.leetcode1844 Replace All Digits with Characters-zh.md" new file mode 100644 index 00000000..5f20b50a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1844.leetcode1844 Replace All Digits with Characters-zh.md" @@ -0,0 +1,93 @@ +# [1844. 将所有数字用字符替换](https://leetcode-cn.com/problems/replace-all-digits-with-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1844.Replace%20All%20Digits%20with%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你一个下标从 0 开始的字符串 s ,它的 偶数 下标处为小写英文字母,奇数 下标处为数字。

    + +

    定义一个函数 shift(c, x) ,其中 c 是一个字符且 x 是一个数字,函数返回字母表中 c 后面第 x 个字符。

    + +
      +
    • 比方说,shift('a', 5) = 'f' 和 shift('x', 0) = 'x' 。
    • +
    + +

    对于每个 奇数 下标 i ,你需要将数字 s[i] 用 shift(s[i-1], s[i]) 替换。

    + +

    请你替换所有数字以后,将字符串 s 返回。题目 保证 shift(s[i-1], s[i]) 不会超过 'z' 。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "a1c1e1"
    +输出:"abcdef"
    +解释:数字被替换结果如下:
    +- s[1] -> shift('a',1) = 'b'
    +- s[3] -> shift('c',1) = 'd'
    +- s[5] -> shift('e',1) = 'f'
    + +

    示例 2:

    + +
    输入:s = "a1b2c3d4e"
    +输出:"abbdcfdhe"
    +解释:数字被替换结果如下:
    +- s[1] -> shift('a',1) = 'b'
    +- s[3] -> shift('b',2) = 'd'
    +- s[5] -> shift('c',3) = 'f'
    +- s[7] -> shift('d',4) = 'h'
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s 只包含小写英文字母和数字。
    • +
    • 对所有 奇数 下标处的 i ,满足 shift(s[i-1], s[i]) <= 'z' 。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def replaceDigits(self, s: str) -> str: + s = list(s) + for i in range(1, len(s), 2): + s[i] = chr(ord(s[i - 1]) + int(s[i])) + return ''.join(s) +``` + +### **Java** + + + +```java +class Solution { + public String replaceDigits(String s) { + char[] chars = s.toCharArray(); + for (int i = 1; i < chars.length; i += 2) { + chars[i] = (char) (chars[i - 1] + (chars[i] - '0')); + } + return new String(chars); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1845.leetcode1845 Seat Reservation Manager-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1845.leetcode1845 Seat Reservation Manager-zh.md" new file mode 100644 index 00000000..2c3399c3 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1845.leetcode1845 Seat Reservation Manager-zh.md" @@ -0,0 +1,123 @@ +# [1845. 座位预约管理系统](https://leetcode-cn.com/problems/seat-reservation-manager) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1845.Seat%20Reservation%20Manager/README_EN.md) + +## 题目描述 + + + +

    请你设计一个管理 n 个座位预约的系统,座位编号从 1 到 n 。

    + +

    请你实现 SeatManager 类:

    + +
      +
    • SeatManager(int n) 初始化一个 SeatManager 对象,它管理从 1 到 n 编号的 n 个座位。所有座位初始都是可预约的。
    • +
    • int reserve() 返回可以预约座位的 最小编号 ,此座位变为不可预约。
    • +
    • void unreserve(int seatNumber) 将给定编号 seatNumber 对应的座位变成可以预约。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:
    +["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]
    +[[5], [], [], [2], [], [], [], [], [5]]
    +输出:
    +[null, 1, 2, null, 2, 3, 4, 5, null]
    +
    +解释:
    +SeatManager seatManager = new SeatManager(5); // 初始化 SeatManager ,有 5 个座位。
    +seatManager.reserve();    // 所有座位都可以预约,所以返回最小编号的座位,也就是 1 。
    +seatManager.reserve();    // 可以预约的座位为 [2,3,4,5] ,返回最小编号的座位,也就是 2 。
    +seatManager.unreserve(2); // 将座位 2 变为可以预约,现在可预约的座位为 [2,3,4,5] 。
    +seatManager.reserve();    // 可以预约的座位为 [2,3,4,5] ,返回最小编号的座位,也就是 2 。
    +seatManager.reserve();    // 可以预约的座位为 [3,4,5] ,返回最小编号的座位,也就是 3 。
    +seatManager.reserve();    // 可以预约的座位为 [4,5] ,返回最小编号的座位,也就是 4 。
    +seatManager.reserve();    // 唯一可以预约的是座位 5 ,所以返回 5 。
    +seatManager.unreserve(5); // 将座位 5 变为可以预约,现在可预约的座位为 [5] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 105
    • +
    • 1 <= seatNumber <= n
    • +
    • 每一次对 reserve 的调用,题目保证至少存在一个可以预约的座位。
    • +
    • 每一次对 unreserve 的调用,题目保证 seatNumber 在调用函数前都是被预约状态。
    • +
    • 对 reserve 和 unreserve 的调用 总共 不超过 105 次。
    • +
    + + +## 解法 + + + +“小根堆”实现。 + + + +### **Python3** + + + +```python +class SeatManager: + + def __init__(self, n: int): + self.q = [i for i in range(1, n + 1)] + + def reserve(self) -> int: + return heapq.heappop(self.q) + + def unreserve(self, seatNumber: int) -> None: + heapq.heappush(self.q, seatNumber) + + +# Your SeatManager object will be instantiated and called as such: +# obj = SeatManager(n) +# param_1 = obj.reserve() +# obj.unreserve(seatNumber) +``` + +### **Java** + + + +```java +class SeatManager { + private PriorityQueue q; + + public SeatManager(int n) { + q = new PriorityQueue<>(n); + for (int i = 1; i <= n; ++i) { + q.offer(i); + } + } + + public int reserve() { + return q.poll(); + } + + public void unreserve(int seatNumber) { + q.offer(seatNumber); + } +} + +/** + * Your SeatManager object will be instantiated and called as such: + * SeatManager obj = new SeatManager(n); + * int param_1 = obj.reserve(); + * obj.unreserve(seatNumber); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1846.leetcode1846 Maximum Element After Decreasing and Rearranging-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1846.leetcode1846 Maximum Element After Decreasing and Rearranging-zh.md" new file mode 100644 index 00000000..53c02ca2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1846.leetcode1846 Maximum Element After Decreasing and Rearranging-zh.md" @@ -0,0 +1,97 @@ +# [1846. 减小和重新排列数组后的最大元素](https://leetcode-cn.com/problems/maximum-element-after-decreasing-and-rearranging) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1846.Maximum%20Element%20After%20Decreasing%20and%20Rearranging/README_EN.md) + +## 题目描述 + + + +

    给你一个正整数数组 arr 。请你对 arr 执行一些操作(也可以不进行任何操作),使得数组满足以下条件:

    + +
      +
    • arr 中 第一个 元素必须为 1 。
    • +
    • 任意相邻两个元素的差的绝对值 小于等于 1 ,也就是说,对于任意的 1 <= i < arr.length (数组下标从 0 开始),都满足 abs(arr[i] - arr[i - 1]) <= 1 。abs(x) 为 x 的绝对值。
    • +
    + +

    你可以执行以下 2 种操作任意次:

    + +
      +
    • 减小 arr 中任意元素的值,使其变为一个 更小的正整数 。
    • +
    • 重新排列 arr 中的元素,你可以以任意顺序重新排列。
    • +
    + +

    请你返回执行以上操作后,在满足前文所述的条件下,arr 中可能的 最大值 。

    + +

     

    + +

    示例 1:

    + +
    +输入:arr = [2,2,1,2,1]
    +输出:2
    +解释:
    +我们可以重新排列 arr 得到 [1,2,2,2,1] ,该数组满足所有条件。
    +arr 中最大元素为 2 。
    +
    + +

    示例 2:

    + +
    +输入:arr = [100,1,1000]
    +输出:3
    +解释:
    +一个可行的方案如下:
    +1. 重新排列 arr 得到 [1,100,1000] 。
    +2. 将第二个元素减小为 2 。
    +3. 将第三个元素减小为 3 。
    +现在 arr = [1,2,3] ,满足所有条件。
    +arr 中最大元素为 3 。
    +
    + +

    示例 3:

    + +
    +输入:arr = [1,2,3,4,5]
    +输出:5
    +解释:数组已经满足所有条件,最大元素为 5 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= arr.length <= 105
    • +
    • 1 <= arr[i] <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1847.leetcode1847 Closest Room-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1847.leetcode1847 Closest Room-zh.md" new file mode 100644 index 00000000..7583fa47 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1847.leetcode1847 Closest Room-zh.md" @@ -0,0 +1,86 @@ +# [1847. 最近的房间](https://leetcode-cn.com/problems/closest-room) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1847.Closest%20Room/README_EN.md) + +## 题目描述 + + + +

    一个酒店里有 n 个房间,这些房间用二维整数数组 rooms 表示,其中 rooms[i] = [roomIdi, sizei] 表示有一个房间号为 roomIdi 的房间且它的面积为 sizei 。每一个房间号 roomIdi 保证是 独一无二 的。

    + +

    同时给你 k 个查询,用二维数组 queries 表示,其中 queries[j] = [preferredj, minSizej] 。第 j 个查询的答案是满足如下条件的房间 id :

    + +
      +
    • 房间的面积 至少 为 minSizej ,且
    • +
    • abs(id - preferredj) 的值 最小 ,其中 abs(x) 是 x 的绝对值。
    • +
    + +

    如果差的绝对值有 相等 的,选择 最小 的 id 。如果 没有满足条件的房间 ,答案为 -1 。

    + +

    请你返回长度为 k 的数组 answer ,其中 answer[j] 为第 j 个查询的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]
    +输出:[3,-1,3]
    +解释:查询的答案如下:
    +查询 [3,1] :房间 3 的面积为 2 ,大于等于 1 ,且号码是最接近 3 的,为 abs(3 - 3) = 0 ,所以答案为 3 。
    +查询 [3,3] :没有房间的面积至少为 3 ,所以答案为 -1 。
    +查询 [5,2] :房间 3 的面积为 2 ,大于等于 2 ,且号码是最接近 5 的,为 abs(3 - 5) = 2 ,所以答案为 3 。
    + +

    示例 2:

    + +
    +输入:rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]
    +输出:[2,1,3]
    +解释:查询的答案如下:
    +查询 [2,3] :房间 2 的面积为 3 ,大于等于 3 ,且号码是最接近的,为 abs(2 - 2) = 0 ,所以答案为 2 。
    +查询 [2,4] :房间 1 和 3 的面积都至少为 4 ,答案为 1 因为它房间编号更小。
    +查询 [2,5] :房间 3 是唯一面积大于等于 5 的,所以答案为 3 。
    + +

     

    + +

    提示:

    + +
      +
    • n == rooms.length
    • +
    • 1 <= n <= 105
    • +
    • k == queries.length
    • +
    • 1 <= k <= 104
    • +
    • 1 <= roomIdi, preferredj <= 107
    • +
    • 1 <= sizei, minSizej <= 107
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1848.leetcode1848 Minimum Distance to the Target Element-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1848.leetcode1848 Minimum Distance to the Target Element-zh.md" new file mode 100644 index 00000000..4ceec42b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1848.leetcode1848 Minimum Distance to the Target Element-zh.md" @@ -0,0 +1,110 @@ +# [1848. 到目标元素的最小距离](https://leetcode-cn.com/problems/minimum-distance-to-the-target-element) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1848.Minimum%20Distance%20to%20the%20Target%20Element/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums (下标 从 0 开始 计数)以及两个整数 targetstart ,请你找出一个下标 i ,满足 nums[i] == targetabs(i - start) 最小化 。注意:abs(x) 表示 x 的绝对值。

    + +

    返回 abs(i - start)

    + +

    题目数据保证 target 存在于 nums 中。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,3,4,5], target = 5, start = 3
    +输出:1
    +解释:nums[4] = 5 是唯一一个等于 target 的值,所以答案是 abs(4 - 3) = 1 。
    +
    + +

    示例 2:

    + +
    输入:nums = [1], target = 1, start = 0
    +输出:0
    +解释:nums[0] = 1 是唯一一个等于 target 的值,所以答案是 abs(0 - 0) = 1 。
    +
    + +

    示例 3:

    + +
    输入:nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
    +输出:0
    +解释:nums 中的每个值都是 1 ,但 nums[0] 使 abs(i - start) 的结果得以最小化,所以答案是 abs(0 - 0) = 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 104
    • +
    • 0 <= start < nums.length
    • +
    • target 存在于 nums
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def getMinDistance(self, nums: List[int], target: int, start: int) -> int: + res = float('inf') + for i, num in enumerate(nums): + if num == target: + res = min(res, abs(i - start)) + return res +``` + +### **Java** + + + +```java +class Solution { + public int getMinDistance(int[] nums, int target, int start) { + int res = Integer.MAX_VALUE; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == target) { + res = Math.min(res, Math.abs(i - start)); + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int getMinDistance(vector& nums, int target, int start) { + int res = nums.size(); + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == target) { + res = min(res, abs(i - start)); + } + } + return res; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1849.leetcode1849 Splitting a String Into Descending Consecutive Values-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1849.leetcode1849 Splitting a String Into Descending Consecutive Values-zh.md" new file mode 100644 index 00000000..0e3e745a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1849.leetcode1849 Splitting a String Into Descending Consecutive Values-zh.md" @@ -0,0 +1,95 @@ +# [1849. 将字符串拆分为递减的连续值](https://leetcode-cn.com/problems/splitting-a-string-into-descending-consecutive-values) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1849.Splitting%20a%20String%20Into%20Descending%20Consecutive%20Values/README_EN.md) + +## 题目描述 + + + +

    给你一个仅由数字组成的字符串 s

    + +

    请你判断能否将 s 拆分成两个或者多个 非空子字符串 ,使子字符串的 数值降序 排列,且每两个 相邻子字符串 的数值之 等于 1

    + +
      +
    • 例如,字符串 s = "0090089" 可以拆分成 ["0090", "089"] ,数值为 [90,89] 。这些数值满足按降序排列,且相邻值相差 1 ,这种拆分方法可行。
    • +
    • 另一个例子中,字符串 s = "001" 可以拆分成 ["0", "01"]["00", "1"]["0", "0", "1"] 。然而,所有这些拆分方法都不可行,因为对应数值分别是 [0,1][0,1][0,0,1] ,都不满足按降序排列的要求。
    • +
    + +

    如果可以按要求拆分 s ,返回 true ;否则,返回 false

    + +

    子字符串 是字符串中的一个连续字符序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "1234"
    +输出:false
    +解释:不存在拆分 s 的可行方法。
    +
    + +

    示例 2:

    + +
    +输入:s = "050043"
    +输出:true
    +解释:s 可以拆分为 ["05", "004", "3"] ,对应数值为 [5,4,3] 。
    +满足按降序排列,且相邻值相差 1 。
    +
    + +

    示例 3:

    + +
    +输入:s = "9080701"
    +输出:false
    +解释:不存在拆分 s 的可行方法。
    +
    + +

    示例 4:

    + +
    +输入:s = "10009998"
    +输出:true
    +解释:s 可以拆分为 ["100", "099", "98"] ,对应数值为 [100,99,98] 。
    +满足按降序排列,且相邻值相差 1
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 20
    • +
    • s 仅由数字组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1850.leetcode1850 Minimum Adjacent Swaps to Reach the Kth Smallest Number-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1850.leetcode1850 Minimum Adjacent Swaps to Reach the Kth Smallest Number-zh.md" new file mode 100644 index 00000000..0afff2fd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1850.leetcode1850 Minimum Adjacent Swaps to Reach the Kth Smallest Number-zh.md" @@ -0,0 +1,97 @@ +# [1850. 邻位交换的最小次数](https://leetcode-cn.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1850.Minimum%20Adjacent%20Swaps%20to%20Reach%20the%20Kth%20Smallest%20Number/README_EN.md) + +## 题目描述 + + + +

    给你一个表示大整数的字符串 num ,和一个整数 k

    + +

    如果某个整数是 num 中各位数字的一个 排列 且它的 值大于 num ,则称这个整数为 妙数 。可能存在很多妙数,但是只需要关注 值最小 的那些。

    + +
      +
    • 例如,num = "5489355142" : +
        +
      • 第 1 个最小妙数是 "5489355214"
      • +
      • 第 2 个最小妙数是 "5489355241"
      • +
      • 第 3 个最小妙数是 "5489355412"
      • +
      • 第 4 个最小妙数是 "5489355421"
      • +
      +
    • +
    + +

    返回要得到第 k最小妙数 需要对 num 执行的 相邻位数字交换的最小次数

    + +

    测试用例是按存在第 k 个最小妙数而生成的。

    + +

     

    + +

    示例 1:

    + +
    输入:num = "5489355142", k = 4
    +输出:2
    +解释:第 4 个最小妙数是 "5489355421" ,要想得到这个数字:
    +- 交换下标 7 和下标 8 对应的位:"5489355142" -> "5489355412"
    +- 交换下标 8 和下标 9 对应的位:"5489355412" -> "5489355421"
    +
    + +

    示例 2:

    + +
    输入:num = "11112", k = 4
    +输出:4
    +解释:第 4 个最小妙数是 "21111" ,要想得到这个数字:
    +- 交换下标 3 和下标 4 对应的位:"11112" -> "11121"
    +- 交换下标 2 和下标 3 对应的位:"11121" -> "11211"
    +- 交换下标 1 和下标 2 对应的位:"11211" -> "12111"
    +- 交换下标 0 和下标 1 对应的位:"12111" -> "21111"
    +
    + +

    示例 3:

    + +
    输入:num = "00123", k = 1
    +输出:1
    +解释:第 1 个最小妙数是 "00132" ,要想得到这个数字:
    +- 交换下标 3 和下标 4 对应的位:"00123" -> "00132"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= num.length <= 1000
    • +
    • 1 <= k <= 1000
    • +
    • num 仅由数字组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1851.leetcode1851 Minimum Interval to Include Each Query-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1851.leetcode1851 Minimum Interval to Include Each Query-zh.md" new file mode 100644 index 00000000..9178d2c7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1851.leetcode1851 Minimum Interval to Include Each Query-zh.md" @@ -0,0 +1,82 @@ +# [1851. 包含每个查询的最小区间](https://leetcode-cn.com/problems/minimum-interval-to-include-each-query) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1851.Minimum%20Interval%20to%20Include%20Each%20Query/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 intervals ,其中 intervals[i] = [lefti, righti] 表示第 i 个区间开始于 lefti 、结束于 righti(包含两侧取值,闭区间)。区间的 长度 定义为区间中包含的整数数目,更正式地表达是 righti - lefti + 1

    + +

    再给你一个整数数组 queries 。第 j 个查询的答案是满足 lefti <= queries[j] <= righti长度最小区间 i 的长度 。如果不存在这样的区间,那么答案是 -1

    + +

    以数组形式返回对应查询的所有答案。

    + +

     

    + +

    示例 1:

    + +
    +输入:intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
    +输出:[3,3,1,4]
    +解释:查询处理如下:
    +- Query = 2 :区间 [2,4] 是包含 2 的最小区间,答案为 4 - 2 + 1 = 3 。
    +- Query = 3 :区间 [2,4] 是包含 3 的最小区间,答案为 4 - 2 + 1 = 3 。
    +- Query = 4 :区间 [4,4] 是包含 4 的最小区间,答案为 4 - 4 + 1 = 1 。
    +- Query = 5 :区间 [3,6] 是包含 5 的最小区间,答案为 6 - 3 + 1 = 4 。
    +
    + +

    示例 2:

    + +
    +输入:intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
    +输出:[2,-1,4,6]
    +解释:查询处理如下:
    +- Query = 2 :区间 [2,3] 是包含 2 的最小区间,答案为 3 - 2 + 1 = 2 。
    +- Query = 19:不存在包含 19 的区间,答案为 -1 。
    +- Query = 5 :区间 [2,5] 是包含 5 的最小区间,答案为 5 - 2 + 1 = 4 。
    +- Query = 22:区间 [20,25] 是包含 22 的最小区间,答案为 25 - 20 + 1 = 6 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= intervals.length <= 105
    • +
    • 1 <= queries.length <= 105
    • +
    • queries[i].length == 2
    • +
    • 1 <= lefti <= righti <= 107
    • +
    • 1 <= queries[j] <= 107
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1852.leetcode1852 Distinct Numbers in Each Subarray-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1852.leetcode1852 Distinct Numbers in Each Subarray-zh.md" new file mode 100644 index 00000000..530032dc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1852.leetcode1852 Distinct Numbers in Each Subarray-zh.md" @@ -0,0 +1,108 @@ +# [1852. Distinct Numbers in Each Subarray](https://leetcode-cn.com/problems/distinct-numbers-in-each-subarray) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1852.Distinct%20Numbers%20in%20Each%20Subarray/README_EN.md) + +## 题目描述 + + + +

    Given an integer array nums and an integer k, you are asked to construct the array ans of size n-k+1 where ans[i] is the number of distinct numbers in the subarray nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]].

    + + + +

    Return the array ans.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums = [1,2,3,2,2,1,3], k = 3
    +
    +Output: [3,2,2,2,3]
    +
    +Explanation: The number of distinct elements in each subarray goes as follows:
    +
    +- nums[0:2] = [1,2,3] so ans[0] = 3
    +
    +- nums[1:3] = [2,3,2] so ans[1] = 2
    +
    +- nums[2:4] = [3,2,2] so ans[2] = 2
    +
    +- nums[3:5] = [2,2,1] so ans[3] = 2
    +
    +- nums[4:6] = [2,1,3] so ans[4] = 3
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums = [1,1,1,1,2,3,4], k = 4
    +
    +Output: [1,2,3,4]
    +
    +Explanation: The number of distinct elements in each subarray goes as follows:
    +
    +- nums[0:3] = [1,1,1,1] so ans[0] = 1
    +
    +- nums[1:4] = [1,1,1,2] so ans[1] = 2
    +
    +- nums[2:5] = [1,1,2,3] so ans[2] = 3
    +
    +- nums[3:6] = [1,2,3,4] so ans[3] = 4
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= k <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1853.leetcode1853 Convert Date Format-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1853.leetcode1853 Convert Date Format-zh.md" new file mode 100644 index 00000000..8d36ebcd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1853.leetcode1853 Convert Date Format-zh.md" @@ -0,0 +1,66 @@ +# [1853. Convert Date Format](https://leetcode-cn.com/problems/convert-date-format) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1853.Convert%20Date%20Format/README_EN.md) + +## 题目描述 + + + +

    Table: Days

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| day         | date |
    ++-------------+------+
    +day is the primary key for this table.
    +
    + +

     

    + +

    Write an SQL query to convert each date in Days into a string formatted as "day_name, month_name day, year".

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Days table:
    ++------------+
    +| day        |
    ++------------+
    +| 2022-04-12 |
    +| 2021-08-09 |
    +| 2020-06-26 |
    ++------------+
    +
    +Result table:
    ++-------------------------+
    +| day                     |
    ++-------------------------+
    +| Tuesday, April 12, 2022 |
    +| Monday, August 9, 2021  |
    +| Friday, June 26, 2020   |
    ++-------------------------+
    +Please note that the output is case-sensitive.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1854.leetcode1854 Maximum Population Year-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1854.leetcode1854 Maximum Population Year-zh.md" new file mode 100644 index 00000000..29409c41 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1854.leetcode1854 Maximum Population Year-zh.md" @@ -0,0 +1,149 @@ +# [1854. 人口最多的年份](https://leetcode-cn.com/problems/maximum-population-year) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1854.Maximum%20Population%20Year/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 logs ,其中每个 logs[i] = [birthi, deathi] 表示第 i 个人的出生和死亡年份。

    + +

    年份 x人口 定义为这一年期间活着的人的数目。第 i 个人被计入年份 x 的人口需要满足:x 在闭区间 [birthi, deathi - 1] 内。注意,人不应当计入他们死亡当年的人口中。

    + +

    返回 人口最多最早 的年份。

    + +

     

    + +

    示例 1:

    + +
    输入:logs = [[1993,1999],[2000,2010]]
    +输出:1993
    +解释:人口最多为 1 ,而 1993 是人口为 1 的最早年份。
    +
    + +

    示例 2:

    + +
    输入:logs = [[1950,1961],[1960,1971],[1970,1981]]
    +输出:1960
    +解释: 
    +人口最多为 2 ,分别出现在 1960 和 1970 。
    +其中最早年份是 1960 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= logs.length <= 100
    • +
    • 1950 <= birthi < deathi <= 2050
    • +
    + +## 解法 + + + +差分数组实现。 + +用 delta 数组记录每个人的出生和死亡年份。 + +题目中起始年份为 1950,我们希望数组的起始下标对应起始年份,并且年份与数组下标一一对应,因此我们需要引入起始年份与数组起始下标之差 `offset=1950`,使得下标 i 对应 `i+offset` 年。 + +遍历 logs 时,将每个人出生年份对应的变化量加上 1,同时将死亡年份对应的变化量减去 1。 + +最后,遍历 delta 数组,可以求出每一年的人口数量并维护其最大值和对应的最小下标 res。遍历结束后,将最小下标加上 offset,即是所求的年份。 + + + +### **Python3** + + + +```python +class Solution: + def maximumPopulation(self, logs: List[List[int]]) -> int: + offset = 1950 + delta = [0] * 101 + # 遍历每个人的出生和死亡年份 + for birth, death in logs: + # 出生年份人数+1 + delta[birth - offset] += 1 + # 死亡年份人数-1 + delta[death - offset] -= 1 + + # mx表示人口数量最大值,cur表示当前年份人口数量,res表示人口数量最大的年份-offset + mx = cur = res = 0 + for i in range(101): + cur += delta[i] + if mx < cur: + mx = cur + res = i + return res + offset +``` + +### **Java** + + + +```java +class Solution { + public int maximumPopulation(int[][] logs) { + int offset = 1950; + int[] delta = new int[101]; + // 遍历每个人的出生和死亡年份 + for (int[] log : logs) { + // 出生年份人数+1 + ++delta[log[0] - offset]; + // 死亡年份人数-1 + --delta[log[1] - offset]; + } + + // mx表示人口数量最大值,cur表示当前年份人口数量,res表示人口数量最大的年份-offset + int mx = 0, cur = 0, res = 0; + for (int i = 0; i < 101; ++i) { + cur += delta[i]; + if (mx < cur) { + mx = cur; + res = i; + } + } + return res + offset; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} logs + * @return {number} + */ +var maximumPopulation = function(logs) { + const offset = 1950; + const len = 2050 - 1950 + 1; + let delta = new Array(len).fill(0); + for (let log of logs) { + delta[log[0] - offset] += 1; + delta[log[1] - offset] -= 1; + } + let max = 0; + let total = 0; + let index = 0; + for (let i = 0; i < len; i++) { + total += delta[i]; + if (total > max) { + max = total; + index = i; + } + } + return index + offset; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1855.leetcode1855 Maximum Distance Between a Pair of Values-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1855.leetcode1855 Maximum Distance Between a Pair of Values-zh.md" new file mode 100644 index 00000000..aee17aae --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1855.leetcode1855 Maximum Distance Between a Pair of Values-zh.md" @@ -0,0 +1,203 @@ +# [1855. 下标对中的最大距离](https://leetcode-cn.com/problems/maximum-distance-between-a-pair-of-values) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1855.Maximum%20Distance%20Between%20a%20Pair%20of%20Values/README_EN.md) + +## 题目描述 + + + +

    给你两个 非递增 的整数数组 nums1​​​​​​ 和 nums2​​​​​​ ,数组下标均 从 0 开始 计数。

    + +

    下标对 (i, j)0 <= i < nums1.length0 <= j < nums2.length 。如果该下标对同时满足 i <= jnums1[i] <= nums2[j] ,则称之为 有效 下标对,该下标对的 距离j - i​​ 。​​

    + +

    返回所有 有效 下标对 (i, j) 中的 最大距离 。如果不存在有效下标对,返回 0

    + +

    一个数组 arr ,如果每个 1 <= i < arr.length 均有 arr[i-1] >= arr[i] 成立,那么该数组是一个 非递增 数组。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
    +输出:2
    +解释:有效下标对是 (0,0), (2,2), (2,3), (2,4), (3,3), (3,4) 和 (4,4) 。
    +最大距离是 2 ,对应下标对 (2,4) 。
    +
    + +

    示例 2:

    + +
    +输入:nums1 = [2,2,2], nums2 = [10,10,1]
    +输出:1
    +解释:有效下标对是 (0,0), (0,1) 和 (1,1) 。
    +最大距离是 1 ,对应下标对 (0,1) 。
    + +

    示例 3:

    + +
    +输入:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
    +输出:2
    +解释:有效下标对是 (2,2), (2,3), (2,4), (3,3) 和 (3,4) 。
    +最大距离是 2 ,对应下标对 (2,4) 。
    +
    + +

    示例 4:

    + +
    +输入:nums1 = [5,4], nums2 = [3,2]
    +输出:0
    +解释:不存在有效下标对,所以返回 0 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length <= 105
    • +
    • 1 <= nums2.length <= 105
    • +
    • 1 <= nums1[i], nums2[j] <= 105
    • +
    • nums1nums2 都是 非递增 数组
    • +
    + +## 解法 + + + +二分查找。 + +遍历数组 nums1,对于每个数字 `nums1[i]`,用二分法找到数组 nums2 中下标最大并且比 `nums1[i]` 还大的数字即可。 + + + +### **Python3** + + + +```python +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + res, n = 0, len(nums2) + for i, num in enumerate(nums1): + left, right = i, n - 1 + while left < right: + mid = (left + right + 1) >> 1 + if nums2[mid] >= num: + left = mid + else: + right = mid - 1 + res = max(res, left - i) + return res +``` + +### **Java** + + + +```java +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int res = 0; + int m = nums1.length, n = nums2.length; + for (int i = 0; i < m; ++i) { + int left = i, right = n - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + res = Math.max(res, left - i); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int res = 0; + int m = nums1.size(), n = nums2.size(); + for (int i = 0; i < m; ++i) { + int left = i, right = n - 1; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + res = max(res, left - i); + } + return res; + } +}; +``` + +### **Go** + +```go +func maxDistance(nums1 []int, nums2 []int) int { + res, n := 0, len(nums2) + for i, num := range nums1 { + left, right := i, n-1 + for left < right { + mid := (left + right + 1) >> 1 + if nums2[mid] >= num { + left = mid + } else { + right = mid - 1 + } + } + if res < left-i { + res = left - i + } + } + return res +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDistance = function(nums1, nums2) { + let res = 0; + let m = nums1.length; + let n = nums2.length; + for (let i = 0; i < m; ++i) { + let left = i; + let right = n - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (nums2[mid] >= nums1[i]) { + left = mid; + } else { + right = mid - 1; + } + } + res = Math.max(res, left - i); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1856.leetcode1856 Maximum Subarray Min-Product-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1856.leetcode1856 Maximum Subarray Min-Product-zh.md" new file mode 100644 index 00000000..e6e9f0a7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1856.leetcode1856 Maximum Subarray Min-Product-zh.md" @@ -0,0 +1,157 @@ +# [1856. 子数组最小乘积的最大值](https://leetcode-cn.com/problems/maximum-subarray-min-product) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1856.Maximum%20Subarray%20Min-Product/README_EN.md) + +## 题目描述 + + + +

    一个数组的 最小乘积 定义为这个数组中 最小值 乘以 数组的  。

    + +
      +
    • 比方说,数组 [3,2,5] (最小值是 2)的最小乘积为 2 * (3+2+5) = 2 * 10 = 20 。
    • +
    + +

    给你一个正整数数组 nums ,请你返回 nums 任意 非空子数组 的最小乘积 的 最大值 。由于答案可能很大,请你返回答案对  109 + 7 取余 的结果。

    + +

    请注意,最小乘积的最大值考虑的是取余操作 之前 的结果。题目保证最小乘积的最大值在 不取余 的情况下可以用 64 位有符号整数 保存。

    + +

    子数组 定义为一个数组的 连续 部分。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,3,2]
    +输出:14
    +解释:最小乘积的最大值由子数组 [2,3,2] (最小值是 2)得到。
    +2 * (2+3+2) = 2 * 7 = 14 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [2,3,3,1,2]
    +输出:18
    +解释:最小乘积的最大值由子数组 [3,3] (最小值是 3)得到。
    +3 * (3+3) = 3 * 6 = 18 。
    +
    + +

    示例 3:

    + +
    +输入:nums = [3,1,5,6,4,2]
    +输出:60
    +解释:最小乘积的最大值由子数组 [5,6,4] (最小值是 4)得到。
    +4 * (5+6+4) = 4 * 15 = 60 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 107
    • +
    + +## 解法 + + + +“前缀和 + 单调栈”实现。 + + + +### **Python3** + + + +```python +class Solution: + def maxSumMinProduct(self, nums: List[int]) -> int: + n = len(nums) + # 前缀和 + pre_sum = [0] * (n + 1) + for i in range(1, n + 1): + pre_sum[i] = pre_sum[i - 1] + nums[i - 1] + + # 单调栈求下一个较小值 + stack = [] + next_lesser = [n] * n + for i in range(n): + while stack and nums[stack[-1]] > nums[i]: + next_lesser[stack.pop()] = i + stack.append(i) + + # 单调栈求前一个较小值 + stack = [] + prev_lesser = [-1] * n + for i in range(n - 1, -1, -1): + while stack and nums[stack[-1]] > nums[i]: + prev_lesser[stack.pop()] = i + stack.append(i) + + res = 0 + for i in range(n): + start, end = prev_lesser[i], next_lesser[i] + t = nums[i] * (pre_sum[end] - pre_sum[start + 1]) + res = max(res, t) + return res % (10 ** 9 + 7) +``` + +### **Java** + + + +```java +class Solution { + public int maxSumMinProduct(int[] nums) { + int n = nums.length; + + // 前缀和 + long[] preSum = new long[n + 1]; + for (int i = 1; i < n + 1; ++i) { + preSum[i] = preSum[i - 1] + nums[i - 1]; + } + + // 单调栈求下一个较小值 + Deque stack = new ArrayDeque<>(); + int[] nextLesser = new int[n]; + Arrays.fill(nextLesser, n); + for (int i = 0; i < n; ++i) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + nextLesser[stack.pop()] = i; + } + stack.push(i); + } + + // 单调栈求前一个较小值 + stack = new ArrayDeque<>(); + int[] prevLesser = new int[n]; + Arrays.fill(prevLesser, -1); + for (int i = n - 1; i >= 0; --i) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + prevLesser[stack.pop()] = i; + } + stack.push(i); + } + long res = 0; + for (int i = 0; i < n; ++i) { + int start = prevLesser[i], end = nextLesser[i]; + long t = nums[i] * (preSum[end] - preSum[start + 1]); + res = Math.max(res, t); + } + return (int) (res % 1000000007); + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1857.leetcode1857 Largest Color Value in a Directed Graph-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1857.leetcode1857 Largest Color Value in a Directed Graph-zh.md" new file mode 100644 index 00000000..d2dff30f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1857.leetcode1857 Largest Color Value in a Directed Graph-zh.md" @@ -0,0 +1,79 @@ +# [1857. 有向图中最大颜色值](https://leetcode-cn.com/problems/largest-color-value-in-a-directed-graph) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1857.Largest%20Color%20Value%20in%20a%20Directed%20Graph/README_EN.md) + +## 题目描述 + + + +

    给你一个 有向图 ,它含有 n 个节点和 m 条边。节点编号从 0 到 n - 1 。

    + +

    给你一个字符串 colors ,其中 colors[i] 是小写英文字母,表示图中第 i 个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组 edges ,其中 edges[j] = [aj, bj] 表示从节点 aj 到节点 bj 有一条 有向边 。

    + +

    图中一条有效 路径 是一个点序列 x1 -> x2 -> x3 -> ... -> xk ,对于所有 1 <= i < k ,从 xi 到 xi+1 在图中有一条有向边。路径的 颜色值 是路径中 出现次数最多 颜色的节点数目。

    + +

    请你返回给定图中有效路径里面的 最大颜色值 。如果图中含有环,请返回 -1 。

    + +

     

    + +

    示例 1:

    + +

    + +
    输入:colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
    +输出:3
    +解释:路径 0 -> 2 -> 3 -> 4 含有 3 个颜色为 "a" 的节点(上图中的红色节点)。
    +
    + +

    示例 2:

    + +

    + +
    输入:colors = "a", edges = [[0,0]]
    +输出:-1
    +解释:从 0 到 0 有一个环。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == colors.length
    • +
    • m == edges.length
    • +
    • 1 <= n <= 105
    • +
    • 0 <= m <= 105
    • +
    • colors 只含有小写英文字母。
    • +
    • 0 <= aj, bj < n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1858.leetcode1858 Longest Word With All Prefixes-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1858.leetcode1858 Longest Word With All Prefixes-zh.md" new file mode 100644 index 00000000..af879885 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1858.leetcode1858 Longest Word With All Prefixes-zh.md" @@ -0,0 +1,113 @@ +# [1858. Longest Word With All Prefixes](https://leetcode-cn.com/problems/longest-word-with-all-prefixes) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1858.Longest%20Word%20With%20All%20Prefixes/README_EN.md) + +## 题目描述 + + + +

    Given an array of strings words, find the longest string in words such that every prefix of it is also in words.

    + + + +
      +
    • For example, let words = ["a", "app", "ap"]. The string "app" has prefixes "ap" and "a", all of which are in words.
    • +
    + + + +

    Return the string described above. If there is more than one string with the same length, return the lexicographically smallest one, and if no string exists, return "".

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: words = ["k","ki","kir","kira", "kiran"]
    +
    +Output: "kiran"
    +
    +Explanation: "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
    +
    +Output: "apple"
    +
    +Explanation: Both "apple" and "apply" have all their prefixes in words.
    +
    +However, "apple" is lexicographically smaller, so we return that.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: words = ["abc", "bc", "ab", "qwe"]
    +
    +Output: ""
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • 1 <= words.length <= 105
    • +
    • 1 <= words[i].length <= 105
    • +
    • 1 <= sum(words[i].length) <= 105
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1859.leetcode1859 Sorting the Sentence-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1859.leetcode1859 Sorting the Sentence-zh.md" new file mode 100644 index 00000000..2d5097a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1859.leetcode1859 Sorting the Sentence-zh.md" @@ -0,0 +1,113 @@ +# [1859. 将句子排序](https://leetcode-cn.com/problems/sorting-the-sentence) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1859.Sorting%20the%20Sentence/README_EN.md) + +## 题目描述 + + + +

    一个 句子 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格。每个单词都只包含小写或大写英文字母。

    + +

    我们可以给一个句子添加 从 1 开始的单词位置索引 ,并且将句子中所有单词 打乱顺序 。

    + +
      +
    • 比方说,句子 "This is a sentence" 可以被打乱顺序得到 "sentence4 a3 is2 This1" 或者 "is2 sentence4 This1 a3" 。
    • +
    + +

    给你一个 打乱顺序 的句子 s ,它包含的单词不超过 9 个,请你重新构造并得到原本顺序的句子。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "is2 sentence4 This1 a3"
    +输出:"This is a sentence"
    +解释:将 s 中的单词按照初始位置排序,得到 "This1 is2 a3 sentence4" ,然后删除数字。
    +
    + +

    示例 2:

    + +
    +输入:s = "Myself2 Me1 I4 and3"
    +输出:"Me Myself and I"
    +解释:将 s 中的单词按照初始位置排序,得到 "Me1 Myself2 and3 I4" ,然后删除数字。
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= s.length <= 200
    • +
    • s 只包含小写和大写英文字母、空格以及从 1 到 9 的数字。
    • +
    • s 中单词数目为 1 到 9 个。
    • +
    • s 中的单词由单个空格分隔。
    • +
    • s 不包含任何前导或者后缀空格。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def sortSentence(self, s: str) -> str: + words = s.split(' ') + arr = [None] * len(words) + for word in words: + idx = int(word[-1]) - 1 + arr[idx] = word[:-1] + return ' '.join(arr) +``` + +### **Java** + + + +```java +class Solution { + public String sortSentence(String s) { + String[] words = s.split(" "); + String[] arr = new String[words.length]; + for (String word : words) { + int idx = word.charAt(word.length() - 1) - '0' - 1; + arr[idx] = word.substring(0, word.length() - 1); + } + return String.join(" ", arr); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {string} + */ +var sortSentence = function(s) { + let words = s.split(' '); + let n = words.length; + let res = new Array(n); + for (let word of words) { + let key = word.slice(-1); + let val = word.slice(0, -1); + res[parseInt(key) - 1] = val; + } + return res.join(' '); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1860.leetcode1860 Incremental Memory Leak-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1860.leetcode1860 Incremental Memory Leak-zh.md" new file mode 100644 index 00000000..50ea5ca4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1860.leetcode1860 Incremental Memory Leak-zh.md" @@ -0,0 +1,140 @@ +# [1860. 增长的内存泄露](https://leetcode-cn.com/problems/incremental-memory-leak) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1860.Incremental%20Memory%20Leak/README_EN.md) + +## 题目描述 + + + +

    给你两个整数 memory1 和 memory2 分别表示两个内存条剩余可用内存的位数。现在有一个程序每秒递增的速度消耗着内存。

    + +

    在第 i 秒(秒数从 1 开始),有 i 位内存被分配到 剩余内存较多 的内存条(如果两者一样多,则分配到第一个内存条)。如果两者剩余内存都不足 i 位,那么程序将 意外退出 。

    + +

    请你返回一个数组,包含 [crashTime, memory1crash, memory2crash] ,其中 crashTime是程序意外退出的时间(单位为秒), memory1crash  memory2crash 分别是两个内存条最后剩余内存的位数。

    + +

     

    + +

    示例 1:

    + +
    输入:memory1 = 2, memory2 = 2
    +输出:[3,1,0]
    +解释:内存分配如下:
    +- 第 1 秒,内存条 1 被占用 1 位内存。内存条 1 现在有 1 位剩余可用内存。
    +- 第 2 秒,内存条 2 被占用 2 位内存。内存条 2 现在有 0 位剩余可用内存。
    +- 第 3 秒,程序意外退出,两个内存条分别有 1 位和 0 位剩余可用内存。
    +
    + +

    示例 2:

    + +
    输入:memory1 = 8, memory2 = 11
    +输出:[6,0,4]
    +解释:内存分配如下:
    +- 第 1 秒,内存条 2 被占用 1 位内存,内存条 2 现在有 10 位剩余可用内存。
    +- 第 2 秒,内存条 2 被占用 2 位内存,内存条 2 现在有 8 位剩余可用内存。
    +- 第 3 秒,内存条 1 被占用 3 位内存,内存条 1 现在有 5 位剩余可用内存。
    +- 第 4 秒,内存条 2 被占用 4 位内存,内存条 2 现在有 4 位剩余可用内存。
    +- 第 5 秒,内存条 1 被占用 5 位内存,内存条 1 现在有 0 位剩余可用内存。
    +- 第 6 秒,程序意外退出,两个内存条分别有 0 位和 4 位剩余可用内存。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 0 <= memory1, memory2 <= 231 - 1
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def memLeak(self, memory1: int, memory2: int) -> List[int]: + i = 1 + while memory1 >= i or memory2 >= i: + if memory1 >= memory2: + memory1 -= i + else: + memory2 -= i + i += 1 + return [i, memory1, memory2] +``` + +### **Java** + + + +```java +class Solution { + public int[] memLeak(int memory1, int memory2) { + int i = 1; + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + ++i; + } + return new int[]{i, memory1, memory2}; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number} memory1 + * @param {number} memory2 + * @return {number[]} + */ +var memLeak = function(memory1, memory2) { + let i = 1; + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + i++; + } + return [i, memory1, memory2]; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector memLeak(int memory1, int memory2) { + int i = 1; + while (memory1 >= i || memory2 >= i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + ++i; + } + return {i, memory1, memory2}; + } +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1861.leetcode1861 Rotating the Box-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1861.leetcode1861 Rotating the Box-zh.md" new file mode 100644 index 00000000..4fc656ea --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1861.leetcode1861 Rotating the Box-zh.md" @@ -0,0 +1,153 @@ +# [1861. 旋转盒子](https://leetcode-cn.com/problems/rotating-the-box) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1861.Rotating%20the%20Box/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的字符矩阵 box ,它表示一个箱子的侧视图。箱子的每一个格子可能为:

    + +
      +
    • '#' 表示石头
    • +
    • '*' 表示固定的障碍物
    • +
    • '.' 表示空位置
    • +
    + +

    这个箱子被 顺时针旋转 90 度 ,由于重力原因,部分石头的位置会发生改变。每个石头会垂直掉落,直到它遇到障碍物,另一个石头或者箱子的底部。重力 不会 影响障碍物的位置,同时箱子旋转不会产生惯性 ,也就是说石头的水平位置不会发生改变。

    + +

    题目保证初始时 box 中的石头要么在一个障碍物上,要么在另一个石头上,要么在箱子的底部。

    + +

    请你返回一个 n x m的矩阵,表示按照上述旋转后,箱子内的结果。

    + +

     

    + +

    示例 1:

    +

    + +
    输入:box = [["#",".","#"]]
    +输出:[["."],
    +      ["#"],
    +      ["#"]]
    +
    + +

    示例 2:

    + +

    + +
    输入:box = [["#",".","*","."],
    +            ["#","#","*","."]]
    +输出:[["#","."],
    +      ["#","#"],
    +      ["*","*"],
    +      [".","."]]
    +
    + +

    示例 3:

    + +

    + +
    输入:box = [["#","#","*",".","*","."],
    +            ["#","#","#","*",".","."],
    +            ["#","#","#",".","#","."]]
    +输出:[[".","#","#"],
    +      [".","#","#"],
    +      ["#","#","*"],
    +      ["#","*","."],
    +      ["#",".","*"],
    +      ["#",".","."]]
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == box.length
    • +
    • n == box[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • box[i][j] 只可能是 '#' ,'*' 或者 '.' 。
    • +
    + +## 解法 + + + +先旋转,再挪动箱子。 + + + +### **Python3** + + + +```python +class Solution: + def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: + m, n = len(box), len(box[0]) + res = [[None] * m for _ in range(n)] + for i in range(m): + for j in range(n): + res[j][m - i - 1] = box[i][j] + for j in range(m): + q = collections.deque() + for i in range(n - 1, -1, -1): + if res[i][j] == '*': + q.clear() + continue + if res[i][j] == '.': + q.append(i) + else: + if not q: + continue + res[q.popleft()][j] = '#' + res[i][j] = '.' + q.append(i) + return res +``` + +### **Java** + + + +```java +class Solution { + public char[][] rotateTheBox(char[][] box) { + int m = box.length, n = box[0].length; + char[][] res = new char[n][m]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + res[j][m - i - 1] = box[i][j]; + } + } + for (int j = 0; j < m; ++j) { + Deque q = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + if (res[i][j] == '*') { + q.clear(); + continue; + } + if (res[i][j] == '.') { + q.offer(i); + } else { + if (q.isEmpty()) { + continue; + } + res[q.poll()][j] = '#'; + res[i][j] = '.'; + q.offer(i); + } + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1862.leetcode1862 Sum of Floored Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1862.leetcode1862 Sum of Floored Pairs-zh.md" new file mode 100644 index 00000000..f57737d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1862.leetcode1862 Sum of Floored Pairs-zh.md" @@ -0,0 +1,72 @@ +# [1862. 向下取整数对和](https://leetcode-cn.com/problems/sum-of-floored-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1862.Sum%20of%20Floored%20Pairs/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,请你返回所有下标对 0 <= i, j < nums.length 的 floor(nums[i] / nums[j]) 结果之和。由于答案可能会很大,请你返回答案对109 + 7 取余 的结果。

    + +

    函数 floor() 返回输入数字的整数部分。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [2,5,9]
    +输出:10
    +解释:
    +floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
    +floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
    +floor(5 / 2) = 2
    +floor(9 / 2) = 4
    +floor(9 / 5) = 1
    +我们计算每一个数对商向下取整的结果并求和得到 10 。
    +
    + +

    示例 2:

    + +
    输入:nums = [7,7,7,7,7,7,7]
    +输出:49
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1863.leetcode1863 Sum of All Subset XOR Totals-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1863.leetcode1863 Sum of All Subset XOR Totals-zh.md" new file mode 100644 index 00000000..93a6efa8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1863.leetcode1863 Sum of All Subset XOR Totals-zh.md" @@ -0,0 +1,150 @@ +# [1863. 找出所有子集的异或总和再求和](https://leetcode-cn.com/problems/sum-of-all-subset-xor-totals) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1863.Sum%20of%20All%20Subset%20XOR%20Totals/README_EN.md) + +## 题目描述 + + + +

    一个数组的 异或总和 定义为数组中所有元素按位 XOR 的结果;如果数组为 ,则异或总和为 0

    + +
      +
    • 例如,数组 [2,5,6]异或总和2 XOR 5 XOR 6 = 1
    • +
    + +

    给你一个数组 nums ,请你求出 nums 中每个 子集异或总和 ,计算并返回这些值相加之

    + +

    注意:在本题中,元素 相同 的不同子集应 多次 计数。

    + +

    数组 a 是数组 b 的一个 子集 的前提条件是:从 b 删除几个(也可能不删除)元素能够得到 a

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,3]
    +输出:6
    +解释:[1,3] 共有 4 个子集:
    +- 空子集的异或总和是 0 。
    +- [1] 的异或总和为 1 。
    +- [3] 的异或总和为 3 。
    +- [1,3] 的异或总和为 1 XOR 3 = 2 。
    +0 + 1 + 3 + 2 = 6
    +
    + +

    示例 2:

    + +
    输入:nums = [5,1,6]
    +输出:28
    +解释:[5,1,6] 共有 8 个子集:
    +- 空子集的异或总和是 0 。
    +- [5] 的异或总和为 5 。
    +- [1] 的异或总和为 1 。
    +- [6] 的异或总和为 6 。
    +- [5,1] 的异或总和为 5 XOR 1 = 4 。
    +- [5,6] 的异或总和为 5 XOR 6 = 3 。
    +- [1,6] 的异或总和为 1 XOR 6 = 7 。
    +- [5,1,6] 的异或总和为 5 XOR 1 XOR 6 = 2 。
    +0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
    +
    + +

    示例 3:

    + +
    输入:nums = [3,4,5,6,7,8]
    +输出:480
    +解释:每个子集的全部异或总和值之和为 480 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 12
    • +
    • 1 <= nums[i] <= 20
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(nums, depth, prev): + self.res += prev + for num in nums[depth:]: + prev ^= num + depth += 1 + dfs(nums, depth, prev) + prev ^= num + + self.res = 0 + dfs(nums, 0, 0) + return self.res +``` + +### **Java** + + + +```java +class Solution { + private int res; + + public int subsetXORSum(int[] nums) { + dfs(nums, 0, 0); + return res; + } + + private void dfs(int[] nums, int depth, int prev) { + res += prev; + for (int i = depth; i < nums.length; ++i) { + prev ^= nums[i]; + dfs(nums, ++depth, prev); + prev ^= nums[i]; + } + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ + var subsetXORSum = function(nums) { + let res = []; + let prev = 0; + dfs(nums, 0, prev, res); + return res.reduce((a, c) => a + c, 0) +}; + +function dfs(nums, depth, prev, res) { + res.push(prev); + for (let i = depth; i < nums.length; i++) { + prev ^= nums[i]; + depth++; + dfs(nums, depth, prev, res); + // bracktrack + prev ^= nums[i]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1864.leetcode1864 Minimum Number of Swaps to Make the Binary String Alternating-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1864.leetcode1864 Minimum Number of Swaps to Make the Binary String Alternating-zh.md" new file mode 100644 index 00000000..d9ad8693 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1864.leetcode1864 Minimum Number of Swaps to Make the Binary String Alternating-zh.md" @@ -0,0 +1,161 @@ +# [1864. 构成交替字符串需要的最小交换次数](https://leetcode-cn.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1864.Minimum%20Number%20of%20Swaps%20to%20Make%20the%20Binary%20String%20Alternating/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 s ,现需要将其转化为一个 交替字符串 。请你计算并返回转化所需的 最小 字符交换次数,如果无法完成转化,返回 -1

    + +

    交替字符串 是指:相邻字符之间不存在相等情况的字符串。例如,字符串 "010""1010" 属于交替字符串,但 "0100" 不是。

    + +

    任意两个字符都可以进行交换,不必相邻

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "111000"
    +输出:1
    +解释:交换位置 1 和 4:"111000" -> "101010" ,字符串变为交替字符串。
    +
    + +

    示例 2:

    + +
    +输入:s = "010"
    +输出:0
    +解释:字符串已经是交替字符串了,不需要交换。
    +
    + +

    示例 3:

    + +
    +输入:s = "1110"
    +输出:-1
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s[i] 的值为 '0''1'
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def minSwaps(self, s: str) -> int: + s0n0 = s0n1 = s1n0 = s1n1 = 0 + for i in range(len(s)): + if (i & 1) == 0: + if s[i] != '0': + s0n0 += 1 + else: + s1n1 += 1 + else: + if s[i] != '0': + s1n0 += 1 + else: + s0n1 += 1 + if s0n0 != s0n1 and s1n0 != s1n1: + return -1 + if s0n0 != s0n1: + return s1n0 + if s1n0 != s1n1: + return s0n0 + return min(s0n0, s1n0) +``` + +### **Java** + + + +```java +class Solution { + public int minSwaps(String s) { + int s0n0 = 0, s0n1 = 0; + int s1n0 = 0, s1n1 = 0; + for (int i = 0; i < s.length(); ++i) { + if ((i & 1) == 0) { + if (s.charAt(i) != '0') { + s0n0 += 1; + } else { + s1n1 += 1; + } + } else { + if (s.charAt(i) != '0') { + s1n0 += 1; + } else { + s0n1 += 1; + } + } + } + if (s0n0 != s0n1 && s1n0 != s1n1) { + return -1; + } + if (s0n0 != s0n1) { + return s1n0; + } + if (s1n0 != s1n1) { + return s0n0; + } + return Math.min(s0n0, s1n0); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {number} + */ + var minSwaps = function(s) { + let n = s.length; + let n1 = [...s].reduce((a, c) => parseInt(c) + a, 0); + let n0 = n - n1; + let count = Infinity; + let half = n / 2; + // 101、1010 + if (n1 == Math.ceil(half) && n0 == Math.floor(half)) { + let cur = 0; + for (let i = 0; i < n; i++) { + if (i % 2 == 0 && s.charAt(i) != '1') cur++; + } + count = Math.min(count, cur); + } + // 010、0101 + if (n0 == Math.ceil(half) && n1 == Math.floor(half)) { + let cur = 0; + for (let i = 0; i < n; i++) { + if (i % 2 == 0 && s.charAt(i) != '0') cur++; + } + count = Math.min(count, cur); + } + return count == Infinity ? -1 : count; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1865.leetcode1865 Finding Pairs With a Certain Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1865.leetcode1865 Finding Pairs With a Certain Sum-zh.md" new file mode 100644 index 00000000..5e8df0d5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1865.leetcode1865 Finding Pairs With a Certain Sum-zh.md" @@ -0,0 +1,145 @@ +# [1865. 找出和为指定值的下标对](https://leetcode-cn.com/problems/finding-pairs-with-a-certain-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1865.Finding%20Pairs%20With%20a%20Certain%20Sum/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 nums1nums2 ,请你实现一个支持下述两类查询的数据结构:

    + +
      +
    1. 累加 ,将一个正整数加到 nums2 中指定下标对应元素上。
    2. +
    3. 计数 ,统计满足 nums1[i] + nums2[j] 等于指定值的下标对 (i, j) 数目(0 <= i < nums1.length0 <= j < nums2.length)。
    4. +
    + +

    实现 FindSumPairs 类:

    + +
      +
    • FindSumPairs(int[] nums1, int[] nums2) 使用整数数组 nums1nums2 初始化 FindSumPairs 对象。
    • +
    • void add(int index, int val)val 加到 nums2[index] 上,即,执行 nums2[index] += val
    • +
    • int count(int tot) 返回满足 nums1[i] + nums2[j] == tot 的下标对 (i, j) 数目。
    • +
    + +

     

    + +

    示例:

    + +
    +输入:
    +["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"]
    +[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]
    +输出:
    +[null, 8, null, 2, 1, null, null, 11]
    +
    +解释:
    +FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);
    +findSumPairs.count(7);  // 返回 8 ; 下标对 (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) 满足 2 + 5 = 7 ,下标对 (5,1), (5,5) 满足 3 + 4 = 7
    +findSumPairs.add(3, 2); // 此时 nums2 = [1,4,5,4,5,4]
    +findSumPairs.count(8);  // 返回 2 ;下标对 (5,2), (5,4) 满足 3 + 5 = 8
    +findSumPairs.count(4);  // 返回 1 ;下标对 (5,0) 满足 3 + 1 = 4
    +findSumPairs.add(0, 1); // 此时 nums2 = [2,4,5,4,5,4]
    +findSumPairs.add(1, 1); // 此时 nums2 = [2,5,5,4,5,4]
    +findSumPairs.count(7);  // 返回 11 ;下标对 (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) 满足 2 + 5 = 7 ,下标对 (5,3), (5,5) 满足 3 + 4 = 7
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums1.length <= 1000
    • +
    • 1 <= nums2.length <= 105
    • +
    • 1 <= nums1[i] <= 109
    • +
    • 1 <= nums2[i] <= 105
    • +
    • 0 <= index < nums2.length
    • +
    • 1 <= val <= 105
    • +
    • 1 <= tot <= 109
    • +
    • 最多调用 addcount 函数各 1000
    • +
    + +## 解法 + + + +“哈希表”实现。 + + + +### **Python3** + + + +```python +class FindSumPairs: + + def __init__(self, nums1: List[int], nums2: List[int]): + self.nums1 = nums1 + self.nums2 = nums2 + self.counter = collections.Counter(nums2) + + def add(self, index: int, val: int) -> None: + old_val = self.nums2[index] + self.counter[old_val] -= 1 + self.nums2[index] += val + self.counter[old_val + val] += 1 + + def count(self, tot: int) -> int: + return sum([self.counter[tot - num] for num in self.nums1]) + +# Your FindSumPairs object will be instantiated and called as such: +# obj = FindSumPairs(nums1, nums2) +# obj.add(index,val) +# param_2 = obj.count(tot) +``` + +### **Java** + + + +```java +class FindSumPairs { + private int[] nums1; + private int[] nums2; + private Map counter; + + public FindSumPairs(int[] nums1, int[] nums2) { + this.nums1 = nums1; + this.nums2 = nums2; + counter = new HashMap<>(); + for (int num : nums2) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + } + + public void add(int index, int val) { + int oldVal = nums2[index]; + counter.put(oldVal, counter.get(oldVal) - 1); + nums2[index] += val; + counter.put(oldVal + val, counter.getOrDefault(oldVal + val, 0) + 1); + } + + public int count(int tot) { + int res = 0; + for (int num : nums1) { + res += counter.getOrDefault(tot - num, 0); + } + return res; + } +} + +/** + * Your FindSumPairs object will be instantiated and called as such: + * FindSumPairs obj = new FindSumPairs(nums1, nums2); + * obj.add(index,val); + * int param_2 = obj.count(tot); + */ +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1866.leetcode1866 Number of Ways to Rearrange Sticks With K Sticks Visible-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1866.leetcode1866 Number of Ways to Rearrange Sticks With K Sticks Visible-zh.md" new file mode 100644 index 00000000..f39f4385 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1866.leetcode1866 Number of Ways to Rearrange Sticks With K Sticks Visible-zh.md" @@ -0,0 +1,80 @@ +# [1866. 恰有 K 根木棍可以看到的排列数目](https://leetcode-cn.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1866.Number%20of%20Ways%20to%20Rearrange%20Sticks%20With%20K%20Sticks%20Visible/README_EN.md) + +## 题目描述 + + + +

    n 根长度互不相同的木棍,长度为从 1n 的整数。请你将这些木棍排成一排,并满足从左侧 可以看到 恰好 k 根木棍。从左侧 可以看到 木棍的前提是这个木棍的 左侧 不存在比它 更长的 木棍。

    + +
      +
    • 例如,如果木棍排列为 [1,3,2,5,4] ,那么从左侧可以看到的就是长度分别为 135 的木棍。
    • +
    + +

    给你 nk ,返回符合题目要求的排列 数目 。由于答案可能很大,请返回对 109 + 7 取余 的结果。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 3, k = 2
    +输出:3
    +解释:[1,3,2], [2,3,1] 和 [2,1,3] 是仅有的能满足恰好 2 根木棍可以看到的排列。
    +可以看到的木棍已经用粗体+斜体标识。
    +
    + +

    示例 2:

    + +
    输入:n = 5, k = 5
    +输出:1
    +解释:[1,2,3,4,5] 是唯一一种能满足全部 5 根木棍可以看到的排列。
    +可以看到的木棍已经用粗体+斜体标识。
    +
    + +

    示例 3:

    + +
    输入:n = 20, k = 11
    +输出:647427950
    +解释:总共有 647427950 (mod 109 + 7) 种能满足恰好有 11 根木棍可以看到的排列。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1000
    • +
    • 1 <= k <= n
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1867.leetcode1867 Orders With Maximum Quantity Above Average-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1867.leetcode1867 Orders With Maximum Quantity Above Average-zh.md" new file mode 100644 index 00000000..8a352b7f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1867.leetcode1867 Orders With Maximum Quantity Above Average-zh.md" @@ -0,0 +1,99 @@ +# [1867. Orders With Maximum Quantity Above Average](https://leetcode-cn.com/problems/orders-with-maximum-quantity-above-average) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1867.Orders%20With%20Maximum%20Quantity%20Above%20Average/README_EN.md) + +## 题目描述 + + + +

    Table: OrdersDetails

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| order_id    | int  |
    +| product_id  | int  |
    +| quantity    | int  |
    ++-------------+------+
    +(order_id, product_id) is the primary key for this table.
    +A single order is represented as multiple rows, one row for each product in the order.
    +Each row of this table contains the quantity ordered of the product product_id in the order order_id.
    +
    + +

     

    + +

    You are running an ecommerce site that is looking for imbalanced orders. An imbalanced order is one whose maximum quantity is strictly greater than the average quantity of every order (including itself).

    + +

    The average quantity of an order is calculated as (total quantity of all products in the order) / (number of different products in the order). The maximum quantity of an order is the highest quantity of any single product in the order.

    + +

    Write an SQL query to find the order_id of all imbalanced orders.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +OrdersDetails table:
    ++----------+------------+----------+
    +| order_id | product_id | quantity |
    ++----------+------------+----------+
    +| 1        | 1          | 12       |
    +| 1        | 2          | 10       |
    +| 1        | 3          | 15       |
    +| 2        | 1          | 8        |
    +| 2        | 4          | 4        |
    +| 2        | 5          | 6        |
    +| 3        | 3          | 5        |
    +| 3        | 4          | 18       |
    +| 4        | 5          | 2        |
    +| 4        | 6          | 8        |
    +| 5        | 7          | 9        |
    +| 5        | 8          | 9        |
    +| 3        | 9          | 20       |
    +| 2        | 9          | 4        |
    ++----------+------------+----------+
    +
    +Result table:
    ++----------+
    +| order_id |
    ++----------+
    +| 1        |
    +| 3        |
    ++----------+
    +
    +The average quantity of each order is:
    +- order_id=1: (12+10+15)/3 = 12.3333333
    +- order_id=2: (8+4+6+4)/4 = 5.5
    +- order_id=3: (5+18+20)/3 = 14.333333
    +- order_id=4: (2+8)/2 = 5
    +- order_id=5: (9+9)/2 = 9
    +
    +The maximum quantity of each order is:
    +- order_id=1: max(12, 10, 15) = 15
    +- order_id=2: max(8, 4, 6, 4) = 8
    +- order_id=3: max(5, 18, 20) = 20
    +- order_id=4: max(2, 8) = 8
    +- order_id=5: max(9, 9) = 9
    +
    +Orders 1 and 3 are imbalanced because they have a maximum quantity that exceeds the average quantity of every order.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1868.leetcode1868 Product of Two Run-Length Encoded Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1868.leetcode1868 Product of Two Run-Length Encoded Arrays-zh.md" new file mode 100644 index 00000000..5b92a5a9 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1868.leetcode1868 Product of Two Run-Length Encoded Arrays-zh.md" @@ -0,0 +1,89 @@ +# [1868. Product of Two Run-Length Encoded Arrays](https://leetcode-cn.com/problems/product-of-two-run-length-encoded-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1868.Product%20of%20Two%20Run-Length%20Encoded%20Arrays/README_EN.md) + +## 题目描述 + + + +

    Run-length encoding is a compression algorithm that allows for an integer array nums with many segments of consecutive repeated numbers to be represented by a (generally smaller) 2D array encoded. Each encoded[i] = [vali, freqi] describes the ith segment of repeated numbers in nums where vali is the value that is repeated freqi times.

    + +
      +
    • For example, nums = [1,1,1,2,2,2,2,2] is represented by the run-length encoded array encoded = [[1,3],[2,5]]. Another way to read this is "three 1's followed by five 2's".
    • +
    + +

    The product of two run-length encoded arrays encoded1 and encoded2 can be calculated using the following steps:

    + +
      +
    1. Expand both encoded1 and encoded2 into the full arrays nums1 and nums2 respectively.
    2. +
    3. Create a new array prodNums of length nums1.length and set prodNums[i] = nums1[i] * nums2[i].
    4. +
    5. Compress prodNums into a run-length encoded array and return it.
    6. +
    + +

    You are given two run-length encoded arrays encoded1 and encoded2 representing full arrays nums1 and nums2 respectively. Both nums1 and nums2 have the same length. Each encoded1[i] = [vali, freqi] describes the ith segment of nums1, and each encoded2[j] = [valj, freqj] describes the jth segment of nums2.

    + +

    Return the product of encoded1 and encoded2.

    + +

    Note: Compression should be done such that the run-length encoded array has the minimum possible length.

    + +

     

    +

    Example 1:

    + +
    +Input: encoded1 = [[1,3],[2,3]], encoded2 = [[6,3],[3,3]]
    +Output: [[6,6]]
    +Explanation: encoded1 expands to [1,1,1,2,2,2] and encoded2 expands to [6,6,6,3,3,3].
    +prodNums = [6,6,6,6,6,6], which is compressed into the run-length encoded array [[6,6]].
    +
    + +

    Example 2:

    + +
    +Input: encoded1 = [[1,3],[2,1],[3,2]], encoded2 = [[2,3],[3,3]]
    +Output: [[2,3],[6,1],[9,2]]
    +Explanation: encoded1 expands to [1,1,1,2,3,3] and encoded2 expands to [2,2,2,3,3,3].
    +prodNums = [2,2,2,6,9,9], which is compressed into the run-length encoded array [[2,3],[6,1],[9,2]].
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= encoded1.length, encoded2.length <= 105
    • +
    • encoded1[i].length == 2
    • +
    • encoded2[j].length == 2
    • +
    • 1 <= vali, freqi <= 104 for each encoded1[i].
    • +
    • 1 <= valj, freqj <= 104 for each encoded2[j].
    • +
    • The full arrays that encoded1 and encoded2 represent are the same length.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1869.leetcode1869 Longer Contiguous Segments of Ones than Zeros-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1869.leetcode1869 Longer Contiguous Segments of Ones than Zeros-zh.md" new file mode 100644 index 00000000..f71164e5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1869.leetcode1869 Longer Contiguous Segments of Ones than Zeros-zh.md" @@ -0,0 +1,148 @@ +# [1869. 哪种连续子字符串更长](https://leetcode-cn.com/problems/longer-contiguous-segments-of-ones-than-zeros) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1869.Longer%20Contiguous%20Segments%20of%20Ones%20than%20Zeros/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 s 。如果字符串中由 1 组成的 最长 连续子字符串 严格长于0 组成的 最长 连续子字符串,返回 true ;否则,返回 false

    + +
      +
    • 例如,s = "110100010" 中,由 1 组成的最长连续子字符串的长度是 2 ,由 0 组成的最长连续子字符串的长度是 3
    • +
    + +

    注意,如果字符串中不存在 0 ,此时认为由 0 组成的最长连续子字符串的长度是 0 。字符串中不存在 1 的情况也适用此规则。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "1101"
    +输出:true
    +解释:
    +由 1 组成的最长连续子字符串的长度是 2:"1101"
    +由 0 组成的最长连续子字符串的长度是 1:"1101"
    +由 1 组成的子字符串更长,故返回 true 。
    +
    + +

    示例 2:

    + +
    +输入:s = "111000"
    +输出:false
    +解释:
    +由 1 组成的最长连续子字符串的长度是 3:"111000"
    +由 0 组成的最长连续子字符串的长度是 3:"111000"
    +由 1 组成的子字符串不比由 0 组成的子字符串长,故返回 false 。
    +
    + +

    示例 3:

    + +
    +输入:s = "110100010"
    +输出:false
    +解释:
    +由 1 组成的最长连续子字符串的长度是 2:"110100010"
    +由 0 组成的最长连续子字符串的长度是 3:"110100010"
    +由 1 组成的子字符串不比由 0 组成的子字符串长,故返回 false 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s[i] 不是 '0' 就是 '1'
    • +
    + +## 解法 + + + +直接遍历字符串,获取“0 子串”和“1 子串”的最大长度 `len0`、`len1`。 + +遍历结束后,若 `len1 > len0`,返回 true,否则返回 false。 + + + +### **Python3** + + + +```python +class Solution: + def checkZeroOnes(self, s: str) -> bool: + len0 = len1 = 0 + t0 = t1 = 0 + for c in s: + if c == '0': + t0 += 1 + t1 = 0 + else: + t0 = 0 + t1 += 1 + len0 = max(len0, t0) + len1 = max(len1, t1) + return len1 > len0 +``` + +### **Java** + + + +```java +class Solution { + public boolean checkZeroOnes(String s) { + int len0 = 0, len1 = 0; + int t0 = 0, t1 = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == '0') { + t0 += 1; + t1 = 0; + } else { + t0 = 0; + t1 += 1; + } + len0 = Math.max(len0, t0); + len1 = Math.max(len1, t1); + } + return len1 > len0; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @return {boolean} + */ + var checkZeroOnes = function(s) { + let max0 = 0, max1 = 0; + let t0 = 0, t1 = 0; + for (let char of s) { + if (char == '0') { + t0++; + t1 = 0; + } else { + t1++; + t0 = 0; + } + max0 = Math.max(max0, t0); + max1 = Math.max(max1, t1); + } + return max1 > max0; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1870.leetcode1870 Minimum Speed to Arrive on Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1870.leetcode1870 Minimum Speed to Arrive on Time-zh.md" new file mode 100644 index 00000000..57ed18f8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1870.leetcode1870 Minimum Speed to Arrive on Time-zh.md" @@ -0,0 +1,229 @@ +# [1870. 准时到达的列车最小时速](https://leetcode-cn.com/problems/minimum-speed-to-arrive-on-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1870.Minimum%20Speed%20to%20Arrive%20on%20Time/README_EN.md) + +## 题目描述 + + + +

    给你一个浮点数 hour ,表示你到达办公室可用的总通勤时间。要到达办公室,你必须按给定次序乘坐 n 趟列车。另给你一个长度为 n 的整数数组 dist ,其中 dist[i] 表示第 i 趟列车的行驶距离(单位是千米)。

    + +

    每趟列车均只能在整点发车,所以你可能需要在两趟列车之间等待一段时间。

    + +
      +
    • 例如,第 1 趟列车需要 1.5 小时,那你必须再等待 0.5 小时,搭乘在第 2 小时发车的第 2 趟列车。
    • +
    + +

    返回能满足你准时到达办公室所要求全部列车的 最小正整数 时速(单位:千米每小时),如果无法准时到达,则返回 -1

    + +

    生成的测试用例保证答案不超过 107 ,且 hour小数点后最多存在两位数字

    + +

     

    + +

    示例 1:

    + +
    +输入:dist = [1,3,2], hour = 6
    +输出:1
    +解释:速度为 1 时:
    +- 第 1 趟列车运行需要 1/1 = 1 小时。
    +- 由于是在整数时间到达,可以立即换乘在第 1 小时发车的列车。第 2 趟列车运行需要 3/1 = 3 小时。
    +- 由于是在整数时间到达,可以立即换乘在第 4 小时发车的列车。第 3 趟列车运行需要 2/1 = 2 小时。
    +- 你将会恰好在第 6 小时到达。
    +
    + +

    示例 2:

    + +
    +输入:dist = [1,3,2], hour = 2.7
    +输出:3
    +解释:速度为 3 时:
    +- 第 1 趟列车运行需要 1/3 = 0.33333 小时。
    +- 由于不是在整数时间到达,故需要等待至第 1 小时才能搭乘列车。第 2 趟列车运行需要 3/3 = 1 小时。
    +- 由于是在整数时间到达,可以立即换乘在第 2 小时发车的列车。第 3 趟列车运行需要 2/3 = 0.66667 小时。
    +- 你将会在第 2.66667 小时到达。
    + +

    示例 3:

    + +
    +输入:dist = [1,3,2], hour = 1.9
    +输出:-1
    +解释:不可能准时到达,因为第 3 趟列车最早是在第 2 小时发车。
    + +

     

    + +

    提示:

    + +
      +
    • n == dist.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= dist[i] <= 105
    • +
    • 1 <= hour <= 109
    • +
    • hours 中,小数点后最多存在两位数字
    • +
    + +## 解法 + + + +二分法。 + +以“二分”的方式枚举速度值,找到满足条件的最小速度。 + + + +### **Python3** + + + +```python +class Solution: + def minSpeedOnTime(self, dist: List[int], hour: float) -> int: + def arrive_on_time(speed): + res = 0 + for i, d in enumerate(dist): + res += (d / speed) if i == len(dist) - 1 else math.ceil(d / speed) + return res <= hour + + left, right = 1, 10 ** 7 + while left < right: + mid = (left + right) >> 1 + if arrive_on_time(mid): + right = mid + else: + left = mid + 1 + return left if arrive_on_time(left) else -1 +``` + +### **Java** + + + +```java +class Solution { + public int minSpeedOnTime(int[] dist, double hour) { + int left = 1, right = (int) 1e7; + while (left < right) { + int mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return arriveOnTime(dist, left, hour) ? left : -1; + } + + private boolean arriveOnTime(int[] dist, int speed, double hour) { + double res = 0; + for (int i = 0; i < dist.length; ++i) { + double cost = dist[i] * 1.0 / speed; + res += (i == dist.length - 1 ? cost : Math.ceil(cost)); + } + return res <= hour; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int minSpeedOnTime(vector& dist, double hour) { + int left = 1, right = 1e7; + while (left < right) { + int mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return arriveOnTime(dist, left, hour) ? left : -1; + } + + bool arriveOnTime(vector& dist, int speed, double hour) { + double res = 0; + for (int i = 0; i < dist.size(); ++i) { + double cost = dist[i] * 1.0 / speed; + res += (i == dist.size() - 1 ? cost : ceil(cost)); + } + return res <= hour; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {number[]} dist + * @param {number} hour + * @return {number} + */ + var minSpeedOnTime = function(dist, hour) { + if (dist.length > Math.ceil(hour)) return -1; + let left = 1, right = 10 ** 7; + while (left < right) { + let mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + + function arriveOnTime (dist, speed, hour) { + let res = 0.0; + let n = dist.length; + for (let i = 0; i < n; i++) { + let cost = parseFloat(dist[i]) / speed; + if (i != n - 1) { + cost = Math.ceil(cost); + } + res += cost; + } + return res <= hour; + } +``` + +### **Go** + +```go +func minSpeedOnTime(dist []int, hour float64) int { + n := len(dist) + left, right := 1, int(1e7) + for left < right { + mid := (left + right) >> 1 + if arriveOnTime(dist, n, float64(mid), hour) { + right = mid + } else { + left = mid + 1 + } + } + if arriveOnTime(dist, n, float64(left), hour) { + return left + } + return -1 +} + +func arriveOnTime(dist []int, n int, speed, hour float64) bool { + var cost float64 + for _, v := range dist[:n-1] { + cost += math.Ceil(float64(v) / speed) + } + cost += float64(dist[n-1]) / speed + return cost <= hour +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1871.leetcode1871 Jump Game VII-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1871.leetcode1871 Jump Game VII-zh.md" new file mode 100644 index 00000000..4fe9683e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1871.leetcode1871 Jump Game VII-zh.md" @@ -0,0 +1,140 @@ +# [1871. 跳跃游戏 VII](https://leetcode-cn.com/problems/jump-game-vii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1871.Jump%20Game%20VII/README_EN.md) + +## 题目描述 + + + +

    给你一个下标从 0 开始的二进制字符串 s 和两个整数 minJump 和 maxJump 。一开始,你在下标 0 处,且该位置的值一定为 '0' 。当同时满足如下条件时,你可以从下标 i 移动到下标 j 处:

    + +
      +
    • i + minJump <= j <= min(i + maxJump, s.length - 1) 且
    • +
    • s[j] == '0'.
    • +
    + +

    如果你可以到达 s 的下标 s.length - 1 处,请你返回 true ,否则返回 false 。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "011010", minJump = 2, maxJump = 3
    +输出:true
    +解释:
    +第一步,从下标 0 移动到下标 3 。
    +第二步,从下标 3 移动到下标 5 。
    +
    + +

    示例 2:

    + +
    +输入:s = "01101110", minJump = 2, maxJump = 3
    +输出:false
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= s.length <= 105
    • +
    • s[i] 要么是 '0' ,要么是 '1'
    • +
    • s[0] == '0'
    • +
    • 1 <= minJump <= maxJump < s.length
    • +
    + +## 解法 + + + +“动态规划 + 前缀和”实现。 + + + +### **Python3** + + + +```python +class Solution: + def canReach(self, s: str, minJump: int, maxJump: int) -> bool: + n = len(s) + dp = [False] * n + dp[0] = True + pre_sum = [0] * (n + 1) + pre_sum[1] = 1 + for i in range(1, n): + if s[i] == '0': + l = max(0, i - maxJump) + r = i - minJump + if r >= l and pre_sum[r + 1] - pre_sum[l] > 0: + dp[i] = True + pre_sum[i + 1] = pre_sum[i] + dp[i] + return dp[n - 1] +``` + +### **Java** + + + +```java +class Solution { + public boolean canReach(String s, int minJump, int maxJump) { + int n = s.length(); + boolean[] dp = new boolean[n]; + dp[0] = true; + int[] preSum = new int[n + 1]; + preSum[1] = 1; + for (int i = 1; i < n; ++i) { + if (s.charAt(i) == '0') { + int l = Math.max(0, i - maxJump); + int r = i - minJump; + if (r >= l && preSum[r + 1] - preSum[l] > 0) { + dp[i] = true; + } + } + preSum[i + 1] = preSum[i] + (dp[i] ? 1 : 0); + } + return dp[n - 1]; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} s + * @param {number} minJump + * @param {number} maxJump + * @return {boolean} + */ +var canReach = function(s, minJump, maxJump) { + let n = s.length; + let dp = new Array(n).fill(0); + let sum = new Array(n + 1).fill(0); + dp[0] = 1; + sum[1] = 1; + for (let i = 1; i < n; i++) { + if (s.charAt(i) == '0') { + let left = Math.max(0, i - maxJump); + let right = i - minJump; + if (left <= right && sum[right + 1] - sum[left] > 0) { + dp[i] = 1; + } + } + sum[i + 1] = sum[i] + dp[i]; + } + return dp.pop(); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1872.leetcode1872 Stone Game VIII-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1872.leetcode1872 Stone Game VIII-zh.md" new file mode 100644 index 00000000..1299b1cd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1872.leetcode1872 Stone Game VIII-zh.md" @@ -0,0 +1,126 @@ +# [1872. 石子游戏 VIII](https://leetcode-cn.com/problems/stone-game-viii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1872.Stone%20Game%20VIII/README_EN.md) + +## 题目描述 + + + +

    Alice 和 Bob 玩一个游戏,两人轮流操作, Alice 先手 。

    + +

    总共有 n 个石子排成一行。轮到某个玩家的回合时,如果石子的数目 大于 1 ,他将执行以下操作:

    + +
      +
    1. 选择一个整数 x > 1 ,并且 移除 最左边的 x 个石子。
    2. +
    3.  移除 的石子价值之  累加到该玩家的分数中。
    4. +
    5. 将一个 新的石子 放在最左边,且新石子的值为被移除石子值之和。
    6. +
    + +

    当只剩下 一个 石子时,游戏结束。

    + +

    Alice 和 Bob 的 分数之差 为 (Alice 的分数 - Bob 的分数) 。 Alice 的目标是 最大化 分数差,Bob 的目标是 最小化 分数差。

    + +

    给你一个长度为 n 的整数数组 stones ,其中 stones[i] 是 从左边起 第 i 个石子的价值。请你返回在双方都采用 最优 策略的情况下,Alice 和 Bob 的 分数之差

    + +

     

    + +

    示例 1:

    + +
    输入:stones = [-1,2,-3,4,-5]
    +输出:5
    +解释:
    +- Alice 移除最左边的 4 个石子,得分增加 (-1) + 2 + (-3) + 4 = 2 ,并且将一个价值为 2 的石子放在最左边。stones = [2,-5] 。
    +- Bob 移除最左边的 2 个石子,得分增加 2 + (-5) = -3 ,并且将一个价值为 -3 的石子放在最左边。stones = [-3] 。
    +两者分数之差为 2 - (-3) = 5 。
    +
    + +

    示例 2:

    + +
    输入:stones = [7,-6,5,10,5,-2,-6]
    +输出:13
    +解释:
    +- Alice 移除所有石子,得分增加 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 ,并且将一个价值为 13 的石子放在最左边。stones = [13] 。
    +两者分数之差为 13 - 0 = 13 。
    +
    + +

    示例 3:

    + +
    输入:stones = [-10,-12]
    +输出:-22
    +解释:
    +- Alice 只有一种操作,就是移除所有石子。得分增加 (-10) + (-12) = -22 ,并且将一个价值为 -22 的石子放在最左边。stones = [-22] 。
    +两者分数之差为 (-22) - 0 = -22 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == stones.length
    • +
    • 2 <= n <= 105
    • +
    • -104 <= stones[i] <= 104
    • +
    + +## 解法 + + + +“前缀和 + 动态规划”实现。 + +每次取走最左边的 x 个石子,把它们的和放回最左边,前缀和 `preSum[x]` 不变。 + +假设 `dp[i]` 表示当 Alice 选择 `[i, n)` 范围内的某个下标时,Alice 与 Bob 分数的最大差值。 + +- 若 Alice 选择 i,她获得的分数是 `preSum[i]`,此时 Bob 会在 `[i+1, n]` 范围内选择,并且 Bob 也会采取最优策略,此时最大差值为 `dp[i+1]`。状态转移方程:`dp[i] = preSum[i] - dp[i+1]`。 +- 若 Alice 没选择 i,那么她需要在 `[i+1, n)` 范围内找,状态转移方程为 `dp[i] = dp[i+1]`。 + +最优策略下,`dp[i] = max(dp[i+1], preSum[i] - dp[i+1])`。这里 `O(n)` 的空间复杂度可以优化为一个变量 f。 + +x 必须大于 1,所以题目即是求 `dp[1]`。 + + + +### **Python3** + + + +```python +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + pre_sum = list(accumulate(stones)) + f = pre_sum[len(stones) - 1] + for i in range(len(stones) - 2, 0, -1): + f = max(f, pre_sum[i] - f) + return f +``` + +### **Java** + + + +```java +class Solution { + public int stoneGameVIII(int[] stones) { + int n = stones.length; + int[] preSum = new int[n]; + preSum[0] = stones[0]; + for (int i = 1; i < n; ++i) { + preSum[i] = preSum[i - 1] + stones[i]; + } + int f = preSum[n - 1]; + for (int i = n - 2; i > 0; --i) { + f = Math.max(f, preSum[i] - f); + } + return f; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1873.leetcode1873 Calculate Special Bonus-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1873.leetcode1873 Calculate Special Bonus-zh.md" new file mode 100644 index 00000000..3b0105b1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1873.leetcode1873 Calculate Special Bonus-zh.md" @@ -0,0 +1,125 @@ +# [1873. Calculate Special Bonus](https://leetcode-cn.com/problems/calculate-special-bonus) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1873.Calculate%20Special%20Bonus/README_EN.md) + +## 题目描述 + + + +

    Table: Employees

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| employee_id | int     |
    +
    +| name        | varchar |
    +
    +| salary      | int     |
    +
    ++-------------+---------+
    +
    +employee_id is the primary key for this table.
    +
    +Each row of this table indicates the employee ID, employee name, and salary.
    +
    +
    + + + +

     

    + + + +

    Write an SQL query to calculate the bonus of each employee. The bonus of an employee is 100% of their salary if the ID of the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an employee is 0 otherwise.

    + + + +

    Return the result table ordered by employee_id.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Employees table:
    +
    ++-------------+---------+--------+
    +
    +| employee_id | name    | salary |
    +
    ++-------------+---------+--------+
    +
    +| 2           | Meir    | 3000   |
    +
    +| 3           | Michael | 3800   |
    +
    +| 7           | Addilyn | 7400   |
    +
    +| 8           | Juan    | 6100   |
    +
    +| 9           | Kannon  | 7700   |
    +
    ++-------------+---------+--------+
    +
    +
    +
    +Result table:
    +
    ++-------------+-------+
    +
    +| employee_id | bonus |
    +
    ++-------------+-------+
    +
    +| 2           | 0     |
    +
    +| 3           | 0     |
    +
    +| 7           | 7400  |
    +
    +| 8           | 0     |
    +
    +| 9           | 7700  |
    +
    ++-------------+-------+
    +
    +
    +
    +The employees with IDs 2 and 8 get 0 bonus because they have an even employee_id.
    +
    +The employee with ID 3 gets 0 bonus because their name starts with 'M'.
    +
    +The rest of the employees get a 100% bonus.
    +
    +
    + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1874.leetcode1874 Minimize Product Sum of Two Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1874.leetcode1874 Minimize Product Sum of Two Arrays-zh.md" new file mode 100644 index 00000000..cb47577f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1874.leetcode1874 Minimize Product Sum of Two Arrays-zh.md" @@ -0,0 +1,97 @@ +# [1874. Minimize Product Sum of Two Arrays](https://leetcode-cn.com/problems/minimize-product-sum-of-two-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1874.Minimize%20Product%20Sum%20of%20Two%20Arrays/README_EN.md) + +## 题目描述 + + + +

    The product sum of two equal-length arrays a and b is equal to the sum of a[i] * b[i] for all 0 <= i < a.length (0-indexed).

    + + + +
      +
    • For example, if a = [1,2,3,4] and b = [5,2,3,1], the product sum would be 1*5 + 2*2 + 3*3 + 4*1 = 22.
    • +
    + + + +

    Given two arrays nums1 and nums2 of length n, return the minimum product sum if you are allowed to rearrange the order of the elements in nums1

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: nums1 = [5,3,4,2], nums2 = [4,2,2,5]
    +
    +Output: 40
    +
    +Explanation: We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: nums1 = [2,1,4,5,7], nums2 = [3,2,4,8,6]
    +
    +Output: 65
    +
    +Explanation: We can rearrange nums1 to become [5,7,4,1,2]. The product sum of [5,7,4,1,2] and [3,2,4,8,6] is 5*3 + 7*2 + 4*4 + 1*8 + 2*6 = 65.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == nums1.length == nums2.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= nums1[i], nums2[i] <= 100
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1875.leetcode1875 Group Employees of the Same Salary-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1875.leetcode1875 Group Employees of the Same Salary-zh.md" new file mode 100644 index 00000000..0b319817 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1875.leetcode1875 Group Employees of the Same Salary-zh.md" @@ -0,0 +1,143 @@ +# [1875. Group Employees of the Same Salary](https://leetcode-cn.com/problems/group-employees-of-the-same-salary) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1875.Group%20Employees%20of%20the%20Same%20Salary/README_EN.md) + +## 题目描述 + + + +

    Table: Employees

    + + + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| employee_id | int     |
    +
    +| name        | varchar |
    +
    +| salary      | int     |
    +
    ++-------------+---------+
    +
    +employee_id is the primary key for this table.
    +
    +Each row of this table indicates the employee ID, employee name, and salary.
    +
    +
    + + + +

     

    + + + +

    A company wants to divide the employees into teams such that all the members on each team have the same salary. The teams should follow these criteria:

    + + + +
      +
    • Each team should consist of at least two employees.
    • +
    • All the employees on a team should have the same salary.
    • +
    • All the employees of the same salary should be assigned to the same team.
    • +
    • If the salary of an employee is unique, we do not assign this employee to any team.
    • +
    • A team's ID is assigned based on the rank of the team's salary relative to the other teams' salaries, where the team with the lowest salary has team_id = 1. Note that the salaries for employees not on a team are not included in this ranking.
    • +
    + + + +

    Write an SQL query to get the team_id of each employee that is in a team.

    + + + +

    Return the result table ordered by team_id in ascending order. In case of a tie, order it by employee_id in ascending order.

    + + + +

    The query result format is in the following example:

    + + + +

     

    + + + +
    +
    +Employees table:
    +
    ++-------------+---------+--------+
    +
    +| employee_id | name    | salary |
    +
    ++-------------+---------+--------+
    +
    +| 2           | Meir    | 3000   |
    +
    +| 3           | Michael | 3000   |
    +
    +| 7           | Addilyn | 7400   |
    +
    +| 8           | Juan    | 6100   |
    +
    +| 9           | Kannon  | 7400   |
    +
    ++-------------+---------+--------+
    +
    +
    +
    +Result table:
    +
    ++-------------+---------+--------+---------+
    +
    +| employee_id | name    | salary | team_id |
    +
    ++-------------+---------+--------+---------+
    +
    +| 2           | Meir    | 3000   | 1       |
    +
    +| 3           | Michael | 3000   | 1       |
    +
    +| 7           | Addilyn | 7400   | 2       |
    +
    +| 9           | Kannon  | 7400   | 2       |
    +
    ++-------------+---------+--------+---------+
    +
    +
    +
    +Meir (employee_id=2) and Michael (employee_id=3) are in the same team because they have the same salary of 3000.
    +
    +Addilyn (employee_id=7) and Kannon (employee_id=9) are in the same team because they have the same salary of 7400.
    +
    +Juan (employee_id=8) is not included in any team because their salary of 6100 is unique (i.e. no other employee has the same salary).
    +
    +The team IDs are assigned as follows (based on salary ranking, lowest first):
    +
    +- team_id=1: Meir and Michael, salary of 3000
    +
    +- team_id=2: Addilyn and Kannon, salary of 7400
    +
    +Juan's salary of 6100 is not included in the ranking because they are not on a team.
    + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1876.leetcode1876 Substrings of Size Three with Distinct Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1876.leetcode1876 Substrings of Size Three with Distinct Characters-zh.md" new file mode 100644 index 00000000..ab25fe53 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1876.leetcode1876 Substrings of Size Three with Distinct Characters-zh.md" @@ -0,0 +1,107 @@ +# [1876. 长度为三且各字符不同的子字符串](https://leetcode-cn.com/problems/substrings-of-size-three-with-distinct-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1876.Substrings%20of%20Size%20Three%20with%20Distinct%20Characters/README_EN.md) + +## 题目描述 + + + +

    如果一个字符串不含有任何重复字符,我们称这个字符串为  字符串。

    + +

    给你一个字符串 s ,请你返回 s 中长度为 3 的 好子字符串 的数量。

    + +

    注意,如果相同的好子字符串出现多次,每一次都应该被记入答案之中。

    + +

    子字符串 是一个字符串中连续的字符序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "xyzzaz"
    +输出:1
    +解释:总共有 4 个长度为 3 的子字符串:"xyz","yzz","zza" 和 "zaz" 。
    +唯一的长度为 3 的好子字符串是 "xyz" 。
    +
    + +

    示例 2:

    + +
    +输入:s = "aababcabc"
    +输出:4
    +解释:总共有 7 个长度为 3 的子字符串:"aab","aba","bab","abc","bca","cab" 和 "abc" 。
    +好子字符串包括 "abc","bca","cab" 和 "abc" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 100
    • +
    • s​​​​​​ 只包含小写英文字母。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def countGoodSubstrings(self, s: str) -> int: + count, n = 0, len(s) + for i in range(n - 2): + count += (s[i] != s[i + 1] and s[i] != s[i + 2] and s[i + 1] != s[i + 2]) + return count +``` + +### **Java** + + + +```java +class Solution { + public int countGoodSubstrings(String s) { + int count = 0, n = s.length(); + for (int i = 0; i < n - 2; ++i) { + char a = s.charAt(i), b = s.charAt(i + 1), c = s.charAt(i + 2); + if (a != b && a != c && b != c) { + ++count; + } + } + return count; + } +} +``` + +### **TypeScript** + +```ts +function countGoodSubstrings(s: string): number { + const n: number = s.length; + let count: number = 0; + for (let i: number = 0; i < n - 2; ++i) { + let a: string = s.charAt(i), b: string = s.charAt(i + 1), c: string = s.charAt(i + 2); + if (a != b && a != c && b != c) { + ++count; + } + } + return count; +}; + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1877.leetcode1877 Minimize Maximum Pair Sum in Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1877.leetcode1877 Minimize Maximum Pair Sum in Array-zh.md" new file mode 100644 index 00000000..04bd3cc8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1877.leetcode1877 Minimize Maximum Pair Sum in Array-zh.md" @@ -0,0 +1,81 @@ +# [1877. 数组中最大数对和的最小值](https://leetcode-cn.com/problems/minimize-maximum-pair-sum-in-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1877.Minimize%20Maximum%20Pair%20Sum%20in%20Array/README_EN.md) + +## 题目描述 + + + +

    一个数对 (a,b) 的 数对和 等于 a + b 。最大数对和 是一个数对数组中最大的 数对和 。

    + +
      +
    • 比方说,如果我们有数对 (1,5) ,(2,3) 和 (4,4)最大数对和 为 max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 。
    • +
    + +

    给你一个长度为 偶数 n 的数组 nums ,请你将 nums 中的元素分成 n / 2 个数对,使得:

    + +
      +
    • nums 中每个元素 恰好 在 一个 数对中,且
    • +
    • 最大数对和 的值 最小 。
    • +
    + +

    请你在最优数对划分的方案下,返回最小的 最大数对和 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [3,5,2,3]
    +输出:7
    +解释:数组中的元素可以分为数对 (3,3) 和 (5,2) 。
    +最大数对和为 max(3+3, 5+2) = max(6, 7) = 7 。
    +
    + +

    示例 2:

    + +
    输入:nums = [3,5,4,2,4,6]
    +输出:8
    +解释:数组中的元素可以分为数对 (3,5),(4,4) 和 (6,2) 。
    +最大数对和为 max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 2 <= n <= 105
    • +
    • n 是 偶数 。
    • +
    • 1 <= nums[i] <= 105
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1878.leetcode1878 Get Biggest Three Rhombus Sums in a Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1878.leetcode1878 Get Biggest Three Rhombus Sums in a Grid-zh.md" new file mode 100644 index 00000000..b957af65 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1878.leetcode1878 Get Biggest Three Rhombus Sums in a Grid-zh.md" @@ -0,0 +1,91 @@ +# [1878. 矩阵中最大的三个菱形和](https://leetcode-cn.com/problems/get-biggest-three-rhombus-sums-in-a-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1878.Get%20Biggest%20Three%20Rhombus%20Sums%20in%20a%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的整数矩阵 grid 。

    + +

    菱形和 指的是 grid 中一个正菱形 边界 上的元素之和。本题中的菱形必须为正方形旋转45度,且四个角都在一个格子当中。下图是四个可行的菱形,每个菱形和应该包含的格子都用了相应颜色标注在图中。

    + +

     

    + +

    注意,菱形可以是一个面积为 0 的区域,如上图中右下角的紫色菱形所示。

    + +

    请你按照 降序 返回 grid 中三个最大的 互不相同的菱形和 。如果不同的和少于三个,则将它们全部返回。

    + +

     

    + +

    示例 1:

    + +
    +输入:grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
    +输出:[228,216,211]
    +解释:最大的三个菱形和如上图所示。
    +- 蓝色:20 + 3 + 200 + 5 = 228
    +- 红色:200 + 2 + 10 + 4 = 216
    +- 绿色:5 + 200 + 4 + 2 = 211
    +
    + +

    示例 2:

    + +
    +输入:grid = [[1,2,3],[4,5,6],[7,8,9]]
    +输出:[20,9,8]
    +解释:最大的三个菱形和如上图所示。
    +- 蓝色:4 + 2 + 6 + 8 = 20
    +- 红色:9 (右下角红色的面积为 0 的菱形)
    +- 绿色:8 (下方中央面积为 0 的菱形)
    +
    + +

    示例 3:

    + +
    +输入:grid = [[7,7,7]]
    +输出:[7]
    +解释:所有三个可能的菱形和都相同,所以返回 [7] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 100
    • +
    • 1 <= grid[i][j] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1879.leetcode1879 Minimum XOR Sum of Two Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1879.leetcode1879 Minimum XOR Sum of Two Arrays-zh.md" new file mode 100644 index 00000000..d4ae49a1 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1879.leetcode1879 Minimum XOR Sum of Two Arrays-zh.md" @@ -0,0 +1,78 @@ +# [1879. 两个数组最小的异或值之和](https://leetcode-cn.com/problems/minimum-xor-sum-of-two-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1879.Minimum%20XOR%20Sum%20of%20Two%20Arrays/README_EN.md) + +## 题目描述 + + + +

    给你两个整数数组 nums1 和 nums2 ,它们长度都为 n 。

    + +

    两个数组的 异或值之和 为 (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (下标从 0 开始)。

    + +
      +
    • 比方说,[1,2,3] 和 [3,2,1] 的 异或值之和 等于 (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4 。
    • +
    + +

    请你将 nums2 中的元素重新排列,使得 异或值之和 最小 。

    + +

    请你返回重新排列之后的 异或值之和 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums1 = [1,2], nums2 = [2,3]
    +输出:2
    +解释:nums2 重新排列得到 [3,2] 。
    +异或值之和为 (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2 。
    + +

    示例 2:

    + +
    输入:nums1 = [1,0,3], nums2 = [5,3,4]
    +输出:8
    +解释:nums2 重新排列得到 [5,4,3] 。
    +异或值之和为 (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums1.length
    • +
    • n == nums2.length
    • +
    • 1 <= n <= 14
    • +
    • 0 <= nums1[i], nums2[i] <= 107
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1880.leetcode1880 Check if Word Equals Summation of Two Words-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1880.leetcode1880 Check if Word Equals Summation of Two Words-zh.md" new file mode 100644 index 00000000..ee337b72 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1880.leetcode1880 Check if Word Equals Summation of Two Words-zh.md" @@ -0,0 +1,162 @@ +# [1880. 检查某单词是否等于两单词之和](https://leetcode-cn.com/problems/check-if-word-equals-summation-of-two-words) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1880.Check%20if%20Word%20Equals%20Summation%20of%20Two%20Words/README_EN.md) + +## 题目描述 + + + +

    字母的 字母值 取决于字母在字母表中的位置,从 0 开始 计数。即,'a' -> 0'b' -> 1'c' -> 2,以此类推。

    + +

    对某个由小写字母组成的字符串 s 而言,其 数值 就等于将 s 中每个字母的 字母值 按顺序 连接转换 成对应整数。

    + +
      +
    • 例如,s = "acb" ,依次连接每个字母的字母值可以得到 "021" ,转换为整数得到 21
    • +
    + +

    给你三个字符串 firstWordsecondWordtargetWord ,每个字符串都由从 'a''j'含 'a''j' )的小写英文字母组成。

    + +

    如果 firstWord secondWord数值之和 等于 targetWord 的数值,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:firstWord = "acb", secondWord = "cba", targetWord = "cdb"
    +输出:true
    +解释:
    +firstWord 的数值为 "acb" -> "021" -> 21
    +secondWord 的数值为 "cba" -> "210" -> 210
    +targetWord 的数值为 "cdb" -> "231" -> 231
    +由于 21 + 210 == 231 ,返回 true
    +
    + +

    示例 2:

    + +
    输入:firstWord = "aaa", secondWord = "a", targetWord = "aab"
    +输出:false
    +解释:
    +firstWord 的数值为 "aaa" -> "000" -> 0
    +secondWord 的数值为 "a" -> "0" -> 0
    +targetWord 的数值为 "aab" -> "001" -> 1
    +由于 0 + 0 != 1 ,返回 false
    + +

    示例 3:

    + +
    输入:firstWord = "aaa", secondWord = "a", targetWord = "aaaa"
    +输出:true
    +解释:
    +firstWord 的数值为 "aaa" -> "000" -> 0
    +secondWord 的数值为 "a" -> "0" -> 0
    +targetWord 的数值为 "aaaa" -> "0000" -> 0
    +由于 0 + 0 == 0 ,返回 true
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= firstWord.length, secondWord.length, targetWord.length <= 8
    • +
    • firstWordsecondWordtargetWord 仅由从 'a''j'含 'a''j' )的小写英文字母组成
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: + def convert(word): + res = 0 + for c in word: + res *= 10 + res += (ord(c) - ord('a')) + return res + return convert(firstWord) + convert(secondWord) == convert(targetWord) +``` + +### **Java** + + + +```java +class Solution { + public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { + return convert(firstWord) + convert(secondWord) == convert(targetWord); + } + + private int convert(String word) { + int res = 0; + for (char c : word.toCharArray()) { + res *= 10; + res += (c - 'a'); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool isSumEqual(string firstWord, string secondWord, string targetWord) { + return convert(firstWord) + convert(secondWord) == convert(targetWord); + } +private: + int convert(string word) { + int res = 0; + for (char c : word) { + res *= 10; + res += (c - 'a'); + } + return res; + } +}; +``` + +### **JavaScript** + +```js +/** + * @param {string} firstWord + * @param {string} secondWord + * @param {string} targetWord + * @return {boolean} + */ + var isSumEqual = function(firstWord, secondWord, targetWord) { + let carry = 0; + let n1 = firstWord.length, n2 = secondWord.length; + let n3 = targetWord.length; + for (let i = 0; i < n3; i++) { + let num1 = getNum(firstWord.charAt(n1 - 1 - i)); + let num2 = getNum(secondWord.charAt(n2 - 1 - i)); + let sum = carry + num1 + num2; + if (getNum(targetWord.charAt(n3 - 1 - i)) != (sum % 10)) return false; + carry = parseInt(sum / 10); + } + return true; +}; + +function getNum (char) { + if (!char) return 0; + return char.charCodeAt() - 'a'.charCodeAt(); +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1881.leetcode1881 Maximum Value after Insertion-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1881.leetcode1881 Maximum Value after Insertion-zh.md" new file mode 100644 index 00000000..b3df81b8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1881.leetcode1881 Maximum Value after Insertion-zh.md" @@ -0,0 +1,140 @@ +# [1881. 插入后的最大值](https://leetcode-cn.com/problems/maximum-value-after-insertion) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1881.Maximum%20Value%20after%20Insertion/README_EN.md) + +## 题目描述 + + + +

    给你一个非常大的整数 n 和一个整数数字 x ,大整数 n 用一个字符串表示。n 中每一位数字和数字 x 都处于闭区间 [1, 9] 中,且 n 可能表示一个 负数

    + +

    你打算通过在 n 的十进制表示的任意位置插入 x最大化 n数值 ​​​​​​。但 不能 在负号的左边插入 x

    + +
      +
    • 例如,如果 n = 73x = 6 ,那么最佳方案是将 6 插入 73 之间,使 n = 763
    • +
    • 如果 n = -55x = 2 ,那么最佳方案是将 2 插在第一个 5 之前,使 n = -255
    • +
    + +

    返回插入操作后,用字符串表示的 n 的最大值。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = "99", x = 9
    +输出:"999"
    +解释:不管在哪里插入 9 ,结果都是相同的。
    +
    + +

    示例 2:

    + +
    +输入:n = "-13", x = 2
    +输出:"-123"
    +解释:向 n 中插入 x 可以得到 -213、-123 或者 -132 ,三者中最大的是 -123 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n.length <= 105
    • +
    • 1 <= x <= 9
    • +
    • n​​​ 中每一位的数字都在闭区间 [1, 9] 中。
    • +
    • n 代表一个有效的整数。
    • +
    • n 表示负数时,将会以字符 '-' 开始。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maxValue(self, n: str, x: int) -> str: + negative = n[0] == '-' + i, res = 0, [] + if negative: + i += 1 + res.append('-') + find = False + while i < len(n): + num = int(n[i]) + if (negative and x < num) or (not negative and x > num): + res.append(str(x)) + find = True + break + res.append(n[i]) + i += 1 + res.append(n[i:] if find else str(x)) + return ''.join(res) +``` + +### **Java** + + + +```java +class Solution { + public String maxValue(String n, int x) { + boolean negative = n.charAt(0) == '-'; + StringBuilder res = new StringBuilder(); + int i = 0; + if (negative) { + ++i; + res.append("-"); + } + boolean find = false; + for (; i < n.length(); ++i) { + int num = n.charAt(i) - '0'; + if ((negative && x < num) || (!negative && x > num)) { + res.append(x); + find = true; + break; + } + res.append(n.charAt(i)); + } + res.append(find ? n.substring(i) : x); + return res.toString(); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} n + * @param {number} x + * @return {string} + */ + var maxValue = function(n, x) { + let nums = [...n]; + let sign = 1, i = 0; + if (nums[0] == '-') { + sign = -1; + i++; + } + while (i < n.length && (nums[i] - x) * sign >= 0) { + i++; + } + nums.splice(i, 0, x); + return nums.join(''); +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1882.leetcode1882 Process Tasks Using Servers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1882.leetcode1882 Process Tasks Using Servers-zh.md" new file mode 100644 index 00000000..1c2e84f0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1882.leetcode1882 Process Tasks Using Servers-zh.md" @@ -0,0 +1,149 @@ +# [1882. 使用服务器处理任务](https://leetcode-cn.com/problems/process-tasks-using-servers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1882.Process%20Tasks%20Using%20Servers/README_EN.md) + +## 题目描述 + + + +

    给你两个 下标从 0 开始 的整数数组 serverstasks ,长度分别为 n​​​​​​ 和 m​​​​​​ 。servers[i] 是第 i​​​​​​​​​​ 台服务器的 权重 ,而 tasks[j] 是处理第 j​​​​​​ 项任务 所需要的时间(单位:秒)。

    + +

    你正在运行一个仿真系统,在处理完所有任务后,该系统将会关闭。每台服务器只能同时处理一项任务。第 0 项任务在第 0 秒可以开始处理,相应地,第 j 项任务在第 j 秒可以开始处理。处理第 j 项任务时,你需要为它分配一台 权重最小 的空闲服务器。如果存在多台相同权重的空闲服务器,请选择 下标最小 的服务器。如果一台空闲服务器在第 t 秒分配到第 j 项任务,那么在 t + tasks[j] 时它将恢复空闲状态。

    + +

    如果没有空闲服务器,则必须等待,直到出现一台空闲服务器,并 尽可能早 地处理剩余任务。 如果有多项任务等待分配,则按照 下标递增 的顺序完成分配。

    + +

    如果同一时刻存在多台空闲服务器,可以同时将多项任务分别分配给它们。

    + +

    构建长度为 m 的答案数组 ans ,其中 ans[j] 是第 j 项任务分配的服务器的下标。

    + +

    返回答案数组 ans​​​​ 。

    + +

     

    + +

    示例 1:

    + +
    +输入:servers = [3,3,2], tasks = [1,2,3,2,1,2]
    +输出:[2,2,0,2,1,2]
    +解释:事件按时间顺序如下:
    +- 0 秒时,第 0 项任务加入到任务队列,使用第 2 台服务器处理到 1 秒。
    +- 1 秒时,第 2 台服务器空闲,第 1 项任务加入到任务队列,使用第 2 台服务器处理到 3 秒。
    +- 2 秒时,第 2 项任务加入到任务队列,使用第 0 台服务器处理到 5 秒。
    +- 3 秒时,第 2 台服务器空闲,第 3 项任务加入到任务队列,使用第 2 台服务器处理到 5 秒。
    +- 4 秒时,第 4 项任务加入到任务队列,使用第 1 台服务器处理到 5 秒。
    +- 5 秒时,所有服务器都空闲,第 5 项任务加入到任务队列,使用第 2 台服务器处理到 7 秒。
    + +

    示例 2:

    + +
    +输入:servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]
    +输出:[1,4,1,4,1,3,2]
    +解释:事件按时间顺序如下:
    +- 0 秒时,第 0 项任务加入到任务队列,使用第 1 台服务器处理到 2 秒。
    +- 1 秒时,第 1 项任务加入到任务队列,使用第 4 台服务器处理到 2 秒。
    +- 2 秒时,第 1 台和第 4 台服务器空闲,第 2 项任务加入到任务队列,使用第 1 台服务器处理到 4 秒。
    +- 3 秒时,第 3 项任务加入到任务队列,使用第 4 台服务器处理到 7 秒。
    +- 4 秒时,第 1 台服务器空闲,第 4 项任务加入到任务队列,使用第 1 台服务器处理到 9 秒。
    +- 5 秒时,第 5 项任务加入到任务队列,使用第 3 台服务器处理到 7 秒。
    +- 6 秒时,第 6 项任务加入到任务队列,使用第 2 台服务器处理到 7 秒。
    + +

     

    + +

    提示:

    + +
      +
    • servers.length == n
    • +
    • tasks.length == m
    • +
    • 1 <= n, m <= 2 * 105
    • +
    • 1 <= servers[i], tasks[j] <= 2 * 105
    • +
    + +## 解法 + + + +“优先队列”实现。 + +定义两个优先级队列,分别表示空闲服务器、使用中的服务器。其中:空闲服务器 `idle` 依据**权重、下标**排序;而使用中的服务器 `busy` 依据**结束时间、权重、下标**排序。 + +遍历任务: + +- 若有使用中的服务器小于任务开始时间,将其加入到空闲服务器队列 `idle` 中; +- 若当前有空闲服务器,那么在空闲队列 `idle` 中取出权重最小的服务器,将其加入使用中的队列 `busy` 中; +- 若当前没有空闲服务器,那么在使用队列 `busy` 中找出最早结束时间且权重最小的服务器,重新加入使用中的队列 `busy` 中。 + + + +### **Python3** + + + +```python +class Solution: + def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: + idle, busy = [], [] + for i, weight in enumerate(servers): + heapq.heappush(idle, (weight, i)) + res = [] + for start, cost in enumerate(tasks): + while busy and busy[0][0] <= start: + _, s, i = heapq.heappop(busy) + heapq.heappush(idle, (s, i)) + if idle: + s, i = heapq.heappop(idle) + heapq.heappush(busy, (start + cost, s, i)) + else: + t, s, i = heapq.heappop(busy) + heapq.heappush(busy, (t + cost, s, i)) + res.append(i) + return res +``` + +### **Java** + + + +```java +class Solution { + public int[] assignTasks(int[] servers, int[] tasks) { + int m = tasks.length, n = servers.length; + PriorityQueue idle = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + PriorityQueue busy = new PriorityQueue<>((a, b) -> { + if (a[0] == b[0]) { + return a[1] == b[1] ? a[2] - b[2] : a[1] - b[1]; + } + return a[0] - b[0]; + }); + for (int i = 0; i < n; ++i) { + idle.offer(new int[]{servers[i], i}); + } + int[] res = new int[m]; + int j = 0; + for (int start = 0; start < m; ++start) { + int cost = tasks[start]; + while (!busy.isEmpty() && busy.peek()[0] <= start) { + int[] item = busy.poll(); + idle.offer(new int[]{item[1], item[2]}); + } + if (!idle.isEmpty()) { + int[] item = idle.poll(); + res[j++] = item[1]; + busy.offer(new int[]{start + cost, item[0], item[1]}); + } else { + int[] item = busy.poll(); + res[j++] = item[2]; + busy.offer(new int[]{item[0] + cost, item[1], item[2]}); + } + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1883.leetcode1883 Minimum Skips to Arrive at Meeting On Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1883.leetcode1883 Minimum Skips to Arrive at Meeting On Time-zh.md" new file mode 100644 index 00000000..ada41317 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1883.leetcode1883 Minimum Skips to Arrive at Meeting On Time-zh.md" @@ -0,0 +1,152 @@ +# [1883. 准时抵达会议现场的最小跳过休息次数](https://leetcode-cn.com/problems/minimum-skips-to-arrive-at-meeting-on-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1883.Minimum%20Skips%20to%20Arrive%20at%20Meeting%20On%20Time/README_EN.md) + +## 题目描述 + + + +

    给你一个整数 hoursBefore ,表示你要前往会议所剩下的可用小时数。要想成功抵达会议现场,你必须途经 n 条道路。道路的长度用一个长度为 n 的整数数组 dist 表示,其中 dist[i] 表示第 i 条道路的长度(单位:千米)。另给你一个整数 speed ,表示你在道路上前进的速度(单位:千米每小时)。

    + +

    当你通过第 i 条路之后,就必须休息并等待,直到 下一个整数小时 才能开始继续通过下一条道路。注意:你不需要在通过最后一条道路后休息,因为那时你已经抵达会议现场。

    + +
      +
    • 例如,如果你通过一条道路用去 1.4 小时,那你必须停下来等待,到 2 小时才可以继续通过下一条道路。如果通过一条道路恰好用去 2 小时,就无需等待,可以直接继续。
    • +
    + +

    然而,为了能准时到达,你可以选择 跳过 一些路的休息时间,这意味着你不必等待下一个整数小时。注意,这意味着与不跳过任何休息时间相比,你可能在不同时刻到达接下来的道路。

    + +
      +
    • 例如,假设通过第 1 条道路用去 1.4 小时,且通过第 2 条道路用去 0.6 小时。跳过第 1 条道路的休息时间意味着你将会在恰好 2 小时完成通过第 2 条道路,且你能够立即开始通过第 3 条道路。
    • +
    + +

    返回准时抵达会议现场所需要的 最小跳过次数 ,如果 无法准时参会 ,返回 -1

    + +

     

    + +

    示例 1:

    + +
    +输入:dist = [1,3,2], speed = 4, hoursBefore = 2
    +输出:1
    +解释:
    +不跳过任何休息时间,你将用 (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 小时才能抵达会议现场。
    +可以跳过第 1 次休息时间,共用 ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 小时抵达会议现场。
    +注意,第 2 次休息时间缩短为 0 ,由于跳过第 1 次休息时间,你是在整数小时处完成通过第 2 条道路。
    +
    + +

    示例 2:

    + +
    +输入:dist = [7,3,5,5], speed = 2, hoursBefore = 10
    +输出:2
    +解释:
    +不跳过任何休息时间,你将用 (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 小时才能抵达会议现场。
    +可以跳过第 1 次和第 3 次休息时间,共用 ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 小时抵达会议现场。
    +
    + +

    示例 3:

    + +
    +输入:dist = [7,3,5,5], speed = 1, hoursBefore = 10
    +输出:-1
    +解释:即使跳过所有的休息时间,也无法准时参加会议。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == dist.length
    • +
    • 1 <= n <= 1000
    • +
    • 1 <= dist[i] <= 105
    • +
    • 1 <= speed <= 106
    • +
    • 1 <= hoursBefore <= 107
    • +
    + +## 解法 + + + +“动态规划”实现。 + +定义 `dp[i][j]` 表示前 i 段道路,跳过了 j 次的最短路程(耗时也一样)。 + +考虑最后一段道路 `dist[i - 1]` 是否跳过: + +- 若没有跳过,那么 `dp[i][j] = ⌈dp[i - 1][j] + dist[i - 1] / speed⌉` +- 若跳过,那么 `dp[i][j] = dp[i - 1][j - 1] + dist[i - 1] / speed` + +综合两种情况,`dp[i][j] = min{⌈dp[i - 1][j] + dist[i - 1] / speed⌉, dp[i - 1][j - 1] + dist[i - 1] / speed}`。 + + + +### **Python3** + + + +```python +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + n = len(dist) + dp = [[float('inf')] * (n + 1) for _ in range(n + 1)] + dp[0][0] = 0 + for i in range(1, n + 1): + for j in range(i + 1): + if i != j: + # 没有跳过 + dp[i][j] = min(dp[i][j], ((dp[i - 1][j] + dist[i - 1] - 1) // speed + 1) * speed) + if j > 0: + # 跳过 + dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + dist[i - 1]) + for i in range(n + 1): + if dp[n][i] <= hoursBefore * speed: + return i + return -1 +``` + +### **Java** + + + +```java +class Solution { + public int minSkips(int[] dist, int speed, int hoursBefore) { + int n = dist.length; + int[][] dp = new int[n + 1][n + 1]; + for (int i = 0; i <= n; ++i) { + for (int j = 0; j <= n; ++j) { + dp[i][j] = Integer.MAX_VALUE; + } + } + dp[0][0] = 0; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j <= i; ++j) { + if (i != j) { + // 没有跳过 + dp[i][j] = Math.min(dp[i][j], ((dp[i - 1][j] + dist[i - 1] - 1) / speed + 1) * speed); + } + if (j > 0) { + // 跳过 + dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + dist[i - 1]); + } + } + } + for (int i = 0; i <= n; ++i) { + if (dp[n][i] <= hoursBefore * speed) { + return i; + } + } + return -1; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1884.leetcode1884 Egg Drop With 2 Eggs and N Floors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1884.leetcode1884 Egg Drop With 2 Eggs and N Floors-zh.md" new file mode 100644 index 00000000..45331fbd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1884.leetcode1884 Egg Drop With 2 Eggs and N Floors-zh.md" @@ -0,0 +1,74 @@ +# [1884. 鸡蛋掉落-两枚鸡蛋](https://leetcode-cn.com/problems/egg-drop-with-2-eggs-and-n-floors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1884.Egg%20Drop%20With%202%20Eggs%20and%20N%20Floors/README_EN.md) + +## 题目描述 + + + +

    给你 2 枚相同 的鸡蛋,和一栋从第 1 层到第 n 层共有 n 层楼的建筑。

    + +

    已知存在楼层 f ,满足 0 <= f <= n ,任何从 高于 f 的楼层落下的鸡蛋都 会碎 ,从 f 楼层或比它低 的楼层落下的鸡蛋都 不会碎

    + +

    每次操作,你可以取一枚 没有碎 的鸡蛋并把它从任一楼层 x 扔下(满足 1 <= x <= n)。如果鸡蛋碎了,你就不能再次使用它。如果某枚鸡蛋扔下后没有摔碎,则可以在之后的操作中 重复使用 这枚鸡蛋。

    + +

    请你计算并返回要确定 f 确切的值 最小操作次数 是多少?

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 2
    +输出:2
    +解释:我们可以将第一枚鸡蛋从 1 楼扔下,然后将第二枚从 2 楼扔下。
    +如果第一枚鸡蛋碎了,可知 f = 0;
    +如果第二没鸡蛋碎了,但第一枚没碎,可知 f = 1;
    +否则,当两个鸡蛋都没碎时,可知 f = 2。
    +
    + +

    示例 2:

    + +
    +输入:n = 100
    +输出:14
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1885.leetcode1885 Count Pairs in Two Arrays-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1885.leetcode1885 Count Pairs in Two Arrays-zh.md" new file mode 100644 index 00000000..044c16bd --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1885.leetcode1885 Count Pairs in Two Arrays-zh.md" @@ -0,0 +1,39 @@ +# [1885. ](https://leetcode-cn.com/problems/count-pairs-in-two-arrays) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1885.Count%20Pairs%20in%20Two%20Arrays/README_EN.md) + +## 题目描述 + + + +None + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1886.leetcode1886 Determine Whether Matrix Can Be Obtained By Rotation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1886.leetcode1886 Determine Whether Matrix Can Be Obtained By Rotation-zh.md" new file mode 100644 index 00000000..df61b197 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1886.leetcode1886 Determine Whether Matrix Can Be Obtained By Rotation-zh.md" @@ -0,0 +1,130 @@ +# [1886. 判断矩阵经轮转后是否一致](https://leetcode-cn.com/problems/determine-whether-matrix-can-be-obtained-by-rotation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1886.Determine%20Whether%20Matrix%20Can%20Be%20Obtained%20By%20Rotation/README_EN.md) + +## 题目描述 + + + +

    给你两个大小为 n x n 的二进制矩阵 mattarget 。现 以 90 度顺时针轮转 矩阵 mat 中的元素 若干次 ,如果能够使 mat 与 target 一致,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
    +输出:true
    +解释:顺时针轮转 90 度一次可以使 mat 和 target 一致。
    +
    + +

    示例 2:

    + +
    +输入:mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
    +输出:false
    +解释:无法通过轮转矩阵中的元素使 equal 与 target 一致。
    +
    + +

    示例 3:

    + +
    +输入:mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
    +输出:true
    +解释:顺时针轮转 90 度两次可以使 mat 和 target 一致。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == mat.length == target.length
    • +
    • n == mat[i].length == target[i].length
    • +
    • 1 <= n <= 10
    • +
    • mat[i][j]target[i][j] 不是 0 就是 1
    • +
    + + +## 解法 + + + +旋转矩阵,判断矩阵是否一致。 + + + +### **Python3** + + + +```python +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + def rotate(matrix): + n = len(matrix) + for i in range(n // 2): + for j in range(i, n - 1 - i): + t = matrix[i][j] + matrix[i][j] = matrix[n - j - 1][i] + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] + matrix[j][n - i - 1] = t + for _ in range(4): + if mat == target: + return True + rotate(mat) + return False +``` + +### **Java** + + + +```java +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + int times = 4; + while (times-- > 0) { + if (equals(mat, target)) { + return true; + } + rotate(mat); + } + return false; + } + + private void rotate(int[][] matrix) { + int n = matrix.length; + for (int i = 0; i < n / 2; ++i) { + for (int j = i; j < n - 1 - i; ++j) { + int t = matrix[i][j]; + matrix[i][j] = matrix[n - j - 1][i]; + matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; + matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; + matrix[j][n - i - 1] = t; + } + } + } + + private boolean equals(int[][] nums1, int[][] nums2) { + int n = nums1.length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (nums1[i][j] != nums2[i][j]) { + return false; + } + } + } + return true; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1887.leetcode1887 Reduction Operations to Make the Array Elements Equal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1887.leetcode1887 Reduction Operations to Make the Array Elements Equal-zh.md" new file mode 100644 index 00000000..b518804e --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1887.leetcode1887 Reduction Operations to Make the Array Elements Equal-zh.md" @@ -0,0 +1,114 @@ +# [1887. 使数组元素相等的减少操作次数](https://leetcode-cn.com/problems/reduction-operations-to-make-the-array-elements-equal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1887.Reduction%20Operations%20to%20Make%20the%20Array%20Elements%20Equal/README_EN.md) + +## 题目描述 + + + +

    给你一个整数数组 nums ,你的目标是令 nums 中的所有元素相等。完成一次减少操作需要遵照下面的几个步骤:

    + +
      +
    1. 找出 nums 中的 最大 值。记这个值为 largest 并取其下标 i下标从 0 开始计数)。如果有多个元素都是最大值,则取最小的 i
    2. +
    3. 找出 nums 中的 下一个最大 值,这个值 严格小于 largest ,记为 nextLargest
    4. +
    5. nums[i] 减少到 nextLargest
    6. +
    + +

    返回使 nums 中的所有元素相等的操作次数。

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [5,1,3]
    +输出:3
    +解释:需要 3 次操作使 nums 中的所有元素相等:
    +1. largest = 5 下标为 0 。nextLargest = 3 。将 nums[0] 减少到 3 。nums = [3,1,3] 。
    +2. largest = 3 下标为 0 。nextLargest = 1 。将 nums[0] 减少到 1 。nums = [1,1,3] 。
    +3. largest = 3 下标为 2 。nextLargest = 1 。将 nums[2] 减少到 1 。nums = [1,1,1] 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [1,1,1]
    +输出:0
    +解释:nums 中的所有元素已经是相等的。
    +
    + +

    示例 3:

    + +
    +输入:nums = [1,1,2,2,3]
    +输出:4
    +解释:需要 4 次操作使 nums 中的所有元素相等:
    +1. largest = 3 下标为 4 。nextLargest = 2 。将 nums[4] 减少到 2 。nums = [1,1,2,2,2] 。
    +2. largest = 2 下标为 2 。nextLargest = 1 。将 nums[2] 减少到 1 。nums = [1,1,1,2,2] 。 
    +3. largest = 2 下标为 3 。nextLargest = 1 。将 nums[3] 减少到 1 。nums = [1,1,1,1,2] 。 
    +4. largest = 2 下标为 4 。nextLargest = 1 。将 nums[4] 减少到 1 。nums = [1,1,1,1,1] 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 5 * 104
    • +
    • 1 <= nums[i] <= 5 * 104
    • +
    + + +## 解法 + + + +“有序字典”实现。 + + + +### **Python3** + + + +```python +class Solution: + def reductionOperations(self, nums: List[int]) -> int: + counter = collections.Counter(nums) + f = res = 0 + n = len(nums) + for _, v in sorted(counter.items(), key=lambda x: x[0]): + f += v + res += (n - f) + return res +``` + +### **Java** + + + +```java +class Solution { + public int reductionOperations(int[] nums) { + TreeMap counter = new TreeMap<>(); + for (int num : nums) { + counter.put(num, counter.getOrDefault(num, 0) + 1); + } + int n = nums.length; + int f = 0, res = 0; + while (counter.size() != 0) { + f += counter.pollFirstEntry().getValue(); + res += (n - f); + } + return res; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1888.leetcode1888 Minimum Number of Flips to Make the Binary String Alternating-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1888.leetcode1888 Minimum Number of Flips to Make the Binary String Alternating-zh.md" new file mode 100644 index 00000000..4625dc3a --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1888.leetcode1888 Minimum Number of Flips to Make the Binary String Alternating-zh.md" @@ -0,0 +1,135 @@ +# [1888. 使二进制字符串字符交替的最少反转次数](https://leetcode-cn.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1888.Minimum%20Number%20of%20Flips%20to%20Make%20the%20Binary%20String%20Alternating/README_EN.md) + +## 题目描述 + + + +

    给你一个二进制字符串 s 。你可以按任意顺序执行以下两种操作任意次:

    + +
      +
    • 类型 1 :删除 字符串 s 的第一个字符并将它 添加 到字符串结尾。
    • +
    • 类型 2 :选择 字符串 s 中任意一个字符并将该字符 反转 ,也就是如果值为 '0' ,则反转得到 '1' ,反之亦然。
    • +
    + +

    请你返回使 s 变成 交替 字符串的前提下, 类型 2 最少 操作次数 。

    + +

    我们称一个字符串是 交替 的,需要满足任意相邻字符都不同。

    + +
      +
    • 比方说,字符串 "010" 和 "1010" 都是交替的,但是字符串 "0100" 不是。
    • +
    + +

     

    + +

    示例 1:

    + +
    输入:s = "111000"
    +输出:2
    +解释:执行第一种操作两次,得到 s = "100011" 。
    +然后对第三个和第六个字符执行第二种操作,得到 s = "101010" 。
    +
    + +

    示例 2:

    + +
    输入:s = "010"
    +输出:0
    +解释:字符串已经是交替的。
    +
    + +

    示例 3:

    + +
    输入:s = "1110"
    +输出:1
    +解释:对第二个字符执行第二种操作,得到 s = "1010" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 105
    • +
    • s[i] 要么是 '0' ,要么是 '1' 。
    • +
    + +## 解法 + + + +“滑动窗口”实现。 + + + +### **Python3** + + + +```python +class Solution: + def minFlips(self, s: str) -> int: + n = len(s) + target = '01' + cnt = 0 + for i, c in enumerate(s): + cnt += c != target[i & 1] + res = min(cnt, n - cnt) + for i in range(n): + cnt -= s[i] != target[i & 1] + cnt += s[i] != target[(i + n) & 1] + res = min(res, cnt, n - cnt) + return res +``` + +### **Java** + + + +```java +class Solution { + public int minFlips(String s) { + int n = s.length(); + String target = "01"; + int cnt = 0; + for (int i = 0; i < n; ++i) { + cnt += (s.charAt(i) == target.charAt(i & 1) ? 0 : 1); + } + int res = Math.min(cnt, n - cnt); + for (int i = 0; i < n; ++i) { + cnt -= (s.charAt(i) == target.charAt(i & 1) ? 0 : 1); + cnt += (s.charAt(i) == target.charAt((i + n) & 1) ? 0 : 1); + res = Math.min(res, Math.min(cnt, n - cnt)); + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function minFlips(s: string): number { + const n: number = s.length; + const target: string[] = ['0', '1']; + let count: number = 0; + for (let i: number = 0; i < n; ++i) { + count += (s.charAt(i) == target[i & 1] ? 0 : 1); + } + let res = Math.min(count, n - count); + for (let i: number = 0; i < n; ++i) { + count -= (s.charAt(i) == target[i & 1] ? 0 : 1); + count += (s.charAt(i) == target[(i + n) & 1] ? 0 : 1); + res = Math.min(res, count, n - count); + } + return res; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1889.leetcode1889 Minimum Space Wasted From Packaging-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1889.leetcode1889 Minimum Space Wasted From Packaging-zh.md" new file mode 100644 index 00000000..47b3436d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1889.leetcode1889 Minimum Space Wasted From Packaging-zh.md" @@ -0,0 +1,187 @@ +# [1889. 装包裹的最小浪费空间](https://leetcode-cn.com/problems/minimum-space-wasted-from-packaging) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1889.Minimum%20Space%20Wasted%20From%20Packaging/README_EN.md) + +## 题目描述 + + + +

    给你 n 个包裹,你需要把它们装在箱子里,每个箱子装一个包裹。总共有 m 个供应商提供 不同尺寸 的箱子(每个规格都有无数个箱子)。如果一个包裹的尺寸 小于等于 一个箱子的尺寸,那么这个包裹就可以放入这个箱子之中。

    + +

    包裹的尺寸用一个整数数组 packages 表示,其中 packages[i] 是第 i 个包裹的尺寸。供应商用二维数组 boxes 表示,其中 boxes[j] 是第 j 个供应商提供的所有箱子尺寸的数组。

    + +

    你想要选择 一个供应商 并只使用该供应商提供的箱子,使得 总浪费空间最小 。对于每个装了包裹的箱子,我们定义 浪费的 空间等于 箱子的尺寸 - 包裹的尺寸 。总浪费空间 为 所有 箱子中浪费空间的总和。

    + +
      +
    • 比方说,如果你想要用尺寸数组为 [4,8] 的箱子装下尺寸为 [2,3,5] 的包裹,你可以将尺寸为 2 和 3 的两个包裹装入两个尺寸为 4 的箱子中,同时把尺寸为 5 的包裹装入尺寸为 8 的箱子中。总浪费空间为 (4-2) + (4-3) + (8-5) = 6 。
    • +
    + +

    请你选择 最优 箱子供应商,使得 总浪费空间最小 。如果 无法 将所有包裹放入箱子中,请你返回 -1 。由于答案可能会 很大 ,请返回它对 109 + 7 取余 的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:packages = [2,3,5], boxes = [[4,8],[2,8]]
    +输出:6
    +解释:选择第一个供应商最优,用两个尺寸为 4 的箱子和一个尺寸为 8 的箱子。
    +总浪费空间为 (4-2) + (4-3) + (8-5) = 6 。
    +
    + +

    示例 2:

    + +
    +输入:packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]
    +输出:-1
    +解释:没有箱子能装下尺寸为 5 的包裹。
    +
    + +

    示例 3:

    + +
    +输入:packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]
    +输出:9
    +解释:选择第三个供应商最优,用两个尺寸为 5 的箱子,两个尺寸为 10 的箱子和两个尺寸为 14 的箱子。
    +总浪费空间为 (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == packages.length
    • +
    • m == boxes.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= m <= 105
    • +
    • 1 <= packages[i] <= 105
    • +
    • 1 <= boxes[j].length <= 105
    • +
    • 1 <= boxes[j][k] <= 105
    • +
    • sum(boxes[j].length) <= 105
    • +
    • boxes[j] 中的元素 互不相同 。
    • +
    + + +## 解法 + + + +“排序 + 二分查找 + 前缀和”实现。 + + + +### **Python3** + + + +```python +class Solution: + def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: + packages.sort() + res = float('inf') + for box in boxes: + box.sort() + if packages[-1] > box[-1]: + continue + t = last = 0 + for b in box: + idx = bisect.bisect_right(packages, b, lo=last) + t += (idx - last) * b + last = idx + res = min(res, t) + return -1 if res == float('inf') else (res - sum(packages)) % (10 ** 9 + 7) +``` + +### **Java** + + + +```java +class Solution { + public int minWastedSpace(int[] packages, int[][] boxes) { + int n = packages.length; + Arrays.sort(packages); + long[] preSum = new long[n + 1]; + for (int i = 0; i < n; ++i) { + preSum[i + 1] = preSum[i] + packages[i]; + } + + long res = Long.MAX_VALUE; + for (int[] box : boxes) { + Arrays.sort(box); + if (packages[n - 1] > box[box.length - 1]) { + continue; + } + long t = 0; + int low = 0; + for (int b : box) { + int idx = searchRight(packages, b, low); + // 这里需要手动转 long + t += ((idx - low) * (long) b - (preSum[idx] - preSum[low])); + low = idx; + } + res = Math.min(res, t); + } + return res == Long.MAX_VALUE ? -1 : (int) (res % 1000000007); + } + + private int searchRight(int[] packages, int target, int low) { + int high = packages.length; + while (low < high) { + int mid = (low + high) >> 1; + if (packages[mid] <= target) { + low = mid + 1; + } else { + high = mid; + } + } + return low; + } +} +``` + +### **TypeScript** + +```ts +function minWastedSpace(packages: number[], boxes: number[][]): number { + const MOD = 10 ** 9 + 7; + packages.sort((a, b) => a - b); + const max_package = packages[packages.length - 1]; + const total = packages.reduce((a, c) => a + c, 0); + let res = Infinity; + for (let box of boxes) { + box.sort((a, b) => a - b); + if (max_package > box[box.length - 1]) continue; + let left = 0, sum = 0; + for (let capacity of box) { + let right = searchRight(packages, capacity, left); + sum += (right - left) * capacity; + left = right; + } + res = Math.min(res, sum); + } + return res == Infinity ? -1 : (res - total) % MOD; +}; + +function searchRight(packages: number[], target: number, left: number): number { + let right = packages.length; + while (left < right) { + let mid = (left + right) >> 1; + if (packages[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1890.leetcode1890 The Latest Login in 2020-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1890.leetcode1890 The Latest Login in 2020-zh.md" new file mode 100644 index 00000000..6bd06ea6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1890.leetcode1890 The Latest Login in 2020-zh.md" @@ -0,0 +1,122 @@ +# [1890. The Latest Login in 2020](https://leetcode-cn.com/problems/the-latest-login-in-2020) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1890.The%20Latest%20Login%20in%202020/README_EN.md) + +## 题目描述 + + + +

    Table: Logins

    + +
    +
    ++----------------+----------+
    +
    +| Column Name    | Type     |
    +
    ++----------------+----------+
    +
    +| user_id        | int      |
    +
    +| time_stamp     | datetime |
    +
    ++----------------+----------+
    +
    +(user_id, time_stamp) is the primary key for this table.
    +
    +Each row contains information about the login time for the user with ID user_id.
    +
    +
    + +

     

    + +

    Write an SQL query to report the latest login for all users in the year 2020. Do not include the users who did not login in 2020.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +
    +Logins table:
    +
    ++---------+---------------------+
    +
    +| user_id | time_stamp          |
    +
    ++---------+---------------------+
    +
    +| 6       | 2020-06-30 15:06:07 |
    +
    +| 6       | 2021-04-21 14:06:06 |
    +
    +| 6       | 2019-03-07 00:18:15 |
    +
    +| 8       | 2020-02-01 05:10:53 |
    +
    +| 8       | 2020-12-30 00:46:50 |
    +
    +| 2       | 2020-01-16 02:49:50 |
    +
    +| 2       | 2019-08-25 07:59:08 |
    +
    +| 14      | 2019-07-14 09:00:00 |
    +
    +| 14      | 2021-01-06 11:59:59 |
    +
    ++---------+---------------------+
    +
    +
    +
    +Result table:
    +
    ++---------+---------------------+
    +
    +| user_id | last_stamp          |
    +
    ++---------+---------------------+
    +
    +| 6       | 2020-06-30 15:06:07 |
    +
    +| 8       | 2020-12-30 00:46:50 |
    +
    +| 2       | 2020-01-16 02:49:50 |
    +
    ++---------+---------------------+
    +
    +
    +
    +User 6 logged into their account 3 times but only once in 2020, so we include this login in the result table.
    +
    +User 8 logged into their account 2 times in 2020, once in February and once in December. We include only the latest one (December) in the result table.
    +
    +User 2 logged into their account 2 times but only once in 2020, so we include this login in the result table.
    +
    +User 14 did not login in 2020, so we do not include them in the result table.
    +
    +
    + +## 解法 + + + + + +### **SQL** + + + +```sql +# Write your MySQL query statement below +SELECT + user_id, + max(time_stamp) AS last_stamp +FROM + Logins +WHERE YEAR(time_stamp) = 2020 +GROUP BY user_id; +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1891.leetcode1891 Cutting Ribbons-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1891.leetcode1891 Cutting Ribbons-zh.md" new file mode 100644 index 00000000..cc8db101 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1891.leetcode1891 Cutting Ribbons-zh.md" @@ -0,0 +1,199 @@ +# [1891. Cutting Ribbons](https://leetcode-cn.com/problems/cutting-ribbons) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1891.Cutting%20Ribbons/README_EN.md) + +## 题目描述 + + + +

    You are given an integer array ribbons, where ribbons[i] represents the length of the ith ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.

    + +
      +
    • For example, if you have a ribbon of length 4, you can: +
        +
      • Keep the ribbon of length 4,
      • +
      • Cut it into one ribbon of length 3 and one ribbon of length 1,
      • +
      • Cut it into two ribbons of length 2,
      • +
      • Cut it into one ribbon of length 2 and two ribbons of length 1, or
      • +
      • Cut it into four ribbons of length 1.
      • +
      +
    • +
    + +

    Your goal is to obtain k ribbons of all the same positive integer length. You are allowed to throw away any excess ribbon as a result of cutting.

    + +

    Return the maximum possible positive integer length that you can obtain k ribbons of, or 0 if you cannot obtain k ribbons of the same length.

    + +

     

    +

    Example 1:

    + +
    +Input: ribbons = [9,7,5], k = 3
    +Output: 5
    +Explanation:
    +- Cut the first ribbon to two ribbons, one of length 5 and one of length 4.
    +- Cut the second ribbon to two ribbons, one of length 5 and one of length 2.
    +- Keep the third ribbon as it is.
    +Now you have 3 ribbons of length 5.
    + +

    Example 2:

    + +
    +Input: ribbons = [7,5,9], k = 4
    +Output: 4
    +Explanation:
    +- Cut the first ribbon to two ribbons, one of length 4 and one of length 3.
    +- Cut the second ribbon to two ribbons, one of length 4 and one of length 1.
    +- Cut the third ribbon to three ribbons, two of length 4 and one of length 1.
    +Now you have 4 ribbons of length 4.
    +
    + +

    Example 3:

    + +
    +Input: ribbons = [5,7,9], k = 22
    +Output: 0
    +Explanation: You cannot obtain k ribbons of the same positive integer length.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= ribbons.length <= 105
    • +
    • 1 <= ribbons[i] <= 105
    • +
    • 1 <= k <= 109
    • +
    + +## 解法 + + + +“二分法”实现。 + + + +### **Python3** + + + +```python +class Solution: + def maxLength(self, ribbons: List[int], k: int) -> int: + low, high = 0, 100000 + while low < high: + mid = (low + high + 1) >> 1 + cnt = 0 + for ribbon in ribbons: + cnt += ribbon // mid + if cnt < k: + high = mid - 1 + else: + low = mid + return low +``` + +### **Java** + + + +```java +class Solution { + public int maxLength(int[] ribbons, int k) { + int low = 0, high = 100000; + while (low < high) { + int mid = (low + high + 1) >> 1; + int cnt = 0; + for (int ribbon : ribbons) { + cnt += ribbon / mid; + } + if (cnt < k) { + high = mid - 1; + } else { + low = mid; + } + } + return low; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} ribbons + * @param {number} k + * @return {number} + */ +var maxLength = function(ribbons, k) { + let low = 0; + let high = 100000; + while (low < high) { + const mid = (low + high + 1) >> 1; + let cnt = 0; + for (let ribbon of ribbons) { + cnt += Math.floor(ribbon / mid); + } + if (cnt < k) { + high = mid - 1; + } else { + low = mid; + } + } + return low; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int maxLength(vector& ribbons, int k) { + int low = 0, high = 100000; + while (low < high) { + int mid = (low + high + 1) / 2; + int cnt = 0; + for (auto ribbon : ribbons) { + cnt += ribbon / mid; + } + if (cnt < k) { + high = mid - 1; + } else { + low = mid; + } + } + return low; + } +}; +``` + +### **Go** + +```go +func maxLength(ribbons []int, k int) int { + low, high := 0, 100000 + for low < high { + mid := (low + high + 1) >> 1 + cnt := 0 + for _, ribbon := range ribbons { + cnt += ribbon / mid + } + if cnt < k { + high = mid - 1 + } else { + low = mid + } + } + return low +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1892.leetcode1892 Page Recommendations II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1892.leetcode1892 Page Recommendations II-zh.md" new file mode 100644 index 00000000..8f5de06d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1892.leetcode1892 Page Recommendations II-zh.md" @@ -0,0 +1,209 @@ +# [1892. Page Recommendations II](https://leetcode-cn.com/problems/page-recommendations-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1892.Page%20Recommendations%20II/README_EN.md) + +## 题目描述 + + + +

    Table: Friendship

    + +
    +
    ++---------------+---------+
    +
    +| Column Name   | Type    |
    +
    ++---------------+---------+
    +
    +| user1_id      | int     |
    +
    +| user2_id      | int     |
    +
    ++---------------+---------+
    +
    +(user1_id, user2_id) is the primary key for this table.
    +
    +Each row of this table indicates that the users user1_id and user2_id are friends.
    +
    +
    + +

     

    + +

    Table: Likes

    + +
    +
    ++-------------+---------+
    +
    +| Column Name | Type    |
    +
    ++-------------+---------+
    +
    +| user_id     | int     |
    +
    +| page_id     | int     |
    +
    ++-------------+---------+
    +
    +(user_id, page_id) is the primary key for this table.
    +
    +Each row of this table indicates that user_id likes page_id.
    +
    +
    + +

     

    + +

    You are implementing a page recommendation system for a social media website. Your system will recommended a page to user_id if the page is liked by at least one friend of user_id and is not liked by user_id.

    + +

    Write an SQL query to find all the possible page recommendations for every user. Each recommendation should appear as a row in the result table with these columns:

    + +
      +
    • user_id: The ID of the user that your system is making the recommendation to.
    • +
    • page_id: The ID of the page that will be recommended to user_id.
    • +
    • friends_likes: The number of the friends of user_id that like page_id.
    • +
    + +

    Return result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +
    +Friendship table:
    +
    ++----------+----------+
    +
    +| user1_id | user2_id |
    +
    ++----------+----------+
    +
    +| 1        | 2        |
    +
    +| 1        | 3        |
    +
    +| 1        | 4        |
    +
    +| 2        | 3        |
    +
    +| 2        | 4        |
    +
    +| 2        | 5        |
    +
    +| 6        | 1        |
    +
    ++----------+----------+
    +
    + 
    +
    +Likes table:
    +
    ++---------+---------+
    +
    +| user_id | page_id |
    +
    ++---------+---------+
    +
    +| 1       | 88      |
    +
    +| 2       | 23      |
    +
    +| 3       | 24      |
    +
    +| 4       | 56      |
    +
    +| 5       | 11      |
    +
    +| 6       | 33      |
    +
    +| 2       | 77      |
    +
    +| 3       | 77      |
    +
    +| 6       | 88      |
    +
    ++---------+---------+
    +
    +
    +
    +Result table:
    +
    ++---------+---------+---------------+
    +
    +| user_id | page_id | friends_likes |
    +
    ++---------+---------+---------------+
    +
    +| 1       | 77      | 2             |
    +
    +| 1       | 23      | 1             |
    +
    +| 1       | 24      | 1             |
    +
    +| 1       | 56      | 1             |
    +
    +| 1       | 33      | 1             |
    +
    +| 2       | 24      | 1             |
    +
    +| 2       | 56      | 1             |
    +
    +| 2       | 11      | 1             |
    +
    +| 2       | 88      | 1             |
    +
    +| 3       | 88      | 1             |
    +
    +| 3       | 23      | 1             |
    +
    +| 4       | 88      | 1             |
    +
    +| 4       | 77      | 1             |
    +
    +| 4       | 23      | 1             |
    +
    +| 5       | 77      | 1             |
    +
    +| 5       | 23      | 1             |
    +
    ++---------+---------+---------------+
    +
    +Take user 1 as an example:
    +
    +  - User 1 is friends with users 2, 3, 4, and 6.
    +
    +  - Recommended pages are 23 (user 2 liked it), 24 (user 3 liked it), 56 (user 3 liked it), 33 (user 6 liked it), and 77 (user 2 and user 3 liked it).
    +
    +  - Note that page 88 is not recommended because user 1 already liked it.
    +
    +
    +
    +Another example is user 6:
    +
    +  - User 6 is friends with user 1.
    +
    +  - User 1 only liked page 88, but user 6 already liked it. Hence, user 6 has no recommendations.
    +
    +
    +
    +You can recommend pages for users 2, 3, 4, and 5 using a similar process.
    +
    +
    + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1893.leetcode1893 Check if All the Integers in a Range Are Covered-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1893.leetcode1893 Check if All the Integers in a Range Are Covered-zh.md" new file mode 100644 index 00000000..36fefb6f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1893.leetcode1893 Check if All the Integers in a Range Are Covered-zh.md" @@ -0,0 +1,75 @@ +# [1893. 检查是否区域内所有整数都被覆盖](https://leetcode-cn.com/problems/check-if-all-the-integers-in-a-range-are-covered) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1893.Check%20if%20All%20the%20Integers%20in%20a%20Range%20Are%20Covered/README_EN.md) + +## 题目描述 + + + +

    给你一个二维整数数组 ranges 和两个整数 left 和 right 。每个 ranges[i] = [starti, endi] 表示一个从 starti 到 endi 的 闭区间 。

    + +

    如果闭区间 [left, right] 内每个整数都被 ranges 中 至少一个 区间覆盖,那么请你返回 true ,否则返回 false 。

    + +

    已知区间 ranges[i] = [starti, endi] ,如果整数 x 满足 starti <= x <= endi ,那么我们称整数x 被覆盖了。

    + +

     

    + +

    示例 1:

    + +
    +输入:ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5
    +输出:true
    +解释:2 到 5 的每个整数都被覆盖了:
    +- 2 被第一个区间覆盖。
    +- 3 和 4 被第二个区间覆盖。
    +- 5 被第三个区间覆盖。
    +
    + +

    示例 2:

    + +
    +输入:ranges = [[1,10],[10,20]], left = 21, right = 21
    +输出:false
    +解释:21 没有被任何一个区间覆盖。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= ranges.length <= 50
    • +
    • 1 <= starti <= endi <= 50
    • +
    • 1 <= left <= right <= 50
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1894.leetcode1894 Find the Student that Will Replace the Chalk-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1894.leetcode1894 Find the Student that Will Replace the Chalk-zh.md" new file mode 100644 index 00000000..76c6b8b7 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1894.leetcode1894 Find the Student that Will Replace the Chalk-zh.md" @@ -0,0 +1,168 @@ +# [1894. 找到需要补充粉笔的学生编号](https://leetcode-cn.com/problems/find-the-student-that-will-replace-the-chalk) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1894.Find%20the%20Student%20that%20Will%20Replace%20the%20Chalk/README_EN.md) + +## 题目描述 + + + +

    一个班级里有 n 个学生,编号为 0 到 n - 1 。每个学生会依次回答问题,编号为 0 的学生先回答,然后是编号为 1 的学生,以此类推,直到编号为 n - 1 的学生,然后老师会重复这个过程,重新从编号为 0 的学生开始回答问题。

    + +

    给你一个长度为 n 且下标从 0 开始的整数数组 chalk 和一个整数 k 。一开始粉笔盒里总共有 k 支粉笔。当编号为 i 的学生回答问题时,他会消耗 chalk[i] 支粉笔。如果剩余粉笔数量 严格小于 chalk[i] ,那么学生 i 需要 补充 粉笔。

    + +

    请你返回需要 补充 粉笔的学生 编号 。

    + +

     

    + +

    示例 1:

    + +
    输入:chalk = [5,1,5], k = 22
    +输出:0
    +解释:学生消耗粉笔情况如下:
    +- 编号为 0 的学生使用 5 支粉笔,然后 k = 17 。
    +- 编号为 1 的学生使用 1 支粉笔,然后 k = 16 。
    +- 编号为 2 的学生使用 5 支粉笔,然后 k = 11 。
    +- 编号为 0 的学生使用 5 支粉笔,然后 k = 6 。
    +- 编号为 1 的学生使用 1 支粉笔,然后 k = 5 。
    +- 编号为 2 的学生使用 5 支粉笔,然后 k = 0 。
    +编号为 0 的学生没有足够的粉笔,所以他需要补充粉笔。
    + +

    示例 2:

    + +
    输入:chalk = [3,4,1,2], k = 25
    +输出:1
    +解释:学生消耗粉笔情况如下:
    +- 编号为 0 的学生使用 3 支粉笔,然后 k = 22 。
    +- 编号为 1 的学生使用 4 支粉笔,然后 k = 18 。
    +- 编号为 2 的学生使用 1 支粉笔,然后 k = 17 。
    +- 编号为 3 的学生使用 2 支粉笔,然后 k = 15 。
    +- 编号为 0 的学生使用 3 支粉笔,然后 k = 12 。
    +- 编号为 1 的学生使用 4 支粉笔,然后 k = 8 。
    +- 编号为 2 的学生使用 1 支粉笔,然后 k = 7 。
    +- 编号为 3 的学生使用 2 支粉笔,然后 k = 5 。
    +- 编号为 0 的学生使用 3 支粉笔,然后 k = 2 。
    +编号为 1 的学生没有足够的粉笔,所以他需要补充粉笔。
    +
    + +

     

    + +

    提示:

    + +
      +
    • chalk.length == n
    • +
    • 1 <= n <= 105
    • +
    • 1 <= chalk[i] <= 105
    • +
    • 1 <= k <= 109
    • +
    + + +## 解法 + + + +“前缀和 + 二分查找”实现。 + + + +### **Python3** + + + +```python +class Solution: + def chalkReplacer(self, chalk: List[int], k: int) -> int: + pre_sum = list(itertools.accumulate(chalk)) + k %= pre_sum[-1] + left, right = 0, len(chalk) - 1 + while left < right: + mid = (left + right) >> 1 + if pre_sum[mid] > k: + right = mid + else: + left = mid + 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int chalkReplacer(int[] chalk, int k) { + int n = chalk.length; + long[] preSum = new long[n + 1]; + for (int i = 0; i < n; ++i) { + preSum[i + 1] = preSum[i] + chalk[i]; + } + k %= preSum[n]; + int left = 0, right = n - 1; + while (left < right) { + int mid = (left + right) >> 1; + if (preSum[mid + 1] > k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int chalkReplacer(vector& chalk, int k) { + int n = chalk.size(); + vector preSum(n + 1); + for (int i = 0; i < n; ++i) { + preSum[i + 1] = preSum[i] + chalk[i]; + } + k %= preSum[n]; + int left = 0, right = n - 1; + while (left < right) { + int mid = left + (right - left >> 1); + if (preSum[mid + 1] > k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; +``` + +### **Go** + +```go +func chalkReplacer(chalk []int, k int) int { + n := len(chalk) + preSum := make([]int, n+1) + for i := 0; i < n; i++ { + preSum[i+1] = preSum[i] + chalk[i] + } + k %= preSum[n] + left, right := 0, n-1 + for left < right { + mid := left + ((right - left) >> 1) + if preSum[mid+1] > k { + right = mid + } else { + left = mid + 1 + } + } + return left +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1895.leetcode1895 Largest Magic Square-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1895.leetcode1895 Largest Magic Square-zh.md" new file mode 100644 index 00000000..22a61cc8 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1895.leetcode1895 Largest Magic Square-zh.md" @@ -0,0 +1,71 @@ +# [1895. 最大的幻方](https://leetcode-cn.com/problems/largest-magic-square) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1895.Largest%20Magic%20Square/README_EN.md) + +## 题目描述 + + + +

    一个 k x k 的 幻方 指的是一个 k x k 填满整数的方格阵,且每一行、每一列以及两条对角线的和 全部相等 。幻方中的整数 不需要互不相同 。显然,每个 1 x 1 的方格都是一个幻方。

    + +

    给你一个 m x n 的整数矩阵 grid ,请你返回矩阵中 最大幻方 的 尺寸 (即边长 k)。

    + +

     

    + +

    示例 1:

    + +
    输入:grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
    +输出:3
    +解释:最大幻方尺寸为 3 。
    +每一行,每一列以及两条对角线的和都等于 12 。
    +- 每一行的和:5+1+6 = 5+4+3 = 2+7+3 = 12
    +- 每一列的和:5+5+2 = 1+4+7 = 6+3+3 = 12
    +- 对角线的和:5+4+3 = 6+4+2 = 12
    +
    + +

    示例 2:

    + +
    输入:grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
    +输出:2
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 1 <= m, n <= 50
    • +
    • 1 <= grid[i][j] <= 106
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1896.leetcode1896 Minimum Cost to Change the Final Value of Expression-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1896.leetcode1896 Minimum Cost to Change the Final Value of Expression-zh.md" new file mode 100644 index 00000000..bd6292c6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1896.leetcode1896 Minimum Cost to Change the Final Value of Expression-zh.md" @@ -0,0 +1,96 @@ +# [1896. 反转表达式值的最少操作次数](https://leetcode-cn.com/problems/minimum-cost-to-change-the-final-value-of-expression) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1896.Minimum%20Cost%20to%20Change%20the%20Final%20Value%20of%20Expression/README_EN.md) + +## 题目描述 + + + +

    给你一个 有效的 布尔表达式,用字符串 expression 表示。这个字符串包含字符 '1''0''&'(按位  运算),'|'(按位  运算),'(' 和 ')' 。

    + +
      +
    • 比方说,"()1|1" 和 "(1)&()" 不是有效 布尔表达式。而 "1", "(((1))|(0))" 和 "1|(0&(1))" 是 有效 布尔表达式。
    • +
    + +

    你的目标是将布尔表达式的  反转 (也就是将 0 变为 1 ,或者将 1 变为 0),请你返回达成目标需要的 最少操作 次数。

    + +
      +
    • 比方说,如果表达式 expression = "1|1|(0&0)&1" ,它的  为 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1 。我们想要执行操作将 新的 表达式的值变成 0 。
    • +
    + +

    可执行的 操作 如下:

    + +
      +
    • 将一个 '1' 变成一个 '0' 。
    • +
    • 将一个 '0' 变成一个 '1' 。
    • +
    • 将一个 '&' 变成一个 '|' 。
    • +
    • 将一个 '|' 变成一个 '&' 。
    • +
    + +

    注意:'&' 的 运算优先级 与 '|' 相同 。计算表达式时,括号优先级 最高 ,然后按照 从左到右 的顺序运算。

    + +

     

    + +

    示例 1:

    + +
    输入:expression = "1&(0|1)"
    +输出:1
    +解释:我们可以将 "1&(0|1)" 变成 "1&(0&1)" ,执行的操作为将一个 '|' 变成一个 '&' ,执行了 1 次操作。
    +新表达式的值为 0 。
    +
    + +

    示例 2:

    + +
    输入:expression = "(0&0)&(0&0&0)"
    +输出:3
    +解释:我们可以将 "(0&0)&(0&0&0)" 变成 "(0|1)|(0&0&0)" ,执行了 3 次操作。
    +新表达式的值为 1 。
    +
    + +

    示例 3:

    + +
    输入:expression = "(0|(1|0&1))"
    +输出:1
    +解释:我们可以将 "(0|(1|0&1))" 变成 "(0|(0|0&1))" ,执行了 1 次操作。
    +新表达式的值为 0 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= expression.length <= 105
    • +
    • expression 只包含 '1''0''&''|''(' 和 ')'
    • +
    • 所有括号都有与之匹配的对应括号。
    • +
    • 不会有空的括号(也就是说 "()" 不是 expression 的子字符串)。
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1897.leetcode1897 Redistribute Characters to Make All Strings Equal-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1897.leetcode1897 Redistribute Characters to Make All Strings Equal-zh.md" new file mode 100644 index 00000000..e419c25c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1897.leetcode1897 Redistribute Characters to Make All Strings Equal-zh.md" @@ -0,0 +1,119 @@ +# [1897. 重新分配字符使所有字符串都相等](https://leetcode-cn.com/problems/redistribute-characters-to-make-all-strings-equal) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1897.Redistribute%20Characters%20to%20Make%20All%20Strings%20Equal/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串数组 words(下标 从 0 开始 计数)。

    + +

    在一步操作中,需先选出两个 不同 下标 ij,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。

    + +

    如果执行任意步操作可以使 words 中的每个字符串都相等,返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    输入:words = ["abc","aabc","bc"]
    +输出:true
    +解释:words[1] 中的第一个 'a' 移动到 words[2] 的最前面。
    +使 words[1] = "abc" 且 words[2] = "abc" 。
    +所有字符串都等于 "abc" ,所以返回 true 。
    +
    + +

    示例 2:

    + +
    输入:words = ["ab","a"]
    +输出:false
    +解释:执行操作无法使所有字符串都相等。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= words.length <= 100
    • +
    • 1 <= words[i].length <= 100
    • +
    • words[i] 由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def makeEqual(self, words: List[str]) -> bool: + counter = collections.Counter() + for word in words: + for c in word: + counter[c] += 1 + n = len(words) + for count in counter.values(): + if count % n != 0: + return False + return True +``` + +### **Java** + + + +```java +class Solution { + public boolean makeEqual(String[] words) { + int[] counter = new int[26]; + for (String word : words) { + for (char c : word.toCharArray()) { + ++counter[c - 'a']; + } + } + int n = words.length; + for (int i = 0; i < 26; ++i) { + if (counter[i] % n != 0) { + return false; + } + } + return true; + } +} +``` + +### **TypeScript** + +```ts +function makeEqual(words: string[]): boolean { + let n = words.length; + let letters = new Array(26).fill(0); + for (let word of words) { + for (let i = 0; i < word.length; ++i) { + ++letters[word.charCodeAt(i) - 97]; + } + } + + for (let i = 0; i < letters.length; ++i) { + if (letters[i] % n != 0) { + return false; + } + } + return true; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1898.leetcode1898 Maximum Number of Removable Characters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1898.leetcode1898 Maximum Number of Removable Characters-zh.md" new file mode 100644 index 00000000..e856c5c2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1898.leetcode1898 Maximum Number of Removable Characters-zh.md" @@ -0,0 +1,232 @@ +# [1898. 可移除字符的最大数目](https://leetcode-cn.com/problems/maximum-number-of-removable-characters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1898.Maximum%20Number%20of%20Removable%20Characters/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 sp ,其中 ps 的一个 子序列 。同时,给你一个元素 互不相同 且下标 从 0 开始 计数的整数数组 removable ,该数组是 s 中下标的一个子集(s 的下标也 从 0 开始 计数)。

    + +

    请你找出一个整数 k0 <= k <= removable.length),选出 removable 中的 k 个下标,然后从 s 中移除这些下标对应的 k 个字符。整数 k 需满足:在执行完上述步骤后, p 仍然是 s 的一个 子序列 。更正式的解释是,对于每个 0 <= i < k ,先标记出位于 s[removable[i]] 的字符,接着移除所有标记过的字符,然后检查 p 是否仍然是 s 的一个子序列。

    + +

    返回你可以找出的 最大 k ,满足在移除字符后 p 仍然是 s 的一个子序列。

    + +

    字符串的一个 子序列 是一个由原字符串生成的新字符串,生成过程中可能会移除原字符串中的一些字符(也可能不移除)但不改变剩余字符之间的相对顺序。

    + +

     

    + +

    示例 1:

    + +
    +输入:s = "abcacb", p = "ab", removable = [3,1,0]
    +输出:2
    +解释:在移除下标 3 和 1 对应的字符后,"abcacb" 变成 "accb" 。
    +"ab" 是 "accb" 的一个子序列。
    +如果移除下标 3、1 和 0 对应的字符后,"abcacb" 变成 "ccb" ,那么 "ab" 就不再是 s 的一个子序列。
    +因此,最大的 k 是 2 。
    +
    + +

    示例 2:

    + +
    +输入:s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]
    +输出:1
    +解释:在移除下标 3 对应的字符后,"abcbddddd" 变成 "abcddddd" 。
    +"abcd" 是 "abcddddd" 的一个子序列。
    +
    + +

    示例 3:

    + +
    +输入:s = "abcab", p = "abc", removable = [0,1,2,3,4]
    +输出:0
    +解释:如果移除数组 removable 的第一个下标,"abc" 就不再是 s 的一个子序列。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= p.length <= s.length <= 105
    • +
    • 0 <= removable.length < s.length
    • +
    • 0 <= removable[i] < s.length
    • +
    • ps 的一个 子字符串
    • +
    • sp 都由小写英文字母组成
    • +
    • removable 中的元素 互不相同
    • +
    + +## 解法 + + + +“二分法 + 判断子序列”实现。 + + + +### **Python3** + + + +```python +class Solution: + def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int: + def check(mid): + m, n, i, j = len(s), len(p), 0, 0 + ids = set(removable[:mid]) + while i < m and j < n: + if i not in ids and s[i] == p[j]: + j += 1 + i += 1 + return j == n + + left, right = 0, len(removable) + while left < right: + mid = (left + right + 1) >> 1 + if check(mid): + left = mid + else: + right = mid - 1 + return left +``` + +### **Java** + + + +```java +class Solution { + public int maximumRemovals(String s, String p, int[] removable) { + int left = 0, right = removable.length; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(s, p, removable, mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(String s, String p, int[] removable, int mid) { + int m = s.length(), n = p.length(), i = 0, j = 0; + Set ids = new HashSet<>(); + for (int k = 0; k < mid; ++k) { + ids.add(removable[k]); + } + while (i < m && j < n) { + if (!ids.contains(i) && s.charAt(i) == p.charAt(j)) { + ++j; + } + ++i; + } + return j == n; + } +} +``` + +### **TypeScript** + +```ts +function maximumRemovals(s: string, p: string, removable: number[]): number { + let left = 0, right = removable.length; + while (left < right) { + let mid = (left + right + 1) >> 1; + if (isSub(s, p, new Set(removable.slice(0, mid)))) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; + +function isSub(str: string, sub: string, idxes: Set): boolean { + let m = str.length, n = sub.length; + let i = 0, j = 0; + while (i < m && j < n) { + if (!idxes.has(i) && str.charAt(i) == sub.charAt(j)) { + ++j; + } + ++i; + } + return j == n; +} +``` + +### **C++** + +```cpp +class Solution { +public: + int maximumRemovals(string s, string p, vector& removable) { + int left = 0, right = removable.size(); + while (left < right) { + int mid = left + right + 1 >> 1; + if (check(s, p, removable, mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + bool check(string s, string p, vector& removable, int mid) { + int m = s.size(), n = p.size(), i = 0, j = 0; + unordered_set ids; + for (int k = 0; k < mid; ++k) { + ids.insert(removable[k]); + } + while (i < m && j < n) { + if (ids.count(i) == 0 && s[i] == p[j]) { + ++j; + } + ++i; + } + return j == n; + } +}; +``` + +### **Go** + +```go +func maximumRemovals(s string, p string, removable []int) int { + left, right := 0, len(removable) + for left < right { + mid := (left + right + 1) >> 1 + if check(s, p, removable, mid) { + left = mid + } else { + right = mid - 1 + } + } + return left +} + +func check(s string, p string, removable []int, mid int) bool { + m, n, i, j := len(s), len(p), 0, 0 + ids := make(map[int]bool) + for k := 0; k < mid; k++ { + ids[removable[k]] = true + } + for i < m && j < n { + if !ids[i] && s[i] == p[j] { + j++ + } + i++ + } + return j == n +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1899.leetcode1899 Merge Triplets to Form Target Triplet-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1899.leetcode1899 Merge Triplets to Form Target Triplet-zh.md" new file mode 100644 index 00000000..4e493834 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1899.leetcode1899 Merge Triplets to Form Target Triplet-zh.md" @@ -0,0 +1,140 @@ +# [1899. 合并若干三元组以形成目标三元组](https://leetcode-cn.com/problems/merge-triplets-to-form-target-triplet) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1800-1899/1899.Merge%20Triplets%20to%20Form%20Target%20Triplet/README_EN.md) + +## 题目描述 + + + +

    三元组 是一个由三个整数组成的数组。给你一个二维整数数组 triplets ,其中 triplets[i] = [ai, bi, ci] 表示第 i三元组 。同时,给你一个整数数组 target = [x, y, z] ,表示你想要得到的 三元组

    + +

    为了得到 target ,你需要对 triplets 执行下面的操作 任意次(可能 次):

    + +
      +
    • 选出两个下标(下标 从 0 开始 计数)iji != j),并 更新 triplets[j][max(ai, aj), max(bi, bj), max(ci, cj)] 。 +
        +
      • 例如,triplets[i] = [2, 5, 3]triplets[j] = [1, 7, 5]triplets[j] 将会更新为 [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]
      • +
      +
    • +
    + +

    如果通过以上操作我们可以使得目标 三元组 target 成为 triplets 的一个 元素 ,则返回 true ;否则,返回 false

    + +

     

    + +

    示例 1:

    + +
    +输入:triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
    +输出:true
    +解释:执行下述操作:
    +- 选择第一个和最后一个三元组 [[2,5,3],[1,8,4],[1,7,5]] 。更新最后一个三元组为 [max(2,1), max(5,7), max(3,5)] = [2,7,5] 。triplets = [[2,5,3],[1,8,4],[2,7,5]]
    +目标三元组 [2,7,5] 现在是 triplets 的一个元素。
    +
    + +

    示例 2:

    + +
    +输入:triplets = [[1,3,4],[2,5,8]], target = [2,5,8]
    +输出:true
    +解释:目标三元组 [2,5,8] 已经是 triplets 的一个元素。
    +
    + +

    示例 3:

    + +
    +输入:triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]
    +输出:true
    +解释:执行下述操作:
    +- 选择第一个和第三个三元组 [[2,5,3],[2,3,4],[1,2,5],[5,2,3]] 。更新第三个三元组为 [max(2,1), max(5,2), max(3,5)] = [2,5,5] 。triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]] 。
    +- 选择第三个和第四个三元组 [[2,5,3],[2,3,4],[2,5,5],[5,2,3]] 。更新第四个三元组为 [max(2,5), max(5,2), max(5,3)] = [5,5,5] 。triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]] 。
    +目标三元组 [5,5,5] 现在是 triplets 的一个元素。
    +
    + +

    示例 4:

    + +
    +输入:triplets = [[3,4,5],[4,5,6]], target = [3,2,5]
    +输出:false
    +解释:无法得到 [3,2,5] ,因为 triplets 不含 2 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= triplets.length <= 105
    • +
    • triplets[i].length == target.length == 3
    • +
    • 1 <= ai, bi, ci, x, y, z <= 1000
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: + maxA = maxB = maxC = 0 + tA, tB, tC = target + for a, b, c in triplets: + if a <= tA and b <= tB and c <= tC: + maxA = max(maxA, a) + maxB = max(maxB, b) + maxC = max(maxC, c) + return (maxA, maxB, maxC) == (tA, tB, tC) +``` + +### **Java** + + + +```java +class Solution { + public boolean mergeTriplets(int[][] triplets, int[] target) { + int maxA = 0, maxB = 0, maxC = 0; + for (int[] triplet : triplets) { + int a = triplet[0], b = triplet[1], c = triplet[2]; + if (a <= target[0] && b <= target[1] && c <= target[2]) { + maxA = Math.max(maxA, a); + maxB = Math.max(maxB, b); + maxC = Math.max(maxC, c); + } + } + return maxA == target[0] && maxB == target[1] && maxC == target[2]; + } +} +``` + +### **TypeScript** + +```ts +function mergeTriplets(triplets: number[][], target: number[]): boolean { + let [x, y, z] = target; // 目标值 + let [i, j, k] = [0, 0, 0]; // 最大值 + for (let triplet of triplets) { + let [a, b, c] = triplet; // 当前值 + if (a <= x && b <= y && c <= z) { + i = Math.max(i, a); + j = Math.max(j, b); + k = Math.max(k, c); + } + } + return i == x && j == y && k == z; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1900.leetcode1900 The Earliest and Latest Rounds Where Players Compete-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1900.leetcode1900 The Earliest and Latest Rounds Where Players Compete-zh.md" new file mode 100644 index 00000000..cccd0061 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1900.leetcode1900 The Earliest and Latest Rounds Where Players Compete-zh.md" @@ -0,0 +1,92 @@ +# [1900. 最佳运动员的比拼回合](https://leetcode-cn.com/problems/the-earliest-and-latest-rounds-where-players-compete) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1900.The%20Earliest%20and%20Latest%20Rounds%20Where%20Players%20Compete/README_EN.md) + +## 题目描述 + + + +

    n 名运动员参与一场锦标赛,所有运动员站成一排,并根据 最开始的 站位从 1n 编号(运动员 1 是这一排中的第一个运动员,运动员 2 是第二个运动员,依此类推)。

    + +

    锦标赛由多个回合组成(从回合 1 开始)。每一回合中,这一排从前往后数的第 i 名运动员需要与从后往前数的第 i 名运动员比拼,获胜者将会进入下一回合。如果当前回合中运动员数目为奇数,那么中间那位运动员将轮空晋级下一回合。

    + +
      +
    • 例如,当前回合中,运动员 1, 2, 4, 6, 7 站成一排 +
        +
      • 运动员 1 需要和运动员 7 比拼
      • +
      • 运动员 2 需要和运动员 6 比拼
      • +
      • 运动员 4 轮空晋级下一回合
      • +
      +
    • +
    + +

    每回合结束后,获胜者将会基于最开始分配给他们的原始顺序(升序)重新排成一排。

    + +

    编号为 firstPlayersecondPlayer 的运动员是本场锦标赛中的最佳运动员。在他们开始比拼之前,完全可以战胜任何其他运动员。而任意两个其他运动员进行比拼时,其中任意一个都有获胜的可能,因此你可以 裁定 谁是这一回合的获胜者。

    + +

    给你三个整数 nfirstPlayersecondPlayer 。返回一个由两个值组成的整数数组,分别表示两位最佳运动员在本场锦标赛中比拼的 最早 回合数和 最晚 回合数。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 11, firstPlayer = 2, secondPlayer = 4
    +输出:[3,4]
    +解释:
    +一种能够产生最早回合数的情景是:
    +回合 1:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
    +回合 2:2, 3, 4, 5, 6, 11
    +回合 3:2, 3, 4
    +一种能够产生最晚回合数的情景是:
    +回合 1:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
    +回合 2:1, 2, 3, 4, 5, 6
    +回合 3:1, 2, 4
    +回合 4:2, 4
    +
    + +

    示例 2:

    + +
    输入:n = 5, firstPlayer = 1, secondPlayer = 5
    +输出:[1,1]
    +解释:两名最佳运动员 1 和 5 将会在回合 1 进行比拼。
    +不存在使他们在其他回合进行比拼的可能。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= n <= 28
    • +
    • 1 <= firstPlayer < secondPlayer <= n
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1901.leetcode1901 Find a Peak Element II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1901.leetcode1901 Find a Peak Element II-zh.md" new file mode 100644 index 00000000..8a7baecf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1901.leetcode1901 Find a Peak Element II-zh.md" @@ -0,0 +1,78 @@ +# [1901. Find a Peak Element II](https://leetcode-cn.com/problems/find-a-peak-element-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1901.Find%20a%20Peak%20Element%20II/README_EN.md) + +## 题目描述 + + + +

    A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.

    + +

    Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].

    + +

    You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.

    + +

    You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: mat = [[1,4],[3,2]]
    +Output: [0,1]
    +Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.
    +
    + +

    Example 2:

    + +

    + +
    +Input: mat = [[10,20,15],[21,30,14],[7,16,32]]
    +Output: [1,1]
    +Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • m == mat.length
    • +
    • n == mat[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • 1 <= mat[i][j] <= 105
    • +
    • No two adjacent cells are equal.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1902.leetcode1902 Depth of BST Given Insertion Order-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1902.leetcode1902 Depth of BST Given Insertion Order-zh.md" new file mode 100644 index 00000000..c44e3278 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1902.leetcode1902 Depth of BST Given Insertion Order-zh.md" @@ -0,0 +1,134 @@ +# [1902. Depth of BST Given Insertion Order](https://leetcode-cn.com/problems/depth-of-bst-given-insertion-order) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1902.Depth%20of%20BST%20Given%20Insertion%20Order/README_EN.md) + +## 题目描述 + + + +

    You are given a 0-indexed integer array order of length n, a permutation of integers from 1 to n representing the order of insertion into a binary search tree.

    + + + +

    A binary search tree is defined as follows:

    + + + +
      +
    • The left subtree of a node contains only nodes with keys less than the node's key.
    • +
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • +
    • Both the left and right subtrees must also be binary search trees.
    • +
    + + + +

    The binary search tree is constructed as follows:

    + + + +
      +
    • order[0] will be the root of the binary search tree.
    • +
    • All subsequent elements are inserted as the child of any existing node such that the binary search tree properties hold.
    • +
    + + + +

    Return the depth of the binary search tree.

    + + + +

    A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: order = [2,1,4,3]
    +
    +Output: 3
    +
    +Explanation: The binary search tree has a depth of 3 with path 2->3->4.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: order = [2,1,3,4]
    +
    +Output: 3
    +
    +Explanation: The binary search tree has a depth of 3 with path 2->3->4.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: order = [1,2,3,4]
    +
    +Output: 4
    +
    +Explanation: The binary search tree has a depth of 4 with path 1->2->3->4.
    +
    +
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == order.length
    • +
    • 1 <= n <= 105
    • +
    • order is a permutation of integers between 1 and n.
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1903.leetcode1903 Largest Odd Number in String-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1903.leetcode1903 Largest Odd Number in String-zh.md" new file mode 100644 index 00000000..8d5f7df2 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1903.leetcode1903 Largest Odd Number in String-zh.md" @@ -0,0 +1,143 @@ +# [1903. 字符串中的最大奇数](https://leetcode-cn.com/problems/largest-odd-number-in-string) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1903.Largest%20Odd%20Number%20in%20String/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 num ,表示一个大整数。请你在字符串 num 的所有 非空子字符串 中找出 值最大的奇数 ,并以字符串形式返回。如果不存在奇数,则返回一个空字符串 ""

    + +

    子字符串 是字符串中的一个连续的字符序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:num = "52"
    +输出:"5"
    +解释:非空子字符串仅有 "5"、"2" 和 "52" 。"5" 是其中唯一的奇数。
    +
    + +

    示例 2:

    + +
    +输入:num = "4206"
    +输出:""
    +解释:在 "4206" 中不存在奇数。
    +
    + +

    示例 3:

    + +
    +输入:num = "35427"
    +输出:"35427"
    +解释:"35427" 本身就是一个奇数。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= num.length <= 105
    • +
    • num 仅由数字组成且不含前导零
    • +
    + + +## 解法 + + + +从后往前遍历字符串中的每个数字,遇到奇数则直接返回结果。若遍历结束仍未遇到奇数,返回空字符串。 + + + +### **Python3** + + + +```python +class Solution: + def largestOddNumber(self, num: str) -> str: + for i in range(len(num) - 1, -1, -1): + if (int(num[i]) & 1) == 1: + return num[:i + 1] + return '' +``` + +### **Java** + + + +```java +class Solution { + public String largestOddNumber(String num) { + for (int i = num.length() - 1; i >= 0; --i) { + int c = num.charAt(i) - '0'; + if ((c & 1) == 1) { + return num.substring(0, i + 1); + } + } + return ""; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} num + * @return {string} + */ + var largestOddNumber = function(num) { + let n = num.length; + for (let j = n - 1; j >= 0; j--) { + if (num.charAt(j) & 1 == 1) { + return num.slice(0, j+1); + } + } + return ''; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + string largestOddNumber(string num) { + for (int i = num.size() - 1; i >= 0; --i) { + int c = num[i] - '0'; + if ((c & 1) == 1) { + return num.substr(0, i + 1); + } + } + return ""; + } +}; +``` + +### **Go** + +```go +func largestOddNumber(num string) string { + for i := len(num) - 1; i >= 0; i-- { + c := num[i] - '0' + if (c & 1) == 1 { + return num[:i+1] + } + } + return "" +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1904.leetcode1904 The Number of Full Rounds You Have Played-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1904.leetcode1904 The Number of Full Rounds You Have Played-zh.md" new file mode 100644 index 00000000..1456ff03 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1904.leetcode1904 The Number of Full Rounds You Have Played-zh.md" @@ -0,0 +1,188 @@ +# [1904. 你完成的完整对局数](https://leetcode-cn.com/problems/the-number-of-full-rounds-you-have-played) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1904.The%20Number%20of%20Full%20Rounds%20You%20Have%20Played/README_EN.md) + +## 题目描述 + + + +

    一款新的在线电子游戏在近期发布,在该电子游戏中,以 刻钟 为周期规划若干时长为 15 分钟 的游戏对局。这意味着,在 HH:00HH:15HH:30HH:45 ,将会开始一个新的对局,其中 HH 用一个从 0023 的整数表示。游戏中使用 24 小时制的时钟 ,所以一天中最早的时间是 00:00 ,最晚的时间是 23:59

    + +

    给你两个字符串 startTimefinishTime ,均符合 "HH:MM" 格式,分别表示你 进入退出 游戏的确切时间,请计算在整个游戏会话期间,你完成的 完整对局的对局数

    + +
      +
    • 例如,如果 startTime = "05:20"finishTime = "05:59" ,这意味着你仅仅完成从 05:3005:45 这一个完整对局。而你没有完成从 05:1505:30 的完整对局,因为你是在对局开始后进入的游戏;同时,你也没有完成从 05:4506:00 的完整对局,因为你是在对局结束前退出的游戏。
    • +
    + +

    如果 finishTime 早于 startTime ,这表示你玩了个通宵(也就是从 startTime 到午夜,再从午夜到 finishTime)。

    + +

    假设你是从 startTime 进入游戏,并在 finishTime 退出游戏,请计算并返回你完成的 完整对局的对局数

    + +

     

    + +

    示例 1:

    + +
    +输入:startTime = "12:01", finishTime = "12:44"
    +输出:1
    +解释:你完成了从 12:15 到 12:30 的一个完整对局。
    +你没有完成从 12:00 到 12:15 的完整对局,因为你是在对局开始后的 12:01 进入的游戏。
    +你没有完成从 12:30 到 12:45 的完整对局,因为你是在对局结束前的 12:44 退出的游戏。
    +
    + +

    示例 2:

    + +
    +输入:startTime = "20:00", finishTime = "06:00"
    +输出:40
    +解释:你完成了从 20:00 到 00:00 的 16 个完整的对局,以及从 00:00 到 06:00 的 24 个完整的对局。
    +16 + 24 = 40
    +
    + +

    示例 3:

    + +
    +输入:startTime = "00:00", finishTime = "23:59"
    +输出:95
    +解释:除最后一个小时你只完成了 3 个完整对局外,其余每个小时均完成了 4 场完整对局。
    +
    + +

     

    + +

    提示:

    + +
      +
    • startTimefinishTime 的格式为 HH:MM
    • +
    • 00 <= HH <= 23
    • +
    • 00 <= MM <= 59
    • +
    • startTimefinishTime 不相等
    • +
    + + +## 解法 + + + +转换为“分钟”进行计算。 + + + +### **Python3** + + + +```python +class Solution: + def numberOfRounds(self, startTime: str, finishTime: str) -> int: + def get(s: str) -> int: + return int(s[:2]) * 60 + int(s[3:]) + + start, finish = get(startTime), get(finishTime) + if start > finish: + finish += 24 * 60 + start, finish = (start + 14) // 15, finish // 15 + return max(0, finish - start) +``` + +### **Java** + + + +```java +class Solution { + public int numberOfRounds(String startTime, String finishTime) { + int start = get(startTime), finish = get(finishTime); + if (start > finish) { + finish += 24 * 60; + } + start = (start + 14) / 15; + finish /= 15; + return Math.max(0, finish - start); + } + + private int get(String s) { + return Integer.parseInt(s.substring(0, 2)) * 60 + Integer.parseInt(s.substring(3)); + } +} +``` + +### **JavaScript** + +```js +/** + * @param {string} startTime + * @param {string} finishTime + * @return {number} + */ + var numberOfRounds = function(startTime, finishTime) { + let m1 = toMinutes(startTime), m2 = toMinutes(finishTime); + + if (m1 > m2) { + m2 += 24 * 60; + } + + let ans = Math.floor(m2 / 15) - Math.ceil(m1 / 15); + return ans < 0 ? 0 : ans; +}; + +function toMinutes(time) { + let [h, m] = time.split(':'); + return Number(h) * 60 + Number(m); +} +``` + +### **C++** + +```cpp +class Solution { +public: + int numberOfRounds(string startTime, string finishTime) { + int start = get(startTime), finish = get(finishTime); + if (start > finish) { + finish += 24 * 60; + } + start = (start + 14) / 15; + finish /= 15; + return max(0, finish - start); + } + +private: + int get(string s) { + int a, b; + sscanf(s.c_str(), "%d:%d", &a, &b); + return a * 60 + b; + } +}; +``` + +### **Go** + +```go +func numberOfRounds(startTime string, finishTime string) int { + start, finish := get(startTime), get(finishTime) + if start > finish { + finish += 24 * 60 + } + start = (start + 14) / 15 + finish /= 15 + if start > finish { + return 0 + } + return finish - start + +} + +func get(s string) int { + var a, b int + fmt.Sscanf(s, "%d:%d", &a, &b) + return a*60 + b +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1905.leetcode1905 Count Sub Islands-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1905.leetcode1905 Count Sub Islands-zh.md" new file mode 100644 index 00000000..78cfce6d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1905.leetcode1905 Count Sub Islands-zh.md" @@ -0,0 +1,227 @@ +# [1905. 统计子岛屿](https://leetcode-cn.com/problems/count-sub-islands) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1905.Count%20Sub%20Islands/README_EN.md) + +## 题目描述 + + + +

    给你两个 m x n 的二进制矩阵 grid1 和 grid2 ,它们只包含 0 (表示水域)和 1 (表示陆地)。一个 岛屿 是由 四个方向 (水平或者竖直)上相邻的 1 组成的区域。任何矩阵以外的区域都视为水域。

    + +

    如果 grid2 的一个岛屿,被 grid1 的一个岛屿 完全 包含,也就是说 grid2 中该岛屿的每一个格子都被 grid1 中同一个岛屿完全包含,那么我们称 grid2 中的这个岛屿为 子岛屿 。

    + +

    请你返回 grid2 中 子岛屿 的 数目 。

    + +

     

    + +

    示例 1:

    + +
    输入:grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
    +输出:3
    +解释:如上图所示,左边为 grid1 ,右边为 grid2 。
    +grid2 中标红的 1 区域是子岛屿,总共有 3 个子岛屿。
    +
    + +

    示例 2:

    + +
    输入:grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
    +输出:2 
    +解释:如上图所示,左边为 grid1 ,右边为 grid2 。
    +grid2 中标红的 1 区域是子岛屿,总共有 2 个子岛屿。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid1.length == grid2.length
    • +
    • n == grid1[i].length == grid2[i].length
    • +
    • 1 <= m, n <= 500
    • +
    • grid1[i][j] 和 grid2[i][j] 都要么是 0 要么是 1 。
    • +
    + +## 解法 + + + +深度优先搜索。 + + + +### **Python3** + + + +```python +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + def dfs(grid1, grid2, i, j, m, n) -> bool: + res = grid1[i][j] == 1 + grid2[i][j] = 0 + for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]: + a, b = i + x, j + y + if a >= 0 and a < m and b >= 0 and b < n and grid2[a][b] == 1: + if not dfs(grid1, grid2, a, b, m, n): + res = False + return res + + m, n = len(grid1), len(grid1[0]) + count = 0 + for i in range(m): + for j in range(n): + if grid2[i][j] == 1 and dfs(grid1, grid2, i, j, m, n): + count += 1 + return count +``` + +### **Java** + + + +```java +class Solution { + private int[][] directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + + public int countSubIslands(int[][] grid1, int[][] grid2) { + int m = grid1.length, n = grid1[0].length; + int count = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid2[i][j] == 1 && dfs(grid1, grid2, i, j, m, n)) { + ++count; + } + } + } + return count; + } + + private boolean dfs(int[][] grid1, int[][] grid2, int i, int j, int m, int n) { + boolean res = grid1[i][j] == 1; + grid2[i][j] = 0; + + for (int[] direction : directions) { + int a = i + direction[0], b = j + direction[1]; + if (a >= 0 && a < m && b >= 0 && b < n && grid2[a][b] == 1) { + if (!dfs(grid1, grid2, a, b, m, n)) { + res = false; + } + } + } + return res; + } +} +``` + +### **TypeScript** + +```ts +function countSubIslands(grid1: number[][], grid2: number[][]): number { + let m = grid1.length, n = grid1[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid2[i][j] == 1 && dfs(grid1, grid2, i, j)) { + ++ans; + } + } + } + return ans; +}; + +function dfs(grid1: number[][], grid2: number[][], i: number, j: number): boolean { + let m = grid1.length, n = grid1[0].length; + let ans = true; + if (grid1[i][j] == 0) { + ans = false; + } + grid2[i][j] = 0; + for (let [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { + let x = i + dx, y = j + dy; + if (x < 0 || x > m - 1 || y < 0 || y > n - 1 || grid2[x][y] == 0) { + continue; + } + if (!dfs(grid1, grid2, x, y)) { + ans = false; + } + } + return ans; +} +``` + +### **C++** + +```cpp +class Solution { +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + int m = grid1.size(), n = grid1[0].size(); + int count = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid2[i][j] == 1 && dfs(grid1, grid2, i, j, m, n)) { + ++count; + } + } + } + return count; + } + +private: + vector> directions = {{0, 1}, {0, - 1}, {1, 0}, {-1, 0}}; + bool dfs(vector>& grid1, vector>& grid2, int i, int j, int m, int n) { + bool res = grid1[i][j] == 1; + grid2[i][j] = 0; + + for (auto direction : directions) { + int a = i + direction[0], b = j + direction[1]; + if (a >= 0 && a < m && b >= 0 && b < n && grid2[a][b] == 1) { + if (!dfs(grid1, grid2, a, b, m, n)) { + res = false; + } + } + } + return res; + } +}; +``` + +### **Go** + +```go +func countSubIslands(grid1 [][]int, grid2 [][]int) int { + m, n := len(grid1), len(grid1[0]) + count := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid2[i][j] == 1 && dfs(grid1, grid2, i, j, m, n) { + count++ + } + } + } + return count +} + +func dfs(grid1 [][]int, grid2 [][]int, i, j, m, n int) bool { + res := grid1[i][j] == 1 + grid2[i][j] = 0 + directions := [4][2]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} + for _, direction := range directions { + a, b := i+direction[0], j+direction[1] + if a >= 0 && a < m && b >= 0 && b < n && grid2[a][b] == 1 { + if !dfs(grid1, grid2, a, b, m, n) { + res = false + } + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1906.leetcode1906 Minimum Absolute Difference Queries-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1906.leetcode1906 Minimum Absolute Difference Queries-zh.md" new file mode 100644 index 00000000..a5b5365d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1906.leetcode1906 Minimum Absolute Difference Queries-zh.md" @@ -0,0 +1,260 @@ +# [1906. 查询差绝对值的最小值](https://leetcode-cn.com/problems/minimum-absolute-difference-queries) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1906.Minimum%20Absolute%20Difference%20Queries/README_EN.md) + +## 题目描述 + + + +

    一个数组 a 的 差绝对值的最小值 定义为:0 <= i < j < a.length 且 a[i] != a[j] 的 |a[i] - a[j]|最小值。如果 a 中所有元素都 相同 ,那么差绝对值的最小值为 -1 。

    + +
      +
    • 比方说,数组 [5,2,3,7,2] 差绝对值的最小值是 |2 - 3| = 1 。注意答案不为 0 ,因为 a[i] 和 a[j] 必须不相等。
    • +
    + +

    给你一个整数数组 nums 和查询数组 queries ,其中 queries[i] = [li, ri] 。对于每个查询 i ,计算 子数组 nums[li...ri] 中 差绝对值的最小值 ,子数组 nums[li...ri] 包含 nums 数组(下标从 0 开始)中下标在 li 和 ri 之间的所有元素(包含 li 和 ri 在内)。

    + +

    请你返回 ans 数组,其中 ans[i] 是第 i 个查询的答案。

    + +

    子数组 是一个数组中连续的一段元素。

    + +

    |x| 的值定义为:

    + +
      +
    • 如果 x >= 0 ,那么值为 x 。
    • +
    • 如果 x < 0 ,那么值为 -x 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
    +输出:[2,1,4,1]
    +解释:查询结果如下:
    +- queries[0] = [0,1]:子数组是 [1,3] ,差绝对值的最小值为 |1-3| = 2 。
    +- queries[1] = [1,2]:子数组是 [3,4] ,差绝对值的最小值为 |3-4| = 1 。
    +- queries[2] = [2,3]:子数组是 [4,8] ,差绝对值的最小值为 |4-8| = 4 。
    +- queries[3] = [0,3]:子数组是 [1,3,4,8] ,差的绝对值的最小值为 |3-4| = 1 。
    +
    + +

    示例 2:

    + +
    +输入:nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
    +输出:[-1,1,1,3]
    +解释:查询结果如下:
    +- queries[0] = [2,3]:子数组是 [2,2] ,差绝对值的最小值为 -1 ,因为所有元素相等。
    +- queries[1] = [0,2]:子数组是 [4,5,2] ,差绝对值的最小值为 |4-5| = 1 。
    +- queries[2] = [0,5]:子数组是 [4,5,2,2,7,10] ,差绝对值的最小值为 |4-5| = 1 。
    +- queries[3] = [3,5]:子数组是 [2,7,10] ,差绝对值的最小值为 |7-10| = 3 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 100
    • +
    • 1 <= queries.length <= 2 * 104
    • +
    • 0 <= li < ri < nums.length
    • +
    + +## 解法 + + + +数组元素范围在 `[1,100]` 之间,对于每个区间 `[left, right]`,可以遍历整数 `1~100`,判断每个整数是否出现,求得差绝对值的最小值。 + +用前缀和 `preSum[i][j]` 表示数组前 i 个元素中包含整数 j 的个数,那么对于区间 `[left, right]`,如果 `preSum[right + 1][j] - preSum[left][j] > 0`,那么表示此区间存在整数 j。j 从 `1~100` 进行遍历,可以判断每个递增整数是否在区间中存在。 + + + +### **Python3** + + + +```python +class Solution: + def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: + m, n = len(nums), len(queries) + pre_sum = [[0] * 101 for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, 101): + t = 1 if nums[i - 1] == j else 0 + pre_sum[i][j] = pre_sum[i - 1][j] + t + + ans = [] + for i in range(n): + left, right = queries[i][0], queries[i][1] + 1 + t = float('inf') + last = -1 + for j in range(1, 101): + if pre_sum[right][j] - pre_sum[left][j] > 0: + if last != -1: + t = min(t, j - last) + last = j + if t == float('inf'): + t = -1 + ans.append(t) + return ans +``` + +### **Java** + + + +```java +class Solution { + public int[] minDifference(int[] nums, int[][] queries) { + int m = nums.length, n = queries.length; + int[][] preSum = new int[m + 1][101]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= 100; ++j) { + int t = nums[i - 1] == j ? 1 : 0; + preSum[i][j] = preSum[i - 1][j] + t; + } + } + + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int left = queries[i][0], right = queries[i][1] + 1; + int t = Integer.MAX_VALUE; + int last = -1; + for (int j = 1; j <= 100; ++j) { + if (preSum[right][j] > preSum[left][j]) { + if (last != -1) { + t = Math.min(t, j - last); + } + last = j; + } + } + if (t == Integer.MAX_VALUE) { + t = -1; + } + ans[i] = t; + } + return ans; + } +} +``` + +### **TypeScript** + +```ts +function minDifference(nums: number[], queries: number[][]): number[] { + let m = nums.length, n = queries.length; + let max = 100; + // let max = Math.max(...nums); + let pre: number[][] = []; + pre.push(new Array(max + 1).fill(0)); + for (let i = 0; i < m; ++i) { + let num = nums[i]; + pre.push(pre[i].slice()); + pre[i + 1][num] += 1; + } + + let ans = []; + for (let [left, right] of queries) { + let last = -1; + let min = Infinity; + for (let j = 1; j < max + 1; ++j) { + if (pre[left][j] < pre[right + 1][j]) { + if (last != -1) { + min = Math.min(min, j - last); + } + last = j; + } + } + ans.push(min == Infinity ? -1 : min); + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector minDifference(vector& nums, vector>& queries) { + int m = nums.size(), n = queries.size(); + int preSum[m + 1][101]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= 100; ++j) { + int t = nums[i - 1] == j ? 1 : 0; + preSum[i][j] = preSum[i - 1][j] + t; + } + } + + vector ans(n); + for (int i = 0; i < n; ++i) { + int left = queries[i][0], right = queries[i][1] + 1; + int t = 101; + int last = -1; + for (int j = 1; j <= 100; ++j) { + if (preSum[right][j] > preSum[left][j]) { + if (last != -1) { + t = min(t, j - last); + } + last = j; + } + } + if (t == 101) { + t = -1; + } + ans[i] = t; + } + return ans; + } +}; +``` + +### **Go** + +```go +func minDifference(nums []int, queries [][]int) []int { + m, n := len(nums), len(queries) + preSum := make([][101]int, m+1) + for i := 1; i <= m; i++ { + for j := 1; j <= 100; j++ { + t := 0 + if nums[i-1] == j { + t = 1 + } + preSum[i][j] = preSum[i-1][j] + t + } + } + + ans := make([]int, n) + for i := 0; i < n; i++ { + left, right := queries[i][0], queries[i][1]+1 + t, last := 101, -1 + for j := 1; j <= 100; j++ { + if preSum[right][j]-preSum[left][j] > 0 { + if last != -1 { + if t > j-last { + t = j - last + } + } + last = j + } + } + if t == 101 { + t = -1 + } + ans[i] = t + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1907.leetcode1907 Count Salary Categories-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1907.leetcode1907 Count Salary Categories-zh.md" new file mode 100644 index 00000000..02998d40 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1907.leetcode1907 Count Salary Categories-zh.md" @@ -0,0 +1,78 @@ +# [1907. Count Salary Categories](https://leetcode-cn.com/problems/count-salary-categories) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1907.Count%20Salary%20Categories/README_EN.md) + +## 题目描述 + + + +

    Table: Accounts

    + +
    ++-------------+------+
    +| Column Name | Type |
    ++-------------+------+
    +| account_id  | int  |
    +| income      | int  |
    ++-------------+------+
    +account_id is the primary key for this table.
    +Each row contains information about the monthly income for one bank account.
    +
    + +

     

    + +

    Write an SQL query to report the number of bank accounts of each salary category. The salary categories are:

    + +
      +
    • "Low Salary": All the salaries strictly less than $20000.
    • +
    • "Average Salary": All the salaries in the inclusive range [$20000, $50000].
    • +
    • "High Salary": All the salaries strictly greater than $50000.
    • +
    + +

    The result table must contain all three categories. If there are no accounts in a category, then report 0. Return the result table in any order.

    + +

    The query result format is in the following example.

    + +

     

    + +
    +Accounts table:
    ++------------+--------+
    +| account_id | income |
    ++------------+--------+
    +| 3          | 108939 |
    +| 2          | 12747  |
    +| 8          | 87709  |
    +| 6          | 91796  |
    ++------------+--------+
    +
    +Result table:
    ++----------------+----------------+
    +| category       | accounts_count |
    ++----------------+----------------+
    +| Low Salary     | 1              |
    +| Average Salary | 0              |
    +| High Salary    | 3              |
    ++----------------+----------------+
    +
    +Low Salary: Account 2.
    +Average Salary: No accounts.
    +High Salary: Accounts 3, 6, and 8.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1908.leetcode1908 Game of Nim-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1908.leetcode1908 Game of Nim-zh.md" new file mode 100644 index 00000000..b7e102a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1908.leetcode1908 Game of Nim-zh.md" @@ -0,0 +1,133 @@ +# [1908. Game of Nim](https://leetcode-cn.com/problems/game-of-nim) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1908.Game%20of%20Nim/README_EN.md) + +## 题目描述 + + + +

    Alice and Bob take turns playing a game with Alice starting first.

    + + + +

    In this game, there are n piles of stones. On each player's turn, the player should remove any positive number of stones from a non-empty pile of his or her choice. The first player who cannot make a move loses, and the other player wins.

    + + + +

    Given an integer array piles, where piles[i] is the number of stones in the ith pile, return true if Alice wins, or false if Bob wins.

    + + + +

    Both Alice and Bob play optimally.

    + + + +

     

    + +

    Example 1:

    + + + +
    +
    +Input: piles = [1]
    +
    +Output: true
    +
    +Explanation: There is only one possible scenario:
    +
    +- On the first turn, Alice removes one stone from the first pile. piles = [0].
    +
    +- On the second turn, there are no stones left for Bob to remove. Alice wins.
    +
    +
    + + + +

    Example 2:

    + + + +
    +
    +Input: piles = [1,1]
    +
    +Output: false
    +
    +Explanation: It can be proven that Bob will always win. One possible scenario is:
    +
    +- On the first turn, Alice removes one stone from the first pile. piles = [0,1].
    +
    +- On the second turn, Bob removes one stone from the second pile. piles = [0,0].
    +
    +- On the third turn, there are no stones left for Alice to remove. Bob wins.
    +
    +
    + + + +

    Example 3:

    + + + +
    +
    +Input: piles = [1,2,3]
    +
    +Output: false
    +
    +Explanation: It can be proven that Bob will always win. One possible scenario is:
    +
    +- On the first turn, Alice removes three stones from the third pile. piles = [1,2,0].
    +
    +- On the second turn, Bob removes one stone from the second pile. piles = [1,1,0].
    +
    +- On the third turn, Alice removes one stone from the first pile. piles = [0,1,0].
    +
    +- On the fourth turn, Bob removes one stone from the second pile. piles = [0,0,0].
    +
    +- On the fifth turn, there are no stones left for Alice to remove. Bob wins.
    + + + +

     

    + +

    Constraints:

    + + + +
      +
    • n == piles.length
    • +
    • 1 <= n <= 7
    • +
    • 1 <= piles[i] <= 7
    • +
    + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1909.leetcode1909 Remove One Element to Make the Array Strictly Increasing-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1909.leetcode1909 Remove One Element to Make the Array Strictly Increasing-zh.md" new file mode 100644 index 00000000..d2dbf3ce --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1909.leetcode1909 Remove One Element to Make the Array Strictly Increasing-zh.md" @@ -0,0 +1,87 @@ +# [1909. 删除一个元素使数组严格递增](https://leetcode-cn.com/problems/remove-one-element-to-make-the-array-strictly-increasing) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1909.Remove%20One%20Element%20to%20Make%20the%20Array%20Strictly%20Increasing/README_EN.md) + +## 题目描述 + + + +

    给你一个下标从 0 开始的整数数组 nums ,如果 恰好 删除 一个 元素后,数组 严格递增 ,那么请你返回 true ,否则返回 false 。如果数组本身已经是严格递增的,请你也返回 true 。

    + +

    数组 nums 是 严格递增 的定义为:对于任意下标的 1 <= i < nums.length 都满足 nums[i - 1] < nums[i] 。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [1,2,10,5,7]
    +输出:true
    +解释:从 nums 中删除下标 2 处的 10 ,得到 [1,2,5,7] 。
    +[1,2,5,7] 是严格递增的,所以返回 true 。
    +
    + +

    示例 2:

    + +
    输入:nums = [2,3,1,2]
    +输出:false
    +解释:
    +[3,1,2] 是删除下标 0 处元素后得到的结果。
    +[2,1,2] 是删除下标 1 处元素后得到的结果。
    +[2,3,2] 是删除下标 2 处元素后得到的结果。
    +[2,3,1] 是删除下标 3 处元素后得到的结果。
    +没有任何结果数组是严格递增的,所以返回 false 。
    + +

    示例 3:

    + +
    输入:nums = [1,1,1]
    +输出:false
    +解释:删除任意元素后的结果都是 [1,1] 。
    +[1,1] 不是严格递增的,所以返回 false 。
    +
    + +

    示例 4:

    + +
    输入:nums = [1,2,3]
    +输出:true
    +解释:[1,2,3] 已经是严格递增的,所以返回 true 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= nums.length <= 1000
    • +
    • 1 <= nums[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1910.leetcode1910 Remove All Occurrences of a Substring-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1910.leetcode1910 Remove All Occurrences of a Substring-zh.md" new file mode 100644 index 00000000..96f39231 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1910.leetcode1910 Remove All Occurrences of a Substring-zh.md" @@ -0,0 +1,83 @@ +# [1910. 删除一个字符串中所有出现的给定子字符串](https://leetcode-cn.com/problems/remove-all-occurrences-of-a-substring) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1910.Remove%20All%20Occurrences%20of%20a%20Substring/README_EN.md) + +## 题目描述 + + + +

    给你两个字符串 s 和 part ,请你对 s 反复执行以下操作直到 所有 子字符串 part 都被删除:

    + +
      +
    • 找到 s 中 最左边 的子字符串 part ,并将它从 s 中删除。
    • +
    + +

    请你返回从 s 中删除所有 part 子字符串以后得到的剩余字符串。

    + +

    一个 子字符串 是一个字符串中连续的字符序列。

    + +

     

    + +

    示例 1:

    + +
    输入:s = "daabcbaabcbc", part = "abc"
    +输出:"dab"
    +解释:以下操作按顺序执行:
    +- s = "daabcbaabcbc" ,删除下标从 2 开始的 "abc" ,得到 s = "dabaabcbc" 。
    +- s = "dabaabcbc" ,删除下标从 4 开始的 "abc" ,得到 s = "dababc" 。
    +- s = "dababc" ,删除下标从 3 开始的 "abc" ,得到 s = "dab" 。
    +此时 s 中不再含有子字符串 "abc" 。
    +
    + +

    示例 2:

    + +
    输入:s = "axxxxyyyyb", part = "xy"
    +输出:"ab"
    +解释:以下操作按顺序执行:
    +- s = "axxxxyyyyb" ,删除下标从 4 开始的 "xy" ,得到 s = "axxxyyyb" 。
    +- s = "axxxyyyb" ,删除下标从 3 开始的 "xy" ,得到 s = "axxyyb" 。
    +- s = "axxyyb" ,删除下标从 2 开始的 "xy" ,得到 s = "axyb" 。
    +- s = "axyb" ,删除下标从 1 开始的 "xy" ,得到 s = "ab" 。
    +此时 s 中不再含有子字符串 "xy" 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • 1 <= part.length <= 1000
    • +
    • s​​​​​​ 和 part 只包小写英文字母。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1911.leetcode1911 Maximum Alternating Subsequence Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1911.leetcode1911 Maximum Alternating Subsequence Sum-zh.md" new file mode 100644 index 00000000..c57dc77c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1911.leetcode1911 Maximum Alternating Subsequence Sum-zh.md" @@ -0,0 +1,83 @@ +# [1911. 最大子序列交替和](https://leetcode-cn.com/problems/maximum-alternating-subsequence-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1911.Maximum%20Alternating%20Subsequence%20Sum/README_EN.md) + +## 题目描述 + + + +

    一个下标从 0 开始的数组的 交替和 定义为 偶数 下标处元素之  减去 奇数 下标处元素之  。

    + +
      +
    • 比方说,数组 [4,2,5,3] 的交替和为 (4 + 5) - (2 + 3) = 4 。
    • +
    + +

    给你一个数组 nums ,请你返回 nums 中任意子序列的 最大交替和 (子序列的下标 重新 从 0 开始编号)。

    + +
      +
    + +

    一个数组的 子序列 是从原数组中删除一些元素后(也可能一个也不删除)剩余元素不改变顺序组成的数组。比方说,[2,7,4] 是 [4,2,3,7,2,1,4] 的一个子序列(加粗元素),但是 [2,4,2] 不是。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [4,2,5,3]
    +输出:7
    +解释:最优子序列为 [4,2,5] ,交替和为 (4 + 5) - 2 = 7 。
    +
    + +

    示例 2:

    + +
    输入:nums = [5,6,7,8]
    +输出:8
    +解释:最优子序列为 [8] ,交替和为 8 。
    +
    + +

    示例 3:

    + +
    输入:nums = [6,2,1,2,4,5]
    +输出:10
    +解释:最优子序列为 [6,1,5] ,交替和为 (6 + 5) - 1 = 10 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 105
    • +
    • 1 <= nums[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1912.leetcode1912 Design Movie Rental System-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1912.leetcode1912 Design Movie Rental System-zh.md" new file mode 100644 index 00000000..cd2d5e6b --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1912.leetcode1912 Design Movie Rental System-zh.md" @@ -0,0 +1,97 @@ +# [1912. 设计电影租借系统](https://leetcode-cn.com/problems/design-movie-rental-system) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1912.Design%20Movie%20Rental%20System/README_EN.md) + +## 题目描述 + + + +

    你有一个电影租借公司和 n 个电影商店。你想要实现一个电影租借系统,它支持查询、预订和返还电影的操作。同时系统还能生成一份当前被借出电影的报告。

    + +

    所有电影用二维整数数组 entries 表示,其中 entries[i] = [shopi, moviei, pricei] 表示商店 shopi 有一份电影 moviei 的拷贝,租借价格为 pricei 。每个商店有 至多一份 编号为 moviei 的电影拷贝。

    + +

    系统需要支持以下操作:

    + +
      +
    • Search:找到拥有指定电影且 未借出 的商店中 最便宜的 5 个 。商店需要按照 价格 升序排序,如果价格相同,则 shopi 较小 的商店排在前面。如果查询结果少于 5 个商店,则将它们全部返回。如果查询结果没有任何商店,则返回空列表。
    • +
    • Rent:从指定商店借出指定电影,题目保证指定电影在指定商店 未借出 。
    • +
    • Drop:在指定商店返还 之前已借出 的指定电影。
    • +
    • Report:返回 最便宜的 5 部已借出电影 (可能有重复的电影 ID),将结果用二维列表 res 返回,其中 res[j] = [shopj, moviej] 表示第 j 便宜的已借出电影是从商店 shopj 借出的电影 moviej 。res 中的电影需要按 价格 升序排序;如果价格相同,则 shopj 较小 的排在前面;如果仍然相同,则 moviej 较小 的排在前面。如果当前借出的电影小于 5 部,则将它们全部返回。如果当前没有借出电影,则返回一个空的列表。
    • +
    + +

    请你实现 MovieRentingSystem 类:

    + +
      +
    • MovieRentingSystem(int n, int[][] entries) 将 MovieRentingSystem 对象用 n 个商店和 entries 表示的电影列表初始化。
    • +
    • List<Integer> search(int movie) 如上所述,返回 未借出 指定 movie 的商店列表。
    • +
    • void rent(int shop, int movie) 从指定商店 shop 借出指定电影 movie 。
    • +
    • void drop(int shop, int movie) 在指定商店 shop 返还之前借出的电影 movie 。
    • +
    • List<List<Integer>> report() 如上所述,返回最便宜的 已借出 电影列表。
    • +
    + +

    注意:测试数据保证 rent 操作中指定商店拥有 未借出 的指定电影,且 drop 操作指定的商店 之前已借出 指定电影。

    + +

     

    + +

    示例 1:

    + +
    +输入:
    +["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"]
    +[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]
    +输出:
    +[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]
    +
    +解释:
    +MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);
    +movieRentingSystem.search(1);  // 返回 [1, 0, 2] ,商店 1,0 和 2 有未借出的 ID 为 1 的电影。商店 1 最便宜,商店 0 和 2 价格相同,所以按商店编号排序。
    +movieRentingSystem.rent(0, 1); // 从商店 0 借出电影 1 。现在商店 0 未借出电影编号为 [2,3] 。
    +movieRentingSystem.rent(1, 2); // 从商店 1 借出电影 2 。现在商店 1 未借出的电影编号为 [1] 。
    +movieRentingSystem.report();   // 返回 [[0, 1], [1, 2]] 。商店 0 借出的电影 1 最便宜,然后是商店 1 借出的电影 2 。
    +movieRentingSystem.drop(1, 2); // 在商店 1 返还电影 2 。现在商店 1 未借出的电影编号为 [1,2] 。
    +movieRentingSystem.search(2);  // 返回 [0, 1] 。商店 0 和 1 有未借出的 ID 为 2 的电影。商店 0 最便宜,然后是商店 1 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 3 * 105
    • +
    • 1 <= entries.length <= 105
    • +
    • 0 <= shopi < n
    • +
    • 1 <= moviei, pricei <= 104
    • +
    • 每个商店 至多 有一份电影 moviei 的拷贝。
    • +
    • searchrentdrop 和 report 的调用 总共 不超过 105 次。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1913.leetcode1913 Maximum Product Difference Between Two Pairs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1913.leetcode1913 Maximum Product Difference Between Two Pairs-zh.md" new file mode 100644 index 00000000..7a6fddbf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1913.leetcode1913 Maximum Product Difference Between Two Pairs-zh.md" @@ -0,0 +1,99 @@ +# [1913. 两个数对之间的最大乘积差](https://leetcode-cn.com/problems/maximum-product-difference-between-two-pairs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1913.Maximum%20Product%20Difference%20Between%20Two%20Pairs/README_EN.md) + +## 题目描述 + + + +

    两个数对 (a, b)(c, d) 之间的 乘积差 定义为 (a * b) - (c * d)

    + +
      +
    • 例如,(5, 6)(2, 7) 之间的乘积差是 (5 * 6) - (2 * 7) = 16
    • +
    + +

    给你一个整数数组 nums ,选出四个 不同的 下标 wxyz ,使数对 (nums[w], nums[x])(nums[y], nums[z]) 之间的 乘积差 取到 最大值

    + +

    返回以这种方式取得的乘积差中的 最大值

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [5,6,2,7,4]
    +输出:34
    +解释:可以选出下标为 1 和 3 的元素构成第一个数对 (6, 7) 以及下标 2 和 4 构成第二个数对 (2, 4)
    +乘积差是 (6 * 7) - (2 * 4) = 34
    +
    + +

    示例 2:

    + +
    输入:nums = [4,2,5,9,7,4,8]
    +输出:64
    +解释:可以选出下标为 3 和 6 的元素构成第一个数对 (9, 8) 以及下标 1 和 5 构成第二个数对 (2, 4)
    +乘积差是 (9 * 8) - (2 * 4) = 64
    +
    + +

     

    + +

    提示:

    + +
      +
    • 4 <= nums.length <= 104
    • +
    • 1 <= nums[i] <= 104
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def maxProductDifference(self, nums: List[int]) -> int: + nums.sort() + return nums[-1] * nums[-2] - nums[0] * nums[1] +``` + +### **Java** + + + +```java +class Solution { + public int maxProductDifference(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxProductDifference = function(nums) { + nums.sort((a, b) => a - b); + let n = nums.length; + let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1914.leetcode1914 Cyclically Rotating a Grid-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1914.leetcode1914 Cyclically Rotating a Grid-zh.md" new file mode 100644 index 00000000..610be8a6 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1914.leetcode1914 Cyclically Rotating a Grid-zh.md" @@ -0,0 +1,162 @@ +# [1914. 循环轮转矩阵](https://leetcode-cn.com/problems/cyclically-rotating-a-grid) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1914.Cyclically%20Rotating%20a%20Grid/README_EN.md) + +## 题目描述 + + + +

    给你一个大小为 m x n 的整数矩阵 grid​​​ ,其中 mn 都是 偶数 ;另给你一个整数 k

    + +

    矩阵由若干层组成,如下图所示,每种颜色代表一层:

    + +

    + +

    矩阵的循环轮转是通过分别循环轮转矩阵中的每一层完成的。在对某一层进行一次循环旋转操作时,层中的每一个元素将会取代其 逆时针 方向的相邻元素。轮转示例如下:

    + +

    返回执行 k 次循环轮转操作后的矩阵。

    + +

     

    + +

    示例 1:

    + +
    输入:grid = [[40,10],[30,20]], k = 1
    +输出:[[10,20],[40,30]]
    +解释:上图展示了矩阵在执行循环轮转操作时每一步的状态。
    + +

    示例 2:

    + + +
    输入:grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2
    +输出:[[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]
    +解释:上图展示了矩阵在执行循环轮转操作时每一步的状态。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == grid.length
    • +
    • n == grid[i].length
    • +
    • 2 <= m, n <= 50
    • +
    • mn 都是 偶数
    • +
    • 1 <= grid[i][j] <= 5000
    • +
    • 1 <= k <= 109
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + def rotate(grid, s1, e1, s2, e2, k): + t = [] + for j in range(e2, e1, -1): + t.append(grid[s1][j]) + for i in range(s1, s2): + t.append(grid[i][e1]) + for j in range(e1, e2): + t.append(grid[s2][j]) + for i in range(s2, s1, -1): + t.append(grid[i][e2]) + k %= len(t) + t = t[-k:] +t[:-k] + k = 0 + for j in range(e2, e1, -1): + grid[s1][j] = t[k] + k += 1 + for i in range(s1, s2): + grid[i][e1] = t[k] + k += 1 + for j in range(e1, e2): + grid[s2][j] = t[k] + k += 1 + for i in range(s2, s1, -1): + grid[i][e2] = t[k] + k += 1 + + m, n = len(grid), len(grid[0]) + s1 = e1 = 0 + s2, e2 = m - 1, n - 1 + while s1 <= s2 and e1 <= e2: + rotate(grid, s1, e1, s2, e2, k) + s1 += 1 + e1 += 1 + s2 -= 1 + e2 -= 1 + return grid +``` + +### **Java** + + + +```java +class Solution { + public int[][] rotateGrid(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + int s1 = 0, e1 = 0; + int s2 = m - 1, e2 = n - 1; + while (s1 <= s2 && e1 <= e2) { + rotate(grid, s1++, e1++, s2--, e2--, k); + } + return grid; + } + + private void rotate(int[][] grid, int s1, int e1, int s2, int e2, int k) { + List t = new ArrayList<>(); + for (int j = e2; j > e1; --j) { + t.add(grid[s1][j]); + } + for (int i = s1; i < s2; ++i) { + t.add(grid[i][e1]); + } + for (int j = e1; j < e2; ++j) { + t.add(grid[s2][j]); + } + for (int i = s2; i > s1; --i) { + t.add(grid[i][e2]); + } + int n = t.size(); + k %= n; + if (k == 0) { + return; + } + k = n - k; + for (int j = e2; j > e1; --j) { + grid[s1][j] = t.get(k); + k = (k + 1) % n; + } + for (int i = s1; i < s2; ++i) { + grid[i][e1] = t.get(k); + k = (k + 1) % n; + } + for (int j = e1; j < e2; ++j) { + grid[s2][j] = t.get(k); + k = (k + 1) % n; + } + for (int i = s2; i > s1; --i) { + grid[i][e2] = t.get(k); + k = (k + 1) % n; + } + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1915.leetcode1915 Number of Wonderful Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1915.leetcode1915 Number of Wonderful Substrings-zh.md" new file mode 100644 index 00000000..7333bca0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1915.leetcode1915 Number of Wonderful Substrings-zh.md" @@ -0,0 +1,126 @@ +# [1915. 最美子字符串的数目](https://leetcode-cn.com/problems/number-of-wonderful-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1915.Number%20of%20Wonderful%20Substrings/README_EN.md) + +## 题目描述 + + + +

    如果某个字符串中 至多一个 字母出现 奇数 次,则称其为 最美 字符串。

    + +
      +
    • 例如,"ccjjc""abab" 都是最美字符串,但 "ab" 不是。
    • +
    + +

    给你一个字符串 word ,该字符串由前十个小写英文字母组成('a''j')。请你返回 word最美非空子字符串 的数目如果同样的子字符串在 word 中出现多次,那么应当对 每次出现 分别计数

    + +

    子字符串 是字符串中的一个连续字符序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:word = "aba"
    +输出:4
    +解释:4 个最美子字符串如下所示:
    +- "aba" -> "a"
    +- "aba" -> "b"
    +- "aba" -> "a"
    +- "aba" -> "aba"
    +
    + +

    示例 2:

    + +
    +输入:word = "aabb"
    +输出:9
    +解释:9 个最美子字符串如下所示:
    +- "aabb" -> "a"
    +- "aabb" -> "aa"
    +- "aabb" -> "aab"
    +- "aabb" -> "aabb"
    +- "aabb" -> "a"
    +- "aabb" -> "abb"
    +- "aabb" -> "b"
    +- "aabb" -> "bb"
    +- "aabb" -> "b"
    +
    + +

    示例 3:

    + +
    +输入:word = "he"
    +输出:2
    +解释:2 个最美子字符串如下所示:
    +- "he" -> "h"
    +- "he" -> "e"
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= word.length <= 105
    • +
    • word 由从 'a''j' 的小写英文字母组成
    • +
    + + +## 解法 + + + +状态压缩 + 前缀和 + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **JavaScript** + +```js +/** + * @param {string} word + * @return {number} + */ +var wonderfulSubstrings = function(word) { + let n = 1 << 10; + let counts = new Array(n).fill(0); + counts[0] = 1; + let pre = 0; + let ans = 0; + for (let c of word) { + let cur = c.charCodeAt(0) - 'a'.charCodeAt(0); + pre ^= (1 << cur); + ans += counts[pre]; + for (let i = 1; i < n; i <<= 1) { + ans += counts[pre ^ i]; + } + ++counts[pre]; + } + return ans; +}; +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1916.leetcode1916 Count Ways to Build Rooms in an Ant Colony-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1916.leetcode1916 Count Ways to Build Rooms in an Ant Colony-zh.md" new file mode 100644 index 00000000..cc59f1fc --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1916.leetcode1916 Count Ways to Build Rooms in an Ant Colony-zh.md" @@ -0,0 +1,82 @@ +# [1916. 统计为蚁群构筑房间的不同顺序](https://leetcode-cn.com/problems/count-ways-to-build-rooms-in-an-ant-colony) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1916.Count%20Ways%20to%20Build%20Rooms%20in%20an%20Ant%20Colony/README_EN.md) + +## 题目描述 + + + +

    你是一只蚂蚁,负责为蚁群构筑 n 间编号从 0n-1 的新房间。给你一个 下标从 0 开始 且长度为 n 的整数数组 prevRoom 作为扩建计划。其中,prevRoom[i] 表示在构筑房间 i 之前,你必须先构筑房间 prevRoom[i] ,并且这两个房间必须 直接 相连。房间 0 已经构筑完成,所以 prevRoom[0] = -1 。扩建计划中还有一条硬性要求,在完成所有房间的构筑之后,从房间 0 可以访问到每个房间。

    + +

    你一次只能构筑 一个 房间。你可以在 已经构筑好的 房间之间自由穿行,只要这些房间是 相连的 。如果房间 prevRoom[i] 已经构筑完成,那么你就可以构筑房间 i

    + +

    返回你构筑所有房间的 不同顺序的数目 。由于答案可能很大,请返回对 109 + 7 取余 的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:prevRoom = [-1,0,1]
    +输出:1
    +解释:仅有一种方案可以完成所有房间的构筑:0 → 1 → 2
    +
    + +

    示例 2:

    + + +
    +输入:prevRoom = [-1,0,0,1,2]
    +输出:6
    +解释:
    +有 6 种不同顺序:
    +0 → 1 → 3 → 2 → 4
    +0 → 2 → 4 → 1 → 3
    +0 → 1 → 2 → 3 → 4
    +0 → 1 → 2 → 4 → 3
    +0 → 2 → 1 → 3 → 4
    +0 → 2 → 1 → 4 → 3
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == prevRoom.length
    • +
    • 2 <= n <= 105
    • +
    • prevRoom[0] == -1
    • +
    • 对于所有的 1 <= i < n ,都有 0 <= prevRoom[i] < n
    • +
    • 题目保证所有房间都构筑完成后,从房间 0 可以访问到每个房间
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1917.leetcode1917 Leetcodify Friends Recommendations-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1917.leetcode1917 Leetcodify Friends Recommendations-zh.md" new file mode 100644 index 00000000..0d39c920 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1917.leetcode1917 Leetcodify Friends Recommendations-zh.md" @@ -0,0 +1,117 @@ +# [1917. Leetcodify Friends Recommendations](https://leetcode-cn.com/problems/leetcodify-friends-recommendations) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1917.Leetcodify%20Friends%20Recommendations/README_EN.md) + +## 题目描述 + + + +

    Table: Listens

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| song_id     | int     |
    +| day         | date    |
    ++-------------+---------+
    +There is no primary key for this table. It may contain duplicates.
    +Each row of this table indicates that the user user_id listened to the song song_id on the day day.
    +
    + +

     

    + +

    Table: Friendship

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user1_id      | int     |
    +| user2_id      | int     |
    ++---------------+---------+
    +(user1_id, user2_id) is the primary key for this table.
    +Each row of this table indicates that the users user1_id and user2_id are friends.
    +Note that user1_id < user2_id.
    +
    + +

     

    + +

    Write an SQL query to recommend friends to Leetcodify users. We recommend user x to user y if:

    + +
      +
    • Users x and y are not friends, and
    • +
    • Users x and y listened to the same three or more different songs on the same day.
    • +
    + +

    Note that friend recommendations are unidirectional, meaning if user x and user y should be recommended to each other, the result table should have both user x recommended to user y and user y recommended to user x.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Listens table:
    ++---------+---------+------------+
    +| user_id | song_id | day        |
    ++---------+---------+------------+
    +| 1       | 10      | 2021-03-15 |
    +| 1       | 11      | 2021-03-15 |
    +| 1       | 12      | 2021-03-15 |
    +| 2       | 10      | 2021-03-15 |
    +| 2       | 11      | 2021-03-15 |
    +| 2       | 12      | 2021-03-15 |
    +| 3       | 10      | 2021-03-15 |
    +| 3       | 11      | 2021-03-15 |
    +| 3       | 12      | 2021-03-15 |
    +| 4       | 10      | 2021-03-15 |
    +| 4       | 11      | 2021-03-15 |
    +| 4       | 13      | 2021-03-15 |
    +| 5       | 10      | 2021-03-16 |
    +| 5       | 11      | 2021-03-16 |
    +| 5       | 12      | 2021-03-16 |
    ++---------+---------+------------+
    +
    +Friendship table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    ++----------+----------+
    +
    +Result table:
    ++---------+----------------+
    +| user_id | recommended_id |
    ++---------+----------------+
    +| 1       | 3              |
    +| 2       | 3              |
    +| 3       | 1              |
    +| 3       | 2              |
    ++---------+----------------+
    +Users 1 and 2 listened to songs 10, 11, and 12 on the same day, but they are already friends.
    +Users 1 and 3 listened to songs 10, 11, and 12 on the same day. Since they are not friends, we recommend them to each other.
    +Users 1 and 4 did not listen to the same three songs.
    +Users 1 and 5 listened to songs 10, 11, and 12, but on different days.
    +
    +Similarly, we can see that users 2 and 3 listened to songs 10, 11, and 12 on the same day and are not friends, so we recommend them to each other.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1918.leetcode1918 Kth Smallest Subarray Sum-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1918.leetcode1918 Kth Smallest Subarray Sum-zh.md" new file mode 100644 index 00000000..1031a633 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1918.leetcode1918 Kth Smallest Subarray Sum-zh.md" @@ -0,0 +1,87 @@ +# [1918. Kth Smallest Subarray Sum](https://leetcode-cn.com/problems/kth-smallest-subarray-sum) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1918.Kth%20Smallest%20Subarray%20Sum/README_EN.md) + +## 题目描述 + + + +

    Given an integer array nums of length n and an integer k, return the kth smallest subarray sum.

    + +

    A subarray is defined as a non-empty contiguous sequence of elements in an array. A subarray sum is the sum of all elements in the subarray.

    + +

     

    +

    Example 1:

    + +
    +Input: nums = [2,1,3], k = 4
    +Output: 3
    +Explanation: The subarrays of [2,1,3] are:
    +- [2] with sum 2
    +- [1] with sum 1
    +- [3] with sum 3
    +- [2,1] with sum 3
    +- [1,3] with sum 4
    +- [2,1,3] with sum 6 
    +Ordering the sums from smallest to largest gives 1, 2, 3, 3, 4, 6. The 4th smallest is 3.
    +
    + +

    Example 2:

    + +
    +Input: nums = [3,3,5,5], k = 7
    +Output: 10
    +Explanation: The subarrays of [3,3,5,5] are:
    +- [3] with sum 3
    +- [3] with sum 3
    +- [5] with sum 5
    +- [5] with sum 5
    +- [3,3] with sum 6
    +- [3,5] with sum 8
    +- [5,5] with sum 10
    +- [3,3,5], with sum 11
    +- [3,5,5] with sum 13
    +- [3,3,5,5] with sum 16
    +Ordering the sums from smallest to largest gives 3, 3, 5, 5, 6, 8, 10, 11, 13, 16. The 7th smallest is 10.
    +
    + +

     

    +

    Constraints:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 2 * 104
    • +
    • 1 <= nums[i] <= 5 * 104
    • +
    • 1 <= k <= n * (n + 1) / 2
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1919.leetcode1919 Leetcodify Similar Friends-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1919.leetcode1919 Leetcodify Similar Friends-zh.md" new file mode 100644 index 00000000..44891ea4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1919.leetcode1919 Leetcodify Similar Friends-zh.md" @@ -0,0 +1,113 @@ +# [1919. Leetcodify Similar Friends](https://leetcode-cn.com/problems/leetcodify-similar-friends) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1919.Leetcodify%20Similar%20Friends/README_EN.md) + +## 题目描述 + + + +

    Table: Listens

    + +
    ++-------------+---------+
    +| Column Name | Type    |
    ++-------------+---------+
    +| user_id     | int     |
    +| song_id     | int     |
    +| day         | date    |
    ++-------------+---------+
    +There is no primary key for this table. It may contain duplicates.
    +Each row of this table indicates that the user user_id listened to the song song_id on the day day.
    +
    + +

     

    + +

    Table: Friendship

    + +
    ++---------------+---------+
    +| Column Name   | Type    |
    ++---------------+---------+
    +| user1_id      | int     |
    +| user2_id      | int     |
    ++---------------+---------+
    +(user1_id, user2_id) is the primary key for this table.
    +Each row of this table indicates that the users user1_id and user2_id are friends.
    +Note that user1_id < user2_id.
    +
    + +

     

    + +

    Write an SQL query to report the similar friends of Leetcodify users. A user x and user y are similar friends if:

    + +
      +
    • Users x and y are friends, and
    • +
    • Users x and y listened to the same three or more different songs on the same day.
    • +
    + +

    Return the result table in any order. Note that you must return the similar pairs of friends the same way they were represented in the input (i.e., always user1_id < user2_id).

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Listens table:
    ++---------+---------+------------+
    +| user_id | song_id | day        |
    ++---------+---------+------------+
    +| 1       | 10      | 2021-03-15 |
    +| 1       | 11      | 2021-03-15 |
    +| 1       | 12      | 2021-03-15 |
    +| 2       | 10      | 2021-03-15 |
    +| 2       | 11      | 2021-03-15 |
    +| 2       | 12      | 2021-03-15 |
    +| 3       | 10      | 2021-03-15 |
    +| 3       | 11      | 2021-03-15 |
    +| 3       | 12      | 2021-03-15 |
    +| 4       | 10      | 2021-03-15 |
    +| 4       | 11      | 2021-03-15 |
    +| 4       | 13      | 2021-03-15 |
    +| 5       | 10      | 2021-03-16 |
    +| 5       | 11      | 2021-03-16 |
    +| 5       | 12      | 2021-03-16 |
    ++---------+---------+------------+
    +
    +Friendship table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    +| 2        | 4        |
    +| 2        | 5        |
    ++----------+----------+
    +
    +Result table:
    ++----------+----------+
    +| user1_id | user2_id |
    ++----------+----------+
    +| 1        | 2        |
    ++----------+----------+
    +
    +Users 1 and 2 are friends, and they listened to songs 10, 11, and 12 on the same day. They are similar friends.
    +Users 1 and 3 listened to songs 10, 11, and 12 on the same day, but they are not friends.
    +Users 2 and 4 are friends, but they did not listen to the same three different songs.
    +Users 2 and 5 are friends and listened to songs 10, 11, and 12, but they did not listen to them on the same day.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1920.leetcode1920 Build Array from Permutation-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1920.leetcode1920 Build Array from Permutation-zh.md" new file mode 100644 index 00000000..76f28ada --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1920.leetcode1920 Build Array from Permutation-zh.md" @@ -0,0 +1,125 @@ +# [1920. 基于排列构建数组](https://leetcode-cn.com/problems/build-array-from-permutation) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1920.Build%20Array%20from%20Permutation/README_EN.md) + +## 题目描述 + + + +

    给你一个 从 0 开始的排列 nums下标也从 0 开始)。请你构建一个 同样长度 的数组 ans ,其中,对于每个 i0 <= i < nums.length),都满足 ans[i] = nums[nums[i]] 。返回构建好的数组 ans

    + +

    从 0 开始的排列 nums 是一个由 0 到 nums.length - 10nums.length - 1 也包含在内)的不同整数组成的数组。

    + +

     

    + +

    示例 1:

    + +
    输入:nums = [0,2,1,5,3,4]
    +输出:[0,1,2,4,5,3]
    +解释:数组 ans 构建如下:
    +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    +    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
    +    = [0,1,2,4,5,3]
    + +

    示例 2:

    + +
    输入:nums = [5,0,1,2,3,4]
    +输出:[4,5,0,1,2,3]
    +解释:数组 ans 构建如下:
    +ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    +    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
    +    = [4,5,0,1,2,3]
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= nums.length <= 1000
    • +
    • 0 <= nums[i] < nums.length
    • +
    • nums 中的元素 互不相同
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def buildArray(self, nums: List[int]) -> List[int]: + return [nums[num] for num in nums] +``` + +### **Java** + + + +```java +class Solution { + public int[] buildArray(int[] nums) { + int[] ans = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) { + ans[i] = nums[nums[i]]; + } + return ans; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var buildArray = function(nums) { + let ans = []; + for (let i = 0; i < nums.length; ++i) { + ans[i] = nums[nums[i]]; + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector buildArray(vector& nums) { + vector ans; + for (int& num : nums) { + ans.push_back(nums[num]); + } + return ans; + } +}; +``` + +### **Go** + +```go +func buildArray(nums []int) []int { + ans := make([]int, len(nums)) + for i, num := range nums { + ans[i] = nums[num] + } + return ans +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1921.leetcode1921 Eliminate Maximum Number of Monsters-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1921.leetcode1921 Eliminate Maximum Number of Monsters-zh.md" new file mode 100644 index 00000000..e961de6c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1921.leetcode1921 Eliminate Maximum Number of Monsters-zh.md" @@ -0,0 +1,181 @@ +# [1921. 消灭怪物的最大数量](https://leetcode-cn.com/problems/eliminate-maximum-number-of-monsters) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1921.Eliminate%20Maximum%20Number%20of%20Monsters/README_EN.md) + +## 题目描述 + + + +

    你正在玩一款电子游戏,在游戏中你需要保护城市免受怪物侵袭。给你一个 下标从 0 开始 且长度为 n 的整数数组 dist ,其中 dist[i] 是第 i 个怪物与城市的 初始距离(单位:米)。

    + +

    怪物以 恒定 的速度走向城市。给你一个长度为 n 的整数数组 speed 表示每个怪物的速度,其中 speed[i] 是第 i 个怪物的速度(单位:米/分)。

    + +

    怪物从 第 0 分钟 时开始移动。你有一把武器,并可以 选择 在每一分钟的开始时使用,包括第 0 分钟。但是你无法在一分钟的中间使用武器。这种武器威力惊人,一次可以消灭任一还活着的怪物。

    + +

    一旦任一怪物到达城市,你就输掉了这场游戏。如果某个怪物 在某一分钟开始时到达城市,这会被视为 输掉 游戏,在你可以使用武器之前,游戏就会结束。

    + +

    返回在你输掉游戏前可以消灭的怪物的 最大 数量。如果你可以在所有怪物到达城市前将它们全部消灭,返回  n

    + +

     

    + +

    示例 1:

    + +
    +输入:dist = [1,3,4], speed = [1,1,1]
    +输出:3
    +解释:
    +第 0 分钟开始时,怪物的距离是 [1,3,4],你消灭了第一个怪物。
    +第 1 分钟开始时,怪物的距离是 [X,2,3],你没有消灭任何怪物。
    +第 2 分钟开始时,怪物的距离是 [X,1,2],你消灭了第二个怪物。
    +第 3 分钟开始时,怪物的距离是 [X,X,1],你消灭了第三个怪物。
    +所有 3 个怪物都可以被消灭。
    + +

    示例 2:

    + +
    +输入:dist = [1,1,2,3], speed = [1,1,1,1]
    +输出:1
    +解释:
    +第 0 分钟开始时,怪物的距离是 [1,1,2,3],你消灭了第一个怪物。
    +第 1 分钟开始时,怪物的距离是 [X,0,1,2],你输掉了游戏。
    +你只能消灭 1 个怪物。
    +
    + +

    示例 3:

    + +
    +输入:dist = [3,2,4], speed = [5,3,2]
    +输出:1
    +解释:
    +第 0 分钟开始时,怪物的距离是 [3,2,4],你消灭了第一个怪物。
    +第 1 分钟开始时,怪物的距离是 [X,0,2],你输掉了游戏。 
    +你只能消灭 1 个怪物。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == dist.length == speed.length
    • +
    • 1 <= n <= 105
    • +
    • 1 <= dist[i], speed[i] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: + n = len(dist) + times = [(dist[i] - 1) // speed[i] for i in range(n)] + times.sort() + for i in range(n): + if times[i] < i: + return i + return n +``` + +### **Java** + + + +```java +class Solution { + public int eliminateMaximum(int[] dist, int[] speed) { + int n = dist.length; + int[] times = new int[n]; + for (int i = 0; i < n; ++i) { + times[i] = (dist[i] - 1) / speed[i]; + } + Arrays.sort(times); + for (int i = 0; i < n; ++i) { + if (times[i] < i) { + return i; + } + } + return n; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} dist + * @param {number[]} speed + * @return {number} + */ + var eliminateMaximum = function(dist, speed) { + let arr = []; + for (let i = 0; i < dist.length; i++) { + arr[i] = dist[i] / speed[i]; + } + arr.sort((a, b) => a - b); + let ans = 0; + while (arr[0] > ans) { + arr.shift(); + ++ans; + } + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + int eliminateMaximum(vector& dist, vector& speed) { + int n = dist.size(); + vector times; + for (int i = 0; i < n; ++i) { + times.push_back((dist[i] - 1) / speed[i]); + } + sort(times.begin(), times.end()); + for (int i = 0; i < n; ++i) { + if (times[i] < i) { + return i; + } + } + return n; + } +}; +``` + +### **Go** + +```go +func eliminateMaximum(dist []int, speed []int) int { + n := len(dist) + times := make([]int, n) + for i := 0; i < n; i++ { + times[i] = (dist[i] - 1) / speed[i] + } + sort.Ints(times) + for i := 0; i < n; i++ { + if times[i] < i { + return i + } + } + return n +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1922.leetcode1922 Count Good Numbers-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1922.leetcode1922 Count Good Numbers-zh.md" new file mode 100644 index 00000000..61c9a4a0 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1922.leetcode1922 Count Good Numbers-zh.md" @@ -0,0 +1,159 @@ +# [1922. 统计好数字的数目](https://leetcode-cn.com/problems/count-good-numbers) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1922.Count%20Good%20Numbers/README_EN.md) + +## 题目描述 + + + +

    我们称一个数字字符串是 好数字 当它满足(下标从 0 开始)偶数 下标处的数字为 偶数 且 奇数 下标处的数字为 质数 (235 或 7)。

    + +
      +
    • 比方说,"2582" 是好数字,因为偶数下标处的数字(2 和 8)是偶数且奇数下标处的数字(5 和 2)为质数。但 "3245" 不是 好数字,因为 3 在偶数下标处但不是偶数。
    • +
    + +

    给你一个整数 n ,请你返回长度为 n 且为好数字的数字字符串 总数 。由于答案可能会很大,请你将它对 109 + 7 取余后返回 。

    + +

    一个 数字字符串 是每一位都由 0 到 9 组成的字符串,且可能包含前导 0 。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 1
    +输出:5
    +解释:长度为 1 的好数字包括 "0","2","4","6","8" 。
    +
    + +

    示例 2:

    + +
    +输入:n = 4
    +输出:400
    +
    + +

    示例 3:

    + +
    +输入:n = 50
    +输出:564908303
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 1015
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def countGoodNumbers(self, n: int) -> int: + mod = 10 ** 9 + 7 + + def myPow(x, n): + res = 1 + while n: + if (n & 1) == 1: + res = res * x % mod + x = x * x % mod + n >>= 1 + return res + + return myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % mod +``` + +### **Java** + + + +```java +class Solution { + private int mod = 1000000007; + + public int countGoodNumbers(long n) { + return (int) (myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % mod); + } + + private long myPow(long x, long n) { + long res = 1; + while (n != 0) { + if ((n & 1) == 1) { + res = res * x % mod; + } + x = x * x % mod; + n >>= 1; + } + return res; + } +} +``` + +### **C++** + +```cpp +int MOD = 1000000007; + +class Solution { +public: + int countGoodNumbers(long long n) { + return (int) (myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % MOD); + } + +private: + long long myPow(long long x, long long n) { + long long res = 1; + while (n) { + if ((n & 1) == 1) { + res = res * x % MOD; + } + x = x * x % MOD; + n >>= 1; + } + return res; + } +}; +``` + +### **Go** + +```go +const mod int64 = 1e9 + 7 + +func countGoodNumbers(n int64) int { + return int(myPow(5, (n+1)>>1) * myPow(4, n>>1) % mod) +} + +func myPow(x, n int64) int64 { + var res int64 = 1 + for n != 0 { + if (n & 1) == 1 { + res = res * x % mod + } + x = x * x % mod + n >>= 1 + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1923.leetcode1923 Longest Common Subpath-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1923.leetcode1923 Longest Common Subpath-zh.md" new file mode 100644 index 00000000..a9bde968 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1923.leetcode1923 Longest Common Subpath-zh.md" @@ -0,0 +1,140 @@ +# [1923. 最长公共子路径](https://leetcode-cn.com/problems/longest-common-subpath) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1923.Longest%20Common%20Subpath/README_EN.md) + +## 题目描述 + + + +

    一个国家由 n 个编号为 0 到 n - 1 的城市组成。在这个国家里,每两个 城市之间都有一条道路连接。

    + +

    总共有 m 个编号为 0 到 m - 1 的朋友想在这个国家旅游。他们每一个人的路径都会包含一些城市。每条路径都由一个整数数组表示,每个整数数组表示一个朋友按顺序访问过的城市序列。同一个城市在一条路径中可能 重复 出现,但同一个城市在一条路径中不会连续出现。

    + +

    给你一个整数 n 和二维数组 paths ,其中 paths[i] 是一个整数数组,表示第 i 个朋友走过的路径,请你返回 每一个 朋友都走过的 最长公共子路径 的长度,如果不存在公共子路径,请你返回 0 。

    + +

    一个 子路径 指的是一条路径中连续的城市序列。

    + +

     

    + +

    示例 1:

    + +
    +输入:n = 5, paths = [[0,1,2,3,4],
    +                     [2,3,4],
    +                     [4,0,1,2,3]]
    +输出:2
    +解释:最长公共子路径为 [2,3] 。
    +
    + +

    示例 2:

    + +
    +输入:n = 3, paths = [[0],[1],[2]]
    +输出:0
    +解释:三条路径没有公共子路径。
    +
    + +

    示例 3:

    + +
    +输入:n = 5, paths = [[0,1,2,3,4],
    +                     [4,3,2,1,0]]
    +输出:1
    +解释:最长公共子路径为 [0],[1],[2],[3] 和 [4] 。它们长度都为 1 。
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 105
    • +
    • m == paths.length
    • +
    • 2 <= m <= 105
    • +
    • sum(paths[i].length) <= 105
    • +
    • 0 <= paths[i][j] < n
    • +
    • paths[i] 中同一个城市不会连续重复出现。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java +class Solution { + int N = 100010; + long[] h = new long[N]; + long[] p = new long[N]; + private int[][] paths; + Map cnt = new HashMap<>(); + Map inner = new HashMap<>(); + + public int longestCommonSubpath(int n, int[][] paths) { + int left = 0, right = N; + for (int[] path : paths) { + right = Math.min(right, path.length); + } + this.paths = paths; + while (left < right) { + int mid = (left + right + 1) >> 1; + if (check(mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } + + private boolean check(int mid) { + cnt.clear(); + inner.clear(); + p[0] = 1; + for (int j = 0; j < paths.length; ++j) { + int n = paths[j].length; + for (int i = 1; i <= n; ++i) { + p[i] = p[i - 1] * 133331; + h[i] = h[i - 1] * 133331 + paths[j][i - 1]; + } + for (int i = mid; i <= n; ++i) { + long val = get(i - mid + 1, i); + if (!inner.containsKey(val) || inner.get(val) != j) { + inner.put(val, j); + cnt.put(val, cnt.getOrDefault(val, 0) + 1); + } + } + } + int max = 0; + for (int val : cnt.values()) { + max = Math.max(max, val); + } + return max == paths.length; + } + + private long get(int l, int r) { + return h[r] - h[l - 1] * p[r - l + 1]; + } +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1924.leetcode1924 Erect the Fence II-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1924.leetcode1924 Erect the Fence II-zh.md" new file mode 100644 index 00000000..43a0d492 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1924.leetcode1924 Erect the Fence II-zh.md" @@ -0,0 +1,76 @@ +# [1924. Erect the Fence II](https://leetcode-cn.com/problems/erect-the-fence-ii) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1924.Erect%20the%20Fence%20II/README_EN.md) + +## 题目描述 + + + +

    You are given a 2D integer array trees where trees[i] = [xi, yi] represents the location of the ith tree in the garden.

    + +

    You are asked to fence the entire garden using the minimum length of rope possible. The garden is well-fenced only if all the trees are enclosed and the rope used forms a perfect circle. A tree is considered enclosed if it is inside or on the border of the circle.

    + +

    More formally, you must form a circle using the rope with a center (x, y) and radius r where all trees lie inside or on the circle and r is minimum.

    + +

    Return the center and radius of the circle as a length 3 array [x, y, r]. Answers within 10-5 of the actual answer will be accepted.

    + +

     

    +

    Example 1:

    + +

    + +
    +Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
    +Output: [2.00000,2.00000,2.00000]
    +Explanation: The fence will have center = (2, 2) and radius = 2
    +
    + +

    Example 2:

    + +

    + +
    +Input: trees = [[1,2],[2,2],[4,2]]
    +Output: [2.50000,2.00000,1.50000]
    +Explanation: The fence will have center = (2.5, 2) and radius = 1.5
    +
    + +

     

    +

    Constraints:

    + +
      +
    • 1 <= trees.length <= 3000
    • +
    • trees[i].length == 2
    • +
    • 0 <= xi, yi <= 3000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1925.leetcode1925 Count Square Sum Triples-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1925.leetcode1925 Count Square Sum Triples-zh.md" new file mode 100644 index 00000000..12a93e14 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1925.leetcode1925 Count Square Sum Triples-zh.md" @@ -0,0 +1,128 @@ +# [1925. 统计平方和三元组的数目](https://leetcode-cn.com/problems/count-square-sum-triples) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1925.Count%20Square%20Sum%20Triples/README_EN.md) + +## 题目描述 + + + +

    一个 平方和三元组 (a,b,c) 指的是满足 a2 + b2 = c2 的 整数 三元组 ab 和 c 。

    + +

    给你一个整数 n ,请你返回满足 1 <= a, b, c <= n 的 平方和三元组 的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:n = 5
    +输出:2
    +解释:平方和三元组为 (3,4,5) 和 (4,3,5) 。
    +
    + +

    示例 2:

    + +
    输入:n = 10
    +输出:4
    +解释:平方和三元组为 (3,4,5),(4,3,5),(6,8,10) 和 (8,6,10) 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= n <= 250
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def countTriples(self, n: int) -> int: + res = 0 + for a in range(1, n + 1): + for b in range(1, n + 1): + t = a ** 2 + b ** 2 + c = int(sqrt(t)) + if c <= n and c ** 2 == t: + res += 1 + return res +``` + +### **Java** + + + +```java +class Solution { + public int countTriples(int n) { + int res = 0; + for (int a = 1; a <= n; ++a) { + for (int b = 1; b <= n; ++b) { + int t = a * a + b * b; + int c = (int) Math.sqrt(t); + if (c <= n && c * c == t) { + ++res; + } + } + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int countTriples(int n) { + int res = 0; + for (int a = 1; a <= n; ++a) { + for (int b = 1; b <= n; ++b) { + int t = a * a + b * b; + int c = (int) sqrt(t); + if (c <= n && c * c == t) { + ++res; + } + } + } + return res; + } +}; +``` + +### **Go** + +```go +func countTriples(n int) int { + res := 0 + for a := 1; a <= n; a++ { + for b := 1; b <= n; b++ { + t := a*a + b*b + c := int(math.Sqrt(float64(t))) + if c <= n && c*c == t { + res++ + } + } + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1926.leetcode1926 Nearest Exit from Entrance in Maze-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1926.leetcode1926 Nearest Exit from Entrance in Maze-zh.md" new file mode 100644 index 00000000..38383d52 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1926.leetcode1926 Nearest Exit from Entrance in Maze-zh.md" @@ -0,0 +1,91 @@ +# [1926. 迷宫中离入口最近的出口](https://leetcode-cn.com/problems/nearest-exit-from-entrance-in-maze) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1926.Nearest%20Exit%20from%20Entrance%20in%20Maze/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的迷宫矩阵 maze (下标从 0 开始),矩阵中有空格子(用 '.' 表示)和墙(用 '+' 表示)。同时给你迷宫的入口 entrance ,用 entrance = [entrancerow, entrancecol] 表示你一开始所在格子的行和列。

    + +

    每一步操作,你可以往 或者  移动一个格子。你不能进入墙所在的格子,你也不能离开迷宫。你的目标是找到离 entrance 最近 的出口。出口 的含义是 maze 边界 上的 空格子entrance 格子 不算 出口。

    + +

    请你返回从 entrance 到最近出口的最短路径的 步数 ,如果不存在这样的路径,请你返回 -1 。

    + +

     

    + +

    示例 1:

    + +
    输入:maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
    +输出:1
    +解释:总共有 3 个出口,分别位于 (1,0),(0,2) 和 (2,3) 。
    +一开始,你在入口格子 (1,2) 处。
    +- 你可以往左移动 2 步到达 (1,0) 。
    +- 你可以往上移动 1 步到达 (0,2) 。
    +从入口处没法到达 (2,3) 。
    +所以,最近的出口是 (0,2) ,距离为 1 步。
    +
    + +

    示例 2:

    + +
    输入:maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
    +输出:2
    +解释:迷宫中只有 1 个出口,在 (1,2) 处。
    +(1,0) 不算出口,因为它是入口格子。
    +初始时,你在入口与格子 (1,0) 处。
    +- 你可以往右移动 2 步到达 (1,2) 处。
    +所以,最近的出口为 (1,2) ,距离为 2 步。
    +
    + +

    示例 3:

    + +
    输入:maze = [[".","+"]], entrance = [0,0]
    +输出:-1
    +解释:这个迷宫中没有出口。
    +
    + +

     

    + +

    提示:

    + +
      +
    • maze.length == m
    • +
    • maze[i].length == n
    • +
    • 1 <= m, n <= 100
    • +
    • maze[i][j] 要么是 '.' ,要么是 '+' 。
    • +
    • entrance.length == 2
    • +
    • 0 <= entrancerow < m
    • +
    • 0 <= entrancecol < n
    • +
    • entrance 一定是空格子。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1927.leetcode1927 Sum Game-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1927.leetcode1927 Sum Game-zh.md" new file mode 100644 index 00000000..724a126d --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1927.leetcode1927 Sum Game-zh.md" @@ -0,0 +1,99 @@ +# [1927. 求和游戏](https://leetcode-cn.com/problems/sum-game) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1927.Sum%20Game/README_EN.md) + +## 题目描述 + + + +

    Alice 和 Bob 玩一个游戏,两人轮流行动,Alice 先手 。

    + +

    给你一个 偶数长度 的字符串 num ,每一个字符为数字字符或者 '?' 。每一次操作中,如果 num 中至少有一个 '?' ,那么玩家可以执行以下操作:

    + +
      +
    1. 选择一个下标 i 满足 num[i] == '?' 。
    2. +
    3. 将 num[i] 用 '0' 到 '9' 之间的一个数字字符替代。
    4. +
    + +

    num 中没有 '?' 时,游戏结束。

    + +

    Bob 获胜的条件是 num 中前一半数字的和 等于 后一半数字的和。Alice 获胜的条件是前一半的和与后一半的和 不相等 。

    + +
      +
    • 比方说,游戏结束时 num = "243801" ,那么 Bob 获胜,因为 2+4+3 = 8+0+1 。如果游戏结束时 num = "243803" ,那么 Alice 获胜,因为 2+4+3 != 8+0+3 。
    • +
    + +

    在 Alice 和 Bob 都采取 最优 策略的前提下,如果 Alice 获胜,请返回 true ,如果 Bob 获胜,请返回 false 。

    + +

     

    + +

    示例 1:

    + +
    +输入:num = "5023"
    +输出:false
    +解释:num 中没有 '?' ,没法进行任何操作。
    +前一半的和等于后一半的和:5 + 0 = 2 + 3 。
    +
    + +

    示例 2:

    + +
    +输入:num = "25??"
    +输出:true
    +解释:Alice 可以将两个 '?' 中的一个替换为 '9' ,Bob 无论如何都无法使前一半的和等于后一半的和。
    +
    + +

    示例 3:

    + +
    +输入:num = "?3295???"
    +输出:false
    +解释:Bob 总是能赢。一种可能的结果是:
    +- Alice 将第一个 '?' 用 '9' 替换。num = "93295???" 。
    +- Bob 将后面一半中的一个 '?' 替换为 '9' 。num = "932959??" 。
    +- Alice 将后面一半中的一个 '?' 替换为 '2' 。num = "9329592?" 。
    +- Bob 将后面一半中最后一个 '?' 替换为 '7' 。num = "93295927" 。
    +Bob 获胜,因为 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= num.length <= 105
    • +
    • num.length 是 偶数 。
    • +
    • num 只包含数字字符和 '?' 。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1928.leetcode1928 Minimum Cost to Reach Destination in Time-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1928.leetcode1928 Minimum Cost to Reach Destination in Time-zh.md" new file mode 100644 index 00000000..2d458aa5 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1928.leetcode1928 Minimum Cost to Reach Destination in Time-zh.md" @@ -0,0 +1,93 @@ +# [1928. 规定时间内到达终点的最小花费](https://leetcode-cn.com/problems/minimum-cost-to-reach-destination-in-time) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1928.Minimum%20Cost%20to%20Reach%20Destination%20in%20Time/README_EN.md) + +## 题目描述 + + + +

    一个国家有 n 个城市,城市编号为 0 到 n - 1 ,题目保证 所有城市 都由双向道路 连接在一起 。道路由二维整数数组 edges 表示,其中 edges[i] = [xi, yi, timei] 表示城市 xi 和 yi 之间有一条双向道路,耗费时间为 timei 分钟。两个城市之间可能会有多条耗费时间不同的道路,但是不会有道路两头连接着同一座城市。

    + +

    每次经过一个城市时,你需要付通行费。通行费用一个长度为 n 且下标从 0 开始的整数数组 passingFees 表示,其中 passingFees[j] 是你经过城市 j 需要支付的费用。

    + +

    一开始,你在城市 0 ,你想要在 maxTime 分钟以内 (包含 maxTime 分钟)到达城市 n - 1 。旅行的 费用 为你经过的所有城市 通行费之和 (包括 起点和终点城市的通行费)。

    + +

    给你 maxTimeedges 和 passingFees ,请你返回完成旅行的 最小费用 ,如果无法在 maxTime 分钟以内完成旅行,请你返回 -1 。

    + +

     

    + +

    示例 1:

    + +

    + +
    +输入:maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
    +输出:11
    +解释:最优路径为 0 -> 1 -> 2 -> 5 ,总共需要耗费 30 分钟,需要支付 11 的通行费。
    +
    + +

    示例 2:

    + +

    + +
    +输入:maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
    +输出:48
    +解释:最优路径为 0 -> 3 -> 4 -> 5 ,总共需要耗费 26 分钟,需要支付 48 的通行费。
    +你不能选择路径 0 -> 1 -> 2 -> 5 ,因为这条路径耗费的时间太长。
    +
    + +

    示例 3:

    + +
    +输入:maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]
    +输出:-1
    +解释:无法在 25 分钟以内从城市 0 到达城市 5 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= maxTime <= 1000
    • +
    • n == passingFees.length
    • +
    • 2 <= n <= 1000
    • +
    • n - 1 <= edges.length <= 1000
    • +
    • 0 <= xi, yi <= n - 1
    • +
    • 1 <= timei <= 1000
    • +
    • 1 <= passingFees[j] <= 1000 
    • +
    • 图中两个节点之间可能有多条路径。
    • +
    • 图中不含有自环。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1929.leetcode1929 Concatenation of Array-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1929.leetcode1929 Concatenation of Array-zh.md" new file mode 100644 index 00000000..84fb639c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1929.leetcode1929 Concatenation of Array-zh.md" @@ -0,0 +1,127 @@ +# [1929. 数组串联](https://leetcode-cn.com/problems/concatenation-of-array) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1929.Concatenation%20of%20Array/README_EN.md) + +## 题目描述 + + + +

    给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 <= i < ni ,满足下述所有要求:

    + +
      +
    • ans[i] == nums[i]
    • +
    • ans[i + n] == nums[i]
    • +
    + +

    具体而言,ans 由两个 nums 数组 串联 形成。

    + +

    返回数组 ans

    + +

     

    + +

    示例 1:

    + +
    +输入:nums = [1,2,1]
    +输出:[1,2,1,1,2,1]
    +解释:数组 ans 按下述方式形成:
    +- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
    +- ans = [1,2,1,1,2,1]
    + +

    示例 2:

    + +
    +输入:nums = [1,3,2,1]
    +输出:[1,3,2,1,1,3,2,1]
    +解释:数组 ans 按下述方式形成:
    +- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
    +- ans = [1,3,2,1,1,3,2,1]
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == nums.length
    • +
    • 1 <= n <= 1000
    • +
    • 1 <= nums[i] <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def getConcatenation(self, nums: List[int]) -> List[int]: + return nums + nums +``` + +### **Java** + + + +```java +class Solution { + public int[] getConcatenation(int[] nums) { + int n = nums.length; + int[] ans = new int[n << 1]; + for (int i = 0; i < n << 1; ++i) { + ans[i] = nums[i % n]; + } + return ans; + } +} +``` + +### **JavaScript** + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var getConcatenation = function(nums) { + let ans = nums.slice(); + ans.splice(nums.length, 0, ...nums); + return ans; +}; +``` + +### **C++** + +```cpp +class Solution { +public: + vector getConcatenation(vector& nums) { + for (int i = 0, n = nums.size(); i < n; ++i) { + nums.push_back(nums[i]); + } + return nums; + } +}; +``` + +### **Go** + +```go +func getConcatenation(nums []int) []int { + return append(nums, nums...) +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1930.leetcode1930 Unique Length-3 Palindromic Subsequences-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1930.leetcode1930 Unique Length-3 Palindromic Subsequences-zh.md" new file mode 100644 index 00000000..e55011bf --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1930.leetcode1930 Unique Length-3 Palindromic Subsequences-zh.md" @@ -0,0 +1,151 @@ +# [1930. 长度为 3 的不同回文子序列](https://leetcode-cn.com/problems/unique-length-3-palindromic-subsequences) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1930.Unique%20Length-3%20Palindromic%20Subsequences/README_EN.md) + +## 题目描述 + + + +

    给你一个字符串 s ,返回 s长度为 3 不同回文子序列 的个数。

    + +

    即便存在多种方法来构建相同的子序列,但相同的子序列只计数一次。

    + +

    回文 是正着读和反着读一样的字符串。

    + +

    子序列 是由原字符串删除其中部分字符(也可以不删除)且不改变剩余字符之间相对顺序形成的一个新字符串。

    + +
      +
    • 例如,"ace""abcde" 的一个子序列。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:s = "aabca"
    +输出:3
    +解释:长度为 3 的 3 个回文子序列分别是:
    +- "aba" ("aabca" 的子序列)
    +- "aaa" ("aabca" 的子序列)
    +- "aca" ("aabca" 的子序列)
    +
    + +

    示例 2:

    + +
    +输入:s = "adc"
    +输出:0
    +解释:"adc" 不存在长度为 3 的回文子序列。
    +
    + +

    示例 3:

    + +
    +输入:s = "bbcbaba"
    +输出:4
    +解释:长度为 3 的 4 个回文子序列分别是:
    +- "bbb" ("bbcbaba" 的子序列)
    +- "bcb" ("bbcbaba" 的子序列)
    +- "bab" ("bbcbaba" 的子序列)
    +- "aba" ("bbcbaba" 的子序列)
    +
    + +

     

    + +

    提示:

    + +
      +
    • 3 <= s.length <= 105
    • +
    • s 仅由小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python +class Solution: + def countPalindromicSubsequence(self, s: str) -> int: + res = 0 + for i in range(26): + c = chr(ord('a') + i) + if c in s: + l, r = s.index(c), s.rindex(c) + chars = {s[j] for j in range(l + 1, r)} + res += len(chars) + return res +``` + +### **Java** + + + +```java +class Solution { + public int countPalindromicSubsequence(String s) { + int res = 0; + for (char c = 'a'; c <= 'z'; ++c) { + int l = s.indexOf(c), r = s.lastIndexOf(c); + Set chars = new HashSet<>(); + for (int i = l + 1; i < r; ++i) { + chars.add(s.charAt(i)); + } + res += chars.size(); + } + return res; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int countPalindromicSubsequence(string s) { + int res = 0; + for (char c = 'a'; c <= 'z'; ++c) { + int l = s.find_first_of(c), r = s.find_last_of(c); + unordered_set chars; + for (int i = l + 1; i < r; ++i) { + chars.insert(s[i]); + } + res += chars.size(); + } + return res; + } +}; +``` + +### **Go** + +```go +func countPalindromicSubsequence(s string) int { + res := 0 + for c := 'a'; c <= 'z'; c++ { + l, r := strings.Index(s, string(c)), strings.LastIndex(s, string(c)) + chars := make(map[byte]bool) + for i := l + 1; i < r; i++ { + chars[s[i]] = true + } + res += len(chars) + } + return res +} +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1931.leetcode1931 Painting a Grid With Three Different Colors-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1931.leetcode1931 Painting a Grid With Three Different Colors-zh.md" new file mode 100644 index 00000000..ea4b2a43 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1931.leetcode1931 Painting a Grid With Three Different Colors-zh.md" @@ -0,0 +1,76 @@ +# [1931. 用三种不同颜色为网格涂色](https://leetcode-cn.com/problems/painting-a-grid-with-three-different-colors) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1931.Painting%20a%20Grid%20With%20Three%20Different%20Colors/README_EN.md) + +## 题目描述 + + + +

    给你两个整数 mn 。构造一个 m x n 的网格,其中每个单元格最开始是白色。请你用 红、绿、蓝 三种颜色为每个单元格涂色。所有单元格都需要被涂色。

    + +

    涂色方案需要满足:不存在相邻两个单元格颜色相同的情况 。返回网格涂色的方法数。因为答案可能非常大, 返回 109 + 7 取余 的结果。

    + +

     

    + +

    示例 1:

    + +
    +输入:m = 1, n = 1
    +输出:3
    +解释:如上图所示,存在三种可能的涂色方案。
    +
    + +

    示例 2:

    + +
    +输入:m = 1, n = 2
    +输出:6
    +解释:如上图所示,存在六种可能的涂色方案。
    +
    + +

    示例 3:

    + +
    +输入:m = 5, n = 5
    +输出:580986
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= m <= 5
    • +
    • 1 <= n <= 1000
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1932.leetcode1932 Merge BSTs to Create Single BST-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1932.leetcode1932 Merge BSTs to Create Single BST-zh.md" new file mode 100644 index 00000000..d428bbfe --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1932.leetcode1932 Merge BSTs to Create Single BST-zh.md" @@ -0,0 +1,114 @@ +# [1932. 合并多棵二叉搜索树](https://leetcode-cn.com/problems/merge-bsts-to-create-single-bst) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1932.Merge%20BSTs%20to%20Create%20Single%20BST/README_EN.md) + +## 题目描述 + + + +

    给你 n二叉搜索树的根节点 ,存储在数组 trees 中(下标从 0 开始),对应 n 棵不同的二叉搜索树。trees 中的每棵二叉搜索树 最多有 3 个节点 ,且不存在值相同的两个根节点。在一步操作中,将会完成下述步骤:

    + +
      +
    • 选择两个 不同的 下标 ij ,要求满足在 trees[i] 中的某个 叶节点 的值等于 trees[j]根节点的值
    • +
    • 用 trees[j] 替换 trees[i] 中的那个叶节点。
    • +
    • trees 中移除 trees[j]
    • +
    + +

    如果在执行 n - 1 次操作后,能形成一棵有效的二叉搜索树,则返回结果二叉树的 根节点 ;如果无法构造一棵有效的二叉搜索树返回 null

    + +

    二叉搜索树是一种二叉树,且树中每个节点均满足下述属性:

    + +
      +
    • 任意节点的左子树中的值都 严格小于 此节点的值。
    • +
    • 任意节点的右子树中的值都 严格大于 此节点的值。
    • +
    + +

    叶节点是不含子节点的节点。

    + +

     

    + +

    示例 1:

    + +
    +输入:trees = [[2,1],[3,2,5],[5,4]]
    +输出:[3,2,5,1,null,4]
    +解释:
    +第一步操作中,选出 i=1 和 j=0 ,并将 trees[0] 合并到 trees[1] 中。
    +删除 trees[0] ,trees = [[3,2,5,1],[5,4]] 。
    +
    +在第二步操作中,选出 i=0 和 j=1 ,将 trees[1] 合并到 trees[0] 中。
    +删除 trees[1] ,trees = [[3,2,5,1,null,4]] 。
    +
    +结果树如上图所示,为一棵有效的二叉搜索树,所以返回该树的根节点。
    + +

    示例 2:

    + +
    +输入:trees = [[5,3,8],[3,2,6]]
    +输出:[]
    +解释:
    +选出 i=0 和 j=1 ,然后将 trees[1] 合并到 trees[0] 中。
    +删除 trees[1] ,trees = [[5,3,8,2,6]] 。
    +
    +结果树如上图所示。仅能执行一次有效的操作,但结果树不是一棵有效的二叉搜索树,所以返回 null 。
    +
    + +

    示例 3:

    + +
    +输入:trees = [[5,4],[3]]
    +输出:[]
    +解释:无法执行任何操作。
    +
    + +

    示例 4:

    + +
    +输入:trees = [[2,1,3]]
    +输出:[2,1,3]
    +解释:trees 中只有一棵树,且这棵树已经是一棵有效的二叉搜索树,所以返回该树的根节点。
    +
    + +

     

    + +

    提示:

    + +
      +
    • n == trees.length
    • +
    • 1 <= n <= 5 * 104
    • +
    • 每棵树中节点数目在范围 [1, 3] 内。
    • +
    • trees 中不存在两棵树根节点值相同的情况。
    • +
    • 输入中的所有树都是 有效的二叉树搜索树
    • +
    • 1 <= TreeNode.val <= 5 * 104.
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1933.leetcode1933 Check if String Is Decomposable Into Value-Equal Substrings-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1933.leetcode1933 Check if String Is Decomposable Into Value-Equal Substrings-zh.md" new file mode 100644 index 00000000..f01cff30 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1933.leetcode1933 Check if String Is Decomposable Into Value-Equal Substrings-zh.md" @@ -0,0 +1,83 @@ +# [1933. 判断字符串是否可分解为值均等的子串](https://leetcode-cn.com/problems/check-if-string-is-decomposable-into-value-equal-substrings) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1933.Check%20if%20String%20Is%20Decomposable%20Into%20Value-Equal%20Substrings/README_EN.md) + +## 题目描述 + + + +

    一个字符串的所有字符都是一样的,被称作等值字符串。

    + +
      +
    • 举例,"1111" 和 "33" 就是等值字符串。
    • +
    • 相比之下,"123"就不是等值字符串。
    • +
    + +

    规则:给出一个数字字符串s,将字符串分解成一些等值字符串,如果有且仅有一个等值子字符串长度为2,其他的等值子字符串的长度都是3.

    + +

    如果能够按照上面的规则分解字符串s,就返回真,否则返回假。

    + +

    子串就是原字符串中连续的字符序列。

    + +

     

    + +

    示例 1:

    + +
    输入: s = "000111000"
    +输出: false
    +解释:  s只能被分解长度为3的等值子字符串。
    +
    + +

    示例 2:

    + +
    输入: s = "00011111222"
    +输出: true
    +解释: s 能被分解为 ["000","111","11","222"].
    +
    + +

    示例 3:

    + +
    输入: s = "01110002223300"
    +输出: false
    +解释: 一个不能被分解的原因是在开头有一个0.
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= s.length <= 1000
    • +
    • s 仅包含数字。
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1934.leetcode1934 Confirmation Rate-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1934.leetcode1934 Confirmation Rate-zh.md" new file mode 100644 index 00000000..c70c8f8c --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1934.leetcode1934 Confirmation Rate-zh.md" @@ -0,0 +1,106 @@ +# [1934. Confirmation Rate](https://leetcode-cn.com/problems/confirmation-rate) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1934.Confirmation%20Rate/README_EN.md) + +## 题目描述 + + + +

    Table: Signups

    + +
    ++----------------+----------+
    +| Column Name    | Type     |
    ++----------------+----------+
    +| user_id        | int      |
    +| time_stamp     | datetime |
    ++----------------+----------+
    +user_id is the primary key for this table.
    +Each row contains information about the signup time for the user with ID user_id.
    +
    + +

     

    + +

    Table: Confirmations

    + +
    ++----------------+----------+
    +| Column Name    | Type     |
    ++----------------+----------+
    +| user_id        | int      |
    +| time_stamp     | datetime |
    +| action         | ENUM     |
    ++----------------+----------+
    +(user_id, time_stamp) is the primary key for this table.
    +user_id is a foreign key with a reference to the Signups table.
    +action is an ENUM of the type ('confirmed', 'timeout')
    +Each row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout').
    + +

     

    + +

    The confirmation rate of a user is the number of 'confirmed' messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is 0.

    + +

    Write an SQL query to find the confirmation rate of each user.

    + +

    Return the result table in any order.

    + +

    The query result format is in the following example:

    + +

     

    + +
    +Signups table:
    ++---------+---------------------+
    +| user_id | time_stamp          |
    ++---------+---------------------+
    +| 3       | 2020-03-21 10:16:13 |
    +| 7       | 2020-01-04 13:57:59 |
    +| 2       | 2020-07-29 23:09:44 |
    +| 6       | 2020-12-09 10:39:37 |
    ++---------+---------------------+
    +
    +Confirmations table:
    ++---------+---------------------+-----------+
    +| user_id | time_stamp          | action    |
    ++---------+---------------------+-----------+
    +| 3       | 2021-01-06 03:30:46 | timeout   |
    +| 3       | 2021-07-14 14:00:00 | timeout   |
    +| 7       | 2021-06-12 11:57:29 | confirmed |
    +| 7       | 2021-06-13 12:58:28 | confirmed |
    +| 7       | 2021-06-14 13:59:27 | confirmed |
    +| 2       | 2021-01-22 00:00:00 | confirmed |
    +| 2       | 2021-02-28 23:59:59 | timeout   |
    ++---------+---------------------+-----------+
    +
    +Result table
    ++---------+-------------------+
    +| user_id | confirmation_rate |
    ++---------+-------------------+
    +| 6       | 0.00              |
    +| 3       | 0.00              |
    +| 7       | 1.00              |
    +| 2       | 0.50              |
    ++---------+-------------------+
    +
    +User 6 did not request any confirmation messages. The confirmation rate is 0.
    +User 3 made 2 requests and both timed out. The confirmation rate is 0.
    +User 7 made 3 requests and all were confirmed. The confirmation rate is 1.
    +User 2 made 2 requests where one was confirmed and the other timed out. The confirmation rate is 1 / 2 = 0.5.
    +
    + + +## 解法 + + + + + +### **SQL** + + + +```sql + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1935.leetcode1935 Maximum Number of Words You Can Type-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1935.leetcode1935 Maximum Number of Words You Can Type-zh.md" new file mode 100644 index 00000000..2bb7427f --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1935.leetcode1935 Maximum Number of Words You Can Type-zh.md" @@ -0,0 +1,77 @@ +# [1935. 可以输入的最大单词数](https://leetcode-cn.com/problems/maximum-number-of-words-you-can-type) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1935.Maximum%20Number%20of%20Words%20You%20Can%20Type/README_EN.md) + +## 题目描述 + + + +

    键盘出现了一些故障,有些字母键无法正常工作。而键盘上所有其他键都能够正常工作。

    + +

    给你一个由若干单词组成的字符串 text ,单词间由单个空格组成(不含前导和尾随空格);另有一个字符串 brokenLetters ,由所有已损坏的不同字母键组成,返回你可以使用此键盘完全输入的 text 中单词的数目。

    + +

     

    + +

    示例 1:

    + +
    输入:text = "hello world", brokenLetters = "ad"
    +输出:1
    +解释:无法输入 "world" ,因为字母键 'd' 已损坏。
    +
    + +

    示例 2:

    + +
    输入:text = "leet code", brokenLetters = "lt"
    +输出:1
    +解释:无法输入 "leet" ,因为字母键 'l' 和 't' 已损坏。
    +
    + +

    示例 3:

    + +
    输入:text = "leet code", brokenLetters = "e"
    +输出:0
    +解释:无法输入任何单词,因为字母键 'e' 已损坏。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= text.length <= 104
    • +
    • 0 <= brokenLetters.length <= 26
    • +
    • text 由若干用单个空格分隔的单词组成,且不含任何前导和尾随空格
    • +
    • 每个单词仅由小写英文字母组成
    • +
    • brokenLetters互不相同 的小写英文字母组成
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1936.leetcode1936 Add Minimum Number of Rungs-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1936.leetcode1936 Add Minimum Number of Rungs-zh.md" new file mode 100644 index 00000000..ea9b7e01 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1936.leetcode1936 Add Minimum Number of Rungs-zh.md" @@ -0,0 +1,96 @@ +# [1936. 新增的最少台阶数](https://leetcode-cn.com/problems/add-minimum-number-of-rungs) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1936.Add%20Minimum%20Number%20of%20Rungs/README_EN.md) + +## 题目描述 + + + +

    给你一个 严格递增 的整数数组 rungs ,用于表示梯子上每一台阶的 高度 。当前你正站在高度为 0 的地板上,并打算爬到最后一个台阶。

    + +

    另给你一个整数 dist 。每次移动中,你可以到达下一个距离你当前位置(地板或台阶)不超过 dist 高度的台阶。当然,你也可以在任何正 整数 高度处插入尚不存在的新台阶。

    + +

    返回爬到最后一阶时必须添加到梯子上的 最少 台阶数。

    + +

     

    + +

    示例 1:

    + +
    +输入:rungs = [1,3,5,10], dist = 2
    +输出:2
    +解释:
    +现在无法到达最后一阶。
    +在高度为 7 和 8 的位置增设新的台阶,以爬上梯子。 
    +梯子在高度为 [1,3,5,7,8,10] 的位置上有台阶。
    +
    + +

    示例 2:

    + +
    +输入:rungs = [3,6,8,10], dist = 3
    +输出:0
    +解释:
    +这个梯子无需增设新台阶也可以爬上去。
    +
    + +

    示例 3:

    + +
    +输入:rungs = [3,4,6,7], dist = 2
    +输出:1
    +解释:
    +现在无法从地板到达梯子的第一阶。 
    +在高度为 1 的位置增设新的台阶,以爬上梯子。 
    +梯子在高度为 [1,3,4,6,7] 的位置上有台阶。
    +
    + +

    示例 4:

    + +
    +输入:rungs = [5], dist = 10
    +输出:0
    +解释:这个梯子无需增设新台阶也可以爬上去。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 1 <= rungs.length <= 105
    • +
    • 1 <= rungs[i] <= 109
    • +
    • 1 <= dist <= 109
    • +
    • rungs 严格递增
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1937.leetcode1937 Maximum Number of Points with Cost-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1937.leetcode1937 Maximum Number of Points with Cost-zh.md" new file mode 100644 index 00000000..3e936842 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1937.leetcode1937 Maximum Number of Points with Cost-zh.md" @@ -0,0 +1,91 @@ +# [1937. 扣分后的最大得分](https://leetcode-cn.com/problems/maximum-number-of-points-with-cost) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1937.Maximum%20Number%20of%20Points%20with%20Cost/README_EN.md) + +## 题目描述 + + + +

    给你一个 m x n 的整数矩阵 points (下标从 0 开始)。一开始你的得分为 0 ,你想最大化从矩阵中得到的分数。

    + +

    你的得分方式为:每一行 中选取一个格子,选中坐标为 (r, c) 的格子会给你的总得分 增加 points[r][c] 。

    + +

    然而,相邻行之间被选中的格子如果隔得太远,你会失去一些得分。对于相邻行 r 和 r + 1 (其中 0 <= r < m - 1),选中坐标为 (r, c1) 和 (r + 1, c2) 的格子,你的总得分 减少 abs(c1 - c2) 。

    + +

    请你返回你能得到的 最大 得分。

    + +

    abs(x) 定义为:

    + +
      +
    • 如果 x >= 0 ,那么值为 x 。
    • +
    • 如果 x < 0 ,那么值为 -x 。
    • +
    + +

     

    + +

    示例 1:

    + +
    +输入:points = [[1,2,3],[1,5,1],[3,1,1]]
    +输出:9
    +解释:
    +蓝色格子是最优方案选中的格子,坐标分别为 (0, 2),(1, 1) 和 (2, 0) 。
    +你的总得分增加 3 + 5 + 3 = 11 。
    +但是你的总得分需要扣除 abs(2 - 1) + abs(1 - 0) = 2 。
    +你的最终得分为 11 - 2 = 9 。
    +
    + +

    示例 2:

    + +
    +输入:points = [[1,5],[2,3],[4,2]]
    +输出:11
    +解释:
    +蓝色格子是最优方案选中的格子,坐标分别为 (0, 1),(1, 1) 和 (2, 0) 。
    +你的总得分增加 5 + 3 + 4 = 12 。
    +但是你的总得分需要扣除 abs(1 - 1) + abs(1 - 0) = 1 。
    +你的最终得分为 12 - 1 = 11 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • m == points.length
    • +
    • n == points[r].length
    • +
    • 1 <= m, n <= 105
    • +
    • 1 <= m * n <= 105
    • +
    • 0 <= points[r][c] <= 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + + diff --git "a/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1938.leetcode1938 Maximum Genetic Difference Query-zh.md" "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1938.leetcode1938 Maximum Genetic Difference Query-zh.md" new file mode 100644 index 00000000..ab942fa4 --- /dev/null +++ "b/\344\270\255\346\226\207\351\242\2301-2000/leetcode401-2000/1938.leetcode1938 Maximum Genetic Difference Query-zh.md" @@ -0,0 +1,79 @@ +# [1938. 查询最大基因差](https://leetcode-cn.com/problems/maximum-genetic-difference-query) + +[English Version](https://github.com/yanglr/leetcode-ac/blob/master/assets/1900-1999/1938.Maximum%20Genetic%20Difference%20Query/README_EN.md) + +## 题目描述 + + + +

    给你一棵 n 个节点的有根树,节点编号从 0 到 n - 1 。每个节点的编号表示这个节点的 独一无二的基因值 (也就是说节点 x 的基因值为 x)。两个基因值的 基因差 是两者的 异或和 。给你整数数组 parents ,其中 parents[i] 是节点 i 的父节点。如果节点 x 是树的  ,那么 parents[x] == -1 。

    + +

    给你查询数组 queries ,其中 queries[i] = [nodei, vali] 。对于查询 i ,请你找到 vali 和 pi 的 最大基因差 ,其中 pi 是节点 nodei 到根之间的任意节点(包含 nodei 和根节点)。更正式的,你想要最大化 vali XOR pi 

    + +

    请你返回数组 ans ,其中 ans[i] 是第 i 个查询的答案。

    + +

     

    + +

    示例 1:

    + +
    输入:parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]
    +输出:[2,3,7]
    +解释:查询数组处理如下:
    +- [0,2]:最大基因差的对应节点为 0 ,基因差为 2 XOR 0 = 2 。
    +- [3,2]:最大基因差的对应节点为 1 ,基因差为 2 XOR 1 = 3 。
    +- [2,5]:最大基因差的对应节点为 2 ,基因差为 5 XOR 2 = 7 。
    +
    + +

    示例 2:

    + +
    输入:parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]
    +输出:[6,14,7]
    +解释:查询数组处理如下:
    +- [4,6]:最大基因差的对应节点为 0 ,基因差为 6 XOR 0 = 6 。
    +- [1,15]:最大基因差的对应节点为 1 ,基因差为 15 XOR 1 = 14 。
    +- [0,5]:最大基因差的对应节点为 2 ,基因差为 5 XOR 2 = 7 。
    +
    + +

     

    + +

    提示:

    + +
      +
    • 2 <= parents.length <= 105
    • +
    • 对于每个 不是 根节点的 i ,有 0 <= parents[i] <= parents.length - 1 。
    • +
    • parents[root] == -1
    • +
    • 1 <= queries.length <= 3 * 104
    • +
    • 0 <= nodei <= parents.length - 1
    • +
    • 0 <= vali <= 2 * 105
    • +
    + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **...** + +``` + +``` + +